#include "main.h"
#define PRINT_TIME_TAG
#define DBG_TAG "main"
#define DBG_LVL DBG_INFO
#include "debug_print.h"

pthread_t pt_uart_send;
pthread_t pt_uart_recv_ack;
pthread_t pt_uart_recv_data;
pthread_t pt_uart_recv_back;
pthread_t pt_mqtt_recv;
pthread_t pt_readqr;
pthread_t pt_reporttag;
pthread_t pt_mqtt;
pthread_t pt_removelog;
pthread_t pt_watchdog;
pthread_t pt_removeduplicatetag;
pthread_t pt_keycheck;
uart_utils_t uartSend = {0};
uart_utils_t uartRecvData = {0};
uart_utils_t uartRecvBack = {0};
mqtt_parm_t mqtt_parm={0};
mqtt_utils_t mqtt_config;
struct input_event buff;

bool newappDownloaded=false;
bool isLightOn=false;
bool isLightOnById=false;
bool isLightOnByGroup=false;
bool isBindTag=false;
bool isSendComEnd=true;
bool isStopBroadcast=false;
bool isStopBroadcastBegin=false;
bool isOtaEnable=false;
jt_only_tag_t onlyTags[200]={0};
int tagCount=0;
int lightbars_size=0;
int lightbars_count=0;
uint8_t changecolor=0;
uint8_t changesound=0;
uint8_t groupno=0;
int fd;
int UPCASE=0;
int count_value=0;
int getPayloadTime=100*1000;//usecond
char softwareVersion[16]="2.1.2";
char stationsn[16]="d126ei4lj4cc00";//TJ250995217957
char productid[8]="10045";
char appKey[32]="fdhQmhqhvbL1cf1K9mUqt";
char appSecret[64]="s3izIliw0CF48Pcsi16rjOmoFRf5WEt8";
char mqttRawPassword[64]="";
char input_value[1024]={0};//94b4e39caf1d45ee9a071d701cc037b4
char input_value_copy[1024]={0};
char *getDevRegisterStatusUrl="https://gaea-zt-express.com/device/modifyRegisterInfo";
char *updateUrl="https://idata-creat.oss-cn-shenzhen.aliyuncs.com/jd_ota.zip";
char *getDevRawPasswordUrl="https://gaea.zt-express.com/device/modifyRegisterInfo";
char *hostDomain="emqx.thingtalk.jdl.com";
char lightsn1[7]={0};
char lightsn2[7]={0};
char lightsn3[7]={0};
char lightsn4[7]={0};
char lightsn5[7]={0};
char lightsn6[7]={0};
char lightsn7[7]={0};
char lightsn8[7]={0};
char lightsn9[7]={0};
char lightsn10[7]={0};
char lightsn11[7]={0};
char lightsn12[7]={0};
char lightsn13[7]={0};
char lightsn14[7]={0};
char lightsn15[7]={0};
char lightsn16[7]={0};
char lightsn17[7]={0};
char lightsn18[7]={0};
char lightsn19[7]={0};
char lightsn20[7]={0};
char lightsn21[7]={0};
char lightsn22[7]={0};
char lightsn23[7]={0};
char lightsn24[7]={0};
char lightsn25[7]={0};
char lightsn26[7]={0};
char lightsn27[7]={0};
char lightsn28[7]={0};
char lightsn29[7]={0};
char lightsn30[7]={0};
int lightsnNum=0;
int mqtt_port=2000;
/*================================================================================*/
void doCommand_help(int argc, char *argv[])
{
    printf("************************************************************\r\n"\
           "all commands are case insensitive\r\n"\
           "help                            print this message\r\n"\
           "SND [01-60]                     set sound S01-S60\r\n"\
           "************************************************************\r\n");
}

void doCommand(int argc, char *argv[])
{
    //sendData(argv[1],argv[0]);
}

__command_initialize("RON", doCommand);
__command_initialize("help",doCommand_help);

/*================================================================================*/
void do_removelog(void)
{ 
    LOG_I("%s\n",__func__);
    FILE *fp; 
    char buffer[5]; 
    char syscmd[32]; 
    int logcount=0;
 
    fp=popen("ls Log.*|wc -l", "r"); 
    fgets(buffer,sizeof(buffer),fp); 
    logcount=atoi(buffer);
    LOG_I("logcount:%d\n",logcount); 
    if(logcount>=3){
        sprintf(syscmd,"ls Log.*|head -%d|xargs rm -fr",logcount-2);
        LOG_I("%s\n",syscmd); 
        system(syscmd);
    }else{
        LOG_I("logcount less than 3,not remove\n");
    }
}

void removeLog(){
    int len=0;
    char *savedtime=NULL;
    char nowtime[16]={0};
    long now=0;
    long saved=0;

    while(1){
        now=getCurrentTime();
        sprintf(nowtime,"%ld",now);
        savedtime=file_to_buffer("logTime",&len);
        if(savedtime==NULL){
            buffer_to_file("logTime",nowtime,strlen(nowtime),"wb");
            savedtime=file_to_buffer("logTime",&len);
        }
        saved=atol(savedtime);
        LOG_I("now=%ld,saved=%ld,nowtime=%s,savedtime=%s\n",now,saved,nowtime,savedtime); 
        if(now-saved>=(60*60*24*5)){
        //if(now-saved>=10){
            buffer_to_file("logTime",nowtime,strlen(nowtime),"wb");
            do_removelog();
        }
        sleep(60*60*1);
    }
}

void enableWatchDog(){
    system("echo 1 > /sys/class/gpio/export");//watchdog enable pin SGM820
    system("echo 112 > /sys/class/gpio/export");//feed watchdog pin red 
    system("echo out > /sys/class/gpio/gpio1/direction");
    system("echo out > /sys/class/gpio/gpio112/direction");
    system("echo 1 > /sys/class/gpio/gpio1/value");
    LOG_I("enable watchdog\n");
    system("echo 1 > /sys/class/gpio/gpio112/value");
}

void feedWatchDog(){
    while(1){
        //LOG_I("feed watchdog\n");
        system("echo 0 > /sys/class/gpio/gpio112/value");
        usleep(100*1000);
        system("echo 1 > /sys/class/gpio/gpio112/value");
        sleep(1);
    }
}

void report_tag(void){
    while(1){
        sleep(60*11);
        LOG_I("report_tag\n");
        light_status_report(); 
    }
}

