#include "yc_protocol.h"
#include "esp_log.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/queue.h"
#include "esp_mac.h"
#include "stdbool.h"
#include "esp_timer.h"
#include "list.h"
#include "user_time.h"
#include "freertos/event_groups.h"
#include "list.h"
#include  "wait_list.h"

#include<stdio.h>
#include<stdlib.h>
#include<time.h>

#include "driver/uart.h"
#include "freertos/timers.h"
#include "SPIFFS.h"




//声明一个TimerHandle_t类型的变量，用于存储定时器句柄

extern EventGroupHandle_t screen_event;


extern  int retry_times;

static const char *LOG_TAG = "yc_protocol";
// esp_timer_handle_t periodic_timer;
esp_timer_handle_t lora_timer;
TERMINAL_INFO_T terminal_info;  //  保存收到的lora数据



Button_Time_t last_button_info;
Button_Time_t new_button_info;



Button_Time_t _0703_button_info;




void changebintotxt(uint8_t *strb,int len);
Node *clockIn_list = NULL;  //打卡  n:crc(ID)   cmd:打卡类型  data:ID

extern char str_operation[6];//运行
extern char str_upKeep[6];//保养
extern char str_shutDown[6];//停机
extern char str_safeKeep[6];//封存
extern char str_waitMaterials[6];//待料
extern char str_breakDown[6];//故障


extern QueueHandle_t left_screen_queue;
uint8_t mac_addr[6];
extern QueueHandle_t right_screen_queue;

extern QueueHandle_t yc_data_queue;
extern YC_DATA_T yc_data;


//extern ListNode *list_head;
#define LEFT_FLAG   1
#define RIGHT_FLAG  2
static uint8_t display_flag = 0;//1:left  2:right
#if 1
#include "esp_attr.h"

RTC_FAST_ATTR Person_t  person[5]=
{    
  {.person_type = Administrator,       },
  {.person_type = product_person,       },
  {.person_type = repair_person,         },
  {.person_type = Maintenance_person,   },
  {.person_type = check_person,         },
  
};


#endif



void reset_default(bool is_dis)
{
    
    extern Machine_info_t default_info;
    Machine_info_t tmp ;
    memcpy(&tmp,&default_info,sizeof(Machine_info_t));
    tmp.power_status = 1;
    esp_read_mac((uint8_t *)tmp.mac_addr, ESP_MAC_WIFI_STA);
    memcpy(&tmp.cid,&Machine_info.cid,20);
    tmp.batt_precent = Machine_info.batt_precent;
    tmp.last_batt_precent = Machine_info.last_batt_precent;
    tmp.rssi = Machine_info.rssi;
    memcpy(&Machine_info,&tmp,sizeof(Machine_info_t));//恢复默认
    spiffs_write(&Machine_info);//保存Machine_info
    if(!is_dis)
    {
        return;
    }
    Paint_leftScreen_main_quick(&Machine_info);
    Paint_rightScreen_main_quick(&Machine_info);
}



#if 0
void insertNode_head(ListNode *head, ListNode *P);
void removeNode_byNumber(ListNode *head,uint16_t number);
ListNode *getListNode_byNumber(ListNode *head,uint16_t number);
ListNode *newListNode(uint16_t number,uint8_t type,char* name);
#endif

/*
*    使用 vTaskList() 前需使能:
*    Enable FreeRTOS trace facility
*    Enable FreeRTOS stats formatting functions
*/
void  print_systenInfo(void)
{
    printf("=================================\r\n");
    printf("=================================\r\n");
    printf("=================================\r\n");
    printf("=================================\r\n");
    printf("=================================\r\n");
    printf("========version V %d.%d.%d==========\r\n",VERSION_X,VERSION_Y,VERSION_Z);
    esp_efuse_mac_get_default((uint8_t*)mac_addr);
    esp_efuse_mac_get_default((uint8_t*)Machine_info.mac_addr);

    #if 1    //获取mac地址
    uint8_t macAddr[6];
	esp_read_mac((uint8_t *)macAddr, ESP_MAC_WIFI_STA);

    //保留以前的mac地址段 
    //mac_addr[0]+=0x02;
	{
		printf("mac addr : %02x:%02x:%02x:%02x:%02x:%02x\n", macAddr[0], macAddr[1], macAddr[2], macAddr[3], macAddr[4], macAddr[5]);
	}

    memcpy((uint8_t*)Machine_info.mac_addr,macAddr,6);

    //Machine_info.mac_addr[0]= Machine_info.mac_addr[0]+0x02;

	printf("Machine_info mac addr : %02x:%02x:%02x:%02x:%02x:%02x\n", Machine_info.mac_addr[0], Machine_info.mac_addr[1], Machine_info.mac_addr[2], Machine_info.mac_addr[3], Machine_info.mac_addr[4], Machine_info.mac_addr[5]);


    #endif

    printf("free_heap_size:%ld \r\n free_internal_heap_size:%ld \r\n minimum_free_heap_size:%ld\r\n",\
    esp_get_free_heap_size(),esp_get_free_internal_heap_size(),esp_get_minimum_free_heap_size());
#if 0
    ESP_LOGW(LOG_TAG,"mac:[%02x-%02x-%02x-%02x-%02x-%02x]",\
                mac_addr[0],mac_addr[1],mac_addr[2],mac_addr[3],mac_addr[4],mac_addr[05]);
    static char InfoBuffer[512] = {0};
    vTaskList((char*)&InfoBuffer);

    ESP_LOGW(LOG_TAG,"free_heap_size:%ld \nfree_internal_heap_size:%ld \nminimum_free_heap_size:%ld",\
    esp_get_free_heap_size(),esp_get_free_internal_heap_size(),esp_get_minimum_free_heap_size());

    printf("任务名      任务状态    优先级    剩余栈   任务序号\r\n");
    printf("\r\n%s\r\n", InfoBuffer);
#endif

}
void send_update_status(void);
void send_status_duration(void);

void terminal_send_data(void)
{
     //send_rssi();
     //vTaskDelay(100 / portTICK_PERIOD_MS);
    send_status_duration();
    //vTaskDelay(50 / portTICK_PERIOD_MS);
    send_update_status();
    //vTaskDelay(100 / portTICK_PERIOD_MS);
    
}
void update_last_button_info(uint8_t btn)
{
    #if 0
    memset(&last_button_info,0,sizeof(Button_Time_t));
    last_button_info.button_info = btn;
    
    last_button_info.Year = Machine_info.year;
    last_button_info.Month = Machine_info.month;
    last_button_info.Day = Machine_info.day;
    last_button_info.Hour = Machine_info.hour;
    last_button_info.Minute = Machine_info.min;
    last_button_info.Second = Machine_info.sec;
    ESP_LOGW(LOG_TAG,"btn = %d [%d-%d-%d]%d:%d:%d", btn, Machine_info.year,Machine_info.month,Machine_info.day,\
    Machine_info.hour, Machine_info.min,Machine_info.sec);
    //last_button_info.time_min = 0;
    #else
    //更新上次的状态
    //获取当前时间
    getRtcTime(&Machine_info);

    Machine_info.last_button.button_info = btn;
    Machine_info.last_button.Year =  Machine_info.year;
    Machine_info.last_button.Month = Machine_info.month;
    Machine_info.last_button.Day = Machine_info.day;
    Machine_info.last_button.Hour =  Machine_info.hour;
    Machine_info.last_button.Minute = Machine_info.min;
    Machine_info.last_button.Second = Machine_info.sec;
    Machine_info.last_button.time_min = 0x00000000;


    #endif
}
void screen_display(void)
{

    font_exit_sleep();
    // ESP_LOGW(LOG_TAG,"display_flag =%d\r\n",display_flag);
    // if(display_flag == 1)
    // {
    //     if(xQueueSend(left_screen_queue,&Machine_info,portMAX_DELAY) != true)
    //     {
    //         ESP_LOGE(LOG_TAG,"queue:left_screen_queue");
    //     }
    // }
    // //vTaskDelay(1000 / portTICK_PERIOD_MS);
    // else if(display_flag == 2)
    // {
    //     if(xQueueSend(right_screen_queue,&Machine_info,portMAX_DELAY) != true)
    //     {
    //         ESP_LOGE(LOG_TAG,"queue:right_screen_queue");
    //     }
    // }
    EventBits_t bits = xEventGroupWaitBits(screen_event,
            LEFT_SCREEN_BIT | RIGHT_SCREEN_BIT,
            pdTRUE,
            pdFALSE,
            0);
    ESP_LOGE(LOG_TAG,"xEventGroupWaitBits bits = %ld",bits);
    /* xEventGroupWaitBits() returns the bits before the call returned, hence we can test which event actually
     * happened. */
    if(bits == 3){

        printf("--------------------left right all screen---------------\r\n");
        while(1)
        {                         
            if( (right_refresh_timer_isActive() == false) )
            {
                printf("right refresh complete %s\r\n",right_refresh_timer_isActive()?"true":"false");
                break;
            }
                vTaskDelay(100/ portTICK_PERIOD_MS);
        }


        while(1)
        {                         
            if( (left_refresh_timer_isActive() == false) )
            {
                printf("2left refresh complete %s\r\n",left_refresh_timer_isActive()?"true":"false");
                break;
            }
                vTaskDelay(100/ portTICK_PERIOD_MS);
        }

        //Paint_leftScreen_main_quick(&Machine_info);

        if(xQueueSend(left_screen_queue,&Machine_info,portMAX_DELAY) != true)
        {
            ESP_LOGE(LOG_TAG,"queue:right_screen_queue");
        }




        vTaskDelay(2000/ portTICK_PERIOD_MS);
        // while(1)
        // {                         
        //     if( (left_refresh_timer_isActive() == false) )
        //     {
        //         printf("left refresh complete %s\r\n",left_refresh_timer_isActive()?"true":"false");
        //         break;
        //     }
        //         vTaskDelay(100/ portTICK_PERIOD_MS);
        // }

        
              while(1)
        {                         
            if( (right_refresh_timer_isActive() == false) )
            {
                printf("right refresh complete %s\r\n",right_refresh_timer_isActive()?"true":"false");
                break;
            }
                vTaskDelay(100/ portTICK_PERIOD_MS);
        }

        //Paint_rightScreen_main_quick(&Machine_info);

        if(xQueueSend(right_screen_queue,&Machine_info,portMAX_DELAY) != true)
        {
            ESP_LOGE(LOG_TAG,"queue:right_screen_queue");
        }

        // while(1)
        // {                         
        //     if( (right_refresh_timer_isActive() == false) )
        //     {
        //         printf("right refresh complete %s\r\n",right_refresh_timer_isActive()?"true":"false");
        //         break;
        //     }
        //         vTaskDelay(100/ portTICK_PERIOD_MS);
        // }

    }
    else if (bits & RIGHT_SCREEN_BIT) {
        ESP_LOGE(LOG_TAG,"RIGHT_SCREEN_BIT");

            while(1)
        {                         
            if( (left_refresh_timer_isActive() == false) )
            {
                printf("3left refresh complete %s\r\n",left_refresh_timer_isActive()?"true":"false");
                break;
            }
                vTaskDelay(100/ portTICK_PERIOD_MS);
        }



        
                while(1)
        {                         
            if( (right_refresh_timer_isActive() == false) )
            {
                printf("4left refresh complete %s\r\n",right_refresh_timer_isActive()?"true":"false");
                break;
            }
                vTaskDelay(100/ portTICK_PERIOD_MS);
        }




        if(xQueueSend(right_screen_queue,&Machine_info,portMAX_DELAY) != true)
        {
            ESP_LOGE(LOG_TAG,"queue:right_screen_queue");
        }
    } 
    else if (bits & LEFT_SCREEN_BIT) {
        


                    while(1)
        {                         
            if( (left_refresh_timer_isActive() == false) )
            {
                printf("5left refresh complete %s\r\n",left_refresh_timer_isActive()?"true":"false");
                break;
            }
                vTaskDelay(100/ portTICK_PERIOD_MS);
        }


                while(1)
        {                         
            if( (right_refresh_timer_isActive() == false) )
            {
                printf("6left refresh complete %s\r\n",right_refresh_timer_isActive()?"true":"false");
                break;
            }
                vTaskDelay(100/ portTICK_PERIOD_MS);
        }


        
        ESP_LOGE(LOG_TAG,"LEFT_SCREEN_BIT");
        if(xQueueSend(left_screen_queue,&Machine_info,portMAX_DELAY) != true)
        {
            ESP_LOGE(LOG_TAG,"queue:left_screen_queue");
        }
    } else {
        ESP_LOGE(LOG_TAG, "UNEXPECTED EVENT");
    }
}

void print_yc_data(const LORA_DATA_T* buf)
{

    int len = (buf->data_buf[13+2])<<8 | (buf->data_buf[14+2]);
    ESP_LOGI(LOG_TAG,"\n总长:0x%02x,crc:0x%02x,\
    \nmac:[%02x-%02x-%02x-%02x-%02x-%02x], \
    \n组内编号:%02x,\
    cmd:0x%02x,\
    总包数:%02x, 当前包:%02x,\
    \n有效数据 len:0x%d",\
    buf->data_len,buf->data_buf[4],\
    buf->data_buf[5],buf->data_buf[6],buf->data_buf[7],\
    buf->data_buf[8],buf->data_buf[9],buf->data_buf[10],\
    buf->data_buf[11],\
    buf->data_buf[12],\
    buf->data_buf[13],buf->data_buf[14],\
    len);

    for(int i=0;i < buf->data_len;i++)
    {
        printf("%02x ",buf->data_buf[i]);
        if(i == (USE_DATA_LEN_INDEX+1))
        {
            printf("data--->\n");
        }
    }
    printf("\n");
}
bool filtered_data(const LORA_DATA_T* buf)
{
    if(buf->data_buf[11] != Machine_info.eflagID)
    {
        if(Machine_info.eflagID == 0)
        {
            ESP_LOGE(LOG_TAG,"err:未分配ID");
        }

        ESP_LOGE(LOG_TAG,"err:eflagID:%02x ,is not %02x",\
        Machine_info.eflagID,buf->data_buf[11]);

        return false;
    }

    if((buf->data_buf[5] != Machine_info.mac_addr[0])||\
        (buf->data_buf[6] != Machine_info.mac_addr[1])||\
        (buf->data_buf[7] != Machine_info.mac_addr[2])||\
        (buf->data_buf[8] != Machine_info.mac_addr[3])||\
        (buf->data_buf[9] != Machine_info.mac_addr[4])||\
        (buf->data_buf[10] != Machine_info.mac_addr[5]))
    {
        ESP_LOGE(LOG_TAG,"err:mac addr:[%02x-%02x-%02x-%02x-%02x-%02x],\
                                    is not:[%02x-%02x-%02x-%02x-%02x-%02x]",\
            Machine_info.mac_addr[0],Machine_info.mac_addr[1],Machine_info.mac_addr[2],\
            Machine_info.mac_addr[3],Machine_info.mac_addr[4],Machine_info.mac_addr[5],\
            buf->data_buf[5],buf->data_buf[6],buf->data_buf[7],\
            buf->data_buf[8],buf->data_buf[9],buf->data_buf[10]);
        return false;
    }

    return true;
}
static int time_synchronization_func(const LORA_DATA_T* buf)
{
    int len = (buf->data_buf[USE_DATA_LEN_INDEX])<<8 | (buf->data_buf[USE_DATA_LEN_INDEX+1]);
    memcpy(terminal_info.time_synchronization,buf->data_buf+DATA_START_LEN,len);

    //yc_timer_restart();
    
    //Machine_info
    Machine_info.year = (terminal_info.time_synchronization[0] << 8) | terminal_info.time_synchronization[1];
    Machine_info.month = terminal_info.time_synchronization[2];
    Machine_info.day = terminal_info.time_synchronization[3];
    Machine_info.hour = terminal_info.time_synchronization[4];
    Machine_info.min = terminal_info.time_synchronization[5];
    Machine_info.sec = terminal_info.time_synchronization[6];
    display_flag = 0;


    setRtcTime(Machine_info.year, Machine_info.month,Machine_info.day, 
                Machine_info.hour,Machine_info.min,Machine_info.sec);




        printf("TIMER SYNC YEAR = %d,MONTH =%d,DAY=%d,HOUR=%d,MIN=%d,SEC =%d\r\n",
        Machine_info.year,
        Machine_info.month,
        Machine_info.day,
        Machine_info.hour,
        Machine_info.min,
        Machine_info.sec);


        getRtcTime(&Machine_info);

    //printf("msg h = %02X,msg l = %02X\r\n",buf->data_buf[13],buf->data_buf[14]);
    int msg_id = ( buf->data_buf[13]>>8)| buf->data_buf[14];  //获取当前消息id 用于删除
    //printf("msg_id =%X\r\n",msg_id);

    return msg_id;    
}
static int terminal_name_func(const LORA_DATA_T* buf)
{
    #define FONT_MAX_LEN    8
    uint8_t font_num = 0;   //获取当前的文字个数

    int i=0;
    
    int len = (buf->data_buf[USE_DATA_LEN_INDEX])<<8 | (buf->data_buf[USE_DATA_LEN_INDEX+1]);
    memset(terminal_info.terminal_name,0,32);
    memcpy(terminal_info.terminal_name,buf->data_buf+DATA_START_LEN,len);
    
    //memcpy(&Machine_info.terminal_name,&terminal_info.terminal_name,len);
    memset(Machine_info.terminal_name,0x00,sizeof(Machine_info.terminal_name)); //清除终端名称信息

    font_num = len/2;
    if(font_num<=FONT_MAX_LEN)
    {
        uincode2gbk((char*)terminal_info.terminal_name,len,(char*)Machine_info.terminal_name);
    }
    else
    {
        uincode2gbk((char*)terminal_info.terminal_name,FONT_MAX_LEN*2,(char*)Machine_info.terminal_name);
        strcat((char *)Machine_info.terminal_name,"...");
    }

    // printf("unicode:");
    // for(i=0;i<len;i++)
    // {
    //     printf("%02x ",terminal_info.terminal_name[i]);
    // }
    // printf("\n");
    // printf("gbk:");
    // for(i=0;i<len;i++)
    // {
    //     printf("%02x ",Machine_info.terminal_name[i]);
    // }

    // printf("setting name %s",Machine_info.terminal_name);
    // printf("\n");

    // display_flag = RIGHT_FLAG;
xEventGroupSetBits(screen_event, RIGHT_SCREEN_BIT);


    //printf("msg h = %02X,msg l = %02X\r\n",buf->data_buf[13],buf->data_buf[14]);
    int msg_id = ( buf->data_buf[13]>>8)| buf->data_buf[14];  //获取当前消息id 用于删除
    //printf("msg_id =%X\r\n",msg_id);


    return msg_id;    
  
}

