#include <fstream>
#include "zlog.h"

#include "communication_cmd.hpp"
#include "localserver/local_server.hpp"
#include "common/common_func.hpp"
#include "common/global.hpp"
#include <boost/algorithm/string.hpp>
#include "dbaccess/sql_db.hpp"
#include "scheduler/schedule.hpp"
#include "localserver/cmt_server.hpp"

extern zlog_category_t *zct;

void JsonData::CmtCmd_80(char* send_data,int& send_length)
{
    zlog_info(zct,"CmtCmd_80");
    GatewayVersion gateway_ver;
    gateway_ver.version = 1;
    memcpy(gateway_ver.mac,GlobalConfig::MacAddr_G.c_str(),sizeof(gateway_ver.mac));
    memcpy(gateway_ver.web_ver,ReadStrByOpt(SYSTEMINFOFILE, "Version", "WebVersion").c_str(),sizeof(gateway_ver.web_ver));
    memcpy(gateway_ver.system_ver,ReadStrByOpt(SYSTEMINFOFILE, "Version", "SystemVersion").c_str(),sizeof(gateway_ver.system_ver));
    memcpy(gateway_ver.gateway_ver,ReadStrByOpt(SYSTEMINFOFILE, "Version", "GateWayVersion").c_str(),sizeof(gateway_ver.gateway_ver));
    memcpy(gateway_ver.ip,GlobalConfig::IpAddr_G.c_str(),sizeof(gateway_ver.ip));
    memcpy(gateway_ver.gateway_type,ReadStrByOpt(SYSTEMINFOFILE, "Version", "GateWayProduct").c_str(),sizeof(gateway_ver.gateway_type));
    memcpy(gateway_ver.gateway_hw_ver,ReadStrByOpt(SYSTEMINFOFILE, "Version", "GateWayHwVesion").c_str(),sizeof(gateway_ver.gateway_hw_ver));
    memcpy(gateway_ver.comm_mode,"以太网",sizeof(gateway_ver.comm_mode));
#ifdef  NR5G_MODULE
    memset(gateway_ver.comm_mode,0,sizeof(gateway_ver.comm_mode));
    memcpy(gateway_ver.comm_mode,"5G",sizeof(gateway_ver.comm_mode));
#endif
#ifdef  Q4G_MODULE
    memset(gateway_ver.comm_mode,0,sizeof(gateway_ver.comm_mode));
    memcpy(gateway_ver.comm_mode,"4G",sizeof(gateway_ver.comm_mode));
#endif
#ifdef  WIFI_MODULE
    memset(gateway_ver.comm_mode,0,sizeof(gateway_ver.comm_mode));
    memcpy(gateway_ver.comm_mode,"WiFi",sizeof(gateway_ver.comm_mode));
#endif
    
    std::string gatewayLocation = sqlite_db_ctrl::instance().GetData(T_GATEWAY_INFO(TNAME), "gatewayLocation", NULL);
    memcpy(gateway_ver.terminal_name,gatewayLocation.c_str(),sizeof(gateway_ver.terminal_name));
    GetSysStatusCMT(gateway_ver.cpu_use,gateway_ver.memory_use,gateway_ver.disk_remain,gateway_ver.temperature);
    memcpy(send_data,&gateway_ver,sizeof(GatewayVersion));
    send_length = sizeof(GatewayVersion);
}