int readQrcode()
{
    fd = open("/dev/input/event2", O_RDONLY);
    if (fd < 0)
    {
        LOG_I("can not open scanner input event2!\n");
        goto error;
    }

    while (1)
    {
        while (read(fd, &buff, sizeof(struct input_event)) == 0)
        {
            ;
        }
        if (buff.type == EV_KEY){
            if(buff.value==0){
#if 0
                LOG_I("type:%d code:%d value:%d\n", buff.type, buff.code, buff.value);
#else
                switch(buff.code){
                    case 2:
                        if(UPCASE==1){
                            input_value[count_value]='!';
                        }else{
                            input_value[count_value]='1';
                        }
                        UPCASE=0;
                        count_value++;
                    break;
                    case 3:
                        if(UPCASE==1){
                            input_value[count_value]='@';
                        }else{
                            input_value[count_value]='2';
                        }
                        UPCASE=0;
                        count_value++;
                    break;
                    case 4:
                        if(UPCASE==1){
                            input_value[count_value]='#';
                        }else{
                            input_value[count_value]='3';
                        }
                        UPCASE=0;
                        count_value++;
                    break;
                    case 5:
                        if(UPCASE==1){
                            input_value[count_value]='$';
                        }else{
                            input_value[count_value]='4';
                        }
                        UPCASE=0;
                        count_value++;
                    break;
                    case 6:
                        if(UPCASE==1){
                            input_value[count_value]='%';
                        }else{
                            input_value[count_value]='5';
                        }
                        UPCASE=0;
                        count_value++;
                    break;
                    case 7:
                        if(UPCASE==1){
                            input_value[count_value]='^';
                        }else{
                            input_value[count_value]='6';
                        }
                        UPCASE=0;
                        count_value++;
                    break;
                    case 8:
                        if(UPCASE==1){
                            input_value[count_value]='&';
                        }else{
                            input_value[count_value]='7';
                        }
                        UPCASE=0;
                        count_value++;
                    break;
                    case 9:
                        if(UPCASE==1){
                            input_value[count_value]='*';
                        }else{
                            input_value[count_value]='8';
                        }
                        UPCASE=0;
                        count_value++;
                    break;
                    case 10:
                        if(UPCASE==1){
                            input_value[count_value]='(';
                        }else{
                            input_value[count_value]='9';
                        }
                        UPCASE=0;
                        count_value++;
                    break;
                    case 11:
                        if(UPCASE==1){
                            input_value[count_value]=')';
                        }else{
                            input_value[count_value]='0';
                        }
                        UPCASE=0;
                        count_value++;
                    break;
                    case 12:
                        if(UPCASE==1){
                            input_value[count_value]='_';
                        }else{
                            input_value[count_value]='-';
                        }
                        UPCASE=0;
                        count_value++;
                    break;
                    case 13:
                        if(UPCASE==1){
                            input_value[count_value]='+';
                        }else{
                            input_value[count_value]='=';
                        }
                        UPCASE=0;
                        count_value++;
                    break;
                    case 16:
                        if(UPCASE==1){
                            input_value[count_value]='Q';
                        }else{
                            input_value[count_value]='q';
                        }
                        UPCASE=0;
                        count_value++;
                    break;
                    case 17:
                        if(UPCASE==1){
                            input_value[count_value]='W';
                        }else{
                            input_value[count_value]='w';
                        }
                        UPCASE=0;
                        count_value++;
                    break;
                    case 18:
                        if(UPCASE==1){
                            input_value[count_value]='E';
                        }else{
                            input_value[count_value]='e';
                        }
                        UPCASE=0;
                        count_value++;
                    break;
                    case 19:
                        if(UPCASE==1){
                            input_value[count_value]='R';
                        }else{
                            input_value[count_value]='r';
                        }
                        UPCASE=0;
                        count_value++;
                    break;
                    case 20:
                        if(UPCASE==1){
                            input_value[count_value]='T';
                        }else{
                            input_value[count_value]='T';
                        }
                        UPCASE=0;
                        count_value++;
                    break;
                    case 21:
                        if(UPCASE==1){
                            input_value[count_value]='Y';
                        }else{
                            input_value[count_value]='y';
                        }
                        UPCASE=0;
                        count_value++;
                    break;
                    case 22:
                        if(UPCASE==1){
                            input_value[count_value]='U';
                        }else{
                            input_value[count_value]='u';
                        }
                        UPCASE=0;
                        count_value++;
                    break;
                    case 23:
                        if(UPCASE==1){
                            input_value[count_value]='I';
                        }else{
                            input_value[count_value]='i';
                        }
                        UPCASE=0;
                        count_value++;
                    break;
                     case 24:
                        if(UPCASE==1){
                            input_value[count_value]='O';
                        }else{
                            input_value[count_value]='o';
                        }
                        UPCASE=0;
                        count_value++;
                    break;
                    case 25:
                        if(UPCASE==1){
                            input_value[count_value]='P';
                        }else{
                            input_value[count_value]='p';
                        }
                        UPCASE=0;
                        count_value++;
                    break;
                    case 26:
                        if(UPCASE==1){
                            input_value[count_value]='{';
                        }else{
                            input_value[count_value]='[';
                        }
                        UPCASE=0;
                        count_value++;
                    break;
                    case 27:
                        if(UPCASE==1){
                            input_value[count_value]='}';
                        }else{
                            input_value[count_value]=']';
                        }
                        UPCASE=0;
                        count_value++;
                    break;
                    case 28:
                        input_value[count_value]='\0';
                        //LOG_I("%s\n",input_value);
                        memset(input_value_copy,0,1024);
                        memcpy(input_value_copy,input_value,1024);
                        memset(input_value,0,1024);
                        count_value=0;
                        int ret=-1;
                        pthread_t pt_handleqrcode;
                        ret = pthread_create(&pt_handleqrcode,NULL,actHandleQrcode,input_value_copy);
                        if(ret!=0){
                            LOG_I("pthread_create handleqrcode fail\n");
                            system("reboot");
                        }else{
                            pthread_detach(pt_handleqrcode);
                        }
                    break;
                    case 30:
                        if(UPCASE==1){
                            input_value[count_value]='A';
                        }else{
                            input_value[count_value]='a';
                        }
                        UPCASE=0;
                        count_value++;
                    break;
                    case 31:
                        if(UPCASE==1){
                            input_value[count_value]='S';
                        }else{
                            input_value[count_value]='s';
                        }
                        UPCASE=0;
                        count_value++;
                    break;
                    case 32:
                        if(UPCASE==1){
                            input_value[count_value]='D';
                        }else{
                            input_value[count_value]='d';
                        }
                        UPCASE=0;
                        count_value++;
                    break;
                    case 33:
                        if(UPCASE==1){
                            input_value[count_value]='F';
                        }else{
                            input_value[count_value]='f';
                        }
                        UPCASE=0;
                        count_value++;
                    break;
                    case 34:
                        if(UPCASE==1){
                            input_value[count_value]='G';
                        }else{
                            input_value[count_value]='g';
                        }
                        UPCASE=0;
                        count_value++;
                    break;
                    case 35:
                        if(UPCASE==1){
                            input_value[count_value]='H';
                        }else{
                            input_value[count_value]='h';
                        }
                        UPCASE=0;
                        count_value++;
                    break;
                    case 36:
                        if(UPCASE==1){
                            input_value[count_value]='J';
                        }else{
                            input_value[count_value]='j';
                        }
                        UPCASE=0;
                        count_value++;
                    break;
                    case 37:
                        if(UPCASE==1){
                            input_value[count_value]='K';
                        }else{
                            input_value[count_value]='k';
                        }
                        UPCASE=0;
                        count_value++;
                    break;
                    case 38:
                        if(UPCASE==1){
                            input_value[count_value]='L';
                        }else{
                            input_value[count_value]='l';
                        }
                        UPCASE=0;
                        count_value++;
                    break;
                    case 39:
                        if(UPCASE==1){
                            input_value[count_value]=':';
                        }else{
                            input_value[count_value]=';';
                        }
                        UPCASE=0;
                        count_value++;
                    break;
                    case 40:
                        if(UPCASE==1){
                            input_value[count_value]='"';
                        }else{
                            input_value[count_value]='\'';
                        }
                        UPCASE=0;
                        count_value++;
                    break;
                    case 42:
                        UPCASE=1;
                    break;
                    case 43:
                        if(UPCASE==1){
                            input_value[count_value]='|';
                        }else{
                            input_value[count_value]='\\';
                        }
                        UPCASE=0;
                        count_value++;
                    break;
                    case 44:
                        if(UPCASE==1){
                            input_value[count_value]='Z';
                        }else{
                            input_value[count_value]='z';
                        }
                        UPCASE=0;
                        count_value++;
                    break;
                    case 45:
                        if(UPCASE==1){
                            input_value[count_value]='X';
                        }else{
                            input_value[count_value]='x';
                        }
                        UPCASE=0;
                        count_value++;
                    break;
                    case 46:
                        if(UPCASE==1){
                            input_value[count_value]='C';
                        }else{
                            input_value[count_value]='c';
                        }
                        UPCASE=0;
                        count_value++;
                    break;
                    case 47:
                        if(UPCASE==1){
                            input_value[count_value]='V';
                        }else{
                            input_value[count_value]='v';
                        }
                        UPCASE=0;
                        count_value++;
                    break;
                    case 48:
                        if(UPCASE==1){
                            input_value[count_value]='B';
                        }else{
                            input_value[count_value]='b';
                        }
                        UPCASE=0;
                        count_value++;
                    break;
                    case 49:
                        if(UPCASE==1){
                            input_value[count_value]='N';
                        }else{
                            input_value[count_value]='n';
                        }
                        UPCASE=0;
                        count_value++;
                    break;
                    case 50:
                        if(UPCASE==1){
                            input_value[count_value]='M';
                        }else{
                            input_value[count_value]='m';
                        }
                        UPCASE=0;
                        count_value++;
                    break;
                    case 51:
                        if(UPCASE==1){
                            input_value[count_value]='<';
                        }else{
                            input_value[count_value]=',';
                        }
                        UPCASE=0;
                        count_value++;
                    break;
                    case 52:
                        if(UPCASE==1){
                            input_value[count_value]='>';
                        }else{
                            input_value[count_value]='.';
                        }
                        UPCASE=0;
                        count_value++;
                    break;
                    case 53:
                        if(UPCASE==1){
                            input_value[count_value]='?';
                        }else{
                            input_value[count_value]='/';
                        }
                        UPCASE=0;
                        count_value++;
                    break;
                }
#endif
            }
        }
    }

    close(fd);
    return 0;
error:
    return 1;
}
#if 0
void writeWpa(char *filename,char *ssid,char *psw){
   LOG_I("%s\n",__func__);
   buffer_to_file(filename,"# WPA-PSK/TKIP\n",strlen("# WPA-PSK/TKIP\n"),"wb"); 
   buffer_to_file(filename,"ap_scan=1\n",strlen("ap_scan=1\n"),"a"); 
   buffer_to_file(filename,"ctrl_interface=/var/run/wpa_supplicant\n",strlen("ctrl_interface=/var/run/wpa_supplicant\n"),"a"); 
   buffer_to_file(filename,"network={\n",strlen("network={\n"),"a"); 
   buffer_to_file(filename,"ssid=\"",strlen("ssid=\""),"a"); 
   buffer_to_file(filename,ssid,strlen(ssid),"a"); 
   buffer_to_file(filename,"\"",strlen("\""),"a"); 
   buffer_to_file(filename,"\n",strlen("\n"),"a"); 
   buffer_to_file(filename,"key_mgmt=WPA-PSK\n",strlen("key_mgmt=WPA-PSK\n"),"a"); 
   buffer_to_file(filename,"proto=WPA RSN\n",strlen("proto=WPA RSN\n"),"a"); 
   buffer_to_file(filename,"pairwise=CCMP TKIP\n",strlen("pairwise=CCMP TKIP\n"),"a"); 
   buffer_to_file(filename,"group=CCMP TKIP\n",strlen("group=CCMP TKIP\n"),"a"); 
   buffer_to_file(filename,"psk=\"",strlen("psk=\""),"a"); 
   buffer_to_file(filename,psw,strlen(psw),"a"); 
   buffer_to_file(filename,"\"",strlen("\""),"a"); 
   buffer_to_file(filename,"\n",strlen("\n"),"a"); 
   buffer_to_file(filename,"}\n",strlen("}\n"),"a"); 
   buffer_to_file(filename,"\n",strlen("\n"),"a"); 
}

void writeWlan(char *filename,char *netway,char *gate,char *ip){
   LOG_I("%s\n",__func__);
   buffer_to_file(filename,"METHOD=",strlen("METHOD="),"wb"); 
   buffer_to_file(filename,netway,strlen(netway),"a"); 
   buffer_to_file(filename,"\n",strlen("\n"),"a"); 
   if(strcmp(netway,"STATIC")==0){
       buffer_to_file(filename,"IPADDR=",strlen("IPADDR="),"a"); 
       buffer_to_file(filename,ip,strlen(ip),"a"); 
       buffer_to_file(filename,"\n",strlen("\n"),"a"); 
       buffer_to_file(filename,"NETMASK=255.255.255.0\n",strlen("NETMASK=255.255.255.0\n"),"a"); 
       buffer_to_file(filename,"GATEWAY=",strlen("GATEWAY="),"a"); 
       buffer_to_file(filename,gate,strlen(gate),"a"); 
       buffer_to_file(filename,"\n",strlen("\n"),"a"); 
   }
}

void removeFile(char *filename){
    char cmd[32]={0};
    sprintf(cmd,"rm %s",filename);
    //LOG_I("%s\n",cmd);
    system(cmd);
}
#endif

void writeNetworkInterface(char *filename,char *dest){
   buffer_to_file(filename,"# interfaces(5) file used by ifup(8) and ifdown(8)",
                    strlen("# interfaces(5) file used by ifup(8) and ifdown(8)"),"wb");
   buffer_to_file(filename,"\n",strlen("\n"),"a");
   buffer_to_file(filename,"# Include files from /etc/network/interfaces.d:",strlen("# Include files from /etc/network/interfaces.d:"),"a");
   buffer_to_file(filename,"\n",strlen("\n"),"a");
   buffer_to_file(filename,"source-directory /etc/network/interfaces.d",strlen("source-directory /etc/network/interfaces.d"),"a");
   buffer_to_file(filename,"\n",strlen("\n"),"a");
   buffer_to_file(filename,"auto lo",strlen("auto lo"),"a");
   buffer_to_file(filename,"\n",strlen("\n"),"a");
   buffer_to_file(filename,"iface lo inet loopback",strlen("iface lo inet loopback"),"a");
   buffer_to_file(filename,"\n",strlen("\n"),"a");
   buffer_to_file(filename,"auto eth0",strlen("auto eth0"),"a");
   buffer_to_file(filename,"\n",strlen("\n"),"a");
   buffer_to_file(filename,"iface eth0 inet dhcp",strlen("iface eth0 inet dhcp"),"a");
   buffer_to_file(filename,"\n",strlen("\n"),"a");
   buffer_to_file(filename,"# address 10.10.12.12",strlen("# address 10.10.12.12"),"a");
   buffer_to_file(filename,"\n",strlen("\n"),"a");
   buffer_to_file(filename,"# netmask 255.255.255.0",strlen("# netmask 255.255.255.0"),"a");
   buffer_to_file(filename,"\n",strlen("\n"),"a");
   buffer_to_file(filename,"# gateway 10.10.12.1",strlen("# gateway 10.10.12.1"),"a");
   buffer_to_file(filename,"\n",strlen("\n"),"a");
   buffer_to_file(filename,"hwaddress ether ",strlen("hwaddress ether "),"a");
   buffer_to_file(filename,dest,strlen(dest),"a");
   system("sync");
}

