/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2022-10-27     theo         the first version
 * 2022-11-11     theo         add the atk-tftlcd show
 */

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

#include "aht10.h"
#include "app_aht10.h"
#include <paho_mqtt.h>
#include <mqtt-latest/dev_pahomqtt.h>
#include <tftlcd-latest/lcd.h>
#include <gpio.h>
#include <sys.h>
#include "cJSON.h"

#define DBG_TAG "app_aht10"
#define DBG_LVL DBG_LOG
#include <rtdbg.h>

/* AHT10 */
extern struct aht10_device *temp_humi_dev;

/* MQTT */
extern MQTTClient client; /* 定义一个MQTT客户端结构体 */

/* 消息队列 */
#define THREAD_STACK_SIZE         1024
#define THREAD_PRIORITY           10
#define THREAD_TIMESLICE          10

static rt_thread_t aht10_thread = RT_NULL; /* 线程控制块 => 类似于身份证号 */
static void aht10_thread_entry(void *parameter);

float humidity = 0, temperature = 0;

int app_aht10_init(void)
{
    rt_err_t rt_err;

    /* 创建温湿度采集线程，名称是 aht10_thread，入口是 aht10_thread_entry */
    aht10_thread = rt_thread_create("aht10_thread",     /* 线程的名称 */
                                    aht10_thread_entry, /* 线程入口函数 */
                                    RT_NULL,            /* 线程入口函数的参数   */
                                    THREAD_STACK_SIZE,  /* 线程栈大小，单位是字节  */
                                    THREAD_PRIORITY,    /* 线程的优先级，数值越小优先级越高 */
                                    THREAD_TIMESLICE);  /* 线程的时间片大小 */

    /* 如果获得线程控制块，启动这个线程 */
    if (aht10_thread != RT_NULL)
        rt_err = rt_thread_startup(aht10_thread);
    else
        rt_kprintf("aht10 thread create failed! \n");

    /* 判断线程是否创建成功 */
    if (rt_err != RT_EOK)
        rt_kprintf("aht10 thread startup error! \n");

    return RT_EOK;
}
//INIT_APP_EXPORT(app_aht10_init);

