diff --git a/.autotools b/.autotools deleted file mode 100644 index a9fdb03..0000000 --- a/.autotools +++ /dev/null @@ -1,83 +0,0 @@ - - - - - - - diff --git a/.cproject b/.cproject deleted file mode 100644 index 32dc3ef..0000000 --- a/.cproject +++ /dev/null @@ -1,217 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - make - - all - true - true - true - - - make - - clear - true - true - true - - - - - diff --git a/.gitignore b/.gitignore index 6db035b..947c154 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,9 @@ -Debug/ -Release/ +*.o +etc/ +lib/ +*.d +*.mk +opt/ +cgi-bin/ +bin/ +GateWay/ diff --git a/.project b/.project deleted file mode 100644 index e525552..0000000 --- a/.project +++ /dev/null @@ -1,27 +0,0 @@ - - - WirelessGateway - - - - - - org.eclipse.cdt.managedbuilder.core.genmakebuilder - clean,full,incremental, - - - - - org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder - full,incremental, - - - - - - org.eclipse.cdt.core.cnature - org.eclipse.cdt.core.ccnature - org.eclipse.cdt.managedbuilder.core.managedBuildNature - org.eclipse.cdt.managedbuilder.core.ScannerConfigNature - - diff --git a/Cidn-SH b/Cidn-SH index 3b81064..565bf3f 100644 Binary files a/Cidn-SH and b/Cidn-SH differ diff --git a/common/SH_CommonFunc.cpp b/common/SH_CommonFunc.cpp index 8c957e3..700cdd6 100644 --- a/common/SH_CommonFunc.cpp +++ b/common/SH_CommonFunc.cpp @@ -216,6 +216,7 @@ void InitGpio(unsigned int gpioN,unsigned int inout) if(-1 == fd) { printf("[%s]:[%d] open gpio direction file error\r\n", __FUNCTION__, __LINE__); + close(fd); } if(inout == 0) @@ -285,7 +286,8 @@ int gpio_set(unsigned int gpioN,char x) fd = open(tmp, O_WRONLY); if(-1 == fd) { - print_red("[%s]:[%d] open gpio export file error\r\n", __FUNCTION__, __LINE__); + print_red("[%s]:[%d][%s] open gpio export file error\r\n", __FUNCTION__, __LINE__,tmp); + close(fd); return (-1);//exit(1); } //设置电平 @@ -452,16 +454,16 @@ int read_data(int fd, char *buff, int len, int timeout) FD_ZERO(&rdfds); FD_SET(fd, &rdfds); - // if (timeout > 0) { - // ret = select(fd+1, &rdfds, NULL, NULL, &to); - // if (ret <= 0) { - // // printf("zigbee doesn't respond!\n"); - // return ret; - // } - // } - if (ioctl(fd, FIONREAD, &len) == -1) { - return -1; - } + if (timeout > 0) { + ret = select(fd+1, &rdfds, NULL, NULL, &to); + if (ret <= 0) { + // printf("zigbee doesn't respond!\n"); + return ret; + } + } + // if (ioctl(fd, FIONREAD, &len) == -1) { + // return -1; + // } ret = read(fd,buff,len); if(ret < 0) { @@ -785,7 +787,7 @@ void ImportConfig(std::string filename) '%s','%s','%s','%s','%s','%s',\ '%s','%s','%s','%s','%s','%s','%s','%s',\ '%s','%s','%s','%s','%s',\ - '%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s'", + '%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s'", vecDataNode[0].c_str(),dataNodeName,vecDataNode[2].c_str(),vecDataNode[3].c_str(),vecDataNode[4].c_str(),\ vecDataNode[5].c_str(),vecDataNode[6].c_str(),vecDataNode[7].c_str(),vecDataNode[8].c_str(),vecDataNode[9].c_str(),\ vecDataNode[10].c_str(),vecDataNode[11].c_str(),vecDataNode[12].c_str(),vecDataNode[13].c_str(),vecDataNode[14].c_str(),\ @@ -794,7 +796,7 @@ void ImportConfig(std::string filename) vecDataNode[25].c_str(),vecDataNode[26].c_str(),vecDataNode[27].c_str(),vecDataNode[28].c_str(),vecDataNode[29].c_str(),\ vecDataNode[30].c_str(),vecDataNode[31].c_str(),vecDataNode[32].c_str(),vecDataNode[33].c_str(),vecDataNode[34].c_str(),\ vecDataNode[35].c_str(),vecDataNode[36].c_str(),vecDataNode[37].c_str(),vecDataNode[38].c_str(),vecDataNode[39].c_str(),\ - vecDataNode[40].c_str(),vecDataNode[41].c_str(),vecDataNode[42].c_str(),vecDataNode[43].c_str()); + vecDataNode[40].c_str(),vecDataNode[41].c_str(),vecDataNode[42].c_str(),vecDataNode[43].c_str(),vecDataNode[44].c_str()); sql_ctl->InsertData(T_SENSOR_INFO(TNAME), insertSql); } @@ -863,25 +865,28 @@ int UpdataDataNodeConfig(std::string filename) break; } dataNode.ZigbeeLongAddr = words[7]; - dataNode.FeatureInterVal = atoi(words[14].c_str()); - dataNode.WaveInterVal = atoi(words[15].c_str()); - dataNode.SamplingRate = atoi(words[16].c_str()); - print_info("words[17] = %s\n",words[17].c_str()); + dataNode.FeatureInterVal = atoi(words[16].c_str()); + dataNode.WaveInterVal = atoi(words[17].c_str()); + dataNode.SamplingRate = atoi(words[18].c_str()); + print_info("words[17] = %s\n",words[19].c_str()); - if(words[17].find("8g") != string::npos){ + if(words[19].find("8g") != string::npos){ dataNode.Range = 0; - }else if(words[17].find("16g") != string::npos){ + }else if(words[19].find("16g") != string::npos){ dataNode.Range = 1; - }else if(words[17].find("32g") != string::npos){ + }else if(words[19].find("32g") != string::npos){ dataNode.Range = 2; - }else if(words[17].find("64g") != string::npos){ + }else if(words[19].find("64g") != string::npos){ dataNode.Range = 3; - }else if(words[17].find("50g") != string::npos){ + }else if(words[19].find("50g") != string::npos){ dataNode.Range = 0; } - dataNode.ACCSampleTime = atoi(words[18].c_str()); - int update = atoi(words[20].c_str()); + dataNode.ACCSampleTime = atoi(words[20].c_str()); + dataNode.VIntegralFilterFrequency = atoi(words[21].c_str()); + dataNode.ZigbeePower = atoi(words[22].c_str()); + dataNode.ZigbeeRetry = atoi(words[23].c_str()); + int update = atoi(words[24].c_str()); if(update == 1) vecDataNode.push_back(dataNode); } @@ -892,9 +897,10 @@ int UpdataDataNodeConfig(std::string filename) char updateSql[1024] = { 0 }; if(vecDataNode.size() > 0){ for(int i = 0; i < vecDataNode.size();i++){ - sprintf(updateSql, "featureInterVal='%d',waveInterVal='%d',range='%d',samplingRate='%d',AccSampleTime = '%d',UpdateFlag = 0", + 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].SamplingRate,vecDataNode[i].ACCSampleTime,vecDataNode[i].VIntegralFilterFrequency,\ + vecDataNode[i].ZigbeePower,vecDataNode[i].ZigbeeRetry); sprintf(whereCon, "dataNodeNo='%s'", vecDataNode[i].ZigbeeLongAddr.c_str()); int iRet = sql_ctl->UpdateTableData(T_SENSOR_INFO(TNAME), updateSql, whereCon); @@ -1014,11 +1020,11 @@ std::string IpAddrInit() return strip; } strip = GetGwIp_(ETH1); - if (strip.compare("0.0.0.0") != 0) { + if (strip.compare("0.0.0.0") != 0 && strip.compare("192.168.188.188") != 0) { return strip; } strip = GetGwIp_(ETH2); - if (strip.compare("0.0.0.0") != 0) { + if (strip.compare("0.0.0.0") != 0 && strip.compare("192.168.188.188") != 0) { return strip; } strip = GetGwIp_(ETH0); @@ -1469,7 +1475,32 @@ std::string GetSysStatus() std::string strJson = fw.write(jsData); return strJson; } +// 将单个16进制字符转换为对应的字节值 +unsigned char hexCharToByte(char c) { + if (c >= '0' && c <= '9') return c - '0'; + if (c >= 'A' && c <= 'F') return c - 'A' + 10; + if (c >= 'a' && c <= 'f') return c - 'a' + 10; + return 0; // 对于无效的字符,返回0 +} +// 将16进制字符串转换为字节数组 +int hexStringToBytes(const char* hexStr, unsigned char* bytes, size_t bytesSize) { + size_t hexLen = strlen(hexStr); + if (hexLen % 2 != 0) { + return -1; // Hex字符串长度应该是偶数 + } + if (bytesSize < hexLen / 2) { + return -1; // 字节数组的大小不足以容纳转换后的字节 + } + + for (size_t i = 0; i < hexLen; i += 2) { + unsigned char highNibble = hexCharToByte(hexStr[i]); + unsigned char lowNibble = hexCharToByte(hexStr[i + 1]); + bytes[i / 2] = (highNibble << 4) | lowNibble; + } + + return 0; // 成功 +} void stringToHex(const char* str, char* hexStr) { while (*str) { sprintf(hexStr, "%02x", (unsigned char)*str); @@ -2461,7 +2492,38 @@ int get_netlink_status(const char *if_name) close(skfd); return edata.data; } +// 将版本号字符串拆分为整数组成的向量 +std::vector splitVersion(const std::string& version) { + std::vector parts; + std::stringstream ss(version); + std::string part; + + // 用点作为分隔符,分割版本号 + while (std::getline(ss, part, '.')) { + parts.push_back(std::stoi(part)); // 将分割后的部分转换为整数 + } + + return parts; +} +// 比较两个版本号 +int compareVersions(const std::string& version1, const std::string& version2) { + std::vector v1 = splitVersion(version1); + std::vector v2 = splitVersion(version2); + + // 找到最长的版本号部分长度 + size_t maxLength = std::max(v1.size(), v2.size()); + + for (size_t i = 0; i < maxLength; ++i) { + int num1 = i < v1.size() ? v1[i] : 0; // 如果某部分不存在,视为0 + int num2 = i < v2.size() ? v2[i] : 0; + + if (num1 > num2) return 1; // version1 大于 version2 + if (num1 < num2) return -1; // version1 小于 version2 + } + + return 0; // 版本号相同 +} static const char* JSON_FIELD_CMD = "cmd";//协议: 命令字段 static const char* JSON_FIELD_NAME = "dataWatchName";//协议: 终端名称 diff --git a/common/SH_CommonFunc.hpp b/common/SH_CommonFunc.hpp index 529590f..ac29d82 100644 --- a/common/SH_CommonFunc.hpp +++ b/common/SH_CommonFunc.hpp @@ -208,6 +208,9 @@ struct DataRecvStatic { float TemBot; int Dip; int Voltage; + float nodeWorkTime; + float nodeSendTime; + }; struct DataRecvDym { @@ -379,6 +382,7 @@ struct Param_10 { std::string straxis; std::string timeStart; std::string timeEnd; + std::string MeasurementID; int mPackageFlag; Param_10():strDataNode(""),strStatic(""),mPackageFlag(0){}; }; @@ -438,7 +442,9 @@ struct Param_40 { Param_40():mMode(0),mChannelId(""),mDataNodeNo(""),mPackageFlag(0),StartFrequency(0),EndFrequency(0){}; }; struct Param_41 { + std::string mdataNodeName; std::string mdataNodeNo; + std::string mMeasurementID; int mfeatureInterVal; int mwaveInterVal; int msamplingRate; @@ -449,8 +455,10 @@ struct Param_41 { std::string menvelopeBandPass; int mviff; std::string mfaultFrequency; - Param_41():mdataNodeNo(""),mfeatureInterVal(0),mwaveInterVal(0),msamplingRate(0),mrange(0),mAccSampleTime(0),\ - mstartBrands(""),mstopBrands(""),menvelopeBandPass(""),mviff(0),mfaultFrequency(""){}; + int ZigbeePower; + int ZigbeeRetry; + Param_41():mdataNodeName(""),mdataNodeNo(""),mfeatureInterVal(0),mwaveInterVal(0),msamplingRate(0),mrange(0),mAccSampleTime(0),\ + mstartBrands(""),mstopBrands(""),menvelopeBandPass(""),mviff(0),mfaultFrequency(""),mMeasurementID{""}{}; }; struct Param_42 { string fileName; @@ -748,6 +756,7 @@ extern void ImportConfig(std::string filename); extern int UpdataDataNodeConfig(std::string filename); extern char* solve(char *dest,const char *src); extern void swap(char *data); +extern int hexStringToBytes(const char* hexStr, unsigned char* bytes, size_t bytesSize); extern int OpenWatchDog(); extern int WriteWatchDog(int fd); @@ -777,5 +786,6 @@ int socketHeart(const char* pSendData); extern bool NetIsOk(); extern int Ping( const char *ips, int timeout); extern int get_netlink_status(const char *if_name); +extern int compareVersions(const std::string& version1, const std::string& version2); extern Mutex g_tDbMutex; #endif diff --git a/common/SH_global.h b/common/SH_global.h index f6ded1f..e893d95 100644 --- a/common/SH_global.h +++ b/common/SH_global.h @@ -74,8 +74,8 @@ public : #define WHITE "\033[1;37m" #ifdef IMX6UL_GATEWAY -#define SAVE_COUNT 2058 //2058,4800 -#define OneWeek 259359//259359,604800 +#define SAVE_COUNT 2592 +#define OneWeek 259359 #endif #ifdef G2UL_GATEWAY #define SAVE_COUNT 4800*4 diff --git a/dbaccess/SH_SqlDB.cpp b/dbaccess/SH_SqlDB.cpp index ec1fc33..b4b29db 100644 --- a/dbaccess/SH_SqlDB.cpp +++ b/dbaccess/SH_SqlDB.cpp @@ -87,6 +87,17 @@ void SqliteDB::SqliteInit(const char *pDbName, bool isDB2) if(iRet == 0){ CreateTable("ALTER TABLE t_sensor_info ADD COLUMN 'batteryPower'"); } + iRet = GetTableRows(" sqlite_master "," name = 't_sensor_info' and sql LIKE '%MeasurementID%' "); + if(iRet == 0){ + CreateTable("ALTER TABLE t_sensor_info ADD COLUMN 'MeasurementID'"); + } + + memset(sql_exec, 0, 2048); + sprintf(sql_exec,"update t_sensor_info set MeasurementID = dataNodeNo where MeasurementID IS NULL ;"); + UpdateTableData(sql_exec,isDB2); + memset(sql_exec, 0, 2048); + sprintf(sql_exec,"update t_sensor_info set MeasurementID = dataNodeNo where MeasurementID = '' ;"); + UpdateTableData(sql_exec,isDB2); //创建传感器数据存储表 memset(sql_exec, 0, 2048); @@ -174,6 +185,20 @@ void SqliteDB::SqliteInit(const char *pDbName, bool isDB2) if(iRet == 0){ CreateTable("ALTER TABLE t_data_waveSend ADD COLUMN 'save'"); } + + memset(sql_exec, 0, 2048); + sprintf(sql_exec, "create table if not exists %s(%s,%s,%s,%s,%s,%s,%s,%s,%s);", + T_BATTERY_INFO(TNAME), + T_BATTERY_INFO(DATANODENO), + T_BATTERY_INFO(DIP), + T_BATTERY_INFO(TEMBOT), + T_BATTERY_INFO(NODEWORKTIME), + T_BATTERY_INFO(NODESENDTIME), + T_BATTERY_INFO(BATTERYVOLTAGE), + T_BATTERY_INFO(BATTERYUSAGE), + T_BATTERY_INFO(BATTERYREMAIN), + T_BATTERY_INFO(TIMESTAMP)); + CreateTable(sql_exec, isDB2); /*memset(sql_exec, 0, 2048); sprintf(sql_exec, "create table if not exists %s(%s,%s,%s,%s,%s integer,%s integer ,%s integer ,%s integer,%s integer);", @@ -346,10 +371,12 @@ int SqliteDB::GetTableColumnCount(const char *tablename, bool isDB2) sqlite3_stmt *stmt; strSql = strSql + tablename + ";"; print_light_green("%s\n", strSql.c_str()); + g_tDbMutex.Lock(); // if (SqlSwitch()) log_system->log_write_system("[info]","%s\n", strSql.c_str()); sqlite3_prepare_v2(GetDbHandle(isDB2), strSql.c_str(), -1, &stmt, 0); count = sqlite3_column_count(stmt); sqlite3_finalize(stmt); + g_tDbMutex.UnLock(); return count; } @@ -366,6 +393,7 @@ int SqliteDB::GetTableRows(const char *tablename, const char *whereCon) print_light_green("%s\n", strSql.c_str()); // if (SqlSwitch()) log_system->log_write_system("[info]","%s\n", strSql.c_str()); sqlite3_stmt *stmt; + g_tDbMutex.Lock(); if (sqlite3_prepare_v2(mDBAcess, strSql.c_str(), -1, &stmt, 0) != SQLITE_OK) { print_error("sqlite3_prepare_v2:%s\n",sqlite3_errmsg(mDBAcess)); sqlite3_finalize(stmt); @@ -376,6 +404,7 @@ int SqliteDB::GetTableRows(const char *tablename, const char *whereCon) nRow = sqlite3_column_int(stmt, 0); } sqlite3_finalize(stmt); + g_tDbMutex.UnLock(); return nRow; } @@ -410,9 +439,11 @@ vec_t SqliteDB::GetDataSingleLine(const char *tablename, const char *column, con print_light_green("%s\n", strSql.c_str()); // if (SqlSwitch()) log_system->log_write_system("[info]","%s\n", strSql.c_str()); sqlite3_stmt *stmt; + g_tDbMutex.Lock(); if (sqlite3_prepare_v2(mDBAcess, strSql.c_str(), -1, &stmt, 0) != SQLITE_OK) { print_error("sqlite3_prepare_v2:%s\n", sqlite3_errmsg(mDBAcess)); sqlite3_finalize(stmt); + g_tDbMutex.UnLock(); return vecResult; } int retStep = sqlite3_step(stmt); @@ -425,6 +456,7 @@ vec_t SqliteDB::GetDataSingleLine(const char *tablename, const char *column, con } } sqlite3_finalize(stmt); + g_tDbMutex.UnLock(); return vecResult; } @@ -534,12 +566,13 @@ array_t SqliteDB::GetDataMultiLineTransaction(const char *tablename, const char } print_light_green("%s\n", strSql.c_str()); // if (SqlSwitch()) log_system->log_write_system("[info]","%s\n", strSql.c_str()); - + g_tDbMutex.Lock(); sqlite3_exec(mDBAcess, "BEGIN", 0, 0, NULL); sqlite3_stmt *stmt; if (sqlite3_prepare_v2(mDBAcess, strSql.c_str(), -1, &stmt, 0) != SQLITE_OK) { print_error("sqlite3_prepare_v2:%s\n", sqlite3_errmsg(mDBAcess)); sqlite3_finalize(stmt); + g_tDbMutex.UnLock(); return arrResult; } sqlite3_reset(stmt); @@ -558,6 +591,7 @@ array_t SqliteDB::GetDataMultiLineTransaction(const char *tablename, const char } sqlite3_finalize(stmt); sqlite3_exec(mDBAcess, "COMMIT", 0, 0, NULL); + g_tDbMutex.UnLock(); return arrResult; } vec_t SqliteDB::GetDataMultiLineOfOneColumn(const char *tablename, const char *column, const char *whereCon) @@ -679,12 +713,14 @@ int SqliteDB::UpdateNodeNameData(const char* tablename, const char* updateColumn print_light_green("%s\n", strSql.c_str()); // if (SqlSwitch()) log_system->log_write_system("[info]","%s\n", strSql.c_str()); char *msg; + g_tDbMutex.Lock(); int iRet = sqlite3_exec(GetDbHandle(isDB2), szSql, 0, 0, &msg); if (iRet != SQLITE_OK) { print_error("sqlite3 error: code=%d msg=%s\n", iRet, msg); sqlite3_free(msg); } + g_tDbMutex.UnLock(); return iRet; } int SqliteDB::UpdateTableData(const char* tablename, const char* updateColumn, const char* whereCond, bool isDB2) @@ -715,8 +751,9 @@ int SqliteDB::UpdateTableData(const char* directSql, bool isDB2) print_light_green("%s\n", directSql); // if (SqlSwitch()) log_system->log_write_system("[info]","%s\n", directSql); char *msg; + g_tDbMutex.Lock(); int iRet = sqlite3_exec(GetDbHandle(isDB2), directSql, 0, 0, &msg); - + g_tDbMutex.UnLock(); if (iRet != SQLITE_OK) { print_error("sqlite3 error: code=%d msg=%s\n", iRet, msg); sqlite3_free(msg); @@ -736,8 +773,9 @@ int SqliteDB::UpdateTableDataOneColumn(const char* tablename, const char* column print_light_green("%s\n", strSql.c_str()); // if (SqlSwitch()) log_system->log_write_system("[info]","%s\n", strSql.c_str()); char *msg; + g_tDbMutex.Lock(); int iRet = sqlite3_exec(GetDbHandle(isDB2), strSql.c_str(), 0, 0, &msg); - + g_tDbMutex.UnLock(); if (iRet != SQLITE_OK) { print_error("sqlite3 error: code=%d msg=%s\n", iRet, msg); sqlite3_free(msg); @@ -749,6 +787,7 @@ int SqliteDB::InsertData(const char* tablename, const char* insertValues, int re { char *msg; int iRet = 0; + g_tDbMutex.Lock(); if (expandable) { char *strSql = (char *)malloc(4096); if (strSql == NULL) { @@ -780,21 +819,154 @@ int SqliteDB::InsertData(const char* tablename, const char* insertValues, int re print_error("sqlite3 error: code=%d msg=%s\n", iRet, msg); sqlite3_free(msg); } + g_tDbMutex.UnLock(); return iRet; } int SqliteDB::InsertData(const char* insertSql) { char *msg; + g_tDbMutex.Lock(); int iRet = sqlite3_exec(GetDbHandle(false), insertSql, 0, 0, &msg); if (iRet != SQLITE_OK) { print_error("sqlite3 error: code=%d msg=%s\n", iRet, msg); sqlite3_free(msg); } + g_tDbMutex.UnLock(); return iRet; } int SqliteDB::CalculateBattery() { - float dayStaticPower = 6.5,dayWavePower = 237;// + LOG_INFO("CalculateBattery start\n"); + char whereCon[1024] = {0}; + char selectSql[1024] = { 0 }; + memset(whereCon,0x00,sizeof(whereCon)); + memset(selectSql,0x00,sizeof(selectSql)); + char updateSql[1024] = { 0 }; + sprintf(selectSql," dataNodeNo,StaticTime,WaveTime,featureInterVal,waveInterVal,samplingRate,batteryPower "); + array_t vecRes = GetDataMultiLine(T_SENSOR_INFO(TNAME), selectSql, NULL); + print_info("res = %d\n",vecRes.size()); + if(vecRes.size() > 0){ + for(int i = 0; i < vecRes.size(); i++){ + float capacity = 0.0,startCapacity = 0.0; + memset(whereCon,0x00,sizeof(whereCon)); + memset(selectSql,0x00,sizeof(selectSql)); + sprintf(whereCon," dataNodeNo = '%s' and batteryRemain <> '' order by timeStamp desc limit 0,1 ",vecRes[i][0].c_str()); + vec_t vecResSig = sql_ctl->GetDataSingleLine(T_BATTERY_INFO(TNAME)," * ",whereCon); + vector vParam; + boost::split( vParam, vecRes[i][6], boost::is_any_of( "," ), boost::token_compress_on ); + if(vecResSig.size() <= 0 || vParam[0] == ""){//第一次计算 + memset(whereCon,0x00,sizeof(whereCon)); + sprintf(whereCon,"dataNodeNo = '%s' ",vecRes[i][0].c_str()); + string Dip = sql_ctl->GetData(T_DATASTATIC_INFO(TNAME)," dip ",whereCon); + if(Dip == ""){ + continue; + } + capacity = (0.9+0.1*(90-atoi(Dip.c_str()))/90)*19000;//mAh //电池总量 + startCapacity = capacity; + + sprintf(updateSql,"batteryPower = '%f,%f' ",startCapacity,startCapacity); + + int iRet = UpdateTableData(T_SENSOR_INFO(TNAME), updateSql, whereCon); + memset(whereCon,0x00,sizeof(whereCon)); + sprintf(whereCon," dataNodeNo = '%s' order by timeStamp asc limit 0,1 ",vecRes[i][0].c_str()); + vecResSig = sql_ctl->GetDataSingleLine(T_BATTERY_INFO(TNAME)," * ",whereCon); + if(vecResSig.size() <= 0){//一条数据都没有 + + continue; + } + + }else{ + capacity = atof(vecResSig[7].c_str()); + } + + print_info("dip = %d\n",atoi(vecResSig[1].c_str())); + + print_info("capacity = %f\n",capacity); + sprintf(whereCon," dataNodeNo = '%s' and timeStamp > '%s'",vecRes[i][0].c_str(),vecResSig[8].c_str()); + array_t vecResbattery = GetDataMultiLine(T_BATTERY_INFO(TNAME), " * ", whereCon); + print_info("vecResbattery size = %d\n",vecResbattery.size()); + if(vecResbattery.size() <= 0){ + continue; + } + int y10_mins = 10 * 365 * 24 * 60; + int d200_mins = 200 * 24 * 60; + int x1 = 25,x2 = 60; + int y1 = 2; + float y2 = (float)y10_mins/(float)d200_mins; + + float k = (y2-y1)/(x2-x1); + vector vecb; + vector vecworkTime; + vector vecsendTime; + float to_math = 0.0; + print_info("vecResbattery = %d,temp = %s\n",vecResbattery.size(),vecResbattery[0][2].c_str()); + //LOG_INFO("vecResbattery = %d,temp = %s\n",vecResbattery.size(),vecResbattery[0][2].c_str()); + for (size_t j = 0; j < vecResbattery.size(); j++) + { + float b = 2 - 25 * k; + float dpm = k * atoi(vecResbattery[j][2].c_str()) + b;//温度 + float cost_e = dpm * atoi(vecRes[i][3].c_str());//特征值时间间隔 + float cost_h = cost_e / 60; + vecworkTime.push_back(atol(vecResbattery[j][3].c_str())); + vecsendTime.push_back(atol(vecResbattery[j][4].c_str())); + to_math += cost_h; + } + + print_info("自放电 = %f\n",to_math); + //LOG_INFO("自放电 = %f\n",to_math); + long sumworkTime = 0.0,sumsendTime = 0.0; + for(size_t j = 0 ; j < vecworkTime.size();j++) + { + sumworkTime += vecworkTime[j]; + } + for(size_t j = 0 ; j < vecsendTime.size();j++) + { + sumsendTime += vecsendTime[j]; + } + print_info("sumworkTime = %ld,sumsendTime = %ld\n",sumworkTime,sumsendTime); + //LOG_INFO("sumworkTime = %ld,sumsendTime = %ld\n",sumworkTime,sumsendTime); + float usageworkTime = ((float)sumworkTime/3600000) * 4; + float usagesendTime = ((float)sumsendTime/3600000) * 39; + print_info("work = %f,send = %f\n",usageworkTime,usagesendTime); + //LOG_INFO("work = %f,send = %f\n",usageworkTime,usagesendTime); + if(to_math < 0) + to_math = 0; + float usageBattery = usageworkTime + usagesendTime + to_math; + print_info("已经使用 = %f\n",atof(vecResSig[6].c_str())); + + float remainBattery = capacity - usageBattery * 0.2; + LOG_INFO("dataNodeNo = %s,已经使用 = %f,剩余电量 = %f\n",vecRes[i][0].c_str(),atof(vecResSig[6].c_str()),remainBattery); + memset(whereCon,0x00,sizeof(whereCon)); + sprintf(whereCon," dataNodeNo = '%s' order by timeStamp desc limit 0,1 ",vecRes[i][0].c_str()); + string strtimeStamp = sql_ctl->GetData(T_BATTERY_INFO(TNAME)," timeStamp ",whereCon); + + sprintf(updateSql, "batteryUsage='%f',batteryRemain='%f'",usageBattery,remainBattery); + memset(whereCon,0x00,sizeof(whereCon)); + sprintf(whereCon, "dataNodeNo ='%s' and timeStamp = '%s'", vecRes[i][0].c_str(),strtimeStamp.c_str()); + sql_ctl->UpdateTableData(T_BATTERY_INFO(TNAME), updateSql, whereCon); + + memset(whereCon,0x00,sizeof(whereCon)); + memset(updateSql,0x00,sizeof(updateSql)); + + + sprintf(whereCon,"dataNodeNo = '%s' ",vecRes[i][0].c_str()); + if(startCapacity > 0){ + sprintf(updateSql,"batteryPower = '%f,%f' ",startCapacity,remainBattery); + }else{ + sprintf(updateSql,"batteryPower = '%s,%f' ",vParam[0].c_str(),remainBattery); + } + + int iRet = UpdateTableData(T_SENSOR_INFO(TNAME), updateSql, whereCon); + string strData = sql_ctl->GetNodeConfigureInfor(whereCon); + data_publish(strData.c_str(), GlobalConfig::Topic_G.mPubConfig.c_str()); + } + } + LOG_INFO("CalculateBattery end\n"); + + + + + /*float dayStaticPower = 6.5,dayWavePower = 237;// char whereCon[1024] = {0}; char selectSql[1024] = { 0 }; memset(whereCon,0x00,sizeof(whereCon)); @@ -839,7 +1011,7 @@ int SqliteDB::CalculateBattery() string strData = sql_ctl->GetNodeConfigureInfor(whereCon); data_publish(strData.c_str(), GlobalConfig::Topic_G.mPubConfig.c_str()); } - } + }*/ print_info("CalculateBattery \n"); return 0; @@ -858,7 +1030,7 @@ int SqliteDB::CalculateDip() GetTimeNet(localtimestamp, 1); readStringValue("config", "loose",looseValue,(char*)GlobalConfig::Config_G.c_str()); vecRes = GetDataMultiLine(T_SENSOR_INFO(TNAME), " * ", NULL); - print_info("vecRes = %d\n",vecRes.size()); + print_info("vecRes111 = %d\n",vecRes.size()); for(int i = 0 ; i < vecRes.size(); i++){ vector vParam; print_info("vecRes =%s\n",vecRes[i][42].c_str()); @@ -900,9 +1072,9 @@ int SqliteDB::CalculateDip() }else if(vParam[1] == "2"){ print_info("localtimestamp = %ld,vParam[2]=%d,%ld\n",atol(localtimestamp),atol(vParam[2].c_str()),atol(localtimestamp) - atol(vParam[2].c_str())); if(atol(localtimestamp) - atol(vParam[2].c_str()) > 86400){ - sprintf(updateSql,"LooseValue = '%f,0' ",vParam[0].c_str()); + sprintf(updateSql,"LooseValue = '%f,0' ",atof(vParam[0].c_str())); }else{ - sprintf(updateSql,"LooseValue = '%f,2,",vParam[0].c_str()); + sprintf(updateSql,"LooseValue = '%f,2,",atof(vParam[0].c_str())); string strUpdateSql = string(updateSql) + vParam[2] + "' " ; memset(updateSql,0x00,sizeof(updateSql)); memcpy(updateSql,strUpdateSql.c_str(),sizeof(updateSql)); @@ -917,6 +1089,7 @@ int SqliteDB::CalculateDip() UpdateTableData(T_SENSOR_INFO(TNAME),updateSql,whereCon); } + print_info("CalculateDip \n"); } int SqliteDB::InintGateway() { @@ -989,7 +1162,6 @@ int SqliteDB::InintGateway() std::string SqliteDB::GetNodeConfigureInfor(const char* whereCon) { vec_t vecRes = GetDataSingleLine(T_SENSOR_INFO(TNAME), "*", whereCon); - printf("vecRes = %d\n",vecRes.size()); if(vecRes.size() < 1) return ""; Json::Value jsSensorData; @@ -997,7 +1169,7 @@ std::string SqliteDB::GetNodeConfigureInfor(const char* whereCon) jsonVal.clear(); jsonVal["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G; jsonVal["cmd"] = "26"; - jsSensorData["dataNodeNo"] = vecRes[0]; + jsSensorData["dataNodeNo"] = vecRes[44]; jsSensorData["dataNodeName"] = vecRes[1]; jsSensorData["initFlag"] = atoi(vecRes[2].c_str()); jsSensorData["accFlag"] = atoi(vecRes[3].c_str()); @@ -1040,6 +1212,7 @@ std::string SqliteDB::GetNodeConfigureInfor(const char* whereCon) jsSensorData["LooseValue"] = (vecRes[42].c_str()); jsSensorData["batteryPower"] = (vecRes[43].c_str()); + Json::FastWriter showValue; Json::Value jsBody; jsBody["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G; @@ -1051,18 +1224,18 @@ std::string SqliteDB::GetNodeConfigureInfor(const char* whereCon) int SqliteDB::QueryofflineData() { - vec_t vecRet = GetDataMultiLineOfOneColumn(T_SENSOR_INFO(TNAME),T_SENSOR_INFO(DATANODENO),NULL); - for(int i = 0; i < vecRet.size();i++){ + array_t arrRetdataNode = GetDataMultiLine(T_SENSOR_INFO(TNAME)," dataNodeNo,MeasurementID ",NULL); + for(int i = 0; i < arrRetdataNode.size();i++){ char StaticTableName[50]={0x00}; - sprintf(StaticTableName,"t_dataStatic_%s",vecRet[i].c_str()); + sprintf(StaticTableName,"t_dataStatic_%s",arrRetdataNode[i][0].c_str()); array_t arrRetData = GetDataMultiLine(StaticTableName, "*","sendMsg = '0' order by timeStamp asc"); - LOG_INFO("mqttresend check datanodeNo %s,data count %d\n",vecRet[i].c_str(),arrRetData.size()); + LOG_INFO("mqttresend check datanodeNo %s,data count %d\n",arrRetdataNode[i][0].c_str(),arrRetData.size()); if(arrRetData.size() < 1) continue; for(int j = 0; j < arrRetData.size();j++){ char dataTableName[50]={0x00}; - sprintf(dataTableName,"t_data_%s",vecRet[i].c_str()); + sprintf(dataTableName,"t_data_%s",arrRetdataNode[i][0].c_str()); char tmpWhere[128]={0x00}; sprintf(tmpWhere,"sendMsg = '0' and timeStamp = '%s'",arrRetData[j][8].c_str()); array_t arrRet = GetDataMultiLine(dataTableName, "*","sendMsg = '0'"); @@ -1071,7 +1244,7 @@ int SqliteDB::QueryofflineData() Json::Value valNodeFeature; for(int k = 0; k < arrRet.size();k++){ - valNodeFeature["dataNodeNo"] = arrRet[k][0].c_str(); + valNodeFeature["dataNodeNo"] = arrRetdataNode[i][1].c_str(); valNodeFeature["ChannelId"] = arrRet[k][1].c_str(); valNodeFeature["diagnosisPk"] = atof(arrRet[k][2].c_str()); valNodeFeature["integratPk"] = atof(arrRet[k][3].c_str()); @@ -1108,7 +1281,7 @@ int SqliteDB::QueryofflineData() root["data"] = valNodeData; root["TimeStamp"] = atoi(arrRetData[j][8].c_str()); - root["dataNodeNo"] = arrRetData[j][0].c_str(); + root["dataNodeNo"] = arrRetdataNode[i][1].c_str(); root["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G; root["status"] = "resend"; Json::FastWriter featureValue; @@ -1163,7 +1336,7 @@ int SqliteDB::QueryofflineData() int length = strWaveData.length(); valWaveData["number"] = length; valWaveData["channelId"] = arrRetData[i][0]; - valWaveData["dataNodeNo"] = arrRetData[i][0]; + valWaveData["dataNodeNo"] = arrRetData[i][0].substr(0,arrRetData[i][0].length()-2); valWaveData["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G; valWaveData["SensorEngineeringUnit"] = ""; valWaveData["timeStamp"] = arrRetData[i][2]; diff --git a/dbaccess/SH_SqlDB.hpp b/dbaccess/SH_SqlDB.hpp index 1b5bb88..b7b2f79 100644 --- a/dbaccess/SH_SqlDB.hpp +++ b/dbaccess/SH_SqlDB.hpp @@ -16,7 +16,7 @@ extern "C"{ #define T_DATASTATIC_INFO(x) T_DATASTATIC_INFO[T_DATASTATIC_INFO_##x] #define T_GATEWAY_INFO(x) T_GATEWAY_INFO[T_GATEWAY_INFO_##x] #define T_DATANODE_TIME(x) T_DATANODE_TIME[T_DATANODE_TIME_##x] -#define T_BATTERY_INFO(x) T_BATTERY_INFO[T_BATTERY_INFO##x] +#define T_BATTERY_INFO(x) T_BATTERY_INFO[T_BATTERY_INFO_##x] typedef std::map map_t; typedef std::vector vec_t; @@ -184,5 +184,18 @@ typedef enum { }T_GATEWAY_INFO_Index; const static char* T_GATEWAY_INFO[] = { "t_gateway_info","gatewayMAC","sensorVersion","gatewayLocation","zigbeePanID","zigbeeChannel","communicationType","signal","localIP","systemVersion","programVersion","webVersion","serverIP","serverPort","status","gateWayUpdate","MAC2"}; - +typedef enum { + T_BATTERY_INFO_TNAME = 0, + T_BATTERY_INFO_DATANODENO, + T_BATTERY_INFO_DIP, + T_BATTERY_INFO_TEMBOT, + T_BATTERY_INFO_NODEWORKTIME, + T_BATTERY_INFO_NODESENDTIME, + T_BATTERY_INFO_BATTERYVOLTAGE, + T_BATTERY_INFO_BATTERYUSAGE, + T_BATTERY_INFO_BATTERYREMAIN, + T_BATTERY_INFO_TIMESTAMP + +}T_BATTERY_INFO_Index; +const static char* T_BATTERY_INFO[] = { "t_battery_info","dataNodeNo","Dip","temBot","nodeWorkTime","nodeSendTime","batteryVoltage","batteryUsage","batteryRemain","timeStamp"}; #endif diff --git a/jsonparse/SH_JsonCmd.cpp b/jsonparse/SH_JsonCmd.cpp index 3554ff2..f1d9093 100644 --- a/jsonparse/SH_JsonCmd.cpp +++ b/jsonparse/SH_JsonCmd.cpp @@ -3,7 +3,6 @@ #include "../platform/SH_PlatformInit.hpp" #include "../MD5/md5.h" - namespace{ PlatformInit *platform = PlatformInit::instance(); Calculation *pCalculation = Calculation::instance(); @@ -174,7 +173,9 @@ std::string JsonData::JsonCmd_25(Param_25 ¶m) bFlag4 = true; } print_info("bFlag1 = %d,bFlag2 = %d,bFlag3 = %d,bFlag4 = %d\n",bFlag1,bFlag2,bFlag3,bFlag4); - +#ifdef IMX6UL_GATEWAY + param.mNet = "Net"; +#endif if (0 == param.mMode &&(bFlag1 && bFlag2 && bFlag3 && bFlag4) && param.mNetworkPortStatus == "STATIC") { WriteStr2Config(NETWORKCONFIG, param.mNet, "dnsName", param.mDnsName); WriteStr2Config(NETWORKCONFIG, param.mNet, "networkPortStatus", param.mNetworkPortStatus); @@ -234,7 +235,7 @@ std::string JsonData::JsonCmd_26(Param_26 ¶m) if (iResult > 0) { for (int j = 0; j < iResult; j++) { Json::Value jsSensorData; - jsSensorData["dataNodeNo"] = arrRes[j][0]; + jsSensorData["dataNodeNo"] = arrRes[j][44]; jsSensorData["dataNodeName"] = arrRes[j][1]; jsSensorData["initFlag"] = atoi(arrRes[j][2].c_str()); jsSensorData["accFlag"] = atoi(arrRes[j][3].c_str()); @@ -276,6 +277,7 @@ std::string JsonData::JsonCmd_26(Param_26 ¶m) jsSensorData["viff"] = atoi(arrRes[j][39].c_str()); jsSensorData["RSSI"] = atoi(arrRes[j][40].c_str()); jsSensorData["Update"] = atoi(arrRes[j][41].c_str()); + jsSensorData["Update"] = atoi(arrRes[j][41].c_str()); jsArray.append(jsSensorData); } } else { @@ -308,7 +310,7 @@ std::string JsonData::JsonCmd_27(Json::Value & recvBody) if (nSize > 0) { for (int i = 0; i < nSize; i++) { char whereCon[128] = { 0 }; - sprintf(whereCon, "%s= '%s'", T_SENSOR_INFO(DATANODENO), recvBody["dataNodeArray"][i].asString().c_str()); + sprintf(whereCon, "%s= '%s'", "MeasurementID", recvBody["dataNodeArray"][i].asString().c_str()); sql_ctl->DeleteTableData(T_SENSOR_INFO(TNAME), whereCon); sql_ctl->DeleteTableData(T_DATA_INFO(TNAME), whereCon); sql_ctl->DeleteTableData(T_DATASTATIC_INFO(TNAME), whereCon); @@ -383,7 +385,7 @@ std::string JsonData::JsonCmd_51(Json::Value & recvBody) std::string DataNodeNo = recvBody["dataNodeNo"].asString(); std::string DataNodeName = recvBody["dataNodeName"].asString(); char szSql[100]={0x00}; - sprintf(szSql,"update %s set dataNodeName = '%s' where dataNodeNo = '%s' ",T_SENSOR_INFO(TNAME),\ + sprintf(szSql,"update %s set dataNodeName = '%s' where MeasurementID = '%s' ",T_SENSOR_INFO(TNAME),\ DataNodeName.c_str(),DataNodeNo.c_str()); int iRet = sql_ctl->UpdateTableData(szSql); if(iRet != 0){ @@ -566,7 +568,8 @@ void JsonData::DataNodeStatusCheck() if (nSize > 0) { for (int i = 0; i < nSize; i++) { std::string strDataNodeNo = vetRes[i][0]; - std::string strChannelId= strDataNodeNo + "-X"; + std::string strMeasurementID = vetRes[i][44]; + std::string strChannelId = strMeasurementID + "-X"; char whereCon[512] = {0x00},tablename[128]={0x00}; sprintf(whereCon, "dataNodeNo='%s' and channelID='%s' ORDER BY timeStamp DESC LIMIT 0,1", strDataNodeNo.c_str(), strChannelId.c_str()); sprintf(tablename,"t_data_%s",strDataNodeNo.c_str()); @@ -742,136 +745,133 @@ std::string JsonData::JsonCmd_Cgi_08() std::string JsonData::JsonCmd_Cgi_09(Param_09 ¶m) { + //LOG_INFO("09 start\n"); Json::Value jsonVal; - jsonVal.clear(); + jsonVal.clear(); - jsonVal[JSON_FIELD_CMD] = "09"; - jsonVal["success"] = true; - jsonVal["message"] = " "; + jsonVal[JSON_FIELD_CMD] = "09"; + jsonVal["success"] = true; + jsonVal["message"] = " "; - char localtimestamp[32] = { 0 }; - GetTimeNet(localtimestamp, 1); - std::string nowTimetamp = std::string(localtimestamp); - char looseValue[10]={0x00}; - readStringValue("config", "loose",looseValue,(char*)GlobalConfig::Config_G.c_str()); + char localtimestamp[32] = { 0 }; + GetTimeNet(localtimestamp, 1); + std::string nowTimetamp = std::string(localtimestamp); + char looseValue[10]={0x00}; + readStringValue("config", "loose",looseValue,(char*)GlobalConfig::Config_G.c_str()); - vec_t vetRes = sql_ctl->GetDataMultiLineOfOneColumn(T_SENSOR_INFO(TNAME), T_SENSOR_INFO(DATANODENO), NULL); - int nSize = vetRes.size(); - if (nSize > 0) { - int packgeNo = param.mPackageFlag; - int packgeMax = 0; - int packgeNum = 0; - jsonVal["package"] = packgeNo; - int lastSize = nSize % 10; - int index = nSize / 10; - if(lastSize > 0 && index > 0){ - packgeMax = index +1; - if(packgeNo +1 == packgeMax){ - packgeNum = nSize; - jsonVal["packageMax"] = index + 1; - } - else{ - packgeNum = (packgeNo+1) * 10; - jsonVal["packageMax"] = index +1; - } - } - else if(lastSize == 0 && index > 0){ - packgeNum = (packgeNo+1) * 10; - packgeMax = index; - jsonVal["packageMax"] = index; - }else if(lastSize > 0 && index == 0){ - packgeNum = lastSize; - packgeMax = index+1; - jsonVal["packageMax"] = index+1; - } + array_t arrResAll = sql_ctl->GetDataMultiLine(T_SENSOR_INFO(TNAME), " dataNodeNo,MeasurementID ", NULL); + int nSize = arrResAll.size(); + if (nSize > 0) { + int packgeNo = param.mPackageFlag; + int packgeMax = 0; + int packgeNum = 0; + jsonVal["package"] = packgeNo; + int lastSize = nSize % 10; + int index = nSize / 10; + if(lastSize > 0 && index > 0){ + packgeMax = index +1; + if(packgeNo +1 == packgeMax){ + packgeNum = nSize; + jsonVal["packageMax"] = index + 1; + } + else{ + packgeNum = (packgeNo+1) * 10; + jsonVal["packageMax"] = index +1; + } + } + else if(lastSize == 0 && index > 0){ + packgeNum = (packgeNo+1) * 10; + packgeMax = index; + jsonVal["packageMax"] = index; + }else if(lastSize > 0 && index == 0){ + packgeNum = lastSize; + packgeMax = index+1; + jsonVal["packageMax"] = index+1; + } - printf("09 packgeNo = %d,packgeNum = %d,lastSize = %d,index = %d\n",packgeNo,packgeNum,lastSize,index); - for (int i = packgeNo * 10; i < packgeNum; i++) { - print_info("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@vetRes=%s\n",vetRes[i].c_str()); - Json::Value jsSensor; - std::string strDataNodeNo = vetRes[i]; - char whereCon[512] = {}; - sprintf(whereCon, "dataNodeNo='%s' ORDER BY timeStamp DESC LIMIT 0,3", strDataNodeNo.c_str()); - // 自数据库获取传感器特征数据 - array_t arrRes; - arrRes = sql_ctl->GetDataMultiLineTransaction(T_DATA_INFO(TNAME), "*", whereCon); - int iResult = arrRes.size(); - if (iResult > 0) { - for (int j = 0; j < iResult; j++) { - Json::Value jsChannelData; - jsChannelData["ChannelId"] = arrRes[j][1]; - jsChannelData["ChannelType"] = "ACCELEROMETER"; - jsChannelData["DiagnosisPeak"] = atof(arrRes[j][2].c_str()); - jsChannelData["IntegratPk2Pk/2"] = atof(arrRes[j][3].c_str()); - jsChannelData["IntegratRMS"] = atof(arrRes[j][4].c_str()); - jsChannelData["RMSValues"] = atof(arrRes[j][5].c_str()); - jsChannelData["EnvelopEnergy"] = atof(arrRes[j][6].c_str()); - jsChannelData["1xAmp"] = atof(arrRes[j][7].c_str()); - jsChannelData["2xAmp"] = atof(arrRes[j][8].c_str()); - jsChannelData["3xAmp"] = atof(arrRes[j][9].c_str()); - jsChannelData["4xAmp"] = atof(arrRes[j][10].c_str()); - jsChannelData["5xAmp"] = atof(arrRes[j][11].c_str()); - jsChannelData["1xPhase"] = atof(arrRes[j][12].c_str()); - jsChannelData["2xPhase"] = atof(arrRes[j][13].c_str()); - jsChannelData["3xPhase"] = atof(arrRes[j][14].c_str()); - jsChannelData["4xPhase"] = atof(arrRes[j][15].c_str()); - jsChannelData["TimeStamp"] = atof(arrRes[j][17].c_str()); - jsSensor.append(jsChannelData); - } - } + printf("09 packgeNo = %d,packgeNum = %d,lastSize = %d,index = %d\n",packgeNo,packgeNum,lastSize,index); + for (int i = packgeNo * 10; i < packgeNum; i++) { + print_info("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@vetRes=%s\n",arrResAll[i][1].c_str()); + Json::Value jsSensor; + std::string strMeasurementID = arrResAll[i][1]; + char whereCon[512] = {}; + sprintf(whereCon, "channelID like '%%%s%%' ORDER BY timeStamp DESC LIMIT 0,3", strMeasurementID.c_str()); + // 自数据库获取传感器特征数据 + array_t arrRes; + arrRes = sql_ctl->GetDataMultiLineTransaction(T_DATA_INFO(TNAME), "*", whereCon); + int iResult = arrRes.size(); + if (iResult > 0) { + for (int j = 0; j < iResult; j++) { + Json::Value jsChannelData; + jsChannelData["ChannelId"] = arrRes[j][1]; + jsChannelData["ChannelType"] = "ACCELEROMETER"; + jsChannelData["DiagnosisPeak"] = atof(arrRes[j][2].c_str()); + jsChannelData["IntegratPk2Pk/2"] = atof(arrRes[j][3].c_str()); + jsChannelData["IntegratRMS"] = atof(arrRes[j][4].c_str()); + jsChannelData["RMSValues"] = atof(arrRes[j][5].c_str()); + jsChannelData["EnvelopEnergy"] = atof(arrRes[j][6].c_str()); + jsChannelData["1xAmp"] = atof(arrRes[j][7].c_str()); + jsChannelData["2xAmp"] = atof(arrRes[j][8].c_str()); + jsChannelData["3xAmp"] = atof(arrRes[j][9].c_str()); + jsChannelData["4xAmp"] = atof(arrRes[j][10].c_str()); + jsChannelData["5xAmp"] = atof(arrRes[j][11].c_str()); + jsChannelData["1xPhase"] = atof(arrRes[j][12].c_str()); + jsChannelData["2xPhase"] = atof(arrRes[j][13].c_str()); + jsChannelData["3xPhase"] = atof(arrRes[j][14].c_str()); + jsChannelData["4xPhase"] = atof(arrRes[j][15].c_str()); + jsChannelData["TimeStamp"] = atof(arrRes[j][17].c_str()); + jsSensor.append(jsChannelData); + } + } - char selectCon[128] = { 0 }; - char column[128]={0}; - char tablename[256]={0}; - sprintf(selectCon, "t_datastatic_%s.dataNodeNo='%s' ORDER BY timeStamp DESC LIMIT 0,1",strDataNodeNo.c_str(),strDataNodeNo.c_str()); - sprintf(column," t_datastatic_%s.*,t_sensor_info.status,t_sensor_info.LooseValue,t_sensor_info.batteryPower ",strDataNodeNo.c_str()); - sprintf(tablename," t_datastatic_%s LEFT JOIN t_sensor_info \ - ON t_datastatic_%s.dataNodeNo = t_sensor_info.dataNodeNo ",strDataNodeNo.c_str(),strDataNodeNo.c_str()); + char selectCon[128] = { 0 }; + char column[128]={0}; + char tablename[256]={0}; + sprintf(selectCon, " t_sensor_info.MeasurementID='%s' ",strMeasurementID.c_str()); + sprintf(column," %s.*,t_sensor_info.status,t_sensor_info.LooseValue,t_sensor_info.batteryPower ",T_DATASTATIC_INFO(TNAME)); + sprintf(tablename," %s LEFT JOIN t_sensor_info \ + ON %s.channelID like '%%%s%%' ",T_DATASTATIC_INFO(TNAME),T_DATASTATIC_INFO(TNAME),strMeasurementID.c_str()); + vec_t vecRes = sql_ctl->GetDataSingleLine(tablename,column, selectCon); + Json::Value jsStaticData; + if(vecRes.size()>0){ + jsStaticData["TemperatureTop"] = atof(vecRes[2].c_str()); + jsStaticData["TemperatureBot"] = atof(vecRes[3].c_str()); + jsStaticData["Dip"] = atof(vecRes[4].c_str()); + jsStaticData["Voltage"] = atof(vecRes[5].c_str()); + jsStaticData["ChannelType"] = "STATUS"; + jsStaticData["ChannelId"] = vecRes[1]; + jsStaticData["TimeStamp"] = vecRes[8]; + jsStaticData["battery"] = vecRes[13]; + jsStaticData["MeasurementID"] = strMeasurementID; + jsStaticData["dataNodeNo"] = arrResAll[i][0]; + jsStaticData["status"] = vecRes[11]; + jsStaticData["loose"] = "0"; - vec_t vecRes = sql_ctl->GetDataSingleLine(tablename,column, selectCon); - Json::Value jsStaticData; - if(vecRes.size()>0){ - jsStaticData["TemperatureTop"] = atof(vecRes[2].c_str()); - jsStaticData["TemperatureBot"] = atof(vecRes[3].c_str()); - jsStaticData["Dip"] = atof(vecRes[4].c_str()); - jsStaticData["Voltage"] = atof(vecRes[5].c_str()); - jsStaticData["ChannelType"] = "STATUS"; - jsStaticData["ChannelId"] = vecRes[1]; - jsStaticData["TimeStamp"] = vecRes[8]; - jsStaticData["battery"] = vecRes[14]; - jsStaticData["dataNodeNo"] = strDataNodeNo; - jsStaticData["status"] = vecRes[12]; - if(atof(looseValue) < atof(vecRes[13].c_str())){ - jsStaticData["loose"] = "1"; - }else{ - jsStaticData["loose"] = "0"; - } - }else{ - jsStaticData["TemperatureTop"] = ""; - jsStaticData["TemperatureBot"] = ""; - jsStaticData["Dip"] = ""; - jsStaticData["Voltage"] = ""; - jsStaticData["ChannelType"] = "STATUS"; - jsStaticData["ChannelId"] = ""; - jsStaticData["TimeStamp"] = ""; - jsStaticData["battery"] = ""; - jsStaticData["dataNodeNo"] = strDataNodeNo; - jsStaticData["status"] = "0"; - jsStaticData["loose"] = "0"; - } + }else{ + jsStaticData["TemperatureTop"] = ""; + jsStaticData["TemperatureBot"] = ""; + jsStaticData["Dip"] = ""; + jsStaticData["Voltage"] = ""; + jsStaticData["ChannelType"] = "STATUS"; + jsStaticData["ChannelId"] = ""; + jsStaticData["TimeStamp"] = ""; + jsStaticData["battery"] = ""; + jsStaticData["MeasurementID"] = strMeasurementID; + jsStaticData["dataNodeNo"] = arrResAll[i][0]; + jsStaticData["status"] = "0"; + jsStaticData["loose"] = "0"; + } + jsSensor.append(jsStaticData); + jsonVal["content"].append(jsSensor); + } - jsSensor.append(jsStaticData); - - jsonVal["content"].append(jsSensor); - } - - } else { - jsonVal["success"] = true; - jsonVal["content"].resize(0); - } - - return showValue.write(jsonVal); + } else { + jsonVal["success"] = true; + jsonVal["content"].resize(0); + } + //LOG_INFO("09 end\n"); + return showValue.write(jsonVal); } std::string JsonData::JsonCmd_Cgi_10(Param_10 ¶m) { @@ -896,17 +896,17 @@ std::string JsonData::JsonCmd_Cgi_10(Param_10 ¶m) } if(param.timeEnd == ""){ - sprintf(whereCon,"dataNodeNo = '%s' and %s <> ''",\ - param.strDataNode.c_str(),param.strStatic.c_str()); + sprintf(whereCon,"channelID like '%%%s%%' and %s <> ''",\ + param.MeasurementID.c_str(),param.strStatic.c_str()); }else{ - sprintf(whereCon,"dataNodeNo = '%s' and %s <> '' and timeStamp < '%s' and timeStamp > '%s' ",\ - param.strDataNode.c_str(),param.strStatic.c_str(),param.timeEnd.c_str(),param.timeStart.c_str()); + sprintf(whereCon," channelID like '%%%s%%' and %s <> '' and timeStamp < '%s' and timeStamp > '%s' ",\ + param.MeasurementID.c_str(),param.strStatic.c_str(),param.timeEnd.c_str(),param.timeStart.c_str()); } + int rows = sql_ctl->GetTableRows(szTableName,whereCon); - printf("rows : %d\n",rows); int packgeNo = param.mPackageFlag; int packgeMax = 0; int packgeNum = 0; @@ -933,51 +933,56 @@ std::string JsonData::JsonCmd_Cgi_10(Param_10 ¶m) jsonVal["packageMax"] = index; } - printf("10 packgeNo = %d,packgeNum = %d,lastSize = %d,index = %d\n",packgeNo,packgeNum,lastSize,index); + //printf("10 packgeNo = %d,packgeNum = %d,lastSize = %d,index = %d\n",packgeNo,packgeNum,lastSize,index); memset(whereCon,0x00,sizeof(whereCon)); if(param.timeEnd == ""){ - sprintf(whereCon,"dataNodeNo = '%s' and %s <> '' order by timeStamp asc LIMIT %d OFFSET %d",\ - param.strDataNode.c_str(),param.strStatic.c_str(),550,packgeNum); + sprintf(whereCon,"channelID like '%%%s%%' and %s <> '' order by timeStamp asc LIMIT %d OFFSET %d",\ + param.MeasurementID.c_str(),param.strStatic.c_str(),550,packgeNum); }else{ - sprintf(whereCon,"dataNodeNo = '%s' and %s <> '' and timeStamp < '%s' and timeStamp > '%s' order by timeStamp asc LIMIT %d OFFSET %d",\ - param.strDataNode.c_str(),param.strStatic.c_str(),param.timeEnd.c_str(),param.timeStart.c_str(),550,packgeNum); + sprintf(whereCon,"channelID like '%%%s%%' and %s <> '' and timeStamp < '%s' and timeStamp > '%s' order by timeStamp asc LIMIT %d OFFSET %d",\ + param.MeasurementID.c_str(),param.strStatic.c_str(),param.timeEnd.c_str(),param.timeStart.c_str(),550,packgeNum); } array_t vecRes; vecRes = sql_ctl->GetDataMultiLine(szTableName, selectCon,whereCon); - + print_info("vecRes = %d\n",vecRes.size()); if(vecRes.size() > 0){ - Json::Value jsStaticData ; + Json::Value jsStaticData; for(int i = 0 ; i < vecRes.size(); i++){ Json::Value iTem; - if(vecRes[i][1] == param.strDataNode + "-X"){ + if(vecRes[i][1] == param.MeasurementID + "-X"){ iTem.append(vecRes[i][0]); iTem.append(vecRes[i][2]); jsStaticData["X"].append(iTem); - }if(vecRes[i][1] == param.strDataNode + "-Y"){ + }if(vecRes[i][1] == param.MeasurementID + "-Y"){ iTem.append(vecRes[i][0]); iTem.append(vecRes[i][2]); jsStaticData["Y"].append(iTem); - }if(vecRes[i][1] == param.strDataNode + "-Z"){ + }if(vecRes[i][1] == param.MeasurementID + "-Z"){ iTem.append(vecRes[i][0]); iTem.append(vecRes[i][2]); jsStaticData["Z"].append(iTem); } - if(vecRes[i][1] == param.strDataNode + "-S"){ + if(vecRes[i][1] == param.MeasurementID + "-S"){ iTem.append(vecRes[i][0]); iTem.append(vecRes[i][2]); jsStaticData["S"].append(iTem); } - //jsStaticData.append(value) } - jsonVal["content"] = (jsStaticData); - jsonVal["Static"] = param.strStatic; - print_info("vecRes = %d,channelID = %s\n",vecRes.size(),vecRes[0][0].c_str()); - }else{ + if(jsStaticData.size() == 0){ jsonVal["success"] = false; jsonVal["content"].resize(0); } + else{ + jsonVal["content"] = (jsStaticData); + } + jsonVal["Static"] = param.strStatic; + print_info("vecRes = %d,channelID = %s\n",vecRes.size(),vecRes[0][0].c_str()); + }else{ + jsonVal["success"] = false; + jsonVal["content"].resize(0); + } }else{ jsonVal["success"] = false; jsonVal["content"].resize(0); @@ -1198,6 +1203,7 @@ std::string JsonData::JsonCmd_Cgi_25(Param_25 ¶m) jsonVal["success"] = true; jsonVal["message"] = " "; jsonVal["cmd"] = "25"; + string strNet = ""; bool bFlag1 = CheckIP(param.mGateway.c_str()); bool bFlag2 = IsValidMask(param.mSubnetMask); bool bFlag3 = CheckIP(param.mIp.c_str()); @@ -1208,7 +1214,10 @@ std::string JsonData::JsonCmd_Cgi_25(Param_25 ¶m) bFlag4 = true; } print_info("bFlag1 = %d,bFlag2 = %d,bFlag3 = %d,bFlag4 = %d\n",bFlag1,bFlag2,bFlag3,bFlag4); - +#ifdef IMX6UL_GATEWAY + strNet = param.mNet; + param.mNet = "Net"; +#endif if (0 == param.mMode &&(bFlag1 && bFlag2 && bFlag3 && bFlag4) && param.mNetworkPortStatus == "STATIC") { WriteStr2Config(NETWORKCONFIG, param.mNet, "dnsName", param.mDnsName); WriteStr2Config(NETWORKCONFIG, param.mNet, "networkPortStatus", param.mNetworkPortStatus); @@ -1242,12 +1251,12 @@ std::string JsonData::JsonCmd_Cgi_25(Param_25 ¶m) jsonVal["success"] = false; } - jsonValnet["dnsName"] = ReadStrByOpt(NETWORKCONFIG, "eth0", "dnsName"); - jsonValnet["networkPortStatus"] = ReadStrByOpt(NETWORKCONFIG, "eth0", "networkPortStatus"); - jsonValnet["gateway"] = ReadStrByOpt(NETWORKCONFIG, "eth0" ,"gateway"); - jsonValnet["subnetMask"] = ReadStrByOpt(NETWORKCONFIG, "eth0", "subnetMask"); - jsonValnet["dataWatchIpAddress"] = ReadStrByOpt(NETWORKCONFIG, "eth0", "ipAddress"); - jsonValnet["hostName"] = ReadStrByOpt(NETWORKCONFIG, "eth0", "hostName"); + jsonValnet["dnsName"] = ReadStrByOpt(NETWORKCONFIG, param.mNet, "dnsName"); + jsonValnet["networkPortStatus"] = ReadStrByOpt(NETWORKCONFIG, param.mNet, "networkPortStatus"); + jsonValnet["gateway"] = ReadStrByOpt(NETWORKCONFIG, param.mNet ,"gateway"); + jsonValnet["subnetMask"] = ReadStrByOpt(NETWORKCONFIG, param.mNet, "subnetMask"); + jsonValnet["dataWatchIpAddress"] = ReadStrByOpt(NETWORKCONFIG, param.mNet, "ipAddress"); + jsonValnet["hostName"] = ReadStrByOpt(NETWORKCONFIG, param.mNet, "hostName"); jsonVal["content"]["eth0"] = jsonValnet; jsonVal["content"]["gatewaytype"] = 0; @@ -1267,6 +1276,7 @@ std::string JsonData::JsonCmd_Cgi_25(Param_25 ¶m) std::string JsonData::JsonCmd_Cgi_26(Param_26 ¶m) { + //LOG_INFO("26 start\n"); Json::Value jsonVal; jsonVal.clear(); @@ -1352,33 +1362,33 @@ std::string JsonData::JsonCmd_Cgi_26(Param_26 ¶m) jsSensorData["timeStamp"] = arrRes[j][38]; jsSensorData["viff"] = atoi(arrRes[j][39].c_str()); vector vParam; + + print_info("loose = %s\n",arrRes[j][42].c_str()); boost::split( vParam, arrRes[j][42], boost::is_any_of( "," ), boost::token_compress_on ); - if(atof(looseValue) < atof(vParam[0].c_str())){ - jsSensorData["loose"] = "1"; - }else{ - jsSensorData["loose"] = "0"; - } - //获取最新zigbee信号 - char szTableName[50]={0x00},selectCon[128]={0x00}; - sprintf(szTableName,"t_dataStatic_%s",arrRes[j][0].c_str()); - memset(selectCon,0x00,sizeof(selectCon)); - sprintf(selectCon, "zigbeeSignal <> '' and zigbeeSignal <> '0' ORDER BY timeStamp desc LIMIT 0,1"); - string strZigbeeSignal = sql_ctl->GetData(szTableName, "zigbeeSignal", selectCon); - memset(selectCon,0x00,sizeof(selectCon)); - sprintf(selectCon, "zigbeeSignalNode <> '' and zigbeeSignalNode <> '0' ORDER BY timeStamp desc LIMIT 0,1"); - string strZigbeeSignalNode = sql_ctl->GetData(szTableName, "zigbeeSignalNode", selectCon); - if(strZigbeeSignal == "") - jsSensorData["RSSI"] = "0," + arrRes[j][40]; - else - jsSensorData["RSSI"] = strZigbeeSignal + "," + strZigbeeSignalNode; + if(vParam.size() > 1) + jsSensorData["loose"] = vParam[1]; + else + jsSensorData["loose"] = "0"; + + vector vParamRSSI; + boost::split( vParamRSSI, arrRes[j][40], boost::is_any_of( "," ), boost::token_compress_on ); + if(vParamRSSI.size() > 1){ + jsSensorData["RSSI"] = arrRes[j][40]; + }else{ + jsSensorData["RSSI"] = "0," + arrRes[j][40]; + } + jsSensorData["update"] = atoi(arrRes[j][41].c_str()); + jsSensorData["MeasurementID"] = arrRes[j][44]; + jsSensorData["battery"] = arrRes[j][43]; jsArray.append(jsSensorData); } } else { jsArray.resize(0); jsonVal["success"] = true; } + //LOG_INFO("26 end\n"); jsonVal["gatewayMac"] = GlobalConfig::MacAddr_G ; jsonVal["gatewayIP"] = GlobalConfig::IpAddr_G ; jsonVal["content"]["dataNodeArray"] = jsArray; @@ -1475,6 +1485,7 @@ std::string JsonData::JsonCmd_Cgi_54(Param_54 ¶m) nodeArray.append(arrRes[j][41]); nodeArray.append(arrRes[j][42]); nodeArray.append(arrRes[j][43]); + nodeArray.append(arrRes[j][44]); jsArray.append(nodeArray); } @@ -1495,15 +1506,6 @@ std::string JsonData::JsonCmd_Cgi_54(Param_54 ¶m) jsBody["ServerConfig"] = jsSystemSetting; jsonVal["content"] = jsBody; - jsonValnet["dnsName"] = ReadStrByOpt(NETWORKCONFIG, "eth0", "dnsName"); - jsonValnet["networkPortStatus"] = ReadStrByOpt(NETWORKCONFIG, "eth0", "networkPortStatus"); - jsonValnet["gateway"] = ReadStrByOpt(NETWORKCONFIG, "eth0" ,"gateway"); - jsonValnet["subnetMask"] = ReadStrByOpt(NETWORKCONFIG, "eth0", "subnetMask"); - jsonValnet["dataWatchIpAddress"] = ReadStrByOpt(NETWORKCONFIG, "eth0", "ipAddress"); - jsonValnet["hostName"] = ReadStrByOpt(NETWORKCONFIG, "eth0", "hostName"); - jsonVal["content"]["eth0"] = jsonValnet; - jsonVal["content"]["gatewaytype"] = 0; - #ifdef G2UL_GATEWAY jsonValnet1["dnsName"] = ReadStrByOpt(NETWORKCONFIG, "eth1", "dnsName"); jsonValnet1["networkPortStatus"] = ReadStrByOpt(NETWORKCONFIG, "eth1", "networkPortStatus"); @@ -1550,6 +1552,7 @@ std::string JsonData::JsonCmd_Cgi_27(Param_27 ¶m) sql_ctl->DeleteTableData(T_DATA_INFO(TNAME), whereCon); sql_ctl->DeleteTableData(T_DATASTATIC_INFO(TNAME), whereCon); sql_ctl->DeleteTableData(T_DATANODE_TIME(TNAME), whereCon); + sql_ctl->DeleteTableData(T_BATTERY_INFO(TNAME), whereCon); char szTableName[50]={0x00}; sprintf(szTableName,"DROP TABLE t_data_%s",param.mDataNodeNo.c_str()); sql_ctl->CreateTable(szTableName, 0); @@ -1559,11 +1562,8 @@ std::string JsonData::JsonCmd_Cgi_27(Param_27 ¶m) }else if(param.mDataNodeNo.length() > 0 && param.mType == "CORRECT"){ char updateSql[1024] = { 0 }; sprintf(whereCon, "%s= '%s'", T_SENSOR_INFO(DATANODENO), param.mDataNodeNo.c_str()); - string strLooseValue = sql_ctl->GetData(T_SENSOR_INFO(TNAME)," LooseValue ",whereCon); - vector vParam; - boost::split( vParam, strLooseValue, boost::is_any_of( "," ), boost::token_compress_on ); GetTimeNet(localtimestamp, 1); - sprintf(updateSql,"LooseValue = '%f,2,",vParam[0].c_str()); + sprintf(updateSql,"LooseValue = '0,2,"); string strUpdateSql = string(updateSql) + string(localtimestamp) + "' " ; print_info("updateSql = %s\n",strUpdateSql.c_str()); sql_ctl->UpdateTableData(T_SENSOR_INFO(TNAME),strUpdateSql.c_str(),whereCon); @@ -2028,7 +2028,8 @@ std::string JsonData::JsonCmd_Cgi_40(Param_40 ¶m) jsonVal["content"] = jsBody; return showValue.write(jsonVal); } -std::string JsonData::JsonCmd_Cgi_41(std::vector ¶m) + +std::string JsonData::JsonCmd_Cgi_41(std::vector ¶m,int isServer) { Json::Value jsonVal; jsonVal.clear(); @@ -2037,17 +2038,34 @@ std::string JsonData::JsonCmd_Cgi_41(std::vector ¶m) jsonVal["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G; jsonVal["success"] = true; jsonVal["message"] = " "; - + char whereCon[1024] = {0}; char updateSql[1024] = { 0 }; //int WaveInteerVal = param.mwaveInterVal/param.mfeatureInterVal; + for(int i = 0; i < param.size();i++){ - sprintf(updateSql, "featureInterVal='%d',waveInterVal='%d',range='%d',samplingRate='%d',AccSampleTime = '%d',\ - startBrands = '%s',stopBrands = '%s',envelopeBandPass = '%s',viff = '%d',faultFrequency = '%s' ,UpdateFlag = 0", - param[i].mfeatureInterVal, param[i].mwaveInterVal,param[i].mrange,\ + char dataNodeName[100]={0x00}; + hexToAscii(param[i].mdataNodeName.c_str(),dataNodeName); + print_info("str = %s\n",dataNodeName); + print_info("dataNodeName = %s\n",param[i].mdataNodeName.c_str()); + int dataNodeNameLength = param[i].mdataNodeName.length(); + if(dataNodeNameLength != 0 ){ + sprintf(updateSql, "dataNodeName = '%s',ZigbeePower = '%d',ZigbeeRetry = '%d',featureInterVal='%d',waveInterVal='%d',range='%d',samplingRate='%d',AccSampleTime = '%d',\ + startBrands = '%s',stopBrands = '%s',envelopeBandPass = '%s',viff = '%d',faultFrequency = '%s' ,MeasurementID = '%s' ,UpdateFlag = -1", + dataNodeName,param[i].ZigbeePower,param[i].ZigbeeRetry,param[i].mfeatureInterVal, param[i].mwaveInterVal,param[i].mrange,\ param[i].msamplingRate,param[i].mAccSampleTime, param[i].mstartBrands.c_str(),\ - param[i].mstopBrands.c_str(),param[i].menvelopeBandPass.c_str(),param[i].mviff,param[i].mfaultFrequency.c_str()); - sprintf(whereCon, "dataNodeNo='%s'", param[i].mdataNodeNo.c_str()); + param[i].mstopBrands.c_str(),param[i].menvelopeBandPass.c_str(),param[i].mviff,param[i].mfaultFrequency.c_str(),param[i].mMeasurementID.c_str()); + }else if(dataNodeNameLength == 0 ){ + sprintf(updateSql, "ZigbeePower = '%d',ZigbeeRetry = '%d',featureInterVal='%d',waveInterVal='%d',range='%d',samplingRate='%d',AccSampleTime = '%d',\ + startBrands = '%s',stopBrands = '%s',envelopeBandPass = '%s',viff = '%d',faultFrequency = '%s',MeasurementID = '%s',UpdateFlag = 0", + param[i].ZigbeePower,param[i].ZigbeeRetry,param[i].mfeatureInterVal, param[i].mwaveInterVal,param[i].mrange,\ + param[i].msamplingRate,param[i].mAccSampleTime, param[i].mstartBrands.c_str(),\ + param[i].mstopBrands.c_str(),param[i].menvelopeBandPass.c_str(),param[i].mviff,param[i].mfaultFrequency.c_str(),param[i].mMeasurementID.c_str()); + } + if(!isServer) + sprintf(whereCon, "dataNodeNo='%s'", param[i].mdataNodeNo.c_str()); + else + sprintf(whereCon, "MeasurementID ='%s'", param[i].mdataNodeNo.c_str()); int iRet = sql_ctl->UpdateTableData(T_SENSOR_INFO(TNAME), updateSql, whereCon); memset(whereCon,0x00,sizeof(whereCon)); @@ -2075,6 +2093,7 @@ std::string JsonData::JsonCmd_Cgi_42(Param_42 ¶m) print_info("strcmd = %s\n",strcmd.c_str()); system(strcmd.c_str()); }else if(param.fileName == "rfsbu.tar"){ + LOG_INFO("update rfsbu.tar\n"); sleep(3); print_info("strcmd = %s\n",param.fileName.c_str()); system("/opt/opt.sh"); @@ -2132,9 +2151,7 @@ std::string JsonData::JsonCmd_Cgi_31(Param_31 ¶m) jsonVal["content"] = jsBody; return showValue.write(jsonVal); - - - + } diff --git a/jsonparse/SH_JsonCmd.hpp b/jsonparse/SH_JsonCmd.hpp index 27f1af4..2033aa6 100644 --- a/jsonparse/SH_JsonCmd.hpp +++ b/jsonparse/SH_JsonCmd.hpp @@ -58,7 +58,7 @@ public : std::string JsonCmd_Cgi_32(Param_32 ¶m); // std::string JsonCmd_Cgi_40(Param_40 ¶m); // - std::string JsonCmd_Cgi_41(std::vector ¶m); // + std::string JsonCmd_Cgi_41(std::vector ¶m,int isServer = 0); // std::string JsonCmd_Cgi_42(Param_42 ¶m); //从web端更新程序 std::string JsonCmd_Cgi_43(); //检测网口状态 diff --git a/localserver/SH_LocalServer.cpp b/localserver/SH_LocalServer.cpp index 4df54c8..c1bac87 100644 --- a/localserver/SH_LocalServer.cpp +++ b/localserver/SH_LocalServer.cpp @@ -215,9 +215,11 @@ void LocalServer::HandleFromServer(const char *pData_r, int pLen, const char *to param.menvelopeBandPass = recvBody[i]["envelopeBandPass"].asString(); param.mviff = recvBody[i]["viff"].asInt(); param.mfaultFrequency = recvBody[i]["faultFrequency"].asString(); + param.ZigbeePower = recvBody[i]["ZigbeePower"].asInt(); + param.ZigbeeRetry = recvBody[i]["ZigbeeRetry"].asInt(); param41.push_back(param); } - std::string data = jd.JsonCmd_Cgi_41(param41); + std::string data = jd.JsonCmd_Cgi_41(param41,1); char whereCon[64] = { 0 }; sprintf(whereCon, "dataNodeNo='%s'", param.mdataNodeNo.c_str()); string strData = sql_ctl->GetNodeConfigureInfor(whereCon); @@ -332,6 +334,7 @@ try{ param.mPackageFlag = recvBody["package"].asInt(); param.timeStart = recvBody["timeStart"].asString(); param.timeEnd = recvBody["timeEnd"].asString(); + param.MeasurementID = recvBody["MeasurementID"].asString(); std::string data = jd.JsonCmd_Cgi_10(param); return data; } @@ -516,6 +519,10 @@ try{ param.menvelopeBandPass = recvBody[i]["envelopeBandPass"].asString(); param.mviff = recvBody[i]["viff"].asInt(); param.mfaultFrequency = recvBody[i]["faultFrequency"].asString(); + param.mdataNodeName = recvBody[i]["dataNodeName"].asString(); + param.ZigbeePower = recvBody[i]["ZigbeePower"].asInt(); + param.ZigbeeRetry = recvBody[i]["ZigbeeRetry"].asInt(); + param.mMeasurementID = recvBody[i]["MeasurementID"].asString(); param41.push_back(param); } std::string data = jd.JsonCmd_Cgi_41(param41); diff --git a/main.cpp b/main.cpp index ddb824d..ba26fc9 100644 --- a/main.cpp +++ b/main.cpp @@ -26,6 +26,7 @@ namespace{ int main(int argc, char *argv[]) { + printf(" Firmware compile time:%s %s,version %s\n", __DATE__, __TIME__,GlobalConfig::Version.c_str()); // 初始化日志记录,日志缓存区,记录数,未使用,后期,命令启动 log_init(SOFTWARE_RUN_LOG, 1380, 160 * 1024); LOG_INFO("####CIDNSOFT start####\n"); @@ -41,14 +42,9 @@ int main(int argc, char *argv[]) // 初始化平台配置文件 platform->PlatFormInit(); - - //启动 mqtt客户端 - boost::thread startMqtt(StartMqttClient); - startMqtt.detach(); - - + sql_ctl->InintGateway(); - sql_ctl->CalculateDip(); + //sql_ctl->CalculateDip(); sql_ctl->CalculateBattery(); pUart->InitZigbee(); // UDP,接收客户端发来的组播消息,用于外接 QT 专家系统,屏蔽之 @@ -74,15 +70,12 @@ int main(int argc, char *argv[]) boost::thread uartWaveReadTh(UartStartWave); uartWaveReadTh.detach(); - - - //启动 mqtt 心跳 - boost::thread startHeart(HeartRep); - startHeart.detach(); - - //启动 mqtt 心跳 + +#ifdef G2UL_GATEWAY + //启动 RUN LED boost::thread startRunLED(RunLED); startRunLED.detach(); +#endif #ifdef NR5G_MODULE print_info("NR5G_MODULE \n"); @@ -136,15 +129,22 @@ int main(int argc, char *argv[]) printf("temp = %02x ",szRes[i]); }*/ - + //启动 mqtt客户端 + boost::thread startMqtt(StartMqttClient); + startMqtt.detach(); + + //启动 mqtt 心跳 + boost::thread startHeart(HeartRep); + startHeart.detach(); int fd = OpenWatchDog(); while (GlobalConfig::QuitFlag_G) { - +#ifdef G2UL_GATEWAY gpio_set(GlobalConfig::GPIO_G.hardWatchDog,1); usleep(20000); gpio_set(GlobalConfig::GPIO_G.hardWatchDog,0); +#endif WriteWatchDog(fd); sleep(20); // data_publish(senddata.c_str(), GlobalConfig::Topic_G.mPubData.c_str()); diff --git a/mqttclient/SH_MqttClient.cpp b/mqttclient/SH_MqttClient.cpp index 3737870..cd67b32 100644 --- a/mqttclient/SH_MqttClient.cpp +++ b/mqttclient/SH_MqttClient.cpp @@ -358,8 +358,8 @@ int start_client(const char *boardname, const char *gwid, const char* gwip, cons rc = mosquitto_loop_forever(mosq, -1, 1); if (rc) { - //fprintf(stderr, "Error: %s\n", mosquitto_strerror(rc)); - //print_info("%s",stderr); + fprintf(stderr, "Error: %s\n", mosquitto_strerror(rc)); + print_info("%s",stderr); } mosq_free: mosquitto_destroy(mosq); diff --git a/platform/SH_PlatformInit.cpp b/platform/SH_PlatformInit.cpp index ae84ba6..03e3120 100644 --- a/platform/SH_PlatformInit.cpp +++ b/platform/SH_PlatformInit.cpp @@ -12,7 +12,7 @@ int GlobalConfig::LinkCount = 0; int GlobalConfig::net0Status = 1; -std::string GlobalConfig::Version = "3.1"; +std::string GlobalConfig::Version = "3.2.1"; std::string GlobalConfig::MacAddr_G = ""; std::string GlobalConfig::MacAddr_G2 = ""; std::string GlobalConfig::IpAddr_G = ""; diff --git a/threadfunc/SH_ThreadFunc.cpp b/threadfunc/SH_ThreadFunc.cpp index 05f211e..d013d02 100644 --- a/threadfunc/SH_ThreadFunc.cpp +++ b/threadfunc/SH_ThreadFunc.cpp @@ -30,7 +30,7 @@ void CheckThread() { print_info("ENTER CHECK THREAD \n"); std::string runinfo = "系统循环检测模块启动"; - + LOG_INFO(runinfo.c_str()); int heart_count = 0; int time_check = 0; @@ -78,7 +78,8 @@ void CheckThread() GlobalConfig::MacAddr_G.c_str()); std::string str = std::string(buf); time_check = 0; - int iRet = data_publish(str.c_str(), GlobalConfig::Topic_G.mPubCmd.c_str()); + int iRet = data_publish(str.c_str(), GlobalConfig::Topic_G.mPubTiming.c_str()); + iRet = data_publish(str.c_str(), GlobalConfig::Topic_G.mPubCmd.c_str()); if(iRet != 0 ) { LOG_ERROR("MQTT connect failed\n"); @@ -208,15 +209,18 @@ void CheckThread() LOG_ERROR("nowTimetamp = %s,lastTime = %s,lTime = %d\n",nowTimetamp.c_str(),strTime.c_str(),lTime); } } - }if(21000 == Battery){ + } + if(1500 == Battery){ Battery = 0; + LOG_INFO("Battery\n"); sql_ctl->CalculateBattery(); } // if(10800 == UpdateZigbee){ // UpdateZigbee = 0; // pUart->UpdateZigbeeInfoCtrl(); // } - if(3600 == loose_check){ + if(3500 == loose_check){ + LOG_INFO("loosecheck\n"); loose_check = 0; sql_ctl->CalculateDip(); } @@ -260,7 +264,7 @@ void CheckThread() jsonVal["cmdBody"] = dataBody; data_publish(showValue.write(jsonVal).c_str(), GlobalConfig::Topic_G.mPubConfig.c_str()); } - if(21000 == logClean){ + if(21600 == logClean){ logClean = 0; DIR *dp; //创建一个指向root路径下每个文件的指针 struct dirent *dirp; @@ -285,14 +289,18 @@ void CheckThread() memcpy(todayDay,buffer+8,2); memcpy(fileMonth,dirp->d_name+5,2); memcpy(todayMonth,buffer+5,2); - string filename = root+ string(dirp->d_name); + string filename = root + string(dirp->d_name); if(atoi(fileMonth) == atoi(todayMonth) ? abs(atoi(todayDay) - atoi(fileDay)) > 15: abs(abs(30-(atoi(fileDay)) + atoi(todayDay))) > 15){ LOG_INFO("filename = %s\n",filename.c_str()); remove(filename.c_str()); } } - + char localtimestamp[32] = { 0 }; + GetTimeNet(localtimestamp, 1); + char whereCon[1024] = {0}; + sprintf(whereCon," timestamp < '%ld' ",atol(localtimestamp) - 15638400); //删除半年前的数据 + sql_ctl->DeleteTableData(T_BATTERY_INFO(TNAME),whereCon); /*staticData = 0; Json::Value jsHeart; Json::FastWriter fw; @@ -397,6 +405,7 @@ void CheckThread() pUart->UpdateZigbeeInfoCtrl(); pUart->bUpdateconfig = false; pUart->bUpdate = false; + pUart->bSendTimeStamp = false; // 延时1秒 sleep(1); std::string str("8888"); @@ -461,7 +470,7 @@ void HeartRep() count = 0; gpio_set(GlobalConfig::GPIO_G.errorLed,0); } - gpio_set(GlobalConfig::GPIO_G.errorLed,0); + //gpio_set(GlobalConfig::GPIO_G.errorLed,0); // if(count > 0){ // bool status = Ping( GlobalConfig::ServerIP.c_str(), 10000); // if(status != 0) @@ -597,11 +606,15 @@ void UartStart() { // onReceiveUart cb = (onReceiveUart)&ProtoConvert::HandleFromUart; // pUart->setCallBack(cb); + print_info("zigAckrep = %d,zigAckreset = %d,zigReset = %d,errorLed = %d,power = %d",\ + GlobalConfig::GPIO_G.zigAckrep,GlobalConfig::GPIO_G.zigAckreset,GlobalConfig::GPIO_G.zigReset,GlobalConfig::GPIO_G.errorLed,\ + GlobalConfig::GPIO_G.power); InitGpio(GlobalConfig::GPIO_G.zigAckrep,0);//ACK InitGpio(GlobalConfig::GPIO_G.zigAckreset,1);//ACK reset InitGpio(GlobalConfig::GPIO_G.zigReset,1);//Zigbee reset gpio_set(GlobalConfig::GPIO_G.zigAckreset,1); gpio_set(GlobalConfig::GPIO_G.zigReset,1); + print_info("GPIO Init1\n"); #ifdef IMX6UL_GATEWAY InitGpio(GlobalConfig::GPIO_G.errorLed,1);//指示灯 @@ -795,7 +808,7 @@ void my_connect_callback(struct mosquitto *mosq, void *obj, int result) void my_disconnect_callback(struct mosquitto *mosq, void *obj, int result) { int ret = 0; - ret = disconnect(); + //ret = disconnect(); //LOG_ERROR("The MQTT connection lost:%d\n", ret); print_debug("The MQTT connection lost\n"); char gwTime[32] = { 0 }; @@ -837,7 +850,8 @@ void my_disconnect_callback(struct mosquitto *mosq, void *obj, int result) print_info("%s\n", buf); #else - int iRet = reconnect(); + // int iRet = reconnect(); + // print_info("reconnect = %d\n",iRet); #endif } @@ -910,7 +924,8 @@ void StartMqttClient() print_info("start mqtt \n"); std::string runinfo = "MQTT通信模块启动"; - while (1) { + while (1) + { if (GlobalConfig::ServerIP.length() > 0) { std::string strEqupNo = GlobalConfig::MacAddr_G; std::string strVersion = GlobalConfig::Version; diff --git a/uart/SH_Uart.cpp b/uart/SH_Uart.cpp index 27140c3..1f16929 100644 --- a/uart/SH_Uart.cpp +++ b/uart/SH_Uart.cpp @@ -45,7 +45,7 @@ int Uart::UartRecv(int fd, char srcshow,char* buffer) if((unsigned short)GlobalConfig::Zigbee_G.MyAddr == 0x9999){ memset(buff, 0, sizeof(buff)); - ret = read_data(fd, buff, BUF_LENGTH, 1); + ret = read_data(fd, buff, BUF_LENGTH, 10); if (ret <= 0 ){ if(!bUpdate && !bUpdateconfig && GlobalConfig::EnterZigBeeWaveTransmittingCnt_G > 15){ timeoutflag ++; @@ -129,7 +129,7 @@ int Uart::UartRecv(int fd, char srcshow,char* buffer) GlobalConfig::EnterZigBeeWaveTransmittingFlag_G = NO_ENTER_TRANSMITTING_STATUS; GlobalConfig::EnterZigBeeWaveTransmittingCnt_G = 0; } - print_debug("offSize = %d\n",offSize); + //print_debug("offSize = %d\n",offSize); } } @@ -475,14 +475,13 @@ int Uart::FindRecvPackage(int bytesRead, char* mUartRecvBuf,char* head) strcat(tmp2,tmp); } LOG_ERROR("error str = %s\n",tmp2); - + GlobalConfig::Zigbee_G.MyAddr = 0x8888; tcflush(fd,TCIOFLUSH); sleep(1); modify_LocalAddr(0x8888); sleep(1); - tcflush(fd,TCIOFLUSH); bModifyAddr = true; - GlobalConfig::Zigbee_G.MyAddr = 0x8888; + bSendTimeStamp = false; GlobalConfig::EnterZigBeeWaveTransmittingFlag_G = NO_ENTER_TRANSMITTING_STATUS; GlobalConfig::EnterZigBeeWaveTransmittingCnt_G = 0; std::vector().swap(m_VecWaveData); @@ -499,13 +498,13 @@ int Uart::FindRecvPackage(int bytesRead, char* mUartRecvBuf,char* head) if(!CheckCrc(RecvBuf,11)){ LOG_INFO("CheckCrc error command 20 \n"); mPackgeIndex = -1; + GlobalConfig::Zigbee_G.MyAddr = 0x8888; tcflush(fd,TCIOFLUSH); sleep(1); modify_LocalAddr(0x8888); sleep(1); - tcflush(fd,TCIOFLUSH); bModifyAddr = true; - GlobalConfig::Zigbee_G.MyAddr = 0x8888; + bSendTimeStamp = false; GlobalConfig::EnterZigBeeWaveTransmittingFlag_G = NO_ENTER_TRANSMITTING_STATUS; GlobalConfig::EnterZigBeeWaveTransmittingCnt_G = 0; break; @@ -528,13 +527,13 @@ int Uart::FindRecvPackage(int bytesRead, char* mUartRecvBuf,char* head) } LOG_ERROR("error str = %s\n",tmp2); print_info("\n"); + GlobalConfig::Zigbee_G.MyAddr = 0x8888; tcflush(fd,TCIOFLUSH); sleep(1); modify_LocalAddr(0x8888); bModifyAddr = true; sleep(1); - tcflush(fd,TCIOFLUSH); - GlobalConfig::Zigbee_G.MyAddr = 0x8888; + bSendTimeStamp = false; GlobalConfig::EnterZigBeeWaveTransmittingFlag_G = NO_ENTER_TRANSMITTING_STATUS; GlobalConfig::EnterZigBeeWaveTransmittingCnt_G = 0; std::vector().swap(m_VecWaveData); @@ -597,11 +596,12 @@ int Uart::FindRecvPackage(int bytesRead, char* mUartRecvBuf,char* head) char updateSql[1024] = { 0 }; char buf[20]={0x00}; sprintf(buf, "%02x%02x", UartRecvBuf[i+3]&0xFF, UartRecvBuf[i+4]&0xFF);//Zigbee 本地地址 2 byte - sprintf(updateSql, "UpdateFlag = 1"); + sprintf(updateSql, "UpdateFlag = UpdateFlag + 1"); sprintf(whereCon, "zigbeeShortAddr='%s'", buf); sql_ctl->UpdateTableData(T_SENSOR_INFO(TNAME), updateSql, whereCon); //string strData = sql_ctl->GetNodeConfigureInfor(whereCon); //data_publish(strData.c_str(), GlobalConfig::Topic_G.mPubConfig.c_str()); + GlobalConfig::Zigbee_G.MyAddr = 0x8888; bUpdateconfig = false; mPackgeIndex = -1; tcflush(fd,TCIOFLUSH); @@ -610,28 +610,45 @@ int Uart::FindRecvPackage(int bytesRead, char* mUartRecvBuf,char* head) bModifyAddr = true; bSendTimeStamp = false; sleep(1); - tcflush(fd,TCIFLUSH); - GlobalConfig::Zigbee_G.MyAddr = 0x8888; + GlobalConfig::EnterZigBeeWaveTransmittingFlag_G = NO_ENTER_TRANSMITTING_STATUS; GlobalConfig::EnterZigBeeWaveTransmittingCnt_G = 0; break; } break; }else if(command == 35){ - LOG_INFO("command = %d ShortAddr :%s\n",command,strShortAddr.c_str()); - for(int j = i; j < i+100;j++){ - printf("%02X ",UartRecvBuf[j]&0xFF); + LOG_INFO("command = %d ShortAddr :%s,Timetamp=%s\n",command,strShortAddr.c_str(),strTimetamp.c_str()); + // for(int j = i; j < i+100;j++){ + // printf("%02X ",UartRecvBuf[j]&0xFF); + // } + char signalNode[10]={0x00}; + sprintf(signalNode,"%02d",UartRecvBuf[i+14]&0xFF); + if(!strcmp(signalNode,"00") || !strcmp(signalNode,"0")){ + char errorInfo[100]={0x00}; + sprintf(errorInfo,"未检测到信号!%s",signalNode); + LOG_ERROR(errorInfo); + }else{ + char whereCon[1024] = {0}; + char updateSql[1024] = { 0 }; + char tableName[100]={0x00}; + sprintf(whereCon, "zigbeeShortAddr='%s'", strShortAddr.c_str()); + vec_t vecDataNodeNo = sql_ctl->GetDataSingleLine(T_SENSOR_INFO(TNAME), " dataNodeNo,RSSI ", whereCon); + memset(whereCon,0x00,sizeof(whereCon)); + sprintf(updateSql, "zigbeeSignalNode = '%02d' ",UartRecvBuf[i+14]&0xFF);//zigbeeRSSIType = 0 传感器获取网关信号强度 + sprintf(whereCon, "dataNodeNo='%s' and timeStamp = '%s'", (char*)vecDataNodeNo[0].c_str(),strTimetamp.c_str()); + sprintf(tableName,"t_dataStatic_%s",(char*)vecDataNodeNo[0].c_str()); + sql_ctl->UpdateTableData(tableName, updateSql, whereCon); + + vector vParamRSSI; + boost::split( vParamRSSI, vecDataNodeNo[1], boost::is_any_of( "," ), boost::token_compress_on ); + if(vParamRSSI.size() > 0){ + sprintf(updateSql, "RSSI = '%s,%02d' ",vParamRSSI[0].c_str(),UartRecvBuf[i+14]&0xFF); + LOG_INFO(updateSql); + sprintf(whereCon, "dataNodeNo='%s'", (char*)vecDataNodeNo[0].c_str()); + sql_ctl->UpdateTableData(T_SENSOR_INFO(TNAME), updateSql, whereCon); + } } - char whereCon[1024] = {0}; - char updateSql[1024] = { 0 }; - char tableName[100]={0x00}; - sprintf(whereCon, "zigbeeShortAddr='%s'", strShortAddr.c_str()); - vec_t vecDataNodeNo = sql_ctl->GetDataSingleLine(T_SENSOR_INFO(TNAME), " dataNodeNo,LooseValue ", whereCon); - memset(whereCon,0x00,sizeof(whereCon)); - sprintf(updateSql, "zigbeeSignalNode = '%02d' ",UartRecvBuf[i+14]&0xFF);//zigbeeRSSIType = 0 传感器获取网关信号强度 - sprintf(whereCon, "dataNodeNo='%s' and timeStamp = '%s'", (char*)vecDataNodeNo[0].c_str(),strTimetamp.c_str()); - sprintf(tableName,"t_dataStatic_%s",(char*)vecDataNodeNo[0].c_str()); - sql_ctl->UpdateTableData(tableName, updateSql, whereCon); + } mPackgeIndex = (unsigned int)UartRecvBuf[i+6]; @@ -683,13 +700,13 @@ int Uart::FindRecvPackage(int bytesRead, char* mUartRecvBuf,char* head) //pTestRecv(command); }else if(command == 218){//DA - LOG_INFO("zigbeeShortAddr = %s , signal = %02d\n",m_strDestShortAddr.c_str(),UartRecvBuf[i+6]&0xFF); + LOG_INFO("command = %d,zigbeeShortAddr = %s , signal = %02d,strTimetamp = %s\n",command,m_strDestShortAddr.c_str(),UartRecvBuf[i+6]&0xFF,strTimetamp.c_str()); char whereCon[1024] = {0}; char updateSql[1024] = { 0 }; char tableName[100]={0x00}; bZigbeeSinal = false; sprintf(whereCon, "zigbeeShortAddr='%s'", m_strDestShortAddr.c_str()); - vec_t vecDataNodeNo = sql_ctl->GetDataSingleLine(T_SENSOR_INFO(TNAME), " dataNodeNo,LooseValue ", whereCon); + vec_t vecDataNodeNo = sql_ctl->GetDataSingleLine(T_SENSOR_INFO(TNAME), " dataNodeNo,LooseValue,RSSI ", whereCon); memset(whereCon,0x00,sizeof(whereCon)); sprintf(updateSql, "zigbeeSignal = '%02d' ",UartRecvBuf[i+6]&0xFF);//zigbeeRSSIType = 1 网关获取传感器信号强度 sprintf(whereCon, "dataNodeNo='%s' and timeStamp = '%s'", (char*)vecDataNodeNo[0].c_str(),strTimetamp.c_str()); @@ -704,6 +721,18 @@ int Uart::FindRecvPackage(int bytesRead, char* mUartRecvBuf,char* head) }else{ jsBody["looseStatus"] = "0"; } + vector vParamRSSI; + boost::split( vParamRSSI, vecDataNodeNo[2], boost::is_any_of( "," ), boost::token_compress_on ); + if(vParamRSSI.size() == 1){ + sprintf(updateSql, "RSSI = '%02d,%s' ",UartRecvBuf[i+6]&0xFF,vParamRSSI[0].c_str()); + LOG_INFO(updateSql); + + }else if(vParamRSSI.size() == 2){ + sprintf(updateSql, "RSSI = '%02d,%s' ",UartRecvBuf[i+6]&0xFF,vParamRSSI[1].c_str()); + LOG_INFO(updateSql); + } + sprintf(whereCon, "dataNodeNo='%s'", (char*)vecDataNodeNo[0].c_str()); + sql_ctl->UpdateTableData(T_SENSOR_INFO(TNAME), updateSql, whereCon); jsonVal["cmd"] = "52"; jsBody["timeStamp"] = strTimetamp; @@ -712,8 +741,6 @@ int Uart::FindRecvPackage(int bytesRead, char* mUartRecvBuf,char* head) std::string dataBody = showValue.write(jsBody); jsonVal["cmdBody"] = dataBody; data_publish(showValue.write(jsonVal).c_str(), GlobalConfig::Topic_G.mPubConfig.c_str()); - - //pTestRecv(command); } } } @@ -1222,6 +1249,8 @@ void Uart::UpdateWirelessNode(unsigned short shortAdd) GlobalConfig::EnterZigBeeWaveTransmittingCnt_G = 0; LOG_INFO("UpdateWirelessNode end"); } + + int Uart::UpdateConfig(unsigned char* pDestShortAddr) { char whereCon[64] = { 0 }; @@ -1247,12 +1276,12 @@ int Uart::UpdateConfig(unsigned char* pDestShortAddr) char tmpbuf[8] = {0x00}; sprintf(tmpbuf,"%02x%02x",pDestShortAddr[0],pDestShortAddr[1]); m_strDestShortAddr = std::string(tmpbuf); - modify_distaddr_info(localAddr,"",pDestShortAddr);//临时参数配置 + //modify_distaddr_info(localAddr,"",pDestShortAddr);//临时参数配置 GlobalConfig::Zigbee_G.MyAddr = 0x9999; boost::this_thread::sleep(boost::posix_time::milliseconds(500)); vec_t vecResult; sprintf(selCon,"featureInterVal,waveInterVal,range,samplingRate,ACCSampleTime,startBrands,stopBrands,\ - envelopeBandPass,faultFrequency,timeStamp,viff"); + envelopeBandPass,faultFrequency,timeStamp,viff,ZigbeePower,ZigbeeRetry,MeasurementID"); vecResult = sql_ctl->GetDataSingleLine(T_SENSOR_INFO(TNAME),selCon,whereCon); print_info("vecResult size = %d\n",vecResult.size()); if(vecResult.size() < 1){ @@ -1267,7 +1296,7 @@ int Uart::UpdateConfig(unsigned char* pDestShortAddr) UpdateData[4]=pDestShortAddr[1]; UpdateData[5]=0x22; UpdateData[6]=0x00; - UpdateData[7]=0xAA; + UpdateData[7]=0x01; UpdateData[8]=UINT16_LOW(atoi(vecResult[0].c_str())); UpdateData[9]=UINT16_HIGH(atoi(vecResult[1].c_str())); UpdateData[10]=UINT16_LOW(atoi(vecResult[1].c_str())); @@ -1299,6 +1328,8 @@ int Uart::UpdateConfig(unsigned char* pDestShortAddr) y = 6; } } + UpdateData[18] = atoi(vecResult[11].c_str()) & 0xFF;; + UpdateData[19] = atoi(vecResult[12].c_str()) & 0xFF;; int x = atoi(vecResult[2].c_str()); UpdateData[21] = BUILD_UINT2(x,y); UpdateData[22] = atoi(vecResult[4].c_str()) & 0xFF; @@ -1355,14 +1386,76 @@ int Uart::UpdateConfig(unsigned char* pDestShortAddr) UpdateData[58] = UINT32_LOW_2(atoi(vecResult[9].c_str())); UpdateData[59] = (atoi(vecResult[10].c_str())) & 0xFF; - unsigned char tmp = 0x00; - for(int k = 0; k < 99;k++){ - tmp +=UpdateData[k]; + + size_t bytesSize = strlen(vecResult[13].c_str()) / 2; + unsigned char* bytes = (unsigned char*)malloc(bytesSize); + + if (hexStringToBytes(vecResult[13].c_str(), bytes, bytesSize) != 0) { + free(bytes); + }else{ + UpdateData[60] = bytes[0]; + UpdateData[61] = bytes[1]; + UpdateData[62] = bytes[2]; + UpdateData[63] = bytes[3]; + UpdateData[64] = bytes[4]; + UpdateData[65] = bytes[5]; + UpdateData[66] = bytes[6]; + UpdateData[67] = bytes[7]; } - UpdateData[99] = tmp; + + free(bytes); + unsigned char tmp1 = 0x00; + for(int k = 0; k < 99;k++){ + tmp1 +=UpdateData[k]; + } + UpdateData[99] = tmp1; tcflush(fd,TCIFLUSH); WriteToUart((const char*)UpdateData,100); return 0; + }else if(vecResultNode[41] == "-1"){ + + bUpdateconfig = true; + unsigned short localAddr = 0x9999; + GlobalConfig::EnterZigBeeWaveTransmittingFlag_G = ENTER_TRANSMITTING_STATUS; + GlobalConfig::EnterZigBeeWaveTransmittingCnt_G = 0; + string strName = sql_ctl->GetData(T_SENSOR_INFO(TNAME)," dataNodeName ",whereCon); + + unsigned char UpdateData[100]={0x00}; + //帧头[3byte] 节点地址[2byte] 数据类型[1byte] 序号[1byte] 数据包[92byte] CRC校验[1byte] + UpdateData[0]=0xAA; + UpdateData[1]=0x55; + UpdateData[2]=0xAA; + UpdateData[3]=pDestShortAddr[0]; + UpdateData[4]=pDestShortAddr[1]; + UpdateData[5]=0x22; + UpdateData[6]=0x00; + UpdateData[7]=0x02; + char hex[200]={0X00}; + stringToHex(strName.c_str(),hex); + size_t bytesSize = strlen(hex) / 2; + unsigned char* bytes = (unsigned char*)malloc(bytesSize); + + if (hexStringToBytes(hex, bytes, bytesSize) != 0) { + free(bytes); + }else{ + for (size_t i = 0; i < bytesSize; i++) + { + UpdateData[8 + i] = bytes[i]; + } + free(bytes); + unsigned char tmp1 = 0x00; + for(int k = 0; k < 99;k++){ + tmp1 += UpdateData[k]; + } + UpdateData[99] = tmp1; + tcflush(fd,TCIFLUSH); + WriteToUart((const char*)UpdateData,100); + return 0; + + } + + + }else{ return -1; } @@ -1465,40 +1558,69 @@ void Uart::DealRecvData(const char *pData) void Uart::DealDataNodeName(const char* pData) { bSendTimeStamp = false; + print_info("DealDataNodeName \n"); string strTime = GetLocalTimeWithMs(); //LOG_INFO("DealDataNodeName Time = %s\n",strTime.c_str()); - unsigned char shortAdd[8]={0x00}; + char szShortAdd[8]={0x00}; + char shortAdd[8]={0x00}; char NodeName[64]={0x00}; + sprintf(szShortAdd, "%02x%02x", pData[3]&0xFF,pData[4]&0xFF); + memcpy(NodeName,&pData[7],64); memcpy(shortAdd,&pData[3],2); - //memcpy(NodeName,&pData[7],64); - - //DealNodeSendTime((unsigned char*)shortAdd); + char whereCon[64] = { 0 }; + char uplCon[200]={0x00}; + int iRet = -1; + UpdateWirelessNodeTime((unsigned char*)shortAdd,1); for(int i = 0; i < 64;i++){ sprintf(&NodeName[i * 2], "%02X", pData[7 + i]&0xFF); } - + char MeasurementID[100]={0x00}; + sprintf(MeasurementID, "%02x%02x%02x%02x%02x%02x%02x%02x", pData[71], pData[72], pData[73], pData[74], + pData[75], pData[76], pData[77],pData[78]); char gbkNodeName[128]={0x00}; + sprintf(whereCon, "zigbeeShortAddr='%s'", szShortAdd); + print_info("whereCon = %s\n",whereCon); + array_t vecRes = sql_ctl->GetDataMultiLine(T_SENSOR_INFO(TNAME)," dataNodeNo, MeasurementID,hardVersion,softVersion",whereCon); + if(vecRes.size() > 1){ + for(int i = 0; i < vecRes.size();i++){ + if(vecRes[i][1] != ""){ + char whereCon1[64] = { 0 }; + sprintf(whereCon1, " dataNodeNo='%s' ", vecRes[i][0].c_str()); + sql_ctl->DeleteTableData(T_SENSOR_INFO(TNAME), whereCon1); + sql_ctl->DeleteTableData(T_DATA_INFO(TNAME), whereCon1); + sql_ctl->DeleteTableData(T_DATASTATIC_INFO(TNAME), whereCon1); + sql_ctl->DeleteTableData(T_DATANODE_TIME(TNAME), whereCon1); + char szTableName[50]={0x00}; + sprintf(szTableName,"DROP TABLE t_data_%s",vecRes[i][0].c_str()); + sql_ctl->CreateTable(szTableName, 0); + memset(szTableName,0x00,sizeof(szTableName)); + sprintf(szTableName,"DROP TABLE t_dataStatic_%s",vecRes[i][0].c_str()); + sql_ctl->CreateTable(szTableName, 0); + } + } + } + string hardVersion = vecRes[0][2]; + string softVersion = vecRes[0][3]; + if((hardVersion == "3.0" && compareVersions(softVersion,"3.6") == -1) || + (hardVersion == "4.0" && compareVersions(softVersion,"4.6") == -1)){ + memcpy(MeasurementID , vecRes[0][0].c_str(),sizeof(MeasurementID)); + } std::string strNodeName(NodeName); print_info("strNodeName = %s\n",strNodeName.c_str()); solve(gbkNodeName,NodeName); print_info("gbkNodeName = %s\n",gbkNodeName); string utfNodeName = GBKToUTF8(gbkNodeName); print_info("NodeName = %s\n",NodeName); - //LOG_INFO("gbkNodeName:%s \n",gbkNodeName); - //LOG_INFO("utfNodeName:%s \n",utfNodeName.c_str()); - unsigned short ushortAdd = BUILD_UINT16(pData[3]&0xFF,pData[4]&0xFF); - char whereCon[64] = { 0 }; - char uplCon[200]={0x00}; - sprintf(whereCon, "zigbeeShortAddr='%02x%02x'", shortAdd[0],shortAdd[1]); print_info("whereCon = %s\n",whereCon); - sprintf(uplCon,"dataNodeName = '%s'",gbkNodeName); - int iRet = sql_ctl->UpdateTableData(T_SENSOR_INFO(TNAME),uplCon,whereCon,0); + sprintf(uplCon,"dataNodeName = '%s' , MeasurementID = '%s'",gbkNodeName,MeasurementID); + iRet = sql_ctl->UpdateTableData(T_SENSOR_INFO(TNAME),uplCon,whereCon,0); string strData = sql_ctl->GetNodeConfigureInfor(whereCon); iRet = data_publish(strData.c_str(), GlobalConfig::Topic_G.mPubConfig.c_str()); } + void Uart::DealDataNodeInfo(const char *pData) { print_info("recv remote zigbee module info\n"); @@ -1735,7 +1857,7 @@ void Uart::DealDataNodeInfo(const char *pData) StaticTime = '%d',WaveTime = '%d',BateryV = '%d',ProductNo = '%s',configFlag = '%d',startBrands = '%s',\ stopBrands = '%s',featureInterVal = '%u',waveInterVal = '%d',samplingRate = '%d',scope = '%s',range = '%d',envelopeBandPass = '%s',faultFrequency = '%s',\ zigbeePanId = '%s',zigbeeChannel = '%d',zigbeeShortAddr = '%s',zigbeeLongAddr = '%s',zigbeeDesAddr = '%s',\ - ZigbeePower = '%d',ZigbeeRetry = '%d',ZigbeeRetryGap = '%d',ACCSampleTime = '%d',status = '%s',timeStamp = '%s',viff = '%d',RSSI = '%d',UpdateFlag = 1", + ZigbeePower = '%d',ZigbeeRetry = '%d',ZigbeeRetryGap = '%d',ACCSampleTime = '%d',status = '%s',timeStamp = '%s',viff = '%d',RSSI = '0,%d',UpdateFlag = 1", dataNodeInfo.InitFlag, dataNodeInfo.AccFlag, dataNodeInfo.ZigbeeFlag, dataNodeInfo.TemTopFlag, dataNodeInfo.TemBotFlag,dataNodeInfo.EquipSta,\ dataNodeInfo.HardVersion.c_str(), dataNodeInfo.SoftVersion.c_str(), dataNodeInfo.BpNo.c_str(), dataNodeInfo.SerialNo.c_str(), dataNodeInfo.FirstPowerTime.c_str(), dataNodeInfo.WakeupTime,\ dataNodeInfo.StaticTime,dataNodeInfo.WaveTime,dataNodeInfo.BateryV,dataNodeInfo.ProductNo.c_str(),dataNodeInfo.ConfigFlag, dataNodeInfo.StartBrands.c_str(), \ @@ -1751,7 +1873,7 @@ void Uart::DealDataNodeInfo(const char *pData) '%d','%d','%d','%s','%d','%s',\ '%s','%u','%d','%d','%s','%d', '%s', '%s',\ '%s','%d','%s','%s','%s',\ - '%d','%d','%d','%d','%s','%s', '%d', '%d','1','0,0',''", + '%d','%d','%d','%d','%s','%s', '%d', '0,%d','1','0,0','',''", dataNodeInfo.ZigbeeLongAddr.c_str(), " ", dataNodeInfo.InitFlag, dataNodeInfo.AccFlag, dataNodeInfo.ZigbeeFlag, dataNodeInfo.TemTopFlag, dataNodeInfo.TemBotFlag,dataNodeInfo.EquipSta,\ dataNodeInfo.HardVersion.c_str(), dataNodeInfo.SoftVersion.c_str(), dataNodeInfo.BpNo.c_str(), dataNodeInfo.SerialNo.c_str(), dataNodeInfo.FirstPowerTime.c_str(), dataNodeInfo.WakeupTime,\ dataNodeInfo.StaticTime,dataNodeInfo.WaveTime,dataNodeInfo.BateryV,dataNodeInfo.ProductNo.c_str(),dataNodeInfo.ConfigFlag, dataNodeInfo.StartBrands.c_str(), \ @@ -1826,7 +1948,13 @@ void Uart::DealDataNodeInfo(const char *pData) } - +void Uart::RecordBattery(string & strLongAddr,DataRecvStatic& dataStatic,string& nowTimetamp) +{ + char insertSql[1024] = { 0 }; + sprintf(insertSql, "'%s','%d','%f','%f','%f','%d','','','%s'", + strLongAddr.c_str(), dataStatic.Dip, dataStatic.TemBot,dataStatic.nodeWorkTime,dataStatic.nodeSendTime, dataStatic.Voltage,nowTimetamp.c_str()); + sql_ctl->InsertData(T_BATTERY_INFO(TNAME), insertSql); +} void Uart::DealDataNodeFeature(const char *pData, int flag) { print_info("recv feature\n"); @@ -1844,7 +1972,7 @@ void Uart::DealDataNodeFeature(const char *pData, int flag) //根据数据包中的传感器的短地址获取数据库中长地址(MAC),在下面判断该传感器是否存在,如果不存在则把数据包丢弃 sprintf(getLongAddr_sql, "zigbeeShortAddr='%s'", strShortAddr.c_str()); //std::string strLongAddr = sql_ctl->GetData(T_SENSOR_INFO(TNAME), T_SENSOR_INFO(ZIGBEELONGADDR), getLongAddr_sql); - vec_t vecResult = sql_ctl->GetDataSingleLine(T_SENSOR_INFO(TNAME)," softVersion,zigbeeLongAddr ",getLongAddr_sql); + vec_t vecResult = sql_ctl->GetDataSingleLine(T_SENSOR_INFO(TNAME)," softVersion,dataNodeNo,MeasurementID ",getLongAddr_sql); if (vecResult.size() < 1) { LOG_ERROR("device info not found %02x%02x\n",pRecvData->ShortAddr[0], pRecvData->ShortAddr[1]); @@ -1854,6 +1982,7 @@ void Uart::DealDataNodeFeature(const char *pData, int flag) print_info("--------->the remote sensor short addr:%s strLongAddr=%s,softVersion = %s\n",buf,vecResult[1].c_str(),vecResult[0].c_str()); std::string strLongAddr = vecResult[1]; + std::string strMeasurementID = vecResult[2]; if (1 == flag) { tcflush(fd,TCIOFLUSH); @@ -1956,6 +2085,57 @@ void Uart::DealDataNodeFeature(const char *pData, int flag) sprintf(buf, "%02x%02x", pRecvData->Data[7], pRecvData->Data[6]); iTemp = (int)strtol(buf, NULL, 16); dataStatic.Voltage = iTemp; + + memset(buf, 0, sizeof(buf)); + sprintf(buf, "%02x%02x", pRecvData->Data[31], pRecvData->Data[30]); + + iTemp = (unsigned int)strtol(buf, NULL, 16); + highbit = iTemp >> 14 & 0x3; + lowbit = iTemp & 0x3fff; + switch (highbit) + { + case 0: + n = 0.0001; + break; + case 1: + n = 0.01; + break; + case 2: + n = 1; + break; + case 3: + n = 100; + break; + } + dataStatic.nodeWorkTime = lowbit * n; + + print_info("workTime = %f\n",dataStatic.nodeWorkTime); + + memset(buf, 0, sizeof(buf)); + sprintf(buf, "%02x%02x", pRecvData->Data[33], pRecvData->Data[32]); + iTemp = (unsigned int)strtol(buf, NULL, 16); + highbit = iTemp >> 14 & 0x3; + lowbit = iTemp & 0x3fff; + switch (highbit) + { + case 0: + n = 0.0001; + break; + case 1: + n = 0.01; + break; + case 2: + n = 1; + break; + case 3: + n = 100; + break; + } + dataStatic.nodeSendTime = lowbit * n; + print_info("SendTime = %f\n",dataStatic.nodeSendTime ); + dataStatic.nodeWorkTime = dataStatic.nodeWorkTime - dataStatic.nodeSendTime; + + RecordBattery(strLongAddr,dataStatic,nowTimetamp); char szTableName[50]={0x00},szTableNameStatic[50]={0x00},szTableNameData[50]={0x00}; sprintf(szTableName,"t_dataStatic_%s",strLongAddr.c_str()); @@ -2005,36 +2185,37 @@ void Uart::DealDataNodeFeature(const char *pData, int flag) sql_ctl->CreateTable(sztmp); } - //////////////////////////////////////////////////////////// - std::string strStaticIndex = sql_ctl->GetData(szTableNameStatic, "StaticIndex", "StaticIndex > 0 order by StaticIndex desc LIMIT 0 , 1"); - // if(abs(atol(strStaticIndex.c_str()) - staticIndex) > 100){ - // sql_ctl->Deletetable(szTableNameStatic); - // sql_ctl->Deletetable(szTableNameData); - // LOG_INFO("staticIndexNOW = %d,strStaticIndexLast = %s\n",staticIndex,strStaticIndex.c_str()); - // } - + ////////////////////////////////////////////////////////////更换电池判断 + sprintf(whereCon," dataNodeNo = '%s' and StaticIndex > 0 order by StaticIndex desc LIMIT 0 , 1 ",strLongAddr.c_str()); + std::string strStaticIndex = sql_ctl->GetData(szTableNameStatic, "StaticIndex", whereCon); + if(atol(strStaticIndex.c_str()) - staticIndex > 100){ + sql_ctl->Deletetable(szTableNameStatic); + sql_ctl->Deletetable(szTableNameData); + LOG_INFO("staticIndexNOW = %d,strStaticIndexLast = %s\n",staticIndex,strStaticIndex.c_str()); + } + print_info("NowstaticIndex = %d,RecordStaticIndex = %d",staticIndex,atol(strStaticIndex.c_str())); if(staticIndex != atol(strStaticIndex.c_str() + 1) && strStaticIndex != "" && staticIndex < atol(strStaticIndex.c_str())) { sprintf(whereCon,"StaticIndex = %d order by StaticIndex desc LIMIT 0 , 1",atol(strStaticIndex.c_str())); vec_t vecResult = sql_ctl->GetDataSingleLine(szTableNameStatic, "timeStamp,StaticIndex", whereCon); - memset(whereCon,0x00,sizeof(whereCon)); - sprintf(whereCon,"dataNodeNo = '%s'",strLongAddr.c_str()); - string staticInterval = sql_ctl->GetData(T_SENSOR_INFO(TNAME), "featureInterval", whereCon); - //LOG_INFO("vecResult0 = %s,vecResult1 = %s\n",vecResult[0].c_str(),vecResult[1].c_str()); - long nNowTimetamp = atol(vecResult[0].c_str()) - (atol(staticInterval.c_str()) * \ - (atol(vecResult[1].c_str()) - staticIndex)) * 60; - char tmp[10]={0x00}; - sprintf(tmp,"%ld",nNowTimetamp); - nowTimetamp = string(tmp); - nodeResend = 1; - //LOG_INFO("nowTimetamp = %s,strOldTime = %s\n",nowTimetamp.c_str(),vecResult[0].c_str()); + if(vecResult.size() > 0){ + memset(whereCon,0x00,sizeof(whereCon)); + sprintf(whereCon,"dataNodeNo = '%s'",strLongAddr.c_str()); + string staticInterval = sql_ctl->GetData(T_SENSOR_INFO(TNAME), "featureInterval", whereCon); + long nNowTimetamp = atol(vecResult[0].c_str()) - (atol(staticInterval.c_str()) * \ + (atol(vecResult[1].c_str()) - staticIndex)) * 60; + char tmp[10]={0x00}; + sprintf(tmp,"%ld",nNowTimetamp); + nowTimetamp = string(tmp); + nodeResend = 1; + } } print_info("nowTimetamp = %s",nowTimetamp.c_str()); // save dataStatic of 7 days char selectCon[128] = { 0 }; - sprintf(selectCon, "channelID='%s' and sendMsg = '1' ORDER BY timeStamp ASC LIMIT 0,1",(strLongAddr + "-S").c_str()); + sprintf(selectCon, "channelID='%s' and sendMsg = '1' ORDER BY timeStamp ASC LIMIT 0,1",(strMeasurementID + "-S").c_str()); std::string strTime = sql_ctl->GetData(szTableName, "timeStamp", selectCon); int Count = sql_ctl->GetTableRows(szTableName, NULL); if(Count == -1){ @@ -2047,32 +2228,39 @@ void Uart::DealDataNodeFeature(const char *pData, int flag) print_info("dataStatic.TemTop : %f dataStatic.TemBot : %f dataStatic.Dip :%d dataStatic.Voltage : %d\n", dataStatic.TemTop\ , dataStatic.TemBot, dataStatic.Dip, dataStatic.Voltage); - sprintf(updateSql, "temTop='%f',temBot='%f',dip='%d',voltage='%d',timeStamp='%s',StaticIndex = %d, nodeResend = %d",\ + sprintf(updateSql, "temTop='%f',temBot='%f',dip='%d',voltage='%d',timeStamp='%s',StaticIndex = %d, nodeResend = %d,zigbeeSignal = '',zigbeeSignalNode = '' ",\ dataStatic.TemTop, dataStatic.TemBot, dataStatic.Dip, dataStatic.Voltage, nowTimetamp.c_str(),staticIndex,nodeResend); - sprintf(whereCon, "channelID='%s' and sendMsg = '1'", (strLongAddr + "-S").c_str()); + sprintf(whereCon, "channelID='%s' and sendMsg = '1'", (strMeasurementID + "-S").c_str()); if ( /*0 == sql_ctl->GetTableRows(T_DATASTATIC_INFO(TNAME), whereCon)*/ (Count * 3 < SAVE_COUNT && lTime < OneWeek ) || strTime.size() == 0 ) { print_info("insert static data to sql\n"); char insertSql[1024] = { 0 }; sprintf(insertSql, "'%s','%s','%f','%f','%d','%d','',%d,'%s','1',%d,''", - strLongAddr.c_str(), (strLongAddr + "-S").c_str(), dataStatic.TemTop, dataStatic.TemBot, dataStatic.Dip, dataStatic.Voltage, staticIndex,nowTimetamp.c_str(),nodeResend); + strLongAddr.c_str(), (strMeasurementID + "-S").c_str(), dataStatic.TemTop, dataStatic.TemBot, dataStatic.Dip, dataStatic.Voltage, staticIndex,nowTimetamp.c_str(),nodeResend); sql_ctl->InsertData(szTableName, insertSql); if(0 == sql_ctl->GetTableRows(T_DATASTATIC_INFO(TNAME), whereCon)){ // First Connect char insertSql[1024] = { 0 }; sprintf(insertSql, "'%s','%s','%f','%f','%d','%d','',%d,'%s','1',%d", - strLongAddr.c_str(), (strLongAddr + "-S").c_str(), dataStatic.TemTop, dataStatic.TemBot, dataStatic.Dip, dataStatic.Voltage, staticIndex,nowTimetamp.c_str(),nodeResend); + strLongAddr.c_str(), (strMeasurementID + "-S").c_str(), dataStatic.TemTop, dataStatic.TemBot, dataStatic.Dip, dataStatic.Voltage, staticIndex,nowTimetamp.c_str(),nodeResend); sql_ctl->InsertData(T_DATASTATIC_INFO(TNAME), insertSql); sql_ctl->CalculateBattery(); } - else + else{ + memset(updateSql,0x00,sizeof(updateSql)); + sprintf(updateSql, "temTop='%f',temBot='%f',dip='%d',voltage='%d',timeStamp='%s',StaticIndex = %d ",\ + dataStatic.TemTop, dataStatic.TemBot, dataStatic.Dip, dataStatic.Voltage, nowTimetamp.c_str(),staticIndex,nodeResend); sql_ctl->UpdateTableData(T_DATASTATIC_INFO(TNAME), updateSql, whereCon); + } } else { memset(whereCon,0x00,sizeof(whereCon)); - sprintf(whereCon, "channelID='%s' and sendMsg = '1' and timeStamp = '%s'", (strLongAddr + "-S").c_str(),strTime.c_str()); + sprintf(whereCon, "channelID='%s' and sendMsg = '1' and timeStamp = '%s'", (strMeasurementID + "-S").c_str(),strTime.c_str()); print_info("update static data to sql\n"); sql_ctl->UpdateTableData(szTableName, updateSql, whereCon); memset(whereCon,0x00,sizeof(whereCon)); - sprintf(whereCon, "channelID='%s' ", (strLongAddr + "-S").c_str()); + sprintf(whereCon, "channelID='%s' ", (strMeasurementID + "-S").c_str()); + memset(updateSql,0x00,sizeof(updateSql)); + sprintf(updateSql, "temTop='%f',temBot='%f',dip='%d',voltage='%d',timeStamp='%s',StaticIndex = %d ",\ + dataStatic.TemTop, dataStatic.TemBot, dataStatic.Dip, dataStatic.Voltage, nowTimetamp.c_str(),staticIndex,nodeResend); sql_ctl->UpdateTableData(T_DATASTATIC_INFO(TNAME), updateSql, whereCon); } memset(szTableName,0x00,sizeof(szTableName)); @@ -2397,7 +2585,7 @@ void Uart::DealDataNodeFeature(const char *pData, int flag) dataDymX.Phase4 = 0; memset(whereCon, 0, 1024); - sprintf(whereCon, "channelID='%s' and sendMsg = '1'", (strLongAddr + "-X").c_str()); + sprintf(whereCon, "channelID='%s' and sendMsg = '1'", (strMeasurementID + "-X").c_str()); memset(updateSql, 0, 1024); sprintf(updateSql, "diagnosisPk='%f',integratPk='%f',integratRMS='%f',rmsValues='%f',envelopEnergy='%f',\ Amp1='%f',Amp2='%f',Amp3='%f',Amp4='%f',Amp5='%f',Phase1='%f',Phase2='%f',Phase3='%f',Phase4='%f',timeStamp='%s',StaticIndex = %d,nodeResend = %d ",\ @@ -2407,7 +2595,7 @@ void Uart::DealDataNodeFeature(const char *pData, int flag) char insertSql[1024] = { 0 }; memset(insertSql,0x00,sizeof(insertSql)); sprintf(insertSql, "'%s','%s','%f','%f','%f','%f','%f','%f','%f','%f','%f','%f','%f','%f','%f','%f',%d,'%s','1',%d", - strLongAddr.c_str(), (strLongAddr + "-X").c_str(), dataDymX.DiagnosisPk, dataDymX.IntegratPk, dataDymX.IntegratRMS, dataDymX.RmsValues, dataDymX.EnvelopEnergy,\ + strLongAddr.c_str(), (strMeasurementID + "-X").c_str(), dataDymX.DiagnosisPk, dataDymX.IntegratPk, dataDymX.IntegratRMS, dataDymX.RmsValues, dataDymX.EnvelopEnergy,\ dataDymX.Amp1, dataDymX.Amp2, dataDymX.Amp3, dataDymX.Amp4, dataDymX.Amp5,dataDymX.Phase1, dataDymX.Phase2, dataDymX.Phase3, dataDymX.Phase4, staticIndex,nowTimetamp.c_str(),nodeResend); sql_ctl->InsertData(szTableName, insertSql); @@ -2417,21 +2605,21 @@ void Uart::DealDataNodeFeature(const char *pData, int flag) sql_ctl->UpdateTableData(T_DATA_INFO(TNAME), updateSql, whereCon); } else { memset(whereCon,0x00,sizeof(whereCon)); - sprintf(whereCon, "channelID='%s' and sendMsg = '1' and timeStamp = '%s'", (strLongAddr + "-X").c_str(),strTime.c_str()); + sprintf(whereCon, "channelID='%s' and sendMsg = '1' and timeStamp = '%s'", (strMeasurementID + "-X").c_str(),strTime.c_str()); // sprintf(whereCon, "channelID='%s' and sendMsg = '1' ", (strLongAddr + "-X").c_str()); sql_ctl->UpdateTableData(szTableName, updateSql, whereCon); memset(whereCon,0x00,sizeof(whereCon)); - sprintf(whereCon, "channelID='%s' ", (strLongAddr + "-X").c_str()); + sprintf(whereCon, "channelID='%s' ", (strMeasurementID + "-X").c_str()); sql_ctl->UpdateTableData(T_DATA_INFO(TNAME), updateSql, whereCon); } print_info("x:%s,%s,diagnosisPk=%f,integratPk=%f,integratRMS=%f,rmsValues=%f,envelopEnergy=%f,Amp1=%f,Amp2=%f,Amp3=%f,Amp4=%f,Amp5=%f,Phase1=%f,Phase2=%f,Phase3=%f,Phase4=%f,timeStamp=%s\n",\ - strLongAddr.c_str(), (strLongAddr + "-X").c_str(), dataDymX.DiagnosisPk, dataDymX.IntegratPk, dataDymX.IntegratRMS, dataDymX.RmsValues, dataDymX.EnvelopEnergy,\ + strLongAddr.c_str(), (strMeasurementID + "-X").c_str(), dataDymX.DiagnosisPk, dataDymX.IntegratPk, dataDymX.IntegratRMS, dataDymX.RmsValues, dataDymX.EnvelopEnergy,\ dataDymX.Amp1, dataDymX.Amp2, dataDymX.Amp3, dataDymX.Amp4, dataDymX.Amp5,dataDymX.Phase1, dataDymX.Phase2, dataDymX.Phase3, dataDymX.Phase4, nowTimetamp.c_str()); Json::Value valNodeData; Json::Value valNodeFeature; - valNodeFeature["dataNodeNo"] = strLongAddr; - valNodeFeature["ChannelId"] = strLongAddr + "-X"; + valNodeFeature["dataNodeNo"] = strMeasurementID; + valNodeFeature["ChannelId"] = strMeasurementID + "-X"; valNodeFeature["diagnosisPk"] = dataDymX.DiagnosisPk; valNodeFeature["integratPk"] = dataDymX.IntegratPk; valNodeFeature["integratRMS"] = dataDymX.IntegratRMS; @@ -2760,7 +2948,7 @@ void Uart::DealDataNodeFeature(const char *pData, int flag) dataDymY.Phase4 = 0; memset(whereCon, 0, 1024); - sprintf(whereCon, "channelID='%s' and sendMsg = '1'", (strLongAddr + "-Y").c_str()); + sprintf(whereCon, "channelID='%s' and sendMsg = '1'", (strMeasurementID + "-Y").c_str()); memset(updateSql, 0, 1024); sprintf(updateSql, "diagnosisPk='%f',integratPk='%f',integratRMS='%f',rmsValues='%f',envelopEnergy='%f',\ Amp1='%f',Amp2='%f',Amp3='%f',Amp4='%f',Amp5='%f',Phase1='%f',Phase2='%f',Phase3='%f',Phase4='%f',timeStamp='%s',StaticIndex = %d,nodeResend = %d ",\ @@ -2770,7 +2958,7 @@ void Uart::DealDataNodeFeature(const char *pData, int flag) char insertSql[1024] = { 0 }; memset(insertSql,0x00,sizeof(insertSql)); sprintf(insertSql, "'%s','%s','%f','%f','%f','%f','%f','%f','%f','%f','%f','%f','%f','%f','%f','%f',%d,'%s','1',%d", - strLongAddr.c_str(), (strLongAddr + "-Y").c_str(), dataDymY.DiagnosisPk, dataDymY.IntegratPk, dataDymY.IntegratRMS, dataDymY.RmsValues, dataDymY.EnvelopEnergy,\ + strLongAddr.c_str(), (strMeasurementID + "-Y").c_str(), dataDymY.DiagnosisPk, dataDymY.IntegratPk, dataDymY.IntegratRMS, dataDymY.RmsValues, dataDymY.EnvelopEnergy,\ dataDymY.Amp1, dataDymY.Amp2, dataDymY.Amp3, dataDymY.Amp4, dataDymY.Amp5,dataDymY.Phase1, dataDymY.Phase2, dataDymY.Phase3, dataDymY.Phase4,staticIndex, nowTimetamp.c_str(),nodeResend); sql_ctl->InsertData(szTableName, insertSql); @@ -2781,20 +2969,20 @@ void Uart::DealDataNodeFeature(const char *pData, int flag) } else { memset(whereCon,0x00,sizeof(whereCon)); - sprintf(whereCon, "channelID='%s' and sendMsg = '1' and timeStamp = '%s'", (strLongAddr + "-Y").c_str(),strTime.c_str()); + sprintf(whereCon, "channelID='%s' and sendMsg = '1' and timeStamp = '%s'", (strMeasurementID + "-Y").c_str(),strTime.c_str()); // sprintf(whereCon, "channelID='%s' and sendMsg = '1' ", (strLongAddr + "-Y").c_str()); sql_ctl->UpdateTableData(szTableName, updateSql, whereCon); memset(whereCon,0x00,sizeof(whereCon)); - sprintf(whereCon, "channelID='%s' ", (strLongAddr + "-Y").c_str()); + sprintf(whereCon, "channelID='%s' ", (strMeasurementID + "-Y").c_str()); sql_ctl->UpdateTableData(T_DATA_INFO(TNAME), updateSql, whereCon); } print_info("y: %s,%s,diagnosisPk=%f,integratPk=%f,integratRMS=%f,rmsValues=%f,envelopEnergy=%f,Amp1=%f,Amp2=%f,Amp3=%f,Amp4=%f,Amp5=%f,Phase1=%f,Phase2=%f,Phase3=%f,Phase4=%f,timeStamp=%s\n",\ - strLongAddr.c_str(), (strLongAddr + "-Y").c_str(), dataDymY.DiagnosisPk, dataDymY.IntegratPk, dataDymY.IntegratRMS, dataDymY.RmsValues, dataDymY.EnvelopEnergy,\ + strLongAddr.c_str(), (strMeasurementID + "-Y").c_str(), dataDymY.DiagnosisPk, dataDymY.IntegratPk, dataDymY.IntegratRMS, dataDymY.RmsValues, dataDymY.EnvelopEnergy,\ dataDymY.Amp1, dataDymY.Amp2, dataDymY.Amp3, dataDymY.Amp4, dataDymY.Amp5,dataDymY.Phase1, dataDymY.Phase2, dataDymY.Phase3, dataDymY.Phase4, nowTimetamp.c_str()); - valNodeFeature["dataNodeNo"] = strLongAddr; - valNodeFeature["ChannelId"] = strLongAddr + "-Y"; + valNodeFeature["dataNodeNo"] = strMeasurementID; + valNodeFeature["ChannelId"] = strMeasurementID + "-Y"; valNodeFeature["diagnosisPk"] = dataDymY.DiagnosisPk; valNodeFeature["integratPk"] = dataDymY.IntegratPk; valNodeFeature["integratRMS"] = dataDymY.IntegratRMS; @@ -3121,7 +3309,7 @@ void Uart::DealDataNodeFeature(const char *pData, int flag) dataDymZ.Phase4 = lowbit * n; memset(whereCon, 0, 1024); - sprintf(whereCon, "channelID='%s' and sendMsg = '1'", (strLongAddr + "-Z").c_str()); + sprintf(whereCon, "channelID='%s' and sendMsg = '1'", (strMeasurementID + "-Z").c_str()); memset(updateSql, 0, 1024); sprintf(updateSql, "diagnosisPk='%f',integratPk='%f',integratRMS='%f',rmsValues='%f',envelopEnergy='%f',\ @@ -3132,7 +3320,7 @@ void Uart::DealDataNodeFeature(const char *pData, int flag) char insertSql[1024] = { 0 }; memset(insertSql,0x00,sizeof(insertSql)); sprintf(insertSql, "'%s','%s','%f','%f','%f','%f','%f','%f','%f','%f','%f','%f','%f','%f','%f','%f',%d,'%s','1',%d", - strLongAddr.c_str(), (strLongAddr + "-Z").c_str(), dataDymZ.DiagnosisPk, dataDymZ.IntegratPk, dataDymZ.IntegratRMS, dataDymZ.RmsValues, dataDymZ.EnvelopEnergy,\ + strLongAddr.c_str(), (strMeasurementID + "-Z").c_str(), dataDymZ.DiagnosisPk, dataDymZ.IntegratPk, dataDymZ.IntegratRMS, dataDymZ.RmsValues, dataDymZ.EnvelopEnergy,\ dataDymZ.Amp1, dataDymZ.Amp2, dataDymZ.Amp3, dataDymZ.Amp4, dataDymZ.Amp5,dataDymZ.Phase1, dataDymZ.Phase2, dataDymZ.Phase3, dataDymZ.Phase4, staticIndex,nowTimetamp.c_str(),nodeResend); sql_ctl->InsertData(szTableName, insertSql); @@ -3143,15 +3331,15 @@ void Uart::DealDataNodeFeature(const char *pData, int flag) } else { memset(whereCon,0x00,sizeof(whereCon)); - sprintf(whereCon, "channelID='%s' and sendMsg = '1' and timeStamp = '%s'", (strLongAddr + "-Z").c_str(),strTime.c_str()); + sprintf(whereCon, "channelID='%s' and sendMsg = '1' and timeStamp = '%s'", (strMeasurementID + "-Z").c_str(),strTime.c_str()); // sprintf(whereCon, "channelID='%s' and sendMsg = '1'", (strLongAddr + "-Z").c_str()); sql_ctl->UpdateTableData(szTableName, updateSql, whereCon); memset(whereCon,0x00,sizeof(whereCon)); - sprintf(whereCon, "channelID='%s' ", (strLongAddr + "-Z").c_str()); + sprintf(whereCon, "channelID='%s' ", (strMeasurementID + "-Z").c_str()); sql_ctl->UpdateTableData(T_DATA_INFO(TNAME), updateSql, whereCon); } print_info("Z: %s,%s,diagnosisPk=%f,integratPk=%f,integratRMS=%f,rmsValues=%f,envelopEnergy=%f,Amp1=%f,Amp2=%f,Amp3=%f,Amp4=%f,Amp5=%f,Phase1=%f,Phase2=%f,Phase3=%f,Phase4=%f,timeStamp=%s\n",\ - strLongAddr.c_str(), (strLongAddr + "-Z").c_str(), dataDymZ.DiagnosisPk, dataDymZ.IntegratPk, dataDymZ.IntegratRMS, dataDymZ.RmsValues, dataDymZ.EnvelopEnergy,\ + strLongAddr.c_str(), (strMeasurementID + "-Z").c_str(), dataDymZ.DiagnosisPk, dataDymZ.IntegratPk, dataDymZ.IntegratRMS, dataDymZ.RmsValues, dataDymZ.EnvelopEnergy,\ dataDymZ.Amp1, dataDymZ.Amp2, dataDymZ.Amp3, dataDymZ.Amp4, dataDymZ.Amp5,dataDymZ.Phase1, dataDymZ.Phase2, dataDymZ.Phase3, dataDymZ.Phase4, nowTimetamp.c_str()); memset(whereCon,0x00,sizeof(whereCon)); @@ -3160,8 +3348,8 @@ void Uart::DealDataNodeFeature(const char *pData, int flag) //string strData = sql_ctl->GetNodeConfigureInfor(whereCon); //data_publish(strData.c_str(), GlobalConfig::Topic_G.mPubConfig.c_str()); //无线传感器Z信息 - valNodeFeature["dataNodeNo"] = strLongAddr; - valNodeFeature["ChannelId"] = strLongAddr + "-Z"; + valNodeFeature["dataNodeNo"] = strMeasurementID; + valNodeFeature["ChannelId"] = strMeasurementID + "-Z"; valNodeFeature["diagnosisPk"] = dataDymZ.DiagnosisPk; valNodeFeature["integratPk"] = dataDymZ.IntegratPk; valNodeFeature["integratRMS"] = dataDymZ.IntegratRMS; @@ -3196,19 +3384,21 @@ void Uart::DealDataNodeFeature(const char *pData, int flag) Json::Value valdatastatic; valdatastatic["TemperatureTop"] = dataStatic.TemTop; valdatastatic["TemperatureBot"] = dataStatic.TemBot; + valdatastatic["WorkTime"] = dataStatic.nodeWorkTime; + valdatastatic["SendTime"] = dataStatic.nodeSendTime; valdatastatic["Dip"] = dataStatic.Dip; valdatastatic["Voltage"] = dataStatic.Voltage; valdatastatic["ChannelType"] = "STATUS"; - valdatastatic["ChannelId"] = strLongAddr + "-S"; + valdatastatic["ChannelId"] = strMeasurementID + "-S"; valdatastatic["TimeStamp"] = nowTimetamp; - valdatastatic["bateryProportion"] = atof(vBattery[0].c_str()); + valdatastatic["bateryProportion"] = atof(vBattery[1].c_str())/atof(vBattery[0].c_str()); valdatastatic["batteryRemainDay"] = atof(vBattery[1].c_str()); - valdatastatic["dataNodeNo"] = strLongAddr; + valdatastatic["dataNodeNo"] = strMeasurementID; valNodeData.append(valdatastatic); root["data"] = valNodeData; root["TimeStamp"] = nowTimetamp; - root["dataNodeNo"] = strLongAddr; + root["dataNodeNo"] = strMeasurementID; root["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G; Json::FastWriter featureValue; std::string strstatisticData = featureValue.write(root); @@ -3244,7 +3434,7 @@ void Uart::DealDataNodeFeature(const char *pData, int flag) } bZigbeeSinal = false; } - + //LOG_INFO("DealDataNodeFeature end\n"); } void Uart::DealDataNodeWave(const char *pData) @@ -3313,6 +3503,7 @@ void Uart::DealWave() std::string strShortAddr = ""; std::string strShortAddrTemp; std::string strLongAddr = ""; + std::string strMeasurementID= ""; std::string strFileName = ""; int iChannel = 0; int iChannelTemp = 0; @@ -3338,7 +3529,8 @@ void Uart::DealWave() sprintf(getLongAddr_sql, "zigbeeShortAddr='%s'", strShortAddr.c_str()); //strLongAddr = sql_ctl->GetData(T_SENSOR_INFO(TNAME), T_SENSOR_INFO(ZIGBEELONGADDR), getLongAddr_sql); vec_t res = sql_ctl->GetDataSingleLine(T_SENSOR_INFO(TNAME)," * ",getLongAddr_sql); - strLongAddr = res[0]; + strLongAddr = res[0]; + strMeasurementID = res[44]; //print_info("3.1.2.3--->strLongAddr : %s\n", strLongAddr.c_str()); if ( 0 == strLongAddr.length() ) { sleep(1); @@ -3476,18 +3668,18 @@ void Uart::DealWave() switch (iChannel) { case 3:{ - strFileName = "/opt/data/" + strLongAddr + "-X.dat"; - strChannelID = strLongAddr + "-X"; + strFileName = "/opt/data/" + strMeasurementID + "-X.dat"; + strChannelID = strMeasurementID + "-X"; } break; case 4:{ - strFileName = "/opt/data/" + strLongAddr + "-Y.dat"; - strChannelID = strLongAddr + "-Y"; + strFileName = "/opt/data/" + strMeasurementID + "-Y.dat"; + strChannelID = strMeasurementID + "-Y"; } break; case 5:{ - strFileName = "/opt/data/" + strLongAddr + "-Z.dat"; - strChannelID = strLongAddr + "-Z"; + strFileName = "/opt/data/" + strMeasurementID + "-Z.dat"; + strChannelID = strMeasurementID + "-Z"; } break; default: @@ -3515,7 +3707,8 @@ void Uart::DealWave() std::string waveTemp(buf); if(i == 0) strWaveData = waveTemp; - strWaveData = strWaveData + "," + waveTemp; + else + strWaveData = strWaveData + "," + waveTemp; } fclose(fp); @@ -3524,7 +3717,7 @@ void Uart::DealWave() int length = vecData.size(); valWaveData["number"] = sampleRate; valWaveData["channelId"] = strChannelID; - valWaveData["dataNodeNo"] = strLongAddr; + valWaveData["dataNodeNo"] = strMeasurementID; valWaveData["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G; valWaveData["SensorEngineeringUnit"] = ""; valWaveData["timeStamp"] = nowTimetamp; diff --git a/uart/SH_Uart.hpp b/uart/SH_Uart.hpp index 1c769ba..62c4a9b 100644 --- a/uart/SH_Uart.hpp +++ b/uart/SH_Uart.hpp @@ -76,6 +76,7 @@ public : void DealNodeSendTime(unsigned char* shortaddr); void ZigbeeInit(); int ZigbeeTest(); + void RecordBattery(string & strLongAddr,DataRecvStatic& dataStatic,string& nowTimetamp); void modify_info(unsigned short id, char * zigbee); void modify_distaddr_info(unsigned short id, char * zigbee,unsigned char* distAddr);