diff --git a/protocols/s7tcpmaster.c b/protocols/s7tcpmaster.c index f61aabf..fea22bf 100644 --- a/protocols/s7tcpmaster.c +++ b/protocols/s7tcpmaster.c @@ -2,12 +2,12 @@ * @file s7tcpmaster.c * @brief 西门子S7Comm TCP客户端主站实现 * - * 轮询机制: 和SLMP/FINS相同,使用myRtumST[20] - * - s7_idx: 0~19 轮转索引,对应 myRtumST[20] - * - **奇数索引**: 读操作,从PLC读取数据存储到 1000 + (idx*20) + i - * - **偶数索引**: 写操作,从 1000 + (idx*20) + i 读取数据写入PLC + * 轮询机制: 和SLMP/FINS完全一致,使用myRtumST[20] + * - myRtumSTIdx: 0~19 轮转索引,对应 myRtumST[20] + * - **奇数索引**: 读操作,从PLC读取数据存储到 master.localStartIdx + (idx*20) + i + * - **偶数索引**: 写操作,从 master.localStartIdx + (idx*20) + i 读取数据写入PLC * - 需要先建立TCP连接,然后完成COTP连接协商和S7Comm参数协商 - * - 协商完成后进入正常轮询读写 + * - 协商完成后进入正常读写轮询 */ #include "s7tcpmaster.h" @@ -15,99 +15,346 @@ #include "wizchip_conf.h" #include "rtuMaster.h" #include "main.h" +#include "common.h" #include -static uint8_t buf[1024]; +// ============================================================================ +// 状态枚举 +// ============================================================================ +typedef enum { + S7_STATE_NEGOTIATE_COTP, // 需要发送COTP协商 + S7_STATE_NEGOTIATE_S7, // 需要发送S7Comm协商 + S7_STATE_RUNNING // 协商完成,正常轮询读写 +} s7_negotiate_state_t; -int32_t loopback_tcpc_s7(uint8_t sn,uint8_t *destip, uint16_t destport) { - int32_t ret; // return value for SOCK_ERRORs +// ============================================================================ +// 工具函数 (从需求文档直接复制) +// ============================================================================ +static void to_big_endian_16(uint16_t value, uint8_t *dest) { + dest[0] = (uint8_t) (value >> 8); // 高字节 + dest[1] = (uint8_t) (value & 0xFF); // 低字节 +} + +static void to_big_endian_24(uint32_t value, uint8_t *dest) { + dest[0] = (uint8_t) (value >> 16); // 最高字节 + dest[1] = (uint8_t) (value >> 8); // 次高字节 + dest[2] = (uint8_t) (value & 0xFF); // 最低字节 +} + +// ============================================================================ +// S7帧结构定义 (从需求文档直接复制) +// ============================================================================ +typedef union { + uint8_t frame[31]; + struct { + uint8_t padding1[23]; + uint8_t read_size[2]; + uint8_t db_id[2]; + uint8_t padding2[1]; + uint8_t start_address[3]; + }; +} s7ReadFrame; + +typedef union { + uint8_t frame[1024]; + struct { + uint8_t padding1[2]; + uint8_t frame_size[2]; + uint8_t padding2[11]; + uint8_t dataframe_size[2]; + uint8_t padding3[6]; + uint8_t data_size[2]; + uint8_t db_id[2]; + uint8_t padding4[1]; + uint8_t start_address[3]; + uint8_t padding5[2]; + uint8_t databyte_size_t8[2]; + uint8_t data[800]; + }; +} s7WriteFrame; + +// ============================================================================ +// 全局变量 +// ============================================================================ +static uint8_t myRtumSTIdx = 0; // 轮询索引 (0~19) +static uint8_t prevReadIdx = 0; +static uint8_t comm_buf[1024]; // 收发缓冲区 (最大1024字节) +static uint16_t timeout = 0; // 超时计数,由主循环递增 +static uint16_t commled_off_timeout = 0; +static uint8_t comm_count; +static s7_negotiate_state_t s7_negotiate_state = S7_STATE_NEGOTIATE_COTP; + +// 协商报文 (从需求文档直接复制) +static uint8_t cotp_negotiate[] = + { 0x03, 0x00, 0x00, 0x16, 0x11, 0xE0, 0x00, 0x00, 0x00, 0x01, 0x00, 0xC0, 0x01, 0x0A, 0xC1, 0x02, 0x01, 0x00, 0xC2, 0x02, 0x03, 0x02 }; +static uint8_t s7_negotiate[] = { 0x03, 0x00, 0x00, 0x19, 0x02, 0xF0, 0x80, 0x32, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0xF0, 0x00, 0x00, 0x01, + 0x00, 0x01, 0x01, 0xE0 }; + +// 预初始化读帧模板 (从需求文档直接复制) +static s7ReadFrame s7_read_frame = { .frame = { 0x03, 0x00, 0x00, 0x1f, 0x02, 0xf0, 0x80, 0x32, 0x01, 0x00, 0x00, 0x02, 0x00, 0x00, 0x0e, 0x00, 0x00, 0x04, 0x01, + 0x12, 0x0A, 0x10, 0x02, 0x00, 0x02, 0x00, 0x01, 0x84, 0x00, 0x00, 0x00 } }; + +// 预初始化写帧模板 (从需求文档直接复制) +static s7WriteFrame s7_write_frame = { .frame = { 0x03, 0x00, 0x00, 0x29, 0x02, 0xf0, 0x80, 0x32, 0x01, 0x00, 0x00, 0x01, 0x00, 0x00, 0x0e, 0x00, 0x0a, 0x05, + 0x01, 0x12, 0x0a, 0x10, 0x02, 0x00, 0x06, 0x00, 0x01, 0x84, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } }; + +// ============================================================================ +// 内部函数 +// ============================================================================ + +/** + * @brief 处理S7读响应,解析数据到寄存器映射 + * @param size: 接收数据长度 + * @return true: 解析成功 + */ +static _Bool handleReadRecvS7(uint16_t size) { + // S7读响应数据起始偏移: 协议头长度是 2 (TPKT) + 4 (COTP) + 10 (S7头) + 4 (参数) = 20字节 + // 数据从偏移 20 开始 + // S7响应中每个字是大端序 (高字节在前,低字节在后) + uint16_t pointNum = get_register(myRtumST[prevReadIdx].size); + + // 最小长度检查: 至少包含协议头 + 数据 + if (size < 20 + pointNum * 2) { + return false; + } + + // 解析响应数据,存储到寄存器映射 + for (int i = 0; i < pointNum; i++) { + uint8_t byte_h = comm_buf[20 + i * 2]; + uint8_t byte_l = comm_buf[20 + i * 2 + 1]; + uint16_t value = (((uint16_t) byte_h) << 8) | byte_l; + // 存储地址和SLMP/FINS一致: master.localStartIdx + (索引*20) + 偏移 + set_register(master.localStartIdx + (20 * prevReadIdx) + i, value); + } + + return true; +} + +/** + * @brief 构建S7请求帧 + * @return 发送长度,0表示不发送(参数非法) + * @note 和SLMP/FINS完全一致: 使用myRtumST[20],奇数索引读,偶数索引写 + */ +static uint16_t handleSendS7(void) { + uint16_t sendsize = 0; + uint16_t db_id = get_register(myRtumST[myRtumSTIdx].slave_id); + uint16_t start_address = get_register(myRtumST[myRtumSTIdx].plc_address); + uint16_t pointNum = get_register(myRtumST[myRtumSTIdx].size); + + // 参数合法性检查 + if (pointNum == 0 || pointNum > 20) { + myRtumSTIdx = (myRtumSTIdx + 1) % 20; + return 0; + } + + // ========== 奇数索引: 读操作 ========== + if (myRtumSTIdx % 2 == 1) { + // 根据参数填充读帧 + to_big_endian_16(db_id, s7_read_frame.db_id); + to_big_endian_24(start_address * 8, s7_read_frame.start_address); + to_big_endian_16(pointNum * 2, s7_read_frame.read_size); + + // 读帧固定31字节,拷贝到发送缓冲区 + memcpy(comm_buf, s7_read_frame.frame, 31); + sendsize = 31; + + prevReadIdx = myRtumSTIdx; + } + // ========== 偶数索引: 写操作 ========== + else { + // 根据参数填充写帧 + uint16_t writebyte_size = pointNum * 2; + uint16_t frame_size = 35 + writebyte_size; + + to_big_endian_16(frame_size, s7_write_frame.frame_size); + to_big_endian_16(4 + writebyte_size, s7_write_frame.dataframe_size); + to_big_endian_16(writebyte_size, s7_write_frame.data_size); + to_big_endian_16(db_id, s7_write_frame.db_id); + to_big_endian_24(start_address * 8, s7_write_frame.start_address); + to_big_endian_16(writebyte_size * 8, s7_write_frame.databyte_size_t8); + + // 从寄存器映射读取数据,填充到写帧,S7使用大端序(高字节在前) + for (int i = 0; i < pointNum; i++) { + uint16_t value = get_register(master.localStartIdx + 20 * myRtumSTIdx + i); + s7_write_frame.data[i * 2] = (value >> 8) & 0xFF; // 高字节在前 + s7_write_frame.data[i * 2 + 1] = value & 0xFF; // 低字节在后 + } + + sendsize = frame_size; + // 边界检查,防止溢出缓冲区 + if (sendsize > sizeof(comm_buf)) { + return 0; + } + memcpy(comm_buf, s7_write_frame.frame, sendsize); + } + + // 索引轮转,下次处理下一个通道 (和SLMP/FINS完全一样) + myRtumSTIdx = (myRtumSTIdx + 1) % 20; + return sendsize; +} + +/** + * @brief 超时计数,由主循环每次调用递增 + * @note 和SLMP/FINS完全一致 + */ +void update_timeout_s7(void) { + if (timeout < 0xffff) { + timeout++; + } + if (commled_off_timeout < 0xffff) { + commled_off_timeout++; + } +} + +// ============================================================================ +// 公共接口 +// ============================================================================ + +/** + * @brief S7 TCP客户端主函数,由顶层loopback_comm调用 + * @param sn: W5500 socket编号 + * @param destip: 目标IP地址 + * @param destport: 目标端口 (通常是102) + * @return int32_t: 0/正表示正常,负表示错误 + */ +int32_t loopback_tcpc_s7(uint8_t sn, uint8_t *destip, uint16_t destport) { + // 通信LED闪烁,和SLMP/FINS完全一致 + if (comm_count > W5500_COMM_LED_TOGGLE_CNT) { + HAL_GPIO_TogglePin(comm_GPIO_Port, comm_Pin); + comm_count = 0; + } + if (commled_off_timeout > W5500_COMM_LED_OFF_TIMEMS) { + HAL_GPIO_WritePin(comm_GPIO_Port, comm_Pin, GPIO_PIN_SET); + } + + int32_t ret; uint16_t size = 0, sentsize = 0; + static uint16_t any_port = 50000; // 本地端口,自动递增 - // Destination (TCP Server) IP info (will be connected) - // >> loopback_tcpc() function parameter - // >> Ex) - // uint8_t destip[4] = {192, 168, 0, 214}; - // uint16_t destport = 5000; - - // Port number for TCP client (will be increased) - static uint16_t any_port = 50000; - - // Socket Status Transitions - // Check the W5500 Socket n status register (Sn_SR, The 'Sn_SR' controlled by Sn_CR command or Packet send/recv status) - switch (getSn_SR(sn)) { + uint8_t sr_status = getSn_SR(sn); + switch (sr_status) { + // ========== 连接已建立: 收发数据 ========== case SOCK_ESTABLISHED: - if (getSn_IR(sn) & Sn_IR_CON) { // Socket n interrupt register mask; TCP CON interrupt = connection with peer is successful -#ifdef _LOOPBACK_DEBUG_ - printf("%d:Connected to - %d.%d.%d.%d : %d\r\n", sn, destip[0], destip[1], destip[2], destip[3], destport); -#endif - setSn_IR(sn, Sn_IR_CON); // this interrupt should be write the bit cleared to '1' + if (getSn_IR(sn) & Sn_IR_CON) { + setSn_IR(sn, Sn_IR_CON); // 清连接中断标志 + // 连接建立后,开始发送COTP协商 + s7_negotiate_state = S7_STATE_NEGOTIATE_COTP; } - ////////////////////////////////////////////////////////////////////////////////////////////// - // Data Transaction Parts; Handle the [data receive and send] process - ////////////////////////////////////////////////////////////////////////////////////////////// - if ((size = getSn_RX_RSR(sn)) > 0) { // Sn_RX_RSR: Socket n Received Size Register, Receiving data length - if (size > 1024) { - size = 1024; // DATA_BUF_SIZE means user defined buffer size (array) + // 1. 接收响应 + if ((size = getSn_RX_RSR(sn)) > 0) { + // 边界保护,不超过缓冲区 + if (size > sizeof(comm_buf)) { + size = sizeof(comm_buf); } - ret = recv(sn, buf, size); // Data Receive process (H/W Rx socket buffer -> User's buffer) + ret = recv(sn, comm_buf, size); + if (ret > 0) { + commled_off_timeout = 0; + comm_count++; - if (ret <= 0) { - return ret; // If the received data length <= 0, receive failed and process end - } - size = (uint16_t) ret; - sentsize = 0; + // 根据协商状态处理接收 + switch (s7_negotiate_state) { + case S7_STATE_NEGOTIATE_COTP: + // 收到COTP响应,进入下一步S7协商,有回应就算通过 + s7_negotiate_state = S7_STATE_NEGOTIATE_S7; + break; - // Data sentsize control - while (size != sentsize) { - ret = send(sn, buf + sentsize, size - sentsize); // Data send process (User's buffer -> Destination through H/W Tx socket buffer) - if (ret < 0) { // Send Error occurred (sent data length < 0) - close(sn); // socket close - return ret; + case S7_STATE_NEGOTIATE_S7: + // 收到S7协商响应,进入正常读写,有回应就算通过 + s7_negotiate_state = S7_STATE_RUNNING; + timeout = 490; // 准备第一次发送 + break; + + case S7_STATE_RUNNING: + // 正常读写,处理读响应 + if (myRtumSTIdx % 2 == 0 || prevReadIdx == 0) { + // 写响应不需要处理 + } else { + handleReadRecvS7(ret); + timeout = 490; + } + break; + + default: + break; } - sentsize += ret; // Don't care SOCKERR_BUSY, because it is zero. } } - ////////////////////////////////////////////////////////////////////////////////////////////// + + // 2. 准备发送数据 + size = 0; + switch (s7_negotiate_state) { + case S7_STATE_NEGOTIATE_COTP: + // 发送COTP协商 + memcpy(comm_buf, cotp_negotiate, sizeof(cotp_negotiate)); + size = sizeof(cotp_negotiate); + break; + + case S7_STATE_NEGOTIATE_S7: + // 发送S7协商 + memcpy(comm_buf, s7_negotiate, sizeof(s7_negotiate)); + size = sizeof(s7_negotiate); + break; + + case S7_STATE_RUNNING: + // 超时触发发送读写请求,和SLMP/FINS一致,超时>500发送 + if (timeout > 500) { + size = handleSendS7(); + if (size == 0) { + // 无效通道,快速跳过 + timeout = 499; + } else { + // 有效发送,重置超时 + timeout = 0; + } + } + break; + + default: + break; + } + + // 3. 发送请求(分片发送,直到发完) + sentsize = 0; + while (size != 0 && sentsize != size) { + ret = send(sn, comm_buf + sentsize, size - sentsize); + if (ret < 0) { + close(sn); + return ret; + } + sentsize += ret; + } break; + // ========== 对方关闭连接 ========== case SOCK_CLOSE_WAIT: -#ifdef _LOOPBACK_DEBUG_ - //printf("%d:CloseWait\r\n",sn); -#endif if ((ret = disconnect(sn)) != SOCK_OK) { return ret; } -#ifdef _LOOPBACK_DEBUG_ - printf("%d:Socket Closed\r\n", sn); -#endif break; + // ========== 初始化: 发起连接 ========== case SOCK_INIT: -#ifdef _LOOPBACK_DEBUG_ - printf("%d:Try to connect to the %d.%d.%d.%d : %d\r\n", sn, destip[0], destip[1], destip[2], destip[3], destport); -#endif if ((ret = connect(sn, destip, destport)) != SOCK_OK) { - return ret; // Try to TCP connect to the TCP server (destination) + return ret; } break; + // ========== socket未打开: 新建socket ========== case SOCK_CLOSED: close(sn); - if ((ret = socket(sn, Sn_MR_TCP, any_port++, 0x00)) != sn) { - if (any_port == 0xffff) { - any_port = 50000; - } - return ret; // TCP socket open with 'any_port' port number + // 端口绕回,超过最大值后重置 + if (any_port == 0xffff) { + any_port = 50000; + } + if ((ret = socket(sn, Sn_MR_TCP, any_port++, SF_IO_NONBLOCK)) != sn) { + return ret; } -#ifdef _LOOPBACK_DEBUG_ - //printf("%d:TCP client loopback start\r\n",sn); - //printf("%d:Socket opened\r\n",sn); -#endif break; + default: break; } - return 1; -} + return 1; +} \ No newline at end of file diff --git a/protocols/s7tcpmaster.h b/protocols/s7tcpmaster.h index d94c1f7..3669eb1 100644 --- a/protocols/s7tcpmaster.h +++ b/protocols/s7tcpmaster.h @@ -14,6 +14,7 @@ extern "C" { int32_t loopback_tcpc_s7(uint8_t sn, uint8_t *destip, uint16_t destport); +void update_timeout_s7(void); #ifdef __cplusplus }