static int terminal_number_func(const LORA_DATA_T* buf)
{
    int len = (buf->data_buf[USE_DATA_LEN_INDEX])<<8 | (buf->data_buf[USE_DATA_LEN_INDEX+1]);
    memcpy(terminal_info.terminal_number,buf->data_buf+DATA_START_LEN,len);
    //memcpy(&Machine_info.terminal_number,&terminal_info.terminal_number,len);
    memset(Machine_info.terminal_number,0x00,sizeof(Machine_info.terminal_number)); //清除终端名称信息

    uincode2gbk((char*)terminal_info.terminal_number,len,(char*)Machine_info.terminal_number);

    // printf("unicode:");
    // for(int i=0;i<len;i++)
    // {
    //     printf("%02x ",terminal_info.terminal_number[i]);
    // }
    // printf("\n");
    // printf("gbk:");
    // for(int i=0;i<len;i++)
    // {
    //     printf("%02x ",Machine_info.terminal_number[i]);
    // }

    printf("setting num %s",Machine_info.terminal_number);
    printf("\n");




    // display_flag = RIGHT_FLAG;
    xEventGroupSetBits(screen_event, RIGHT_SCREEN_BIT);

    //printf("msg h = %02X,msg l = %02X\r\n",buf->data_buf[13],buf->data_buf[14]);
    int msg_id = ( buf->data_buf[13]>>8)| buf->data_buf[14];  //获取当前消息id 用于删除
    //printf("msg_id =%X\r\n",msg_id);


    return msg_id;    
}
static int electric_quantity_func(const LORA_DATA_T* buf)
{
    terminal_info.batt_percent = buf->data_buf[DATA_START_LEN];

    ESP_LOGI(LOG_TAG,"batt_percent : %d",terminal_info.batt_percent);
    // display_flag = RIGHT_FLAG;
    xEventGroupSetBits(screen_event, RIGHT_SCREEN_BIT);
    //printf("msg h = %02X,msg l = %02X\r\n",buf->data_buf[13],buf->data_buf[14]);
    int msg_id = ( buf->data_buf[13]>>8)| buf->data_buf[14];  //获取当前消息id 用于删除
    //printf("msg_id =%X\r\n",msg_id);
    return msg_id;    
}
static int signal_strength_func(const LORA_DATA_T* buf)
{
    // terminal_info.rssi = buf->data_buf[DATA_START_LEN];
    // ESP_LOGI(LOG_TAG,"rssi : %d",terminal_info.rssi);

    // Machine_info.rssi = terminal_info.rssi;
    
    // display_flag = RIGHT_FLAG;

    //printf("msg h = %02X,msg l = %02X\r\n",buf->data_buf[13],buf->data_buf[14]);
    int msg_id = ( buf->data_buf[13]>>8)| buf->data_buf[14];  //获取当前消息id 用于删除
    //printf("msg_id =%X\r\n",msg_id);


    return msg_id;    
}

static int screen_refresh_cycle_func(const LORA_DATA_T* buf)
{
    terminal_info.refresh_cycle = buf->data_buf[DATA_START_LEN];
    ESP_LOGI(LOG_TAG,"refresh_cycle : %d",terminal_info.refresh_cycle);
    Machine_info.refresh_cycle = terminal_info.refresh_cycle;
    // display_flag = RIGHT_FLAG;
    xEventGroupSetBits(screen_event, RIGHT_SCREEN_BIT);

    //printf("msg h = %02X,msg l = %02X\r\n",buf->data_buf[13],buf->data_buf[14]);
    int msg_id = ( buf->data_buf[13]>>8)| buf->data_buf[14];  //获取当前消息id 用于删除
    //printf("msg_id =%X\r\n",msg_id);


    return msg_id;    
}

static int screen_left_func(const LORA_DATA_T* buf)
{
    terminal_info.left_epd = buf->data_buf[DATA_START_LEN];
    ESP_LOGI(LOG_TAG,"left_epd : %d",terminal_info.left_epd);
    Machine_info.left_display_mode = terminal_info.left_epd;

    // display_flag = LEFT_FLAG;
    xEventGroupSetBits(screen_event, LEFT_SCREEN_BIT);

    //printf("msg h = %02X,msg l = %02X\r\n",buf->data_buf[13],buf->data_buf[14]);
    int msg_id = ( buf->data_buf[13]>>8)| buf->data_buf[14];  //获取当前消息id 用于删除
    //printf("msg_id =%X\r\n",msg_id);
    return msg_id;    
}
static int screen_right_func(const LORA_DATA_T* buf)
{
    terminal_info.right_epd = buf->data_buf[DATA_START_LEN];
    Machine_info.right_display_mode = terminal_info.right_epd;
    ESP_LOGW(LOG_TAG,"-----right_epd : %d",terminal_info.right_epd);

    // display_flag = RIGHT_FLAG;
    xEventGroupSetBits(screen_event, RIGHT_SCREEN_BIT);

    //printf("msg h = %02X,msg l = %02X\r\n",buf->data_buf[13],buf->data_buf[14]);
    int msg_id = ( buf->data_buf[13]>>8)| buf->data_buf[14];  //获取当前消息id 用于删除
    //printf("msg_id =%X\r\n",msg_id);


    return msg_id;    
}
static int rsponsible_person_change_func(const LORA_DATA_T* buf)
{   
    int len = ((buf->data_buf[USE_DATA_LEN_INDEX])<<8) | ((buf->data_buf[USE_DATA_LEN_INDEX+1]));

//    for(int i = 0;i<buf->data_len;i++)
//    {
//         printf("%02X",buf->data_buf[i]);
//    }

    int msg_id = ( buf->data_buf[13]>>8)| buf->data_buf[14];  //获取当前消息id 用于删除


    ESP_LOGW(LOG_TAG,"tmp name len = %d",len);

    memcpy(terminal_info.rsponsible_person_change,buf->data_buf+DATA_START_LEN,len);
    //ESP_LOGI(LOG_TAG,"mode:[%02x] len = %d",terminal_info.rsponsible_person_change[2],len);
    uint16_t tmp_number;
    uint8_t tmp_type;

    if(len == 3)
    {
         return msg_id;    
    }else{

            char* tmp_name;
            tmp_name = (char*)malloc((len-3+1));

                memset(tmp_name,0x00,(len-3+1));

                uincode2gbk((char*)terminal_info.rsponsible_person_change+3,(len-3),tmp_name);

                // printf("tmp_name = %s\r\n",tmp_name);
                tmp_name[len-2] = '\0';
                //memcpy(tmp_name,(char*)terminal_info.rsponsible_person_change+3,len-3);

            #if 0
                for(int i=0;i<strlen(tmp_name);i++)
                {
                    printf("%02x ",tmp_name[i]);
                }
                printf("\n%d\n",strlen(tmp_name));
            #endif
                tmp_number = (terminal_info.rsponsible_person_change[0]<<8)|(terminal_info.rsponsible_person_change[1]&0xFF);
                tmp_type = terminal_info.rsponsible_person_change[2];

                #if 0
                ListNode *p = newListNode(tmp_number,tmp_type,tmp_name);
                insertNode_head(list_head,p);
                #else


                memset(Machine_info.person[tmp_type].string_name,0x00,sizeof(Machine_info.person[tmp_type].string_name));
                person_add(tmp_type ,tmp_number,tmp_name,Machine_info.person[tmp_type].string_name);
                ESP_LOGE(LOG_TAG,"add name = %s\r\n",Machine_info.person[tmp_type].string_name);
                #endif


                // display_flag = RIGHT_FLAG;
                xEventGroupSetBits(screen_event, RIGHT_SCREEN_BIT);

                //printf("msg h = %02X,msg l = %02X\r\n",buf->data_buf[13],buf->data_buf[14]);
             
                //printf("msg_id =%X\r\n",msg_id);
                free(tmp_name);
                tmp_name = NULL;
 }


    return msg_id;    

}

static int rsponsible_person_delete_func(const LORA_DATA_T* buf)
{
    uint16_t tmp_number;
    uint8_t tmp_type;

    int len = (buf->data_buf[USE_DATA_LEN_INDEX])<<8 | (buf->data_buf[USE_DATA_LEN_INDEX+1]);

    memcpy(terminal_info.rsponsible_person_delete,buf->data_buf+DATA_START_LEN,len);


    tmp_number = (terminal_info.rsponsible_person_delete[0]<<8)|(terminal_info.rsponsible_person_delete[1]&0xFF);
    tmp_type = terminal_info.rsponsible_person_delete[2];


    #if 1
         int num = person_get_num(tmp_type);  //获取当前类型人员数量

          int is_exist = person_get_num_is_exist(tmp_type,tmp_number);

          if(is_exist) 
          {
            memset(Machine_info.person[tmp_type].string_name,0x00,sizeof(Machine_info.person[tmp_type].string_name));
            person_del(tmp_type ,tmp_number,NULL,Machine_info.person[tmp_type].string_name);
          }


    #endif


    // display_flag = RIGHT_FLAG;
xEventGroupSetBits(screen_event, RIGHT_SCREEN_BIT);
xEventGroupSetBits(screen_event, LEFT_SCREEN_BIT);
    //printf("msg h = %02X,msg l = %02X\r\n",buf->data_buf[13],buf->data_buf[14]);
    int msg_id = ( buf->data_buf[13]>>8)| buf->data_buf[14];  //获取当前消息id 用于删除
    //printf("msg_id =%X\r\n",msg_id);

    return msg_id;    
}
// #define SET_BIT(flag,_bit) 			(flag |= (0x01 << _bit))
// #define CLE_BIT(flag,_bit) 			(flag &= ~(0x01 << _bit))
static int production_punch_func(const LORA_DATA_T* buf)
{
    int len = (buf->data_buf[USE_DATA_LEN_INDEX])<<8 | (buf->data_buf[USE_DATA_LEN_INDEX+1]);
    memcpy(terminal_info.production_punch,buf->data_buf+DATA_START_LEN,len);    
    ESP_LOG_BUFFER_HEX(LOG_TAG,terminal_info.production_punch,len);
    if(terminal_info.production_punch[1] == 0)  
    {
        Machine_info.checkIn_set[terminal_info.production_punch[0]].checkIn_close = true;//关闭该类型打卡
    }
    else
    {
        Machine_info.checkIn_set[terminal_info.production_punch[0]].checkIn_close = false;//开启该类型打卡
    }

    ESP_LOGW(LOG_TAG,"打卡设置： 类型[%d]  %s",terminal_info.production_punch[0],terminal_info.production_punch[1]?"开启":"关闭");

    if(len > 2)//数据长度大于2 ，说明设置了别名
    {
        memset(Machine_info.checkIn_set[terminal_info.production_punch[0]].other_name,0,10);
        // memcpy(Machine_info.checkIn_set[terminal_info.production_punch[0]].other_name,terminal_info.production_punch+2,len-2);
        uincode2gbk((char*)terminal_info.production_punch+2,len-2,(char*)Machine_info.checkIn_set[terminal_info.production_punch[0]].other_name);
    }
    // display_flag = RIGHT_FLAG;
    xEventGroupSetBits(screen_event, RIGHT_SCREEN_BIT);
    xEventGroupSetBits(screen_event, LEFT_SCREEN_BIT);
    int msg_id = ( buf->data_buf[13]>>8)| buf->data_buf[14];  //获取当前消息id 用于删除

    return msg_id;
}
static int personnel_check_in_func(const LORA_DATA_T* buf)
{
    //ESP_LOGI(LOG_TAG,"check in : %s,person type : 0x%02x",buf->data_buf[DATA_START_LEN+1] ? "OUT":"IN",buf->data_buf[DATA_START_LEN]);
    int len = (buf->data_buf[USE_DATA_LEN_INDEX])<<8 | (buf->data_buf[USE_DATA_LEN_INDEX+1]);
    memcpy(terminal_info.personnel_check_in,buf->data_buf+DATA_START_LEN,len); 

    //printf("msg h = %02X,msg l = %02X\r\n",buf->data_buf[13],buf->data_buf[14]);
    int msg_id = ( buf->data_buf[13]>>8)| buf->data_buf[14];  //获取当前消息id 用于删除
    //printf("msg_id =%X\r\n",msg_id);

    // display_flag = RIGHT_FLAG;
    xEventGroupSetBits(screen_event, RIGHT_SCREEN_BIT);
    xEventGroupSetBits(screen_event, LEFT_SCREEN_BIT);
    ESP_LOG_BUFFER_HEX(LOG_TAG,terminal_info.personnel_check_in,len);
    int ID_crc = crc8(&terminal_info.personnel_check_in[2],len-2,0x5a,0x51);//lora_crc8( , ,0x5a,0x51);暂定对人员id求crc
    ESP_LOGW(LOG_TAG,"打卡类型[%d] %s ,ID_crc = %d",terminal_info.personnel_check_in[0],Machine_info.checkIn_set[terminal_info.personnel_check_in[0]].checkIn_close?"关闭":"开启",ID_crc);
    if(!(Machine_info.checkIn_set[terminal_info.personnel_check_in[0]].checkIn_close))//开启打卡
    {
        if(terminal_info.personnel_check_in[1] == 0x00)//打卡签入
        {
            // Machine_info.personnel_check_in[terminal_info.personnel_check_in[0]]++;
            // Node *find  = findNode(Send_list,msg_id);
            Machine_info.checkIn_set[terminal_info.personnel_check_in[0]].number++;
            Node *find  = findNode(clockIn_list,ID_crc);
            // printList(clockIn_list);
            if(find==NULL)
            {
                Machine_info.checkIn_set[terminal_info.personnel_check_in[0]].real_number++;
                clockIn_list = postInsert(clockIn_list,ID_crc,terminal_info.personnel_check_in[0],(&terminal_info.personnel_check_in)+2,len-2);
            }
            else
            {
                ESP_LOGE(LOG_TAG,"该人员已存在");
            }

        }
        else if(terminal_info.personnel_check_in[1] == 0x01)//check out
        {
            Node *find  = findNode(clockIn_list,ID_crc);
            if(find!=NULL)
            {
                clockIn_list = deleteNode(clockIn_list,ID_crc);
                Machine_info.checkIn_set[terminal_info.personnel_check_in[0]].real_number--;
            }
        }
        else
        {
            ESP_LOGE(LOG_TAG,"err:not in or out");
        }
    }
    //printList(clockIn_list);
    return msg_id;    
} 
uint8_t change_btn_reversal(uint8_t reversal_btn);
static void set_button_anotherName(void)//cmd 0x0d操作
{
    uint8_t tmp = change_btn_reversal(terminal_info.status_setting[0]);
    if((terminal_info.status_setting[0] == 0)&&(terminal_info.status_setting[1] == 0))
    {//[0]:状态  [1]:开关   ————>运行不能关闭，这两位都为0，说明没有收到信息
        // ESP_LOGW(LOG_TAG,"默认按键");
        return ;//没有cmd[0x0d]的lora信息
    }
    if(terminal_info.status_setting[1] == 0x00)//close
    {
        
        Machine_info.btn_dis_flag[tmp-1] = false;
        ESP_LOGE(LOG_TAG,"按键状态关闭，清空按键文字 状态%d",tmp);
        switch (terminal_info.status_setting[0])//按键状态关闭，清空按键文字
        {
        case 0x00:
            memset(Machine_info.btn_operation,0,6);
            break;
        case 0x01:
            memset(Machine_info.btn_waitMaterials_info,0,6);
            break;
        case 0x02:
            memset(Machine_info.btn_safeKeep_info,0,6);
            break;
        case 0x03:
            memset(Machine_info.btn_breakDown_info,0,6);
            break;
        case 0x04:
            memset(Machine_info.btn_upKeep_info,0,6);
            break;
        case 0x05:
            memset(Machine_info.btn_shutDown_info,0,6);
            break;        
        default:
            ESP_LOGE(LOG_TAG,"err:按键状态%d",__LINE__);
            break;
        }
    }
    else if(terminal_info.status_setting[1] == 0x01)//open 
    {
        Machine_info.btn_dis_flag[tmp-1] = true;
        //ESP_LOGW(LOG_TAG,"别名：[%02x %02x %02x %02x]",terminal_info.status_setting[2],terminal_info.status_setting[3],terminal_info.status_setting[4],terminal_info.status_setting[5]);
        if((terminal_info.status_setting[2] == 0x00) && (terminal_info.status_setting[3] == 0x00))
        {//别名为两个字，这判断第一个字为空,为空就赋值初始化的按键信息
            ESP_LOGE(LOG_TAG,"button is open[other name is NULL] %d",terminal_info.status_setting[0]);
            switch (terminal_info.status_setting[0])
            {
            case 0x00://运行
                printf("clear btn_operation display\r\n");
                memcpy(Machine_info.btn_operation,str_operation,6);
                break;
            case 0x01://待料
                printf("clear btn_waitMaterials_info display\r\n");
                memcpy(Machine_info.btn_waitMaterials_info,str_waitMaterials,6);
                break;
            case 0x02://封存
                printf("clear btn_safeKeep_info display\r\n");
                memcpy(Machine_info.btn_safeKeep_info,str_safeKeep,6);
                break;
            case 0x03://故障
                printf("clear btn_breakDown_info display\r\n");
                memcpy(Machine_info.btn_breakDown_info,str_breakDown,6);
                break;
            case 0x04://保养
                printf("clear btn_upKeep_info display\r\n");
                memcpy(Machine_info.btn_upKeep_info,str_upKeep,6);
                break;
            case 0x05://停机
                printf("clear btn_shutDown_info display\r\n");
                memcpy(Machine_info.btn_shutDown_info,str_shutDown,6);
                break;
            default:
                printf("other btn_operation display\r\n");
                ESP_LOGE(LOG_TAG,"err:按键状态%d",__LINE__);
                break;
            }
        }
        else
        {
           // ESP_LOGW(LOG_TAG,"button is open[other name] %d",terminal_info.status_setting[0]);
            switch (terminal_info.status_setting[0])
            {
            case 0x00:
                memset(Machine_info.btn_operation,0,6);
                uincode2gbk((char*)terminal_info.status_setting + 2,4,(char*)Machine_info.btn_operation);
                //ESP_LOG_BUFFER_HEX(LOG_TAG,&Machine_info.btn_operation,6);
                break;
            case 0x01:
                memset(Machine_info.btn_waitMaterials_info,0,6);
                uincode2gbk((char*)terminal_info.status_setting + 2,4,(char*)Machine_info.btn_waitMaterials_info);
                //ESP_LOG_BUFFER_HEX(LOG_TAG,&Machine_info.btn_waitMaterials_info,6);
                break;
            case 0x02:
                memset(Machine_info.btn_safeKeep_info,0,6);
                uincode2gbk((char*)terminal_info.status_setting + 2,4,(char*)Machine_info.btn_safeKeep_info);
                //ESP_LOG_BUFFER_HEX(LOG_TAG,&Machine_info.btn_safeKeep_info,6);
                break;
            case 0x03:
                memset(Machine_info.btn_breakDown_info,0,6);
                uincode2gbk((char*)terminal_info.status_setting + 2,4,(char*)Machine_info.btn_breakDown_info);
                //ESP_LOG_BUFFER_HEX(LOG_TAG,&Machine_info.btn_breakDown_info,6);
                break;
            case 0x04:
                memset(Machine_info.btn_upKeep_info,0,6);
                uincode2gbk((char*)terminal_info.status_setting + 2,4,(char*)Machine_info.btn_upKeep_info);
                //ESP_LOG_BUFFER_HEX(LOG_TAG,&Machine_info.btn_upKeep_info,6);
                break;
            case 0x05:
                memset(Machine_info.btn_shutDown_info,0,6);
                uincode2gbk((char*)terminal_info.status_setting + 2,4,(char*)Machine_info.btn_shutDown_info);
                //ESP_LOG_BUFFER_HEX(LOG_TAG,&Machine_info.btn_shutDown_info,6);
                break;        
            default:
                ESP_LOGE(LOG_TAG,"err:按键状态%d",__LINE__);
                break;
            }
        }
    }
    else
    {
        ESP_LOGE(LOG_TAG,"not open or close");
    }

}
uint8_t change_btn(uint8_t btn);

