#include "bsp_ml307r.h"
#include "at_chat.h"
#include "at_port.h"
#include "bsp_uart.h"
#include "log.h"
#include "stdio.h"
#include "CONFIG.h"
#include "SLEEP.h"
#include "bsp_iwdg.h"
#include "bsp_bmp390.h"
#include "bsp_tim.h"
#include "time.h"
#include <stdlib.h>
#include "cJSON.h"
#undef  LOG_ENABLE
#define LOG_ENABLE  1

IotFlagStruct  IotFlag_t;

#define ML307_PERIODIC_EVT (0x0001 << 0)


MultiTimer Multi_Power_ON_t;  //开机
MultiTimer Multi_Power_OFF_t; //关机
MultiTimer Multi_Restart_t;   //重启
MultiTimer Multi_Cpin_t;      //cpin
MultiTimer Multi_Connect_t;   //Connect
MultiTimer Multi_Send_t;      //Send
MultiTimer Multi_StopTask_t;  //StopTask
MultiTimer Multi_Loop_t;      //Loop
MultiTimer Multi_GetInfo_t;   //siminfo

static tmosTaskID ml307_task_id = INVALID_TASK_ID;

at_obj_t *ml307r_obj;


int Ml307r_Gpio_Init(void)
{
    GPIOB_SetBits(ENABLE_3_8_V);
    GPIOB_ModeCfg(ENABLE_3_8_V, GPIO_ModeOut_PP_5mA);

    GPIOB_ResetBits(ML307_RST_PIN);
    GPIOB_ModeCfg(ML307_RST_PIN, GPIO_ModeOut_PP_5mA);

    GPIOB_ModeCfg(USIM_DECT_PIN, GPIO_ModeIN_Floating);

    GPIOB_ModeCfg(ML307_PWR_PIN, GPIO_ModeOut_PP_5mA);

    return 0;
}

// 初始化 cJSON 使用 TMOS 的内存管理函数
void Init_cJSON_With_TMOS(void)
{
    cJSON_Hooks hooks;
    hooks.malloc_fn = (void *(*)(size_t))tmos_msg_allocate; 
    hooks.free_fn = (void (*)(void *))tmos_msg_deallocate;    
    cJSON_InitHooks(&hooks);
}

void At_Debug(const char *fmt, ...)
{
    va_list args;
    va_start(args, fmt);
    vprintf(fmt, args);
    va_end(args);
}

void Ml307_Delay_Ms(uint16_t ms)
{
    DelayMs(ms);
}

void Ml307_Delay_us(uint16_t us)
{
    DelayUs(us);
}

static const at_adapter_t at_adapter =
{
    .write  = BSP_Uart1_Send_Data,
    .read   = BSP_Uart1_Receive_Data,
    .debug  = At_Debug,
    .recv_bufsize   = 256,
    .urc_bufsize    = 512
};

static uint8_t state = 0;
/*
 * 时间间隔,单位:ms,默认:10s
 */
#define   POWERON_RETRY_INTERVAL_TIME           (10*1000UL)
#define   RESTART_RETRY_INTERVAL_TIME           (40*1000UL)
#define   CPIN_RETRY_INTERVAL_TIME              (20*1000UL)
#define   CONNECT_RETRY_INTERVAL_TIME           (20*1000UL)
#define   SEND_RETRY_INTERVAL_TIME              (30*1000UL)
#define   STOP_TASK_INTERVAL_TIME               (15*1000UL)
#define   LOOP_INTERVAL_TIME                    (30*1000UL)
#define   GETINFO_INTERVAL_TIME                 (20*1000UL)

//开机回调
void Power_ON_t_CallBack(MultiTimer* timer, void* userData)
{
    IotFlag_t.PowerOn_error_flag = 1;
}

//重启超时回调
void Restart_CallBack(MultiTimer* timer, void* userData)
{
    IotFlag_t.restart_error_flag = 1;
}

//Cpin超时回调
void Cpin_CallBack(MultiTimer* timer, void* userData)
{
    IotFlag_t.sim_error_flag = 1;
}

//Connect超时回调
void Connect_CallBack(MultiTimer* timer, void* userData)
{
    IotFlag_t.Connect_error_flag = 1; 
}

//GetInfo超时回调
void GetInfo_CallBack(MultiTimer* timer, void* userData)
{
    IotFlag_t.ModInfo_error_flag = 1;
}

//Send超时回调
void Send_CallBack(MultiTimer* timer, void* userData)
{
    IotFlag_t.send_error_flag = 1; 
}

//Loop回调
void Loop_CallBack(MultiTimer* timer, void* userData)
{
    state = 0;
    IotFlag_t.Loop_count_flag++;
    IotFlag_t.module_init_flag = 1;
    IotFlag_t.Iot_Retry_flag = 0;
}