char* insert_colon(const char* src, int interval) {
    if (!src || interval <= 0) return NULL;

    size_t len = strlen(src);
    if (len == 0) {  // 空字符串返回空
        char* res = malloc(1);
        if (res) res[0] = '\0';
        return res;
    }

    // 计算新字符串长度
    size_t sections = (len + interval - 1) / interval;  // 总段数
    size_t new_len = len + (sections - 1);              // 新长度 = 原长 + 冒号数
    char* new_str = malloc(new_len + 1);                // 分配内存:ml-citation{ref="2" data="citationList"}
    if (!new_str) return NULL;

    size_t src_idx = 0, dst_idx = 0;
    while (src_idx < len) {
        // 计算本次复制的字符数
        size_t copy_size = (len - src_idx < (size_t)interval) ? (len - src_idx) : (size_t)interval;
        memcpy(new_str + dst_idx, src + src_idx, copy_size);  // 块复制:ml-citation{ref="3" data="citationList"}
        src_idx += copy_size;
        dst_idx += copy_size;

        // 非末尾段时插入冒号
        if (src_idx < len) new_str[dst_idx++] = ':';
    }
    new_str[dst_idx] = '\0';  // 终止符:ml-citation{ref="7" data="citationList"}
    return new_str;
}

void *actHandleQrcode(void *parm){
    char *str=(char *)parm;
    LOG_I("scan:%s\n",str);
    if(strstr(str,"{")!=NULL){
#if 0
        char deviceSecret[64]={0};
        char deviceCode[64]={0};
        char netWorkType[64]={0};
        char netWorkSsid[64]={0};
        char netWorkPassword[64]={0};
        get_string_from_json_string_by_key_unescape(str, "deviceSecret",deviceSecret,64);
        LOG_I("deviceSecret:%s\n",deviceSecret);
        get_string_from_json_string_by_key_unescape(str, "deviceCode",deviceCode,64);
        LOG_I("deviceCode:%s\n",deviceCode);
        if(strcmp(deviceSecret,"")!=0 && strcmp(deviceCode,"")!=0){
            buffer_to_file("deviceSecret",deviceSecret,strlen(deviceSecret),"wb");
            buffer_to_file("savedDevSn",deviceCode,strlen(deviceCode),"wb");
        }
        get_string_from_json_string_by_key_unescape(str, "netWorkType",netWorkType,64);
        LOG_I("netWorkType:%s\n",netWorkType);

        if(strcmp(netWorkType,"net_wifi")==0){
            buffer_to_file("nettype","net_wifi",strlen("net_wifi"),"wb");
            get_string_from_json_string_by_key_unescape(str, "netWorkSsid",netWorkSsid,64);
            LOG_I("netWorkSsid:%s\n",netWorkSsid);
            get_string_from_json_string_by_key_unescape(str, "netWorkPassword",netWorkPassword,64);
            LOG_I("netWorkPassword:%s\n",netWorkPassword);
            if(strcmp(netWorkSsid,"")!=0 && strcmp(netWorkPassword,"")!=0){
                writeWpa("/etc/wpa_supplicant.conf",netWorkSsid,netWorkPassword);
                sleep(1);
                system("reboot");
            }else{
            }
        }else if(strcmp(netWorkType,"net_wired")==0){
            buffer_to_file("nettype","net_wired",strlen("net_wired"),"wb");
            LOG_I("use wired\n");
            sleep(1);
            system("reboot");
        }else if(strcmp(netWorkType,"net_mobile")==0){
            buffer_to_file("nettype","net_mobile",strlen("net_mobile"),"wb");
            LOG_I("use mobile\n");
            sleep(1);
            system("reboot");
        }
#endif
    }else{
#if 1
        if(strstr(str,"d")!=NULL && strlen(str)>=27){
            LOG_I("ok\n");
            char *result=NULL;
            char *p;
            result=strtok_r(str,":",&p);
            while(result!=NULL){
                if(strstr(result,"d")!=NULL){
                    LOG_I("save sn:%s\n",result);
                    buffer_to_file("savedDevSn",result,strlen(result),"wb");
                }else{
                    //LOG_I("save mac:%s\n",result);
                    //buffer_to_file("savedDevMac",result,strlen(result),"wb");
                    char* destmac = insert_colon(result, 2);
                    LOG_I("save mac:%s\n",destmac);
                    writeNetworkInterface("/etc/network/interfaces",destmac);
                }
                result=strtok_r(NULL,",",&p);
            }
        }        
#else
        if(strstr(str,"d1")!=NULL){
            buffer_to_file("savedDevSn",str,strlen(str),"wb");
        }
#endif
    }
    pthread_exit(NULL);
}

char *file_to_buffer(const char *pathname, unsigned int *size){
    FILE *fp = NULL;
    char *temp = NULL;
    fp = fopen(pathname, "rb");
    if(fp==NULL){
        //LOG_I("open %s error\n", pathname);
    }else{
        fseek(fp,0,2);
        *size = ftell(fp);
        rewind(fp);
        temp = (char *)malloc(*size);
        fread(temp, 1, *size, fp);
        fclose(fp);
    }
    return temp;
}

/*================================================================================*/
void showShellInfo(char *command){
    FILE *fp;
    char buffer[512]={0};
    fp=popen(command, "r");
    fread(buffer,1,sizeof(buffer),fp);
    LOG_I("\n%s",buffer);
}

void getTimeStr(char *buffer,int len){
    time_t timep;
    struct tm *p;
    time (&timep);
    p=localtime(&timep);
    strftime (buffer,len,"%Y-%m-%d %H:%M:%S",p);
}

long getCurrentTime(){
    struct timeval begin;
    gettimeofday(&begin,NULL);
    long long beginTime = (long long)begin.tv_sec * 1000 + (long long)begin.tv_usec / 1000;
    long last=beginTime/1000;
    return last;
}

void myrand(char *randnum,int len){
    int i;
    srand((unsigned)time(0));
    for(i=0;i<=len-1;i++)
        randnum[i]=rand()%10 +'0';
    randnum[len]='\0';
}

void removeSpaces(char *str) {
    int i = 0, j = 0;
    while (str[i] != '\0') {
        if (str[i] != ' ') {
            str[j++] = str[i];
        }
        i++;
    }
    str[j] = '\0';
}
 
void getDevRawPassword(char *devsn){
    LOG_I("devsn:%s\n",devsn);
    json_object *root = NULL;
    const char *payload = NULL;
    char send_request[256]={0};
    char signbase64[256]={0};
    char signtmp[256]={0};
    char jsondata[256] = {0};
    char tmpdata[256] = {0};
    //char tmpdata1[64] = {0};
    char buffer[512];
    FILE *fp;
    root = json_object_new_object();
    if(root == NULL){
        LOG_I("json_object_new_object error\n");
    }else{
        json_object_object_add(root, "deviceId",json_object_new_string(devsn));
        json_object_object_add(root, "oldPassword",json_object_new_string("12345"));
        payload = json_object_to_json_string(root);
        removeSpaces(payload);
        strcpy(signtmp,payload);
        strcat(signtmp,appSecret);
        //LOG_I("signtmp:%s\n",signtmp);
        get_base64_md5_from_string(signbase64, sizeof(signbase64), signtmp, strlen(signtmp));
        //LOG_I("signbase64:%s\n",signbase64);
        sprintf(send_request,"curl -X POST -H 'x-appKey:%s' -H 'x-datadigest:%s' -H 'Content-Type: application/json' -d '%s' %s",
                appKey,signbase64,payload,getDevRawPasswordUrl);
        LOG_I("send_request:%s\n",send_request);
        fp=popen(send_request,"r");
        fgets(buffer,sizeof(buffer),fp);
        //get_string_from_json_string_by_key_unescape(buffer, "message", tmpdata1, sizeof(tmpdata1));
        //LOG_I("message: %s\n",tmpdata1);
        get_string_from_json_string_by_key_unescape(buffer, "result", tmpdata, sizeof(tmpdata));
        LOG_I("result: %s\n",tmpdata);

        snprintf(jsondata, sizeof(jsondata), "{%s}", tmpdata);
        //LOG_I("jsondata:%s\n",jsondata);
        get_string_from_json_string_by_key_unescape(jsondata, "password", mqttRawPassword, sizeof(mqttRawPassword));
        LOG_I("save mqttRawPassword:%s\n",mqttRawPassword);

        if(strcmp(mqttRawPassword,"")!=0){
            buffer_to_file("mqttRawPassword",mqttRawPassword,strlen(mqttRawPassword),"wb");
        }
    }
}

void checkOtaKey(void){
    int len=0;
    int keycount=0;
    char *readresult=NULL;
    while(1){
        if(isOtaEnable){
            //system("echo 0 > /sys/class/gpio/gpio113/value");
            //sleep(1);
            //system("echo 1 > /sys/class/gpio/gpio113/value");
            sleep(1);
        }else{
            readresult=file_to_buffer("/sys/class/gpio/gpio63/value",&len);
            //LOG_I("resetKey:%s\n",readresult);
            if(readresult!=NULL){
                if(strcmp(readresult,"0\n")==0){
                    keycount++;
                    if(keycount==3){
                        keycount=0;
                        isOtaEnable=true;
                        //isLEDOtaSuccess=false;
                        //isAPOtaSuccess=false;
                        //isSendComEnd=true;
                        LOG_I("OTA enable\n");
                        update_app();
                    }
                }
            }
            usleep(100*1000);
        }
    }
}