void JsonData::CmtCmd_81(char* recv_body,int& count,char* send_data,int& send_length)
{
    int featureInterVal;
    int waveInterVal;
    int waveResendNum;
    int maxSensorNum;
    int sensorCount;
    array_t arrRes;
    char whereCon[512]={0};
    if (recv_body != NULL)
    {
        printf("count = %d\n",count);
        char short_addr_[256]={0};
        for (int i = 0; i < count; i++){
            char temp[5]={0};
            memcpy(temp,recv_body + i * 4,4);
            printf("short_addr = %s\n",temp);
            strcat(short_addr_,"'");
            strcat(short_addr_,temp);
            strcat(short_addr_,"'");
            if (i + 1 != count){
                strcat(short_addr_  ,",");
            }
        }
        sprintf(whereCon,"zigbeeShortAddr IN (%s)",short_addr_);
        arrRes = sqlite_db_ctrl::instance().GetDataMultiLineTransaction(T_SENSOR_INFO(TNAME), "*", whereCon);
    }else{
        arrRes = sqlite_db_ctrl::instance().GetDataMultiLineTransaction(T_SENSOR_INFO(TNAME), "*", NULL);
    }
    int iResult = arrRes.size();
    printf("result = %d\n",iResult);
    int j = 0;
    if (iResult > 0) {
        SensorInfo sensor_info[iResult];
        for (; j < iResult; j++)
        {
            memcpy(sensor_info[j].sensor_name,arrRes[j][1].c_str(),sizeof(sensor_info[j].sensor_name));
            memcpy(sensor_info[j].measurement_id,arrRes[j][44].c_str(),sizeof(sensor_info[j].measurement_id));
            memcpy(sensor_info[j].short_addr , arrRes[j][30].c_str(),sizeof(sensor_info[j].short_addr));
            memcpy(sensor_info[j].hw_ver,arrRes[j][8].c_str(),sizeof(sensor_info[j].hw_ver));
            memcpy(sensor_info[j].soft_ver,arrRes[j][9].c_str(),sizeof(sensor_info[j].soft_ver));
            std::vector<std::string> vParamRSSI;
            boost::split(vParamRSSI, arrRes[j][40], boost::is_any_of(","), boost::token_compress_on);
            if (vParamRSSI.size() > 1) {
                sensor_info[j].gateway_rssi = (atof(vParamRSSI[0].c_str())/255) * 100;
                sensor_info[j].sensor_rssi = (atof(vParamRSSI[1].c_str())/255) * 100;
            } else {
                sensor_info[j].gateway_rssi = (atof(vParamRSSI[0].c_str())/255) * 100;
                sensor_info[j].sensor_rssi = 99;
            }
            std::vector<std::string> vParambattery;
            boost::split(vParambattery, arrRes[j][43], boost::is_any_of(","), boost::token_compress_on);
            if (vParambattery.size() > 1) {
                sensor_info[j].battry = (atof(vParambattery[1].c_str())/atof(vParambattery[0].c_str())) * 100;
            } else {
                sensor_info[j].battry = 99;
            }
            std::vector<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"){
                    sensor_info[j].loose_status = 1;
                }else{
                    sensor_info[j].loose_status = 0;
                }  
            }
            char whereCon[256]={0x00};
            sprintf(whereCon,"dataNodeNo = '%s'",arrRes[j][44].c_str());
            vec_t vecRes = sqlite_db_ctrl::instance().GetDataSingleLine(T_DATASTATIC_INFO(TNAME), "temTop,temBot",whereCon);
            if (vecRes.size() > 0)
            {
                sensor_info[j].temperature_top = atoi(vecRes[0].c_str());
                sensor_info[j].temperature_bot = atoi(vecRes[1].c_str());
            }else{
                sensor_info[j].temperature_top = 200;
                sensor_info[j].temperature_bot  = 200;
            }
            
            memcpy(sensor_info[j].product,arrRes[j][17].c_str(),sizeof(sensor_info[j].product));
            if (arrRes[j][17] == "01"){
                memcpy(sensor_info[j].product,"DN101",sizeof(sensor_info[j].product));
            }else if (arrRes[j][17] == "02"){
                memcpy(sensor_info[j].product,"DN102",sizeof(sensor_info[j].product));
            }  
            sensor_info[j].status = atoi(arrRes[j][37].c_str());

            char szTableName[100] = {0x00};
            memset(whereCon,0,sizeof(whereCon));
            sprintf(szTableName, " t_data_waveSend ");
            const char *sql = 
        	" timestamp >= strftime('%s', 'now', '-1 day', 'start of day','utc') "
        	"AND timestamp < strftime('%s', 'now', '-1 day','start of day','utc','+24 hours') ";
            sprintf(whereCon," and channelID = '%s-X'",arrRes[j][44].c_str());
			std::string	strsql = std::string(sql) + std::string(whereCon);
			int waveX_Count = sqlite_db_ctrl::instance().GetTableRows(szTableName,strsql.c_str());

            memset(whereCon,0,sizeof(whereCon));
            sprintf(whereCon," and channelID = '%s-Y'",arrRes[j][44].c_str());
			strsql = std::string(sql) + std::string(whereCon);
			int waveY_Count = sqlite_db_ctrl::instance().GetTableRows(szTableName,strsql.c_str());

            memset(whereCon,0,sizeof(whereCon));
            sprintf(whereCon," and channelID = '%s-Z'",arrRes[j][44].c_str());
			strsql = std::string(sql) + std::string(whereCon);
			int waveZ_Count = sqlite_db_ctrl::instance().GetTableRows(szTableName,strsql.c_str());
            zlog_info(zct,"wave x = %d,wave y = %d,wave z  = %d",waveZ_Count,waveY_Count,waveZ_Count);
            memset(whereCon,0,sizeof(whereCon));
            memset(szTableName,0,sizeof(szTableName));
            sprintf(szTableName, " t_dataStatic_%s ",arrRes[j][44].c_str());
            sprintf(whereCon," and channelID = '%s-S'",arrRes[j][44].c_str());
			strsql = std::string(sql) + std::string(whereCon);
			int static_Count = sqlite_db_ctrl::instance().GetTableRows(szTableName,strsql.c_str());

            scheduler::instance().GetScheduleConfig(featureInterVal,waveInterVal,waveResendNum,maxSensorNum);
            zlog_info(zct,"wavex = %d,featureInterVal = %d,waveInterVal = %d",waveX_Count,featureInterVal,waveInterVal);
            int day_count = 86400 / waveInterVal;
            
            sensor_info[j].wave_x_reporting_rate = (float( waveX_Count)/(86400/waveInterVal)) * 100;
            sensor_info[j].wave_y_reporting_rate = (float(waveY_Count)/(86400/waveInterVal)) * 100;
            sensor_info[j].wave_z_reporting_rate = (float(waveZ_Count)/(86400/waveInterVal)) * 100;
            sensor_info[j].eigen_value_reporting_rate = (float(static_Count)/(86400/featureInterVal)) * 100;
            day_count = 86400 / featureInterVal;
            printf("static_Count = %d,day_count = %d,wave_x_reporting_rate = %d\n",static_Count,day_count,sensor_info[j].eigen_value_reporting_rate );

            memset(whereCon,0,sizeof(whereCon));
            sprintf(whereCon,"channelID = '%s-Z'",arrRes[j][44].c_str());
            std::string integratRMS = sqlite_db_ctrl::instance().GetData(T_DATA_INFO(TNAME), "integratRMS",whereCon);

            sensor_info[j].velocity_rms  =  atof(integratRMS.c_str());
            sensor_info[j].upgrade_status = atoi(arrRes[j][46].c_str());
            memset(whereCon,0,sizeof(whereCon));
            sprintf(whereCon,"short_addr = '%s' ORDER BY start_timestamp DESC limit 0,1",arrRes[j][30].c_str());
            std::string upgrade_time = sqlite_db_ctrl::instance().GetData("firmware_upgrade", " start_timestamp ", whereCon);
            memcpy(sensor_info[j].upgrade_time,upgrade_time.c_str(),sizeof(sensor_info[j].upgrade_time));
            sensor_info[j].version = 1;
        }   
        memcpy(send_data ,(char*)&sensor_info[0],sizeof(SensorInfo) * j);
        send_length = sizeof(SensorInfo) * j;
        zlog_info(zct,"sizeof(SensorInfo) = %d",sizeof(SensorInfo)*j);
        zlog_info(zct,"send_length = %d",send_length);
    }
    
}

