From 9a6cfe282301771da29ca9d0e79531f2a6198392 Mon Sep 17 00:00:00 2001 From: zhangsheng Date: Thu, 23 Jan 2025 20:07:10 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E7=AE=A1=E7=90=86=E8=BD=AF?= =?UTF-8?q?=E4=BB=B6=E9=83=A8=E5=88=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- common/common_func.cpp | 51 ++++ common/common_func.hpp | 2 +- jsonparse/cmt_parse.cpp | 540 +++++++++++++++++++++++++++++++++++ jsonparse/web_cmd_parse3.cpp | 8 + localserver/cmt_cmd.cpp | 110 +++++++ localserver/cmt_server.cpp | 95 ++++++ localserver/cmt_server.hpp | 235 +++++++++++++++ localserver/local_server.hpp | 21 +- main.cpp | 5 +- platform/platform_init.cpp | 17 +- threadfunc/thread_func.cpp | 9 + threadfunc/thread_func.hpp | 1 + uart/uart.cpp | 16 +- uart/uart.hpp | 2 +- uart/uart_feature_parse.cpp | 22 +- 15 files changed, 1106 insertions(+), 28 deletions(-) create mode 100644 jsonparse/cmt_parse.cpp create mode 100644 localserver/cmt_cmd.cpp create mode 100644 localserver/cmt_server.cpp create mode 100644 localserver/cmt_server.hpp diff --git a/common/common_func.cpp b/common/common_func.cpp index 15abba6..7d63619 100644 --- a/common/common_func.cpp +++ b/common/common_func.cpp @@ -951,7 +951,58 @@ int getSysIntValue(char *key) { fclose(fp); return value; } +int GetSysStatusCMT(int& cpu_use,int& mem_use,int& disk_remain,int& cpu_temp) +{ + 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; + + char name[8]; + double cpu_sys = -1; + double cpu_user = -1; + double cpu_total = -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%ld", 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%ld", 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; + float rateUser = cpu_user * 100.0 / cpu_total; + float rateSys = cpu_sys * 100.0 / cpu_total; + if (rateUser > 95) { + rateUser = 92; + } + char hardTotal[32]; + char hardFree[32]; + char rateHardUse[32]; + char chRes[100]; + memset(chRes, 0, 100); + getDiskInfo(hardTotal, hardFree); + std::string strhardFree(hardFree); + char key[128] = {0}; + memset(key, 0, sizeof(key)); + sprintf(key, "/sys/class/thermal/thermal_zone0/temp"); + int temp = getSysIntValue(key); + cpu_use = rateUser; + mem_use = fMemRate * 100; + disk_remain = atoi(strhardFree.substr(0, strhardFree.length() - 1).c_str()); + cpu_temp = temp / 1000.0; +} std::string GetSysStatus(Json::Value &jsData) { long mem_used = -1; long mem_free = -1; diff --git a/common/common_func.hpp b/common/common_func.hpp index 22c2719..e08a1ba 100644 --- a/common/common_func.hpp +++ b/common/common_func.hpp @@ -380,7 +380,7 @@ void ZoneConfig(std::string zoneid); * @return std::string CPU MEM DISK info */ std::string GetSysStatus(Json::Value &jsData); - +int GetSysStatusCMT(int& cpu_use,int& mem_use,int& disk_remain,int& cpu_temp); bool CheckIP(const char* ip); bool IsValidMask(std::string mask); diff --git a/jsonparse/cmt_parse.cpp b/jsonparse/cmt_parse.cpp new file mode 100644 index 0000000..eb87ec4 --- /dev/null +++ b/jsonparse/cmt_parse.cpp @@ -0,0 +1,540 @@ +#include +#include "zlog.h" + +#include "communication_cmd.hpp" +#include "localserver/local_server.hpp" +#include "common/common_func.hpp" +#include "common/global.hpp" +#include +#include "dbaccess/sql_db.hpp" +#include "scheduler/schedule.hpp" +#include "localserver/cmt_server.hpp" + +extern zlog_category_t *zct; + +void JsonData::CmtCmd_80(char* send_data,int& send_length) +{ + zlog_info(zct,"CmtCmd_80"); + GatewayVersion gateway_ver; + gateway_ver.version = 1; + memcpy(gateway_ver.mac,GlobalConfig::MacAddr_G.c_str(),sizeof(gateway_ver.mac)); + memcpy(gateway_ver.web_ver,ReadStrByOpt(SYSTEMINFOFILE, "Version", "WebVersion").c_str(),sizeof(gateway_ver.web_ver)); + memcpy(gateway_ver.system_ver,ReadStrByOpt(SYSTEMINFOFILE, "Version", "SystemVersion").c_str(),sizeof(gateway_ver.system_ver)); + memcpy(gateway_ver.gateway_ver,ReadStrByOpt(SYSTEMINFOFILE, "Version", "GateWayVersion").c_str(),sizeof(gateway_ver.gateway_ver)); + memcpy(gateway_ver.ip,GlobalConfig::IpAddr_G.c_str(),sizeof(gateway_ver.ip)); + memcpy(gateway_ver.gateway_type,ReadStrByOpt(SYSTEMINFOFILE, "Version", "GateWayProduct").c_str(),sizeof(gateway_ver.gateway_type)); + memcpy(gateway_ver.gateway_hw_ver,ReadStrByOpt(SYSTEMINFOFILE, "Version", "GateWayHwVesion").c_str(),sizeof(gateway_ver.gateway_hw_ver)); +#ifdef NR5G_MODULE + memcpy(gateway_ver.comm_mode,"5G",sizeof(gateway_ver.comm_mode)); +#endif +#ifdef Q4G_MODULE + memcpy(gateway_ver.comm_mode,"4G",sizeof(gateway_ver.comm_mode)); +#endif +#ifdef WIFI_MODULE + memcpy(gateway_ver.comm_mode,"WiFi",sizeof(gateway_ver.comm_mode)); +#endif + memcpy(gateway_ver.comm_mode,"有线",sizeof(gateway_ver.comm_mode)); + memcpy(gateway_ver.terminal_name,ReadStrByOpt(NETWORKCONFIG, "eth0", "hostName").c_str(),sizeof(gateway_ver.terminal_name)); + GetSysStatusCMT(gateway_ver.cpu_use,gateway_ver.memory_use,gateway_ver.disk_remain,gateway_ver.temperature); + memcpy(send_data,&gateway_ver,sizeof(GatewayVersion)); + send_length = sizeof(GatewayVersion); +} + +void JsonData::CmtCmd_81(char* recv_body,int& count,char* send_data,int& send_length) +{ + int featureInterVal; + int featureInterTime; + int waveInterVal; + int waveInterTime; + int maxSensorNum; + int sensorCount; + array_t arrRes; + char whereCon[512]={0}; + if (recv_body != NULL) + { + printf("count = %d\n",count); + char short_addr_[256]={0}; + for (size_t i = 0; i < count; i++){ + char temp[5]={0}; + memcpy(temp,recv_body + i * 4,4); + printf("short_addr = %s\n",temp); + strcat(short_addr_,"'"); + strcat(short_addr_,temp); + strcat(short_addr_,"'"); + if (i + 1 != count){ + strcat(short_addr_ ,","); + } + } + sprintf(whereCon,"zigbeeShortAddr IN (%s)",short_addr_); + arrRes = sqlite_db_ctrl::instance().GetDataMultiLineTransaction(T_SENSOR_INFO(TNAME), "*", whereCon); + }else{ + arrRes = sqlite_db_ctrl::instance().GetDataMultiLineTransaction(T_SENSOR_INFO(TNAME), "*", NULL); + } + int iResult = arrRes.size(); + printf("result = %d\n",iResult); + size_t j = 0; + if (iResult > 0) { + SensorInfo sensor_info[iResult]; + for (; j < iResult; j++) + { + memcpy(sensor_info[j].sensor_name,arrRes[j][1].c_str(),sizeof(sensor_info[j].sensor_name)); + memcpy(sensor_info[j].measurement_id,arrRes[j][44].c_str(),sizeof(sensor_info[j].measurement_id)); + memcpy(sensor_info[j].short_addr , arrRes[j][30].c_str(),sizeof(sensor_info[j].short_addr)); + memcpy(sensor_info[j].hw_ver,arrRes[j][8].c_str(),sizeof(sensor_info[j].hw_ver)); + memcpy(sensor_info[j].soft_ver,arrRes[j][9].c_str(),sizeof(sensor_info[j].soft_ver)); + std::vector vParamRSSI; + boost::split(vParamRSSI, arrRes[j][40], boost::is_any_of(","), boost::token_compress_on); + if (vParamRSSI.size() > 1) { + sensor_info[j].gateway_rssi = (atof(vParamRSSI[0].c_str())/255) * 100; + sensor_info[j].sensor_rssi = (atof(vParamRSSI[1].c_str())/255) * 100; + } else { + sensor_info[j].gateway_rssi = (atof(vParamRSSI[0].c_str())/255) * 100; + sensor_info[j].sensor_rssi = 99; + } + std::vector vParambattery; + boost::split(vParambattery, arrRes[j][43], boost::is_any_of(","), boost::token_compress_on); + if (vParambattery.size() > 1) { + sensor_info[j].battry = (atof(vParambattery[1].c_str())/atof(vParambattery[0].c_str())) * 100; + } else { + sensor_info[j].battry = 99; + } + std::vector vParam; + boost::split(vParam, arrRes[j][42], boost::is_any_of(","), boost::token_compress_on); + if (vParam.size() > 1){ + if (vParam[1] != "0"){ + sensor_info[j].loose_status = 1; + }else{ + sensor_info[j].loose_status = 0; + } + } + char whereCon[256]={0x00}; + sprintf(whereCon,"dataNodeNo = '%s'",arrRes[j][44].c_str()); + vec_t vecRes = sqlite_db_ctrl::instance().GetDataSingleLine(T_DATASTATIC_INFO(TNAME), "temTop,temBot",whereCon); + if (vecRes.size() > 0) + { + sensor_info[j].temperature_top = atoi(vecRes[0].c_str()); + sensor_info[j].temperature_bot = atoi(vecRes[1].c_str()); + }else{ + sensor_info[j].temperature_top = 200; + sensor_info[j].temperature_bot = 200; + } + + memcpy(sensor_info[j].product,arrRes[j][17].c_str(),sizeof(sensor_info[j].product)); + if (arrRes[j][17] == "01"){ + memcpy(sensor_info[j].product,"DN101",sizeof(sensor_info[j].product)); + }else if (arrRes[j][17] == "02"){ + memcpy(sensor_info[j].product,"DN102",sizeof(sensor_info[j].product)); + } + sensor_info[j].status = atoi(arrRes[j][37].c_str()); + + char szTableName[100] = {0x00}; + memset(whereCon,0,sizeof(whereCon)); + sprintf(szTableName, " t_data_waveSend "); + const char *sql = + " timestamp >= strftime('%s', 'now', '-1 day', 'start of day','utc') " + "AND timestamp < strftime('%s', 'now', '-1 day','start of day','utc','+24 hours') "; + sprintf(whereCon," and channelID = '%s-X'",arrRes[j][44].c_str()); + std::string strsql = std::string(sql) + std::string(whereCon); + int waveX_Count = sqlite_db_ctrl::instance().GetTableRows(szTableName,strsql.c_str()); + + memset(whereCon,0,sizeof(whereCon)); + sprintf(whereCon," and channelID = '%s-Y'",arrRes[j][44].c_str()); + strsql = std::string(sql) + std::string(whereCon); + int waveY_Count = sqlite_db_ctrl::instance().GetTableRows(szTableName,strsql.c_str()); + + memset(whereCon,0,sizeof(whereCon)); + sprintf(whereCon," and channelID = '%s-Z'",arrRes[j][44].c_str()); + strsql = std::string(sql) + std::string(whereCon); + int waveZ_Count = sqlite_db_ctrl::instance().GetTableRows(szTableName,strsql.c_str()); + + memset(whereCon,0,sizeof(whereCon)); + memset(szTableName,0,sizeof(szTableName)); + sprintf(szTableName, " t_dataStatic_%s ",arrRes[j][44].c_str()); + sprintf(whereCon," and channelID = '%s-S'",arrRes[j][44].c_str()); + strsql = std::string(sql) + std::string(whereCon); + int static_Count = sqlite_db_ctrl::instance().GetTableRows(szTableName,strsql.c_str()); + + scheduler::instance().GetScheduleConfig(featureInterVal,waveInterVal,featureInterTime,waveInterTime,maxSensorNum); + zlog_info(zct,"wavex = %d,featureInterVal = %d,waveInterVal = %d",waveX_Count,featureInterVal,waveInterVal); + int day_count = 86400 / waveInterVal; + + sensor_info[j].wave_x_reporting_rate = float( waveX_Count/ day_count) * 100; + printf("day_count = %d,wave_x_reporting_rate = %d\n",day_count,sensor_info[j].wave_x_reporting_rate ); + sensor_info[j].wave_y_reporting_rate = (float(waveY_Count)/(86400/waveInterVal)) * 100; + sensor_info[j].wave_z_reporting_rate = (float(waveZ_Count)/(86400/waveInterVal)) * 100; + sensor_info[j].eigen_value_reporting_rate = (float(static_Count)/(86400/featureInterVal)) * 100; + day_count = 86400 / featureInterVal; + printf("static_Count = %d,day_count = %d,wave_x_reporting_rate = %d\n",static_Count,day_count,sensor_info[j].eigen_value_reporting_rate ); + + memset(whereCon,0,sizeof(whereCon)); + sprintf(whereCon,"channelID = '%s-Z'",arrRes[j][44].c_str()); + std::string integratRMS = sqlite_db_ctrl::instance().GetData(T_DATA_INFO(TNAME), "integratRMS",whereCon); + + sensor_info[j].velocity_rms = atof(integratRMS.c_str()); + sensor_info[j].upgrade_status = atoi(arrRes[j][46].c_str()); + memset(whereCon,0,sizeof(whereCon)); + sprintf(whereCon,"short_addr = '%s' ORDER BY start_timestamp DESC limit 0,1",arrRes[j][30].c_str()); + std::string upgrade_time = sqlite_db_ctrl::instance().GetData("firmware_upgrade", " start_timestamp ", whereCon); + memcpy(sensor_info[j].upgrade_time,upgrade_time.c_str(),sizeof(sensor_info[j].upgrade_time)); + sensor_info[j].version = 1; + } + memcpy(send_data,&sensor_info,sizeof(SensorInfo) * j); + send_length = sizeof(SensorInfo) * j; + zlog_info(zct,"sizeof(SensorInfo) = %d",sizeof(SensorInfo)*j); + zlog_info(zct,"send_length = %d",send_length); + } + +} + +void JsonData::CmtCmd_82(char* MeasurementID,char* send_data,int& channel,int& send_length) +{ + FILE* pFile = NULL; + char* buffer = NULL; + int thisSize = 0; + WaveRes wave; + char whereCon[64]={0}; + sprintf(whereCon,"MeasurementID = '%s'",MeasurementID); + vec_t vecRes = sqlite_db_ctrl::instance().GetDataSingleLine(T_SENSOR_INFO(TNAME), "samplingRate,ACCSampleTime",whereCon); + std::string strChannel = ""; + + if (channel == 1){ + strChannel = "X"; + }else if(channel == 2){ + strChannel = "Y"; + }else if (channel == 3){ + strChannel = "Z"; + } + std::string data_file = "/opt/data/" + std::string(MeasurementID) + "-" + strChannel + ".dat"; + zlog_info(zct, "strFileName = %s", data_file.c_str()); + + pFile = fopen(data_file.c_str(), "rb"); + if (pFile != NULL) { + while (fgetc(pFile) != EOF) { + ++thisSize; + } + rewind(pFile); + fseek(pFile, 32, SEEK_SET);//跳过32个字节的时间戳 + buffer = (char*)malloc(thisSize - 32); + fread(buffer, sizeof(char), thisSize - 32, pFile); + fclose(pFile); + } + wave.sampling_rate = atoi(vecRes[0].c_str()); + wave.sampling_time = atoi(vecRes[1].c_str()); + wave.version = 1; + send_length = sizeof(WaveRes) + thisSize - 32; + memcpy(send_data,(char*)&wave,sizeof(WaveRes)); + memcpy(send_data + sizeof(WaveRes) ,buffer,thisSize - 32); + free(buffer); +} + +void JsonData::CmtCmd_83(char* recv_body,int& count,char* send_data,int& send_length) +{ + array_t arrRes; + std::string filename = ""; + char whereCon[128]={0}; + if (recv_body){ + printf("count = %d\n",count); + char MeasurementID_[256]={0}; + for (size_t i = 0; i < count; i++){ + char temp[21]={0}; + memcpy(temp,recv_body + i * 20,20); + printf("short_addr = %s\n",temp); + strcat(MeasurementID_,"'"); + strcat(MeasurementID_,temp); + strcat(MeasurementID_,"'"); + if (i + 1 != count){ + strcat(MeasurementID_ ,","); + } + } + sprintf(whereCon,"MeasurementID IN (%s)",MeasurementID_); + arrRes = sqlite_db_ctrl::instance().GetDataMultiLineTransaction(T_SENSOR_INFO(TNAME), "*", whereCon); + }else{ + arrRes = sqlite_db_ctrl::instance().GetDataMultiLineTransaction(T_SENSOR_INFO(TNAME), "*", NULL); + } + if (arrRes.size() > 0){ + char localtimestamp[32] = {0}; + std::string current_time = GetLocalTimeWithMs(); + filename = "/opt/DataNode/config_" + GlobalConfig::MacAddr_G + "_" + std::string(current_time)+ ".csv"; + std::ofstream csvFile(filename); + if (!csvFile.is_open()) { + std::cerr << "Error: Could not open file " << filename << std::endl; + return; + } + // 写入 CSV 标题行 + csvFile << "GW MAC,Product,IP,PanID,Signal Channel,Terminal Name,SN,Sensor MAC,Measurement ID," + "Short Addr,Sensor Name,Update Date,Gateway RSSI,Sensor RSSI,HW Ver,Soft Ver,Sampling Rate," + "Range,Sampling Time,VIFF,Power,Retry Time\n"; + for (size_t i = 0; i < count; i++) + { + DownloadConfig download_config; + memcpy(download_config.gw_mac,GlobalConfig::MacAddr_G.c_str(),sizeof(download_config.gw_mac)); + if (arrRes[i][17] == "01"){ + memcpy(download_config.product,"DN101",sizeof(download_config.product)); + }else if (arrRes[i][17] == "02"){ + memcpy(download_config.product,"DN102",sizeof(download_config.product)); + } + memcpy(download_config.ip,GlobalConfig::IpAddr_G.c_str(),sizeof(download_config.ip)); + download_config.panid = atoi(arrRes[i][28].c_str()); + download_config.signal_channle = atoi(arrRes[i][29].c_str()); + memcpy(download_config.terminal_name,"",sizeof(download_config.terminal_name)); + memcpy(download_config.sn,arrRes[i][11].c_str(),sizeof(download_config.sn)); + memcpy(download_config.sensor_mac,arrRes[i][0].c_str(),sizeof(download_config.sensor_mac)); + memcpy(download_config.measurement_id,arrRes[i][44].c_str(),sizeof(download_config.measurement_id)); + download_config.short_addr = atoi(arrRes[i][30].c_str()); + memcpy(download_config.sensor_name,arrRes[i][1].c_str(),sizeof(download_config.sensor_name)); + memcpy(download_config.update_date,arrRes[i][38].c_str(),sizeof(download_config.update_date)); + std::vector vParamRSSI; + boost::split(vParamRSSI, arrRes[i][40], boost::is_any_of(","), boost::token_compress_on); + if (vParamRSSI.size() > 1) { + download_config.gateway_rssi = (atof(vParamRSSI[0].c_str())/255) * 100; + download_config.sensor_rssi = (atof(vParamRSSI[1].c_str())/255) * 100; + } else { + download_config.gateway_rssi = (atof(vParamRSSI[0].c_str())/255) * 100; + download_config.sensor_rssi = 99; + } + memcpy(download_config.hw_ver,arrRes[i][8].c_str(),sizeof(download_config.hw_ver)); + memcpy(download_config.soft_ver,arrRes[i][9].c_str(),sizeof(download_config.soft_ver)); + download_config.sampling_rate = atoi(arrRes[i][23].c_str()); + download_config.range = atoi(arrRes[i][25].c_str()); + download_config.sampling_time = atoi(arrRes[i][36].c_str()); + download_config.viff = atoi(arrRes[i][39].c_str()); + download_config.power = atoi(arrRes[i][33].c_str()); + download_config.retry_time = atoi(arrRes[i][34].c_str()); + + csvFile << download_config.gw_mac << ',' << download_config.product << ','<< download_config.ip << ',' << download_config.panid << ',' + << download_config.signal_channle << ','<< download_config.terminal_name << ','<< download_config.sn << ','<< download_config.sensor_mac << ',' + << download_config.measurement_id << ','<< download_config.short_addr << ','<< download_config.sensor_name << ','<< download_config.update_date << ',' + << download_config.gateway_rssi << ','<< download_config.sensor_rssi << ','<< download_config.hw_ver << ','<< download_config.soft_ver << ',' + << download_config.sampling_rate << ','<< download_config.range << ','<< download_config.sampling_time << ','<< download_config.viff << ',' + << download_config.power << ','<< download_config.retry_time << '\n' ; + } + csvFile.close(); + std::cout << "CSV file written to " << filename << std::endl; + } + send_length = sizeof(DownloadConfigRes); + DownloadConfigRes download_condfig_res; + download_condfig_res.version = 1; + memcpy(download_condfig_res.filename,filename.c_str(),sizeof(download_condfig_res.filename)); + memcpy(send_data,(char*)&download_condfig_res,sizeof(DownloadConfigRes)); + zlog_info(zct, "cmd 83 send_length = %d",send_length); + +} + +void JsonData::CmtCmd_84(char* filename,char* file_md5,char* send_data,int& send_length) +{ + std::vector vecDataNode; + UploadConfigRes upload_condfig_res; + upload_condfig_res.code = 0; + sprintf(upload_condfig_res.message ,"%s",""); + send_length = sizeof(UploadConfigRes); + char file_path[64]={0}; + char cmd[128]={0}; + sprintf(cmd, "mv /opt/%s /opt/DataNode/",filename); + system(cmd); + sprintf(file_path, "/opt/DataNode/%s",filename); + std::ifstream csv_data(file_path, std::ios::in); + int iRet = 0; + if (!csv_data.is_open()) { + zlog_error(zct, "UpdataDataNodeConfig fail to open:%s", file_path); + } + std::string line; + std::vector words; + std::string word; + + DataNodeInfo dataNode; + getline(csv_data, line); + + std::istringstream sin; + while (getline(csv_data, line)) { + words.clear(); + sin.clear(); + sin.str(line); + while (getline(sin, word, ',')) { + words.push_back(word); + } + std::string mac = words[0]; + if (mac != GlobalConfig::MacAddr_G) { + iRet = -2; + break; + } + dataNode.ZigbeeLongAddr = words[7]; + dataNode.ZigbeeShortAddr = words[9]; + dataNode.SamplingRate = atoi(words[16].c_str()); + dataNode.Range = atoi(words[17].c_str()); + dataNode.ACCSampleTime = atoi(words[18].c_str()); + dataNode.VIntegralFilterFrequency = atoi(words[19].c_str()); + dataNode.ZigbeePower = atoi(words[20].c_str()); + dataNode.ZigbeeRetry = atoi(words[21].c_str()); + vecDataNode.push_back(dataNode); + } + csv_data.close(); + if (vecDataNode.size() == 0) { + zlog_error(zct, "UpdataDataNodeConfig vecDataNode is 0"); + upload_condfig_res.code = 0; + sprintf(upload_condfig_res.message ,"%s",""); + memcpy(send_data,(char*)&upload_condfig_res,sizeof(UploadConfigRes)); + return ; + } + + char whereCon[1024] = {0}; + char updateSql[1024] = {0}; + for (size_t i = 0; i < vecDataNode.size(); i++) { + sprintf(updateSql, "featureInterVal='%d',waveInterVal='%d',range='%d',samplingRate='%d',AccSampleTime = '%d',viff ='%d' ,ZigbeePower = '%d',ZigbeeRetry = '%d',UpdateFlag = 0", vecDataNode[i].FeatureInterVal, vecDataNode[i].WaveInterVal, vecDataNode[i].Range, + vecDataNode[i].SamplingRate, vecDataNode[i].ACCSampleTime, vecDataNode[i].VIntegralFilterFrequency, vecDataNode[i].ZigbeePower, vecDataNode[i].ZigbeeRetry); + sprintf(whereCon, "dataNodeNo='%s'", vecDataNode[i].ZigbeeLongAddr.c_str()); + + iRet = sqlite_db_ctrl::instance().UpdateTableData(T_SENSOR_INFO(TNAME), updateSql, whereCon); + if (iRet != 0) { + zlog_error(zct, "UpdataDataNodeConfig UpdateTableData fail"); + } + uint16_t short_addr; + char *end_ptr = NULL; + short_addr = strtol(vecDataNode[i].ZigbeeShortAddr.c_str(), &end_ptr, 16); + int res = scheduler::instance().UpdateSensorConfig(short_addr); + + memset(whereCon, 0x00, sizeof(whereCon)); + memset(updateSql, 0x00, sizeof(updateSql)); + } + + memcpy(send_data,(char*)&upload_condfig_res,sizeof(UploadConfigRes)); + zlog_info(zct, "cmd 84 send_length = %d",send_length); +} + +void JsonData::CmtCmd_85(char* filename,char* file_md5,char* send_data,int& send_length) +{ + zlog_info(zct,"file_path = %s,file_md5 = %d",filename,file_md5); + sleep(3); + int iRet = system("/opt/opt.sh"); + zlog_info(zct, "iRet = %d", iRet); + if (iRet == -1) { + zlog_error(zct, "system() error"); + } +} + +void JsonData::CmtCmd_86(char* recv_body,int& count,char* filename,char* file_md5,char* send_data,int& send_length) +{ + zlog_info(zct,"file_path = %s,file_md5 = %d",filename,file_md5); + UpgradeSensorRes upgrade_sensor_res; + upgrade_sensor_res.code = 0; + sprintf(upgrade_sensor_res.message ,"%s",""); + send_length = sizeof(UpgradeSensorRes); + char cmd[128]={0}; + char file_path[64]={0}; + sprintf(cmd, "mv /opt/%s /opt/DataNode/",filename); + system(cmd); + sprintf(file_path, "/opt/DataNode/%s",filename); + FILE * pFile=NULL; + size_t thisSize = 0; + char *buffer=NULL; + pFile = fopen (file_path,"rb"); + if (pFile==NULL) { + zlog_error(zct,"Error opening file"); + } + else + { + while (fgetc(pFile) != EOF) { + ++thisSize; + } + rewind(pFile); + buffer = (char*)malloc(thisSize); + fread (buffer, sizeof (char), thisSize, pFile); + fclose (pFile); + } + zlog_info(zct,"Read %zu bytes", thisSize); + char sensor_type[6] = {0}; + char sf_version[10] = {0}; + memcpy(sensor_type, buffer, 5); + zlog_info(zct,"model:%s", sensor_type); + char c[2] = {0}; + c[0] = buffer[5]; + uint8_t hw_ver = atoi(c); + c[0] = buffer[6]; + uint8_t sf_ver_m = atoi(c); + c[0] = buffer[7]; + uint8_t sf_ver_s = atoi(c); + sprintf(sf_version,"%d.%d",sf_ver_m,sf_ver_s); + unsigned char ch_crc = 0x00; + int packgeSize = 0; + ch_crc = buffer[12]; + packgeSize = BUILD_UINT32(buffer[8],buffer[9],buffer[10],buffer[11]); + zlog_info(zct,"sf_ver_m = %d",sf_ver_m); + zlog_info(zct,"sf_ver_s = %d",sf_ver_s); + zlog_info(zct,"hw_ver = %d",hw_ver); + zlog_info(zct,"sensor_type = %s",sensor_type); + zlog_info(zct,"packgeSize = %d",packgeSize); + zlog_info(zct,"ch_crc = %02x",ch_crc); + unsigned char sum = 0x00; + for(size_t i = 13; i < thisSize;i++){ + sum += buffer[i]; + } + if (sum % 256 != ch_crc){ + zlog_error(zct,"package CRC error,filename = %s",file_path); + upgrade_sensor_res.code = 1; + sprintf(upgrade_sensor_res.message ,"%s","package CRC error"); + memcpy(send_data,(char*)&upgrade_sensor_res,sizeof(DownloadConfigRes)); + return; + } + zlog_info(zct,"sum = %x\n",sum % 256); + char localtimestamp[32] = {0}; + GetTimeNet(localtimestamp, 1); + for (size_t i = 0; i < count; i++) + { + char wherecon[100] = {0}; + char insertSql[200] = {0}; + char updateSql[100] = {0}; + char short_addr_[21] = {0}; + memcpy(short_addr_,recv_body + i * 4,4); + sprintf(wherecon," zigbeeShortAddr = '%s' ",short_addr_); + vec_t vecResult = sqlite_db_ctrl::instance().GetDataSingleLine(T_SENSOR_INFO(TNAME), " hardVersion,softVersion,ProductNo,zigbeeShortAddr ", wherecon); + if (hw_ver != atoi(vecResult[0].c_str())){ + zlog_error(zct,"hardVersion error,filename = %s",file_path); + upgrade_sensor_res.code = 2; + sprintf(upgrade_sensor_res.message ,"%s","hardVersion error"); + memcpy(send_data,(char*)&upgrade_sensor_res,sizeof(DownloadConfigRes)); + return; + } + sprintf(insertSql, " '%s','%s','','','','','%d.%d','%s',1,'%s'",vecResult[3].c_str(),localtimestamp,sf_ver_m,sf_ver_s,vecResult[1].c_str(),filename); + sqlite_db_ctrl::instance().InsertData(" firmware_upgrade ", insertSql); + //0 默认状态,1 升级中,2 升级成功,3 升级失败 + memset(wherecon,0,sizeof(wherecon)); + memset(updateSql,0,sizeof(updateSql)); + sprintf(wherecon," zigbeeShortAddr = '%s'",vecResult[3].c_str()); + sprintf(updateSql, " upgradeStatus = %d ", 1); + sqlite_db_ctrl::instance().UpdateTableData(T_SENSOR_INFO(TNAME), updateSql,wherecon); + uint16_t short_addr; + char *end_ptr = NULL; + short_addr = strtol(vecResult[3].c_str(), &end_ptr, 16); + int res = scheduler::instance().UpgradeSensor(short_addr,std::string(sensor_type),atoi(vecResult[0].c_str()),vecResult[1],std::string(sf_version)); + } + free(buffer); +} + +void JsonData::CmtCmd_88(char* recv_body,int& count) +{ + +} + +std::string get_file_md5(const std::string& file_path) { + // 使用 md5sum 命令计算文件的 MD5 值 + std::string command = "md5sum " + file_path + " | awk '{ print $1 }'"; + + // 使用 popen 执行命令并获取输出 + std::array buffer; + std::string result; + std::shared_ptr pipe(popen(command.c_str(), "r"), pclose); + + if (!pipe) { + std::cerr << "Error: Unable to run md5sum command" << std::endl; + return ""; + } + + // 从命令的输出流中读取数据 + while (fgets(buffer.data(), buffer.size(), pipe.get()) != nullptr) { + result += buffer.data(); + } + + // 去除末尾的换行符 + result.erase(result.find_last_not_of("\n") + 1); + + return result; +} diff --git a/jsonparse/web_cmd_parse3.cpp b/jsonparse/web_cmd_parse3.cpp index 9869a81..d954f5d 100644 --- a/jsonparse/web_cmd_parse3.cpp +++ b/jsonparse/web_cmd_parse3.cpp @@ -619,6 +619,14 @@ std::string JsonData::JsonCmd_Cgi_59(Param_59 ¶m) { Json::Value iTem; iTem.append(arrResult[i][1]); iTem.append(arrResult[i][0]); + int time = 0; + int lost_data_time = atol(arrResult[i][1].c_str()) - atol(arrResult[i][1].c_str()); + if (param.mMode == 1){ + time = abs(lost_data_time/featureInterVal); + }else if(param.mMode == 2){ + time = abs(lost_data_time/waveInterVal); + } + iTem.append(time); valData.append(iTem); } jsonVal["content"] = valData; diff --git a/localserver/cmt_cmd.cpp b/localserver/cmt_cmd.cpp new file mode 100644 index 0000000..02fbef0 --- /dev/null +++ b/localserver/cmt_cmd.cpp @@ -0,0 +1,110 @@ +#include +#include "zlog.h" +#include "cmt_server.hpp" +#include "local_server.hpp" +#include "jsonparse/communication_cmd.hpp" +#include "common/global.hpp" + +extern zlog_category_t *zct; + +void LocalServer::HandleTcp_cmd(const char* recv_data,char* send_data,uint8_t& rescmd,int& send_length,int recvbody_length) +{ + zlog_info(zct,"HandleTcp_cmd"); + PackageHead head; + memcpy(&head,recv_data,sizeof(PackageHead)); + uint8_t cmd = head.cmd; + rescmd = head.cmd; + printf("cmd = %d\n",cmd); + JsonData jd; + switch (cmd) + { + case 1:{ + Search search; + search.version = 1; + memcpy(search.mac,GlobalConfig::MacAddr_G.c_str(),sizeof(search.mac)); + search.gw_type = kGWTDG102; + send_length = sizeof(Search); + memcpy(send_data,&search,sizeof(Search)); + }break; + case kGateWayVersion: { + jd.CmtCmd_80(send_data,send_length); + }break; + case kSensorInfo:{ + char *recv_body = NULL; + if (recvbody_length > 0){ + recv_body = (char*)malloc(recvbody_length - 4); + memcpy(recv_body,recv_data + sizeof(PackageHead) + 4,recvbody_length - 4); + } + int count = 0; + memcpy((char*)&count,recv_data + sizeof(PackageHead),4); + jd.CmtCmd_81(recv_body,count,send_data,send_length); + if (recv_body){ + free(recv_body); + } + }break; + case kSensorWave:{ + WaveReq wave_req; + memcpy(&wave_req,recv_data + sizeof(PackageHead),sizeof(WaveReq)); + jd.CmtCmd_82(wave_req.measurement_id,send_data,wave_req.channel,send_length); + + }break; + case KDownloadConfig:{ + char *recv_body = NULL; + int count = 0; + if (recvbody_length > 0){ + recv_body = (char*)malloc(recvbody_length - 4); + memcpy((char*)&count,(char*)recv_data + sizeof(PackageHead),4); + memcpy(recv_body,recv_data + sizeof(PackageHead) + 4,recvbody_length - 4); + } + jd.CmtCmd_83(recv_body,count,send_data,send_length); + if (recv_body){ + free(recv_body); + } + }break; + case KUploadConfig:{ + UploadConfigReq upload_config; + memcpy(&upload_config,recv_data + sizeof(PackageHead),sizeof(UploadConfigReq)); + printf("filename = %s\n",upload_config.filename); + jd.CmtCmd_84(upload_config.filename,upload_config.md5,send_data,send_length); + + }break; + case KUpgadeGateway:{ + + UpgradeGwReq upgrade_gw; + memcpy(&upgrade_gw,recv_data + sizeof(PackageHead),sizeof(UpgradeGwReq)); + jd.CmtCmd_85(upgrade_gw.filename,upgrade_gw.md5,send_data,send_length); + }break; + case KUpgradeSensor:{ + char *recv_body = NULL; + int count = 0; + if (recvbody_length > 0){ + recv_body = (char*)malloc(recvbody_length - sizeof(UpgradeSensorReq) - 4); + memcpy((char*)&count,(char*)recv_data + sizeof(PackageHead) + sizeof(UpgradeSensorReq) ,4); + memcpy(recv_body,recv_data + sizeof(PackageHead) + sizeof(UpgradeSensorReq) + 4,recvbody_length - sizeof(UpgradeSensorReq) - 4); + } + UpgradeSensorReq upgrade_sensor; + memcpy(&upgrade_sensor,recv_data + sizeof(PackageHead),sizeof(UpgradeSensorReq)); + jd.CmtCmd_86(recv_body,count,upgrade_sensor.filename,upgrade_sensor.md5,send_data,send_length); + }break; + case KEigenvalue:{ + + } + break; + case KUpgradeSensorStop:{ + char *recv_body = NULL; + int count = 0; + if (recvbody_length > 0){ + recv_body = (char*)malloc(recvbody_length - 4); + memcpy((char*)&count,(char*)recv_data + sizeof(PackageHead) ,4); + memcpy(recv_body,recv_data + sizeof(PackageHead) + 4 ,recvbody_length - 4); + } + UpgradeSensorReq upgrade_sensor; + memcpy(&upgrade_sensor,recv_data + sizeof(PackageHead),sizeof(UpgradeSensorReq)); + jd.CmtCmd_88(recv_body,count); + } + break; + default: + break; + } + +} diff --git a/localserver/cmt_server.cpp b/localserver/cmt_server.cpp new file mode 100644 index 0000000..c895e0b --- /dev/null +++ b/localserver/cmt_server.cpp @@ -0,0 +1,95 @@ +#include "cmt_server.hpp" +#include +#include +#include +#include +#include +#include + +#include "localserver/local_server.hpp" + +extern zlog_category_t *zct; + +void CMTSession::start() { + data_ = (char*)malloc(CMT_TCP_LEN); + memset(data_, 0, CMT_TCP_LEN); + sessionSet_.insert(shared_from_this()); // 将会话添加到会话集合中 + do_read(); +} +void CMTSession::set_data(char *data, int len) { + memcpy(data_, data, len); +} +void CMTSession::do_write(std::size_t length) { + auto self(shared_from_this()); + zlog_debug(zct, "[CMT] response len = %d", length); + boost::asio::async_write(socket_, boost::asio::buffer(data_, length), [this, self](boost::system::error_code ec, std::size_t /*length*/) { + if (ec) { + zlog_error(zct, "[CMT] fail to send data, %s, %d", ec.category().name(), ec.value()); + socket_.close(); + sessionSet_.erase(shared_from_this()); + } else { + zlog_debug(zct, "[CMT] waiting for next message..."); + do_read(); + // socket_.close(); + // sessionSet_.erase(shared_from_this()); + } + }); +} + +void CMTServer::do_accept() { + acceptor_.async_accept(socket_, [this](boost::system::error_code ec) { + zlog_debug(zct, "[CMT] accept a socket"); + if (!ec) { + std::make_shared(std::move(socket_), sessionSet_)->start(); + } + + do_accept(); + }); +} +void CMTSession::do_read() { + auto self(shared_from_this()); + socket_.async_read_some(boost::asio::buffer(data_, CMT_TCP_LEN), [this, self](boost::system::error_code ec, std::size_t length) { + if (!ec) { + if (length == 0) { + zlog_warn(zct, "[CMT] Client disconnected (length 0)"); + sessionSet_.erase(shared_from_this()); + return; + } + + if (length < 6 || data_[0] != 0xAA || data_[1] != 0x55 || data_[2] != 0xAA) { + zlog_warn(zct, "[CMT] invalid data package, len:%d", length); + do_read(); + } + uint8_t cmd = data_[3]; + int payload_len = 0; + memcpy((char*)&payload_len, (char*)&data_[4], 4); + payload_len = htonl(payload_len); + zlog_debug(zct, "[CMT] cmd: %d, message len: %d, payload len: %d, head:%2x-%2x-%2x", cmd, length, payload_len, data_[0], data_[1], data_[2]); + zlog_debug(zct, "[CMT] payload bytes %d, %d", data_[4], data_[5]); + int send_data_len = 0; + char send_data[96100] = {0}; + LocalServer::HandleTcp_cmd(data_,send_data,cmd,send_data_len,payload_len); + PackageHead pkg_head; + pkg_head.head[0] = 0xAA; + pkg_head.head[1] = 0x55; + pkg_head.head[2] = 0xAA; + pkg_head.cmd = cmd; + pkg_head.len = send_data_len; + memset(data_,0,sizeof(data_)); + memcpy(data_, &pkg_head, head_len_); + memcpy(data_ + head_len_, &send_data, send_data_len); + do_write(head_len_ + send_data_len); + + } else if (ec == boost::asio::error::eof){ + zlog_warn(zct, "[CMT] Client disconnect the connection"); + sessionSet_.erase(shared_from_this()); + } else if (ec == boost::asio::error::connection_reset){ + zlog_warn(zct, "[CMT] Connection reset by client"); + sessionSet_.erase(shared_from_this()); + } else { + zlog_error(zct, "[CMT] Error message, reason: %s", ec.message().c_str()); + socket_.close(); + sessionSet_.erase(shared_from_this()); + } + }); +} diff --git a/localserver/cmt_server.hpp b/localserver/cmt_server.hpp new file mode 100644 index 0000000..8cd0a97 --- /dev/null +++ b/localserver/cmt_server.hpp @@ -0,0 +1,235 @@ +#ifndef CMT_PROTOCOL_HPP_ +#define CMT_PROTOCOL_HPP_ +#include +#include +#include +#include +#include +#include + +using boost::asio::ip::tcp; + +#define CMT_TCP_LEN 100000 + +//1 tcp server可以参考本安有线中的代码,侦听端口10000 +//2 定义无线网关与传感器用到的结构 +//3 包头为 + +#pragma pack(1) +struct PackageHead{ + uint8_t head[3]; // 固定值:0xAA55AA + uint8_t cmd; + int len; + char data[0]; +}; + +//网关版本和状态信息cmd 80 +struct GatewayVersion{ + int version; // 写1 + char web_ver[12]; + char system_ver[12]; + char gateway_ver[12]; + char ip[16]; + char gateway_type[12]; + char gateway_hw_ver[12]; + char terminal_name[32]; // 终端名称,如果为空,填写Default + int cpu_use; + int memory_use; + int disk_remain; + int temperature; + char comm_mode[10]; + char mac[20]; +}; +enum SensorStatus{ + OFFLINE = 0, + ONLINE = 1 +}; +enum SensorUpgradeStatus{ + UPGRADE_NORMAL = 0, + UPGRADING = 1, + UPGRADE_SUCCESS = 2, + UPGRADE_FALIED = 3 +}; +enum LooseStatus{ + NORMAL = 0, + LOOSE = 1 +}; +//传感器信息cmd 81 + +struct SensorInfoReq{ + char short_addr[4]; +}; +struct SensorInfo{ + int version; + char sensor_name[64]; + char measurement_id[20]; + char short_addr[5]; + char hw_ver[12]; + char soft_ver[12]; + int gateway_rssi; + int sensor_rssi; + int battry; + int loose_status; //参考 LooseStatus + int temperature_bot; + int temperature_top; + char product[6]; // DN101;DN102 + int status; // 参考 SensorStatus + int eigen_value_reporting_rate; + int wave_x_reporting_rate; + int wave_y_reporting_rate; + int wave_z_reporting_rate; + float velocity_rms; + int upgrade_status; // 参考 SensorUpgradeStatus + char upgrade_time[20]; +}; + +enum ChannelType{ + X = 1, + Y = 2, + Z = 3 +}; +//波形cmd 82 +struct WaveReq{ + char measurement_id[20]; + int channel;//参考 ChannelType +}; + +struct WaveRes{ + int version; + int sampling_rate; + int sampling_time; + char wave[0]; +}; + +//下载配置 cmd 83 +struct DownloadConfigReq{ + char measurement_id[20]; +}; +enum Range{ + RANGE_8G = 0, + RANGE_16G = 1, + RANGE_32G = 2, + RANGE_64G = 3, + RANGE_50G = 4 +}; +struct DownloadConfigRes{ + int version; + char filename[128]; +}; +struct DownloadConfig{ + char gw_mac[20]; + char product[6]; // DN101;DN102 + char ip[16]; + int panid; + int signal_channle; + char terminal_name[32]; + char sn[10]; + char sensor_mac[20]; + char measurement_id[20]; + int short_addr; + char sensor_name[64]; + char update_date[20]; + int gateway_rssi; + int sensor_rssi; + char hw_ver[12]; + char soft_ver[12]; + int sampling_rate; + int range; //量程 参考 Range + int sampling_time; + int viff; //速度积分起始频率 + int power; //zigbee发射功率 + int retry_time; //zigbee重发次数 +}; + +//上传配置 cmd 84 +struct UploadConfigReq{ + char filename[64]; + char md5[33]; +}; +struct UploadConfigRes{ + int code; + char message[64]; +}; +//网关更新 cmd 85 +struct UpgradeGwReq{ + char filename[64]; + char md5[33]; +}; + +struct UpgradeGwRes{ + int code; + char message[64]; +}; +//传感器更新 cmd 86 +struct UpgradeSensorReq{ + char filename[64]; + char md5[33]; + char upgrade_short_addr[0]; +}; +struct UpgradeSensorRes{ + int code; + char message[64]; +}; +//获取特征值 cmd 87 + + +//停止更新传感器 cmd 88 +struct UpgradeStopReq{ + int short_addr; +}; + +// 搜索应答 cmd 1 +struct Search { + int version; + char mac[20]; + int gw_type; // GatewayType +}; + +class CMTSession : public std::enable_shared_from_this { +public: + CMTSession(tcp::socket socket, std::unordered_set>& sessionSet) : socket_(std::move(socket)), sessionSet_(sessionSet) { + web_version_ = "1.0.1"; + version_ = 1; + head_len_ = sizeof(PackageHead); + } + ~CMTSession() { + if (data_ != nullptr) { + free(data_); + } + } + + void start(); + void set_data(char *data, int len); + void do_write(std::size_t length); + +private: + void do_read(); + + tcp::socket socket_; + std::unordered_set>& sessionSet_; + char *data_; + std::string web_version_; + int version_; + int head_len_; +}; + +class CMTServer { +public: + CMTServer(boost::asio::io_service& io_service, short port) : acceptor_(io_service, tcp::endpoint(tcp::v4(), port)), socket_(io_service) { do_accept(); } + + // 向所有客户端发送消息 + void send_message_to_all(char *message, int len) { + for (auto& session : sessionSet_) { + session->set_data(message, len); + session->do_write(len); + } + } +private: + void do_accept(); + + tcp::acceptor acceptor_; + tcp::socket socket_; + std::unordered_set> sessionSet_; +}; + +#endif diff --git a/localserver/local_server.hpp b/localserver/local_server.hpp index 82d19f4..8ae0f00 100644 --- a/localserver/local_server.hpp +++ b/localserver/local_server.hpp @@ -53,15 +53,32 @@ enum WebCommand { kWaveRecords = 61, kWaveReceive = 62, kWaveSend = 63, - kFeatureSend = 64 -}; + kFeatureSend = 64, + //CMT TCP + kGateWayVersion = 80, + kSensorInfo = 81, + kSensorWave = 82, + KDownloadConfig = 83, + KUploadConfig = 84, + KUpgadeGateway = 85, + KUpgradeSensor = 86, + KEigenvalue = 87, + KUpgradeSensorStop = 88 +}; +enum GatewayType{ + kGWTDW2700 = 1, + + kGWTDG101 = 10, + kGWTDG102 = 11 +}; class LocalServer { public: LocalServer(); virtual ~LocalServer(); static void HandleFromServer(const char *pData, int pLen, const char *topic); static std::string HandleCgi_cmd(std::string &pData); + static void HandleTcp_cmd(const char* recvData,char* send_data,uint8_t& rescmd,int& reslength,int recvbody_length = 0); }; #endif // LOCAL_SERVER_HPP_ diff --git a/main.cpp b/main.cpp index 4689ec6..2b25772 100644 --- a/main.cpp +++ b/main.cpp @@ -132,7 +132,10 @@ int main(int argc, char *argv[]) { zlog_error(zbt, "internal error - lzo_init() failed !!!"); zlog_error(zbt, "(this usually indicates a compiler bug - try recompiling\nwithout optimizations, and enable '-DLZO_DEBUG' for diagnostics)"); } - + //启动CMT server + boost::thread startTcpCmt(attrs, StartCMTServer); + startTcpCmt.detach(); + int fd = OpenWatchDog(); int count = 0; while (GlobalConfig::QuitFlag_G) { diff --git a/platform/platform_init.cpp b/platform/platform_init.cpp index 96d0e1e..7279e23 100644 --- a/platform/platform_init.cpp +++ b/platform/platform_init.cpp @@ -79,22 +79,7 @@ void PlatformInit::Init() { strMac.insert(14, ":"); ModifyMac((char*)strMac.c_str()); } -#ifdef G2UL_GATEWAY - std::string strMac2 = sqlite_db_ctrl::instance().GetData("t_gateway_info", "MAC2", NULL); - if (strMac2 == "60294D208518") { - char szUpdateSql[100] = {0x00}; - sprintf(szUpdateSql, "MAC2 = '%s'", GlobalConfig::MacAddr_G2.c_str()); - sqlite_db_ctrl::instance().UpdateTableData("t_gateway_info", szUpdateSql, NULL); - } else if (strMac2 != GlobalConfig::MacAddr_G2) { - zlog_error(zbt, "MAC error strMac2 = %s,MacAddr_G2 = %s", strMac2.c_str(), GlobalConfig::MacAddr_G2.c_str()); - strMac2.insert(2, ":"); - strMac2.insert(5, ":"); - strMac2.insert(8, ":"); - strMac2.insert(11, ":"); - strMac2.insert(14, ":"); - ModifyMac((char*)strMac2.c_str()); - } -#endif + } catch (...) { zlog_error(zbt, "PlatFormInit exception happend."); std::string errorinfo = "系统初始化异常"; diff --git a/threadfunc/thread_func.cpp b/threadfunc/thread_func.cpp index 44d7c56..dd5173f 100644 --- a/threadfunc/thread_func.cpp +++ b/threadfunc/thread_func.cpp @@ -20,6 +20,7 @@ #include "utility/udp_scan.hpp" #include "utility/search_dev.hpp" #include "localserver/local_server.hpp" +#include "localserver/cmt_server.hpp" extern zlog_category_t *zct; extern zlog_category_t *zbt; @@ -27,6 +28,7 @@ static std::string serverPort; Dial dial; static int clean_memory = 0; +std::unique_ptr g_mgr_server; void StartCgiServer() { zlog_info(zbt, "start deal cgi"); @@ -46,6 +48,13 @@ void RunLED() { } } +void StartCMTServer() { + sleep(2); + boost::asio::io_service io_service; + g_mgr_server = std::make_unique(io_service, 10000); + io_service.run(); +} + void HeartRep() { int count = 0; while (1) { diff --git a/threadfunc/thread_func.hpp b/threadfunc/thread_func.hpp index d4e9454..a9c7b58 100644 --- a/threadfunc/thread_func.hpp +++ b/threadfunc/thread_func.hpp @@ -17,6 +17,7 @@ void CheckThread(); //循环检测线程 void StartMqttClient(); //启动mqtt服务 void SearchThread(); //组播功能, 提供发现设备功能 void StartCgiServer(); //启动cgi处理服务端 +void StartCMTServer(); void HeartRep(); void UartStart(); // void TestUart(); diff --git a/uart/uart.cpp b/uart/uart.cpp index 7b1a9f6..0dd6146 100644 --- a/uart/uart.cpp +++ b/uart/uart.cpp @@ -534,7 +534,13 @@ void Uart::DealRecvData(const char *pData) { DealUpgrade(ushortAdd,2); scheduler::instance().UpgradeResult(ushortAdd,0); zlog_info(zbt, "[UPGRADE SUCCESS] shortAdd = %02x%02x,command = %d,recvcode = %d ",UINT16_HIGH(ushortAdd),UINT16_LOW(ushortAdd),command,recvcode); - }else{ + }else if (recvcode == 5) + { + DealUpgrade(ushortAdd,2); + scheduler::instance().UpgradeResult(ushortAdd,0); + zlog_warn(zbt, "[UPGRADE ALREADY] shortAdd = %02x%02x,command = %d,recvcode = %d ",UINT16_HIGH(ushortAdd),UINT16_LOW(ushortAdd),command,recvcode); + }else + { DealUpgrade(ushortAdd,3); scheduler::instance().UpgradeResult(ushortAdd,recvcode); zlog_warn(zbt, "[UPGRADE FAILED] shortAdd = %02x%02x,command = %d,recvcode = %d ",UINT16_HIGH(ushortAdd),UINT16_LOW(ushortAdd),command,recvcode); @@ -1069,7 +1075,7 @@ int Uart::FindRecvPackage(int bytesRead, char *mUartRecvBuf, char *head) { strChannelID = strMeasurementID + "-Z"; } - sprintf(insertSql, "'%s','%s','%s',%d,'%d','%s' ", strMeasurementID.c_str(),strShortAddr.c_str(),localtimestamp,bytesRead,0,error_msg.c_str()); + sprintf(insertSql, "'%s','%s','%s',%d,'%d','%s' ", strChannelID.c_str(),strShortAddr.c_str(),localtimestamp,bytesRead,0,error_msg.c_str()); sqlite_db_ctrl::instance().InsertData(" receive_wave_status ", insertSql); JsonData jd; jd.JsonCmd_32(strMeasurementID,1,1,strChannelID,error_msg); @@ -1104,15 +1110,19 @@ int Uart::FindRecvPackage(int bytesRead, char *mUartRecvBuf, char *head) { memset(whereCon, 0x00, sizeof(whereCon)); if (command == WAVE_X){ error_msg = "Crc error,wave X"; + strChannelID = strMeasurementID + "-X"; }else if (command == WAVE_Y){ error_msg = "Crc error,wave Y"; + strChannelID = strMeasurementID + "-Y"; }else if (command == WAVE_Z){ error_msg = "Crc error,wave Z"; + strChannelID = strMeasurementID + "-Z"; } - sprintf(insertSql, "'%s','%s','%s',%d,'%d','%s' ", strMeasurementID.c_str(),strShortAddr.c_str(),localtimestamp,bytesRead,0,error_msg.c_str()); + sprintf(insertSql, "'%s','%s','%s',%d,'%d','%s' ", strChannelID.c_str(),strShortAddr.c_str(),localtimestamp,bytesRead,0,error_msg.c_str()); sqlite_db_ctrl::instance().InsertData(" receive_wave_status ", insertSql); JsonData jd; jd.JsonCmd_32(strMeasurementID,1,1,strChannelID,error_msg); + break; } mlastSize = 0; diff --git a/uart/uart.hpp b/uart/uart.hpp index cc7780a..25ca150 100644 --- a/uart/uart.hpp +++ b/uart/uart.hpp @@ -183,7 +183,7 @@ public: void DealWave(); std::vector DealData(int ichannel, float coe, unsigned int sampleRate, int ACCSampleTime, std::string strProduct); float Calcoe(int ran, int iChannel, std::string& product, int range); - void WriteDatFile(int sampleRate, std::string& strMeasurementID, int iChannel, std::vector& vecData, std::string strProduct,int ACCSampleTime); + void WriteDatFile(int sampleRate, std::string& strMeasurementID, int iChannel, std::vector& vecData,std::string &product,int ACCSampleTime); float ScaleConvert(int highbit); void DataExtract(RecvData *p, int id, unsigned int &lowbit, float &n); diff --git a/uart/uart_feature_parse.cpp b/uart/uart_feature_parse.cpp index 9cd81a7..2c1fd03 100644 --- a/uart/uart_feature_parse.cpp +++ b/uart/uart_feature_parse.cpp @@ -780,15 +780,29 @@ void Uart::DealWave() { wave_trans_ = false; return; } - if (m_waveCountX > 0 || m_waveCountY > 0 || m_waveCountZ > 0){ + if (m_waveCountX > 0 || m_waveCountY > 0 || m_waveCountZ > 0){ char localtimestamp[32] = {0}; GetTimeNet(localtimestamp, 1); char insertSql[100] = {0x00}; char whereCon[50] = {0x00}; sprintf(whereCon, "MeasurementID='%s'",strMeasurementID.c_str()); memset(whereCon, 0x00, sizeof(whereCon)); - sprintf(insertSql, "'%s','%02x%02x','%s',0,'1','%s' ", strMeasurementID.c_str(),(wave_shortAddr >> 8) & 0xFF,wave_shortAddr & 0xFF,localtimestamp,""); - sqlite_db_ctrl::instance().InsertData(" receive_wave_status ", insertSql); + if (m_waveCountX > 0) + { + sprintf(insertSql, "'%s-X','%02x%02x','%s',0,'1','%s' ", strMeasurementID.c_str(),(wave_shortAddr >> 8) & 0xFF,wave_shortAddr & 0xFF,localtimestamp,""); + sqlite_db_ctrl::instance().InsertData(" receive_wave_status ", insertSql); + } + if (m_waveCountY > 0) + { + sprintf(insertSql, "'%s-Y','%02x%02x','%s',0,'1','%s' ", strMeasurementID.c_str(),(wave_shortAddr >> 8) & 0xFF,wave_shortAddr & 0xFF,localtimestamp,""); + sqlite_db_ctrl::instance().InsertData(" receive_wave_status ", insertSql); + } + if (m_waveCountZ > 0) + { + sprintf(insertSql, "'%s-Z','%02x%02x','%s',0,'1','%s' ", strMeasurementID.c_str(),(wave_shortAddr >> 8) & 0xFF,wave_shortAddr & 0xFF,localtimestamp,""); + sqlite_db_ctrl::instance().InsertData(" receive_wave_status ", insertSql); + } + } std::string ran = ""; @@ -873,7 +887,7 @@ float Uart::Calcoe(int ran, int iChannel, std::string &product, int range) { return coe; } -void Uart::WriteDatFile(int sampleRate, std::string &strMeasurementID, int iChannel, std::vector &vecData, std::string product,int ACCSampleTime) { +void Uart::WriteDatFile(int sampleRate, std::string &strMeasurementID, int iChannel, std::vector &vecData,std::string &product,int ACCSampleTime) { if (vecData.size() <= 0) return; std::string strFileName = ""; char localtimestamp[32] = {0};