/*
 #include <mqtt-latest/dev_pahomqtt.h>
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2022-10-28     theo         the first version
 */

#include <stdlib.h>
#include <string.h>
#include <stdint.h>

#include <paho_mqtt.h>
#include "dev_pahomqtt.h"
#include <modules-latest/aht10-latest/app_aht10.h>
#include <gpio.h>

/* MQTT登录参数 */
#define MQTT_Uri    "tcp://EV1UDHPANW.iotcloud.tencentdevices.com:1883"                           /* MQTT服务器的地址和端口号 */
#define ClientId    "EV1UDHPANWdev"                                                               /* ClientId需要唯一 */
#define UserName    "EV1UDHPANWdev;12010126;9Z6ET;1668808988"                                     /* 用户名 */
#define PassWord    "0911622e91d52bc27ed1d9cb6035d2c5ba536a8c4bc47ab7848858b0f6765f3a;hmacsha256" /* 用户名对应的密码 */

/* MQTT回调函数 */
MQTTClient client; /* 定义一个MQTT客户端结构体 */
static void mqtt_connect_callback(MQTTClient *c);                            /* MQTT 连接事件回调函数 */
static void mqtt_online_callback(MQTTClient *c);                             /* MQTT 上线事件回调函数 */
static void mqtt_online_callback(MQTTClient *c);                             /* MQTT 上线事件回调函数 */
static void mqtt_offline_callback(MQTTClient *c);                            /* MQTT 下线事件回调函数 */
static void mqtt_sub_callback(MQTTClient *c, MessageData *msg_data);         /* 收到订阅的 Topic 的消息时的回调函数 */
static void mqtt_sub_default_callback(MQTTClient *c, MessageData *msg_data); /* 默认的订阅回调函数，如果有订阅的 Topic 没有设置回调函数，则使用该默认回调函数 */

int flag;

/**
 * created & setting MQTT
 */
int mqtt_init(void)
{
    rt_err_t rt_err;

    /* 对MQTT客户端结构体变量进行配置 */
    client.isconnected = 0;
    client.uri = MQTT_Uri;

    /* 配置MQTT的连接参数 */
    MQTTPacket_connectData condata = MQTTPacket_connectData_initializer; /* 初始化 condata 参数 */
    memcpy(&client.condata, &condata, sizeof(condata));
    client.condata.clientID.cstring = ClientId;
    client.condata.keepAliveInterval = 30;
    client.condata.cleansession = 1;
    client.condata.username.cstring = UserName;
    client.condata.password.cstring = PassWord;

    /* 为MQTT申请内存 */
    client.buf_size = client.readbuf_size = 2048;
    client.buf = rt_calloc(1, client.buf_size);
    client.readbuf = rt_calloc(1, client.readbuf_size);
    if (!(client.buf && client.readbuf))
    {
        rt_kprintf("no memory for MQTT client buffer!\r\n");
        goto _exit;
    }

    /* 设置事件回调函数 */
    client.connect_callback = mqtt_connect_callback;
    client.online_callback = mqtt_online_callback;
    client.offline_callback = mqtt_offline_callback;

    /* 设置订阅表和事件回调函数*/
    client.messageHandlers[0].topicFilter = SET_TOPIC;
    client.messageHandlers[0].callback = mqtt_sub_callback;
    client.messageHandlers[0].qos = QOS1;

    /* 设置默认的订阅主题*/
    client.defaultMessageHandler = mqtt_sub_default_callback;

    /* 启动 mqtt client */
    rt_err = paho_mqtt_start(&client);

    if(rt_err == 0)
    {
        /* 启动 AHT10 温湿度检测 */
        rt_thread_delay(3000);
        app_aht10_init();

        if(flag == 1)
        {
            BEEP_ON;
            rt_thread_delay(200);
        }
        else
        {
            BEEP_OFF;
        }
    }

_exit:
    return RT_EOK;
}
//INIT_APP_EXPORT(mqtt_init);

/* MQTT 连接事件回调函数 */
static void mqtt_connect_callback(MQTTClient *c)
{
    rt_kprintf("mqtt connect!\n");
}
/* MQTT 上线事件回调函数 */
static void mqtt_online_callback(MQTTClient *c)
{
    rt_kprintf("mqtt online!\n");
}
/* MQTT 下线事件回调函数 */
static void mqtt_offline_callback(MQTTClient *c)
{
    rt_kprintf("mqtt offline!\n");
}

/* 收到订阅的 Topic 的消息时的回调函数 */
static void mqtt_sub_callback(MQTTClient *c, MessageData *msg_data)
{
    char str[20], str1[20], str2[20], msg_buf[20];

    *((char *) msg_data->message->payload + msg_data->message->payloadlen) = '\0';
//    rt_kprintf("Receive topic: %.*s, message data:\r\n", msg_data->topicName->lenstring.len, msg_data->topicName->lenstring.data);
//    rt_kprintf("%.*s\r\n", msg_data->message->payloadlen, (char *) msg_data->message->payload);

    /* 提取收到订阅的 Topic 消息 */
//    rt_kprintf("%s\r\n", (char *) msg_data->message->payload);

    int len = strlen((char *) msg_data->message->payload);
    strncpy(str, (char *) msg_data->message->payload + len - 3, 3);
//    rt_kprintf("%s\n", str);
    strncpy(str1, str, 1);
//    rt_kprintf("%s\n", str1);
    strncpy(str2, str1, 1);
//    rt_kprintf("BEEP: %s\n", str2);

    rt_kprintf("Software in operation...\n");
    /* 蜂鸣器状态 */
    flag = atoi(str2);

    if(flag == 1)
    {
        BEEP_ON;
        rt_thread_delay(200);
        rt_sprintf(msg_buf, "{\"method\":\"report\",\"clientToken\":\"3\",\"params\":{\"beep\":%d}}", 0);
        paho_mqtt_publish(&client, QOS1, POST_TOPIC, msg_buf);
    }
    else
    {
        BEEP_OFF;
    }
}

/* 默认的订阅回调函数，如果有订阅的 Topic 没有设置回调函数，则使用该默认回调函数 */
static void mqtt_sub_default_callback(MQTTClient *c, MessageData *msg_data)
{
    *((char *) msg_data->message->payload + msg_data->message->payloadlen) = '\0';
    rt_kprintf("Receive topic: %.*s, message data:\r\n", msg_data->topicName->lenstring.len, msg_data->topicName->lenstring.data);
    rt_kprintf("%.*s\r\n", msg_data->message->payloadlen, (char *) msg_data->message->payload);
}

/* 腾讯云mqtt设置参考:
 * https://blog.csdn.net/weixin_45381001/article/details/123221328
 * https://cloud.tencent.com/document/product/634/14630
 * https://cloud.tencent.com/document/product/634/32546
 */