//StopTask超时回调
void StopTask_CallBack(MultiTimer* timer, void* userData)
{
    logDebug("BSP_Ml307_Power_Off\r\n");
    IotFlag_t.Loop_count_flag = 0;
    if(IotFlag_t.PowerOn_error_flag == 1)
    {
        IotFlag_t.PowerOn_error_flag = 0;
        tmos_stop_task(ml307_task_id, ML307_PERIODIC_EVT); 
        BSP_RequestSleep();
    }else{
        // BSP_Ml307_Power_Off();          //关机
        tmos_stop_task(ml307_task_id, ML307_PERIODIC_EVT); 
        BSP_RequestSleep();
    }
    IotFlag_t.Date_Sending_flag = 0;
}

//模块准备就绪
static int URC_Module_Ready_Cb(at_urc_info_t *info)
{
    logDebug("module CPIN READY ! \r\n");

    return 0;
}


/**
 * @brief urc订阅表
 */
static const urc_item_t urc_table[] =
{
    {.prefix = "+CPIN: READY",       .endmark = '\n',  .handler = URC_Module_Ready_Cb},//模块准备就绪
};


uint64_t imei_dec = 0;//十进制的IMEI,用作随机时延的入参
TsModule_Info_t Module_Info_t = {0};
//Convert strings to hexadecimal strings and store them in hex_arry
void Module_String2Hex(char *hex_arry, char *str)
{
    for (int i = 0; i < strlen(str); i++)
    {
        sprintf(hex_arry + (i * 2), "%02X", str[i]);
    }
}

static void Module_Get_Imei_Cb(at_response_t *r)
{
    char imei[16] = {0};
    if (r->code == AT_RESP_OK)
    {
        if (sscanf(r->prefix, "+GSN:%s\r\n", imei) == 1)
        {
            logDebug("imei: %s\r\n", imei);
            imei_dec = strtoll(imei, NULL, 10);
            Module_String2Hex(Module_Info_t.imei, imei);
            sprintf(Module_Info_t.imei_len, "%04X", strlen(Module_Info_t.imei)/2);
            logDebug("Module_Info_t.imei: %s\r\n", Module_Info_t.imei);
        }
    }
    else
    {
        logDebug("'CGSN' command response failed!\r\n");
    }
}

/*
 * @brief 获取IMEI数据
 * @return
 */
static void Module_Get_Imei(void)
{
    at_attr_t attr;
    at_attr_deinit(&attr);
    attr.prefix = "+GSN:";
    attr.cb = Module_Get_Imei_Cb;
    at_send_singlline(ml307r_obj, &attr, "AT+GSN=1");
}

static void Module_Get_Imsi_Cb(at_response_t *r)
{
    char imsi[60] = {0};
    if (r->code == AT_RESP_OK)
    {
        if (sscanf(r->prefix, "%s\r\n", imsi) == 1)
        {
            logDebug("imsi:%s\r\n",imsi);
            Module_String2Hex(Module_Info_t.imsi, imsi);
            sprintf( Module_Info_t.imsi_len, "%04X", strlen(Module_Info_t.imsi)/2);
            logDebug("Module_Info_t.imsi: %s\r\n", Module_Info_t.imsi);
        }
    }
    else
    {
        logDebug("'AT+CIMI' command response failed!\r\n");
    }
}

/*
 * @brief 获取IMSI数据
 * @return
 */
static void Module_Get_Imsi(void)
{
    at_attr_t attr;
    at_attr_deinit(&attr);
    attr.prefix = "46";
    attr.suffix = "\r\n";
    attr.cb = Module_Get_Imsi_Cb; 
    at_send_singlline(ml307r_obj, &attr, "AT+CIMI");
}


static void Module_Get_Iccid_Cb(at_response_t *r)
{
    char iccid[30] = {0};

    if (r->code == AT_RESP_OK)
    {
        //+QCCID: 898604D3102280304162
        if (sscanf(r->prefix, "+MCCID: %s", iccid) == 1)
        {
            logDebug("iccid: %s\r\n", iccid);
            Module_String2Hex(Module_Info_t.iccid, iccid);
            sprintf( Module_Info_t.iccid_len, "%04X", strlen(Module_Info_t.iccid)/2);
            logDebug("Module_Info_t.iccid: %s\r\n", Module_Info_t.iccid);
        }
    }
    else
    {
        logDebug("'AT+QCCID' command response failed!\r\n");
    }
}

/*
 * @brief 获取ICCID数据
 * @return
 */
static void Module_Get_Iccid(void)
{
    at_attr_t attr;
    at_attr_deinit(&attr);
    attr.prefix = "+MCCID:";
    attr.cb = Module_Get_Iccid_Cb;
    at_send_singlline(ml307r_obj, &attr, "AT+MCCID");
}


//从字符串中提取特定格式的时间信息。
void find_and_extract(char* string_buf, char* result)
{
    const char *start = "+CCLK: \"";
    const char *end = "+32\"";

    char *s = strstr(string_buf, start);
    if(s)
    {
        s += strlen(start);
        char *e = strstr(s, end);
        if(e)
        {
            *e = '\0';
            strncpy(result, s, e-s+1);
        }
    }
}

/*
 * 时区设置：默认东八区
 */
#define TIMER_ZONE                              (8U)