void update_app(void){
    system("rm -fr ota");
    system("mkdir ota");
    char otaCmd[256]={0};
    sprintf(otaCmd,"curl -o /root/ota/jd_ota.zip %s",updateUrl);
    system(otaCmd);
    sleep(15);
    system("unzip ota/jd_ota.zip");
    system("mv jd_ota/* ota");
    system("rm -fr jd_ota");
    system("mv ota/start.sh /root");
    sleep(1);
    system("reboot");
}
/*================================================================================*/
void mqtt_init(){
    int ret=0;
    char username[32] = {0};
    char password[32] = {0};
    char clientid[256] = {0};
    //char clientid[256] = "TJ250995217957|signmethod=hmacsha1|timestamp=1741416329331";
    char hostip[16]={0};
    //char protocol[64]="mqtt";
    //char RawPassword[64]="94b4e39caf1d45ee9a071d701cc037b4";
    struct timeval tv;
    //MQTTASYNC_TRACE_MAXIMUM
    //MQTTASYNC_TRACE_MEDIUM
    //MQTTASYNC_TRACE_MINIMUM
    //MQTTASYNC_TRACE_PROTOCOL
    //MQTTASYNC_TRACE_ERROR
    //MQTTASYNC_TRACE_SEVERE
    //MQTTASYNC_TRACE_FATAL
    //mqtt_config.tracelevel=get_trace_level_by_name("MQTTASYNC_TRACE_PROTOCOL"); 
    //gettimeofday(&tv, NULL);
    snprintf(clientid,sizeof(clientid),"%s",stationsn);
    //LOG_I("clientid:%s,mqttRawPassword:%s\n",clientid,mqttRawPassword);
    
    //hmacsha1(mqttRawPassword,clientid,password,sizeof(password));
    mqtt_config.tracelevel=MQTTASYNC_TRACE_PROTOCOL; 
    mqtt_config.retain=0;
    mqtt_config.port=mqtt_port;
    mqtt_config.keepalive=30;
    //memset(mqtt_config.protocol,0,sizeof(mqtt_config.protocol));
    //memcpy(mqtt_config.protocol,protocol,sizeof(protocol));
    memset(mqtt_config.clientid,0,sizeof(mqtt_config.clientid));
    memcpy(mqtt_config.clientid,clientid,sizeof(clientid));
    snprintf(username, sizeof(username), "%s", stationsn);
    LOG_I("username:%s,password:%s\n",username,password);
    memset(mqtt_config.productcode, 0, sizeof(mqtt_config.productcode));
    memcpy(mqtt_config.productcode, productid, strlen(productid));
    memset(mqtt_config.username, 0, sizeof(mqtt_config.username));
    memcpy(mqtt_config.username, username, strlen(username));
    memset(mqtt_config.password, 0, sizeof(mqtt_config.password));
    memcpy(mqtt_config.password, password, strlen(password));
    get_ip_by_domain(hostDomain,hostip,16);
    memset(mqtt_config.host, 0, sizeof(mqtt_config.host));
    memcpy(mqtt_config.host, hostip, strlen(hostip));
    mqtt_config.MQTTVersion = 4;
    
    /* will options */
    mqtt_config.will_topic = NULL;
    mqtt_config.will_payload = NULL;
    mqtt_config.will_qos = 2;
    mqtt_config.will_retain = 0;
    /* TLS options */
    mqtt_config.insecure = 1;
    mqtt_config.capath = NULL;
    mqtt_config.cert = "./custom.crt";
    mqtt_config.cafile = "./ca.crt";
    mqtt_config.key = "./custom.key";
    mqtt_config.keypass = NULL;
    mqtt_config.ciphers = NULL;
   
    ret = sem_init(&mqtt_config.sem_connect, 0, 0);
    if (ret != 0)
    {
        LOG_I("sem_connect init error\n");
        goto error;
    }

    ret = mqtt_utils_init(&mqtt_config);
    if (ret < 0)
    {
        LOG_I("mqtt_utils_init error\n");
        ret = -1;
        goto error;
    }
    sem_wait(&mqtt_config.sem_connect);
    ret = 0;
error:
    return;
}

/*================================================================================*/
void *thread_keycheck(void *arg){
    checkOtaKey();
}

void *thread_reporttag(void *arg){
    report_tag();
}

void *thread_mqtt(void *arg){
    mqtt_init();
}

void *thread_removelog(void *arg){
    removeLog();
}

void *thread_feed_watchdog(void *arg){
    feedWatchDog();
}

void *thread_readqr(void *arg){
    readQrcode();
}

void *thread_uart_recv_ack(void *arg){
    uint16_t parm_ack;
    int ret=0;
    while(1){
        ret=uart_data_receive_ack(&uartSend,&parm_ack);
        if(ret>0){
            LOG_I("ack:%x\n",parm_ack);
            if(parm_ack==0x2323){
                jt_led_or_group_package_t led_ctrl={
                    .s.color=changecolor,
                    .s.sound=changesound,
                    .s.single=0,
                    .s.flash=3,
                };//0xC1 11000001 flash高位
                jt_led_or_group_package_t group={
                    .group=groupno,
                };//0xC1 11000001 flash高位
                //jt_led_or_group_package_t stop={
                //    .group=0x72,
                //};//0xC1 11000001 flash高位
                jt_group_package_t groups[1]={{groupno,led_ctrl}};
                //jt_group_package_t groups_stop[2]={{0x58,stop},{0xE3,0x00}};
#if 0
                uint32_t tag1=strtol(lightsn1,NULL,16);
                uint32_t tag2=strtol(lightsn2,NULL,16);
                uint32_t tag3=strtol(lightsn3,NULL,16);
                uint32_t tag4=strtol(lightsn4,NULL,16);
                uint32_t tag5=strtol(lightsn5,NULL,16);
                uint32_t tag6=strtol(lightsn6,NULL,16);
                uint32_t tag7=strtol(lightsn7,NULL,16);
                uint32_t tag8=strtol(lightsn8,NULL,16);
                uint32_t tag9=strtol(lightsn9,NULL,16);
                uint32_t tag10=strtol(lightsn10,NULL,16);
                uint32_t tag11=strtol(lightsn11,NULL,16);
                uint32_t tag12=strtol(lightsn12,NULL,16);
                uint32_t tag13=strtol(lightsn13,NULL,16);
                uint32_t tag14=strtol(lightsn14,NULL,16);
                uint32_t tag15=strtol(lightsn15,NULL,16);
                uint32_t tag16=strtol(lightsn16,NULL,16);
                uint32_t tag17=strtol(lightsn17,NULL,16);
                uint32_t tag18=strtol(lightsn18,NULL,16);
                uint32_t tag19=strtol(lightsn19,NULL,16);
                uint32_t tag20=strtol(lightsn20,NULL,16);
                uint32_t tag21=strtol(lightsn21,NULL,16);
                uint32_t tag22=strtol(lightsn22,NULL,16);
                uint32_t tag23=strtol(lightsn23,NULL,16);
                uint32_t tag24=strtol(lightsn24,NULL,16);
                uint32_t tag25=strtol(lightsn25,NULL,16);
                uint32_t tag26=strtol(lightsn26,NULL,16);
                uint32_t tag27=strtol(lightsn27,NULL,16);
                uint32_t tag28=strtol(lightsn28,NULL,16);
                uint32_t tag29=strtol(lightsn29,NULL,16);
                uint32_t tag30=strtol(lightsn30,NULL,16);
#else
                //low power
#if 0
                uint32_t tag1=strtol("000511",NULL,16);
                uint32_t tag2=strtol("00051C",NULL,16);
                uint32_t tag3=strtol("000E99",NULL,16);
                uint32_t tag4=strtol("004137",NULL,16);
                uint32_t tag5=strtol("004348",NULL,16);
                uint32_t tag6=strtol("004391",NULL,16);
                uint32_t tag7=strtol("004DB8",NULL,16);
                uint32_t tag8=strtol("005966",NULL,16);
                uint32_t tag9=strtol("014BEE",NULL,16);
                uint32_t tag10=strtol("014BF0",NULL,16);
#else
                uint32_t tag1=strtol("014C17",NULL,16);
                uint32_t tag2=strtol("014C04",NULL,16);
                uint32_t tag3=strtol("014C06",NULL,16);
                uint32_t tag4=strtol("014C02",NULL,16);
                uint32_t tag5=strtol("014C11",NULL,16);
                uint32_t tag6=strtol(lightsn6,NULL,16);
                uint32_t tag7=strtol(lightsn7,NULL,16);
                uint32_t tag8=strtol(lightsn8,NULL,16);
                uint32_t tag9=strtol(lightsn9,NULL,16);
                uint32_t tag10=strtol(lightsn10,NULL,16);

#endif
                uint32_t tag11=strtol(lightsn11,NULL,16);
                uint32_t tag12=strtol(lightsn12,NULL,16);
                uint32_t tag13=strtol(lightsn13,NULL,16);
                uint32_t tag14=strtol(lightsn14,NULL,16);
                uint32_t tag15=strtol(lightsn15,NULL,16);
                uint32_t tag16=strtol(lightsn16,NULL,16);
                uint32_t tag17=strtol(lightsn17,NULL,16);
                uint32_t tag18=strtol(lightsn18,NULL,16);
                uint32_t tag19=strtol(lightsn19,NULL,16);
                uint32_t tag20=strtol(lightsn20,NULL,16);
                uint32_t tag21=strtol(lightsn21,NULL,16);
                uint32_t tag22=strtol(lightsn22,NULL,16);
                uint32_t tag23=strtol(lightsn23,NULL,16);
                uint32_t tag24=strtol(lightsn24,NULL,16);
                uint32_t tag25=strtol(lightsn25,NULL,16);
                uint32_t tag26=strtol(lightsn26,NULL,16);
                uint32_t tag27=strtol(lightsn27,NULL,16);
                uint32_t tag28=strtol(lightsn28,NULL,16);
                uint32_t tag29=strtol(lightsn29,NULL,16);
                uint32_t tag30=strtol(lightsn30,NULL,16);

#endif
#if 0
                if(isStopBroadcast){
                    uart_data_send_lighton_by_group(&uartSend,groups_stop,2);
                    isStopBroadcast=false;
                }
#endif
                if(isLightOn){
                    jt_tag_package_t tags[30]={{(tag1>>16)&0xFF,(tag1>>8)&0xFF,(tag1)&0xFF,led_ctrl},
                                              {(tag2>>16)&0xFF,(tag2>>8)&0xFF,(tag2)&0xFF,led_ctrl},
                                              {(tag3>>16)&0xFF,(tag3>>8)&0xFF,(tag3)&0xFF,led_ctrl},
                                              {(tag4>>16)&0xFF,(tag4>>8)&0xFF,(tag4)&0xFF,led_ctrl},
                                              {(tag5>>16)&0xFF,(tag5>>8)&0xFF,(tag5)&0xFF,led_ctrl},
                                              {(tag6>>16)&0xFF,(tag6>>8)&0xFF,(tag6)&0xFF,led_ctrl},
                                              {(tag7>>16)&0xFF,(tag7>>8)&0xFF,(tag7)&0xFF,led_ctrl},
                                              {(tag8>>16)&0xFF,(tag8>>8)&0xFF,(tag8)&0xFF,led_ctrl},
                                              {(tag9>>16)&0xFF,(tag9>>8)&0xFF,(tag9)&0xFF,led_ctrl},
                                              {(tag10>>16)&0xFF,(tag10>>8)&0xFF,(tag10)&0xFF,led_ctrl},
                                              {(tag11>>16)&0xFF,(tag11>>8)&0xFF,(tag11)&0xFF,led_ctrl},
                                              {(tag12>>16)&0xFF,(tag12>>8)&0xFF,(tag12)&0xFF,led_ctrl},
                                              {(tag13>>16)&0xFF,(tag13>>8)&0xFF,(tag13)&0xFF,led_ctrl},
                                              {(tag14>>16)&0xFF,(tag14>>8)&0xFF,(tag14)&0xFF,led_ctrl},
                                              {(tag15>>16)&0xFF,(tag15>>8)&0xFF,(tag15)&0xFF,led_ctrl},
                                              {(tag16>>16)&0xFF,(tag16>>8)&0xFF,(tag16)&0xFF,led_ctrl},
                                              {(tag17>>16)&0xFF,(tag17>>8)&0xFF,(tag17)&0xFF,led_ctrl},
                                              {(tag18>>16)&0xFF,(tag18>>8)&0xFF,(tag18)&0xFF,led_ctrl},
                                              {(tag19>>16)&0xFF,(tag19>>8)&0xFF,(tag19)&0xFF,led_ctrl},
                                              {(tag20>>16)&0xFF,(tag20>>8)&0xFF,(tag20)&0xFF,led_ctrl},
                                              {(tag21>>16)&0xFF,(tag21>>8)&0xFF,(tag21)&0xFF,led_ctrl},
                                              {(tag22>>16)&0xFF,(tag22>>8)&0xFF,(tag22)&0xFF,led_ctrl},
                                              {(tag23>>16)&0xFF,(tag23>>8)&0xFF,(tag23)&0xFF,led_ctrl},
                                              {(tag24>>16)&0xFF,(tag24>>8)&0xFF,(tag24)&0xFF,led_ctrl},
                                              {(tag25>>16)&0xFF,(tag25>>8)&0xFF,(tag25)&0xFF,led_ctrl},
                                              {(tag26>>16)&0xFF,(tag26>>8)&0xFF,(tag26)&0xFF,led_ctrl},
                                              {(tag27>>16)&0xFF,(tag27>>8)&0xFF,(tag27)&0xFF,led_ctrl},
                                              {(tag28>>16)&0xFF,(tag28>>8)&0xFF,(tag28)&0xFF,led_ctrl},
                                              {(tag29>>16)&0xFF,(tag29>>8)&0xFF,(tag29)&0xFF,led_ctrl},
                                              {(tag30>>16)&0xFF,(tag30>>8)&0xFF,(tag30)&0xFF,led_ctrl}};
                    uart_data_send_lighton_or_group(&uartSend,tags,lightbars_size);
                    isLightOn=false;
#if 0
                    isStopBroadcastBegin=false;
                    while(1){
                        usleep(150*1000);
                        if(isStopBroadcastBegin){
                            break;
                        }
                    }
                    uart_data_send_head(&uartSend,'R',5,30/5,1);//stop broadcast by groupno
                    isStopBroadcast=true;
#endif
                }
  
                if(isBindTag){
                    jt_tag_package_t tags[30]={{(tag1>>16)&0xFF,(tag1>>8)&0xFF,(tag1)&0xFF,group},
                                              {(tag2>>16)&0xFF,(tag2>>8)&0xFF,(tag2)&0xFF,group},
                                              {(tag3>>16)&0xFF,(tag3>>8)&0xFF,(tag3)&0xFF,group},
                                              {(tag4>>16)&0xFF,(tag4>>8)&0xFF,(tag4)&0xFF,group},
                                              {(tag5>>16)&0xFF,(tag5>>8)&0xFF,(tag5)&0xFF,group},
                                              {(tag6>>16)&0xFF,(tag6>>8)&0xFF,(tag6)&0xFF,group},
                                              {(tag7>>16)&0xFF,(tag7>>8)&0xFF,(tag7)&0xFF,group},
                                              {(tag8>>16)&0xFF,(tag8>>8)&0xFF,(tag8)&0xFF,group},
                                              {(tag9>>16)&0xFF,(tag9>>8)&0xFF,(tag9)&0xFF,group},
                                              {(tag10>>16)&0xFF,(tag10>>8)&0xFF,(tag10)&0xFF,group},
                                              {(tag11>>16)&0xFF,(tag11>>8)&0xFF,(tag11)&0xFF,group},
                                              {(tag12>>16)&0xFF,(tag12>>8)&0xFF,(tag12)&0xFF,group},
                                              {(tag13>>16)&0xFF,(tag13>>8)&0xFF,(tag13)&0xFF,group},
                                              {(tag14>>16)&0xFF,(tag14>>8)&0xFF,(tag14)&0xFF,group},
                                              {(tag15>>16)&0xFF,(tag15>>8)&0xFF,(tag15)&0xFF,group},
                                              {(tag16>>16)&0xFF,(tag16>>8)&0xFF,(tag16)&0xFF,group},
                                              {(tag17>>16)&0xFF,(tag17>>8)&0xFF,(tag17)&0xFF,group},
                                              {(tag18>>16)&0xFF,(tag18>>8)&0xFF,(tag18)&0xFF,group},
                                              {(tag19>>16)&0xFF,(tag19>>8)&0xFF,(tag19)&0xFF,group},
                                              {(tag20>>16)&0xFF,(tag20>>8)&0xFF,(tag20)&0xFF,group},
                                              {(tag21>>16)&0xFF,(tag21>>8)&0xFF,(tag21)&0xFF,group},
                                              {(tag22>>16)&0xFF,(tag22>>8)&0xFF,(tag22)&0xFF,group},
                                              {(tag23>>16)&0xFF,(tag23>>8)&0xFF,(tag23)&0xFF,group},
                                              {(tag24>>16)&0xFF,(tag24>>8)&0xFF,(tag24)&0xFF,group},
                                              {(tag25>>16)&0xFF,(tag25>>8)&0xFF,(tag25)&0xFF,group},
                                              {(tag26>>16)&0xFF,(tag26>>8)&0xFF,(tag26)&0xFF,group},
                                              {(tag27>>16)&0xFF,(tag27>>8)&0xFF,(tag27)&0xFF,group},
                                              {(tag28>>16)&0xFF,(tag28>>8)&0xFF,(tag28)&0xFF,group},
                                              {(tag29>>16)&0xFF,(tag29>>8)&0xFF,(tag29)&0xFF,group},
                                              {(tag30>>16)&0xFF,(tag30>>8)&0xFF,(tag30)&0xFF,group}};
                    uart_data_send_lighton_or_group(&uartSend,tags,lightbars_size);
                    isBindTag=false;
                }

                if(isLightOnById){
                    uart_data_send_lighton_by_id(&uartSend,0x00,0xFF,0x00000000,0xFFFFFFFF,led_ctrl,0x0000);
                    isLightOnById=false;
                }

                if(isLightOnByGroup){
                    uart_data_send_lighton_by_group(&uartSend,groups,1);
                    isLightOnByGroup=false;
                }
            }else if(parm_ack==0x4646){
               isSendComEnd=true; 
            }else if(parm_ack==0x5252){
               uart_data_receive_version(&uartSend);
               isSendComEnd=true; 
            }
        }else{
           isSendComEnd=true; 
        }
        usleep(100*1000);
    }
}

