#include "uart.hpp"
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <termios.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <boost/algorithm/string.hpp>
#include <zlog.h>
#include "common/common_func.hpp"
#include "minilzo/minilzo.h"
#include "scheduler/wave_feature_set.hpp"
#include "scheduler/schedule.hpp"

extern zlog_category_t* zct;
extern zlog_category_t* zbt;
#define IN_LEN      (128*1024ul)
#define OUT_LEN     (IN_LEN + IN_LEN / 16 + 64 + 3)
unsigned char fw_outdata[70000]={0};
unsigned char fw_senddata[70000]={0};

/* Work-memory needed for compression. Allocate memory in units
 * of 'lzo_align_t' (instead of 'char') to make sure it is properly aligned.
 */

/*#define HEAP_ALLOC(var,size) \
    lzo_align_t __LZO_MMODEL var [ ((size) + (sizeof(lzo_align_t) - 1)) / sizeof(lzo_align_t) ]

static HEAP_ALLOC(wrkmem, LZO1X_1_MEM_COMPRESS);*/

void Uart::openSwitch() {
    char buffer[100] = {0x00};
    int len;
    int fdSwitch = config_uart("/dev/ttymxc1", B38400);
    char strSend[8] = {0x01, 0x06, 0x00, 0x00, 0x00, 0x00, 0x89, 0xCA};
    len = write_data(fdSwitch, (char*)strSend, 8);
    sleep(1);
    len = read_data(fdSwitch, (char*)buffer, 100, 10);
    for (int i = 0; i < len; i++) zlog_info(zct, "%02X ", buffer[i] & 0xFF);
    char strSend2[8] = {0x01, 0x06, 0x00, 0x00, 0x00, 0x01, 0x48, 0x0A};
    len = write_data(fdSwitch, (char*)strSend2, 8);
    sleep(1);
    len = read_data(fdSwitch, (char*)buffer, 100, 10);
    for (int i = 0; i < len; i++) zlog_info(zct, "%02X ", buffer[i] & 0xFF);
    close(fdSwitch);
}

