fix build bugs.

This commit is contained in:
pandx 2024-10-24 16:01:21 +08:00
parent 28d588728c
commit f16d2839e8
20 changed files with 492 additions and 496 deletions

View File

@ -14,8 +14,35 @@
#include <unistd.h> #include <unistd.h>
#include <linux/sockios.h> #include <linux/sockios.h>
#include <linux/rtc.h> #include <linux/rtc.h>
#include <linux/rtc.h> #include <sys/socket.h>
#include <netinet/in.h>
#include <net/if.h>
#include <stdlib.h>
#include <memory.h>
#include <string>
#include <list>
#include <iostream>
#include <fstream>
#include <arpa/inet.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <memory.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include "dirent.h"
#include <iconv.h>
#include <termios.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/ip_icmp.h>
#include <netdb.h>
#include <boost/algorithm/string/split.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/algorithm/string/classification.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/xpressive/xpressive_dynamic.hpp> #include <boost/xpressive/xpressive_dynamic.hpp>
#include <json/json.h>
#include <zlog.h> #include <zlog.h>
#include "global.hpp" #include "global.hpp"
#include "dbaccess/sql_db.hpp" #include "dbaccess/sql_db.hpp"
@ -202,7 +229,8 @@ void InitGpio(unsigned int gpioN, unsigned int inout) {
memcpy(tmp2, "P16_1", 5); memcpy(tmp2, "P16_1", 5);
sprintf(tmp, "/sys/class/gpio/%s/direction", tmp2); sprintf(tmp, "/sys/class/gpio/%s/direction", tmp2);
#else if IMX6UL_GATEWAY #endif
#ifdef IMX6UL_GATEWAY
sprintf(tmp, "/sys/class/gpio/gpio%d/direction", gpioN); sprintf(tmp, "/sys/class/gpio/gpio%d/direction", gpioN);
#endif #endif
@ -268,7 +296,8 @@ int gpio_set(unsigned int gpioN, char x) {
else if (gpioN == 489) else if (gpioN == 489)
memcpy(tmp2, "P16_1", 5); memcpy(tmp2, "P16_1", 5);
sprintf(tmp, "/sys/class/gpio/%s/value", tmp2); sprintf(tmp, "/sys/class/gpio/%s/value", tmp2);
#else if IMX6UL_GATEWAY #endif
#ifdef IMX6UL_GATEWAY
sprintf(tmp, "/sys/class/gpio/gpio%d/value", gpioN); sprintf(tmp, "/sys/class/gpio/gpio%d/value", gpioN);
#endif #endif
@ -294,7 +323,7 @@ int gpio_set(unsigned int gpioN, char x) {
return (-1); return (-1);
} }
} }
zlog_info(zbt, "gpio%d set %d ok", gpioN, x) zlog_info(zbt, "gpio%d set %d ok", gpioN, x);
close(fd); close(fd);
return 0; return 0;
} }
@ -338,7 +367,8 @@ int gpio_read(unsigned int gpioN) {
else if (gpioN == 489) else if (gpioN == 489)
memcpy(tmp2, "P16_1", 5); memcpy(tmp2, "P16_1", 5);
sprintf(tmp, "/sys/class/gpio/%s/value", tmp2); sprintf(tmp, "/sys/class/gpio/%s/value", tmp2);
#else if IMX6UL_GATEWAY #endif
#ifdef IMX6UL_GATEWAY
sprintf(tmp, "/sys/class/gpio/gpio%d/value", gpioN); sprintf(tmp, "/sys/class/gpio/gpio%d/value", gpioN);
#endif #endif
//闂備胶鎳撻悘姘跺箰閸濄儲顫曢柟杈╁€峣o value闂備礁鎼崐绋棵洪敐鍛瀻闁跨噦鎷<E599A6> //闂備胶鎳撻悘姘跺箰閸濄儲顫曢柟杈╁€峣o value闂備礁鎼崐绋棵洪敐鍛瀻闁跨噦鎷<E599A6>
@ -389,7 +419,6 @@ int config_uart(const char *port, int speed) {
int write_data(int fd, char *buff, int len) { int write_data(int fd, char *buff, int len) {
int ret; int ret;
char buf[100];
ret = write(fd, buff, len); ret = write(fd, buff, len);
if (ret < 0) { if (ret < 0) {
zlog_error(zct, "write failed"); zlog_error(zct, "write failed");
@ -465,11 +494,11 @@ tm *get_current_date() {
int iyear = 0; int iyear = 0;
int imonth = 0; int imonth = 0;
int day = 0; int day = 0;
int hour = 0; // int hour = 0;
iyear = tm_info->tm_year + 1900; iyear = tm_info->tm_year + 1900;
imonth = tm_info->tm_mon + 1; imonth = tm_info->tm_mon + 1;
day = tm_info->tm_mday; day = tm_info->tm_mday;
hour = tm_info->tm_hour; // hour = tm_info->tm_hour;
zlog_info(zct, "year = %d,month = %d,day = %d", iyear, imonth, day); zlog_info(zct, "year = %d,month = %d,day = %d", iyear, imonth, day);
return tm_info; return tm_info;
} }
@ -602,10 +631,10 @@ std::vector<DataNodeUpdate> ReadStrUpdate(std::string filename) {
is.open(filename.c_str(), std::ios::in); is.open(filename.c_str(), std::ios::in);
if (reader.parse(is, root)) { if (reader.parse(is, root)) {
zlog_info(zbt, "root = %d", root.size()); zlog_info(zbt, "root = %d", root.size());
for (int i = 0; i < root.size(); i++) { for (size_t i = 0; i < root.size(); i++) {
hwVersion = root[i]["hw_vesion"]; hwVersion = root[i]["hw_vesion"];
for (int i = 0; i < hwVersion.size(); i++) { for (size_t j = 0; j < hwVersion.size(); j++) {
datanodeUpdate.hwVersion.push_back(hwVersion[i].asString()); datanodeUpdate.hwVersion.push_back(hwVersion[j].asString());
} }
datanodeUpdate.strUpdataFileName = root[i]["fw_name"].asString(); datanodeUpdate.strUpdataFileName = root[i]["fw_name"].asString();
datanodeUpdate.strSoftVersion = root[i]["sf_vesion"].asString(); datanodeUpdate.strSoftVersion = root[i]["sf_vesion"].asString();
@ -623,7 +652,7 @@ void ReadStrConfig(std::string filename) {
std::fstream is; std::fstream is;
Json::Reader reader; Json::Reader reader;
is.open(filename.c_str(), std::ios::in); is.open(filename.c_str(), std::ios::in);
string zigbeeChannel; std::string zigbeeChannel;
if (reader.parse(is, root) == 0) { if (reader.parse(is, root) == 0) {
zlog_error(zbt, "fail to parse file:%s", filename.c_str()); zlog_error(zbt, "fail to parse file:%s", filename.c_str());
return; return;
@ -631,7 +660,7 @@ void ReadStrConfig(std::string filename) {
gateWay = root["gateWay"]; gateWay = root["gateWay"];
dataNode = root["dataNodeArray"]; dataNode = root["dataNodeArray"];
zlog_info(zbt, "dataNode = %d", dataNode.size()); zlog_info(zbt, "dataNode = %d", dataNode.size());
for (int i = 0; i < dataNode.size(); i++) { for (size_t i = 0; i < dataNode.size(); i++) {
std::string softVersion = dataNode[i]["softVersion"].asString(); std::string softVersion = dataNode[i]["softVersion"].asString();
std::string bpNo = dataNode[i]["bpNo"].asString(); std::string bpNo = dataNode[i]["bpNo"].asString();
zlog_info(zbt, "bpNo = %s", bpNo.c_str()); zlog_info(zbt, "bpNo = %s", bpNo.c_str());
@ -722,11 +751,11 @@ void ImportConfig(std::string filename) {
jsSystemSetting = root["ServerConfig"]; jsSystemSetting = root["ServerConfig"];
jsondataNodeArray = root["dataNodeArray"]; jsondataNodeArray = root["dataNodeArray"];
char insertSql[1024] = {0}; char insertSql[1024] = {0};
for (int i = 0; i < jsondataNodeArray.size(); i++) { for (size_t i = 0; i < jsondataNodeArray.size(); i++) {
Json::Value valNode = jsondataNodeArray[i]; Json::Value valNode = jsondataNodeArray[i];
std::vector<std::string> vecDataNode; std::vector<std::string> vecDataNode;
for (size_t j = 0; j < valNode.size(); j++) { for (size_t j = 0; j < valNode.size(); j++) {
vecDataNode.push_back(string(valNode[j].asString())); vecDataNode.push_back(std::string(valNode[j].asString()));
} }
char dataNodeName[100] = {0x00}; char dataNodeName[100] = {0x00};
hexToAscii(vecDataNode[1].c_str(), dataNodeName); hexToAscii(vecDataNode[1].c_str(), dataNodeName);
@ -777,7 +806,7 @@ void ImportConfig(std::string filename) {
int UpdataDataNodeConfig(std::string filename) { int UpdataDataNodeConfig(std::string filename) {
std::vector<DataNodeInfo> vecDataNode; //濠电姰鍨瑰﹢杈ㄦ櫠濡も偓鍗遍柟瀵稿仧閳绘棃鏌嶈閸撴氨绮欐径鎰垫晜闁告洦鍘介幉鑽ょ磽娴娈紓鍌涙皑閹蹭即宕卞☉妯啃曢梺纭呮彧缁犳垵鈻嶉敓锟<E69593> std::vector<DataNodeInfo> vecDataNode; //濠电姰鍨瑰﹢杈ㄦ櫠濡も偓鍗遍柟瀵稿仧閳绘棃鏌嶈閸撴氨绮欐径鎰垫晜闁告洦鍘介幉鑽ょ磽娴娈紓鍌涙皑閹蹭即宕卞☉妯啃曢梺纭呮彧缁犳垵鈻嶉敓锟<E69593>
//濠电偛顕慨浼村磿閹绢噮鏁嬪ù鍏兼綑缁€鍌炴煏婢舵盯妾柣鎾寸懅閳ь剚顔栭崰鏍崲閹寸偞娅犻柨鏇楀亾妞ゆ洩缍侀崺鈧い鎺戝濡﹢鏌涢妷顖炴妞ゆ劧鎷<E58AA7> //濠电偛顕慨浼村磿閹绢噮鏁嬪ù鍏兼綑缁€鍌炴煏婢舵盯妾柣鎾寸懅閳ь剚顔栭崰鏍崲閹寸偞娅犻柨鏇楀亾妞ゆ洩缍侀崺鈧い鎺戝濡﹢鏌涢妷顖炴妞ゆ劧鎷<E58AA7>
std::ifstream csv_data(filename, ios::in); std::ifstream csv_data(filename, std::ios::in);
int iRet = 0; int iRet = 0;
if (!csv_data.is_open()) { if (!csv_data.is_open()) {
zlog_error(zbt, "UpdataDataNodeConfig fail to open:%s", filename.c_str()); zlog_error(zbt, "UpdataDataNodeConfig fail to open:%s", filename.c_str());
@ -811,15 +840,15 @@ int UpdataDataNodeConfig(std::string filename) {
dataNode.WaveInterVal = atoi(words[17].c_str()); dataNode.WaveInterVal = atoi(words[17].c_str());
dataNode.SamplingRate = atoi(words[18].c_str()); dataNode.SamplingRate = atoi(words[18].c_str());
if (words[19].find("8g") != string::npos) { if (words[19].find("8g") != std::string::npos) {
dataNode.Range = 0; dataNode.Range = 0;
} else if (words[19].find("16g") != string::npos) { } else if (words[19].find("16g") != std::string::npos) {
dataNode.Range = 1; dataNode.Range = 1;
} else if (words[19].find("32g") != string::npos) { } else if (words[19].find("32g") != std::string::npos) {
dataNode.Range = 2; dataNode.Range = 2;
} else if (words[19].find("64g") != string::npos) { } else if (words[19].find("64g") != std::string::npos) {
dataNode.Range = 3; dataNode.Range = 3;
} else if (words[19].find("50g") != string::npos) { } else if (words[19].find("50g") != std::string::npos) {
dataNode.Range = 0; dataNode.Range = 0;
} }
@ -839,7 +868,7 @@ int UpdataDataNodeConfig(std::string filename) {
char whereCon[1024] = {0}; char whereCon[1024] = {0};
char updateSql[1024] = {0}; char updateSql[1024] = {0};
for (int i = 0; i < vecDataNode.size(); i++) { for (size_t i = 0; i < vecDataNode.size(); i++) {
sprintf(updateSql, "featureInterVal='%d',waveInterVal='%d',range='%d',samplingRate='%d',AccSampleTime = '%d',viff ='%d' ,ZigbeePower = '%d',ZigbeeRetry = '%d',UpdateFlag = 0", vecDataNode[i].FeatureInterVal, vecDataNode[i].WaveInterVal, vecDataNode[i].Range, sprintf(updateSql, "featureInterVal='%d',waveInterVal='%d',range='%d',samplingRate='%d',AccSampleTime = '%d',viff ='%d' ,ZigbeePower = '%d',ZigbeeRetry = '%d',UpdateFlag = 0", vecDataNode[i].FeatureInterVal, vecDataNode[i].WaveInterVal, vecDataNode[i].Range,
vecDataNode[i].SamplingRate, vecDataNode[i].ACCSampleTime, vecDataNode[i].VIntegralFilterFrequency, vecDataNode[i].ZigbeePower, vecDataNode[i].ZigbeeRetry); vecDataNode[i].SamplingRate, vecDataNode[i].ACCSampleTime, vecDataNode[i].VIntegralFilterFrequency, vecDataNode[i].ZigbeePower, vecDataNode[i].ZigbeeRetry);
sprintf(whereCon, "dataNodeNo='%s'", vecDataNode[i].ZigbeeLongAddr.c_str()); sprintf(whereCon, "dataNodeNo='%s'", vecDataNode[i].ZigbeeLongAddr.c_str());
@ -1010,9 +1039,9 @@ std::string IpAddrInit() {
// } // }
std::string &ClearAllSpace(std::string &str) { std::string &ClearAllSpace(std::string &str) {
int index = 0; size_t index = 0;
if (!str.empty()) { if (!str.empty()) {
while ((index = str.find(' ', index)) != string::npos) { while ((index = str.find(' ', index)) != std::string::npos) {
str.erase(index, 1); str.erase(index, 1);
} }
} }
@ -1059,7 +1088,7 @@ std::string GetSysInfo() {
Emmcinfo = ClearAllSpace(Emmcinfo); Emmcinfo = ClearAllSpace(Emmcinfo);
char sysinfo[128] = {0}; char sysinfo[128] = {0};
sprintf(sysinfo, "%-13s%-13s%-13s%-13s ", to_string(c).substr(0, 4).c_str(), CpuSys.c_str(), CpuUse.c_str(), Emmcinfo.c_str()); sprintf(sysinfo, "%-13s%-13s%-13s%-13s ", std::to_string(c).substr(0, 4).c_str(), CpuSys.c_str(), CpuUse.c_str(), Emmcinfo.c_str());
return std::string(sysinfo); return std::string(sysinfo);
} }
@ -1074,7 +1103,7 @@ int SetTime(unsigned long seconds, int milliseconds) {
void ZoneConfig(std::string zoneid) { void ZoneConfig(std::string zoneid) {
int a = 0; int a = 0;
std::string zonelists[] = {"UTC+12", "UTC+11", "UTC+10", "UTC+9", "UTC+8", "UTC+7", "UTC+6", "UTC+5", "UTC+4", "UTC+3", "UTC+2", "UTC+1", "UTC+0", "UTC-1", "UTC-2", "UTC-3", "UTC-4", "UTC-5", "UTC-6", "UTC-7", "UTC-8", "UTC-9", "UTC-10", "UTC-11"}; std::string zonelists[] = {"UTC+12", "UTC+11", "UTC+10", "UTC+9", "UTC+8", "UTC+7", "UTC+6", "UTC+5", "UTC+4", "UTC+3", "UTC+2", "UTC+1", "UTC+0", "UTC-1", "UTC-2", "UTC-3", "UTC-4", "UTC-5", "UTC-6", "UTC-7", "UTC-8", "UTC-9", "UTC-10", "UTC-11"};
for (int i = 0; i < sizeof(zonelists); i++) { for (size_t i = 0; i < sizeof(zonelists); i++) {
if (zoneid.compare(zonelists[i]) == 0) { if (zoneid.compare(zonelists[i]) == 0) {
a = i; a = i;
zlog_info(zbt, "[ZoneConfig] zoneid:%s, a: %d", zoneid.c_str(), a); zlog_info(zbt, "[ZoneConfig] zoneid:%s, a: %d", zoneid.c_str(), a);
@ -1225,41 +1254,40 @@ std::string GetSysStatus() {
mem_used = mem_total - mem_free; mem_used = mem_total - mem_free;
float fMemRate = 1.0 * mem_used / mem_total; float fMemRate = 1.0 * mem_used / mem_total;
float fCpuRate; // float fCpuRate;
char name[8]; char name[8];
double cpu_idle = -1; // double cpu_idle = -1;
double cpu_sys = -1; double cpu_sys = -1;
double cpu_user = -1; double cpu_user = -1;
double cpu_total = -1; double cpu_total = -1;
double cpu_wait = -1; // double cpu_wait = -1;
long int user, nice, sys, idle, iowait, irq, softirq; long int user, nice, sys, idle, iowait, irq, softirq;
std::string strCpu1 = GetFileContent("/proc/stat", 1); std::string strCpu1 = GetFileContent("/proc/stat", 1);
sscanf(strCpu1.c_str(), "%s%ld%ld%ld%ld%ld%ld%d", name, &user, &nice, &sys, &idle, &iowait, &irq, &softirq); sscanf(strCpu1.c_str(), "%s%ld%ld%ld%ld%ld%ld%ld", name, &user, &nice, &sys, &idle, &iowait, &irq, &softirq);
sleep(1); sleep(1);
long int userNext, niceNext, sysNext, idleNext, iowaitNext, irqNext, softirqNext; long int userNext, niceNext, sysNext, idleNext, iowaitNext, irqNext, softirqNext;
std::string strCpu2 = GetFileContent("/proc/stat", 1); std::string strCpu2 = GetFileContent("/proc/stat", 1);
sscanf(strCpu2.c_str(), "%s%ld%ld%ld%ld%ld%ld%d", name, &userNext, &niceNext, &sysNext, &idleNext, &iowaitNext, &irqNext, &softirqNext); sscanf(strCpu2.c_str(), "%s%ld%ld%ld%ld%ld%ld%ld", name, &userNext, &niceNext, &sysNext, &idleNext, &iowaitNext, &irqNext, &softirqNext);
cpu_total = (userNext + niceNext + sysNext + idleNext + iowaitNext + irqNext + softirqNext) - (user + nice + sys + idle + iowait + irq + softirq); cpu_total = (userNext + niceNext + sysNext + idleNext + iowaitNext + irqNext + softirqNext) - (user + nice + sys + idle + iowait + irq + softirq);
cpu_user = userNext - user; cpu_user = userNext - user;
cpu_sys = sysNext - sys; cpu_sys = sysNext - sys;
cpu_wait = iowaitNext - iowait; // cpu_wait = iowaitNext - iowait;
cpu_idle = idleNext - idle; // cpu_idle = idleNext - idle;
fCpuRate = 1.0 * (cpu_total - cpu_idle) / cpu_total; // fCpuRate = 1.0 * (cpu_total - cpu_idle) / cpu_total;
float rateUser = cpu_user * 100.0 / cpu_total; float rateUser = cpu_user * 100.0 / cpu_total;
float rateSys = cpu_sys * 100.0 / cpu_total; float rateSys = cpu_sys * 100.0 / cpu_total;
if (rateUser > 95) { if (rateUser > 95) {
rateUser = 92; rateUser = 92;
} }
char hardName[32];
char hardTotal[32]; char hardTotal[32];
char hardUse[32];
char hardFree[32]; char hardFree[32];
char rateHardUse[32]; char rateHardUse[32];
const char *getEmmcInfo = "df -h | grep /opt";
char chRes[100]; char chRes[100];
memset(chRes, 0, 100); memset(chRes, 0, 100);
#ifdef IMX6UL_GATEWAY #ifdef IMX6UL_GATEWAY
char hardName[32];
char hardUse[32];
const char *getEmmcInfo = "df -h | grep /opt";
system_custom(getEmmcInfo, chRes); system_custom(getEmmcInfo, chRes);
sscanf(chRes, "%s%s%s%s%s", hardName, hardTotal, hardUse, hardFree, rateHardUse); sscanf(chRes, "%s%s%s%s%s", hardName, hardTotal, hardUse, hardFree, rateHardUse);
#endif #endif
@ -1288,9 +1316,9 @@ std::string GetSysStatus() {
jsData["temperature"] = temp / 1000.0; jsData["temperature"] = temp / 1000.0;
jsData["temperatureNR5G"] = atoi(GlobalConfig::NR5GTemp.c_str()); jsData["temperatureNR5G"] = atoi(GlobalConfig::NR5GTemp.c_str());
double total = atof(strhardTotal.substr(0, strhardTotal.length() - 1).c_str()); float total = atof(strhardTotal.substr(0, strhardTotal.length() - 1).c_str());
double free = atof(strhardFree.substr(0, strhardFree.length() - 1).c_str()); float free = atof(strhardFree.substr(0, strhardFree.length() - 1).c_str());
double use = ((total - free) / total) * 100; float use = ((total - free) / total) * 100;
jsData["hardDiskUse"] = use; jsData["hardDiskUse"] = use;
jsData["cpuSystemUse"] = rateSys; jsData["cpuSystemUse"] = rateSys;
@ -1362,10 +1390,10 @@ unsigned char ch2hex(char ch) {
return 0; return 0;
} }
string tohex(const string &str) { std::string tohex(const std::string &str) {
string ret; std::string ret;
static const char *hex = "0123456789ABCDEF"; static const char *hex = "0123456789ABCDEF";
for (int i = 0; i != str.size(); ++i) { for (size_t i = 0; i != str.size(); ++i) {
ret.push_back(hex[(str[i] >> 4) & 0xf]); ret.push_back(hex[(str[i] >> 4) & 0xf]);
ret.push_back(hex[str[i] & 0xf]); ret.push_back(hex[str[i] & 0xf]);
} }
@ -1537,7 +1565,7 @@ int set_opt(int fd, int nSpeed, int nBits, char nEvent, int nStop) {
int getcsq() { int getcsq() {
int ret = 0; int ret = 0;
char csq[128] = {0}; char csq[128] = {0};
int fd = 0, sig = 0; int fd = 0;
if ((fd = open("/dev/ttyUSB2", O_RDWR | O_NOCTTY | O_NDELAY)) < 0) { if ((fd = open("/dev/ttyUSB2", O_RDWR | O_NOCTTY | O_NDELAY)) < 0) {
zlog_error(zct, "fail to open /dev/ttyUSB2"); zlog_error(zct, "fail to open /dev/ttyUSB2");
@ -1573,13 +1601,13 @@ int getcsq() {
return -1; return -1;
} }
GlobalConfig::NetStatus = GetOneContent(csq, 1, ","); GlobalConfig::NetStatus = GetOneContent(csq, 1, ",");
string signal = GetOneContent(csq, 13, ","); std::string signal = GetOneContent(csq, 13, ",");
GlobalConfig::NetSignal = atoi(signal.c_str()); GlobalConfig::NetSignal = atoi(signal.c_str());
zlog_info(zct, "NetStatus = %s,NetSignal = %d", GlobalConfig::NetStatus.c_str(), GlobalConfig::NetSignal); zlog_info(zct, "NetStatus = %s,NetSignal = %d", GlobalConfig::NetStatus.c_str(), GlobalConfig::NetSignal);
return atoi(signal.c_str()); return atoi(signal.c_str());
} }
void IniReadValue(char *section, char *key, char *val, const char *file) { void IniReadValue(const char *section, const char *key, char *val, const char *file) {
FILE *fp; FILE *fp;
int i = 0; int i = 0;
int lineContentLen = 0; int lineContentLen = 0;
@ -1642,21 +1670,21 @@ void IniReadValue(char *section, char *key, char *val, const char *file) {
} }
} }
int readStringValue(const char *section, char *key, char *val, const char *file) { int readStringValue(const char *section, const char *key, char *val, const char *file) {
char sect[SECTION_MAX_LEN]; // char sect[SECTION_MAX_LEN];
zlog_info(zct, "section = %s, key = %s, file = %s", section, key, file); zlog_info(zct, "section = %s, key = %s, file = %s", section, key, file);
if (section == NULL || key == NULL || val == NULL || file == NULL) { if (section == NULL || key == NULL || val == NULL || file == NULL) {
zlog_error(zct, "input parameter, section:%s, key:%s, val:%s, file:%s exist NULL", section, key, val, file); zlog_error(zct, "input parameter, section:%s, key:%s, val:%s, file:%s exist NULL", section, key, val, file);
return -1; return -1;
} }
memset(sect, 0, SECTION_MAX_LEN); // memset(sect, 0, SECTION_MAX_LEN);
sprintf(sect, "[%s]", section); // sprintf(sect, "[%s]", section);
IniReadValue(sect, key, val, file); IniReadValue(section, key, val, file);
return 0; return 0;
} }
int readIntValue(const char *section, char *key, const char *file) { int readIntValue(const char *section, const char *key, const char *file) {
char strValue[STRVALUE_MAX_LEN]; char strValue[STRVALUE_MAX_LEN];
memset(strValue, '\0', STRVALUE_MAX_LEN); memset(strValue, '\0', STRVALUE_MAX_LEN);
if (readStringValue(section, key, strValue, file) != 0) { if (readStringValue(section, key, strValue, file) != 0) {
@ -1665,19 +1693,19 @@ int readIntValue(const char *section, char *key, const char *file) {
return (atoi(strValue)); return (atoi(strValue));
} }
void IniWriteValue(const char *section, char *key, char *val, const char *file) { void IniWriteValue(const char *section, const char *key, char *val, const char *file) {
FILE *fp; FILE *fp;
int i = 0, n = 0, err = 0; // int i = 0, n = 0, err = 0;
int lineContentLen = 0; // int lineContentLen = 0;
int position = 0; // int position = 0;
char lineContent[LINE_CONTENT_MAX_LEN]; char lineContent[LINE_CONTENT_MAX_LEN];
char strWrite[LINE_CONTENT_MAX_LEN]; char strWrite[LINE_CONTENT_MAX_LEN];
bool bFoundSection = false; bool bFoundSection = false;
bool bFoundKey = false; bool bFoundKey = false;
int err = 0;
memset(lineContent, '\0', LINE_CONTENT_MAX_LEN); memset(lineContent, '\0', LINE_CONTENT_MAX_LEN);
memset(strWrite, '\0', LINE_CONTENT_MAX_LEN); memset(strWrite, '\0', LINE_CONTENT_MAX_LEN);
n = sprintf(strWrite, "%s=%s\n", key, val); sprintf(strWrite, "%s=%s\n", key, val);
fp = fopen(file, "r+"); fp = fopen(file, "r+");
if (fp == NULL) { if (fp == NULL) {
zlog_error(zct, "fail to open:%s", file); zlog_error(zct, "fail to open:%s", file);
@ -1721,39 +1749,39 @@ void IniWriteValue(const char *section, char *key, char *val, const char *file)
} }
} }
int writeStringVlaue(const char *section, char *key, char *val, const char *file) { int writeStringVlaue(const char *section, const char *key, char *val, const char *file) {
char sect[SECTION_MAX_LEN]; // char sect[SECTION_MAX_LEN];
zlog_debug(zct, "section = %s, key = %s, file = %s\n", section, key, file); zlog_debug(zct, "section = %s, key = %s, file = %s", section, key, file);
if (section == NULL || key == NULL || val == NULL || file == NULL) { if (section == NULL || key == NULL || val == NULL || file == NULL) {
zlog_error(zct, "input parameter(s) is NULL!"); zlog_error(zct, "input parameter(s) is NULL!");
return -1; return -1;
} }
memset(sect, 0, SECTION_MAX_LEN); // memset(sect, 0, SECTION_MAX_LEN);
sprintf(sect, "[%s]", section); // sprintf(sect, "[%s]", section);
IniWriteValue(sect, key, val, file); IniWriteValue(section, key, val, file);
return 0;
} }
int writeIntValue(const char *section, char *key, int val, const char *file) { int writeIntValue(const char *section, const char *key, int val, const char *file) {
char strValue[STRVALUE_MAX_LEN]; char strValue[STRVALUE_MAX_LEN];
memset(strValue, 0, STRVALUE_MAX_LEN); memset(strValue, 0, STRVALUE_MAX_LEN);
sprintf(strValue, "%d", val); sprintf(strValue, "%d", val);
writeStringVlaue(section, key, strValue, file); writeStringVlaue(section, key, strValue, file);
return 0;
} }
int getDiskInfo(char *diskTotal, char *diskFree) { int getDiskInfo(char *diskTotal, char *diskFree) {
DISK diskInfo; DISK diskInfo;
/* 1.闂備礁鍚嬮崕鎶藉床閼艰翰浜归柨鐕傛嫹/home/濠电偞鍨堕幐鎼侇敄婢跺⿴鐒藉ù鐓庣摠閸庡秹鏌涢弴銊ュ幋闁稿鎸鹃幏鐘差啅椤斿吋娅嶉梻鍌欐祰椤曟粓骞忛敓锟<E69593> */ /* 1.闂備礁鍚嬮崕鎶藉床閼艰翰浜归柨鐕傛嫹/home/濠电偞鍨堕幐鎼侇敄婢跺⿴鐒藉ù鐓庣摠閸庡秹鏌涢弴銊ュ幋闁稿鎸鹃幏鐘差啅椤斿吋娅嶉梻鍌欐祰椤曟粓骞忛敓锟<E69593> */
statfs("/", &diskInfo); statfs("/", &diskInfo);
unsigned long long blocksize = diskInfo.f_bsize; //婵犳鍣徊鐣屾崲鐎喗鐓傛繛鎾插悍ock闂傚倷鐒﹁ぐ鍐嚐椤栨壕鍋撻崹顐€跨€规洏鍎甸、鏇㈠Χ閸℃瑦娈搁梺璇插缁嬫帡銆冩径瀣╃箚妞ゆ挶鍨归弸渚€鏌ㄩ悤鍌涘 unsigned long long blocksize = diskInfo.f_bsize;
unsigned long long totalsize = blocksize * diskInfo.f_blocks; //闂備浇顕栭崜婵嗙暦闂堟稈鏋旈柟瀵稿Л閸嬫挸鈽夊▎妯荤暯婵犵妲呴崣鍐嚕椤愩倖鏆滄い鏂垮⒔椤︾敧_blocks濠电偞鍨堕幐楣冾敋閻氱棶ck闂備焦鐪归崝宀€鈧凹鍙冨鎶芥偄閸忕厧鍓梺璺ㄥ櫐閹凤拷 unsigned long long totalsize = blocksize * diskInfo.f_blocks;
//printf("Total_size=%llu B =%llu KB =%llu MB = %llu GB\n",\
totalsize,totalsize>>10,totalsize>>20, totalsize>>30);
/* 2.闂備礁鍚嬮崕鎶藉床閼艰翰浜归柛銉e妿閳绘棃鏌嶈閸撴氨绮欐径灞稿亾閿濆簼绨婚柍閿嬬墪闇夐柨婵嗘閹冲懘鏌嶇憴鍕⒌婵﹤顭峰鍫曞箣閻愬樊浼呴梻浣告啞閻燁垶宕归幎钘夋瀬闁靛牆娲ㄩ惌姘箾瀹割喕绨奸柨娑氬枛閺岋綁濡搁妷銉患闂侀潧娲ゅú銊︾閹间焦鏅搁柨鐕傛嫹 */ /* 2.闂備礁鍚嬮崕鎶藉床閼艰翰浜归柛銉e妿閳绘棃鏌嶈閸撴氨绮欐径灞稿亾閿濆簼绨婚柍閿嬬墪闇夐柨婵嗘閹冲懘鏌嶇憴鍕⒌婵﹤顭峰鍫曞箣閻愬樊浼呴梻浣告啞閻燁垶宕归幎钘夋瀬闁靛牆娲ㄩ惌姘箾瀹割喕绨奸柨娑氬枛閺岋綁濡搁妷銉患闂侀潧娲ゅú銊︾閹间焦鏅搁柨鐕傛嫹 */
unsigned long long freeDisk = diskInfo.f_bfree * blocksize; //闂備礁鎲¢幐鎾疾濞嗘垹绀婇柟瀵稿Х閻碍绻涘顔荤凹闁挎稓鍠栭弻锝夊Ω閵夈儺浠奸梺闈涙搐濞层劍绂嶉幖浣规櫢闁跨噦鎷<E599A6> unsigned long long freeDisk = diskInfo.f_bfree * blocksize; //闂備礁鎲¢幐鎾疾濞嗘垹绀婇柟瀵稿Х閻碍绻涘顔荤凹闁挎稓鍠栭弻锝夊Ω閵夈儺浠奸梺闈涙搐濞层劍绂嶉幖浣规櫢闁跨噦鎷<E599A6>
unsigned long long availableDisk = diskInfo.f_bavail * blocksize; //闂備礁鎲¢悷顖炲垂閹惰棄鏋侀柕鍫濇川閻碍绻涘顔荤凹闁挎稓鍠庨…鍧楀醇閸℃鏆熸慨锝忔嫹 // unsigned long long availableDisk = diskInfo.f_bavail * blocksize; //闂備礁鎲¢悷顖炲垂閹惰棄鏋侀柕鍫濇川閻碍绻涘顔荤凹闁挎稓鍠庨…鍧楀醇閸℃鏆熸慨锝忔嫹
//printf("Disk_free=%llu MB =%llu GB Disk_available=%llu MB = %llu GB\n",\
freeDisk>>20,freeDisk>>30,availableDisk>>20, availableDisk>>30);
sprintf(diskTotal, "%llu", totalsize >> 20); sprintf(diskTotal, "%llu", totalsize >> 20);
sprintf(diskFree, "%llu", freeDisk >> 20); sprintf(diskFree, "%llu", freeDisk >> 20);
return 1; return 1;
@ -1802,7 +1830,7 @@ int socketHeart(const char *pSendData) {
} }
// 闂備礁鎲¢悷锕傚垂閸ф鐒垫い鎴f硶椤︼妇绱掗崫鍕挃闁圭懓瀚伴幖褰掝敃閿濆棭鍟€闂備胶顢婇鏍窗閺嶎偀鍋撶喊澶嬪 // 闂備礁鎲¢悷锕傚垂閸ф鐒垫い鎴f硶椤︼妇绱掗崫鍕挃闁圭懓瀚伴幖褰掝敃閿濆棭鍟€闂備胶顢婇鏍窗閺嶎偀鍋撶喊澶嬪
const char heartbeat[] = "Heartbeat";
ssize_t bytesSent = send(sockfd, pSendData, strlen(pSendData), MSG_NOSIGNAL); ssize_t bytesSent = send(sockfd, pSendData, strlen(pSendData), MSG_NOSIGNAL);
if (bytesSent == -1) { if (bytesSent == -1) {
zlog_error(zct, "Failed to send heartbeat packet."); zlog_error(zct, "Failed to send heartbeat packet.");

View File

@ -1,8 +1,11 @@
#ifndef COMMON_FUNC_HPP_ #ifndef COMMON_FUNC_HPP_
#define COMMON_FUNC_HPP_ #define COMMON_FUNC_HPP_
#include <string.h>
#include <sys/statfs.h>
#include <string> #include <string>
#include <vector> #include <vector>
#include <iostream>
// #include <stdio.h> // #include <stdio.h>
// #include <unistd.h> // #include <unistd.h>
// #include <sys/socket.h> // #include <sys/socket.h>
@ -470,7 +473,7 @@ int UpdataDataNodeConfig(std::string filename);
char* solve(char* dest, const char* src); char* solve(char* dest, const char* src);
void swap(char* data); void swap(char* data);
int hexStringToBytes(const char* hexStr, unsigned char* bytes, size_t bytesSize); int hexStringToBytes(const char* hexStr, unsigned char* bytes, size_t bytesSize);
void int2bytes(int i, unsigned char *bytes, int size);
int OpenWatchDog(); int OpenWatchDog();
int WriteWatchDog(int fd); int WriteWatchDog(int fd);
@ -478,10 +481,10 @@ int WriteWatchDog(int fd);
int getcsq(); int getcsq();
std::string GetGwIp_(const char* eth_name); std::string GetGwIp_(const char* eth_name);
std::string GetOneContent(const char* szData, int nRow, const char* szSeparate); std::string GetOneContent(const char* szData, int nRow, const char* szSeparate);
int readStringValue(const char* section, char* key, char* val, const char* file); int readStringValue(const char* section, const char* key, char* val, const char* file);
int writeStringVlaue(const char* section, char* key, char* val, const char* file); int writeStringVlaue(const char* section, const char* key, char* val, const char* file);
int readIntValue(const char* section, char* key, const char* file); int readIntValue(const char* section, const char* key, const char* file);
int writeIntValue(const char* section, char* key, int val, const char* file); int writeIntValue(const char* section, const char* key, int val, const char* file);
int getDiskInfo(char* diskTotal, char* diskFree); int getDiskInfo(char* diskTotal, char* diskFree);

View File

@ -1,6 +1,9 @@
#include "sql_db.hpp" #include "sql_db.hpp"
#include <unistd.h> #include <unistd.h>
#include <boost/algorithm/string.hpp>
#include <zlog.h> #include <zlog.h>
#include <json/json.h>
#include "mqttclient/mqtt_client.h"
#include "common/global.hpp" #include "common/global.hpp"
#include "utility/calculation.hpp" #include "utility/calculation.hpp"
@ -13,92 +16,196 @@ SqliteDB::~SqliteDB() {}
void SqliteDB::SqliteInit(const char *pDbName) { void SqliteDB::SqliteInit(const char *pDbName) {
char sql_exec[2048]; char sql_exec[2048];
memset(sql_exec, 0, 2048);
//创建传感器信息存储表 //创建传感器信息存储表
memset(sql_exec, 0, 2048); memset(sql_exec, 0, 2048);
sprintf(sql_exec, "create table if not exists %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,%s,%s);", T_SENSOR_INFO(TNAME), T_SENSOR_INFO(DATANODENO), T_SENSOR_INFO(DATANODENAME), sprintf(sql_exec, "create table if not exists %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,%s,%s,%s);",
T_SENSOR_INFO(INITFLAG), T_SENSOR_INFO(ACCFLAG), T_SENSOR_INFO(ZIGBEEFLAG), T_SENSOR_INFO(TEMTOPFLAG), T_SENSOR_INFO(TEMBOTFLAG), T_SENSOR_INFO(EQUIPSTA), T_SENSOR_INFO(HARDVERSION), T_SENSOR_INFO(SOFTVERSION), T_SENSOR_INFO(BPNO), T_SENSOR_INFO(SERIALNO), T_SENSOR_INFO(TNAME),
T_SENSOR_INFO(FIRSTPOWERNO), "WakeupTime", "StaticTime", "WaveTime", "BateryV", "ProductNo", T_SENSOR_INFO(CONFIGFLAG), T_SENSOR_INFO(STARTBRANDS), T_SENSOR_INFO(STOPBRANDS), T_SENSOR_INFO(FEATUREINTERVAL), T_SENSOR_INFO(WAVEINTERVAL), T_SENSOR_INFO(SAMPLINGRATE), T_SENSOR_INFO(DATANODENO),
T_SENSOR_INFO(SCOPE), T_SENSOR_INFO(RANGE), T_SENSOR_INFO(ENVELOPEBANDPASS), T_SENSOR_INFO(FAULTFREQUENCY), T_SENSOR_INFO(ZIGBEEPANID), T_SENSOR_INFO(ZIGBEECHANNEL), T_SENSOR_INFO(ZIGBEESHORTADDR), T_SENSOR_INFO(ZIGBEELONGADDR), T_SENSOR_INFO(ZIGBEEDESADDR), T_SENSOR_INFO(DATANODENAME),
"ZigbeePower", "ZigbeeRetry", "ZigbeeRetryGap", "ACCSampleTime", T_SENSOR_INFO(STATUS), T_SENSOR_INFO(TIMESTAMP), T_SENSOR_INFO(VIFF), T_SENSOR_INFO(RSSI), "UpdateFlag", "LooseValue", "batteryPower"), T_SENSOR_INFO(INITFLAG),
CreateTable(sql_exec); T_SENSOR_INFO(ACCFLAG),
T_SENSOR_INFO(ZIGBEEFLAG),
T_SENSOR_INFO(TEMTOPFLAG),
T_SENSOR_INFO(TEMBOTFLAG),
T_SENSOR_INFO(EQUIPSTA),
T_SENSOR_INFO(HARDVERSION),
T_SENSOR_INFO(SOFTVERSION),
T_SENSOR_INFO(BPNO),
T_SENSOR_INFO(SERIALNO),
T_SENSOR_INFO(FIRSTPOWERNO),
"WakeupTime",
"StaticTime",
"WaveTime",
"BateryV",
"ProductNo",
T_SENSOR_INFO(CONFIGFLAG),
T_SENSOR_INFO(STARTBRANDS),
T_SENSOR_INFO(STOPBRANDS),
T_SENSOR_INFO(FEATUREINTERVAL),
T_SENSOR_INFO(WAVEINTERVAL),
T_SENSOR_INFO(SAMPLINGRATE),
T_SENSOR_INFO(SCOPE),
T_SENSOR_INFO(RANGE),
T_SENSOR_INFO(ENVELOPEBANDPASS),
T_SENSOR_INFO(FAULTFREQUENCY),
T_SENSOR_INFO(ZIGBEEPANID),
T_SENSOR_INFO(ZIGBEECHANNEL),
T_SENSOR_INFO(ZIGBEESHORTADDR),
T_SENSOR_INFO(ZIGBEELONGADDR),
T_SENSOR_INFO(ZIGBEEDESADDR),
"ZigbeePower",
"ZigbeeRetry",
"ZigbeeRetryGap",
"ACCSampleTime",
T_SENSOR_INFO(STATUS),
T_SENSOR_INFO(TIMESTAMP),
T_SENSOR_INFO(VIFF),
T_SENSOR_INFO(RSSI),
"UpdateFlag",
"LooseValue",
"batteryPower");
CreateTable(sql_exec);
int iRet = GetTableRows(" sqlite_master ", " name = 't_sensor_info' and sql LIKE '%LooseValue%' "); int iRet = GetTableRows(" sqlite_master "," name = 't_sensor_info' and sql LIKE '%LooseValue%' ");
if (iRet == 0) { if(iRet == 0){
CreateTable("ALTER TABLE t_sensor_info ADD COLUMN 'LooseValue'"); CreateTable("ALTER TABLE t_sensor_info ADD COLUMN 'LooseValue'");
} }
iRet = GetTableRows(" sqlite_master ", " name = 't_sensor_info' and sql LIKE '%batteryPower%' "); iRet = GetTableRows(" sqlite_master "," name = 't_sensor_info' and sql LIKE '%batteryPower%' ");
if (iRet == 0) { if(iRet == 0){
CreateTable("ALTER TABLE t_sensor_info ADD COLUMN 'batteryPower'"); CreateTable("ALTER TABLE t_sensor_info ADD COLUMN 'batteryPower'");
} }
iRet = GetTableRows(" sqlite_master ", " name = 't_sensor_info' and sql LIKE '%MeasurementID%' "); iRet = GetTableRows(" sqlite_master "," name = 't_sensor_info' and sql LIKE '%MeasurementID%' ");
if (iRet == 0) { if(iRet == 0){
CreateTable("ALTER TABLE t_sensor_info ADD COLUMN 'MeasurementID'"); CreateTable("ALTER TABLE t_sensor_info ADD COLUMN 'MeasurementID'");
} }
iRet = GetTableRows(" sqlite_master ", " name = 't_sensor_info' and sql LIKE '%NodeWaveSend%' "); iRet = GetTableRows(" sqlite_master "," name = 't_sensor_info' and sql LIKE '%NodeWaveSend%' ");
if (iRet == 0) { if(iRet == 0){
CreateTable("ALTER TABLE t_sensor_info ADD COLUMN 'NodeWaveSend'"); CreateTable("ALTER TABLE t_sensor_info ADD COLUMN 'NodeWaveSend'");
} }
memset(sql_exec, 0, 2048); memset(sql_exec, 0, 2048);
sprintf(sql_exec, "update t_sensor_info set MeasurementID = dataNodeNo where MeasurementID IS NULL ;"); sprintf(sql_exec,"update t_sensor_info set MeasurementID = dataNodeNo where MeasurementID IS NULL ;");
UpdateTableData(sql_exec); UpdateTableData(sql_exec);
memset(sql_exec, 0, 2048); memset(sql_exec, 0, 2048);
sprintf(sql_exec, "update t_sensor_info set MeasurementID = dataNodeNo where MeasurementID = '' ;"); sprintf(sql_exec,"update t_sensor_info set MeasurementID = dataNodeNo where MeasurementID = '' ;");
UpdateTableData(sql_exec); UpdateTableData(sql_exec);
//创建传感器数据存储表 //创建传感器数据存储表
memset(sql_exec, 0, 2048); memset(sql_exec, 0, 2048);
sprintf(sql_exec, "create table if not exists %s(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s integer,%s,%s);", T_DATA_INFO(TNAME), T_DATA_INFO(DATANODENO), T_DATA_INFO(CHANNELID), T_DATA_INFO(DIAGNOSISEAK), T_DATA_INFO(INTEGRATPK), T_DATA_INFO(INTEGRATRMS), sprintf(sql_exec, "create table if not exists %s(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s integer,%s,%s,%s);",
T_DATA_INFO(RMSVALUES), T_DATA_INFO(ENVELOPNERGY), T_DATA_INFO(AMP1), T_DATA_INFO(AMP2), T_DATA_INFO(AMP3), T_DATA_INFO(AMP4), T_DATA_INFO(AMP5), T_DATA_INFO(PHASE1), T_DATA_INFO(PHASE2), T_DATA_INFO(PHASE3), T_DATA_INFO(PHASE4), T_DATA_INFO(STATICINDEX), T_DATA_INFO(TNAME),
T_DATA_INFO(TIMESTAMP), T_DATA_INFO(SENDMSG), T_DATA_INFO(NODERESEND)); T_DATA_INFO(DATANODENO),
T_DATA_INFO(CHANNELID),
T_DATA_INFO(DIAGNOSISEAK),
T_DATA_INFO(INTEGRATPK),
T_DATA_INFO(INTEGRATRMS),
T_DATA_INFO(RMSVALUES),
T_DATA_INFO(ENVELOPNERGY),
T_DATA_INFO(AMP1),
T_DATA_INFO(AMP2),
T_DATA_INFO(AMP3),
T_DATA_INFO(AMP4),
T_DATA_INFO(AMP5),
T_DATA_INFO(PHASE1),
T_DATA_INFO(PHASE2),
T_DATA_INFO(PHASE3),
T_DATA_INFO(PHASE4),
T_DATA_INFO(STATICINDEX),
T_DATA_INFO(TIMESTAMP),
T_DATA_INFO(SENDMSG),
T_DATA_INFO(NODERESEND));
CreateTable(sql_exec); CreateTable(sql_exec);
iRet = GetTableRows(" sqlite_master ", " name = 't_data_info' and sql LIKE '%nodeResend%' "); iRet = GetTableRows(" sqlite_master "," name = 't_data_info' and sql LIKE '%nodeResend%' ");
if (iRet == 0) { if(iRet == 0){
CreateTable("ALTER TABLE t_data_info ADD COLUMN 'nodeResend'"); CreateTable("ALTER TABLE t_data_info ADD COLUMN 'nodeResend'");
} }
//创建传感器静态数据存储表 //创建传感器静态数据存储表
memset(sql_exec, 0, 2048); memset(sql_exec, 0, 2048);
sprintf(sql_exec, "create table if not exists %s(%s,%s,%s,%s,%s,%s,%s,%s integer,%s,%s);", T_DATASTATIC_INFO(TNAME), T_DATASTATIC_INFO(DATANODENO), T_DATASTATIC_INFO(CHANNELID), T_DATASTATIC_INFO(TEMTOP), T_DATASTATIC_INFO(TEMBOT), T_DATASTATIC_INFO(DIP), sprintf(sql_exec, "create table if not exists %s(%s,%s,%s,%s,%s,%s,%s,%s integer,%s,%s,%s);",
T_DATASTATIC_INFO(VOLTAGE), "Battery", T_DATASTATIC_INFO(STATICINDEX), T_DATASTATIC_INFO(TIMESTAMP), T_DATASTATIC_INFO(SENDMSG), T_DATASTATIC_INFO(NODERESEND)); T_DATASTATIC_INFO(TNAME),
T_DATASTATIC_INFO(DATANODENO),
T_DATASTATIC_INFO(CHANNELID),
T_DATASTATIC_INFO(TEMTOP),
T_DATASTATIC_INFO(TEMBOT),
T_DATASTATIC_INFO(DIP),
T_DATASTATIC_INFO(VOLTAGE),
"Battery",
T_DATASTATIC_INFO(STATICINDEX),
T_DATASTATIC_INFO(TIMESTAMP),
T_DATASTATIC_INFO(SENDMSG),
T_DATASTATIC_INFO(NODERESEND));
CreateTable(sql_exec); CreateTable(sql_exec);
iRet = GetTableRows(" sqlite_master ", " name = 't_datastatic_info' and sql LIKE '%nodeResend%' "); iRet = GetTableRows(" sqlite_master "," name = 't_datastatic_info' and sql LIKE '%nodeResend%' ");
if (iRet == 0) { if(iRet == 0){
CreateTable("ALTER TABLE t_datastatic_info ADD COLUMN 'nodeResend'"); CreateTable("ALTER TABLE t_datastatic_info ADD COLUMN 'nodeResend'");
} }
memset(sql_exec, 0, 2048); memset(sql_exec, 0, 2048);
sprintf(sql_exec, "create table if not exists %s(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s);", T_GATEWAY_INFO(TNAME), T_GATEWAY_INFO(GATEWAYMAC), T_GATEWAY_INFO(SENSORVER), T_GATEWAY_INFO(GATEWAYLOCATION), T_GATEWAY_INFO(ZIGBEEPANID), T_GATEWAY_INFO(ZIGBEECHANNEL), sprintf(sql_exec, "create table if not exists %s(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s);",
T_GATEWAY_INFO(COMMUNICATIONTYPE), T_GATEWAY_INFO(SIGNAL), T_GATEWAY_INFO(LOCALIP), T_GATEWAY_INFO(SYSTEMVERSION), T_GATEWAY_INFO(PROGRAMVERSION), T_GATEWAY_INFO(WEBVERSION), T_GATEWAY_INFO(SERVERIP), T_GATEWAY_INFO(SERVERPORT), T_GATEWAY_INFO(STATUS), T_GATEWAY_INFO(TNAME),
T_GATEWAY_INFO(GATEWAYUPDATE), T_GATEWAY_INFO(MAC2)); T_GATEWAY_INFO(GATEWAYMAC),
T_GATEWAY_INFO(SENSORVER),
T_GATEWAY_INFO(GATEWAYLOCATION),
T_GATEWAY_INFO(ZIGBEEPANID),
T_GATEWAY_INFO(ZIGBEECHANNEL),
T_GATEWAY_INFO(COMMUNICATIONTYPE),
T_GATEWAY_INFO(SIGNAL),
T_GATEWAY_INFO(LOCALIP),
T_GATEWAY_INFO(SYSTEMVERSION),
T_GATEWAY_INFO(PROGRAMVERSION),
T_GATEWAY_INFO(WEBVERSION),
T_GATEWAY_INFO(SERVERIP),
T_GATEWAY_INFO(SERVERPORT),
T_GATEWAY_INFO(STATUS),
T_GATEWAY_INFO(GATEWAYUPDATE),
T_GATEWAY_INFO(MAC2));
CreateTable(sql_exec);
memset(sql_exec, 0, 2048);
sprintf(sql_exec, "create table if not exists %s(%s,%s,%s,%s,%s);",
"t_data_waveSend","channelID","waveName","timeStamp","sendMsg","save");
CreateTable(sql_exec);
iRet = GetTableRows(" sqlite_master "," name = 't_data_waveSend' and sql LIKE '%sendMsg%' ");
if(iRet == 0){
CreateTable("ALTER TABLE t_data_waveSend ADD COLUMN 'sendMsg'");
}
iRet = GetTableRows(" sqlite_master "," name = 't_data_waveSend' and sql LIKE '%save%' ");
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); CreateTable(sql_exec);
memset(sql_exec, 0, 2048); memset(sql_exec, 0, 2048);
sprintf(sql_exec, "create table if not exists %s(%s,%s,%s,%s,%s);", "t_data_waveSend", "channelID", "waveName", "timeStamp", "sendMsg", "save"); sprintf(sql_exec, "create table if not exists %s(%s,%s,%s,%s,%s,%s,%s,%s,%s);",
CreateTable(sql_exec); "t_battery_history",
T_BATTERY_INFO(DATANODENO),
iRet = GetTableRows(" sqlite_master ", " name = 't_data_waveSend' and sql LIKE '%sendMsg%' "); T_BATTERY_INFO(DIP),
if (iRet == 0) { T_BATTERY_INFO(TEMBOT),
CreateTable("ALTER TABLE t_data_waveSend ADD COLUMN 'sendMsg'"); T_BATTERY_INFO(NODEWORKTIME),
} T_BATTERY_INFO(NODESENDTIME),
iRet = GetTableRows(" sqlite_master ", " name = 't_data_waveSend' and sql LIKE '%save%' "); T_BATTERY_INFO(BATTERYVOLTAGE),
if (iRet == 0) { T_BATTERY_INFO(BATTERYUSAGE),
CreateTable("ALTER TABLE t_data_waveSend ADD COLUMN 'save'"); T_BATTERY_INFO(BATTERYREMAIN),
} T_BATTERY_INFO(TIMESTAMP));
CreateTable(sql_exec);
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);
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_history", 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);
} }
void SqliteDB::Createtable(const char *ptableName) { void SqliteDB::Createtable(const char *ptableName) {
@ -108,17 +215,17 @@ void SqliteDB::Createtable(const char *ptableName) {
sprintf(sql_exec, "create table if not exists %s(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s integer,%s,%s,%s);", ptableName, T_DATA_INFO(DATANODENO), T_DATA_INFO(CHANNELID), T_DATA_INFO(DIAGNOSISEAK), T_DATA_INFO(INTEGRATPK), T_DATA_INFO(INTEGRATRMS), sprintf(sql_exec, "create table if not exists %s(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s integer,%s,%s,%s);", ptableName, T_DATA_INFO(DATANODENO), T_DATA_INFO(CHANNELID), T_DATA_INFO(DIAGNOSISEAK), T_DATA_INFO(INTEGRATPK), T_DATA_INFO(INTEGRATRMS),
T_DATA_INFO(RMSVALUES), T_DATA_INFO(ENVELOPNERGY), T_DATA_INFO(AMP1), T_DATA_INFO(AMP2), T_DATA_INFO(AMP3), T_DATA_INFO(AMP4), T_DATA_INFO(AMP5), T_DATA_INFO(PHASE1), T_DATA_INFO(PHASE2), T_DATA_INFO(PHASE3), T_DATA_INFO(PHASE4), "StaticIndex", T_DATA_INFO(TIMESTAMP), T_DATA_INFO(RMSVALUES), T_DATA_INFO(ENVELOPNERGY), T_DATA_INFO(AMP1), T_DATA_INFO(AMP2), T_DATA_INFO(AMP3), T_DATA_INFO(AMP4), T_DATA_INFO(AMP5), T_DATA_INFO(PHASE1), T_DATA_INFO(PHASE2), T_DATA_INFO(PHASE3), T_DATA_INFO(PHASE4), "StaticIndex", T_DATA_INFO(TIMESTAMP),
"sendMsg", "nodeResend"); "sendMsg", "nodeResend");
CreateTable(sql_exec, 0); CreateTable(sql_exec);
memset(sql_exec, 0, 2048); memset(sql_exec, 0, 2048);
sprintf(sql_exec, "CREATE INDEX %s_1 ON %s (%s)", ptableName, ptableName, T_DATA_INFO(DATANODENO)); sprintf(sql_exec, "CREATE INDEX %s_1 ON %s (%s)", ptableName, ptableName, T_DATA_INFO(DATANODENO));
CreateTable(sql_exec, 0); CreateTable(sql_exec);
} }
void SqliteDB::SqliteInitDel(const char *pDbName) { void SqliteDB::SqliteInitDel(const char *pDbName) {
Deletetable(T_DATA_INFO(TNAME)); Deletetable(T_DATA_INFO(TNAME));
Deletetable(T_DATASTATIC_INFO(TNAME)); Deletetable(T_DATASTATIC_INFO(TNAME));
vec_t vecResult = GetDataMultiLineOfOneColumn(T_SENSOR_INFO(TNAME), T_SENSOR_INFO(ZIGBEELONGADDR), NULL); vec_t vecResult = GetDataMultiLineOfOneColumn(T_SENSOR_INFO(TNAME), T_SENSOR_INFO(ZIGBEELONGADDR), NULL);
for (int i = 0; i < vecResult.size() && vecResult.size() > 0; i++) { for (size_t i = 0; i < vecResult.size() && vecResult.size() > 0; i++) {
char sztableName[100] = {0x00}; char sztableName[100] = {0x00};
sprintf(sztableName, "t_data_%s", vecResult[i].c_str()); sprintf(sztableName, "t_data_%s", vecResult[i].c_str());
Deletetable(sztableName); Deletetable(sztableName);
@ -132,7 +239,7 @@ void SqliteDB::Deletetable(const char *ptableName) {
//创建传感器数据存储表 //创建传感器数据存储表
memset(sql_exec, 0, 2048); memset(sql_exec, 0, 2048);
sprintf(sql_exec, "DROP TABLE %s ;", ptableName); sprintf(sql_exec, "DROP TABLE %s ;", ptableName);
int iRet = sqlite3_exec(GetDbHandle(false), sql_exec, 0, 0, NULL); int iRet = sqlite3_exec(GetDbHandle(), sql_exec, 0, 0, NULL);
if (iRet != SQLITE_OK) { if (iRet != SQLITE_OK) {
zlog_error(zbt, "fail to delete table:%s", ptableName); zlog_error(zbt, "fail to delete table:%s", ptableName);
} }
@ -144,10 +251,10 @@ void SqliteDB::CreatedataStatictable(const char *ptableName) {
memset(sql_exec, 0, 2048); memset(sql_exec, 0, 2048);
sprintf(sql_exec, "create table if not exists %s(%s,%s,%s,%s,%s,%s,%s,%s integer,%s,%s,%s,%s integer,%s,%s);", ptableName, T_DATASTATIC_INFO(DATANODENO), T_DATASTATIC_INFO(CHANNELID), T_DATASTATIC_INFO(TEMTOP), T_DATASTATIC_INFO(TEMBOT), T_DATASTATIC_INFO(DIP), sprintf(sql_exec, "create table if not exists %s(%s,%s,%s,%s,%s,%s,%s,%s integer,%s,%s,%s,%s integer,%s,%s);", ptableName, T_DATASTATIC_INFO(DATANODENO), T_DATASTATIC_INFO(CHANNELID), T_DATASTATIC_INFO(TEMTOP), T_DATASTATIC_INFO(TEMBOT), T_DATASTATIC_INFO(DIP),
T_DATASTATIC_INFO(VOLTAGE), "zigbeeSignal", "StaticIndex", T_DATASTATIC_INFO(TIMESTAMP), "sendMsg", "nodeResend", "zigbeeSignalNode", "statisticType", "timing"); T_DATASTATIC_INFO(VOLTAGE), "zigbeeSignal", "StaticIndex", T_DATASTATIC_INFO(TIMESTAMP), "sendMsg", "nodeResend", "zigbeeSignalNode", "statisticType", "timing");
CreateTable(sql_exec, 0); CreateTable(sql_exec);
memset(sql_exec, 0, 2048); memset(sql_exec, 0, 2048);
sprintf(sql_exec, "CREATE INDEX %s_1 ON %s (%s)", ptableName, ptableName, T_DATA_INFO(DATANODENO)); sprintf(sql_exec, "CREATE INDEX %s_1 ON %s (%s)", ptableName, ptableName, T_DATA_INFO(DATANODENO));
CreateTable(sql_exec, 0); CreateTable(sql_exec);
} }
bool SqliteDB::OpenDB(const char *pDbName) { bool SqliteDB::OpenDB(const char *pDbName) {
@ -158,7 +265,7 @@ bool SqliteDB::OpenDB(const char *pDbName) {
sqlite3_exec(mDBAcess, "PRAGMA cache_size=8000;", 0, 0, 0); sqlite3_exec(mDBAcess, "PRAGMA cache_size=8000;", 0, 0, 0);
sqlite3_exec(mDBAcess, "PRAGMA temp_store = MEMORY;", 0, 0, 0); sqlite3_exec(mDBAcess, "PRAGMA temp_store = MEMORY;", 0, 0, 0);
sqlite3_exec(mDBAcess, "PRAGMA auto_vacuum = 1;", 0, 0, 0); sqlite3_exec(mDBAcess, "PRAGMA auto_vacuum = 1;", 0, 0, 0);
print_info("Success To Open DataBase!\n"); zlog_info(zbt, "Success To Open DataBase!");
} else { } else {
zlog_error(zbt, "Fail To Open DataBase:%s, ret:%d", pDbName, ret); zlog_error(zbt, "Fail To Open DataBase:%s, ret:%d", pDbName, ret);
return false; return false;
@ -198,7 +305,7 @@ int SqliteDB::GetTableColumnCount(const char *tablename) {
int count = 0; int count = 0;
sqlite3_stmt *stmt; sqlite3_stmt *stmt;
strSql = strSql + tablename + ";"; strSql = strSql + tablename + ";";
print_light_green("%s\n", strSql.c_str()); zlog_info(zct, "%s", strSql.c_str());
sqlite3_prepare_v2(GetDbHandle(), strSql.c_str(), -1, &stmt, 0); sqlite3_prepare_v2(GetDbHandle(), strSql.c_str(), -1, &stmt, 0);
count = sqlite3_column_count(stmt); count = sqlite3_column_count(stmt);
sqlite3_finalize(stmt); sqlite3_finalize(stmt);
@ -270,34 +377,6 @@ vec_t SqliteDB::GetDataSingleLine(const char *tablename, const char *column, con
return vecResult; return vecResult;
} }
char *SqliteDB::GetDataChar(const char *tablename, const char *column, const char *whereCon) {
char szRes[100] = {0x00};
std::string strSql = "select ";
if (whereCon != NULL) {
strSql = strSql + column + " from " + tablename + " where " + whereCon + ";";
} else {
strSql = strSql + column + " from " + tablename + ";";
}
zlog_info(zct, "[GetDataChar] sql:%s", strSql.c_str());
sqlite3_stmt *stmt;
g_tDbMutex.Lock();
if (sqlite3_prepare_v2(mDBAcess, strSql.c_str(), -1, &stmt, 0) != SQLITE_OK) {
zlog_error(zct, "sqlite3_prepare_v2:%s, sql:[%s]", sqlite3_errmsg(mDBAcess), strSql.c_str());
sqlite3_finalize(stmt);
g_tDbMutex.UnLock();
return NULL;
}
int retStep = sqlite3_step(stmt);
if (retStep == SQLITE_ROW) {
char *columninfo = (char *)sqlite3_column_text(stmt, 0);
memcpy(szRes, columninfo, sizeof(szRes));
}
sqlite3_finalize(stmt);
g_tDbMutex.UnLock();
return szRes;
}
std::string SqliteDB::GetData(const char *tablename, const char *column, const char *whereCon) { std::string SqliteDB::GetData(const char *tablename, const char *column, const char *whereCon) {
std::string strRes = ""; std::string strRes = "";
std::string strSql = "select "; std::string strSql = "select ";
@ -308,11 +387,12 @@ std::string SqliteDB::GetData(const char *tablename, const char *column, const c
} }
zlog_info(zct, "[GetData] sql:%s", strSql.c_str()); zlog_info(zct, "[GetData] sql:%s", strSql.c_str());
sqlite3_stmt *stmt; sqlite3_stmt *stmt;
g_tDbMutex.Lock(); std::unique_lock<std::mutex> lock(mtx_);
mtx_.lock();
if (sqlite3_prepare_v2(mDBAcess, strSql.c_str(), -1, &stmt, 0) != SQLITE_OK) { if (sqlite3_prepare_v2(mDBAcess, strSql.c_str(), -1, &stmt, 0) != SQLITE_OK) {
zlog_error(zct, "sqlite3_prepare_v2:%s, sql:[%s]", sqlite3_errmsg(mDBAcess), strSql.c_str()); zlog_error(zct, "sqlite3_prepare_v2:%s, sql:[%s]", sqlite3_errmsg(mDBAcess), strSql.c_str());
sqlite3_finalize(stmt); sqlite3_finalize(stmt);
g_tDbMutex.UnLock(); mtx_.unlock();
return strRes; return strRes;
} }
int retStep = sqlite3_step(stmt); int retStep = sqlite3_step(stmt);
@ -321,7 +401,7 @@ std::string SqliteDB::GetData(const char *tablename, const char *column, const c
strRes = columninfo != NULL ? columninfo : ""; strRes = columninfo != NULL ? columninfo : "";
} }
sqlite3_finalize(stmt); sqlite3_finalize(stmt);
g_tDbMutex.UnLock(); mtx_.unlock();
return strRes; return strRes;
} }
@ -336,11 +416,12 @@ array_t SqliteDB::GetDataMultiLine(const char *tablename, const char *column, co
zlog_info(zct, "[GetDataMultiLine] sql:%s", strSql.c_str()); zlog_info(zct, "[GetDataMultiLine] sql:%s", strSql.c_str());
sqlite3_stmt *stmt; sqlite3_stmt *stmt;
g_tDbMutex.Lock(); std::unique_lock<std::mutex> lock(mtx_);
mtx_.lock();
if (sqlite3_prepare_v2(mDBAcess, strSql.c_str(), -1, &stmt, 0) != SQLITE_OK) { if (sqlite3_prepare_v2(mDBAcess, strSql.c_str(), -1, &stmt, 0) != SQLITE_OK) {
zlog_error(zct, "sqlite3_prepare_v2:%s, sql:[%s]", sqlite3_errmsg(mDBAcess), strSql.c_str()); zlog_error(zct, "sqlite3_prepare_v2:%s, sql:[%s]", sqlite3_errmsg(mDBAcess), strSql.c_str());
sqlite3_finalize(stmt); sqlite3_finalize(stmt);
g_tDbMutex.UnLock(); mtx_.unlock();
return arrResult; return arrResult;
} }
int retStep = sqlite3_step(stmt); int retStep = sqlite3_step(stmt);
@ -356,7 +437,7 @@ array_t SqliteDB::GetDataMultiLine(const char *tablename, const char *column, co
retStep = sqlite3_step(stmt); retStep = sqlite3_step(stmt);
} }
sqlite3_finalize(stmt); sqlite3_finalize(stmt);
g_tDbMutex.UnLock(); mtx_.unlock();
return arrResult; return arrResult;
} }
@ -519,14 +600,15 @@ int SqliteDB::UpdateTableData(const char *tablename, const char *updateColumn, c
} }
zlog_info(zct, "[UpdateTableData] sql:%s", strSql.c_str()); zlog_info(zct, "[UpdateTableData] sql:%s", strSql.c_str());
char *msg; char *msg;
g_tDbMutex.Lock(); std::unique_lock<std::mutex> lock(mtx_);
mtx_.lock();
int iRet = sqlite3_exec(GetDbHandle(), strSql.c_str(), 0, 0, &msg); int iRet = sqlite3_exec(GetDbHandle(), strSql.c_str(), 0, 0, &msg);
if (iRet != SQLITE_OK) { if (iRet != SQLITE_OK) {
zlog_error(zct, "sqlite3 error: code=%d msg=%s sql=[%s]", iRet, msg, strSql.c_str()); zlog_error(zct, "sqlite3 error: code=%d msg=%s sql=[%s]", iRet, msg, strSql.c_str());
sqlite3_free(msg); sqlite3_free(msg);
} }
g_tDbMutex.UnLock(); mtx_.unlock();
return iRet; return iRet;
} }
@ -564,7 +646,7 @@ int SqliteDB::InsertData(const char *tablename, const char *insertValues, int re
if (expandable) { if (expandable) {
char *strSql = (char *)malloc(4096); char *strSql = (char *)malloc(4096);
if (strSql == NULL) { if (strSql == NULL) {
print_error("malloc error\n"); zlog_error(zct, "malloc error");
abort(); abort();
} }
char strReplace[] = "replace into "; char strReplace[] = "replace into ";
@ -573,7 +655,7 @@ int SqliteDB::InsertData(const char *tablename, const char *insertValues, int re
memset(strReplace, 0, sizeof(strSql)); memset(strReplace, 0, sizeof(strSql));
} }
sprintf(strSql, "%s %s%s %s %s %s", "insert into", strReplace, tablename, "values(", insertValues, ");"); sprintf(strSql, "%s %s%s %s %s %s", "insert into", strReplace, tablename, "values(", insertValues, ");");
zlog_info(zct, "[InsertData] expandable sql:%s", strSql.c_str()); zlog_info(zct, "[InsertData] expandable sql:%s", strSql);
iRet = sqlite3_exec(GetDbHandle(), strSql, 0, 0, &msg); iRet = sqlite3_exec(GetDbHandle(), strSql, 0, 0, &msg);
if (iRet != SQLITE_OK) { if (iRet != SQLITE_OK) {
@ -601,7 +683,7 @@ int SqliteDB::InsertData(const char *tablename, const char *insertValues, int re
int SqliteDB::InsertData(const char *insertSql) { int SqliteDB::InsertData(const char *insertSql) {
char *msg; char *msg;
int iRet = sqlite3_exec(GetDbHandle(false), insertSql, 0, 0, &msg); int iRet = sqlite3_exec(GetDbHandle(), insertSql, 0, 0, &msg);
if (iRet != SQLITE_OK) { if (iRet != SQLITE_OK) {
zlog_error(zct, "sqlite3 error: code=%d msg=%s sql=[%s]", iRet, msg, insertSql); zlog_error(zct, "sqlite3 error: code=%d msg=%s sql=[%s]", iRet, msg, insertSql);
sqlite3_free(msg); sqlite3_free(msg);
@ -620,7 +702,7 @@ int SqliteDB::CalculateBattery() {
array_t vecRes = GetDataMultiLine(T_SENSOR_INFO(TNAME), selectSql, NULL); array_t vecRes = GetDataMultiLine(T_SENSOR_INFO(TNAME), selectSql, NULL);
zlog_info(zct, "res = %d", vecRes.size()); zlog_info(zct, "res = %d", vecRes.size());
if (vecRes.size() > 0) { if (vecRes.size() > 0) {
for (int i = 0; i < vecRes.size(); i++) { for (size_t i = 0; i < vecRes.size(); i++) {
float capacity = 0.0, startCapacity = 0.0; float capacity = 0.0, startCapacity = 0.0;
memset(whereCon, 0x00, sizeof(whereCon)); memset(whereCon, 0x00, sizeof(whereCon));
memset(selectSql, 0x00, sizeof(selectSql)); memset(selectSql, 0x00, sizeof(selectSql));
@ -640,7 +722,7 @@ int SqliteDB::CalculateBattery() {
sprintf(updateSql, "batteryPower = '%f,%f' ", startCapacity, startCapacity); sprintf(updateSql, "batteryPower = '%f,%f' ", startCapacity, startCapacity);
int iRet = UpdateTableData(T_SENSOR_INFO(TNAME), updateSql, whereCon); UpdateTableData(T_SENSOR_INFO(TNAME), updateSql, whereCon);
memset(whereCon, 0x00, sizeof(whereCon)); memset(whereCon, 0x00, sizeof(whereCon));
sprintf(whereCon, " dataNodeNo = '%s' order by timeStamp asc limit 0,1 ", vecRes[i][0].c_str()); sprintf(whereCon, " dataNodeNo = '%s' order by timeStamp asc limit 0,1 ", vecRes[i][0].c_str());
vecResSig = sqlite_db_ctrl::instance().GetDataSingleLine(T_BATTERY_INFO(TNAME), " * ", whereCon); vecResSig = sqlite_db_ctrl::instance().GetDataSingleLine(T_BATTERY_INFO(TNAME), " * ", whereCon);
@ -733,7 +815,7 @@ int SqliteDB::CalculateBattery() {
sprintf(updateSql, "batteryPower = '%s,%f' ", vParam[0].c_str(), remainBattery); sprintf(updateSql, "batteryPower = '%s,%f' ", vParam[0].c_str(), remainBattery);
} }
int iRet = UpdateTableData(T_SENSOR_INFO(TNAME), updateSql, whereCon); UpdateTableData(T_SENSOR_INFO(TNAME), updateSql, whereCon);
std::string strData = sqlite_db_ctrl::instance().GetNodeConfigureInfor(whereCon); std::string strData = sqlite_db_ctrl::instance().GetNodeConfigureInfor(whereCon);
data_publish(strData.c_str(), GlobalConfig::Topic_G.mPubConfig.c_str()); data_publish(strData.c_str(), GlobalConfig::Topic_G.mPubConfig.c_str());
} }
@ -756,7 +838,7 @@ int SqliteDB::CalculateDip() {
readStringValue("config", "loose", looseValue, (char *)GlobalConfig::Config_G.c_str()); readStringValue("config", "loose", looseValue, (char *)GlobalConfig::Config_G.c_str());
vecRes = GetDataMultiLine(T_SENSOR_INFO(TNAME), " * ", NULL); vecRes = GetDataMultiLine(T_SENSOR_INFO(TNAME), " * ", NULL);
zlog_info(zct, "vecRes111 = %d", vecRes.size()); zlog_info(zct, "vecRes111 = %d", vecRes.size());
for (int i = 0; i < vecRes.size(); i++) { for (size_t i = 0; i < vecRes.size(); i++) {
std::vector<std::string> vParam; std::vector<std::string> vParam;
zlog_info(zct, "vecRes = %s", vecRes[i][42].c_str()); zlog_info(zct, "vecRes = %s", vecRes[i][42].c_str());
boost::split(vParam, vecRes[i][42], boost::is_any_of(","), boost::token_compress_on); boost::split(vParam, vecRes[i][42], boost::is_any_of(","), boost::token_compress_on);
@ -792,7 +874,7 @@ int SqliteDB::CalculateDip() {
} }
} else if (vParam[1] == "1") { } else if (vParam[1] == "1") {
} else if (vParam[1] == "2") { } else if (vParam[1] == "2") {
zlog_info(zct, "localtimestamp = %ld,vParam[2]=%d,%ld", atol(localtimestamp), atol(vParam[2].c_str()), atol(localtimestamp) - atol(vParam[2].c_str())); zlog_info(zct, "localtimestamp = %ld,vParam[2]=%ld,%ld", atol(localtimestamp), atol(vParam[2].c_str()), atol(localtimestamp) - atol(vParam[2].c_str()));
if (atol(localtimestamp) - atol(vParam[2].c_str()) > 86400) { if (atol(localtimestamp) - atol(vParam[2].c_str()) > 86400) {
sprintf(updateSql, "LooseValue = '%f,0' ", atof(vParam[0].c_str())); sprintf(updateSql, "LooseValue = '%f,0' ", atof(vParam[0].c_str()));
} else { } else {
@ -810,6 +892,7 @@ int SqliteDB::CalculateDip() {
UpdateTableData(T_SENSOR_INFO(TNAME), updateSql, whereCon); UpdateTableData(T_SENSOR_INFO(TNAME), updateSql, whereCon);
} }
zlog_info(zct, "CalculateDip"); zlog_info(zct, "CalculateDip");
return 0;
} }
int SqliteDB::InintGateway() { int SqliteDB::InintGateway() {
@ -875,6 +958,7 @@ int SqliteDB::InintGateway() {
dataBody = showValue.write(jsBody); dataBody = showValue.write(jsBody);
jsonVal["cmdBody"] = dataBody; jsonVal["cmdBody"] = dataBody;
data_publish(showValue.write(jsonVal).c_str(), GlobalConfig::Topic_G.mPubConfig.c_str()); data_publish(showValue.write(jsonVal).c_str(), GlobalConfig::Topic_G.mPubConfig.c_str());
return 0;
} }
std::string SqliteDB::GetNodeConfigureInfor(const char *whereCon) { std::string SqliteDB::GetNodeConfigureInfor(const char *whereCon) {
@ -955,14 +1039,14 @@ std::string SqliteDB::GetNodeConfigureInfor(const char *whereCon) {
int SqliteDB::QueryofflineData() { int SqliteDB::QueryofflineData() {
array_t arrRetdataNode = GetDataMultiLine(T_SENSOR_INFO(TNAME), " dataNodeNo,MeasurementID ", NULL); array_t arrRetdataNode = GetDataMultiLine(T_SENSOR_INFO(TNAME), " dataNodeNo,MeasurementID ", NULL);
for (int i = 0; i < arrRetdataNode.size(); i++) { for (size_t i = 0; i < arrRetdataNode.size(); i++) {
char StaticTableName[50] = {0x00}; char StaticTableName[50] = {0x00};
sprintf(StaticTableName, "t_dataStatic_%s", arrRetdataNode[i][0].c_str()); sprintf(StaticTableName, "t_dataStatic_%s", arrRetdataNode[i][0].c_str());
array_t arrRetData = GetDataMultiLine(StaticTableName, "*", "sendMsg = '0' order by timeStamp asc"); array_t arrRetData = GetDataMultiLine(StaticTableName, "*", "sendMsg = '0' order by timeStamp asc");
zlog_info(zct, "mqttresend check datanodeNo %s,data count %d", arrRetdataNode[i][0].c_str(), arrRetData.size()); zlog_info(zct, "mqttresend check datanodeNo %s,data count %d", arrRetdataNode[i][0].c_str(), arrRetData.size());
if (arrRetData.size() < 1) continue; if (arrRetData.size() < 1) continue;
for (int j = 0; j < arrRetData.size(); j++) { for (size_t j = 0; j < arrRetData.size(); j++) {
char dataTableName[50] = {0x00}; char dataTableName[50] = {0x00};
sprintf(dataTableName, "t_data_%s", arrRetdataNode[i][0].c_str()); sprintf(dataTableName, "t_data_%s", arrRetdataNode[i][0].c_str());
char tmpWhere[128] = {0x00}; char tmpWhere[128] = {0x00};
@ -971,7 +1055,7 @@ int SqliteDB::QueryofflineData() {
if (arrRet.size() > 0) { if (arrRet.size() > 0) {
Json::Value valNodeData; Json::Value valNodeData;
Json::Value valNodeFeature; Json::Value valNodeFeature;
for (int k = 0; k < arrRet.size(); k++) { for (size_t k = 0; k < arrRet.size(); k++) {
valNodeFeature["dataNodeNo"] = arrRetdataNode[i][1].c_str(); valNodeFeature["dataNodeNo"] = arrRetdataNode[i][1].c_str();
valNodeFeature["ChannelId"] = arrRet[k][1].c_str(); valNodeFeature["ChannelId"] = arrRet[k][1].c_str();
valNodeFeature["diagnosisPk"] = atof(arrRet[k][2].c_str()); valNodeFeature["diagnosisPk"] = atof(arrRet[k][2].c_str());
@ -1032,19 +1116,19 @@ int SqliteDB::QueryofflineData() {
array_t arrRetData = GetDataMultiLine("t_data_waveSend", "*", whereCon); array_t arrRetData = GetDataMultiLine("t_data_waveSend", "*", whereCon);
zlog_info(zct, "mqttresend check wave count %d", arrRetData.size()); zlog_info(zct, "mqttresend check wave count %d", arrRetData.size());
if (arrRetData.size() > 0) { if (arrRetData.size() > 0) {
for (int i = 0; i < arrRetData.size(); i++) { for (size_t i = 0; i < arrRetData.size(); i++) {
std::string strWaveData = ""; std::string strWaveData = "";
if (access(arrRetData[i][1].c_str(), 0) >= 0) { if (access(arrRetData[i][1].c_str(), 0) >= 0) {
std::vector<float> vecWave; std::vector<float> vecWave;
char localtimestamp[32] = {0}; char localtimestamp[32] = {0};
float fTemp = 0; float fTemp = 0;
std::ifstream inFile(arrRetData[i][1].c_str(), ios::in | ios::binary); std::ifstream inFile(arrRetData[i][1].c_str(), std::ios::in | std::ios::binary);
inFile.read((char *)localtimestamp, sizeof(localtimestamp)); inFile.read((char *)localtimestamp, sizeof(localtimestamp));
while (inFile.read((char *)&fTemp, sizeof(fTemp))) { while (inFile.read((char *)&fTemp, sizeof(fTemp))) {
vecWave.push_back(fTemp); vecWave.push_back(fTemp);
} }
for (int i = 0; i < vecWave.size(); i++) { for (size_t i = 0; i < vecWave.size(); i++) {
char buf[33] = {0x00}; char buf[33] = {0x00};
memset(buf, 0x00, sizeof(buf)); memset(buf, 0x00, sizeof(buf));
sprintf(buf, "%.2f", vecWave[i]); sprintf(buf, "%.2f", vecWave[i]);
@ -1080,6 +1164,7 @@ int SqliteDB::QueryofflineData() {
} }
} }
} }
return 0;
} }
int SqliteDB::CalculateData() { int SqliteDB::CalculateData() {
@ -1211,6 +1296,7 @@ int SqliteDB::CalculateData() {
zlog_info(zct, "plan Statistic Count = %d , 06 Count = %d , Timing Count = %d , CountWaveX = %d ", planCountStatistic * vecRet.size(), planCount * vecRet.size(), planCount * vecRet.size(), planCount * vecRet.size()); zlog_info(zct, "plan Statistic Count = %d , 06 Count = %d , Timing Count = %d , CountWaveX = %d ", planCountStatistic * vecRet.size(), planCount * vecRet.size(), planCount * vecRet.size(), planCount * vecRet.size());
zlog_info(zct, "reality Statistic Count = %d , 06 Count = %d , Timing Count = %d , CountWaveX = %d ,CountWaveY = %d ,CountWaveZ = %d ", StatisticCountTotal, SixCountTotal, TimingCountTotal, CountWaveXTotal, CountWaveYTotal, CountWaveZTotal); zlog_info(zct, "reality Statistic Count = %d , 06 Count = %d , Timing Count = %d , CountWaveX = %d ,CountWaveY = %d ,CountWaveZ = %d ", StatisticCountTotal, SixCountTotal, TimingCountTotal, CountWaveXTotal, CountWaveYTotal, CountWaveZTotal);
} }
return 0;
} }
int SqliteDB::TransBegin() { return sqlite3_exec(mDBAcess, "begin;", 0, 0, 0); } int SqliteDB::TransBegin() { return sqlite3_exec(mDBAcess, "begin;", 0, 0, 0); }

View File

@ -7,6 +7,7 @@ extern "C" {
#include <string.h> #include <string.h>
#include <map> #include <map>
#include <vector> #include <vector>
#include <mutex>
#include <boost/container/detail/singleton.hpp> #include <boost/container/detail/singleton.hpp>
#define T_SENSOR_INFO(x) T_SENSOR_INFO[T_SENSOR_INFO_##x] #define T_SENSOR_INFO(x) T_SENSOR_INFO[T_SENSOR_INFO_##x]
@ -41,7 +42,6 @@ public:
int AlterTable(const char *tablename, const char *column, bool isAdd = true); int AlterTable(const char *tablename, const char *column, bool isAdd = true);
vec_t GetDataSingleLine(const char *tablename, const char *column, const char *whereCon); vec_t GetDataSingleLine(const char *tablename, const char *column, const char *whereCon);
std::string GetData(const char *tablename, const char *column, const char *whereCon); std::string GetData(const char *tablename, const char *column, const char *whereCon);
char *GetDataChar(const char *tablename, const char *column, const char *whereCon);
array_t GetDataMultiLine(const char *tablename, const char *column, const char *whereCon); array_t GetDataMultiLine(const char *tablename, const char *column, const char *whereCon);
array_t GetDataMultiLineTransaction(const char *tablename, const char *column, const char *whereCon); array_t GetDataMultiLineTransaction(const char *tablename, const char *column, const char *whereCon);
vec_t GetDataMultiLineOfOneColumn(const char *tablename, const char *column, const char *whereCon); vec_t GetDataMultiLineOfOneColumn(const char *tablename, const char *column, const char *whereCon);
@ -66,6 +66,7 @@ public:
private: private:
sqlite3 *GetDbHandle(); sqlite3 *GetDbHandle();
sqlite3 *mDBAcess; sqlite3 *mDBAcess;
std::mutex mtx_;
}; };
typedef boost::container::dtl::singleton_default<SqliteDB> sqlite_db_ctrl; typedef boost::container::dtl::singleton_default<SqliteDB> sqlite_db_ctrl;

View File

@ -1,7 +1,9 @@
#include "communication_cmd.hpp" #include "communication_cmd.hpp"
#include <zlog.h> #include <zlog.h>
#include "common/global.hpp"
#include "dbaccess/sql_db.hpp" #include "dbaccess/sql_db.hpp"
#include "mqttclient/mqtt_client.h"
#include "datatransfer/data_trans.hpp"
#include "platform/platform_init.hpp" #include "platform/platform_init.hpp"
#include "utility/md5.h" #include "utility/md5.h"
@ -97,7 +99,7 @@ std::string JsonData::JsonCmd_23(Param_23 &param) {
WriteStr2Config(SERVERCONFIG, "Server", "CommMode", param.mCommMode); WriteStr2Config(SERVERCONFIG, "Server", "CommMode", param.mCommMode);
WriteStr2Config(SERVERCONFIG, "Server", "Password", param.mPassword); WriteStr2Config(SERVERCONFIG, "Server", "Password", param.mPassword);
WriteStr2Config(SERVERCONFIG, "Server", "UserName", param.mUserName); WriteStr2Config(SERVERCONFIG, "Server", "UserName", param.mUserName);
print_info("param.mCommMode = %s\n", param.mCommMode.c_str()); zlog_info(zct, "param.mCommMode = %s", param.mCommMode.c_str());
if ("1" == param.mCommMode) { //有线连接 if ("1" == param.mCommMode) { //有线连接
system("mv /etc/init.d/S91quectel-CM.sh /etc/init.d/wireless.sh"); system("mv /etc/init.d/S91quectel-CM.sh /etc/init.d/wireless.sh");
system("mv /etc/init.d/S95check5G /etc/init.d/wireless5G"); system("mv /etc/init.d/S95check5G /etc/init.d/wireless5G");
@ -157,7 +159,7 @@ std::string JsonData::JsonCmd_25(Param_25 &param) {
} else { } else {
bFlag4 = true; bFlag4 = true;
} }
print_info("bFlag1 = %d,bFlag2 = %d,bFlag3 = %d,bFlag4 = %d\n", bFlag1, bFlag2, bFlag3, bFlag4); zlog_info(zct, "bFlag1 = %d,bFlag2 = %d,bFlag3 = %d,bFlag4 = %d", bFlag1, bFlag2, bFlag3, bFlag4);
#ifdef IMX6UL_GATEWAY #ifdef IMX6UL_GATEWAY
param.mNet = "Net"; param.mNet = "Net";
#endif #endif
@ -188,7 +190,7 @@ std::string JsonData::JsonCmd_25(Param_25 &param) {
#ifdef IMX6UL_GATEWAY #ifdef IMX6UL_GATEWAY
system("sed -i '7c udhcpc -i eth0 > /dev/null &' /etc/init.d/S90start_userapp.sh"); system("sed -i '7c udhcpc -i eth0 > /dev/null &' /etc/init.d/S90start_userapp.sh");
#endif #endif
platform->EquipIpInit(param.mNet); PlatformInit::EquipIpInit(param.mNet);
} else if (0 == param.mMode && (!bFlag1 || !bFlag2 || !bFlag3 || !bFlag4) && param.mNetworkPortStatus == "STATIC") { } else if (0 == param.mMode && (!bFlag1 || !bFlag2 || !bFlag3 || !bFlag4) && param.mNetworkPortStatus == "STATIC") {
jsonVal["success"] = false; jsonVal["success"] = false;
@ -442,8 +444,8 @@ std::string JsonData::JsonCmd_52() {
sprintf(whereCon, "sendMsg = '0' and timeStamp = '%s'", strTimeStamp.c_str()); sprintf(whereCon, "sendMsg = '0' and timeStamp = '%s'", strTimeStamp.c_str());
int iRet = data_publish(data.c_str(), GlobalConfig::Topic_G.mPubCmd.c_str()); int iRet = data_publish(data.c_str(), GlobalConfig::Topic_G.mPubCmd.c_str());
if (iRet == 0) { if (iRet == 0) {
sqlite_db_ctrl::instance().DeleteTableData(T_DATA_INFO(TNAME), whereCon, 0); sqlite_db_ctrl::instance().DeleteTableData(T_DATA_INFO(TNAME), whereCon);
sqlite_db_ctrl::instance().DeleteTableData(T_DATASTATIC_INFO(TNAME), whereCon, 0); sqlite_db_ctrl::instance().DeleteTableData(T_DATASTATIC_INFO(TNAME), whereCon);
} }
mssleep(100); mssleep(100);
} }
@ -458,8 +460,7 @@ std::string JsonData::JsonCmd_53(Json::Value &recvBody) {
jsonVal["cmd"] = "53"; jsonVal["cmd"] = "53";
jsonVal["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G; jsonVal["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G;
std::string looseValue = recvBody["looseValue"].asString(); std::string looseValue = recvBody["looseValue"].asString();
int iRet = writeStringVlaue("config", (char*)std::string("loose").c_str(), (char *)looseValue.c_str(), (char *)GlobalConfig::Config_G.c_str());
int iRet = writeStringVlaue("config", "loose", (char *)looseValue.c_str(), (char *)GlobalConfig::Config_G.c_str());
if (iRet != 0) { if (iRet != 0) {
jsonVal["success"] = false; jsonVal["success"] = false;
jsonVal["message"] = "update failed"; jsonVal["message"] = "update failed";
@ -500,7 +501,7 @@ void JsonData::DataNodeStatusCheck() {
std::string nowTimetamp = std::string(localtimestamp); std::string nowTimetamp = std::string(localtimestamp);
int lNowTime = atoi(nowTimetamp.c_str()); int lNowTime = atoi(nowTimetamp.c_str());
int onlineCheck = readIntValue("config", "online", (char *)GlobalConfig::Config_G.c_str()); int onlineCheck = readIntValue("config", "online", (char *)GlobalConfig::Config_G.c_str());
int loseTime = readIntValue("config", "loseTime", (char *)GlobalConfig::Config_G.c_str()); //int loseTime = readIntValue("config", "loseTime", (char *)GlobalConfig::Config_G.c_str());
int nodeOnline = readIntValue("config", "nodeOnline", (char *)GlobalConfig::Config_G.c_str()); int nodeOnline = readIntValue("config", "nodeOnline", (char *)GlobalConfig::Config_G.c_str());
int count = 0; int count = 0;
if (nSize > 0) { if (nSize > 0) {
@ -545,7 +546,7 @@ std::string JsonData::JsonCmd_07() {
jsonVal.clear(); jsonVal.clear();
std::string sysStatus = GetSysStatus(); std::string sysStatus = GetSysStatus();
print_info("sysStatus : %s\n", sysStatus.c_str()); zlog_info(zct, "sysStatus : %s", sysStatus.c_str());
Json::Features f = Json::Features::strictMode(); Json::Features f = Json::Features::strictMode();
Json::Reader recvReader(f); Json::Reader recvReader(f);
Json::Value recvSys; Json::Value recvSys;

View File

@ -1,5 +1,7 @@
#include "communication_cmd.hpp" #include "communication_cmd.hpp"
#include <zlog.h> #include <zlog.h>
#include "common/global.hpp"
#include "mqttclient/mqtt_client.h"
#include "dbaccess/sql_db.hpp" #include "dbaccess/sql_db.hpp"
#include "platform/platform_init.hpp" #include "platform/platform_init.hpp"
#include "utility/md5.h" #include "utility/md5.h"
@ -70,10 +72,9 @@ std::string JsonData::JsonCmd_Cgi_02(Param_02 &param) {
char buf[256] = {0}; char buf[256] = {0};
sprintf(buf, "{\"dataNodeGatewayNo\":\"%s\",\"cmd\":\"12\",\"status\":\"REQ\"}", GlobalConfig::MacAddr_G.c_str()); sprintf(buf, "{\"dataNodeGatewayNo\":\"%s\",\"cmd\":\"12\",\"status\":\"REQ\"}", GlobalConfig::MacAddr_G.c_str());
std::string str = std::string(buf); std::string str = std::string(buf);
int iRet = data_publish(str.c_str(), GlobalConfig::Topic_G.mPubCmd.c_str()); data_publish(str.c_str(), GlobalConfig::Topic_G.mPubCmd.c_str());
} }
} else if (1 == param.mMode) { } else if (1 == param.mMode) {
char cmd[256] = {0};
char localtimestamp[32] = {0}; char localtimestamp[32] = {0};
GetTimeNet(localtimestamp, 1); GetTimeNet(localtimestamp, 1);
std::string nowTimetamp = std::string(localtimestamp); std::string nowTimetamp = std::string(localtimestamp);
@ -103,26 +104,7 @@ std::string JsonData::JsonCmd_Cgi_07() {
} }
return show_value_.write(jsonVal); return show_value_.write(jsonVal);
} }
std::string JsonData::JsonCmd_07() {
Json::Value jsonVal;
jsonVal.clear();
std::string sysStatus = GetSysStatus();
zlog_info(zct, "sysStatus : %s", sysStatus.c_str());
Json::Features f = Json::Features::strictMode();
Json::Reader recvReader(f);
Json::Value recvSys;
jsonVal[JSON_FIELD_CMD] = "07";
jsonVal["success"] = true;
jsonVal["message"] = " ";
if (recvReader.parse(sysStatus, recvSys)) {
jsonVal["cmdBody"] = sysStatus;
} else {
jsonVal["success"] = false;
jsonVal["message"] = "状态获取失败";
}
return show_value_.write(jsonVal);
}
std::string JsonData::JsonCmd_Cgi_08() { std::string JsonData::JsonCmd_Cgi_08() {
Json::Value jsonVal; Json::Value jsonVal;
jsonVal.clear(); jsonVal.clear();
@ -329,7 +311,7 @@ std::string JsonData::JsonCmd_Cgi_10(Param_10 &param) {
zlog_info(zct, "vecRes = %d", vecRes.size()); zlog_info(zct, "vecRes = %d", vecRes.size());
if (vecRes.size() > 0) { if (vecRes.size() > 0) {
Json::Value jsStaticData; Json::Value jsStaticData;
for (int i = 0; i < vecRes.size(); i++) { for (size_t i = 0; i < vecRes.size(); i++) {
Json::Value iTem; Json::Value iTem;
if (vecRes[i][1] == param.MeasurementID + "-X") { if (vecRes[i][1] == param.MeasurementID + "-X") {
iTem.append(vecRes[i][0]); iTem.append(vecRes[i][0]);
@ -371,51 +353,6 @@ std::string JsonData::JsonCmd_Cgi_10(Param_10 &param) {
return show_value_.write(jsonVal); return show_value_.write(jsonVal);
} }
std::string JsonData::JsonCmd_Cgi_11(Param_11 &param) {
Json::Value jsonVal, jsSensor;
jsonVal.clear();
jsonVal[JSON_FIELD_CMD] = "11";
jsonVal["success"] = true;
jsonVal["message"] = " ";
char whereCon[512] = {};
sprintf(whereCon, "dataNodeNo='%s' ORDER BY timeStamp DESC LIMIT 0,3", param.DataNodeNo.c_str());
// 自数据库获取传感器特征数据
array_t arrRes;
arrRes = sqlite_db_ctrl::instance().GetDataMultiLineTransaction(T_DATA_INFO(TNAME), "*", whereCon);
int iResult = arrRes.size();
zlog_info(zct, "iResult = %d", iResult);
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);
}
} else {
jsonVal["success"] = false;
jsonVal["content"].resize(0);
}
jsonVal["content"] = jsSensor;
return show_value_.write(jsonVal);
}
std::string JsonData::JsonCmd_Cgi_20(Param_20 &param) { std::string JsonData::JsonCmd_Cgi_20(Param_20 &param) {
Json::Value jsonVal; Json::Value jsonVal;
jsonVal.clear(); jsonVal.clear();
@ -567,7 +504,7 @@ std::string JsonData::JsonCmd_Cgi_25(Param_25 &param) {
jsonVal["success"] = true; jsonVal["success"] = true;
jsonVal["message"] = " "; jsonVal["message"] = " ";
jsonVal["cmd"] = "25"; jsonVal["cmd"] = "25";
string strNet = ""; std::string strNet = "";
bool bFlag1 = CheckIP(param.mGateway.c_str()); bool bFlag1 = CheckIP(param.mGateway.c_str());
bool bFlag2 = IsValidMask(param.mSubnetMask); bool bFlag2 = IsValidMask(param.mSubnetMask);
bool bFlag3 = CheckIP(param.mIp.c_str()); bool bFlag3 = CheckIP(param.mIp.c_str());
@ -596,7 +533,7 @@ std::string JsonData::JsonCmd_Cgi_25(Param_25 &param) {
zlog_info(zct, "GateWay = %s", GateWay); zlog_info(zct, "GateWay = %s", GateWay);
system(GateWay); system(GateWay);
#endif #endif
Platform::EquipIpInit(param.mNet); PlatformInit::EquipIpInit(param.mNet);
} else if (0 == param.mMode && param.mNetworkPortStatus == "DHCP") { } else if (0 == param.mMode && param.mNetworkPortStatus == "DHCP") {
WriteStr2Config(NETWORKCONFIG, param.mNet, "dnsName", ""); WriteStr2Config(NETWORKCONFIG, param.mNet, "dnsName", "");
@ -609,7 +546,7 @@ std::string JsonData::JsonCmd_Cgi_25(Param_25 &param) {
#ifdef IMX6UL_GATEWAY #ifdef IMX6UL_GATEWAY
system("sed -i '7c udhcpc -i eth0 > /dev/null &' /etc/init.d/S90start_userapp.sh"); system("sed -i '7c udhcpc -i eth0 > /dev/null &' /etc/init.d/S90start_userapp.sh");
#endif #endif
platform->EquipIpInit(param.mNet); PlatformInit::EquipIpInit(param.mNet);
} else if (0 == param.mMode && (!bFlag1 || !bFlag2 || !bFlag3 || !bFlag4) && param.mNetworkPortStatus == "STATIC") { } else if (0 == param.mMode && (!bFlag1 || !bFlag2 || !bFlag3 || !bFlag4) && param.mNetworkPortStatus == "STATIC") {
jsonVal["success"] = false; jsonVal["success"] = false;

View File

@ -1,8 +1,12 @@
#include "communication_cmd.hpp" #include "communication_cmd.hpp"
#include <boost/algorithm/string.hpp>
#include <zlog.h> #include <zlog.h>
#include "common/global.hpp"
#include "mqttclient/mqtt_client.h"
#include "dbaccess/sql_db.hpp" #include "dbaccess/sql_db.hpp"
#include "platform/platform_init.hpp" #include "platform/platform_init.hpp"
#include "utility/md5.h" #include "utility/md5.h"
#include "utility/calculation.hpp"
extern zlog_category_t *zct; extern zlog_category_t *zct;
@ -272,10 +276,10 @@ std::string JsonData::JsonCmd_Cgi_27(Param_27 &param) {
sqlite_db_ctrl::instance().DeleteTableData(T_BATTERY_INFO(TNAME), whereCon); sqlite_db_ctrl::instance().DeleteTableData(T_BATTERY_INFO(TNAME), whereCon);
char szTableName[50] = {0x00}; char szTableName[50] = {0x00};
sprintf(szTableName, "DROP TABLE t_data_%s", param.mDataNodeNo.c_str()); sprintf(szTableName, "DROP TABLE t_data_%s", param.mDataNodeNo.c_str());
sqlite_db_ctrl::instance().CreateTable(szTableName, 0); sqlite_db_ctrl::instance().CreateTable(szTableName);
memset(szTableName, 0x00, sizeof(szTableName)); memset(szTableName, 0x00, sizeof(szTableName));
sprintf(szTableName, "DROP TABLE t_dataStatic_%s", param.mDataNodeNo.c_str()); sprintf(szTableName, "DROP TABLE t_dataStatic_%s", param.mDataNodeNo.c_str());
sqlite_db_ctrl::instance().CreateTable(szTableName, 0); sqlite_db_ctrl::instance().CreateTable(szTableName);
} else if (param.mDataNodeNo.length() > 0 && param.mType == "CORRECT") { } else if (param.mDataNodeNo.length() > 0 && param.mType == "CORRECT") {
char updateSql[1024] = {0}; char updateSql[1024] = {0};
sprintf(whereCon, "%s= '%s'", T_SENSOR_INFO(DATANODENO), param.mDataNodeNo.c_str()); sprintf(whereCon, "%s= '%s'", T_SENSOR_INFO(DATANODENO), param.mDataNodeNo.c_str());
@ -329,9 +333,9 @@ std::string JsonData::JsonCmd_Cgi_29(Param_29 &param) {
std::string strWaveData = ""; std::string strWaveData = "";
std::string filename = "/opt/data/" + param.mChannelId + ".dat"; std::string filename = "/opt/data/" + param.mChannelId + ".dat";
if (access(filename.c_str(), 0) >= 0) { if (access(filename.c_str(), 0) >= 0) {
std::ifstream inFile(filename.c_str(), ios::in | ios::binary); std::ifstream inFile(filename.c_str(), std::ios::in | std::ios::binary);
if (!inFile) { if (!inFile) {
print_error("read channel data error\n"); zlog_error(zct, "read channel data error, filename:%s", filename.c_str());
jsonVal["success"] = false; jsonVal["success"] = false;
jsonVal["message"] = "error"; jsonVal["message"] = "error";
} else { } else {
@ -378,8 +382,8 @@ std::string JsonData::JsonCmd_Cgi_29(Param_29 &param) {
jsBody["channelId"] = param.mChannelId; jsBody["channelId"] = param.mChannelId;
jsBody["package"] = param.mPackageFlag; jsBody["package"] = param.mPackageFlag;
zlog_info(zct, "vecWave.size() = %d,sample = %d,second = %f", vecWave.size(), atoi(res[23].c_str()), float(vecWave.size() / atoi(res[23].c_str()))); zlog_info(zct, "vecWave.size() = %d,sample = %d,second = %f", vecWave.size(), atoi(res[23].c_str()), float(vecWave.size() / atoi(res[23].c_str())));
string::size_type comper = param.mChannelId.find("Z"); std::string::size_type comper = param.mChannelId.find("Z");
if (comper != string::npos && res[17] == "02") { if (comper != std::string::npos && res[17] == "02") {
jsBody["second"] = float((float)vecWave.size() / (float)atoi(res[23].c_str())); jsBody["second"] = float((float)vecWave.size() / (float)atoi(res[23].c_str()));
} else if (res[17] == "01") { } else if (res[17] == "01") {
jsBody["second"] = float((float)vecWave.size() / (float)atoi(res[23].c_str())); jsBody["second"] = float((float)vecWave.size() / (float)atoi(res[23].c_str()));
@ -388,7 +392,7 @@ std::string JsonData::JsonCmd_Cgi_29(Param_29 &param) {
} }
jsBody["Data"] = strWaveData; jsBody["Data"] = strWaveData;
jsBody["timestamp"] = string(localtimestamp); jsBody["timestamp"] = std::string(localtimestamp);
jsonVal["content"] = jsBody; jsonVal["content"] = jsBody;
return show_value_.write(jsonVal); return show_value_.write(jsonVal);
} }
@ -403,7 +407,6 @@ std::string JsonData::JsonCmd_Cgi_30(Param_30 &param) {
jsonVal["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G; jsonVal["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G;
jsonVal["success"] = true; jsonVal["success"] = true;
jsonVal["message"] = ""; jsonVal["message"] = "";
int i = 0;
std::string strWaveData; std::string strWaveData;
std::string filename = "/opt/data/" + param.mChannelId + ".dat"; std::string filename = "/opt/data/" + param.mChannelId + ".dat";
char localtimestamp[32] = {0}; char localtimestamp[32] = {0};
@ -417,22 +420,22 @@ std::string JsonData::JsonCmd_Cgi_30(Param_30 &param) {
sprintf(whereCon, "dataNodeNo='%s'", param.mDataNodeNo.c_str()); sprintf(whereCon, "dataNodeNo='%s'", param.mDataNodeNo.c_str());
vec_t res = sqlite_db_ctrl::instance().GetDataSingleLine(T_SENSOR_INFO(TNAME), " * ", whereCon); vec_t res = sqlite_db_ctrl::instance().GetDataSingleLine(T_SENSOR_INFO(TNAME), " * ", whereCon);
if (access(filename.c_str(), 0) >= 0) { if (access(filename.c_str(), 0) >= 0) {
std::ifstream inFile(filename.c_str(), ios::in | ios::binary); std::ifstream inFile(filename.c_str(), std::ios::in | std::ios::binary);
if (!inFile) { if (!inFile) {
print_error("read channel data error\n"); zlog_error(zct, "read channel data error, filename:%s", filename.c_str());
jsonVal["success"] = "false"; jsonVal["success"] = "false";
jsonVal["message"] = "error"; jsonVal["message"] = "error";
} else { } else {
float fTemp = 0; float fTemp = 0;
inFile.read((char *)localtimestamp, sizeof(localtimestamp)); inFile.read((char *)localtimestamp, sizeof(localtimestamp));
string::size_type comper = param.mChannelId.find("Z"); std::string::size_type comper = param.mChannelId.find("Z");
if (comper != string::npos && res[17] == "02") { if (comper != std::string::npos && res[17] == "02") {
while (inFile.read((char *)&fTemp, sizeof(fTemp))) { while (inFile.read((char *)&fTemp, sizeof(fTemp))) {
vecWave.push_back(fTemp); vecWave.push_back(fTemp);
} }
//进行傅立叶变换 //进行傅立叶变换
pCalculation->FFTSpec(vecWave, fftWave); Calculation::FFTSpec(vecWave, fftWave);
sampleRateReference = 1000; sampleRateReference = 1000;
} else { } else {
@ -441,7 +444,7 @@ std::string JsonData::JsonCmd_Cgi_30(Param_30 &param) {
} }
//进行傅立叶变换 //进行傅立叶变换
pCalculation->FFTSpec(vecWave, fftWave); Calculation::FFTSpec(vecWave, fftWave);
sampleRateReference = 1024; sampleRateReference = 1024;
} }
int flag = param.mPackageFlag; int flag = param.mPackageFlag;
@ -481,7 +484,7 @@ std::string JsonData::JsonCmd_Cgi_30(Param_30 &param) {
jsBody["channelId"] = param.mChannelId; jsBody["channelId"] = param.mChannelId;
jsBody["package"] = param.mPackageFlag; jsBody["package"] = param.mPackageFlag;
jsBody["timestamp"] = string(localtimestamp); jsBody["timestamp"] = std::string(localtimestamp);
jsBody["Data"] = strWaveData; jsBody["Data"] = strWaveData;
double resolution = 0.0; double resolution = 0.0;
@ -493,8 +496,8 @@ std::string JsonData::JsonCmd_Cgi_30(Param_30 &param) {
resolution = (((double)SampleRate / 1000) * 1016) / vecWave.size(); resolution = (((double)SampleRate / 1000) * 1016) / vecWave.size();
} else if (res[17] == "02") { } else if (res[17] == "02") {
string::size_type comper = param.mChannelId.find("Z"); std::string::size_type comper = param.mChannelId.find("Z");
if (comper != string::npos) { if (comper != std::string::npos) {
SampleRate = atoi(res[23].c_str()); SampleRate = atoi(res[23].c_str());
resolution = (double)SampleRate / vecWave.size(); resolution = (double)SampleRate / vecWave.size();
zlog_info(zct, "@@@@@@@@@@@@@@@@@@@@sample_rate=%d,resolution = %f", SampleRate, resolution); zlog_info(zct, "@@@@@@@@@@@@@@@@@@@@sample_rate=%d,resolution = %f", SampleRate, resolution);
@ -532,17 +535,16 @@ std::string JsonData::JsonCmd_Cgi_40(Param_40 &param) {
int i = 0; int i = 0;
int sampleRateReference = 0; int sampleRateReference = 0;
std::vector<float> vecWave; std::vector<float> vecWave;
/* 新增代码 */ char whereCon[64] = {0};
char whereCon[64] = {};
sprintf(whereCon, "dataNodeNo='%s'", param.mDataNodeNo.c_str()); sprintf(whereCon, "dataNodeNo='%s'", param.mDataNodeNo.c_str());
vec_t res = sqlite_db_ctrl::instance().GetDataSingleLine(T_SENSOR_INFO(TNAME), " * ", whereCon); vec_t res = sqlite_db_ctrl::instance().GetDataSingleLine(T_SENSOR_INFO(TNAME), " * ", whereCon);
std::string strWaveData; std::string strWaveData;
std::string filename = "/opt/data/" + param.mChannelId + ".dat"; std::string filename = "/opt/data/" + param.mChannelId + ".dat";
char localtimestamp[32] = {0}; char localtimestamp[32] = {0};
if (access(filename.c_str(), 0) >= 0) { if (access(filename.c_str(), 0) >= 0) {
std::ifstream inFile(filename.c_str(), ios::in | ios::binary); std::ifstream inFile(filename.c_str(), std::ios::in | std::ios::binary);
if (!inFile) { if (!inFile) {
print_error("read channel data error\n"); zlog_error(zct, "read channel data error, filename:%s", filename.c_str());
jsonVal["success"] = "false"; jsonVal["success"] = "false";
jsonVal["message"] = "error"; jsonVal["message"] = "error";
} else { } else {
@ -552,14 +554,14 @@ std::string JsonData::JsonCmd_Cgi_40(Param_40 &param) {
std::vector<float> hanningWave; std::vector<float> hanningWave;
std::vector<float> addhanningWave; std::vector<float> addhanningWave;
inFile.read((char *)localtimestamp, sizeof(localtimestamp)); inFile.read((char *)localtimestamp, sizeof(localtimestamp));
string::size_type comper = param.mChannelId.find("Z"); std::string::size_type comper = param.mChannelId.find("Z");
if (comper != string::npos && res[17] == "02") { if (comper != std::string::npos && res[17] == "02") {
while (inFile.read((char *)&fTemp, sizeof(fTemp))) { while (inFile.read((char *)&fTemp, sizeof(fTemp))) {
vecWave.push_back(fTemp); vecWave.push_back(fTemp);
} }
//添加汉宁窗 //添加汉宁窗
pCalculation->Hanning(vecWave, hanningWave); Calculation::Hanning(vecWave, hanningWave);
for (int i = 0; i < vecWave.size(); i++) { for (size_t i = 0; i < vecWave.size(); i++) {
addhanningWave.push_back(vecWave[i] * hanningWave[i]); addhanningWave.push_back(vecWave[i] * hanningWave[i]);
} }
@ -569,7 +571,7 @@ std::string JsonData::JsonCmd_Cgi_40(Param_40 &param) {
param.EndFrequency = 5000; param.EndFrequency = 5000;
} }
pCalculation->envSpec(addhanningWave, envWave, param.StartFrequency, param.EndFrequency); Calculation::envSpec(addhanningWave, envWave, param.StartFrequency, param.EndFrequency);
sampleRateReference = 1000; sampleRateReference = 1000;
} else { } else {
@ -588,8 +590,8 @@ std::string JsonData::JsonCmd_Cgi_40(Param_40 &param) {
} }
//添加汉宁窗 //添加汉宁窗
pCalculation->Hanning(vecWave, hanningWave); Calculation::Hanning(vecWave, hanningWave);
for (int i = 0; i < vecWave.size(); i++) { for (size_t i = 0; i < vecWave.size(); i++) {
addhanningWave.push_back(vecWave[i] * hanningWave[i]); addhanningWave.push_back(vecWave[i] * hanningWave[i]);
} }
@ -599,7 +601,7 @@ std::string JsonData::JsonCmd_Cgi_40(Param_40 &param) {
param.EndFrequency = 5000; param.EndFrequency = 5000;
} }
pCalculation->envSpec(addhanningWave, envWave, param.StartFrequency, param.EndFrequency); Calculation::envSpec(addhanningWave, envWave, param.StartFrequency, param.EndFrequency);
sampleRateReference = 1024; sampleRateReference = 1024;
} }
/*for(int i = 0; i < envWave.size();i++){ /*for(int i = 0; i < envWave.size();i++){
@ -651,7 +653,7 @@ std::string JsonData::JsonCmd_Cgi_40(Param_40 &param) {
jsBody["channelId"] = param.mChannelId; jsBody["channelId"] = param.mChannelId;
jsBody["package"] = param.mPackageFlag; jsBody["package"] = param.mPackageFlag;
jsBody["timestamp"] = string(localtimestamp); jsBody["timestamp"] = std::string(localtimestamp);
jsBody["Data"] = strWaveData; jsBody["Data"] = strWaveData;
double resolution = 0.0; double resolution = 0.0;
@ -662,8 +664,8 @@ std::string JsonData::JsonCmd_Cgi_40(Param_40 &param) {
zlog_info(zct, "@@@@@@@@@@@@@@@@@@@@sample_rate=%d", SampleRate); zlog_info(zct, "@@@@@@@@@@@@@@@@@@@@sample_rate=%d", SampleRate);
resolution = (((double)SampleRate / 1000) * 1016) / 8192; resolution = (((double)SampleRate / 1000) * 1016) / 8192;
} else if (res[17] == "02") { } else if (res[17] == "02") {
string::size_type comper = param.mChannelId.find("Z"); std::string::size_type comper = param.mChannelId.find("Z");
if (comper != string::npos) { if (comper != std::string::npos) {
SampleRate = atoi(res[23].c_str()); SampleRate = atoi(res[23].c_str());
resolution = (double)SampleRate / vecWave.size(); resolution = (double)SampleRate / vecWave.size();
@ -697,7 +699,7 @@ std::string JsonData::JsonCmd_Cgi_41(std::vector<Param_41> &param, int isServer)
char whereCon[1024] = {0}; char whereCon[1024] = {0};
char updateSql[1024] = {0}; char updateSql[1024] = {0};
for (int i = 0; i < param.size(); i++) { for (size_t i = 0; i < param.size(); i++) {
char dataNodeName[100] = {0x00}; char dataNodeName[100] = {0x00};
hexToAscii(param[i].mdataNodeName.c_str(), dataNodeName); hexToAscii(param[i].mdataNodeName.c_str(), dataNodeName);
zlog_info(zct, "str = %s", dataNodeName); zlog_info(zct, "str = %s", dataNodeName);

View File

@ -1,8 +1,13 @@
#include "communication_cmd.hpp" #include "communication_cmd.hpp"
#include <fstream>
#include <boost/algorithm/string.hpp>
#include <zlog.h> #include <zlog.h>
#include "common/global.hpp"
#include "dbaccess/sql_db.hpp" #include "dbaccess/sql_db.hpp"
#include "platform/platform_init.hpp" #include "platform/platform_init.hpp"
#include "utility/md5.h" #include "utility/md5.h"
#include "wifi_5g/wpa_client.h"
#include "utility/calculation.hpp"
extern zlog_category_t *zct; extern zlog_category_t *zct;
@ -215,7 +220,7 @@ std::string JsonData::JsonCmd_Cgi_53(std::vector<Param_53> &param) {
char whereCon[1024] = {0}; char whereCon[1024] = {0};
char updateSql[1024] = {0}; char updateSql[1024] = {0};
for (int i = 0; i < param.size(); i++) { for (size_t i = 0; i < param.size(); i++) {
if (param[i].mUpdateKey2 == "") { if (param[i].mUpdateKey2 == "") {
sprintf(updateSql, "%s='%s',UpdateFlag = 0", param[i].mUpdateKey.c_str(), param[i].mUpdateValue.c_str()); sprintf(updateSql, "%s='%s',UpdateFlag = 0", param[i].mUpdateKey.c_str(), param[i].mUpdateValue.c_str());
} else if (param[i].mUpdateKey3 == "" && param[i].mUpdateKey2 != "") { } else if (param[i].mUpdateKey3 == "" && param[i].mUpdateKey2 != "") {
@ -256,14 +261,13 @@ std::string JsonData::JsonCmd_Cgi_55(Param_55 &param) {
std::string strWaveData = ""; std::string strWaveData = "";
std::string filename = "/opt/data/" + param.mChannelId + ".dat"; std::string filename = "/opt/data/" + param.mChannelId + ".dat";
if (access(filename.c_str(), 0) >= 0) { if (access(filename.c_str(), 0) >= 0) {
std::ifstream inFile(filename.c_str(), ios::in | ios::binary); std::ifstream inFile(filename.c_str(), std::ios::in | std::ios::binary);
if (!inFile) { if (!inFile) {
print_error("read channel data error\n"); zlog_error(zct, "read channel data error, filename:%s", filename.c_str());
jsonVal["success"] = false; jsonVal["success"] = false;
jsonVal["message"] = "error"; jsonVal["message"] = "error";
} else { } else {
float fTemp = 0; float fTemp = 0;
std::vector<float> hanningWave; std::vector<float> hanningWave;
inFile.read((char *)localtimestamp, sizeof(localtimestamp)); inFile.read((char *)localtimestamp, sizeof(localtimestamp));
while (inFile.read((char *)&fTemp, sizeof(fTemp))) { while (inFile.read((char *)&fTemp, sizeof(fTemp))) {
@ -274,8 +278,8 @@ std::string JsonData::JsonCmd_Cgi_55(Param_55 &param) {
resolution = (((double)SampleRate / 1000) * 1016) / vecWave.size(); resolution = (((double)SampleRate / 1000) * 1016) / vecWave.size();
} else if (res[17] == "02") { } else if (res[17] == "02") {
string::size_type comper = param.mChannelId.find("Z"); std::string::size_type comper = param.mChannelId.find("Z");
if (comper != string::npos) { if (comper != std::string::npos) {
resolution = (double)SampleRate / vecWave.size(); resolution = (double)SampleRate / vecWave.size();
zlog_info(zct,"@@@@@@@@@@@@@@@@@@@@sample_rate=%d,resolution = %f", SampleRate, resolution); zlog_info(zct,"@@@@@@@@@@@@@@@@@@@@sample_rate=%d,resolution = %f", SampleRate, resolution);
} else { } else {
@ -286,7 +290,7 @@ std::string JsonData::JsonCmd_Cgi_55(Param_55 &param) {
} }
//积分 //积分
pCalculation->Integration(vecWave, IntegrationWave, resolution); Calculation::Integration(vecWave, IntegrationWave, resolution);
int flag = param.mPackageFlag; int flag = param.mPackageFlag;
flag = (flag + 1) * 1024; flag = (flag + 1) * 1024;
@ -327,8 +331,8 @@ std::string JsonData::JsonCmd_Cgi_55(Param_55 &param) {
jsBody["channelId"] = param.mChannelId; jsBody["channelId"] = param.mChannelId;
jsBody["package"] = param.mPackageFlag; jsBody["package"] = param.mPackageFlag;
zlog_info(zct,"vecWave.size() = %d,sample = %d,second = %f", IntegrationWave.size(), atoi(res[23].c_str()), float(IntegrationWave.size() / atoi(res[23].c_str()))); zlog_info(zct,"vecWave.size() = %d,sample = %d,second = %f", IntegrationWave.size(), atoi(res[23].c_str()), float(IntegrationWave.size() / atoi(res[23].c_str())));
string::size_type comper = param.mChannelId.find("Z"); std::string::size_type comper = param.mChannelId.find("Z");
if (comper != string::npos && res[17] == "02") { if (comper != std::string::npos && res[17] == "02") {
jsBody["second"] = float((float)IntegrationWave.size() / (float)atoi(res[23].c_str())); jsBody["second"] = float((float)IntegrationWave.size() / (float)atoi(res[23].c_str()));
} else if (res[17] == "01") { } else if (res[17] == "01") {
jsBody["second"] = float((float)IntegrationWave.size() / (float)atoi(res[23].c_str())); jsBody["second"] = float((float)IntegrationWave.size() / (float)atoi(res[23].c_str()));
@ -337,7 +341,7 @@ std::string JsonData::JsonCmd_Cgi_55(Param_55 &param) {
} }
jsBody["Data"] = strWaveData; jsBody["Data"] = strWaveData;
jsBody["timestamp"] = string(localtimestamp); jsBody["timestamp"] = std::string(localtimestamp);
jsonVal["content"] = jsBody; jsonVal["content"] = jsBody;
return show_value_.write(jsonVal); return show_value_.write(jsonVal);
} }
@ -352,7 +356,7 @@ std::string JsonData::JsonCmd_Cgi_56(Param_56 &param) {
jsonVal["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G; jsonVal["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G;
jsonVal["success"] = true; jsonVal["success"] = true;
jsonVal["message"] = ""; jsonVal["message"] = "";
int i = 0; // int i = 0;
std::string strWaveData; std::string strWaveData;
std::string filename = "/opt/data/" + param.mChannelId + ".dat"; std::string filename = "/opt/data/" + param.mChannelId + ".dat";
char localtimestamp[32] = {0}; char localtimestamp[32] = {0};
@ -371,24 +375,24 @@ std::string JsonData::JsonCmd_Cgi_56(Param_56 &param) {
zlog_info(zct,"sensor type %s", res[17].c_str()); zlog_info(zct,"sensor type %s", res[17].c_str());
if (access(filename.c_str(), 0) >= 0) { if (access(filename.c_str(), 0) >= 0) {
std::ifstream inFile(filename.c_str(), ios::in | ios::binary); std::ifstream inFile(filename.c_str(), std::ios::in | std::ios::binary);
if (!inFile) { if (!inFile) {
print_error("read channel data error\n"); zlog_error(zct, "read channel data error, filename:%s", filename.c_str());
jsonVal["success"] = "false"; jsonVal["success"] = "false";
jsonVal["message"] = "error"; jsonVal["message"] = "error";
} else { } else {
float fTemp = 0; float fTemp = 0;
inFile.read((char *)localtimestamp, sizeof(localtimestamp)); inFile.read((char *)localtimestamp, sizeof(localtimestamp));
string::size_type comper = param.mChannelId.find("Z"); std::string::size_type comper = param.mChannelId.find("Z");
if (comper != string::npos && res[17] == "02") { if (comper != std::string::npos && res[17] == "02") {
while (inFile.read((char *)&fTemp, sizeof(fTemp))) { while (inFile.read((char *)&fTemp, sizeof(fTemp))) {
vecWave.push_back(fTemp); vecWave.push_back(fTemp);
} }
//积分 //积分
resolution = (double)SampleRate / vecWave.size(); resolution = (double)SampleRate / vecWave.size();
pCalculation->Integration(vecWave, IntegrationWave, resolution); Calculation::Integration(vecWave, IntegrationWave, resolution);
pCalculation->FFTSpec(IntegrationWave, fftWave); Calculation::FFTSpec(IntegrationWave, fftWave);
sampleRateReference = 1000; sampleRateReference = 1000;
} else { } else {
@ -402,8 +406,8 @@ std::string JsonData::JsonCmd_Cgi_56(Param_56 &param) {
resolution = (((double)SampleRate / 1000) * 1016) / vecWave.size(); resolution = (((double)SampleRate / 1000) * 1016) / vecWave.size();
} else if (res[17] == "02") { } else if (res[17] == "02") {
string::size_type comper = param.mChannelId.find("Z"); std::string::size_type comper = param.mChannelId.find("Z");
if (comper != string::npos) { if (comper != std::string::npos) {
SampleRate = atoi(res[23].c_str()); SampleRate = atoi(res[23].c_str());
resolution = (double)SampleRate / vecWave.size(); resolution = (double)SampleRate / vecWave.size();
@ -420,8 +424,8 @@ std::string JsonData::JsonCmd_Cgi_56(Param_56 &param) {
} }
// 积分 // 积分
pCalculation->Integration(vecWave, IntegrationWave, resolution); Calculation::Integration(vecWave, IntegrationWave, resolution);
pCalculation->FFTSpec(IntegrationWave, fftWave); Calculation::FFTSpec(IntegrationWave, fftWave);
sampleRateReference = 1024; sampleRateReference = 1024;
} }
@ -469,7 +473,7 @@ std::string JsonData::JsonCmd_Cgi_56(Param_56 &param) {
jsBody["channelId"] = param.mChannelId; jsBody["channelId"] = param.mChannelId;
jsBody["package"] = param.mPackageFlag; jsBody["package"] = param.mPackageFlag;
jsBody["timestamp"] = string(localtimestamp); jsBody["timestamp"] = std::string(localtimestamp);
jsBody["Data"] = strWaveData; jsBody["Data"] = strWaveData;
zlog_info(zct,"@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@the sample rate is %d,the resolution %f", SampleRate, resolution); zlog_info(zct,"@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@the sample rate is %d,the resolution %f", SampleRate, resolution);

View File

@ -1,6 +1,11 @@
#include "local_server.hpp" #include "local_server.hpp"
#include <string.h>
#include <zlog.h> #include <zlog.h>
#include <json/json.h> #include <json/json.h>
#include "common/global.hpp"
#include "common/common_func.hpp"
#include "mqttclient/mqtt_client.h"
#include "dbaccess/sql_db.hpp"
#include "utility/secure.hpp" #include "utility/secure.hpp"
#include "jsonparse/communication_cmd.hpp" #include "jsonparse/communication_cmd.hpp"
@ -166,7 +171,7 @@ void LocalServer::HandleFromServer(const char *pData_r, int pLen, const char *to
JsonData jd; JsonData jd;
Param_41 param; Param_41 param;
std::vector<Param_41> param41; std::vector<Param_41> param41;
for (int i = 0; i < recvBody.size(); i++) { for (size_t i = 0; i < recvBody.size(); i++) {
param.mdataNodeNo = recvBody[i]["dataNodeNo"].asString(); param.mdataNodeNo = recvBody[i]["dataNodeNo"].asString();
param.mfeatureInterVal = recvBody[i]["featureInterVal"].asInt(); param.mfeatureInterVal = recvBody[i]["featureInterVal"].asInt();
param.mwaveInterVal = recvBody[i]["waveInterVal"].asInt(); param.mwaveInterVal = recvBody[i]["waveInterVal"].asInt();

View File

@ -1,7 +1,18 @@
#include "local_server.hpp" #include "local_server.hpp"
#include <unistd.h>
#include <boost/lexical_cast.hpp>
#include <json/json.h> #include <json/json.h>
#include <zlog.h> #include <zlog.h>
#include "mqttclient/mqtt_client.h"
#include "common/global.hpp"
#include "common/parameter_defination.hpp"
#include "dbaccess/sql_db.hpp"
#include "common/common_func.hpp"
#include "jsonparse/communication_cmd.hpp"
extern zlog_category_t *zct;
std::string LocalServer::HandleCgi_cmd(std::string &pData) { std::string LocalServer::HandleCgi_cmd(std::string &pData) {
try { try {
zlog_info(zct,"HandleCgi Data = %s ", pData.c_str()); zlog_info(zct,"HandleCgi Data = %s ", pData.c_str());
@ -228,7 +239,7 @@ std::string LocalServer::HandleCgi_cmd(std::string &pData) {
JsonData jd; JsonData jd;
Param_41 param; Param_41 param;
std::vector<Param_41> param41; std::vector<Param_41> param41;
for (int i = 0; i < recvBody.size(); i++) { for (size_t i = 0; i < recvBody.size(); i++) {
param.mdataNodeNo = recvBody[i]["dataNodeNo"].asString(); param.mdataNodeNo = recvBody[i]["dataNodeNo"].asString();
param.mfeatureInterVal = recvBody[i]["featureInterVal"].asInt(); param.mfeatureInterVal = recvBody[i]["featureInterVal"].asInt();
param.mwaveInterVal = recvBody[i]["waveInterVal"].asInt(); param.mwaveInterVal = recvBody[i]["waveInterVal"].asInt();
@ -306,7 +317,7 @@ std::string LocalServer::HandleCgi_cmd(std::string &pData) {
JsonData jd; JsonData jd;
Param_53 param; Param_53 param;
std::vector<Param_53> param53; std::vector<Param_53> param53;
for (int i = 0; i < recvBody.size(); i++) { for (size_t i = 0; i < recvBody.size(); i++) {
param.mdataNodeNo = recvBody[i]["dataNodeNo"].asString(); param.mdataNodeNo = recvBody[i]["dataNodeNo"].asString();
param.mUpdateKey = recvBody[i]["updateKey"].asString(); param.mUpdateKey = recvBody[i]["updateKey"].asString();
param.mUpdateValue = recvBody[i]["updateValue"].asString(); param.mUpdateValue = recvBody[i]["updateValue"].asString();
@ -319,7 +330,7 @@ std::string LocalServer::HandleCgi_cmd(std::string &pData) {
std::string data = jd.JsonCmd_Cgi_53(param53); std::string data = jd.JsonCmd_Cgi_53(param53);
char whereCon[64] = {0}; char whereCon[64] = {0};
sprintf(whereCon, "UpdateFlag <> 0 "); sprintf(whereCon, "UpdateFlag <> 0 ");
string strData = sqlite_db_ctrl::instance().GetNodeConfigureInfor(whereCon); std::string strData = sqlite_db_ctrl::instance().GetNodeConfigureInfor(whereCon);
data_publish(strData.c_str(), GlobalConfig::Topic_G.mPubConfig.c_str()); data_publish(strData.c_str(), GlobalConfig::Topic_G.mPubConfig.c_str());
return data; return data;
} break; } break;
@ -376,4 +387,6 @@ std::string LocalServer::HandleCgi_cmd(std::string &pData) {
Json::FastWriter fw; Json::FastWriter fw;
return fw.write(jsVal); return fw.write(jsVal);
} }
zlog_error(zct, "invalid command");
return "";
} }

View File

@ -17,6 +17,7 @@
#include "utility/aes.h" #include "utility/aes.h"
#include "dbaccess/sql_db.hpp" #include "dbaccess/sql_db.hpp"
#include "uart/uart.hpp" #include "uart/uart.hpp"
#include "minilzo/minilzo.h"
extern std::vector<RecvData> g_VecWaveDataX; extern std::vector<RecvData> g_VecWaveDataX;
extern std::vector<RecvData> g_VecWaveDataY; extern std::vector<RecvData> g_VecWaveDataY;
@ -53,7 +54,7 @@ int main(int argc, char *argv[]) {
sqlite_db_ctrl::instance().InintGateway(); sqlite_db_ctrl::instance().InintGateway();
uart_inst::instance().InitZigbee(); uart_inst::instance().InitZigbeeHW();
// UDP接收客户端发来的组播消息用于外接 QT 专家系统,屏蔽之 // UDP接收客户端发来的组播消息用于外接 QT 专家系统,屏蔽之
boost::thread searchT(SearchThread); boost::thread searchT(SearchThread);
searchT.detach(); searchT.detach();
@ -119,7 +120,7 @@ int main(int argc, char *argv[]) {
startTcpCgi.detach(); startTcpCgi.detach();
sleep(5); sleep(5);
uart_inst::instance().ZigbeeInit(); uart_inst::instance().ZigbeeParameterConfig();
sleep(1); sleep(1);
uart_inst::instance().UpdateZigbeeInfoCtrl(); uart_inst::instance().UpdateZigbeeInfoCtrl();

View File

@ -18,6 +18,8 @@
#include "common/global.hpp" #include "common/global.hpp"
#include "utility/secure.hpp" #include "utility/secure.hpp"
extern zlog_category_t *zct;
static char res_topic[100]; static char res_topic[100];
static char req_topic[100]; static char req_topic[100];
struct mosquitto *mosq = NULL; struct mosquitto *mosq = NULL;
@ -47,7 +49,7 @@ int data_publish(const char *str, const char *topic) {
std::string pData = (std::string)str; std::string pData = (std::string)str;
char *base64_aes = new char[pData.length() * 2]; char *base64_aes = new char[pData.length() * 2];
memset(base64_aes, 0, pData.length() * 2); memset(base64_aes, 0, pData.length() * 2);
Secure::instance()->Base64Encode((unsigned char *)pData.c_str(), base64_aes, pData.length()); secure::instance().Base64Encode((unsigned char *)pData.c_str(), base64_aes, pData.length());
iRet = mosquitto_publish(mosq, &mid_sent, topic, strlen(base64_aes), base64_aes, ud.topic_qos, false); iRet = mosquitto_publish(mosq, &mid_sent, topic, strlen(base64_aes), base64_aes, ud.topic_qos, false);
if (base64_aes != NULL) delete[] base64_aes; if (base64_aes != NULL) delete[] base64_aes;
@ -64,7 +66,7 @@ int data_publish(const char *str, const char *topic) {
int data_publish_wave(WAVE_CONTAIN *str, const char *topic) { int data_publish_wave(WAVE_CONTAIN *str, const char *topic) {
int iRet = -1; int iRet = -1;
if (mosq != NULL) { if (mosq != NULL) {
print_blue("data_publish:Unit : %s type:%d flag : %d channelid : %s total : %d count : %d number :%d floats:%f floate:%f\n", str->SensorEngineeringUnit, str->type, str->flag, str->channelId, str->total, str->count, str->number, str->waveData[0], zlog_info(zct, "data_publish:Unit : %s type:%d flag : %d channelid : %s total : %d count : %d number :%d floats:%f floate:%f\n", str->SensorEngineeringUnit, str->type, str->flag, str->channelId, str->total, str->count, str->number, str->waveData[0],
str->waveData[(str->number - 2)]); str->waveData[(str->number - 2)]);
iRet = mosquitto_publish(mosq, &mid_sent, topic, sizeof(WAVE_CONTAIN), str, ud.topic_qos, false); iRet = mosquitto_publish(mosq, &mid_sent, topic, sizeof(WAVE_CONTAIN), str, ud.topic_qos, false);
} }
@ -95,29 +97,24 @@ int start_client(const char *boardname, const char *gwid, const char *gwip, cons
bool debug = true; bool debug = true;
int rc = 0; int rc = 0;
char hostname[256]; char hostname[256];
char err[1024];
int len; int len;
char will_payload[100]; char will_payload[100];
long will_payloadlen = 0; long will_payloadlen = 0;
int will_qos = 0; int will_qos = 0;
bool will_retain = false; bool will_retain = false;
char *will_topic = NULL; char *will_topic = NULL;
bool insecure = false;
char *tls_version = NULL;
char *psk = NULL; char *psk = NULL;
char *psk_identity = NULL; char *psk_identity = NULL;
char *ciphers = NULL;
bool use_srv = false; bool use_srv = false;
mqttsdata_t mqttsdata; mqttsdata_t mqttsdata;
signal(SIGCHLD, SIG_IGN); // signal函数作用为一个信号注册一个信号处理函数。其中SIGCHLD在一个进程终止或者停止时将SIGCHLD信号发送给父进程。而信号处理函数是一个函数指针不过它使用的是预定义函数SIG_IGN(忽视信号) signal(SIGCHLD, SIG_IGN); // signal函数作用为一个信号注册一个信号处理函数。其中SIGCHLD在一个进程终止或者停止时将SIGCHLD信号发送给父进程。而信号处理函数是一个函数指针不过它使用的是预定义函数SIG_IGN(忽视信号)
signal(SIGPIPE, SIG_IGN); signal(SIGPIPE, SIG_IGN);
int reconnect = 0;
if (my_connect_callback == NULL || my_message_callback == NULL || my_subscribe_callback == NULL || my_log_callback == NULL) { if (my_connect_callback == NULL || my_message_callback == NULL || my_subscribe_callback == NULL || my_log_callback == NULL) {
zlog_error(zct,"please call the register_collback function first."); zlog_error(zct,"please call the register_collback function first.");
return -1; return -1;
} }
int qos = readIntValue("config", "qos", (char *)GlobalConfig::Config_G.c_str()); int qos = readIntValue("config", (char*)std::string("qos").c_str(), (char *)GlobalConfig::Config_G.c_str());
mosquitto_lib_init(); //使用mosquitto库函数前需进行初始化 mosquitto_lib_init(); //使用mosquitto库函数前需进行初始化
memset(&mqttsdata, 0, sizeof(mqttsdata_t)); memset(&mqttsdata, 0, sizeof(mqttsdata_t));
memcpy(mqttsdata.gwid, gwid, strlen(gwid)); memcpy(mqttsdata.gwid, gwid, strlen(gwid));
@ -186,7 +183,7 @@ int start_client(const char *boardname, const char *gwid, const char *gwip, cons
zlog_error(zct, "Error: You must specify a topic to subscribe to."); zlog_error(zct, "Error: You must specify a topic to subscribe to.");
return 1; return 1;
} }
if (will_payload && !will_topic) { if (!will_topic) {
zlog_error(zct, "Error: Will payload given, but no will topic given."); zlog_error(zct, "Error: Will payload given, but no will topic given.");
return 1; return 1;
} }
@ -248,14 +245,14 @@ int start_client(const char *boardname, const char *gwid, const char *gwip, cons
if (!psk) { if (!psk) {
psk = (char *)malloc(32 * sizeof(char)); psk = (char *)malloc(32 * sizeof(char));
if (!psk) { if (!psk) {
zlog_error(zct, "Error: No free space %d", __LINE__); zlog_error(zct, "Error: No free space 1");
return -1; return -1;
} }
memset(psk, 0, 32); memset(psk, 0, 32);
snprintf(psk, 32, "%ld", getpid()); snprintf(psk, 32, "%d", getpid());
psk_identity = (char *)malloc(32 * sizeof(char)); psk_identity = (char *)malloc(32 * sizeof(char));
if (!psk_identity) { if (!psk_identity) {
zlog_error(zct, "Error: No free space %d", __LINE__); zlog_error(zct, "Error: No free space 2");
free(psk); free(psk);
return -1; return -1;
} }
@ -318,4 +315,5 @@ mosq_free:
id = NULL; id = NULL;
mosq = NULL; mosq = NULL;
sleep(1); sleep(1);
return 0;
} }

View File

@ -1,6 +1,7 @@
#include "platform_init.hpp" #include "platform_init.hpp"
#include <zlog.h> #include <zlog.h>
#include <fstream> #include <fstream>
#include <json/json.h>
#include "common/global.hpp" #include "common/global.hpp"
#include "dbaccess/sql_db.hpp" #include "dbaccess/sql_db.hpp"
@ -53,14 +54,14 @@ void PlatformInit::Init() {
transform(GlobalConfig::MacAddr_G2.begin(), GlobalConfig::MacAddr_G2.end(), GlobalConfig::MacAddr_G2.begin(), ::toupper); transform(GlobalConfig::MacAddr_G2.begin(), GlobalConfig::MacAddr_G2.end(), GlobalConfig::MacAddr_G2.begin(), ::toupper);
GlobalConfig::IpAddr_G = IpAddrInit(); GlobalConfig::IpAddr_G = IpAddrInit();
zlog_info(zbt, "GlobalConfig::IpAddr_G : %s", GlobalConfig::IpAddr_G.c_str()); zlog_info(zbt, "GlobalConfig::IpAddr_G : %s", GlobalConfig::IpAddr_G.c_str());
this->ConfigFileCheck(); ConfigFileCheck();
zlog_info(zbt, "ConfigFileCheck"); zlog_info(zbt, "ConfigFileCheck");
this->TopicInit(); TopicInit();
zlog_info(zbt, "TopicInit"); zlog_info(zbt, "TopicInit");
this->ServerIpInit(); ServerIpInit();
zlog_info(zbt, "TopicInit"); zlog_info(zbt, "TopicInit");
this->Sqlite3Init(); Sqlite3Init();
this->GPIOInit(); GPIOInit();
zlog_info(zbt, "ServerIP : %s ", GlobalConfig::ServerIP.c_str()); zlog_info(zbt, "ServerIP : %s ", GlobalConfig::ServerIP.c_str());
std::string strMac = sqlite_db_ctrl::instance().GetData("t_gateway_info", "gatewayMAC", NULL); std::string strMac = sqlite_db_ctrl::instance().GetData("t_gateway_info", "gatewayMAC", NULL);
@ -157,11 +158,11 @@ int PlatformInit::ServerIpInit() {
GlobalConfig::ServerIP = ReadStrByOpt(SERVERCONFIG, "Server", "localServerIpAddress"); GlobalConfig::ServerIP = ReadStrByOpt(SERVERCONFIG, "Server", "localServerIpAddress");
GlobalConfig::ServerPort = atoi(ReadStrByOpt(SERVERCONFIG, "Server", "localServerPort").c_str()); GlobalConfig::ServerPort = atoi(ReadStrByOpt(SERVERCONFIG, "Server", "localServerPort").c_str());
} }
return 0;
} }
void PlatformInit::Sqlite3Init() { void PlatformInit::Sqlite3Init() {
sqlite_db_ctrl::instance().OpenDB(GlobalConfig::DbName_G.c_str()); sqlite_db_ctrl::instance().OpenDB(GlobalConfig::DbName_G.c_str());
char szValue[10] = {0x00};
int nType = readIntValue("Update", "type", (char*)GlobalConfig::Config_G.c_str()); int nType = readIntValue("Update", "type", (char*)GlobalConfig::Config_G.c_str());
if (nType == 1) { if (nType == 1) {
sqlite_db_ctrl::instance().SqliteInitDel(GlobalConfig::DbName_G.c_str()); sqlite_db_ctrl::instance().SqliteInitDel(GlobalConfig::DbName_G.c_str());
@ -186,7 +187,8 @@ void PlatformInit::GPIOInit() {
GlobalConfig::GPIO_G.runLed = 409; GlobalConfig::GPIO_G.runLed = 409;
GlobalConfig::GPIO_G.errorLed = 410; GlobalConfig::GPIO_G.errorLed = 410;
GlobalConfig::GPIO_G.netResetNet0 = 489; GlobalConfig::GPIO_G.netResetNet0 = 489;
#else if IMX6UL_GATEWAY #endif
#ifdef IMX6UL_GATEWAY
GlobalConfig::GPIO_G.zigAckrep = 119; GlobalConfig::GPIO_G.zigAckrep = 119;
GlobalConfig::GPIO_G.zigAckreset = 120; GlobalConfig::GPIO_G.zigAckreset = 120;
GlobalConfig::GPIO_G.zigReset = 116; GlobalConfig::GPIO_G.zigReset = 116;
@ -238,7 +240,6 @@ void PlatformInit::UserInit() {
void PlatformInit::EquipIpInit(std::string eth) { void PlatformInit::EquipIpInit(std::string eth) {
// eth0 初始化 // eth0 初始化
int flag = 0;
std::string networkPortStatus = ReadStrByOpt(NETWORKCONFIG, eth, "networkPortStatus"); std::string networkPortStatus = ReadStrByOpt(NETWORKCONFIG, eth, "networkPortStatus");
std::string subnetMask = ReadStrByOpt(NETWORKCONFIG, eth, "subnetMask"); std::string subnetMask = ReadStrByOpt(NETWORKCONFIG, eth, "subnetMask");
std::string gateway = ReadStrByOpt(NETWORKCONFIG, eth, "gateway"); std::string gateway = ReadStrByOpt(NETWORKCONFIG, eth, "gateway");
@ -267,7 +268,7 @@ void PlatformInit::EquipIpInit(std::string eth) {
system("sed -i '7c ' /etc/systemd/network/dynamic/20-eth1-dynamic.network"); system("sed -i '7c ' /etc/systemd/network/dynamic/20-eth1-dynamic.network");
} }
#endif #endif
flag = 0; // flag = 0;
} }
if (0 == networkPortStatus.compare("STATIC")) { if (0 == networkPortStatus.compare("STATIC")) {
std::string cmd = ""; std::string cmd = "";
@ -314,7 +315,7 @@ void PlatformInit::EquipIpInit(std::string eth) {
system(cmd.c_str()); system(cmd.c_str());
} }
#endif #endif
flag = 1; // flag = 1;
} }
#ifdef IMX6UL_GATEWAY #ifdef IMX6UL_GATEWAY

View File

@ -59,7 +59,7 @@ private:
* @brief mqtt主题初始化 * @brief mqtt主题初始化
* @return void * @return void
*/ */
void TopicInit(); static void TopicInit();
}; };

View File

@ -29,15 +29,11 @@ void CheckThread() {
int HardStatus = 0; int HardStatus = 0;
int logClean = 0; int logClean = 0;
int Battery = 0; int Battery = 0;
int UpdateZigbee = 0;
int commSignal = 0; int commSignal = 0;
int loose_check = 0; int loose_check = 0;
int mqttresend = 0; int mqttresend = 0;
int rebootsystem = 0;
int ModifyAddr = 0; int ModifyAddr = 0;
int wifi_reconnect_count = 0;
int checkNet0 = 0; int checkNet0 = 0;
int connectCount = 0;
while (GlobalConfig::QuitFlag_G) { while (GlobalConfig::QuitFlag_G) {
GlobalConfig::threadStatus = 1; GlobalConfig::threadStatus = 1;
@ -186,8 +182,6 @@ void CheckThread() {
} }
#endif #endif
#endif #endif
} else {
connectCount = 0;
} }
} }
if (HardStatus == 3600) { // one hour 3600 if (HardStatus == 3600) { // one hour 3600
@ -229,7 +223,7 @@ void CheckThread() {
jd.DataNodeStatusCheck(); jd.DataNodeStatusCheck();
Param_29 param; Param_29 param;
std::string cmd29 = jd.JsonCmd_29(param); std::string cmd29 = jd.JsonCmd_29(param);
int iRet = data_publish(cmd29.c_str(), GlobalConfig::Topic_G.mPubCmd.c_str()); data_publish(cmd29.c_str(), GlobalConfig::Topic_G.mPubCmd.c_str());
char localtimestamp[32] = {0}; char localtimestamp[32] = {0};
GetTimeNet(localtimestamp, 1); GetTimeNet(localtimestamp, 1);
std::string nowTimetamp = std::string(localtimestamp); std::string nowTimetamp = std::string(localtimestamp);
@ -238,9 +232,9 @@ void CheckThread() {
sleep(1); sleep(1);
std::string strTime = sqlite_db_ctrl::instance().GetData(T_DATASTATIC_INFO(TNAME), "timeStamp", selectCon); std::string strTime = sqlite_db_ctrl::instance().GetData(T_DATASTATIC_INFO(TNAME), "timeStamp", selectCon);
long lTime = atol(nowTimetamp.c_str()) - atol(strTime.c_str()); long lTime = atol(nowTimetamp.c_str()) - atol(strTime.c_str());
zlog_info(zct, "online check = %d", lTime); zlog_info(zct, "online check = %ld", lTime);
if (lTime > 1800) { if (lTime > 1800) {
zlog_error(zct, "nowTimetamp = %s,lastTime = %s,lTime = %d", nowTimetamp.c_str(), strTime.c_str(), lTime); zlog_error(zct, "nowTimetamp = %s,lastTime = %s,lTime = %ld", nowTimetamp.c_str(), strTime.c_str(), lTime);
} }
} }
} }

View File

@ -477,7 +477,7 @@ void RecvUpdateFile() {
acceptor.accept(socket); acceptor.accept(socket);
boost::system::error_code ec; boost::system::error_code ec;
if (ec) { if (ec) {
zlog_error("%s\n", boost::system::system_error(ec).what()); zlog_error(zct, "%s\n", boost::system::system_error(ec).what());
} }
FILE *fp; FILE *fp;
char buffer[1024]; char buffer[1024];
@ -489,11 +489,7 @@ void RecvUpdateFile() {
zlog_info(zct,"File:\t Can Not Open To Write"); zlog_info(zct,"File:\t Can Not Open To Write");
exit(1); exit(1);
} }
while (len = socket.read_some(boost::asio::buffer(buffer), ec)) { while ((len = socket.read_some(boost::asio::buffer(buffer), ec))) {
if (len < 0) {
zlog_info(zct,"Receive Data From Server Failed!");
break;
}
write_len = fwrite(buffer, sizeof(char), len, fp); write_len = fwrite(buffer, sizeof(char), len, fp);
if (write_len < len) { if (write_len < len) {
zlog_info(zct, "File:test Write Failed!"); zlog_info(zct, "File:test Write Failed!");

View File

@ -10,7 +10,7 @@
#include <boost/lexical_cast.hpp> #include <boost/lexical_cast.hpp>
#include <boost/algorithm/string.hpp> #include <boost/algorithm/string.hpp>
#include <boost/bind.hpp> #include <boost/bind.hpp>
#include <boost/timer.hpp> #include <boost/timer/timer.hpp>
#include <boost/date_time/posix_time/posix_time.hpp> #include <boost/date_time/posix_time/posix_time.hpp>
#include <zlog.h> #include <zlog.h>
#include <json/json.h> #include <json/json.h>
@ -1097,7 +1097,7 @@ int Uart::FindRecvPackage(int bytesRead, char *mUartRecvBuf, char *head) {
Json::Value jsBody, jsonVal; Json::Value jsBody, jsonVal;
Json::FastWriter showValue; Json::FastWriter showValue;
char looseValue[10] = {0x00}; char looseValue[10] = {0x00};
readStringValue("config", (char*)"loose", looseValue, GlobalConfig::Config_G.c_str()); readStringValue("config", (char *)"loose", looseValue, GlobalConfig::Config_G.c_str());
if (atof(looseValue) < atof(vecDataNodeNo[1].c_str())) { if (atof(looseValue) < atof(vecDataNodeNo[1].c_str())) {
jsBody["looseStatus"] = "1"; jsBody["looseStatus"] = "1";
} else { } else {
@ -1127,3 +1127,13 @@ int Uart::FindRecvPackage(int bytesRead, char *mUartRecvBuf, char *head) {
} }
return 0; return 0;
} }
bool Uart::CheckCrc(char *pCheckBuff, int No) {
unsigned char tmp = 0x00;
for (int i = 0; i < No; i++) {
tmp += (unsigned char)pCheckBuff[i];
}
if ((unsigned char)pCheckBuff[No] != (unsigned char)tmp) return false;
return true;
}

View File

@ -29,14 +29,6 @@ void Uart::openSwitch() {
close(fdSwitch); close(fdSwitch);
} }
void int2bytes(int i, unsigned char* bytes, int size) {
memset(bytes, 0, sizeof(unsigned char) * size);
bytes[0] = (unsigned char)(0xff & i);
bytes[1] = (unsigned char)((0xff00 & i) >> 8);
bytes[2] = (unsigned char)((0xff0000 & i) >> 16);
bytes[3] = (unsigned char)((0xff000000 & i) >> 24);
}
bool Uart::ReadUpdatePackge(unsigned char* pDestShortAddr) { bool Uart::ReadUpdatePackge(unsigned char* pDestShortAddr) {
// compare hardversion in update list // compare hardversion in update list
std::vector<std::string> strHWversion; std::vector<std::string> strHWversion;
@ -265,7 +257,6 @@ int Uart::UpdateConfig(unsigned char* pDestShortAddr) {
if (vecResultNode[41] == "0") { if (vecResultNode[41] == "0") {
zlog_info(zct, "UpdateConfig"); zlog_info(zct, "UpdateConfig");
bUpdateconfig = true; bUpdateconfig = true;
unsigned short localAddr = 0x9999;
GlobalConfig::EnterZigBeeWaveTransmittingFlag_G = ENTER_TRANSMITTING_STATUS; GlobalConfig::EnterZigBeeWaveTransmittingFlag_G = ENTER_TRANSMITTING_STATUS;
GlobalConfig::EnterZigBeeWaveTransmittingCnt_G = 0; GlobalConfig::EnterZigBeeWaveTransmittingCnt_G = 0;
@ -438,7 +429,6 @@ int Uart::UpdateConfig(unsigned char* pDestShortAddr) {
return 0; return 0;
} else if (vecResultNode[41] == "-1") { } else if (vecResultNode[41] == "-1") {
bUpdateconfig = true; bUpdateconfig = true;
unsigned short localAddr = 0x9999;
GlobalConfig::EnterZigBeeWaveTransmittingFlag_G = ENTER_TRANSMITTING_STATUS; GlobalConfig::EnterZigBeeWaveTransmittingFlag_G = ENTER_TRANSMITTING_STATUS;
GlobalConfig::EnterZigBeeWaveTransmittingCnt_G = 0; GlobalConfig::EnterZigBeeWaveTransmittingCnt_G = 0;
std::string strName = sqlite_db_ctrl::instance().GetData(T_SENSOR_INFO(TNAME), " dataNodeName ", whereCon); std::string strName = sqlite_db_ctrl::instance().GetData(T_SENSOR_INFO(TNAME), " dataNodeName ", whereCon);

View File

@ -74,14 +74,14 @@ void Calculation::_FFT(std::vector<float> &vecData, std::vector<float> &vecFFTre
inHilFFt = (fftw_complex *)fftw_malloc(sizeof(fftw_complex) * vecData.size()); inHilFFt = (fftw_complex *)fftw_malloc(sizeof(fftw_complex) * vecData.size());
outHilFFt = (fftw_complex *)fftw_malloc(sizeof(fftw_complex) * vecData.size()); outHilFFt = (fftw_complex *)fftw_malloc(sizeof(fftw_complex) * vecData.size());
for (int j = 0; j < vecData.size(); j++) { for (size_t j = 0; j < vecData.size(); j++) {
inHilFFt[j][0] = (double)vecData[j]; inHilFFt[j][0] = (double)vecData[j];
inHilFFt[j][1] = 0; inHilFFt[j][1] = 0;
} }
FFT(vecData.size(), inHilFFt, outHilFFt); FFT(vecData.size(), inHilFFt, outHilFFt);
// fftShift(outHilFFt, vecData.size()); // fftShift(outHilFFt, vecData.size());
for (int i = 0; i < vecData.size(); i++) { for (size_t i = 0; i < vecData.size(); i++) {
vecFFTrealData.push_back(outHilFFt[i][0]); vecFFTrealData.push_back(outHilFFt[i][0]);
vecFFTimageData.push_back(outHilFFt[i][1]); vecFFTimageData.push_back(outHilFFt[i][1]);
} }
@ -128,23 +128,23 @@ float Calculation::min(std::vector<float> &vecData) {
} }
void Calculation::absVec(std::vector<float> &vecAbsData, std::vector<float> &vecData) { void Calculation::absVec(std::vector<float> &vecAbsData, std::vector<float> &vecData) {
for (int i = 0; i < vecData.size(); i++) { for (size_t i = 0; i < vecData.size(); i++) {
vecAbsData.push_back(fabs(vecData[i])); vecAbsData.push_back(fabs(vecData[i]));
} }
return; return;
} }
float Calculation::mean(std::vector<float> &vecData) { float Calculation::mean(std::vector<float> &vecData) {
double meanTemp = 0; float meanTemp = 0;
for (int i = 0; i < vecData.size(); i++) { for (size_t i = 0; i < vecData.size(); i++) {
meanTemp = meanTemp += vecData[i]; meanTemp += vecData[i];
} }
return meanTemp / vecData.size(); return meanTemp / vecData.size();
} }
void Calculation::drop_mean(std::vector<float> &vecDropMeanData, std::vector<float> &vecData) { void Calculation::drop_mean(std::vector<float> &vecDropMeanData, std::vector<float> &vecData) {
float fMean = mean(vecData); float fMean = mean(vecData);
for (int i = 0; i < vecData.size(); i++) { for (size_t i = 0; i < vecData.size(); i++) {
vecDropMeanData.push_back(vecData[i] - fMean); vecDropMeanData.push_back(vecData[i] - fMean);
} }
return; return;
@ -152,7 +152,7 @@ void Calculation::drop_mean(std::vector<float> &vecDropMeanData, std::vector<flo
float Calculation::srm(std::vector<float> &vecData) { float Calculation::srm(std::vector<float> &vecData) {
double dSrmTemp = 0; double dSrmTemp = 0;
for (int i = 0; i < vecData.size(); i++) { for (size_t i = 0; i < vecData.size(); i++) {
dSrmTemp = dSrmTemp + sqrt(vecData[i]); dSrmTemp = dSrmTemp + sqrt(vecData[i]);
} }
dSrmTemp = dSrmTemp / vecData.size(); dSrmTemp = dSrmTemp / vecData.size();
@ -160,9 +160,9 @@ float Calculation::srm(std::vector<float> &vecData) {
} }
float Calculation::rms(std::vector<float> &vecData) { float Calculation::rms(std::vector<float> &vecData) {
double rmsTemp = 0; float rmsTemp = 0;
for (int i = 0; i < vecData.size(); i++) { for (size_t i = 0; i < vecData.size(); i++) {
rmsTemp = rmsTemp += (vecData[i] * vecData[i]); rmsTemp += (vecData[i] * vecData[i]);
} }
rmsTemp = rmsTemp / vecData.size(); rmsTemp = rmsTemp / vecData.size();
return sqrt(rmsTemp); return sqrt(rmsTemp);
@ -181,16 +181,16 @@ float Calculation::getSample_variance(std::vector<float> a) {
} }
float Calculation::variance(std::vector<float> &vecDropMeanData) { float Calculation::variance(std::vector<float> &vecDropMeanData) {
double varianceTemp = 0; float varianceTemp = 0;
for (int i = 0; i < vecDropMeanData.size(); i++) { for (size_t i = 0; i < vecDropMeanData.size(); i++) {
varianceTemp = varianceTemp += (vecDropMeanData[i] * vecDropMeanData[i]); varianceTemp += (vecDropMeanData[i] * vecDropMeanData[i]);
} }
return varianceTemp / vecDropMeanData.size(); return varianceTemp / vecDropMeanData.size();
} }
float Calculation::skew_state(std::vector<float> &vecDropMeanData, float fVariance) { float Calculation::skew_state(std::vector<float> &vecDropMeanData, float fVariance) {
double tempSkew = 0; float tempSkew = 0;
for (int i = 0; i < vecDropMeanData.size(); i++) { for (size_t i = 0; i < vecDropMeanData.size(); i++) {
tempSkew = tempSkew + pow(vecDropMeanData[i], 3); tempSkew = tempSkew + pow(vecDropMeanData[i], 3);
} }
tempSkew = tempSkew / vecDropMeanData.size(); tempSkew = tempSkew / vecDropMeanData.size();
@ -199,8 +199,8 @@ float Calculation::skew_state(std::vector<float> &vecDropMeanData, float fVarian
} }
float Calculation::kurtosis(std::vector<float> &vecDropMeanData, float fVariance) { float Calculation::kurtosis(std::vector<float> &vecDropMeanData, float fVariance) {
double tempkurtosis = 0; float tempkurtosis = 0;
for (int i = 0; i < vecDropMeanData.size(); i++) { for (size_t i = 0; i < vecDropMeanData.size(); i++) {
tempkurtosis = tempkurtosis + pow(vecDropMeanData[i], 4); tempkurtosis = tempkurtosis + pow(vecDropMeanData[i], 4);
} }
tempkurtosis = tempkurtosis / vecDropMeanData.size(); tempkurtosis = tempkurtosis / vecDropMeanData.size();
@ -321,12 +321,12 @@ void Calculation::FFTSpec(std::vector<float> &vecData, std::vector<float> &vecFF
inFFt = (fftw_complex *)fftw_malloc(sizeof(fftw_complex) * vecData.size()); inFFt = (fftw_complex *)fftw_malloc(sizeof(fftw_complex) * vecData.size());
outFFt = (fftw_complex *)fftw_malloc(sizeof(fftw_complex) * vecData.size()); outFFt = (fftw_complex *)fftw_malloc(sizeof(fftw_complex) * vecData.size());
for (int j = 0; j < vecData.size(); j++) { for (size_t j = 0; j < vecData.size(); j++) {
inFFt[j][0] = (double)vecData[j]; inFFt[j][0] = (double)vecData[j];
inFFt[j][1] = 0; inFFt[j][1] = 0;
} }
FFT(vecData.size(), inFFt, outFFt); FFT(vecData.size(), inFFt, outFFt);
for (int j = 0; j < vecData.size() / 2; j++) { for (size_t j = 0; j < vecData.size() / 2; j++) {
vecFFTSpecData.push_back(sqrt(outFFt[j][0] * outFFt[j][0] + outFFt[j][1] * outFFt[j][1]) * 2 / vecData.size()); vecFFTSpecData.push_back(sqrt(outFFt[j][0] * outFFt[j][0] + outFFt[j][1] * outFFt[j][1]) * 2 / vecData.size());
} }
} }
@ -338,8 +338,8 @@ void Calculation::envSpec(std::vector<float> &vecData, std::vector<float> &vecEn
std::vector<float> veciFFtData2; std::vector<float> veciFFtData2;
std::vector<float> vecHilbertData; std::vector<float> vecHilbertData;
_FFT(vecData, vecFFTrealData, vecFFTimageData); _FFT(vecData, vecFFTrealData, vecFFTimageData);
for (int i = 0; i < vecFFTrealData.size(); i++) { for (size_t i = 0; i < vecFFTrealData.size(); i++) {
if (i > StartFrequency && i < EndFrequency) { if (i > (size_t)StartFrequency && i < (size_t)EndFrequency) {
vecRealData.push_back(vecFFTrealData.at(i)); vecRealData.push_back(vecFFTrealData.at(i));
vecImageData.push_back(vecFFTimageData.at(i)); vecImageData.push_back(vecFFTimageData.at(i));
} else { } else {
@ -348,7 +348,7 @@ void Calculation::envSpec(std::vector<float> &vecData, std::vector<float> &vecEn
} }
} }
_iFFT(vecRealData, vecImageData, veciFFtData); _iFFT(vecRealData, vecImageData, veciFFtData);
for (int j = 0; j < veciFFtData.size(); j++) { for (size_t j = 0; j < veciFFtData.size(); j++) {
veciFFtData2.push_back(veciFFtData[j] * 2); veciFFtData2.push_back(veciFFtData[j] * 2);
} }
hilbert(veciFFtData2, vecHilbertData, veciFFtData2.size()); hilbert(veciFFtData2, vecHilbertData, veciFFtData2.size());
@ -374,7 +374,7 @@ void Calculation::Integration(std::vector<float> &vecData, std::vector<float> &r
_FFT(vecData, realshiftfft, imageshiftfft); _FFT(vecData, realshiftfft, imageshiftfft);
//在频域上进行5-1000 Hz的带通滤波 //在频域上进行5-1000 Hz的带通滤波
for (int i = 0; i < vecData.size() / 2 + 1; ++i) { for (size_t i = 0; i < vecData.size() / 2 + 1; ++i) {
double frequency = i * resolution; // 计算当前频率分量 double frequency = i * resolution; // 计算当前频率分量
if (frequency < 5 || frequency > 1000) { if (frequency < 5 || frequency > 1000) {
// 将5 Hz 到 1000 Hz 之外的频率成分设置为0 // 将5 Hz 到 1000 Hz 之外的频率成分设置为0
@ -385,7 +385,7 @@ void Calculation::Integration(std::vector<float> &vecData, std::vector<float> &r
} }
} }
for (int k = 1; k < realshiftfft.size() + 1; k++) { for (size_t k = 1; k < realshiftfft.size() + 1; k++) {
double frequency = k * resolution; // 计算当前频率分量 double frequency = k * resolution; // 计算当前频率分量
realvalue.push_back((realshiftfft.at(k - 1) / (frequency * 2 * M_PI)) * 1000 * 2); //单位转换mm/s,*1000 *2 精度损失 realvalue.push_back((realshiftfft.at(k - 1) / (frequency * 2 * M_PI)) * 1000 * 2); //单位转换mm/s,*1000 *2 精度损失
imagevalue.push_back((imageshiftfft.at(k - 1) / (frequency * 2 * M_PI)) * 1000 * 2); //单位转换mm/s,*1000 imagevalue.push_back((imageshiftfft.at(k - 1) / (frequency * 2 * M_PI)) * 1000 * 2); //单位转换mm/s,*1000

View File

@ -41,79 +41,6 @@
#define CMSPAR 010000000000 #define CMSPAR 010000000000
#endif #endif
/*
* convert baud_rate to speed_t
*/
static speed_t get_speed(unsigned int baud_rate) {
switch (baud_rate) {
case 0:
return B0;
case 50:
return B50;
case 75:
return B75;
case 110:
return B110;
case 150:
return B150;
case 200:
return B200;
case 300:
return B300;
case 600:
return B600;
case 1200:
return B1200;
case 1800:
return B1800;
case 2400:
return B2400;
case 4800:
return B4800;
case 9600:
return B9600;
case 19200:
return B19200;
case 38400:
return B38400;
case 57600:
return B57600;
case 115200:
return B115200;
case 230400:
return B230400;
case 460800:
return B460800;
case 500000:
return B500000;
case 576000:
return B576000;
case 921600:
return B921600;
case 1000000:
return B1000000;
case 1152000:
return B1152000;
case 1500000:
return B1500000;
case 2000000:
return B2000000;
case 2500000:
return B2500000;
case 3000000:
return B3000000;
case 3500000:
return B3500000;
case 4000000:
return B4000000;
default:
//unsupported baud rate
return 0;
}
}
/** /**
* set baud rate of serial port * set baud rate of serial port
* *
@ -125,7 +52,6 @@ static speed_t get_speed(unsigned int baud_rate) {
*/ */
int serial_set_baud_rate(int file_descriptor, int baud_rate) { int serial_set_baud_rate(int file_descriptor, int baud_rate) {
int iFd = file_descriptor; int iFd = file_descriptor;
int len,ret;
struct termios opt; struct termios opt;
tcgetattr(iFd, &opt); tcgetattr(iFd, &opt);
cfsetispeed(&opt, B115200); cfsetispeed(&opt, B115200);
@ -337,9 +263,9 @@ int serial_set_timeout(int file_descriptor, int timeout) {
* return -1 if failed, and errno is set * return -1 if failed, and errno is set
*/ */
int serial_open(char* port, int baud_rate) { int serial_open(char* port, int baud_rate) {
char buf[128]; // char buf[128];
//
snprintf(buf, sizeof(buf), "/dev/ttyS%d", port); // snprintf(buf, sizeof(buf), "/dev/ttyS%s", port);
return serial_open_file(port, baud_rate); return serial_open_file(port, baud_rate);
} }