void *thread_uart_recv_data(void *arg){
    uint16_t parmAck;
    uint16_t tagCodeHead;
    uint32_t tagCode;
    uint8_t tagSignal;
    uint8_t totalLen;
    uint8_t tagFeature;
    uint8_t count;
    uint8_t batteryV;
    uint16_t version;
    uint8_t ledCtrl;
    uint16_t signCode;
    uint16_t reserve;
    uint32_t lableParm;
    while(1){
       uart_data_receive_data_back(&uartRecvData,&parmAck,&tagCodeHead,&tagCode,&tagSignal,&totalLen,&tagFeature,
                                   &count,&batteryV,&version,&ledCtrl,&signCode,&reserve,&lableParm); 
       LOG_I("recv_data:%04x,%04x,tag:%08x,%02x,%02x,%02x,%02x,battery:%02x,%04x,%02x,%04x,reserve:%04x,%08x\n",
             parmAck,tagCodeHead,tagCode,tagSignal,totalLen,tagFeature,count,batteryV,version,ledCtrl,signCode,reserve,lableParm);
       isStopBroadcastBegin=true;
       //sleep(2);
    }
}

void *thread_uart_recv_back(void *arg){
    uint16_t parmAck;
    uint16_t tagCodeHead;
    uint32_t tagCode;
    uint8_t tagSignal;
    uint8_t totalLen;
    uint8_t tagFeature;
    uint8_t count;
    uint8_t batteryV;
    uint16_t version;
    uint8_t ledCtrl;
    uint16_t signCode;
    uint16_t reserve;
    uint32_t lableParm;
    while(1){
       uart_data_receive_data_back(&uartRecvBack,&parmAck,&tagCodeHead,&tagCode,&tagSignal,&totalLen,&tagFeature,
                                   &count,&batteryV,&version,&ledCtrl,&signCode,&reserve,&lableParm); 
       //LOG_I("recv_back:%04x,%04x,tag:%08x,%02x,%02x,%02x,%02x,battery:%02x,%04x,%02x,%04x,reserve:%04x,%08x\n",
       //      parmAck,tagCodeHead,tagCode,tagSignal,totalLen,tagFeature,count,batteryV,version,ledCtrl,signCode,reserve,lableParm);
       PutDataIntoQueue(tagCode,batteryV,reserve);
       if(tagFeature==0xFF){
           //LOG_I("heart beat\n");
       }else if(tagFeature==0xFD){
           LOG_I("key\n");
       }else if(tagFeature==0xFC){
           LOG_I("broadcast parm\n");
       }
    }
}

void functions_reply(char *task_id,char *msg_id){
   json_object *functions = NULL;
   functions=json_object_new_array();
   json_object *function = json_object_new_object();
   json_object *out = json_object_new_object();
   json_object_object_add(function, "key", json_object_new_string("relay-lightbar.control"));
   json_object_object_add(out, "dev-name", json_object_new_string(""));
   json_object_object_add(out, "task-id", json_object_new_string(task_id));
   json_object_object_add(out, "code", json_object_new_int(200));
   json_object_object_add(out, "desc", json_object_new_string("success"));
   json_object_object_add(out, "ext1", json_object_new_string(""));
   json_object_object_add(out, "ext2", json_object_new_string(""));
   json_object_object_add(function, "parameters", out);
   json_object_array_add(functions,function);
   mqtt_server_reply(stationsn,msg_id,functions);
}

void station_status_report(){
   json_object *events = NULL;
   char myid[32]={0};
   char local_ip[32] = {0};
   char local_mac[32]={0};
   char time_buffer[16] = ""; 
   struct timeval tv;
   myrand(myid,19);
   getLocalIp(local_ip);
   getLocalMac(local_mac);
   gettimeofday(&tv, NULL);
   snprintf(time_buffer,sizeof(time_buffer),"%ld",tv.tv_sec*1000+tv.tv_usec);

   events=json_object_new_array();
   json_object *event = json_object_new_object();
   json_object *parameters = json_object_new_object();
   json_object_object_add(event, "key", json_object_new_string("relay-base.basic-report"));
   json_object_object_add(parameters, "dev-name", json_object_new_string(""));
   json_object_object_add(parameters, "comp-code", json_object_new_string("idata"));
   json_object_object_add(parameters, "mac-addr", json_object_new_string(local_mac));
   json_object_object_add(parameters, "mode", json_object_new_string(""));
   json_object_object_add(parameters, "ip", json_object_new_string(local_ip));
   json_object_object_add(parameters, "sys-ver", json_object_new_string(softwareVersion));
   json_object_object_add(parameters, "site", json_object_new_string(""));
   json_object_object_add(parameters, "occ-time", json_object_new_string(time_buffer));
   json_object_object_add(parameters, "ext1", json_object_new_string(""));
   json_object_object_add(parameters, "ext2", json_object_new_string(""));
   json_object_object_add(event, "parameters", parameters);
   json_object_array_add(events,event);
   mqtt_server_events_report(stationsn,myid,events);
}

