#include "communication_cmd.hpp"
#include <zlog.h>
#include <boost/algorithm/string.hpp>
#include "common/global.hpp"
#include "dbaccess/sql_db.hpp"
#include "mqttclient/mqtt_client.h"
#include "datatransfer/data_trans.hpp"
#include "platform/platform_init.hpp"
#include "utility/md5.h"
#include "scheduler/schedule.hpp"

extern zlog_category_t *zct;

// cmd  "20"
const char *JSON_FIELD_CMD = "cmd";                  //协议:    命令字段
const char *JSON_FIELD_NAME = "dataNodeGatewayName"; //协议: 终端名称
const char *JSON_FIELD_dataNodeGatewayNo = "dataNodeGatewayNo";
const char *JSON_FIELD_ASSETID = "dataNodeGatewayAssetId"; //协议:    资产编号  字段
const char *JSON_FIELD_ADDEDBY = "dataNodeGatewayAddedBy"; //协议:    添加人  字段
const char *JSON_FIELD_DEVICETYPE = "deviceType";
const char *JSON_FIELD_ADDEDDATE = "dataNodeGatewayAddedDate";
const char *JSON_FIELD_IPADDRESS = "dataNodeGatewayIpAddress";
const char *JSON_FIELD_SN = "serialNumber";
const char *JSON_FIELD_VERSION = "softVersion";
const char *JSON_FIELD_TIMEZONE = "timezone";

// cmd  "23"
const char *JSON_FIELD_SERVERIP = "localServerIpAddress";
const char *JSON_FIELD_SERVERPORT = "localServerPort";
const char *JSON_FIELD_CommMode = "CommMode";

std::string JsonData::JsonCmd_20(Param_20 &param) {
    Json::Value jsonVal;
    jsonVal.clear();
    jsonVal["success"] = true;
    jsonVal["message"] = "";
    if (0 == param.mMode) {
        char localtimestamp[32] = {0};
        GetTimeNet(localtimestamp, 1);
        std::string nowTimetamp = std::string(localtimestamp);
        WriteStr2Config(SYSTEMINFOFILE, "SystemInfo", "dataNodeGatewayName", param.mDataWatchName);
        WriteStr2Config(SYSTEMINFOFILE, "SystemInfo", "dataNodeGatewayAssetId", param.mDataWatchAssetId);
        WriteStr2Config(SYSTEMINFOFILE, "SystemInfo", "dataNodeGatewayAddedBy", param.mDataWatchAddedBy);
        WriteStr2Config(SYSTEMINFOFILE, "SystemInfo", "dataNodeGatewayAddedDate", nowTimetamp);
    }

    std::string boardtype = GetFileContent(BOARDTYPE, 1);
    std::string ip = IpAddrInit();
    jsonVal[JSON_FIELD_CMD] = "20";
    jsonVal[JSON_FIELD_dataNodeGatewayNo] = GlobalConfig::MacAddr_G;
    jsonVal["cmdSerial"] = param.mCmdSerial;

    Json::Value jsSystemInfo;
    Json::Value jsBody;

    std::string strwebVersion = ReadStrByOpt(SYSTEMINFOFILE, "Version", "WebVersion");
    std::string strsystemVersion = ReadStrByOpt(SYSTEMINFOFILE, "Version", "SystemVersion");
    std::string strGatewayVersion = ReadStrByOpt(SYSTEMINFOFILE, "Version", "GateWayVersion");

    jsSystemInfo["WebVersion"] = strwebVersion;
    jsSystemInfo["SystemVersion"] = strsystemVersion;
    jsSystemInfo["GateWayVersion"] = strGatewayVersion;

    jsSystemInfo[JSON_FIELD_NAME] = ReadStrByOpt(SYSTEMINFOFILE, "SystemInfo", "dataNodeGatewayName");
    jsSystemInfo[JSON_FIELD_dataNodeGatewayNo] = GlobalConfig::MacAddr_G;
    jsSystemInfo[JSON_FIELD_ASSETID] = ReadStrByOpt(SYSTEMINFOFILE, "SystemInfo", "dataNodeGatewayAssetId");
    jsSystemInfo[JSON_FIELD_ADDEDBY] = ReadStrByOpt(SYSTEMINFOFILE, "SystemInfo", "dataNodeGatewayAddedBy");
    jsSystemInfo[JSON_FIELD_ADDEDDATE] = ReadStrByOpt(SYSTEMINFOFILE, "SystemInfo", "dataNodeGatewayAddedDate");
    jsSystemInfo[JSON_FIELD_DEVICETYPE] = boardtype;
    jsSystemInfo[JSON_FIELD_IPADDRESS] = ip;
    jsSystemInfo[JSON_FIELD_VERSION] = GlobalConfig::Version;
    jsSystemInfo[JSON_FIELD_TIMEZONE] = ReadStrByOpt(SYSTEMINFOFILE, "SystemInfo", "timezone");
    jsSystemInfo["zigbeePanId"] = GlobalConfig::ZigbeeInfo_G.PanID;
    jsSystemInfo["zigbeeChannel"] = GlobalConfig::ZigbeeInfo_G.Channel;
    jsSystemInfo["zigbeeAddr"] = GlobalConfig::ZigbeeInfo_G.MyAddr;
    jsSystemInfo[JSON_FIELD_SERVERIP] = ReadStrByOpt(SERVERCONFIG, "Server", "localServerIpAddress");
    jsSystemInfo[JSON_FIELD_SERVERPORT] = atoi(ReadStrByOpt(SERVERCONFIG, "Server", "localServerPort").c_str());
    jsSystemInfo[JSON_FIELD_CommMode] = atoi(ReadStrByOpt(SERVERCONFIG, "Server", "CommMode").c_str());
    jsBody["SystemInfo"] = jsSystemInfo;

    std::string dataBody = show_value_.write(jsBody);
    jsonVal["cmdBody"] = dataBody;
    return show_value_.write(jsonVal);
}

