#include "common.h"
#include "mqtt_verify.h"
#include "mqtt_init.h"
#include "device_identity.h"
#include "mqtt_infor_handle.h"
#include "mylog.h"

struct mosquitto *mosq;


uint16_t AppExit_pin_pwm=0;//判断坦克或者车的退出

//mqtt初始化
int mqtt_init() {

    mosquitto_lib_init();
    // 这里创建mosq可以保留，也可以删除这一行，让创建放到 Mqtt_onnect 里
    mosq = mosquitto_new(NULL, true, NULL);
    if (!mosq) {
        my_zlog_fatal("Failed to create Mosquitto client");
        return -1;
    }
    mosquitto_int_option(mosq, MOSQ_OPT_PROTOCOL_VERSION, MQTT_PROTOCOL_V5);
    return 0;
}

//回调函数
void on_connect(struct mosquitto *mosq, void *obj, int rc) {
    if (rc == 0) {
        my_zlog_debug("Connected to broker");
        mosquitto_subscribe(mosq, NULL, mqtt_topic_app2dev_number(), 0);
        mosquitto_subscribe(mosq, NULL, mqtt_topic_ser2dev_number(), 0);
    } else {
        fprintf(stderr, "Connection failed with code %d\n", rc);
        my_zlog_fatal("Connection failed");
    }
}


//消息回环函数  
void on_message(struct mosquitto *mosq, void *obj, const struct mosquitto_message *message) {

    // 确保消息有效
    if (message->payload && message->payloadlen) { // 将消息内容转换为字符串
        char *payload_str = (char *)malloc(message->payloadlen + 1);
        if (!payload_str) {
            return;
        } 

        memcpy(payload_str, message->payload, message->payloadlen);
        payload_str[message->payloadlen] = '\0';

        // 解析 JSON
        cJSON *json = cJSON_Parse(payload_str);
        if(json != NULL){
            if(device_message_receive(json)==0) my_zlog_debug("进入设备接收mqtt");
        }                     
        
        // 释放 payload 字符串
        free(payload_str); 
        cJSON_Delete(json); 
    }
}

// 返回连接结果，0成功，非0失败
int mqtt_create(struct mosquitto *mosq) { 
    mosquitto_reconnect_delay_set(mosq, 2, 10, true);
    mosquitto_connect_callback_set(mosq, on_connect);
    mosquitto_message_callback_set(mosq, on_message);
    mosquitto_username_pw_set(mosq, USERNAME, PASSWORD);

    int rc = mosquitto_connect(mosq, BROKER_ADDRESS, BROKER_PORT, 60);
    if (rc != MOSQ_ERR_SUCCESS) {
        my_zlog_warn("Failed to connect to broker: %s", mosquitto_strerror(rc));
        // 不销毁 mosq，等待调用者处理重连
        return rc;
    }
    return 0; // 成功
}   

//阻塞型
int mqtt_cycle(struct mosquitto *mosq) {
    // 这个函数会阻塞直到连接断开或错误返回
    int rc = mosquitto_loop_forever(mosq, -1, 1);
    if (rc != MOSQ_ERR_SUCCESS) {
        my_zlog_warn("mqtt loop error: %s", mosquitto_strerror(rc));
        return rc;
    }
}

// int mqtt_cycle(struct mosquitto *mosq) {//非阻塞型
//     int rc;
//     while (1) {
//         rc = mosquitto_loop(mosq, 100, 1);  // 每秒检查一次
//         if (rc != MOSQ_ERR_SUCCESS) {
//             my_zlog_warn("mosquitto loop error: %s,(code: %d)", mosquitto_strerror(rc),rc);
//             return -1;  // 跳出循环，重新连接
//         }
//         Delay_Ms(0, 3);  // 防止空转
//     }
// }

//mqtt清理
void mqtt_clean(struct mosquitto *mosq){
      // 清理
    mosquitto_destroy(mosq);
    mosquitto_lib_cleanup();
    my_zlog_notice("清理成功");
}