From 4caf18be5b4e75b025bd98e44970c1d8502b17d3 Mon Sep 17 00:00:00 2001 From: wlxuz Date: Mon, 9 Sep 2024 09:55:03 +0800 Subject: [PATCH 1/7] =?UTF-8?q?=E4=BF=AE=E6=94=B9utils?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: wlxuz Change-Id: I6fe2388452598c7b591c49797c22640cf29dcfeb --- CMakeLists.txt | 14 +- conditional_variable.h | 2 +- conditional_variable_posix.cpp | 75 ++-- config.cpp | 157 -------- config.h | 91 ----- custom.cpp | 665 +++++++++++++++++---------------- custom.h | 50 +-- decrypt.cpp | 192 ---------- decrypt.h | 39 -- dfile.cpp | 230 ++++++------ fixlist.cpp | 161 ++++---- fixlist.h | 43 +-- lock.h | 5 +- lock_posix.cpp | 136 ++++--- logger.cpp | 84 ++++- logger.h | 286 ++++++-------- macro.h | 101 +++++ shared_ptr.h | 4 +- shellcmd.cpp | 74 ++-- shellcmd.h | 15 +- signals.h | 42 --- signals_posix.cpp | 155 -------- socket_request.cpp | 324 ---------------- socket_request.h | 63 ---- sqlite.cpp | 217 ----------- sqlite.h | 70 ---- threads/thread.h | 4 +- threads/thread_delegate.cc | 8 +- threads/thread_delegate.h | 2 +- threads/thread_posix.cc | 40 +- timer.cc | 8 +- 31 files changed, 1047 insertions(+), 2310 deletions(-) delete mode 100755 config.cpp delete mode 100755 config.h delete mode 100644 decrypt.cpp delete mode 100644 decrypt.h create mode 100644 macro.h delete mode 100755 signals.h delete mode 100755 signals_posix.cpp delete mode 100755 socket_request.cpp delete mode 100755 socket_request.h delete mode 100755 sqlite.cpp delete mode 100755 sqlite.h diff --git a/CMakeLists.txt b/CMakeLists.txt index 7c56596..8b2603b 100755 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2,16 +2,14 @@ set(MODULE utils) aux_source_directory(. DIRSRCS) aux_source_directory(./threads/ DIRSRCS) -#aux_source_directory(./worker/ DIRSRCS) -#aux_source_directory(./cppDES/cppDES/ DIRSRCS) + include_directories( ./ ../include) add_library(${MODULE} ${DIRSRCS}) -if (DAS_ACQUIRE OR DAS_CLIENT) - target_link_libraries(${MODULE} sqlite3 crypto) -endif() -target_link_libraries(${MODULE} pthread rt inifile2 event) -#target_link_libraries(${MODULE} ${CMAKE_BINARY_DIR}/thirdparty/Libevent/lib/libevent.a) -#target_link_libraries(${MODULE} ${CMAKE_BINARY_DIR}/thirdparty/Libevent/lib/libevent_pthreads.a) +target_link_libraries(${MODULE} pthread rt) + +install(TARGETS ${MODULE} + DESTINATION lib/ + PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE GROUP_READ GROUP_EXECUTE WORLD_READ) \ No newline at end of file diff --git a/conditional_variable.h b/conditional_variable.h index c12b0a6..63d8b5a 100755 --- a/conditional_variable.h +++ b/conditional_variable.h @@ -47,6 +47,6 @@ class ConditionalVariable { pthread_cond_t cond_var_; private: - DISALLOW_COPY_AND_ASSIGN(ConditionalVariable); + DISALLOW_COPY_AND_ASSIGN(ConditionalVariable); }; // namespace sync_primitives #endif // SRC_COMPONENTS_INCLUDE_UTILS_CONDITIONAL_VARIABLE_H_ diff --git a/conditional_variable_posix.cpp b/conditional_variable_posix.cpp index c16d503..facd59b 100755 --- a/conditional_variable_posix.cpp +++ b/conditional_variable_posix.cpp @@ -13,57 +13,57 @@ const long kNanosecondsPerMillisecond = 1000000; } ConditionalVariable::ConditionalVariable() { - pthread_condattr_t attrs; - int initialized = pthread_condattr_init(&attrs); - if (initialized != 0) - LOG_ERR("Failed to initialize conditional variable attributes"); - pthread_condattr_setclock(&attrs, CLOCK_MONOTONIC); - initialized = pthread_cond_init(&cond_var_, &attrs); - if (initialized != 0) - LOG_ERR("Failed to initialize " - "conditional variable"); - int rv = pthread_condattr_destroy(&attrs); - if (rv != 0) - LOG_ERR("Failed to destroy conditional variable attributes"); + pthread_condattr_t attrs; + int initialized = pthread_condattr_init(&attrs); + if (initialized != 0) + HTELINK_LOG_ERR("Failed to initialize conditional variable attributes"); + pthread_condattr_setclock(&attrs, CLOCK_MONOTONIC); + initialized = pthread_cond_init(&cond_var_, &attrs); + if (initialized != 0) + HTELINK_LOG_ERR("Failed to initialize " + "conditional variable"); + int rv = pthread_condattr_destroy(&attrs); + if (rv != 0) + HTELINK_LOG_ERR("Failed to destroy conditional variable attributes"); } ConditionalVariable::~ConditionalVariable() { - pthread_cond_destroy(&cond_var_); + pthread_cond_destroy(&cond_var_); } void ConditionalVariable::NotifyOne() { - int signaled = pthread_cond_signal(&cond_var_); - if (signaled != 0) - LOG_ERR("Failed to signal conditional variable"); + int signaled = pthread_cond_signal(&cond_var_); + if (signaled != 0) + HTELINK_LOG_ERR("Failed to signal conditional variable"); } void ConditionalVariable::Broadcast() { - int signaled = pthread_cond_broadcast(&cond_var_); - if (signaled != 0) - LOG_ERR("Failed to broadcast conditional variable"); + int signaled = pthread_cond_broadcast(&cond_var_); + if (signaled != 0) + HTELINK_LOG_ERR("Failed to broadcast conditional variable"); } bool ConditionalVariable::Wait(Lock& lock) { - lock.AssertTakenAndMarkFree(); - int wait_status = pthread_cond_wait(&cond_var_, &lock.mutex_); - lock.AssertFreeAndMarkTaken(); - if (wait_status != 0) { - LOG_ERR("Failed to wait for conditional variable"); - return false; - } - return true; + lock.AssertTakenAndMarkFree(); + int wait_status = pthread_cond_wait(&cond_var_, &lock.mutex_); + lock.AssertFreeAndMarkTaken(); + if (wait_status != 0) { + HTELINK_LOG_ERR("Failed to wait for conditional variable"); + return false; + } + return true; } bool ConditionalVariable::Wait(AutoLock& auto_lock) { - Lock& lock = auto_lock.GetLock(); - lock.AssertTakenAndMarkFree(); - int wait_status = pthread_cond_wait(&cond_var_, &lock.mutex_); - lock.AssertFreeAndMarkTaken(); - if (wait_status != 0) { - LOG_ERR("Failed to wait for conditional variable"); - return false; - } - return true; + Lock &lock = auto_lock.GetLock(); + lock.AssertTakenAndMarkFree(); + int wait_status = pthread_cond_wait(&cond_var_, &lock.mutex_); + lock.AssertFreeAndMarkTaken(); + if (wait_status != 0) { + HTELINK_LOG_ERR("Failed to wait for conditional variable"); + return false; + } + return true; } ConditionalVariable::WaitStatus ConditionalVariable::WaitFor( @@ -97,8 +97,7 @@ ConditionalVariable::WaitStatus ConditionalVariable::WaitFor( break; } default: { - LOG_ERR("Failed to timewait for conditional variable timedwait_status: %d" - ,timedwait_status); + HTELINK_LOG_ERR("Failed to timewait for conditional variable timedwait_status: %d", timedwait_status); } } return wait_status; diff --git a/config.cpp b/config.cpp deleted file mode 100755 index 2eaa922..0000000 --- a/config.cpp +++ /dev/null @@ -1,157 +0,0 @@ -/************************************************************************* - > File Name: config.cpp - > Author: xuwenlong - > Mail: myxuan475@126.com - > Created Time: 2018年04月28日 星期六 14时31分09秒 - ************************************************************************/ - -#include "config.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace utils -{ - -using namespace std; -using namespace inifile; - -string GetCompletePath(const string &file) -{ - string path; - path = getenv(CONFIG_DIR_ENV); - path +="/config/"+file; - return path; -} - -BOOL GetSectionList(const string& pszSectionName,map &mapList) -{ - IniFile ini; - if (-1 == ini.load(GetCompletePath("Config.ini"))) - return FALSE; - int ret = ini.getValues(pszSectionName,mapList); - return ret == 0; -} - -void WriteSectionList( - const string& pszSectionName,map &maplist) -{ - IniFile ini; - if (RET_ERR == ini.load(GetCompletePath("Config.ini"))) - return; - for (map::iterator iter=maplist.begin(); - iter!=maplist.end();iter++) { - ini.setValue(pszSectionName,iter->first,iter->second); - } - ini.save(); -} - -void WriteConfigFileStringValue( - const string &file,const string &pszSectionName, - const string &pszKeyName,const string &pszValue) -{ - IniFile ini; - if (RET_ERR == ini.load(GetCompletePath(file))) - return; - ini.setValue(pszSectionName,pszKeyName,pszValue); - ini.save(); -} - -void WriteConfigFileIntValue( - const string &file,const string &pszSectionName, - const string &pszKeyName,S32 pszValue) -{ - IniFile ini; - if (RET_ERR == ini.load(GetCompletePath(file))) - return; - stringstream ss; - ss< File Name: config.h - > Author: xuwenlong - > Mail: myxuan475@126.com - > Created Time: 2018年04月28日 星期六 14时31分17秒 - ************************************************************************/ -/********************************************************************** -* 版权所有 (C)2015, Zhou Zhaoxiong。 -* -* 文件名称:GetConfig.c -* 文件标识:无 -* 内容摘要:演示Linux下配置文件的读取方法 -* 其它说明:无 -* 当前版本:V1.0 -* 作 者:Zhou Zhaoxiong -* 完成日期:20150507 -* -**********************************************************************/ - -#ifndef __FILE_CONFIG_H__ -#define __FILE_CONFIG_H__ - -#include -#include -#include -#include -#include -#include - -namespace utils { - -using namespace std; - -/********************************************************************** -* 功能描述: 获取配置文件完整路径(包含文件名) -* 输入参数: pszConfigFileName-配置文件名 - pszWholePath-配置文件完整路径(包含文件名) -* 输出参数: 无 -* 返 回 值: 无 -* 其它说明: 无 -* 修改日期 版本号 修改人 修改内容 -* ------------------------------------------------------------------ -* 20150507 V1.0 Zhou Zhaoxiong 创建 -********************************************************************/ -std::string GetCompletePath(const string &file); - -BOOL GetSectionList(const string& pszSectionName,map &mapList); -void WriteSectionList( - const string& pszSectionName,map &maplist); - -void WriteConfigFileStringValue(const string &file,const string &pszSectionName,const string &pszKeyName, const string &pszValue); - -void WriteConfigFileIntValue(const string &file,const string &pszSectionName,const string &pszKeyName, S32 pszValue); - -bool HasSection(const string &file,const string §ion); -/********************************************************************** -* 功能描述: 从配置文件中获取字符串 -* 输入参数: pszSectionName-段名, 如: GENERAL - pszKeyName-配置项名, 如: EmployeeName - pDefaultVal-默认值 - iOutputLen-输出缓存长度 - pszConfigFileName-配置文件名 -* 输出参数: pszOutput-输出缓存 -* 返 回 值: 无 -* 其它说明: 无 -* 修改日期 版本号 修改人 修改内容 -* ------------------------------------------------------------------ -* 20150507 V1.0 Zhou Zhaoxiong 创建 -********************************************************************/ -string GetConfigFileStringValue(const string &file, const string &pszSectionName, const string &pszKeyName, const string &pDefaultVal); - - -/********************************************************************** -* 功能描述: 从配置文件中获取整型变量 -* 输入参数: pszSectionName-段名, 如: GENERAL - pszKeyName-配置项名, 如: EmployeeName - iDefaultVal-默认值 - pszConfigFileName-配置文件名 -* 输出参数: 无 -* 返 回 值: iGetValue-获取到的整数值 -1-获取失败 -* 其它说明: 无 -* 修改日期 版本号 修改人 修改内容 -* ------------------------------------------------------------------ -* 20150507 V1.0 Zhou Zhaoxiong 创建 -********************************************************************/ -S32 GetConfigFileIntValue(const string &file, const string &pszSectionName, const string &pszKeyName, U32 iDefaultVal); - -F32 GetConfigFileFloatValue(const string &file, const string &pszSectionName, const string &pszKeyName, F32 iDefaultVal); - -} -#endif diff --git a/custom.cpp b/custom.cpp index 765f9c9..b82a032 100755 --- a/custom.cpp +++ b/custom.cpp @@ -1,70 +1,80 @@ /************************************************************************* - > File Name: custom.cpp - > Author: xuwenlong - > Mail: myxuan475@126.com - > Created Time: 2018年02月01日 星期四 13时47分45秒 + > File Name: custom.cpp + > Author: xuwenlong + > Mail: myxuan475@126.com + > Created Time: 2018年02月01日 星期四 13时47分45秒 ************************************************************************/ -#include -#include -#include -#include -#include +#include "custom.h" #include #include -#include -#include -#include #include +#include +#include +#include +#include +#include +#include #include #include -#include "custom.h" +#include +#include +#include namespace utils { -using namespace std; -vector Split(const char *src,const char *delim) + +std::vector Split(const char *src, const char *delim) { - char * strc = (char *)malloc(strlen(src)+1); + char *strc = (char *)malloc(strlen(src) + 1); strcpy(strc, src); - vector resultVec; - char* tmpStr = strtok(strc, delim); - while (tmpStr != NULL) - { - resultVec.push_back(string(tmpStr)); + std::vector resultVec; + char *tmpStr = strtok(strc, delim); + while (tmpStr != NULL) { + resultVec.push_back(std::string(tmpStr)); tmpStr = strtok(NULL, delim); } free(strc); return resultVec; } -vector< string> Split(const string &src,const string &pattern) +std::vector Split(const std::string &src, const std::string &pattern) { - vector ret; - string str = src; - if(pattern.empty() || str.empty()) + std::vector ret; + std::string str = src; + if (pattern.empty() || str.empty()) return ret; - size_t start=0; - size_t index=str.find_first_of(pattern,0); + size_t start = 0; + size_t index = str.find_first_of(pattern, 0); - while(index!=str.npos) - { - if(start!=index) - ret.push_back(str.substr(start,index-start)); - start=index+1; - index=str.find_first_of(pattern,start); + while (index != str.npos) { + if (start != index) + ret.push_back(str.substr(start, index - start)); + start = index + 1; + index = str.find_first_of(pattern, start); } - string sub = str.substr(start); - if(!sub.empty()) + std::string sub = str.substr(start); + if (!sub.empty()) ret.push_back(sub); return ret; } -bool StartWith(const string& str,const string &substr) +bool StartWith(const std::string &str, const std::string &substr) { return 0 == str.find(substr); } +std::string get_rand(int len) +{ + std::string result; + srand(time(NULL)); + + for (int i = 0; i < len; ++i) { + result.append(1, '0' + (rand() % 10)); + } + return result; +} + /* * 去除字符串右端空格 */ @@ -73,8 +83,9 @@ char *strtrimr(char *pstr) int i; i = strlen(pstr) - 1; - while (isspace(pstr[i]) && (i >= 0)) + while (isspace(pstr[i]) && (i >= 0)) { pstr[i--] = '\0'; + } return pstr; } @@ -84,224 +95,220 @@ char *strtrimr(char *pstr) */ char *strtriml(char *pstr) { - int i = 0,j; + int i = 0, j; j = strlen(pstr) - 1; while (isspace(pstr[i]) && (i <= j)) i++; - if (0(isillegal)) +std::string <rim(std::string &str) +{ + // std::string::iterator p = find_if(str.begin(), + // str.end(),illegalchar());// not1(ptr_fun(isillegal)) int i = 0; - for (;i < str.length();i++) { + for (; i < str.length(); i++) { if (isillformat(str[0])) { - str.erase(0,1); - } - else + str.erase(0, 1); + } else break; } return str; } -string& rtrim(string &str) { - int i = str.length()-1; - for (;i >= 0;i--) { +std::string &rtrim(std::string &str) +{ + int i = str.length() - 1; + for (; i >= 0; i--) { if (isillformat(str[i])) { - str.erase(i,1); - } - else + str.erase(i, 1); + } else break; } return str; } -string& trim(string &str) { +std::string &trim(std::string &str) +{ ltrim(rtrim(str)); return str; } -int strtoint(const char *str, int len) { +int strtoint(const char *str, int len) +{ int result = 0; const char *p = str; - while(*p != '\0' && (len--) != 0) { - if (*p >= '0' && *p <='9') - result = *p - '0' +result*10; + while (*p != '\0' && (len--) != 0) { + if (*p >= '0' && *p <= '9') + result = *p - '0' + result * 10; ++p; } return result; } -int strtohex(const char *str,int len) { +int strtohex(const char *str, int len) +{ int result = 0; const char *p = str; - while(*p != '\0' && (len--) != 0) { + while (*p != '\0' && (len--) != 0) { if (*p >= 'A' && *p <= 'F') - result = *p - 'A'+10 +result*16; - else if(*p >= 'a' && *p <= 'f') - result = *p - 'a' +10 +result*16; - else if (*p >= '0' && *p <='9') - result = *p - '0' +result*16; + result = *p - 'A' + 10 + result * 16; + else if (*p >= 'a' && *p <= 'f') + result = *p - 'a' + 10 + result * 16; + else if (*p >= '0' && *p <= '9') + result = *p - '0' + result * 16; ++p; } return result; } -char digittochar(unsigned char digit) { +char digittochar(unsigned char digit) +{ if (digit <= 9) - return digit+'0'; + return digit + '0'; else - return (digit-10+'A'); + return (digit - 10 + 'A'); } -inline int chartobcd(const char c) { +inline int chartobcd(const char c) +{ return (c & 0x0f); } -inline int chartohex(const char c) { - if (c >= 'a' && c <= 'f') { - return (c-'a'+10); - } - else if (c >= 'A' && c <= 'F') { - return (c-'A'+10); - } - else { - return (c-'0'); +inline int chartohex(const char c) +{ + if (c >= 'a' && c <= 'f') { + return (c - 'a' + 10); + } else if (c >= 'A' && c <= 'F') { + return (c - 'A' + 10); + } else { + return (c - '0'); } } /* * 默认10进制 */ -int strtocmd(const char *str,unsigned char *& cmd) { +int strtocmd(const char *str, unsigned char *&cmd) +{ int olen = 0; int ilen = strlen(str); - int il=ilen-1; - while(il>=0 && (str[il] == ' ' || str[il] == '\t') ) { + int il = ilen - 1; + while (il >= 0 && (str[il] == ' ' || str[il] == '\t')) { --il; } - ilen = il+1; + ilen = il + 1; if (ilen < 1) return olen; - cmd = (unsigned char *)malloc(ilen+1); - bzero(cmd,ilen+1); + cmd = (unsigned char *)malloc(ilen + 1); + bzero(cmd, ilen + 1); - if (str[ilen-1] == 'B' || str[ilen-1] == 'b') { + if (str[ilen - 1] == 'B' || str[ilen - 1] == 'b') { int flag = 0; - for (int i = ilen-2;i >= 0;i--) { + for (int i = ilen - 2; i >= 0; i--) { if (isdigit(str[i])) { if (++flag == 1) { cmd[olen] = chartobcd(str[i]); if (i == 0) olen++; - } - else { -// cmd[olen] = cmd[olen]<<4; - cmd[olen] |= chartobcd(str[i])<<4; + } else { + // cmd[olen] = cmd[olen]<<4; + cmd[olen] |= chartobcd(str[i]) << 4; olen++; flag = 0; } - } - else { - if (str[i]==' ') - olen++; + } else { + if (str[i] == ' ') + olen++; flag = 0; } } return olen; - } - else if (str[ilen-1] == 'H' || str[ilen-1] == 'h') { + } else if (str[ilen - 1] == 'H' || str[ilen - 1] == 'h') { int flag = 0; - for (int i = 0;i < ilen-1;i++) { + for (int i = 0; i < ilen - 1; i++) { if (isxdigit(str[i])) { if (++flag == 1) { cmd[olen] = chartohex(str[i]); - } - else { - cmd[olen] = cmd[olen]<<4; + } else { + cmd[olen] = cmd[olen] << 4; cmd[olen] |= chartohex(str[i]); olen++; flag = 0; } - } - else { + } else { olen++; flag = 0; } } return olen; - } - else { - S64 digit = atoll(str); + } else { + int64_t digit = atoll(str); union { - S64 d; - U8 a[8]; - }ud; - ud.d=digit; + int64_t d; + uint8_t a[8]; + } ud; + ud.d = digit; - if (digit <= 256){ - cmd[0]=ud.a[0]; + if (digit <= 256) { + cmd[0] = ud.a[0]; return 1; - } - else if(digit <= 65536) { - cmd[0]=ud.a[1]; - cmd[1]=ud.a[0]; + } else if (digit <= 65536) { + cmd[0] = ud.a[1]; + cmd[1] = ud.a[0]; return 2; - } - else { - cmd[0]=ud.a[3]; - cmd[1]=ud.a[2]; - cmd[2]=ud.a[1]; - cmd[3]=ud.a[0]; + } else { + cmd[0] = ud.a[3]; + cmd[1] = ud.a[2]; + cmd[2] = ud.a[1]; + cmd[3] = ud.a[0]; return 4; } } - return olen; + return olen; } /* * 默认16进制,不支持其他数字格式 */ -int strtohexcmd(const char *str,unsigned char*& cmd) { +int strtohexcmd(const char *str, unsigned char *&cmd) +{ int length = 0; int index = 0; const char *p = str; - while(*p != '\0' && *(p+1) != '\0') { - if (isxdigit(*p) && isxdigit(*(p+1))){ + while (*p != '\0' && *(p + 1) != '\0') { + if (isxdigit(*p) && isxdigit(*(p + 1))) { length++; - p +=2; - } - else + p += 2; + } else p++; } if (length == 0) @@ -310,30 +317,27 @@ int strtohexcmd(const char *str,unsigned char*& cmd) { p = str; - while(*p != '\0' && *(p+1) != '\0') { - if (isxdigit(*p) && isxdigit(*(p+1))){ - cmd[index++] = strtohex(p,2); + while (*p != '\0' && *(p + 1) != '\0') { + if (isxdigit(*p) && isxdigit(*(p + 1))) { + cmd[index++] = strtohex(p, 2); p += 2; - } - else + } else p++; } return length; } -string hexcmdtostr( - const unsigned char *cmd, - const int byte, - const char postfix) { - string result; +std::string hexcmdtostr(const unsigned char *cmd, const int byte, const char postfix) +{ + std::string result; - for (int i = 0;i < byte;i++) { - result += digittochar((cmd[i]&0xf0)>>4); - result += digittochar(cmd[i]&0x0f); - if (i != byte-1) { + for (int i = 0; i < byte; i++) { + result += digittochar((cmd[i] & 0xf0) >> 4); + result += digittochar(cmd[i] & 0x0f); + if (i != byte - 1) { if (postfix != '\0') - result +=postfix; - result +=' '; + result += postfix; + result += ' '; } } return result; @@ -342,16 +346,15 @@ string hexcmdtostr( /* * 字符串转成压缩bcd码 */ -int asc_to_bcd(char * dest,const char *src) +int asc_to_bcd(char *dest, const char *src) { unsigned char temp; - while(*src !='\0') - { + while (*src != '\0') { temp = *src; - *dest = ((temp&0x0f)<<4); + *dest = ((temp & 0x0f) << 4); src++; temp = *src; - *dest |= (temp&0x0f); + *dest |= (temp & 0x0f); src++; dest++; } @@ -362,164 +365,157 @@ int asc_to_bcd(char * dest,const char *src) * src为需要进行转换的字符串 * src_len为src的长度即strlen(src) */ -int asc_to_bcd_right(char *dest,const char *src,int src_len) +int asc_to_bcd_right(char *dest, const char *src, int src_len) { unsigned char temp; - if((src_len %2) !=0) - { - *dest = 0; - temp = *src; - *dest |= (temp&0xf); - src++; - dest++; + if ((src_len % 2) != 0) { + *dest = 0; + temp = *src; + *dest |= (temp & 0xf); + src++; + dest++; } - return asc_to_bcd(dest,src); + return asc_to_bcd(dest, src); } /* 参数dest为申请的存放得到压缩bcd码的字符串, * src为需要进行转换的字符串 * src_len为src的长度即strlen(src) */ -int asc_to_bcd_left(char *dest,const char *src,int src_len) +int asc_to_bcd_left(char *dest, const char *src, int src_len) { unsigned char temp; - if((src_len %2) !=0) - { - dest[src_len-1] &=0; + if ((src_len % 2) != 0) { + dest[src_len - 1] &= 0; } - return asc_to_bcd(dest,src); + return asc_to_bcd(dest, src); } /************************************************************************************************************************* -*函数 : void HextoBCD(u8 *pBuff,u8 len) -*功能 : 十六进制转为BCD码 -*参数 : pBuff:输入的十六进制数组,len:数组长度 -*返回 : 无 -*依赖 : 底层宏定义 -* 作者 : li_qcxy@126.com -* 时间 : 2017-1-5 -* 最后修改时间: -*说明 : -*************************************************************************************************************************/ -void hextobcd(unsigned char *pBuff,unsigned char len) //十六进制转为BCD码 -{ -unsigned char i,temp; -for(i=0;i= '0' && c <= '9') || (c >='a' && c<= 'f') || -// (c >= 'A' && c <= 'F')) ; + // return ((c >= '0' && c <= '9') || (c >='a' && c<= 'f') || + // (c >= 'A' && c <= 'F')) ; return isxdigit(c); } bool isTerminator(const char c) { -// return (c == ')' || c == '(' || c == '[' || c == ']' ||c == '{' || c == '}'|| -// c == '$' || c == ' ' || c== '+' || c== '-' || -// c == '*' || c == '/' || c == '%' || c== ',' || c == '&'); + // return (c == ')' || c == '(' || c == '[' || c == ']' ||c == '{' || c + // == '}'|| + // c == '$' || c == ' ' || c== '+' || c== '-' || + // c == '*' || c == '/' || c == '%' || c== ',' || c == '&'); return !(isalpha(c) || isalnum(c) || c == '_'); } bool isCharactor(const char c) { -// return ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_'); - return isalpha(c) || c=='_'; + // return ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_'); + return isalpha(c) || c == '_'; } -bool isHexDigit(const char *str) { +bool isHexDigit(const char *str) +{ int len = strlen(str); - int il=len-1; - while(il>=0 && (str[il] == ' ' || str[il] == '\t') ) { + int il = len - 1; + while (il >= 0 && (str[il] == ' ' || str[il] == '\t')) { --il; } - len = il+1; + len = il + 1; if (len < 2) return false; - if (str[len-1] == 'H' || str[len-1] == 'h') { - for (int i = 0;i < len-1;i++) { + if (str[len - 1] == 'H' || str[len - 1] == 'h') { + for (int i = 0; i < len - 1; i++) { if (!isxdigit(str[i])) return false; } return true; - } - else if (len >= 3 && str[0] == '0' && (str[1] == 'x' || str[1] == 'X')) { - for (int i = 2;i < len;i++) { + } else if (len >= 3 && str[0] == '0' && (str[1] == 'x' || str[1] == 'X')) { + for (int i = 2; i < len; i++) { if (!isxdigit(str[i])) return false; } @@ -528,19 +524,20 @@ bool isHexDigit(const char *str) { return false; } -bool isBCD(const char *str) { +bool isBCD(const char *str) +{ int len = strlen(str); - int il=len-1; - while(il>=0 && (str[il] == ' ' || str[il] == '\t') ) { + int il = len - 1; + while (il >= 0 && (str[il] == ' ' || str[il] == '\t')) { --il; } - len = il+1; + len = il + 1; if (len < 2) return false; - if (str[len-1] == 'B' || str[len-1] == 'b') { - for (int i = 0;i < len-1;i++) { + if (str[len - 1] == 'B' || str[len - 1] == 'b') { + for (int i = 0; i < len - 1; i++) { if (!isdigit(str[i])) return false; } @@ -549,15 +546,16 @@ bool isBCD(const char *str) { return false; } -bool isDecimal(const char *str,bool &f) { +bool isDecimal(const char *str, bool &f) +{ int flag = 0; int len = strlen(str); f = false; if (len == 0) return false; - for (int i = 0;i < len;i++) { - if ( str[i] == '.') { + for (int i = 0; i < len; i++) { + if (str[i] == '.') { flag += 1; if (flag == 2 || i == 0) return false; @@ -570,47 +568,60 @@ bool isDecimal(const char *str,bool &f) { return true; } -bool isInteger(const char *str) { +bool isInteger(const char *str) +{ bool f; - if (isDecimal(str,f)) + if (isDecimal(str, f)) return !f; return false; } -bool existFile(const char *file) { -// FILE* fp = fopen(file,"r"); - int acs = access(file,F_OK); - return acs==0; -// if (!fp) -// return false; -// fclose(fp); -// return true; -// int acs = access(file,F_OK); -// int err = errno; -// return (-1 != access(file,F_OK)); +std::string get_executable_directory() { + char buffer[120]; + ssize_t len = readlink("/proc/self/exe", buffer, sizeof(buffer)-1); + if (len == -1) { + perror("readlink"); + return ""; + } + buffer[len] = '\0'; + return std::string(dirname(buffer)); +} + +bool existFile(const char *file) +{ + // FILE* fp = fopen(file,"r"); + int acs = access(file, F_OK); + return acs == 0; + // if (!fp) + // return false; + // fclose(fp); + // return true; + + // int acs = access(file,F_OK); + // int err = errno; + + // return (-1 != access(file,F_OK)); } -string logFileNotoday(const char *path) +std::string logFileNotoday(const char *path) { DIR *dir; struct dirent *file; - string filename; - string today = utils::todaytostr(); + std::string filename; + std::string today = utils::todaytostr(); - if ((dir=opendir(path)) == NULL) - { + if ((dir = opendir(path)) == NULL) { return filename; } - while ((file = readdir(dir)) != NULL) - { - if(strcmp(file->d_name,".")==0 || strcmp(file->d_name,"..")==0) ///current dir OR parrent dir + while ((file = readdir(dir)) != NULL) { + if (strcmp(file->d_name, ".") == 0 || strcmp(file->d_name, "..") == 0) /// current dir OR parrent dir continue; - if(file->d_type != 8) ///file + if (file->d_type != 8) /// file continue; - if (utils::StartWith(file->d_name,today)) + if (utils::StartWith(file->d_name, today)) continue; filename = file->d_name; break; @@ -619,99 +630,99 @@ string logFileNotoday(const char *path) return filename; } -string logFile(const char *path) +std::string logFile(const char *path) { DIR *dir; struct dirent *file; - string filename; - vector filelist; + std::string filename; + std::vector filelist; - if ((dir=opendir(path)) == NULL) - { + if ((dir = opendir(path)) == NULL) { return filename; } - while ((file = readdir(dir)) != NULL) - { - if(strcmp(file->d_name,".")==0 || strcmp(file->d_name,"..")==0) ///current dir OR parrent dir + while ((file = readdir(dir)) != NULL) { + if (strcmp(file->d_name, ".") == 0 || strcmp(file->d_name, "..") == 0) /// current dir OR parrent dir continue; - if(file->d_type != 8) ///file + if (file->d_type != 8) /// file continue; filelist.push_back(file->d_name); break; } closedir(dir); - if (filelist.size()>0) { - sort(filelist.begin(),filelist.end(),less()); + if (filelist.size() > 0) { + sort(filelist.begin(), filelist.end(), std::less()); filename = filelist.at(0); } return filename; } -time_t strtotime(const string &str) +time_t strtotime(const std::string &str) { - char *cha = (char*)str.data(); // 将string转换成char*。 - tm tm_; // 定义tm结构体。 - int year, month, day, hour, minute, second;// 定义时间的各个int临时变量。 - sscanf(cha, "%04d%02d%02d%02d%02d%02d", &year, &month, &day, &hour, &minute, &second);// 将string存储的日期时间,转换为int临时变量。 - tm_.tm_year = year - 1900; // 年,由于tm结构体存储的是从1900年开始的时间,所以tm_year为int临时变量减去1900。 - tm_.tm_mon = month - 1; // 月,由于tm结构体的月份存储范围为0-11,所以tm_mon为int临时变量减去1。 - tm_.tm_mday = day; // 日。 - tm_.tm_hour = hour; // 时。 - tm_.tm_min = minute; // 分。 - tm_.tm_sec = second; // 秒。 - tm_.tm_isdst = 0; // 非夏令时。 - time_t t_ = mktime(&tm_); // 将tm结构体转换成time_t格式。 - return t_; // 返回值。 -} - -string todaytostr() + char *cha = (char *)str.data(); // 将string转换成char*。 + tm tm_; // 定义tm结构体。 + int year, month, day, hour, minute, second; // 定义时间的各个int临时变量。 + sscanf(cha, "%04d%02d%02d%02d%02d%02d", &year, &month, &day, &hour, &minute, + &second); // 将string存储的日期时间,转换为int临时变量。 + tm_.tm_year = year - 1900; // 年,由于tm结构体存储的是从1900年开始的时间,所以tm_year为int临时变量减去1900。 + tm_.tm_mon = month - 1; // 月,由于tm结构体的月份存储范围为0-11,所以tm_mon为int临时变量减去1。 + tm_.tm_mday = day; // 日。 + tm_.tm_hour = hour; // 时。 + tm_.tm_min = minute; // 分。 + tm_.tm_sec = second; // 秒。 + tm_.tm_isdst = 0; // 非夏令时。 + time_t t_ = mktime(&tm_); // 将tm结构体转换成time_t格式。 + return t_; // 返回值。 +} + +std::string todaytostr() { char szTime[50]; struct tm *tm2; time_t today = time(NULL); tm2 = localtime(&today); -// tm2=gmtime(&time); - strftime(szTime,sizeof(szTime),"%Y-%m-%d",tm2); + // tm2=gmtime(&time); + strftime(szTime, sizeof(szTime), "%Y-%m-%d", tm2); - return string(szTime); + return std::string(szTime); } -string timetostr(const time_t &time,int flag) +std::string timetostr(const time_t &time, int flag) { char szTime[50]; struct tm *tm2; - tm2=localtime(&time); -// tm2=gmtime(&time);strftime(szTime,sizeof(szTime),"%Y-%m-%d %H:%M:%S",tm2); - switch(flag) { - case 0: - strftime(szTime,sizeof(szTime),"%Y-%m-%d %H:%M:%S",tm2); - break; - case 1: - strftime(szTime,sizeof(szTime),"%Y-%m-%d %H:%M",tm2); - break; - case 2: - strftime(szTime,sizeof(szTime),"%Y-%m-%d %H:%M",tm2); - break; - case 3: - strftime(szTime,sizeof(szTime),"%Y-%m-%d %H",tm2); - break; - case 9: - strftime(szTime,sizeof(szTime),"%04Y%02m%02d%02H%02M%02S",tm2); - break; - default: - strftime(szTime,sizeof(szTime),"%Y-%m-%d",tm2); - break; + tm2 = localtime(&time); + // tm2=gmtime(&time);strftime(szTime,sizeof(szTime),"%Y-%m-%d + // %H:%M:%S",tm2); + switch (flag) { + case 0: + strftime(szTime, sizeof(szTime), "%Y-%m-%d %H:%M:%S", tm2); + break; + case 1: + strftime(szTime, sizeof(szTime), "%Y-%m-%d %H:%M", tm2); + break; + case 2: + strftime(szTime, sizeof(szTime), "%Y-%m-%d %H:%M", tm2); + break; + case 3: + strftime(szTime, sizeof(szTime), "%Y-%m-%d %H", tm2); + break; + case 9: + strftime(szTime, sizeof(szTime), "%04Y%02m%02d%02H%02M%02S", tm2); + break; + default: + strftime(szTime, sizeof(szTime), "%Y-%m-%d", tm2); + break; } - return string(szTime); + return std::string(szTime); } -string nowtostr() +std::string nowtostr() { return timetostr(time(NULL)); } -} +} // namespace utils diff --git a/custom.h b/custom.h index 4e96a88..4be678d 100755 --- a/custom.h +++ b/custom.h @@ -1,24 +1,24 @@ /************************************************************************* - > File Name: custom.h - > Author: xuwenlong - > Mail: myxuan475@126.com - > Created Time: 2018年02月01日 星期四 13时48分08秒 + > File Name: custom.h + > Author: xuwenlong + > Mail: myxuan475@126.com + > Created Time: 2018年02月01日 星期四 13时48分08秒 ************************************************************************/ #ifndef __CUSTOM_H__ #define __CUSTOM_H__ -#include -#include -#include +#include #include -#include +#include +#include namespace utils { -using namespace std; -vector Split(const char *src,const char *delim); -vector Split(const string &src,const string &pattern); -bool StartWith(const string& str, const string &substr); +std::vector Split(const char *src, const char *delim); +std::vector Split(const std::string &src, const std::string &pattern); +bool StartWith(const std::string &str, const std::string &substr); + +std::string get_rand(int len); /* * 去除字符串右端空格 */ @@ -31,11 +31,11 @@ char *strtriml(char *pstr); char *strtrim(char *pstr); -string& ltrim(string &str); +std::string <rim(std::string &str); -string& rtrim(string &str); +std::string &rtrim(std::string &str); -string& trim(string &str); +std::string &trim(std::string &str); int strtoint(const char *str,int len = -1); int strtohex(const char *str, int len = -1); @@ -49,7 +49,7 @@ int strtocmd(const char *str,unsigned char *& cmd); * 字符串转换成16进制命令 */ int strtohexcmd(const char *str,unsigned char*& cmd); -string hexcmdtostr(const unsigned char *cmd,const int byte,const char postfix ='\0'); +std::string hexcmdtostr(const unsigned char *cmd, const int byte, const char postfix = '\0'); /* * 字符串转成压缩bcd码 @@ -80,12 +80,12 @@ int asc_to_bcd_left(char *dest,const char *src,int src_len); *说明 : *************************************************************************************************************************/ void hextobcd(unsigned char *pBuff,unsigned char len); //十六进制转为BCD码 -U32 strtimetobcd(const string &daytime); +uint32_t strtimetobcd(const std::string &daytime); void bcdtohex(unsigned char *pBuff,unsigned char len); //BCD码转为十六进制 -void InvertUint8(U8 *dBuf,U8 *srcBuf); -void InvertUint16(U16 *dBuf,U16 *srcBuf); +void InvertUint8(uint8_t *dBuf, uint8_t *srcBuf); +void InvertUint16(uint16_t *dBuf, uint16_t *srcBuf); bool isHexDigtal(const char c); bool isTerminator(const char c); @@ -93,16 +93,16 @@ bool isCharactor(const char c); bool isHexDigit(const char *str); bool isDecimal(const char *str,bool &fl); bool isInteger(const char *str); - +std::string get_executable_directory(); bool existFile(const char *file); -string logFileNotoday(const char *path); -string logFile(const char *path); +std::string logFileNotoday(const char *path); +std::string logFile(const char *path); time_t strtotime(const std::string &str); -string todaytostr(); -string timetostr(const time_t &time,int flag = 0); -string nowtostr(); +std::string todaytostr(); +std::string timetostr(const time_t &time, int flag = 0); +std::string nowtostr(); } #endif//__CUSTOM_H__ diff --git a/decrypt.cpp b/decrypt.cpp deleted file mode 100644 index 7a43519..0000000 --- a/decrypt.cpp +++ /dev/null @@ -1,192 +0,0 @@ -/************************************************************************* - > File Name: decrypt.cpp - > Author: xuwenlong - > Mail: myxuan475@126.com - > Created Time: 2018年10月17日 星期三 14时25分23秒 - ************************************************************************/ -#include "decrypt.h" -#include -#include -#include -#include - - -/* sz_in_buff 输入字符串 -* key 为密钥 -* iv为偏移量 -* sz_out_buff 加密输出字符串 -*/ -int aes_encrypt_pkcs5pading(unsigned char *sz_in_buff, int sz_in_len, unsigned char *key,unsigned char *iv, unsigned char *sz_out_buff) -{ - EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new(); - - int isSuccess = 0; - int outl = 0; - - EVP_CIPHER_CTX_init(ctx); - - EVP_EncryptInit_ex(ctx, EVP_aes_128_cbc(), NULL, key, iv); - EVP_CIPHER_CTX_set_padding(ctx, 1); - - isSuccess = EVP_EncryptUpdate(ctx, sz_out_buff, &outl,sz_in_buff,sz_in_len); - if(!isSuccess) - { - printf("EVP_EncryptUpdate() failed"); - EVP_CIPHER_CTX_cleanup(ctx); - return 0; - } - int last = 0; - isSuccess = EVP_EncryptFinal_ex(ctx,sz_out_buff + outl,&last); - if(!isSuccess) - { - printf("EVP_EncryptUpdate() failed"); - EVP_CIPHER_CTX_cleanup(ctx); - return 0; - } - outl += last; - EVP_CIPHER_CTX_cleanup(ctx); - EVP_CIPHER_CTX_free(ctx); - return outl; -} - -//--------------------- -//作者:viewsky11 -//来源:CSDN -//原文:https://blog.csdn.net/viewsky11/article/details/78983234 -//版权声明:本文为博主原创文章,转载请附上博文链接! - -UtilsCrypt::UtilsCrypt(const std::string &key_, MODE mode_) -{ - private_key = key_; - mode = mode_; -} - -UtilsCrypt::~UtilsCrypt() -{ - if (ctx == NULL) return; - EVP_CIPHER_CTX_cleanup(ctx); - EVP_CIPHER_CTX_free(ctx); - ctx = NULL; -} - -bool UtilsCrypt::InitCrypt() -{ - unsigned char iv[AES_BLOCK_SIZE]; - ctx = EVP_CIPHER_CTX_new(); - //初始化 - memset(iv,0,AES_BLOCK_SIZE); - memcpy(iv,private_key.c_str(),AES_BLOCK_SIZE); - //初始化ctx,加密算法初始化 - EVP_CIPHER_CTX_init(ctx); - int isSuccess = EVP_EncryptInit_ex(ctx,EVP_aes_128_cbc(),NULL,iv,iv); - if(!isSuccess) { - printf("EVP_DecryptInit_ex() failed"); - EVP_CIPHER_CTX_cleanup(ctx); - return false; - } - - //解密数据 - EVP_CIPHER_CTX_set_padding(ctx,1); - return true; -} - -std::string UtilsCrypt::Encrypt(const char *data,int len) -{ - unsigned char sz_out_buff[560] = {0}; - int outl = 0; - int isSuccess = EVP_EncryptUpdate(ctx, sz_out_buff, &outl,(const unsigned char*)data,len); - if(!isSuccess) - return ""; - return std::string((char *)sz_out_buff,outl); -} - -std::string UtilsCrypt::Decrypt(const std::string &str) -{ -#if 0 - char *out; - unsigned char iv[AES_BLOCK_SIZE]; - int length = 0; - - //初始化 - memset(iv,0,AES_BLOCK_SIZE); - memcpy(iv,private_key.c_str(),AES_BLOCK_SIZE); - length = ((str.length() + AES_BLOCK_SIZE-1)/AES_BLOCK_SIZE)*AES_BLOCK_SIZE; - out = (char *)malloc(length); - int len = aes_decrypt_pkcs5pading((unsigned char*)str.c_str(),str.length(),iv,iv,(unsigned char *)out); - if (len <= 0) - return ""; - std::string strout(out,len); - free(out); - return strout; -#endif -} - -std::string UtilsCrypt::FinalEncrypt() -{ - unsigned char sz_out_buff[560] = {0}; - int last = 0; - int isSuccess = EVP_EncryptFinal_ex(ctx, sz_out_buff, &last); - if (!isSuccess) { - return ""; - } - return std::string((char*)sz_out_buff,last); -} - -//std::string UtilsCrypt::Encrypt(const unsigned char *data, int len) -//{ -// unsigned char *result; -// unsigned char iv[AES_BLOCK_SIZE]; -// AES_KEY en_key; -// int length = 0; - -// //初始化 -// memset(iv,0,AES_BLOCK_SIZE); -// memcpy(iv,private_key.c_str(),AES_BLOCK_SIZE); -//// des_setparity(key); -// length = ((len + AES_BLOCK_SIZE-1)/AES_BLOCK_SIZE)*AES_BLOCK_SIZE; - -// std::string str((char*)data,len); -// for (int i = len;i < length;i++) { -// str+='\n'; -// } - -// result = (unsigned char *)malloc(length); - -// memset(result,0,length); - -// AES_set_encrypt_key((unsigned char*)private_key.c_str(),AES_BLOCK_SIZE*8,&en_key); - -// if (mode == cbc) -// AES_cbc_encrypt((unsigned char*)str.c_str(),result,length,&en_key,iv,AES_ENCRYPT); -// else if (mode == ecb) -// AES_ecb_encrypt((unsigned char*)str.c_str(),result,&en_key,AES_ENCRYPT); - -// std::string encrypt; -// encrypt.append((char *)result,length); -// delete result; -// return encrypt; -//} - -int UtilsCrypt::Decrypt(const char *data, int len,char* &out) -{ - unsigned char iv[AES_BLOCK_SIZE]; - AES_KEY en_key; - int olen = 0; - - //初始化 - memset(iv,0,AES_BLOCK_SIZE); - memcpy(iv,private_key.c_str(),AES_BLOCK_SIZE); -// des_setparity(key); - olen = ((len + AES_BLOCK_SIZE-1)/AES_BLOCK_SIZE)*AES_BLOCK_SIZE; - out = (char *)malloc(olen+1); - - memset(out,0,olen); - - AES_set_decrypt_key((unsigned char *)private_key.c_str(),AES_BLOCK_SIZE*8,&en_key); - - if (mode == cbc) - AES_cbc_encrypt((unsigned char*)data,(unsigned char*)out,len,&en_key,iv,AES_DECRYPT); - else if (mode == ecb) - AES_ecb_encrypt((unsigned char*)data,(unsigned char*)out,&en_key,AES_DECRYPT); - return olen; -} diff --git a/decrypt.h b/decrypt.h deleted file mode 100644 index 54ba123..0000000 --- a/decrypt.h +++ /dev/null @@ -1,39 +0,0 @@ -/************************************************************************* - > File Name: decrypt.h - > Author: xuwenlong - > Mail: myxuan475@126.com - > Created Time: 2018年10月17日 星期三 14时25分30秒 - ************************************************************************/ -#ifndef __DECRYPT_H__ -#define __DECRYPT_H__ -#include -#include -#include -#include -#include -#include - -class UtilsCrypt -{ -public: - typedef enum {ecb = 0,cbc}MODE; - - UtilsCrypt(const std::string &key_,MODE mode_ = ecb); - virtual ~UtilsCrypt(); - - bool InitCrypt(); - std::string Encrypt(const char *str, int len); - std::string Decrypt(const std::string &str); - - std::string FinalEncrypt(); - -// std::string Encrypt(const unsigned char *data,int len); - int Decrypt(const char *data,int len, char *&out); -private: - std::string private_key; - MODE mode;//0:ecb,1:cbc - EVP_CIPHER_CTX *ctx; -}; - - -#endif diff --git a/dfile.cpp b/dfile.cpp index b9baae0..329d996 100755 --- a/dfile.cpp +++ b/dfile.cpp @@ -1,188 +1,184 @@ -#include -#include -#include -#include +#include #include -//#include < -#include +#include +#include +#include +// #include < +#include #include #include -#include +#include -#define DFile "xhnc.txt" -#define DMFile "mhnc.txt" +#define DFile "xhnc.txt" +#define DMFile "mhnc.txt" +// #define C_FILE -//#define C_FILE +// QMutex s_mutex_fd,s_mutex_n; -//QMutex s_mutex_fd,s_mutex_n; +namespace utils { -namespace utils -{ - -int get_mem_info(char info[],int size) +int get_mem_info(char info[], int size) { return 0; -// __pid_t id=getpid(); -// char fi[100]={0}; -// sprintf(fi,"/proc/%d/status",id); -// int fd; -// fd=open(fi,O_RDONLY); // /proc/meminfo" -// read(fd,info,size); -// close(fd); -// return fd; + // __pid_t id=getpid(); + // char fi[100]={0}; + // sprintf(fi,"/proc/%d/status",id); + // int fd; + // fd=open(fi,O_RDONLY); // /proc/meminfo" + // read(fd,info,size); + // close(fd); + // return fd; } -int get_cpu_info(char info[],int size) +int get_cpu_info(char info[], int size) { - FILE *fd=fopen("/proc/cpuinfo","rb"); - if(NULL==fd) + FILE* fd = fopen("/proc/cpuinfo", "rb"); + if (NULL == fd) return -1; - fread(info,size,1,fd); + fread(info, size, 1, fd); return fclose(fd); } -void write_debug_info_to_dir(const char *dir,const char* str,...) +void write_debug_info_to_dir(const char* dir, const char* str, ...) { -// char buf[500]={0}; -// va_list ap; -//// int retval; -// va_start(ap,str); - -// vsprintf(buf,str,ap); -// va_end(ap); -// int fd; -// fd=open(dir,O_CREAT|O_WRONLY|O_APPEND); -// write(fd,buf,strlen(buf)); -// close(fd); + // char buf[500]={0}; + // va_list ap; + //// int retval; + // va_start(ap,str); + + // vsprintf(buf,str,ap); + // va_end(ap); + // int fd; + // fd=open(dir,O_CREAT|O_WRONLY|O_APPEND); + // write(fd,buf,strlen(buf)); + // close(fd); } -void write_debug_info(const char* str,...) +void write_debug_info(const char* str, ...) { -// return; -// if(debug_text_brower==NULL) -// return; -// if(!debug_text_brower->IsRun()) -// return; -// char buf[500]={0}; -// va_list ap; -// int retval; -// va_start(ap,str); - -// vsprintf(buf,str,ap); -// va_end(ap); -//// int fd; -//// fd=open(DFile,O_CREAT|O_WRONLY|O_APPEND); -//// write(fd,buf,strlen(buf)); -//// close(fd); -// debug_text_brower->write_debug_info(QString(buf)); + // return; + // if(debug_text_brower==NULL) + // return; + // if(!debug_text_brower->IsRun()) + // return; + // char buf[500]={0}; + // va_list ap; + // int retval; + // va_start(ap,str); + + // vsprintf(buf,str,ap); + // va_end(ap); + //// int fd; + //// fd=open(DFile,O_CREAT|O_WRONLY|O_APPEND); + //// write(fd,buf,strlen(buf)); + //// close(fd); + // debug_text_brower->write_debug_info(QString(buf)); } - -void write_debug_time(const char* str,...) +void write_debug_time(const char* str, ...) { -//// return; -// if(debug_text_brower==NULL) -// return; -// if(!debug_text_brower->IsRun()) -// return; -// char buf[200]={0}; -// va_list ap; -//// int retval; -// va_start(ap,str); - -// vsprintf(buf,str,ap); -// va_end(ap); -// char cbuf[300]={0}; -// sprintf(cbuf,"%s:%s",buf,QDateTime::currentDateTime().time().toString("mm:ss:zzz").toStdString().data()); - -// int fd; -// fd=open("smpl_inj",O_WRONLY|O_CREAT|O_APPEND); -// write(fd,buf,strlen(cbuf)); -// close(fd); - -// debug_text_brower->write_debug_info(QString(cbuf)); + //// return; + // if(debug_text_brower==NULL) + // return; + // if(!debug_text_brower->IsRun()) + // return; + // char buf[200]={0}; + // va_list ap; + //// int retval; + // va_start(ap,str); + + // vsprintf(buf,str,ap); + // va_end(ap); + // char cbuf[300]={0}; + // sprintf(cbuf,"%s:%s",buf,QDateTime::currentDateTime().time().toString("mm:ss:zzz").toStdString().data()); + + // int fd; + // fd=open("smpl_inj",O_WRONLY|O_CREAT|O_APPEND); + // write(fd,buf,strlen(cbuf)); + // close(fd); + + // debug_text_brower->write_debug_info(QString(cbuf)); } -bool file_exist (const char *file) +bool file_exist(const char* file) { - if (file == NULL) - return false; - return access(file, 0)==0; + if (file == NULL) + return false; + return access(file, 0) == 0; } -int load_file(const char *dir,int start,char buf[],int count,int size) +int load_file(const char* dir, int start, char buf[], int count, int size) { - if(dir==NULL||buf==NULL||size<=0||start<0) + if (dir == NULL || buf == NULL || size <= 0 || start < 0) return -1; -// chmod(dir,S_IREAD|S_IWRITE); + // chmod(dir,S_IREAD|S_IWRITE); #ifdef C_FILE - FILE *fd=fopen(dir,"rb+"); - if(NULL==fd) + FILE* fd = fopen(dir, "rb+"); + if (NULL == fd) return -1; - if (-1 == fseek(fd,start,SEEK_SET)) { + if (-1 == fseek(fd, start, SEEK_SET)) { LOG_ERR("fseek error"); } - int r = fread(buf,size,count,fd); + int r = fread(buf, size, count, fd); fclose(fd); return 1; #else - int fd = open(dir,O_RDONLY|O_CREAT,0755); - int sk = lseek(fd,start,SEEK_SET); - int rd = read(fd,buf,size*count); + int fd = open(dir, O_RDONLY | O_CREAT, 0755); + int sk = lseek(fd, start, SEEK_SET); + int rd = read(fd, buf, size * count); close(fd); return rd; #endif } -void delete_file(const char *dir) +void delete_file(const char* dir) { - if(dir==NULL) + if (dir == NULL) return; -// chmod(dir,S_IREAD|S_IWRITE|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH); + // chmod(dir,S_IREAD|S_IWRITE|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH); remove(dir); -// QFile::remove(QString(dir)); + // QFile::remove(QString(dir)); } -int save_file(const char *dir,int start,const char buf[],int count,int size) +int save_file(const char* dir, int start, const char buf[], int count, int size) { - if(dir==NULL||buf==NULL||size<=0||start<0) + if (dir == NULL || buf == NULL || size <= 0 || start < 0) return -1; - //if(access(dir,F_OK)) + // if(access(dir,F_OK)) // chmod(dir,S_IREAD|S_IWRITE); #ifdef C_FILE - FILE *fd=fopen(dir,"ab+"); - if(NULL==fd) + FILE* fd = fopen(dir, "ab+"); + if (NULL == fd) return -1; - if (-1 == fseek(fd,start,SEEK_SET)) { + if (-1 == fseek(fd, start, SEEK_SET)) { LOG_ERR("fseek error"); } -// read(fd,(char*)buf,size); - int w = fwrite(buf,size,count,fd); + // read(fd,(char*)buf,size); + int w = fwrite(buf, size, count, fd); fclose(fd); return 1; #else - int fd = open(dir,O_WRONLY|O_CREAT,0755); - lseek(fd,start,SEEK_SET); - int r = write(fd,buf,size*count); + int fd = open(dir, O_WRONLY | O_CREAT, 0755); + lseek(fd, start, SEEK_SET); + int r = write(fd, buf, size * count); close(fd); return r; #endif } -void reset_file(const char *dir,int length) +void reset_file(const char* dir, int length) { #ifdef C_FILE - FILE *fd=fopen(dir,"wb+"); - if(NULL==fd) + FILE* fd = fopen(dir, "wb+"); + if (NULL == fd) return; - ftruncate(fileno(fd),length); + ftruncate(fileno(fd), length); fclose(fd); #else - int fd = open(dir,O_WRONLY,0755); - ftruncate(fd,length); + int fd = open(dir, O_WRONLY, 0755); + ftruncate(fd, length); close(fd); #endif } -} - +} // namespace utils diff --git a/fixlist.cpp b/fixlist.cpp index 1094c6f..ac23245 100755 --- a/fixlist.cpp +++ b/fixlist.cpp @@ -1,57 +1,57 @@ +#include "dfile.h" #include "fixlist.h" #include "stdio.h" -#include "dfile.h" -#include -#include +#include "vendor_global.h" #include +#include -#define DATA_SHIFT sizeof(U64) +#define DATA_SHIFT sizeof(uint64_t) -template -FixList::FixList(S32 id): - fileData(id){ +template +FixList::FixList(int32_t id) : fileData(id) +{ } -template -FixList::FixList(const FixList &fixlist) +template +FixList::FixList(const FixList &fixlist) { operator =(fixlist); } -template -FixList& FixList::operator =(const FixList &fixlist) +template +FixList &FixList::operator=(const FixList &fixlist) { fileData = fixlist.fileData; return *this; } -template -FixList::~FixList() +template +FixList::~FixList() { /* 保存内容 */ } -template -void FixList::removeLast() +template +void FixList::removeLast() { fileData.removeLast(); } -template -bool FixList::isFull() +template +bool FixList::isFull() { - U16 length = fileData.readLength(); + uint16_t length = fileData.readLength(); return (M!=-1 && length == M); } -template -void FixList::push_back(T &t) +template +void FixList::push_back(T &t) { append(t); } -template -void FixList::append(T &t) +template +void FixList::append(T &t) { if (isFull()) { fileData.removeAt(0); @@ -60,83 +60,81 @@ void FixList::append(T &t) fileData.writeBack(t); } -template -T FixList::operator [](int index) +template +T FixList::operator[](int index) { T t; this->at(&t,index); return t; } -template -T FixList::at(int index) +template +T FixList::at(int index) { T t; this->at(&t,index); return t; } - -template -bool FixList::at(T *d, int start) +template +bool FixList::at(T *d, int start) { - U64 length = fileData.readLength(); + uint64_t length = fileData.readLength(); if (start >= length) return false; *d = fileData.readAt(start); return true; } -template -T FixList::end() +template +T FixList::end() { return fileData.readLast(); } -template -void FixList::replace(int start, T &t) +template +void FixList::replace(int start, T &t) { fileData.writeAt(start,t); } -template -void FixList::remove(int index) +template +void FixList::remove(int index) { fileData.removeAt(index); } -template -void FixList::clear() +template +void FixList::clear() { fileData.clear(); } -template -bool FixList::isEmpty() +template +bool FixList::isEmpty() { return fileData.empty(); } -template -int FixList::count() +template +int FixList::count() { return fileData.readLength(); } -template -int FixList::size() +template +int FixList::size() { return count (); } -template -FixList::FileData::FileData(S32 id): - file_cs(true) +template +FixList::FileData::FileData(int32_t id) : file_cs(true) { - int len = 30+strlen(getenv(CONFIG_DIR_ENV)); + int len = 30 + VENDOR_DB_PATH.length(); filename = (char*)malloc(len); memset(filename,0,len); - sprintf(filename,"%s/data/LIST%04d.data",getenv(CONFIG_DIR_ENV),id); + sprintf(filename, "%s/LIST%04d.data", VENDOR_DB_PATH.c_str(), id); if(!utils::file_exist(filename)) { @@ -144,9 +142,8 @@ FixList::FileData::FileData(S32 id): } } -template -FixList::FileData::FileData(const FixList::FileData &fileData): - file_cs(true) +template +FixList::FileData::FileData(const FixList::FileData &fileData) : file_cs(true) { char *filename_ = (char*)malloc(strlen(fileData.filename)+1); strcpy(filename_,fileData.filename); @@ -156,39 +153,39 @@ FixList::FileData::FileData(const FixList::FileData &fileData): filename = filename_; } -template -FixList::FileData::~FileData() +template +FixList::FileData::~FileData() { AutoLock autolock(file_cs); free(filename); } -template -U64 FixList::FileData::readLength() +template +uint64_t FixList::FileData::readLength() { AutoLock autolock(file_cs); - U64 length = 0; + uint64_t length = 0; utils::load_file(filename,0,(char*)&length,DATA_SHIFT); return length; } -template -void FixList::FileData::writeLength(U64 length) +template +void FixList::FileData::writeLength(uint64_t length) { AutoLock autolock(file_cs); utils::save_file(filename,0,(char*)&length,DATA_SHIFT); } -template -T FixList::FileData::readLast() +template +T FixList::FileData::readLast() { AutoLock autolock(file_cs); - U64 length = readLength(); + uint64_t length = readLength(); return readAt(length-1); } -template -T FixList::FileData::readAt(U64 index) +template +T FixList::FileData::readAt(uint64_t index) { AutoLock autolock(file_cs); T d; @@ -196,55 +193,55 @@ T FixList::FileData::readAt(U64 index) return d; } -template -void FixList::FileData::writeAt(U64 index,const T& d) +template +void FixList::FileData::writeAt(uint64_t index, const T &d) { AutoLock autolock(file_cs); - U64 length = readLength(); + uint64_t length = readLength(); if (index>=length) return; utils::save_file(filename,DATA_SHIFT+sizeof(T)*index,(const char*)&d,1,sizeof(T)); } -template -void FixList::FileData::writeBack(const T &d) +template +void FixList::FileData::writeBack(const T &d) { AutoLock autolock(file_cs); - U64 length = readLength(); + uint64_t length = readLength(); utils::save_file(filename,DATA_SHIFT+length*sizeof(T),(char*)&d,1,sizeof(T)); length ++; writeLength(length); } -template -void FixList::FileData::removeLast() +template +void FixList::FileData::removeLast() { AutoLock autolock(file_cs); - U64 length = readLength(); + uint64_t length = readLength(); length--; writeLength(length); utils::reset_file(filename,DATA_SHIFT+length*sizeof(T)); } -template -void FixList::FileData::clear() +template +void FixList::FileData::clear() { AutoLock autolock(file_cs); utils::reset_file(filename,DATA_SHIFT); writeLength(0); } -template -void FixList::FileData::removeAt(U64 index) +template +void FixList::FileData::removeAt(uint64_t index) { AutoLock autolock(file_cs); - U64 length = readLength(); + uint64_t length = readLength(); if (index>=length) return; - U64 rl = length-index-1; + uint64_t rl = length - index - 1; length--; T *data = (T*)malloc(sizeof(T)*rl); @@ -257,10 +254,10 @@ void FixList::FileData::removeAt(U64 index) free(data); } -template -bool FixList::FileData::empty() +template +bool FixList::FileData::empty() { AutoLock autolock(file_cs); - U64 length = readLength(); + uint64_t length = readLength(); return length == 0; } diff --git a/fixlist.h b/fixlist.h index 8046794..8cff68e 100755 --- a/fixlist.h +++ b/fixlist.h @@ -1,28 +1,25 @@ #ifndef __FIXLIST_H__ #define __FIXLIST_H__ -#include +#include "lock.h" #include +#include #include #include -#include -#include "lock.h" //-------------------------------------------------------------------------------------------------- //使用相当于QList的用法,只是内部处理不同,完全可以当QList来用 //--------------------------------------------------------------------------------------------------- //泛型类 -template -class FixList -{ -public: +template class FixList { + public: //len:动态数组长度,当超过len时会自动保存到文件中,动态数组中始终 //存放的是最后一波数据 //max:总长度,超过部分将删除,若max==-1,则表示无限长 - FixList(S32 id); -// FixList(const char* idstr); + FixList(int32_t id); + // FixList(const char* idstr); FixList(const FixList& fixlist); @@ -63,20 +60,20 @@ private: private: class FileData{ public: - FileData(S32 id); - FileData(const FileData& fileData); - virtual ~FileData(); - - U64 readLength(); - void writeLength(U64 length); - T readLast(); - T readAt(U64 index); - void writeAt(U64 index, const T &d); - void writeBack(const T& d); - void removeLast(); - void clear(); - void removeAt(U64 index); - bool empty(); + FileData(int32_t id); + FileData(const FileData& fileData); + virtual ~FileData(); + + uint64_t readLength(); + void writeLength(uint64_t length); + T readLast(); + T readAt(uint64_t index); + void writeAt(uint64_t index, const T& d); + void writeBack(const T& d); + void removeLast(); + void clear(); + void removeAt(uint64_t index); + bool empty(); private: char *filename; Lock file_cs; diff --git a/lock.h b/lock.h index 58c22f0..f9451ab 100755 --- a/lock.h +++ b/lock.h @@ -1,11 +1,11 @@ #ifndef SRC_COMPONENTS_INCLUDE_UTILS_LOCK_H_ #define SRC_COMPONENTS_INCLUDE_UTILS_LOCK_H_ +#include "atomic.h" +#include "macro.h" #include #include #include -#include -#include "atomic.h" class SpinMutex { public: @@ -40,7 +40,6 @@ class Lock { Lock(bool is_recursive); ~Lock(); - bool IsLocked(); // Ackquire the lock. Must be called only once on a thread. // Please consider using AutoLock to capture it. void Acquire(); diff --git a/lock_posix.cpp b/lock_posix.cpp index a1afaa3..92aa22e 100755 --- a/lock_posix.cpp +++ b/lock_posix.cpp @@ -1,108 +1,106 @@ #include "lock.h" #include +#include #include #include #include -#include - Lock::Lock() #ifndef NDEBUG - : lock_taken_(0) - , is_mutex_recursive_(false) + : + lock_taken_(0), is_mutex_recursive_(false) #endif // NDEBUG { - Init(false); + Init(false); } Lock::Lock(bool is_recursive) #ifndef NDEBUG - : lock_taken_(0) - , is_mutex_recursive_(is_recursive) + : + lock_taken_(0), is_mutex_recursive_(is_recursive) #endif // NDEBUG { - Init(is_recursive); + Init(is_recursive); } -Lock::~Lock() { +Lock::~Lock() +{ #ifndef NDEBUG - if (lock_taken_ > 0) { - LOG_ERR("Destroying non-released mutex %p", &mutex_); - } + if (lock_taken_ > 0) { + HTELINK_LOG_ERR("Destroying non-released mutex %p", &mutex_); + } #endif - int32_t status = pthread_mutex_destroy(&mutex_); - - if (status != 0) { - LOG_ERR("Failed to destroy mutex %p:%s", &mutex_,strerror(status)); - } + int32_t status = pthread_mutex_destroy(&mutex_); + if (status != 0) { + HTELINK_LOG_ERR("Failed to destroy mutex %p:%s", &mutex_, strerror(status)); + } } -bool Lock::IsLocked() +void Lock::Acquire() { - return lock_taken_>0; + const int32_t status = pthread_mutex_lock(&mutex_); + if (status != 0) { + HTELINK_LOG_ERR("Failed to acquire mutex %p:%s", &mutex_, strerror(status)); + NOTREACHED(); + } else { + AssertFreeAndMarkTaken(); + } } -void Lock::Acquire() { - const int32_t status = pthread_mutex_lock(&mutex_); - if (status != 0) { - LOG_ERR("Failed to acquire mutex %p:%s", &mutex_ ,strerror(status)); - NOTREACHED(); - } else { - AssertFreeAndMarkTaken(); - } -} - -void Lock::Release() { - AssertTakenAndMarkFree(); - const int32_t status = pthread_mutex_unlock(&mutex_); - if (status != 0) { - LOG_ERR("Failed to unlock mutex %p :%s" , &mutex_ ,strerror(status)); - } +void Lock::Release() +{ + AssertTakenAndMarkFree(); + const int32_t status = pthread_mutex_unlock(&mutex_); + if (status != 0) { + HTELINK_LOG_ERR("Failed to unlock mutex %p :%s", &mutex_, strerror(status)); + } } -bool Lock::Try() { - const int32_t status = pthread_mutex_trylock(&mutex_); - if (status == 0) { +bool Lock::Try() +{ + const int32_t status = pthread_mutex_trylock(&mutex_); + if (status == 0) { #ifndef NDEBUG - lock_taken_++; + lock_taken_++; #endif - return true; - } - return false; + return true; + } + return false; } #ifndef NDEBUG -void Lock::AssertFreeAndMarkTaken() { - if ((lock_taken_ > 0) && !is_mutex_recursive_) { - LOG_ERR("Locking already taken not recursive mutex"); - NOTREACHED(); - } - lock_taken_++; +void Lock::AssertFreeAndMarkTaken() +{ + if ((lock_taken_ > 0) && !is_mutex_recursive_) { + HTELINK_LOG_ERR("Locking already taken not recursive mutex"); + NOTREACHED(); + } + lock_taken_++; } -void Lock::AssertTakenAndMarkFree() { - if (lock_taken_ == 0) { - LOG_ERR("Unlocking a mutex that is not taken"); - NOTREACHED(); - } - lock_taken_--; +void Lock::AssertTakenAndMarkFree() +{ + if (lock_taken_ == 0) { + HTELINK_LOG_ERR("Unlocking a mutex that is not taken"); + NOTREACHED(); + } + lock_taken_--; } #endif -void Lock::Init(bool is_recursive) { - - pthread_mutexattr_t attr; - pthread_mutexattr_init(&attr); - - const int32_t mutex_type = - is_recursive ? PTHREAD_MUTEX_RECURSIVE : PTHREAD_MUTEX_ERRORCHECK; - - pthread_mutexattr_settype(&attr, mutex_type); - const int32_t status = pthread_mutex_init(&mutex_, &attr); - pthread_mutexattr_destroy(&attr); - if (status != 0) { - LOG_ERR("Failed to initialize mutex. %s", strerror(status)); - DCHECK(status != 0); - } +void Lock::Init(bool is_recursive) +{ + pthread_mutexattr_t attr; + pthread_mutexattr_init(&attr); + + const int32_t mutex_type = is_recursive ? PTHREAD_MUTEX_RECURSIVE : PTHREAD_MUTEX_ERRORCHECK; + + pthread_mutexattr_settype(&attr, mutex_type); + const int32_t status = pthread_mutex_init(&mutex_, &attr); + pthread_mutexattr_destroy(&attr); + if (status != 0) { + HTELINK_LOG_ERR("Failed to initialize mutex. %s", strerror(status)); + DCHECK(status != 0); + } } diff --git a/logger.cpp b/logger.cpp index 0dc7af8..15262dd 100755 --- a/logger.cpp +++ b/logger.cpp @@ -1,11 +1,13 @@ -/************************************************************************* - * > File Name: logger.h - * > Author: xuwenlong - * > Mail: myxuan475@126.com +/************************************************************************* + * > File Name: logger.h + * > Author: xuwenlong + * > Mail: myxuan475@126.com * > Created Time: 2018年01月17日 星期三 10时17分14秒 ************************************************************************/ #include "logger.h" +#include "vendor_global.h" +namespace utils { static bool g_enable = true; void set_enable(bool enable) @@ -17,3 +19,77 @@ bool get_enable() { return g_enable; } + +std::string check_disk_log(const std::string &logdir) +{ + if (log_is_full()) { + std::string log; + const std::string filename = utils::logFile(logdir.c_str()); + if (filename.empty()) + return ""; + log = logdir + "/" + filename; + remove(log.c_str()); + return filename; + } + return ""; +} + +FILE *openhandle() +{ + FILE *fp; + + if (getenv("LOG")) { + if (!strcmp(getenv("LOG"), "stdout")) { + fp = stdout; + dup2(STDOUT_FILENO, STDERR_FILENO); + return fp; + } + } + + if (!get_enable()) + return NULL; + + char path[256]; + + std::string execDir = utils::get_executable_directory(); + + sprintf(path, "%s/%s-%s.log", std::string(VENDOR_LOG_PATH).c_str(), utils::todaytostr().c_str(), execDir.c_str()); + + /* move files if disk full*/ + check_disk_log(std::string(VENDOR_LOG_PATH).c_str()); + + fp = fopen(path, "a+"); + return fp; +} + +void closehandle(FILE *fp) +{ + if (getenv("LOG")) { + if (!strcmp(getenv("LOG"), "stdout")) { + return; + } + } + if (fp) { + fflush(fp); + fclose(fp); + } +} + +bool log_is_full() +{ + struct statfs diskinfo; + statfs("/", &diskinfo); + + double ffree = diskinfo.f_bfree / 1024.0 * diskinfo.f_bsize / 1024.0; + double ftotal = diskinfo.f_blocks / 1024.0 * diskinfo.f_bsize / 1024.0; + +#if HTNICE_K4 + if (ffree < 0.35 * ftotal) + return true; +#else + if (ffree < 0.25 * ftotal) + return true; +#endif + return false; +} +}; // namespace utils diff --git a/logger.h b/logger.h index e3a540f..5abfb56 100755 --- a/logger.h +++ b/logger.h @@ -1,224 +1,152 @@ -/************************************************************************* - * > File Name: logger.h - * > Author: xuwenlong - * > Mail: myxuan475@126.com +/************************************************************************* + * > File Name: logger.h + * > Author: xuwenlong + * > Mail: myxuan475@126.com * > Created Time: 2018年01月17日 星期三 10时17分14秒 ************************************************************************/ #ifndef __LOGGER_H__ #define __LOGGER_H__ +#include "custom.h" +#include "macro.h" #include #include -#include #include -#include -#include +#include +#include +#include #include #include -#include -#include - +namespace utils { void set_enable(bool enable); bool get_enable(); -#define LOG_ENABLE(enable) set_enable(enable) - -#define __FILENAME__(x) (strrchr(x,'/')?strrchr(x,'/')+1:x) - -inline static int get_current_exename(char name[256]) { - char *path_end; - char dir[256] = {0}; - if (readlink("/proc/self/exe",dir,sizeof(dir)) <= 0) - return -1; - path_end = strrchr(dir,'/'); - if (!path_end) - return -1; - ++path_end; - strcpy(name,path_end); - return 0; -} - -inline static bool log_is_full() -{ - struct statfs diskinfo; - statfs("/",&diskinfo); - - double ffree = diskinfo.f_bfree/1024.0*diskinfo.f_bsize/1024.0; - double ftotal = diskinfo.f_blocks/1024.0*diskinfo.f_bsize/1024.0; - -#if HTNICE_K4 - if (ffree < 0.35*ftotal) - return true; -#else - if (ffree < 0.25*ftotal) - return true; -#endif - return false; -} - -inline static std::string check_disk_log(const std::string &logdir) -{ - if (log_is_full()) { - std::string log; - const std::string filename = utils::logFile(logdir.c_str()); - if (filename.empty()) - return ""; - log = logdir+"/" + filename; - remove(log.c_str()); - return filename; - } - return ""; -} - -inline static FILE* openhandle() { - FILE* fp; - - if (getenv("LOG")) { - if (!strcmp(getenv("LOG"),"stdout")) { - fp = stdout; - return fp; - } - } - - if (!get_enable()) - return NULL; - - char path[MAX_NAME_LEN]; - char exename[MAX_NAME_LEN] = {0}; - get_current_exename(exename); - - sprintf(path,"%s/log/%s-%s.log", - getenv(CONFIG_DIR_ENV), - utils::todaytostr().c_str(), - exename[0]?exename:"leo-das"); - - /* move files if disk full*/ - char check_path[MAX_NAME_LEN]; - sprintf(check_path,"%s/log",getenv(CONFIG_DIR_ENV)); - check_disk_log(check_path); - - fp = fopen(path,"a+"); - return fp; -} - -inline static void closehandle(FILE *fp) { - if (getenv("LOG")) { - if (!strcmp(getenv("LOG"),"stdout")) { - return; - } - } - if (fp) { - fflush(fp); - fclose(fp); - } -} - -#define LOG_INFO(format,...) do{\ - FILE *fp = openhandle(); \ - if (fp) {\ - fprintf(fp,"[INFO] %s,%d,%s,%s:" format,\ - __FILENAME__(__FILE__),__LINE__,__FUNCTION__,utils::nowtostr().c_str(),##__VA_ARGS__);\ - fprintf(fp,"\n");\ - closehandle(fp);\ - }\ - }while(0) - -#define LOG_ERR(format,...) do{\ - FILE *fp = openhandle(); \ - if (fp) {\ - fprintf(fp,"[ERROR] %s,%d,%s,%s:" format,\ - __FILENAME__(__FILE__),__LINE__,__FUNCTION__,utils::nowtostr().c_str(),##__VA_ARGS__);\ - fprintf(fp,"\n");\ - closehandle(fp);\ - }\ - }while(0) - -#define LOG_WARN(format,...) do{\ - FILE *fp = openhandle(); \ - if (fp) {\ - fprintf(fp,"[WARN] %s,%d,%s,%s:" format,\ - __FILENAME__(__FILE__),__LINE__,__FUNCTION__,utils::nowtostr().c_str(),##__VA_ARGS__);\ - fprintf(fp,"\n");\ - closehandle(fp);\ - }\ - }while(0) - -#define LOG_DEBUG(format,...) do {\ - FILE *fp = openhandle(); \ - if (fp) {\ - fprintf(fp,"[DEBUG] %s,%d,%s,%s:" format,\ - __FILENAME__(__FILE__),__LINE__,__FUNCTION__,utils::nowtostr().c_str(),##__VA_ARGS__);\ - fprintf(fp,"\n");\ - closehandle(fp);\ - }\ - }while(0) - -#define LOG_FIXME(format,...) do{\ - FILE *fp = openhandle(); \ - if (fp) {\ - fprintf(fp,"[FIXME] %s,%d,%s,%s:" format,\ - __FILENAME__(__FILE__),__LINE__,__FUNCTION__,utils::nowtostr().c_str(),##__VA_ARGS__);\ - fprintf(fp,"\n");\ - closehandle(fp);\ - }\ - }while(0) - -class LogTrace -{ +#define HTELINK_LOG_ENABLE(enable) utils::set_enable(enable) + +#define __FILENAME__(x) (strrchr(x, '/') ? strrchr(x, '/') + 1 : x) + +inline bool log_is_full(); + +std::string check_disk_log(const std::string &logdir); + +FILE *openhandle(); +void closehandle(FILE *fp); + +#define HTELINK_LOG_INFO(format, ...) \ + do { \ + FILE *fp = utils::openhandle(); \ + if (fp) { \ + fprintf(fp, "%s,%s,%d,%s [INFO]:" format, utils::nowtostr().c_str(), __FILENAME__(__FILE__), __LINE__, \ + __FUNCTION__, ##__VA_ARGS__); \ + fprintf(fp, "\n"); \ + utils::closehandle(fp); \ + } \ + } while (0) + +#define HTELINK_LOG_ERR(format, ...) \ + do { \ + FILE *fp = utils::openhandle(); \ + if (fp) { \ + fprintf(fp, "%s, %s, %d,%s [ERROR]:" format, utils::nowtostr().c_str(), __FILENAME__(__FILE__), __LINE__, \ + __FUNCTION__, ##__VA_ARGS__); \ + fprintf(fp, "\n"); \ + utils::closehandle(fp); \ + } \ + } while (0) + +#define HTELINK_LOG_WARN(format, ...) \ + do { \ + FILE *fp = utils::openhandle(); \ + if (fp) { \ + fprintf(fp, "%s, %s,%d,%s [WARN]:" format, utils::nowtostr().c_str(), __FILENAME__(__FILE__), __LINE__, \ + __FUNCTION__, ##__VA_ARGS__); \ + fprintf(fp, "\n"); \ + utils::closehandle(fp); \ + } \ + } while (0) + +#define HTELINK_LOG_DEBUG(format, ...) \ + do { \ + FILE *fp = utils::openhandle(); \ + if (fp) { \ + fprintf(fp, "%s, %s,%d,%s [DEBUG]:" format, utils::nowtostr().c_str(), __FILENAME__(__FILE__), __LINE__, \ + __FUNCTION__, ##__VA_ARGS__); \ + fprintf(fp, "\n"); \ + utils::closehandle(fp); \ + } \ + } while (0) + +#define HTELINK_LOG_FIXME(format, ...) \ + do { \ + FILE *fp = utils::openhandle(); \ + if (fp) { \ + fprintf(fp, "%s, %s,%d,%s [FIXME]:" format, utils::nowtostr().c_str(), __FILENAME__(__FILE__), __LINE__, \ + __FUNCTION__, ##__VA_ARGS__); \ + fprintf(fp, "\n"); \ + utils::closehandle(fp); \ + } \ + } while (0) + +class LogTrace { public: - - LogTrace(const char *_file,int _line,const char *_function){ + LogTrace(const char *_file, int _line, const char *_function) + { int funlen = strlen(_function); int filelen = strlen(_file); - loginfo = (char*)malloc(filelen+funlen+10); - sprintf(loginfo,"%s,%d,%s", - _file, - _line, - _function); + loginfo = (char *)malloc(filelen + funlen + 10); + sprintf(loginfo, "%s,%d,%s", _file, _line, _function); FILE *fp = openhandle(); if (fp) { - fprintf(fp,"[TRACE] %s Enter\n",loginfo); + fprintf(fp, "[TRACE] %s Enter\n", loginfo); closehandle(fp); } - } - LogTrace(const char *_module){ + LogTrace(const char *_module) + { int funlen = strlen(_module); - loginfo = (char*)malloc(funlen+1); - strcpy(loginfo,_module); + loginfo = (char *)malloc(funlen + 1); + strcpy(loginfo, _module); FILE *fp = openhandle(); if (fp) { - fprintf(fp,"[TRACE] %s Enter\n",loginfo); + fprintf(fp, "[TRACE] %s Enter\n", loginfo); closehandle(fp); } } - ~LogTrace(){ + ~LogTrace() + { FILE *fp = openhandle(); if (fp) { - fprintf(fp,"[TRACE] %s Exit\n",loginfo); + fprintf(fp, "[TRACE] %s Exit\n", loginfo); closehandle(fp); } free(loginfo); } + private: char *loginfo; }; -#define LOG_MODULE_TRACE(name) class LogInfo { \ - public:\ - LogTrace *logTrace; \ - LogInfo() { logTrace = new LogTrace(#name);}\ - ~LogInfo(){delete logTrace;}\ - }logInfo - -#define LOG_TRACE() LogTrace logTrace(__FILENAME__(__FILE__),\ - __LINE__,\ - __FUNCTION__) +#define HTELINK_LOG_MODULE_TRACE(name) \ + class LogInfo { \ + public: \ + LogTrace *logTrace; \ + LogInfo() \ + { \ + logTrace = new LogTrace(#name); \ + } \ + ~LogInfo() \ + { \ + delete logTrace; \ + } \ + } logInfo + +#define HTELINK_LOG_TRACE() LogTrace logTrace(__FILENAME__(__FILE__), __LINE__, __FUNCTION__) +} // namespace utils #endif//__LOGGER_H__ diff --git a/macro.h b/macro.h new file mode 100644 index 0000000..89f9586 --- /dev/null +++ b/macro.h @@ -0,0 +1,101 @@ +#ifndef SRC_COMPONENTS_INCLUDE_UTILS_MACRO_H_ +#define SRC_COMPONENTS_INCLUDE_UTILS_MACRO_H_ +#include +#ifdef DEBUG +#include +#else // RELEASE +#include +#endif + +// A macro to set some action for variable to avoid "unused variable" warning +#define UNUSED(x) (void)x; +// A macro to disallow the copy constructor and operator= functions +// This should be used in the private: declarations for a class +#define DISALLOW_COPY_AND_ASSIGN(TypeName) \ + TypeName(const TypeName &); \ + void operator=(const TypeName &) + +// A macro to allow utils::Singleton call derivative constructor and destructor +#define FRIEND_BASE_SINGLETON_CLASS(TypeName) friend class utils::Singleton + +#define FRIEND_BASE_SINGLETON_CLASS_WITH_DELETER(TypeName, TypeDeleter) \ + friend class utils::Singleton + +// A macro to allow utils::deleters::Deleter::~Deleter() call class destructor +#define FRIEND_DELETER_DESTRUCTOR(TypeName) friend utils::deleters::Deleter::~Deleter() + +#ifdef DEBUG +#define ASSERT(condition) \ + FLUSH_LOGGER(); \ + do { \ + DEINIT_LOGGER(); \ + assert(condition); \ + } while (false) +#else // RELEASE +#define ASSERT(condition) \ + { \ + if (!(condition)) { \ + fprintf(stderr, "Failed condition \"" #condition "\" [%s:%d][%s]\n\n", __FILE__, __LINE__, __FUNCTION__); \ + } \ + assert((condition)); \ + } \ + while (0) +#endif + +#define DCHECK(condition) \ + if (!(condition)) { \ + ASSERT((condition)); \ + } + +/* + * Will cauch assert on debug version, + * Will return return_value in release build + */ +#define DCHECK_OR_RETURN(condition, return_value) \ + if (!(condition)) { \ + ASSERT((condition)); \ + return (return_value); \ + } +/* + * Will cauch assert on debug version, + * Will return return_value in release build + */ +#define DCHECK_OR_RETURN_VOID(condition) \ + if (!(condition)) { \ + ASSERT((condition)); \ + return; \ + } + +#define EXPORT_FUNCTION(TypeName) extern "C" TypeName *Create(); + +#define EXPORT_FUNCTION_IMPL(TypeName) \ + extern "C" TypeName *Create() \ + { \ + return new TypeName(); \ + } + +#define NOTREACHED() DCHECK(!"Unreachable code") + +// Allows to perform static check that virtual function from base class is +// actually being overriden if compiler support is available +#if __cplusplus >= 201103L +#define OVERRIDE override +#define FINAL final +#else +#define OVERRIDE +#define FINAL +#endif + +/* + * @brief Calculate size of na array + * @param arr array, which size need to calculate + */ +#define ARRAYSIZE(arr) sizeof(arr) / sizeof(*arr) + +#ifdef BUILD_TESTS +#define FRIEND_TEST(test_case_name, test_name) friend class test_case_name##_##test_name##_Test +#else // BUILD_TESTS +#define FRIEND_TEST(test_case_name, test_name) +#endif // BUILD_TESTS + +#endif // SRC_COMPONENTS_INCLUDE_UTILS_MACRO_H_ diff --git a/shared_ptr.h b/shared_ptr.h index 8292143..2d9c8fd 100755 --- a/shared_ptr.h +++ b/shared_ptr.h @@ -5,9 +5,9 @@ #include #include -#include #include "atomic.h" -#include +# include +# include namespace utils { diff --git a/shellcmd.cpp b/shellcmd.cpp index dbee605..f0b581b 100755 --- a/shellcmd.cpp +++ b/shellcmd.cpp @@ -1,70 +1,65 @@ /************************************************************************* - > File Name: shellcmd.cpp - > Author: xuwenlong - > Mail: myxuan475@126.com - > Created Time: 2018年01月22日 星期一 14时40分20秒 + > File Name: shellcmd.cpp + > Author: xuwenlong + > Mail: myxuan475@126.com + > Created Time: 2018年01月22日 星期一 14时40分20秒 ************************************************************************/ #include "shellcmd.h" -#include -#include #include +#include +#include -ShellCmd::ShellCmd(shell_runcallback callback_): - callback(callback_) -{ -} +ShellCmd::ShellCmd(shell_runcallback callback_) : callback(callback_) {} -ShellCmd::ShellCmd() -{ -} +ShellCmd::ShellCmd() {} -S32 ShellCmd::RunCmd(const S8 *cmd, void *data) +int32_t ShellCmd::RunCmd(const char* cmd, void* data) { - FILE *fp; + FILE* fp; char buffer[256] = {0}; char shell[256] = {0}; - sprintf(shell,"%s",cmd); - LOG_INFO("shell:%s",shell); + sprintf(shell, "%s", cmd); + HTELINK_LOG_INFO("shell:%s", shell); - fp = popen(shell,"r"); + fp = popen(shell, "r"); if (!fp) { - LOG_ERR("popen faild,%s",strerror(errno)); + HTELINK_LOG_ERR("popen faild,%s", strerror(errno)); return -1; } - while(!feof(fp)) { - if(fgets(buffer,sizeof(buffer),fp) != NULL) { - LOG_INFO("%s",buffer); - if (!callback(buffer,data)) + while (!feof(fp)) { + if (fgets(buffer, sizeof(buffer), fp) != NULL) { + HTELINK_LOG_INFO("%s", buffer); + if (!callback(buffer, data)) break; } } return pclose(fp); } -std::string ShellCmd::ShellGet(const S8 *cmd) +std::string ShellCmd::ShellGet(const char* cmd) { - FILE *fp; + FILE* fp; std::string result; char buffer[256] = {0}; char shell[256] = {0}; - sprintf(shell,"%s",cmd); + sprintf(shell, "%s", cmd); - LOG_INFO("shell:%s",shell); + HTELINK_LOG_INFO("shell:%s", shell); - fp = popen(shell,"r"); + fp = popen(shell, "r"); if (!fp) { - LOG_ERR("popen faild,%s",strerror(errno)); + HTELINK_LOG_ERR("popen faild,%s", strerror(errno)); return result; } while (!feof(fp)) { - if(fgets(buffer,sizeof(buffer),fp) != NULL) { - LOG_DEBUG("%s",buffer); + if (fgets(buffer, sizeof(buffer), fp) != NULL) { + HTELINK_LOG_DEBUG("%s", buffer); result += buffer; } } @@ -72,28 +67,27 @@ std::string ShellCmd::ShellGet(const S8 *cmd) return result; } -S32 ShellCmd::ShellSet(const S8 *cmd) +int32_t ShellCmd::ShellSet(const char* cmd) { - FILE *fp; + FILE* fp; char buffer[256] = {0}; char shell[256] = {0}; - sprintf(shell,"%s",cmd); + sprintf(shell, "%s", cmd); - LOG_INFO("shell:%s",shell); + HTELINK_LOG_INFO("shell:%s", shell); - fp = popen(shell,"r"); + fp = popen(shell, "r"); if (!fp) { - LOG_ERR("popen faild,%s",strerror(errno)); + HTELINK_LOG_ERR("popen faild,%s", strerror(errno)); return -1; } while (!feof(fp)) { - if(fgets(buffer,sizeof(buffer),fp) != NULL) { - LOG_INFO("%s",buffer); + if (fgets(buffer, sizeof(buffer), fp) != NULL) { + HTELINK_LOG_INFO("%s", buffer); } } return pclose(fp); } - diff --git a/shellcmd.h b/shellcmd.h index d7a467d..f14ec1e 100755 --- a/shellcmd.h +++ b/shellcmd.h @@ -1,12 +1,11 @@ /************************************************************************* - > File Name: shellcmd.h - > Author: xuwenlong - > Mail: myxuan475@126.com - > Created Time: 2018年01月22日 星期一 14时40分36秒 + > File Name: shellcmd.h + > Author: xuwenlong + > Mail: myxuan475@126.com + > Created Time: 2018年01月22日 星期一 14时40分36秒 ************************************************************************/ #include -#include typedef bool (*shell_runcallback)(const char *line,void *data); @@ -15,9 +14,9 @@ class ShellCmd public: ShellCmd(shell_runcallback callback_); ShellCmd(); - S32 RunCmd(const S8 *cmd,void *data); - std::string ShellGet(const S8 *cmd); - S32 ShellSet(const S8 *cmd); + int32_t RunCmd(const char* cmd, void* data); + std::string ShellGet(const char* cmd); + int32_t ShellSet(const char* cmd); static void result(const char *line); private: shell_runcallback callback; diff --git a/signals.h b/signals.h deleted file mode 100755 index c79a99f..0000000 --- a/signals.h +++ /dev/null @@ -1,42 +0,0 @@ -#ifndef SRC_COMPONENTS_UTILS_INCLUDE_UTILS_SIGNALS_H_ -#define SRC_COMPONENTS_UTILS_INCLUDE_UTILS_SIGNALS_H_ - -#ifdef __QNXNTO__ -typedef void (*sighandler_t)(int); -#else -#include -#endif -#include -#include -#include -#include - -namespace utils { - -class MessageQueue -{ -public: - MessageQueue(); - ~MessageQueue(); - Json::Value Execute(int mode,const std::string &script); -private: - Json::Value executeScript(int mode,const std::string &script); - void doEvent(); - static void event_timeout( - evutil_socket_t fd, - short event,void *arg); - static void event_cb( - evutil_socket_t fd, - short event,void *arg); -private: - struct event_base *m_ebase; - std::string m_strscript; - int m_mode; - Json::Value m_jsonResult; -}; - -BOOL WaitTerminationSignals( - sighandler_t sig_handler); -} - -#endif // SRC_COMPONENTS_UTILS_INCLUDE_UTILS_SIGNALS_H_ diff --git a/signals_posix.cpp b/signals_posix.cpp deleted file mode 100755 index 022d432..0000000 --- a/signals_posix.cpp +++ /dev/null @@ -1,155 +0,0 @@ -#include -#include -#include -#include - -#include "signals.h" -#include -#include "shellcmd.h" - -namespace utils { -struct event_base *base_handler(); -void signal_cb(evutil_socket_t fd,short event,void *arg); - -MessageQueue::MessageQueue(): - m_ebase(NULL) -{ -} - -MessageQueue::~MessageQueue() -{ -} - -Json::Value MessageQueue::Execute(int mode, const string &script) -{ - struct event *evn; -// struct event *ev; - - m_ebase = event_base_new(); - m_mode = mode; - m_strscript = script; - -// ev = event_new(base_handler(),-1,EV_TIMEOUT, -// event_cb,this); - - evn = event_new(m_ebase,-1,EV_TIMEOUT, - event_cb,this); - struct timeval tv; - tv.tv_sec = 0; - tv.tv_usec = 1000; -// event_add(evn,&tv); -// tv1.tv_sec = 0; -// tv1.tv_usec = 500000; - event_add(evn,&tv); - event_base_dispatch(m_ebase); - event_base_free(m_ebase); -// event_del(ev); -// event_free(ev); - event_free(evn); - return m_jsonResult; -} - -Json::Value MessageQueue::executeScript(int mode, const string &script) -{ - Json::Value result; - if (mode == 0) { - //get - ShellCmd shellCmd; - string res = shellCmd.ShellGet(script.c_str()); - if (res.empty()) - { - return result; - } - Json::CharReaderBuilder builder; - Json::CharReader *reader = builder.newCharReader(); - string err; - const char *pStr = res.c_str(); - int length = res.length(); - if (!reader->parse(pStr,pStr+length,&result,&err)) { - LOG_ERR("parse error:%s",err.c_str()); - delete reader; - return result; - } - delete reader; - return result; - } - else if (mode == 1){ - ShellCmd shellCmd; - int res = shellCmd.ShellSet(script.c_str()); - result = res; - return result; - } - else { - ShellCmd shellCmd; - string res = shellCmd.ShellGet(script.c_str()); - result = res; - return result; - } -} - -void MessageQueue::doEvent() -{ - m_jsonResult = executeScript( - m_mode, - m_strscript); - - event_base_loopbreak(m_ebase); -} - -void MessageQueue::event_timeout(int fd, short event, void *arg) -{ - LOG_TRACE(); - struct event_base *base = (struct event_base*)arg; - event_base_loopbreak(base); -} - -void MessageQueue::event_cb(int fd, short event, void *arg) -{ - LOG_TRACE(); - MessageQueue *msgQue = static_cast(arg); - msgQue->doEvent(); -} - -BOOL WaitTerminationSignals(sighandler_t sig_handler) -{ - LOG_TRACE(); - struct event_base *base = base_handler(); - struct event *signal_int = evsignal_new(base,SIGINT,signal_cb,base);/*event_self_cbarg()*/ - if(!signal_int || event_add(signal_int,NULL) < 0) - { - LOG_ERR("create or add signal_int failed"); - return false; - } - event_dispatch(); - event_del(signal_int); - sig_handler(event_get_signal(signal_int)); - - event_free(signal_int); -// event_base_free(base); - - return true; -} - -struct event_base *base_handler() -{ - static struct event_base *s_ebase = NULL; - if (s_ebase == NULL) - s_ebase = event_init(); - return s_ebase; -} - -void signal_cb(evutil_socket_t fd,short event,void *arg) -{ - LOG_TRACE(); - struct event_base *base = (struct event_base *)arg; - event_base_loopbreak(base); -} - -void event_cb(evutil_socket_t fd,short event,void *arg) -{ - LOG_TRACE(); - struct event_base *base = (struct event_base *)arg; - event_base_loopbreak(base); -} - -} diff --git a/socket_request.cpp b/socket_request.cpp deleted file mode 100755 index fb9452f..0000000 --- a/socket_request.cpp +++ /dev/null @@ -1,324 +0,0 @@ -/************************************************************************* - > File Name: socket_request.cpp - > Author: xuwenlong - > Mail: myxuan475@126.com - > Created Time: 2018年07月18日 星期三 14时36分48秒 - ************************************************************************/ -#include "socket_request.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -using namespace std; - -SocketRequest::SocketRequest(int port, const string &ipAddr, int timeout): - m_ipAddr(ipAddr), - m_iPort(port), - m_iTimeout(timeout*1000) { - -} - -//Json::Value SocketRequest::scriptRequest(const string &script,int mode ) -//{ -// Json::Value params; -// params["mode"] = mode; -// params["script"] = script; -// return sendRequest("executeScript",params); -//} - -Json::Value SocketRequest::sendRequest(const string &method,const Json::Value ¶ms) -{ - static int id = 1; - Json::Value root; - root["id"] = (id++)%10000; - root["jsonrpc"] = "2.0"; - root["method"] = method; - root["params"] = params; - - Json::StreamWriterBuilder jsbuilder; - jsbuilder["commentStyle"] = "None"; - jsbuilder["indentation"] = ""; // or whatever you like - Json::StreamWriter *writer = jsbuilder.newStreamWriter(); - std::ostringstream osout; - writer->write(root,&osout); - std::string json_file = osout.str(); - - string retstr; - delete writer; - - if (!sendRequest(json_file,retstr)) - return Json::nullValue; - Json::Value result; - Json::CharReaderBuilder builder; - builder["collectComments"] = false; - Json::CharReader *reader = builder.newCharReader(); - std::string err; - const char *pStr = retstr.c_str(); - int len = retstr.length(); - if (!reader->parse(pStr,pStr+len,&result,&err)) { - LOG_ERR("error parse,%s,%s",retstr.c_str(),err.c_str()); - delete reader; - return Json::nullValue; - } - delete reader; - if (!result.isMember("result")) { - LOG_ERR("json format error,%s",retstr.c_str()); - return Json::nullValue; - } - return result["result"]; -} - -void* SocketRequest::request_callback(void *arg) { - req_param *req = (req_param*)arg; - int fd = req->fd; - int timeout = req->timeout; - stack cFlag; - int pos = 0; - int can; - while((can = req->handle->canRead(fd,timeout))>0) { - - char buffer[64] = {0}; - int length = recv(fd, buffer, sizeof(buffer)-1, 0); - if (length>0){ - req->buffer.append(buffer,length); - req->ret = req->handle->addAndParseStr(req->buffer,cFlag,pos); - if (req->ret == 0 || req->ret == 2) - return NULL; - } - else { - if (errno == 0) { - break; - } - else if(errno == EINTR ) { - LOG_ERR("%d,%s break",errno,strerror(errno)); - break; - } - else if (errno == EAGAIN) { - if (timeout <= 0) - return NULL; - continue; - } - else { - LOG_ERR("%d,%s break",errno,strerror(errno)); - req->ret = false; - break; - } - } - if (timeout <= 0) - return NULL; - } - - return NULL; -} - -bool SocketRequest::sendRequest(const string &send,string &receive) { - int fd = open_server(m_ipAddr.c_str(),m_iPort); - - if (fd == -1) { - return false; - } - if (!sendData(fd,send.c_str(),send.length())) { - close_server(fd); - return false; - } - pthread_t pt; - - req_param req(m_iTimeout); - req.handle = this; - req.fd = fd; - - pthread_create(&pt,NULL,&request_callback,&req); - pthread_join(pt,NULL); - close_server(fd); - if (req.ret == 0) - receive = req.buffer; - return req.ret==0; -} - -int SocketRequest::open_server(const string &ipAddr,int port) { - int socketfd; - struct sockaddr_in remote_addr; - - memset(&remote_addr,0,sizeof(remote_addr)); //数据初始化--清零 - remote_addr.sin_family=AF_INET; //设置为IP通信 - remote_addr.sin_addr.s_addr=inet_addr(ipAddr.c_str());//服务器IP地址 - remote_addr.sin_port=htons(port); //服务器端口号 - - /* 创建客户端套接字--IPv4协议,面向连接通信,TCP协议 */ - if((socketfd = socket(PF_INET,SOCK_STREAM,0))<0) { - return false; - } - - /* 将套接字绑定到服务器的网络地址上 */ - if(connect(socketfd,(struct sockaddr *)&remote_addr,sizeof(struct sockaddr))<0) - { - close(socketfd); - return -1; - } - - fcntl(socketfd,F_SETFL,O_NONBLOCK); - return socketfd; -} - -void SocketRequest::close_server(int fd) { - close(fd); -} - -bool SocketRequest::sendData(int fd,const char *pData, int iLength) -{ - int total = 0; - do { - int iSent = send(fd, - (const char *)pData + total, - iLength - total, 0); - if (-1 == iSent) { - return false; - } - total += iSent; - } while (total < iLength); - if (total < iLength) - return false; - return true; -} - -int SocketRequest::canRead(int fd, int &timeout) -{ - fd_set fset; - int ret; - - FD_ZERO(&fset); - FD_SET(fd,&fset); - - timeval time; - time.tv_sec = timeout/1000; - time.tv_usec = (timeout%1000)*1000; - - ret = select(fd+1,&fset,NULL,NULL,&time); - - timeout = time.tv_sec*1000+time.tv_usec/1000; - if ( ret < 0){ - LOG_ERR("socket closed"); - return ret; - } - else if(ret == 0) { - LOG_ERR("timeout"); - return ret; - } - if (FD_ISSET(fd,&fset)) { - return ret; - } - return 0; -} - - -//0:ok -//1:not complete, -//2:illegal -int SocketRequest::addAndParseStr( - const string &szBuffer, - std::stack &m_cFlag, int &pos) -{ - const char *pStr = NULL; - int length = 0; - int i = 0; - - pStr = szBuffer.c_str(); - length = szBuffer.length(); - i = pos; - - for (;i < length;i++) { - char c = pStr[i]; - - switch(c) - { - case '{': - if (!m_cFlag.empty()) { - char top = m_cFlag.top(); - if (top == '"') - break; - } - m_cFlag.push('{'); - break; - case '}': - if (!m_cFlag.empty()) { - char top = m_cFlag.top(); - if (top == '"') - break; - else if (top == '[') { - //删去不合法 - return 2; - } - else if (top == '{') { - m_cFlag.pop(); - if (m_cFlag.empty()) { - return 0; - } - } - } - else { - //删去不合法 - return 2; - } - break; - case '[': - if (!m_cFlag.empty()) { - char top = m_cFlag.top(); - if (top == '"') - break; - } - m_cFlag.push('['); - break; - case ']': - if (!m_cFlag.empty()) { - char top = m_cFlag.top(); - if (top == '"') - break; - else if (top == '{') { - //删去不合法 - return 2; - } - else if (top == '[') { - m_cFlag.pop(); - if (m_cFlag.empty()) { - return 0; - } - } - } - else { - //删去不合法 - return 2; - } - break; - case '"': - if (!m_cFlag.empty()) { - char top = m_cFlag.top(); - if (top == '"') { - m_cFlag.pop(); - break; - } - } - m_cFlag.push('"'); - break; - case '\\': - ++i; - break; - default: - break; - } - } - pos = i; - return 1; -} - diff --git a/socket_request.h b/socket_request.h deleted file mode 100755 index ae6cb34..0000000 --- a/socket_request.h +++ /dev/null @@ -1,63 +0,0 @@ -/************************************************************************* - > File Name: socket_request.h - > Author: xuwenlong - > Mail: myxuan475@126.com - > Created Time: 2018年07月18日 星期三 14时37分08秒 - ************************************************************************/ -#ifndef __SOCKET_REQUEST_H__ -#define __SOCKET_REQUEST_H__ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -using namespace std; - -class SocketRequest -{ -public: - SocketRequest(int port = ASSIST_PORT, - const string &ipAddr = "127.0.0.1", - int timeout = 25); -// Json::Value scriptRequest(const string &script, int mode = 0); - - Json::Value sendRequest(const string &method,const Json::Value ¶ms); - - class req_param { - public: - req_param(int timeout_) { - ret = 1; - timeout = timeout_; - } - - SocketRequest *handle; - int ret; - int fd; - string buffer; - int timeout; - }; - int addAndParseStr( - const string &szBuffer, - stack &m_cFlag, - int &pos); -private: - int open_server(const string &ipAddr, int port); - void close_server(int fd); - int canRead(int fd,int &timeout); - bool sendData(int fd,const char *pData, int iLength); - bool sendRequest(const string &send,string &receive); - - static void* request_callback(void *arg); -private: - const string m_ipAddr; - int m_iPort; - int m_iTimeout; -}; - -#endif diff --git a/sqlite.cpp b/sqlite.cpp deleted file mode 100755 index 90caf48..0000000 --- a/sqlite.cpp +++ /dev/null @@ -1,217 +0,0 @@ -/************************************************************************* - > File Name: sqlite.cpp - > Author: xuwenlong - > Mail: myxuan475@126.com - > Created Time: 2018年02月01日 星期四 09时48分23秒 - ************************************************************************/ - -#include -#include -#include -#include "sqlite.h" -#include - -#define MAX_SQL_LEN 128 - -SqliteHelper::SqliteHelper( - SqliteInterface *interface, - const std::string &file, - const std::string &table): - m_pInterface(interface), - m_pSqlite3(NULL), - m_pFile(file), - m_pTable(table) -{ - OpenTable(); -} - -SqliteHelper::SqliteHelper( - const std::string &file, - const std::string &table): - m_pInterface(NULL), - m_pSqlite3(NULL), - m_pFile(file), - m_pTable(table) -{ - OpenTable(); -} - -SqliteHelper::~SqliteHelper() -{ -// sqlite3_close(m_pSqlite3); - CloseTable(); -} - -bool SqliteHelper::OpenTable() -{ - if (m_pSqlite3) - return true; - char sql_file[256]; - sprintf(sql_file,"%s/config/%s",getenv(CONFIG_DIR_ENV),m_pFile.c_str()); - if (sqlite3_open(sql_file,&m_pSqlite3)){ - LOG_ERR("can't open database %s,%s",sql_file,sqlite3_errmsg(m_pSqlite3)); - m_pSqlite3 = NULL; - return false; - } - return true; -} - -bool SqliteHelper::CloseTable() -{ - sqlite3_close(m_pSqlite3); - m_pSqlite3 = NULL; - return true; -} - -void SqliteHelper::SetFile(const std::string &file) -{ - m_pFile = file; -} - -void SqliteHelper::SetTable(const std::string &table) -{ - m_pTable = table; -} - -BOOL SqliteHelper::Create(const char *items) -{ - BOOL ret; - int len = strlen(items); - char *sql = (char*)malloc(MAX_SQL_LEN+len); -// SqliteLock sqllock(this); - - sprintf(sql,"create table if not exists %s(%s)", - m_pTable.c_str(),items); - ret = exeSQL(0,NULL,sql); - free(sql); - return ret; -} - -BOOL SqliteHelper::Insert(const char *items, const char *values) -{ - BOOL ret; - int len = strlen(items)+strlen(values); - char *sql = (char*)malloc(MAX_SQL_LEN+len); - -// SqliteLock sqllock(this); - sprintf(sql,"insert into %s(%s) values(%s);", - m_pTable.c_str(),items,values); - ret = exeSQL(0,NULL,sql); - free(sql); - return ret; -} - -BOOL SqliteHelper::Select(int searchId,void *data, const char *items, const char *condition) -{ - char *sql; - int len = strlen(items); - BOOL ret; - -// SqliteLock sqllock(this); - sql = (char*)malloc(len+MAX_SQL_LEN); - bzero(sql,len+MAX_SQL_LEN); - - if (!condition) - sprintf(sql,"select %s from %s;",items,m_pTable.c_str()); - else - sprintf(sql,"select %s from %s where %s;", - items,m_pTable.c_str(),condition); - ret = exeSQL(searchId,data,sql); - free(sql); - return ret; -} - -BOOL SqliteHelper::Select(int searchId, void *data, const char *table, const char *items, const char *condition) -{ - char *sql; - int len = strlen(items); - BOOL ret; -// SqliteLock sqllock(this); - sql = (char*)malloc(len+MAX_SQL_LEN); - bzero(sql,len+MAX_SQL_LEN); - - if (!condition) - sprintf(sql,"select %s from %s;",items,table); - else - sprintf(sql,"select %s from %s where %s;", - items,table,condition); - ret = exeSQL(searchId,data,sql); - free(sql); - return ret; -} - -BOOL SqliteHelper::Delete(const char *condition) -{ - BOOL ret; - int len = condition?strlen(condition):0; - char *sql = (char*)malloc(MAX_SQL_LEN+len); - -// SqliteLock sqllock(this); - if (condition) - sprintf(sql,"delete from %s where %s;", - m_pTable.c_str(),condition); - else - sprintf(sql,"delete from %s;", - m_pTable.c_str()); - ret = exeSQL(0,NULL,sql); - free(sql); - return ret; -} - -BOOL SqliteHelper::Update(const char *item, const char *condition) -{ - BOOL ret; - int len = strlen(item)+strlen(condition); - char *sql = (char*)malloc(MAX_SQL_LEN+len); -// SqliteLock sqllock(this); - sprintf(sql,"update %s set %s where %s;", - m_pTable.c_str(),item,condition); - ret= exeSQL(0,NULL,sql); - free(sql); - return ret; -} - -int SqliteHelper::callback(void *data, int argc, char **argv, char **azColName) -{ - SqliteData *sd = static_cast(data); -// for(int i=0; isearchId, azColName[i], argv[i] ? argv[i] : "NULL"); -// } - if (sd->interface && sd->searchId != 0) - return sd->interface->OnSqliteResult(sd->searchId,sd->data,argc,argv,azColName); - else { - if (argc==0) - return 0; - std::string* result = (std::string *)sd->data; - *result = argv[0]; - } - return 0; -} - -BOOL SqliteHelper::exeSQL(int searchId,void *data, const char *sql) -{ - char *zErrMsg = NULL; - SqliteData sd = {m_pInterface,data,searchId}; - - try { - int nRet = sqlite3_exec( - m_pSqlite3,sql, - SqliteHelper::callback, - &sd,&zErrMsg); - if (nRet == SQLITE_OK) { - return TRUE; - } - else - { - LOG_ERR("sqlite error: %s",zErrMsg); - sqlite3_free(zErrMsg); - return FALSE; - } - } - catch(std::exception& e) { - LOG_ERR("exception:%s",e.what()); - return FALSE; - } - - return FALSE; -} diff --git a/sqlite.h b/sqlite.h deleted file mode 100755 index 778cb3c..0000000 --- a/sqlite.h +++ /dev/null @@ -1,70 +0,0 @@ -/************************************************************************* - > File Name: sqlite.h - > Author: xuwenlong - > Mail: myxuan475@126.com - > Created Time: 2018年02月01日 星期四 09时48分33秒 - ************************************************************************/ -#ifndef __SQLITE_H__ -#define __SQLITE_H__ - -#include -#include -#include -#include - -class SqliteInterface -{ -public: - virtual int OnSqliteResult(int searchId,void * data,int argc,char **argv,char **azColName) = 0; -}; - -class SqliteHelper -{ -public: - SqliteHelper(SqliteInterface *interface,const std::string &file, const std::string &table); - SqliteHelper(const std::string &file, const std::string &table); - virtual ~SqliteHelper(); - - bool OpenTable(); - bool CloseTable(); - - void SetFile(const std::string &file); - void SetTable(const std::string &table); - - BOOL Create(const char *items); - BOOL Insert(const char *items,const char *values); - BOOL Select(int searchId,void *data,const char *items,const char *condition = NULL); - BOOL Select(int searchId,void *data,const char *table,const char *items,const char *condition); - BOOL Delete(const char *condition); - BOOL Update(const char *item,const char *condition); - - struct SqliteData{ - SqliteInterface *interface; - void *data; - int searchId; - }; - static int callback(void *data,int argc,char **argv,char **azColName); -private: -#if 0 - class SqliteLock { - public: - SqliteLock(SqliteHelper *helper): - m_pHelper(helper){ - m_pHelper->OpenTable(); - } - ~SqliteLock() { - m_pHelper->CloseTable(); - } - private: - SqliteHelper *m_pHelper; - }; -#endif - BOOL exeSQL(int searchId,void *data, const char *sql); -private: - sqlite3 * m_pSqlite3; - std::string m_pTable; - std::string m_pFile; - SqliteInterface * m_pInterface; -}; - -#endif//__SQLITE_H__ diff --git a/threads/thread.h b/threads/thread.h index 5f9f3e6..22d748e 100755 --- a/threads/thread.h +++ b/threads/thread.h @@ -42,11 +42,11 @@ #include #include +#include "conditional_variable.h" +#include "lock.h" #include "macro.h" #include "thread_delegate.h" #include "thread_options.h" -#include "utils/conditional_variable.h" -#include "utils/lock.h" namespace threads { diff --git a/threads/thread_delegate.cc b/threads/thread_delegate.cc index d0135bd..562961d 100755 --- a/threads/thread_delegate.cc +++ b/threads/thread_delegate.cc @@ -49,11 +49,11 @@ ThreadDelegate::~ThreadDelegate() { void ThreadDelegate::exitThreadMain() { if (thread_) { if (thread_->IsCurrentThread()) { - LOG_ERR("pthread exit"); - pthread_exit(NULL); + HTELINK_LOG_ERR("pthread exit"); + pthread_exit(NULL); } else { - LOG_ERR("pthread cancel"); - pthread_cancel(thread_->thread_handle()); + HTELINK_LOG_ERR("pthread cancel"); + pthread_cancel(thread_->thread_handle()); } thread_ = NULL; } diff --git a/threads/thread_delegate.h b/threads/thread_delegate.h index 5b433c5..63acc62 100755 --- a/threads/thread_delegate.h +++ b/threads/thread_delegate.h @@ -35,7 +35,7 @@ #include -#include "utils/lock.h" +#include "lock.h" namespace threads { diff --git a/threads/thread_posix.cc b/threads/thread_posix.cc index 421c544..97a86ea 100755 --- a/threads/thread_posix.cc +++ b/threads/thread_posix.cc @@ -118,9 +118,7 @@ void Thread::SetNameForId(const PlatformThreadHandle& thread_id, name.erase(THREAD_NAME_SIZE); const int rc = pthread_setname_np(thread_id, name.c_str()); if (rc != EOK) { - LOG_WARN("Couldn't set pthread name \" %s \" ,error code %d(%s)", - name.c_str(), - rc,strerror(rc)); + HTELINK_LOG_WARN("Couldn't set pthread name \" %s \" ,error code %d(%s)", name.c_str(), rc, strerror(rc)); } #endif } @@ -156,14 +154,14 @@ bool Thread::start(const ThreadOptions& options) { // running = 0 if (!delegate_) { - LOG_ERR("Cannot start thread %s",name_.c_str()); - // 0 - state_lock unlocked - return false; + HTELINK_LOG_ERR("Cannot start thread %s", name_.c_str()); + // 0 - state_lock unlocked + return false; } if (isThreadRunning_) { - LOG_ERR("EXIT thread %s,is already running",name_.c_str()); - return true; + HTELINK_LOG_ERR("EXIT thread %s,is already running", name_.c_str()); + return true; } thread_options_ = options; @@ -171,17 +169,17 @@ bool Thread::start(const ThreadOptions& options) { pthread_attr_t attributes; int pthread_result = pthread_attr_init(&attributes); if (pthread_result != EOK) { - LOG_WARN("Couldn't init pthread attributes. Error code = %d(%s)" - ,pthread_result,strerror(pthread_result)); + HTELINK_LOG_WARN( + "Couldn't init pthread attributes. Error code = %d(%s)", pthread_result, strerror(pthread_result)); } if (!thread_options_.is_joinable()) { pthread_result = pthread_attr_setdetachstate(&attributes, PTHREAD_CREATE_DETACHED); if (pthread_result != EOK) { - LOG_WARN("Couldn't set detach state attribute. Error code = %d(%s)" - ,pthread_result,strerror(pthread_result)); - thread_options_.is_joinable(false); + HTELINK_LOG_WARN( + "Couldn't set detach state attribute. Error code = %d(%s)", pthread_result, strerror(pthread_result)); + thread_options_.is_joinable(false); } } @@ -189,8 +187,8 @@ bool Thread::start(const ThreadOptions& options) { if (stack_size >= Thread::kMinStackSize) { pthread_result = pthread_attr_setstacksize(&attributes, stack_size); if (pthread_result != EOK) { - LOG_WARN("Couldn't set stacksize = %d,Error code = %d(%s)" - ,stack_size,pthread_result,strerror(pthread_result)); + HTELINK_LOG_WARN( + "Couldn't set stacksize = %d,Error code = %d(%s)", stack_size, pthread_result, strerror(pthread_result)); } } else { ThreadOptions thread_options_temp(Thread::kMinStackSize, @@ -208,8 +206,8 @@ bool Thread::start(const ThreadOptions& options) { state_cond_.Wait(auto_lock); thread_created_ = true; } else { - LOG_ERR("Couldn't create thread %s,Error code = %d(%s)" - ,name_.c_str(),pthread_result,strerror(pthread_result)); + HTELINK_LOG_ERR( + "Couldn't create thread %s,Error code = %d(%s)", name_.c_str(), pthread_result, strerror(pthread_result)); } } stopped_ = false; @@ -244,13 +242,9 @@ void Thread::join() { #ifndef HTNICE_OLDK4 char curr[128] = {0}; pthread_getname_np(pthread_self(),curr,128); - LOG_DEBUG("Waiting for # %s finished iteration in thread # %s", - name_.c_str(), - curr); + HTELINK_LOG_DEBUG("Waiting for # %s finished iteration in thread # %s", name_.c_str(), curr); #else - LOG_DEBUG("Waiting for # %s finished iteration in thread # %lu", - name_.c_str(), - pthread_self()); + HTELINK_LOG_DEBUG("Waiting for # %s finished iteration in thread # %lu", name_.c_str(), pthread_self()); #endif state_cond_.Wait(auto_lock); pthread_join(handle_,NULL); diff --git a/timer.cc b/timer.cc index 6d97bcd..f870faa 100755 --- a/timer.cc +++ b/timer.cc @@ -61,7 +61,7 @@ Timer::~Timer() { delegate_.reset(); threads::DeleteThread(thread_); - LOG_DEBUG("Timer %s has been destroyed", name_.c_str()); + HTELINK_LOG_DEBUG("Timer %s has been destroyed", name_.c_str()); } void Timer::Start(const Milliseconds timeout, @@ -81,7 +81,7 @@ void Timer::Start(const Milliseconds timeout, }; StartDelegate(timeout); StartThread(); - LOG_DEBUG("Timer %s has been startd",name_.c_str()); + HTELINK_LOG_DEBUG("Timer %s has been startd", name_.c_str()); } void Timer::Stop() { @@ -89,7 +89,7 @@ void Timer::Stop() { StopThread(); StopDelegate(); single_shot_ = true; - LOG_DEBUG("Timer %s has been stopped",name_.c_str()); + HTELINK_LOG_DEBUG("Timer %s has been stopped", name_.c_str()); } bool Timer::is_running() const { @@ -207,7 +207,7 @@ void Timer::TimerDelegate::threadMain() { timer_->OnTimeout(); } } else { - LOG_DEBUG("Timer has been force reset"); + HTELINK_LOG_DEBUG("Timer has been force reset"); } } } -- Gitee From 034992cce4c723624d15685fbf1f0baf466d4650 Mon Sep 17 00:00:00 2001 From: wlxuz Date: Tue, 15 Oct 2024 19:41:53 +0800 Subject: [PATCH 2/7] =?UTF-8?q?#1=20=E5=AE=8C=E5=96=84logger?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: wlxuz Change-Id: I9dc080097d094ed08cb9b44c003eba88ec3ef7e4 --- bytes.h | 20 +++++++++ logger.cpp | 84 ++++++++++++++++++++++++++++++++------ logger.h | 116 ++++++++++++++++++++--------------------------------- macro.h | 15 +++---- 4 files changed, 143 insertions(+), 92 deletions(-) create mode 100644 bytes.h diff --git a/bytes.h b/bytes.h new file mode 100644 index 0000000..b035852 --- /dev/null +++ b/bytes.h @@ -0,0 +1,20 @@ +#ifndef UTILS_BYTES_H +#define UTILS_BYTES_H +#include +#include + +namespace utils { +template +T BytesToNumber(const std::vector &bytes, size_t offset) +{ + T result = 0; + size_t numBytes = sizeof(T); + for (size_t i = 0; i < numBytes; ++i) { + result = (result << 8) | bytes[offset + i]; + } + return result; +} + +} // namespace utils + +#endif \ No newline at end of file diff --git a/logger.cpp b/logger.cpp index 15262dd..b259afc 100755 --- a/logger.cpp +++ b/logger.cpp @@ -6,9 +6,12 @@ ************************************************************************/ #include "logger.h" #include "vendor_global.h" +#include +#include namespace utils { static bool g_enable = true; +static int32_t g_level = 0; void set_enable(bool enable) { @@ -20,6 +23,21 @@ bool get_enable() return g_enable; } +void set_level(int32_t level) +{ + g_level = level; +} + +int32_t get_level() +{ + return g_level; +} + +const char *file_rchr(const char *file) +{ + return strrchr(file, '/') ? strrchr(file, '/') + 1 : file; +} + std::string check_disk_log(const std::string &logdir) { if (log_is_full()) { @@ -28,6 +46,7 @@ std::string check_disk_log(const std::string &logdir) if (filename.empty()) return ""; log = logdir + "/" + filename; + // printf("remove file: %s\n", log.c_str()); remove(log.c_str()); return filename; } @@ -49,16 +68,13 @@ FILE *openhandle() if (!get_enable()) return NULL; - char path[256]; - - std::string execDir = utils::get_executable_directory(); - - sprintf(path, "%s/%s-%s.log", std::string(VENDOR_LOG_PATH).c_str(), utils::todaytostr().c_str(), execDir.c_str()); - + std::string path = VENDOR_LOG_PATH + "/" + utils::todaytostr() + "_" + + std::string(file_rchr(utils::get_executable_directory().c_str())) + ".log"; + // printf("path: %s\n", path.c_str()); /* move files if disk full*/ check_disk_log(std::string(VENDOR_LOG_PATH).c_str()); - fp = fopen(path, "a+"); + fp = fopen(path.c_str(), "a+"); return fp; } @@ -75,6 +91,50 @@ void closehandle(FILE *fp) } } +std::string log_level_name(int32_t level) +{ + switch (level) { + case LOG_DEBUG: + return "DEBUG"; + case LOG_INFO: + return "INFO"; + case LOG_WARNING: + return "WARNNING"; + case LOG_ERR: + return "ERR"; + case LOG_FIXME: + return "FIXME"; + break; + + default: + break; + } + return "DEBUG"; +} + +void write_log(int32_t level, const std::string &file, int line, const std::string &func, const char *format, ...) +{ + if (level < get_level()) { + return; + } + FILE *fp = utils::openhandle(); + if (fp) { + fprintf(fp, "%s,%u,%u,%s,%d,%s [%s]:", utils::nowtostr().c_str(), getpid(), utils::gettid(), file.c_str(), line, + func.c_str(), log_level_name(level).c_str()); + va_list args; + va_start(args, format); + vfprintf(fp, format, args); + va_end(args); + fprintf(fp, "\n"); + utils::closehandle(fp); + } +} + +int gettid() +{ + return getuid(); +} + bool log_is_full() { struct statfs diskinfo; @@ -83,13 +143,11 @@ bool log_is_full() double ffree = diskinfo.f_bfree / 1024.0 * diskinfo.f_bsize / 1024.0; double ftotal = diskinfo.f_blocks / 1024.0 * diskinfo.f_bsize / 1024.0; -#if HTNICE_K4 - if (ffree < 0.35 * ftotal) - return true; -#else - if (ffree < 0.25 * ftotal) + // printf("total: %f, free: %f, %f%%\n", ftotal, ffree, 100 * ffree / ftotal); + + if ((100 * ffree / ftotal) < 15) return true; -#endif + return false; } }; // namespace utils diff --git a/logger.h b/logger.h index 5abfb56..ed3e0c8 100755 --- a/logger.h +++ b/logger.h @@ -8,7 +8,7 @@ #define __LOGGER_H__ #include "custom.h" -#include "macro.h" +#include #include #include #include @@ -21,10 +21,15 @@ namespace utils { void set_enable(bool enable); bool get_enable(); +void set_level(int32_t level); +int32_t get_level(); +const char *file_rchr(const char *file); + +typedef enum { LOG_DEBUG = 0, LOG_INFO, LOG_WARNING, LOG_ERR, LOG_FIXME } LOG_LEVEL; #define HTELINK_LOG_ENABLE(enable) utils::set_enable(enable) -#define __FILENAME__(x) (strrchr(x, '/') ? strrchr(x, '/') + 1 : x) +#define __FILENAME__(x) utils::file_rchr(x) inline bool log_is_full(); @@ -32,88 +37,56 @@ std::string check_disk_log(const std::string &logdir); FILE *openhandle(); void closehandle(FILE *fp); - -#define HTELINK_LOG_INFO(format, ...) \ - do { \ - FILE *fp = utils::openhandle(); \ - if (fp) { \ - fprintf(fp, "%s,%s,%d,%s [INFO]:" format, utils::nowtostr().c_str(), __FILENAME__(__FILE__), __LINE__, \ - __FUNCTION__, ##__VA_ARGS__); \ - fprintf(fp, "\n"); \ - utils::closehandle(fp); \ - } \ - } while (0) - -#define HTELINK_LOG_ERR(format, ...) \ - do { \ - FILE *fp = utils::openhandle(); \ - if (fp) { \ - fprintf(fp, "%s, %s, %d,%s [ERROR]:" format, utils::nowtostr().c_str(), __FILENAME__(__FILE__), __LINE__, \ - __FUNCTION__, ##__VA_ARGS__); \ - fprintf(fp, "\n"); \ - utils::closehandle(fp); \ - } \ - } while (0) - -#define HTELINK_LOG_WARN(format, ...) \ - do { \ - FILE *fp = utils::openhandle(); \ - if (fp) { \ - fprintf(fp, "%s, %s,%d,%s [WARN]:" format, utils::nowtostr().c_str(), __FILENAME__(__FILE__), __LINE__, \ - __FUNCTION__, ##__VA_ARGS__); \ - fprintf(fp, "\n"); \ - utils::closehandle(fp); \ - } \ - } while (0) - -#define HTELINK_LOG_DEBUG(format, ...) \ - do { \ - FILE *fp = utils::openhandle(); \ - if (fp) { \ - fprintf(fp, "%s, %s,%d,%s [DEBUG]:" format, utils::nowtostr().c_str(), __FILENAME__(__FILE__), __LINE__, \ - __FUNCTION__, ##__VA_ARGS__); \ - fprintf(fp, "\n"); \ - utils::closehandle(fp); \ - } \ - } while (0) - -#define HTELINK_LOG_FIXME(format, ...) \ - do { \ - FILE *fp = utils::openhandle(); \ - if (fp) { \ - fprintf(fp, "%s, %s,%d,%s [FIXME]:" format, utils::nowtostr().c_str(), __FILENAME__(__FILE__), __LINE__, \ - __FUNCTION__, ##__VA_ARGS__); \ - fprintf(fp, "\n"); \ - utils::closehandle(fp); \ - } \ +void write_log(int32_t level, const std::string &file, int line, const std::string &func, const char *format, ...); + +int gettid(); + +#define HTELINK_LOG_INFO(format, ...) \ + utils::write_log(utils::LOG_INFO, __FILENAME__(__FILE__), __LINE__, __FUNCTION__, format, ##__VA_ARGS__) +#define HTELINK_LOG_ERR(format, ...) \ + utils::write_log(utils::LOG_ERR, __FILENAME__(__FILE__), __LINE__, __FUNCTION__, format, ##__VA_ARGS__) +#define HTELINK_LOG_WARN(format, ...) \ + utils::write_log(utils::LOG_WARNING, __FILENAME__(__FILE__), __LINE__, __FUNCTION__, format, ##__VA_ARGS__) +#define HTELINK_LOG_DEBUG(format, ...) \ + utils::write_log(utils::LOG_DEBUG, __FILENAME__(__FILE__), __LINE__, __FUNCTION__, format, ##__VA_ARGS__) +#define HTELINK_LOG_FIXME(format, ...) \ + utils::write_log(utils::LOG_FIXME, __FILENAME__(__FILE__), __LINE__, __FUNCTION__, format, ##__VA_ARGS__) + +#define HTELINK_LOG_CMD(desc, cmd, len) \ + do { \ + FILE *fp = utils::openhandle(); \ + if (fp) { \ + fprintf(fp, "%s,%u,%u, %s,%d,%s [%s]:", utils::nowtostr().c_str(), getpid(), utils::gettid(), \ + __FILENAME__(__FILE__), __LINE__, __FUNCTION__, desc); \ + for (int i = 0; i < (len); i++) { \ + fprintf(fp, "%02x ", ((uint8_t *)(cmd))[i]); \ + } \ + fprintf(fp, "\n"); \ + fflush(fp); \ + utils::closehandle(fp); \ + } \ } while (0) class LogTrace { public: LogTrace(const char *_file, int _line, const char *_function) { - int funlen = strlen(_function); - int filelen = strlen(_file); - - loginfo = (char *)malloc(filelen + funlen + 10); - sprintf(loginfo, "%s,%d,%s", _file, _line, _function); + loginfo = + std::string(_file) + std::string(", ") + std::to_string(_line) + std::string(", ") + std::string(_function); FILE *fp = openhandle(); if (fp) { - fprintf(fp, "[TRACE] %s Enter\n", loginfo); + fprintf(fp, "[TRACE] %s Enter\n", loginfo.c_str()); closehandle(fp); } } LogTrace(const char *_module) { - int funlen = strlen(_module); - - loginfo = (char *)malloc(funlen + 1); - strcpy(loginfo, _module); + loginfo = std::string(_module); FILE *fp = openhandle(); if (fp) { - fprintf(fp, "[TRACE] %s Enter\n", loginfo); + fprintf(fp, "[TRACE] %s Enter\n", loginfo.c_str()); closehandle(fp); } } @@ -122,17 +95,16 @@ public: { FILE *fp = openhandle(); if (fp) { - fprintf(fp, "[TRACE] %s Exit\n", loginfo); + fprintf(fp, "[TRACE] %s Exit\n", loginfo.c_str()); closehandle(fp); } - free(loginfo); } private: - char *loginfo; + std::string loginfo; }; -#define HTELINK_LOG_MODULE_TRACE(name) \ +#define HTELINK_MODULE_TRACE(name) \ class LogInfo { \ public: \ LogTrace *logTrace; \ @@ -146,7 +118,7 @@ private: } \ } logInfo -#define HTELINK_LOG_TRACE() LogTrace logTrace(__FILENAME__(__FILE__), __LINE__, __FUNCTION__) +#define HTELINK_TRACE() utils::LogTrace logTrace(__FILENAME__(__FILE__), __LINE__, __FUNCTION__) } // namespace utils #endif//__LOGGER_H__ diff --git a/macro.h b/macro.h index 89f9586..2492a64 100644 --- a/macro.h +++ b/macro.h @@ -6,6 +6,7 @@ #else // RELEASE #include #endif +#include "logger.h" // A macro to set some action for variable to avoid "unused variable" warning #define UNUSED(x) (void)x; @@ -32,13 +33,13 @@ assert(condition); \ } while (false) #else // RELEASE -#define ASSERT(condition) \ - { \ - if (!(condition)) { \ - fprintf(stderr, "Failed condition \"" #condition "\" [%s:%d][%s]\n\n", __FILE__, __LINE__, __FUNCTION__); \ - } \ - assert((condition)); \ - } \ +#define ASSERT(condition) \ + { \ + if (!(condition)) { \ + HTELINK_LOG_ERR("Failed condition \"" #condition "\"\n\n"); \ + } \ + assert((condition)); \ + } \ while (0) #endif -- Gitee From d3149b0d747acd65d41d0ce13b68e898687782a5 Mon Sep 17 00:00:00 2001 From: wlxuz Date: Thu, 2 Jan 2025 08:50:29 +0800 Subject: [PATCH 3/7] =?UTF-8?q?=E9=80=82=E9=85=8Dwindows?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: wlxuz Change-Id: Ia6ecf611b9b997fdb4cb436c5f55227970159548 --- CMakeLists.txt | 3 +- conditional_variable.h | 2 +- custom.cpp | 97 ++++++++++++++++++++++-------------------- custom.h | 7 +-- logger.cpp | 27 +++++++----- logger.h | 2 +- macro.h | 9 ++-- 7 files changed, 78 insertions(+), 69 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 8b2603b..e5491d0 100755 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,14 +1,13 @@ set(MODULE utils) aux_source_directory(. DIRSRCS) -aux_source_directory(./threads/ DIRSRCS) include_directories( ./ ../include) add_library(${MODULE} ${DIRSRCS}) -target_link_libraries(${MODULE} pthread rt) +# target_link_libraries(${MODULE} pthread rt) install(TARGETS ${MODULE} DESTINATION lib/ diff --git a/conditional_variable.h b/conditional_variable.h index 63d8b5a..04c3bad 100755 --- a/conditional_variable.h +++ b/conditional_variable.h @@ -3,7 +3,7 @@ #include #include -#include +#include "macro.h" class AutoLock; class Lock; diff --git a/custom.cpp b/custom.cpp index b82a032..b10dd00 100755 --- a/custom.cpp +++ b/custom.cpp @@ -20,6 +20,11 @@ #include #include #include +#include +#include "logger.h" +#ifdef WIN32 +#include +#endif namespace utils { @@ -120,6 +125,12 @@ bool isillformat(char c) return (isspace(c) || c == '\n' || c == '\r' || c == '\0'); } +bool isInvisibleChar(char ch) +{ + return std::isspace(static_cast(ch)) || ch == '\n' || + ch == '\n'; +} + std::string <rim(std::string &str) { // std::string::iterator p = find_if(str.begin(), @@ -147,10 +158,12 @@ std::string &rtrim(std::string &str) return str; } -std::string &trim(std::string &str) +std::string trim(std::string &str) { - ltrim(rtrim(str)); - return str; + auto wsfront = std::find_if_not(str.begin(), str.end(), isInvisibleChar); + auto wsback = + std::find_if_not(str.rbegin(), str.rend(), isInvisibleChar).base(); + return (wsback <= wsfront ? std::string() : std::string(wsfront, wsback)); } int strtoint(const char *str, int len) @@ -227,7 +240,11 @@ int strtocmd(const char *str, unsigned char *&cmd) if (ilen < 1) return olen; cmd = (unsigned char *)malloc(ilen + 1); +#ifdef WIN32 + memset(cmd, 0, ilen + 1); +#else bzero(cmd, ilen + 1); +#endif if (str[ilen - 1] == 'B' || str[ilen - 1] == 'b') { int flag = 0; @@ -483,10 +500,6 @@ bool isHexDigtal(char c) bool isTerminator(const char c) { - // return (c == ')' || c == '(' || c == '[' || c == ']' ||c == '{' || c - // == '}'|| - // c == '$' || c == ' ' || c== '+' || c== '-' || - // c == '*' || c == '/' || c == '%' || c== ',' || c == '&'); return !(isalpha(c) || isalnum(c) || c == '_'); } @@ -576,16 +589,21 @@ bool isInteger(const char *str) return false; } - - std::string get_executable_directory() { char buffer[120]; - ssize_t len = readlink("/proc/self/exe", buffer, sizeof(buffer)-1); +#ifndef WIN32 + ssize_t len = readlink("/proc/self/exe", buffer, sizeof(buffer) - 1); if (len == -1) { perror("readlink"); return ""; } - buffer[len] = '\0'; +#else + DWORD len = GetCurrentDirectory(120, buffer); + if (len == 0) { + HTELINK_LOG_ERR("GetCurrentDirectory failed, %d", GetLastError()); + return ""; + } +#endif return std::string(dirname(buffer)); } @@ -594,25 +612,21 @@ bool existFile(const char *file) // FILE* fp = fopen(file,"r"); int acs = access(file, F_OK); return acs == 0; - // if (!fp) - // return false; - // fclose(fp); - // return true; - - // int acs = access(file,F_OK); - // int err = errno; - - // return (-1 != access(file,F_OK)); } -std::string logFileNotoday(const char *path) +std::vector get_file_list(const std::string &fileDir) { + std::vector filelist; +#if __cplusplus >= 201703L + for (auto &entry : std::filesystem::directory_iterator(fileDir)) { + if (entry.is_regular_file()) { + filelist.push_back(entry.path().string()); + } + } +#else DIR *dir; struct dirent *file; - std::string filename; - std::string today = utils::todaytostr(); - - if ((dir = opendir(path)) == NULL) { + if ((dir = opendir(fileDir.c_str())) == NULL) { return filename; } @@ -621,35 +635,18 @@ std::string logFileNotoday(const char *path) continue; if (file->d_type != 8) /// file continue; - if (utils::StartWith(file->d_name, today)) - continue; - filename = file->d_name; + filelist.push_back(file->d_name); break; } closedir(dir); - return filename; +#endif + return filelist; } -std::string logFile(const char *path) +std::string logFile(const std::string &path) { - DIR *dir; - struct dirent *file; std::string filename; - std::vector filelist; - - if ((dir = opendir(path)) == NULL) { - return filename; - } - - while ((file = readdir(dir)) != NULL) { - if (strcmp(file->d_name, ".") == 0 || strcmp(file->d_name, "..") == 0) /// current dir OR parrent dir - continue; - if (file->d_type != 8) /// file - continue; - filelist.push_back(file->d_name); - break; - } - closedir(dir); + std::vector filelist = get_file_list(path); if (filelist.size() > 0) { sort(filelist.begin(), filelist.end(), std::less()); filename = filelist.at(0); @@ -657,6 +654,12 @@ std::string logFile(const char *path) return filename; } +int32_t logFileCount(const std::string &path) +{ + std::vector filelist = get_file_list(path); + return filelist.size(); +} + time_t strtotime(const std::string &str) { char *cha = (char *)str.data(); // 将string转换成char*。 diff --git a/custom.h b/custom.h index 4be678d..bffbb19 100755 --- a/custom.h +++ b/custom.h @@ -35,7 +35,7 @@ std::string <rim(std::string &str); std::string &rtrim(std::string &str); -std::string &trim(std::string &str); +std::string trim(std::string &str); int strtoint(const char *str,int len = -1); int strtohex(const char *str, int len = -1); @@ -96,8 +96,9 @@ bool isInteger(const char *str); std::string get_executable_directory(); bool existFile(const char *file); -std::string logFileNotoday(const char *path); -std::string logFile(const char *path); +std::vector get_file_list(const std::string &fileDir); +std::string logFile(const std::string &path); +int32_t logFileCount(const std::string &path); time_t strtotime(const std::string &str); std::string todaytostr(); diff --git a/logger.cpp b/logger.cpp index b259afc..f257b89 100755 --- a/logger.cpp +++ b/logger.cpp @@ -8,6 +8,9 @@ #include "vendor_global.h" #include #include +#ifdef WIN32 +#include +#endif namespace utils { static bool g_enable = true; @@ -40,7 +43,7 @@ const char *file_rchr(const char *file) std::string check_disk_log(const std::string &logdir) { - if (log_is_full()) { + if (utils::logFileCount(logdir) > VENDOR_LOG_STORE_DAYS) { std::string log; const std::string filename = utils::logFile(logdir.c_str()); if (filename.empty()) @@ -71,8 +74,6 @@ FILE *openhandle() std::string path = VENDOR_LOG_PATH + "/" + utils::todaytostr() + "_" + std::string(file_rchr(utils::get_executable_directory().c_str())) + ".log"; // printf("path: %s\n", path.c_str()); - /* move files if disk full*/ - check_disk_log(std::string(VENDOR_LOG_PATH).c_str()); fp = fopen(path.c_str(), "a+"); return fp; @@ -132,22 +133,28 @@ void write_log(int32_t level, const std::string &file, int line, const std::stri int gettid() { +#ifdef WIN32 + return GetCurrentThreadId(); +#else return getuid(); +#endif } bool log_is_full() { - struct statfs diskinfo; - statfs("/", &diskinfo); + // struct statfs diskinfo; + // statfs("/", &diskinfo); - double ffree = diskinfo.f_bfree / 1024.0 * diskinfo.f_bsize / 1024.0; - double ftotal = diskinfo.f_blocks / 1024.0 * diskinfo.f_bsize / 1024.0; + // double ffree = diskinfo.f_bfree / 1024.0 * diskinfo.f_bsize / 1024.0; + // double ftotal = diskinfo.f_blocks / 1024.0 * diskinfo.f_bsize / 1024.0; - // printf("total: %f, free: %f, %f%%\n", ftotal, ffree, 100 * ffree / ftotal); + // // printf("total: %f, free: %f, %f%%\n", ftotal, ffree, 100 * ffree / + // ftotal); - if ((100 * ffree / ftotal) < 15) - return true; + // if ((100 * ffree / ftotal) < 15) + // return true; + // return false; return false; } }; // namespace utils diff --git a/logger.h b/logger.h index ed3e0c8..ac99fe9 100755 --- a/logger.h +++ b/logger.h @@ -13,7 +13,7 @@ #include #include #include -#include +// #include #include #include #include diff --git a/macro.h b/macro.h index 2492a64..b1c74e0 100644 --- a/macro.h +++ b/macro.h @@ -93,10 +93,9 @@ */ #define ARRAYSIZE(arr) sizeof(arr) / sizeof(*arr) -#ifdef BUILD_TESTS -#define FRIEND_TEST(test_case_name, test_name) friend class test_case_name##_##test_name##_Test -#else // BUILD_TESTS -#define FRIEND_TEST(test_case_name, test_name) -#endif // BUILD_TESTS +// #ifdef BUILD_TESTS +// #define FRIEND_TEST(test_case_name, test_name) friend class +// test_case_name##_##test_name##_Test #else // BUILD_TESTS #define +// FRIEND_TEST(test_case_name, test_name) #endif // BUILD_TESTS #endif // SRC_COMPONENTS_INCLUDE_UTILS_MACRO_H_ -- Gitee From 24b05d6e30389d73147e5237b9cdbb66874eb3c7 Mon Sep 17 00:00:00 2001 From: myxuan475 Date: Tue, 4 Mar 2025 15:38:30 +0800 Subject: [PATCH 4/7] =?UTF-8?q?=E5=88=A0=E9=99=A4=E4=B8=8D=E5=BF=85?= =?UTF-8?q?=E8=A6=81=E7=9A=84=E6=96=87=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: myxuan475 Change-Id: Ic8a381ef9a6a051dc9718eb33851c7e242aa54f2 --- CMakeLists.txt | 6 +- atomic.h | 0 atomic_object.h | 0 conditional_variable.h | 0 conditional_variable_posix.cpp | 0 custom.cpp | 23 ++- custom.h | 8 +- des.cpp | 0 des.h | 0 dfile.cpp | 0 dfile.h | 0 fixlist.cpp | 263 ------------------------------- fixlist.h | 85 ---------- lock.h | 0 lock_posix.cpp | 0 logger.cpp | 42 ++++- logger.h | 105 +++++++++---- network.cpp | 63 ++++++++ network.h | 20 +++ shared_ptr.cpp | 13 -- shared_ptr.h | 227 --------------------------- shellcmd.cpp | 0 shellcmd.h | 1 + threads/thread.h | 248 ----------------------------- threads/thread_delegate.cc | 67 -------- threads/thread_delegate.h | 94 ----------- threads/thread_options.h | 106 ------------- threads/thread_posix.cc | 274 --------------------------------- timer.cc | 218 -------------------------- timer.h | 234 ---------------------------- timer_task.h | 17 -- 31 files changed, 222 insertions(+), 1892 deletions(-) mode change 100755 => 100644 CMakeLists.txt mode change 100755 => 100644 atomic.h mode change 100755 => 100644 atomic_object.h mode change 100755 => 100644 conditional_variable.h mode change 100755 => 100644 conditional_variable_posix.cpp mode change 100755 => 100644 custom.cpp mode change 100755 => 100644 custom.h mode change 100755 => 100644 des.cpp mode change 100755 => 100644 des.h mode change 100755 => 100644 dfile.cpp mode change 100755 => 100644 dfile.h delete mode 100755 fixlist.cpp delete mode 100755 fixlist.h mode change 100755 => 100644 lock.h mode change 100755 => 100644 lock_posix.cpp mode change 100755 => 100644 logger.cpp mode change 100755 => 100644 logger.h create mode 100644 network.cpp create mode 100644 network.h delete mode 100755 shared_ptr.cpp delete mode 100755 shared_ptr.h mode change 100755 => 100644 shellcmd.cpp mode change 100755 => 100644 shellcmd.h delete mode 100755 threads/thread.h delete mode 100755 threads/thread_delegate.cc delete mode 100755 threads/thread_delegate.h delete mode 100755 threads/thread_options.h delete mode 100755 threads/thread_posix.cc delete mode 100755 timer.cc delete mode 100755 timer.h delete mode 100755 timer_task.h diff --git a/CMakeLists.txt b/CMakeLists.txt old mode 100755 new mode 100644 index e5491d0..18c633c --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -6,9 +6,9 @@ include_directories( ./ ../include) -add_library(${MODULE} ${DIRSRCS}) -# target_link_libraries(${MODULE} pthread rt) +add_library(${MODULE} SHARED ${DIRSRCS}) +target_link_libraries(${MODULE} ws2_32 Iphlpapi Mprapi) install(TARGETS ${MODULE} DESTINATION lib/ - PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE GROUP_READ GROUP_EXECUTE WORLD_READ) \ No newline at end of file + PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE GROUP_READ GROUP_EXECUTE WORLD_READ) diff --git a/atomic.h b/atomic.h old mode 100755 new mode 100644 diff --git a/atomic_object.h b/atomic_object.h old mode 100755 new mode 100644 diff --git a/conditional_variable.h b/conditional_variable.h old mode 100755 new mode 100644 diff --git a/conditional_variable_posix.cpp b/conditional_variable_posix.cpp old mode 100755 new mode 100644 diff --git a/custom.cpp b/custom.cpp old mode 100755 new mode 100644 index b10dd00..5bda376 --- a/custom.cpp +++ b/custom.cpp @@ -344,7 +344,7 @@ int strtohexcmd(const char *str, unsigned char *&cmd) return length; } -std::string hexcmdtostr(const unsigned char *cmd, const int byte, const char postfix) +std::string hexcmdtostr(const unsigned char *cmd, const int byte, const char postfix, const char sep) { std::string result; @@ -354,7 +354,9 @@ std::string hexcmdtostr(const unsigned char *cmd, const int byte, const char pos if (i != byte - 1) { if (postfix != '\0') result += postfix; - result += ' '; + if (sep != '\0') { + result += sep; + } } } return result; @@ -728,4 +730,21 @@ std::string nowtostr() return timetostr(time(NULL)); } +std::vector strtohexcmd(const std::string &str) +{ + int index = 0; + std::vector result; + + const char *p = str.c_str(); + while (*p != '\0' && *(p + 1) != '\0') { + if (isxdigit(*p) && isxdigit(*(p + 1))) { + result.push_back(strtohex(p, 2)); + p += 2; + } else { + p++; + } + } + return result; +} + } // namespace utils diff --git a/custom.h b/custom.h old mode 100755 new mode 100644 index bffbb19..d724f10 --- a/custom.h +++ b/custom.h @@ -11,6 +11,8 @@ #include #include #include +#include +#include namespace utils { @@ -49,7 +51,11 @@ int strtocmd(const char *str,unsigned char *& cmd); * 字符串转换成16进制命令 */ int strtohexcmd(const char *str,unsigned char*& cmd); -std::string hexcmdtostr(const unsigned char *cmd, const int byte, const char postfix = '\0'); +std::string hexcmdtostr(const unsigned char *cmd, + const int byte, + const char postfix = '\0', + const char sep = ' '); +std::vector strtohexcmd(const std::string &str); /* * 字符串转成压缩bcd码 diff --git a/des.cpp b/des.cpp old mode 100755 new mode 100644 diff --git a/des.h b/des.h old mode 100755 new mode 100644 diff --git a/dfile.cpp b/dfile.cpp old mode 100755 new mode 100644 diff --git a/dfile.h b/dfile.h old mode 100755 new mode 100644 diff --git a/fixlist.cpp b/fixlist.cpp deleted file mode 100755 index ac23245..0000000 --- a/fixlist.cpp +++ /dev/null @@ -1,263 +0,0 @@ -#include "dfile.h" -#include "fixlist.h" -#include "stdio.h" -#include "vendor_global.h" -#include -#include - -#define DATA_SHIFT sizeof(uint64_t) - -template -FixList::FixList(int32_t id) : fileData(id) -{ -} - -template -FixList::FixList(const FixList &fixlist) -{ - operator =(fixlist); -} - -template -FixList &FixList::operator=(const FixList &fixlist) -{ - fileData = fixlist.fileData; - return *this; -} - -template -FixList::~FixList() -{ - /* 保存内容 */ -} - -template -void FixList::removeLast() -{ - fileData.removeLast(); -} - -template -bool FixList::isFull() -{ - uint16_t length = fileData.readLength(); - return (M!=-1 && length == M); -} - -template -void FixList::push_back(T &t) -{ - append(t); -} - -template -void FixList::append(T &t) -{ - if (isFull()) { - fileData.removeAt(0); - } - - fileData.writeBack(t); -} - -template -T FixList::operator[](int index) -{ - T t; - this->at(&t,index); - return t; -} - -template -T FixList::at(int index) -{ - T t; - this->at(&t,index); - return t; -} - -template -bool FixList::at(T *d, int start) -{ - uint64_t length = fileData.readLength(); - if (start >= length) - return false; - *d = fileData.readAt(start); - return true; -} - -template -T FixList::end() -{ - return fileData.readLast(); -} - -template -void FixList::replace(int start, T &t) -{ - fileData.writeAt(start,t); -} - -template -void FixList::remove(int index) -{ - fileData.removeAt(index); -} - -template -void FixList::clear() -{ - fileData.clear(); -} - -template -bool FixList::isEmpty() -{ - return fileData.empty(); -} - -template -int FixList::count() -{ - return fileData.readLength(); -} - -template -int FixList::size() -{ - return count (); -} - -template -FixList::FileData::FileData(int32_t id) : file_cs(true) -{ - int len = 30 + VENDOR_DB_PATH.length(); - filename = (char*)malloc(len); - memset(filename,0,len); - sprintf(filename, "%s/LIST%04d.data", VENDOR_DB_PATH.c_str(), id); - - if(!utils::file_exist(filename)) - { - writeLength(0); - } -} - -template -FixList::FileData::FileData(const FixList::FileData &fileData) : file_cs(true) -{ - char *filename_ = (char*)malloc(strlen(fileData.filename)+1); - strcpy(filename_,fileData.filename); - if (filename) { - free(filename); - } - filename = filename_; -} - -template -FixList::FileData::~FileData() -{ - AutoLock autolock(file_cs); - free(filename); -} - -template -uint64_t FixList::FileData::readLength() -{ - AutoLock autolock(file_cs); - uint64_t length = 0; - utils::load_file(filename,0,(char*)&length,DATA_SHIFT); - return length; -} - -template -void FixList::FileData::writeLength(uint64_t length) -{ - AutoLock autolock(file_cs); - utils::save_file(filename,0,(char*)&length,DATA_SHIFT); -} - -template -T FixList::FileData::readLast() -{ - AutoLock autolock(file_cs); - uint64_t length = readLength(); - return readAt(length-1); -} - -template -T FixList::FileData::readAt(uint64_t index) -{ - AutoLock autolock(file_cs); - T d; - utils::load_file(filename,DATA_SHIFT+sizeof(T)*index,(char*)&d,1,sizeof(T)); - return d; -} - -template -void FixList::FileData::writeAt(uint64_t index, const T &d) -{ - AutoLock autolock(file_cs); - uint64_t length = readLength(); - - if (index>=length) - return; - utils::save_file(filename,DATA_SHIFT+sizeof(T)*index,(const char*)&d,1,sizeof(T)); -} - -template -void FixList::FileData::writeBack(const T &d) -{ - AutoLock autolock(file_cs); - uint64_t length = readLength(); - - utils::save_file(filename,DATA_SHIFT+length*sizeof(T),(char*)&d,1,sizeof(T)); - length ++; - writeLength(length); -} - -template -void FixList::FileData::removeLast() -{ - AutoLock autolock(file_cs); - uint64_t length = readLength(); - length--; - writeLength(length); - utils::reset_file(filename,DATA_SHIFT+length*sizeof(T)); -} - -template -void FixList::FileData::clear() -{ - AutoLock autolock(file_cs); - utils::reset_file(filename,DATA_SHIFT); - writeLength(0); -} - -template -void FixList::FileData::removeAt(uint64_t index) -{ - AutoLock autolock(file_cs); - uint64_t length = readLength(); - - if (index>=length) - return; - uint64_t rl = length - index - 1; - length--; - - T *data = (T*)malloc(sizeof(T)*rl); - bzero(data,sizeof(T)*rl); - writeLength(length); - utils::load_file(filename,DATA_SHIFT+(index+1)*sizeof(T),(char*)data,rl,sizeof(T)); - utils::save_file(filename,DATA_SHIFT+index*sizeof(T),(char*)data,rl,sizeof(T)); - utils::reset_file(filename,DATA_SHIFT+length*sizeof(T)); - - free(data); -} - -template -bool FixList::FileData::empty() -{ - AutoLock autolock(file_cs); - uint64_t length = readLength(); - return length == 0; -} diff --git a/fixlist.h b/fixlist.h deleted file mode 100755 index 8cff68e..0000000 --- a/fixlist.h +++ /dev/null @@ -1,85 +0,0 @@ -#ifndef __FIXLIST_H__ -#define __FIXLIST_H__ - -#include "lock.h" -#include -#include -#include -#include - -//-------------------------------------------------------------------------------------------------- -//使用相当于QList的用法,只是内部处理不同,完全可以当QList来用 -//--------------------------------------------------------------------------------------------------- - -//泛型类 -template class FixList { - public: - //len:动态数组长度,当超过len时会自动保存到文件中,动态数组中始终 - //存放的是最后一波数据 - //max:总长度,超过部分将删除,若max==-1,则表示无限长 - - FixList(int32_t id); - // FixList(const char* idstr); - - FixList(const FixList& fixlist); - - FixList& operator=(const FixList& fixlist); - - virtual ~FixList(); - - void push_back (T &t); - - void append(T &t); - - T operator[](int index); - - T at(int index); - - bool at(T *d,int start); - - T end(); - - int last(); - - void replace(int start,T &t); - - void remove(int index); - - void clear(); - - bool isEmpty(); - - int count();//当前的数据个数 - - int size (); - -private: - //是否已经满了 - bool isFull(); - void removeLast(); -private: - class FileData{ - public: - FileData(int32_t id); - FileData(const FileData& fileData); - virtual ~FileData(); - - uint64_t readLength(); - void writeLength(uint64_t length); - T readLast(); - T readAt(uint64_t index); - void writeAt(uint64_t index, const T& d); - void writeBack(const T& d); - void removeLast(); - void clear(); - void removeAt(uint64_t index); - bool empty(); - private: - char *filename; - Lock file_cs; - }; - - FileData fileData; -}; - -#endif // FixList_H diff --git a/lock.h b/lock.h old mode 100755 new mode 100644 diff --git a/lock_posix.cpp b/lock_posix.cpp old mode 100755 new mode 100644 diff --git a/logger.cpp b/logger.cpp old mode 100755 new mode 100644 index f257b89..d10ef14 --- a/logger.cpp +++ b/logger.cpp @@ -5,16 +5,22 @@ * > Created Time: 2018年01月17日 星期三 10时17分14秒 ************************************************************************/ #include "logger.h" -#include "vendor_global.h" #include #include #ifdef WIN32 #include #endif +#ifndef DONT_GLOBAL_VENDOR +#include "vendor_global.h" +#else +const int32_t VENDOR_LOG_STORE_DAYS = 30; +const std::string VENDOR_LOG_PATH = "./"; +#endif namespace utils { static bool g_enable = true; static int32_t g_level = 0; +LogFunc g_logFunc = nullptr; void set_enable(bool enable) { @@ -43,7 +49,11 @@ const char *file_rchr(const char *file) std::string check_disk_log(const std::string &logdir) { +#ifndef DONT_GLOBAL_VENDOR if (utils::logFileCount(logdir) > VENDOR_LOG_STORE_DAYS) { +#else + if (utils::logFileCount(logdir) > 30) { +#endif std::string log; const std::string filename = utils::logFile(logdir.c_str()); if (filename.empty()) @@ -59,7 +69,6 @@ std::string check_disk_log(const std::string &logdir) FILE *openhandle() { FILE *fp; - if (getenv("LOG")) { if (!strcmp(getenv("LOG"), "stdout")) { fp = stdout; @@ -118,17 +127,22 @@ void write_log(int32_t level, const std::string &file, int line, const std::stri if (level < get_level()) { return; } + + char buf[256] = {0}; + va_list args; + va_start(args, format); + vsnprintf(buf, 255, format, args); + va_end(args); FILE *fp = utils::openhandle(); if (fp) { fprintf(fp, "%s,%u,%u,%s,%d,%s [%s]:", utils::nowtostr().c_str(), getpid(), utils::gettid(), file.c_str(), line, func.c_str(), log_level_name(level).c_str()); - va_list args; - va_start(args, format); - vfprintf(fp, format, args); - va_end(args); - fprintf(fp, "\n"); + fprintf(fp, "%s\n", buf); utils::closehandle(fp); } + if (g_logFunc) { + g_logFunc(level, file, line, func, buf); + } } int gettid() @@ -157,4 +171,18 @@ bool log_is_full() // return false; return false; } + +void register_logfunc(LogFunc logFunc) +{ + g_logFunc = logFunc; +} + +LogFunc logfunc() +{ + if (g_logFunc == nullptr) { + g_logFunc = write_log; + } + return g_logFunc; +} + }; // namespace utils diff --git a/logger.h b/logger.h old mode 100755 new mode 100644 index ac99fe9..1be4ddd --- a/logger.h +++ b/logger.h @@ -14,6 +14,8 @@ #include #include // #include +#include +#include #include #include #include @@ -24,6 +26,12 @@ bool get_enable(); void set_level(int32_t level); int32_t get_level(); const char *file_rchr(const char *file); +void write_log(int32_t level, + const std::string &file, + int line, + const std::string &func, + const char *format, + ...); typedef enum { LOG_DEBUG = 0, LOG_INFO, LOG_WARNING, LOG_ERR, LOG_FIXME } LOG_LEVEL; @@ -35,22 +43,44 @@ inline bool log_is_full(); std::string check_disk_log(const std::string &logdir); -FILE *openhandle(); -void closehandle(FILE *fp); -void write_log(int32_t level, const std::string &file, int line, const std::string &func, const char *format, ...); +/* log func */ +using LogFunc + = std::function; +LogFunc logfunc(); +void register_logfunc(LogFunc logFunc); int gettid(); #define HTELINK_LOG_INFO(format, ...) \ - utils::write_log(utils::LOG_INFO, __FILENAME__(__FILE__), __LINE__, __FUNCTION__, format, ##__VA_ARGS__) + write_log(utils::LOG_INFO, \ + __FILENAME__(__FILE__), \ + __LINE__, \ + __FUNCTION__, \ + format, \ + ##__VA_ARGS__) #define HTELINK_LOG_ERR(format, ...) \ - utils::write_log(utils::LOG_ERR, __FILENAME__(__FILE__), __LINE__, __FUNCTION__, format, ##__VA_ARGS__) + write_log(utils::LOG_ERR, __FILENAME__(__FILE__), __LINE__, __FUNCTION__, format, ##__VA_ARGS__) #define HTELINK_LOG_WARN(format, ...) \ - utils::write_log(utils::LOG_WARNING, __FILENAME__(__FILE__), __LINE__, __FUNCTION__, format, ##__VA_ARGS__) + write_log(utils::LOG_WARNING, \ + __FILENAME__(__FILE__), \ + __LINE__, \ + __FUNCTION__, \ + format, \ + ##__VA_ARGS__) #define HTELINK_LOG_DEBUG(format, ...) \ - utils::write_log(utils::LOG_DEBUG, __FILENAME__(__FILE__), __LINE__, __FUNCTION__, format, ##__VA_ARGS__) + write_log(utils::LOG_DEBUG, \ + __FILENAME__(__FILE__), \ + __LINE__, \ + __FUNCTION__, \ + format, \ + ##__VA_ARGS__) #define HTELINK_LOG_FIXME(format, ...) \ - utils::write_log(utils::LOG_FIXME, __FILENAME__(__FILE__), __LINE__, __FUNCTION__, format, ##__VA_ARGS__) + write_log(utils::LOG_FIXME, \ + __FILENAME__(__FILE__), \ + __LINE__, \ + __FUNCTION__, \ + format, \ + ##__VA_ARGS__) #define HTELINK_LOG_CMD(desc, cmd, len) \ do { \ @@ -69,39 +99,42 @@ int gettid(); class LogTrace { public: - LogTrace(const char *_file, int _line, const char *_function) + LogTrace(bool &status, + const std::string &file, + int line, + const std::string &function, + const char *format, + ...) + : loginfo_("") + , file_(file) + , line_(line) + , function_(function) + , status_(status) { - loginfo = - std::string(_file) + std::string(", ") + std::to_string(_line) + std::string(", ") + std::string(_function); - - FILE *fp = openhandle(); - if (fp) { - fprintf(fp, "[TRACE] %s Enter\n", loginfo.c_str()); - closehandle(fp); - } - } - - LogTrace(const char *_module) - { - loginfo = std::string(_module); - FILE *fp = openhandle(); - if (fp) { - fprintf(fp, "[TRACE] %s Enter\n", loginfo.c_str()); - closehandle(fp); - } + char buf[256] = {0}; + va_list args; + va_start(args, format); + vsnprintf(buf, 255, format, args); + va_end(args); + loginfo_ = buf; + write_log(utils::LOG_INFO, file_, line_, function_, "%s ...", loginfo_.c_str()); } ~LogTrace() { - FILE *fp = openhandle(); - if (fp) { - fprintf(fp, "[TRACE] %s Exit\n", loginfo.c_str()); - closehandle(fp); + if (status_) { + write_log(utils::LOG_INFO, file_, line_, function_, "%s OK", loginfo_.c_str()); + } else { + write_log(utils::LOG_ERR, file_, line_, function_, "%s Failed", loginfo_.c_str()); } } private: - std::string loginfo; + std::string loginfo_; + std::string file_; + std::string function_; + int line_; + bool &status_; }; #define HTELINK_MODULE_TRACE(name) \ @@ -118,7 +151,13 @@ private: } \ } logInfo -#define HTELINK_TRACE() utils::LogTrace logTrace(__FILENAME__(__FILE__), __LINE__, __FUNCTION__) +#define HTELINK_TRACE(status, format, ...) \ + utils::LogTrace logTrace(status, \ + __FILENAME__(__FILE__), \ + __LINE__, \ + __FUNCTION__, \ + format, \ + ##__VA_ARGS__) } // namespace utils #endif//__LOGGER_H__ diff --git a/network.cpp b/network.cpp new file mode 100644 index 0000000..5f52d19 --- /dev/null +++ b/network.cpp @@ -0,0 +1,63 @@ +#include "network.h" +#include +#ifdef WIN32 +#include +#include +#endif +#include "logger.h" +#include + +namespace utils { +sockaddr_in sockaddr_netmask2broadcast(const struct sockaddr *addr, const struct sockaddr *netmask) +{ + sockaddr_in broadAddr; + if (addr->sa_family == AF_INET) { + struct sockaddr_in *addr4 = (struct sockaddr_in *) addr; + struct sockaddr_in *netmask4 = (struct sockaddr_in *) netmask; + // 将IP地址和子网掩码转换为32位无符号整数 + uint32_t ip = ntohl(addr4->sin_addr.s_addr); + uint32_t netmask_val = ntohl(netmask4->sin_addr.s_addr); + HTELINK_LOG_INFO("ip: %08x, mask: %08x", ip, netmask_val); + + // 计算网络地址 + uint32_t network_addr = ip & netmask_val; + uint32_t broadcast_addr = network_addr | ~netmask_val; + broadAddr.sin_addr.s_addr = htonl(broadcast_addr); + broadAddr.sin_family = addr->sa_family; + broadAddr.sin_port = addr4->sin_port; + } + return broadAddr; +} + +std::tuple netaddr2subnet(const std::string &ip, const std::string &mask) +{ + struct in_addr addr; + struct in_addr netMask; + inet_pton(AF_INET, ip.c_str(), &addr); + inet_pton(AF_INET, mask.c_str(), &netMask); + + return std::make_tuple( ntohl(addr.S_un.S_addr) & ntohl(netMask.S_un.S_addr), + (ntohl(addr.S_un.S_addr) | ntohl(~netMask.S_un.S_addr))); +} + +std::string ipaddr2string(const struct sockaddr *sa) +{ + char ipstr[INET6_ADDRSTRLEN]; + void *addr; + + // Check if it is IPv4 or IPv6 + if (sa->sa_family == AF_INET) { // IPv4 + struct sockaddr_in *s4 = (struct sockaddr_in *) sa; + addr = &(s4->sin_addr); + } else if (sa->sa_family == AF_INET6) { // IPv6 + struct sockaddr_in6 *s6 = (struct sockaddr_in6 *) sa; + addr = &(s6->sin6_addr); + } else { + return "N/A"; + } + + // Convert the IP to a string and print it + inet_ntop(sa->sa_family, addr, ipstr, sizeof(ipstr)); + return ipstr; +} +} // namespace utils diff --git a/network.h b/network.h new file mode 100644 index 0000000..6cd6312 --- /dev/null +++ b/network.h @@ -0,0 +1,20 @@ +#ifndef UTILS_NETWORK_H +#define UTILS_NETWORK_H +#include +#include +#include +#include +#include +#include +#include +#if WIN32 +#include +#endif + +namespace utils { +sockaddr_in sockaddr_netmask2broadcast(const sockaddr *addr, const sockaddr *netmask); +std::string ipaddr2string(const struct sockaddr *sa); +std::tuple netaddr2subnet(const std::string &ip, const std::string &mask); +} // namespace utils + +#endif // UTILS_NETWORK_H diff --git a/shared_ptr.cpp b/shared_ptr.cpp deleted file mode 100755 index 9271407..0000000 --- a/shared_ptr.cpp +++ /dev/null @@ -1,13 +0,0 @@ -/************************************************************************* - > File Name: shared_ptr.cpp - > Author: xuwenlong - > Mail: myxuan475@126.com - > Created Time: 2018年09月30日 星期日 10时11分07秒 - ************************************************************************/ -#include "shared_ptr.h" -#include - -namespace utils{ - - -} diff --git a/shared_ptr.h b/shared_ptr.h deleted file mode 100755 index 2d9c8fd..0000000 --- a/shared_ptr.h +++ /dev/null @@ -1,227 +0,0 @@ -#ifndef SRC_COMPONENTS_INCLUDE_UTILS_SHARED_PTR_H_ -#define SRC_COMPONENTS_INCLUDE_UTILS_SHARED_PTR_H_ - -#include -#include -#include - -#include "atomic.h" -# include -# include - -namespace utils { - -class RefrenceObj -{ -public: - RefrenceObj(): - mReferenceCounter(0) { - } - - virtual ~RefrenceObj() { -// dropReference(); - - } - -public: - int refenceCount() { - return mReferenceCounter; - } - - int addReference() { - return atomic_post_inc(&mReferenceCounter);; - } - - int dropReference() { - if (mReferenceCounter == 0) { - return 0; - } - return atomic_post_dec(&mReferenceCounter); - } - - bool valid() { - return (mReferenceCounter > 0); - } -private: - /** - * @brief Pointer to reference counter. - **/ - - uint32_t mReferenceCounter; -}; - -/** - * @brief Shared pointer. - * - * Pointer to an object with reference counting. - * Object will be automatically deallocated when last shared - * pointer is destroyed. - * - * @tparam ObjectType Type of wrapped object. - **/ -template -class SharedPtr { - - public: - /** - * @brief Constructor. - * - * Initialize shared pointer with wrapped object. - * Reference counter will be initialized to 1. - * - * @param Object Wrapped object. - **/ - SharedPtr(RefrenceObj* Object); - - SharedPtr(); - - /** - * @brief Copy constructor. - * - * Initialize shared pointer with another shared pointer. - * Reference counter will be incremented. - * - * @param Other Other shared pointer. - **/ - SharedPtr(const SharedPtr& Other); - - /** - * @brief Destructor. - * - * Decrement reference counter and destroy wrapped object - * if reference counter reaches zero. - **/ - ~SharedPtr(); - - /** - * @brief Assignment operator. - * - * Drop reference to currently referenced object and add - * reference to assigned object. - * - * @param Other Shared pointer to an object - * that must be referenced. - * - * @return Reference to this shared pointer. - **/ - SharedPtr& operator=(const SharedPtr& Other); - - bool operator==(const SharedPtr& Other) const; - - bool operator<(const SharedPtr& other) const; - - /** - * @brief Member access operator. - * - * @return Wrapped object. - **/ - ObjectType* operator->() const; - - ObjectType& operator*() const; - operator bool() const; - - ObjectType* get() const; - - /** - * @return true if mObject not NULL - */ - bool valid() const; - - private: - - /** - * @brief Wrapped object. - **/ - RefrenceObj* mObject; -}; - -template -SharedPtr::SharedPtr(utils::RefrenceObj *Object) - : mObject(Object) { - //DCHECK(Object != NULL); - if (Object) - mObject->addReference(); -} - -template -SharedPtr::SharedPtr() - : mObject(0) {} - -template -SharedPtr::SharedPtr( - const SharedPtr &Other) - : mObject(0) { - *this = Other; -} - -template -SharedPtr::~SharedPtr() { - if (mObject) { - int inc = mObject->dropReference(); - if (inc == 1) { - delete mObject; -// LOG_ERR("delete %p",mObject); - mObject = NULL; - } - } -} - -template -SharedPtr& utils::SharedPtr::operator=( - const SharedPtr& Other) { - if (mObject) - mObject->dropReference(); - mObject = Other.mObject; - - if (mObject) - mObject->addReference(); - - return *this; -} - -template -bool SharedPtr::operator==( - const SharedPtr& Other) const { - return (mObject == Other.mObject); -} - -template -bool SharedPtr::operator<( - const SharedPtr& other) const { - return (mObject < other.mObject); -} - -template -ObjectType* SharedPtr::operator->() const { - DCHECK(mObject); - return (ObjectType*)mObject; -} - -template -ObjectType& SharedPtr::operator*() const { - DCHECK(mObject); - return *(ObjectType*)mObject; -} - -template -SharedPtr::operator bool() const { - return valid(); -} - -template -ObjectType* SharedPtr::get() const { - return (ObjectType*)mObject; -} - -template -bool SharedPtr::valid() const { - if (mObject) - return mObject->valid(); - return false; -} - -} // namespace utils - -#endif // SRC_COMPONENTS_INCLUDE_UTILS_SHARED_PTR_H_ - -// vim: set ts=2 sw=2 et: diff --git a/shellcmd.cpp b/shellcmd.cpp old mode 100755 new mode 100644 diff --git a/shellcmd.h b/shellcmd.h old mode 100755 new mode 100644 index f14ec1e..dd60f4f --- a/shellcmd.h +++ b/shellcmd.h @@ -6,6 +6,7 @@ ************************************************************************/ #include +#include typedef bool (*shell_runcallback)(const char *line,void *data); diff --git a/threads/thread.h b/threads/thread.h deleted file mode 100755 index 22d748e..0000000 --- a/threads/thread.h +++ /dev/null @@ -1,248 +0,0 @@ -/* - * Copyright (c) 2015, Ford Motor Company - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * Redistributions of source code must retain the above copyright notice, this - * list of conditions and the following disclaimer. - * - * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following - * disclaimer in the documentation and/or other materials provided with the - * distribution. - * - * Neither the name of the Ford Motor Company nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef SRC_COMPONENTS_INCLUDE_UTILS_THREADS_THREAD_H_ -#define SRC_COMPONENTS_INCLUDE_UTILS_THREADS_THREAD_H_ - - -#define OS_POSIX -#if defined(OS_POSIX) -#include -#endif - -#include -#include - -#include "conditional_variable.h" -#include "lock.h" -#include "macro.h" -#include "thread_delegate.h" -#include "thread_options.h" - -namespace threads { - -#if defined(OS_POSIX) -typedef pthread_t PlatformThreadHandle; -#else -#error Please implement thread for your OS -#endif - -//typedef pthread_t PlatformThreadHandle; - -/** - * @brief Non platform specific thread abstraction that establishes a - * threads::ThreadDelegate on a new thread. - * - * ThreadDelegate example: - * class TestThread : public threads::ThreadDelegate { - * public: - * void threadMain() { - * printf("Hello, thread!\n"); - * sleep(2); - * } - * }; - * - * Example usage: - * threads::Thread thread("test thread", new TestThread()); - * thread.startWithOptions( - * threads::ThreadOptions(threads::Thread::kMinStackSize)); - * printf("join!\n"); - * thread.join(); - * printf("ok!\n"); - */ - -class Thread; -void enqueue_to_join(Thread* thread); - -Thread* CreateThread(const char* name, ThreadDelegate* delegate); -void DeleteThread(Thread* thread); - -class Thread { - private: - const std::string name_; - // Should be locked to protect delegate_ value - Lock delegate_lock_; - ThreadDelegate* delegate_; - PlatformThreadHandle handle_; - ThreadOptions thread_options_; - // Should be locked to protect isThreadRunning_ and thread_created_ values - Lock state_lock_; - volatile unsigned int isThreadRunning_; - volatile bool stopped_; - volatile bool finalized_; - bool thread_created_; - // Signalled when Thread::start() is called - ConditionalVariable run_cond_; - - public: - /** - * @brief Starts the thread. - * @return true if the thread was successfully started. - */ - bool start(); - - /** - * @brief Starts the thread. Behaves exactly like \ref start() in addition to - * allow to override the default options. - * @param options Thread options. Look for 'threads/thread_options.h' - * for details. - * @return true if the thread was successfully started. - */ - bool start(const ThreadOptions& options); - - Lock& delegate_lock() { - return delegate_lock_; - } - - ThreadDelegate* delegate() const { - return delegate_; - } - - void set_delegate(ThreadDelegate* delegate) { - delegate_ = delegate; - } - - friend Thread* CreateThread(const char* name, ThreadDelegate* delegate); - friend void DeleteThread(Thread* thread); - - public: - // Yield current thread - static void yield(); - - // Get unique ID of currently executing thread - static PlatformThreadHandle CurrentId(); - - // Give thread thread_id a name, helpful for debugging - static void SetNameForId(const PlatformThreadHandle& thread_id, - std::string name); - - /** - * @brief Signals the thread to exit and returns once the thread has exited. - * After this method returns, the Thread object is completely reset and may - * be used as if it were newly constructed (i.e., Start may be called again). - * - * Stop may be called multiple times and is simply ignored if the thread is - * already stopped. - */ - void stop(); - - void join(); - - /** - * @brief Get thread name. - * @return thread name - */ - const std::string& name() { - return name_; - } - - /** - * @brief Returns true if the thread has been started, and not yet stopped. - * When a thread is running, the thread_id_ is non-zero. - * @return true if the thread has been started, and not yet stopped. - */ - bool is_running() const { - return isThreadRunning_; - } - - bool is_created() const { - return thread_created_; - } - - void set_running(bool running); - - /** - * @brief Is thread joinable? - * @return - Returns true if the thread is joinable. - */ - bool is_joinable() const { - return thread_options_.is_joinable(); - } - - /** - * @brief Thread stack size - * @return thread stack size - */ - size_t stack_size() const { - return thread_options_.stack_size(); - } - - /** - * @brief The native thread handle. - * @return thread handle. - */ - PlatformThreadHandle thread_handle() const { - return handle_; - } - - /** - * @brief Checks if invoked in this Thread context - * @return True if called from this Thread class, false otherwise - */ - bool IsCurrentThread() const; - - /** - * @brief Thread options. - * @return thread options. - */ - const ThreadOptions& thread_options() const { - return thread_options_; - } - - /** - * @brief Minimum size of thread stack for specific platform. - */ - static size_t kMinStackSize; - - protected: - ConditionalVariable state_cond_; - - private: - /** - * Ctor. - * @param name - display string to identify the thread. - * @param delegate - thread procedure delegate. Look for - * 'threads/thread_delegate.h' for details. - * LifeCycle thread , otherwise it will be joined in stop method - * NOTE: delegate will be deleted after thread will be joined - * This constructor made private to prevent - * Thread object to be created on stack - */ - Thread(const char* name, ThreadDelegate* delegate); - virtual ~Thread(); - static void* threadFunc(void* arg); - static void cleanup(void* arg); - DISALLOW_COPY_AND_ASSIGN(Thread); -}; - -} // namespace threads -#endif // SRC_COMPONENTS_INCLUDE_UTILS_THREADS_THREAD_H_ diff --git a/threads/thread_delegate.cc b/threads/thread_delegate.cc deleted file mode 100755 index 562961d..0000000 --- a/threads/thread_delegate.cc +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright (c) 2015, Ford Motor Company - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * Redistributions of source code must retain the above copyright notice, this - * list of conditions and the following disclaimer. - * - * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following - * disclaimer in the documentation and/or other materials provided with the - * distribution. - * - * Neither the name of the Ford Motor Company nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -#include "thread_delegate.h" - -#include - -#include "thread.h" -#include "lock.h" -#include - -namespace threads { - -ThreadDelegate::~ThreadDelegate() { - if (thread_) { - thread_->set_delegate(NULL); - } -} - -void ThreadDelegate::exitThreadMain() { - if (thread_) { - if (thread_->IsCurrentThread()) { - HTELINK_LOG_ERR("pthread exit"); - pthread_exit(NULL); - } else { - HTELINK_LOG_ERR("pthread cancel"); - pthread_cancel(thread_->thread_handle()); - } - thread_ = NULL; - } -} - -void ThreadDelegate::set_thread(Thread* thread) { - DCHECK(thread); - thread_ = thread; -} - -} // namespace threads diff --git a/threads/thread_delegate.h b/threads/thread_delegate.h deleted file mode 100755 index 63acc62..0000000 --- a/threads/thread_delegate.h +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright (c) 2013, Ford Motor Company - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * Redistributions of source code must retain the above copyright notice, this - * list of conditions and the following disclaimer. - * - * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following - * disclaimer in the documentation and/or other materials provided with the - * distribution. - * - * Neither the name of the Ford Motor Company nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef SRC_COMPONENTS_INCLUDE_UTILS_THREADS_THREAD_DELEGATE_H_ -#define SRC_COMPONENTS_INCLUDE_UTILS_THREADS_THREAD_DELEGATE_H_ - -#include - -#include "lock.h" - -namespace threads { - -enum ThreadState { kInit = 0, kStarted = 1, kStopReq = 2 }; - -class Thread; - -/** - * Thread procedure interface. - * Look for "threads/thread.h" for example - */ -class ThreadDelegate { - public: - ThreadDelegate() : state_(kInit), thread_(NULL) {} - /** - * \brief Thread procedure. - */ - virtual void threadMain() = 0; - - /** - * Should be called to free all resources allocated in threadMain - * and exiting threadMain - * This function should be blocking and return only when threadMain() will be - * finished in other case segmantation failes are possible - */ - virtual void exitThreadMain(); - - virtual ~ThreadDelegate(); - - Thread* thread() const { - return thread_; - } - - void set_thread(Thread* thread); - - bool ImproveState(unsigned int to) { - state_lock_.Lock(); - if ((state_ + 1 == to) || (to == kInit && state_ == kStopReq)) { - state_ = to; - } - state_lock_.Unlock(); - return state_ == to; - } - - unsigned int state() const { - return state_; - } - - private: - volatile unsigned int state_; - SpinMutex state_lock_; - Thread* thread_; -}; - -} // namespace threads -#endif // SRC_COMPONENTS_INCLUDE_UTILS_THREADS_THREAD_DELEGATE_H_ diff --git a/threads/thread_options.h b/threads/thread_options.h deleted file mode 100755 index 2f5c90a..0000000 --- a/threads/thread_options.h +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Copyright (c) 2013, Ford Motor Company - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * Redistributions of source code must retain the above copyright notice, this - * list of conditions and the following disclaimer. - * - * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following - * disclaimer in the documentation and/or other materials provided with the - * distribution. - * - * Neither the name of the Ford Motor Company nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef SRC_COMPONENTS_INCLUDE_UTILS_THREADS_THREAD_OPTIONS_H_ -#define SRC_COMPONENTS_INCLUDE_UTILS_THREADS_THREAD_OPTIONS_H_ - -#include - -namespace threads { - -/** - * @brief Startup options for thread. - * Look for "threads/thread.h" for example - */ -class ThreadOptions { - public: - /** - * Ctor - * @param stack_size - thread stack size. If stack size less than - * threads::Thread::kMinStackSize the default value is used. - * 0 - default stack size for current platform. - * @param is_joinable - is thread joinable? - */ - explicit ThreadOptions(size_t stack_size = 0, bool is_joinable = true) - : stack_size_(stack_size), is_joinable_(is_joinable) {} - - /** - * Dtor. - */ - virtual ~ThreadOptions() {} - - /** - * Copy ctor. - * @param options - new options. - */ - ThreadOptions(const ThreadOptions& options) { - *this = options; - } - - /** - * Assign operator. - * @param options - new options. - * @return new options. - */ - ThreadOptions& operator=(const ThreadOptions& options) { - stack_size_ = options.stack_size(); - is_joinable_ = options.is_joinable(); - return *this; - } - - /** - * Stack size. - * @return Stack size for thread. - */ - size_t stack_size() const { - return stack_size_; - } - - /** - * Is thread joinable? - * @return - Returns true if the thread is joinable. - */ - bool is_joinable() const { - return is_joinable_; - } - - void is_joinable(bool val) { - is_joinable_ = val; - } - - protected: - size_t stack_size_; - bool is_joinable_; -}; - -} // namespace threads -#endif // SRC_COMPONENTS_INCLUDE_UTILS_THREADS_THREAD_OPTIONS_H_ diff --git a/threads/thread_posix.cc b/threads/thread_posix.cc deleted file mode 100755 index 97a86ea..0000000 --- a/threads/thread_posix.cc +++ /dev/null @@ -1,274 +0,0 @@ -/* - * Copyright (c) 2015, Ford Motor Company - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * Redistributions of source code must retain the above copyright notice, this - * list of conditions and the following disclaimer. - * - * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following - * disclaimer in the documentation and/or other materials provided with the - * distribution. - * - * Neither the name of the Ford Motor Company nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -#include -#include -#include -#include -#include -#include -#include - -#include "threads/thread.h" -#include "atomic.h" -#include "threads/thread_delegate.h" -#include "logger.h" - -#ifndef __QNXNTO__ -const int EOK = 0; -#endif - -#if defined(OS_POSIX) -const size_t THREAD_NAME_SIZE = 128; -#endif - -namespace threads { - -size_t Thread::kMinStackSize = - PTHREAD_STACK_MIN; /* Ubuntu : 16384 ; QNX : 256; */ - -void Thread::cleanup(void* arg) { - Thread* thread = reinterpret_cast(arg); - AutoLock auto_lock(thread->state_lock_); - thread->isThreadRunning_ = false; - thread->thread_created_ = false; - thread->state_cond_.Broadcast(); -} - -void* Thread::threadFunc(void* arg) { - // 0 - state_lock unlocked - // stopped = 0 - // running = 0 - // finalized = 0 - // 4 - state_lock unlocked - // stopped = 1 - // running = 1 - // finalized = 0 - // 5 - state_lock unlocked - // stopped = 1 - // running = 1 - // finalized = 1 - pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL); - - threads::Thread* thread = reinterpret_cast(arg); - DCHECK(thread); - - pthread_cleanup_push(&cleanup, thread); - - thread->state_lock_.Acquire(); - thread->state_cond_.Broadcast(); - -// while (!thread->finalized_) { - thread->run_cond_.Wait(thread->state_lock_); - if (!thread->stopped_ && !thread->finalized_) { - thread->isThreadRunning_ = true; - thread->state_lock_.Release(); - - pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL); - pthread_testcancel(); - if (!thread->delegate_) - exit(EXIT_FAILURE); - thread->delegate_->threadMain(); - pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL); - - thread->state_lock_.Acquire(); - thread->isThreadRunning_ = false; - } -// thread->state_cond_.Broadcast(); -// } - - thread->state_lock_.Release(); - pthread_cleanup_pop(1); - return NULL; -} - -void Thread::SetNameForId(const PlatformThreadHandle& thread_id, - std::string name) { -#ifndef HTNICE_OLDK4 - if (name.size() > THREAD_NAME_SIZE) - name.erase(THREAD_NAME_SIZE); - const int rc = pthread_setname_np(thread_id, name.c_str()); - if (rc != EOK) { - HTELINK_LOG_WARN("Couldn't set pthread name \" %s \" ,error code %d(%s)", name.c_str(), rc, strerror(rc)); - } -#endif -} - -Thread::Thread(const char* name, ThreadDelegate* delegate) - : name_(name ? name : "undefined") - , delegate_(delegate) - , handle_(0) - , thread_options_(PTHREAD_STACK_MIN*2,false) - , isThreadRunning_(0) - , stopped_(false) - , finalized_(false) - , thread_created_(false) - , state_lock_(true){} - -bool Thread::start() { - return start(thread_options_); -} - -PlatformThreadHandle Thread::CurrentId() { - return pthread_self(); -} - -bool Thread::IsCurrentThread() const { - return pthread_equal(CurrentId(), thread_handle()); -} - -bool Thread::start(const ThreadOptions& options) { - - AutoLock auto_lock(state_lock_); - // 1 - state_lock locked - // stopped = 0 - // running = 0 - - if (!delegate_) { - HTELINK_LOG_ERR("Cannot start thread %s", name_.c_str()); - // 0 - state_lock unlocked - return false; - } - - if (isThreadRunning_) { - HTELINK_LOG_ERR("EXIT thread %s,is already running", name_.c_str()); - return true; - } - - thread_options_ = options; - - pthread_attr_t attributes; - int pthread_result = pthread_attr_init(&attributes); - if (pthread_result != EOK) { - HTELINK_LOG_WARN( - "Couldn't init pthread attributes. Error code = %d(%s)", pthread_result, strerror(pthread_result)); - } - - if (!thread_options_.is_joinable()) { - pthread_result = - pthread_attr_setdetachstate(&attributes, PTHREAD_CREATE_DETACHED); - if (pthread_result != EOK) { - HTELINK_LOG_WARN( - "Couldn't set detach state attribute. Error code = %d(%s)", pthread_result, strerror(pthread_result)); - thread_options_.is_joinable(false); - } - } - - const size_t stack_size = thread_options_.stack_size(); - if (stack_size >= Thread::kMinStackSize) { - pthread_result = pthread_attr_setstacksize(&attributes, stack_size); - if (pthread_result != EOK) { - HTELINK_LOG_WARN( - "Couldn't set stacksize = %d,Error code = %d(%s)", stack_size, pthread_result, strerror(pthread_result)); - } - } else { - ThreadOptions thread_options_temp(Thread::kMinStackSize, - thread_options_.is_joinable()); - thread_options_ = thread_options_temp; - } - - if (!thread_created_) { - // state_lock 1 - pthread_result = pthread_create(&handle_, &attributes, threadFunc, this); - if (pthread_result == EOK) { - SetNameForId(handle_, name_); - // state_lock 0 - // possible concurrencies: stop and threadFunc - state_cond_.Wait(auto_lock); - thread_created_ = true; - } else { - HTELINK_LOG_ERR( - "Couldn't create thread %s,Error code = %d(%s)", name_.c_str(), pthread_result, strerror(pthread_result)); - } - } - stopped_ = false; - run_cond_.NotifyOne(); - pthread_attr_destroy(&attributes); - return pthread_result == EOK; -} - -void Thread::yield() { - sched_yield(); -} - -void Thread::stop() { - AutoLock auto_lock(state_lock_); - - stopped_ = true; - - if (delegate_ && isThreadRunning_) { - delegate_->exitThreadMain(); - } -} - -void Thread::join() { -// DCHECK_OR_RETURN_VOID(!IsCurrentThread()); - - stop(); - - AutoLock auto_lock(state_lock_); - run_cond_.NotifyOne(); - if (isThreadRunning_) { - if (!pthread_equal(pthread_self(), handle_)) { -#ifndef HTNICE_OLDK4 - char curr[128] = {0}; - pthread_getname_np(pthread_self(),curr,128); - HTELINK_LOG_DEBUG("Waiting for # %s finished iteration in thread # %s", name_.c_str(), curr); -#else - HTELINK_LOG_DEBUG("Waiting for # %s finished iteration in thread # %lu", name_.c_str(), pthread_self()); -#endif - state_cond_.Wait(auto_lock); - pthread_join(handle_,NULL); - } - } -} - -Thread::~Thread() { - AutoLock auto_lock(state_lock_); - finalized_ = true; - stopped_ = true; - join(); - // in some platforms pthread_join behaviour is undefined when thread is - // not created(pthread_create) and call pthread_join. -} - -Thread* CreateThread(const char* name, ThreadDelegate* delegate) { - Thread* thread = new Thread(name, delegate); - delegate->set_thread(thread); - return thread; -} - -void DeleteThread(Thread* thread) { - delete thread; -} - -} // namespace threads diff --git a/timer.cc b/timer.cc deleted file mode 100755 index f870faa..0000000 --- a/timer.cc +++ /dev/null @@ -1,218 +0,0 @@ -/* - * Copyright (c) 2016, Ford Motor Company - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * Redistributions of source code must retain the above copyright notice, this - * list of conditions and the following disclaimer. - * - * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following - * disclaimer in the documentation and/or other materials provided with the - * distribution. - * - * Neither the name of the Ford Motor Company nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -#include "timer.h" - -#include - -#include "macro.h" -#include "logger.h" -#include "lock.h" -#include "timer_task.h" -#include "conditional_variable.h" -#include "threads/thread.h" -#include "threads/thread_delegate.h" - -Timer::Timer(const std::string& name, TimerTask* task) - : name_(name) - , task_(task) - , state_lock_(true) - , delegate_(new TimerDelegate(this, state_lock_)) - , thread_(threads::CreateThread(name_.c_str(), delegate_.get())) - , single_shot_(true) { - DCHECK(!name_.empty()); - DCHECK(task_); - DCHECK(thread_); -} - -Timer::~Timer() { - AutoLock auto_lock(state_lock_); - StopThread(); - StopDelegate(); - single_shot_ = true; - - delegate_.reset(); - threads::DeleteThread(thread_); - HTELINK_LOG_DEBUG("Timer %s has been destroyed", name_.c_str()); -} - -void Timer::Start(const Milliseconds timeout, - const TimerType timer_type) { - AutoLock auto_lock(state_lock_); - StopThread(); - switch (timer_type) { - case kSingleShot: { - single_shot_ = true; - break; - } - case kPeriodic: { - single_shot_ = false; - break; - } - default: { ASSERT("timer_type should be kSingleShot or kPeriodic"); } - }; - StartDelegate(timeout); - StartThread(); - HTELINK_LOG_DEBUG("Timer %s has been startd", name_.c_str()); -} - -void Timer::Stop() { - AutoLock auto_lock(state_lock_); - StopThread(); - StopDelegate(); - single_shot_ = true; - HTELINK_LOG_DEBUG("Timer %s has been stopped", name_.c_str()); -} - -bool Timer::is_running() const { - AutoLock auto_lock(state_lock_); - return !delegate_->stop_flag(); -} - -bool Timer::IsRunning() const -{ - return is_running(); -} - -Milliseconds Timer::timeout() const { - AutoLock auto_lock(state_lock_); - return delegate_->timeout(); -} - -void Timer::set_timeout(Milliseconds timeout) -{ - delegate_->set_timeout(timeout); -} - -void Timer::StartDelegate(const Milliseconds timeout) const { - delegate_->set_stop_flag(false); - delegate_->set_timeout(timeout); -} - -void Timer::StopDelegate() const { - delegate_->set_stop_flag(true); - delegate_->set_timeout(0); -} - -void Timer::StartThread() { - if (delegate_->finalized_flag()) { - return; - } - - DCHECK_OR_RETURN_VOID(thread_); - if (!thread_->IsCurrentThread()) { - thread_->start(); - } -} - -void Timer::StopThread() { - if (delegate_->finalized_flag()) { - return; - } - - DCHECK_OR_RETURN_VOID(thread_); - if (!thread_->IsCurrentThread()) { - delegate_->set_finalized_flag(true); - { - AutoUnlock auto_unlock(state_lock_); - thread_->join(); - } - delegate_->set_finalized_flag(false); - } -} - -void Timer::OnTimeout() const { - { - AutoLock auto_lock(state_lock_); - if (single_shot_) { - StopDelegate(); - } - } - - DCHECK_OR_RETURN_VOID(task_); - task_->RunTimer(); -} - -Timer::TimerDelegate::TimerDelegate( - const Timer* timer,Lock& state_lock_ref) - : timer_(timer) - , timeout_(0) - , stop_flag_(true) - , finalized_flag_(false) - , state_lock_ref_(state_lock_ref) - , state_condition_() { - DCHECK(timer_); -} - -void Timer::TimerDelegate::set_timeout(const Milliseconds timeout) { - timeout_ = timeout; -} - -Milliseconds Timer::TimerDelegate::timeout() const { - return timeout_; -} - -void Timer::TimerDelegate::set_stop_flag(const bool stop_flag) { - stop_flag_ = stop_flag; -} - -bool Timer::TimerDelegate::stop_flag() const { - return stop_flag_; -} - -void Timer::TimerDelegate::set_finalized_flag( - const bool finalized_flag) { - finalized_flag_ = finalized_flag; -} - -bool Timer::TimerDelegate::finalized_flag() const { - return finalized_flag_; -} - -void Timer::TimerDelegate::threadMain() { - AutoLock auto_lock(state_lock_ref_); - while (!stop_flag_ && !finalized_flag_) { - if (ConditionalVariable::kTimeout == - state_condition_.WaitFor(auto_lock, timeout_)) { - if (timer_) { - AutoUnlock auto_unlock(auto_lock); - timer_->OnTimeout(); - } - } else { - HTELINK_LOG_DEBUG("Timer has been force reset"); - } - } -} - -void Timer::TimerDelegate::exitThreadMain() { - AutoLock auto_lock(state_lock_ref_); - state_condition_.NotifyOne(); -} diff --git a/timer.h b/timer.h deleted file mode 100755 index ca9d884..0000000 --- a/timer.h +++ /dev/null @@ -1,234 +0,0 @@ -/* - * Copyright (c) 2016, Ford Motor Company - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * Redistributions of source code must retain the above copyright notice, this - * list of conditions and the following disclaimer. - * - * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following - * disclaimer in the documentation and/or other materials provided with the - * distribution. - * - * Neither the name of the Ford Motor Company nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -#ifndef SRC_COMPONENTS_UTILS_INCLUDE_UTILS_TIMER_H_ -#define SRC_COMPONENTS_UTILS_INCLUDE_UTILS_TIMER_H_ - -#include -#include -#include - -#include "macro.h" -#include "lock.h" -#include "timer_task.h" -#include "threads/thread.h" -#include "threads/thread_delegate.h" - -typedef uint32_t Milliseconds; - -/** - * @brief Enumeration listing of possible timer types. - * Single shot timer signals only once and then stops counting. - * Periodic timer signals every time specific value is reached - * and then restarts. - */ -enum TimerType { - /** - * @brief Periodic calls to task - */ - kPeriodic = 0, - /** - * @brief Single call to task - */ - kSingleShot = 1 -}; - -/** - * @brief Timer calls custom callback function after - * specified timeout has been elapsed. - * Thread-safe class - */ -class Timer { - public: - /** - * @brief Constructor - * Does not start timer - * @param name Timer name for identification - * @param task Task for tracking - */ - Timer(const std::string& name, TimerTask* task); - - /** - * @brief Destructor - * Stops timer if it's running - */ - ~Timer(); - - /** - * @brief Starts timer with specified timeout - * @param timeout Timer timeout - * @param enum timer_type Timer type enum value. - */ - void Start(const Milliseconds timeout, const TimerType timer_type); - - /** - * @brief Stops timer if it's running - */ - void Stop(); - - /** - * @brief Gets current timer status - * @return True in case of timer is running, false otherwise - */ - bool is_running() const; - bool IsRunning() const; - - /** - * @brief Gets current timer timeout - * @return Current timeout in milliseconds. - * Null if timer has not been started - */ - Milliseconds timeout() const; - - void set_timeout(Milliseconds timeout); - const std::string &timer_name() const{return name_;} - - private: - /** - * @brief Delegate for timer thread - */ - class TimerDelegate : public threads::ThreadDelegate { - public: - /** - * @brief Constructor - * @param timer Timer instance pointer for callback calling - */ - TimerDelegate(const Timer* timer, Lock& state_lock_ref); - - /** - * @brief Sets timer timeout - * @param timeout Timeout in milliseconds to be set - */ - void set_timeout(const Milliseconds timeout); - - /** - * @brief Gets timer timeout - * @return Timer timeout - */ - Milliseconds timeout() const; - - /** - * @brief Sets timer delegate stop flag - * @param stop_flag Bool flag to be set - */ - void set_stop_flag(const bool stop_flag); - - /** - * @brief Gets timer delegate stop flag - * @return Delegate stop flag - */ - bool stop_flag() const; - - /** - * @brief Sets timer delegate finalized flag - * @param finalized_flag Bool flag to be set - */ - void set_finalized_flag(const bool finalized_flag); - - /** - * @brief Gets timer delegate finalized flag - * @return Delegate finalized flag - */ - bool finalized_flag() const; - - void threadMain() OVERRIDE; - void exitThreadMain() OVERRIDE; - - private: - const Timer* timer_; - Milliseconds timeout_; - - /** - * @brief Stop flag shows if timer should be stopped - * after next iteration - */ - bool stop_flag_; - - /** - * @brief Finalized flag shows if timer is finalized - * and cannot be restarted until actual thread stopping - */ - bool finalized_flag_; - - Lock& state_lock_ref_; - ConditionalVariable state_condition_; - - DISALLOW_COPY_AND_ASSIGN(TimerDelegate); - }; - - /** - * @brief Sets up timer delegate to start state. - * Not thread-safe - * @param timeout Timer timeout - */ - void StartDelegate(const Milliseconds timeout) const; - - /** - * @brief Sets up timer delegate to stop state. - * Not thread-safe - */ - void StopDelegate() const; - - /** - * @brief Starts timer thread. - * Not thread-safe - */ - void StartThread(); - - /** - * @brief Stops timer thread. - * Not thread-safe - */ - void StopThread(); - - /** - * @brief Callback called on timeout. - * Not thread-safe - */ - void OnTimeout() const; - - const std::string name_; - TimerTask* task_; - - mutable Lock state_lock_; - - mutable std::auto_ptr delegate_; - threads::Thread* thread_; - - /** - * @brief Single shot flag shows if timer should be fired once - */ - bool single_shot_; - - DISALLOW_COPY_AND_ASSIGN(Timer); -}; - -#endif // SRC_COMPONENTS_UTILS_INCLUDE_UTILS_TIMER_H_ diff --git a/timer_task.h b/timer_task.h deleted file mode 100755 index 76a5f27..0000000 --- a/timer_task.h +++ /dev/null @@ -1,17 +0,0 @@ - -#ifndef SRC_COMPONENTS_UTILS_INCLUDE_UTILS_TIMER_TASK_H_ -#define SRC_COMPONENTS_UTILS_INCLUDE_UTILS_TIMER_TASK_H_ - - -/** - * @brief The TimerTask interface - */ -class TimerTask { - public: - /** - * @brief this method calls callback from callee - */ - virtual void RunTimer() = 0; -}; - -#endif // SRC_COMPONENTS_UTILS_INCLUDE_UTILS_TIMER_TASK_H_ -- Gitee From eee5cff56af6b7950f17500ff065394e574ae8a0 Mon Sep 17 00:00:00 2001 From: myxuan475 Date: Tue, 29 Apr 2025 16:39:41 +0800 Subject: [PATCH 5/7] =?UTF-8?q?windows=E4=BF=AE=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: myxuan475 Change-Id: I9a75d1061c5a8e2ba9d0eeaa6226790a2818fc4b --- custom.cpp | 59 +++++++++++++++++++++++++++++++++++++++++++++++++++--- custom.h | 8 +++++++- lock.h | 52 +++++++++++++++++++++++------------------------ logger.cpp | 4 ++-- logger.h | 4 ++-- 5 files changed, 93 insertions(+), 34 deletions(-) diff --git a/custom.cpp b/custom.cpp index 5bda376..62c2ed0 100644 --- a/custom.cpp +++ b/custom.cpp @@ -6,11 +6,15 @@ ************************************************************************/ #include "custom.h" +#include "logger.h" #include +#include #include #include #include +#include #include +#include #include #include #include @@ -19,9 +23,6 @@ #include #include #include -#include -#include -#include "logger.h" #ifdef WIN32 #include #endif @@ -64,6 +65,15 @@ std::vector Split(const std::string &src, const std::string &patter return ret; } +bool Contain(const std::string &str, const std::string &sub, bool sense) +{ + std::string lowerStr = str; + if (sense == false) { + std::transform(lowerStr.begin(), lowerStr.end(), lowerStr.begin(), ::tolower); + } + return lowerStr.find(sub) != std::string::npos; +} + bool StartWith(const std::string &str, const std::string &substr) { return 0 == str.find(substr); @@ -747,4 +757,47 @@ std::vector strtohexcmd(const std::string &str) return result; } +std::string replace(std::string &src, const std::string &before, const std::string &after) +{ + for (size_t pos = 0; pos != std::string::npos; pos += after.length()) { + pos = src.find(before, pos); + if (pos != std::string::npos) { + src.replace(pos, before.length(), after); + } else { + break; + } + } + return src; +} + +std::string hexcmdtostr(const std::vector &cmd, const char sep) +{ + std::string result; + int i = 0; + for (std::vector::const_iterator iter = cmd.begin(); iter != cmd.end(); ++iter) { + result += digittochar(*iter); + if ((i++ % 2 == 0) && iter + 1 != cmd.end() && sep != '\0') { + result += sep; + } + } + if (i % 2 == 0) { + result += '0'; + } + return result; +} + +std::string hexcmdtohexstr(const std::vector &cmd) +{ + std::string result; + for (std::vector::const_iterator iter = cmd.begin(); iter != cmd.end(); ++iter) { + result += *iter; + } + return result; +} + +double round(double v, int32_t precision) +{ + return std::round(v * precision) / (1.0 * precision); +} + } // namespace utils diff --git a/custom.h b/custom.h index d724f10..513ceb5 100644 --- a/custom.h +++ b/custom.h @@ -19,13 +19,15 @@ namespace utils std::vector Split(const char *src, const char *delim); std::vector Split(const std::string &src, const std::string &pattern); bool StartWith(const std::string &str, const std::string &substr); - +bool Contain(const std::string &str, const std::string &sub, bool sense = true); std::string get_rand(int len); /* * 去除字符串右端空格 */ char *strtrimr(char *pstr); +std::string replace(std::string &src, const std::string &oldStr, const std::string &after); + /* * 去除字符串左端空格 */ @@ -56,6 +58,8 @@ std::string hexcmdtostr(const unsigned char *cmd, const char postfix = '\0', const char sep = ' '); std::vector strtohexcmd(const std::string &str); +std::string hexcmdtostr(const std::vector &cmd, const char sep = ' '); +std::string hexcmdtohexstr(const std::vector &cmd); /* * 字符串转成压缩bcd码 @@ -99,6 +103,8 @@ bool isCharactor(const char c); bool isHexDigit(const char *str); bool isDecimal(const char *str,bool &fl); bool isInteger(const char *str); +double round(double v, int32_t precision = 1); + std::string get_executable_directory(); bool existFile(const char *file); diff --git a/lock.h b/lock.h index f9451ab..3eb71cf 100644 --- a/lock.h +++ b/lock.h @@ -7,32 +7,32 @@ #include #include -class SpinMutex { - public: - SpinMutex() : state_(0) {} - void Lock() { - // Comment below add exception for lint error - // Reason: FlexeLint doesn't know about compiler's built-in instructions - /*lint -e1055*/ - if (atomic_post_set(&state_) == 0) { - return; - } - for (;;) { - sched_yield(); - /*lint -e1055*/ - if (state_ == 0 && atomic_post_set(&state_) == 0) { - return; - } - } - } - void Unlock() { - state_ = 0; - } - ~SpinMutex() {} - - private: - volatile unsigned int state_; -}; +// class SpinMutex { +// public: +// SpinMutex() : state_(0) {} +// void Lock() { +// // Comment below add exception for lint error +// // Reason: FlexeLint doesn't know about compiler's built-in instructions +// /*lint -e1055*/ +// if (atomic_post_set(&state_) == 0) { +// return; +// } +// for (;;) { +// sched_yield(); +// /*lint -e1055*/ +// if (state_ == 0 && atomic_post_set(&state_) == 0) { +// return; +// } +// } +// } +// void Unlock() { +// state_ = 0; +// } +// ~SpinMutex() {} + +// private: +// volatile unsigned int state_; +// }; class Lock { public: diff --git a/logger.cpp b/logger.cpp index d10ef14..9ef0354 100644 --- a/logger.cpp +++ b/logger.cpp @@ -128,10 +128,10 @@ void write_log(int32_t level, const std::string &file, int line, const std::stri return; } - char buf[256] = {0}; + char buf[512] = {0}; va_list args; va_start(args, format); - vsnprintf(buf, 255, format, args); + vsnprintf(buf, 511, format, args); va_end(args); FILE *fp = utils::openhandle(); if (fp) { diff --git a/logger.h b/logger.h index 1be4ddd..1baaf88 100644 --- a/logger.h +++ b/logger.h @@ -123,9 +123,9 @@ public: ~LogTrace() { if (status_) { - write_log(utils::LOG_INFO, file_, line_, function_, "%s OK", loginfo_.c_str()); + write_log(utils::LOG_INFO, file_, line_, function_, "%s成功", loginfo_.c_str()); } else { - write_log(utils::LOG_ERR, file_, line_, function_, "%s Failed", loginfo_.c_str()); + write_log(utils::LOG_ERR, file_, line_, function_, "%s失败", loginfo_.c_str()); } } -- Gitee From fa00d984a41198338ada6f851fe08b977eac8068 Mon Sep 17 00:00:00 2001 From: wlxuz Date: Tue, 10 Jun 2025 15:56:22 +0800 Subject: [PATCH 6/7] modify log to fmb Signed-off-by: wlxuz Change-Id: Ia8ce3ed7cbbb64c472192062a1acd2bbfc12706f --- CMakeLists.txt | 9 +++- custom.cpp | 92 ++++++++++++++++++++++---------- custom.h | 6 ++- lock_posix.cpp | 25 +++++---- logger.cpp | 69 ++++++++++++------------ logger.h | 139 +++++++++++++++++++++---------------------------- network.cpp | 2 + network.h | 2 + 8 files changed, 191 insertions(+), 153 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 18c633c..6f5d081 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -6,8 +6,15 @@ include_directories( ./ ../include) -add_library(${MODULE} SHARED ${DIRSRCS}) +add_library(${MODULE} ${DIRSRCS}) +if(CMAKE_SYSTEM_NAME STREQUAL "Windows") target_link_libraries(${MODULE} ws2_32 Iphlpapi Mprapi) +else() +target_link_libraries(${MODULE} pthread) +endif() +target_link_directories(${MODULE} PUBLIC ${FMTLIB_LIBS_DIR}) +target_link_libraries(${MODULE} fmt) +target_include_directories(${MODULE} PUBLIC ${FMTLIB_INCLUDE_DIR}) install(TARGETS ${MODULE} DESTINATION lib/ diff --git a/custom.cpp b/custom.cpp index 5bda376..65633e6 100644 --- a/custom.cpp +++ b/custom.cpp @@ -19,8 +19,11 @@ #include #include #include +#include #include +#if __cplusplus >= 201703L #include +#endif #include "logger.h" #ifdef WIN32 #include @@ -166,6 +169,20 @@ std::string trim(std::string &str) return (wsback <= wsfront ? std::string() : std::string(wsfront, wsback)); } +int check_number_type(const std::string &input) +{ + std::regex integerRegex(R"(^[-+]?\d+$)"); + std::regex floatRegex(R"(^[-+]?(\d*\.\d+|\d+\.?\d*)([eE][-+]?\d+)?$)"); + + if (std::regex_match(input, integerRegex)) { + return TYPE_NUM_INT; + } else if (std::regex_match(input, floatRegex)) { + return TYPE_NUM_FLOAT; + } else { + return TYPE_NUM_NONE; + } +} + int strtoint(const char *str, int len) { int result = 0; @@ -362,6 +379,27 @@ std::string hexcmdtostr(const unsigned char *cmd, const int byte, const char pos return result; } +std::string hexcmdtostr(const std::vector &cmd, const char sep) +{ + std::string result; + size_t total_len = cmd.size() * 2; + if (sep != '\0' && cmd.size() > 1) { + total_len += cmd.size() - 1; // 分隔符数量 + } + result.reserve(total_len); + + std::for_each(cmd.begin(), cmd.end(), [&](uint8_t c) { + if (!result.empty()) { + if (sep != '\0') { + result += sep; + } + } + result += digittochar((c & 0xf0) >> 4); + result += digittochar(c & 0x0f); + }); + return result; +} + /* * 字符串转成压缩bcd码 */ @@ -591,22 +629,19 @@ bool isInteger(const char *str) return false; } -std::string get_executable_directory() { - char buffer[120]; -#ifndef WIN32 - ssize_t len = readlink("/proc/self/exe", buffer, sizeof(buffer) - 1); - if (len == -1) { - perror("readlink"); - return ""; - } -#else - DWORD len = GetCurrentDirectory(120, buffer); - if (len == 0) { - HTELINK_LOG_ERR("GetCurrentDirectory failed, %d", GetLastError()); - return ""; - } -#endif - return std::string(dirname(buffer)); +std::string get_executable_name() +{ + char *path_end; + char dir[256] = {0}; + if (readlink("/proc/self/exe", dir, sizeof(dir)) <= 0) { + return ""; + } + path_end = strrchr(dir, '/'); + if (!path_end) { + return ""; + } + ++path_end; + return std::string(path_end); } bool existFile(const char *file) @@ -629,18 +664,19 @@ std::vector get_file_list(const std::string &fileDir) DIR *dir; struct dirent *file; if ((dir = opendir(fileDir.c_str())) == NULL) { - return filename; - } - - while ((file = readdir(dir)) != NULL) { - if (strcmp(file->d_name, ".") == 0 || strcmp(file->d_name, "..") == 0) /// current dir OR parrent dir - continue; - if (file->d_type != 8) /// file - continue; - filelist.push_back(file->d_name); - break; - } - closedir(dir); + return filelist; + } + + while ((file = readdir(dir)) != NULL) { + if (strcmp(file->d_name, ".") == 0 || + strcmp(file->d_name, "..") == 0) /// current dir OR parrent dir + continue; + if (file->d_type != 8) /// file + continue; + filelist.push_back(file->d_name); + break; + } + closedir(dir); #endif return filelist; } diff --git a/custom.h b/custom.h index d724f10..cefacc4 100644 --- a/custom.h +++ b/custom.h @@ -38,7 +38,8 @@ std::string <rim(std::string &str); std::string &rtrim(std::string &str); std::string trim(std::string &str); - +typedef enum { TYPE_NUM_NONE = 0, TYPE_NUM_INT, TYPE_NUM_FLOAT } TYPE_NUMBER; +int check_number_type(const std::string &input); int strtoint(const char *str,int len = -1); int strtohex(const char *str, int len = -1); char digittochar(unsigned char digit); @@ -55,6 +56,7 @@ std::string hexcmdtostr(const unsigned char *cmd, const int byte, const char postfix = '\0', const char sep = ' '); +std::string hexcmdtostr(const std::vector &cmd, const char sep = ' '); std::vector strtohexcmd(const std::string &str); /* @@ -99,7 +101,7 @@ bool isCharactor(const char c); bool isHexDigit(const char *str); bool isDecimal(const char *str,bool &fl); bool isInteger(const char *str); -std::string get_executable_directory(); +std::string get_executable_name(); bool existFile(const char *file); std::vector get_file_list(const std::string &fileDir); diff --git a/lock_posix.cpp b/lock_posix.cpp index 92aa22e..da4b733 100644 --- a/lock_posix.cpp +++ b/lock_posix.cpp @@ -27,25 +27,27 @@ Lock::~Lock() { #ifndef NDEBUG if (lock_taken_ > 0) { - HTELINK_LOG_ERR("Destroying non-released mutex %p", &mutex_); - } + HTELINK_LOG_ERR("Destroying non-released mutex %p", (void *)&mutex_); + } #endif int32_t status = pthread_mutex_destroy(&mutex_); if (status != 0) { - HTELINK_LOG_ERR("Failed to destroy mutex %p:%s", &mutex_, strerror(status)); - } + HTELINK_LOG_ERR( + "Failed to destroy mutex %p:%s", (void *)&mutex_, strerror(status)); + } } void Lock::Acquire() { const int32_t status = pthread_mutex_lock(&mutex_); if (status != 0) { - HTELINK_LOG_ERR("Failed to acquire mutex %p:%s", &mutex_, strerror(status)); - NOTREACHED(); - } else { - AssertFreeAndMarkTaken(); - } + HTELINK_LOG_ERR( + "Failed to acquire mutex %p:%s", (void *)&mutex_, strerror(status)); + NOTREACHED(); + } else { + AssertFreeAndMarkTaken(); + } } void Lock::Release() @@ -53,8 +55,9 @@ void Lock::Release() AssertTakenAndMarkFree(); const int32_t status = pthread_mutex_unlock(&mutex_); if (status != 0) { - HTELINK_LOG_ERR("Failed to unlock mutex %p :%s", &mutex_, strerror(status)); - } + HTELINK_LOG_ERR( + "Failed to unlock mutex %p :%s", (void *)&mutex_, strerror(status)); + } } bool Lock::Try() diff --git a/logger.cpp b/logger.cpp index d10ef14..ba3958d 100644 --- a/logger.cpp +++ b/logger.cpp @@ -16,11 +16,17 @@ const int32_t VENDOR_LOG_STORE_DAYS = 30; const std::string VENDOR_LOG_PATH = "./"; #endif +#include +#include +#include +#include +#include namespace utils { static bool g_enable = true; static int32_t g_level = 0; LogFunc g_logFunc = nullptr; +static std::mutex g_logMutex; void set_enable(bool enable) { @@ -47,12 +53,12 @@ const char *file_rchr(const char *file) return strrchr(file, '/') ? strrchr(file, '/') + 1 : file; } -std::string check_disk_log(const std::string &logdir) +std::string check_disk_log(const std::string &logdir, int32_t days) { #ifndef DONT_GLOBAL_VENDOR - if (utils::logFileCount(logdir) > VENDOR_LOG_STORE_DAYS) { + if (utils::logFileCount(logdir) > std::min(days, VENDOR_LOG_STORE_DAYS)) { #else - if (utils::logFileCount(logdir) > 30) { + if (utils::logFileCount(logdir) > std::min(days, 30)) { #endif std::string log; const std::string filename = utils::logFile(logdir.c_str()); @@ -77,15 +83,16 @@ FILE *openhandle() } } - if (!get_enable()) - return NULL; + if (!get_enable()) { + return NULL; + } - std::string path = VENDOR_LOG_PATH + "/" + utils::todaytostr() + "_" + - std::string(file_rchr(utils::get_executable_directory().c_str())) + ".log"; - // printf("path: %s\n", path.c_str()); + std::string path = VENDOR_LOG_PATH + "/" + utils::todaytostr() + "_" + + utils::get_executable_name() + ".log"; + // printf("path: %s\n", path.c_str()); - fp = fopen(path.c_str(), "a+"); - return fp; + fp = fopen(path.c_str(), "a+"); + return fp; } void closehandle(FILE *fp) @@ -122,35 +129,34 @@ std::string log_level_name(int32_t level) return "DEBUG"; } -void write_log(int32_t level, const std::string &file, int line, const std::string &func, const char *format, ...) +void write_log(int32_t level, const std::string &file, int line, + const std::string &func, const std::string &format) { if (level < get_level()) { return; } - char buf[256] = {0}; - va_list args; - va_start(args, format); - vsnprintf(buf, 255, format, args); - va_end(args); - FILE *fp = utils::openhandle(); - if (fp) { - fprintf(fp, "%s,%u,%u,%s,%d,%s [%s]:", utils::nowtostr().c_str(), getpid(), utils::gettid(), file.c_str(), line, - func.c_str(), log_level_name(level).c_str()); - fprintf(fp, "%s\n", buf); - utils::closehandle(fp); - } - if (g_logFunc) { - g_logFunc(level, file, line, func, buf); - } + do { + std::lock_guard lockLog(g_logMutex); + FILE *fp = utils::openhandle(); + if (fp) { + fmt::print(fp, "{},{},{},{},{},{} [{}]:{}\n", utils::nowtostr(), + getpid(), utils::gettid(), file, line, func, + log_level_name(level), format); + utils::closehandle(fp); + } + } while (0); + if (g_logFunc) { + g_logFunc(level, file, line, func, format); + } } -int gettid() +uint32_t gettid() { #ifdef WIN32 return GetCurrentThreadId(); #else - return getuid(); + return static_cast(pthread_self()); #endif } @@ -179,10 +185,9 @@ void register_logfunc(LogFunc logFunc) LogFunc logfunc() { - if (g_logFunc == nullptr) { - g_logFunc = write_log; - } - return g_logFunc; + if (g_logFunc == nullptr) { + } + return g_logFunc; } }; // namespace utils diff --git a/logger.h b/logger.h index 1be4ddd..5ea6b29 100644 --- a/logger.h +++ b/logger.h @@ -19,6 +19,9 @@ #include #include #include +#include +#include +#include namespace utils { void set_enable(bool enable); @@ -26,12 +29,12 @@ bool get_enable(); void set_level(int32_t level); int32_t get_level(); const char *file_rchr(const char *file); -void write_log(int32_t level, - const std::string &file, - int line, - const std::string &func, - const char *format, - ...); + +void write_log(int32_t level, const std::string &file, int line, + const std::string &func, const std::string &format); + +FILE *openhandle(); +void closehandle(FILE *fp); typedef enum { LOG_DEBUG = 0, LOG_INFO, LOG_WARNING, LOG_ERR, LOG_FIXME } LOG_LEVEL; @@ -41,46 +44,42 @@ typedef enum { LOG_DEBUG = 0, LOG_INFO, LOG_WARNING, LOG_ERR, LOG_FIXME } LOG_LE inline bool log_is_full(); -std::string check_disk_log(const std::string &logdir); +std::string check_disk_log(const std::string &logdir, int32_t days); + +template +std::string format_string(const char *format, const Args &...args) +{ + try { + return fmt::sprintf(format, std::forward(args)...); + } catch (const fmt::format_error &e) { + std::cerr << "Format error: " << e.what() << std::endl; + return std::string("log format error:") + e.what(); + } +} /* log func */ -using LogFunc - = std::function; +using LogFunc = std::function; LogFunc logfunc(); void register_logfunc(LogFunc logFunc); -int gettid(); - -#define HTELINK_LOG_INFO(format, ...) \ - write_log(utils::LOG_INFO, \ - __FILENAME__(__FILE__), \ - __LINE__, \ - __FUNCTION__, \ - format, \ - ##__VA_ARGS__) -#define HTELINK_LOG_ERR(format, ...) \ - write_log(utils::LOG_ERR, __FILENAME__(__FILE__), __LINE__, __FUNCTION__, format, ##__VA_ARGS__) -#define HTELINK_LOG_WARN(format, ...) \ - write_log(utils::LOG_WARNING, \ - __FILENAME__(__FILE__), \ - __LINE__, \ - __FUNCTION__, \ - format, \ - ##__VA_ARGS__) -#define HTELINK_LOG_DEBUG(format, ...) \ - write_log(utils::LOG_DEBUG, \ - __FILENAME__(__FILE__), \ - __LINE__, \ - __FUNCTION__, \ - format, \ - ##__VA_ARGS__) -#define HTELINK_LOG_FIXME(format, ...) \ - write_log(utils::LOG_FIXME, \ - __FILENAME__(__FILE__), \ - __LINE__, \ - __FUNCTION__, \ - format, \ - ##__VA_ARGS__) +uint32_t gettid(); + +#define HTELINK_LOG_INFO(format, ...) \ + write_log(utils::LOG_INFO, __FILENAME__(__FILE__), __LINE__, __FUNCTION__, \ + utils::format_string(format, ##__VA_ARGS__)) +#define HTELINK_LOG_ERR(format, ...) \ + write_log(utils::LOG_ERR, __FILENAME__(__FILE__), __LINE__, __FUNCTION__, \ + utils::format_string(format, ##__VA_ARGS__)) +#define HTELINK_LOG_WARN(format, ...) \ + write_log(utils::LOG_WARNING, __FILENAME__(__FILE__), __LINE__, \ + __FUNCTION__, utils::format_string(format, ##__VA_ARGS__)) +#define HTELINK_LOG_DEBUG(format, ...) \ + write_log(utils::LOG_DEBUG, __FILENAME__(__FILE__), __LINE__, \ + __FUNCTION__, utils::format_string(format, ##__VA_ARGS__)) +#define HTELINK_LOG_FIXME(format, ...) \ + write_log(utils::LOG_FIXME, __FILENAME__(__FILE__), __LINE__, \ + __FUNCTION__, utils::format_string(format, ##__VA_ARGS__)) #define HTELINK_LOG_CMD(desc, cmd, len) \ do { \ @@ -99,42 +98,28 @@ int gettid(); class LogTrace { public: - LogTrace(bool &status, - const std::string &file, - int line, - const std::string &function, - const char *format, - ...) - : loginfo_("") - , file_(file) - , line_(line) - , function_(function) - , status_(status) - { - char buf[256] = {0}; - va_list args; - va_start(args, format); - vsnprintf(buf, 255, format, args); - va_end(args); - loginfo_ = buf; - write_log(utils::LOG_INFO, file_, line_, function_, "%s ...", loginfo_.c_str()); - } - - ~LogTrace() - { - if (status_) { - write_log(utils::LOG_INFO, file_, line_, function_, "%s OK", loginfo_.c_str()); - } else { - write_log(utils::LOG_ERR, file_, line_, function_, "%s Failed", loginfo_.c_str()); - } - } + LogTrace(const std::string &file, int line, const std::string &function, + const std::string &format) + : loginfo_("") + , file_(file) + , line_(line) + , function_(function) + { + loginfo_ = format; + write_log( + utils::LOG_INFO, file_, line_, function_, loginfo_ + " Enter"); + } + + ~LogTrace() + { + write_log(utils::LOG_INFO, file_, line_, function_, loginfo_ + " Exit"); + } private: std::string loginfo_; std::string file_; std::string function_; - int line_; - bool &status_; + int line_; }; #define HTELINK_MODULE_TRACE(name) \ @@ -151,13 +136,9 @@ private: } \ } logInfo -#define HTELINK_TRACE(status, format, ...) \ - utils::LogTrace logTrace(status, \ - __FILENAME__(__FILE__), \ - __LINE__, \ - __FUNCTION__, \ - format, \ - ##__VA_ARGS__) +#define HTELINK_TRACE(format, ...) \ + utils::LogTrace logTrace(__FILENAME__(__FILE__), __LINE__, __FUNCTION__, \ + utils::format_string(format, ##__VA_ARGS__)) } // namespace utils #endif//__LOGGER_H__ diff --git a/network.cpp b/network.cpp index 5f52d19..9759ca8 100644 --- a/network.cpp +++ b/network.cpp @@ -8,6 +8,7 @@ #include namespace utils { +#if WIN32 sockaddr_in sockaddr_netmask2broadcast(const struct sockaddr *addr, const struct sockaddr *netmask) { sockaddr_in broadAddr; @@ -60,4 +61,5 @@ std::string ipaddr2string(const struct sockaddr *sa) inet_ntop(sa->sa_family, addr, ipstr, sizeof(ipstr)); return ipstr; } +#endif } // namespace utils diff --git a/network.h b/network.h index 6cd6312..926677e 100644 --- a/network.h +++ b/network.h @@ -12,9 +12,11 @@ #endif namespace utils { +#if WIN32 sockaddr_in sockaddr_netmask2broadcast(const sockaddr *addr, const sockaddr *netmask); std::string ipaddr2string(const struct sockaddr *sa); std::tuple netaddr2subnet(const std::string &ip, const std::string &mask); +#endif } // namespace utils #endif // UTILS_NETWORK_H -- Gitee From cb50d001c316e62e1b06481b17d079dc9cc470ef Mon Sep 17 00:00:00 2001 From: myxuan475 Date: Tue, 10 Jun 2025 15:56:58 +0800 Subject: [PATCH 7/7] log Signed-off-by: myxuan475 Change-Id: I414611ca633e9f3ac185952eb76b06cd6ceb2365 --- logger.cpp | 53 +++++++++++++++++++++++++++++++++-------------------- 1 file changed, 33 insertions(+), 20 deletions(-) diff --git a/logger.cpp b/logger.cpp index 9ef0354..264c9e1 100644 --- a/logger.cpp +++ b/logger.cpp @@ -80,8 +80,8 @@ FILE *openhandle() if (!get_enable()) return NULL; - std::string path = VENDOR_LOG_PATH + "/" + utils::todaytostr() + "_" + - std::string(file_rchr(utils::get_executable_directory().c_str())) + ".log"; + std::string path = VENDOR_LOG_PATH + "/" + utils::todaytostr() + "_" + + std::string(file_rchr(utils::get_executable_directory().c_str())) + ".log"; // printf("path: %s\n", path.c_str()); fp = fopen(path.c_str(), "a+"); @@ -104,39 +104,52 @@ void closehandle(FILE *fp) std::string log_level_name(int32_t level) { switch (level) { - case LOG_DEBUG: - return "DEBUG"; - case LOG_INFO: - return "INFO"; - case LOG_WARNING: - return "WARNNING"; - case LOG_ERR: - return "ERR"; - case LOG_FIXME: - return "FIXME"; - break; - - default: - break; + case LOG_DEBUG: + return "DEBUG"; + case LOG_INFO: + return "INFO"; + case LOG_WARNING: + return "WARNNING"; + case LOG_ERR: + return "ERR"; + case LOG_FIXME: + return "FIXME"; + break; + + default: + break; } return "DEBUG"; } -void write_log(int32_t level, const std::string &file, int line, const std::string &func, const char *format, ...) +void write_log(int32_t level, + const std::string &file, + int line, + const std::string &func, + const char *format, + ...) { if (level < get_level()) { return; } + return; - char buf[512] = {0}; + char buf[4096] = {0}; va_list args; va_start(args, format); vsnprintf(buf, 511, format, args); va_end(args); FILE *fp = utils::openhandle(); if (fp) { - fprintf(fp, "%s,%u,%u,%s,%d,%s [%s]:", utils::nowtostr().c_str(), getpid(), utils::gettid(), file.c_str(), line, - func.c_str(), log_level_name(level).c_str()); + fprintf(fp, + "%s,%u,%u,%s,%d,%s [%s]:", + utils::nowtostr().c_str(), + getpid(), + utils::gettid(), + file.c_str(), + line, + func.c_str(), + log_level_name(level).c_str()); fprintf(fp, "%s\n", buf); utils::closehandle(fp); } -- Gitee