void JsonData::CmtCmd_82(char* MeasurementID,char* send_data,int& channel,int& send_length)
{
    FILE* pFile = NULL;
    char* buffer = NULL;
    int  thisSize = 32;
    WaveRes wave;
    char whereCon[64]={0};
    sprintf(whereCon,"MeasurementID = '%s'",MeasurementID);
    vec_t vecRes = sqlite_db_ctrl::instance().GetDataSingleLine(T_SENSOR_INFO(TNAME), "samplingRate,ACCSampleTime",whereCon);
    std::string strChannel = "";

    if (channel == 1){
        strChannel = "X";
    }else if(channel == 2){
        strChannel = "Y";
    }else if (channel == 3){
        strChannel = "Z";
    }
    std::string data_file = "/opt/data/" + std::string(MeasurementID) + "-" + strChannel + ".dat";
    zlog_info(zct, "strFileName = %s", data_file.c_str());
    
    pFile = fopen(data_file.c_str(), "rb");
    if (pFile != NULL) {
        while (fgetc(pFile) != EOF) {
            ++thisSize;
        }
        rewind(pFile);
        fseek(pFile, 32, SEEK_SET);//跳过32个字节的时间戳
        buffer = (char*)malloc(thisSize - 32);
        fread(buffer, sizeof(char), thisSize - 32, pFile);
        fclose(pFile);

		wave.sampling_rate = atoi(vecRes[0].c_str());
		wave.sampling_time = atoi(vecRes[1].c_str());
		wave.version = 1;
		send_length = sizeof(WaveRes) + thisSize - 32;
		memcpy(send_data,(char*)&wave,sizeof(WaveRes));
		memcpy(send_data + sizeof(WaveRes) ,buffer,thisSize - 32);
		free(buffer);
    }
}