// 将本地时间转换为对应时区时间
static void Time_Zone_Conversion(struct tm* timeInfo)
{
    // 根据时区差异进行转换，这里时区差为8小时，没有分钟差异。
    timeInfo -> tm_hour += TIMER_ZONE; //小时部分加8小时
    if (timeInfo -> tm_hour >= 24)
    {                                  //如果超过24小时，则天数加1，小时数减24。
        timeInfo -> tm_mday++;
        timeInfo -> tm_hour -= 24;
        if (timeInfo -> tm_mday >365)
        {
            timeInfo -> tm_year += 1;
        }
    }
}


struct tm Network_Time_t;//网络时间

static void Module_Timer_Cb(at_response_t *r)
{
    int year, mounth, days, hous, min, sec;

    char urc_buf[32] = {0};

    if (r->code == AT_RESP_OK)
    {
        // +CCLK: "24/02/01,05:11:35+32"
        find_and_extract(r->recvbuf, urc_buf);
        if(sscanf(urc_buf, "%d/%d/%d,%d:%d:%d", &year, &mounth, &days, &hous, &min, &sec) == 6)
        {
            logDebug("urc_buf:%s\r\n", urc_buf);
            Network_Time_t.tm_year = (2000 + year);
            Network_Time_t.tm_mon  = mounth;
            Network_Time_t.tm_mday = days;
            Network_Time_t.tm_hour = hous;//此时为零区时间，需要转化为东八区
            Network_Time_t.tm_min  = min;
            Network_Time_t.tm_sec  = sec;
            Time_Zone_Conversion(&Network_Time_t);//时区设置

            // RTC_InitTime(Network_Time_t.tm_year, Network_Time_t.tm_mon, Network_Time_t.tm_mday,
            //                               Network_Time_t.tm_hour, Network_Time_t.tm_min, Network_Time_t.tm_sec); //更新当前时间
            // IotFlag_t.update_time_flag = 1;
            logDebug("NET Timer :%04d-%02d-%02d, %02d:%02d:%02d\r\n", Network_Time_t.tm_year, Network_Time_t.tm_mon, Network_Time_t.tm_mday,
                    Network_Time_t.tm_hour, Network_Time_t.tm_min, Network_Time_t.tm_sec);
        }
        else
        {
               logDebug("Network time resolution failed\r\n");//网络时间解析失败
        }
    }
    else
    {
        logDebug("Network time acquisition failed\r\n");//网络时间获取失败
    }
}

static void Module_Timer(void)
{
    at_attr_t attr;

    at_attr_deinit(&attr);
    attr.cb = Module_Timer_Cb;
    at_send_singlline(ml307r_obj, &attr, "AT+CCLK?");
}


Ts_Network_Service_Info_t Service_Info_t = {0};

static void Module_NetWork_Info_Cb(at_response_t *r)
{
    if (r->code == AT_RESP_OK)
    {
        //"radio",<rat>,<rsrp>,<rssi>,<tx_power>,<tx_time>,<rx_time>,<last_cellid>,<last_ecl>,<last_sinr>,<last_earfcn>,<last_pci>,<rsrq>
        //+MUESTATS: "radio",4,-660,-400,-32768,0,0,0FB5E606,255,280,38950,22,-60）
        char *token = strtok(r->prefix, ",");
        int i = 0;
        while (token != NULL)
        {
            if (i == 0)
            {
                i++;
                token = strtok(NULL, ",");
                continue;
            }
            char hex_str[20] = {0};
            if ((i == 2)||(i == 3)||(i == 4)||(i == 12))
            {
                long int num = strtol((token+1), NULL, 10);
                sprintf(hex_str, "%08X", num);
            }
            else
            {
                if (i != 7)
                {
                    long int num = strtol(token, NULL, 10);
                    if ((i == 2)||(i == 9))
                    {
                        // num = num*10;
                        sprintf(hex_str, "%08X", num);
                    }
                    else
                    {
                        sprintf(hex_str, "%08X", num);
                    }
                }
            }
            switch (i)
            {
                case 1:
                    strcpy(Service_Info_t.rat, hex_str);
                    break;
                case 2:
                    strcpy(Service_Info_t.rsrp, hex_str);
                    break;
                case 3:
                    strcpy(Service_Info_t.rssi, hex_str);
                    break;
                case 4:
                    sprintf(Service_Info_t.tx_power,"%08s", hex_str);

                    break;
                case 5:
                    strcpy(Service_Info_t.tx_time, hex_str);
                    break;
                case 6:
                    strcpy(Service_Info_t.rx_time, hex_str);//rsrp实际值x10上
                    break;
                case 7:
                    strncpy(hex_str, token+1, 8);
                    sprintf(Service_Info_t.last_cellid,"%08s", hex_str);
                    break;
                case 8:
                    strcpy(Service_Info_t.last_ecl, hex_str);//sinr实际值x10上报
                    break;
                case 9:
                    strcpy(Service_Info_t.last_sinr, hex_str);
                    break;
                case 10:
                    strcpy(Service_Info_t.last_earfcn, hex_str);
                    break;
                case 11:
                    strcpy(Service_Info_t.last_pci, hex_str);
                    break;
                case 12:
                    strcpy(Service_Info_t.rsrq, hex_str);
                    break;
                default:
                    break;
            }
            i++;
            token = strtok(NULL, ",");
        }
        //    logDebug("Service_Info_t = %s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s\r\n", Service_Info_t.rat,
        //            Service_Info_t.rsrp,Service_Info_t.rssi,Service_Info_t.tx_power,Service_Info_t.tx_time,
        //            Service_Info_t.rx_time,Service_Info_t.last_cellid,Service_Info_t.last_ecl,Service_Info_t.last_sinr,
        //            Service_Info_t.last_earfcn,Service_Info_t.last_pci,Service_Info_t.rsrq);
        IotFlag_t.ModInfo_success_flag = 1;
    }
    else
    {
        logDebug("AT+MUESTATS=radio command response failed!\r\n");
    }
}