std::string JsonData::JsonCmd_22(Param_22 &param) {
    Json::Value jsonVal;
    jsonVal.clear();
    jsonVal["success"] = true;
    jsonVal["message"] = "";
    if (0 == param.mMode) {
        WriteStr2Config(SYSTEMINFOFILE, "SystemInfo", "timezone", param.mTimeZone);
    }

    jsonVal[JSON_FIELD_CMD] = "22";
    jsonVal[JSON_FIELD_dataNodeGatewayNo] = GlobalConfig::MacAddr_G;
    jsonVal["cmdSerial"] = param.mCmdSerial;

    Json::Value jsSystemSetting;
    Json::Value jsBody;
    jsBody[JSON_FIELD_TIMEZONE] = ReadStrByOpt(SYSTEMINFOFILE, "SystemInfo", "timezone");

    std::string dataBody = show_value_.write(jsBody);
    jsonVal["cmdBody"] = dataBody;

    return show_value_.write(jsonVal);
}

std::string JsonData::JsonCmd_23(Param_23 &param) {
    Json::Value jsonVal;
    jsonVal.clear();
    jsonVal["success"] = true;
    jsonVal["message"] = "";
    if (0 == param.mMode) {
        WriteStr2Config(SERVERCONFIG, "Server", "localServerIpAddress", param.mServerIp);
        WriteStr2Config(SERVERCONFIG, "Server", "localServerPort", param.mPort);
        WriteStr2Config(SERVERCONFIG, "Server", "CommMode", param.mCommMode);
        WriteStr2Config(SERVERCONFIG, "Server", "Password", param.mPassword);
        WriteStr2Config(SERVERCONFIG, "Server", "UserName", param.mUserName);
        zlog_info(zct, "param.mCommMode = %s", param.mCommMode.c_str());
        if ("1" == param.mCommMode) { //有线连接
            system("mv /etc/init.d/S91quectel-CM.sh /etc/init.d/wireless.sh");
            system("mv /etc/init.d/S95check5G /etc/init.d/wireless5G");
        } else if ("2" == param.mCommMode) { //无线连接 4G
            system("mv /etc/init.d/wireless4G /etc/init.d/S91check4G");
            system("mv /etc/init.d/S95check5G /etc/init.d/wireless5G");
        } else if ("3" == param.mCommMode) { //无线连接 5G
            system("mv /etc/init.d/wireless5G /etc/init.d/S95check5G");
            system("mv /etc/init.d/S91check4G /etc/init.d/wireless4G");
        }
        sleep(1);
        system("reboot");
    }

    jsonVal[JSON_FIELD_CMD] = "23";
    jsonVal[JSON_FIELD_dataNodeGatewayNo] = GlobalConfig::MacAddr_G;
    jsonVal["cmdSerial"] = param.mCmdSerial;

    Json::Value jsSystemSetting;
    Json::Value jsBody;

    Json::Value jsHeart;
    Json::FastWriter fw;
    jsHeart["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G;
    jsHeart["status"] = "online_V3.0";
    std::string strJson = fw.write(jsHeart);
    int iRet = data_publish(strJson.c_str(), GlobalConfig::Topic_G.mPubHeart.c_str());
    if (iRet == 0) {
        jsBody["status"] = 0;
    } else {
        jsBody["status"] = -1;
    }

    jsBody[JSON_FIELD_SERVERIP] = ReadStrByOpt(SERVERCONFIG, "Server", "localServerIpAddress");
    jsBody[JSON_FIELD_SERVERPORT] = atoi(ReadStrByOpt(SERVERCONFIG, "Server", "localServerPort").c_str());
    jsBody[JSON_FIELD_CommMode] = atoi(ReadStrByOpt(SERVERCONFIG, "Server", "CommMode").c_str());
    jsBody["Password"] = (ReadStrByOpt(SERVERCONFIG, "Server", "Password"));
    jsBody["UserName"] = (ReadStrByOpt(SERVERCONFIG, "Server", "UserName"));
    std::string dataBody = show_value_.write(jsBody);
    jsonVal["cmdBody"] = dataBody;

    return show_value_.write(jsonVal);
}

std::string JsonData::JsonCmd_25(Param_25 &param) {
    Json::Value jsonVal;
    jsonVal.clear();
    jsonVal["success"] = true;
    jsonVal["message"] = " ";
    jsonVal["cmd"] = "25";
    bool bFlag1 = CheckIP(param.mGateway.c_str());
    bool bFlag2 = IsValidMask(param.mSubnetMask);
    bool bFlag3 = CheckIP(param.mIp.c_str());
    bool bFlag4 = false;
    if (param.mDnsName.size() > 0) {
        bFlag4 = CheckIP(param.mDnsName.c_str());
    } else {
        bFlag4 = true;
    }
    zlog_info(zct, "bFlag1 = %d,bFlag2 = %d,bFlag3 = %d,bFlag4 = %d", bFlag1, bFlag2, bFlag3, bFlag4);

    param.mNet = "Net";

    if (0 == param.mMode && (bFlag1 && bFlag2 && bFlag3 && bFlag4) && param.mNetworkPortStatus == "STATIC") {
        WriteStr2Config(NETWORKCONFIG, param.mNet, "dnsName", param.mDnsName);
        WriteStr2Config(NETWORKCONFIG, param.mNet, "networkPortStatus", param.mNetworkPortStatus);
        WriteStr2Config(NETWORKCONFIG, param.mNet, "gateway", param.mGateway);
        WriteStr2Config(NETWORKCONFIG, param.mNet, "subnetMask", param.mSubnetMask);
        WriteStr2Config(NETWORKCONFIG, param.mNet, "ipAddress", param.mIp);
        WriteStr2Config(NETWORKCONFIG, param.mNet, "hostName", param.mHostName);

        char GateWay[100] = {0x00};
        sprintf(GateWay, "sed -i '7c route add default gw %s' /etc/init.d/S90start_userapp.sh", param.mGateway.c_str());
        system(GateWay);

        PlatformInit::EquipIpInit(param.mNet);

    } else if (0 == param.mMode && param.mNetworkPortStatus == "DHCP") {
        WriteStr2Config(NETWORKCONFIG, param.mNet, "dnsName", "");
        WriteStr2Config(NETWORKCONFIG, param.mNet, "networkPortStatus", param.mNetworkPortStatus);
        WriteStr2Config(NETWORKCONFIG, param.mNet, "gateway", "");
        WriteStr2Config(NETWORKCONFIG, param.mNet, "subnetMask", "");
        WriteStr2Config(NETWORKCONFIG, param.mNet, "ipAddress", "");
        WriteStr2Config(NETWORKCONFIG, param.mNet, "hostName", "");

        system("sed -i '7c udhcpc -i eth0  > /dev/null &' /etc/init.d/S90start_userapp.sh");
        PlatformInit::EquipIpInit(param.mNet);

    } else if (0 == param.mMode && (!bFlag1 || !bFlag2 || !bFlag3 || !bFlag4) && param.mNetworkPortStatus == "STATIC") {
        jsonVal["success"] = false;
    }

    jsonVal["content"]["dnsName"] = ReadStrByOpt(NETWORKCONFIG, param.mNet, "dnsName");
    jsonVal["content"]["networkPortStatus"] = ReadStrByOpt(NETWORKCONFIG, param.mNet, "networkPortStatus");
    jsonVal["content"]["gateway"] = ReadStrByOpt(NETWORKCONFIG, param.mNet, "gateway");
    jsonVal["content"]["subnetMask"] = ReadStrByOpt(NETWORKCONFIG, param.mNet, "subnetMask");
    jsonVal["content"]["dataWatchIpAddress"] = ReadStrByOpt(NETWORKCONFIG, param.mNet, "ipAddress");
    jsonVal["content"]["hostName"] = ReadStrByOpt(NETWORKCONFIG, param.mNet, "hostName");
    return show_value_.write(jsonVal);
}

std::string JsonData::JsonCmd_26(Param_26 &param) {
    Json::Value jsonVal;
    jsonVal.clear();
    jsonVal["cmd"] = "26";
    jsonVal["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G;
    jsonVal["cmdSerial"] = param.mCmdSerial;
    jsonVal["success"] = true;
    jsonVal["message"] = "查询成功";
    Json::Value jsArray;
    array_t arrRes;
    arrRes = sqlite_db_ctrl::instance().GetDataMultiLine(T_SENSOR_INFO(TNAME), "*", NULL);
    int iResult = arrRes.size();
    if (iResult > 0) {
        for (int j = 0; j < iResult; j++) {
            Json::Value jsSensorData;
            jsSensorData["dataNodeNo"] = arrRes[j][44];
            char NodeName[100]={0};
            stringToHex(arrRes[j][1].c_str(),NodeName);
            jsSensorData["dataNodeNameHex"] = NodeName;
            jsSensorData["dataNodeName"] = arrRes[j][1];
            jsSensorData["initFlag"] = atoi(arrRes[j][2].c_str());
            jsSensorData["accFlag"] = atoi(arrRes[j][3].c_str());
            jsSensorData["zigbeeFlag"] = atoi(arrRes[j][4].c_str());
            jsSensorData["temTopFlag"] = atoi(arrRes[j][5].c_str());
            jsSensorData["temBotFlag"] = atoi(arrRes[j][6].c_str());
            jsSensorData["equipsta"] = atoi(arrRes[j][7].c_str());
            jsSensorData["hardVersion"] = arrRes[j][8];
            jsSensorData["softVersion"] = arrRes[j][9];
            jsSensorData["bpNo"] = arrRes[j][10];
            jsSensorData["serialNo"] = arrRes[j][11];
            jsSensorData["firstPowerTime"] = arrRes[j][12];
            jsSensorData["WakeupTime"] = atoi(arrRes[j][13].c_str());
            jsSensorData["StaticTime"] = atoi(arrRes[j][14].c_str());
            jsSensorData["WaveTime"] = atoi(arrRes[j][15].c_str());
            jsSensorData["BateryV"] = arrRes[j][16];
            jsSensorData["ProductNo"] = arrRes[j][17];
            jsSensorData["configFlag"] = atoi(arrRes[j][18].c_str());
            jsSensorData["startBrands"] = arrRes[j][19];
            jsSensorData["stopBrands"] = arrRes[j][20];
            jsSensorData["featureInterVal"] = (arrRes[j][21]);
            jsSensorData["waveInterVal"] = atoi(arrRes[j][22].c_str());
            jsSensorData["samplingRate"] = atoi(arrRes[j][23].c_str());
            jsSensorData["range"] = atoi(arrRes[j][25].c_str());
            jsSensorData["envelopeBandPass"] = arrRes[j][26];
            jsSensorData["faultFrequency"] = arrRes[j][27];
            jsSensorData["zigbeePanId"] = arrRes[j][28];
            jsSensorData["zigbeeChannel"] = (arrRes[j][29]);
            jsSensorData["zigbeeAddr"] = arrRes[j][30];
            jsSensorData["zigbeeLongAddr"] = arrRes[j][31];
            jsSensorData["zigbeeDesAddr"] = arrRes[j][32];
            jsSensorData["ZigbeePower"] = atoi(arrRes[j][33].c_str());
            jsSensorData["ZigbeeRetry"] = atoi(arrRes[j][34].c_str());
            jsSensorData["ZigbeeRetryGap"] = atoi(arrRes[j][35].c_str());
            jsSensorData["ACCSampleTime"] = atoi(arrRes[j][36].c_str());
            jsSensorData["status"] = atoi(arrRes[j][37].c_str());
            jsSensorData["timeStamp"] = arrRes[j][38];
            jsSensorData["viff"] = atoi(arrRes[j][39].c_str());
            jsSensorData["RSSI"] = arrRes[j][40];
            jsSensorData["Update"] = atoi(arrRes[j][41].c_str());
            jsSensorData["looseValue"] = arrRes[j][42];
            jsSensorData["battery"] = arrRes[j][43];
            jsSensorData["MeasurementID"] = arrRes[j][44];
            jsSensorData["nodeWaveSend"] = arrRes[j][45];
            jsArray.append(jsSensorData);
        }
    } else {
        jsArray.resize(0);
        jsonVal["success"] = false;
        jsonVal["message"] = "查询失败";
    }

    Json::Value jsBody;
    jsBody["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G;
    jsBody["dataNodeArray"] = jsArray;
    std::string dataBody = show_value_.write(jsBody);
    jsonVal["cmdBody"] = dataBody;
    return show_value_.write(jsonVal);
}

std::string JsonData::JsonCmd_27(Json::Value &recvBody) {
    Json::Value jsonVal;
    jsonVal.clear();
    jsonVal["success"] = true;
    jsonVal["message"] = "";
    jsonVal["cmd"] = "27";
    jsonVal["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G;

    int nSize = recvBody["dataNodeArray"].size();

    if (nSize > 0) {
        for (int i = 0; i < nSize; i++) {
            char whereCon[128] = {0};
            sprintf(whereCon, "%s= '%s'", "MeasurementID", recvBody["dataNodeArray"][i].asString().c_str());
            sqlite_db_ctrl::instance().DeleteTableData(T_SENSOR_INFO(TNAME), whereCon);
            sqlite_db_ctrl::instance().DeleteTableData(T_DATA_INFO(TNAME), whereCon);
            sqlite_db_ctrl::instance().DeleteTableData(T_DATASTATIC_INFO(TNAME), whereCon);
            sqlite_db_ctrl::instance().DeleteTableData(T_DATANODE_TIME(TNAME), whereCon);
        }
    } else {
        jsonVal["success"] = false;
        jsonVal["message"] = "没有传感器号";
    }
    return show_value_.write(jsonVal);
}

std::string JsonData::JsonCmd_50(Json::Value &recvBody) {
    Json::Value jsonVal;
    jsonVal.clear();
    jsonVal["success"] = true;
    jsonVal["message"] = "";
    jsonVal["cmd"] = "50";
    jsonVal["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G;

    std::string updateDevice = recvBody["updateDevice"].asString(); // 1 DataNode 2 GateWay
    std::string updateURL = recvBody["updateURL"].asString();
    std::string updateName = recvBody["updateName"].asString();
    std::string md5 = recvBody["MD5"].asString();
    std::string strResponse;
    updateName = "/opt/" + updateName;
    if (access(updateName.c_str(), 0) == 0) {
        char cmd[100] = {0x00};
        sprintf(cmd, "rm -rf %s", updateName.c_str());
        system(cmd);
    }
    sleep(2);
    int iRet = data_trans::instance().dl_curl_post_req(updateURL, "", updateName);
    if (iRet != 0) {
        jsonVal["success"] = false;
        jsonVal["message"] = "download failed";
        return show_value_.write(jsonVal);
    }
    std::string md5Val = md5file(updateName.c_str());
    zlog_info(zct, "md5Val = %s", md5Val.c_str());
    zlog_info(zct, "md5 = %s", md5.c_str());
    if (md5 != md5Val) {
        jsonVal["success"] = false;
        jsonVal["message"] = "download file check failed";
        return show_value_.write(jsonVal);
    }
    if (updateDevice == "1") { // update sensor
        std::string strcmd = "tar xvf ";
        strcmd = strcmd + updateName;
        strcmd = strcmd + " -C /opt/";
        system(strcmd.c_str());
    } else if (updateDevice == "2") { // update gateway
        sleep(3);
        system("/opt/opt.sh");
    }
    return show_value_.write(jsonVal);
}

std::string JsonData::JsonCmd_51(Json::Value &recvBody) {
    Json::Value jsonVal;
    jsonVal.clear();
    jsonVal["success"] = true;
    jsonVal["message"] = "";
    jsonVal["cmd"] = "51";
    jsonVal["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G;
    std::string DataNodeNo = recvBody["dataNodeNo"].asString();
    std::string DataNodeName = recvBody["dataNodeName"].asString();
    char szSql[100] = {0x00};
    sprintf(szSql, "update %s set  dataNodeName = '%s' where MeasurementID = '%s' ", T_SENSOR_INFO(TNAME), DataNodeName.c_str(), DataNodeNo.c_str());
    int iRet = sqlite_db_ctrl::instance().UpdateTableData(szSql);
    if (iRet != 0) {
        jsonVal["success"] = false;
        jsonVal["message"] = "updata dataNodeName failed";
    }
    return show_value_.write(jsonVal);
}

std::string JsonData::JsonCmd_52() {
    Json::Value jsonVal;
    jsonVal.clear();
    jsonVal["success"] = true;
    jsonVal["message"] = "";
    char whereCon[512] = {};
    std::string strTimeStamp = "";
    char selectCon[128] = {0};
    memcpy(selectCon, "sendMsg = '0'", 13);
    int count = sqlite_db_ctrl::instance().GetTableRows(T_DATASTATIC_INFO(TNAME), selectCon);
    if (count < 1) {
        return "";
    }
    std::string tmp_cond;
    tmp_cond = "sendMsg = '0' ORDER BY timeStamp DESC  LIMIT 0,3";
    memcpy(whereCon, tmp_cond.c_str(), tmp_cond.length());
    for (int i = 0; i < count; i++) {
        Json::Value jsSensor;
        std::string strDataNodeNo = "";
        jsonVal.clear();
        jsonVal["cmd"] = "52";
        
        // 自数据库获取传感器特征数据
        array_t arrRes;
        arrRes = sqlite_db_ctrl::instance().GetDataMultiLine(T_DATA_INFO(TNAME), "*", whereCon);
        int iResult = arrRes.size();
        if (iResult > 0) {
            for (int j = 0; j < iResult; j++) {
                Json::Value jsChannelData;
                strDataNodeNo = arrRes[j][0];
                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());
                strTimeStamp = std::string(arrRes[j][16]);
                jsSensor.append(jsChannelData);
            }
        }

        memset(selectCon, 0x00, sizeof(selectCon));
        sprintf(selectCon, "dataNodeNo='%s' and sendMsg = '0'  ORDER BY timeStamp DESC  LIMIT 0,1", strDataNodeNo.c_str());
        vec_t vecRes = sqlite_db_ctrl::instance().GetDataSingleLine(T_DATASTATIC_INFO(TNAME), "*", selectCon);
        Json::Value jsStaticData;
        if (vecRes.size() > 0) {
            jsStaticData["TemperatureTop"] = atof(vecRes[2].c_str());
            jsStaticData["TemperatureBot"] = atof(vecRes[3].c_str());
            jsStaticData["Dip"] = atof(vecRes[4].c_str());
            jsStaticData["Voltage"] = atof(vecRes[5].c_str());
            jsStaticData["ChannelType"] = "STATUS";
            jsStaticData["ChannelId"] = vecRes[1];
            jsStaticData["TimeStamp"] = vecRes[7];
            jsStaticData["dataNodeNo"] = strDataNodeNo;
        }

        jsSensor.append(jsStaticData);

        jsonVal["content"].append(jsSensor);
        std::string data = show_value_.write(jsonVal);
        memset(whereCon, 0x00, sizeof(whereCon));
        sprintf(whereCon, "sendMsg = '0' and timeStamp = '%s'", strTimeStamp.c_str());
        int iRet = data_publish(data.c_str(), GlobalConfig::Topic_G.mPubCmd.c_str());
        if (iRet == 0) {
            sqlite_db_ctrl::instance().DeleteTableData(T_DATA_INFO(TNAME), whereCon);
            sqlite_db_ctrl::instance().DeleteTableData(T_DATASTATIC_INFO(TNAME), whereCon);
        }
        mssleep(100);
    }
    return "";
}

std::string JsonData::JsonCmd_53(Json::Value &recvBody) {
    Json::Value jsonVal;
    jsonVal.clear();
    jsonVal["success"] = true;
    jsonVal["message"] = "";
    jsonVal["cmd"] = "53";
    jsonVal["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G;
    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());
    if (iRet != 0) {
        jsonVal["success"] = false;
        jsonVal["message"] = "update failed";
    }
    return show_value_.write(jsonVal);
}

int JsonData::JsonCmd_29() {
    Json::Value jsonVal;
    Json::Value jsBody;
    Json::Value jsSystemSetting;
    jsonVal.clear();
    jsonVal["cmd"] = "29";
    jsonVal["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G;
    jsBody["WebVersion"] = ReadStrByOpt(SYSTEMINFOFILE, "Version", "WebVersion");
    jsBody["SystemVersion"] = ReadStrByOpt(SYSTEMINFOFILE, "Version", "SystemVersion");
    jsBody["GateWayVersion"] = ReadStrByOpt(SYSTEMINFOFILE, "Version", "GateWayVersion");
    jsBody["localIP"] = GlobalConfig::IpAddr_G;
    jsBody["dataNodeGatewayType"] = ReadStrByOpt(SYSTEMINFOFILE, "Version", "GateWayProduct");
    jsBody["CommMode"] = "以太网";
#ifdef  NR5G_MODULE
    jsBody["CommMode"] = "5G";
#endif
#ifdef  Q4G_MODULE
    jsBody["CommMode"] = "4G";
#endif
#ifdef  WIFI_MODULE
    jsBody["CommMode"] = "WiFi";
#endif
    jsBody["GateWayHwVesion"] = ReadStrByOpt(SYSTEMINFOFILE, "Version", "GateWayHwVesion");
    jsonVal["cmdBody"] = jsBody;
    char localtimestamp[32] = {0};
    GetTimeNet(localtimestamp, 1);
    jsonVal["timestamp"] = localtimestamp;
    int res = data_publish(show_value_.write(jsonVal).c_str(), GlobalConfig::Topic_G.mPubStatus.c_str());
    if(res !=0 ){
        zlog_warn(zct, "data_publish res = %d", res);
    }
    return 0;
}
int JsonData::JsonCmd_30(){
    Json::Value jsonVal;
    Json::Value jsBody;
    Json::Value jsSystemSetting;
    Json::Value jsArray;
    jsonVal.clear();
    jsonVal["cmd"] = "30";
    array_t arrRes;
    arrRes = sqlite_db_ctrl::instance().GetDataMultiLineTransaction(T_SENSOR_INFO(TNAME), "*", NULL);
    int iResult = arrRes.size();
    if (iResult > 0) {
        for (int j = 0; j < iResult; j++) {
            Json::Value jsSensorData;
            jsSensorData["dataNodeNo"] = arrRes[j][44];
            char NodeName[100]={0};
            stringToHex(arrRes[j][1].c_str(),NodeName);
            jsSensorData["dataNodeName"] = NodeName;
            jsSensorData["acc"] = atoi(arrRes[j][3].c_str());
            jsSensorData["zigbee"] = atoi(arrRes[j][4].c_str());
            jsSensorData["temTop"] = atoi(arrRes[j][5].c_str());
            jsSensorData["temBot"] = atoi(arrRes[j][6].c_str());
            jsSensorData["hwVersion"] = arrRes[j][8];
            jsSensorData["softVersion"] = arrRes[j][9];
            jsSensorData["bpNo"] = arrRes[j][10];
            jsSensorData["serialNo"] = arrRes[j][11];
            jsSensorData["firstPowerTime"] = arrRes[j][12];
            jsSensorData["WakeupTime"] = atoi(arrRes[j][13].c_str());
            jsSensorData["StaticTime"] = atoi(arrRes[j][14].c_str());
            jsSensorData["WaveTime"] = atoi(arrRes[j][15].c_str());
            jsSensorData["BateryV"] = arrRes[j][16];
            jsSensorData["ProductNo"] = arrRes[j][17];
            jsSensorData["configFlag"] = atoi(arrRes[j][18].c_str());
            jsSensorData["startBrands"] = arrRes[j][19];
            jsSensorData["stopBrands"] = arrRes[j][20];
            jsSensorData["featureInterVal"] = atoi(arrRes[j][21].c_str());
            jsSensorData["waveInterVal"] = atoi(arrRes[j][22].c_str());
            jsSensorData["samplingRate"] = atoi(arrRes[j][23].c_str());
            jsSensorData["range"] = atoi(arrRes[j][25].c_str());
            jsSensorData["envelopeBandPass"] = arrRes[j][26];
            jsSensorData["faultFrequency"] = arrRes[j][27];
            jsSensorData["zigbeePanId"] = arrRes[j][28];
            jsSensorData["zigbeeChannel"] = (arrRes[j][29]);
            jsSensorData["zigbeeAddr"] = arrRes[j][30];
            jsSensorData["zigbeeLongAddr"] = arrRes[j][31];
            jsSensorData["zigbeeDesAddr"] = arrRes[j][32];
            jsSensorData["ZigbeePower"] = atoi(arrRes[j][33].c_str());
            jsSensorData["ZigbeeRetry"] = atoi(arrRes[j][34].c_str());
            jsSensorData["ZigbeeRetryGap"] = atoi(arrRes[j][35].c_str());
            jsSensorData["ACCSampleTime"] = atoi(arrRes[j][36].c_str());
            jsSensorData["status"] = atoi(arrRes[j][37].c_str());
            jsSensorData["timeStamp"] = arrRes[j][38];
            jsSensorData["viff"] = atoi(arrRes[j][39].c_str());
            std::vector<std::string> vParam;
            boost::split(vParam, arrRes[j][42], boost::is_any_of(","), boost::token_compress_on);
            if (vParam.size() > 1){
                if (vParam[1] != "0"){
                    jsSensorData["looseStatus"] = 1;
                }else{
                    jsSensorData["looseStatus"] = 0;
                }  
            }
            std::vector<std::string> vParamRSSI;
            boost::split(vParamRSSI, arrRes[j][40], boost::is_any_of(","), boost::token_compress_on);
            if (vParamRSSI.size() > 1) {
                jsSensorData["gatewayRSSI"] = atoi(vParamRSSI[0].c_str());
                jsSensorData["sensorRSSI"] = atoi(vParamRSSI[1].c_str());
            } else {
                jsSensorData["gatewayRSSI"] = 0;
                jsSensorData["sensorRSSI"] = atoi(arrRes[j][40].c_str());
            }
            jsSensorData["update"] = atoi(arrRes[j][41].c_str());
            jsSensorData["MeasurementID"] = arrRes[j][44];
            std::vector<std::string> vParambattery;
            boost::split(vParambattery, arrRes[j][43], boost::is_any_of(","), boost::token_compress_on);
            if (vParambattery.size() > 1) {
                jsSensorData["battery"] = float(atof(vParambattery[1].c_str())/atof(vParambattery[0].c_str()));
            } else {
                jsSensorData["battery"] = 0.99;
            }
            char whereCon[50]={0x00};
            sprintf(whereCon,"dataNodeNo = '%s'",arrRes[j][44].c_str());
            vec_t vecRes = sqlite_db_ctrl::instance().GetDataSingleLine(T_DATASTATIC_INFO(TNAME), "temTop,temBot",whereCon);
            if (vecRes.size() > 0)
            {
                jsSensorData["temTop"] = atof(vecRes[0].c_str());
                jsSensorData["temBot"] = atof(vecRes[1].c_str());
            }else{
                jsSensorData["temTop"] = 200.0;
                jsSensorData["temBot"] = 200.0;
            }
            jsArray.append(jsSensorData);
        }
    } else {
        jsArray.resize(0);
        jsonVal["success"] = true;
    }
    jsBody["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G;
    jsBody["dataNodeArray"] = jsArray;
    jsonVal["cmdBody"] = jsBody;
    char localtimestamp[32] = {0};
    GetTimeNet(localtimestamp, 1);
    jsonVal["timestamp"] = localtimestamp;
    int res = data_publish(show_value_.write(jsonVal).c_str(), GlobalConfig::Topic_G.mPubStatus.c_str());
    if(res !=0 ){
        zlog_warn(zct, "data_publish res = %d", res);
    }
    return 0;
}
int JsonData::JsonCmd_31(){
    Json::Value jsonVal;
    jsonVal.clear();
    Json::Value jsBody;
    jsonVal["cmd"] = "31";
    jsonVal["success"] = true;
    jsonVal["message"] = "";
    int featureInterVal;
    int waveInterVal;
    int waveResendNum;
    int maxSensorNum;
    int sensorCount;
    
    sensorCount = sqlite_db_ctrl::instance().GetTableRows(T_SENSOR_INFO(TNAME), NULL);
    scheduler::instance().GetScheduleConfig(featureInterVal,waveInterVal,waveResendNum,maxSensorNum);
    jsBody["featureInterVal"] = featureInterVal;
    jsBody["featureInterTime"] = 0;
    jsBody["waveInterVal"] = waveInterVal;
    jsBody["waveInterTime"] = 0;
    jsBody["maxSensorNum"] = maxSensorNum;
    jsBody["sensorCount"] = sensorCount;
    jsonVal["cmdBody"] = jsBody;
    char localtimestamp[32] = {0};
    GetTimeNet(localtimestamp, 1);
    jsonVal["timestamp"] = localtimestamp;
    int res = data_publish(show_value_.write(jsonVal).c_str(), GlobalConfig::Topic_G.mPubStatus.c_str());
    if(res !=0 ){
         zlog_warn(zct, "data_publish res = %d", res);
    }
    return 0;
}
int JsonData::JsonCmd_32(std::string MeasurementID,int  status,int type,std::string Data,std::string Msg){
    Json::Value jsonVal;
    jsonVal.clear();
    Json::Value jsBody;
    Json::FastWriter show_value_;
    jsonVal["cmd"] = "32";
    jsonVal["success"] = true;
    jsonVal["message"] = "";
    jsBody["dataNodeNo"] = MeasurementID;
    jsBody["errorStatus"] = status;
    jsBody["errorType"] = type;
    jsBody["errorData"] = Data;
    jsBody["errorMsg"] = Msg;
    jsonVal["cmdBody"] = jsBody;
    char timestamp[32] = {0};
    GetTimeNet(timestamp, 1);
    jsonVal["timestamp"] = timestamp;
    int res = data_publish(show_value_.write(jsonVal).c_str(), GlobalConfig::Topic_G.mPubStatus.c_str());
    if(res !=0 ){
         zlog_warn(zct, "data_publish res = %d", res);
    }
    return 0;
}
void JsonData::DataNodeStatusCheck() {
    array_t vetRes = sqlite_db_ctrl::instance().GetDataMultiLine(T_SENSOR_INFO(TNAME), "*", NULL);
    int nSize = vetRes.size();

    char localtimestamp[32] = {0};
    GetTimeNet(localtimestamp, 1);
    std::string nowTimetamp = std::string(localtimestamp);
    int lNowTime = atoi(nowTimetamp.c_str());
    int onlineCheck = readIntValue("config", "online", (char *)GlobalConfig::Config_G.c_str());
    int nodeOnline = readIntValue("config", "nodeOnline", (char *)GlobalConfig::Config_G.c_str());
    int count = 0;
    if (nSize > 0) {
        for (int i = 0; i < nSize; i++) {
            std::string strDataNodeNo = vetRes[i][0];
            std::string strMeasurementID = vetRes[i][44];
            std::string strChannelId = strMeasurementID + "-X";
            char whereCon[512] = {0x00}, tablename[128] = {0x00};
            sprintf(whereCon, "dataNodeNo='%s' and channelID='%s' ORDER BY timeStamp DESC  LIMIT 0,1", strMeasurementID.c_str(), strChannelId.c_str());
            sprintf(tablename, "t_data_%s", strMeasurementID.c_str());
            std::string strTimeRes = sqlite_db_ctrl::instance().GetData(tablename, "timeStamp", whereCon);
            if (strTimeRes.length() > 0) {
                int llastTime = atoi(strTimeRes.c_str());
                int lTimeTemp = lNowTime - llastTime;
                lTimeTemp = abs(lTimeTemp);
                if (lTimeTemp > onlineCheck) {
                    zlog_warn(zct, "offline DataNodeStatusCheck DataNodeNo = %s lNowTime = %d,llastTime = %d,interval = %s", strDataNodeNo.c_str(),lNowTime, llastTime, vetRes[i][21].c_str());
                    char whereCon[32] = {0};
                    sprintf(whereCon, "dataNodeNo='%s'", strDataNodeNo.c_str());
                    sqlite_db_ctrl::instance().UpdateTableData(T_SENSOR_INFO(TNAME), "status='0'", whereCon);
                    count++;
                } else {
                    char whereCon[32] = {0};
                    sprintf(whereCon, "dataNodeNo='%s'", strDataNodeNo.c_str());
                    sqlite_db_ctrl::instance().UpdateTableData(T_SENSOR_INFO(TNAME), "status='1'", whereCon);
                }
            }
        }
        if (count == nSize && nodeOnline && count != 0) {
            zlog_error(zct, "ALL Node offline,count = %d", count);
            char whereCon[100]={0};
            sprintf(whereCon,"DATE(timestamp, 'unixepoch') = DATE('now') ORDER BY timeStamp DESC limit 0,1");
            std::string strCount = sqlite_db_ctrl::instance().GetData(" reboot_record ", "count", whereCon);
            if (atoi(strCount.c_str()) < 3)//当天大于三次不再重启进程
            {
                char insertSql[64] = {0};
                sprintf(insertSql, "'%s',%d,'%s'",localtimestamp,atoi(strCount.c_str())+1,"ALL Node offline");
                sqlite_db_ctrl::instance().InsertData(" reboot_record ", insertSql);
                exit(0);
            }else{
                zlog_warn(zct, "reboot now count = %d",atoi(strCount.c_str()));
            }
        }
    }
}

int JsonData::JsonCmd_07() {
    Json::Value jsonVal;
    jsonVal.clear();
    Json::Value jsData;
    std::string sysStatus = GetSysStatus(jsData);

    zlog_info(zct, "sysStatus : %s", sysStatus.c_str());
    Json::Features f = Json::Features::strictMode();
    Json::Reader recvReader(f);
    Json::Value recvSys;
    jsonVal["cmd"] = "07";
    jsonVal["success"] = true;
    jsonVal["message"] = " ";
    char localtimestamp[32] = {0};
    GetTimeNet(localtimestamp, 1);
    jsonVal["timestamp"] = localtimestamp;
    if (recvReader.parse(sysStatus, recvSys)) {
        jsonVal["cmdBody"] = jsData;
    } else {
        jsonVal["success"] = false;
        jsonVal["message"] = "状态获取失败";
    }
    data_publish(show_value_.write(jsonVal).c_str(), GlobalConfig::Topic_G.mPubStatus.c_str());
    return 0;
}