static int status_setting_func(const LORA_DATA_T* buf)
{
    int len = (buf->data_buf[USE_DATA_LEN_INDEX])<<8 | (buf->data_buf[USE_DATA_LEN_INDEX+1]);

    memset(terminal_info.status_setting,0x00,sizeof(terminal_info.status_setting));
    memcpy(terminal_info.status_setting,buf->data_buf+DATA_START_LEN,len);  //别名 
    ESP_LOGE(LOG_TAG,"len = %d ",len);
    ESP_LOG_BUFFER_HEX(LOG_TAG,terminal_info.status_setting,10);
    set_button_anotherName();
    //当前按键状态关闭了
    if((change_btn(Machine_info.left_state) == terminal_info.status_setting[0]) && (Machine_info.btn_dis_flag[Machine_info.left_state-1] == false))
    {
        ESP_LOGE(LOG_TAG,"按键发送");
        send_button_key_queue(STATE_OPERATION);
    }
    else
    {
        // display_flag = LEFT_FLAG;
        xEventGroupSetBits(screen_event, LEFT_SCREEN_BIT);
    }
    ESP_LOGW(LOG_TAG,"按键 :%s  %s  %s  %s  %s  %s",\
                                                    Machine_info.btn_dis_flag[0]?"开启":"关闭",\
                                                    Machine_info.btn_dis_flag[1]?"开启":"关闭",\
                                                    Machine_info.btn_dis_flag[2]?"开启":"关闭",\
                                                    Machine_info.btn_dis_flag[3]?"开启":"关闭",\
                                                    Machine_info.btn_dis_flag[4]?"开启":"关闭",\
                                                    Machine_info.btn_dis_flag[5]?"开启":"关闭");

    int msg_id = ( buf->data_buf[13]>>8)| buf->data_buf[14];  //获取当前消息id 用于删除
    return msg_id;

}
static int status_duration_func(const LORA_DATA_T* buf)
{
    int len = (buf->data_buf[USE_DATA_LEN_INDEX])<<8 | (buf->data_buf[USE_DATA_LEN_INDEX+1]);
    memcpy(terminal_info.status_duration,buf->data_buf+DATA_START_LEN,len);    


    //printf("msg h = %02X,msg l = %02X\r\n",buf->data_buf[13],buf->data_buf[14]);
    int msg_id = ( buf->data_buf[13]>>8)| buf->data_buf[14];  //获取当前消息id 用于删除
    //printf("msg_id =%X\r\n",msg_id);
    return msg_id;    

}

static int update_and_duration_func(const LORA_DATA_T* buf)
{
    int len = (buf->data_buf[USE_DATA_LEN_INDEX])<<8 | (buf->data_buf[USE_DATA_LEN_INDEX+1]);
    memcpy(terminal_info.update_and_duration,buf->data_buf+DATA_START_LEN,len);   
    
    //printf("msg h = %02X,msg l = %02X\r\n",buf->data_buf[13],buf->data_buf[14]);
    int msg_id = ( buf->data_buf[13]>>8)| buf->data_buf[14];  //获取当前消息id 用于删除
    //printf("msg_id =%X\r\n",msg_id);

    return msg_id;

}
static int announcement_func(const LORA_DATA_T* buf)
{
    int len = (buf->data_buf[USE_DATA_LEN_INDEX])<<8 | (buf->data_buf[USE_DATA_LEN_INDEX+1]);
    memcpy(terminal_info.announcement,buf->data_buf+DATA_START_LEN,len);   //拷贝公告
    ESP_LOG_BUFFER_HEX(LOG_TAG,terminal_info.announcement,len);
    ESP_LOGW(LOG_TAG,"设置公告");
    //memcpy(&Machine_info.terminal_name,&terminal_info.terminal_name,len);
    memset(Machine_info.announcement,0x00,sizeof(Machine_info.announcement)); //清除终端公告信息
    uincode2gbk((char*)terminal_info.announcement,len,(char*)Machine_info.announcement);
    

    // printf("unicode:");
    // for(i=0;i<len;i++)
    // {
    //     printf("%02x ",terminal_info.terminal_name[i]);
    // }
    // printf("\n");
    // printf("gbk:");
    // for(i=0;i<len;i++)
    // {
    //     printf("%02x ",Machine_info.terminal_name[i]);
    // }

    // printf("setting gong gao %s",Machine_info.announcement);
    // printf("\n");

    // display_flag = RIGHT_FLAG;
    xEventGroupSetBits(screen_event, RIGHT_SCREEN_BIT);

     //printf("msg h = %02X,msg l = %02X\r\n",buf->data_buf[13],buf->data_buf[14]);
    int msg_id = ( buf->data_buf[13]>>8)| buf->data_buf[14];  //获取当前消息id 用于删除
    //printf("msg_id =%X\r\n",msg_id);
    return msg_id;    
 

}

void set_statisticsData(uint8_t* data)
{
    // memset(&Machine_info.num_goodProducts,0,32);
    // memset(&Machine_info.num_badProducts,0,32);
    #define __DATA_SIZE  24
    for(int i=0;i<8;i++)
    {   
        
        Machine_info.num_goodProducts[i] = (data[0+i*__DATA_SIZE]<<24)|(data[1+i*__DATA_SIZE]<<16)|(data[2+i*__DATA_SIZE]<<8)|(data[3+i*__DATA_SIZE]);
        Machine_info.num_badProducts[i] = (data[4+i*__DATA_SIZE]<<24)|(data[5+i*__DATA_SIZE]<<16)|(data[6+i*__DATA_SIZE]<<8)|(data[7+i*__DATA_SIZE]);
        Machine_info.scale_UR_int[i] = (data[8+i*__DATA_SIZE]);
        Machine_info.scale_UR_dec[i] = (data[9+i*__DATA_SIZE]);
        Machine_info.scale_YR_int[i] = (data[10+i*__DATA_SIZE]);
        Machine_info.scale_YR_dec[i] = (data[11+i*__DATA_SIZE]);
        Machine_info.num_manHour[i] = (data[12+i*__DATA_SIZE]<<8)|(data[13+i*__DATA_SIZE]);
        Machine_info.num_people[i] = (data[14+i*__DATA_SIZE]<<8)|(data[15+i*__DATA_SIZE]);
        Machine_info.num_production[i] = (data[16+i*__DATA_SIZE]<<8)|(data[17+i*__DATA_SIZE]);
        Machine_info.num_repair[i] = (data[18+i*__DATA_SIZE]<<8)|(data[19+i*__DATA_SIZE]);
        Machine_info.num_inspection[i] = (data[20+i*__DATA_SIZE]<<8)|(data[21+i*__DATA_SIZE]);
        Machine_info.num_upkeep[i] = (data[22+i*__DATA_SIZE]<<8)|(data[23+i*__DATA_SIZE]);
        //ESP_LOGW(LOG_TAG,"good:[%ld] bad[%ld]",Machine_info.num_goodProducts[i],Machine_info.num_badProducts[i]);
    }
}
static int capacity_statistics_func(const LORA_DATA_T* buf)
{
    #if 1
    int len = (buf->data_buf[USE_DATA_LEN_INDEX])<<8 | (buf->data_buf[USE_DATA_LEN_INDEX+1]);
    memcpy(terminal_info.capacity_statistics,buf->data_buf+DATA_START_LEN,len);   

    #endif

    //printf("msg h = %02X,msg l = %02X\r\n",buf->data_buf[13],buf->data_buf[14]);
    int msg_id = ( buf->data_buf[13]>>8)| buf->data_buf[14];  //获取当前消息id 用于删除
    //printf("msg_id =%X\r\n",msg_id);
    set_statisticsData(terminal_info.capacity_statistics);

        // display_flag = RIGHT_FLAG;
        xEventGroupSetBits(screen_event, RIGHT_SCREEN_BIT);

    return msg_id;     
}
static int responsible_person_synchronize_info_func(const LORA_DATA_T* buf)
{
    int len = (buf->data_buf[USE_DATA_LEN_INDEX])<<8 | (buf->data_buf[USE_DATA_LEN_INDEX+1]);
    memcpy(terminal_info.responsible_person_synchronize_info,buf->data_buf+DATA_START_LEN,len);    

    //printf("msg h = %02X,msg l = %02X\r\n",buf->data_buf[13],buf->data_buf[14]);
    int msg_id = ( buf->data_buf[13]>>8)| buf->data_buf[14];  //获取当前消息id 用于删除
    //printf("msg_id =%X\r\n",msg_id);

        // display_flag = RIGHT_FLAG;
        xEventGroupSetBits(screen_event, RIGHT_SCREEN_BIT);

    return msg_id;    

}
static int status_led_func(const LORA_DATA_T* buf)
{
    terminal_info.states_led = buf->data_buf[DATA_START_LEN];
    //printf("msg h = %02X,msg l = %02X\r\n",buf->data_buf[13],buf->data_buf[14]);
    int msg_id = ( buf->data_buf[13]>>8)| buf->data_buf[14];  //获取当前消息id 用于删除
    //printf("msg_id =%X\r\n",msg_id);

    return msg_id;
}
static int logo_led_func(const LORA_DATA_T* buf)
{
    terminal_info.logo_led = buf->data_buf[DATA_START_LEN];

    //printf("msg h = %02X,msg l = %02X\r\n",buf->data_buf[13],buf->data_buf[14]);
    int msg_id = ( buf->data_buf[13]>>8)| buf->data_buf[14];  //获取当前消息id 用于删除
    //printf("msg_id =%X\r\n",msg_id);


    return msg_id;    
}
static int battery_temperature_func(const LORA_DATA_T* buf)
{
    terminal_info.batt_temperature[0] = buf->data_buf[DATA_START_LEN];
    terminal_info.batt_temperature[1] = buf->data_buf[DATA_START_LEN+1];

    //printf("msg h = %02X,msg l = %02X\r\n",buf->data_buf[13],buf->data_buf[14]);
    int msg_id = ( buf->data_buf[13]>>8)| buf->data_buf[14];  //获取当前消息id 用于删除
    //printf("msg_id =%X\r\n",msg_id);
    return msg_id;    
}
static int station_name_func(const LORA_DATA_T* buf)
{
    #define FONT_MAX_LEN  8
    uint8_t font_num = 0;   //获取当前的文字个数
    int i=0;
    int len = (buf->data_buf[USE_DATA_LEN_INDEX])<<8 | (buf->data_buf[USE_DATA_LEN_INDEX+1]);
    memset(terminal_info.station_name,0,32);
    memcpy(terminal_info.station_name,buf->data_buf+DATA_START_LEN,len);
    
    //memcpy(&Machine_info.terminal_name,&terminal_info.terminal_name,len);
    memset(Machine_info.station_name,0x00,sizeof(Machine_info.station_name)); //清除终端名称信息

    font_num = len/2;
    if(font_num<=FONT_MAX_LEN)
    {
        uincode2gbk((char*)terminal_info.station_name,len,(char*)Machine_info.station_name);
    }
    else
    {
        uincode2gbk((char*)terminal_info.station_name,FONT_MAX_LEN*2,(char*)Machine_info.station_name);
        strcat((char *)Machine_info.station_name,"...");
    }
    // display_flag = RIGHT_FLAG;
    xEventGroupSetBits(screen_event, RIGHT_SCREEN_BIT);

    int msg_id = ( buf->data_buf[13]>>8)| buf->data_buf[14];  //获取当前消息id 用于删除
    return msg_id;   
}
static int station_number_func(const LORA_DATA_T* buf)
{
    int len = (buf->data_buf[USE_DATA_LEN_INDEX])<<8 | (buf->data_buf[USE_DATA_LEN_INDEX+1]);
    memcpy(terminal_info.station_number,buf->data_buf+DATA_START_LEN,len);
    memset(Machine_info.station_number,0x00,sizeof(Machine_info.station_number));

    uincode2gbk((char*)terminal_info.station_number,len,(char*)Machine_info.station_number);

    // display_flag = RIGHT_FLAG;
    xEventGroupSetBits(screen_event, RIGHT_SCREEN_BIT);

    int msg_id = ( buf->data_buf[13]>>8)| buf->data_buf[14];  //获取当前消息id 用于删除
    return msg_id;      
}
static int responsible_person_setup_func(const LORA_DATA_T* buf)
{
    int len = (buf->data_buf[USE_DATA_LEN_INDEX])<<8 | (buf->data_buf[USE_DATA_LEN_INDEX+1]);

    ESP_LOG_BUFFER_HEX(LOG_TAG,buf->data_buf + DATA_START_LEN,len);
    ESP_LOGE(LOG_TAG,"设置责任人 类型[%d]%s",buf->data_buf[DATA_START_LEN],buf->data_buf[DATA_START_LEN+1]?"开启":"关闭");
    if(buf->data_buf[DATA_START_LEN+1] == 0x01)//开
    {
        Machine_info.person[buf->data_buf[DATA_START_LEN]].Charge_close = false;
        memset(Machine_info.person[buf->data_buf[DATA_START_LEN]].other_name,0,16);
        uincode2gbk(buf->data_buf+DATA_START_LEN +2,len-2,(char*)Machine_info.person[buf->data_buf[DATA_START_LEN]].other_name);
        // ESP_LOG_BUFFER_HEX(LOG_TAG,Machine_info.person[buf->data_buf[DATA_START_LEN]].other_name,len);
    }
    else if(buf->data_buf[DATA_START_LEN+1] == 0x00)//关
    {
        Machine_info.person[buf->data_buf[DATA_START_LEN]].Charge_close = true;
    }
       ESP_LOGE(LOG_TAG,"Charge_close %d %d %d %d %d",Machine_info.person[0].Charge_close,Machine_info.person[1].Charge_close,Machine_info.person[2].Charge_close,\
    Machine_info.person[3].Charge_close,Machine_info.person[4].Charge_close);
    // display_flag = RIGHT_FLAG;
    xEventGroupSetBits(screen_event, RIGHT_SCREEN_BIT);
    int msg_id = ( buf->data_buf[13]>>8)| buf->data_buf[14];  //获取当前消息id 用于删除
    return msg_id;    
}
static int system_bulletin_func(const LORA_DATA_T* buf)
{
    ESP_LOGE(LOG_TAG,"system_bulletin_func");
    int len = (buf->data_buf[USE_DATA_LEN_INDEX])<<8 | (buf->data_buf[USE_DATA_LEN_INDEX+1]);
    memcpy(terminal_info.systemMessage,buf->data_buf+DATA_START_LEN,len); 
    memset(Machine_info.systemMessage,0x00,sizeof(Machine_info.systemMessage)); 
    uincode2gbk((char*)terminal_info.systemMessage,len,(char*)Machine_info.systemMessage);
    
    int msg_id = ( buf->data_buf[13]>>8)| buf->data_buf[14];  //获取当前消息id 用于删除
    return msg_id;    
}