/*
 * @brief 获取连接网络的参数信息
 * @return
 */
static void Module_NetWork_Info(void)
{
    at_attr_t attr;

    at_attr_deinit(&attr);
    attr.prefix = "+MUESTATS: ";
    attr.cb = Module_NetWork_Info_Cb;
    at_send_singlline(ml307r_obj, &attr, "AT+MUESTATS=\"radio\"");
}


static void BSP_Get_Module_Info(void)
{
    at_send_data(ml307r_obj, NULL, "+++", 3);               // 退出透传模式
    Module_Get_Imei();
    Module_Get_Imsi();
    Module_Get_Iccid();
    Module_Timer();
    Module_NetWork_Info();                                  // 获取网络连接信息
    // at_send_singlline(ml307r_obj, NULL, "AT+MIPMODE=0,1");  // 进入透传模式
}


/*
 * @brief 创建设备
 * @return 
 */
static int BSP_Module_Connect_CtWing_Handle(at_env_t *e)
{
    switch (e->state)
    {
        case 0:
            logDebug("create device...\r\n");  
            e->println(e, "AT+MIPOPEN=0,\"TCP\",\"112.125.89.8\",44679,,1");  // 8.135.10.183,32994
            e->reset_timer(e);
            e->state++;
            break;
        case 1:
            if (e->contains(e, "CONNECT"))
            {
                IotFlag_t.Connect_success_flag = 1; 
                logDebug("create device complete\r\n");
                e->finish(e, AT_RESP_OK);
            }
            else if (e->is_timeout(e, 5000))
            {
                e->state--;
                if (++e->i > 3)
                {
                    logDebug("create device error\r\n");
                    IotFlag_t.Connect_error_flag = 1; 
                    e->finish(e, AT_RESP_ERROR);
                }
            }
            break;
        default:
            break;
    }
    return 0;
}
//连接服务器
static void BSP_Module_Connect_CtWing(void)
{
    at_do_work(ml307r_obj, NULL, BSP_Module_Connect_CtWing_Handle);//创建设备
}


//向服务器发送数据
void BSP_Module_Send_Data(uint8_t* data, uint8_t len)
{
    at_attr_t attr;
    at_send_data(ml307r_obj, &attr, data, len);
}

// 设备状态枚举
typedef enum {
    DEVICE_STATUS_NORMAL = 0,  // 正常状态
    DEVICE_STATUS_CLOSED,      // 关闭状态
    DEVICE_STATUS_FAULT,       // 故障状态
    DEVICE_STATUS_LOW_BATTERY  // 低电量状态
} device_status_t;

// 创建基础JSON对象
static cJSON* Create_Base_Json(void)
{
    cJSON *root = cJSON_CreateObject();
    if (root == NULL) {
        logDebug("创建JSON对象失败\r\n");
        return NULL;
    }

    // 创建设备信息对象
    cJSON *device = cJSON_CreateObject();
    if (device == NULL) {
        cJSON_Delete(root);
        return NULL;
    }
    
    // 添加设备基本信息
    cJSON_AddStringToObject(device, "id", "SCV001");
    
    // 获取当前时间
    char time_str[20];
    sprintf(time_str, "%04d-%02d-%02d %02d:%02d:%02d", 
            Network_Time_t.tm_year, Network_Time_t.tm_mon, Network_Time_t.tm_mday,
            Network_Time_t.tm_hour, Network_Time_t.tm_min, Network_Time_t.tm_sec);
    cJSON_AddStringToObject(device, "time", time_str);
    
    // 将设备信息添加到根对象
    cJSON_AddItemToObject(root, "device", device);
    
    // 添加标准信息
    cJSON *standards = cJSON_CreateObject();
    if (standards) {
        char iot_id[32];
        sprintf(iot_id, "IoT-SCV-%s", Module_Info_t.imei);
        cJSON_AddStringToObject(standards, "iotId", iot_id);
        cJSON_AddItemToObject(root, "standards", standards);
    }
    
    return root;
}

