#if NET_SIMPLE==1
#include "sys.h"
#include "delay.h"
#include "usart.h"
#include "led.h"
#include "key.h"
#include "lcd.h"
#include "beep.h"
#include "usmart.h"
#include "sram.h"
#include "lan8720.h"
#include "timer.h"
#include "rtc.h"
#include "adc.h"
#include "malloc.h"
#include "lwip/netif.h"
#include "lwip_comm.h"
#include "lwipopts.h"
#include "netif/etharp.h"
#include "lwip/ip_addr.h"
#include "lwip/dns.h"
#include <string.h>

/****************************************************************************************
 *  底层网络部分 100% 复制你【飞快的自动测试版】，保证速度完全一致
 ****************************************************************************************/
#define LWIP_SAFE_POLL()  do { lwip_periodic_handle(); } while(0)

// ==========================
// 重定向标准库 malloc/free
// ==========================
#include <stdlib.h>
void* malloc(size_t size)
{
    return mymalloc(SRAMIN, size);
}

void free(void* p)
{
    myfree(SRAMIN, p);
}

// ==========================
// 安全读取【真实生效IP】
// ==========================
void get_lwip_real_ip(u8 *ip)
{
    if(netif_default == NULL) {
        ip[0]=ip[1]=ip[2]=ip[3]=0;
        return;
    }
    ip[0] = ip4_addr1(&netif_default->ip_addr);
    ip[1] = ip4_addr2(&netif_default->ip_addr);
    ip[2] = ip4_addr3(&netif_default->ip_addr);
    ip[3] = ip4_addr4(&netif_default->ip_addr);
}

void get_lwip_real_gw(u8 *gw)
{
    if(netif_default == NULL) {
        gw[0]=gw[1]=gw[2]=gw[3]=0;
        return;
    }
    gw[0] = ip4_addr1(&netif_default->gw);
    gw[1] = ip4_addr2(&netif_default->gw);
    gw[2] = ip4_addr3(&netif_default->gw);
    gw[3] = ip4_addr4(&netif_default->gw);
}

// ==========================
// 判断 LwIP 网络是否真正就绪
// ==========================
uint8_t lwip_net_is_ready(void)
{
    if(netif_default == NULL) return 0;
    if(!netif_is_up(netif_default)) return 0;
    if(netif_default->ip_addr.addr == 0) return 0;
    return 1;
}

// ==========================
// MQTT SDK
// ==========================
#include "mqtt_client_sdk.h"

// ==========================
// MQTT CONFIG
// ==========================
#define MQTT_BROKER_IP          "192.168.3.10"
#define MQTT_BROKER_PORT        1883
#define MQTT_CLIENT_ID          "STM32F407_DEVICE"
#define MQTT_SUB_TOPIC          "stm32/cmd"
#define MQTT_PUB_TOPIC          "stm32/data"

static MqttSdkClient g_mqtt_client = NULL;

// ==========================
// MQTT MSG CALLBACK
// ==========================
static void mqtt_msg_callback(const MqttSdkMsg* msg)
{
    if(!msg || !msg->topic || !msg->payload) return;
    printf("\r\n[MQTT RX]\r\nTopic: %s\r\nData: %.*s\r\n", msg->topic, (int)msg->payload_len, msg->payload);
}

// ==========================
// MQTT CONN CALLBACK
// ==========================
static void mqtt_conn_callback(const MqttSdkBrokerRespStatus* status)
{
    if(!status) return;
    if(status->resp_type == MQTT_SDK_BROKER_RESP_CONNACK)
    {
        if(status->err_code == MQTT_SDK_OK)
        {
            printf("[MQTT] Connected OK\r\n");
            LED1 = 0;
            xxl_mqtt_sdk_client_subscribe(g_mqtt_client, MQTT_SUB_TOPIC, MQTT_SDK_QOS0, NULL);
        }
    }
}

// ==========================
// MQTT 初始化
// ==========================
static void mqtt_init(void)
{
    MqttSdkClientCfg cfg = {0};
    xxl_mqtt_sdk_global_init();

    cfg.client_id     = MQTT_CLIENT_ID;
    cfg.broker_ip     = MQTT_BROKER_IP;
    cfg.broker_port   = MQTT_BROKER_PORT;
    cfg.clean_start   = true;
    cfg.keep_alive    = 60;
    cfg.mqtt_version  = MQTT_SDK_PROTOCOL_V311;

    g_mqtt_client = xxl_mqtt_sdk_client_create(&cfg, mqtt_msg_callback, mqtt_conn_callback);
    if(g_mqtt_client) printf("[MQTT] Client create OK!\r\n");
}