void light_status_report(){
   LOG_I("%s:tagCount:%d\n",__func__,tagCount);
   json_object *events = NULL;
   events=json_object_new_array();
   char myid[32]={0};
   char time_buffer[16] = "";
   struct timeval tv;

   myrand(myid,19);
   gettimeofday(&tv, NULL);
   snprintf(time_buffer,sizeof(time_buffer),"%ld",tv.tv_sec*1000+tv.tv_usec);
 
   for(int i=0;i<tagCount;i++){
       //LOG_I("onlyTags:%06X,%04x,%04x\n",onlyTags[i].name,onlyTags[i].battery,onlyTags[i].reserve);
       char tagName[9]={0};
       char group[3]={0};
       int status=0;
       sprintf(tagName,"%06X",onlyTags[i].name);
       sprintf(group,"%02X",(onlyTags[i].reserve>>8)&&0xFF);
       if(strcmp(group,"00")==0 || strcmp(group,"FF")==0){
           status=1;
       }else{
           status=2;
       }
       //if(onlyTags[i].battery<=24){
       //    status=3;
       //}

       json_object *event = json_object_new_object();
       json_object *parameters = json_object_new_object();
       json_object_object_add(event, "key", json_object_new_string("relay-lightbar.status-report"));
       json_object_object_add(parameters, "dev-name", json_object_new_string(""));
       json_object_object_add(parameters, "light-id", json_object_new_string(tagName));
       json_object_object_add(parameters, "status", json_object_new_int(status));
       if(onlyTags[i].battery>=30){
           json_object_object_add(parameters, "battery", json_object_new_int(100));
       }else if(onlyTags[i].battery>=29 && onlyTags[i].battery<30){
           json_object_object_add(parameters, "battery", json_object_new_int(90));
       }else if(onlyTags[i].battery>=28 && onlyTags[i].battery<29){
           json_object_object_add(parameters, "battery", json_object_new_int(70));
       }else if(onlyTags[i].battery>=27 && onlyTags[i].battery<28){
           json_object_object_add(parameters, "battery", json_object_new_int(60));
       }else if(onlyTags[i].battery>=26 && onlyTags[i].battery<27){
           json_object_object_add(parameters, "battery", json_object_new_int(50));
       }else if(onlyTags[i].battery>=25 && onlyTags[i].battery<26){
           json_object_object_add(parameters, "battery", json_object_new_int(40));
       }else if(onlyTags[i].battery>=24 && onlyTags[i].battery<25){
           json_object_object_add(parameters, "battery", json_object_new_int(30));
       }
       json_object_object_add(parameters, "group-no", json_object_new_string(group));
       json_object_object_add(parameters, "occ-time", json_object_new_string(time_buffer));
       json_object_object_add(parameters, "ext1", json_object_new_string(""));
       json_object_object_add(parameters, "ext2", json_object_new_string(""));
       json_object_object_add(event, "parameters", parameters);
       json_object_array_add(events,event);
   }
   
   if(tagCount>0){
       mqtt_server_events_report(stationsn,myid,events);
       tagCount=0;
       memset(onlyTags,0,sizeof(onlyTags));
   }
}

void addOnlyTag(uint32_t tagname,uint16_t battery,uint16_t reserve){
    int i=0;
    if(tagCount==0){
        jt_only_tag_t jt_only_tag = {
            .name=tagname,
            .battery=battery,  
            .reserve=reserve,
        };
        onlyTags[tagCount]=jt_only_tag;
        tagCount++;
    }else{
        for(i=0;i<tagCount;i++){
           if(tagname==onlyTags[i].name){
               break;
           }
        }
        if(i==tagCount){
            jt_only_tag_t jt_only_tag = {
                .name=tagname,
                .battery=battery,
                .reserve=reserve,
            };
            onlyTags[tagCount]=jt_only_tag;
            tagCount++;
        }
    }
    if(tagCount==100){
        light_status_report();
    }
}

void *thread_remove_duplicate_tag(void *arg){
    uint32_t tagname=0;
    uint16_t battery=0;
    uint16_t reserve=0;
    while(1){
        if(GetDataFromQueue(&tagname,&battery,&reserve)==0){
            //LOG_I("%08x,%04x\n",tagname,battery);
            addOnlyTag(tagname,battery,reserve);
        }
    }
}