static int hardware_update_func(const LORA_DATA_T* buf)
{
    //printf("msg h = %02X,msg l = %02X\r\n",buf->data_buf[13],buf->data_buf[14]);
    int msg_id = ( buf->data_buf[13]>>8)| buf->data_buf[14];  //获取当前消息id 用于删除
    //printf("msg_id =%X\r\n",msg_id);
    return msg_id;    

}


/*硬件回复命令ACK*/  /*长度 返回result结果及长度*/ 


/*********************************************************************************
* function   :   reply_ack_func  
* Description :  回复ACK cmd 指定命令      
* Input       :  cmd 命令  msg_id 当前的ID号 用于网关删除自身的已经接受到ACK 的数据  result 返回当前的数据 
* Output      :  
* Author      :  祁鑫                  Data : 2023 8.12
**********************************************************************************/
int reply_ack_func(int cmd,int msg_id,bool is_send,uint8_t *result)
{

    uint8_t strlorabuf[50]={0};
    uint8_t mac[6] = {0};

    strlorabuf[0]=0x5A;
    strlorabuf[1]=0x51;
    strlorabuf[2]=0x00; //crc

    //int byteArrayLength = hexStringToByteArray((char *)C_MAC, (unsigned char *)mac);  //HEX字符串转HEX数组
    for(int i = 0;i<6;i++)
    {
        strlorabuf[3+i]=Machine_info.gateway_mac[i]; //网关的mac地址
    }

    strlorabuf[9] = Machine_info.eflagID; //组内编号

    strlorabuf[10] = cmd;  //命令

    strlorabuf[11] = (msg_id>>8)&0xff;     //总包
    strlorabuf[12] = msg_id&0xff;          //当前包

    strlorabuf[13] = 0x00;     //当前长度

    strlorabuf[14] = PROTOCOL_RSPONSIBLE_ACK;   //ACK命令字段

#if 0
    //设备cid长度
    memcpy(&strlorabuf[15],cid,cid_len); //拷贝cid
    strlorabuf[13] = cid_len+1;     //重新设置当前当前长度
#endif
    int crc = 0;               //计算crc
    for(int i = 0;i<sizeof(strlorabuf);i++)
    {
        crc +=strlorabuf[i];
    }
    strlorabuf[2] = crc;

    if(result!=NULL)
    {
       memcpy(result,strlorabuf,15);
    }

    if(is_send)
    {

        lora_send_data((char *)strlorabuf,15);
        uart_wait_tx_idle_polling(UART_NUM_1);
    }

    return 15;
}






/*硬件配网回复*/   //参数cid  cid长度 返回result    结果及长度
int reply_gwpair_ack_func(uint8_t *cid,uint8_t cid_len,uint8_t *result)
{

    uint8_t strlorabuf[50]={0};
    uint8_t mac[6] = {0};

    strlorabuf[0]=0x5A;
    strlorabuf[1]=0x51;
    strlorabuf[2]=0x00; //crc

    //int byteArrayLength = hexStringToByteArray((char *)C_MAC, (unsigned char *)mac);  //HEX字符串转HEX数组
    for(int i = 0;i<6;i++)
    {
        strlorabuf[3+i]=Machine_info.gateway_mac[i]; //网关的mac地址
    }

    strlorabuf[9] = Machine_info.eflagID; //组内编号

    strlorabuf[10] = 0x80;  //配对命令

    strlorabuf[11] = 0x01;     //总包
    strlorabuf[12] = 0x01;     //当前包

    strlorabuf[13] = 0x00;     //当前长度

    strlorabuf[14] = 0x01;     //请求成功

    //设备cid长度
    memcpy(&strlorabuf[15],cid,cid_len); //拷贝cid


    strlorabuf[13] = cid_len+1;     //重新设置当前当前长度

    int crc = 0;               //计算crc
    for(int i = 0;i<sizeof(strlorabuf);i++)
    {
        crc +=strlorabuf[i];
    }
    strlorabuf[2] = crc;

    memcpy(result,strlorabuf,14+cid_len+1);

    return 14+cid_len+1;

}


/*硬件配网*/
static void hardware_gwpair_func(const LORA_DATA_T* buf)
{

    uint8_t child_mac[6] = {0};     //子设备的mac地址
    uint8_t gateway_mac[6] = {0};  //网关的组内编号
    int child_num = 0;
    int gateway_num = 0;

    #if 0
        for(int i = 0;i<buf->data_len;i++)
        {
            printf("%02X",buf->data_buf[i]);
        }
    #endif
    uint64_t time=0x000000000000LL;
    //printf("1\r\n");
    memcpy(child_mac,&buf->data_buf[3],6);
    //printf("2\r\n");
    gateway_num = buf->data_buf[9];
    //printf("3\r\n");
    memcpy(gateway_mac,&buf->data_buf[14],6);
    //printf("4\r\n");
    child_num = buf->data_buf[20];
    //printf("5\r\n");
    //printf("\r\n");
    //   for(int i = 21;i<27;i++)
    //   {
    // 	  printf("%02X",buf->data_buf[i]);
    //   }
 #if 0   
  #include <inttypes.h>
  time|=(buf->data_buf[26]<<0);
  //printf("time = %" PRIX64 "\r\n",time);
  time|=(buf->data_buf[25]<<8);
  //printf("time = %" PRIX64 "\r\n",time);
  time|=(buf->data_buf[24]<<16);
  //printf("time = %" PRIX64 "\r\n",time);
  time|=(buf->data_buf[23]<<24);
  //printf("time = %" PRIX64 "\r\n",time);
  #if 0
  uint64_t temp = 0;
  temp |=(buf->data_buf[22]<<32);
  temp |=(buf->data_buf[21]<<40);
  printf("temp = %" PRIX64 "\r\n",temp);
  #endif

  #if 1
  int64_t temp = 0;
  temp = buf->data_buf[22];
  time|=(temp<<32);//(buf->data_buf[22]<<32);
  #else
  time|=temp;
  #endif
  //printf("time = %" PRIX64 "\r\n",(uint64_t)time);
  #if 0
  time|=(buf->data_buf[21]<<40);
  #else
  temp = 0;
  temp = buf->data_buf[21];
  time|=(temp<<40);//(buf->data_buf[22]<<32);
  //time|=(buf->data_buf[21]<<40);
  #endif
  //printf("time = %" PRIX64 "\r\n",(uint64_t)time);
  //uint64_t value = 0x018B1E3D24AC;
  //printf("Value as a 64-bit integer: %" PRIu64 "\n", value);
  //printf("Value as a 64-bit integer: %" PRIX64 "\n", value);
#if 0
        time=(buf->data_buf[21]<<40)+
        (buf->data_buf[22]<<32)+
        (buf->data_buf[23]<<24)+
        (buf->data_buf[24]<<16)+
        (buf->data_buf[25]<<8) +
        (buf->data_buf[26]<<0);      
#endif
#else


    Machine_info.lora_new_channel  = buf->data_buf[21];
    printf("Machine_info.lora_new_channel =%d\r\n",Machine_info.lora_new_channel);

    memcpy(Machine_info.timestamp,&buf->data_buf[22],13);   

    printf("Machine_info.timestamp =%s\r\n",Machine_info.timestamp);


    int timezone_offset = 8;     // 中国时区偏移为UTC+8，你可以根据需要设置不同的时区偏移
    Machine_info.time_offset = timezone_offset;

    timestamp_to_local_time(Machine_info.timestamp,
    Machine_info.time_offset,
    &Machine_info.year, 
    &Machine_info.month,
    &Machine_info.day, 
    &Machine_info.hour,
    &Machine_info.min,
    &Machine_info.sec);
    setRtcTime(Machine_info.year, Machine_info.month,Machine_info.day, 
    Machine_info.hour,Machine_info.min,Machine_info.sec);





    //更新当前状态时间
    Machine_info.current_button.Year = Machine_info.year;
    Machine_info.current_button.Month = Machine_info.month;
    Machine_info.current_button.Day = Machine_info.day;
    Machine_info.current_button.Hour = Machine_info.hour;
    Machine_info.current_button.Minute = Machine_info.min;
    Machine_info.current_button.Second = Machine_info.sec;

    Machine_info.last_button.Year = Machine_info.year;
    Machine_info.last_button.Month = Machine_info.month;
    Machine_info.last_button.Day = Machine_info.day;
    Machine_info.last_button.Hour = Machine_info.hour;
    Machine_info.last_button.Minute = Machine_info.min;
    Machine_info.last_button.Second = Machine_info.sec;




#endif







    printf("gateway mac = ");
    for(int i = 0;i<6;i++)
    printf("%02X",gateway_mac[i]);
    printf("\r\n");
    printf("gateway num = %d\r\n",gateway_num);
    printf("child mac = ");
    for(int i = 0;i<6;i++)
    printf("%02X",child_mac[i]);
    printf("\r\n");
    printf("child_num num = %d\r\n",child_num);
    printf("time = %llu\r\n",time);
    printf("time = %llx\r\n",time);
    //(3000 - (480 - 1*100))


	#include "user_sleep.h"
    #include "esp_sleep.h"

    //配网完成设置休眠唤醒时间
    if(Machine_info.eflagID == 0xff)
    {
        #if 0
        printf("sleep time = %d ms\r\n",(TIMER_WAKEUP_TIME_US*child_num)/1000);
        esp_sleep_enable_timer_wakeup(TIMER_WAKEUP_TIME_US*child_num);  //配置当前休眠的唤醒时间
        #else
        esp_sleep_enable_timer_wakeup(TIMER_WAKEUP_TIME_US);  //配置当前休眠的唤醒时间
        #endif
    }


    Machine_info.eflagID = child_num;  //保存当前的子设备组内编号


    memcpy(Machine_info.gateway_mac,gateway_mac,6);

    
    //配网成功 回复 ACK 设置新的信道

    Machine_info.paired = 1;  //已配对


    #if 0
    send_pair_ack();
    #else
    int msg_id = ( buf->data_buf[11]<<8)| buf->data_buf[12];  //获取当前消息id 用于删除
    printf("msg_id =%X\r\n",msg_id);

    reply_ack_func(PROTOCOL_HARDWARE_GWPAIRED,msg_id,true,NULL);  //回复ack

    #endif
    // vTaskDelay(200 / portTICK_PERIOD_MS);
    // //修改信道前修改设备ID 及 设备ID
    //  dymatic_change_device_id(child_num+1);
    //  dymatic_change_dst_device_id(0x00000001);
    // //切换信道
    // dymatic_change_chanel(Machine_info.lora_new_channel);  //切换信道
    // lora_get_rssi();

    vTaskDelay(200 / portTICK_PERIOD_MS);
    Machine_info.rssi = set_lora(Machine_info.lora_new_channel,Machine_info.eflagID);
    f_send_version();
    f_send_reply_status(0x01);  //回复在线状态
    send_update_status();
    // f_send_lora_rssi(Machine_info.rssi);
    f_send_lora_rssi(100);//刚配完直接发100
    f_send_battary_vaule(Machine_info.batt_precent);


#if USER_LIGHT_SLEEP_ENABLE || USER_DEEP_SLEEP_ENABLE
    sleep_timer_start(2000);  //进入睡眠
#endif



    //printf("start timer id = %d,%d\r\n",Machine_info.eflagID,Machine_info.eflagID * TIMER_CAN_SEND_TIME);
    //Already_send_timer_start(Machine_info.eflagID * TIMER_CAN_SEND_TIME);
}





/*硬件取消配网*/
static void hardware_ungwpair_func(const LORA_DATA_T* buf)
{
   uint8_t child_mac[6] = {0};     //子设备的mac地址
   uint8_t gateway_mac[6] = {0};  //网关的组内编号
    int child_num = 0;
    int gateway_num = 0;
    
    uint64_t time=0x000000000000LL;


    memcpy(child_mac,&buf->data_buf[3],6);
    gateway_num = buf->data_buf[9];
  
    memcpy(gateway_mac,&buf->data_buf[14],6);

    child_num = buf->data_buf[20];

  #include <inttypes.h>
  time|=(buf->data_buf[26]<<0);

  time|=(buf->data_buf[25]<<8);

  time|=(buf->data_buf[24]<<16);

  time|=(buf->data_buf[23]<<24);

 

  #if 1
  int64_t temp = 0;
  temp = buf->data_buf[22];
  time|=(temp<<32);//(buf->data_buf[22]<<32);
  #else
  time|=temp;
  #endif
  //printf("time = %" PRIX64 "\r\n",(uint64_t)time);
  #if 0
  time|=(buf->data_buf[21]<<40);
  #else
  temp = 0;
  temp = buf->data_buf[21];
  time|=(temp<<40);//(buf->data_buf[22]<<32);
  //time|=(buf->data_buf[21]<<40);
  #endif
  //printf("time = %" PRIX64 "\r\n",(uint64_t)time);
  //uint64_t value = 0x018B1E3D24AC;
  //printf("Value as a 64-bit integer: %" PRIu64 "\n", value);
  //printf("Value as a 64-bit integer: %" PRIX64 "\n", value);

    printf("gateway mac = ");
    for(int i = 0;i<6;i++)
    printf("%02X",gateway_mac[i]);
    printf("\r\n");
    printf("gateway num = %d\r\n",gateway_num);
    printf("child mac = ");
    for(int i = 0;i<6;i++)
    printf("%02X",child_mac[i]);
    printf("\r\n");
    printf("child_num num = %d\r\n",child_num);
    printf("time = %llu\r\n",time);
    printf("time = %llx\r\n",time);
    //(3000 - (480 - 1*100))


	#include "user_sleep.h"
    #include "esp_sleep.h"




    memcpy(Machine_info.gateway_mac,gateway_mac,6);

    //取消配网成功 回复 ACK 设置新的信道

    #if 0
    send_pair_ack();
    #else
    int msg_id = ( buf->data_buf[11]<<8)| buf->data_buf[12];  //获取当前消息id 用于删除
    //printf("msg_id =%X\r\n",msg_id);

    reply_ack_func(PROTOCOL_HARDWARE_UNGWPAIRED,msg_id,true,NULL);  //回复ack


    #endif


	//#include "user_sleep.h"
    //#include "esp_sleep.h"

    extern void sleep_timer_stop();
    extern void Already_send_timer_stop();


    sleep_timer_stop();
    Already_send_timer_stop();


    //修改信道前修改设备ID 及 设备ID
     dymatic_change_device_id(0x00000001);
     dymatic_change_dst_device_id(0xFFFFFFFF);
    //切换信道
    reset_default(true);
    vTaskDelay(300 / portTICK_PERIOD_MS);
    Machine_info.lora_new_channel = LORA_CHANENL;
    // dymatic_change_chanel(Machine_info.lora_factory_channel);  //切换信道
    reset_lora();
}
/*网关收到终端发送的数据 ACK 终端收到用于删除当前的msgid的数据*/
static void hardware_ack_delete_msg_id(const LORA_DATA_T* buf)
{

         int msg_id = ( buf->data_buf[11]>>8)| buf->data_buf[12];  //获取当前消息id 用于删除当前链表的数据


         int current =  countNodes(Send_list);   //获取当前节点数据


         Node *find  = findNode(Send_list,msg_id);


         if(find != NULL)
        {
            // printf("delete list node bofore = %d\r\n",msg_id);
            // printList(Send_list);
            Send_list =  deleteNode(Send_list,msg_id);
            // printf("delete list node msg_id = %d\r\n",msg_id);

            // printf("delete list node after = %d\r\n",msg_id);
            // printList(Send_list);

        }
        else
        {
            ESP_LOGE(LOG_TAG,"delete fail");
        }


  display_flag = 0;

}