void JsonData::CmtCmd_83(char* recv_body,int& count,char* send_data,int& send_length)
{
    array_t arrRes;
    std::string filename = "";
    char whereCon[512]={0};
    if (recv_body){
        printf("count = %d\n",count);
        char MeasurementID_[256]={0};
        for (int i = 0; i < count; i++){
            char temp[21]={0};
            memcpy(temp,recv_body + i * 20,20);
            printf("short_addr = %s\n",temp);
            strcat(MeasurementID_,"'");
            strcat(MeasurementID_,temp);
            strcat(MeasurementID_,"'");
            if (i + 1 != count){
                strcat(MeasurementID_  ,",");
            }
        }
        sprintf(whereCon,"MeasurementID IN (%s)",MeasurementID_);
        arrRes = sqlite_db_ctrl::instance().GetDataMultiLineTransaction(T_SENSOR_INFO(TNAME), "*", whereCon);
    }else{
        arrRes = sqlite_db_ctrl::instance().GetDataMultiLineTransaction(T_SENSOR_INFO(TNAME), "*", NULL);
    }
    if (arrRes.size() > 0){
        std::string current_time = GetLocalTimeWithMs();
        filename = "/opt/DataNode/config_" + GlobalConfig::MacAddr_G +  "_" + std::string(current_time)+ ".csv";
        std::ofstream csvFile(filename);
        if (!csvFile.is_open()) {
            std::cerr << "Error: Could not open file " << filename << std::endl;
            return;
        }
         // 写入 CSV 标题行
        csvFile << "GW MAC,Product,IP,PanID,Signal Channel,Terminal Name,SN,Sensor MAC,Measurement ID,"
                "Short Addr,Sensor Name,Update Date,Gateway RSSI,Sensor RSSI,HW Ver,Soft Ver,Sampling Rate,"
                "Range,Sampling Time,VIFF,Power,Retry Time\n";
        for (int i = 0; i < count; i++)
        {
            DownloadConfig download_config;
            memcpy(download_config.gw_mac,GlobalConfig::MacAddr_G.c_str(),sizeof(download_config.gw_mac));
            if (arrRes[i][17] == "01"){
                memcpy(download_config.product,"DN101",sizeof(download_config.product));
            }else if (arrRes[i][17] == "02"){
                memcpy(download_config.product,"DN102",sizeof(download_config.product));
            }  
            memcpy(download_config.ip,GlobalConfig::IpAddr_G.c_str(),sizeof(download_config.ip));
            download_config.panid = atoi(arrRes[i][28].c_str());
            download_config.signal_channle = atoi(arrRes[i][29].c_str());
            memcpy(download_config.terminal_name,"",sizeof(download_config.terminal_name));
            memcpy(download_config.sn,arrRes[i][11].c_str(),sizeof(download_config.sn));
            memcpy(download_config.sensor_mac,arrRes[i][0].c_str(),sizeof(download_config.sensor_mac));
            memcpy(download_config.measurement_id,arrRes[i][44].c_str(),sizeof(download_config.measurement_id));
            download_config.short_addr = atoi(arrRes[i][30].c_str());
            memcpy(download_config.sensor_name,arrRes[i][1].c_str(),sizeof(download_config.sensor_name));
            memcpy(download_config.update_date,arrRes[i][38].c_str(),sizeof(download_config.update_date));
            std::vector<std::string> vParamRSSI;
            boost::split(vParamRSSI, arrRes[i][40], boost::is_any_of(","), boost::token_compress_on);
            if (vParamRSSI.size() > 1) {
                download_config.gateway_rssi = (atof(vParamRSSI[0].c_str())/255) * 100;
                download_config.sensor_rssi = (atof(vParamRSSI[1].c_str())/255) * 100;
            } else {
                download_config.gateway_rssi =  (atof(vParamRSSI[0].c_str())/255) * 100;
                download_config.sensor_rssi = 99;
            }
            memcpy(download_config.hw_ver,arrRes[i][8].c_str(),sizeof(download_config.hw_ver));
            memcpy(download_config.soft_ver,arrRes[i][9].c_str(),sizeof(download_config.soft_ver));
            download_config.sampling_rate = atoi(arrRes[i][23].c_str());
            download_config.range = atoi(arrRes[i][25].c_str());
            download_config.sampling_time = atoi(arrRes[i][36].c_str());
            download_config.viff = atoi(arrRes[i][39].c_str());
            download_config.power = atoi(arrRes[i][33].c_str());
            download_config.retry_time = atoi(arrRes[i][34].c_str());
            
            csvFile << download_config.gw_mac << ',' << download_config.product << ','<< download_config.ip << ',' << download_config.panid << ','
                    << download_config.signal_channle << ','<< download_config.terminal_name << ','<< download_config.sn << ','<< download_config.sensor_mac << ','
                    << download_config.measurement_id << ','<< download_config.short_addr << ','<< download_config.sensor_name << ','<< download_config.update_date << ','
                    << download_config.gateway_rssi << ','<< download_config.sensor_rssi << ','<< download_config.hw_ver << ','<< download_config.soft_ver << ','
                    << download_config.sampling_rate << ','<< download_config.range << ','<< download_config.sampling_time << ','<< download_config.viff << ','
                    << download_config.power << ','<< download_config.retry_time << '\n' ;
        }
        csvFile.close();
        std::cout << "CSV file written to " << filename << std::endl;
    }
    send_length = sizeof(DownloadConfigRes);
    DownloadConfigRes download_condfig_res;
    download_condfig_res.version = 1;
    memcpy(download_condfig_res.filename,filename.c_str(),sizeof(download_condfig_res.filename));
    memcpy(send_data,(char*)&download_condfig_res,sizeof(DownloadConfigRes));
    zlog_info(zct, "cmd 83 send_length = %d",send_length);
    
}