void *thread_mqtt_recv(void *arg){
    char payload[1024]={0};
    char msg_functions[1024] ={0};
    char msg_functions_value[1024] ={0};
    char msg_in[512] ={0};
    char msg_in_value[512] ={0};
    char msg_lightbars[4] ={0};
    while(1){
        if(isSendComEnd){
            if(GetDataFromMQueue(payload)==0){
                LOG_I("payload:%s\n",payload);
                get_string_from_json_string_by_key_unescape(payload,"messageId",mqtt_parm.msg_messageId,sizeof(mqtt_parm.msg_messageId));
                LOG_I("messageId:%s\n",mqtt_parm.msg_messageId);              

                get_size_from_json_string_arry_by_key(payload, "functions", &mqtt_parm.msg_opNumber);
                LOG_I("functions size = %d\n", mqtt_parm.msg_opNumber);
                for(int i = 0; i <  mqtt_parm.msg_opNumber; i++){
                   get_string_from_json_string_arry_by_key(payload,"functions",msg_functions_value,1024,i);
                   snprintf(msg_functions, sizeof(msg_functions), "{%s}", msg_functions_value);
                   LOG_I("msg_functions = %s\n", msg_functions);
                   get_string_from_json_string_by_key_unescape(msg_functions, "key", mqtt_parm.msg_key,sizeof(mqtt_parm.msg_key));
                   LOG_I("msg_key = %s\n", mqtt_parm.msg_key);
                   get_string_from_json_string_by_key_unescape(msg_functions, "in", msg_in_value,sizeof(msg_in_value));
                   snprintf(msg_in, sizeof(msg_in), "{%s}", msg_in_value);
                   LOG_I("msg_in = %s\n", msg_in);
                   get_string_from_json_string_by_key_unescape(msg_in, "dev-name", mqtt_parm.msg_devName,sizeof(mqtt_parm.msg_devName));
                   LOG_I("msg_devName = %s\n", mqtt_parm.msg_devName);
                   get_string_from_json_string_by_key_unescape(msg_in, "task-id", mqtt_parm.msg_taskId,sizeof(mqtt_parm.msg_taskId));
                   LOG_I("msg_taskId = %s\n", mqtt_parm.msg_taskId);
                   get_string_from_json_string_by_key_unescape(msg_in, "group-no", mqtt_parm.msg_groupNo,sizeof(mqtt_parm.msg_groupNo));
                   LOG_I("msg_groupNo = %s\n", mqtt_parm.msg_groupNo);
                   get_int_from_json_string_by_key(msg_in,"action",&mqtt_parm.msg_action);
                   LOG_I("msg_action = %d\n", mqtt_parm.msg_action);
                   get_int_from_json_string_by_key(msg_in,"color",&mqtt_parm.msg_color);
                   LOG_I("msg_color = %d\n", mqtt_parm.msg_color);
                   //0灭 1红 2蓝 3绿 4黄 5紫 6青 7白 jingdong
                   //0灭 1蓝 2绿 3青 4红 5紫 6黄 7白 yitaile
                   if(mqtt_parm.msg_color==1){
                       changecolor=4;
                   }else if(mqtt_parm.msg_color==2){
                       changecolor=1;
                   }else if(mqtt_parm.msg_color==3){
                       changecolor=2;
                   }else if(mqtt_parm.msg_color==4){
                       changecolor=6;
                   }else if(mqtt_parm.msg_color==5){
                       changecolor=5;
                   }else if(mqtt_parm.msg_color==6){
                       changecolor=3;
                   }else if(mqtt_parm.msg_color==7){
                       changecolor=7;
                   }else if(mqtt_parm.msg_color==0){
                       changecolor=1;
                   }
                   LOG_I("changecolor=%d\n",changecolor);
                   get_int_from_json_string_by_key(msg_in,"duration",&mqtt_parm.msg_duration);
                   LOG_I("msg_duration = %d\n", mqtt_parm.msg_duration);
                   if(mqtt_parm.msg_duration<=5){
                       mqtt_parm.msg_duration=5;
                       LOG_I("new msg_duration = %d\n", mqtt_parm.msg_duration);
                   }
                   //get_string_from_json_string_by_key_unescape(msg_in, "lightbars", msg_lightbars_value,sizeof(msg_lightbars_value));
                   lightbars_size=0;
                   get_size_from_json_string_arry_by_key(msg_in, "lightbars", &lightbars_size);
                   LOG_I("lightbars_size = %d\n", lightbars_size);
                   memset(lightsn1,0,7);
                   memset(lightsn2,0,7);
                   memset(lightsn3,0,7);
                   memset(lightsn4,0,7);
                   memset(lightsn5,0,7);
                   memset(lightsn6,0,7);
                   memset(lightsn7,0,7);
                   memset(lightsn8,0,7);
                   memset(lightsn9,0,7);
                   memset(lightsn10,0,7);
                   memset(lightsn11,0,7);
                   memset(lightsn12,0,7);
                   memset(lightsn13,0,7);
                   memset(lightsn14,0,7);
                   memset(lightsn15,0,7);
                   memset(lightsn16,0,7);
                   memset(lightsn17,0,7);
                   memset(lightsn18,0,7);
                   memset(lightsn19,0,7);
                   memset(lightsn20,0,7);
                   memset(lightsn21,0,7);
                   memset(lightsn22,0,7);
                   memset(lightsn23,0,7);
                   memset(lightsn24,0,7);
                   memset(lightsn25,0,7);
                   memset(lightsn26,0,7);
                   memset(lightsn27,0,7);
                   memset(lightsn28,0,7);
                   memset(lightsn29,0,7);
                   memset(lightsn30,0,7);
                   for(int j=0;j<lightbars_size;j++){
                       get_string_from_json_string_arry_by_key(msg_in,"lightbars",mqtt_parm.msg_sn,7,j);
                       if(j==0){
                           memcpy(lightsn1,mqtt_parm.msg_sn,strlen(mqtt_parm.msg_sn));
                           LOG_I("%s\n",lightsn1);
                       }else if(j==1){
                           memcpy(lightsn2,mqtt_parm.msg_sn,strlen(mqtt_parm.msg_sn));
                           LOG_I("%s\n",lightsn2);
                       }else if(j==2){
                           memcpy(lightsn3,mqtt_parm.msg_sn,strlen(mqtt_parm.msg_sn));
                           LOG_I("%s\n",lightsn3);
                       }else if(j==3){
                           memcpy(lightsn4,mqtt_parm.msg_sn,strlen(mqtt_parm.msg_sn));
                           LOG_I("%s\n",lightsn4);
                       }else if(j==4){
                           memcpy(lightsn5,mqtt_parm.msg_sn,strlen(mqtt_parm.msg_sn));
                           LOG_I("%s\n",lightsn5);
                       }else if(j==5){
                           memcpy(lightsn6,mqtt_parm.msg_sn,strlen(mqtt_parm.msg_sn));
                           LOG_I("%s\n",lightsn6);
                       }else if(j==6){
                           memcpy(lightsn7,mqtt_parm.msg_sn,strlen(mqtt_parm.msg_sn));
                           LOG_I("%s\n",lightsn7);
                       }else if(j==7){
                           memcpy(lightsn8,mqtt_parm.msg_sn,strlen(mqtt_parm.msg_sn));
                           LOG_I("%s\n",lightsn8);
                       }else if(j==8){
                           memcpy(lightsn9,mqtt_parm.msg_sn,strlen(mqtt_parm.msg_sn));
                           LOG_I("%s\n",lightsn9);
                       }else if(j==9){
                           memcpy(lightsn10,mqtt_parm.msg_sn,strlen(mqtt_parm.msg_sn));
                           LOG_I("%s\n",lightsn10);
                       }else if(j==10){
                           memcpy(lightsn11,mqtt_parm.msg_sn,strlen(mqtt_parm.msg_sn));
                           LOG_I("%s\n",lightsn11);
                       }else if(j==11){
                           memcpy(lightsn12,mqtt_parm.msg_sn,strlen(mqtt_parm.msg_sn));
                           LOG_I("%s\n",lightsn12);
                       }else if(j==12){
                           memcpy(lightsn13,mqtt_parm.msg_sn,strlen(mqtt_parm.msg_sn));
                           LOG_I("%s\n",lightsn13);
                       }else if(j==13){
                           memcpy(lightsn14,mqtt_parm.msg_sn,strlen(mqtt_parm.msg_sn));
                           LOG_I("%s\n",lightsn14);
                       }else if(j==14){
                           memcpy(lightsn15,mqtt_parm.msg_sn,strlen(mqtt_parm.msg_sn));
                           LOG_I("%s\n",lightsn15);
                       }else if(j==15){
                           memcpy(lightsn16,mqtt_parm.msg_sn,strlen(mqtt_parm.msg_sn));
                           LOG_I("%s\n",lightsn16);
                       }else if(j==16){
                           memcpy(lightsn17,mqtt_parm.msg_sn,strlen(mqtt_parm.msg_sn));
                           LOG_I("%s\n",lightsn17);
                       }else if(j==17){
                           memcpy(lightsn18,mqtt_parm.msg_sn,strlen(mqtt_parm.msg_sn));
                           LOG_I("%s\n",lightsn18);
                       }else if(j==18){
                           memcpy(lightsn19,mqtt_parm.msg_sn,strlen(mqtt_parm.msg_sn));
                           LOG_I("%s\n",lightsn19);
                       }else if(j==19){
                           memcpy(lightsn20,mqtt_parm.msg_sn,strlen(mqtt_parm.msg_sn));
                           LOG_I("%s\n",lightsn20);
                       }else if(j==20){
                           memcpy(lightsn21,mqtt_parm.msg_sn,strlen(mqtt_parm.msg_sn));
                           LOG_I("%s\n",lightsn21);
                       }else if(j==21){
                           memcpy(lightsn22,mqtt_parm.msg_sn,strlen(mqtt_parm.msg_sn));
                           LOG_I("%s\n",lightsn22);
                       }else if(j==22){
                           memcpy(lightsn23,mqtt_parm.msg_sn,strlen(mqtt_parm.msg_sn));
                           LOG_I("%s\n",lightsn23);
                       }else if(j==23){
                           memcpy(lightsn24,mqtt_parm.msg_sn,strlen(mqtt_parm.msg_sn));
                           LOG_I("%s\n",lightsn24);
                       }else if(j==24){
                           memcpy(lightsn25,mqtt_parm.msg_sn,strlen(mqtt_parm.msg_sn));
                           LOG_I("%s\n",lightsn25);
                       }else if(j==25){
                           memcpy(lightsn26,mqtt_parm.msg_sn,strlen(mqtt_parm.msg_sn));
                           LOG_I("%s\n",lightsn26);
                       }else if(j==26){
                           memcpy(lightsn27,mqtt_parm.msg_sn,strlen(mqtt_parm.msg_sn));
                           LOG_I("%s\n",lightsn27);
                       }else if(j==27){
                           memcpy(lightsn28,mqtt_parm.msg_sn,strlen(mqtt_parm.msg_sn));
                           LOG_I("%s\n",lightsn28);
                       }else if(j==28){
                           memcpy(lightsn29,mqtt_parm.msg_sn,strlen(mqtt_parm.msg_sn));
                           LOG_I("%s\n",lightsn29);
                       }else if(j==29){
                           memcpy(lightsn30,mqtt_parm.msg_sn,strlen(mqtt_parm.msg_sn));
                           LOG_I("%s\n",lightsn30);
                       }
                   }

                   get_string_from_json_string_by_key_unescape(msg_in, "time", mqtt_parm.msg_time,sizeof(mqtt_parm.msg_time));
                   LOG_I("msg_time = %s\n", mqtt_parm.msg_time);
                   get_string_from_json_string_by_key_unescape(msg_in, "ext1", mqtt_parm.msg_ext1,sizeof(mqtt_parm.msg_ext1));
                   LOG_I("msg_ext1 = %s\n", mqtt_parm.msg_ext1);
                   get_string_from_json_string_by_key_unescape(msg_in, "ext2", mqtt_parm.msg_ext2,sizeof(mqtt_parm.msg_ext2));
                   LOG_I("msg_ext2 = %s\n", mqtt_parm.msg_ext2);
                   functions_reply(mqtt_parm.msg_taskId,mqtt_parm.msg_messageId);
                   if(mqtt_parm.msg_action==1){
                       LOG_I("light on by id\n");
                       lightbars_count+=lightbars_size;
                       
                       if(lightbars_count>=30){

                       }else {
                       }
                       isSendComEnd=false;
                       isLightOnByGroup=false;
                       isLightOnById=false;
                       isLightOn=true;
                       isBindTag=false;
                       changesound=1;
                       //P点灯 B绑定 &群控(不支持) *根据id点亮
                       uart_data_send_head(&uartSend,'P',5,mqtt_parm.msg_duration/5,lightbars_size);
                   }else if(mqtt_parm.msg_action==2){
                       LOG_I("light off by id\n");
                       isSendComEnd=false;
                       isLightOnByGroup=false;
                       isLightOnById=false;
                       isLightOn=true;
                       isBindTag=false;
                       changecolor=0;
                       changesound=0;
                       uart_data_send_head(&uartSend,'P',5,mqtt_parm.msg_duration/5,lightbars_size);
                   }else if(mqtt_parm.msg_action==3){
                       LOG_I("light on all\n");
                       isSendComEnd=false;
                       isLightOnByGroup=false;
                       isLightOnById=true;
                       isLightOn=false;
                       isBindTag=false;
                       changesound=1;
                       uart_data_send_head(&uartSend,'*',5,mqtt_parm.msg_duration/5,1);
                   }else if(mqtt_parm.msg_action==4){
                       LOG_I("light off all\n");
                       isSendComEnd=false;
                       isLightOnByGroup=false;
                       isLightOnById=true;
                       isLightOn=false;
                       isBindTag=false;
                       changecolor=0;
                       changesound=0;
                       uart_data_send_head(&uartSend,'*',5,mqtt_parm.msg_duration/5,1);
                   }else if(mqtt_parm.msg_action==5){
                       LOG_I("light on by group\n");
                       changesound=1;
                       if(strcmp(mqtt_parm.msg_groupNo,"0")==0){
                           LOG_I("group unbind\n");
                           isSendComEnd=false;
                           isLightOnByGroup=true;
                           isLightOnById=false;
                           isLightOn=false;
                           isBindTag=false;
                           groupno=0;
                           uart_data_send_head(&uartSend,'&',5,mqtt_parm.msg_duration/5,1);
                       }else if(strcmp(mqtt_parm.msg_groupNo,"1")==0){
                           LOG_I("group bind\n");
                           isSendComEnd=false;
                           isLightOnByGroup=true;
                           isLightOnById=false;
                           isLightOn=false;
                           isBindTag=false;
                           groupno=1;
                           uart_data_send_head(&uartSend,'&',5,mqtt_parm.msg_duration/5,1);
                       }else if(strcmp(mqtt_parm.msg_groupNo,"255")==0){
                           LOG_I("group light on all\n");
                           isSendComEnd=false;
                           isLightOnByGroup=false;
                           isLightOnById=true;
                           isLightOn=false;
                           isBindTag=false;
                           uart_data_send_head(&uartSend,'*',5,mqtt_parm.msg_duration/5,1);
                       }
                   }else if(mqtt_parm.msg_action==6){
                       LOG_I("light off by group\n");
                       changecolor=0;
                       changesound=0;
                       if(strcmp(mqtt_parm.msg_groupNo,"0")==0){
                           LOG_I("group unbind\n");
                           isSendComEnd=false;
                           isLightOnByGroup=true;
                           isLightOnById=false;
                           isLightOn=false;
                           isBindTag=false;
                           groupno=0;
                           uart_data_send_head(&uartSend,'&',5,mqtt_parm.msg_duration/5,1);
                       }else if(strcmp(mqtt_parm.msg_groupNo,"1")==0){
                           LOG_I("group bind\n");
                           isSendComEnd=false;
                           isLightOnByGroup=true;
                           isLightOnById=false;
                           isLightOn=false;
                           isBindTag=false;
                           groupno=1;
                           uart_data_send_head(&uartSend,'&',5,mqtt_parm.msg_duration/5,1);
                       }else if(strcmp(mqtt_parm.msg_groupNo,"255")==0){
                           LOG_I("group light off all\n");
                           isSendComEnd=false;
                           isLightOnByGroup=false;
                           isLightOnById=true;
                           isLightOn=false;
                           isBindTag=false;
                           uart_data_send_head(&uartSend,'*',5,mqtt_parm.msg_duration/5,1);
                       }
                   }else if(mqtt_parm.msg_action==7){
                       LOG_I("bind\n");
                       isSendComEnd=false;
                       isLightOnByGroup=false;
                       isLightOnById=false;
                       isLightOn=false;
                       isBindTag=true;
                       groupno=1;
                       uart_data_send_head(&uartSend,'B',5,0,lightbars_size);
                   }else if(mqtt_parm.msg_action==8){
                       LOG_I("unbind\n");
                       isSendComEnd=false;
                       isLightOnByGroup=false;
                       isLightOnById=false;
                       isLightOn=false;
                       isBindTag=true;
                       groupno=0;
                       uart_data_send_head(&uartSend,'B',5,0,lightbars_size);
                   }
                }
            }
            usleep(getPayloadTime);
        }else{
            usleep(getPayloadTime);
        }
    }
}
/*================================================================================*/
void hmacsha1(char *key,char* data,char *signbase64,int signbase64_len){
    char result[256]={0};
    size_t len=sizeof(result);
    //LOG_I("key_len:%d,data_len:%d\n",strlen(key),strlen(data));
    hmac_sha1(key,strlen(key),data,strlen(data),result,&len);
    //LOG_I("result_len:%d\n",len);
    int t_i;
    //for(t_i=0;t_i<len;t_i++)
    //    printf("%x ",result[t_i]);
    Base64_encode( signbase64, signbase64_len, result,strlen(result));
    //printf("last:%s\n",signbase64);
}