void business_logic_func(const LORA_DATA_T* buf,uint8_t cmd_index,int msg)
{
    int cmd = 0;    //当前的命令
    int msg_id = 0; //消息的id
    bool is_rsp_ack = false;
    #if 0
    printf("cmd = %02X\r\n",buf->data_buf[cmd_index]);
    #endif

    cmd =  buf->data_buf[cmd_index]; 


    switch (buf->data_buf[cmd_index])
    {
    case PROTOCOL_TIME_SYNCHRONIZATION:
    
            msg_id = time_synchronization_func(buf);
            //is_rsp_ack = true;
        break;
    case PROTOCOL_TERMINAL_NAME:
            msg_id = terminal_name_func(buf);
            //is_rsp_ack = true;
        break;
    case PROTOCOL_TERMINAL_NUMBER:
            msg_id = terminal_number_func(buf);
              //is_rsp_ack = true;
        break;
    case PROTOCOL_ELECTRIC_QUANTITY:
           msg_id =  electric_quantity_func(buf);
             //is_rsp_ack = true;
        break;
    case PROTOCOL_SIGNAL_STRENGTH:
           msg_id = signal_strength_func(buf);
             //is_rsp_ack = true;
        break;
    case PROTOCOL_SCREEN_REFRESH_CYCLE:
            msg_id = screen_refresh_cycle_func(buf);
              //is_rsp_ack = true;
        break;
    case PROTOCOL_SCREEN_LEFT:
           msg_id =  screen_left_func(buf);
             //is_rsp_ack = true;
        break;
    case PROTOCOL_SCREEN_RIGHT:
          msg_id = screen_right_func(buf);
            //is_rsp_ack = true;
        break;
    case PROTOCOL_RSPONSIBLE_PERSON_CHANGE:
          msg_id =   rsponsible_person_change_func(buf);
            //is_rsp_ack = true;
        break;
    case PROTOCOL_RSPONSIBLE_PERSON_DELETE:
          msg_id =   rsponsible_person_delete_func(buf);
            //is_rsp_ack = true;
        break;
    case PROTOCOL_PRODUCTION_PUNCH_CARD:
          msg_id =   production_punch_func(buf);
           // is_rsp_ack = true;
        break;
    case PROTOCOL_PERSONNEL_CHECK_IN:
         msg_id =    personnel_check_in_func(buf);
           //is_rsp_ack = true;
        break;
    case PROTOCOL_STATUS_SETTING:
         msg_id =    status_setting_func(buf);
           //is_rsp_ack = true;
        break;
    case PROTOCOL_STATUS_DURATION:
         msg_id =    status_duration_func(buf);
           //is_rsp_ack = true;
        break;
    case PROTOCOL_UPDATE_AND_DURATION:
         msg_id =    update_and_duration_func(buf);
         //  is_rsp_ack = true;
        break;
    case PROTOCOL_ANNOUNCEMENT:
         msg_id =    announcement_func(buf);
         //  is_rsp_ack = true;
        break;
    case PROTOCOL_CAPACITY_STATISTICS:
         msg_id =    capacity_statistics_func(buf);
         //  is_rsp_ack = true;
        break;
    case PROTOCOL_RESPONSIBLE_PERSON_SYNCHRONIZE_INFO:
         msg_id =    responsible_person_synchronize_info_func(buf);
        //   is_rsp_ack = true;
        break; 
    case PROTOCOL_STATUS_LED:
        msg_id =     status_led_func(buf);
        //  is_rsp_ack = true;
        break;
    case PROTOCOL_LOG_LED:
        msg_id =     logo_led_func(buf);
       //   is_rsp_ack = true;
        break;
    case PROTOCOL_BATTERY_TEMPERATURE:
        msg_id =     battery_temperature_func(buf);
      //    is_rsp_ack = true;
        break;
    case PROTOCOL_STATION_NAME:
        msg_id = station_name_func(buf);
      //      is_rsp_ack = true;
    break;
    case PROTOCOL_STATION_NUMBER:
        msg_id = station_number_func(buf);
      //      is_rsp_ack = true;
    break;
    case PROTOCOL_RESPONSIBLE_PERSON_SETUP:
        msg_id = responsible_person_setup_func(buf);
       //     is_rsp_ack = true;
    break;
    case PROTOCOL_SYSTEM_BULLETIN:
        msg_id = system_bulletin_func(buf);
          //  is_rsp_ack = true;
    break;
    case PROTOCOL_HARDWARE_UPDATE:
        msg_id =     hardware_update_func(buf);
       // is_rsp_ack = true;
        break;   

    case PROTOCOL_HARDWARE_GWPAIRED:  //配网 暂时单独发送ack 
    reset_default(false);
    hardware_gwpair_func(buf);
    Paint_leftScreen_main_quick(&Machine_info);
    Paint_rightScreen_main_quick(&Machine_info);
    break;

    case PROTOCOL_HARDWARE_UNGWPAIRED: //取消配网
    printf("pair ungwpaired\r\n");
    hardware_ungwpair_func(buf);
    break;

    case PROTOCOL_RSPONSIBLE_ACK:

    printf("receive gateway ack delete data in list\r\n");
    hardware_ack_delete_msg_id(buf);

    break;



    default:
        ESP_LOGE(LOG_TAG,"ERR:CMD = 0x%02x",buf->data_buf[cmd_index]);
        break;
    }
 
#if  USER_NOT_SLEEP_ENABLE   
     send_can_I_receive(); //发送可以接受的命令
#endif

}

void uincode2gbk(char *str,uint16_t len,char *out_buffer)
 {
    char strtmp[1024];
    char str1[3];
    unsigned int  iunicode,i;
    unsigned int  igbk;
    memset(strtmp,0,1024);
    char* p_text = str;
     int index = 0;

   i=0;

  int length = len;

    while(length)
    {
       if( (str[i] == 0) &&  (str[i+1])<0x80)  //ASCII 码 *text是ASCII码
      {

        str1[0]=(str[i+1])&0xff;
        memcpy(&strtmp[index],str1,1);  
        index+=1;
      }   
      else
      {
        iunicode=(str[i]<<8)+str[i+1];
        igbk=U2G(iunicode);
        str1[0]=(igbk>>8)&0xff;
        str1[1]=igbk&0xff;
        memcpy(&strtmp[index],str1,2);
        index+=2;
      }
      length-=2;
      i+=2;
    }
    //ESP_LOGW(LOG_TAG,"index:%d",index);
    memcpy(out_buffer,strtmp,index);
 }
// 计算数组元素的总和
uint32_t sumArray(uint8_t array[], int size) {
    uint32_t sum = 0;
    for (int i = 0; i < size; i++) {
        sum += array[i];
    }
    return sum;
}
void mac_to_hex(char *out_string,char *in_string)	
{
    sprintf(out_string,"%02X:%02X:%02X:%02X:%02X:%02X",
    in_string[0],
    in_string[1],
    in_string[2],
    in_string[3],
    in_string[4],
    in_string[5]
    );
   // ESP_LOG_BUFFER_HEX("--->",out_string,17);
}
void qrcode_protocol_create(char *result,Machine_info_t info)
{
    // char str_https[] = "https://www.yeechart.com/antnest_download.php?data=";
    char str_https[] = "https://www.yeechart.com/yeechart_download.php?data=";
    Qrcode_protocol_t Qcode;
    char qrcode_protocol[1024]={0}; 

    Qcode.head[0] = 0x5a;
    Qcode.head[1] = 0x51;
    Qcode.CRC = 0x00;

    Qcode.mac.cmd = 0x03;
    Qcode.mac.len = 0x11;
    esp_read_mac((uint8_t *)mac_addr, ESP_MAC_WIFI_STA);
    mac_to_hex((char *)Qcode.mac.mac_addr,(char*)mac_addr);
    //strcpy((char *)Qcode.mac.mac_addr,(char*)mac_addr);

    Qcode.client.cmd = 0X04;
#if 1 //硬件设备id (qx 设置)
    strcpy((char *)Qcode.client.client_id,(char*)info.cid);
    Qcode.client.len = strlen((char *)Qcode.client.client_id);
#else //假硬件设备id
    strcpy((char *)Qcode.client.client_id,"whc_test");
    Qcode.client.len = strlen((char *)Qcode.client.client_id);
#endif

    Qcode.product.cmd = 0x05;
    strcpy((char *)Qcode.product.product,"020101");
    Qcode.product.len = strlen((char*)Qcode.product.product);

    Qcode.time.cmd = 0x61;
    Qcode.time.len = 0x0E;

#if 1
    Qcode.time.Year = info.year;
    Qcode.time.Month = info.month;
    Qcode.time.Day = info.day;
    Qcode.time.Hour = info.hour;
    Qcode.time.Minute = info.min;
    Qcode.time.Second = info.sec;
#else
    Qcode.time.Year = 2023;
    Qcode.time.Month = 9;
    Qcode.time.Day = 19;
    Qcode.time.Hour = 19;
    Qcode.time.Minute = 30;
    Qcode.time.Second = 20;
#endif
    int time_index = 0;
    sprintf((char *)(Qcode.time.time + time_index * 2), "%02X%02X", Qcode.time.Year>>8,Qcode.time.Year&0xff);
    time_index +=2;
    sprintf((char *)(Qcode.time.time + time_index * 2), "%02X", Qcode.time.Month);
    time_index+=1;
    sprintf((char *)(Qcode.time.time + time_index * 2), "%02X", Qcode.time.Day);
    time_index+=1;
    sprintf((char *)(Qcode.time.time + time_index * 2), "%02X", Qcode.time.Hour);
    time_index+=1;
    sprintf((char *)(Qcode.time.time + time_index * 2), "%02X", Qcode.time.Minute);
    time_index+=1;
    sprintf((char *)(Qcode.time.time + time_index * 2), "%02X", Qcode.time.Second);


    uint32_t crc = 0;
    crc += Qcode.head[0];
    crc += Qcode.head[1];

    crc += sumArray((uint8_t*)&Qcode.mac,sizeof(Qcode.mac));

    crc += Qcode.client.cmd;
    crc += Qcode.client.len;

    int len =0,i=0;

    len =Qcode.client.len;

    while(len)
    {
        crc += Qcode.client.client_id[i];
        len--;
        i++;
    }

    crc += Qcode.product.cmd;
    crc += Qcode.product.len;

    i = 0;
    len = Qcode.product.len;
    while(len)
    {
    if(Qcode.product.product[i] != '0')
    {
        crc += Qcode.product.product[i];
    }else
    {
        break;
    }
    len--;
    i++;
    }

    i = 0;
    len = Qcode.time.len;
    while(len)
    {
        if(Qcode.time.time[i] != '0')
        {
            crc += Qcode.time.time[i];
        }
        else
        {
            break;
        }
        len--;
        i++;
    }


    Qcode.CRC = crc&0xff;

    int index = 0;

    sprintf(qrcode_protocol + index * 2, "%02X%02X", Qcode.head[0],Qcode.head[1]);
    index +=2;
    sprintf(qrcode_protocol + index * 2, "%02X", Qcode.CRC);
    index +=1;

    sprintf(qrcode_protocol + index * 2, "%02X%02X", Qcode.mac.cmd,Qcode.mac.len);
    index +=2;
    // 转换16进制数组为ASCII字符串  mac 地址
        for (int i = 0; i < Qcode.mac.len; i++) {
            sprintf(qrcode_protocol + index * 2, "%02X",Qcode.mac.mac_addr[i]);
            index +=1;
        }





    sprintf(qrcode_protocol + index * 2, "%02X%02X", Qcode.client.cmd,Qcode.client.len);
    index +=2;

    // 转换16进制数组为ASCII字符串  client id
        for (int i = 0; i < Qcode.client.len; i++) {

            if(Qcode.client.client_id[i] != 0)
            {
                sprintf(qrcode_protocol + index * 2, "%02X", Qcode.client.client_id[i]);
                index +=1;
            }

        }
    


    // 转换16进制数组为ASCII字符串   product
    sprintf(qrcode_protocol + index * 2, "%02X%02X", Qcode.product.cmd,Qcode.product.len);
    index +=2;
        for (int i = 0; i < Qcode.product.len; i++) {

                //if(Qcode.product.product[i] != '0')
                {//这里产品id为0也需要
                sprintf(qrcode_protocol + index * 2, "%02X", Qcode.product.product[i]);
                index +=1;
                }

        }



    // 转换16进制数组为ASCII字符串   time
    sprintf(qrcode_protocol + index * 2, "%02X%02X", Qcode.time.cmd,Qcode.time.len);
    index +=2;

    for (int i = 0; i < Qcode.time.len; i++) {

        //if(Qcode.time.time[i] != '0')
        {//这里时间为0也需要
        sprintf(qrcode_protocol + index * 2, "%02X", Qcode.time.time[i]);
        index +=1;
        }

    }

    strcpy(result,str_https);
    strcat(result,qrcode_protocol);
    // ESP_LOGW(LOG_TAG,"二维码信息：%s",result);
}





// 函数用于查找字节序列在数组中出现的次数，并返回出现位置的索引
int findByteSequence(const u8* array, int arraySize, const u8* sequence, int sequenceSize, int** positions) {
    int count = 0;
    int* indices = NULL;

    for (int i = 0; i <= arraySize - sequenceSize; i++) {
        // 检查当前位置开始的字节序列是否与目标序列匹配
        int j;
        for (j = 0; j < sequenceSize; j++) {
            if (array[i + j] != sequence[j]) {
                break; // 不匹配，跳出循环
            }
        }

        if (j == sequenceSize) {
            count++; // 找到匹配的序列

            // 记录匹配位置的索引
            int* temp = (int*)realloc(indices, count * sizeof(int));
            if (temp == NULL) {
                // 内存分配失败，处理错误
                if (indices != NULL) {
                    free(indices);
                }
                return -1;
            }
            indices = temp;
            indices[count - 1] = i;
        }
    }

    *positions = indices; // 传递匹配位置的索引数组
    return count;
}


//匹配mac地址是否为本机
bool  mac_is_true(uint8_t *mac)
{

    if(
    	(mac[0] ==  Machine_info.mac_addr[0]) &&
        (mac[1] ==  Machine_info.mac_addr[1]) &&
        (mac[2] ==  Machine_info.mac_addr[2]) &&
        (mac[3] ==  Machine_info.mac_addr[3]) &&
        (mac[4] ==  Machine_info.mac_addr[4]) &&
        (mac[5] ==  Machine_info.mac_addr[5]) 
      )
     {
        return true;
     }
           

    return false;
}

