/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2024-04-18     lijian       the first version
 */
#include <MQTT.h>

MQTT_t MQTT;

char buffer_sn[40] ;
char buffer_sn1[40] ;
char buffer_sn2[40] ;

/**
 * mqtt初始化
 * @return
 */
rt_uint8_t MQTT_init()
{
    char buf[64];

    rt_sprintf(buf, "AT+MCONFIG=\"%s\",\"%s\",\"%s\"\r\n", MQTT.MQTT_CLI_ID, MQTT.MQTT_USERNAME, MQTT.MQTT_PWD);
    //AT_send("AT+MCONFIG=\"RP121380\",\"RP121380\",\"\"\r\n"); //MQTT <client ID> , <username> , <password>
    AT_send(buf);
    rt_thread_mdelay(300);

    rt_sprintf(buf, "AT+MIPSTART=\"%s\",\"%s\"\r\n", MQTT.MQTT_ADDR, MQTT.MQTT_PORT);
//    AT_send("AT+MIPSTART=\"8.130.165.100\",8082\r\n");//MQTT <ip addr> , <port>
    AT_send(buf);
    rt_thread_mdelay(300);

    AT_send("AT+MCONNECT=0,60000\r\n");//MQTT <clean_session> , <keepalive>

    rt_thread_mdelay(3000);


    /*
     * 最大 4100 个字节。字符串类型，须用双引号括住。
        注:消息中内嵌的双引号请用\22 表达；控制字符回车
        \r(0x0D)请用\0D 表达；控制字符换行\n（0x0A）
        请用\0A 表达；控制字符反斜杠\（0x5C）请用\5C
        表达
        如果是 MCU 发消息，需要用\\22，\\0D，
        \\0A，\\5C 来表达，即\需要转义成\\
     *
     */
    //AT_send("AT+MPUB=\"v1/devices/me/telemetry\",0,0,\"{\"IN0\":1}\"\r\n");
//    rt_thread_mdelay(1000);
//    AT_send("AT+MPUB=\"v1/devices/me/telemetry\",0,0,\"{\\22IN0\\22:1}\"\r\n");

   // get_MQTT_flag();

    return RT_EOK;

}

//MQTT发送函数
void MQTT_PUB()
{
    //char buffer[32];
    // rt_sprintf(buffer, "{\\\"IN0:1\\\":%d;\\\"ZQ_ON\\\":%d;\\\"YD_ON\\\":%d;\\\"SUM\\\":%ld}", MQTT.MQTT_ADDR);
   // AT_send("AT+MQTTPUB=%s,0,0,%s\r\n", MQTT_PUBTOPIC, "");
   AT_send("AT+MPUB=\"v1/devices/me/telemetry\",0,0,\"{\\22IN0\\22:1}\"\r\n");
}

/**
 * 心跳函数
 */
void MQTT_Keep_Alive()
{
    AT_send("AT+MPUB=\"v1/devices/me/telemetry\",0,0,\"{\\22IN0\\22:1}\"\r\n");
}

/**
 * 获取MQTT连接状态
 * @return
 */
rt_uint8_t get_MQTT_Status_flag()
{
    set_check_flag(1);
    rt_uint8_t i = 0;
    //MQTTSTATU :<state>   0 离线   1 已经登陆认证过   2 还没认证，需要发送 MCONNECT
    AT_send("AT+MQTTSTATU\r\n");
    while (!get_MQTT_STATUS())
    {
        rt_thread_mdelay(100);
        if (i > 3)
        {
            break;
        }
        i++;
    }

    if (MQTT.log) {
        rt_kprintf("MQTT status:%d\n", get_MQTT_STATUS());
    }

    return get_MQTT_STATUS();
}

void set_mqtt_log(uint8_t log){
    MQTT.log = log;
}

/**
 * MQTT重连
 * @return
 */
void MQTT_RE_init()
{
    AT_send("AT+MDISCONNECT\r\n");
    rt_thread_mdelay(2000);
    AT_send("AT+MCONNECT=0,60000\r\n");
}

/**
 * 发送电平
 * @param key
 */
void MQTT_Send_Key(rt_uint16_t key)
{

    rt_sprintf(buffer_sn1 , "AT+MQTTPUB=\"v1/devices/me/telemetry\",0,0,\"{\"IN\":%04x}\"\r\n" , key);

    AT_send(buffer_sn1);
}

/**
 * 发送modbus
 * @param key
 */
void MQTT_Send_Modbus(rt_uint16_t key)
{

    rt_sprintf(buffer_sn2 , "AT+MQTTPUB=\"v1/devices/me/telemetry\",0,0,\"{\"Modbus\":%d}\"\r\n" , key);

    AT_send(buffer_sn2);
}

/**
 * 发送转速针数
 */
//void MQTT_Send_SpeedNeedle()
//{
//    rt_sprintf(buffer_sn , "AT+MQTTPUB=\"v1/devices/me/telemetry\",0,0,\"{\"Speed\":%d;\"NeedlCount\":%d}\"\r\n" , get_Data_Speed(get_Flag_Speed_IO()) , get_Data_NeedleCount(get_Flag_Needle_IO()));
//    AT_send(buffer_sn);
//}




