/******************************************************************************
 * @file      drv_eg25gminipice.c
 * @brief     drv_eg25gminipice.c drivers
 * @version   V1.0
 * @author    Gary
 * @copyright
 ******************************************************************************/

#include "drv_eg25gminipice.h"

#define UART2_BAUDRATE 115200
#define MAX_RETRY 3

extern char deviceSN[17];

//4G实例化
static uint8_t sim_rec_buf[MAX_RECV_LEN] = {0};
LTE4G_STATIC_INIT(sim_item, 1, 0, 0, 1024,sim_rec_buf);


void drv_sim_push_data(Lte4GItem* item, uint8_t *buf, uint16_t len)
{
    uint16_t i = 0;

    if((item != NULL) && (item->buf_pos + len < item->buf_size))
    {
        for (i = 0; i < len; i++)
        {
            item->buf[item->buf_pos++] = buf[i];
        }
    }
}

void drv_uart2_Init(void) 
{
    RCC->APB1ENR |= RCC_APB1ENR_USART2EN;  // 使能 USART2 时钟
    RCC->AHB1ENR |= RCC_AHB1ENR_GPIOAEN;   // 使能 GPIOA 时钟

    GPIOA->MODER |= (2 << (2 * 2)) | (2 << (3 * 2));  // PA2(TX), PA3(RX) 复用模式
    GPIOA->AFR[0] |= (7 << (2 * 4)) | (7 << (3 * 4)); // 复用 AF7 (USART2)

    USART2->BRR = SystemCoreClock / UART2_BAUDRATE;
    USART2->CR1 = USART_CR1_TE | USART_CR1_RE | USART_CR1_UE;  // 使能串口、发送和接收
}

void drv_uart2_sendbyte(char c) 
{
    while (!(USART2->SR & USART_SR_TXE));  // 等待发送完成
    USART2->DR = c;
}

void drv_uart2_sendString(const char *str) 
{
    while (*str) {
        drv_uart2_sendbyte(*str++);
    }
}

void drv_send_at_cmd(const char *cmd, int delay_ms) 
{
    drv_uart2_sendString(cmd);
    drv_uart2_sendString("\r\n");  // AT 指令以 "\r\n" 结尾
    kit_time_dly_ms(30);
}



void drv_eg25g_init(void) 
{
    drv_send_at_cmd("AT", 500);                   // 1. 测试 AT 指令
    drv_send_at_cmd("AT+CPIN?", 500);             // 2. 查询 SIM 卡状态
    drv_send_at_cmd("AT+COPS=0", 500);            // 3. 让模块自动选择运营商
    drv_send_at_cmd("AT+CEREG?", 1000);           // 4. 查询 4G 注册状态
    // drv_send_at_cmd("AT+CGDCONT=1,\"IP\",\"your_apn\"", 500);  // 5. 设置 APN  如果支持自动识别则不需要设置apn
    drv_send_at_cmd("AT+CGACT=1,1", 1000);        // 6. 激活 PDP（获取 IP）
    drv_send_at_cmd("AT+CGPADDR=1", 500);         // 7. 查询分配的 IP 地址
}

// 发送 AT 指令并等待返回值,可用于此优化初始化函数
int drv_send_at_cmd2(const char *cmd, int delay_ms) 
{
    for (int i = 0; i < MAX_RETRY; i++)  // 失败最多重试 MAX_RETRY 次
    {
		drv_uart2_sendString(cmd);
		drv_uart2_sendString("\r\n");  // AT 指令以 "\r\n" 结尾
		kit_time_dly_ms(30);
        
        if (sim_item.buf_pos > 0 && strstr((const char*)sim_item.buf, "OK"))  // 解析返回值
        {
            return 1;  // 成功
        }
    }
    return 0;  // 失败
}

void drv_eg25g_init2(void) 
{
    if (!drv_send_at_cmd2("AT", 500)) return;                   // 1. 测试 AT 指令
    if (!drv_send_at_cmd2("AT+CPIN?", 500)) return;             // 2. 查询 SIM 卡状态
    if (!drv_send_at_cmd2("AT+COPS=0", 500)) return;            // 3. 让模块自动选择运营商
    if (!drv_send_at_cmd2("AT+CEREG?", 1000)) return;           // 4. 查询 4G 注册状态
    if (!drv_send_at_cmd2("AT+CGDCONT=1,\"IP\",\"your_apn\"", 500)) return;  // 5. 设置 APN
    if (!drv_send_at_cmd2("AT+CGACT=1,1", 1000)) return;        // 6. 激活 PDP（获取 IP）
    if (!drv_send_at_cmd2("AT+CGPADDR=1", 500)) return;         // 7. 查询分配的 IP 地址
}