// 添加网络信息到JSON对象
static void Add_Network_Info(cJSON *root)
{
    if (root == NULL) return;
    
    cJSON *network = cJSON_CreateObject();
    if (network == NULL) return;
    
    // 解析信号强度，这里简单处理为0-5的整数值
    int signal_strength = 0;
    long rssi = strtol(Service_Info_t.rssi, NULL, 16);
    if (rssi > -90) signal_strength = 5;
    else if (rssi > -100) signal_strength = 4;
    else if (rssi > -110) signal_strength = 3;
    else if (rssi > -120) signal_strength = 2;
    else if (rssi > -130) signal_strength = 1;
    
    // 解析信噪比
    float sinr = strtol(Service_Info_t.last_sinr, NULL, 16) / 10.0f;
    
    cJSON_AddNumberToObject(network, "sinr", sinr);
    cJSON_AddNumberToObject(network, "signal", signal_strength);
    cJSON_AddItemToObject(root, "network", network);
}

// 添加常规状态信息到JSON对象
static void Add_Normal_Status(cJSON *root)
{
    if (root == NULL) return;
    
    // 添加状态信息
    cJSON_AddStringToObject(root, "status", "normal");
    
    // 添加监控信息
    cJSON *monitor = cJSON_CreateObject();
    if (monitor) {
        // 这里添加传感器数据，如压力值等
        float pressure = 0.75; // 示例值，应从传感器获取
        cJSON_AddNumberToObject(monitor, "pressure", pressure);
        cJSON_AddBoolToObject(monitor, "lowVoltage", false);
        cJSON_AddItemToObject(root, "monitor", monitor);
    }
}

// 添加关闭状态信息到JSON对象
static void Add_Closed_Status(cJSON *root)
{
    if (root == NULL) return;
    
    // 添加状态信息
    cJSON_AddStringToObject(root, "status", "closed");
    
    // 添加监控信息
    cJSON *monitor = cJSON_CreateObject();
    if (monitor) {
        float pressure = 0.0; // 阀门关闭时压力为0
        cJSON_AddNumberToObject(monitor, "pressure", pressure);
        cJSON_AddBoolToObject(monitor, "lowVoltage", false);
        cJSON_AddItemToObject(root, "monitor", monitor);
    }
}

// 添加故障状态信息到JSON对象
static void Add_Fault_Status(cJSON *root)
{
    if (root == NULL) return;
    
    // 添加状态信息
    cJSON_AddStringToObject(root, "status", "fault");
    
    // 添加故障信息
    cJSON *fault = cJSON_CreateObject();
    if (fault) {
        cJSON_AddBoolToObject(fault, "lowBattery", false);
        cJSON_AddNumberToObject(fault, "code", 1); // 故障代码
        cJSON_AddItemToObject(root, "fault", fault);
    }
    
    // 添加监控信息
    cJSON *monitor = cJSON_CreateObject();
    if (monitor) {
        float pressure = 0.8; // 示例值
        cJSON_AddNumberToObject(monitor, "pressure", pressure);
        cJSON_AddBoolToObject(monitor, "lowVoltage", false);
        cJSON_AddItemToObject(root, "monitor", monitor);
    }
}

// 添加低电量状态信息到JSON对象
static void Add_Low_Battery_Status(cJSON *root)
{
    if (root == NULL) return;
    
    // 添加状态信息
    cJSON_AddStringToObject(root, "status", "warning");
    
    // 添加故障信息
    cJSON *fault = cJSON_CreateObject();
    if (fault) {
        cJSON_AddBoolToObject(fault, "lowBattery", true);
        cJSON_AddNumberToObject(fault, "code", 2); // 低电量代码
        cJSON_AddItemToObject(root, "fault", fault);
    }
    
    // 添加监控信息
    cJSON *monitor = cJSON_CreateObject();
    if (monitor) {
        float pressure = 0.78; // 示例值
        cJSON_AddNumberToObject(monitor, "pressure", pressure);
        cJSON_AddBoolToObject(monitor, "lowVoltage", true);
        cJSON_AddItemToObject(root, "monitor", monitor);
    }
}

// 根据设备状态构建JSON数据
static char* Build_Status_Json(device_status_t status)
{
    // 创建基础JSON结构
    cJSON *root = Create_Base_Json();
    if (root == NULL) {
        return NULL;
    }
    
    // 根据状态添加不同的信息
    switch (status) {
        case DEVICE_STATUS_NORMAL:
            Add_Normal_Status(root);
            break;
        case DEVICE_STATUS_CLOSED:
            Add_Closed_Status(root);
            break;
        case DEVICE_STATUS_FAULT:
            Add_Fault_Status(root);
            break;
        case DEVICE_STATUS_LOW_BATTERY:
            Add_Low_Battery_Status(root);
            break;
        default:
            Add_Normal_Status(root);
            break;
    }
    
    // 添加网络信息
    Add_Network_Info(root);
    
    // 将JSON转换为字符串
    char *json_string = cJSON_PrintUnformatted(root);
    
    // 释放JSON对象
    cJSON_Delete(root);
    
    return json_string;
}

char *json_data;

