diff --git a/CMakeLists.txt b/CMakeLists.txt old mode 100755 new mode 100644 index 7c5659619a3b49cb7ba805df2ff9b459dd5f73d4..6f5d0817805e820155245e0c534c386709a35e81 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,17 +1,21 @@ 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) +if(CMAKE_SYSTEM_NAME STREQUAL "Windows") +target_link_libraries(${MODULE} ws2_32 Iphlpapi Mprapi) +else() +target_link_libraries(${MODULE} pthread) 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_directories(${MODULE} PUBLIC ${FMTLIB_LIBS_DIR}) +target_link_libraries(${MODULE} fmt) +target_include_directories(${MODULE} PUBLIC ${FMTLIB_INCLUDE_DIR}) + +install(TARGETS ${MODULE} + DESTINATION lib/ + 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/bytes.h b/bytes.h new file mode 100644 index 0000000000000000000000000000000000000000..b0358528a4396aad43c472d2595b39def47a3e4e --- /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/conditional_variable.h b/conditional_variable.h old mode 100755 new mode 100644 index c12b0a62f5b24cc737ef493a66ece5843e6a952c..04c3bad320ab58289820365ee7e042e739e303fb --- a/conditional_variable.h +++ b/conditional_variable.h @@ -3,7 +3,7 @@ #include #include -#include +#include "macro.h" class AutoLock; class Lock; @@ -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 old mode 100755 new mode 100644 index c16d503a318bf0d3996c84f0f070086886cbb0b2..facd59b47ce2e7d0de40a40e73a0272ca655b0e1 --- 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 2eaa92299c2969db45ee398a6603e762ec65a476..0000000000000000000000000000000000000000 --- 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 old mode 100755 new mode 100644 index 765f9c9ada450ce87577c7c47d3b6e2178ff3928..d81608707c5a5cc5ac032088fcabc3a42321e18d --- a/custom.cpp +++ b/custom.cpp @@ -1,70 +1,101 @@ /************************************************************************* - > 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 "logger.h" #include +#include #include -#include -#include -#include #include +#include +#include +#include +#include +#include +#include +#include +#include #include #include -#include "custom.h" +#include +#include +#include +#include +#if __cplusplus >= 201703L +#include +#endif +#include "logger.h" +#ifdef WIN32 +#include +#endif 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 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); } +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 +104,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 +116,246 @@ 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(ch)) || ch == '\n' || + ch == '\n'; } -string& ltrim(string &str) { -// string::iterator p = find_if(str.begin(), str.end(),illegalchar());// not1(ptr_fun(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) { - ltrim(rtrim(str)); - return str; +std::string trim(std::string &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 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 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); - - if (str[ilen-1] == 'B' || str[ilen-1] == 'b') { + 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; - 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,48 +364,67 @@ 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, const char sep) +{ + 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; + if (sep != '\0') { + result += sep; + } } } 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码 */ -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 +435,153 @@ 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码 + *函数 : 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 !(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 +590,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 +612,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,148 +634,209 @@ 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)); -} - -string logFileNotoday(const char *path) +std::string get_executable_name() { - DIR *dir; - struct dirent *file; - string filename; - string today = utils::todaytostr(); - - 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; - if (utils::StartWith(file->d_name,today)) - continue; - filename = file->d_name; - break; - } - closedir(dir); - return filename; + 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) +{ + // FILE* fp = fopen(file,"r"); + int acs = access(file, F_OK); + return acs == 0; } -string logFile(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; - string filename; - 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); - if (filelist.size()>0) { - sort(filelist.begin(),filelist.end(),less()); + if ((dir = opendir(fileDir.c_str())) == NULL) { + 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; +} + +std::string logFile(const std::string &path) +{ + std::string filename; + std::vector filelist = get_file_list(path); + if (filelist.size() > 0) { + sort(filelist.begin(), filelist.end(), std::less()); filename = filelist.at(0); } return filename; } -time_t strtotime(const string &str) +int32_t logFileCount(const std::string &path) { - 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::vector filelist = get_file_list(path); + return filelist.size(); } -string todaytostr() +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_; // 返回值。 +} + +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; - } - - return string(szTime); -} - -string nowtostr() + 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 std::string(szTime); +} + +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; +} + +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 old mode 100755 new mode 100644 index 4e96a886960c15cb0d63802628f8fbda90169761..72fac1f2e13128612e58374fead912f0c7c0a0d4 --- a/custom.h +++ b/custom.h @@ -1,29 +1,33 @@ /************************************************************************* - > 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 +#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); +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); + /* * 去除字符串左端空格 */ @@ -31,12 +35,13 @@ char *strtriml(char *pstr); char *strtrim(char *pstr); -string& ltrim(string &str); - -string& rtrim(string &str); +std::string <rim(std::string &str); -string& trim(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); @@ -49,7 +54,14 @@ 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', + const char sep = ' '); +std::string hexcmdtostr(const std::vector &cmd, 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码 @@ -80,12 +92,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 +105,20 @@ 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_name(); +double round(double v, int32_t precision = 1); +std::string get_executable_directory(); bool existFile(const char *file); -string logFileNotoday(const char *path); -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); -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 7a435199d2535e724dc5159aee1f1277987e655e..0000000000000000000000000000000000000000 --- 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 54ba12336dbfc074b1e6b17708ba68833b69088e..0000000000000000000000000000000000000000 --- 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/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 index b9baae0537e15947866d7ec3add459371e0c8643..329d9969f8a5bcce3a7514bd53e9933e33513490 --- 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/dfile.h b/dfile.h old mode 100755 new mode 100644 diff --git a/fixlist.cpp b/fixlist.cpp deleted file mode 100755 index 1094c6f1dfe177424df6d707ac70a6f62cd8ccd8..0000000000000000000000000000000000000000 --- a/fixlist.cpp +++ /dev/null @@ -1,266 +0,0 @@ -#include "fixlist.h" -#include "stdio.h" -#include "dfile.h" -#include -#include -#include - -#define DATA_SHIFT sizeof(U64) - -template -FixList::FixList(S32 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() -{ - U16 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) -{ - U64 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(S32 id): - file_cs(true) -{ - int len = 30+strlen(getenv(CONFIG_DIR_ENV)); - filename = (char*)malloc(len); - memset(filename,0,len); - sprintf(filename,"%s/data/LIST%04d.data",getenv(CONFIG_DIR_ENV),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 -U64 FixList::FileData::readLength() -{ - AutoLock autolock(file_cs); - U64 length = 0; - utils::load_file(filename,0,(char*)&length,DATA_SHIFT); - return length; -} - -template -void FixList::FileData::writeLength(U64 length) -{ - AutoLock autolock(file_cs); - utils::save_file(filename,0,(char*)&length,DATA_SHIFT); -} - -template -T FixList::FileData::readLast() -{ - AutoLock autolock(file_cs); - U64 length = readLength(); - return readAt(length-1); -} - -template -T FixList::FileData::readAt(U64 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(U64 index,const T& d) -{ - AutoLock autolock(file_cs); - U64 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); - U64 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); - U64 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(U64 index) -{ - AutoLock autolock(file_cs); - U64 length = readLength(); - - if (index>=length) - return; - U64 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); - U64 length = readLength(); - return length == 0; -} diff --git a/fixlist.h b/fixlist.h deleted file mode 100755 index 80467942453123aed65e9e6cd434775c73fe3380..0000000000000000000000000000000000000000 --- a/fixlist.h +++ /dev/null @@ -1,88 +0,0 @@ -#ifndef __FIXLIST_H__ -#define __FIXLIST_H__ - -#include -#include -#include -#include -#include -#include "lock.h" - -//-------------------------------------------------------------------------------------------------- -//使用相当于QList的用法,只是内部处理不同,完全可以当QList来用 -//--------------------------------------------------------------------------------------------------- - -//泛型类 -template -class FixList -{ -public: - //len:动态数组长度,当超过len时会自动保存到文件中,动态数组中始终 - //存放的是最后一波数据 - //max:总长度,超过部分将删除,若max==-1,则表示无限长 - - FixList(S32 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(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(); - 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 index 58c22f0bca2ad1f1b2966c8883628836e709cca0..3eb71cf326d73940ec6f2d7006fbfe6c1588b9c0 --- a/lock.h +++ b/lock.h @@ -1,38 +1,38 @@ #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: - 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: @@ -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 old mode 100755 new mode 100644 index a1afaa377117ea0c9b051170242959b81aedd457..da4b733814a9e71b031e66fd488f7ff7b55824bd --- a/lock_posix.cpp +++ b/lock_posix.cpp @@ -1,108 +1,109 @@ #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", (void *)&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", (void *)&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", (void *)&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", (void *)&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 old mode 100755 new mode 100644 index 0dc7af8e5bf21e89b38b45a588d6193a43608090..e79492315fe6fdc033e9171b63aff504745e2a70 --- a/logger.cpp +++ b/logger.cpp @@ -1,12 +1,32 @@ -/************************************************************************* - * > 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 +#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 +#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) { @@ -17,3 +37,161 @@ 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, int32_t days) +{ +#ifndef DONT_GLOBAL_VENDOR + if (utils::logFileCount(logdir) > std::min(days, VENDOR_LOG_STORE_DAYS)) { +#else + if (utils::logFileCount(logdir) > std::min(days, 30)) { +#endif + std::string log; + const std::string filename = utils::logFile(logdir.c_str()); + if (filename.empty()) + return ""; + log = logdir + "/" + filename; + // printf("remove file: %s\n", log.c_str()); + 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; + } + + std::string path = VENDOR_LOG_PATH + "/" + utils::todaytostr() + "_" + + utils::get_executable_name() + ".log"; + // printf("path: %s\n", path.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()); + + fp = fopen(path.c_str(), "a+"); + return fp; +} + +void closehandle(FILE *fp) +{ + if (getenv("LOG")) { + if (!strcmp(getenv("LOG"), "stdout")) { + return; + } + } + if (fp) { + fflush(fp); + fclose(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 std::string &format) +{ + if (level < get_level()) { + return; + } + return; + + 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); + } +} + +uint32_t gettid() +{ +#ifdef WIN32 + return GetCurrentThreadId(); +#else + return static_cast(pthread_self()); +#endif +} + +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; + + // // printf("total: %f, free: %f, %f%%\n", ftotal, ffree, 100 * ffree / + // ftotal); + + // if ((100 * ffree / ftotal) < 15) + // return true; + + // return false; + return false; +} + +void register_logfunc(LogFunc logFunc) +{ + g_logFunc = logFunc; +} + +LogFunc logfunc() +{ + if (g_logFunc == nullptr) { + } + return g_logFunc; +} + +}; // namespace utils diff --git a/logger.h b/logger.h old mode 100755 new mode 100644 index e3a540fe5fb2cb9eccc9dbf241ccfec6ab68bfe6..5ea6b29103750edcf61ca2f1c6ca126fb6de4fc2 --- a/logger.h +++ b/logger.h @@ -1,224 +1,144 @@ -/************************************************************************* - * > 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 #include #include -#include #include -#include -#include +#include +// #include +#include +#include +#include #include #include -#include -#include - +#include +#include +#include +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); -#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; -} +void write_log(int32_t level, const std::string &file, int line, + const std::string &func, const std::string &format); -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; -} +FILE *openhandle(); +void closehandle(FILE *fp); -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; +typedef enum { LOG_DEBUG = 0, LOG_INFO, LOG_WARNING, LOG_ERR, LOG_FIXME } LOG_LEVEL; - char path[MAX_NAME_LEN]; - char exename[MAX_NAME_LEN] = {0}; - get_current_exename(exename); +#define HTELINK_LOG_ENABLE(enable) utils::set_enable(enable) - sprintf(path,"%s/log/%s-%s.log", - getenv(CONFIG_DIR_ENV), - utils::todaytostr().c_str(), - exename[0]?exename:"leo-das"); +#define __FILENAME__(x) utils::file_rchr(x) - /* 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); +inline bool log_is_full(); - fp = fopen(path,"a+"); - return fp; -} +std::string check_disk_log(const std::string &logdir, int32_t days); -inline static void closehandle(FILE *fp) { - if (getenv("LOG")) { - if (!strcmp(getenv("LOG"),"stdout")) { - return; - } - } - if (fp) { - fflush(fp); - fclose(fp); - } +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(); + } } -#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 -{ +/* log func */ +using LogFunc = std::function; +LogFunc logfunc(); +void register_logfunc(LogFunc logFunc); + +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 { \ + 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 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"); + } - 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); - - FILE *fp = openhandle(); - if (fp) { - fprintf(fp,"[TRACE] %s Enter\n",loginfo); - closehandle(fp); - } - - } - - LogTrace(const char *_module){ - int funlen = strlen(_module); - - loginfo = (char*)malloc(funlen+1); - strcpy(loginfo,_module); - FILE *fp = openhandle(); - if (fp) { - fprintf(fp,"[TRACE] %s Enter\n",loginfo); - closehandle(fp); - } - } - - ~LogTrace(){ - FILE *fp = openhandle(); - if (fp) { - fprintf(fp,"[TRACE] %s Exit\n",loginfo); - closehandle(fp); - } - free(loginfo); - } private: - char *loginfo; + std::string loginfo_; + std::string file_; + std::string function_; + int line_; }; -#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_MODULE_TRACE(name) \ + class LogInfo { \ + public: \ + LogTrace *logTrace; \ + LogInfo() \ + { \ + logTrace = new LogTrace(#name); \ + } \ + ~LogInfo() \ + { \ + delete logTrace; \ + } \ + } logInfo + +#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/macro.h b/macro.h new file mode 100644 index 0000000000000000000000000000000000000000..b1c74e05db2f63b386b6d5d88c7d8d170f305c63 --- /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 +#include "logger.h" + +// 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)) { \ + HTELINK_LOG_ERR("Failed condition \"" #condition "\"\n\n"); \ + } \ + 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/network.cpp b/network.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9759ca817facaa33500c0dffc1a653407812eb1c --- /dev/null +++ b/network.cpp @@ -0,0 +1,65 @@ +#include "network.h" +#include +#ifdef WIN32 +#include +#include +#endif +#include "logger.h" +#include + +namespace utils { +#if WIN32 +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; +} +#endif +} // namespace utils diff --git a/network.h b/network.h new file mode 100644 index 0000000000000000000000000000000000000000..926677ef5eb5dc430abadd7c71516eca950154c2 --- /dev/null +++ b/network.h @@ -0,0 +1,22 @@ +#ifndef UTILS_NETWORK_H +#define UTILS_NETWORK_H +#include +#include +#include +#include +#include +#include +#include +#if WIN32 +#include +#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 diff --git a/shared_ptr.cpp b/shared_ptr.cpp deleted file mode 100755 index 9271407891271d2f8ada061eac454cbf8e1e22bf..0000000000000000000000000000000000000000 --- 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 829214341124240064e30f5a97998955a25fd515..0000000000000000000000000000000000000000 --- 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 -#include "atomic.h" -#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 index dbee6056e0668e9bde7da48f1770fa87848de8f3..f0b581b35c6caf82c1a7202019c83c1b170f1f68 --- 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 old mode 100755 new mode 100644 index d7a467d6e4b81e982bc97def31c58085ccb740ab..dd60f4f1212ec196853e27ec014f6f40b5278840 --- a/shellcmd.h +++ b/shellcmd.h @@ -1,12 +1,12 @@ /************************************************************************* - > 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 +#include typedef bool (*shell_runcallback)(const char *line,void *data); @@ -15,9 +15,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 c79a99f584fcd582d52c8a31ebb68464959b91b4..0000000000000000000000000000000000000000 --- 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 022d432a1bfaa9be9087a78828845b333cc4a087..0000000000000000000000000000000000000000 --- 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 fb9452f092ced09be6cd89b2393e17eefa67ee11..0000000000000000000000000000000000000000 --- 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 ae6cb349130cc2047b5db96e17f7c86a1e5b6d23..0000000000000000000000000000000000000000 --- 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 90caf48d3a64de1cb4f6a3911ed89aa051dd1521..0000000000000000000000000000000000000000 --- 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 778cb3c8e6179ecc5c4dd9e86952640bee438df1..0000000000000000000000000000000000000000 --- 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 deleted file mode 100755 index 5f9f3e61f5847327f67a6900c5347cf61fdde19b..0000000000000000000000000000000000000000 --- 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 "macro.h" -#include "thread_delegate.h" -#include "thread_options.h" -#include "utils/conditional_variable.h" -#include "utils/lock.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 d0135bd67c0fd1975ea9ae23c25809b82fdae845..0000000000000000000000000000000000000000 --- 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()) { - LOG_ERR("pthread exit"); - pthread_exit(NULL); - } else { - 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 5b433c530b796c785ddf18a5a532609f8d7e27eb..0000000000000000000000000000000000000000 --- 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 "utils/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 2f5c90ae44235047af78aff5c7c8c14c57da0f16..0000000000000000000000000000000000000000 --- 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 421c5442c9a34dea8527460765bd8dde5db1cd03..0000000000000000000000000000000000000000 --- a/threads/thread_posix.cc +++ /dev/null @@ -1,280 +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) { - 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_) { - 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; - } - - thread_options_ = 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)); - } - - 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); - } - } - - 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) { - 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 { - 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); - 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()); -#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 6d97bcda2b85a32c0291f9d6b7332269f9e662dc..0000000000000000000000000000000000000000 --- 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_); - 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(); - LOG_DEBUG("Timer %s has been startd",name_.c_str()); -} - -void Timer::Stop() { - AutoLock auto_lock(state_lock_); - StopThread(); - StopDelegate(); - single_shot_ = true; - 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 { - 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 ca9d884cf7a7d2044ce5a8c3fac660bc37fbe9e3..0000000000000000000000000000000000000000 --- 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 76a5f2758c036b986b17aac26ebd46f0319ea10d..0000000000000000000000000000000000000000 --- 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_