bool subcontract(YC_DATA_T* data)
{



    int rsp_msgid = 0; 

    int index = 0;
    int all_len = data->len;
    uint8_t* buf = data->data;
    USE_DATA_T use_data;

    bool refresh_flag = false;
    #if 1

    u8 targetSequence[] = {0x5A, 0x51};
    int sequenceSize = sizeof(targetSequence);

    int* positions = NULL;
    int result = findByteSequence(buf, all_len, targetSequence, sequenceSize, &positions);
 



    if(result>1)
    {
        int data_len = 0;
        data_len = (buf[0]<<8)|(buf[1]);
        printf("cmd 5A 51 find times %d,all data len = %d\r\n", result,data_len);  
    }


    if(result == 1)
    {
        printf("cmd 5A 51 find times %d,data len = %d\r\n", result,data->len);
        for(int index = 0;index<result;index++)
        {
            if( (buf[0] == 0x5A )&&(buf[1] == 0x51) &&(result == 1))
            {
            //单条命令处理逻辑

                use_data.data_len = all_len; //(((buf[positions[index] - 2])<<8) | ((buf[positions[index] - 1])))+2;
                memcpy(use_data.data_buf,data->data ,use_data.data_len);
                //print_yc_data(&use_data);
                printf("single cmd len =%d\r\n",use_data.data_len);
                for(int i = 0;i<use_data.data_len;i++)
                {
                    printf("%02X",use_data.data_buf[i]);
                }
                printf("\r\n");

                bool is = mac_is_true(&use_data.data_buf[3]);

                if(is)
                {
                    business_logic_func(&use_data,USE_CMD_LEN_INDEX -2,0);
                    refresh_flag =true;
                }else
                {
                    printf("mac is fail not deal\r\n");
                }

    
            }else
            {

                    rsp_msgid = (buf[13]<<8)|buf[14];  //获取当前消息id 用于删除

                    printf("rsp_msgid %02x,%02x,%d\r\n",buf[13],buf[14],rsp_msgid);
        
                    for(int index = 0;index<result;index++)
                    {
                            //多条指令处理逻辑

                            bool is = mac_is_true(&buf[positions[index] + 3]);
                            if(is)
                            {
                    use_data.data_len =(((buf[positions[index] - 2])<<8) | ((buf[positions[index] - 1]))) + 2;
                    memcpy(use_data.data_buf,data->data + (positions[index] -2) ,use_data.data_len);
                                //print_yc_data(&use_data);
                                business_logic_func(&use_data,USE_CMD_LEN_INDEX,rsp_msgid);
                                refresh_flag =true;
                            }else
                            {
                                printf("mac is fail not deal\r\n");
                            }
                    }



                    //if(is_rsp_ack)
                    {
                        reply_ack_func(0x00,rsp_msgid,true,NULL);  //回复ack
                        spiffs_write(&Machine_info);
                        ESP_LOGE(LOG_TAG,"cmd = %02X  msg = %X start reply ack\r\n",0x00,rsp_msgid);
                    }
            }
        

        }

    }



    if(result > 1)
    {

          printf("not single cmd len =%d\r\n",use_data.data_len);


          rsp_msgid = (buf[13]<<8)|buf[14];  //获取当前消息id 用于删除;
          printf("rsp_msgid %02x,%02x,%d\r\n",buf[13],buf[14],rsp_msgid);
        
            for(int index = 0;index<result;index++)
            {
                    //多条指令处理逻辑

                    bool is = mac_is_true(&buf[positions[index] + 3]);
                    if(is)
                    {
                        use_data.data_len = 15 + 2 + (((buf[positions[index] +13])<<8) | ((buf[positions[index]+14])));


                        use_data.data_buf[0] = 0x00;
                        use_data.data_buf[1] = 0x00;

                        memcpy(&use_data.data_buf[2],data->data +(positions[index]) ,use_data.data_len + 15);


                    // printf("================last result============== len =%d\r\n",use_data.data_len);
                    //     for(int i = 0;i<use_data.data_len;i++)
                    //     {
                    //             printf("%02x",use_data.data_buf[i]);
                    //     }
                    //     printf("================last result==============\r\n");
                    
                    //  print_yc_data(&use_data);
                        business_logic_func(&use_data,USE_CMD_LEN_INDEX ,rsp_msgid);
                        refresh_flag =true;
                    }else
                    {
                        printf("mac is fail not deal\r\n");
                    }
            }
            //if(is_rsp_ack)
            {
                reply_ack_func(0x00,rsp_msgid,true,NULL);  //回复ack
                spiffs_write(&Machine_info);
                ESP_LOGE(LOG_TAG,"cmd = %02X  msg = %X start reply ack\r\n",0x00,rsp_msgid);
            }
    }   


#if 0
    u8 targetSequence1[] = {0x55, 0x51};
    int sequenceSize1 = sizeof(targetSequence);

    int* positions1 = NULL;
     result = findByteSequence(buf, all_len, targetSequence1, sequenceSize1, &positions1);

    if(result!=0)
    {
        printf("ack 55 51 find time %d\r\n", result);
    }

      for(int index = 0;index<result;index++)
    {
        //use_data.data_len =(((buf[positions[index] - 2])<<8) | ((buf[positions[index] - 1])))+2;
        //memcpy(use_data.data_buf,data->data + (positions[index] -2) ,use_data.data_len);
        //print_yc_data(&use_data);
        use_data.data_len = all_len;
        memcpy(use_data.data_buf,data->data + (positions1[index]) ,use_data.data_len);
        business_ack_func(&use_data);
        //refresh_flag =true;
    }
#endif




    // #if 1


    //       for (int i = 0; i < all_len; i++)
    //         {
    //             printf("%02x",buf[i]);
    //         }

    // #endif


    free(positions);

    //free(positions1);
    #if 0
    printf("index:");
    if (result > 0) {
        //printf("出现的位置索引：");
        for (int i = 0; i < result; i++) {
            printf("%d,", positions[i]);
        }
        printf("\n");
       
    }
    #endif


    #else
    while(all_len>0)
    {
        // ESP_LOGW(LOG_TAG,"-->[%d]",all_len);
        // for(int i=0;i<all_len;i++)
        // {
        //     printf("%02x ",data->data[i]);
        // }
        // printf("\n");
        if( ((buf[index+2]) == 0x5A) && ((buf[index +3]) == 0x51))
        {
            use_data.data_len =(((buf[index])<<8) | ((buf[index + 1])))+2;
            memcpy(use_data.data_buf,data->data+index,use_data.data_len);
            all_len-=(use_data.data_len);
            index+=(use_data.data_len);
            //print_yc_data(&use_data);
            business_logic_func(&use_data);
            refresh_flag =true;
        }
        else 
        {
            all_len--;
            index++;
            //ESP_LOGE(LOG_TAG,"err:data");
            //break;
        }
    }
    #endif

    return refresh_flag;
}


//len：有效数据长度，不是总长//
static void protocol_package(char cmd, const uint8_t* info, int len)
{
    #define __PACKAGE 15
    uint8_t* __str = (uint8_t*)malloc(sizeof(uint8_t)*(__PACKAGE+len)*2);

    __str[0] = 0x5a;
    __str[1] = 0x51;

    __str[2] = 0x00;

    __str[3] = mac_addr[0];
    __str[4] = mac_addr[1];
    __str[5] = mac_addr[2];
    __str[6] = mac_addr[3];
    __str[7] = mac_addr[4];
    __str[8] = mac_addr[5];

    __str[9] = Machine_info.eflagID;

    __str[10] = cmd;
#if 0
    __str[11] = 0x01;//当前只为一包
    __str[12] = 0x01;//当前只为一包
#else

    //随机数
    srand((unsigned int)time(NULL));
    int time_rand = rand() % 65535 + 1;//生成1~100的随机数
    __str[11] = (time_rand>>8)&0xFF;
    __str[12] = time_rand&0xFF;
#endif
    //分包
    __str[13] = (len>>8)&0xFF;
    __str[14] = len&0xFF;

    memcpy(__str+__PACKAGE,info,len);
    int i = 0,sum = 0;
    for(i=0;i<len+__PACKAGE;i++)
    {
        sum+=__str[i];
    }
    __str[2] = sum&0xFF;

    printf("crc=%02x ",__str[2]);

    printf("-->package:");
    for(i=0;i<len+__PACKAGE;i++)
    {
        printf("%02x ",__str[i]);
    }
    printf("\n");

    changebintotxt(__str,len+__PACKAGE);


    #if 0
    Send_list = postInsert(Send_list, time_rand,cmd,(char *)__str,(int)(len+__PACKAGE)*2);//len*2
    #else
    lora_send_data((char *)__str,len+__PACKAGE);
    #endif
    free(__str);
}

int txttobin(uint8_t *strlorabuf)
{
  int len=0,i=0;
  uint8_t strbuf[1024];
  char ch=0,chhi=0,chlo=0;
  len = strlen((char *)strlorabuf);
  strcpy((char *)strbuf,(char *)strlorabuf);
  memset(strlorabuf,0,len);
  //Serial.print("jiexishuju:");Serial.println((char *)strbuf);
  for(i=0;i<len;i++)
	{
		
		ch = strbuf[i*2];
		if((ch >=0x30 && ch <= 0x39 )||
			(ch >=0x41 && ch <= 0x5a )||
			(ch >=0x61 && ch <= 0x7a ))
		{
			{
				if(ch >=0x30 && ch <= 0x39)
					ch = ch-0x30;
				else if(ch >=0x41 && ch <= 0x5a )
					ch = ch-0x37;
				else
					ch = ch-0x57;
				ch &= 0x000f;
				chhi = (ch<<4);
			}
			ch = strbuf[i*2+1];
			if((ch >=0x30 && ch <= 0x39 )||
				(ch >=0x41 && ch <= 0x5a )||
				(ch >=0x61 && ch <= 0x7a ))
			{
				if(ch >=0x30 && ch <= 0x39)
					ch = ch-0x30;
				else if(ch >=0x41 && ch <= 0x5a )
					ch = ch-0x37;
				else
					ch = ch-0x57;
				ch &= 0x000f;
				ch = chhi+ch;
			} 	
			strlorabuf[i]=ch;
		}
	}
  //Serial.write(strlorabuf,len);
  return i;
  
}
void changebintotxt(uint8_t *strb,int len)
{
  int i=0;
  uint8_t strtxt[512];
  char ch,chhi,chlo;
  memset(strtxt,0,512);
  for(i=0;i<len;i++)
  {
		ch = strb[i];
		chhi = ch;
		chhi >>= 4;
		chhi &= 0x000f;
		if(chhi <= 9)
			chhi += 0x30;
		else
			chhi += 0x37;
		strtxt[i*2]=chhi;
		chlo = ch;
		chlo &= 0x000f;
		if(chlo <= 9)
			chlo += 0x30;
		else
			chlo += 0x37;
		strtxt[i*2+1]=chlo;
		
	}
  strcpy((char *)strb,(char *)strtxt);
}

void f_send_get_chart_data(void)
{

   uint8_t strlorabuf[200];
   uint8_t  strnum[20];

   static int rssiold=0;
   int crc16=0,i=0,len=0;

  strlorabuf[0]=0x5A;
  strlorabuf[1]=0x51;//包头
  strlorabuf[2]=0x00;  //校验和               

 strlorabuf[3]=mac_addr[0];
 strlorabuf[4]=mac_addr[1];
 strlorabuf[5]=mac_addr[2];
 strlorabuf[6]=mac_addr[3];
 strlorabuf[7]=mac_addr[4];
 strlorabuf[8]=mac_addr[5];  
 strlorabuf[9]=Machine_info.eflagID; //组内编号
 strlorabuf[10]=0x11;  //cmd命令字


Machine_info.msg_id =  allocateMsgIdNum();  //分配ID
strlorabuf[11]=((Machine_info.msg_id)>>8)&0XFF;//
strlorabuf[12]=((Machine_info.msg_id)>>0)&0XFF;//总包数，当前包数


  strlorabuf[13]=0x00;
  strlorabuf[14]=0x00;//长度
  strlorabuf[15]=0;
  
   crc16=strlorabuf[0]+strlorabuf[1];
  for(i=3;i<15;i++)
    crc16=crc16+strlorabuf[i];
   strlorabuf[2]=crc16&0xff;

  changebintotxt(strlorabuf,15);
  //Serial.println((char *)strlorabuf);
  strcat((char *)strlorabuf,(char *)Machine_info.cid);
  len=strlen((char *)strlorabuf);

  //lora_send_data((char *)strlorabuf,len);
    Send_list = postInsert(Send_list,Machine_info.msg_id, Machine_info.msg_id,(char *)strlorabuf,len); //插入数据
}
void f_send_version(void)
{
    
    ESP_LOGW(LOG_TAG,"f_send_version");
    uint8_t strlorabuf[200];
    uint8_t  strnum[20];

    static int rssiold=0;
    int crc16=0,i=0,len=0;

    strlorabuf[0]=0x5A;
    strlorabuf[1]=0x51;//包头
    strlorabuf[2]=0x00;  //校验和               

    strlorabuf[3]=mac_addr[0];
    strlorabuf[4]=mac_addr[1];
    strlorabuf[5]=mac_addr[2];
    strlorabuf[6]=mac_addr[3];
    strlorabuf[7]=mac_addr[4];
    strlorabuf[8]=mac_addr[5];  
    strlorabuf[9]=Machine_info.eflagID; //组内编号
    strlorabuf[10]=0x91;  //cmd命令字


    Machine_info.msg_id =  allocateMsgIdNum();  //分配ID
    strlorabuf[11]=((Machine_info.msg_id)>>8)&0XFF;//
    strlorabuf[12]=((Machine_info.msg_id)>>0)&0XFF;//总包数，当前包数


    strlorabuf[13]=0x00;
    strlorabuf[14]=0x01;//长度
    strlorabuf[15]=(VERSION_X)&0xff;
    strlorabuf[16]=(VERSION_Y)&0xff;
    strlorabuf[17]=(VERSION_Z)&0xff;
    strlorabuf[18]=0;
    
    crc16=strlorabuf[0]+strlorabuf[1];
    for(i=3;i<18;i++)
        crc16=crc16+strlorabuf[i];
    strlorabuf[2]=crc16&0xff;

    changebintotxt(strlorabuf,18);
    //Serial.println((char *)strlorabuf);
    strcat((char *)strlorabuf,(char *)Machine_info.cid);
    len=strlen((char *)strlorabuf);

    Send_list = postInsert(Send_list,Machine_info.msg_id, Machine_info.msg_id,(char *)strlorabuf,len); //插入数据
}
void f_send_lora_rssi(int rssi)
{
    
    // ESP_LOGW(LOG_TAG,"f_send_lora_rssi:rssi = %d",rssi);
    uint8_t strlorabuf[200];
    uint8_t  strnum[20];

    static int rssiold=0;
    int crc16=0,i=0,len=0;

    strlorabuf[0]=0x5A;
    strlorabuf[1]=0x51;//包头
    strlorabuf[2]=0x00;  //校验和               

    strlorabuf[3]=mac_addr[0];
    strlorabuf[4]=mac_addr[1];
    strlorabuf[5]=mac_addr[2];
    strlorabuf[6]=mac_addr[3];
    strlorabuf[7]=mac_addr[4];
    strlorabuf[8]=mac_addr[5];  
    strlorabuf[9]=Machine_info.eflagID; //组内编号
    strlorabuf[10]=0x05;  //cmd命令字


    Machine_info.msg_id =  allocateMsgIdNum();  //分配ID
    strlorabuf[11]=((Machine_info.msg_id)>>8)&0XFF;//
    strlorabuf[12]=((Machine_info.msg_id)>>0)&0XFF;//总包数，当前包数


    strlorabuf[13]=0x00;
    strlorabuf[14]=0x01;//长度
    strlorabuf[15]=(rssi)&0xff;
    strlorabuf[16]=0;
    
    crc16=strlorabuf[0]+strlorabuf[1];
    for(i=3;i<16;i++)
        crc16=crc16+strlorabuf[i];
    strlorabuf[2]=crc16&0xff;

    changebintotxt(strlorabuf,16);
    //Serial.println((char *)strlorabuf);
    strcat((char *)strlorabuf,(char *)Machine_info.cid);
    len=strlen((char *)strlorabuf);


    Send_list = postInsert(Send_list,Machine_info.msg_id, Machine_info.msg_id,(char *)strlorabuf,len); //插入数据

}

void f_send_battary_vaule(int battry)
{

   uint8_t strlorabuf[200];
   uint8_t  strnum[20];

   static int rssiold=0;
   int crc16=0,i=0,len=0;

  strlorabuf[0]=0x5A;
  strlorabuf[1]=0x51;//包头
  strlorabuf[2]=0x00;  //校验和               

 strlorabuf[3]=mac_addr[0];
 strlorabuf[4]=mac_addr[1];
 strlorabuf[5]=mac_addr[2];
 strlorabuf[6]=mac_addr[3];
 strlorabuf[7]=mac_addr[4];
 strlorabuf[8]=mac_addr[5];  
 strlorabuf[9]=Machine_info.eflagID; //组内编号
 strlorabuf[10]=0x04;  //cmd命令字


Machine_info.msg_id =  allocateMsgIdNum();  //分配ID
strlorabuf[11]=((Machine_info.msg_id)>>8)&0XFF;//
strlorabuf[12]=((Machine_info.msg_id)>>0)&0XFF;//总包数，当前包数


  strlorabuf[13]=0x00;
  strlorabuf[14]=0x01;//长度
  strlorabuf[15]=(battry)&0xff;
  strlorabuf[16]=0;
  
   crc16=strlorabuf[0]+strlorabuf[1];
  for(i=3;i<16;i++)
    crc16=crc16+strlorabuf[i];
   strlorabuf[2]=crc16&0xff;

  changebintotxt(strlorabuf,16);
  //Serial.println((char *)strlorabuf);
  strcat((char *)strlorabuf,(char *)Machine_info.cid);
  len=strlen((char *)strlorabuf);


  Send_list = postInsert(Send_list,Machine_info.msg_id, Machine_info.msg_id,(char *)strlorabuf,len); //插入数据

}




void f_send_reply_status(int status)
{

   uint8_t strlorabuf[200];
   uint8_t  strnum[20];

   static int rssiold=0;
   int crc16=0,i=0,len=0;

  strlorabuf[0]=0x5A;
  strlorabuf[1]=0x51;//包头
  strlorabuf[2]=0x00;  //校验和               

 strlorabuf[3]=mac_addr[0];
 strlorabuf[4]=mac_addr[1];
 strlorabuf[5]=mac_addr[2];
 strlorabuf[6]=mac_addr[3];
 strlorabuf[7]=mac_addr[4];
 strlorabuf[8]=mac_addr[5];  
 strlorabuf[9]=Machine_info.eflagID; //组内编号
 strlorabuf[10]=0x06;  //cmd命令字


Machine_info.msg_id =  allocateMsgIdNum();  //分配ID
strlorabuf[11]=((Machine_info.msg_id)>>8)&0XFF;//
strlorabuf[12]=((Machine_info.msg_id)>>0)&0XFF;//总包数，当前包数


  strlorabuf[13]=0x00;
  strlorabuf[14]=0x01;//长度
  strlorabuf[15]=(status)&0xff;
  strlorabuf[16]=0;
  
   crc16=strlorabuf[0]+strlorabuf[1];
  for(i=3;i<16;i++)
    crc16=crc16+strlorabuf[i];
   strlorabuf[2]=crc16&0xff;

  changebintotxt(strlorabuf,16);
  //Serial.println((char *)strlorabuf);
  strcat((char *)strlorabuf,(char *)Machine_info.cid);
  len=strlen((char *)strlorabuf);


  Send_list = postInsert(Send_list,Machine_info.msg_id, Machine_info.msg_id,(char *)strlorabuf,len); //插入数据

}