/**********************************************************/
int main(void)
{
    u8 real_ip[4] = {0};
    u8 real_gw[4] = {0};
    u8 mqtt_started = 0;
    extern u32 lwip_localtime;
    static u32 last_lwip_tick = 0;

    // =============================
    // 底层初始化 100% 和快版本一致
    // =============================
    HAL_Init();
    Stm32_Clock_Init(336,8,2,7);
    delay_init(168);
    uart_init(115200);
    LED_Init();
    BEEP_Init();
    KEY_Init();
    LCD_Init();
    SRAM_Init();
    MY_ADC_Init();
    RTC_Init();
    TIM3_Init(1000-1,83);  // 快版本专用分频

    my_mem_init(SRAMIN);
    my_mem_init(SRAMEX);
    my_mem_init(SRAMCCM);

    printf("\r\n\r\n=============================================\r\n");
    printf(" STM32F407 LwIP + MQTT Example\r\n");
    printf("=============================================\r\n");

    // DHCP 关闭
    lwipdev.dhcpstatus = 0;

    // 静态IP
    lwipdev.ip[0] = 192;
    lwipdev.ip[1] = 168;
    lwipdev.ip[2] = 3;
    lwipdev.ip[3] = 130;

    // 掩码
    lwipdev.netmask[0] = 255;
    lwipdev.netmask[1] = 255;
    lwipdev.netmask[2] = 255;
    lwipdev.netmask[3] = 0;

    // 网关
    lwipdev.gateway[0] = 192;
    lwipdev.gateway[1] = 168;
    lwipdev.gateway[2] = 3;
    lwipdev.gateway[3] = 1;

    // MAC
    lwipdev.mac[0] = 0x00;
    lwipdev.mac[1] = 0x11;
    lwipdev.mac[2] = 0x22;
    lwipdev.mac[3] = 0x33;
    lwipdev.mac[4] = 0x44;
    lwipdev.mac[5] = 0x55;

    // ==========================
    // LwIP 初始化（超快版）
    // ==========================
    while(lwip_comm_init())
    {
        printf("[NET] LwIP Init FAIL, Retry...\r\n");
        delay_ms(50);
        LWIP_SAFE_POLL();
    }
    printf("[NET] LwIP Init OK\r\n");

    // ==========================
    // DNS 初始化（快版专用）
    // ==========================
    {
        ip_addr_t dns_srv;
        IP4_ADDR(&dns_srv, 223, 5, 5, 5);
        dns_setserver(0, &dns_srv);
        IP4_ADDR(&dns_srv, 8, 8, 8, 8);
        dns_setserver(1, &dns_srv);
        printf("[NET] DNS Server OK\r\n");
    }

    // ==========================
    // 等待IP（全速无阻塞）
    // ==========================
    printf("[NET] Waiting for IP ready...\r\n");
    while (!lwip_net_is_ready())
    {
        LWIP_SAFE_POLL();
    }

    get_lwip_real_ip(real_ip);
    get_lwip_real_gw(real_gw);

    printf("\r\n=============================================\r\n");
    printf("[NET] REAL IP     : %d.%d.%d.%d\r\n", real_ip[0],real_ip[1],real_ip[2],real_ip[3]);
    printf("[NET] REAL GW     : %d.%d.%d.%d\r\n", real_gw[0],real_gw[1],real_gw[2],real_gw[3]);
    printf("=============================================\r\n\r\n");

    mqtt_init();

    // ==========================
    // 主循环（10ms 精准调度，和快版完全一样）
    // ==========================
    while(1)
    {
        if(lwip_localtime - last_lwip_tick >= 10)
        {
            last_lwip_tick = lwip_localtime;
            lwip_periodic_handle();
        }

        // MQTT 自动连接
        if(mqtt_started == 0 && lwip_net_is_ready())
        {
            delay_ms(200);
            printf("[MQTT] Connecting...\r\n");
            xxl_mqtt_sdk_client_connect(g_mqtt_client);
            mqtt_started = 1;
        }

        if(g_mqtt_client != NULL)
        {
            xxl_mqtt_sdk_client_loop(g_mqtt_client);
        }

        LED0 = !LED0;
        delay_ms(10);
    }
}

#include <time.h>
static uint32_t g_tick_sec = 0;
time_t time(time_t *t)
{
    static uint32_t last_tick = 0;
    uint32_t now = HAL_GetTick();
    if(now - last_tick >= 1000) { g_tick_sec++; last_tick = now; }
    if(t) *t = g_tick_sec;
    return g_tick_sec;
}

#endif