static int SendMessage(at_env_t *e)
{
    switch (e->state)
    {
        case 0:
            logDebug("SendMessage start!\r\n");
            e->println(e, "AT+MIPSEND=0,%d,\"%s\"",strlen(json_data),json_data);
            e->reset_timer(e);
            e->state++;
            break;
        case 1:
            if (e->contains(e, "OK"))
            {
                logDebug("SendMessage end!\r\n");
                IotFlag_t.send_complete_flag = 1;
                e->finish(e, AT_RESP_OK);
            }
            if (e->is_timeout(e, 5000))
            {
                e->state--;
                if (++e->i > 3)
                {
                    logDebug("SendMessage error!\r\n");
                    IotFlag_t.send_complete_flag = 1;
                    e->finish(e, AT_RESP_ERROR);
                }
            }
            break;
    }
    return 0;
}

static void BSP_SendMessage(void)
{
    at_do_work(ml307r_obj, NULL, SendMessage);
}


void BSP_ML307_SendMessage(void)
{
    // 根据系统状态确定设备状态
    device_status_t device_status;
    
    // // 这里根据实际系统状态判断逻辑进行修改
    // if (fault_state) {
    //     device_status = DEVICE_STATUS_FAULT;
    // } else {
    //     // 检查其他状态，例如电池电量等
    //     // 这里可以添加更多状态检测逻辑
    //     device_status = DEVICE_STATUS_NORMAL;
    // }


    if(IotFlag_t.Valve_Close_flag)
    {
        IotFlag_t.Valve_Close_flag = 0;
        device_status = DEVICE_STATUS_CLOSED;
    }
    
    
    // 构建JSON数据
    json_data = Build_Status_Json(device_status);
    
    if (json_data != NULL) {
        logDebug("json_data len %d\r\n",strlen(json_data));
        BSP_SendMessage();
    } else {
        logDebug("Build_Status_Json error!\n");
        IotFlag_t.send_error_flag = 1;
    }
}

static int Ml307_Power_On(at_env_t *e)
{
    switch (e->state)
    {
        case 0:
            logDebug("Ml307_Power_On start!\r\n");
            GPIOB_SetBits(ML307_PWR_PIN);
            e->reset_timer(e);
            e->state++;
            break;
        case 1:
            #define ML307_POWER_ON_TIME 3
            if (e->is_timeout(e, ML307_POWER_ON_TIME *1000))
            {
                logDebug("Ml307_Power_On end!\r\n");
                GPIOB_ResetBits(ML307_PWR_PIN);
                IotFlag_t.PowerOn_success_flag = 1;
                e->finish(e, AT_RESP_OK);
            }
            break;
    }
    return 0;
}

static void BSP_Ml307_Power_On(void)
{
    at_do_work(ml307r_obj, NULL, Ml307_Power_On);
}


static int Ml307_Power_Off(at_env_t *e)
{
    switch (e->state)
    {
        case 0:
            logDebug("Ml307_Power_Off start!\r\n");
            GPIOB_SetBits(ML307_PWR_PIN);
            e->reset_timer(e);
            e->state++;
            break;
        case 1:
            #define M307_POWER_OFF_TIME 4
            if (e->is_timeout(e, M307_POWER_OFF_TIME * 1000))
            {
                GPIOB_ResetBits(ML307_PWR_PIN);
                logDebug("Ml307_Power_Off end!\r\n");
                e->reset_timer(e);
                e->state++;
           }
            break;
        case 2:
            if (e->is_timeout(e, 1000))
            {
                e->finish(e, AT_RESP_OK);
            }
            break;
    }
    return 0;
}

static void BSP_Ml307_Power_Off(void)
{
    at_do_work(ml307r_obj, NULL, Ml307_Power_Off);
}


static int Module_Restart_Work(at_env_t *e)
{
    switch (e->state)
    {
        case 0:
            logDebug("restart module...\r\n");
            e->println(e, "AT+CFUN=1,1");//重启模块
            e->reset_timer(e);
            e->state++;
            break;
        case 1:
            if (e->contains(e, "OK"))
            {
                 logDebug("restart module complete\r\n");
                 e->reset_timer(e);
                 e->state++;
            }
            if (e->is_timeout(e, 5000))
            {
                e->state--;
                if (++e->i > 3)
                {
                    IotFlag_t.restart_error_flag = 1;
                    logDebug("Module restart error\r\n");
                    e->finish(e, AT_RESP_ERROR);
                }
           }
            break;
        case 2:
            logDebug("Check if the Module is ready\r\n");
            e->println(e, "AT");
            e->reset_timer(e);
            e->state++;
            break;
        case 3:
            if (e->contains(e, "OK"))
            {
                IotFlag_t.restart_success_flag = 1;
                e->recvclr(e);
                e->finish(e, AT_RESP_OK);
                logDebug("Module is ready\r\n");
            }
            if (e->is_timeout(e, 5000))
            {
                e->state--;
                if (++e->i > 3)
                {
                    IotFlag_t.restart_error_flag = 1;
                    logDebug("Module  error\r\n");
                    e->finish(e, AT_RESP_ERROR);
                }
            }
            break;
        }
    return 0;
}
//重启模块
static void BSP_Restart_Module(void)
{
    at_do_work(ml307r_obj, NULL, Module_Restart_Work);//重启后生效
}



