/** * @file modbustcpslave.h * @brief Modbus TCP从站服务头文件 */ #ifndef MODBUSTCPSLAVE_H #define MODBUSTCPSLAVE_H #ifdef __cplusplus extern "C" { #endif #include #include #ifndef DATA_BUF_SIZE #define DATA_BUF_SIZE 2048 #endif // ============================================================================ // 结构体定义 // ============================================================================ // RTU接收状态结构体 typedef struct { uint8_t buf[512]; // 接收缓冲区 _Bool done; // 接收完成标志 uint16_t size; // 接收数据长度 } RtuRxST; // ============================================================================ // 全局变量 // ============================================================================ extern uint8_t loopback_tcps_modbus_rxbuf[1024]; extern uint8_t loopback_tcps_modbus_txbuf[1024]; // ============================================================================ // 接口函数 // ============================================================================ /** * @brief Modbus TCP服务主函数,W5500socket主循环处理 * @param sn: socket编号 * @param port: 监听端口 (通常502) * @return 0/正表示正常,负表示错误 */ int32_t loopback_tcps_modbus(uint8_t sn, uint16_t port); /** * @brief Modbus TCP转RTU转发,TCP -> RS485 -> TCP * @param sn: socket编号 * @param buf: TCP接收缓冲区 * @param port: 监听端口 * @param timeout: 超时计数指针 * @param rtu_rx: RTU接收状态结构体 * @return 0/正表示正常,负表示错误 */ int32_t loopback_tcps_modbus_to485(uint8_t sn, uint8_t *buf, uint16_t port, uint16_t *timeout, RtuRxST *rtu_rx); /** * @brief Modbus TCP转RTU格式转换 * @param tcp_buf: TCP输入缓冲区 * @param rtu_buf: RTU输出缓冲区 * @return RTU帧长度 */ uint16_t tcp_to_rtu(uint8_t *tcp_buf, uint8_t *rtu_buf); /** * @brief Modbus RTU转TCP格式转换 * @param rtu_buf: RTU输入缓冲区 * @param tcp_buf: TCP输出缓冲区 * @param rtu_len: RTU帧长度 * @param rx_buf: 原TCP缓冲区(拷贝MBAP头) * @return TCP帧长度,0表示CRC错误 */ uint16_t rtu_to_tcp(uint8_t *rtu_buf, uint8_t *tcp_buf, uint16_t rtu_len, uint8_t *rx_buf); #ifdef __cplusplus } #endif #endif