/* 温湿度采集线程入口函数*/
static void aht10_thread_entry(void *parameter)
{
    rt_uint32_t cnt = 0;

    /* 邮件定义 */
//    char msg_buf[20];

    /* cJSON 处理  */
    cJSON *cjson_message = NULL;
    cJSON *cjson_params = NULL;
    cJSON *cjson_params_temperature_humidity = NULL;
    cJSON *cjson_temp = cJSON_CreateNumber((int)temperature);
    cJSON *cjson_hum = cJSON_CreateNumber((int)humidity);

    /* 生成 JSON 字符串 */
    cjson_params_temperature_humidity = cJSON_CreateObject();
    cJSON_AddItemToObject(cjson_params_temperature_humidity, "temperature_value", cjson_temp);
    cJSON_AddItemToObject(cjson_params_temperature_humidity, "humidity_value", cjson_hum);

    cjson_params = cJSON_CreateObject();
    cJSON_AddItemToObject(cjson_params, "params", cjson_params_temperature_humidity);

    cjson_message = cJSON_CreateObject();
    cJSON_AddItemToObject(cjson_message, "method", cJSON_CreateString("report"));
    cJSON_AddItemToObject(cjson_message, "clientToken", cJSON_CreateString("12"));
    cJSON_AddItemToObject(cjson_message, "params", cjson_params_temperature_humidity);

//格式：
//    {
//            "method":       "report",
//            "clientToken":  "12",
//            "params":       {
//                    "temperature_value":    47,
//                    "humidity_value":       23
//            }
//    }
//https://blog.csdn.net/qq_27508477/article/details/107323765?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522166985467716800192266802%2522%252C%2522scm%2522%253A%252220140713.130102334..%2522%257D&request_id=166985467716800192266802&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~baidu_landing_v2~default-1-107323765-null-null.142^v67^wechat_v2,201^v3^add_ask,213^v2^t3_esquery_v2&utm_term=rtt%20cJSON&spm=1018.2226.3001.4187


#ifdef AHT10_ATK_LCD_SHOW
    u32 humidity_show_1, humidity_show_2;
    uint8_t *temperature_show_1, temperature_show_2;

    LCD_Init(); /* 初始化LCD FSMC接口 */
    POINT_COLOR=RED; /* 画笔颜色：红色 */

    LCD_ShowString(20, 240, 210, 24, 24, "humidity   : ");
    LCD_ShowString(208, 240, 210, 24, 24, ".");
    LCD_ShowString(240, 240, 210, 24, 24, "%");

    LCD_ShowString(20, 300, 210, 24, 24, "temperature: ");
    LCD_ShowString(208, 300, 210, 24, 24, ".");
    LCD_ShowString(240, 300, 210, 24, 24, "C");
#endif

    for(;;)
    {
        /* read humidity 采集湿度 */
        humidity = aht10_read_humidity(temp_humi_dev);
//        rt_kprintf("humidity   : %d.%d %%\n", (int) humidity, (int) (humidity * 10) % 10); /* former is integer and behind is decimal */
#ifdef AHT10_ATK_LCD_SHOW
        humidity_show_1 = (int) humidity;
        humidity_show_2 = (int) (humidity * 10) % 10;
        LCD_ShowNum(184, 240, humidity_show_1, 2, 24);
        LCD_ShowNum(218, 240, humidity_show_2, 1, 24);
#endif

        /* read temperature 采集温度 */
        temperature = aht10_read_temperature(temp_humi_dev);
//        rt_kprintf("temperature: %d.%d C\n", (int) temperature, (int) (temperature * 10) % 10); /* former is integer and behind is decimal */
#ifdef AHT10_ATK_LCD_SHOW
        temperature_show_1 = (int) temperature;
        temperature_show_2 = (int) (temperature * 10) % 10;
        LCD_ShowNum(184, 300, temperature_show_1, 2, 24);
        LCD_ShowNum(218, 300, temperature_show_2, 1, 24);
#endif

        /* send humidity and temperature to tencent cloud */
//        rt_sprintf(msg_buf, "{\"method\":\"report\",\"clientToken\":\"12\",\"params\":{\"humidity_value\":%d,\"temperature_value\":%d}}", (int) humidity, (int) temperature);
//        paho_mqtt_publish(&client, QOS1, POST_TOPIC, msg_buf);

        /* 生成 JSON 字符串 */
        cjson_params_temperature_humidity = cJSON_CreateObject();
        cJSON_AddNumberToObject(cjson_params_temperature_humidity, "temperature_value", cJSON_SetNumberValue(cjson_temp, (int)temperature));
        cJSON_AddNumberToObject(cjson_params_temperature_humidity, "humidity_value", cJSON_SetNumberValue(cjson_hum, (int)humidity));

        /* 打印 JSON 字符 */
//        LOG_D(cJSON_Print(cjson_message));
        char *msg = cJSON_PrintUnformatted(cjson_message); /* 这个函数内部会申请空间，用完需要释放 */
        if ((msg != NULL) && paho_mqtt_publish(&client, QOS1, POST_TOPIC, msg) == 0)
        {
            rt_kprintf("message: %s\t%d\r\n", msg, cnt++);
//            rt_kprintf("temperature: %d humidity: %d\n", (int) temperature, (int) humidity);
            cJSON_free(msg); /* 释放 print 申请的空间 */
            cJSON_Delete(cjson_params_temperature_humidity); /* 释放内存 */
        }

        LED1_ON;
        rt_thread_delay(500);
        LED1_OFF;
    }
}

/* 参考：
 * https://blog.csdn.net/qq_38113006/article/details/105349975?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522166687812816782388080836%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fall.%2522%257D&request_id=166687812816782388080836&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~first_rank_ecpm_v1~rank_v31_ecpm-7-105349975-null-null.142
 * https://zhuanlan.zhihu.com/p/377252749
 * https://www.rt-thread.org/document/site/#/rt-thread-version/rt-thread-standard/programming-manual/device/i2c/i2c?id=i2c-%e6%80%bb%e7%ba%bf%e8%ae%be%e5%a4%87%e4%bd%bf%e7%94%a8%e7%a4%ba%e4%be%8b
 */