static int simcom_init(at_env_t *e)
{
    switch (e->state)
    {
        case 0:
            logDebug("simcom_cpin!\r\n");
            e->println(e, "AT+CPIN?");
            e->reset_timer(e);
            e->state++;
            break;
        case 1:
            if (e->contains(e, "+CPIN: READY"))
            {
                IotFlag_t.sim_success_flag = 1;
                logDebug("simcom CPIN READY!\r\n");
                e->finish(e, AT_RESP_OK);
            }
            if (e->is_timeout(e, 5000))
            {
                e->state--;
                if (++e->i > 3)
                {
                    IotFlag_t.sim_error_flag = 1;
                    logDebug("simcom CPIN NO READY!\r\n");
                    e->finish(e, AT_RESP_ERROR);
                }
            }
            break;
    }
    return 0;
}
//CPIN
static void BSP_simcom_init(void)
{
    at_do_work(ml307r_obj, NULL, simcom_init);
}


static void BSP_Iot_Loop(void)
{
    switch (state)
    {
        case 0:                                  //开机
            if(IotFlag_t.module_init_flag)       //初始化正常
            {
                logDebug("IotFlag_t.module_init_flag %d\r\n",IotFlag_t.module_init_flag);
                IotFlag_t.module_init_flag = 0;
                MultiTimerStart(&Multi_Power_ON_t,POWERON_RETRY_INTERVAL_TIME, Power_ON_t_CallBack, NULL);
                logDebug("BSP_Ml307_Power_On\r\n");
                BSP_Ml307_Power_On();          
            }
            if (IotFlag_t.PowerOn_success_flag)   //开机成功
            {
                logDebug("BSP_Ml307_Power_On!\r\n");
                MultiTimerStop(&Multi_Power_ON_t);
                state++;
            }
            if (IotFlag_t.PowerOn_error_flag)     
            {
                logDebug("PowerOn_error_flag!\r\n");
                state = 6;
            }
            break;
        case 1:                                   //重启
            if(IotFlag_t.PowerOn_success_flag)    //开机正常
            {
                IotFlag_t.PowerOn_success_flag = 0;
                MultiTimerStart(&Multi_Restart_t, RESTART_RETRY_INTERVAL_TIME, Restart_CallBack, NULL);
                BSP_Restart_Module();             
            }
            if (IotFlag_t.restart_success_flag)   //重启成功
            {
                logDebug("restart_success_flag!\r\n");
                MultiTimerStop(&Multi_Restart_t);
                state++;
            }
            if(IotFlag_t.restart_error_flag == 1)  
            {
                MultiTimerStop(&Multi_Restart_t);
                IotFlag_t.restart_error_flag = 0;
                state = 6;
            }
            break;
        case 2:                                  //sim状态
            if(IotFlag_t.restart_success_flag)   //重启成功
            {
                IotFlag_t.restart_success_flag = 0;
                MultiTimerStart(&Multi_Cpin_t, CPIN_RETRY_INTERVAL_TIME, Cpin_CallBack, NULL);
                BSP_simcom_init();               
            }
            if (IotFlag_t.sim_success_flag)       //sim成功
            {
                logDebug("BSP_Get_Module_Info!!!\r\n");
                MultiTimerStop(&Multi_Cpin_t);
                state++;
            }
            if(IotFlag_t.sim_error_flag == 1)  
            {
                logDebug("BSP_simcom_init Error !\r\n");
                MultiTimerStop(&Multi_Cpin_t);
                IotFlag_t.sim_error_flag = 0;
                state = 6;
            }
            break;
        case 3:                                  //连接
            if(IotFlag_t.sim_success_flag)       //sim正常
            {
                IotFlag_t.sim_success_flag = 0;
                MultiTimerStart(&Multi_Connect_t, CONNECT_RETRY_INTERVAL_TIME, Connect_CallBack, NULL);
                BSP_Module_Connect_CtWing();     
            }
            if (IotFlag_t.Connect_success_flag)   //连接成功
            {
                logDebug("Connect_success_flag!\r\n");
                MultiTimerStop(&Multi_Connect_t);
                state++;
            }
            if(IotFlag_t.Connect_error_flag == 1)  
            {
                logDebug("Connect_error_flag!\r\n");
                IotFlag_t.Connect_error_flag = 0;
                MultiTimerStop(&Multi_Connect_t);
                state = 6;
            }
            break;
        case 4:                                  //sim info
            if(IotFlag_t.Connect_success_flag)   //连接正常
            {
                IotFlag_t.Connect_success_flag = 0;
                MultiTimerStart(&Multi_GetInfo_t, GETINFO_INTERVAL_TIME, GetInfo_CallBack, NULL);
                BSP_Get_Module_Info();           
            }
            if (IotFlag_t.ModInfo_success_flag)   //get success
            {
                logDebug("ModInfo_success_flag!\r\n");
                MultiTimerStop(&Multi_GetInfo_t);
                state++;
            }
            if(IotFlag_t.ModInfo_error_flag == 1)  
            {
                logDebug("ModInfo_error_flag!\r\n");
                MultiTimerStop(&Multi_GetInfo_t);
                IotFlag_t.ModInfo_error_flag = 0;
                state = 6;
            }
            break;
        case 5:                                  //发送数据
            if(IotFlag_t.ModInfo_success_flag)   //连接正常
            {
                IotFlag_t.ModInfo_success_flag = 0;
                MultiTimerStart(&Multi_Send_t, SEND_RETRY_INTERVAL_TIME, Send_CallBack, NULL);
                BSP_ML307_SendMessage();           
            }
            if (IotFlag_t.send_complete_flag)      //发送成功
            {
                logDebug("send_complete_flag!\r\n");
                MultiTimerStop(&Multi_Send_t);
                state++;
            }
            if(IotFlag_t.send_error_flag == 1)  
            {
                logDebug("send_error_flag!\r\n");
                MultiTimerStop(&Multi_Send_t);
                IotFlag_t.send_error_flag = 0;
                state = 6;
            }
            break;
        case 6:                                  //处理
            if(IotFlag_t.send_complete_flag == 1)
            {
                logDebug("send_complete_into_stop\r\n");
                IotFlag_t.send_complete_flag = 0;
                state = 0;   
                tmos_msg_deallocate((uint8_t *)json_data);
                MultiTimerStart(&Multi_StopTask_t, STOP_TASK_INTERVAL_TIME, StopTask_CallBack, NULL);  //关闭
            }else
            {
                if (IotFlag_t.Loop_count_flag > 2)
                {
                    logDebug("Loop_count_flag_end %d\r\n",IotFlag_t.Loop_count_flag);
                    state = 0;
                    IotFlag_t.Iot_Retry_flag = 0;
                    IotFlag_t.module_init_flag = 0;
                    MultiTimerStart(&Multi_StopTask_t, STOP_TASK_INTERVAL_TIME, StopTask_CallBack, NULL);
                }
                if((IotFlag_t.Iot_Retry_flag == 0)&&(IotFlag_t.Loop_count_flag < 3))
                {
                    logDebug("error_into_loop\r\n");
                    logDebug("Loop_count_flag %d\r\n",IotFlag_t.Loop_count_flag);
                    BSP_Ml307_Power_Off();          //关机
                    MultiTimerStart(&Multi_Loop_t, LOOP_INTERVAL_TIME, Loop_CallBack, NULL);
                    IotFlag_t.Iot_Retry_flag = 1;
                }
            }
            break;
    }
}

