/***************************************************************************
 * File Name: trans.c
 * Description: 传输层核心逻辑实现（全平台端口重试版）
 *              支持跨平台（Windows/STM32/RISCV），实现UDP数据传输与分片重组
 *              新增：全平台统一端口重试机制，解决端口冲突问题
 * Author: ZXY
 * Team: 西安芯祥联科技
 * Date Created: 2024-09-17
 * Version: 3.8（全平台端口重试支持）
 * Platform: 多平台兼容
 ***************************************************************************/

#include "trans.h"
#include "type.h"
#include "agent_log.h"  // 引入日志模块
#include <string.h>
#include <stdio.h>
#include "snmp_agent_cfg.h"


// 解决Windows Socket API过时警告
#define _WINSOCK_DEPRECATED_NO_WARNINGS

// 多端口重试配置 - 所有平台共用
#define PORT_RETRY_COUNT 6
static const uint16 g_fallback_ports[PORT_RETRY_COUNT] = {161, 1610, 10161, 20161, 30161, 40161};

// -------------------------- 平台头文件与全局变量 --------------------------
// Windows平台配置
#ifdef WIN_AGENT_APP
#pragma comment(lib, "ws2_32.lib")  // 自动链接Winsock2库
#include <winsock2.h>
#include <ws2tcpip.h>

typedef struct {
    SOCKET udp_socket;       // UDP套接字句柄
    HANDLE recv_thread;      // 接收线程句柄
    volatile LONG thread_running; // 线程运行标志
    CRITICAL_SECTION socket_lock; // 套接字操作锁
} WinTransHw;

HANDLE g_recv_thread = NULL;        // 全局接收线程句柄
#endif

// STM32平台配置
#ifdef STM32
#include "lwip/udp.h"
#include "lwip/ip.h"
#include "stm32f4xx_hal.h"
#include "es_stack.h"
#define STM32_ETH_IRQ_PRIORITY 5
#define STM32_ES_IRQ_PRIORITY 5
#endif

// RISC-V平台配置
#ifdef RISCV
#include "riscv_hal.h"
#include "eth_driver.h"
#include "es_driver.h"
#define RISCV_ETH_BASE 0x10000000
#define RISCV_ES_BASE 0x10001000
#endif

// 全局初始化状态
bool8 g_transinit = BOOL8_FALSE;

// -------------------------- 函数声明 --------------------------
static bool8 trans_hw_init(TransCtx* ctx);
static bool8 trans_hw_send(TransCtx* ctx, const uint8* data, uint16 len, 
                          const uint8* dst_ip, uint16 dst_port);
static void trans_queue_init(TransRecvQueue* q);
static bool8 trans_queue_enqueue(TransRecvQueue* q, const uint8* data, uint16 len);
static bool8 trans_queue_dequeue(TransRecvQueue* q, uint8* buf, uint16* len);
static bool8 ip_in_whitelist(const uint8* ip, const uint8 whitelist[][4], uint8 count);
static bool8 ip_str_to_bytes(const char* ip_str, uint8* ip_bytes);
static bool8 trans_hw_reset(TransCtx* ctx);
static bool8 is_port_available(uint16 port, TransType type);
// 新增：通用端口绑定函数，所有平台共用逻辑
static bool8 trans_bind_port(TransCtx* ctx, uint16 port);