void  JsonData::CmtCmd_84(char* filename,char* file_md5,char* send_data,int& send_length)
{ 
    std::vector<DataNodeInfo> vecDataNode;
    UploadConfigRes upload_condfig_res;
    upload_condfig_res.code = 0;
    upload_condfig_res.version = 1;
    sprintf(upload_condfig_res.message ,"%s","");
    send_length = sizeof(UploadConfigRes);
    char file_path[64]={0}; 
    char cmd[128]={0};
    sprintf(cmd, "mv /opt/%s /opt/DataNode/",filename);
    system(cmd);
    sprintf(file_path, "/opt/DataNode/%s",filename);
    if(get_file_md5(file_path) != std::string(file_md5))
    {
        zlog_error(zct, "file md5 error = %s",file_path);
        upload_condfig_res.code = 1;
        sprintf(upload_condfig_res.message ,"%s","");
        memcpy(send_data,(char*)&upload_condfig_res,sizeof(UploadConfigRes));
        return ;
    }
    std::ifstream csv_data(file_path, std::ios::in);
    int iRet = 0;
    if (!csv_data.is_open()) {
        zlog_error(zct, "UpdataDataNodeConfig fail to open:%s", file_path);
    } 
    std::string line;
    std::vector<std::string> words; 
    std::string word;

    DataNodeInfo dataNode;
    getline(csv_data, line);

    std::istringstream sin;    
    while (getline(csv_data, line)) {
        words.clear();
        sin.clear();
        sin.str(line);
        while (getline(sin, word, ',')) {           
            words.push_back(word);
        }
        std::string mac = words[0];
        if (mac != GlobalConfig::MacAddr_G) {
            iRet = -2;
            break;
        }
        dataNode.ZigbeeLongAddr = words[7];
        dataNode.ZigbeeShortAddr = words[9];
        dataNode.SamplingRate = atoi(words[16].c_str());        
        dataNode.Range = atoi(words[17].c_str()); 
        dataNode.ACCSampleTime = atoi(words[18].c_str());
        dataNode.VIntegralFilterFrequency = atoi(words[19].c_str());
        dataNode.ZigbeePower = atoi(words[20].c_str());
        dataNode.ZigbeeRetry = atoi(words[21].c_str());
        vecDataNode.push_back(dataNode);
    }
    csv_data.close();    
    if (vecDataNode.size() == 0) {
        zlog_error(zct, "UpdataDataNodeConfig vecDataNode is 0");
        upload_condfig_res.code = 2;
        sprintf(upload_condfig_res.message ,"%s","upgrade sensor is 0");
        memcpy(send_data,(char*)&upload_condfig_res,sizeof(UploadConfigRes));
        return ;
    }    
    
    char whereCon[1024] = {0};
    char updateSql[1024] = {0};    
    for (size_t i = 0; i < vecDataNode.size(); i++) {
        sprintf(updateSql, "range='%d',samplingRate='%d',AccSampleTime = '%d',viff ='%d' ,ZigbeePower = '%d',ZigbeeRetry = '%d',UpdateFlag = 0", vecDataNode[i].Range,
                vecDataNode[i].SamplingRate, vecDataNode[i].ACCSampleTime, vecDataNode[i].VIntegralFilterFrequency, vecDataNode[i].ZigbeePower, vecDataNode[i].ZigbeeRetry);
        sprintf(whereCon, "dataNodeNo='%s'", vecDataNode[i].ZigbeeLongAddr.c_str());

        iRet = sqlite_db_ctrl::instance().UpdateTableData(T_SENSOR_INFO(TNAME), updateSql, whereCon);
        if (iRet != 0) {
            zlog_error(zct, "UpdataDataNodeConfig UpdateTableData fail");
        }
        uint16_t short_addr;
        char *end_ptr = NULL;
        short_addr = strtol(vecDataNode[i].ZigbeeShortAddr.c_str(), &end_ptr, 16);
        scheduler::instance().UpdateSensorConfig(short_addr);

        memset(whereCon, 0x00, sizeof(whereCon));
        memset(updateSql, 0x00, sizeof(updateSql));
    }      
    
    memcpy(send_data,(char*)&upload_condfig_res,sizeof(UploadConfigRes));
    zlog_info(zct, "cmd 84 send_length = %d",send_length);
}

