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

extern zlog_category_t *zct;

std::string JsonData::JsonCmd_Cgi_26(Param_26 &param) {
    Json::Value jsonVal;
    jsonVal.clear();

    jsonVal["cmd"] = "26";
    jsonVal["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G;
    jsonVal["success"] = true;
    jsonVal["message"] = " ";
    int lowSignal = -1, signalThreshold = -1, lowBatteryLevel = -1, batteryLevelThreshold = -1;
    lowSignal = readIntValue("config", "lowSignal", (char *)GlobalConfig::Config_G.c_str());
    signalThreshold = readIntValue("config", "signalThreshold", (char *)GlobalConfig::Config_G.c_str());
    lowBatteryLevel = readIntValue("config", "lowBatteryLevel", (char *)GlobalConfig::Config_G.c_str());
    batteryLevelThreshold = readIntValue("config", "batteryLevelThreshold", (char *)GlobalConfig::Config_G.c_str());
    char looseValue[10] = {0x00};
    char whereCon[100] = {0};
    std::string effect = "" ,rssi = "0",batteryPower = "";
    readStringValue("config", "loose", looseValue, (char *)GlobalConfig::Config_G.c_str());
    Json::Value jsArray;
    array_t arrRes;
    arrRes = sqlite_db_ctrl::instance().GetDataMultiLineTransaction(T_SENSOR_INFO(TNAME), "*", NULL);
    int iResult = arrRes.size();
    if (iResult > 0) {
        int packgeNo = param.mPackageFlag;
        int packgeMax = 0;
        int packgeNum = 0;
        jsonVal["package"] = packgeNo;
        int lastSize = iResult % 10;
        int index = iResult / 10;
        if (lastSize > 0 && index > 0) {
            packgeMax = index + 1;
            if (packgeNo + 1 == packgeMax) {
                packgeNum = iResult;
                jsonVal["packageMax"] = index + 1;
            } else {
                packgeNum = (packgeNo + 1) * 10;
                jsonVal["packageMax"] = index + 1;
            }
        } else if (lastSize == 0 && index > 0) {
            packgeNum = (packgeNo + 1) * 10;
            packgeMax = index;
            jsonVal["packageMax"] = index;
        } else if (lastSize > 0 && index == 0) {
            packgeNum = lastSize;
            packgeMax = index + 1;
            jsonVal["packageMax"] = index;
        }
        for (int j = packgeNo * 10; j < packgeNum; j++) {
            Json::Value jsSensorData;
            jsSensorData["dataNodeNo"] = arrRes[j][0];
            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["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"] = 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)
                jsSensorData["loose"] = vParam[1];
            else
                jsSensorData["loose"] = "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["RSSI"] = atof(vParamRSSI[1].c_str()) / 255.0;
            } else {
                jsSensorData["RSSI"] = arrRes[j][40];
                rssi = arrRes[j][40];
            }
            batteryPower = arrRes[j][43];
            std::vector<std::string> vParamBatteryPower;
            float fBatteryPower = 100.0;
            if(batteryPower != ""){
                boost::split(vParamBatteryPower, batteryPower, boost::is_any_of(","), boost::token_compress_on);
                if (vParamBatteryPower.size() > 0) {
                    fBatteryPower = atof(vParamBatteryPower[1].c_str())/atof(vParamBatteryPower[0].c_str());
                }
            }
            memset(whereCon,0x00,sizeof(whereCon));
            sprintf(whereCon,"shortAddr = '%s' ",arrRes[j][30].c_str());
            vec_t vecResult = sqlite_db_ctrl::instance().GetDataSingleLine("t_shutdown_info","*",whereCon);
            if (vecResult.size() == 0)
            {
                effect = "0";
            }else{
                effect = vecResult[5];
            }
            
            
            //同时满足时的优先级：低电量>低信号>停机
            if(effect == "1"){
                jsSensorData["waveStatus"] = 0; //灰色
            }
            if(lowSignal == 1 && atof(rssi.c_str()) < signalThreshold){
                jsSensorData["waveStatus"] = 1;//红色
            }
            if(lowBatteryLevel == 1 && fBatteryPower < batteryLevelThreshold){
                jsSensorData["waveStatus"] = 2;//红色
            }

            jsSensorData["update"] = atoi(arrRes[j][41].c_str());
            jsSensorData["MeasurementID"] = arrRes[j][44];
            jsSensorData["battery"] = arrRes[j][43];
            jsSensorData["nodeWaveSend"] = arrRes[j][45];
            jsSensorData["upgradeStatus"] = arrRes[j][46];
            jsArray.append(jsSensorData);
        }
    } else {
        jsArray.resize(0);
        jsonVal["success"] = true;
    }
    jsonVal["gatewayMac"] = GlobalConfig::MacAddr_G;
    jsonVal["gatewayIP"] = GlobalConfig::IpAddr_G;
    jsonVal["content"]["dataNodeArray"] = jsArray;
    return show_value_.write(jsonVal);
}