// -------------------------- 通用端口操作函数 --------------------------
static bool8 is_port_available(uint16 port, TransType type) {
#ifdef WIN_AGENT_APP
    // 修复：Windows平台端口检测前初始化WSA
    WSADATA wsaData;
    int wsa_ret = WSAStartup(MAKEWORD(2, 2), &wsaData);
    if (wsa_ret != 0) {
        agent_log_error("is_port_available: WSAStartup失败 [错误:%d]", wsa_ret);
        return BOOL8_FALSE;
    }

    SOCKET test_socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    if (test_socket == INVALID_SOCKET) {
        agent_log_error("is_port_available: 创建测试套接字失败");
        WSACleanup();
        return BOOL8_FALSE;
    }
    
    struct sockaddr_in addr;
    memset(&addr, 0, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = INADDR_ANY;
    addr.sin_port = htons(port);
    
    bool8 result = bind(test_socket, (struct sockaddr*)&addr, sizeof(addr)) == 0;
    if (!result) {
        int err = WSAGetLastError();
        if (err == 10048) {
            agent_log_debug("is_port_available: Windows端口%d已被占用", port);
        } else {
            agent_log_warn("is_port_available: Windows端口%d检测失败 [错误:%d]", port, err);
        }
    }
    closesocket(test_socket);
    WSACleanup();  // 清理WSA资源
    return result;
#elif defined(STM32)
    if (type != TRANS_ETH) return BOOL8_TRUE;
    
    struct udp_pcb* test_pcb = udp_new();
    if (!test_pcb) return BOOL8_FALSE;
    
    ip_addr_t local_ip;
    IP4_ADDR(&local_ip, 0, 0, 0, 0);
    err_t err = udp_bind(test_pcb, &local_ip, port);
    udp_remove(test_pcb);
    if (err != ERR_OK) {
        agent_log_debug("is_port_available: STM32端口%d不可用 [错误:%d]", port, err);
    }
    return err == ERR_OK;
#elif defined(RISCV)
    // RISC-V平台端口检测
    if (type == TRANS_ETH) {
        // 保存当前端口
        uint16 current_port = *(volatile uint16*)(RISCV_ETH_BASE + 0x04);
        // 尝试设置测试端口
        bool8 result = eth_set_port(RISCV_ETH_BASE, port);
        // 恢复原端口
        eth_set_port(RISCV_ETH_BASE, current_port);
        return result;
    } else {
        uint16 current_port = *(volatile uint16*)(RISCV_ES_BASE + 0x04);
        bool8 result = es_set_port(RISCV_ES_BASE, port);
        es_set_port(RISCV_ES_BASE, current_port);
        return result;
    }
#else
    // 其他平台默认返回可用
    return BOOL8_TRUE;
#endif
}

static bool8 trans_bind_port(TransCtx* ctx, uint16 port) {
    if (ctx == NULL || port == 0) {
        agent_log_error("trans_bind_port: 无效参数");
        return BOOL8_FALSE;
    }

#ifdef WIN_AGENT_APP
    WinTransHw* hw = (WinTransHw*)ctx->hw.hw_specific;
    if (hw == NULL) return BOOL8_FALSE;

    struct sockaddr_in local_addr;
    memset(&local_addr, 0, sizeof(local_addr));
    local_addr.sin_family = AF_INET;
    local_addr.sin_addr.s_addr = INADDR_ANY;
    local_addr.sin_port = htons(port);

    // 允许端口重用
    int reuse = 1;
    setsockopt(hw->udp_socket, SOL_SOCKET, SO_REUSEADDR, 
              (const char*)&reuse, sizeof(reuse));

    if (bind(hw->udp_socket, (struct sockaddr*)&local_addr, sizeof(local_addr)) == SOCKET_ERROR) {
        agent_log_debug("trans_bind_port: Windows端口%d绑定失败 [错误:%d]", 
                      port, WSAGetLastError());
        return BOOL8_FALSE;
    }

    agent_log_info("trans_bind_port: Windows成功绑定端口%d", port);
    return BOOL8_TRUE;
#elif defined(STM32)
    if (ctx->type == TRANS_ETH && ctx->hw.udp_pcb != NULL) {
        ip_addr_t local_ip;
        IP4_ADDR(&local_ip, ctx->local_ip[0], ctx->local_ip[1], 
                ctx->local_ip[2], ctx->local_ip[3]);
        
        err_t err = udp_bind(ctx->hw.udp_pcb, &local_ip, port);
        if (err != ERR_OK) {
            agent_log_debug("trans_bind_port: STM32端口%d绑定失败 [错误:%d]", port, err);
            return BOOL8_FALSE;
        }
        
        agent_log_info("trans_bind_port: STM32成功绑定端口%d", port);
        return BOOL8_TRUE;
    } else if (ctx->type == TRANS_ES) {
        // ES端口绑定
        bool8 result = (es_bind(ctx->hw.es_handle, port) == ES_OK);
        if (result) {
            agent_log_info("trans_bind_port: STM32 ES成功绑定端口%d", port);
        } else {
            agent_log_debug("trans_bind_port: STM32 ES端口%d绑定失败", port);
        }
        return result;
    }
#elif defined(RISCV)
    if (ctx->type == TRANS_ETH) {
        bool8 result = eth_set_port(ctx->hw.eth_base, port);
        if (result) {
            agent_log_info("trans_bind_port: RISC-V ETH成功绑定端口%d", port);
        } else {
            agent_log_debug("trans_bind_port: RISC-V ETH端口%d绑定失败", port);
        }
        return result;
    } else {
        bool8 result = es_set_port(ctx->hw.es_base, port);
        if (result) {
            agent_log_info("trans_bind_port: RISC-V ES成功绑定端口%d", port);
        } else {
            agent_log_debug("trans_bind_port: RISC-V ES端口%d绑定失败", port);
        }
        return result;
    }
#else
    // 其他平台默认绑定成功
    agent_log_info("trans_bind_port: 未知平台绑定端口%d", port);
    return BOOL8_TRUE;
#endif
}

// -------------------------- IP工具函数 --------------------------
static bool8 ip_str_to_bytes(const char* ip_str, uint8* ip_bytes) {
    if (!ip_str || !ip_bytes) {
        agent_log_error("ip_str_to_bytes: 无效参数");
        return BOOL8_FALSE;
    }
    
    int octets[4];
#ifdef WIN_AGENT_APP
    if (sscanf_s(ip_str, "%d.%d.%d.%d", &octets[0], &octets[1], &octets[2], &octets[3]) != 4) {
        agent_log_error("ip_str_to_bytes: 解析IP失败 - %s", ip_str);
        return BOOL8_FALSE;
    }
#else
    if (sscanf(ip_str, "%d.%d.%d.%d", &octets[0], &octets[1], &octets[2], &octets[3]) != 4) {
        agent_log_error("ip_str_to_bytes: 解析IP失败 - %s", ip_str);
        return BOOL8_FALSE;
    }
#endif
    
    for (int i = 0; i < 4; i++) {
        if (octets[i] < 0 || octets[i] > 255) {
            agent_log_error("ip_str_to_bytes: IP段无效 - %d", octets[i]);
            return BOOL8_FALSE;
        }
        ip_bytes[i] = (uint8)octets[i];
    }
    agent_log_debug("ip_str_to_bytes: 转换成功 - %s", ip_str);
    return BOOL8_TRUE;
}

// -------------------------- 白名单检查实现 --------------------------
static bool8 ip_in_whitelist(const uint8* ip, const uint8 whitelist[][4], uint8 count) {
    if (ip == NULL) {
        agent_log_error("ip_in_whitelist: IP地址为空");
        return BOOL8_FALSE;
    }
    if (count == 0) {
        agent_log_debug("ip_in_whitelist: 白名单为空，允许所有IP");
        return BOOL8_TRUE;
    }
    
    // 允许本地回环地址（127.0.0.1）
    if (ip[0] == 127 && ip[1] == 0 && ip[2] == 0 && ip[3] == 1) {
        agent_log_debug("ip_in_whitelist: 允许回环地址 127.0.0.1");
        return BOOL8_TRUE;
    }
    
    for (uint8 i = 0; i < count; i++) {
        if (memcmp(ip, whitelist[i], 4) == 0) {
            agent_log_debug("ip_in_whitelist: 允许IP %d.%d.%d.%d",
                           ip[0], ip[1], ip[2], ip[3]);
            return BOOL8_TRUE;
        }
    }
    
    agent_log_warn("ip_in_whitelist: 拒绝IP %d.%d.%d.%d（不在白名单）",
                  ip[0], ip[1], ip[2], ip[3]);
    return BOOL8_FALSE;
}

// -------------------------- 平台接收逻辑实现 --------------------------
// Windows接收线程
#ifdef WIN_AGENT_APP
static DWORD WINAPI udp_recv_thread(LPVOID param) {
    TransCtx* ctx = (TransCtx*)param;
    if (ctx == NULL) {
        agent_log_fatal("udp_recv_thread: 无效的上下文参数");
        return 1;
    }
    
    WinTransHw* hw = (WinTransHw*)ctx->hw.hw_specific;
    if (hw == NULL) {
        agent_log_fatal("udp_recv_thread: 硬件句柄为空");
        return 1;
    }
    
    uint8 recv_buf[MAX_MSG_LEN];
    struct sockaddr_in src_addr;
    int src_addr_len = sizeof(src_addr);
    int recv_len;

    agent_log_info("udp_recv_thread: 线程已启动 [端口:%d]", ctx->port);

    while (InterlockedCompareExchange(&hw->thread_running, 0, 0)) {
        recv_len = recvfrom(
            hw->udp_socket,
            (char*)recv_buf,
            MAX_MSG_LEN,
            0,
            (struct sockaddr*)&src_addr,
            &src_addr_len
        );

        if (recv_len > 0 && recv_len <= MAX_MSG_LEN) {
            uint8 src_ip[4];
            memcpy(src_ip, &src_addr.sin_addr.s_addr, 4);
            uint16 src_port = ntohs(src_addr.sin_port);
            
            agent_log_debug("udp_recv_thread: 收到数据 [长度:%d, 来源:%d.%d.%d.%d:%d]",
                          recv_len, src_ip[0], src_ip[1], src_ip[2], src_ip[3], src_port);
            
            if (!ip_in_whitelist(src_ip, ctx->whitelist, ctx->whitelist_count)) {
                continue;
            }
            
            memcpy(ctx->nms_ip, src_ip, 4);
            ctx->nms_port = src_port;
            ctx->nms_addr_valid = BOOL8_TRUE;
            agent_log_debug("udp_recv_thread: 更新NMS地址 %d.%d.%d.%d:%d",
                          src_ip[0], src_ip[1], src_ip[2], src_ip[3], src_port);
            
            trans_eth_irq_handler(ctx, recv_buf, (uint16)recv_len, src_ip, src_port);
        } else if (recv_len == SOCKET_ERROR) {
            int err = WSAGetLastError();
            if (err == WSAECONNRESET) {
                uint8 src_ip[4];
                memcpy(src_ip, &src_addr.sin_addr.s_addr, 4);
                agent_log_debug("udp_recv_thread: 收到ICMP重置 from %d.%d.%d.%d",
                              src_ip[0], src_ip[1], src_ip[2], src_ip[3]);
                continue;
            }
            else if (err == WSAETIMEDOUT) {
                continue;
            }
            else if (err == WSAENOTSOCK) {
                agent_log_error("udp_recv_thread: 套接字无效，尝试重置...");
                if (!trans_hw_reset(ctx)) {
                    agent_log_fatal("udp_recv_thread: 硬件重置失败，退出线程");
                    break;
                }
                continue;
            }
            else if (err == WSAEINTR) {
                continue;
            }
            
            agent_log_error("udp_recv_thread: 套接字错误: %d，退出接收线程", err);
            break;
        }
    }
    
    agent_log_info("udp_recv_thread: 线程已退出");
    return 0;
}
#endif

// STM32 UDP接收回调
#ifdef STM32
static void stm32_udp_recv_cb(void *arg, struct udp_pcb *pcb, struct pbuf *p, 
                             const ip_addr_t *src_ip, u16_t src_port) {
    TransCtx* ctx = (TransCtx*)arg;
    if (ctx == NULL || p == NULL || src_ip == NULL) {
        agent_log_error("stm32_udp_recv_cb: 无效参数");
        if (p != NULL) pbuf_free(p);
        return;
    }

    uint8 data[MAX_MSG_LEN];
    uint16 len = p->tot_len;
    if (len <= MAX_MSG_LEN) {
        pbuf_copy_partial(p, data, len, 0);
        uint8 src_ip4[4];
        memcpy(src_ip4, &src_ip->addr, 4);
        
        agent_log_debug("stm32_udp_recv_cb: 收到数据 [长度:%d, 来源:%d.%d.%d.%d:%d]",
                      len, src_ip4[0], src_ip4[1], src_ip4[2], src_ip4[3], src_port);
        
        if (!ip_in_whitelist(src_ip4, ctx->whitelist, ctx->whitelist_count)) {
            pbuf_free(p);
            return;
        }
        
        memcpy(ctx->nms_ip, src_ip4, 4);
        ctx->nms_port = src_port;
        ctx->nms_addr_valid = BOOL8_TRUE;
        agent_log_debug("stm32_udp_recv_cb: 更新NMS地址 %d.%d.%d.%d:%d",
                      src_ip4[0], src_ip4[1], src_ip4[2], src_ip4[3], src_port);
        
        trans_eth_irq_handler(ctx, data, len, src_ip4, src_port);
    } else {
        agent_log_warn("stm32_udp_recv_cb: 数据过长 [长度:%d > %d]", len, MAX_MSG_LEN);
    }
    pbuf_free(p);
}
#endif

// RISC-V以太网接收中断处理
#ifdef RISCV
static void riscv_eth_irq_handler(void *arg) {
    TransCtx* ctx = (TransCtx*)arg;
    if (ctx == NULL || ctx->type != TRANS_ETH) {
        agent_log_error("riscv_eth_irq_handler: 无效参数");
        return;
    }

    uint32 irq_status = *(volatile uint32*)(ctx->hw.eth_base + 0x0C);
    if (!(irq_status & (1 << 0))) return;

    uint16 len = *(volatile uint16*)(ctx->hw.eth_base + 0x14);
    if (len == 0 || len > MAX_MSG_LEN) {
        agent_log_warn("riscv_eth_irq_handler: 无效长度 %d", len);
        *(volatile uint32*)(ctx->hw.eth_base + 0x0C) = 1 << 0;
        return;
    }

    uint8 data[MAX_MSG_LEN];
    memcpy(data, (void*)(ctx->hw.eth_base + 0x20), len);
    uint8 src_ip[4] = {
        *(volatile uint8*)(ctx->hw.eth_base + 0x18),
        *(volatile uint8*)(ctx->hw.eth_base + 0x19),
        *(volatile uint8*)(ctx->hw.eth_base + 0x1A),
        *(volatile uint8*)(ctx->hw.eth_base + 0x1B)
    };
    uint16 src_port = *(volatile uint16*)(ctx->hw.eth_base + 0x1C);
    
    agent_log_debug("riscv_eth_irq_handler: 收到数据 [长度:%d, 来源:%d.%d.%d.%d:%d]",
                  len, src_ip[0], src_ip[1], src_ip[2], src_ip[3], src_port);
    
    if (!ip_in_whitelist(src_ip, ctx->whitelist, ctx->whitelist_count)) {
        *(volatile uint32*)(ctx->hw.eth_base + 0x0C) = 1 << 0;
        return;
    }
    
    memcpy(ctx->nms_ip, src_ip, 4);
    ctx->nms_port = src_port;
    ctx->nms_addr_valid = BOOL8_TRUE;
    agent_log_debug("riscv_eth_irq_handler: 更新NMS地址 %d.%d.%d.%d:%d",
                  src_ip[0], src_ip[1], src_ip[2], src_ip[3], src_port);
    
    trans_eth_irq_handler(ctx, data, len, src_ip, src_port);
    *(volatile uint32*)(ctx->hw.eth_base + 0x0C) = 1 << 0;
}
#endif

// -------------------------- 队列操作实现 --------------------------
static void trans_queue_init(TransRecvQueue* q) {
    if (q == NULL) {
        agent_log_error("trans_queue_init: 队列指针为空");
        return;
    }
    memset(q, 0, sizeof(TransRecvQueue));
    q->head = q->tail = q->count = 0;
    agent_log_debug("trans_queue_init: 队列初始化完成");
}

// 优化1: 改进队列溢出处理，增加详细日志
static bool8 trans_queue_enqueue(TransRecvQueue* q, const uint8* data, uint16 len) {
    if (q == NULL || data == NULL || len == 0 || len > MAX_MSG_LEN) {
        agent_log_error("trans_queue_enqueue: 无效参数 [len=%d]", len);
        return BOOL8_FALSE;
    }
    
    uint32 primask = platform_irq_save();
    bool8 overflow = BOOL8_FALSE;
    
    if (q->count >= TRANS_QUEUE_DEPTH) {
        q->tail = (q->tail + 1) % TRANS_QUEUE_DEPTH;
        q->count--;
        overflow = BOOL8_TRUE;
        agent_log_warn("trans_queue_enqueue: 队列溢出，丢弃 oldest 消息 [当前深度:%d]", TRANS_QUEUE_DEPTH);
    }
    
    memcpy(q->buf[q->head], data, len);
    q->len[q->head] = len;
    q->head = (q->head + 1) % TRANS_QUEUE_DEPTH;
    q->count++;
    
    platform_irq_restore(primask);
    
    agent_log_debug("trans_queue_enqueue: 入队%s [长度:%d, 队列计数:%d]", 
                  overflow ? "(溢出处理后)" : "成功", len, q->count);
    return BOOL8_TRUE;
}

// 优化点1: 空队列读取不打印错误日志，只返回FALSE
static bool8 trans_queue_dequeue(TransRecvQueue* q, uint8* buf, uint16* len) {
    // 只在参数无效时打印错误
    if (q == NULL || buf == NULL || len == NULL) {
        agent_log_error("trans_queue_dequeue: 无效参数");
        *len = 0;
        return BOOL8_FALSE;
    }
    
    // 空队列时不打印错误，静默返回FALSE
    if (q->count == 0) {
        *len = 0;
        return BOOL8_FALSE;
    }
    
    uint32 primask = platform_irq_save();
    *len = q->len[q->tail];
    memcpy(buf, q->buf[q->tail], *len);
    // 新增：清空出队的缓存，避免残留
    memset(q->buf[q->tail], 0, MAX_MSG_LEN);
    q->len[q->tail] = 0;
    q->tail = (q->tail + 1) % TRANS_QUEUE_DEPTH;
    q->count--;
    platform_irq_restore(primask);
    
    agent_log_debug("trans_queue_dequeue: 出队成功 [长度:%d, 队列计数:%d]", *len, q->count);
    return BOOL8_TRUE;
}

// -------------------------- 硬件重置函数（全平台支持） --------------------------
static bool8 trans_hw_reset(TransCtx* ctx) {
    if (ctx == NULL || ctx->state == TRANS_STATE_UNINIT) {
        agent_log_error("trans_hw_reset: 无效上下文或未初始化");
        return BOOL8_FALSE;
    }

    agent_log_info("trans_hw_reset: 开始硬件重置");
    uint16 original_port = ctx->port;

    // 所有平台通用的重置前清理
    ctx->nms_addr_valid = BOOL8_FALSE;
    memset(ctx->nms_ip, 0, 4);
    ctx->nms_port = 0;
    trans_queue_init(&ctx->recv_q);

#ifdef WIN_AGENT_APP
    WinTransHw* hw = (WinTransHw*)ctx->hw.hw_specific;
    if (ctx->type == TRANS_ETH && hw != NULL) {
        // 停止接收线程
        InterlockedExchange(&hw->thread_running, 0);
        if (hw->recv_thread != NULL) {
            agent_log_debug("trans_hw_reset: 等待接收线程退出");
            WaitForSingleObject(hw->recv_thread, 1000);
            CloseHandle(hw->recv_thread);
            hw->recv_thread = NULL;
        }
        
        // 关闭并重新创建套接字
        EnterCriticalSection(&hw->socket_lock);
        if (hw->udp_socket != INVALID_SOCKET) {
            closesocket(hw->udp_socket);
            hw->udp_socket = INVALID_SOCKET;
        }
        
        hw->udp_socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
        if (hw->udp_socket == INVALID_SOCKET) {
            agent_log_error("trans_hw_reset: 创建套接字失败 [错误:%d]", WSAGetLastError());
            LeaveCriticalSection(&hw->socket_lock);
            return BOOL8_FALSE;
        }
        
        // 端口重试逻辑（所有平台统一模式）
        bool8 bind_success = BOOL8_FALSE;
        // 1. 尝试原始端口
        if (trans_bind_port(ctx, original_port)) {
            bind_success = BOOL8_TRUE;
            ctx->port = original_port;
        } 
        // 2. 尝试备用端口
        else {
            for (int i = 0; i < PORT_RETRY_COUNT; i++) {
                if (g_fallback_ports[i] == original_port) continue;
                if (trans_bind_port(ctx, g_fallback_ports[i])) {
                    ctx->port = g_fallback_ports[i];
                    bind_success = BOOL8_TRUE;
                    break;
                }
            }
        }
        
        if (!bind_success) {
            closesocket(hw->udp_socket);
            hw->udp_socket = INVALID_SOCKET;
            LeaveCriticalSection(&hw->socket_lock);
            agent_log_error("trans_hw_reset: Windows所有端口绑定失败");
            return BOOL8_FALSE;
        }
        
        LeaveCriticalSection(&hw->socket_lock);
        
        // 重启接收线程
        InterlockedExchange(&hw->thread_running, 1);
        hw->recv_thread = CreateThread(NULL, 0, udp_recv_thread, ctx, 0, NULL);
        if (hw->recv_thread == NULL) {
            closesocket(hw->udp_socket);
            hw->udp_socket = INVALID_SOCKET;
            agent_log_error("trans_hw_reset: 创建接收线程失败 [错误:%d]", GetLastError());
            return BOOL8_FALSE;
        }
        
        agent_log_info("trans_hw_reset: Windows重置完成 [新端口:%d]", ctx->port);
        return BOOL8_TRUE;
    }
#elif defined(STM32)
    if (ctx->type == TRANS_ETH && ctx->hw.udp_pcb != NULL) {
        // 保存当前UDP控制块
        struct udp_pcb* old_pcb = ctx->hw.udp_pcb;
        // 创建新的UDP控制块
        ctx->hw.udp_pcb = udp_new();
        if (!ctx->hw.udp_pcb) {
            ctx->hw.udp_pcb = old_pcb;
            agent_log_error("trans_hw_reset: STM32创建UDP控制块失败");
            return BOOL8_FALSE;
        }
        
        // 端口重试逻辑（统一模式）
        bool8 bind_success = BOOL8_FALSE;
        // 1. 尝试原始端口
        if (trans_bind_port(ctx, original_port)) {
            bind_success = BOOL8_TRUE;
            ctx->port = original_port;
        }
        // 2. 尝试备用端口
        else {
            for (int i = 0; i < PORT_RETRY_COUNT; i++) {
                if (g_fallback_ports[i] == original_port) continue;
                if (trans_bind_port(ctx, g_fallback_ports[i])) {
                    ctx->port = g_fallback_ports[i];
                    bind_success = BOOL8_TRUE;
                    break;
                }
            }
        }
        
        if (!bind_success) {
            udp_remove(ctx->hw.udp_pcb);
            ctx->hw.udp_pcb = old_pcb;
            agent_log_error("trans_hw_reset: STM32所有端口绑定失败");
            return BOOL8_FALSE;
        }
        
        // 移除旧控制块
        udp_remove(old_pcb);
        // 重新注册回调
        udp_recv(ctx->hw.udp_pcb, stm32_udp_recv_cb, ctx);
        
        agent_log_info("trans_hw_reset: STM32重置完成 [新端口:%d]", ctx->port);
        return BOOL8_TRUE;
    } else if (ctx->type == TRANS_ES && ctx->hw.es_handle != NULL) {
        // ES端口重试逻辑
        bool8 bind_success = BOOL8_FALSE;
        // 1. 尝试原始端口
        if (trans_bind_port(ctx, original_port)) {
            bind_success = BOOL8_TRUE;
            ctx->port = original_port;
        }
        // 2. 尝试备用端口
        else {
            for (int i = 0; i < PORT_RETRY_COUNT; i++) {
                if (g_fallback_ports[i] == original_port) continue;
                if (trans_bind_port(ctx, g_fallback_ports[i])) {
                    ctx->port = g_fallback_ports[i];
                    bind_success = BOOL8_TRUE;
                    break;
                }
            }
        }
        
        if (!bind_success) {
            agent_log_error("trans_hw_reset: STM32 ES所有端口绑定失败");
            return BOOL8_FALSE;
        }
        
        agent_log_info("trans_hw_reset: STM32 ES重置完成 [新端口:%d]", ctx->port);
        return BOOL8_TRUE;
    }
#elif defined(RISCV)
    if (ctx->type == TRANS_ETH) {
        // 端口重试逻辑
        bool8 bind_success = BOOL8_FALSE;
        // 1. 尝试原始端口
        if (trans_bind_port(ctx, original_port)) {
            bind_success = BOOL8_TRUE;
            ctx->port = original_port;
        }
        // 2. 尝试备用端口
        else {
            for (int i = 0; i < PORT_RETRY_COUNT; i++) {
                if (g_fallback_ports[i] == original_port) continue;
                if (trans_bind_port(ctx, g_fallback_ports[i])) {
                    ctx->port = g_fallback_ports[i];
                    bind_success = BOOL8_TRUE;
                    break;
                }
            }
        }
        
        if (!bind_success) {
            agent_log_error("trans_hw_reset: RISC-V ETH所有端口绑定失败");
            return BOOL8_FALSE;
        }
        
        // 重新使能中断
        eth_enable_irq(ctx->hw.eth_base);
        agent_log_info("trans_hw_reset: RISC-V ETH重置完成 [新端口:%d]", ctx->port);
        return BOOL8_TRUE;
    } else {
        // ES端口重试
        bool8 bind_success = BOOL8_FALSE;
        // 1. 尝试原始端口
        if (trans_bind_port(ctx, original_port)) {
            bind_success = BOOL8_TRUE;
            ctx->port = original_port;
        }
        // 2. 尝试备用端口
        else {
            for (int i = 0; i < PORT_RETRY_COUNT; i++) {
                if (g_fallback_ports[i] == original_port) continue;
                if (trans_bind_port(ctx, g_fallback_ports[i])) {
                    ctx->port = g_fallback_ports[i];
                    bind_success = BOOL8_TRUE;
                    break;
                }
            }
        }
        
        if (!bind_success) {
            agent_log_error("trans_hw_reset: RISC-V ES所有端口绑定失败");
            return BOOL8_FALSE;
        }
        
        agent_log_info("trans_hw_reset: RISC-V ES重置完成 [新端口:%d]", ctx->port);
        return BOOL8_TRUE;
    }
#endif
    
    agent_log_warn("trans_hw_reset: 不支持的硬件类型重置");
    return BOOL8_TRUE;
}

// -------------------------- 平台硬件初始化（全平台端口重试） --------------------------
static bool8 trans_hw_init(TransCtx* ctx) {
    if (ctx == NULL) {
        agent_log_error("trans_hw_init: 上下文为空");
        return BOOL8_FALSE;
    }
    memset(&ctx->hw, 0, sizeof(TransHwHandle));

    // 所有平台统一的端口选择逻辑
    uint16 selected_port = ctx->port;
    
    // 检查初始端口是否可用
    if (!is_port_available(selected_port, ctx->type)) {
        agent_log_warn("trans_hw_init: 端口%d已被占用，尝试备用端口", selected_port);
        
        // 遍历备用端口
        for (int i = 0; i < PORT_RETRY_COUNT; i++) {
            if (is_port_available(g_fallback_ports[i], ctx->type)) {
                selected_port = g_fallback_ports[i];
                agent_log_info("trans_hw_init: 选择备用端口%d", selected_port);
                break;
            }
        }
    }
    
    // 使用选中的端口进行初始化
    ctx->port = selected_port;

#ifdef WIN_AGENT_APP
    WinTransHw* hw = (WinTransHw*)malloc(sizeof(WinTransHw));
    if (hw == NULL) {
        agent_log_fatal("trans_hw_init: 内存分配失败");
        return BOOL8_FALSE;
    }
    memset(hw, 0, sizeof(WinTransHw));
    hw->thread_running = 0;
    InitializeCriticalSection(&hw->socket_lock);
    ctx->hw.hw_specific = hw;

    WSADATA wsaData;
    int ret = WSAStartup(MAKEWORD(2, 2), &wsaData);
    if (ret != 0) {
        agent_log_fatal("trans_hw_init: WSAStartup失败 [错误:%d]", ret);
        free(hw);
        ctx->hw.hw_specific = NULL;
        return BOOL8_FALSE;
    }

    if (ctx->type == TRANS_ETH) {
        EnterCriticalSection(&hw->socket_lock);
        hw->udp_socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
        if (hw->udp_socket == INVALID_SOCKET) {
            agent_log_fatal("trans_hw_init: 创建套接字失败 [错误:%d]", WSAGetLastError());
            WSACleanup();
            DeleteCriticalSection(&hw->socket_lock);
            free(hw);
            ctx->hw.hw_specific = NULL;
            return BOOL8_FALSE;
        }

        // 设置套接字选项
        int reuse = 1;
        setsockopt(hw->udp_socket, SOL_SOCKET, SO_REUSEADDR, 
                  (const char*)&reuse, sizeof(reuse));

        int broadcast = 1;
        setsockopt(hw->udp_socket, SOL_SOCKET, SO_BROADCAST,
                  (const char*)&broadcast, sizeof(broadcast));

        int timeout = 1000;
        setsockopt(hw->udp_socket, SOL_SOCKET, SO_RCVTIMEO,
                  (const char*)&timeout, sizeof(timeout));
        
        // 绑定已选择的端口
        if (!trans_bind_port(ctx, ctx->port)) {
            int err = WSAGetLastError();
            agent_log_fatal("trans_hw_init: 端口绑定失败 [最后错误:%d]", err);
            closesocket(hw->udp_socket);
            WSACleanup();
            DeleteCriticalSection(&hw->socket_lock);
            free(hw);
            ctx->hw.hw_specific = NULL;
            return BOOL8_FALSE;
        }
        LeaveCriticalSection(&hw->socket_lock);
        agent_log_info("trans_hw_init: Windows套接字绑定成功 [端口:%d]", ctx->port);
    } else {
        // 优化点：为Windows平台的TRANS_ES类型提供基础支持框架
        agent_log_info("trans_hw_init: Windows平台对TRANS_ES类型的支持正在开发中");
        // 可以在这里添加Windows平台对TRANS_ES的实现
        DeleteCriticalSection(&hw->socket_lock);
        free(hw);
        ctx->hw.hw_specific = NULL;
        return BOOL8_TRUE; // 临时改为返回成功，避免初始化失败
    }
#elif defined(STM32)
    if (ctx->type == TRANS_ETH) {
        ctx->hw.udp_pcb = udp_new();
        if (ctx->hw.udp_pcb == NULL) {
            agent_log_fatal("trans_hw_init: 创建UDP控制块失败");
            return BOOL8_FALSE;
        }

        // 绑定已选择的端口
        if (!trans_bind_port(ctx, ctx->port)) {
            agent_log_fatal("trans_hw_init: STM32绑定端口失败 [端口:%d]", ctx->port);
            udp_remove(ctx->hw.udp_pcb);
            return BOOL8_FALSE;
        }
        
        udp_recv(ctx->hw.udp_pcb, stm32_udp_recv_cb, ctx);
        agent_log_info("trans_hw_init: STM32 UDP初始化成功 [端口:%d]", ctx->port);

        // 配置中断
        ctx->hw.eth_irq_num = ETH_IRQn;
        HAL_NVIC_SetPriority((IRQn_Type)ctx->hw.eth_irq_num, STM32_ETH_IRQ_PRIORITY, 0);
        HAL_NVIC_EnableIRQ((IRQn_Type)ctx->hw.eth_irq_num);
    } else {
        ctx->hw.es_handle = es_stack_init();
        if (ctx->hw.es_handle == NULL) {
            agent_log_fatal("trans_hw_init: STM32 ES初始化失败");
            return BOOL8_FALSE;
        }
        
        // 绑定已选择的端口
        if (!trans_bind_port(ctx, ctx->port)) {
            agent_log_fatal("trans_hw_init: STM32 ES绑定端口失败 [端口:%d]", ctx->port);
            return BOOL8_FALSE;
        }
        
        agent_log_info("trans_hw_init: STM32 ES初始化成功 [端口:%d]", ctx->port);

        // 配置中断
        ctx->hw.es_irq_num = ES_IRQn;
        HAL_NVIC_SetPriority((IRQn_Type)ctx->hw.es_irq_num, STM32_ES_IRQ_PRIORITY, 0);
        HAL_NVIC_EnableIRQ((IRQn_Type)ctx->hw.es_irq_num);
    }
#elif defined(RISCV)
    if (ctx->type == TRANS_ETH) {
        ctx->hw.eth_base = RISCV_ETH_BASE;
        *(volatile uint32*)(ctx->hw.eth_base + 0x00) = 1 << 0;  // 复位
        while (*(volatile uint32*)(ctx->hw.eth_base + 0x00) & (1 << 0));
        
        // 绑定已选择的端口
        if (!trans_bind_port(ctx, ctx->port)) {
            agent_log_fatal("trans_hw_init: RISCV ETH绑定端口失败 [端口:%d]", ctx->port);
            return BOOL8_FALSE;
        }
        
        // 配置网络参数
        *(volatile uint32*)(ctx->hw.eth_base + 0x24) = 
            (ctx->local_ip[0] << 24) | (ctx->local_ip[1] << 16) | 
            (ctx->local_ip[2] << 8) | ctx->local_ip[3];
            
        *(volatile uint32*)(ctx->hw.eth_base + 0x28) = 
            (ctx->subnet_mask[0] << 24) | (ctx->subnet_mask[1] << 16) | 
            (ctx->subnet_mask[2] << 8) | ctx->subnet_mask[3];
            
        *(volatile uint32*)(ctx->hw.eth_base + 0x2C) = 
            (ctx->gateway[0] << 24) | (ctx->gateway[1] << 16) | 
            (ctx->gateway[2] << 8) | ctx->gateway[3];
            
        *(volatile uint32*)(ctx->hw.eth_base + 0x08) |= 1 << 0;    // 使能接收
        riscv_irq_register(RISCV_ETH_IRQn, riscv_eth_irq_handler, ctx);
        riscv_irq_enable(RISCV_ETH_IRQn);
        agent_log_info("trans_hw_init: RISC-V ETH初始化成功 [端口:%d]", ctx->port);
    } else {
        ctx->hw.es_base = RISCV_ES_BASE;
        *(volatile uint32*)(ctx->hw.es_base + 0x00) = 1 << 0;  // 复位
        while (*(volatile uint32*)(ctx->hw.es_base + 0x00) & (1 << 0));
        
        // 绑定已选择的端口
        if (!trans_bind_port(ctx, ctx->port)) {
            agent_log_fatal("trans_hw_init: RISCV ES绑定端口失败 [端口:%d]", ctx->port);
            return BOOL8_FALSE;
        }
        
        agent_log_info("trans_hw_init: RISC-V ES初始化成功 [端口:%d]", ctx->port);
    }
#else
    agent_log_fatal("trans_hw_init: 不支持的平台");
    return BOOL8_FALSE;
#endif

    agent_log_info("trans_hw_init: 硬件初始化完成");
    return BOOL8_TRUE;
}

// -------------------------- 硬件发送 --------------------------
static bool8 trans_hw_send(TransCtx* ctx, const uint8* data, uint16 len, 
                          const uint8* dst_ip, uint16 dst_port) {
    if (ctx == NULL || data == NULL || len == 0) {
        agent_log_error("trans_hw_send: 无效参数 [len=%d]", len);
        return BOOL8_FALSE;
    }

    agent_log_debug("trans_hw_send: 准备发送数据 [长度:%d, 目标:%d.%d.%d.%d:%d]",
                  len, dst_ip[0], dst_ip[1], dst_ip[2], dst_ip[3], dst_port);

#ifdef WIN_AGENT_APP
    WinTransHw* hw = (WinTransHw*)ctx->hw.hw_specific;
    if (ctx->type == TRANS_ETH && dst_ip != NULL && hw != NULL) {
        struct sockaddr_in dst_addr;
        memset(&dst_addr, 0, sizeof(dst_addr));
        dst_addr.sin_family = AF_INET;
        memcpy(&dst_addr.sin_addr.s_addr, dst_ip, 4);
        dst_addr.sin_port = htons(dst_port);

        EnterCriticalSection(&hw->socket_lock);
        int send_len = sendto(
            hw->udp_socket,
            (const char*)data,
            len,
            0,
            (struct sockaddr*)&dst_addr,
            sizeof(dst_addr)
        );
        LeaveCriticalSection(&hw->socket_lock);
        
        if (send_len == len) {
            agent_log_debug("trans_hw_send: 数据发送成功 [长度:%d]", len);
            return BOOL8_TRUE;
        } else {
            agent_log_error("trans_hw_send: 发送失败 [实际发送:%d, 预期:%d, 错误:%d]",
                          send_len, len, WSAGetLastError());
            return BOOL8_FALSE;
        }
    }
#elif defined(STM32)
    if (ctx->type == TRANS_ETH && dst_ip != NULL && ctx->hw.udp_pcb != NULL) {
        ip_addr_t dst_addr;
        IP4_ADDR(&dst_addr, dst_ip[0], dst_ip[1], dst_ip[2], dst_ip[3]);
        struct pbuf* p = pbuf_alloc(PBUF_TRANSPORT, len, PBUF_RAM);
        if (p == NULL) {
            agent_log_error("trans_hw_send: 分配pbuf失败");
            return BOOL8_FALSE;
        }
        
        memcpy(p->payload, data, len);
        err_t err = udp_sendto(ctx->hw.udp_pcb, p, &dst_addr, dst_port);
        pbuf_free(p);
        
        if (err == ERR_OK) {
            agent_log_debug("trans_hw_send: 数据发送成功 [长度:%d]", len);
            return BOOL8_TRUE;
        } else {
            agent_log_error("trans_hw_send: 发送失败 [错误:%d]", err);
            return BOOL8_FALSE;
        }
    } else if (ctx->type == TRANS_ES && ctx->hw.es_handle != NULL) {
        bool8 result = (es_send(ctx->hw.es_handle, data, len) == ES_OK) ? BOOL8_TRUE : BOOL8_FALSE;
        if (result) {
            agent_log_debug("trans_hw_send: ES数据发送成功 [长度:%d]", len);
        } else {
            agent_log_error("trans_hw_send: ES发送失败");
        }
        return result;
    }
#elif defined(RISCV)
    if (ctx->type == TRANS_ETH) {
        while (!(*(volatile uint32*)(ctx->hw.eth_base + 0x10) & (1 << 1)));
        *(volatile uint32*)(ctx->hw.eth_base + 0x14) = len;
        memcpy((void*)(ctx->hw.eth_base + 0x20), data, len);
        *(volatile uint32*)(ctx->hw.eth_base + 0x18) = 
            (dst_ip[0] << 24) | (dst_ip[1] << 16) | (dst_ip[2] << 8) | dst_ip[3];
        *(volatile uint32*)(ctx->hw.eth_base + 0x1C) = dst_port;
        *(volatile uint32*)(ctx->hw.eth_base + 0x18) |= 1 << 0;
        agent_log_debug("trans_hw_send: RISC-V数据发送成功 [长度:%d]", len);
        return BOOL8_TRUE;
    }
#endif

    agent_log_error("trans_hw_send: 发送失败，不支持的平台或参数");
    return BOOL8_FALSE;
}

// -------------------------- IP配置管理接口 --------------------------
//bool8 trans_load_ip_config(TransCtx* ctx, const char* config_path) {
//    if (!ctx || !config_path) {
//        agent_log_error("trans_load_ip_config: 无效参数");
//        return BOOL8_FALSE;
//    }

//    agent_log_info("trans_load_ip_config: 加载IP配置 [路径:%s]", config_path);

//    FILE* f;
//#ifdef WIN_AGENT_APP
//    errno_t err = fopen_s(&f, config_path, "r");
//    if (err != 0 || f == NULL) {
//        agent_log_error("trans_load_ip_config: 打开文件失败 [错误:%d]", err);
//        return BOOL8_FALSE;
//    }
//#else
//    f = fopen(config_path, "r");
//    if (f == NULL) {
//        agent_log_error("trans_load_ip_config: 打开文件失败 [错误:%d]", errno);
//        return BOOL8_FALSE;
//    }
//#endif

//    char line[128];
//    uint8 temp_ip[4], temp_gw[4], temp_mask[4], temp_nms[4];
//    bool8 use_dhcp = BOOL8_FALSE;
//    IpMode ip_mode = IP_MODE_STATIC;

//    while (fgets(line, sizeof(line), f)) {
//        if (strstr(line, "IP_MODE=")) {
//            if (strstr(line, "DHCP")) {
//                ip_mode = IP_MODE_DHCP;
//                use_dhcp = BOOL8_TRUE;
//                agent_log_debug("trans_load_ip_config: 配置IP模式为DHCP");
//            } else {
//                ip_mode = IP_MODE_STATIC;
//                use_dhcp = BOOL8_FALSE;
//                agent_log_debug("trans_load_ip_config: 配置IP模式为静态");
//            }
//        }
//        else if (strstr(line, "IP_ADDRESS=") && ip_mode == IP_MODE_STATIC) {
//            if (!ip_str_to_bytes(strchr(line, '=') + 1, temp_ip)) {
//                fclose(f);
//                agent_log_error("trans_load_ip_config: 解析IP地址失败");
//                return BOOL8_FALSE;
//            }
//            agent_log_debug("trans_load_ip_config: 配置IP地址 %d.%d.%d.%d",
//                          temp_ip[0], temp_ip[1], temp_ip[2], temp_ip[3]);
//        }
//        else if (strstr(line, "GATEWAY=") && ip_mode == IP_MODE_STATIC) {
//            if (!ip_str_to_bytes(strchr(line, '=') + 1, temp_gw)) {
//                fclose(f);
//                agent_log_error("trans_load_ip_config: 解析网关失败");
//                return BOOL8_FALSE;
//            }
//            agent_log_debug("trans_load_ip_config: 配置网关 %d.%d.%d.%d",
//                          temp_gw[0], temp_gw[1], temp_gw[2], temp_gw[3]);
//        }
//        else if (strstr(line, "SUBNET_MASK=") && ip_mode == IP_MODE_STATIC) {
//            if (!ip_str_to_bytes(strchr(line, '=') + 1, temp_mask)) {
//                fclose(f);
//                agent_log_error("trans_load_ip_config: 解析子网掩码失败");
//                return BOOL8_FALSE;
//            }
//            agent_log_debug("trans_load_ip_config: 配置子网掩码 %d.%d.%d.%d",
//                          temp_mask[0], temp_mask[1], temp_mask[2], temp_mask[3]);
//        }
//        else if (strstr(line, "DEFAULT_NMS_IP=")) {
//            if (!ip_str_to_bytes(strchr(line, '=') + 1, temp_nms)) {
//                fclose(f);
//                agent_log_error("trans_load_ip_config: 解析默认NMS IP失败");
//                return BOOL8_FALSE;
//            }
//            memcpy(ctx->default_nms_ip, temp_nms, 4);
//            agent_log_debug("trans_load_ip_config: 配置默认NMS IP %d.%d.%d.%d",
//                          temp_nms[0], temp_nms[1], temp_nms[2], temp_nms[3]);
//        }
//    }
//    
//    fclose(f);
//    
//    ctx->ip_mode = ip_mode;
//    ctx->use_dhcp = use_dhcp;
//    
//    if (ip_mode == IP_MODE_STATIC) {
//        memcpy(ctx->local_ip, temp_ip, 4);
//        memcpy(ctx->gateway, temp_gw, 4);
//        memcpy(ctx->subnet_mask, temp_mask, 4);
//        agent_log_info("trans_load_ip_config: 静态IP配置加载完成");
//    } else {
//        agent_log_info("trans_load_ip_config: DHCP配置加载完成");
//    }
//    
//    return BOOL8_TRUE;
//}

bool8 trans_auto_config_ip(TransCtx* ctx) {
    if (!ctx) {
        agent_log_error("trans_auto_config_ip: 无效参数");
        return BOOL8_FALSE;
    }

    agent_log_info("trans_auto_config_ip: 开始自动配置IP");

    ctx->ip_mode = IP_MODE_DHCP;
    ctx->use_dhcp = BOOL8_TRUE;

#ifdef STM32
    if (ctx->hw.udp_pcb && dhcp_supplied_address(ctx->hw.udp_pcb)) {
        memcpy(ctx->local_ip, &ctx->hw.udp_pcb->local_ip.addr, 4);
        memcpy(ctx->subnet_mask, &ctx->hw.udp_pcb->netmask.addr, 4);
        memcpy(ctx->gateway, &ctx->hw.udp_pcb->gw.addr, 4);
        agent_log_info("trans_auto_config_ip: STM32 DHCP配置成功 %d.%d.%d.%d",
                      ctx->local_ip[0], ctx->local_ip[1], ctx->local_ip[2], ctx->local_ip[3]);
        return BOOL8_TRUE;
    } else {
        if (dhcp_start(ctx->hw.udp_pcb) == ERR_OK) {
            uint32 timeout = 10000;
            uint32 start = platform_get_tick();
            agent_log_debug("trans_auto_config_ip: 等待DHCP响应...");
            while (timeout > (platform_get_tick() - start)) {
                if (dhcp_supplied_address(ctx->hw.udp_pcb)) {
                    memcpy(ctx->local_ip, &ctx->hw.udp_pcb->local_ip.addr, 4);
                    memcpy(ctx->subnet_mask, &ctx->hw.udp_pcb->netmask.addr, 4);
                    memcpy(ctx->gateway, &ctx->hw.udp_pcb->gw.addr, 4);
                    agent_log_info("trans_auto_config_ip: STM32 DHCP配置成功 %d.%d.%d.%d",
                                  ctx->local_ip[0], ctx->local_ip[1], ctx->local_ip[2], ctx->local_ip[3]);
                    return BOOL8_TRUE;
                }
                platform_delay_ms(100);
            }
            agent_log_warn("trans_auto_config_ip: STM32 DHCP超时");
        } else {
            agent_log_error("trans_auto_config_ip: STM32 DHCP启动失败");
        }
    }
#elif defined(WIN_AGENT_APP)
    WSADATA wsaData;
    if (WSAStartup(MAKEWORD(2, 2), &wsaData) == 0) {
        char hostname[256];
        if (gethostname(hostname, sizeof(hostname)) == 0) {
            struct addrinfo hints = {0};
            struct addrinfo* result;
            hints.ai_family = AF_INET;
            hints.ai_socktype = SOCK_DGRAM;
            
            int status = getaddrinfo(hostname, NULL, &hints, &result);
            if (status == 0 && result != NULL) {
                struct sockaddr_in* ipv4 = (struct sockaddr_in*)result->ai_addr;
                if (ntohl(ipv4->sin_addr.s_addr) != 0x7F000001) {  // 排除回环地址
                    memcpy(ctx->local_ip, &ipv4->sin_addr.s_addr, 4);
                    
                    uint32 mask = 0x00FFFFFF;
                    memcpy(ctx->subnet_mask, &mask, 4);
                    
                    uint32 gateway = ntohl(ipv4->sin_addr.s_addr) & 0xFFFFFF00 | 0x01;
                    gateway = htonl(gateway);
                    memcpy(ctx->gateway, &gateway, 4);
                    
                    freeaddrinfo(result);
                    WSACleanup();
                    agent_log_info("trans_auto_config_ip: Windows IP配置成功 %d.%d.%d.%d",
                                  ctx->local_ip[0], ctx->local_ip[1], ctx->local_ip[2], ctx->local_ip[3]);
                    return BOOL8_TRUE;
                }
                freeaddrinfo(result);
            }
        }
        WSACleanup();
        agent_log_warn("trans_auto_config_ip: Windows IP配置失败");
    } else {
        agent_log_error("trans_auto_config_ip: Windows WSAStartup失败");
    }
#elif defined(LINUX)
    int fd;
    struct ifreq ifr;
    const char* ifname = "eth0";
    fd = socket(AF_INET, SOCK_DGRAM, 0);
    ifr.ifr_addr.sa_family = AF_INET;
    strncpy(ifr.ifr_name, ifname, IFNAMSIZ-1);
    if (ioctl(fd, SIOCGIFADDR, &ifr) == 0) {
        struct sockaddr_in* addr = (struct sockaddr_in*)&ifr.ifr_addr;
        memcpy(ctx->local_ip, &addr->sin_addr.s_addr, 4);
        if (ioctl(fd, SIOCGIFNETMASK, &ifr) == 0) {
            struct sockaddr_in* mask = (struct sockaddr_in*)&ifr.ifr_addr;
            memcpy(ctx->subnet_mask, &mask->sin_addr.s_addr, 4);
            FILE* f = fopen("/proc/net/route", "r");
            if (f) {
                char line[256];
                while (fgets(line, sizeof(line), f)) {
                    char iface[IFNAMSIZ];
                    uint32 dest, gw, flags;
                    if (sscanf(line, "%s %x %x %x", iface, &dest, &gw, &flags) == 4) {
                        if (dest == 0 && strcmp(iface, ifname) == 0) {
                            memcpy(ctx->gateway, &gw, 4);
                            break;
                        }
                    }
                }
                fclose(f);
            }
            close(fd);
            agent_log_info("trans_auto_config_ip: Linux IP配置成功 %d.%d.%d.%d",
                          ctx->local_ip[0], ctx->local_ip[1], ctx->local_ip[2], ctx->local_ip[3]);
            return BOOL8_TRUE;
        }
    }
    close(fd);
    agent_log_warn("trans_auto_config_ip: Linux IP配置失败");
#elif defined(RISCV)
    if (eth_dhcp_get_status(ctx->hw.eth_base) == DHCP_STATUS_SUCCESS) {
        uint32 ip = *(volatile uint32*)(ctx->hw.eth_base + 0x30);
        uint32 mask = *(volatile uint32*)(ctx->hw.eth_base + 0x34);
        uint32 gw = *(volatile uint32*)(ctx->hw.eth_base + 0x38);
        memcpy(ctx->local_ip, &ip, 4);
        memcpy(ctx->subnet_mask, &mask, 4);
        memcpy(ctx->gateway, &gw, 4);
        agent_log_info("trans_auto_config_ip: RISC-V DHCP配置成功 %d.%d.%d.%d",
                      ctx->local_ip[0], ctx->local_ip[1], ctx->local_ip[2], ctx->local_ip[3]);
        return BOOL8_TRUE;
    } else {
        if (eth_dhcp_start(ctx->hw.eth_base) == 0) {
            uint32 timeout = 10000;
            uint32 start = platform_get_tick();
            agent_log_debug("trans_auto_config_ip: 等待DHCP响应...");
            while (timeout > (platform_get_tick() - start)) {
                if (eth_dhcp_get_status(ctx->hw.eth_base) == DHCP_STATUS_SUCCESS) {
                    uint32 ip = *(volatile uint32*)(ctx->hw.eth_base + 0x30);
                    uint32 mask = *(volatile uint32*)(ctx->hw.eth_base + 0x34);
                    uint32 gw = *(volatile uint32*)(ctx->hw.eth_base + 0x38);
                    memcpy(ctx->local_ip, &ip, 4);
                    memcpy(ctx->subnet_mask, &mask, 4);
                    memcpy(ctx->gateway, &gw, 4);
                    agent_log_info("trans_auto_config_ip: RISC-V DHCP配置成功 %d.%d.%d.%d",
                                  ctx->local_ip[0], ctx->local_ip[1], ctx->local_ip[2], ctx->local_ip[3]);
                    return BOOL8_TRUE;
                }
                platform_delay_ms(100);
            }
            agent_log_warn("trans_auto_config_ip: RISC-V DHCP超时");
        } else {
            agent_log_error("trans_auto_config_ip: RISC-V DHCP启动失败");
        }
    }
#endif

    // 自动获取失败，使用默认IP
    uint8 default_ip[] = {192, 168, 1, 100};
    uint8 default_gw[] = {192, 168, 1, 1};
    uint8 default_mask[] = {255, 255, 255, 0};
    memcpy(ctx->local_ip, default_ip, 4);
    memcpy(ctx->gateway, default_gw, 4);
    memcpy(ctx->subnet_mask, default_mask, 4);
    ctx->ip_mode = IP_MODE_STATIC;
    ctx->use_dhcp = BOOL8_FALSE;
    agent_log_warn("trans_auto_config_ip: 自动配置失败，使用默认IP %d.%d.%d.%d",
                  default_ip[0], default_ip[1], default_ip[2], default_ip[3]);
    return BOOL8_TRUE;
}

void trans_set_default_nms_ip(TransCtx* ctx, const uint8* nms_ip) {
    if (ctx && nms_ip) {
        memcpy(ctx->default_nms_ip, nms_ip, 4);
        agent_log_info("trans_set_default_nms_ip: 设置默认NMS IP %d.%d.%d.%d",
                      nms_ip[0], nms_ip[1], nms_ip[2], nms_ip[3]);
    } else {
        agent_log_error("trans_set_default_nms_ip: 无效参数");
    }
}

const uint8* trans_get_nms_ip(TransCtx* ctx) {
    if (ctx) {
        if (ctx->nms_addr_valid) {
            agent_log_debug("trans_get_nms_ip: 获取当前NMS IP %d.%d.%d.%d",
                          ctx->nms_ip[0], ctx->nms_ip[1], ctx->nms_ip[2], ctx->nms_ip[3]);
            return ctx->nms_ip;
        }
        agent_log_debug("trans_get_nms_ip: 获取默认NMS IP %d.%d.%d.%d",
                      ctx->default_nms_ip[0], ctx->default_nms_ip[1], 
                      ctx->default_nms_ip[2], ctx->default_nms_ip[3]);
        return ctx->default_nms_ip;
    }
    agent_log_error("trans_get_nms_ip: 无效参数");
    return NULL;
}

const uint8* trans_get_local_ip(TransCtx* ctx) {
    if (ctx) {
        agent_log_debug("trans_get_local_ip: 获取本地IP %d.%d.%d.%d",
                      ctx->local_ip[0], ctx->local_ip[1], ctx->local_ip[2], ctx->local_ip[3]);
        return ctx->local_ip;
    }
    agent_log_error("trans_get_local_ip: 无效参数");
    return NULL;
}

// -------------------------- 公共接口实现 --------------------------
bool8 trans_init(TransType type, uint16 port, 
                void (*recv_cb)(TransType, const uint8*, uint16), 
                TransCtx* ctx) {
    if (ctx == NULL || type >= TRANS_MAX || port == 0) {
        agent_log_error("trans_init: 无效参数 [type=%d, port=%d]", type, port);
        return BOOL8_FALSE;
    }
    
    memset(ctx, 0, sizeof(TransCtx));
    ctx->type = type;
    ctx->port = port;
    ctx->recv_cb = recv_cb;
    ctx->state = TRANS_STATE_UNINIT;
    ctx->nms_addr_valid = BOOL8_FALSE;
    
    trans_queue_init(&ctx->recv_q);
    ctx->whitelist_count = 0;
    
    agent_log_info("trans_init: 开始传输层初始化 [类型:%d, 端口:%d]", type, port);
    
    if (!trans_hw_init(ctx)) {
        ctx->state = TRANS_STATE_ERROR;
        agent_log_fatal("trans_init: 硬件初始化失败");
        return BOOL8_FALSE;
    }
    
    ctx->state = TRANS_STATE_READY;
    g_transinit = BOOL8_TRUE;
    agent_log_info("trans_init: 传输层初始化完成 [类型:%d, 端口:%d]", type, port);
    return BOOL8_TRUE;
}

bool8 trans_send(TransCtx* ctx, const uint8* data, uint16 len, 
                const uint8* dst_ip, uint16 dst_port) {
    if (ctx == NULL || ctx->state != TRANS_STATE_READY || data == NULL || len == 0 || len > MAX_MSG_LEN) {
        agent_log_error("trans_send: 无效参数 [state=%d, len=%d]", ctx ? ctx->state : -1, len);
        return BOOL8_FALSE;
    }
    
    // 尝试发送
    bool8 send_result = trans_hw_send(ctx, data, len, dst_ip, dst_port);
    
    // 发送失败且是端口相关错误时尝试重置（全平台支持）
    if (!send_result) {
#ifdef WIN_AGENT_APP
        int err = WSAGetLastError();
        if (err == 10048 || err == 10055) { // 端口占用或缓冲区不足
            agent_log_error("trans_send: Windows端口错误，尝试重置 [%d]", err);
            trans_hw_reset(ctx);
            send_result = trans_hw_send(ctx, data, len, dst_ip, dst_port);
        }
#elif defined(STM32)
        // STM32端口错误处理
        agent_log_error("trans_send: STM32发送失败，尝试重置");
        trans_hw_reset(ctx);
        send_result = trans_hw_send(ctx, data, len, dst_ip, dst_port);
#elif defined(RISCV)
        // RISC-V端口错误处理
        agent_log_error("trans_send: RISC-V发送失败，尝试重置");
        trans_hw_reset(ctx);
        send_result = trans_hw_send(ctx, data, len, dst_ip, dst_port);
#endif
    }
    
    return send_result;
}

// 优化点2: 改进状态检查，减少错误日志输出
bool8 trans_recv(TransCtx* ctx, uint8* buf, uint16* len) {
    // 仅在首次检测到错误状态时打印信息，避免重复刷屏
    if (ctx == NULL || buf == NULL || len == NULL) {
        agent_log_error("trans_recv: 无效参数");
        *len = 0;
        return BOOL8_FALSE;
    }
    
    // 状态检查，使用debug级别日志且只在状态变化时打印
    if (ctx->state != TRANS_STATE_READY) {
        static int last_state = -1;
        if (ctx->state != last_state) {
            agent_log_debug("trans_recv: 传输层未就绪 [state=%d]", ctx->state);
            last_state = ctx->state;
        }
        *len = 0;
        return BOOL8_FALSE;
    }
    
    return trans_queue_dequeue(&ctx->recv_q, buf, len);
}

//bool8 trans_reset(TransCtx* ctx) {
//    if (ctx == NULL) {
//        agent_log_error("trans_reset: 无效参数");
//        return BOOL8_FALSE;
//    }
//    
//    agent_log_info("trans_reset: 开始传输层重置");
//    
//    TransType type = ctx->type;
//    uint16 port = ctx->port;
//    void (*recv_cb)(TransType, const uint8*, uint16) = ctx->recv_cb;
//    
//    trans_stop(ctx);
//    bool8 result = trans_init(type, port, recv_cb, ctx);
//    
//    if (result) {
//        agent_log_info("trans_reset: 传输层重置成功");
//    } else {
//        agent_log_error("trans_reset: 传输层重置失败");
//    }
//    return result;
//}

// -------------------------- 兼容旧接口 --------------------------
bool8 trans_cfg_trans(TransType type, uint16 port, TransCtx* ctx) {
//    agent_log_warn("trans_cfg_trans: 已过时，建议使用trans_init");
    return trans_init(type, port, NULL, ctx);
}

bool8 trans_start(TransCtx* ctx) {
    if (ctx == NULL || ctx->state != TRANS_STATE_READY) {
        agent_log_error("trans_start: 无效上下文或状态 [state=%d]", ctx ? ctx->state : -1);
        return BOOL8_FALSE;
    }
    
    agent_log_info("trans_start: 启动传输层 [类型:%d, 端口:%d]", ctx->type, ctx->port);
    
#ifdef STM32
    if (ctx->type == TRANS_ETH) {
        udp_recv(ctx->hw.udp_pcb, stm32_udp_recv_cb, ctx);
        agent_log_info("trans_start: STM32 ETH接收已启动");
    } else {
        es_start_recv(ctx->hw.es_handle);
        agent_log_info("trans_start: STM32 ES接收已启动");
    }
#elif defined(RISCV)
    if (ctx->type == TRANS_ETH) {
        *(volatile uint32*)(ctx->hw.eth_base + 0x08) |= 1 << 0;
        agent_log_info("trans_start: RISC-V ETH接收已启动");
    } else {
        *(volatile uint32*)(ctx->hw.es_base + 0x08) |= 1 << 0;
        agent_log_info("trans_start: RISC-V ES接收已启动");
    }
#elif defined(WIN_AGENT_APP)
    WinTransHw* hw = (WinTransHw*)ctx->hw.hw_specific;
    if (hw != NULL) {
        InterlockedExchange(&hw->thread_running, 1);
        
        if (hw->recv_thread != NULL) {
            agent_log_debug("trans_start: 关闭现有接收线程");
            WaitForSingleObject(hw->recv_thread, 1000);
            CloseHandle(hw->recv_thread);
            hw->recv_thread = NULL;
        }
        
        hw->recv_thread = CreateThread(NULL, 0, udp_recv_thread, ctx, 0, NULL);
        if (hw->recv_thread != NULL) {
            agent_log_info("trans_start: Windows UDP接收线程已启动 [ID:%p]", hw->recv_thread);
            return BOOL8_TRUE;
        } else {
            agent_log_error("trans_start: 创建接收线程失败 [错误:%d]", GetLastError());
            return BOOL8_FALSE;
        }
    }
#endif
    return BOOL8_TRUE;
}

void trans_stop(TransCtx* ctx) {
    if (ctx == NULL || ctx->state == TRANS_STATE_UNINIT) {
        agent_log_warn("trans_stop: 无效上下文或未初始化");
        return;
    }
    
    agent_log_info("trans_stop: 停止传输层 [类型:%d]", ctx->type);
    
#ifdef WIN_AGENT_APP
    WinTransHw* hw = (WinTransHw*)ctx->hw.hw_specific;
    if (ctx->type == TRANS_ETH && hw != NULL && hw->udp_socket != INVALID_SOCKET) {
        InterlockedExchange(&hw->thread_running, 0);
        if (hw->recv_thread != NULL) {
            WaitForSingleObject(hw->recv_thread, 1000);
            CloseHandle(hw->recv_thread);
            hw->recv_thread = NULL;
        }
        EnterCriticalSection(&hw->socket_lock);
        closesocket(hw->udp_socket);
        hw->udp_socket = INVALID_SOCKET;
        LeaveCriticalSection(&hw->socket_lock);
    }
    WSACleanup();
    if (hw != NULL) {
        DeleteCriticalSection(&hw->socket_lock);
        free(hw);
        ctx->hw.hw_specific = NULL;
    }
#elif defined(STM32)
    if (ctx->type == TRANS_ETH && ctx->hw.udp_pcb != NULL) {
        udp_remove(ctx->hw.udp_pcb);
        ctx->hw.udp_pcb = NULL;
    } else if (ctx->type == TRANS_ES && ctx->hw.es_handle != NULL) {
        es_stop_recv(ctx->hw.es_handle);
        ctx->hw.es_handle = NULL;
    }
    HAL_NVIC_DisableIRQ((IRQn_Type)((ctx->type == TRANS_ETH) ? ctx->hw.eth_irq_num : ctx->hw.es_irq_num));
#elif defined(RISCV)
    if (ctx->type == TRANS_ETH) {
        *(volatile uint32*)(ctx->hw.eth_base + 0x08) &= ~(1 << 0);
        riscv_irq_disable(RISCV_ETH_IRQn);
    } else {
        *(volatile uint32*)(ctx->hw.es_base + 0x08) &= ~(1 << 0);
    }
#endif
    
    ctx->state = TRANS_STATE_UNINIT;
    agent_log_info("trans_stop: 传输层已停止");
}

// -------------------------- 旧接口发送函数 --------------------------
bool8 trans_send_eth(const uint8* data, uint16 len) {
    agent_log_warn("trans_send_eth: 已过时，建议使用trans_send");
    static TransCtx ctx;
    if (ctx.state != TRANS_STATE_READY) {
        if (!trans_cfg_trans(TRANS_ETH, g_fallback_ports[0], &ctx)) {
            agent_log_error("trans_send_eth: 初始化失败");
            return BOOL8_FALSE;
        }
        trans_start(&ctx);
    }
    uint8* dst_ip = ctx.nms_addr_valid ? ctx.nms_ip : (uint8[]){255, 255, 255, 255};
    uint16 dst_port = ctx.nms_addr_valid ? ctx.nms_port : g_fallback_ports[0];
    
    return trans_send(&ctx, data, len, dst_ip, dst_port);
}

bool8 trans_send_es(const uint8* data, uint16 len) {
    agent_log_warn("trans_send_es: 已过时，建议使用trans_send");
    static TransCtx ctx;
    if (ctx.state != TRANS_STATE_READY) {
        if (!trans_cfg_trans(TRANS_ES, g_fallback_ports[0], &ctx)) {
            agent_log_error("trans_send_es: 初始化失败");
            return BOOL8_FALSE;
        }
        trans_start(&ctx);
    }
    return trans_send(&ctx, data, len, NULL, g_fallback_ports[0]);
}

// -------------------------- 中断处理函数（核心优化点） --------------------------
// 优化2: 分离入队和回调判断，修复错误日志误报问题
void trans_eth_irq_handler(TransCtx* ctx, const uint8* data, uint16 len, 
                           const uint8* src_ip, uint16 src_port) {
    if (ctx == NULL || data == NULL || len == 0 || src_ip == NULL) {
        agent_log_error("trans_eth_irq_handler: 无效参数");
        return;
    }
    
    agent_log_debug("trans_eth_irq_handler: 处理ETH数据 [长度:%d]", len);
    
    // 先执行入队操作
    bool8 enqueue_result = trans_queue_enqueue(&ctx->recv_q, data, len);
    
    // 单独判断入队结果
    if (!enqueue_result) {
        agent_log_warn("trans_eth_irq_handler: 数据入队失败");
        return;
    }
    
    // 入队成功后再处理回调
    if (ctx->recv_cb != NULL) {
        ctx->recv_cb(TRANS_ETH, data, len);
    }
}

// 优化3: 对ES中断处理做相同修复
void trans_es_irq_handler(TransCtx* ctx, const uint8* data, uint16 len, 
                          const uint8* src_addr, uint16 src_port) {
    if (ctx == NULL || data == NULL || len == 0 || src_addr == NULL) {
        agent_log_error("trans_es_irq_handler: 无效参数");
        return;
    }
    
    agent_log_debug("trans_es_irq_handler: 处理ES数据 [长度:%d]", len);
    
    // 先执行入队操作
    bool8 enqueue_result = trans_queue_enqueue(&ctx->recv_q, data, len);
    
    // 单独判断入队结果
    if (!enqueue_result) {
        agent_log_warn("trans_es_irq_handler: 数据入队失败");
        return;
    }
    
    // 入队成功后再处理回调
    if (ctx->recv_cb != NULL) {
        ctx->recv_cb(TRANS_ES, data, len);
    }
}

// -------------------------- 白名单设置函数实现 --------------------------
void trans_set_nms_whitelist(TransCtx* ctx, const uint8 ips[][4], uint8 count) {
    if (ctx == NULL) {
        agent_log_error("trans_set_nms_whitelist: 无效参数");
        return;
    }
    
    // 检查白名单是否变化，避免重复设置
    if (count == ctx->whitelist_count) {
        bool8 same = BOOL8_TRUE;
        for (uint8 i = 0; i < count; i++) {
            if (memcmp(ips[i], ctx->whitelist[i], 4) != 0) {
                same = BOOL8_FALSE;
                break;
            }
        }
        if (same) return; // 白名单未变化，直接返回
    }
    
    ctx->whitelist_count = 0;
    for (uint8 i = 0; i < count && i < NMS_WHITELIST_MAX; i++) {
        memcpy(ctx->whitelist[i], ips[i], 4);
        ctx->whitelist_count++;
        agent_log_debug("trans_set_nms_whitelist: 添加白名单IP %d.%d.%d.%d",
                      ips[i][0], ips[i][1], ips[i][2], ips[i][3]);
    }
    
    agent_log_info("trans_set_nms_whitelist: 白名单设置完成 [数量:%d]", ctx->whitelist_count);
}