#define MQTT_BROKER     "47.120.14.45"   // 你的 MQTT 服务器地址
#define MQTT_PORT       3011               // MQTT 端口
#define MQTT_CLIENT_ID  "fc41d_client"       // 客户端 ID
#define MQTT_USER       "user"               // MQTT 用户名
#define MQTT_PASSWORD   "password"           // MQTT 密码
#define MQTT_MESSAGE    "Hello from FC41D!"  // 发送的消息
#define WIFI_TIMEOUT 1000

// 连接 MQTT 服务器
uint8_t drv_mqtt_connect()
{
    //1、设置 MQTT 协议的版本号为 V4
//    snprintf(cmd, sizeof(cmd), "AT+QMTCFG=\"version\",1,4");
//    if (!drv_at_send_cmd(cmd, "OK", WIFI_TIMEOUT))
//    {
//        KIT_PRINTF("Failed to set MQTT server!\r\n");
//        return 1;
//    }
	
	//2、建立 MQTT 客户端与服务器之间的会话连接
		char cmd[100] = {0};
	
    snprintf(cmd, sizeof(cmd), "AT+QMTOPEN=0,\"%s\",%d",MQTT_BROKER,MQTT_PORT);
    if (!drv_at_send_cmd(cmd, "OK", WIFI_TIMEOUT))
    {
//        KIT_PRINTF("Failed to set MQTT server!\r\n");
        return 1;
    }
		
		char mqtt_conn_cmd[52];  // 缓冲区足够存放完整 AT 指令

		snprintf(mqtt_conn_cmd, sizeof(mqtt_conn_cmd), "AT+QMTCONN=0,\"BCU%s\"", deviceSN);

		// 发送命令
		if (!drv_at_send_cmd(mqtt_conn_cmd, "OK", WIFI_TIMEOUT)) 
		{
				// 处理错误
		}

    //2、MQTT 客户端与服务器之间建立 MQTT 连接 AT+QMTCONN=<clientID>,<client_identity>,<username>,<password>
		
		char control_topic[42], read_topic[42], mqtt_sub_cmd[128];
		snprintf(control_topic, sizeof(control_topic), "bluesun/bms/control/%s", deviceSN);
		snprintf(read_topic, sizeof(read_topic), "bluesun/bms/read/%s", deviceSN);

		// 构造 AT+QMTSUB 命令
		snprintf(mqtt_sub_cmd, sizeof(mqtt_sub_cmd), "AT+QMTSUB=0,1,\"%s\",0,\"%s\",0", control_topic, read_topic);

		// 发送 AT+QMTSUB
		if (!drv_at_send_cmd(mqtt_sub_cmd, "OK", WIFI_TIMEOUT)) 
		{
				// 处理错误
		}
//		
//		if (!drv_at_send_cmd("AT+QMTSUB=1,1,\"bluesun/bms/read/11223344\",0,\"bluesun/bms/control/11223344\",0", "OK", WIFI_TIMEOUT))
//    {
////        KIT_PRINTF("Failed to set MQTT client credentials!\r\n");
//    }

//    KIT_PRINTF("MQTT Connection Successful!\r\n");
    return 0;
}

//void drv_mqtt_connect(void) 
//{
////    drv_send_at_cmd("AT+QMTCFG=\"recv/mode\",0,0,1", 500);
//    drv_send_at_cmd("AT+QMTOPEN=0,\"47.120.14.45\",3011", 5000);
//    drv_send_at_cmd("AT+QMTCONN=0,\"clientBCUwifi01\"", 5000);
//		drv_send_at_cmd("AT+QMTSUB=0,1,\"BCU01\",2", 5000);
//}
/*
void drv_mqtt_publish(const char *topic, const char *message) 
{
    char cmd[128];
    sprintf(cmd, "AT+QMTPUB=0,0,0,0,\"%s\",\"%s\"", topic, message);
    drv_send_at_cmd(cmd, 500);
}
*/

/*

int main(void) {
    SystemInit();
    drv_uart2_Init();
		
		
		
		
		
    drv_eg25g_init();
    drv_mqtt_connect();
    
    while (1) 
	{
        drv_mqtt_publish("sensor/data", "{\"temperature\":25.3}");
        for (volatile int i = 0; i < 10000000; i++);  // 发送间隔
    }
}

*/