void Ml307r_Loop(void)
{
    FEED_IWDG();
    at_obj_process(ml307r_obj);
    BSP_Iot_Loop();
}

__HIGH_CODE
__attribute__((noinline))
uint16_t Ml307r_Handle(uint8_t task_id, uint16_t events)
{
    if (events & ML307_PERIODIC_EVT)
    {
        Ml307r_Loop();
        tmos_start_task(ml307_task_id, ML307_PERIODIC_EVT, MS1_TO_SYSTEM_TIME(5));  //5
        return (events ^ ML307_PERIODIC_EVT);
    }
    return 0;
}

void BSP_Ml307r_Init(void)
{
    if(IotFlag_t.Date_Sending_flag == 0)
    {
        BSP_UART1_Init();
        Ml307r_Gpio_Init();
        ml307r_obj = at_obj_create(&at_adapter);//Create AT communication object
        if(ml307r_obj != NULL) 
        {
            Init_cJSON_With_TMOS();
            at_obj_set_urc(ml307r_obj, urc_table, sizeof(urc_table) / sizeof(urc_table[0]));
            IotFlag_t.module_init_flag = 1;
            IotFlag_t.Date_Sending_flag = 1;
            BSP_BlockSleep();
            ml307_task_id = TMOS_ProcessEventRegister(Ml307r_Handle);
            // tmos_set_event(ml307_task_id, ML307_PERIODIC_EVT);
            tmos_start_task(ml307_task_id, ML307_PERIODIC_EVT, MS1_TO_SYSTEM_TIME(300)); //电流稳定后再启动模组 
        }
    }else
    {
        logDebug("ERROR ,Iot_Send_Data!!!\r\n");
    }
}

void Iot_Send_Data(void)
{
    if(IotFlag_t.Date_Sending_flag == 0)
    {
        logDebug("Iot_Send_Data!!!\r\n");
        BSP_UART1_Init();
        Ml307r_Gpio_Init();
        logDebug("Ml307r_Init_Finish!!!\r\n");
        if(ml307r_obj != NULL) 
        {
            IotFlag_t.Date_Sending_flag = 1;
            IotFlag_t.module_init_flag = 1;
            BSP_BlockSleep();
            ml307_task_id = TMOS_ProcessEventRegister(Ml307r_Handle);
            // tmos_set_event(ml307_task_id, ML307_PERIODIC_EVT);
            tmos_start_task(ml307_task_id, ML307_PERIODIC_EVT, MS1_TO_SYSTEM_TIME(300)); //电流稳定后再启动模组 
        }else
        {
            BSP_Ml307r_Init();
        }
    }else
    {
        logDebug("ERROR ,Iot_Send_Data!!!\r\n");
    }
}