//唤醒时发送是否可以接收数据命令
void send_can_I_receive()
{
    printf("->can i\n");
     uint8_t strlorabuf[200];
     strlorabuf[0] = 0x5A;
     strlorabuf[1] = 0x51;
     strlorabuf[2] = 0x51;
     strlorabuf[3] = 0x5A;
     strlorabuf[4] = 0x00;
     #if 0
     strlorabuf[5] = 0x01;
     #else
     strlorabuf[5] = Machine_info.eflagID;


    if(Send_list!=NULL)
    {
        strlorabuf[6] = 0x01;
    }else
    {
        strlorabuf[6] = 0x00;
    }

 strlorabuf[7] = Machine_info.mac_addr[0];
 strlorabuf[8] = Machine_info.mac_addr[1];
 strlorabuf[9] = Machine_info.mac_addr[2];
 strlorabuf[10] = Machine_info.mac_addr[3];
 strlorabuf[11] = Machine_info.mac_addr[4];
 strlorabuf[12] = Machine_info.mac_addr[5];

    int crc = 0;

    for(int i =0;i<13;i++)
    {
        crc+=strlorabuf [i]; 
    }

     strlorabuf[13] = crc&0xff;


     #endif
     //send_lora_data(strlorabuf,len);  //不直接发送
     lora_send_data((char *)strlorabuf,14);
}


//发送是否可以接收数据命令
// void send_pair_ack()
// {
//      uint8_t strlorabuf[200];
//      strlorabuf[0] = 0x5A;
//      strlorabuf[1] = 0x51;
//      strlorabuf[2] = 0x51;
//      strlorabuf[3] = 0x5A;
//      strlorabuf[4] = 0x00;
//      #if 0
//      strlorabuf[5] = 0x01;
//      #else
//      strlorabuf[5] = Machine_info.eflagID;
//      strlorabuf[6] = lora_channel + 1;
//      #endif
//      //send_lora_data(strlorabuf,len);  //不直接发送
//      lora_send_data((char *)strlorabuf,7);
// }




void send_rssi(void)
{
    char rssi = Machine_info.rssi;
    #if 0
    protocol_package(0x05,&rssi,1);
    #else

    f_send_lora_rssi(rssi);
    #endif
}
// 4bytes、32bit数据大小端转化
#define L2B32(Little) (Little = ((Little & 0xff) << 24) | (((Little) & 0xff00) << 8) | (((Little) & 0xff0000) >> 8) | ((Little >> 24) & 0xff))


uint8_t change_btn_reversal(uint8_t reversal_btn)//lora收到按键，转化为本地状态
{
    uint8_t btn_tmp = 0;
    switch (reversal_btn)
    {
    case 0:
        btn_tmp = 1;
        break;
    case 1:
        btn_tmp = 6;
        break;
    case 2:
        btn_tmp = 4;
        break;
    case 3:
        btn_tmp = 3;
        break;
    case 4:
        btn_tmp = 5;
        break;
    case 5:
        btn_tmp = 2;
        break;
        break;
    default:
        btn_tmp = 1;
        break;
    }

    return btn_tmp;
}
uint8_t change_btn(uint8_t btn)
{
    uint8_t btn_tmp = 0;
    switch (btn)
    {
    case 1:
        btn_tmp = 0;
        break;
    case 2:
        btn_tmp = 5;
        break;
    case 3:
        btn_tmp = 3;
        break;
    case 4:
        btn_tmp = 2;
        break;
    case 5:
        btn_tmp = 4;
        break;
    case 6:
        btn_tmp = 1;
        break;
    default:
        btn_tmp = 0;
        break;
    }
    // ESP_LOGW(LOG_TAG,"btn = [%d] ,btn_tmp[%d]",btn,btn_tmp);
    return btn_tmp;
}
/*发送状态持续的时间  状态持续时长(0x0E)*/
void send_status_duration(void)
{
    #if 0
    uint8_t* dur = (uint8_t*)malloc(sizeof(uint8_t)*(12));

    memcpy(dur,&last_button_info.button_info,1);
    memcpy(dur+1,&last_button_info.Year,2);
    memcpy(dur+3,&last_button_info.Month,1);
    memcpy(dur+4,&last_button_info.Day,1);
    memcpy(dur+5,&last_button_info.Hour,1);
    memcpy(dur+6,&last_button_info.Minute,1);
    memcpy(dur+7,&last_button_info.Second,1);

    uint32_t tmp = last_button_info.time_min;
    L2B32(tmp);
    memcpy(dur+8,&tmp,4);

    ESP_LOGW(LOG_TAG,"log  -->btn = %d [%d-%d-%d]%d:%d:%d   <%04ld>",\
                    last_button_info.button_info, last_button_info.Year,\
                    last_button_info.Month,last_button_info.Day,\
                    last_button_info.Hour, last_button_info.Minute,\
                    last_button_info.Second,last_button_info.time_min);

    protocol_package(0x0E,dur,12);
    last_button_info.time_min = 0;
    free(dur);
    #else

uint8_t strlorabuf[200];

int crc16=0,i=0,len=0;

// 帧头    
strlorabuf[0]=0x5A;//包头                        
strlorabuf[1]=0x51;//包头
strlorabuf[2]=0x00;  //校验和               

strlorabuf[3]=mac_addr[0];
strlorabuf[4]=mac_addr[1];
strlorabuf[5]=mac_addr[2];
strlorabuf[6]=mac_addr[3];
strlorabuf[7]=mac_addr[4];
strlorabuf[8]=mac_addr[5];  
strlorabuf[9]=Machine_info.eflagID; //组内编号
strlorabuf[10]=0x0E;  //cmd命令字

Machine_info.msg_id =  allocateMsgIdNum();  //分配ID
strlorabuf[11]=((Machine_info.msg_id)>>8)&0XFF;//
strlorabuf[12]=((Machine_info.msg_id)>>0)&0XFF;//总包数，当前包数

strlorabuf[13]=0x00;
strlorabuf[14]=0x0C;//长度

uint8_t tmp = change_btn(Machine_info.last_button.button_info);
 strlorabuf[15]=tmp;//上一次的状态
  
  if((Machine_info.last_button.Year == 0x00) &&(Machine_info.last_button.Month == 0x00)&&(Machine_info.last_button.Day == 0x00) )
  {

    strlorabuf[16]=0x00;
    strlorabuf[17]=0x00;
    strlorabuf[18]=0x00;
    strlorabuf[19]=0x00;
    strlorabuf[20]=0x00;
    strlorabuf[21]=0x00;
    strlorabuf[22]=0x00;

    printf("time is not sync\r\n");

  }else
  {
    strlorabuf[16]=(Machine_info.last_button.Year>>8)&0xff;
    strlorabuf[17]=Machine_info.last_button.Year&0xff;
    strlorabuf[18]=Machine_info.last_button.Month;
    strlorabuf[19]=Machine_info.last_button.Day;
    strlorabuf[20]=Machine_info.last_button.Hour;
    strlorabuf[21]=Machine_info.last_button.Minute;
    strlorabuf[22]=Machine_info.last_button.Second;

    
  }

  strlorabuf[23]=( Machine_info.Duration_time>>24)&0xff;//分钟计算
  strlorabuf[24]=( Machine_info.Duration_time>>16)&0xff;
  strlorabuf[25]=( Machine_info.Duration_time>>8)&0xff;
  strlorabuf[26]=( Machine_info.Duration_time)&0xff;
  strlorabuf[27]=0;
  
   crc16=strlorabuf[0]+strlorabuf[1];
  for(i=3;i<27;i++)
    crc16=crc16+strlorabuf[i];
   strlorabuf[2]=crc16&0xff;
    // ESP_LOGE(LOG_TAG,"{cmd:0e}send_status_duration btn -->[%d] -->Duration_time = %ld -->time :%d %d %d %d %d %d %d",strlorabuf[15],Machine_info.Duration_time,strlorabuf[16],strlorabuf[17],strlorabuf[18],strlorabuf[19],strlorabuf[20],strlorabuf[21],strlorabuf[22]);

  changebintotxt(strlorabuf,27);


  //printf("Machine_info cid %s\r\n",Machine_info.cid);
 
  strcat((char *)strlorabuf,(char *)Machine_info.cid);
  len=strlen((char *)strlorabuf);


#if 0
  lora_send_data((char *)strlorabuf,len);

#else

//printList(Send_list);

Send_list = postInsert(Send_list,Machine_info.msg_id, Machine_info.msg_id,(char *)strlorabuf,len); //插入数据

#endif


//lora_send_data((char *)strlorabuf,len);

 last_button_info.time_min = 0;


#endif
}


/*当前最新的状态*/
void send_update_status(void)
{

    #if 0
    uint8_t* update = (uint8_t*)malloc(sizeof(uint8_t)*(12));
    memset(&new_button_info,0,sizeof(Button_Time_t));
    new_button_info.Year = Machine_info.year;
    new_button_info.Month = Machine_info.month;
    new_button_info.Day = Machine_info.day;
    new_button_info.Hour = Machine_info.hour;
    new_button_info.Minute = Machine_info.min;
    new_button_info.Second = Machine_info.sec;
    new_button_info.time_min = 0;


    memcpy(update,&last_button_info.button_info,1);
    memcpy(update+1,&new_button_info.Year,2);
    memcpy(update+3,&new_button_info.Month,1);
    memcpy(update+4,&new_button_info.Day,1);
    memcpy(update+5,&new_button_info.Hour,1);
    memcpy(update+6,&new_button_info.Minute,1);
    memcpy(update+7,&new_button_info.Second,1);
    memcpy(update+8,&new_button_info.time_min,4);

    protocol_package(0x0F,update,12);
    free(update);
    #else



// memset(&Machine_info.current_button,0,sizeof(Button_Time_t));


    Machine_info.current_button.Year = Machine_info.year;
    Machine_info.current_button.Month = Machine_info.month;
    Machine_info.current_button.Day = Machine_info.day;
    Machine_info.current_button.Hour = Machine_info.hour;
    Machine_info.current_button.Minute = Machine_info.min;
    Machine_info.current_button.Second = Machine_info.sec;
    Machine_info.current_button.time_min = 0;




uint8_t strlorabuf[200];

uint8_t  strnum[20];

  int crc16=0,i=0,len=0;

  // 帧头                                目标地址           源地址(id)           长度              模式                具体内容 	              校验 
  strlorabuf[0]=0x5A;
  strlorabuf[1]=0x51;//包头
  strlorabuf[2]=0x00;  //校验和               

 strlorabuf[3]=mac_addr[0];
 strlorabuf[4]=mac_addr[1];
 strlorabuf[5]=mac_addr[2];
 strlorabuf[6]=mac_addr[3];
 strlorabuf[7]=mac_addr[4];
 strlorabuf[8]=mac_addr[5]; 
 
 strlorabuf[9]=Machine_info.eflagID; //组内编号

 strlorabuf[10]=0x0F;  //cmd命令字

 Machine_info.msg_id =  allocateMsgIdNum();  //分配ID
 strlorabuf[11]=((Machine_info.msg_id)>>8)&0XFF;//
 strlorabuf[12]=((Machine_info.msg_id)>>0)&0XFF;//总包数，当前包数
 
  strlorabuf[13]=0x00;

  strlorabuf[14]=0x0C;//长度

    uint8_t tmp = change_btn(Machine_info.current_button.button_info);

  strlorabuf[15]=tmp;//当前的状态
  
  if((Machine_info.current_button.Year == 0x00) &&(Machine_info.current_button.Month == 0x00)&&(Machine_info.current_button.Day == 0x00) )
  {

    strlorabuf[16]=0x00;
    strlorabuf[17]=0x00;
    strlorabuf[18]=0x00;
    strlorabuf[19]=0x00;
    strlorabuf[20]=0x00;
    strlorabuf[21]=0x00;
    strlorabuf[22]=0x00;

    printf("time is not sync\r\n");

  }else
  {
    strlorabuf[16]=(Machine_info.current_button.Year>>8)&0xff;
    strlorabuf[17]=Machine_info.current_button.Year&0xff;
    strlorabuf[18]=Machine_info.current_button.Month;
    strlorabuf[19]=Machine_info.current_button.Day;
    strlorabuf[20]=Machine_info.current_button.Hour;
    strlorabuf[21]=Machine_info.current_button.Minute;
    strlorabuf[22]=Machine_info.current_button.Second;
  }



  strlorabuf[23]=( Machine_info.current_button.time_min>>24)&0xff;//分钟计算
  strlorabuf[24]=( Machine_info.current_button.time_min>>16)&0xff;
  strlorabuf[25]=( Machine_info.current_button.time_min>>8)&0xff;
  strlorabuf[26]= Machine_info.current_button.time_min&0xff;
  strlorabuf[27]=0;
// ESP_LOGE(LOG_TAG,"@@send_update_status -->btn = [%d] -->time :%d %d %d %d %d %d %d",strlorabuf[15],strlorabuf[16],strlorabuf[17],strlorabuf[18],strlorabuf[19],strlorabuf[20],strlorabuf[21],strlorabuf[22]);

   crc16=strlorabuf[0]+strlorabuf[1];
  for(i=3;i<27;i++)
    crc16=crc16+strlorabuf[i];
   strlorabuf[2]=crc16&0xff;


  changebintotxt(strlorabuf,27);

//   printf("Machine_info cid %s\r\n",Machine_info.cid);
 
  strcat((char *)strlorabuf,(char *)Machine_info.cid);
  len=strlen((char *)strlorabuf);

#if 0
    lora_send_data((char *)strlorabuf,len);
#else
    Send_list = postInsert(Send_list,Machine_info.msg_id, Machine_info.msg_id,(char *)strlorabuf,len); //插入数据

#endif

  Machine_info.last_button.time_min = 0;



    #endif
}




void send_ACK(char cmd,bool flag)
{
    uint8_t ack = 0;
    if(flag)
        ack = 0x01;
    else
        ack = 0x00;
    protocol_package(cmd,&ack,1);
}

void adc1_init(void)
{
    //-------------ADC Init---------------//
    adc_oneshot_unit_init_cfg_t init_config = {
        .unit_id = ADC_UNIT_1,
        .ulp_mode = ADC_ULP_MODE_DISABLE,
    };
    ESP_ERROR_CHECK(adc_oneshot_new_unit(&init_config, &adc1_handle));
}
// void set_status_heights(void)
// {
//     extern uint32_t arr_heights[10];
//     memcpy(&_0703_button_info,&last_button_info,sizeof(Button_Time_t));
//     switch (_0703_button_info.button_info)
//     {
//         case 0:
//         case 1://yunxing
//             arr_heights[0]+=1;
//         break;
//         case 2://tingji
//             arr_heights[1]+=1;
//         break;
//         case 3://guzhang
//             arr_heights[2]+=1;
//         break;
//         case 4://fengcun
//             arr_heights[3]+=1;
//         break;
//         case 5://baoyang
//             arr_heights[4]+=1;
//         break;
//         case 6://dailiao
//             arr_heights[5]+=1;
//         break;
//         default:

//         break;
//     }
//     // ESP_LOGE(LOG_TAG,"button_info = %d ,time_min = %ld ---%ld - %ld - %ld - %ld - %ld - %ld",
//     //                 _0703_button_info.button_info,_0703_button_info.time_min,
//     //                 arr_heights[0],arr_heights[1],arr_heights[2],
//     //                 arr_heights[3],arr_heights[4],arr_heights[5]);
// }
void set_status_heights(void)
{
    //     STATE_OPERATION             = 1,        //运行
    // STATE_SHUT_DOWN             = 2,        //停机
    // STATE_BREAKDOWN             = 3,        //故障
    // STATE_SAFEKEEP              = 4,        //封存
    // STATE_UPKEEP                = 5,        //保养
    // STATE_WAIT_MATERIALS        = 6,        //待料
    extern uint32_t arr_heights[10];
    switch (Machine_info.last_button.button_info)
    {
        case 0:
        case 1://yunxing
            arr_heights[0]+=Machine_info.Duration_time;
        break;
        case 2://tingji
            arr_heights[1]+=Machine_info.Duration_time;
        break;
        case 3://guzhang
            arr_heights[2]+=Machine_info.Duration_time;
        break;
        case 4://fengcun
            arr_heights[3]+=Machine_info.Duration_time;
        break;
        case 5://baoyang
            arr_heights[4]+=Machine_info.Duration_time;
        break;
        case 6://dailiao
            arr_heights[5]+=Machine_info.Duration_time;
        break;
        default:

        break;
    }
    // ESP_LOGE(LOG_TAG,"button_info = %d ,time_min = %ld ---%ld - %ld - %ld - %ld - %ld - %ld",
    //                 _0703_button_info.button_info,_0703_button_info.time_min,
    //                 arr_heights[0],arr_heights[1],arr_heights[2],
    //                 arr_heights[3],arr_heights[4],arr_heights[5]);
}
// void periodic_timer_callback(void* arg)
// {
//     // if(++Machine_info.sec == 60)
//     // {
//     //     last_button_info.time_min+=1;
//     //     set_status_heights();
//     //     printf("time min ++\r\n");
//     //     printf("YEAR = %d,MONTH =%d,DAY=%d,HOUR=%d,MIN=%d,SEC =%d\r\n",
//     //     Machine_info.year,
//     //     Machine_info.month,
//     //     Machine_info.day,
//     //     Machine_info.hour,
//     //     Machine_info.min,
//     //     Machine_info.sec);