void Uart::UpdateWirelessNode(uint16_t shortAdd) {
    
    int upgrade_status = 2;
    char localtimestamp[32] = {0};
    GetTimeNet(localtimestamp, 1);
    char insertSql[100] = {0};
    char wherecon[512] = {0};
    sprintf(wherecon," short_Addr = '%02x%02x' and status = 3 and start_timestamp > ( SELECT MAX(submit_timestamp) FROM firmware_upgrade ) order by start_timestamp DESC",UINT16_HIGH(shortAdd), UINT16_LOW(shortAdd));
    std::string spend_count = sqlite_db_ctrl::instance().GetData(" firmware_upgrade ","spend_count",wherecon);
    //if (atoi(spend_count.c_str())  >= 12)
    {
        zlog_warn(zbt, "UpdateWirelessNode spend_count %d,shortAddr = %02x%02x", atoi(spend_count.c_str()), UINT16_HIGH(shortAdd), UINT16_LOW(shortAdd));
    }
    if (spend_count == "")spend_count = "0";
    
    memset(wherecon,0,sizeof(wherecon));
    sprintf(wherecon," short_Addr = '%02x%02x' order by submit_timestamp DESC",UINT16_HIGH(shortAdd), UINT16_LOW(shortAdd));
    std::string firmware_name = sqlite_db_ctrl::instance().GetData(" firmware_upgrade ","firmware_name",wherecon);
    memset(wherecon,0,sizeof(wherecon));
    sprintf(wherecon," zigbeeShortAddr = '%02x%02x' ",UINT16_HIGH(shortAdd), UINT16_LOW(shortAdd));
    vec_t vecResult = sqlite_db_ctrl::instance().GetDataSingleLine(T_SENSOR_INFO(TNAME), " hardVersion,softVersion,ProductNo,upgradeStatus ", wherecon);
    if(vecResult.size() < 1){
        return ;
    }
    if (vecResult[3] == "2"){
        zlog_warn(zbt, "UpdateWirelessNode already ,shortAddr = %02x%02x", UINT16_HIGH(shortAdd), UINT16_LOW(shortAdd));
        return;
    }
    
    std::string strTime = GetLocalTimeWithMs();
    zlog_warn(zbt, "UpdateWirelessNode start = %s UpdateWirelessNode id = %02x %02x", strTime.c_str(), UINT16_HIGH(shortAdd), UINT16_LOW(shortAdd));
    bUpdate = true;
    FILE* pFile = NULL;
    long unsigned int  thisSize = 0;
    long unsigned int out_len = 0;
    unsigned char* buffer = NULL;
    int compress = 0;
    memset(fw_outdata,0,sizeof(fw_outdata));
    memset(fw_senddata,0,sizeof(fw_senddata));
    DataNodeUpdateFile = "/opt/DataNode/" + firmware_name;
    zlog_info(zct, "strFileName = %s", DataNodeUpdateFile.c_str());
    pFile = fopen(DataNodeUpdateFile.c_str(), "rb");
    if (pFile != NULL) {
        while (fgetc(pFile) != EOF) {
            ++thisSize;
        }
        rewind(pFile);
        buffer = (unsigned char*)malloc(thisSize);
        fread(buffer, sizeof(unsigned char), thisSize, pFile);
        fclose(pFile);

        char sensor_type[6] = {0};
        char sf_version[10] = {0};
        memcpy(sensor_type, buffer, 5);
        printf("model:%s\n", 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\n",sf_ver_m);
        zlog_info(zct,"sf_ver_s = %d\n",sf_ver_s);
        zlog_info(zct,"hw_ver = %d\n",hw_ver);
        zlog_info(zct,"sensor_type = %s\n",sensor_type);
        zlog_info(zct,"packgeSize = %d\n",packgeSize);
        zlog_info(zct,"ch_crc = %02x\n",ch_crc);

        sprintf(insertSql, " '%02x%02x','','%s','','','%d','%d.%d','%s',1,''",UINT16_HIGH(shortAdd), UINT16_LOW(shortAdd),localtimestamp,atoi(spend_count.c_str()) + 1,sf_ver_m,sf_ver_s,vecResult[1].c_str());
        sqlite_db_ctrl::instance().InsertData(" firmware_upgrade ", insertSql);

        // int r = lzo1x_1_compress(buffer, thisSize, fw_outdata, &out_len, wrkmem);
        // if (r == LZO_E_OK){
        //     printf("compressed %lu bytes into %lu bytes\n",
        //     (unsigned long) thisSize, (unsigned long) out_len);
        //     if (out_len <  thisSize){
        //         zlog_warn(zct, "compressed %lu bytes into %lu bytes", (unsigned long)thisSize, (unsigned long)out_len);
        //         memcpy(fw_senddata,fw_outdata,out_len);
        //         thisSize = out_len;
        //         compress = 1;
        //     }
        // }
        // else
        // {
        //     /* this should NEVER happen */
        //     zlog_error(zct,"internal error - compression failed: %d", r);
        // }
        // /* check for an incompressible block */
        // if (out_len >= thisSize)
        // {
        //     zlog_warn(zct,"This block contains incompressible data.out_len = %lu,thisSize = %lu",out_len,thisSize);
        //     memcpy(fw_senddata,buffer,thisSize);
        // }
        //memcpy(fw_senddata,buffer,thisSize);
        unsigned char Data[100] = {0x00};
        unsigned char size[4] = {0x00};
        zlog_info(zct, "thisSize = %d", (int)thisSize);
        //帧头[3byte]	节点地址[2byte]	数据类型[1byte]	序号[1byte]	升级包大小[4byte]	CRC校验[1byte]
        Data[0] = 0xAA;
        Data[1] = 0x55;
        Data[2] = 0xAA;
        Data[3] = UINT16_HIGH(shortAdd);
        Data[4] = UINT16_LOW(shortAdd);
        Data[5] = 0x0C;
        Data[6] = 0x00;
        if (compress == 1){
            int2bytes(out_len, size, 4);
        }else{
            int2bytes(thisSize, size, 4);
        }
        Data[13] = size[0];
        Data[14] = size[1];
        Data[15] = size[2];
        Data[16] = size[3];
        Data[17] = compress & 0xFF;

        unsigned char tmp = 0x00;
        for (int i = 0; i < 100; i++) {
            tmp += Data[i];
        }
        Data[99] = tmp;
        sleep(1);
        WriteToUart((const char*)Data, 100);
        int iRet = CheckZigbeeACK();
        if (iRet == 0) {
            zlog_info(zct, "Packge ACK send success,shortAddr = %02x%02x", UINT16_HIGH(shortAdd), UINT16_LOW(shortAdd));
        } else {
            zlog_warn(zct, "Packge ACK send failed,shortAddr = %02x%02x", UINT16_HIGH(shortAdd), UINT16_LOW(shortAdd));
        }
        mssleep(50000);
        int Count = thisSize / 92;
        int lastSize = thisSize % 92;
        unsigned char UpdateData[100] = {0x00};
        //帧头[3byte]	节点地址[2byte]	数据类型[1byte]	序号[1byte]	数据包[92byte]	CRC校验[1byte]
        zlog_warn(zbt, "Start Upgrade!!! file Size = %d,fileName = %s,Count = %d,lastSize = %d,shortAddr = %02x%02x", (int)thisSize,DataNodeUpdateFile.c_str(),Count,lastSize,UINT16_HIGH(shortAdd), UINT16_LOW(shortAdd));
        tmp = 0x00;
        gpio_set(GlobalConfig::GPIO_G.zigAckreset, 0);
        mssleep(1000);
        gpio_set(GlobalConfig::GPIO_G.zigAckreset, 1);
        for(int j = 0; j < Count;j++){
            int time ,value;
            UpdateData[0]=0xAA;
            UpdateData[1]=0x55;
            UpdateData[2]=0xAA;
            UpdateData[3]=UINT16_HIGH(shortAdd);
            UpdateData[4]=UINT16_LOW(shortAdd);
            UpdateData[5]=0x10;
            UpdateData[6]=0xff & j;
            memcpy(&UpdateData[7],buffer + 92 * j,92);
            tmp = 0x00;
            for(int k = 0; k < 99;k++){
                tmp +=UpdateData[k];
            }
            UpdateData[99] = tmp;
            WriteToUart((const char*)UpdateData,100);
            if(gpio_read(GlobalConfig::GPIO_G.zigAckrep) == 48)
                gpio_set(GlobalConfig::GPIO_G.zigAckreset,1);
            time = 0;
            do{
                value = gpio_read(GlobalConfig::GPIO_G.zigAckrep);
                if(value == 49)
                    break;
                mssleep(10000);
                time += 1;
            }while(time < 150);
            if(time >= 150){
            	zlog_warn(zct, "gpio_read failed shortAdd %02x %02x,index = %d", UINT16_HIGH(shortAdd), UINT16_LOW(shortAdd),j);
				zlog_warn(zct, "gpio_read failed \n");
                scheduler::instance().UpgradeResult(shortAdd,kRecvDataLenError);
				bUpdate = false;
                upgrade_status = 3;
				goto endUpdate;
            }
            gpio_set(GlobalConfig::GPIO_G.zigAckreset,0);
            mssleep(2000);
            memset(UpdateData,0x00,sizeof(UpdateData));
            mssleep(5000);
        }
        if(gpio_read(GlobalConfig::GPIO_G.zigAckrep) == 48)
            gpio_set(GlobalConfig::GPIO_G.zigAckreset,1);

        if (lastSize > 0) {
            UpdateData[0] = 0xAA;
            UpdateData[1] = 0x55;
            UpdateData[2] = 0xAA;
            UpdateData[3] = UINT16_HIGH(shortAdd);
            UpdateData[4] = UINT16_LOW(shortAdd);
            UpdateData[5] = 0x10;
            UpdateData[6] = 0xff & Count;
            memcpy(&UpdateData[7], buffer + 92 * Count, lastSize);
            tmp = 0x00;
            for (int k = 0; k < 99; k++) {
                tmp += UpdateData[k];
            }
            UpdateData[99] = tmp;
            WriteToUart((const char*)UpdateData, 100);
            mssleep(1000);
            int time = 0;
            do{
                int value = gpio_read(GlobalConfig::GPIO_G.zigAckrep);
                if(value == 49){
                    gpio_set(GlobalConfig::GPIO_G.zigAckreset,0);
                    mssleep(10000);
                    if(gpio_read(GlobalConfig::GPIO_G.zigAckrep) == 48){
                        gpio_set(GlobalConfig::GPIO_G.zigAckreset,1);
                        break;
                    }
                }
                mssleep(10000);
                time += 1;
            }while(time < 150);
            if (time >= 150) {
                zlog_warn(zct, "gpio_read failed shortAdd %02x %02x", UINT16_HIGH(shortAdd), UINT16_LOW(shortAdd));
                zlog_warn(zct, "gpio_read failed \n");
                scheduler::instance().UpgradeResult(shortAdd,kRecvDataLenError);
                bUpdate = false;
                upgrade_status = 3;
                goto endUpdate;
            }
            memset(UpdateData, 0x00, sizeof(UpdateData));
        }
        zlog_warn(zct, "Update END!!! file Size = %d", (int)thisSize);
    } else {
        zlog_warn(zct, "open file failed ");
    }
endUpdate:
    char localtimestamp_end[32] = {0};
    GetTimeNet(localtimestamp_end, 1);
    char updateSql[1024] = { 0 };
    memset(wherecon,0,sizeof(wherecon));
    sprintf(wherecon," start_timestamp = '%s' and short_addr = '%02x%02x'",localtimestamp,UINT16_HIGH(shortAdd), UINT16_LOW(shortAdd));
    sprintf(updateSql, " end_timestamp = '%s',spend_time = %ld,status = %d",localtimestamp_end,atol(localtimestamp_end)-atol(localtimestamp), upgrade_status);
    sqlite_db_ctrl::instance().UpdateTableData(" firmware_upgrade ", updateSql,wherecon);

    free(buffer);
    tcflush(fd, TCIFLUSH);
    sleep(1);
    bUpdate = false;
    bSendTimeStamp = false;
    DataNodeUpdateFile = "";
    zlog_warn(zbt, "UpdateWirelessNode end,shortAddr = %02x%02x",UINT16_HIGH(shortAdd), UINT16_LOW(shortAdd));
}

int Uart::UpdateConfig(uint16_t ushortAdd) {
    char whereCon[64] = {0};
    char selCon[1024] = {0x00};
    sprintf(whereCon, "zigbeeShortAddr='%02x%02x'", UINT16_HIGH(ushortAdd),UINT16_LOW(ushortAdd));

    vec_t vecResultNode = sqlite_db_ctrl::instance().GetDataSingleLine(T_SENSOR_INFO(TNAME), "*", whereCon);
    if (vecResultNode.size() <= 0) return -1;
    
    zlog_warn(zct, "UpdateConfig ushortAdd = %02x%02x",UINT16_HIGH(ushortAdd),UINT16_LOW(ushortAdd));
    GlobalConfig::EnterZigBeeWaveTransmittingFlag_G = ENTER_TRANSMITTING_STATUS;
    GlobalConfig::EnterZigBeeWaveTransmittingCnt_G = 0;

    char tmpbuf[8] = {0x00};
    sprintf(tmpbuf, "%02x%02x", UINT16_HIGH(ushortAdd),UINT16_LOW(ushortAdd));
    m_strDestShortAddr = std::string(tmpbuf);

    mssleep(500);
    vec_t vecResult;
    sprintf(selCon, "featureInterVal,waveInterVal,range,samplingRate,ACCSampleTime,startBrands,stopBrands,\
            envelopeBandPass,faultFrequency,timeStamp,viff,ZigbeePower,ZigbeeRetry,MeasurementID,NodeWaveSend");
    vecResult = sqlite_db_ctrl::instance().GetDataSingleLine(T_SENSOR_INFO(TNAME), selCon, whereCon);
    zlog_info(zct, "vecResult size = %d", vecResult.size());
    if (vecResult.size() < 1) {
        return -1;
    }
    unsigned char UpdateData[100] = {0x00};
    //帧头[3byte]	节点地址[2byte]	数据类型[1byte]	序号[1byte]	数据包[92byte]	CRC校验[1byte]
    UpdateData[0] = 0xAA;
    UpdateData[1] = 0x55;
    UpdateData[2] = 0xAA;
    UpdateData[3] = UINT16_HIGH(ushortAdd);
    UpdateData[4] = UINT16_LOW(ushortAdd);
    UpdateData[5] = 0x0A;
    UpdateData[6] = 0x00;
    UpdateData[7] = 0x01;
    UpdateData[8] = UINT16_LOW(atoi(vecResult[0].c_str()));
    UpdateData[9] = UINT16_HIGH(atoi(vecResult[1].c_str()));
    UpdateData[10] = UINT16_LOW(atoi(vecResult[1].c_str()));
    int y = 0;
    if (vecResultNode[17] == "01") {
        if (vecResult[3] == "3200") {
            y = 0;
        } else if (vecResult[3] == "6400") {
            y = 1;
        } else if (vecResult[3] == "12800") {
            y = 2;
        } else if (vecResult[3] == "25600") {
            y = 3;
        }
    } else if (vecResultNode[17] == "02") {
        if (vecResult[3] == "8000") {
            y = 0;
        } else if (vecResult[3] == "16000") {
            y = 1;
        } else if (vecResult[3] == "24000") {
            y = 2;
        } else if (vecResult[3] == "32000") {
            y = 3;
        } else if (vecResult[3] == "48000") {
            y = 4;
        } else if (vecResult[3] == "96000") {
            y = 5;
        } else if (vecResult[3] == "192000") {
            y = 6;
        }
    }
    UpdateData[18] = atoi(vecResult[11].c_str()) & 0xFF;
    UpdateData[19] = atoi(vecResult[12].c_str()) & 0xFF;
    int x = atoi(vecResult[2].c_str());
    UpdateData[21] = BUILD_UINT2(x, y);
    UpdateData[22] = atoi(vecResult[4].c_str()) & 0xFF;
    zlog_info(zct, "vecResult size = %s==%s==%s==%s=%s\n", vecResult[5].c_str(), vecResult[6].c_str(), vecResult[7].c_str(), vecResult[8].c_str(), vecResult[14].c_str());
    std::vector<std::string> vStart, vStop, vEnvelopeBandPass, vfaultFrequency, vNodeWaveSend;
    boost::split(vStart, vecResult[5], boost::is_any_of(","), boost::token_compress_on);
    boost::split(vStop, vecResult[6], boost::is_any_of(","), boost::token_compress_on);
    boost::split(vEnvelopeBandPass, vecResult[7], boost::is_any_of(","), boost::token_compress_on);
    boost::split(vfaultFrequency, vecResult[8], boost::is_any_of(","), boost::token_compress_on);
    if (vecResult[14] != "") boost::split(vNodeWaveSend, vecResult[14], boost::is_any_of(","), boost::token_compress_on);

    UpdateData[23] = UINT16_HIGH(atoi(vStart[0].c_str()));
    UpdateData[24] = UINT16_LOW(atoi(vStart[0].c_str()));
    UpdateData[25] = UINT16_HIGH(atoi(vStop[0].c_str()));
    UpdateData[26] = UINT16_LOW(atoi(vStop[0].c_str()));

    UpdateData[27] = UINT16_HIGH(atoi(vStart[1].c_str()));
    UpdateData[28] = UINT16_LOW(atoi(vStart[1].c_str()));
    UpdateData[29] = UINT16_HIGH(atoi(vStop[1].c_str()));
    UpdateData[30] = UINT16_LOW(atoi(vStop[1].c_str()));

    UpdateData[31] = UINT16_HIGH(atoi(vStart[2].c_str()));
    UpdateData[32] = UINT16_LOW(atoi(vStart[2].c_str()));
    UpdateData[33] = UINT16_HIGH(atoi(vStop[2].c_str()));
    UpdateData[34] = UINT16_LOW(atoi(vStop[2].c_str()));

    UpdateData[35] = UINT16_HIGH(atoi(vStart[3].c_str()));
    UpdateData[36] = UINT16_LOW(atoi(vStart[3].c_str()));
    UpdateData[37] = UINT16_HIGH(atoi(vStop[3].c_str()));
    UpdateData[38] = UINT16_LOW(atoi(vStop[3].c_str()));

    UpdateData[39] = UINT16_HIGH(atoi(vStart[4].c_str()));
    UpdateData[40] = UINT16_LOW(atoi(vStart[4].c_str()));
    UpdateData[41] = UINT16_HIGH(atoi(vStop[4].c_str()));
    UpdateData[42] = UINT16_LOW(atoi(vStop[4].c_str()));

    UpdateData[43] = UINT16_HIGH(atoi(vEnvelopeBandPass[0].c_str()));
    UpdateData[44] = UINT16_LOW(atoi(vEnvelopeBandPass[0].c_str()));
    UpdateData[45] = UINT16_HIGH(atoi(vEnvelopeBandPass[1].c_str()));
    UpdateData[46] = UINT16_LOW(atoi(vEnvelopeBandPass[1].c_str()));

    UpdateData[47] = UINT16_HIGH(atoi(vfaultFrequency[0].c_str()));
    UpdateData[48] = UINT16_LOW(atoi(vfaultFrequency[0].c_str()));
    UpdateData[49] = UINT16_HIGH(atoi(vfaultFrequency[1].c_str()));
    UpdateData[50] = UINT16_LOW(atoi(vfaultFrequency[1].c_str()));

    UpdateData[51] = UINT16_HIGH(atoi(vfaultFrequency[2].c_str()));
    UpdateData[52] = UINT16_LOW(atoi(vfaultFrequency[2].c_str()));
    UpdateData[53] = UINT16_HIGH(atoi(vfaultFrequency[3].c_str()));
    UpdateData[54] = UINT16_LOW(atoi(vfaultFrequency[3].c_str()));

    UpdateData[55] = UINT32_HIGH_1(atoi(vecResult[9].c_str()));
    UpdateData[56] = UINT32_HIGH_2(atoi(vecResult[9].c_str()));
    UpdateData[57] = UINT32_LOW_1(atoi(vecResult[9].c_str()));
    UpdateData[58] = UINT32_LOW_2(atoi(vecResult[9].c_str()));

    UpdateData[59] = (atoi(vecResult[10].c_str())) & 0xFF;

    size_t bytesSize = strlen(vecResult[13].c_str()) / 2;
    unsigned char* bytes = (unsigned char*)malloc(bytesSize);

    if (hexStringToBytes(vecResult[13].c_str(), bytes, bytesSize) == 0) {
        UpdateData[60] = bytes[0];
        UpdateData[61] = bytes[1];
        UpdateData[62] = bytes[2];
        UpdateData[63] = bytes[3];
        UpdateData[64] = bytes[4];
        UpdateData[65] = bytes[5];
        UpdateData[66] = bytes[6];
        UpdateData[67] = bytes[7];
    }
    unsigned char byte = 0;
    if (vNodeWaveSend.size() > 0) {
        if (vNodeWaveSend[0] == "0") {
            Binary_Bit(&byte, 0, 0);
        }
        if (vNodeWaveSend[0] == "1") {
            Binary_Bit(&byte, 0, 1);
        }
        if (vNodeWaveSend[1] == "0") {
            Binary_Bit(&byte, 1, 0);
        }
        if (vNodeWaveSend[1] == "1") {
            Binary_Bit(&byte, 1, 1);
        }
        if (vNodeWaveSend[2] == "0") {
            Binary_Bit(&byte, 2, 0);
        }
        if (vNodeWaveSend[2] == "1") {
            Binary_Bit(&byte, 2, 1);
        }
    }
    UpdateData[68] = byte;
    free(bytes);
    unsigned char tmp1 = 0x00;
    for (int k = 0; k < 99; k++) {
        tmp1 += UpdateData[k];
    }
    UpdateData[99] = tmp1;
    tcflush(fd, TCIFLUSH);
    WriteToUart((const char*)UpdateData, 100);
    int iRet = CheckZigbeeACK();
    if (iRet == 0) {
        zlog_info(zct, "updateconfig ACK send success,shortAddr = %02x%02x", UINT16_HIGH(ushortAdd),UINT16_LOW(ushortAdd));
    } else {
        zlog_warn(zct, "updateconfig ACK send failed,shortAddr = %02x%02x", UINT16_HIGH(ushortAdd),UINT16_LOW(ushortAdd));
    }

    mssleep(50000);
    std::string strName = sqlite_db_ctrl::instance().GetData(T_SENSOR_INFO(TNAME), " dataNodeName ", whereCon);

    memset(UpdateData,0x00,sizeof(UpdateData));
    //帧头[3byte]	节点地址[2byte]	数据类型[1byte]	序号[1byte]	数据包[92byte]	CRC校验[1byte]
    UpdateData[0] = 0xAA;
    UpdateData[1] = 0x55;
    UpdateData[2] = 0xAA;
    UpdateData[3] = UINT16_HIGH(ushortAdd);
    UpdateData[4] = UINT16_LOW(ushortAdd);
    UpdateData[5] = 0x0A;
    UpdateData[6] = 0x01;
    char hex[200] = {0x00};
    stringToHex(strName.c_str(), hex);
    bytesSize = strlen(hex) / 2;
    bytes = (unsigned char*)malloc(bytesSize);

    if (hexStringToBytes(hex, bytes, bytesSize) != 0) {
        free(bytes);
    } else {
        for (size_t i = 0; i < bytesSize; i++) {
            UpdateData[7 + i] = bytes[i];
        }
        free(bytes);
        unsigned char tmp1 = 0x00;
        for (int k = 0; k < 99; k++) {
            tmp1 += UpdateData[k];
        }
        UpdateData[99] = tmp1;
        tcflush(fd, TCIFLUSH);
        WriteToUart((const char*)UpdateData, 100);
        int iRet = CheckZigbeeACK();
        if (iRet == 0) {
            zlog_info(zct, "updataname ACK send success,shortAddr = %02x%02x", UINT16_HIGH(ushortAdd),UINT16_LOW(ushortAdd));
        } else {
            zlog_warn(zct, "updataname ACK send failed,shortAddr = %02x%02x", UINT16_HIGH(ushortAdd),UINT16_LOW(ushortAdd));
        }
        return 0;
    }
    return 0;
    
}

int Uart::UpdateWirelessNodeTime(unsigned char* pDestShortAddr, int modifyaddr /*,int nodewaveindex,int nodetime,int nodeindex*/) {
    if (modifyaddr) modify_DistAddr(pDestShortAddr);
    mssleep(10000);

    char localtimestamp[32] = {0x00};
    int millisecond = 0;

    std::string rtcTime = GetRTC(localtimestamp, millisecond);
    zlog_info(zct, "ShortAddr  = %02x%02x,rtcTime = %s,localtimestamp = %s,millisecond = %d,bSendTimeStamp = %d ", pDestShortAddr[0], pDestShortAddr[1], rtcTime.c_str(), localtimestamp, millisecond, bSendTimeStamp);

    unsigned char UpdateData[100] = {0x00};
    UpdateData[0] = 0xAA;
    UpdateData[1] = 0x55;
    UpdateData[2] = 0xAA;
    UpdateData[3] = pDestShortAddr[0];
    UpdateData[4] = pDestShortAddr[1];
    UpdateData[5] = 0x23;
    UpdateData[6] = 0x00;
    UpdateData[7] = 0x00;
    UpdateData[8] = UINT32_LOW_2(atol(localtimestamp));
    UpdateData[9] = UINT32_LOW_1(atol(localtimestamp));
    UpdateData[10] = UINT32_HIGH_2(atol(localtimestamp));
    UpdateData[11] = UINT32_HIGH_1(atol(localtimestamp));
    UpdateData[12] = UINT16_LOW(millisecond);
    UpdateData[13] = UINT16_HIGH(millisecond);

    unsigned char tmp = 0x00;
    for (int k = 0; k < 99; k++) {
        tmp += UpdateData[k];
    }
    UpdateData[99] = tmp;
    WriteToUart((const char*)UpdateData, 100);
    int iRet = CheckZigbeeACK();
    if (iRet == 0) {
        zlog_info(zct, "NodeTime ACK send success,shortAddr = %02x%02x", pDestShortAddr[0], pDestShortAddr[1]);
    } else {
        zlog_warn(zct, "NodeTime ACK send failed,shortAddr = %02x%02x", pDestShortAddr[0], pDestShortAddr[1]);
    }
    return iRet;
}
int Uart::TaskResp(ScheduleTask scheduleTask){

    memset(send_data,0,sizeof(send_data));
    send_data[0] = 0xAA;
    send_data[1] = 0x55;
    send_data[2] = 0xAA;
    send_data[3] = (scheduleTask.shortAddr >> 8) & 0xFF;
    send_data[4] = scheduleTask.shortAddr & 0xFF;
    send_data[5] = scheduleTask.cmd & 0xFF;
    send_data[6] = 0x00;
    char localtimestamp[32] = {0x00};
    int millisecond = 0;
    std::string rtcTime = GetRTC(localtimestamp, millisecond);
    if (rtcTime == "")
    {
        GetTimeNet(localtimestamp, 1);
    }
    
    scheduleTask.timeStamp = atoi(localtimestamp);
    zlog_info(zct,"next taskID = %d\n",scheduleTask.next_taskID);

    send_data[7] = UINT16_LOW(scheduleTask.duration);
    send_data[8] = UINT16_HIGH(scheduleTask.duration);
    send_data[9]  = UINT32_LOW_2(scheduleTask.timeStamp);
    send_data[10] = UINT32_LOW_1(scheduleTask.timeStamp);
    send_data[11] = UINT32_HIGH_2(scheduleTask.timeStamp);
    send_data[12] = UINT32_HIGH_1(scheduleTask.timeStamp);
    send_data[20] = scheduleTask.acc_z;
    send_data[21] = scheduleTask.next_taskID & 0xFF;
    send_data[22] = UINT16_LOW(scheduleTask.millisecond);
    send_data[23] = UINT16_HIGH(scheduleTask.millisecond);

    if (scheduleTask.next_taskID == WAVE_CMD)
    {
        uint8_t x = 0,y = 0,z = 1;
        if (scheduleTask.z)
        {
            x = 1;
            y = 1;
            z = 0;
        }
        zlog_info(zct,"wave x = %d,y = %d,z = %d,scheduleTask.z = %d\n",x,y,z,scheduleTask.z);
        send_data[17] = x;
        send_data[18] = y;
        send_data[19] = z;
    }
    unsigned char tmp = 0x00;
    for (int k = 0; k < 99; k++) {
        tmp += send_data[k];
    }
    send_data[99] = tmp;
    if (scheduleTask.cmd == REVIVE_DURATION)
    {
        map_send_data[scheduleTask.shortAddr] = std::vector<uint8_t>(send_data, send_data + 100);
    }
    mssleep(50000);
    WriteToUart((const char*)send_data, 100);
    mssleep(50000);
    WriteToUart((const char*)send_data, 100);
    mssleep(50000);
    WriteToUart((const char*)send_data, 100);
    
    int iRet = CheckZigbeeACK();
    if (iRet == 0) {
        zlog_info(zct, "TaskResp ACK send success,shortAddr = %02x%02x", UINT16_HIGH(scheduleTask.shortAddr),UINT16_LOW(scheduleTask.shortAddr));
    } else {
        zlog_warn(zct, "TaskResp ACK send failed,shortAddr = %02x%02x", UINT16_HIGH(scheduleTask.shortAddr),UINT16_LOW(scheduleTask.shortAddr));
    }
    return iRet;
}
int Uart::SendReviveDuration(ReviveDuration recvDuration){

    unsigned char UpdateData[100] = {0};
    UpdateData[0] = 0xAA;
    UpdateData[1] = 0x55;
    UpdateData[2] = 0xAA;
    UpdateData[3] = (recvDuration.shortAddr >> 8) & 0xFF;
    UpdateData[4] = recvDuration.shortAddr & 0xFF;
    UpdateData[5] = recvDuration.cmd;
    UpdateData[6] = 0x00;
    UpdateData[7] = (recvDuration.duration >> 8) & 0xFF; 
    UpdateData[8] = recvDuration.duration & 0xFF;

    unsigned char tmp = 0x00;
    for (int k = 0; k < 99; k++) {
        tmp += UpdateData[k];
    }
    UpdateData[99] = tmp;
    WriteToUart((const char*)UpdateData, 100);
    int iRet = CheckZigbeeACK();
    if (iRet == 0) {
        zlog_info(zct, "SendReviveDuration ACK send success,shortAddr = %d", recvDuration.shortAddr);
    } else {
        zlog_warn(zct, "SendReviveDuration ACK send failed,shortAddr = %d", recvDuration.shortAddr);
    }
    return iRet;
}
int Uart::WaveResp(uint16_t shortAddr){
    unsigned char sendData[8] = {0};
    sendData[0] = 0xAA;
    sendData[1] = 0x55;
    sendData[2] = 0xAA;
    sendData[3] = (shortAddr >> 8) & 0xFF;
    sendData[4] = shortAddr & 0xFF;
    sendData[5] = 0x12;
    sendData[6] = 0x00;
    unsigned char tmp = 0x00;
    for (int k = 0; k < 7; k++) {
        tmp += sendData[k];
    }
    sendData[7] = tmp;
    WriteToUart((const char*)sendData, 8);
    mssleep(50000);
    WriteToUart((const char*)sendData, 8);
    mssleep(50000);
    WriteToUart((const char*)sendData, 8);
    int iRet = CheckZigbeeACK();
    if (iRet == 0) {
        zlog_info(zct, "WaveResp ACK send success,shortAddr = %x", shortAddr);
    } else {
        zlog_warn(zct, "WaveResp ACK send failed,shortAddr = %x", shortAddr);
    }
    return iRet;
}
int Uart::CheckZigbeeACK() {
    if (gpio_read(GlobalConfig::GPIO_G.zigAckrep) == 48) gpio_set(GlobalConfig::GPIO_G.zigAckreset, 1);
    int time = 0, value = 0, iRet = -1;
    do {
        value = gpio_read(GlobalConfig::GPIO_G.zigAckrep);
        if (value == 49) {
            iRet = 0;
            break;
        }
        time += 1;
        mssleep(10000);
    } while (time < 150);
    return iRet;
}