void getLocalIp(char *local_ip){
    FILE *fp;
    char buffer[64]={0};
    fp=popen("ifconfig eth0 | grep 'inet' | awk '{print $2}' | cut -d':' -f2","r");
    fgets(buffer,sizeof(buffer),fp);
    //LOG_I("buffer:%s\n",buffer);
    memcpy(local_ip,buffer,strlen(buffer)-1);
}
void getLocalMac(char *local_mac){
    FILE *fp;
    char buffer[64]={0};
    fp=popen("ifconfig eth0 | grep 'ether' | awk '{print $2}' | tr -d ':'","r");
    fgets(buffer,sizeof(buffer),fp);
    //LOG_I("buffer:%s\n",buffer);
    memcpy(local_mac,buffer,strlen(buffer)-1);
}

void saveStartUpTime(){
    system("rm ./startUpTime");
    struct timeval tv;
    char startUpTime[32] = {0};
    gettimeofday(&tv, NULL);
    snprintf(startUpTime,sizeof(startUpTime),"%ld",tv.tv_sec);
    buffer_to_file("startUpTime",startUpTime,strlen(startUpTime),"wb");
}

void calculateStartUpTime(char *startTime){
    char *result=NULL;
    struct timeval tv;
    int len=0;
    result=file_to_buffer("startUpTime",&len);
    if(result!=NULL){
        LOG_I("startUpTime:%s\n",result);
        gettimeofday(&tv, NULL);
        LOG_I("nowUpTime:%ld\n",tv.tv_sec);
        snprintf(startTime,11,"%ld",tv.tv_sec-atoi(result));
    }
}

void updateStationInfo(char *msg_id){
    char local_ip[32] = {0};
    char startTime[11]={0};
    getLocalIp(local_ip);
    LOG_I("local_ip:%s\n",local_ip);
    calculateStartUpTime(startTime);
    LOG_I("Time:%s\n",startTime);
    //mqtt_server_station_status_report(msg_id,productid,stationsn,local_ip,softwareVersion,"1",startTime);
}

bool timeNew(){
    struct timeval tv;
    gettimeofday(&tv, NULL);
    long gettime=tv.tv_sec*1000+tv.tv_usec;
    LOG_I("gettime:%ld\n",gettime);
    if(gettime<1744000000000){
        return false;
    }

    return true;
}
//==========================================================================================
int main(int argc, char *argv[])
{
    int ret = -1;
    uint32_t can_id;
    char recv_data[8]={0};
    char command_buffer[256] = "";
    int len=0;
    int getTimeCount=0;
    char *readresult=NULL;
    char networktype[32]={0};

    LOG_I("version:%s\n",softwareVersion);
    system("insmod /system/lib/modules/wk2xxx_spi.ko");
    system("timedatectl set-timezone Asia/Shanghai");
    uart_open(&uartSend,"/dev/ttyS0");//U12 ttyS0,U14 ttyS4,U21 ttysWK0 U13 ttysWK1 U15 ttysWK2 U22 ttysWK3 U20 ttyS1
    uart_init(&uartSend,115200,8,1,'N',0);
    uart_open(&uartRecvData,"/dev/ttyS4");
    uart_init(&uartRecvData,115200,8,1,'N',0);

    uart_open(&uartRecvBack,"/dev/ttysWK0");
    uart_init(&uartRecvBack,115200,8,1,'N',0);
    //doCommand_help(0, NULL);
    system("echo 113 > /sys/class/gpio/export");//pin 113 yellow 
    system("echo out > /sys/class/gpio/gpio113/direction");
    system("echo 63 > /sys/class/gpio/export");//pin 63 key
    system("echo in > /sys/class/gpio/gpio63/direction");
#if 0
    enableWatchDog();
    ret = pthread_create(&pt_watchdog,NULL,thread_feed_watchdog,NULL);
    if(ret!=0){
       LOG_I("pthread_create watchdog fail\n");
       system("reboot");
    }else{
       LOG_I("pthread_create watchdog success\n");
       pthread_detach(pt_watchdog);
    }
#endif
    ret = pthread_create(&pt_uart_recv_ack,NULL,thread_uart_recv_ack,NULL);
    if(ret!=0){
       LOG_I("pthread_create uart_recv_ack fail\n");
       system("reboot");
    }else{
       pthread_detach(pt_uart_recv_ack);
       LOG_I("pthread_create uart_recv_ack success\n");
    }
   
    ret = pthread_create(&pt_uart_recv_data,NULL,thread_uart_recv_data,NULL);
    if(ret!=0){
       LOG_I("pthread_create uart_recv_data fail\n");
       system("reboot");
    }else{
       pthread_detach(pt_uart_recv_data);
       LOG_I("pthread_create uart_recv_data success\n");
    }

    ret = pthread_create(&pt_uart_recv_back,NULL,thread_uart_recv_back,NULL);
    if(ret!=0){
       LOG_I("pthread_create uart_recv_back fail\n");
       system("reboot");
    }else{
       pthread_detach(pt_uart_recv_back);
       LOG_I("pthread_create uart_recv_back success\n");
    }

    ret = pthread_create(&pt_mqtt_recv,NULL,thread_mqtt_recv,NULL);
    if(ret!=0){
       LOG_I("pthread_create mqtt_recv fail\n");
       system("reboot");
    }else{
       pthread_detach(pt_mqtt_recv);
       LOG_I("pthread_create mqtt_recv success\n");
    }

    ret = pthread_create(&pt_removeduplicatetag,NULL,thread_remove_duplicate_tag,NULL);
    if(ret!=0){
       LOG_I("pthread_create remove duplicate tag send fail\n");
    }else{
       LOG_I("pthread_create remove duplicate tag success\n");
       pthread_detach(pt_removeduplicatetag);
    }

    ret = pthread_create(&pt_removelog,NULL,thread_removelog,NULL);
    if(ret!=0){
       LOG_I("pthread_create removelog fail\n");
       system("reboot");
    }else{
       LOG_I("pthread_create removelog success\n");
       pthread_detach(pt_removelog);
    }
#if 0
    ret = pthread_create(&pt_readqr,NULL,thread_readqr,NULL);
    if(ret!=0){
       LOG_I("pthread_create readqr fail\n");
       system("reboot");
    }else{
       LOG_I("pthread_create readqr success\n");
       pthread_detach(pt_readqr);
    }
#endif
    ret = pthread_create(&pt_reporttag,NULL,thread_reporttag,NULL);
    if(ret!=0){
       LOG_I("pthread_create reporttag fail\n");
       system("reboot");
    }else{
       LOG_I("pthread_create reporttag success\n");
       pthread_detach(pt_reporttag);
    }

    ret = pthread_create(&pt_keycheck,NULL,thread_keycheck,NULL);
    if(ret!=0){
       LOG_I("pthread_create keycheck fail\n");
       system("reboot");
    }else{
       LOG_I("pthread_create keycheck success\n");
       pthread_detach(pt_keycheck);
    }
#if 0
    readresult=file_to_buffer("mqttRawPassword",&len);
    if(readresult!=NULL){
        strncpy(mqttRawPassword,readresult,len);
        readresult=NULL;
        LOG_I("saved mqttRawPassword:%s\n",mqttRawPassword);
    }else{
        if((ping("8.8.8.8") == 0)||(ping("8.8.4.4") == 0)){
            getDevRawPassword(stationsn);
        }else{
            LOG_I("getDevRawPassword net not ready\n");
            sleep(3);
        }
    }

    readresult=file_to_buffer("LightEnable",&len);
    if(readresult!=NULL){
        if(strcmp(readresult,"enable")==0){
            isLightEnable=true;
        }else{
            isLightEnable=false;
        }
        readresult=NULL;
    }

#endif
    readresult=file_to_buffer("savedDevSn",&len);
    while(readresult==NULL){
        readresult=file_to_buffer("savedDevSn",&len);
        sleep(5);
        LOG_I("please scan sn\n");
    }
    strncpy(stationsn,readresult,len);
    readresult=NULL;
    LOG_I("saved stationsn:%s\n",stationsn);
#if 0
    isSendComEnd=false;
    isLightOnByGroup=false;
    isLightOnById=false;
    isLightOn=true;
    isBindTag=false;
    lightbars_size=5;
    changecolor=4;
    changesound=1;
    groupno=1;
    //uart_data_send_head(&uartSend,'B',5,0,lightbars_size);//bind groupno
    uart_data_send_head(&uartSend,'P',5,10/5,lightbars_size);//lighton by tag
    //uart_data_send_head(&uartSend,'*',5,5/5,0);//lighton by id
    //uart_data_send_head(&uartSend,'&',5,5/5,1);//lighton by groupno
                    //uart_data_send_head(&uartSend,'R',5,30/5,1);//stop broadcast by groupno
                    //isStopBroadcast=true;
#endif
#if 1
    while(1){
        if((ping("8.8.8.8") == 0)||(ping("8.8.4.4") == 0)){
            LOG_I("net ok\n");
            while(!timeNew()){
                //LOG_I("sleep\n");
                getTimeCount++;
                if(getTimeCount==100){
                    break;    
                }
                sleep(1);
            }
            //saveStartUpTime();
            ret = pthread_create(&pt_mqtt,NULL,thread_mqtt,NULL);
            if(ret!=0){
                LOG_I("pthread_create mqtt fail\n");
                system("reboot");
            }else{
                pthread_detach(pt_mqtt);
                LOG_I("pthread_create mqtt success\n");
            }
            break;
        }else{
            LOG_I("net not ready\n");
            sleep(3);
        }
    }
#endif
    while(1)
    {
        fgets(command_buffer, sizeof(command_buffer), stdin);
        if(execute_command(command_buffer, (command_t *)&__start_command, (&__stop_command - &__start_command)/2) < 0)
        {
            LOG_I("unsupport command!\r\n");
        }
    }
    return 0;
}