void  JsonData::CmtCmd_85(char* filename,char* file_md5,char* send_data,int& send_length)
{
    zlog_info(zct,"filename = %s,file_md5 = %s",filename,file_md5);
    char file_path[64]={0};
    sprintf(file_path, "/opt/%s",filename);
    if(get_file_md5(file_path) != std::string(file_md5))
    {
        zlog_error(zct, "file md5 error = %s",file_path);
        return ;
    }
    sleep(3);
    int iRet = system("/opt/opt.sh");
    zlog_info(zct, "iRet = %d", iRet);
    if (iRet == -1) {
        zlog_error(zct, "system() error");
    }
}

void  JsonData::CmtCmd_86(char* recv_body,int& count,char* filename,char* file_md5,char* send_data,int& send_length)
{
    zlog_info(zct,"filename = %s,file_md5 = %s",filename,file_md5);
    
    UpgradeSensorRes upgrade_sensor_res;
    upgrade_sensor_res.code = 0;
    upgrade_sensor_res.version = 1;
    sprintf(upgrade_sensor_res.message ,"%s","");
    send_length = sizeof(UpgradeSensorRes);
    char cmd[128]={0};
    char file_path[64]={0};
    sprintf(cmd, "mv /opt/%s /opt/DataNode/",filename);
    system(cmd);
    sprintf(file_path, "/opt/DataNode/%s",filename);
    if(get_file_md5(file_path) != std::string(file_md5))
    {
        upgrade_sensor_res.code = 1;
        sprintf(upgrade_sensor_res.message ,"%s","file md5 error");
        memcpy(send_data,(char*)&upgrade_sensor_res,sizeof(DownloadConfigRes));
        return ;
    }
    FILE * pFile=NULL;
    size_t thisSize = 0;
    char *buffer=NULL;
    pFile = fopen (file_path,"rb");
    if (pFile==NULL) {
        zlog_error(zct,"Error opening file");
    }
    else
    {
        while (fgetc(pFile) != EOF) {
            ++thisSize;
        }
        rewind(pFile);
        buffer = (char*)malloc(thisSize);
        fread (buffer, sizeof (char), thisSize, pFile);
        fclose (pFile);
    }
    zlog_info(zct,"Read %zu bytes", thisSize);
    char sensor_type[6] = {0};
    char sf_version[10] = {0};
    memcpy(sensor_type, buffer, 5);
    zlog_info(zct,"model:%s", sensor_type);
    char c[2] = {0};
    c[0] = buffer[5];
    uint8_t hw_ver = atoi(c);
    c[0] = buffer[6];
    uint8_t sf_ver_m = atoi(c);
    c[0] = buffer[7];
    uint8_t sf_ver_s = atoi(c);
    sprintf(sf_version,"%d.%d",sf_ver_m,sf_ver_s);
    unsigned char ch_crc = 0x00;
    int packgeSize = 0;
    ch_crc = buffer[12];
    packgeSize = BUILD_UINT32(buffer[8],buffer[9],buffer[10],buffer[11]);
    zlog_info(zct,"sf_ver_m = %d",sf_ver_m);
    zlog_info(zct,"sf_ver_s = %d",sf_ver_s);
    zlog_info(zct,"hw_ver = %d",hw_ver);
    zlog_info(zct,"sensor_type = %s",sensor_type);
    zlog_info(zct,"packgeSize = %d",packgeSize);
    zlog_info(zct,"ch_crc = %02x",ch_crc);
    unsigned char sum = 0x00;
    for(size_t i = 13; i < thisSize;i++){
        sum += buffer[i];
    }
    if (sum % 256 != ch_crc){
        zlog_error(zct,"package CRC error,filename = %s",file_path);
        upgrade_sensor_res.code = 2;
        sprintf(upgrade_sensor_res.message ,"%s","package CRC error");
        memcpy(send_data,(char*)&upgrade_sensor_res,sizeof(DownloadConfigRes));
        return;
    }
    zlog_info(zct,"sum = %x\n",sum % 256);
    char localtimestamp[32] = {0};
    GetTimeNet(localtimestamp, 1);
    std::vector<UpgradeParameter> param_list;
    for (size_t i = 0; i < count; i++)
    {
        UpgradeParameter upgrade_parameter;
        char wherecon[100] = {0};
        char insertSql[200] = {0};
        char updateSql[100] = {0};
        char short_addr_[21] = {0};
        memcpy(short_addr_,recv_body + i * 4,4);
        sprintf(wherecon," zigbeeShortAddr = '%s' ",short_addr_);
        vec_t vecResult = sqlite_db_ctrl::instance().GetDataSingleLine(T_SENSOR_INFO(TNAME), " hardVersion,softVersion,ProductNo,zigbeeShortAddr ", wherecon);
        if (hw_ver != atoi(vecResult[0].c_str())){
            zlog_error(zct,"hardVersion error,filename = %s",file_path);
            upgrade_sensor_res.code = 2;
            sprintf(upgrade_sensor_res.message ,"%s","hardVersion error");
            memcpy(send_data,(char*)&upgrade_sensor_res,sizeof(DownloadConfigRes));
            return;
        }
        sprintf(insertSql, " '%s','%s','','','','','%d.%d','%s',1,'%s'",vecResult[3].c_str(),localtimestamp,sf_ver_m,sf_ver_s,vecResult[1].c_str(),filename);
        sqlite_db_ctrl::instance().InsertData(" firmware_upgrade ", insertSql);
        //0 默认状态，1 升级中，2 升级成功,3 升级失败,4 停止升级
        memset(wherecon,0,sizeof(wherecon));
        memset(updateSql,0,sizeof(updateSql));
        sprintf(wherecon," zigbeeShortAddr =  '%s'",vecResult[3].c_str());
        sprintf(updateSql, " upgradeStatus = %d ", 1);
        sqlite_db_ctrl::instance().UpdateTableData(T_SENSOR_INFO(TNAME), updateSql,wherecon);
        uint16_t short_addr;
        char *end_ptr = NULL;
        short_addr = strtol(vecResult[3].c_str(), &end_ptr, 16);
        upgrade_parameter.short_addr = short_addr;
        upgrade_parameter.sensor_type = std::string(sensor_type);
        upgrade_parameter.hw_version = atoi(vecResult[0].c_str());
        upgrade_parameter.current_sw_version = vecResult[1];
        upgrade_parameter.upgrade_sw_version = std::string(sf_version);
        param_list.push_back(upgrade_parameter);
    }    
    int res = scheduler::instance().UpgradeSensor(param_list);
    free(buffer);
}
void  JsonData::CmtCmd_87(char* MeasurementID,char* send_data,int& send_length)
{
    array_t arrRes;
    char whereCon[128] = {};
    sprintf(whereCon, "channelID like '%%%s%%' ORDER BY timeStamp DESC  LIMIT 0,3", MeasurementID);
    arrRes = sqlite_db_ctrl::instance().GetDataMultiLineTransaction(T_DATA_INFO(TNAME), "*", whereCon);
    int iResult = arrRes.size();
    if (iResult > 0) {
        int j = 0;
        GetEigenvalueRes get_eigenvalue_res[iResult];
        for (; j < iResult; j++) {
            get_eigenvalue_res[j].version = 1;
            if(arrRes[j][1] == (std::string(MeasurementID) +"-X")){
                get_eigenvalue_res[j].channel = 1;
            }else if (arrRes[j][1] == (std::string(MeasurementID) +"-Y")){
                get_eigenvalue_res[j].channel = 2;
            }else if (arrRes[j][1] == (std::string(MeasurementID) +"-Z")){
                get_eigenvalue_res[j].channel = 3;
            }
            printf("channle = %d\n",get_eigenvalue_res[j].channel);
            get_eigenvalue_res[j].DiagnosisPk = atof(arrRes[j][2].c_str());
            get_eigenvalue_res[j].IntegratPk = atof(arrRes[j][3].c_str());
            get_eigenvalue_res[j].IntegratRMS = atof(arrRes[j][4].c_str());
            get_eigenvalue_res[j].RmsValues = atof(arrRes[j][5].c_str());
            get_eigenvalue_res[j].EnvelopEnergy = atof(arrRes[j][6].c_str());
            get_eigenvalue_res[j].Amp1 = atof(arrRes[j][7].c_str());
            get_eigenvalue_res[j].Amp2 = atof(arrRes[j][8].c_str());
            get_eigenvalue_res[j].Amp3 = atof(arrRes[j][9].c_str());
            get_eigenvalue_res[j].Amp4 = atof(arrRes[j][10].c_str());
            get_eigenvalue_res[j].Amp5 = atof(arrRes[j][11].c_str());
            get_eigenvalue_res[j].Phase1 = atof(arrRes[j][12].c_str());
            get_eigenvalue_res[j].Phase2 = atof(arrRes[j][13].c_str());
            get_eigenvalue_res[j].Phase3 = atof(arrRes[j][14].c_str());
            get_eigenvalue_res[j].Phase4 = atof(arrRes[j][15].c_str());
            get_eigenvalue_res[j].Time = atoi(arrRes[j][17].c_str());
        }
        memcpy(send_data,(char*)get_eigenvalue_res,sizeof(GetEigenvalueRes) * j);
        send_length = sizeof(GetEigenvalueRes) * j;
    }
}
void  JsonData::CmtCmd_88(char* recv_body,int& count,char* send_data,int& send_length)
{
    if (recv_body != NULL)
    {
        char wherecon[512] = {0};
        char updateSql[100] = {0};
        printf("count = %d\n",count);
        char short_addr_[256]={0};
        for (int i = 0; i < count; i++){
            char temp[5]={0};
            memcpy(temp,recv_body + i * 4,4);
            uint16_t short_addr;
            char *end_ptr = NULL;
            short_addr = strtol(temp, &end_ptr, 16);
            scheduler::instance().UpgradeResult(short_addr,kUpgradeSuccess);

            printf("short_addr = %s\n",temp);
            strcat(short_addr_,"'");
            strcat(short_addr_,temp);
            strcat(short_addr_,"'");
            if (i + 1 != count){
                strcat(short_addr_  ,",");
            }
        }
        sprintf(updateSql, " upgradeStatus = %d ", 4);     
        sprintf(wherecon,"zigbeeShortAddr IN (%s)",short_addr_);
        sqlite_db_ctrl::instance().UpdateTableData(T_SENSOR_INFO(TNAME), updateSql,wherecon);
        UpgradeStopRes upgrade_stop_res;
        upgrade_stop_res.code = 0;
        upgrade_stop_res.version = 1;
        sprintf(upgrade_stop_res.message ,"%s","");
        memcpy(send_data,(char*)&upgrade_stop_res,sizeof(UpgradeStopRes));
        send_length = sizeof(UpgradeStopRes);
    }
}


