提交 1e162fa4 authored 作者: blu's avatar blu

event notifier rev1: new issues interface and a set of utilities, preparing for rev2

上级 ab66cd7b
...@@ -209,14 +209,15 @@ int saveLocalConfigration(json &config, string fileName) ...@@ -209,14 +209,15 @@ int saveLocalConfigration(json &config, string fileName)
// } // }
// write prettified JSON file // write prettified JSON file
try{ try {
std::ofstream o(fileName); std::ofstream o(fileName);
o << std::setw(4) << config << std::endl; o << std::setw(4) << config << std::endl;
}catch(exception &e) { }
catch(exception &e) {
spdlog::error("saveLocalConfigration failed to write configuration to file {}: {}\n{}", fileName, e.what(), config.dump()); spdlog::error("saveLocalConfigration failed to write configuration to file {}: {}\n{}", fileName, e.what(), config.dump());
return -2; return -2;
} }
return ret; return ret;
} }
......
...@@ -3,13 +3,15 @@ ...@@ -3,13 +3,15 @@
#include <string> #include <string>
using namespace std; using namespace std;
double getDiskAvailPercent(string path) { double getDiskAvailPercent(string path)
{
struct statvfs fiData; struct statvfs fiData;
if((statvfs(path.c_str(),&fiData)) < 0 ) { if((statvfs(path.c_str(),&fiData)) < 0 ) {
} else { }
double fper = fiData.f_bavail/double(fiData.f_blocks); else {
cout << fper << endl; double fper = fiData.f_bavail/double(fiData.f_blocks);
return fper; cout << fper << endl;
return fper;
} }
return -1; return -1;
...@@ -20,8 +22,8 @@ int main( int argc, char *argv[] ) ...@@ -20,8 +22,8 @@ int main( int argc, char *argv[] )
struct statvfs fiData; struct statvfs fiData;
if( argc < 2 ) { if( argc < 2 ) {
cout <<"Usage, ./size dir1 dir2 ... dirN\n"; cout <<"Usage, ./size dir1 dir2 ... dirN\n";
return(1); return(1);
} }
//Lets loopyloop through the argvs //Lets loopyloop through the argvs
......
...@@ -49,7 +49,7 @@ int downloadFile(string fileUrl, string outUrl) ...@@ -49,7 +49,7 @@ int downloadFile(string fileUrl, string outUrl)
/* write the page body to this file handle */ /* write the page body to this file handle */
curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp); curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
auto res = curl_easy_perform(curl); auto res = curl_easy_perform(curl);
if(res != CURLE_OK){ if(res != CURLE_OK) {
spdlog::error("failed to upload files: {}", curl_easy_strerror(res)); spdlog::error("failed to upload files: {}", curl_easy_strerror(res));
return -1; return -1;
} }
......
...@@ -55,7 +55,8 @@ private: ...@@ -55,7 +55,8 @@ private:
json allIssues; json allIssues;
json buildIssuesForIpc(string ipcSn, json &v){ json buildIssuesForIpc(string ipcSn, json &v)
{
json ret; json ret;
auto now = chrono::duration_cast<chrono::seconds>(chrono::system_clock::now().time_since_epoch()).count(); auto now = chrono::duration_cast<chrono::seconds>(chrono::system_clock::now().time_since_epoch()).count();
// check mgr status first // check mgr status first
...@@ -72,31 +73,33 @@ private: ...@@ -72,31 +73,33 @@ private:
)"_json; )"_json;
data["time"] = now; data["time"] = now;
bool hasIssue = false; bool hasIssue = false;
if(v.count("mgrTerminal") == 0|| v["mgrTerminal"].size() == 0||v["mgrTerminal"].count("online") == 0){ if(v.count("mgrTerminal") == 0|| v["mgrTerminal"].size() == 0||v["mgrTerminal"].count("online") == 0) {
data["catId"] = "AV_NO_CONFIG"; data["catId"] = "AV_NO_CONFIG";
data["msg"] = "no configuratoin"; data["msg"] = "no configuratoin";
hasIssue = true; hasIssue = true;
}else{ }
if(!v["mgrTerminal"]["online"].get<bool>()){ else {
if(!v["mgrTerminal"]["online"].get<bool>()) {
data["msg"] = fmt::format(data["msg"].get<string>(), v["mgrTerminal"]["sn"].get<string>(), ipcSn); data["msg"] = fmt::format(data["msg"].get<string>(), v["mgrTerminal"]["sn"].get<string>(), ipcSn);
hasIssue = true; hasIssue = true;
} }
} }
if(hasIssue){ if(hasIssue) {
if(ret.count(data["catId"].get<string>()) == 0){ if(ret.count(data["catId"].get<string>()) == 0) {
ret[data["catId"].get<string>()] = data; ret[data["catId"].get<string>()] = data;
} }
}else{ }
else {
// check runtime issues // check runtime issues
if(v.count("issues") != 0 && v["issues"].size() != 0){ if(v.count("issues") != 0 && v["issues"].size() != 0) {
for(auto &[m,n]: v["issues"].items()){ for(auto &[m,n]: v["issues"].items()) {
auto modId = m; auto modId = m;
for(auto &[i,j]: n.items()){ for(auto &[i,j]: n.items()) {
auto catId = i; auto catId = i;
auto data = j; auto data = j;
if(catId != EV_MSG_REPORT_CATID_AVMODOFFLINE) { if(catId != EV_MSG_REPORT_CATID_AVMODOFFLINE) {
if(ret.count(catId) == 0){ if(ret.count(catId) == 0) {
ret[catId] = data; ret[catId] = data;
} }
} }
...@@ -104,12 +107,13 @@ private: ...@@ -104,12 +107,13 @@ private:
} }
} }
} }
return ret; return ret;
} }
void storeReportMsg(string selfId, string ipcSn, json &ipcStatus, string catId, string msg, bool active){ void storeReportMsg(string selfId, string ipcSn, json &ipcStatus, string catId, string msg, bool active)
{
json data; json data;
data["msg"] = msg; data["msg"] = msg;
data["modId"] = "ALL"; data["modId"] = "ALL";
...@@ -122,10 +126,11 @@ private: ...@@ -122,10 +126,11 @@ private:
if(ipcStatus["issues"].count(selfId) == 0) { if(ipcStatus["issues"].count(selfId) == 0) {
ipcStatus["issues"][selfId] = json(); ipcStatus["issues"][selfId] = json();
} }
if(active){ if(active) {
ipcStatus["issues"][selfId][catId] = data; ipcStatus["issues"][selfId][catId] = data;
}else{ }
if(ipcStatus["issues"][selfId].count(catId) != 0){ else {
if(ipcStatus["issues"][selfId].count(catId) != 0) {
ipcStatus["issues"][selfId].erase(catId); ipcStatus["issues"][selfId].erase(catId);
} }
} }
...@@ -155,7 +160,7 @@ private: ...@@ -155,7 +160,7 @@ private:
peerData["mgr2ipc"][k] = json(); peerData["mgr2ipc"][k] = json();
} }
peerData["mgr2ipc"][k][ipcSn] = 1; peerData["mgr2ipc"][k][ipcSn] = 1;
for(auto &[mn, ma]: modules.items()) { for(auto &[mn, ma]: modules.items()) {
for(auto &m:ma) { for(auto &m:ma) {
string modGid; string modGid;
...@@ -762,7 +767,7 @@ private: ...@@ -762,7 +767,7 @@ private:
if(peerData["ipcStatus"].count(ipcSn) != 0) { if(peerData["ipcStatus"].count(ipcSn) != 0) {
auto &ipcStatus = peerData["ipcStatus"][ipcSn]; auto &ipcStatus = peerData["ipcStatus"][ipcSn];
if(ipcStatus.count("mgrTerminal") == 0){ if(ipcStatus.count("mgrTerminal") == 0) {
ipcStatus["mgrTerminal"] = json(); ipcStatus["mgrTerminal"] = json();
ipcStatus["mgrTerminal"]["sn"] = peerId; ipcStatus["mgrTerminal"]["sn"] = peerId;
ipcStatus["mgrTerminal"]["online"] = true; ipcStatus["mgrTerminal"]["online"] = true;
...@@ -811,21 +816,21 @@ private: ...@@ -811,21 +816,21 @@ private:
} }
auto issues = buildIssuesForIpc(ipcSn, ipcStatus); auto issues = buildIssuesForIpc(ipcSn, ipcStatus);
if(allIssues.count(ipcSn) == 0){ if(allIssues.count(ipcSn) == 0) {
allIssues[ipcSn] = json(); allIssues[ipcSn] = json();
} }
bool report = false; bool report = false;
if(issues.size() > 0){ if(issues.size() > 0) {
for(auto &[kk,vv]: issues.items()){ for(auto &[kk,vv]: issues.items()) {
if(allIssues[ipcSn].count(kk) == 0) { if(allIssues[ipcSn].count(kk) == 0) {
report = true; report = true;
break; break;
} }
} }
} }
if(report){ if(report) {
/// TODO: /// TODO:
} }
} }
else { else {
...@@ -1455,7 +1460,7 @@ public: ...@@ -1455,7 +1460,7 @@ public:
else { else {
// nop // nop
} }
ret["data"]["detail"] = detail; ret["data"]["detail"] = detail;
...@@ -1580,11 +1585,11 @@ public: ...@@ -1580,11 +1585,11 @@ public:
lock_guard<recursive_mutex> lg(mutIpcStatus); lock_guard<recursive_mutex> lg(mutIpcStatus);
if(this->peerData["ipcStatus"].count(sn) != 0) { if(this->peerData["ipcStatus"].count(sn) != 0) {
auto dsn = this->peerData["ipcStatus"][sn]["mgrTerminal"]["sn"].get<string>(); auto dsn = this->peerData["ipcStatus"][sn]["mgrTerminal"]["sn"].get<string>();
if(this->peerData["ipcStatus"][sn]["mgrTerminal"]["online"].get<bool>()){ if(this->peerData["ipcStatus"][sn]["mgrTerminal"]["online"].get<bool>()) {
// online // online
json j = getConfigForDevice(dsn); json j = getConfigForDevice(dsn);
if(j["code"] == 0) { if(j["code"] == 0) {
for(auto &[k,v]:j["data"].items()){ for(auto &[k,v]:j["data"].items()) {
auto &ipcs = v["ipcs"]; auto &ipcs = v["ipcs"];
for(auto &ipc: ipcs) { for(auto &ipc: ipcs) {
if(ipc["sn"] == sn) { if(ipc["sn"] == sn) {
...@@ -1605,11 +1610,13 @@ public: ...@@ -1605,11 +1610,13 @@ public:
payload["data"]["start"] = start; payload["data"]["start"] = start;
payload["data"]["end"] = end; payload["data"]["end"] = end;
ret = this->handleCmd(payload); ret = this->handleCmd(payload);
}else{ }
else {
ret["code"] = 3; ret["code"] = 3;
ret["msg"] = dsn + " invalid config for slicer"; ret["msg"] = dsn + " invalid config for slicer";
} }
}else{ }
else {
// offline // offline
ret["code"] = 2; ret["code"] = 2;
ret["msg"] = dsn + " terminal off line"; ret["msg"] = dsn + " terminal off line";
...@@ -1766,11 +1773,11 @@ public: ...@@ -1766,11 +1773,11 @@ public:
lock_guard<recursive_mutex> lg(mutIpcStatus); lock_guard<recursive_mutex> lg(mutIpcStatus);
json &ipcStatus = peerData["ipcStatus"]; json &ipcStatus = peerData["ipcStatus"];
json ret; json ret;
for(auto &[k,v]: ipcStatus.items()){ for(auto &[k,v]: ipcStatus.items()) {
auto ipcSn = k; auto ipcSn = k;
// //
auto r = buildIssuesForIpc(k, v); auto r = buildIssuesForIpc(k, v);
if(r.size() > 0){ if(r.size() > 0) {
ret[ipcSn] = r; ret[ipcSn] = r;
} }
} }
......
...@@ -457,12 +457,13 @@ private: ...@@ -457,12 +457,13 @@ private:
int ret = 0; int ret = 0;
meta["type"] = EV_MSG_META_TYPE_CMD; meta["type"] = EV_MSG_META_TYPE_CMD;
meta["value"] = cmdVal; meta["value"] = cmdVal;
if(msg == "0"){ if(msg == "0") {
auto sp = strutils::split(peerId, ':'); auto sp = strutils::split(peerId, ':');
if(sp.size() == 3){ if(sp.size() == 3) {
system((string("pkill -9 ") + sp[1]).c_str()); system((string("pkill -9 ") + sp[1]).c_str());
} }
}else{ }
else {
ret = z_send(pRouter, peerId, this->daemonId, meta, msg); ret = z_send(pRouter, peerId, this->daemonId, meta, msg);
if(ret < 0) { if(ret < 0) {
spdlog::error("evdaemon {} failed to send msg to peer {}: {} - {}", devSn, peerId, meta.dump(), msg); spdlog::error("evdaemon {} failed to send msg to peer {}: {} - {}", devSn, peerId, meta.dump(), msg);
...@@ -786,7 +787,8 @@ private: ...@@ -786,7 +787,8 @@ private:
if(v.size() == 1) { if(v.size() == 1) {
if(data["metaValue"] == EV_MSG_META_VALUE_CMD_REVESETUN) { if(data["metaValue"] == EV_MSG_META_VALUE_CMD_REVESETUN) {
manageReverseTun(true, data["data"]); manageReverseTun(true, data["data"]);
}else if(data["metaValue"] == EV_MSG_META_VALUE_CMD_UPDATE){ }
else if(data["metaValue"] == EV_MSG_META_VALUE_CMD_UPDATE) {
// //
} }
else { else {
...@@ -1085,8 +1087,8 @@ public: ...@@ -1085,8 +1087,8 @@ public:
}); });
thHeartBeat.detach(); thHeartBeat.detach();
thSubMonitor = thread([this](){ thSubMonitor = thread([this]() {
while(true){ while(true) {
{ {
unique_lock<mutex> lk(this->mutSubMonitor); unique_lock<mutex> lk(this->mutSubMonitor);
this->cvSubMonitor.wait(lk, [this] {return !this->bColdStart;}); this->cvSubMonitor.wait(lk, [this] {return !this->bColdStart;});
...@@ -1170,7 +1172,7 @@ public: ...@@ -1170,7 +1172,7 @@ public:
#define EV_WATCHDOG_STOP uint8_t(0xFD) #define EV_WATCHDOG_STOP uint8_t(0xFD)
class EvWatchDog { class EvWatchDog {
private: private:
int fd_dog = 0; int fd_dog = 0;
string tty; string tty;
bool disabled = false; bool disabled = false;
...@@ -1194,18 +1196,19 @@ class EvWatchDog { ...@@ -1194,18 +1196,19 @@ class EvWatchDog {
return -1; return -1;
} }
cfsetospeed(&tio,B115200); // 115200 baud cfsetospeed(&tio,B115200); // 115200 baud
//cfsetispeed(&tio,B115200); //cfsetispeed(&tio,B115200);
if(-1 == tcsetattr(tty_fd,TCSANOW,&tio)){ if(-1 == tcsetattr(tty_fd,TCSANOW,&tio)) {
spdlog::error("evdaemon failed to set tty {}", tty); spdlog::error("evdaemon failed to set tty {}", tty);
return -1; return -1;
} }
return tty_fd; return tty_fd;
} }
int watchdog_feed(int fd, uint8_t intervalMs){ int watchdog_feed(int fd, uint8_t intervalMs)
{
if(fd <=0) { if(fd <=0) {
spdlog::error("evdaemon invalid watchdog fd"); spdlog::error("evdaemon invalid watchdog fd");
return -1; return -1;
...@@ -1213,19 +1216,22 @@ class EvWatchDog { ...@@ -1213,19 +1216,22 @@ class EvWatchDog {
uint8_t check = ~intervalMs; uint8_t check = ~intervalMs;
uint8_t data[] = {0xFE, 0xFE, intervalMs, check, 0xEF}; uint8_t data[] = {0xFE, 0xFE, intervalMs, check, 0xEF};
spdlog::debug("evdaemon feed watch dog: {}, {}", intervalMs, check); spdlog::debug("evdaemon feed watch dog: {}, {}", intervalMs, check);
if( -1 == write(fd,data,5)){ if( -1 == write(fd,data,5)) {
spdlog::error("evdaemon failed to write watchdog fd"); spdlog::error("evdaemon failed to write watchdog fd");
return -1; return -1;
}else{ }
else {
return 0; return 0;
} }
} }
int _EV_WATCHDOG_STOP(int fd){ int _EV_WATCHDOG_STOP(int fd)
{
return watchdog_feed(fd, EV_WATCHDOG_STOP); return watchdog_feed(fd, EV_WATCHDOG_STOP);
} }
int watchdog_close(int fd) { int watchdog_close(int fd)
{
spdlog::info("evdaemon disabling watch dog.."); spdlog::info("evdaemon disabling watch dog..");
if(fd > 0) { if(fd > 0) {
_EV_WATCHDOG_STOP(fd); _EV_WATCHDOG_STOP(fd);
...@@ -1233,17 +1239,19 @@ class EvWatchDog { ...@@ -1233,17 +1239,19 @@ class EvWatchDog {
} }
return 0; return 0;
} }
public: public:
EvWatchDog() = delete; EvWatchDog() = delete;
EvWatchDog(string tty):tty(tty){ EvWatchDog(string tty):tty(tty)
{
if((fd_dog = watchdog_init(tty)) < 0) { if((fd_dog = watchdog_init(tty)) < 0) {
spdlog::error("evdaemon can't open watchdog tty, ignore watchdog"); spdlog::error("evdaemon can't open watchdog tty, ignore watchdog");
fd_dog = 0; fd_dog = 0;
} }
} }
thread run(){ thread run()
thread th = thread([this](){ {
thread th = thread([this]() {
uint8_t intval = 10; uint8_t intval = 10;
if(this->fd_dog > 0) { if(this->fd_dog > 0) {
while(!this->disabled) { while(!this->disabled) {
...@@ -1252,14 +1260,16 @@ class EvWatchDog { ...@@ -1252,14 +1260,16 @@ class EvWatchDog {
} }
watchdog_close(this->fd_dog); watchdog_close(this->fd_dog);
this->fd_dog = 0; this->fd_dog = 0;
}else{ }
else {
this->fd_dog = 0; this->fd_dog = 0;
} }
}); });
return th; return th;
} }
void stop(){ void stop()
{
if(fd_dog > 0 && !disabled) { if(fd_dog > 0 && !disabled) {
disabled = true; disabled = true;
while(fd_dog != 0) { while(fd_dog != 0) {
...@@ -1296,7 +1306,7 @@ int main() ...@@ -1296,7 +1306,7 @@ int main()
signal(SIGKILL, cleanup); signal(SIGKILL, cleanup);
thread t = gWatchDog.run(); thread t = gWatchDog.run();
if(t.joinable()){ if(t.joinable()) {
t.detach(); t.detach();
} }
//sigignore(SIGCHLD); //sigignore(SIGCHLD);
......
...@@ -396,9 +396,9 @@ public: ...@@ -396,9 +396,9 @@ public:
spdlog::info("{} boot", devSn); spdlog::info("{} boot", devSn);
SingletonProcess self(selfName, 0); SingletonProcess self(selfName, 0);
if(!self()){ if(!self()) {
spdlog::error("{} already running. ignore this instance", selfName); spdlog::error("{} already running. ignore this instance", selfName);
exit(0); exit(0);
} }
// //
......
...@@ -325,7 +325,7 @@ protected: ...@@ -325,7 +325,7 @@ protected:
spdlog::error("{} failed read packet in 30s, restart", selfId); spdlog::error("{} failed read packet in 30s, restart", selfId);
kill(getpid(), SIGTERM); kill(getpid(), SIGTERM);
} }
pktCntLast = this->pktCnt; pktCntLast = this->pktCnt;
} }
}); });
......
...@@ -302,9 +302,10 @@ private: ...@@ -302,9 +302,10 @@ private:
} }
unique_lock<mutex> lk(this->mutMsg); unique_lock<mutex> lk(this->mutMsg);
bool got = this->cvMsg.wait_for(lk, 30s, [this] {return this->gotFormat;}); bool got = this->cvMsg.wait_for(lk, 30s, [this] {return this->gotFormat;});
if(got){ if(got) {
}else{ }
else {
// restart // restart
spdlog::error("{} failed wait for avformatctx for {}s, restart", devSn, 30); spdlog::error("{} failed wait for avformatctx for {}s, restart", devSn, 30);
exit(1); exit(1);
...@@ -524,8 +525,8 @@ protected: ...@@ -524,8 +525,8 @@ protected:
in_stream = pAVFormatInput->streams[packet.stream_index]; in_stream = pAVFormatInput->streams[packet.stream_index];
packet.stream_index = streamList[packet.stream_index]; packet.stream_index = streamList[packet.stream_index];
if(streamList[packet.stream_index] == -1) { if(streamList[packet.stream_index] == -1) {
av_packet_unref(&packet); av_packet_unref(&packet);
continue; continue;
} }
out_stream = pAVFormatRemux->streams[packet.stream_index]; out_stream = pAVFormatRemux->streams[packet.stream_index];
...@@ -623,9 +624,9 @@ public: ...@@ -623,9 +624,9 @@ public:
spdlog::info("{} boot", selfId); spdlog::info("{} boot", selfId);
SingletonProcess self(selfName, iid); SingletonProcess self(selfName, iid);
if(!self()){ if(!self()) {
spdlog::error("{} already running. ignore this instance", selfId); spdlog::error("{} already running. ignore this instance", selfId);
exit(0); exit(0);
} }
// //
...@@ -637,24 +638,26 @@ public: ...@@ -637,24 +638,26 @@ public:
} }
// setup heath checker // setup heath checker
thHealdChecker = thread([this]{ thHealdChecker = thread([this] {
int cnt = 0; int cnt = 0;
uint64_t pktCntLast = pktCnt; uint64_t pktCntLast = pktCnt;
while(true){ while(true)
{
if(cnt >=3) { if(cnt >=3) {
kill(getpid(), SIGTERM); kill(getpid(), SIGTERM);
exit(1); exit(1);
} }
this_thread::sleep_for(chrono::seconds(30)); this_thread::sleep_for(chrono::seconds(30));
if(pktCntLast == pktCnt){ if(pktCntLast == pktCnt) {
cnt++; cnt++;
}else{ }
else {
pktCntLast = pktCnt; pktCntLast = pktCnt;
cnt = 0; cnt = 0;
} }
} }
}); });
if(thHealdChecker.joinable()){ if(thHealdChecker.joinable()) {
thHealdChecker.detach(); thHealdChecker.detach();
} }
......
...@@ -196,7 +196,8 @@ private: ...@@ -196,7 +196,8 @@ private:
} }
bProcessed = true; bProcessed = true;
spdlog::info("{} debug:record event enqueued: {}", selfId, evt.dump()); spdlog::info("{} debug:record event enqueued: {}", selfId, evt.dump());
}else{ }
else {
spdlog::error("{} debug:record format error: {}", selfId, body.dump()); spdlog::error("{} debug:record format error: {}", selfId, body.dump());
} }
} }
...@@ -451,9 +452,10 @@ private: ...@@ -451,9 +452,10 @@ private:
} }
unique_lock<mutex> lk(this->mutMsg); unique_lock<mutex> lk(this->mutMsg);
bool got = this->cvMsg.wait_for(lk, 30s, [this] {return this->gotFormat;}); bool got = this->cvMsg.wait_for(lk, 30s, [this] {return this->gotFormat;});
if(got){ if(got) {
}else{ }
else {
// restart // restart
spdlog::error("{} failed wait for avformatctx for {}s, restart", devSn, 30); spdlog::error("{} failed wait for avformatctx for {}s, restart", devSn, 30);
exit(1); exit(1);
...@@ -592,8 +594,8 @@ protected: ...@@ -592,8 +594,8 @@ protected:
AVStream *in_stream = nullptr, *out_stream = nullptr; AVStream *in_stream = nullptr, *out_stream = nullptr;
in_stream = pAVFormatInput->streams[packet.stream_index]; in_stream = pAVFormatInput->streams[packet.stream_index];
if(streamList[packet.stream_index] == -1) { if(streamList[packet.stream_index] == -1) {
av_packet_unref(&packet); av_packet_unref(&packet);
continue; continue;
} }
packet.stream_index = streamList[packet.stream_index]; packet.stream_index = streamList[packet.stream_index];
out_stream = pAVFormatRemux->streams[packet.stream_index]; out_stream = pAVFormatRemux->streams[packet.stream_index];
...@@ -945,9 +947,9 @@ public: ...@@ -945,9 +947,9 @@ public:
spdlog::info("{} boot", selfId); spdlog::info("{} boot", selfId);
//TODO: single process //TODO: single process
SingletonProcess self(selfName, iid); SingletonProcess self(selfName, iid);
if(!self()){ if(!self()) {
spdlog::error("{} already running. ignore this instance", selfId); spdlog::error("{} already running. ignore this instance", selfId);
exit(0); exit(0);
} }
// //
...@@ -961,24 +963,26 @@ public: ...@@ -961,24 +963,26 @@ public:
// health checker // health checker
// setup heath checker // setup heath checker
thHealdChecker = thread([this]{ thHealdChecker = thread([this] {
int cnt = 0; int cnt = 0;
uint64_t pktCntLast = pktCnt; uint64_t pktCntLast = pktCnt;
while(true){ while(true)
{
if(cnt >=3) { if(cnt >=3) {
kill(getpid(), SIGTERM); kill(getpid(), SIGTERM);
exit(1); exit(1);
} }
this_thread::sleep_for(chrono::seconds(30)); this_thread::sleep_for(chrono::seconds(30));
if(pktCntLast == pktCnt){ if(pktCntLast == pktCnt) {
cnt++; cnt++;
}else{ }
else {
pktCntLast = pktCnt; pktCntLast = pktCnt;
cnt = 0; cnt = 0;
} }
} }
}); });
if(thHealdChecker.joinable()){ if(thHealdChecker.joinable()) {
thHealdChecker.detach(); thHealdChecker.detach();
} }
...@@ -1092,7 +1096,8 @@ public: ...@@ -1092,7 +1096,8 @@ public:
// th.detach(); // th.detach();
// continue; // continue;
}else if(tse > end*10){ }
else if(tse > end*10) {
spdlog::error("{} thEventHandler invalid event range ({}, {})", selfId, tss, tse); spdlog::error("{} thEventHandler invalid event range ({}, {})", selfId, tss, tse);
continue; continue;
} }
...@@ -1126,7 +1131,7 @@ public: ...@@ -1126,7 +1131,7 @@ public:
if(hasError) { if(hasError) {
continue; continue;
} }
/// let the upload script do the following jobs /// let the upload script do the following jobs
spdlog::info("{} scheduled file upload range:({},{}) = ({}, {}), url: {}", selfId, tss, tse, this->videoFileTs2Name(tss), this->videoFileTs2Name(tse), this->videoFileServerApi); spdlog::info("{} scheduled file upload range:({},{}) = ({}, {}), url: {}", selfId, tss, tse, this->videoFileTs2Name(tss), this->videoFileTs2Name(tse), this->videoFileServerApi);
// string strResp; // string strResp;
...@@ -1141,32 +1146,33 @@ public: ...@@ -1141,32 +1146,33 @@ public:
// } // }
// if(jEvt["cnt"].get<int>() <= 0) { // if(jEvt["cnt"].get<int>() <= 0) {
// TODO: report message to cloud // TODO: report message to cloud
// string msg = fmt::format("{} failed to upload videos over N times: {}", selfId, strResp); // string msg = fmt::format("{} failed to upload videos over N times: {}", selfId, strResp);
// spdlog::error(msg); // spdlog::error(msg);
// TODO: move to failed folder // TODO: move to failed folder
string dirDest = "/var/data/evsuits/failed_events/"; string dirDest = "/var/data/evsuits/failed_events/";
system((string("mkdir -p ") + dirDest).c_str()); system((string("mkdir -p ") + dirDest).c_str());
auto bfPer = sysutils::getDiskAvailPercent(dirDest); auto bfPer = sysutils::getDiskAvailPercent(dirDest);
if(bfPer >= 0.1) { if(bfPer >= 0.1) {
}else{ }
system((string("rm -fr ") + dirDest).c_str()); else {
} system((string("rm -fr ") + dirDest).c_str());
}
json postArgs;
postArgs["params"] = params; json postArgs;
postArgs["fileNames"] = fileNames; postArgs["params"] = params;
string fname = dirDest + params["startTime"].get<string>() + "_" + params["endTime"].get<string>() + "evt.json"; postArgs["fileNames"] = fileNames;
try { string fname = dirDest + params["startTime"].get<string>() + "_" + params["endTime"].get<string>() + "evt.json";
ofstream ofs(fname); try {
ofs << postArgs; ofstream ofs(fname);
// for(auto &f:fileNames) { ofs << postArgs;
// fs::copy(fs::path(string(f)),fs::path(dirDest)); // for(auto &f:fileNames) {
// } // fs::copy(fs::path(string(f)),fs::path(dirDest));
} // }
catch(exception &e) { }
spdlog::error("evcloudsvc {} {}:{} exception: {}", selfId, __FILE__, __LINE__, e.what()); catch(exception &e) {
} spdlog::error("evcloudsvc {} {}:{} exception: {}", selfId, __FILE__, __LINE__, e.what());
}
// } // }
// else { // else {
// spdlog::info("{} retrying upload", selfId); // spdlog::info("{} retrying upload", selfId);
......
...@@ -64,32 +64,39 @@ static char lightLed(bool on) ...@@ -64,32 +64,39 @@ static char lightLed(bool on)
list<string> ledPattList; list<string> ledPattList;
void ledPattDefault(){ void ledPattDefault()
{
ledPattList.push_back("1"); ledPattList.push_back("1");
} }
void ledPattAPMode(){ void ledPattAPMode()
{
ledPattList.push_back("10"); ledPattList.push_back("10");
} }
void ledTryWifi(){ void ledTryWifi()
{
ledPattList.push_back("1110"); ledPattList.push_back("1110");
} }
void ledNoNetwork(){ void ledNoNetwork()
{
ledPattList.push_back("1000"); ledPattList.push_back("1000");
} }
#else #else
void ledPattDefault(){ void ledPattDefault()
{
} }
void ledPattAPMode(){ void ledPattAPMode()
{
} }
void ledNoNetwork(){ void ledNoNetwork()
{
} }
#endif #endif
...@@ -196,7 +203,7 @@ public: ...@@ -196,7 +203,7 @@ public:
}); });
} }
public: public:
json enableMode(int mode) json enableMode(int mode)
{ {
lock_guard<mutex> lk(mutMode); lock_guard<mutex> lk(mutMode);
...@@ -433,20 +440,24 @@ WifiMgr mgr; ...@@ -433,20 +440,24 @@ WifiMgr mgr;
#ifdef EMBED_HW_ILS #ifdef EMBED_HW_ILS
static int key_event_fd; static int key_event_fd;
key_msg key_event_msg; key_msg key_event_msg;
void hand_sig(int sig) { void hand_sig(int sig)
read(key_event_fd, &key_event_msg, sizeof(key_event_msg)); {
spdlog::info("key event id {}, time {}, count {}", key_event_msg.key_id, key_event_msg.time, key_event_msg.count); read(key_event_fd, &key_event_msg, sizeof(key_event_msg));
spdlog::info("key event id {}, time {}, count {}", key_event_msg.key_id, key_event_msg.time, key_event_msg.count);
if(key_event_msg.count == 5) { if(key_event_msg.count == 5) {
// switch AP mode // switch AP mode
mgr.enableMode(1); mgr.enableMode(1);
}else if(key_event_msg.count == 3){ }
else if(key_event_msg.count == 3) {
// station mode // station mode
mgr.scanWifi(); mgr.scanWifi();
mgr.enableMode(2); mgr.enableMode(2);
}else if(key_event_msg.count == 5 && key_event_msg.time * 10 >= 10 * 1000){ }
else if(key_event_msg.count == 5 && key_event_msg.time * 10 >= 10 * 1000) {
// clear SN && reboot // clear SN && reboot
system("rm -fr /opt/lvldb && reboot"); system("rm -fr /opt/lvldb && reboot");
}else if((key_event_msg.count == 1 && key_event_msg.time * 10 >= 10 * 1000)){ }
else if((key_event_msg.count == 1 && key_event_msg.time * 10 >= 10 * 1000)) {
// restart network and evdaemon // restart network and evdaemon
system("/sbin/ifdown -a; /sbin/ifup -a; systemctl restart evdaemon"); system("/sbin/ifdown -a; /sbin/ifup -a; systemctl restart evdaemon");
} }
...@@ -480,15 +491,17 @@ int main() ...@@ -480,15 +491,17 @@ int main()
lastPatt = ledPattList.front(); lastPatt = ledPattList.front();
ledPattList.pop_front(); ledPattList.pop_front();
} }
for(auto &c: lastPatt) { for(auto &c: lastPatt) {
if(c == lastMode){ if(c == lastMode) {
//skip //skip
}else{ }
if(c == '1'){ else {
// on if(c == '1') {
// on
lightLed(true); lightLed(true);
}else{ }
else {
lightLed(false); lightLed(false);
} }
lastMode = c; lastMode = c;
......
...@@ -72,13 +72,15 @@ vector<long> LoadVideoFiles(string path, int days, int maxSlices, map<long, stri ...@@ -72,13 +72,15 @@ vector<long> LoadVideoFiles(string path, int days, int maxSlices, map<long, stri
auto posS = fname.find_last_of('/'); auto posS = fname.find_last_of('/');
if(posS == string::npos) { if(posS == string::npos) {
posS = 0; posS = 0;
}else{ }
else {
posS = posS +1; posS = posS +1;
} }
auto posE = fname.find_last_of('.'); auto posE = fname.find_last_of('.');
if(posE == string::npos) { if(posE == string::npos) {
posE = fname.size()-1; posE = fname.size()-1;
}else{ }
else {
posE = posE -1; posE = posE -1;
} }
if(posE < posS) { if(posE < posS) {
...@@ -93,7 +95,7 @@ vector<long> LoadVideoFiles(string path, int days, int maxSlices, map<long, stri ...@@ -93,7 +95,7 @@ vector<long> LoadVideoFiles(string path, int days, int maxSlices, map<long, stri
catch(exception &e) { catch(exception &e) {
spdlog::error("LoasdVideoFiles exception : {}", e.what()); spdlog::error("LoasdVideoFiles exception : {}", e.what());
} }
// skip old items // skip old items
list<long>olds; list<long>olds;
int delta = maxSlices - tsRing.size(); int delta = maxSlices - tsRing.size();
...@@ -109,7 +111,7 @@ vector<long> LoadVideoFiles(string path, int days, int maxSlices, map<long, stri ...@@ -109,7 +111,7 @@ vector<long> LoadVideoFiles(string path, int days, int maxSlices, map<long, stri
} }
v.push_back(i); v.push_back(i);
} }
// merge // merge
if(skip > 0) { if(skip > 0) {
tsNeedProc.insert(std::upper_bound(tsNeedProc.begin(), tsNeedProc.end(), tsRing.front()), tsRing.begin(), pos); tsNeedProc.insert(std::upper_bound(tsNeedProc.begin(), tsNeedProc.end(), tsRing.front()), tsRing.begin(), pos);
......
/* /*
module: av_common module: av_common
description: description:
author: Bruce.Lu <lzbgt@icloud.com> author: Bruce.Lu <lzbgt@icloud.com>
update: 2019/08/23 update: 2019/08/23
*/ */
...@@ -42,8 +42,7 @@ void avlogThrow(void *avcl, int lvl, const char *fmt, ...) ...@@ -42,8 +42,7 @@ void avlogThrow(void *avcl, int lvl, const char *fmt, ...)
} }
// AVPacketSerializer // AVPacketSerializer
namespace AVPacketSerializer namespace AVPacketSerializer {
{
int encode(AVPacket &pkt, char **bytes) int encode(AVPacket &pkt, char **bytes)
{ {
int cnt = 0; int cnt = 0;
...@@ -52,13 +51,11 @@ int encode(AVPacket &pkt, char **bytes) ...@@ -52,13 +51,11 @@ int encode(AVPacket &pkt, char **bytes)
//side data //side data
// TODO: ignore side_data // TODO: ignore side_data
// pkt.side_data_elems = 0; // pkt.side_data_elems = 0;
wholeSize += sizeof(pkt.side_data_elems); wholeSize += sizeof(pkt.side_data_elems);
if (pkt.side_data_elems != 0) if (pkt.side_data_elems != 0) {
{
spdlog::debug("having side data: {}", pkt.side_data_elems); spdlog::debug("having side data: {}", pkt.side_data_elems);
for (int i = 0; i < pkt.side_data_elems; i++) for (int i = 0; i < pkt.side_data_elems; i++) {
{
wholeSize += pkt.side_data[i].size + sizeof(AVPacketSideData::type) + sizeof(AVPacketSideData::size); wholeSize += pkt.side_data[i].size + sizeof(AVPacketSideData::type) + sizeof(AVPacketSideData::size);
} }
} }
...@@ -80,10 +77,8 @@ int encode(AVPacket &pkt, char **bytes) ...@@ -80,10 +77,8 @@ int encode(AVPacket &pkt, char **bytes)
//side data //side data
memcpy((*bytes) + cnt, &(pkt.side_data_elems), sizeof(pkt.side_data_elems)); memcpy((*bytes) + cnt, &(pkt.side_data_elems), sizeof(pkt.side_data_elems));
cnt += sizeof(pkt.side_data_elems); cnt += sizeof(pkt.side_data_elems);
if (pkt.side_data_elems != 0) if (pkt.side_data_elems != 0) {
{ for (int i = 0; i < pkt.side_data_elems; i++) {
for (int i = 0; i < pkt.side_data_elems; i++)
{
memcpy((*bytes) + cnt, &(pkt.side_data[i].size), sizeof(pkt.side_data[i].size)); memcpy((*bytes) + cnt, &(pkt.side_data[i].size), sizeof(pkt.side_data[i].size));
cnt += sizeof(pkt.side_data[i].size); cnt += sizeof(pkt.side_data[i].size);
memcpy((*bytes) + cnt, pkt.side_data[i].data, pkt.side_data[i].size); memcpy((*bytes) + cnt, pkt.side_data[i].data, pkt.side_data[i].size);
...@@ -118,9 +113,9 @@ int encode(AVPacket &pkt, char **bytes) ...@@ -118,9 +113,9 @@ int encode(AVPacket &pkt, char **bytes)
memcpy((*bytes) + cnt, PS_MARK_E, strlen(PS_MARK_E)); memcpy((*bytes) + cnt, PS_MARK_E, strlen(PS_MARK_E));
cnt += strlen(PS_MARK_E); cnt += strlen(PS_MARK_E);
if(cnt != wholeSize) { if(cnt != wholeSize) {
spdlog::error("pkt encode : {} != {}", wholeSize, cnt); spdlog::error("pkt encode : {} != {}", wholeSize, cnt);
} }
assert(cnt == wholeSize); assert(cnt == wholeSize);
av_log(NULL, AV_LOG_DEBUG, "pkt origin size %d, serialized size: %d, elems: %d", pkt.size, wholeSize, pkt.side_data_elems); av_log(NULL, AV_LOG_DEBUG, "pkt origin size %d, serialized size: %d, elems: %d", pkt.size, wholeSize, pkt.side_data_elems);
return wholeSize; return wholeSize;
...@@ -132,8 +127,7 @@ int decode(char *bytes, int len, AVPacket *pkt, long long *ts = nullptr) ...@@ -132,8 +127,7 @@ int decode(char *bytes, int len, AVPacket *pkt, long long *ts = nullptr)
//AVPacket *pkt = (AVPacket*)malloc(sizeof(AVPacket)); //AVPacket *pkt = (AVPacket*)malloc(sizeof(AVPacket));
int ret = 0; int ret = 0;
int got = 0; int got = 0;
if (memcmp(PS_MARK_E, bytes + len - strlen(PS_MARK_E), strlen(PS_MARK_E)) != 0 || memcmp(PS_MARK_S, bytes, strlen(PS_MARK_S))) if (memcmp(PS_MARK_E, bytes + len - strlen(PS_MARK_E), strlen(PS_MARK_E)) != 0 || memcmp(PS_MARK_S, bytes, strlen(PS_MARK_S))) {
{
spdlog::error("invalid packet. len {}", len); spdlog::error("invalid packet. len {}", len);
return -1; return -1;
} }
...@@ -151,11 +145,10 @@ int decode(char *bytes, int len, AVPacket *pkt, long long *ts = nullptr) ...@@ -151,11 +145,10 @@ int decode(char *bytes, int len, AVPacket *pkt, long long *ts = nullptr)
memcpy(&pkt->side_data_elems, bytes + got, sizeof(pkt->side_data_elems)); memcpy(&pkt->side_data_elems, bytes + got, sizeof(pkt->side_data_elems));
got += sizeof(pkt->side_data_elems); got += sizeof(pkt->side_data_elems);
if(pkt->side_data_elems != 0){ if(pkt->side_data_elems != 0) {
pkt->side_data =(AVPacketSideData*) av_malloc(sizeof(AVPacketSideData) * pkt->side_data_elems ); pkt->side_data =(AVPacketSideData*) av_malloc(sizeof(AVPacketSideData) * pkt->side_data_elems );
} }
for (int i = 0; i < pkt->side_data_elems; i++) for (int i = 0; i < pkt->side_data_elems; i++) {
{
memcpy(&(pkt->side_data[i].size), bytes + got, sizeof(pkt->side_data[i].size)); memcpy(&(pkt->side_data[i].size), bytes + got, sizeof(pkt->side_data[i].size));
got += sizeof(pkt->side_data[i].size); got += sizeof(pkt->side_data[i].size);
pkt->side_data[i].data = (uint8_t *)av_malloc(pkt->side_data[i].size); pkt->side_data[i].data = (uint8_t *)av_malloc(pkt->side_data[i].size);
...@@ -204,8 +197,7 @@ void mqPacketFree(void *data, void *hint) ...@@ -204,8 +197,7 @@ void mqPacketFree(void *data, void *hint)
} }
// AVFormatCtxSerializer // AVFormatCtxSerializer
namespace AVFormatCtxSerializer namespace AVFormatCtxSerializer {
{
/** /**
* memory layerout * memory layerout
* PS_MARK_S | NUM_STREAMS | AVSTREAM+AVCODEPAR | WHOLESIZE | PS_MARK_E * PS_MARK_S | NUM_STREAMS | AVSTREAM+AVCODEPAR | WHOLESIZE | PS_MARK_E
...@@ -220,30 +212,30 @@ int encode(AVFormatContext *ctx, char **bytes, vector<int> ids = vector<int>()) ...@@ -220,30 +212,30 @@ int encode(AVFormatContext *ctx, char **bytes, vector<int> ids = vector<int>())
wholeSize += strlen(PS_MARK_S); wholeSize += strlen(PS_MARK_S);
// num streams // num streams
wholeSize += sizeof(ctx->nb_streams); wholeSize += sizeof(ctx->nb_streams);
int numStreams = ctx->nb_streams; int numStreams = ctx->nb_streams;
if(ids.size() != 0) { if(ids.size() != 0) {
numStreams = ids.size(); numStreams = ids.size();
}else{ }
for(int i = 0; i < numStreams; i++){ else {
ids.push_back(i); for(int i = 0; i < numStreams; i++) {
} ids.push_back(i);
}
} }
spdlog::info("encode num of streams: {}, {}", ctx->nb_streams, numStreams); spdlog::info("encode num of streams: {}, {}", ctx->nb_streams, numStreams);
for(auto i: ids){ for(auto i: ids) {
spdlog::info("\t sid: {}", i); spdlog::info("\t sid: {}", i);
// TODO: ignore extradata // TODO: ignore extradata
// ctx->streams[i]->codecpar->extradata_size = 0; // ctx->streams[i]->codecpar->extradata_size = 0;
} }
for (auto i:ids) for (auto i:ids) {
{
wholeSize += sizeof(AVStream); wholeSize += sizeof(AVStream);
wholeSize += sizeof(AVCodecParameters); wholeSize += sizeof(AVCodecParameters);
//extradata //extradata
wholeSize += sizeof(ctx->streams[i]->codecpar->extradata_size); wholeSize += sizeof(ctx->streams[i]->codecpar->extradata_size);
if(ctx->streams[i]->codecpar->extradata_size!=0){ if(ctx->streams[i]->codecpar->extradata_size!=0) {
wholeSize += ctx->streams[i]->codecpar->extradata_size; wholeSize += ctx->streams[i]->codecpar->extradata_size;
} }
} }
...@@ -257,8 +249,7 @@ int encode(AVFormatContext *ctx, char **bytes, vector<int> ids = vector<int>()) ...@@ -257,8 +249,7 @@ int encode(AVFormatContext *ctx, char **bytes, vector<int> ids = vector<int>())
got += strlen(PS_MARK_S); got += strlen(PS_MARK_S);
memcpy((*bytes) + got, (void *)&(numStreams), sizeof(ctx->nb_streams)); memcpy((*bytes) + got, (void *)&(numStreams), sizeof(ctx->nb_streams));
got += sizeof(ctx->nb_streams); got += sizeof(ctx->nb_streams);
for (auto i: ids) for (auto i: ids) {
{
// //
memcpy((*bytes) + got, ctx->streams[i], sizeof(AVStream)); memcpy((*bytes) + got, ctx->streams[i], sizeof(AVStream));
got += sizeof(AVStream); got += sizeof(AVStream);
...@@ -275,11 +266,11 @@ int encode(AVFormatContext *ctx, char **bytes, vector<int> ids = vector<int>()) ...@@ -275,11 +266,11 @@ int encode(AVFormatContext *ctx, char **bytes, vector<int> ids = vector<int>())
got += sizeof(wholeSize); got += sizeof(wholeSize);
memcpy((*bytes) + got, PS_MARK_E, strlen(PS_MARK_E)); memcpy((*bytes) + got, PS_MARK_E, strlen(PS_MARK_E));
got += strlen(PS_MARK_E); got += strlen(PS_MARK_E);
if(wholeSize != got){ if(wholeSize != got) {
spdlog::error("avctx encode wholesize: {}, should be {}", got, wholeSize); spdlog::error("avctx encode wholesize: {}, should be {}", got, wholeSize);
} }
assert(wholeSize == got); assert(wholeSize == got);
return wholeSize; return wholeSize;
} }
...@@ -288,8 +279,7 @@ int decode(char *bytes, int len, AVFormatContext *pCtx) ...@@ -288,8 +279,7 @@ int decode(char *bytes, int len, AVFormatContext *pCtx)
int ret = 0; int ret = 0;
int got = 0; int got = 0;
memcpy(&ret, bytes +len -strlen(PS_MARK_E) - sizeof(ret), sizeof(ret)); memcpy(&ret, bytes +len -strlen(PS_MARK_E) - sizeof(ret), sizeof(ret));
if ((memcmp(PS_MARK_S, bytes + got, strlen(PS_MARK_S)) != 0 && memcmp(PS_MARK_E, bytes + len - strlen(PS_MARK_E), strlen(PS_MARK_E)) != 0)||ret != len) if ((memcmp(PS_MARK_S, bytes + got, strlen(PS_MARK_S)) != 0 && memcmp(PS_MARK_E, bytes + len - strlen(PS_MARK_E), strlen(PS_MARK_E)) != 0)||ret != len) {
{
spdlog::error("invalid avformatctx: {} {}", ret, len); spdlog::error("invalid avformatctx: {} {}", ret, len);
return -1; return -1;
} }
...@@ -301,8 +291,7 @@ int decode(char *bytes, int len, AVFormatContext *pCtx) ...@@ -301,8 +291,7 @@ int decode(char *bytes, int len, AVFormatContext *pCtx)
pCtx->nb_streams = ret; pCtx->nb_streams = ret;
spdlog::debug("avctx decode streams:{}", ret); spdlog::debug("avctx decode streams:{}", ret);
int numExtra = ret; int numExtra = ret;
for (int i = 0; i < numExtra; i++) for (int i = 0; i < numExtra; i++) {
{
ret = 0; ret = 0;
pCtx->streams[i] = (AVStream *)av_malloc(sizeof(AVStream)); pCtx->streams[i] = (AVStream *)av_malloc(sizeof(AVStream));
memcpy(pCtx->streams[i], bytes + got, sizeof(AVStream)); memcpy(pCtx->streams[i], bytes + got, sizeof(AVStream));
...@@ -327,15 +316,14 @@ int decode(char *bytes, int len, AVFormatContext *pCtx) ...@@ -327,15 +316,14 @@ int decode(char *bytes, int len, AVFormatContext *pCtx)
if(len != ret) { if(len != ret) {
spdlog::error("avformatctx decode: {:d} {:d} {:d}", ret, len, got); spdlog::error("avformatctx decode: {:d} {:d} {:d}", ret, len, got);
} }
assert(ret == len); assert(ret == len);
return ret; return ret;
} }
void freeCtx(AVFormatContext *pCtx) void freeCtx(AVFormatContext *pCtx)
{ {
for (int i = 0; i < pCtx->nb_streams; i++) for (int i = 0; i < pCtx->nb_streams; i++) {
{
free(pCtx->streams[i]->codecpar); free(pCtx->streams[i]->codecpar);
if(pCtx->streams[i]->codecpar->extradata_size != 0) { if(pCtx->streams[i]->codecpar->extradata_size != 0) {
free(pCtx->streams[i]->codecpar->extradata); free(pCtx->streams[i]->codecpar->extradata);
......
/* /*
module: avcvhelper module: avcvhelper
description: description:
author: Bruce.Lu <lzbgt@icloud.com> author: Bruce.Lu <lzbgt@icloud.com>
update: 2019/08/23 update: 2019/08/23
*/ */
...@@ -90,7 +90,8 @@ void frame2mat(AVPixelFormat format, const AVFrame * frame, cv::Mat& image) ...@@ -90,7 +90,8 @@ void frame2mat(AVPixelFormat format, const AVFrame * frame, cv::Mat& image)
sws_freeContext(conversion); sws_freeContext(conversion);
} }
float getEntropy(cv::Mat &frame){ float getEntropy(cv::Mat &frame)
{
int histSize = 256; int histSize = 256;
/// Set the ranges ( for B,G,R) ) /// Set the ranges ( for B,G,R) )
float range[] = { 0, 256 } ; float range[] = { 0, 256 } ;
......
/* /*
module: common module: common
description: description:
author: Bruce.Lu <lzbgt@icloud.com> author: Bruce.Lu <lzbgt@icloud.com>
update: 2019/08/23 update: 2019/08/23
*/ */
......
/* /*
module: database module: database
description: description:
author: Bruce.Lu <lzbgt@icloud.com> author: Bruce.Lu <lzbgt@icloud.com>
update: 2019/08/23 update: 2019/08/23
*/ */
...@@ -8,7 +8,7 @@ update: 2019/08/23 ...@@ -8,7 +8,7 @@ update: 2019/08/23
#ifndef __DATABASE_SL__ #ifndef __DATABASE_SL__
#define __DATABASE_SL__ #define __DATABASE_SL__
extern "C" { extern "C" {
#include "../vendor/sqlite/sqlite3.h" #include "../vendor/sqlite/sqlite3.h"
} }
#include <string> #include <string>
...@@ -23,13 +23,13 @@ using namespace std; ...@@ -23,13 +23,13 @@ using namespace std;
using json = nlohmann::json; using json = nlohmann::json;
namespace DB { namespace DB {
typedef int (*callback)(void*,int,char**,char**); typedef int (*callback)(void*,int,char**,char**);
int exec(void *pUserData, char* fileName, const char* stmt, callback cb); int exec(void *pUserData, char* fileName, const char* stmt, callback cb);
int getInfo(void *info, int active, const char*fileName); int getInfo(void *info, int active, const char*fileName);
int clearTable(const char *tableName, const char* fileName); int clearTable(const char *tableName, const char* fileName);
int setInfo(void* info, const char*fileName); int setInfo(void* info, const char*fileName);
int loadLocalConfigration(json &config, string fileName); int loadLocalConfigration(json &config, string fileName);
int saveLocalConfigration(json &config, string fileName); int saveLocalConfigration(json &config, string fileName);
} }
#endif #endif
\ No newline at end of file
...@@ -10,51 +10,51 @@ using namespace nlohmann; ...@@ -10,51 +10,51 @@ using namespace nlohmann;
using namespace std; using namespace std;
namespace LVDB { namespace LVDB {
#define LVDB_PATH "/opt/lvldb/" #define LVDB_PATH "/opt/lvldb/"
// sn, config // sn, config
#define LVDB_FILE_GENERAL LVDB_PATH "general.db" #define LVDB_FILE_GENERAL LVDB_PATH "general.db"
// slices, log // slices, log
#define LVDB_FILE_LOG LVDB_PATH"log.db" #define LVDB_FILE_LOG LVDB_PATH"log.db"
#define LVDB_KEY_SUFFIX_BACK "_bak" #define LVDB_KEY_SUFFIX_BACK "_bak"
#define LVDB_KEY_SN "SN" #define LVDB_KEY_SN "SN"
#define LVDB_KEY_CONFIG "CONFIG" #define LVDB_KEY_CONFIG "CONFIG"
typedef int (*cb_verify_str)(const string&); typedef int (*cb_verify_str)(const string&);
typedef int (*cb_verify_json)(const json&); typedef int (*cb_verify_json)(const json&);
int setValue(const string &value, string key, string fileName="", cb_verify_str cb=NULL); int setValue(const string &value, string key, string fileName="", cb_verify_str cb=NULL);
int getValue(string &value, string key, string fileName="", cb_verify_str cb=NULL); int getValue(string &value, string key, string fileName="", cb_verify_str cb=NULL);
int setValue(const json &value, string key, string fileName="", cb_verify_json cb=NULL); int setValue(const json &value, string key, string fileName="", cb_verify_json cb=NULL);
int getValue(json &value, string key, string fileName="", cb_verify_json cb=NULL); int getValue(json &value, string key, string fileName="", cb_verify_json cb=NULL);
// //
json * findConfigModule(json &config, string sn, string moduleName, int iid); json * findConfigModule(json &config, string sn, string moduleName, int iid);
// //
int delValue(string key, string fileName); int delValue(string key, string fileName);
// //
vector<string> getKeys(string fileName = ""); vector<string> getKeys(string fileName = "");
// sn, updatetime, boottime // sn, updatetime, boottime
int setSn(json &info,string fileName=LVDB_FILE_GENERAL); int setSn(json &info,string fileName=LVDB_FILE_GENERAL);
int getSn(json &info,string fileName=LVDB_FILE_GENERAL); int getSn(json &info,string fileName=LVDB_FILE_GENERAL);
// cloudutils::config // cloudutils::config
int getLocalConfig(json &config, string key = "", string fileName=LVDB_FILE_GENERAL); int getLocalConfig(json &config, string key = "", string fileName=LVDB_FILE_GENERAL);
int setLocalConfig(json &config, string key = "", string fileName=LVDB_FILE_GENERAL); int setLocalConfig(json &config, string key = "", string fileName=LVDB_FILE_GENERAL);
// slices // slices
int getSlices(json &slices, string fileName); int getSlices(json &slices, string fileName);
int setSlices(json &slices, string fileName); int setSlices(json &slices, string fileName);
// log // log
int getLog(json &log, json &writeOptions, string fileName); int getLog(json &log, json &writeOptions, string fileName);
int setLog(json &log, json &readOptions, string fileName); int setLog(json &log, json &readOptions, string fileName);
typedef int(*cb_traverse_configration_module)(string modname, json &mod, void *pUser); typedef int(*cb_traverse_configration_module)(string modname, json &mod, void *pUser);
int traverseConfigureModules(json &config, cb_traverse_configration_module cb, void *pUser = NULL, string moduleName = ""); int traverseConfigureModules(json &config, cb_traverse_configration_module cb, void *pUser = NULL, string moduleName = "");
} // namespace LVDB } // namespace LVDB
#endif #endif
\ No newline at end of file
...@@ -58,7 +58,7 @@ using namespace ghc::filesystem; ...@@ -58,7 +58,7 @@ using namespace ghc::filesystem;
using ifstream = ghc::filesystem::ifstream; using ifstream = ghc::filesystem::ifstream;
using ofstream = ghc::filesystem::ofstream; using ofstream = ghc::filesystem::ofstream;
using fstream = ghc::filesystem::fstream; using fstream = ghc::filesystem::fstream;
} }
#endif #endif
#endif // GHC_FILESYSTEM_STD_H #endif // GHC_FILESYSTEM_STD_H
...@@ -62,7 +62,7 @@ using namespace ghc::filesystem; ...@@ -62,7 +62,7 @@ using namespace ghc::filesystem;
using ifstream = ghc::filesystem::ifstream; using ifstream = ghc::filesystem::ifstream;
using ofstream = ghc::filesystem::ofstream; using ofstream = ghc::filesystem::ofstream;
using fstream = ghc::filesystem::fstream; using fstream = ghc::filesystem::fstream;
} }
#endif #endif
#endif // GHC_FILESYSTEM_STD_FWD_H #endif // GHC_FILESYSTEM_STD_FWD_H
...@@ -34,8 +34,7 @@ static const size_t default_async_q_size = 8192; ...@@ -34,8 +34,7 @@ static const size_t default_async_q_size = 8192;
// if a global thread pool doesn't already exist, create it with default queue // if a global thread pool doesn't already exist, create it with default queue
// size of 8192 items and single thread. // size of 8192 items and single thread.
template<async_overflow_policy OverflowPolicy = async_overflow_policy::block> template<async_overflow_policy OverflowPolicy = async_overflow_policy::block>
struct async_factory_impl struct async_factory_impl {
{
template<typename Sink, typename... SinkArgs> template<typename Sink, typename... SinkArgs>
static std::shared_ptr<async_logger> create(std::string logger_name, SinkArgs &&... args) static std::shared_ptr<async_logger> create(std::string logger_name, SinkArgs &&... args)
{ {
...@@ -44,8 +43,7 @@ struct async_factory_impl ...@@ -44,8 +43,7 @@ struct async_factory_impl
// create global thread pool if not already exists.. // create global thread pool if not already exists..
std::lock_guard<std::recursive_mutex> tp_lock(registry_inst.tp_mutex()); std::lock_guard<std::recursive_mutex> tp_lock(registry_inst.tp_mutex());
auto tp = registry_inst.get_tp(); auto tp = registry_inst.get_tp();
if (tp == nullptr) if (tp == nullptr) {
{
tp = std::make_shared<details::thread_pool>(details::default_async_q_size, 1); tp = std::make_shared<details::thread_pool>(details::default_async_q_size, 1);
registry_inst.set_tp(tp); registry_inst.set_tp(tp);
} }
......
...@@ -29,31 +29,29 @@ ...@@ -29,31 +29,29 @@
namespace spdlog { namespace spdlog {
// Async overflow policy - block by default. // Async overflow policy - block by default.
enum class async_overflow_policy enum class async_overflow_policy {
{
block, // Block until message can be enqueued block, // Block until message can be enqueued
overrun_oldest // Discard oldest message in the queue if full when trying to overrun_oldest // Discard oldest message in the queue if full when trying to
// add new item. // add new item.
}; };
namespace details { namespace details {
class thread_pool; class thread_pool;
} }
class async_logger final : public std::enable_shared_from_this<async_logger>, public logger class async_logger final : public std::enable_shared_from_this<async_logger>, public logger {
{
friend class details::thread_pool; friend class details::thread_pool;
public: public:
template<typename It> template<typename It>
async_logger(std::string logger_name, It begin, It end, std::weak_ptr<details::thread_pool> tp, async_logger(std::string logger_name, It begin, It end, std::weak_ptr<details::thread_pool> tp,
async_overflow_policy overflow_policy = async_overflow_policy::block); async_overflow_policy overflow_policy = async_overflow_policy::block);
async_logger(std::string logger_name, sinks_init_list sinks_list, std::weak_ptr<details::thread_pool> tp, async_logger(std::string logger_name, sinks_init_list sinks_list, std::weak_ptr<details::thread_pool> tp,
async_overflow_policy overflow_policy = async_overflow_policy::block); async_overflow_policy overflow_policy = async_overflow_policy::block);
async_logger(std::string logger_name, sink_ptr single_sink, std::weak_ptr<details::thread_pool> tp, async_logger(std::string logger_name, sink_ptr single_sink, std::weak_ptr<details::thread_pool> tp,
async_overflow_policy overflow_policy = async_overflow_policy::block); async_overflow_policy overflow_policy = async_overflow_policy::block);
std::shared_ptr<logger> clone(std::string new_name) override; std::shared_ptr<logger> clone(std::string new_name) override;
......
...@@ -108,8 +108,7 @@ using level_t = std::atomic<int>; ...@@ -108,8 +108,7 @@ using level_t = std::atomic<int>;
// Log level enum // Log level enum
namespace level { namespace level {
enum level_enum enum level_enum {
{
trace = SPDLOG_LEVEL_TRACE, trace = SPDLOG_LEVEL_TRACE,
debug = SPDLOG_LEVEL_DEBUG, debug = SPDLOG_LEVEL_DEBUG,
info = SPDLOG_LEVEL_INFO, info = SPDLOG_LEVEL_INFO,
...@@ -127,25 +126,21 @@ enum level_enum ...@@ -127,25 +126,21 @@ enum level_enum
#endif #endif
static string_view_t level_string_views[] SPDLOG_LEVEL_NAMES; static string_view_t level_string_views[] SPDLOG_LEVEL_NAMES;
static const char *short_level_names[]{"T", "D", "I", "W", "E", "C", "O"}; static const char *short_level_names[] {"T", "D", "I", "W", "E", "C", "O"};
inline string_view_t &to_string_view(spdlog::level::level_enum l) SPDLOG_NOEXCEPT inline string_view_t &to_string_view(spdlog::level::level_enum l) SPDLOG_NOEXCEPT {
{
return level_string_views[l]; return level_string_views[l];
} }
inline const char *to_short_c_str(spdlog::level::level_enum l) SPDLOG_NOEXCEPT inline const char *to_short_c_str(spdlog::level::level_enum l) SPDLOG_NOEXCEPT {
{
return short_level_names[l]; return short_level_names[l];
} }
inline spdlog::level::level_enum from_str(const std::string &name) SPDLOG_NOEXCEPT inline spdlog::level::level_enum from_str(const std::string &name) SPDLOG_NOEXCEPT {
{
int level = 0; int level = 0;
for (const auto &level_str : level_string_views) for (const auto &level_str : level_string_views)
{ {
if (level_str == name) if (level_str == name) {
{
return static_cast<level::level_enum>(level); return static_cast<level::level_enum>(level);
} }
level++; level++;
...@@ -160,8 +155,7 @@ using level_hasher = std::hash<int>; ...@@ -160,8 +155,7 @@ using level_hasher = std::hash<int>;
// Pattern time - specific time getting to use for pattern_formatter. // Pattern time - specific time getting to use for pattern_formatter.
// local time by default // local time by default
// //
enum class pattern_time_type enum class pattern_time_type {
{
local, // log localtime local, // log localtime
utc // log utc utc // log utc
}; };
...@@ -169,8 +163,7 @@ enum class pattern_time_type ...@@ -169,8 +163,7 @@ enum class pattern_time_type
// //
// Log exception // Log exception
// //
class spdlog_ex : public std::exception class spdlog_ex : public std::exception {
{
public: public:
explicit spdlog_ex(std::string msg) explicit spdlog_ex(std::string msg)
: msg_(std::move(msg)) : msg_(std::move(msg))
...@@ -202,8 +195,7 @@ using filename_t = std::wstring; ...@@ -202,8 +195,7 @@ using filename_t = std::wstring;
using filename_t = std::string; using filename_t = std::string;
#endif #endif
struct source_loc struct source_loc {
{
SPDLOG_CONSTEXPR source_loc() SPDLOG_CONSTEXPR source_loc()
: filename{""} : filename{""}
, line{0} , line{0}
......
...@@ -31,7 +31,10 @@ inline spdlog::async_logger::async_logger( ...@@ -31,7 +31,10 @@ inline spdlog::async_logger::async_logger(
inline spdlog::async_logger::async_logger( inline spdlog::async_logger::async_logger(
std::string logger_name, sink_ptr single_sink, std::weak_ptr<details::thread_pool> tp, async_overflow_policy overflow_policy) std::string logger_name, sink_ptr single_sink, std::weak_ptr<details::thread_pool> tp, async_overflow_policy overflow_policy)
: async_logger(std::move(logger_name), {std::move(single_sink)}, std::move(tp), overflow_policy) : async_logger(std::move(logger_name),
{
std::move(single_sink)
}, std::move(tp), overflow_policy)
{ {
} }
...@@ -41,12 +44,10 @@ inline void spdlog::async_logger::sink_it_(details::log_msg &msg) ...@@ -41,12 +44,10 @@ inline void spdlog::async_logger::sink_it_(details::log_msg &msg)
#if defined(SPDLOG_ENABLE_MESSAGE_COUNTER) #if defined(SPDLOG_ENABLE_MESSAGE_COUNTER)
incr_msg_counter_(msg); incr_msg_counter_(msg);
#endif #endif
if (auto pool_ptr = thread_pool_.lock()) if (auto pool_ptr = thread_pool_.lock()) {
{
pool_ptr->post_log(shared_from_this(), msg, overflow_policy_); pool_ptr->post_log(shared_from_this(), msg, overflow_policy_);
} }
else else {
{
throw spdlog_ex("async log: thread pool doesn't exist anymore"); throw spdlog_ex("async log: thread pool doesn't exist anymore");
} }
} }
...@@ -54,12 +55,10 @@ inline void spdlog::async_logger::sink_it_(details::log_msg &msg) ...@@ -54,12 +55,10 @@ inline void spdlog::async_logger::sink_it_(details::log_msg &msg)
// send flush request to the thread pool // send flush request to the thread pool
inline void spdlog::async_logger::flush_() inline void spdlog::async_logger::flush_()
{ {
if (auto pool_ptr = thread_pool_.lock()) if (auto pool_ptr = thread_pool_.lock()) {
{
pool_ptr->post_flush(shared_from_this(), overflow_policy_); pool_ptr->post_flush(shared_from_this(), overflow_policy_);
} }
else else {
{
throw spdlog_ex("async flush: thread pool doesn't exist anymore"); throw spdlog_ex("async flush: thread pool doesn't exist anymore");
} }
} }
...@@ -69,30 +68,24 @@ inline void spdlog::async_logger::flush_() ...@@ -69,30 +68,24 @@ inline void spdlog::async_logger::flush_()
// //
inline void spdlog::async_logger::backend_log_(const details::log_msg &incoming_log_msg) inline void spdlog::async_logger::backend_log_(const details::log_msg &incoming_log_msg)
{ {
try try {
{ for (auto &s : sinks_) {
for (auto &s : sinks_) if (s->should_log(incoming_log_msg.level)) {
{
if (s->should_log(incoming_log_msg.level))
{
s->log(incoming_log_msg); s->log(incoming_log_msg);
} }
} }
} }
SPDLOG_CATCH_AND_HANDLE SPDLOG_CATCH_AND_HANDLE
if (should_flush_(incoming_log_msg)) if (should_flush_(incoming_log_msg)) {
{
backend_flush_(); backend_flush_();
} }
} }
inline void spdlog::async_logger::backend_flush_() inline void spdlog::async_logger::backend_flush_()
{ {
try try {
{ for (auto &sink : sinks_) {
for (auto &sink : sinks_)
{
sink->flush(); sink->flush();
} }
} }
......
...@@ -11,8 +11,7 @@ ...@@ -11,8 +11,7 @@
namespace spdlog { namespace spdlog {
namespace details { namespace details {
template<typename T> template<typename T>
class circular_q class circular_q {
{
public: public:
using item_type = T; using item_type = T;
...@@ -28,8 +27,7 @@ public: ...@@ -28,8 +27,7 @@ public:
v_[tail_] = std::move(item); v_[tail_] = std::move(item);
tail_ = (tail_ + 1) % max_items_; tail_ = (tail_ + 1) % max_items_;
if (tail_ == head_) // overrun last item if full if (tail_ == head_) { // overrun last item if full
{
head_ = (head_ + 1) % max_items_; head_ = (head_ + 1) % max_items_;
++overrun_counter_; ++overrun_counter_;
} }
......
...@@ -23,8 +23,7 @@ ...@@ -23,8 +23,7 @@
namespace spdlog { namespace spdlog {
namespace details { namespace details {
struct console_stdout struct console_stdout {
{
static std::FILE *stream() static std::FILE *stream()
{ {
return stdout; return stdout;
...@@ -37,8 +36,7 @@ struct console_stdout ...@@ -37,8 +36,7 @@ struct console_stdout
#endif #endif
}; };
struct console_stderr struct console_stderr {
{
static std::FILE *stream() static std::FILE *stream()
{ {
return stderr; return stderr;
...@@ -51,8 +49,7 @@ struct console_stderr ...@@ -51,8 +49,7 @@ struct console_stderr
#endif #endif
}; };
struct console_mutex struct console_mutex {
{
using mutex_t = std::mutex; using mutex_t = std::mutex;
static mutex_t &mutex() static mutex_t &mutex()
{ {
...@@ -61,8 +58,7 @@ struct console_mutex ...@@ -61,8 +58,7 @@ struct console_mutex
} }
}; };
struct console_nullmutex struct console_nullmutex {
{
using mutex_t = null_mutex; using mutex_t = null_mutex;
static mutex_t &mutex() static mutex_t &mutex()
{ {
......
...@@ -22,8 +22,7 @@ ...@@ -22,8 +22,7 @@
namespace spdlog { namespace spdlog {
namespace details { namespace details {
class file_helper class file_helper {
{
public: public:
const int open_tries = 5; const int open_tries = 5;
...@@ -44,10 +43,8 @@ public: ...@@ -44,10 +43,8 @@ public:
close(); close();
auto *mode = truncate ? SPDLOG_FILENAME_T("wb") : SPDLOG_FILENAME_T("ab"); auto *mode = truncate ? SPDLOG_FILENAME_T("wb") : SPDLOG_FILENAME_T("ab");
_filename = fname; _filename = fname;
for (int tries = 0; tries < open_tries; ++tries) for (int tries = 0; tries < open_tries; ++tries) {
{ if (!os::fopen_s(&fd_, fname, mode)) {
if (!os::fopen_s(&fd_, fname, mode))
{
return; return;
} }
...@@ -59,8 +56,7 @@ public: ...@@ -59,8 +56,7 @@ public:
void reopen(bool truncate) void reopen(bool truncate)
{ {
if (_filename.empty()) if (_filename.empty()) {
{
throw spdlog_ex("Failed re opening file - was not opened before"); throw spdlog_ex("Failed re opening file - was not opened before");
} }
open(_filename, truncate); open(_filename, truncate);
...@@ -73,8 +69,7 @@ public: ...@@ -73,8 +69,7 @@ public:
void close() void close()
{ {
if (fd_ != nullptr) if (fd_ != nullptr) {
{
std::fclose(fd_); std::fclose(fd_);
fd_ = nullptr; fd_ = nullptr;
} }
...@@ -84,16 +79,14 @@ public: ...@@ -84,16 +79,14 @@ public:
{ {
size_t msg_size = buf.size(); size_t msg_size = buf.size();
auto data = buf.data(); auto data = buf.data();
if (std::fwrite(data, 1, msg_size, fd_) != msg_size) if (std::fwrite(data, 1, msg_size, fd_) != msg_size) {
{
throw spdlog_ex("Failed writing to file " + os::filename_to_str(_filename), errno); throw spdlog_ex("Failed writing to file " + os::filename_to_str(_filename), errno);
} }
} }
size_t size() const size_t size() const
{ {
if (fd_ == nullptr) if (fd_ == nullptr) {
{
throw spdlog_ex("Cannot use size() on closed file " + os::filename_to_str(_filename)); throw spdlog_ex("Cannot use size() on closed file " + os::filename_to_str(_filename));
} }
return os::filesize(fd_); return os::filesize(fd_);
...@@ -128,15 +121,13 @@ public: ...@@ -128,15 +121,13 @@ public:
// no valid extension found - return whole path and empty string as // no valid extension found - return whole path and empty string as
// extension // extension
if (ext_index == filename_t::npos || ext_index == 0 || ext_index == fname.size() - 1) if (ext_index == filename_t::npos || ext_index == 0 || ext_index == fname.size() - 1) {
{
return std::make_tuple(fname, spdlog::filename_t()); return std::make_tuple(fname, spdlog::filename_t());
} }
// treat casese like "/etc/rc.d/somelogfile or "/abc/.hiddenfile" // treat casese like "/etc/rc.d/somelogfile or "/abc/.hiddenfile"
auto folder_index = fname.rfind(details::os::folder_sep); auto folder_index = fname.rfind(details::os::folder_sep);
if (folder_index != filename_t::npos && folder_index >= ext_index - 1) if (folder_index != filename_t::npos && folder_index >= ext_index - 1) {
{
return std::make_tuple(fname, spdlog::filename_t()); return std::make_tuple(fname, spdlog::filename_t());
} }
......
...@@ -14,8 +14,7 @@ namespace details { ...@@ -14,8 +14,7 @@ namespace details {
namespace fmt_helper { namespace fmt_helper {
template<size_t Buffer_Size> template<size_t Buffer_Size>
inline spdlog::string_view_t to_string_view(const fmt::basic_memory_buffer<char, Buffer_Size> &buf) SPDLOG_NOEXCEPT inline spdlog::string_view_t to_string_view(const fmt::basic_memory_buffer<char, Buffer_Size> &buf) SPDLOG_NOEXCEPT {
{
return spdlog::string_view_t(buf.data(), buf.size()); return spdlog::string_view_t(buf.data(), buf.size());
} }
...@@ -30,8 +29,7 @@ template<size_t Buffer_Size> ...@@ -30,8 +29,7 @@ template<size_t Buffer_Size>
inline void append_string_view(spdlog::string_view_t view, fmt::basic_memory_buffer<char, Buffer_Size> &dest) inline void append_string_view(spdlog::string_view_t view, fmt::basic_memory_buffer<char, Buffer_Size> &dest)
{ {
auto *buf_ptr = view.data(); auto *buf_ptr = view.data();
if (buf_ptr != nullptr) if (buf_ptr != nullptr) {
{
dest.append(buf_ptr, buf_ptr + view.size()); dest.append(buf_ptr, buf_ptr + view.size());
} }
} }
...@@ -53,22 +51,18 @@ inline unsigned count_digits(T n) ...@@ -53,22 +51,18 @@ inline unsigned count_digits(T n)
template<size_t Buffer_Size> template<size_t Buffer_Size>
inline void pad2(int n, fmt::basic_memory_buffer<char, Buffer_Size> &dest) inline void pad2(int n, fmt::basic_memory_buffer<char, Buffer_Size> &dest)
{ {
if (n > 99) if (n > 99) {
{
append_int(n, dest); append_int(n, dest);
} }
else if (n > 9) // 10-99 else if (n > 9) { // 10-99
{
dest.push_back(static_cast<char>('0' + n / 10)); dest.push_back(static_cast<char>('0' + n / 10));
dest.push_back(static_cast<char>('0' + n % 10)); dest.push_back(static_cast<char>('0' + n % 10));
} }
else if (n >= 0) // 0-9 else if (n >= 0) { // 0-9
{
dest.push_back('0'); dest.push_back('0');
dest.push_back(static_cast<char>('0' + n)); dest.push_back(static_cast<char>('0' + n));
} }
else // negatives (unlikely, but just in case, let fmt deal with it) else { // negatives (unlikely, but just in case, let fmt deal with it)
{
fmt::format_to(dest, "{:02}", n); fmt::format_to(dest, "{:02}", n);
} }
} }
...@@ -78,8 +72,7 @@ inline void pad_uint(T n, unsigned int width, fmt::basic_memory_buffer<char, Buf ...@@ -78,8 +72,7 @@ inline void pad_uint(T n, unsigned int width, fmt::basic_memory_buffer<char, Buf
{ {
static_assert(std::is_unsigned<T>::value, "pad_uint must get unsigned T"); static_assert(std::is_unsigned<T>::value, "pad_uint must get unsigned T");
auto digits = count_digits(n); auto digits = count_digits(n);
if (width > digits) if (width > digits) {
{
const char *zeroes = "0000000000000000000"; const char *zeroes = "0000000000000000000";
dest.append(zeroes, zeroes + width - digits); dest.append(zeroes, zeroes + width - digits);
} }
......
...@@ -13,8 +13,7 @@ ...@@ -13,8 +13,7 @@
namespace spdlog { namespace spdlog {
namespace details { namespace details {
struct log_msg struct log_msg {
{
log_msg(source_loc loc, const std::string *loggers_name, level::level_enum lvl, string_view_t view) log_msg(source_loc loc, const std::string *loggers_name, level::level_enum lvl, string_view_t view)
: logger_name(loggers_name) : logger_name(loggers_name)
......
...@@ -10,8 +10,7 @@ ...@@ -10,8 +10,7 @@
namespace spdlog { namespace spdlog {
namespace details { namespace details {
struct null_mutex struct null_mutex {
{
void lock() {} void lock() {}
void unlock() {} void unlock() {}
bool try_lock() bool try_lock()
...@@ -20,8 +19,7 @@ struct null_mutex ...@@ -20,8 +19,7 @@ struct null_mutex
} }
}; };
struct null_atomic_int struct null_atomic_int {
{
int value; int value;
null_atomic_int() = default; null_atomic_int() = default;
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论