#include #include #include "SH_global.h" #include "SH_CommonFunc.hpp" #include static boost::mutex s_config_mu; int CheckFileVersion(int argc, char** argv) { std::string strVersion = GlobalConfig::Version; int optionchar; /*选项字�??*/ if (argc >= 2) { if (strcmp(argv[1], "--debugmode") == 0){ GlobalConfig::RUN_MODE = 1; return 0; } optionchar = getopt(argc, argv, "vVhH?"); switch (optionchar) { case 'v': case 'V': GlobalConfig::RUN_MODE = 1; print_debug("Compile time:%s %s\n", __DATE__, __TIME__); print_debug("The internal version is:%s.\n", strVersion.c_str()); break; case 'h': case 'H': case '?': printf("Please input -v or -V to get the file version.\n"); break; default: break; } return 1; } return 0; } std::string GetCurrentTime() { struct tm nowtime; struct timeval tv; char time_now[128]; gettimeofday(&tv, NULL); localtime_r(&tv.tv_sec,&nowtime); sprintf(time_now,"%d-%d-%d %d:%d:%d.%03d ", nowtime.tm_year+1900, nowtime.tm_mon+1, nowtime.tm_mday, nowtime.tm_hour, nowtime.tm_min, nowtime.tm_sec, (int)(tv.tv_usec/1000) ); std::string strtime_now = std::string((char*)time_now); return strtime_now; } int system_custom(const char *cmd, char *buf) { FILE * fp; int res; char temp[1024] = {0}; if (cmd == NULL) { return -1; } if ((fp = popen(cmd, "r") ) == NULL) { print_error("popen error\n"); return -1; } else { buf[0] = '\0'; while (fgets(temp, sizeof(temp), fp)) { strcat(buf, temp); } res = pclose(fp); } char *p; int pos = 0; p = strstr(buf, "\n"); if(p != NULL){ pos = p - buf; buf[pos] = '\0'; } return res; } std::string GetDayDate() { time_t t = time(0); char tmp[64]; strftime(tmp, sizeof(tmp), "%Y-%m-%d",localtime(&t)); std::string data = std::string((char*)tmp); return data; } void GetTimeNet(char* timebuf,int type) { struct timeval tv; gettimeofday(&tv, NULL); int millisecond = tv.tv_usec / 1000; if(type == 0){ sprintf(timebuf, "%ld%03d", tv.tv_sec, millisecond); } else { sprintf(timebuf, "%ld", tv.tv_sec); } } void GetTime_(char time_buff[],TIME_SIZE len) { int i = sizeof(time_buff); memset(time_buff, 0, i); time_t timep; time(&timep); strcpy(time_buff, ctime(&timep)); std::string strtemp = time_buff; strtemp = strtemp.substr(11, len); memset(time_buff, 0, strlen(time_buff)); strcpy(time_buff, strtemp.c_str()); } std::string ReadStrByOpt(std::string filename, std::string config, std::string option) { boost::mutex::scoped_lock lock(s_config_mu); Json::Value root; Json::Reader reader; std::string value; std::fstream is; is.open(filename.c_str(), std::ios::in); if (reader.parse(is, root)) { value = root[config]["option"][option].asString(); } is.close(); return value; } std::vector ReadStrByOpt(std::string filename,std::string strUpdataFileName) { boost::mutex::scoped_lock lock(s_config_mu); Json::Value root,hwVersion; Json::Reader reader; std::vector value; std::fstream is; is.open(filename.c_str(), std::ios::in); if (reader.parse(is, root)) { hwVersion = root["hw_vesion"]; strUpdataFileName = root["fw_name"].asString(); } for(int i = 0; i < hwVersion.size();i++){ value.push_back(hwVersion[i].asString()); } is.close(); return value; } int WriteStr2Config(std::string filename, std::string config, std::string option, std::string value, bool listable) { boost::mutex::scoped_lock lock(s_config_mu); Json::Value root; Json::Value subroot; Json::Value list; Json::Value op; Json::Reader reader; std::fstream is; is.open(filename.c_str(), std::ios::in); if (reader.parse(is, root)) { subroot = root[config]; if (listable) list = root[config]["list"]; else op = root[config]["option"]; } is.close(); if (listable) { list[option].append(Json::Value(value)); subroot["list"] = list; } else { op[option] = Json::Value(value); subroot["option"] = op; } root[config] = subroot; Json::StyledWriter sw; std::ofstream os; os.open(filename.c_str()); os << sw.write(root); os.close(); return 0; } std::string GetLocalMac() { int sock_mac; struct ifreq ifr_mac; char mac_addr[30]; sock_mac = socket( AF_INET, SOCK_STREAM, 0 ); if( sock_mac == -1) { perror("create socket falise...mac/n"); return ""; } memset(&ifr_mac,0,sizeof(ifr_mac)); strncpy(ifr_mac.ifr_name, "eth0", sizeof(ifr_mac.ifr_name)-1); if( (ioctl( sock_mac, SIOCGIFHWADDR, &ifr_mac)) < 0) { printf("mac ioctl error/n"); return ""; } sprintf(mac_addr,"%02x%02x%02x%02x%02x%02x", (unsigned char)ifr_mac.ifr_hwaddr.sa_data[0], (unsigned char)ifr_mac.ifr_hwaddr.sa_data[1], (unsigned char)ifr_mac.ifr_hwaddr.sa_data[2], (unsigned char)ifr_mac.ifr_hwaddr.sa_data[3], (unsigned char)ifr_mac.ifr_hwaddr.sa_data[4], (unsigned char)ifr_mac.ifr_hwaddr.sa_data[5]); printf("local mac:%s /n",mac_addr); close( sock_mac ); return std::string( mac_addr ); } std::string GetGwIp_(const char *eth_name) { int sockfd; char gwip_[16] = {0}; if (-1 == (sockfd = socket(PF_INET, SOCK_STREAM, 0))) { perror_info("socket"); return ""; } struct ifreq req; struct sockaddr_in *host; bzero(&req, sizeof(struct ifreq)); strcpy(req.ifr_name, eth_name); print_info("eth_name = %s\n",eth_name); ioctl(sockfd, SIOCGIFADDR, &req); host = (struct sockaddr_in*) &req.ifr_addr; close(sockfd); if (host) { strcpy(gwip_, inet_ntoa(host->sin_addr)); } return std::string(gwip_); } std::string IpAddrInit() { const char *WLAN0 = "wlan0"; const char *ETH0 = "eth0"; std::string strip; strip = GetGwIp_(ETH0); if (strip.compare("0.0.0.0") == 0) { strip = GetGwIp_(WLAN0); } return strip; } std::string GetWorkNic() { const char *WLAN0 = "wlan0"; const char *ETH0 = "eth0"; std::string strip; strip = GetGwIp_(WLAN0); if (strip.compare("0.0.0.0") != 0) { return std::string(WLAN0); } strip = GetGwIp_(ETH0); if (strip.compare("0.0.0.0") != 0) { return std::string(ETH0); } return std::string(ETH0); } std::string& ClearAllSpace(std::string &str) { int index = 0; if( !str.empty()) { while( (index = str.find(' ',index)) != string::npos) { str.erase(index,1); } }return str; } std::string GetSysInfo() { const char * getCpuUse = "top -b -n 1 |grep Cpu | cut -d \",\" -f 1 | cut -d \":\" -f 2 |tr -d ' us'"; char chRes[100] = {0}; system_custom(getCpuUse, chRes); std::string CpuUse = std::string(chRes); const char * getCpuSys = "top -b -n 1 |grep Cpu | cut -d \",\" -f 2 |tr -d ' sy'"; memset(chRes, 0, 100); system_custom(getCpuSys, chRes); std::string CpuSys = std::string(chRes); const char * getMemtotal = "cat /proc/meminfo | grep MemTotal | awk -F"":"" '{print $2}' |tr -d ' kB'"; memset(chRes, 0, 100); system_custom(getMemtotal, chRes); std::string MemTotal = std::string(chRes); const char * getMemFree = "cat /proc/meminfo | grep MemFree | awk -F"":"" '{print $2}' |tr -d ' kB'"; memset(chRes, 0, 100); system_custom(getMemFree, chRes); std::string MemFree = std::string(chRes); float a = boost::lexical_cast(MemFree); float b = boost::lexical_cast(MemTotal); float c = (1 - a/b)*100; const char * getEmmcInfo = "df -h | grep /dev/root"; memset(chRes, 0, 100); system_custom(getEmmcInfo, chRes); std::string Emmcinfo = std::string(chRes); std::size_t found = Emmcinfo.find("%"); if (found != std::string::npos) { Emmcinfo = Emmcinfo.substr(found-3, 3); } Emmcinfo = ClearAllSpace(Emmcinfo); char sysinfo[128] = {0}; sprintf(sysinfo, "%-13s%-13s%-13s%-13s ", boost::lexical_cast(c).substr(0,4).c_str(), CpuSys.c_str(), CpuUse.c_str(), Emmcinfo.c_str()); return std::string(sysinfo); } void StartWriteToDat() { print_info("start writetoDat\n"); } float * ReSample(int WaveDataLength, int N, int *NewWaveDataLength, std::vector & WaveData) { if (N <= 0) return NULL; int NewLength = (int)WaveDataLength / N; float * _OutputData = new float[NewLength]; for(int i = 0; i < NewLength; i++) { _OutputData[i] = WaveData[i * N]; } *NewWaveDataLength = NewLength; return _OutputData; } int SetTime(unsigned long seconds, int milliseconds) { struct timeval tv; time_t timep = (time_t)seconds; tv.tv_sec = timep; tv.tv_usec = milliseconds*1000; return settimeofday(&tv, NULL); } void RemoveConfig() { char cmd[32] = { 0 }; sprintf(cmd, "rm /CIDW/config/*"); system(cmd); exit(0); } extern void ZoneConfig(std::string zoneid) { int a = 0; std::string zonelists[] = {"UTC+12","UTC+11","UTC+10","UTC+9","UTC+8","UTC+7","UTC+6","UTC+5","UTC+4","UTC+3","UTC+2","UTC+1","UTC+0","UTC-1","UTC-2","UTC-3","UTC-4","UTC-5","UTC-6","UTC-7","UTC-8","UTC-9","UTC-10","UTC-11"}; for (int i = 0;i < sizeof(zonelists);i++) { if (zoneid.compare(zonelists[i]) == 0) { a = i; cout << "a = " << a << endl; break; } } switch(a){ case 0:zoneid = "GMT-12";break; case 1:zoneid = "GMT-11";break; case 2:zoneid = "GMT-10";break; case 3:zoneid = "GMT-9";break; case 4:zoneid = "GMT-8";break; case 5:zoneid = "GMT-7";break; case 6:zoneid = "GMT-6";break; case 7:zoneid = "GMT-5";break; case 8:zoneid = "GMT-4";break; case 9:zoneid = "GMT-3";break; case 10:zoneid = "GMT-2";break; case 11:zoneid = "GMT-1";break; case 12:zoneid = "GMT-0";break; case 13:zoneid = "GMT+1";break; case 14:zoneid = "GMT+2";break; case 15:zoneid = "GMT+3";break; case 16:zoneid = "GMT+4";break; case 17:zoneid = "GMT+5";break; case 18:zoneid = "GMT+6";break; case 19:zoneid = "GMT+7";break; case 20:zoneid = "GMT+8";break; case 21:zoneid = "GMT+9";break; case 22:zoneid = "GMT+10";break; case 23:zoneid = "GMT+11";break; } char cmd[256] = { 0 }; // sprintf(cmd, "rm /etc/localtime"); // system(cmd); memset(cmd, 0, 256); sprintf(cmd, "sudo ln -sf /usr/share/zoneinfo/Etc/%s /etc/localtime", zoneid.c_str()); system(cmd); print_info("change timezone success!\n"); } std::string GetFileContent(std::string filename, int line) { std::string strFileContent(""); std::ifstream ifileOut(filename.c_str()); if(ifileOut.is_open()) { //文件打开 int i = 1; while (!ifileOut.eof()) { if (line == 0) { std::string strTemp(""); getline(ifileOut, strTemp); strFileContent += strTemp; strFileContent += "\r\n"; } if (line != 0) { std::string strTemp(""); getline(ifileOut, strTemp); if (line == i) { strFileContent = strTemp; break; } } ++i; } ifileOut.close(); } return strFileContent; } //BOOST用正则表达式验证ip地址合法 bool CheckIP(const char *ip) { using namespace boost::xpressive; /* 定义正则表达式 */ cregex reg_ip = cregex::compile("(25[0-5]|2[0-5][0-9]|1[0-9][0-9]|[1-9][0-9]|[1-9])[.](25[0-5]|2[0-5][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])[.](25[0-5]|2[0-5][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])[.](25[0-5]|2[0-5][0-9]|1[0-9][0-9]|[1-9][0-9]|[1-9])"); return regex_match(ip, reg_ip); } bool IsValidMask(std::string mask) { int iRet = -1; // 将IP地址由“点分十进制”转换成 “二进制整数” struct in_addr s; iRet = inet_pton(AF_INET, mask.c_str(), &s); // 转换成功返回1,说明是有效的IP地址 if (iRet == 1) { // 从网络字节顺序转换为主机字节顺序 unsigned int addr = ntohl(s.s_addr); // 转换为二进制字符串 std::bitset<32> b((int)addr); std::string strMask = b.to_string(); // 查找二进制字符串中的"01",如果不存在,说明是有效的子网掩码 return (strMask.find("01") == std::string::npos); } return false; } // int StatusPub() // { // long mem_used = -1; // long mem_free = -1; // long mem_total = -1; // long mem_cached = -1; // char name1[20]; // std::string strMemTotal = GetFileContent("/proc/meminfo", 1); // std::string strMemFree = GetFileContent("/proc/meminfo", 2); // std::string strMemCache = GetFileContent("/proc/meminfo", 5); // sscanf(strMemTotal.c_str(),"%s%ld",name1,&mem_total); // sscanf(strMemFree.c_str(),"%s%ld",name1,&mem_free); // sscanf(strMemCache.c_str(),"%s%ld",name1,&mem_cached); // mem_used = mem_total - mem_free; // float fMemRate = 1.0 * mem_used / mem_total; // float fCpuRate; // char name[8]; // double cpu_idle = -1; // double cpu_sys = -1; // double cpu_user = -1; // double cpu_total = -1; // double cpu_wait = -1; // long int user,nice,sys,idle,iowait,irq,softirq; // std::string strCpu1 = GetFileContent("/proc/stat", 1); // sscanf(strCpu1.c_str(),"%s%ld%ld%ld%ld%ld%ld%d",name,&user,&nice,&sys,&idle,&iowait,&irq,&softirq); // boost::this_thread::sleep(boost::posix_time::seconds(2)); // long int userNext,niceNext,sysNext,idleNext,iowaitNext,irqNext,softirqNext; // std::string strCpu2 = GetFileContent("/proc/stat", 1); // sscanf(strCpu2.c_str(),"%s%ld%ld%ld%ld%ld%ld%d",name,&userNext,&niceNext,&sysNext,&idleNext,&iowaitNext,&irqNext,&softirqNext); // cpu_total = (userNext+niceNext+sysNext+idleNext+iowaitNext+irqNext+softirqNext) - (user+nice+sys+idle+iowait+irq+softirq); // cpu_user = userNext - user; // cpu_sys = sysNext - sys; // cpu_wait = iowaitNext - iowait; // cpu_idle = idleNext - idle; // fCpuRate = 1.0*(cpu_total - cpu_idle) / cpu_total; // float rateUser = cpu_user *100.0/cpu_total; // float rateSys = cpu_sys * 100.0/cpu_total; // if (rateUser > 95) { // rateUser = 92; // } // /*获取温度 */ // std::string tempRaw = GetFileContent(TEMPER_RAW, 1); // std::string temperOffset = GetFileContent(TEMPER_OFFSET, 1); // std::string temperScale = GetFileContent(TEMPER_SCALE, 1); // float temperature = ((boost::lexical_cast(tempRaw) + boost::lexical_cast(temperOffset)) * boost::lexical_cast(temperScale))/1000; // char hardName[32]; // char hardTotal[32]; // char hardUse[32]; // char hardFree[32]; // char rateHardUse[32]; // const char * getEmmcInfo = "df -h | grep /dev/root"; // char chRes[100]; // memset(chRes, 0, 100); // system_custom(getEmmcInfo, chRes); // sscanf(chRes,"%s%s%s%s%s",hardName, hardTotal, hardUse, hardFree, rateHardUse); // std::string strhardTotal(hardTotal); // std::string strhardFree(hardFree); // std::string strrateHardUse(rateHardUse); // Json::Value jsData; // Json::FastWriter fw; // jsData["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G; // jsData["cpuUserUse"] = rateUser; // jsData["memoryTotal"] = (int)mem_total; // jsData["memoryFree"] = (int)mem_free; // jsData["memoryUse"] = fMemRate * 100; // jsData["hardDiskTotal"] = boost::lexical_cast(strhardTotal.substr(0,strhardTotal.length() - 1)); // jsData["hardDiskFree"] = boost::lexical_cast(strhardFree.substr(0,strhardFree.length() - 1)); // double total = boost::lexical_cast(strhardTotal.substr(0,strhardTotal.length() - 1)); // double free = boost::lexical_cast(strhardFree.substr(0,strhardFree.length() - 1)); // double use = ((total - free) / free) * 100; // // jsData["hardDiskUse"] = boost::lexical_cast(strrateHardUse.substr(0,strrateHardUse.length() - 1)); // jsData["hardDiskUse"] = use; // jsData["cpuSystemUse"] = rateSys; // jsData["temperature"] = temperature; // char localtimestamp[32] = { 0 }; // GetTimeNet(localtimestamp, 1); // std::string nowTimetamp = std::string(localtimestamp); // jsData["updateTime"] = nowTimetamp; // std::string strJson = fw.write(jsData); // data_publish(strJson.c_str(), GlobalConfig::Topic_G.mPubStatus.c_str()); // std::string strInfo = "mem:"+boost::lexical_cast(fMemRate * 100) + "tem:"+boost::lexical_cast(temperature); // return 0; // } std::string GetSysStatus() { long mem_used = -1; long mem_free = -1; long mem_total = -1; long mem_cached = -1; char name1[20]; std::string strMemTotal = GetFileContent("/proc/meminfo", 1); std::string strMemFree = GetFileContent("/proc/meminfo", 2); std::string strMemCache = GetFileContent("/proc/meminfo", 5); sscanf(strMemTotal.c_str(),"%s%ld",name1,&mem_total); sscanf(strMemFree.c_str(),"%s%ld",name1,&mem_free); sscanf(strMemCache.c_str(),"%s%ld",name1,&mem_cached); mem_used = mem_total - mem_free; float fMemRate = 1.0 * mem_used / mem_total; float fCpuRate; char name[8]; double cpu_idle = -1; double cpu_sys = -1; double cpu_user = -1; double cpu_total = -1; double cpu_wait = -1; long int user,nice,sys,idle,iowait,irq,softirq; std::string strCpu1 = GetFileContent("/proc/stat", 1); sscanf(strCpu1.c_str(),"%s%ld%ld%ld%ld%ld%ld%d",name,&user,&nice,&sys,&idle,&iowait,&irq,&softirq); sleep(1); long int userNext,niceNext,sysNext,idleNext,iowaitNext,irqNext,softirqNext; std::string strCpu2 = GetFileContent("/proc/stat", 1); sscanf(strCpu2.c_str(),"%s%ld%ld%ld%ld%ld%ld%d",name,&userNext,&niceNext,&sysNext,&idleNext,&iowaitNext,&irqNext,&softirqNext); cpu_total = (userNext+niceNext+sysNext+idleNext+iowaitNext+irqNext+softirqNext) - (user+nice+sys+idle+iowait+irq+softirq); cpu_user = userNext - user; cpu_sys = sysNext - sys; cpu_wait = iowaitNext - iowait; cpu_idle = idleNext - idle; fCpuRate = 1.0*(cpu_total - cpu_idle) / cpu_total; float rateUser = cpu_user *100.0/cpu_total; float rateSys = cpu_sys * 100.0/cpu_total; if (rateUser > 95) { rateUser = 92; } char hardName[32]; char hardTotal[32]; char hardUse[32]; char hardFree[32]; char rateHardUse[32]; const char * getEmmcInfo = "df -h | grep /opt"; char chRes[100]; memset(chRes, 0, 100); system_custom(getEmmcInfo, chRes); sscanf(chRes,"%s%s%s%s%s",hardName, hardTotal, hardUse, hardFree, rateHardUse); std::string strhardTotal(hardTotal); std::string strhardFree(hardFree); std::string strrateHardUse(rateHardUse); Json::Value jsData; Json::FastWriter fw; jsData["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G; jsData["cpuUserUse"] = rateUser; jsData["memoryTotal"] = (int)mem_total; jsData["memoryFree"] = (int)mem_free; jsData["memoryUse"] = fMemRate * 100; jsData["hardDiskTotal"] = boost::lexical_cast(strhardTotal.substr(0,strhardTotal.length() - 1)); jsData["hardDiskFree"] = boost::lexical_cast(strhardFree.substr(0,strhardFree.length() - 1)); double total = boost::lexical_cast(strhardTotal.substr(0,strhardTotal.length() - 1)); double free = boost::lexical_cast(strhardFree.substr(0,strhardFree.length() - 1)); double use = ((total - free) / total) * 100; // jsData["hardDiskUse"] = boost::lexical_cast(strrateHardUse.substr(0,strrateHardUse.length() - 1)); jsData["hardDiskUse"] = use; jsData["cpuSystemUse"] = rateSys; char localtimestamp[32] = { 0 }; GetTimeNet(localtimestamp, 1); std::string nowTimetamp = std::string(localtimestamp); jsData["updateTime"] = nowTimetamp; std::string strJson = fw.write(jsData); return strJson; } void swap(char *data) { int tmp; tmp = data[1]; data[1] = data[0]; data[0] = tmp; } static const char* JSON_FIELD_CMD = "cmd";//协议: 命令字段 static const char* JSON_FIELD_NAME = "dataWatchName";//协议: 终端名称 static const char* JSON_FIELD_dataNodeGatewayNo = "dataNodeGatewayNo"; static const char* JSON_FIELD_ASSETID = "dataWatchAssetId";//协议: 资产编号 字段 static const char* JSON_FIELD_ADDEDBY = "dataWatchAddedBy";//协议: 添加人 字段 static const char* JSON_FIELD_DEVICETYPE = "deviceType"; static const char* JSON_FIELD_ADDEDDATE = "dataWatchAddedDate"; static const char* JSON_FIELD_IPADDRESS = "dataWatchIpAddress"; static const char* JSON_FIELD_SN = "serialNumber"; static const char* JSON_FIELD_VERSION = "softVersion"; static const char* JSON_FIELD_TIMEZONE = "timezone";