/**
 * @brief 设置MQTT服务器IP地址
 * @param rt_uint8_t addr MQTT服务器的IP地址值
 * @return none
 */
void set_MQTT_ADDR(char* addr)
{
    for (rt_uint8_t var = 0; var < sizeof(MQTT.MQTT_ADDR); var++)
    {
        MQTT.MQTT_ADDR[var] = addr[var];
    }
}

/**
 * @brief 获取MQTT服务器IP地址
 * @return rt_uint8_t 返回MQTT服务器的IP地址值
 */
char* get_MQTT_ADDR()
{
    return MQTT.MQTT_ADDR;
}

/**
 * @brief 设置MQTT服务器端口
 * @param rt_uint8_t port MQTT服务器的端口号
 * @return none
 */
void set_MQTT_PORT(char* port)
{
    for (rt_uint8_t var = 0; var < sizeof(MQTT.MQTT_PORT); var++)
    {
        MQTT.MQTT_PORT[var] = port[var];
    }
}

/**
 * @brief 获取MQTT服务器端口
 * @return rt_uint8_t 返回MQTT服务器的端口号
 */
char* get_MQTT_PORT()
{
    return MQTT.MQTT_PORT;
}

/**
 * @brief 设置MQTT客户端ID
 * @param rt_uint8_t cli_id MQTT客户端ID值
 * @return none
 */
void set_MQTT_CLI_ID(char* cli_id)
{
    for (rt_uint8_t var = 0; var < sizeof(MQTT.MQTT_CLI_ID); var++)
    {
        MQTT.MQTT_CLI_ID[var] = cli_id[var];
    }
}

/**
 * @brief 获取MQTT客户端ID
 * @return rt_uint8_t 返回MQTT客户端ID值
 */
char* get_MQTT_CLI_ID()
{
    return MQTT.MQTT_CLI_ID;
}

/**
 * @brief 设置MQTT用户名
 * @param rt_uint8_t username MQTT用户名值
 * @return none
 */
void set_MQTT_USERNAME(char* username)
{
    for (rt_uint8_t var = 0; var < sizeof(MQTT.MQTT_USERNAME); var++)
    {
        MQTT.MQTT_USERNAME[var] = username[var];
    }
}

/**
 * @brief 获取MQTT用户名
 * @return rt_uint8_t 返回MQTT用户名值
 */
char* get_MQTT_USERNAME()
{
    return MQTT.MQTT_USERNAME;
}

/**
 * @brief 设置MQTT密码
 * @param rt_uint8_t pwd MQTT密码值
 * @return none
 */
void set_MQTT_PWD(char* PWD)
{
    for (rt_uint8_t var = 0; var < sizeof(MQTT.MQTT_PWD); var++)
    {
        MQTT.MQTT_PWD[var] = PWD[var];
    }
}

/**
 * @brief 获取MQTT密码
 * @return rt_uint8_t 返回MQTT密码值
 */
char* get_MQTT_PWD()
{
    return MQTT.MQTT_PWD;
}

/**
 * @brief 设置MQTT订阅话题
 * @param rt_uint8_t topic MQTT订阅话题值
 * @return none
 */
void set_MQTT_TOPIC(rt_uint8_t topic)
{
    MQTT.MQTT_TOPIC = topic;
}

/**
 * @brief 获取MQTT订阅话题
 * @return rt_uint8_t 返回MQTT订阅话题值
 */
rt_uint8_t get_MQTT_TOPIC()
{
    return MQTT.MQTT_TOPIC;
}

/**
 * @brief 设置MQTT连接状态
 * @param rt_uint8_t status MQTT连接状态值（1已连接，0未连接）
 * @return none
 */
void set_MQTT_STATUS(rt_uint8_t status)
{
    MQTT.MQTT_STATUS = status;
}

/**
 * @brief 获取MQTT连接状态
 * @return rt_uint8_t 返回MQTT连接状态值（1已连接，0未连接）
 */
rt_uint8_t get_MQTT_STATUS()
{
    return MQTT.MQTT_STATUS;
}

/**
 * @brief 设置MQTT配置更新标志位
 * @param rt_uint8_t update_flag MQTT配置更新标志位值（1有更新，0无更新，2无改变）
 * @return none
 */
void set_MQTT_UPDATE_FLAG(rt_uint8_t update_flag)
{
    MQTT.MQTT_UPDATE_FLAG = update_flag;
}

/**
 * @brief 获取MQTT配置更新标志位
 * @return rt_uint8_t 返回MQTT配置更新标志位值（1有更新，0无更新，2无改变）
 */
rt_uint8_t get_MQTT_UPDATE_FLAG()
{
    return MQTT.MQTT_UPDATE_FLAG;
}

/**
 * @brief 设置/获取Key值
 * @param rt_uint8_t key 要设置的Key值
 * @return rt_uint8_t 返回当前的Key值
 */
void set_MQTT_Key(rt_uint8_t key)
{
    MQTT.Key = key;
}

rt_uint8_t get_MQTT_Key()
{
    return MQTT.Key;
}