//     //     Machine_info.sec=0;
//     //     if(++Machine_info.min == 60)
//     //     {
//     //         Machine_info.min=0;
//     //         if(++Machine_info.hour == 24)
//     //         {
//     //             Machine_info.hour=0;
//     //             Machine_info.day++;
                
//     //             if(IS_FEB_MONTH && IS_LEAP_YEAR && IS_SMALL_MONTH && IS_BIG_MONTH)
//     //             {
//     //                 Machine_info.day=0;

//     //                 if(++Machine_info.month == 13)
//     //                 {
//     //                     Machine_info.month=1;
//     //                     Machine_info.year++;
//     //                 }
//     //             }
//     //         }
//     //     }
//     // }
// }

void lora_timer_callback(void* arg)
{
    ESP_LOGD(LOG_TAG," lora_timer_callback");
    
    if(xQueueSend(yc_data_queue,&yc_data,0) != true)
    {
        ESP_LOGE(LOG_TAG,"yc_data_queue send is fail");
    }
    yc_data.len = 0;
    yc_data.index = 0;
}
void timer_init(void)
{
    // const esp_timer_create_args_t periodic_timer_args = {
    //         .callback = &periodic_timer_callback,
    //         /* name is optional, but may help identify the timer when debugging */
    //         .name = "periodic"
    // };

    // ESP_ERROR_CHECK(esp_timer_create(&periodic_timer_args, &periodic_timer));
    // /* The timer has been created but is not running yet */

    // ESP_ERROR_CHECK(esp_timer_start_periodic(periodic_timer, 1*1000*1000));



        //lora timer
    const esp_timer_create_args_t lora_timer_args = {
            .callback = &lora_timer_callback,
            /* argument specified here will be passed to timer callback function */
            .name = "one-shot"
    };
    ESP_ERROR_CHECK(esp_timer_create(&lora_timer_args, &lora_timer));
}
// void yc_timer_restart(void)
// {
//     ESP_LOGI(LOG_TAG,"timer restart");
//     ESP_ERROR_CHECK(esp_timer_stop(periodic_timer));
//     ESP_ERROR_CHECK(esp_timer_start_periodic(periodic_timer, 1*1000*1000));
// }


void lora_timer_start(void)
{
    ESP_ERROR_CHECK(esp_timer_start_once(lora_timer, 500*1000));//500ms
}
void lora_tiemr_stop(void)
{
    ESP_ERROR_CHECK(esp_timer_stop(lora_timer));
}
void lora_timer_restart(void)
{
    ESP_ERROR_CHECK(esp_timer_stop(lora_timer));
    ESP_ERROR_CHECK(esp_timer_start_once(lora_timer, 500*1000));//500ms
}




#if 1

/*********************************************************************************
* function   :   analysis_protocol     
* Description :  lora 接受数据解析函数
* Input       :  
* Output      :  
* Author      :  祁鑫                  Data : 2023 9.18
**********************************************************************************/	
void  analysis_protocol(char *result,int len)
{
  int index = 0;
  int length = 0;

  int count = len;

  int num = 0;


        while(count)
        {
         
              if( ((result[index+2]) == 0x5A) && ((result[index +3]) == 0x51))
              {
                length = ((result[index])<<8) | ((result[index + 1])); 
                num++;
                printf("num =%d,length=%d\r\n",num,length);

                #if 1
                for(int i = 0;i<length;i++)
                {
                  printf("%02x",result[index+2+i]);
                }
                #endif
                printf("\r\n");

              // 匹配mac地址    //计算校验和
              if( 
                  (Machine_info.mac_addr[0] == (result[index+5]))  &&
                  (Machine_info.mac_addr[1] == (result[index+6]))  &&
                  (Machine_info.mac_addr[2] == (result[index+7]))  &&
                  (Machine_info.mac_addr[3] == (result[index+8]))  &&
                  (Machine_info.mac_addr[4] == (result[index+9]))  &&
                  (Machine_info.mac_addr[5] == (result[index+10]))
                )
                {

                          //mac地址匹配
                          printf("mac check ok\r\n");
                          //packetparsing((unsigned char *)&result[index+2]);  //16进制解析数据

                }else
                {
                        printf("mac = %02x%02x%02x%02x%02x%02x\r\n",
                        result[index+5],
                        result[index+6],
                        result[index+7],
                        result[index+8],
                        result[index+9],
                        result[index+10]);
                        printf("device mac = %02x%02x%02x%02x%02x%02x\r\n",
                        Machine_info.mac_addr[0],
                        Machine_info.mac_addr[1],
                        Machine_info.mac_addr[2],
                        Machine_info.mac_addr[3],
                        Machine_info.mac_addr[4],
                        Machine_info.mac_addr[5]   
                        );
                          //mac地址匹配
                          printf("mac check fail\r\n");

                }    

              }
             
              {
                     index++;
              }
              
              count--;
        }
            //printf("num =%d\r\n",num);

#if 0
        if(left_display_refresh == true)
        {
          left_display_refresh = false;
                PIC_display((unsigned char *)dspbuf_left);
        }   
            reflashdfpr(dspbuf);
 #endif       


}















/*********************************************************************************
* function   :   selectionSort  
* Description :  进行数据排序并输出排序后的数据 从小到大的索引
* Input       :  
* Output      :  
* Author      :  祁鑫                  Data : 2023 8.12
**********************************************************************************/
void selectionSort(int arr[], int n, int indices[]) {
    for (int i = 0; i < n - 1; i++) {
        int minIndex = i;
        for (int j = i + 1; j < n; j++) {
            if (arr[j] < arr[minIndex]) {
                minIndex = j;
            }
        }
        
        // 交换元素
        int temp = arr[i];
        arr[i] = arr[minIndex];
        arr[minIndex] = temp;

        // 更新索引
        int tempIndex = indices[i];
        indices[i] = indices[minIndex];
        indices[minIndex] = tempIndex;
    }
}



/*********************************************************************************
* function   :   person_get_num_is_exist  
* Description :  获取当前类型序号是否存在
* Input       :  
* Output      :  
* Author      :  祁鑫                  Data : 2023 8.12
**********************************************************************************/

int  person_get_num_is_exist(uint8_t type,uint16_t num)
{
     uint8_t  index = 0;
 
    // printf("person_get_num_is_exist %d\r\n",num);

    


            if(type== person[type].person_type) 
            {
              
                for(int i  = 0;i<PERSON_MAX_NAME;i++)
                {
                    if(person[type].person_name[i].person_num == num)
                    {
                            //printf("person_get_num is exist\r\n");
                            return 1;
                    }
                }
            
            }

          //printf("person_get_num not exist\r\n");
          return 0;
}


/*********************************************************************************
* function   :   person_get_num  
* Description :  获取当前类型人员数量
* Input       :  
* Output      :  
* Author      :  祁鑫                  Data : 2023 8.12
**********************************************************************************/

int  person_get_num(uint8_t type)
{
     uint8_t  index = 0;
              //printf("person_get_num\r\n");
            if(type== person[type].person_type) //管理员
            {
              
                
                 //查找当前不为空的字符串数组
                for(int i  = 0;i<PERSON_MAX_NAME;i++)
                {
                    if(strlen((char *)&person[type].person_name[i].person_name)!=0)
                       {
                          index++;
                       } 
                }
            
            }

    
          return index;
}
/*********************************************************************************
* function   :   person_add  
* Description :  人员添加/更新
* Input       :  
* Output      :  
* Author      :  祁鑫                  Data : 2023 8.12
**********************************************************************************/

void person_add(uint8_t type,uint8_t num,char* in,char *out)
{
//printf("person_add\r\n");
            if(type== person[type].person_type) //管理员
            {
                 uint8_t  index = 0;
                
                 //查找当前不为空的字符串数组
                for(int i  = 0;i<PERSON_MAX_NAME;i++)
                {
                  //Serial.println(person[type].person_name[i].person_num);
                  //如果序号存在更新
                  if(person[type].person_name[i].person_num == num)
                  {
                     //Serial.print("person_num exist = ");
                     //Serial.println(person[type].person_name[i].person_num);
                        index = i;
                        break;
                  }

                  //如果序号不存在添加
                  if(strlen((char *)&person[type].person_name[i].person_name)==0)
                  {
                    //Serial.print("person_num not exist = ");
               
                        index = i;
                        person[type].person_name[i].person_num =num;
                    //Serial.println(person[type].person_name[i].person_num);
                  break;
                  }
                }
                  if(index>PERSON_MAX_NAME)
                  {

                  }else
                  {
                      if(person[type].person_name[index].person_num == num)
                      {
                            memset(&person[type].person_name[index].person_name,0x00,PERSON_NAME_MAX_LEN);
                      }
                       strcpy((char *)&person[type].person_name[index].person_name,in);
                  }

                //Serial.println("show font");
//开始显示数据
int   sort_buffer[PERSON_MAX_NAME]={0};  //获取当前序号值

  int indices[PERSON_MAX_NAME];              //排序后的索引值
    for (int i = 0; i < PERSON_MAX_NAME; i++) {
        indices[i] = i;
    }

//拷贝序号数据
for(int i = 0;i<PERSON_MAX_NAME;i++)
{
  sort_buffer[i] =  person[type].person_name[i].person_num;
}


selectionSort(sort_buffer, PERSON_MAX_NAME, indices);

#if 0
    //Serial.print("Sorted array: ");
    for (int i = 0; i < PERSON_MAX_NAME; i++) {
        //Serial.print(sort_buffer[i]);
        //Serial.print(",");
    }
//Serial.println("");
    //Serial.print("\nOriginal indices: ");
    for (int i = 0; i < PERSON_MAX_NAME; i++) {
        //Serial.print(indices[i]);
        //Serial.print(",");
    }
//Serial.println("");
#endif
#if 0

 //进行序号排序
 bubbleSort(sort_buffer, PERSON_MAX_NAME);
 #endif


                for(int i  = 0;i<PERSON_MAX_NAME;i++)
                {

                  int display_index = 0;

                       display_index   = indices[i];  //获取当前显示的索引

                       //Serial.println(person[type].person_name[display_index].person_num);
                       if(strlen((char *)&person[type].person_name[display_index].person_name)!=0)
                       {
                            strcat(out,(char *)&person[type].person_name[display_index].person_name);  
                            strcat(out," ");   
                       }  

                }
          }
}
/*********************************************************************************
* function   :   person_del  
* Description :  人员删除
* Input       :  
* Output      :  
* Author      :  祁鑫                  Data : 2023 8.12
**********************************************************************************/
void person_del(uint8_t type,uint8_t num,char* in,char *out)
{

    //printf("person_del\r\n");
  //Serial.print("delete num ");
  //Serial.println(num);

              if(type== person[type].person_type) 
            {
                 uint8_t  index = 0;
                
                 //查找当前不为空的字符串数组
                for(int i  = 0;i<PERSON_MAX_NAME;i++)
                {
                  //如果序号存在
                  if(person[type].person_name[i].person_num == num)
                  {
                       printf("person_num exist \r\n");
                     //Serial.println(person[type].person_name[i].person_num);
                        index = i;
                        break;
                  }
                    //return;
                }


                
                  {
                      if((person[type].person_name[index].person_num == num) )
                      {
                            //清空显示
                            //Serial.println("delete index data");
                            printf("delete index data \r\n");
                            person[type].person_name[index].person_num = 0;
                            memset(&person[type].person_name[index].person_name,0x00,PERSON_NAME_MAX_LEN);
                      }
                       //strcpy((char *)&person[type].person_name[index].person_name,in);
                  }
                      //Serial.println("show font");

#if 0
                for(int i  = 0;i<PERSON_MAX_NAME;i++)
                {

                       Serial.println(person[type].person_name[i].person_num);
                       if(strlen((char *)&person[type].person_name[i].person_name)!=0)
                       {
                            strcat(out,(char *)&person[type].person_name[i].person_name);  
                            strcat(out,"  ");   
                       }  

                }
#else
//开始显示数据  
int   sort_buffer[PERSON_MAX_NAME]={0};  //获取当前序号值

  int indices[PERSON_MAX_NAME];              //排序后的索引值
    for (int i = 0; i < PERSON_MAX_NAME; i++) {
        indices[i] = i;
    }

//拷贝序号数据
for(int i = 0;i<PERSON_MAX_NAME;i++)
{
  sort_buffer[i] =  person[type].person_name[i].person_num;
}


selectionSort(sort_buffer, PERSON_MAX_NAME, indices);

#if 0
    Serial.print("Sorted array: ");
    for (int i = 0; i < PERSON_MAX_NAME; i++) {
        Serial.print(sort_buffer[i]);
        Serial.print(",");
    }
Serial.println("");
    Serial.print("\nOriginal indices: ");
    for (int i = 0; i < PERSON_MAX_NAME; i++) {
        Serial.print(indices[i]);
        Serial.print(",");
    }
Serial.println("");
#endif
                for(int i  = 0;i<PERSON_MAX_NAME;i++)
                {

                  int display_index = 0;

                       display_index   = indices[i];  //获取当前显示的索引

                       //Serial.println(person[type].person_name[display_index].person_num);
                       if(strlen((char *)&person[type].person_name[display_index].person_name)!=0)
                       {
                            strcat(out,(char *)&person[type].person_name[display_index].person_name);  
                            strcat(out," ");   
                            printf("out = %s\r\n",out);
                       }  

                }

#endif                

              

      }
}
















#endif




void loro_gwpair_ack(int destaddr,int sourceaddr,int cmd,int st,char *strd)
{
  uint8_t strlorabuf[50];
  int crc16=0,len,i;
   memset(strlorabuf,0,50);    
  //源地址 是指网关地址
  //帧头                                                目标地址                      源地址(id)                  长度               模式           具体内容 	              校验 
  strlorabuf[0]=0x55;
  strlorabuf[1]=0xaa;
  strlorabuf[2]=destaddr&0xff;
  strlorabuf[3]=sourceaddr&0xff;
  strlorabuf[4]=0x02;
  strlorabuf[5]=cmd;
  strlorabuf[6]=st;
  strcpy((char *)(strlorabuf+7),strd); //mac+c_id
   crc16=strlorabuf[0]+strlorabuf[1]+strlorabuf[2]+strlorabuf[3]+strlorabuf[4]+strlorabuf[5]+strlorabuf[6];
  len=strlen(strd);
  strlorabuf[4]=4+len;
  for(i=0;i<len;i++)
    crc16=crc16+strlorabuf[7+len];

   strlorabuf[7+len]=(crc16>>8)&0xff;
   strlorabuf[8+len]=crc16&0xff;
   strlorabuf[9+len]=0;
   #if 0
   send_lora_data(strlorabuf,9+len);
   #else
   //loraSerial.write((char *)strlorabuf,len); 

  lora_send_data((char *)strlorabuf,len);
   #endif
}





void lora_rev_cmd_send_ack()
{


}
void right_screen_send()
{
    if(xQueueSend(right_screen_queue,&Machine_info,portMAX_DELAY) != true)
    {
        ESP_LOGE(LOG_TAG,"queue:right_screen_queue");
    } 
}
void user_compare(int last,int now)//这个函数用来比较rssi和 电量变化 刷右屏//
{
    if((last == now)||(Machine_info.power_status == 0))
    {
        // ESP_LOGW(LOG_TAG,"last[%d]-now[%d]",last,now);
        return;
    }
    // printf("user_compare last[%d] now[%d] \n",last,now); 
    bool is_send_right_screen = false;
    switch (last)
    {
        case 100:
            if(now != 100)
            {
                is_send_right_screen =true;
            }
        break;
        case 75 ... 99:
            if((now == 100) || (now<75))
            {
                is_send_right_screen =true;
            }
        break;
        case 50 ... 74:
            if((now > 74) || (now<50))
            {
                is_send_right_screen =true;
            }
        break;
        case 25 ... 49:
            if((now >49) || (now<25))
            {
                is_send_right_screen =true;
            }
        break;
        case 0 ... 24:
            if((now == 0) || (now>24))
            {
                is_send_right_screen =true;
            }
        break;
        default:
        ESP_LOGE(LOG_TAG,"err:not 0~100");
        break;
    }
    if(is_send_right_screen)
        right_screen_send();
}





void user_compare_power_off(int last,int now)//这个函数用来比较关机状态时电量变化 刷右屏//
{
    if((last == now))
    {
        // ESP_LOGW(LOG_TAG,"last[%d]-now[%d]",last,now);
        return;
    }
    // printf("user_compare_power_off last[%d] now[%d] \n",last,now);
    extern void dis_right_instructions();
    switch (last)
    {
        case 100:
            if(now != 100)
            {
                    gpio_hold_dis(PIN_R_CS);
                    dis_right_instructions();
            }
        break;
        case 75 ... 99:
            if((now == 100) || (now<75))
            {
                gpio_hold_dis(PIN_R_CS);
                dis_right_instructions();
            }
        break;
        case 50 ... 74:
            if((now > 74) || (now<50))
            {
                gpio_hold_dis(PIN_R_CS);
                dis_right_instructions();
            }
        break;
        case 25 ... 49:
            if((now >49) || (now<25))
            {
                gpio_hold_dis(PIN_R_CS);
                dis_right_instructions();

            }
        break;
        case 0 ... 24:
            if((now == 0) || (now>24))
            {
                gpio_hold_dis(PIN_R_CS);
                dis_right_instructions();
            }
        break;
        default:
        ESP_LOGE(LOG_TAG,"err:not 0~100");
        break;
    }
}