std::string JsonData::JsonCmd_Cgi_54(Param_54 &param) {
    Json::Value jsonVal;
    jsonVal.clear();

    jsonVal["cmd"] = "54";
    jsonVal["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G;
    jsonVal["success"] = true;
    jsonVal["message"] = " ";

    Json::Value jsArray, nodeArray, gatewayArray;
    array_t arrRes;
    arrRes = sqlite_db_ctrl::instance().GetDataMultiLineTransaction(T_SENSOR_INFO(TNAME), "*", NULL);
    int iResult = arrRes.size();
    if (iResult > 0) {
        int packgeNo = param.mPackageFlag;
        int packgeMax = 0;
        int packgeNum = 0;
        jsonVal["package"] = packgeNo;
        int lastSize = iResult % 10;
        int index = iResult / 10;
        if (lastSize > 0 && index > 0) {
            packgeMax = index + 1;
            if (packgeNo + 1 == packgeMax) {
                packgeNum = iResult;
                jsonVal["packageMax"] = index + 1;
            } else {
                packgeNum = (packgeNo + 1) * 10;
                jsonVal["packageMax"] = index + 1;
            }
        } else if (lastSize == 0 && index > 0) {
            packgeNum = (packgeNo + 1) * 10;
            packgeMax = index;
            jsonVal["packageMax"] = index;
        } else if (lastSize > 0 && index == 0) {
            packgeNum = lastSize;
            packgeMax = index + 1;
            jsonVal["packageMax"] = index;
        }

        for (int j = packgeNo * 10; j < packgeNum; j++) {
            Json::Value nodeArray;
            char hex[100];
            nodeArray.append(arrRes[j][0]);
            stringToHex(arrRes[j][1].c_str(), hex);
            nodeArray.append(hex);
            for (int k = 2; k <= 46; ++k) {
                nodeArray.append(arrRes[j][k]);
            }            
            jsArray.append(nodeArray);
        }

    } else {
        jsArray.resize(0);
        jsonVal["success"] = true;
    }
    Json::Value jsSystemSetting, jsonValnet, jsonValnet1, jsSystemInfo, jsonValZigbee;
    Json::Value jsBody;

    jsSystemSetting["ServerIpAddress"] = ReadStrByOpt(SERVERCONFIG, "Server", "localServerIpAddress");
    jsSystemSetting["ServerPort"] = (ReadStrByOpt(SERVERCONFIG, "Server", "localServerPort").c_str());
    jsSystemSetting["CommMode"] = (ReadStrByOpt(SERVERCONFIG, "Server", "CommMode").c_str());
    jsSystemSetting["UserName"] = ReadStrByOpt(SERVERCONFIG, "Server", "UserName");
    jsSystemSetting["Password"] = ReadStrByOpt(SERVERCONFIG, "Server", "Password");
    jsSystemSetting["APN"] = ReadStrByOpt(SERVERCONFIG, "Server", "APN");
    jsBody["ServerConfig"] = jsSystemSetting;
    jsonVal["content"] = jsBody;

#ifdef G2UL_GATEWAY
    jsonValnet1["dnsName"] = ReadStrByOpt(NETWORKCONFIG, "eth1", "dnsName");
    jsonValnet1["networkPortStatus"] = ReadStrByOpt(NETWORKCONFIG, "eth1", "networkPortStatus");
    jsonValnet1["gateway"] = ReadStrByOpt(NETWORKCONFIG, "eth1", "gateway");
    jsonValnet1["subnetMask"] = ReadStrByOpt(NETWORKCONFIG, "eth1", "subnetMask");
    jsonValnet1["dataWatchIpAddress"] = ReadStrByOpt(NETWORKCONFIG, "eth1", "ipAddress");
    jsonValnet1["hostName"] = ReadStrByOpt(NETWORKCONFIG, "eth1", "hostName");
    jsonVal["content"]["eth1"] = jsonValnet1;
    jsonVal["content"]["gatewaytype"] = 1;
#endif

    jsSystemInfo["GateWayVersion"] = ReadStrByOpt(SYSTEMINFOFILE, "Version", "GateWayVersion");
    jsSystemInfo["SystemVersion"] = ReadStrByOpt(SYSTEMINFOFILE, "Version", "SystemVersion");
    jsSystemInfo["WebVersion"] = ReadStrByOpt(SYSTEMINFOFILE, "Version", "WebVersion");
    jsSystemInfo["GateWayHwVesion"] = ReadStrByOpt(SYSTEMINFOFILE, "Version", "GateWayHwVesion");
    jsSystemInfo["GateWayProduct"] = ReadStrByOpt(SYSTEMINFOFILE, "Version", "GateWayProduct");
    jsonVal["content"]["SystemInfo"] = jsSystemInfo;

    jsonValZigbee["channel"] = ReadStrByOpt(ZIGBEECONFIG, "Zigbee", "channel");
    jsonValZigbee["PanID"] = ReadStrByOpt(ZIGBEECONFIG, "Zigbee", "PanID");
    jsonVal["content"]["zigbee"] = jsonValZigbee;

    jsonVal["gatewayMac"] = GlobalConfig::MacAddr_G;
    jsonVal["gatewayIP"] = GlobalConfig::IpAddr_G;
    jsonVal["content"]["dataNodeArray"] = jsArray;
    jsonVal["content"]["gateWay"] = gatewayArray;
    return show_value_.write(jsonVal);
}

std::string JsonData::JsonCmd_Cgi_27(std::vector<Param_27>  &param) {
    Json::Value jsonVal;
    jsonVal.clear();

    jsonVal["cmd"] = "27";
    jsonVal["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G;
    jsonVal["success"] = true;
    jsonVal["message"] = " ";
    char whereCon[128] = {0};
    char localtimestamp[32] = {0};
    for (size_t i = 0; i < param.size(); i++)
    {
        zlog_info(zct,"type = %s",param[i].mType.c_str());
        if (param[i].mDataNodeNo.length() > 0 && param[i].mType == "DELETE") {
            sprintf(whereCon, "%s= '%s'", T_SENSOR_INFO(DATANODENO), param[i].mDataNodeNo.c_str());
            sqlite_db_ctrl::instance().DeleteTableData(T_SENSOR_INFO(TNAME), whereCon);
            memset(whereCon,0,sizeof(whereCon));
            sprintf(whereCon, "%s= '%s'", T_SENSOR_INFO(DATANODENO), param[i].mMeasurementID.c_str());
            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_BATTERY_INFO(TNAME), whereCon);
            sqlite_db_ctrl::instance().DeleteTableData(" t_battery_history ", whereCon);
            memset(whereCon,0,sizeof(whereCon));
            sprintf(whereCon, "MeasurementID = '%s'", param[i].mMeasurementID.c_str());
            sqlite_db_ctrl::instance().DeleteTableData(" t_debug_info ", whereCon);
            sqlite_db_ctrl::instance().DeleteTableData(" t_shutdown_info ", whereCon);
            sqlite_db_ctrl::instance().DeleteTableData(" t_wave_triger_info ", whereCon);
            memset(whereCon,0,sizeof(whereCon));
            sprintf(whereCon, "channelID like '%%%s%%'", param[i].mMeasurementID.c_str());
            sqlite_db_ctrl::instance().DeleteTableData(" t_data_waveSend ", whereCon);
            char szTableName[50] = {0x00};
            sprintf(szTableName, "DROP TABLE t_data_%s", param[i].mMeasurementID.c_str());
            sqlite_db_ctrl::instance().CreateTable(szTableName);
            memset(szTableName, 0x00, sizeof(szTableName));
            sprintf(szTableName, "DROP TABLE t_dataStatic_%s", param[i].mMeasurementID.c_str());
            sqlite_db_ctrl::instance().CreateTable(szTableName);
            uint16_t short_addr;
            char *end_ptr = NULL;
            short_addr = strtol(param[i].mShortAddr.c_str(), &end_ptr, 16);
            zlog_warn(zct,"delete short_addr = %02x%02x",UINT16_HIGH(short_addr),UINT16_LOW(short_addr));
            scheduler::instance().ClearScheduleCfg(short_addr);
    
        } else if (param[i].mDataNodeNo.length() > 0 && param[i].mType == "CORRECT") {
            char updateSql[1024] = {0};
            sprintf(whereCon, "%s= '%s'", T_SENSOR_INFO(DATANODENO), param[i].mDataNodeNo.c_str());
            GetTimeNet(localtimestamp, 1);
            sprintf(updateSql, "LooseValue = '0,2,");
            std::string strUpdateSql = std::string(updateSql) + std::string(localtimestamp) + "' ";
            sqlite_db_ctrl::instance().UpdateTableData(T_SENSOR_INFO(TNAME), strUpdateSql.c_str(), whereCon);
        } else {
            jsonVal["success"] = false;
            jsonVal["message"] = "没有传感器号";
        }
    }
    return show_value_.write(jsonVal);
}

std::string JsonData::JsonCmd_Cgi_28(Param_28 &param) {
    Json::Value jsonVal;
    jsonVal.clear();

    jsonVal["cmd"] = "28";
    jsonVal["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G;
    jsonVal["success"] = true;
    jsonVal["message"] = "";

    if (param.mDataNodeNo.length() > 0) {
        char updateColumn[128] = {0};
        char whereCon[64] = {0};
        sprintf(whereCon, "dataNodeNo='%s'", param.mDataNodeNo.c_str());
        sprintf(updateColumn, "dataNodeName='%s'", param.mDataNodeName.c_str());
        sqlite_db_ctrl::instance().UpdateTableData(T_SENSOR_INFO(TNAME), updateColumn, whereCon);
    } else {
        jsonVal["success"] = false;
        jsonVal["message"] = "没有传感器号";
    }
    return show_value_.write(jsonVal);
}

std::string JsonData::JsonCmd_Cgi_29(Param_29 &param) {
    Json::Value jsonVal;
    Json::Value jsBody;
    Json::Value SystemSetting;
    jsonVal.clear();
    jsonVal["cmd"] = "29";
    jsonVal["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G;
    jsonVal["success"] = true;
    jsonVal["message"] = " ";
    std::vector<float> vecWave;
    char whereCon[64] = {};
    sprintf(whereCon, "dataNodeNo='%s'", param.mDataNodeNo.c_str());
    vec_t res = sqlite_db_ctrl::instance().GetDataSingleLine(T_SENSOR_INFO(TNAME), " * ", whereCon);
    char localtimestamp[32] = {0};
    std::string strWaveData = "";
    std::string filename = "/opt/data/" + param.mChannelId + ".dat";
    std::string softVersion = res[9];
    std::string productNo = res[17];
    if ((compareVersions(softVersion, "2.6") == -1 && productNo == "02") || productNo == "01")  // DN101所有版本和DN102 2.6以前版本
    {
        if (access(filename.c_str(), 0) >= 0 && param.mMode == 0) {
            std::ifstream inFile(filename.c_str(), std::ios::in | std::ios::binary);
            if (!inFile) {
                zlog_error(zct, "read channel data error, filename:%s", filename.c_str());
                jsonVal["success"] = false;
                jsonVal["message"] = "error";
            } else {
                float fTemp = 0.0f;
                inFile.read((char *)localtimestamp, sizeof(localtimestamp));
                while (inFile.read((char *)&fTemp, sizeof(fTemp))) {
                    vecWave.push_back(fTemp);
                }

                int flag = param.mPackageFlag;
                flag = (flag + 1) * 1024;
                int number = vecWave.size();
                int start = param.mPackageFlag * 1024;
                if (number < 1024) {
                    flag = number;
                    start = 0;
                }
                char buf[32];
                for (int i = start; i < flag; i++) {
                    if (i == start) {
                        memset(buf, 0, 32);
                        sprintf(buf, "%.2f", vecWave[i]);
                        std::string waveTemp(buf);
                        strWaveData = waveTemp;

                    } else {
                        memset(buf, 0, 32);
                        sprintf(buf, "%.2f", vecWave[i]);
                        std::string waveTemp(buf);
                        strWaveData = strWaveData + "," + waveTemp;
                    }
                }
                int max = number / 1024;
                if (max == 0 && number > 0) {
                    max = 1;
                }
                jsBody["packageMax"] = max;
            }

        } else {
            jsonVal["success"] = false;
            jsonVal["message"] = "没有数据文件";
        }
        
        zlog_info(zct, "vecWave.size() = %zu,sample = %d,second = %f", vecWave.size(), atoi(res[23].c_str()), float(vecWave.size() / atoi(res[23].c_str())));
        std::string::size_type comper = param.mChannelId.find("Z");
        if (comper != std::string::npos && res[17] == "02") {
            jsBody["second"] = float((float)vecWave.size() / (float)atoi(res[23].c_str()));
        } else if (res[17] == "01") {
            jsBody["second"] = float((float)vecWave.size() / (float)atoi(res[23].c_str()));
        } else {
            jsBody["second"] = 1;
        }
    }else {
        if (param.mMode == 1)  // DN102 有高频和低频
        {
            filename = "/opt/data/" + param.mChannelId + "-LF.dat";
            jsBody["second"] = 3.2;
        }else{
            std::string::size_type comper = param.mChannelId.find("Z");
            if (comper != std::string::npos ) {
                jsBody["second"] = 1.28; 
            } else {
                jsBody["second"] = 1.6;
            }
        }
        zlog_info(zct,"filename %s",filename.c_str());
        if (access(filename.c_str(), 0) >= 0) {
            std::ifstream inFile(filename.c_str(), std::ios::in | std::ios::binary);
            if (!inFile) {
                zlog_error(zct, "read channel data error, filename:%s", filename.c_str());
                jsonVal["success"] = false;
                jsonVal["message"] = "error";
            } else {
                float fTemp = 0.0f;
                inFile.read((char *)localtimestamp, sizeof(localtimestamp));
                while (inFile.read((char *)&fTemp, sizeof(fTemp))) {
                    vecWave.push_back(fTemp);
                }

                int flag = param.mPackageFlag;
                flag = (flag + 1) * 1024;
                int number = vecWave.size();
                int start = param.mPackageFlag * 1024;
                if (number < 1024) {
                    flag = number;
                    start = 0;
                }
                char buf[32];
                for (int i = start; i < flag; i++) {
                    if (i == start) {
                        memset(buf, 0, 32);
                        sprintf(buf, "%.2f", vecWave[i]);
                        std::string waveTemp(buf);
                        strWaveData = waveTemp;

                    } else {
                        memset(buf, 0, 32);
                        sprintf(buf, "%.2f", vecWave[i]);
                        std::string waveTemp(buf);
                        strWaveData = strWaveData + "," + waveTemp;
                    }
                }
                int max = number / 1024;
                if (max == 0 && number > 0) {
                    max = 1;
                }
                jsBody["packageMax"] = max;
            }

        } else {
            jsonVal["success"] = false;
            jsonVal["message"] = "没有数据文件";
        }   
        
    }
    jsBody["channelId"] = param.mChannelId;
    jsBody["package"] = param.mPackageFlag;

    jsBody["Data"] = strWaveData;
    jsBody["timestamp"] = std::string(localtimestamp);
    jsonVal["content"] = jsBody;
    return show_value_.write(jsonVal);
}

std::string JsonData::JsonCmd_Cgi_30(Param_30 &param) {
    Json::Value jsonVal;
    Json::Value jsBody;
    Json::Value SystemSetting;
    jsonVal.clear();

    jsonVal["cmd"] = "30";
    jsonVal["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G;
    jsonVal["success"] = true;
    jsonVal["message"] = "";
    std::string strWaveData;
    std::string filename = "/opt/data/" + param.mChannelId + ".dat";
    char localtimestamp[32] = {0};
    std::vector<float> vecWave;
    std::vector<float> hanningWave;
    std::vector<float> addhanningWave;
    std::vector<float> fftWave;
    int sampleRateReference = 0;
    /* 新增代码 */
    char whereCon[64] = {};
    sprintf(whereCon, "dataNodeNo='%s'", param.mDataNodeNo.c_str());
    vec_t res = sqlite_db_ctrl::instance().GetDataSingleLine(T_SENSOR_INFO(TNAME), " * ", whereCon);
    std::string softVersion = res[9];
    std::string productNo = res[17];
    if ((compareVersions(softVersion, "2.6") == -1 && productNo == "02") || productNo == "01")  // DN101所有版本和DN102 2.6以前版本
    {
        if (access(filename.c_str(), 0) >= 0) {
            std::ifstream inFile(filename.c_str(), std::ios::in | std::ios::binary);
            if (!inFile) {
                zlog_error(zct, "read channel data error, filename:%s", filename.c_str());
                jsonVal["success"] = "false";
                jsonVal["message"] = "error";
            } else {
                float fTemp = 0.0f;
    
                inFile.read((char *)localtimestamp, sizeof(localtimestamp));
                std::string::size_type comper = param.mChannelId.find("Z");
                if (comper != std::string::npos && res[17] == "02") {
                    while (inFile.read((char *)&fTemp, sizeof(fTemp))) {
                        vecWave.push_back(fTemp);
                    }
                    //进行傅立叶变换
                    Calculation::FFTSpec(vecWave, fftWave);
                    sampleRateReference = 1000;
    
                } else {
                    while (inFile.read((char *)&fTemp, sizeof(fTemp))) { // 取8K进行计算
                        vecWave.push_back(fTemp);
                    }
    
                    //进行傅立叶变换
                    Calculation::FFTSpec(vecWave, fftWave);
                    sampleRateReference = 1024;
                }
                int flag = param.mPackageFlag;
                flag = (flag + 1) * sampleRateReference;
                int number = fftWave.size();
                int start = param.mPackageFlag * sampleRateReference;
                if (number < sampleRateReference) {
                    flag = number;
                    start = 0;
                }
                char buf[32];
                for (int i = start; i < flag; i++) {
                    if (i == start) {
                        memset(buf, 0, 32);
                        sprintf(buf, "%.6f", fftWave[i]);
                        std::string waveTemp(buf);
                        strWaveData = waveTemp;
    
                    } else {
                        memset(buf, 0, 32);
                        sprintf(buf, "%.6f", fftWave[i]);
                        std::string waveTemp(buf);
                        strWaveData = strWaveData + "," + waveTemp;
                    }
                }
    
                int max = number / sampleRateReference;
                if (max == 0 && number > 0) {
                    max = 1;
                }
                jsBody["packageMax"] = max;
            }
        } else {
            jsonVal["success"] = false;
            jsonVal["message"] = "没有数据文件";
        }
    }else {
        if (param.mMode == 1 && productNo == "02")  // DN102 有高频和低频
        {
            filename = "/opt/data/" + param.mChannelId + "-LF.dat";
        }       
        if (access(filename.c_str(), 0) >= 0) {
            std::ifstream inFile(filename.c_str(), std::ios::in | std::ios::binary);
            if (!inFile) {
                zlog_error(zct, "read channel data error, filename:%s", filename.c_str());
                jsonVal["success"] = "false";
                jsonVal["message"] = "error";
            } else {
                float fTemp = 0.0f;
    
                inFile.read((char *)localtimestamp, sizeof(localtimestamp));

                while (inFile.read((char *)&fTemp, sizeof(fTemp))) {
                    vecWave.push_back(fTemp);
                }
                zlog_info(zct,"LF vecWave size %zu,filename = %s",vecWave.size(),filename.c_str());
                //进行傅立叶变换
                Calculation::FFTSpec(vecWave, fftWave);
                sampleRateReference = 1024;
                
                int flag = param.mPackageFlag;
                flag = (flag + 1) * sampleRateReference;
                int number = fftWave.size();
                int start = param.mPackageFlag * sampleRateReference;
                if (number < sampleRateReference) {
                    flag = number;
                    start = 0;
                }
                char buf[32];
                for (int i = start; i < flag; i++) {
                    if (i == start) {
                        memset(buf, 0, 32);
                        sprintf(buf, "%.6f", fftWave[i]);
                        std::string waveTemp(buf);
                        strWaveData = waveTemp;
    
                    } else {
                        memset(buf, 0, 32);
                        sprintf(buf, "%.6f", fftWave[i]);
                        std::string waveTemp(buf);
                        strWaveData = strWaveData + "," + waveTemp;
                    }
                }
    
                int max = number / sampleRateReference;
                if (max == 0 && number > 0) {
                    max = 1;
                }
                jsBody["packageMax"] = max;
            }
        } else {
            jsonVal["success"] = false;
            jsonVal["message"] = "没有数据文件";
        }   
    }
    jsBody["channelId"] = param.mChannelId;
    jsBody["package"] = param.mPackageFlag;
    jsBody["timestamp"] = std::string(localtimestamp);
    jsBody["Data"] = strWaveData;

    double resolution = 0.0;
    int SampleRate = 0;
    zlog_info(zct, "sensor type %s", res[17].c_str());
    if (res[17] == "01") {
        SampleRate = atoi(res[23].c_str());
        zlog_info(zct, "sample_rate=%d", SampleRate);
        resolution = (((double)SampleRate / 1000) * 1016) / vecWave.size();

    } 
    if ((res[17] == "02" && compareVersions(softVersion, "2.6") == -1) || productNo == "01") {
        std::string::size_type comper = param.mChannelId.find("Z");
        if (comper != std::string::npos) {
            SampleRate = atoi(res[23].c_str());
            resolution = (double)SampleRate / vecWave.size();
            zlog_info(zct, "sample_rate=%d,resolution = %f", SampleRate, resolution);
        } else {
            SampleRate = 8192;
            zlog_info(zct, "sample_rate=%d", SampleRate);
            if (vecWave.size() < 8192) {
                resolution = (double)SampleRate / vecWave.size();
            } else {
                resolution = (double)SampleRate / 8192;
            }
        }
    }
    if(param.mMode == 0 && productNo == "02"){
        std::string::size_type comper = param.mChannelId.find("Z");
        if (comper != std::string::npos) {
            resolution = 1 / 1.28;
        }else{
            resolution = 1 / 1.6;
        }
    }else if(param.mMode == 1 && productNo == "02"){
        resolution = 1 / 3.2;
    }

    zlog_info(zct, "the sample rate is %d,the resolution %f", SampleRate, resolution);
    char buf[32];
    memset(buf, 0, 32);
    sprintf(buf, "%f", resolution);
    jsBody["resolution"] = std::string(buf);

    jsonVal["content"] = jsBody;
    return show_value_.write(jsonVal);
}

std::string JsonData::JsonCmd_Cgi_40(Param_40 &param) {
    Json::Value jsonVal;
    Json::Value jsBody;
    Json::Value SystemSetting;
    jsonVal.clear();

    jsonVal["cmd"] = "40";
    jsonVal["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G;
    jsonVal["success"] = true;
    jsonVal["message"] = "";
    int i = 0;
    int sampleRateReference = 0;
    std::vector<float> vecWave;
    char whereCon[64] = {0};
    sprintf(whereCon, "dataNodeNo='%s'", param.mDataNodeNo.c_str());
    vec_t res = sqlite_db_ctrl::instance().GetDataSingleLine(T_SENSOR_INFO(TNAME), " * ", whereCon);
    std::string strWaveData;
    std::string filename = "/opt/data/" + param.mChannelId + ".dat";
    char localtimestamp[32] = {0};
    if (access(filename.c_str(), 0) >= 0) {
        std::ifstream inFile(filename.c_str(), std::ios::in | std::ios::binary);
        if (!inFile) {
            zlog_error(zct, "read channel data error, filename:%s", filename.c_str());
            jsonVal["success"] = "false";
            jsonVal["message"] = "error";
        } else {
            float fTemp = 0;

            std::vector<float> envWave;
            std::vector<float> hanningWave;
            std::vector<float> addhanningWave;
            inFile.read((char *)localtimestamp, sizeof(localtimestamp));
            std::string::size_type comper = param.mChannelId.find("Z");
            if (comper != std::string::npos && res[17] == "02") {
                while (inFile.read((char *)&fTemp, sizeof(fTemp))) {
                    vecWave.push_back(fTemp);
                }
                //添加汉宁窗
                Calculation::Hanning(vecWave, hanningWave);
                for (size_t i = 0; i < vecWave.size(); i++) {
                    addhanningWave.push_back(vecWave[i] * hanningWave[i]);
                }

                //进行傅立叶变换
                if (param.StartFrequency == 0) {
                    param.StartFrequency = 3000;
                    param.EndFrequency = 5000;
                }

                Calculation::envSpec(addhanningWave, envWave, param.StartFrequency, param.EndFrequency);
                sampleRateReference = 1000;

            } else {
                while (inFile.read((char *)&fTemp, sizeof(fTemp))) { // 取8K进行计算
                    if (i < 8192) {
                        vecWave.push_back(fTemp);
                    } else {
                        break;
                    }
                    i++;
                }
                if (vecWave.size() < 8192) {
                    for (int i = vecWave.size(); i < 8192; i++) {
                        vecWave.push_back(0);
                    }
                }

                //添加汉宁窗
                Calculation::Hanning(vecWave, hanningWave);
                for (size_t i = 0; i < vecWave.size(); i++) {
                    addhanningWave.push_back(vecWave[i] * hanningWave[i]);
                }

                //进行傅立叶变换
                if (param.StartFrequency == 0) {
                    param.StartFrequency = 3000;
                    param.EndFrequency = 5000;
                }

                Calculation::envSpec(addhanningWave, envWave, param.StartFrequency, param.EndFrequency);
                sampleRateReference = 1024;
            }
            /*for(int i = 0; i < envWave.size();i++){
                envWave[i] = envWave[i]*2;
            }*/

            zlog_info(zct, "2---------------------------------------------->%d", envWave.size());
            zlog_info(zct, "2---------------------------------------------->%f", envWave[10]);

            zlog_info(zct, "after fft--------------------------------------------------->fftWave.size()=%d", envWave.size());

            int flag = param.mPackageFlag;
            flag = (flag + 1) * sampleRateReference;
            int number = envWave.size();
            int start = param.mPackageFlag * sampleRateReference;
            zlog_info(zct, "param.mPackageFlag = %d", param.mPackageFlag);
            zlog_info(zct, "param.start = %d", start);
            zlog_info(zct, "param.flag = %d", flag);
            if (number < sampleRateReference) {
                flag = number;
                start = 0;
            }
            char buf[32];
            for (int i = start; i < flag; i++) {
                if (i == start) {
                    memset(buf, 0, 32);
                    sprintf(buf, "%.6f", envWave[i]);
                    std::string waveTemp(buf);
                    strWaveData = waveTemp;

                } else {
                    memset(buf, 0, 32);
                    sprintf(buf, "%.6f", envWave[i]);
                    std::string waveTemp(buf);
                    strWaveData = strWaveData + "," + waveTemp;
                }
            }

            int max = number / sampleRateReference;
            if (max == 0 && number > 0) {
                max = 1;
            }
            jsBody["packageMax"] = max;
        }
    } else {
        jsonVal["success"] = false;
        jsonVal["message"] = "没有数据文件";
    }

    jsBody["channelId"] = param.mChannelId;
    jsBody["package"] = param.mPackageFlag;
    jsBody["timestamp"] = std::string(localtimestamp);
    jsBody["Data"] = strWaveData;

    double resolution = 0.0;
    int SampleRate = 0;
    zlog_info(zct, "sensor type %s", res[17].c_str());
    if (res[17] == "01") {
        SampleRate = atoi(res[23].c_str());
        zlog_info(zct, "sample_rate=%d", SampleRate);
        resolution = (((double)SampleRate / 1000) * 1016) / 8192;
    } else if (res[17] == "02") {
        std::string::size_type comper = param.mChannelId.find("Z");
        if (comper != std::string::npos) {
            SampleRate = atoi(res[23].c_str());

            resolution = (double)SampleRate / vecWave.size();
            zlog_info(zct, "sample_rate=%d,resolution = %f", SampleRate, resolution);
        } else {
            SampleRate = 8000;
            zlog_info(zct, "sample_rate=%d", SampleRate);
            resolution = (((double)SampleRate / 1000) * 1024) / 8192;
        }
    }

    zlog_info(zct, "the sample rate is %d,the resolution %f", SampleRate, resolution);
    char buf[32];
    memset(buf, 0, 32);
    sprintf(buf, "%f", resolution);
    jsBody["resolution"] = std::string(buf);

    jsonVal["content"] = jsBody;
    return show_value_.write(jsonVal);
}

std::string JsonData::JsonCmd_Cgi_41(std::vector<Param_41> &param, int isServer) {
    Json::Value jsonVal;
    jsonVal.clear();

    jsonVal["cmd"] = "41";
    jsonVal["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G;
    jsonVal["success"] = true;
    jsonVal["message"] = " ";

    char whereCon[1024] = {0};
    char updateSql[1024] = {0};

    for (size_t i = 0; i < param.size(); i++) {

        if (!isServer)
            sprintf(whereCon, "dataNodeNo='%s'", param[i].mdataNodeNo.c_str());
        else
            sprintf(whereCon, "MeasurementID ='%s'", param[i].mdataNodeNo.c_str());

        std::string zigbeeShortAddr = sqlite_db_ctrl::instance().GetData(T_SENSOR_INFO(TNAME), " zigbeeShortAddr ", whereCon);
       
        uint16_t short_addr;
        char *end_ptr = NULL;
        short_addr = strtol(zigbeeShortAddr.c_str(), &end_ptr, 16);
        int res = scheduler::instance().UpdateSensorConfig(short_addr);
        if (res != 0){
            jsonVal["success"] = false;
            jsonVal["message"] = "update error";
            return show_value_.write(jsonVal);
        }
        char dataNodeName[100] = {0x00};
        hexToAscii(param[i].mdataNodeName.c_str(), dataNodeName);
        zlog_info(zct, "str = %s", dataNodeName);
        zlog_info(zct, "dataNodeName = %s", param[i].mdataNodeName.c_str());
        int dataNodeNameLength = param[i].mdataNodeName.length();
        if (dataNodeNameLength != 0) {
            sprintf(updateSql, "dataNodeName = '%s',ZigbeePower = '%d',ZigbeeRetry = '%d',range='%d',samplingRate='%d',AccSampleTime = '%d',\
				startBrands = '%s',stopBrands = '%s',envelopeBandPass = '%s',viff = '%d',faultFrequency = '%s' ,MeasurementID = '%s' ,UpdateFlag = -1",
                    dataNodeName, param[i].ZigbeePower, param[i].ZigbeeRetry, param[i].mrange, param[i].msamplingRate, param[i].mAccSampleTime, param[i].mstartBrands.c_str(), param[i].mstopBrands.c_str(),
                    param[i].menvelopeBandPass.c_str(), param[i].mviff, param[i].mfaultFrequency.c_str(), param[i].mMeasurementID.c_str());
        } else if (dataNodeNameLength == 0) {
            sprintf(updateSql, "ZigbeePower = '%d',ZigbeeRetry = '%d',range='%d',samplingRate='%d',AccSampleTime = '%d',\
				startBrands = '%s',stopBrands = '%s',envelopeBandPass = '%s',viff = '%d',faultFrequency = '%s',MeasurementID = '%s',UpdateFlag = 0",
                    param[i].ZigbeePower, param[i].ZigbeeRetry,  param[i].mrange, param[i].msamplingRate, param[i].mAccSampleTime, param[i].mstartBrands.c_str(), param[i].mstopBrands.c_str(), param[i].menvelopeBandPass.c_str(),
                    param[i].mviff, param[i].mfaultFrequency.c_str(), param[i].mMeasurementID.c_str());
        }
         int iRet = sqlite_db_ctrl::instance().UpdateTableData(T_SENSOR_INFO(TNAME), updateSql, whereCon);
        memset(whereCon, 0x00, sizeof(whereCon));
        memset(updateSql, 0x00, sizeof(updateSql));
        if (iRet != 0) jsonVal["success"] = false;
    }
    return show_value_.write(jsonVal);
}

std::string JsonData::JsonCmd_Cgi_42(Param_42 &param) {
    Json::Value jsonVal;
    jsonVal.clear();
    jsonVal["cmd"] = "42";
    jsonVal["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G;
    jsonVal["success"] = true;
    jsonVal["message"] = "上传成功!";
    char cmd[100] = {0x00};
    strcpy(cmd, "rm -rf /tmp/cgic*");
    system(cmd);
    if (param.fileName == "DataNode.tar") {
        std::string strcmd = "tar xvf /opt/";
        strcmd = strcmd + param.fileName;
        strcmd = strcmd + " -C /opt/";
        zlog_info(zct, "strcmd = %s", strcmd.c_str());
        system(strcmd.c_str());
    } else if (param.fileName == "rfsbu.tar") {
        zlog_info(zct, "update rfsbu.tar");
        sleep(3);
        zlog_info(zct, "strcmd = %s", param.fileName.c_str());
        int iRet = system("/opt/opt.sh");
        zlog_info(zct, "iRet = %d", iRet);
        if (iRet == -1) {
            zlog_error(zct, "system() error");
        }
    } else if (param.fileName == "update.json") {
        zlog_info(zct, "strcmd = %s", param.fileName.c_str());

        ReadStrConfig("/opt/update.json");
    } else if (param.fileName == "backup.json") {
        ImportConfig("/opt/backup.json");
    } else if (param.fileName == "DataNode.csv") {
        zlog_info(zct, "strcmd = %s", param.fileName.c_str());

        int iRet = UpdataDataNodeConfig("/opt/DataNode.csv");
        std::string str = std::to_string(iRet) + "个传感器更新成功";
        if (iRet < 0) {
            jsonVal["success"] = false;
            jsonVal["message"] = "更新失败!";
        } else {
            jsonVal["success"] = true;
            jsonVal["message"] = str;
        }

    }
    return show_value_.write(jsonVal);
}

std::string JsonData::JsonCmd_Cgi_31(Param_31 &param) {
    Json::Value jsonVal;
    jsonVal.clear();
    jsonVal["cmd"] = "31";
    if (0 == param.mMode) {
        WriteStr2Config(ZIGBEECONFIG, "Zigbee", "channel", param.mChannelId);
        WriteStr2Config(ZIGBEECONFIG, "Zigbee", "PanID", param.mPanID);
        char whereCon[1024] = {0};
		char updateSql[1024] = { 0 };
		sprintf(updateSql, "zigbeePanID = '%s',zigbeeChannel = '%s'",\
				param.mPanID.c_str(),param.mChannelId.c_str());
		sprintf(whereCon, "gatewayMAC='%s'", GlobalConfig::MacAddr_G.c_str());
		sqlite_db_ctrl::instance().UpdateTableData(T_GATEWAY_INFO(TNAME), updateSql, whereCon);
		system("reboot");
    }
    Json::Value jsBody;
    jsonVal["message"] = "设置完成";
    jsonVal["success"] = true;
    jsBody["channel"] = ReadStrByOpt(ZIGBEECONFIG, "Zigbee", "channel");
    jsBody["panID"] = GlobalConfig::ZigbeeInfo_G.PanID;
    jsBody["RetryNum"] = GlobalConfig::ZigbeeInfo_G.RetryNum;
    jsBody["TranTimeout"] = GlobalConfig::ZigbeeInfo_G.TranTimeout;
    jsBody["status"] = "1";
    jsonVal["content"] = jsBody;

    return show_value_.write(jsonVal);
}

std::string JsonData::JsonCmd_Cgi_32(Param_32 &param) {
    Json::Value jsonVal;
    jsonVal.clear();

    jsonVal["cmd"] = "32";
    jsonVal["success"] = true;
    jsonVal["message"] = "";
    Json::Value jsBody;
    std::string strWaveData;

    jsBody["channelId"] = param.mChannelId;
    jsBody["package"] = param.mPackageFlag;
    jsBody["Data"] = strWaveData;

    jsonVal["content"] = jsBody;
    return show_value_.write(jsonVal);
}

std::string JsonData::JsonCmd_Cgi_43() {
    Json::Value jsonVal;
    jsonVal.clear();
    jsonVal["success"] = true;
    jsonVal["message"] = "";
    return show_value_.write(jsonVal);
}
