From 9f3b8cf65aac685e69b8519f0c20266d93bf74e8 Mon Sep 17 00:00:00 2001 From: claw <18896825080@163.com> Date: Fri, 3 Apr 2026 16:45:01 +0800 Subject: [PATCH] protocol --- comm/loopback.c | 50 - comm/loopback.h | 44 - comm/main.c | 396 -------- comm/modbusSlave.c | 940 ------------------ comm/modbusSlave.h | 38 - comm/protocols/finsudpmaster.c | 239 ----- comm/protocols/modbustcpslave.c | 317 ------ comm/protocols/modbustcpslave.h | 82 -- comm/protocols/s7tcpmaster.c | 438 -------- comm/protocols/s7tcpmaster.h | 65 -- comm/rtuMaster.c | 170 ---- comm/rtuMaster.h | 41 - comm/slmpMaster.c | 37 - comm/slmpMaster.h | 53 - protocols/common.c | 8 + protocols/common.h | 14 + protocols/finsudpmaster.c | 211 ++++ {comm/protocols => protocols}/finsudpmaster.h | 4 - protocols/modbustcpslave.c | 121 +++ protocols/modbustcpslave.h | 38 + protocols/s7tcpmaster.c | 113 +++ protocols/s7tcpmaster.h | 22 + {comm/protocols => protocols}/slmptcpmaster.c | 188 ++-- {comm/protocols => protocols}/slmptcpmaster.h | 8 +- 24 files changed, 619 insertions(+), 3018 deletions(-) delete mode 100644 comm/loopback.c delete mode 100644 comm/loopback.h delete mode 100644 comm/main.c delete mode 100644 comm/modbusSlave.c delete mode 100644 comm/modbusSlave.h delete mode 100644 comm/protocols/finsudpmaster.c delete mode 100644 comm/protocols/modbustcpslave.c delete mode 100644 comm/protocols/modbustcpslave.h delete mode 100644 comm/protocols/s7tcpmaster.c delete mode 100644 comm/protocols/s7tcpmaster.h delete mode 100644 comm/rtuMaster.c delete mode 100644 comm/rtuMaster.h delete mode 100644 comm/slmpMaster.c delete mode 100644 comm/slmpMaster.h create mode 100644 protocols/common.c create mode 100644 protocols/common.h create mode 100644 protocols/finsudpmaster.c rename {comm/protocols => protocols}/finsudpmaster.h (86%) create mode 100644 protocols/modbustcpslave.c create mode 100644 protocols/modbustcpslave.h create mode 100644 protocols/s7tcpmaster.c create mode 100644 protocols/s7tcpmaster.h rename {comm/protocols => protocols}/slmptcpmaster.c (55%) rename {comm/protocols => protocols}/slmptcpmaster.h (75%) diff --git a/comm/loopback.c b/comm/loopback.c deleted file mode 100644 index 502fa3b..0000000 --- a/comm/loopback.c +++ /dev/null @@ -1,50 +0,0 @@ -#include -#include "loopback.h" -#include "protocols/modbustcpslave.h" -#include "protocols/finsudpmaster.h" -#include "protocols/slmptcpmaster.h" -#include "rtuMaster.h" - -#define DBID1_IDX 1000 -#define START1_IDX 1001 -#define SIZE1_IDX 1002 -#define TOMOD_IDX 1003 -#define DBID2_IDX 1005 -#define START2_IDX 1006 -#define SIZE2_IDX 1007 -#define FROMMOD_IDX 1008 - -#if LOOPBACK_MODE == LOOPBACK_MAIN_NOBLCOK - -// 全局共享变量定义 -uint16_t client_wait_timeout = 0; -uint16_t comm_count = 0; -uint16_t slmpTimegap = 0; -uint16_t fins_timeout = 0; - -// 通用字节序转换工具函数 -void to_big_endian_16(uint16_t value, uint8_t *dest) { - dest[0] = (uint8_t)(value >> 8); // 高字节在前 - dest[1] = (uint8_t)(value & 0xFF); // 低字节在后 -} - -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); // 最低字节 -} - -// 顶层统一入口,根据PLC类型选择协议 -void loopback_comm(uint8_t *ip, uint16_t port, uint8_t node) { - if (master.plc_type == 0) { - // 0 -> SLMP TCP (三菱) - loopback_tcpc_slmp(1, ip, port); - } else if (master.plc_type == 1) { - // 1 -> OMR FINS UDP (欧姆龙) - loopback_udpc_omrfins(1, ip, port, node); - } - // 始终启动Modbus TCP服务在端口502 - loopback_tcps_modbus(0, 502); -} - -#endif diff --git a/comm/loopback.h b/comm/loopback.h deleted file mode 100644 index a4de0cd..0000000 --- a/comm/loopback.h +++ /dev/null @@ -1,44 +0,0 @@ -#ifndef _LOOPBACK_H_ -#define _LOOPBACK_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -#include -#include -#include "protocols/modbustcpslave.h" -#include "protocols/finsudpmaster.h" -#include "protocols/slmptcpmaster.h" - -/* Loopback test debug message printout enable */ -//#define _LOOPBACK_DEBUG_ -/* DATA_BUF_SIZE define for Loopback example */ -#ifndef DATA_BUF_SIZE -#define DATA_BUF_SIZE 2048 -#endif - -/************************/ -/* Select LOOPBACK_MODE */ -/************************/ -#define LOOPBACK_MAIN_NOBLOCK 0 -#define LOOPBACK_MODE LOOPBACK_MAIN_NOBLOCK - -// 全局共享变量 -extern uint16_t client_wait_timeout; -extern uint16_t comm_count; -extern uint16_t slmpTimegap; -extern uint16_t fins_timeout; - -// 工具函数声明 -void to_big_endian_16(uint16_t value, uint8_t *dest); -void to_big_endian_24(uint32_t value, uint8_t *dest); - -// 顶层统一入口 -void loopback_comm(uint8_t *ip, uint16_t port, uint8_t node); - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/comm/main.c b/comm/main.c deleted file mode 100644 index 5ee8d3b..0000000 --- a/comm/main.c +++ /dev/null @@ -1,396 +0,0 @@ -/* USER CODE BEGIN Header */ -/** - ****************************************************************************** - * @file : main.c - * @brief : Main program body - ****************************************************************************** - * @attention - * - * Copyright (c) 2026 STMicroelectronics. - * All rights reserved. - * - * This software is licensed under terms that can be found in the LICENSE file - * in the root directory of this software component. - * If no LICENSE file comes with this software, it is provided AS-IS. - * - ****************************************************************************** - */ -/* USER CODE END Header */ -/* Includes ------------------------------------------------------------------*/ -#include "main.h" -#include "dma.h" -#include "iwdg.h" -#include "spi.h" -#include "tim.h" -#include "usart.h" -#include "gpio.h" - -/* Private includes ----------------------------------------------------------*/ -/* USER CODE BEGIN Includes */ -#include "w5500/w5500.h" -#include "w5500/w5500_port.h" -#include "w5500/loopback.h" -#include "w5500/webpages.h" -#include "w5500/httpUtil.h" -#include "w5500/slmpMaster.h" -#include "w5500/modbus_crc.h" -#include "w5500/modbusSlave.h" -#include "w5500/rtuMaster.h" -/* USER CODE END Includes */ - -/* Private typedef -----------------------------------------------------------*/ -/* USER CODE BEGIN PTD */ - -/* USER CODE END PTD */ - -/* Private define ------------------------------------------------------------*/ -/* USER CODE BEGIN PD */ - -/* USER CODE END PD */ - -/* Private macro -------------------------------------------------------------*/ -/* USER CODE BEGIN PM */ - -/* USER CODE END PM */ - -/* Private variables ---------------------------------------------------------*/ - -/* USER CODE BEGIN PV */ - -uint8_t local_ip[4], slmp_ip[4]; -uint16_t slmp_port; - -uint16_t out_word1 = 0; - -uint16_t speed = 0; -uint16_t speed_idx = 0; -/* USER CODE END PV */ - -/* Private function prototypes -----------------------------------------------*/ -void SystemClock_Config(void); -/* USER CODE BEGIN PFP */ - -/* USER CODE END PFP */ - -/* Private user code ---------------------------------------------------------*/ -/* USER CODE BEGIN 0 */ -//////////////////////////////////////////////////////////// ↓定时器(TIME6=1MS)↓ ///////////////////////////////////////////// -uint16_t beatcnt = 0; -_Bool beatval; -uint16_t runbeat, rstbtn_timeout; -void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim) { - - if (htim == &htim6) { - update_timeout_slmp(); - update_timeout_fins(); - - if (runbeat < 1000) { //控制运行指示灯间隔1秒闪烁 - runbeat++; - } else { - runbeat = 0; - HAL_GPIO_TogglePin(run_GPIO_Port, run_Pin); - set_register(109, HAL_GPIO_ReadPin(run_GPIO_Port, run_Pin) ? 1 : 0); //109运行心跳位,间隔1秒闪烁 - } - - if (HAL_GPIO_ReadPin(rstbtn_GPIO_Port, rstbtn_Pin) == GPIO_PIN_RESET) { //系统参数初始化等待延时,如果按下3秒系统设定数据复位 - if (rstbtn_timeout < 0xffff) { - rstbtn_timeout++; - } else { - rstbtn_timeout = 0; - } - } - } -} -//////////////////////////////////////////////////////////// ↑定时器↑ ///////////////////////////////////////////// -///////////////////////////////////// -uint16_t flash_reset[100]; - -void reset_button() { - if (rstbtn_timeout > 3000) { - memset(flash_reset, 0xFF, 200); - Write_To_Flash_uint16(EDIT_FLASH_ADDRESS, flash_reset, 100); - rstbtn_timeout = 0; - set_register(120, get_register(120) + 1); - } -} - - -////////////////////////////////////////////////////////////↓将110地址输出给继电器↓///////////////////////////////////////////// -int getBit(int num, int n) { - return (num & (1 << n)) >> n; -} - -void map_out(uint16_t startAddress) { - out_word1 = get_register(startAddress); - - (getBit(out_word1, 0)) ? HAL_GPIO_WritePin(o1_GPIO_Port, o1_Pin, GPIO_PIN_SET) : HAL_GPIO_WritePin(o1_GPIO_Port, o1_Pin, GPIO_PIN_RESET); - (getBit(out_word1, 1)) ? HAL_GPIO_WritePin(o2_GPIO_Port, o2_Pin, GPIO_PIN_SET) : HAL_GPIO_WritePin(o2_GPIO_Port, o2_Pin, GPIO_PIN_RESET); - (getBit(out_word1, 2)) ? HAL_GPIO_WritePin(o3_GPIO_Port, o3_Pin, GPIO_PIN_SET) : HAL_GPIO_WritePin(o3_GPIO_Port, o3_Pin, GPIO_PIN_RESET); - (getBit(out_word1, 3)) ? HAL_GPIO_WritePin(o4_GPIO_Port, o4_Pin, GPIO_PIN_SET) : HAL_GPIO_WritePin(o4_GPIO_Port, o4_Pin, GPIO_PIN_RESET); - (getBit(out_word1, 4)) ? HAL_GPIO_WritePin(o5_GPIO_Port, o5_Pin, GPIO_PIN_SET) : HAL_GPIO_WritePin(o5_GPIO_Port, o5_Pin, GPIO_PIN_RESET); - (getBit(out_word1, 5)) ? HAL_GPIO_WritePin(o6_GPIO_Port, o6_Pin, GPIO_PIN_SET) : HAL_GPIO_WritePin(o6_GPIO_Port, o6_Pin, GPIO_PIN_RESET); - (getBit(out_word1, 6)) ? HAL_GPIO_WritePin(o7_GPIO_Port, o7_Pin, GPIO_PIN_SET) : HAL_GPIO_WritePin(o7_GPIO_Port, o7_Pin, GPIO_PIN_RESET); - (getBit(out_word1, 7)) ? HAL_GPIO_WritePin(o8_GPIO_Port, o8_Pin, GPIO_PIN_SET) : HAL_GPIO_WritePin(o8_GPIO_Port, o8_Pin, GPIO_PIN_RESET); - - (getBit(out_word1, 8)) ? HAL_GPIO_WritePin(o9_GPIO_Port, o9_Pin, GPIO_PIN_SET) : HAL_GPIO_WritePin(o9_GPIO_Port, o9_Pin, GPIO_PIN_RESET); - (getBit(out_word1, 9)) ? HAL_GPIO_WritePin(o10_GPIO_Port, o10_Pin, GPIO_PIN_SET) : HAL_GPIO_WritePin(o10_GPIO_Port, o10_Pin, GPIO_PIN_RESET); - (getBit(out_word1, 10)) ? HAL_GPIO_WritePin(o11_GPIO_Port, o11_Pin, GPIO_PIN_SET) : HAL_GPIO_WritePin(o11_GPIO_Port, o11_Pin, GPIO_PIN_RESET); - (getBit(out_word1, 11)) ? HAL_GPIO_WritePin(o12_GPIO_Port, o12_Pin, GPIO_PIN_SET) : HAL_GPIO_WritePin(o12_GPIO_Port, o12_Pin, GPIO_PIN_RESET); - (getBit(out_word1, 12)) ? HAL_GPIO_WritePin(o13_GPIO_Port, o13_Pin, GPIO_PIN_SET) : HAL_GPIO_WritePin(o13_GPIO_Port, o13_Pin, GPIO_PIN_RESET); - (getBit(out_word1, 13)) ? HAL_GPIO_WritePin(o14_GPIO_Port, o14_Pin, GPIO_PIN_SET) : HAL_GPIO_WritePin(o14_GPIO_Port, o14_Pin, GPIO_PIN_RESET); - (getBit(out_word1, 14)) ? HAL_GPIO_WritePin(o15_GPIO_Port, o15_Pin, GPIO_PIN_SET) : HAL_GPIO_WritePin(o15_GPIO_Port, o15_Pin, GPIO_PIN_RESET); - (getBit(out_word1, 15)) ? HAL_GPIO_WritePin(o16_GPIO_Port, o16_Pin, GPIO_PIN_SET) : HAL_GPIO_WritePin(o16_GPIO_Port, o16_Pin, GPIO_PIN_RESET); - -} -////////////////////////////////////////////////////////////↑将110地址输出给继电器上///////////////////////////////////////////// - -void Read_From_Flash(uint32_t startAddress, uint16_t *buffer, uint32_t numElements) { - for (uint32_t i = 0; i < numElements; i++) { - buffer[i] = *(__IO uint16_t*) (startAddress + (i * 2)); - } -} - -void load_data() { - // 初始化保存数据 - uint16_t readDataBuffer[FLASH_SAVE_SIZE]; - - Read_From_Flash(EDIT_FLASH_ADDRESS, readDataBuffer, FLASH_SAVE_SIZE); - - set_register_range(MODBUS_SAVE_START, FLASH_SAVE_SIZE, readDataBuffer); - - //加载参数 - slmp_port = get_register(85); - slmp_ip[0] = get_register(81); - slmp_ip[1] = get_register(82); - slmp_ip[2] = get_register(83); - slmp_ip[3] = get_register(84); - if (slmp_ip[0] == 0xff || slmp_ip[1] == 0xff || slmp_ip[2] == 0xff || slmp_ip[3] == 0xff) { - slmp_ip[0] = 192; - slmp_ip[1] = 168; - slmp_ip[2] = 1; - slmp_ip[3] = 9; - set_register(81, 192); - set_register(82, 168); - set_register(83, 1); - set_register(84, 9); - } - - if (slmp_port == 0xffff) { - set_register(85, 1025); - } - - local_ip[0] = get_register(86); - local_ip[1] = get_register(87); - local_ip[2] = get_register(88); - local_ip[3] = get_register(89); - if (local_ip[0] == 0xff || local_ip[1] == 0xff || local_ip[2] == 0xff || local_ip[3] == 0xff) { - local_ip[0] = 192; - local_ip[1] = 168; - local_ip[2] = 1; - local_ip[3] = 13; - set_register(86, 192); - set_register(87, 168); - set_register(88, 1); - set_register(89, 13); - } - - if (get_register(90) < 1 || get_register(90) > 0xff) { - set_register(90, 120); - } - - for (uint16_t i = 0; i < 80; i++) { - if (get_register(i) == 0xffff) { - set_register(i, 0); - } - } - - set_slaveid(get_register(90)); - - if (get_register(80) == 0xffff) { - set_register(80, 0); - } - - uint32_t BaudRate = 0; - switch (get_register(80)) { - case 0: - BaudRate = 9600; - break; - case 1: - BaudRate = 14400; - break; - case 2: - BaudRate = 19200; - break; - case 3: - BaudRate = 38400; - break; - case 4: - BaudRate = 56000; - break; - case 5: - BaudRate = 57600; - break; - case 6: - BaudRate = 115200; - break; - default: - BaudRate = 9600; - break; - } - MX_USART1_UART_Init(BaudRate); - - if (get_register(91) == 0xffff) { - set_register(91, 0); - } - - master.localSlaveId = get_register(90); - master.isMaster = get_register(91) ? 1 : 0; - master.plc_type = get_register(92); -} - -void commled() { - if (comm_count > 100) { - HAL_GPIO_TogglePin(comm_GPIO_Port, comm_Pin); - comm_count = 0; - } - - if (getSn_SR(0) == SOCK_CLOSED && getSn_SR(1) == SOCK_CLOSED) { - HAL_GPIO_WritePin(comm_GPIO_Port, comm_Pin, GPIO_PIN_SET); - } -} - -/* USER CODE END 0 */ - -/** - * @brief The application entry point. - * @retval int - */ -int main(void) { - - /* USER CODE BEGIN 1 */ - - /* USER CODE END 1 */ - - /* MCU Configuration--------------------------------------------------------*/ - - /* Reset of all peripherals, Initializes the Flash interface and the Systick. */ - HAL_Init(); - - /* USER CODE BEGIN Init */ - - /* USER CODE END Init */ - - /* Configure the system clock */ - SystemClock_Config(); - - /* USER CODE BEGIN SysInit */ - - /* USER CODE END SysInit */ - - /* Initialize all configured peripherals */ - MX_GPIO_Init(); - MX_DMA_Init(); - MX_IWDG_Init(); -// MX_USART1_UART_Init(); - MX_SPI1_Init(); - MX_TIM6_Init(); - /* USER CODE BEGIN 2 */ - HAL_TIM_Base_Start_IT(&htim6); - load_data(); - w5500_init(local_ip); - httpServer_init(); - reg_httpServer_cbfunc(NVIC_SystemReset, NULL); - reg_httpServer_webContent((uint8_t*) "index.html", (uint8_t*) rtu_master); - reg_httpServer_webContent((uint8_t*) "ajax.js", (uint8_t*) w5x00web_ajax_js); - initRtuMaster(); - - /* USER CODE END 2 */ - - /* Infinite loop */ - /* USER CODE BEGIN WHILE */ - while (1) { - /* USER CODE END WHILE */ - - /* USER CODE BEGIN 3 */ - HAL_IWDG_Refresh(&hiwdg); - map_out(110); - reset_button(); - commled(); - - httpServer_run_main(); - - // 网口通信 - loopback_comm(slmp_ip, slmp_port, local_ip[3]); - // 串口通信 - RTU_Master_Loop(); - } - /* USER CODE END 3 */ -} - -/** - * @brief System Clock Configuration - * @retval None - */ -void SystemClock_Config(void) { - RCC_OscInitTypeDef RCC_OscInitStruct = { 0 }; - RCC_ClkInitTypeDef RCC_ClkInitStruct = { 0 }; - - /** Initializes the RCC Oscillators according to the specified parameters - * in the RCC_OscInitTypeDef structure. - */ - RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI | RCC_OSCILLATORTYPE_LSI; - RCC_OscInitStruct.HSIState = RCC_HSI_ON; - RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT; - RCC_OscInitStruct.LSIState = RCC_LSI_ON; - RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; - RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI_DIV2; - RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9; - if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) { - Error_Handler(); - } - - /** Initializes the CPU, AHB and APB buses clocks - */ - RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2; - RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; - RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; - RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2; - RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1; - - if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_1) != HAL_OK) { - Error_Handler(); - } -} - -/* USER CODE BEGIN 4 */ - -/* USER CODE END 4 */ - -/** - * @brief This function is executed in case of error occurrence. - * @retval None - */ -void Error_Handler(void) { - /* USER CODE BEGIN Error_Handler_Debug */ - /* User can add his own implementation to report the HAL error return state */ - __disable_irq(); - while (1) { - } - /* USER CODE END Error_Handler_Debug */ -} -#ifdef USE_FULL_ASSERT -/** - * @brief Reports the name of the source file and the source line number - * where the assert_param error has occurred. - * @param file: pointer to the source file name - * @param line: assert_param error line source number - * @retval None - */ -void assert_failed(uint8_t *file, uint32_t line) -{ - /* USER CODE BEGIN 6 */ - /* User can add his own implementation to report the file name and line number, - ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */ - /* USER CODE END 6 */ -} -#endif /* USE_FULL_ASSERT */ diff --git a/comm/modbusSlave.c b/comm/modbusSlave.c deleted file mode 100644 index 539e788..0000000 --- a/comm/modbusSlave.c +++ /dev/null @@ -1,940 +0,0 @@ -#include "modbusSlave.h" -#include "modbus_crc.h" -#include "string.h" -#include "stdio.h" - -uint16_t tcp_ledcnt = 0; -uint16_t u232_ledcnt = 0; -uint16_t u485_ledcnt = 0; - -static uint8_t SLAVE_ID = 7; - -static uint16_t Holding_Registers_Database[3000] = { 0 }; - -void set_slaveid(uint8_t val) { - SLAVE_ID = val; -} - -uint8_t get_slaveid() { - return SLAVE_ID; -} - -void get_register_range(uint16_t start, uint16_t size, uint16_t *buf) { - for (uint16_t i = 0; i < size; i++) { - buf[i] = Holding_Registers_Database[start + i]; - } -} - -void get_register_range_to_u8(uint16_t start, uint16_t count, uint8_t *buf) { - for (int i = 0; i < count; ++i) { - // 获取当前 uint16_t 值 - uint16_t current = Holding_Registers_Database[start + i]; - // 高字节放在低地址 - if (get_register(1009) == 10) { - buf[2 * i] = (uint8_t) (current >> 8); // 高字节 - buf[2 * i + 1] = (uint8_t) (current); // 低字节 - } else { - buf[2 * i] = (uint8_t) (current); // 低字节 - buf[2 * i + 1] = (uint8_t) (current >> 8); // 高字节 - } - - } -} - -void set_register_range(uint16_t start, uint16_t size, uint16_t *buf) { - for (uint16_t i = 0; i < size; i++) { - Holding_Registers_Database[start + i] = buf[i]; - } -} - -void set_register_range_u8(uint16_t start, uint16_t size, uint8_t *buf) { - for (uint16_t i = 0; i < size; i++) { - Holding_Registers_Database[start + i] = buf[i]; - } -} - -void set_register(uint16_t index, uint16_t value) { - Holding_Registers_Database[index] = value; -} - -void set_register_u32(uint16_t index, uint32_t value) { - uint16_t high = (value >> 16) & 0xFFFF; - uint16_t low = value & 0xFFFF; - Holding_Registers_Database[index] = low; - Holding_Registers_Database[index + 1] = high; -} - -uint32_t get_register_u32(uint16_t index) { - uint32_t low = Holding_Registers_Database[index]; - uint32_t high = Holding_Registers_Database[index + 1]; - return (high << 16) | low; -} - -void set_register_float(uint16_t index, float value) { - FloatToUint16 converter; - converter.value = value; - Holding_Registers_Database[index] = converter.u16[0]; - Holding_Registers_Database[index + 1] = converter.u16[1]; -} - -uint16_t get_register(uint16_t index) { - return Holding_Registers_Database[index]; -} - -float get_register_float(uint16_t index) { - FloatToUint16 converter; - converter.u16[0] = Holding_Registers_Database[index]; - converter.u16[1] = Holding_Registers_Database[index + 1]; - return converter.value; -} - -// *************************** MODBUS TCP start************************ - -uint16_t readHoldingRegs_tcp(uint8_t *rx_buf, uint8_t *tx_buf) { - uint16_t startAddr = ((rx_buf[8] << 8) | rx_buf[9]); - uint16_t numRegs = ((rx_buf[10] << 8) | rx_buf[11]); - uint16_t frame_size = numRegs * 2 + 3; - - tx_buf[0] = rx_buf[0]; - tx_buf[1] = rx_buf[1]; - tx_buf[2] = rx_buf[2]; - tx_buf[3] = rx_buf[3]; - tx_buf[4] = (frame_size >> 8) & 0xFF; - tx_buf[5] = frame_size & 0xFF; - tx_buf[6] = rx_buf[6]; - tx_buf[7] = rx_buf[7]; - tx_buf[8] = numRegs * 2; - int index = 9; - - for (int i = 0; i < numRegs; i++) { - tx_buf[index++] = (Holding_Registers_Database[startAddr] >> 8) & 0xFF; - tx_buf[index++] = (Holding_Registers_Database[startAddr]) & 0xFF; - startAddr++; - } - return numRegs * 2 + 9; -} - -uint16_t writeMultiRegs_tcp(uint8_t *rx_buf, uint8_t *tx_buf) { - uint16_t startAddr = ((rx_buf[8] << 8) | rx_buf[9]); - uint8_t write_size = rx_buf[12] / 2; - uint8_t write_value_idx = 13; - while (write_size > 0) { - uint8_t left = rx_buf[write_value_idx++]; - uint8_t right = rx_buf[write_value_idx++]; - uint16_t this_value = (left << 8) | right; - Holding_Registers_Database[startAddr++] = this_value; - write_size--; - } - memcpy(tx_buf, rx_buf, 12); - tx_buf[4] = 0x00; - tx_buf[5] = 6; - return 12; -} - -uint16_t writeSingleReg_tcp(uint8_t *rx_buf, uint8_t *tx_buf) { - uint16_t startAddr = ((rx_buf[8] << 8) | rx_buf[9]); - uint8_t left = rx_buf[10]; - uint8_t right = rx_buf[11]; - uint16_t this_value = (left << 8) | right; - Holding_Registers_Database[startAddr] = this_value; - memcpy(tx_buf, rx_buf, 12); - tx_buf[4] = 0x00; - tx_buf[5] = 0x06; - return 12; -} - -uint16_t handleModbusTcp(uint8_t *rx_buf, uint8_t *tx_buf) { - switch (rx_buf[7]) { - case 0x03: - return readHoldingRegs_tcp(rx_buf, tx_buf); - break; - case 0x06: - return writeSingleReg_tcp(rx_buf, tx_buf); - break; - case 0x10: - return writeMultiRegs_tcp(rx_buf, tx_buf); - break; - default: - break; - } - return 0; -} - -// *************************** MODBUS TCP end************************ - -uint8_t readHoldingRegs_rtu(uint8_t *rx_buf, uint8_t *tx_buf) { - uint16_t startAddr = ((rx_buf[2] << 8) | rx_buf[3]); // start Register Address - uint16_t numRegs = ((rx_buf[4] << 8) | rx_buf[5]); // number to registers master has requested - - tx_buf[0] = SLAVE_ID; // slave ID - tx_buf[1] = rx_buf[1]; // function code - tx_buf[2] = numRegs * 2; // Byte count - int endIdx = 3; // we need to keep track of how many bytes has been stored in MDTxData Buffer - - for (int i = 0; i < numRegs; i++) // Load the actual data into MDTxData buffer - { - tx_buf[endIdx++] = (Holding_Registers_Database[startAddr] >> 8) & 0xFF; // extract the higher byte - tx_buf[endIdx++] = (Holding_Registers_Database[startAddr]) & 0xFF; // extract the lower byte - startAddr++; // increment the register address - } - - return endIdx; -} - -uint8_t writeSingleReg_rtu(uint8_t *rx_buf, uint8_t *tx_buf) { - uint16_t startAddr = ((rx_buf[2] << 8) | rx_buf[3]); // start Register Address - uint16_t this_value = (rx_buf[4] << 8) | rx_buf[5]; - Holding_Registers_Database[startAddr] = this_value; - memcpy(tx_buf, rx_buf, 6); - return 6; -} - -uint8_t writeMultiRegs_rtu(uint8_t *rx_buf, uint8_t *tx_buf) { - uint16_t startAddr = ((rx_buf[2] << 8) | rx_buf[3]); // start Register Address - uint16_t numRegs = ((rx_buf[4] << 8) | rx_buf[5]); // number to registers master has requested - - int endIdx = 7; // we need to keep track of index in MDRxData - for (int i = 0; i < numRegs; i++) { - uint16_t highByte = rx_buf[endIdx++] << 8; - uint16_t lowByte = rx_buf[endIdx++]; - Holding_Registers_Database[startAddr++] = highByte | lowByte; - } - - memcpy(tx_buf, rx_buf, 6); - return 6; -} - -uint8_t handleModbusRtu(uint8_t *rx_buf, uint8_t *tx_buf) { -// if(huart == &huart3){ -// u232_ledcnt =0; -// }else if(huart == &huart4){ -// u485_ledcnt =0; -// } - switch (rx_buf[1]) { - case 0x03: - return readHoldingRegs_rtu(rx_buf, tx_buf); - break; - case 0x06: - return writeSingleReg_rtu(rx_buf, tx_buf); - break; - case 0x10: - return writeMultiRegs_rtu(rx_buf, tx_buf); - break; - default: - break; - } - return 0; -} -///////////////////////////////////////////↓485从站功能↓/////////////////////////////////////// -void handleModbusRtu_NEW(uint8_t *rx_buf, uint8_t *tx_buf, uint8_t rxSize, UART_HandleTypeDef *huart) { - uint8_t txSize; - uint16_t crc = crc16(rx_buf, rxSize - 2); - if (crc != ((rx_buf[rxSize - 2] << 8) | rx_buf[rxSize - 1])) { - txSize = 0; - } - if (rx_buf[0] == SLAVE_ID) { - tcp_ledcnt = 0; - switch (rx_buf[1]) { - case 0x03: - txSize = readHoldingRegs_rtu(rx_buf, tx_buf); - break; - case 0x06: - txSize = writeSingleReg_rtu(rx_buf, tx_buf); - break; - case 0x10: - txSize = writeMultiRegs_rtu(rx_buf, tx_buf); - break; - default: - break; - } - } - - if (txSize > 0) { - HAL_GPIO_WritePin(re485_GPIO_Port, re485_Pin, GPIO_PIN_SET); - crc = crc16(tx_buf, txSize); - tx_buf[txSize] = crc & 0xFF; - tx_buf[txSize + 1] = (crc >> 8) & 0xFF; - HAL_UART_Transmit_DMA(huart, tx_buf, txSize + 2); - - } else { - HAL_GPIO_WritePin(re485_GPIO_Port, re485_Pin, GPIO_PIN_RESET); - HAL_UARTEx_ReceiveToIdle_DMA(huart, rx_buf, 1024); - } -} -///////////////////////////////////////////↑485从站功能↑/////////////////////////////////////// -//extern uint8_t MDRxData[256]; -//extern uint8_t MDTxData[256]; -//extern UART_HandleTypeDef huart1; -//void modbusException (uint8_t exceptioncode) -//{ -// //| SLAVE_ID | FUNCTION_CODE | Exception code | CRC | -// //| 1 BYTE | 1 BYTE | 1 BYTE | 2 BYTES | -// -// MDTxData[0] = MDRxData[0]; // slave ID -// MDTxData[1] = MDRxData[1]|0x80; // adding 1 to the MSB of the function code -// MDTxData[2] = exceptioncode; // Load the Exception code -// sendData(MDTxData, 3); // send Data... CRC will be calculated in the function -//} -// -//void check_exception(uint16_t numRegs, uint16_t endAddr){ -// if ((numRegs<1)||(numRegs>125)) -// { -// modbusException (ILLEGAL_DATA_VALUE); -// return 0; -// } -// -// uint16_t endAddr = startAddr+numRegs-1; -// if (endAddr>999) -// { -// modbusException(ILLEGAL_DATA_ADDRESS); -// return 0; -// } -//} - -//void sendData (uint8_t *data, int size) -//{ -// // we will calculate the CRC in this function itself -// uint16_t crc = crc16(data, size); -// data[size] = crc&0xFF; -// data[size+1] = (crc>>8)&0xFF; -// HAL_UART_Transmit_DMA(&huart6, data, size+2); -//} -// -//void test_freq(void) -//{ -// if(test_idx>9998){ -// test_idx = 0; -// } -// Holding_Registers_Database[0] = test_idx; -// test_idx++; -//} -// -//void test_spi(uint16_t data){ -// Holding_Registers_Database[0] = data; -//} -// -//void set_holdR_data(uint16_t* data, uint8_t size) -//{ -// memcpy(Holding_Registers_Database, data, size); -// -//} -// -//void set_holdR_value(uint16_t idx, uint16_t value){ -// -// Holding_Registers_Database[idx] = value; -//} -// -//uint16_t get_holdR_value(uint16_t idx){ -// return Holding_Registers_Database[idx]; -//} -// -// -// -//float get_hold_float(uint8_t idx){ -// union FloatToBytes converter; -// uint16_t left = Holding_Registers_Database[idx]; -// uint16_t right = Holding_Registers_Database[idx+1]; -// converter.byteValues[0] = right; -// converter.byteValues[1] = right<<8; -// converter.byteValues[2] = left; -// converter.byteValues[3] = left<<8; -// return converter.floatValue; -//} -// -//void set_hold_float(uint8_t idx, float value){ -// union FloatToBytes converter; -// converter.floatValue = value; -// uint16_t highValue = (converter.byteValues[1] << 8) | converter.byteValues[0]; -// uint16_t lowValue = (converter.byteValues[3] << 8) | converter.byteValues[2]; -// Holding_Registers_Database[idx] = highValue; -// Holding_Registers_Database[idx+1] = lowValue; -//} -// -//void setup_defalut_values(float* default_values){ -// for(uint8_t i=0; i<7;i++){ -// union FloatToBytes converter; -// converter.floatValue = default_values[i]; -// uint16_t highValue = (converter.byteValues[1] << 8) | converter.byteValues[0]; -// uint16_t lowValue = (converter.byteValues[3] << 8) | converter.byteValues[2]; -// Holding_Registers_Database[i*2] = highValue; -// Holding_Registers_Database[i*2+1] = lowValue; -// } -// -//} -// -//void setup_default_uint16(uint16_t* default_values,uint8_t size){ -// for(uint8_t i=0; i125)) // maximum no. of Registers as per the PDF -// { -// modbusException (ILLEGAL_DATA_VALUE); // send an exception -// return 0; -// } -// -// uint16_t endAddr = startAddr+numRegs-1; // end Register -// if (endAddr>1000) -// { -// modbusException(ILLEGAL_DATA_ADDRESS); // send an exception -// return 0; -// } -// -// -// MDTxData[0] = SLAVE_ID; // slave ID -// MDTxData[1] = MDRxData[1]; // function code -// MDTxData[2] = numRegs*2; // Byte count -// int indx = 3; // we need to keep track of how many bytes has been stored in MDTxData Buffer -// -// for (int i=0; i>8)&0xFF; // extract the higher byte -// MDTxData[indx++] = (Holding_Registers_Database[startAddr])&0xFF; // extract the lower byte -// startAddr++; // increment the register address -// } -// -// sendData(MDTxData, indx); // send data... CRC will be calculated in the function itself -// -// return 1; // success -//} -// -//uint8_t readHoldingRegs_with_targetHuart (UART_HandleTypeDef *targetHuart) -//{ -// uint16_t startAddr = ((MDRxData[2]<<8)|MDRxData[3]); // start Register Address -// -// uint16_t numRegs = ((MDRxData[4]<<8)|MDRxData[5]); // number to registers master has requested -// if ((numRegs<1)||(numRegs>125)) // maximum no. of Registers as per the PDF -// { -// modbusException (ILLEGAL_DATA_VALUE); // send an exception -// return 0; -// } -// -// uint16_t endAddr = startAddr+numRegs-1; // end Register -// if (endAddr>1000) -// { -// modbusException(ILLEGAL_DATA_ADDRESS); // send an exception -// return 0; -// } -// -// -// MDTxData[0] = SLAVE_ID; // slave ID -// MDTxData[1] = MDRxData[1]; // function code -// MDTxData[2] = numRegs*2; // Byte count -// int indx = 3; // we need to keep track of how many bytes has been stored in MDTxData Buffer -// -// for (int i=0; i>8)&0xFF; // extract the higher byte -// MDTxData[indx++] = (Holding_Registers_Database[startAddr])&0xFF; // extract the lower byte -// startAddr++; // increment the register address -// } -// -// sendData_with_target_huart(MDTxData, indx, targetHuart); // send data... CRC will be calculated in the function itself -// -// return 1; // success -//} -// -// -//uint8_t readInputRegs (void) -//{ -// uint16_t startAddr = ((MDRxData[2]<<8)|MDRxData[3]); // start Register Address -// -// uint16_t numRegs = ((MDRxData[4]<<8)|MDRxData[5]); // number to registers master has requested -// if ((numRegs<1)||(numRegs>125)) // maximum no. of Registers as per the PDF -// { -// modbusException (ILLEGAL_DATA_VALUE); // send an exception -// return 0; -// } -// -// uint16_t endAddr = startAddr+numRegs-1; // end Register -// if (endAddr>49) // end Register can not be more than 49 as we only have record of 50 Registers in total -// { -// modbusException(ILLEGAL_DATA_ADDRESS); // send an exception -// return 0; -// } -// -// // Prepare MDTxData buffer -// -// //| SLAVE_ID | FUNCTION_CODE | BYTE COUNT | DATA | CRC | -// //| 1 BYTE | 1 BYTE | 1 BYTE | N*2 BYTES | 2 BYTES | -// -// MDTxData[0] = SLAVE_ID; // slave ID -// MDTxData[1] = MDRxData[1]; // function code -// MDTxData[2] = numRegs*2; // Byte count -// int indx = 3; // we need to keep track of how many bytes has been stored in MDTxData Buffer -// -// for (int i=0; i>8)&0xFF; // extract the higher byte -// MDTxData[indx++] = (Input_Registers_Database[startAddr])&0xFF; // extract the lower byte -// startAddr++; // increment the register address -// } -// -// sendData(MDTxData, indx); // send data... CRC will be calculated in the function itself -// return 1; // success -//} -// -//uint8_t writeHoldingRegs (void) -//{ -// uint16_t startAddr = ((MDRxData[2]<<8)|MDRxData[3]); // start Register Address -// -// uint16_t numRegs = ((MDRxData[4]<<8)|MDRxData[5]); // number to registers master has requested -// if ((numRegs<1)||(numRegs>123)) // maximum no. of Registers as per the PDF -// { -// modbusException (ILLEGAL_DATA_VALUE); // send an exception -// return 0; -// } -// -// uint16_t endAddr = startAddr+numRegs-1; // end Register -// if (endAddr>49) // end Register can not be more than 49 as we only have record of 50 Registers in total -// { -// modbusException(ILLEGAL_DATA_ADDRESS); // send an exception -// return 0; -// } -// -// /* start saving 16 bit data -// * Data starts from MDRxData[7] and we need to combine 2 bytes together -// * 16 bit Data = firstByte<<8|secondByte -// */ -// int indx = 7; // we need to keep track of index in MDRxData -// for (int i=0; i123)) // maximum no. of Registers as per the PDF -// { -// modbusException (ILLEGAL_DATA_VALUE); // send an exception -// return 0; -// } -// -// uint16_t endAddr = startAddr+numRegs-1; // end Register -// if (endAddr>49) // end Register can not be more than 49 as we only have record of 50 Registers in total -// { -// modbusException(ILLEGAL_DATA_ADDRESS); // send an exception -// return 0; -// } -// -// /* start saving 16 bit data -// * Data starts from MDRxData[7] and we need to combine 2 bytes together -// * 16 bit Data = firstByte<<8|secondByte -// */ -// int indx = 7; // we need to keep track of index in MDRxData -// for (int i=0; i999) // The Register Address can not be more than 49 as we only have record of 50 Registers in total -// { -// modbusException(ILLEGAL_DATA_ADDRESS); // send an exception -// return 0; -// } -// -// /* Save the 16 bit data -// * Data is the combination of 2 bytes, MDRxData[4] and MDRxData[5] -// */ -// uint16_t this_value = (MDRxData[4]<<8)|MDRxData[5]; -// Holding_Registers_Database[startAddr] = this_value; -// -// -//// if(startAddr==0){ -//// htim2.Instance->CCR1 = this_value; // 25-125 = 0-180 -//// } -// -// // Prepare Response -// -// //| SLAVE_ID | FUNCTION_CODE | Start Addr | Data | CRC | -// //| 1 BYTE | 1 BYTE | 2 BYTE | 2 BYTES | 2 BYTES | -// -// MDTxData[0] = SLAVE_ID; // slave ID -// MDTxData[1] = MDRxData[1]; // function code -// MDTxData[2] = MDRxData[2]; // Start Addr HIGH Byte -// MDTxData[3] = MDRxData[3]; // Start Addr LOW Byte -// MDTxData[4] = MDRxData[4]; // Reg Data HIGH Byte -// MDTxData[5] = MDRxData[5]; // Reg Data LOW Byte -// -// sendData(MDTxData, 6); // send data... CRC will be calculated in the function itself -// return 1; // success -//} -// -// -//uint8_t writeSingleReg_with_targetHuart (UART_HandleTypeDef *targetHuart) -//{ -// uint16_t startAddr = ((MDRxData[2]<<8)|MDRxData[3]); // start Register Address -// -// if (startAddr>999) // The Register Address can not be more than 49 as we only have record of 50 Registers in total -// { -// modbusException(ILLEGAL_DATA_ADDRESS); // send an exception -// return 0; -// } -// -// /* Save the 16 bit data -// * Data is the combination of 2 bytes, MDRxData[4] and MDRxData[5] -// */ -// uint16_t this_value = (MDRxData[4]<<8)|MDRxData[5]; -// Holding_Registers_Database[startAddr] = this_value; -// -// -//// if(startAddr==0){ -//// htim2.Instance->CCR1 = this_value; // 25-125 = 0-180 -//// } -// -// // Prepare Response -// -// //| SLAVE_ID | FUNCTION_CODE | Start Addr | Data | CRC | -// //| 1 BYTE | 1 BYTE | 2 BYTE | 2 BYTES | 2 BYTES | -// -// MDTxData[0] = SLAVE_ID; // slave ID -// MDTxData[1] = MDRxData[1]; // function code -// MDTxData[2] = MDRxData[2]; // Start Addr HIGH Byte -// MDTxData[3] = MDRxData[3]; // Start Addr LOW Byte -// MDTxData[4] = MDRxData[4]; // Reg Data HIGH Byte -// MDTxData[5] = MDRxData[5]; // Reg Data LOW Byte -// -// sendData_with_target_huart(MDTxData, 6, targetHuart); // send data... CRC will be calculated in the function itself -// return 1; // success -//} -// -// -//uint8_t readCoils (void) -//{ -// uint16_t startAddr = ((MDRxData[2]<<8)|MDRxData[3]); // start Coil Address -// -// uint16_t numCoils = ((MDRxData[4]<<8)|MDRxData[5]); // number to coils master has requested -// if ((numCoils<1)||(numCoils>2000)) // maximum no. of coils as per the PDF -// { -// modbusException (ILLEGAL_DATA_VALUE); // send an exception -// return 0; -// } -// -// uint16_t endAddr = startAddr+numCoils-1; // Last coils address -// if (endAddr>199) // end coil can not be more than 199 as we only have record of 200 (0-199) coils in total -// { -// modbusException(ILLEGAL_DATA_ADDRESS); // send an exception -// return 0; -// } -// -// -// //reset MDTxData buffer -// memset (MDTxData, '\0', 256); -// -// // Prepare MDTxData buffer -// -// //| SLAVE_ID | FUNCTION_CODE | BYTE COUNT | DATA | CRC | -// //| 1 BYTE | 1 BYTE | 1 BYTE | N*2 BYTES | 2 BYTES | -// -// MDTxData[0] = SLAVE_ID; // slave ID -// MDTxData[1] = MDRxData[1]; // function code -// MDTxData[2] = (numCoils/8) + ((numCoils%8)>0 ? 1:0); // Byte count -// int indx = 3; // we need to keep track of how many bytes has been stored in MDTxData Buffer -// -// /* The approach is simple. We will read 1 bit at a time and store them in the Txdata buffer. -// * First find the offset in the first byte we read from, for eg- if the start coil is 13, -// * we will read from database[1] with an offset of 5. This bit will be stored in the MDTxData[0] at 0th position. -// * Then we will keep shifting the database[1] to the right and read the bits. -// * Once the bitposition has crossed the value 7, we will increment the startbyte -// * When the indxposition exceeds 7, we increment the indx variable, so to copy into the next byte of the MDTxData -// * This keeps going until the number of coils required have been copied -// */ -// int startByte = startAddr/8; // which byte we have to start extracting the data from -// uint16_t bitPosition = startAddr%8; // The shift position in the first byte -// int indxPosition = 0; // The shift position in the current indx of the MDTxData buffer -// -// // Load the actual data into MDTxData buffer -// for (int i=0; i> bitPosition) &0x01) << indxPosition; -// indxPosition++; bitPosition++; -// if (indxPosition>7) // if the indxposition exceeds 7, we have to copy the data into the next byte position -// { -// indxPosition = 0; -// indx++; -// } -// if (bitPosition>7) // if the bitposition exceeds 7, we have to increment the startbyte -// { -// bitPosition=0; -// startByte++; -// } -// } -// -// if (numCoils%8 != 0)indx++; // increment the indx variable, only if the numcoils is not a multiple of 8 -// sendData(MDTxData, indx); // send data... CRC will be calculated in the function itself -// return 1; // success -//} -// -// -//uint8_t readInputs (void) -//{ -// uint16_t startAddr = ((MDRxData[2]<<8)|MDRxData[3]); // start Register Address -// -// uint16_t numCoils = ((MDRxData[4]<<8)|MDRxData[5]); // number to coils master has requested -// if ((numCoils<1)||(numCoils>2000)) // maximum no. of coils as per the PDF -// { -// modbusException (ILLEGAL_DATA_VALUE); // send an exception -// return 0; -// } -// -// uint16_t endAddr = startAddr+numCoils-1; // Last coils address -// if (endAddr>199) // end coil can not be more than 199 as we only have record of 200 (0-199) coils in total -// { -// modbusException(ILLEGAL_DATA_ADDRESS); // send an exception -// return 0; -// } -// -// -// //reset MDTxData buffer -// memset (MDTxData, '\0', 256); -// -// // Prepare MDTxData buffer -// -// //| SLAVE_ID | FUNCTION_CODE | BYTE COUNT | DATA | CRC | -// //| 1 BYTE | 1 BYTE | 1 BYTE | N*2 BYTES | 2 BYTES | -// -// MDTxData[0] = SLAVE_ID; // slave ID -// MDTxData[1] = MDRxData[1]; // function code -// MDTxData[2] = (numCoils/8) + ((numCoils%8)>0 ? 1:0); // Byte count -// int indx = 3; // we need to keep track of how many bytes has been stored in MDTxData Buffer -// -// /* The approach is simple. We will read 1 bit at a time and store them in the Txdata buffer. -// * First find the offset in the first byte we read from, for eg- if the start coil is 13, -// * we will read from database[1] with an offset of 5. This bit will be stored in the MDTxData[0] at 0th position. -// * Then we will keep shifting the database[1] to the right and read the bits. -// * Once the bitposition has crossed the value 7, we will increment the startbyte -// * When the indxposition exceeds 7, we increment the indx variable, so to copy into the next byte of the MDTxData -// * This keeps going until the number of coils required have been copied -// */ -// int startByte = startAddr/8; // which byte we have to start extracting the data from -// uint16_t bitPosition = startAddr%8; // The shift position in the first byte -// int indxPosition = 0; // The shift position in the current indx of the MDTxData buffer -// -// // Load the actual data into MDTxData buffer -// for (int i=0; i> bitPosition) &0x01) << indxPosition; -// indxPosition++; bitPosition++; -// if (indxPosition>7) // if the indxposition exceeds 7, we have to copy the data into the next byte position -// { -// indxPosition = 0; -// indx++; -// } -// if (bitPosition>7) // if the bitposition exceeds 7, we have to increment the startbyte -// { -// bitPosition=0; -// startByte++; -// } -// } -// -// if (numCoils%8 != 0)indx++; // increment the indx variable, only if the numcoils is not a multiple of 8 -// sendData(MDTxData, indx); // send data... CRC will be calculated in the function itself -// return 1; // success -//} -// -// -//uint8_t writeSingleCoil (void) -//{ -// uint16_t startAddr = ((MDRxData[2]<<8)|MDRxData[3]); // start Coil Address -// -// if (startAddr>199) // The Coil Address can not be more than 199 as we only have record of 200 Coils in total -// { -// modbusException(ILLEGAL_DATA_ADDRESS); // send an exception -// return 0; -// } -// -// /* Calculation for the bit in the database, where the modification will be done */ -// int startByte = startAddr/8; // which byte we have to start writing the data into -// uint16_t bitPosition = startAddr%8; // The shift position in the first byte -// -// -// /* The next 2 bytes in the MDRxData determines the state of the coil -// * A value of FF 00 hex requests the coil to be ON. -// * A value of 00 00 requests it to be OFF. -// * All other values are illegal and will not affect the coil. -// */ -// -// if ((MDRxData[4] == 0xFF) && (MDRxData[5] == 0x00)) -// { -// Coils_Database[startByte] |= 1<1968)) // maximum no. of coils as per the PDF -// { -// modbusException (ILLEGAL_DATA_VALUE); // send an exception -// return 0; -// } -// -// uint16_t endAddr = startAddr+numCoils-1; // Last coils address -// if (endAddr>199) // end coil can not be more than 199 as we only have record of 200 (0-199) coils in total -// { -// modbusException(ILLEGAL_DATA_ADDRESS); // send an exception -// return 0; -// } -// -// /* Calculation for the bit in the database, where the modification will be done */ -// int startByte = startAddr/8; // which byte we have to start writing the data into -// uint16_t bitPosition = startAddr%8; // The shift position in the first byte -// int indxPosition = 0; // The shift position in the current indx of the MDRxData buffer -// -// int indx = 7; // we need to keep track of index in MDRxData -// -// /* The approach is simple. We will read 1 bit (starting from the very first bit in the MDRxData Buffer) -// * at a time and store them in the Database. -// * First find the offset in the first byte we write into, for eg- if the start coil is 13, -// * we will Write into database[1] with an offset of 5. This bit is read from the MDRxData[indx] at 0th indxposition. -// * Then we will keep shifting the MDRxData[indx] to the right and read the bits. -// * Once the bitposition has crossed the value 7, we will increment the startbyte and start modifying the next byte in the database -// * When the indxposition exceeds 7, we increment the indx variable, so to copy from the next byte of the MDRxData -// * This keeps going until the number of coils required have been modified -// */ -// -// // Modify the bits as per the Byte received -// for (int i=0; i>indxPosition)&0x01) == 1) -// { -// Coils_Database[startByte] |= 1<7) // if the indxposition exceeds 7, we have to copy the data into the next byte position -// { -// indxPosition = 0; -// indx++; -// } -// if (bitPosition>7) // if the bitposition exceeds 7, we have to increment the startbyte -// { -// bitPosition=0; -// startByte++; -// } -// } -// -// // Prepare Response -// -// //| SLAVE_ID | FUNCTION_CODE | Start Addr | Data | CRC | -// //| 1 BYTE | 1 BYTE | 2 BYTE | 2 BYTES | 2 BYTES | -// -// MDTxData[0] = SLAVE_ID; // slave ID -// MDTxData[1] = MDRxData[1]; // function code -// MDTxData[2] = MDRxData[2]; // Start Addr HIGH Byte -// MDTxData[3] = MDRxData[3]; // Start Addr LOW Byte -// MDTxData[4] = MDRxData[4]; // num of coils HIGH Byte -// MDTxData[5] = MDRxData[5]; // num of coils LOW Byte -// -// sendData(MDTxData, 6); // send data... CRC will be calculated in the function itself -// return 1; // success -//} -// -// -// - -// -//uint8_t modbus0x06_tcp (uint8_t* rx_buf) -//{ -// uint16_t startAddr = ((rx_buf[8]<<8)|rx_buf[9]); -// uint8_t left = rx_buf[10]; -// uint8_t right = rx_buf[11]; -// uint16_t this_value = (left<<8)|right; -// Holding_Registers_Database[startAddr] = this_value; -// return 1; -//} diff --git a/comm/modbusSlave.h b/comm/modbusSlave.h deleted file mode 100644 index bcdc22a..0000000 --- a/comm/modbusSlave.h +++ /dev/null @@ -1,38 +0,0 @@ -/* - * modbusSlave.h - * - * Created on: Oct 27, 2022 - * Author: controllerstech.com - */ - -#ifndef INC_MODBUSSLAVE_H_ -#define INC_MODBUSSLAVE_H_ - -#include "main.h" - -typedef union { - float value; - uint16_t u16[2]; -} FloatToUint16; -uint32_t get_register_u32(uint16_t index); -void set_slaveid(uint8_t val); -uint8_t get_slaveid(); -void set_register_range(uint16_t start, uint16_t size, uint16_t *buf); -void set_register_range_u8(uint16_t start, uint16_t size, uint8_t *buf); -void set_register_u32(uint16_t index, uint32_t value); -void set_register(uint16_t index, uint16_t value); -void set_register_float(uint16_t index, float value); - -uint16_t get_register(uint16_t index); -void get_register_range(uint16_t start, uint16_t size, uint16_t *buf); -void get_register_range_to_u8(uint16_t start, uint16_t count, uint8_t *buf); -float get_register_float(uint16_t index); - -uint8_t handleModbusRtu(uint8_t *rx_buf, uint8_t *tx_buf); -void handleModbusRtu_NEW(uint8_t *rx_buf, uint8_t *tx_buf, uint8_t rxSize, UART_HandleTypeDef *huart); -uint16_t handleModbusTcp(uint8_t* rx_buf, uint8_t* tx_buf); -uint16_t readHoldingRegs_tcp (uint8_t* rx_buf, uint8_t* tx_buf); -uint16_t writeSingleReg_tcp (uint8_t* rx_buf, uint8_t* tx_buf); -uint16_t writeMultiRegs_tcp (uint8_t* rx_buf, uint8_t* tx_buf); - -#endif diff --git a/comm/protocols/finsudpmaster.c b/comm/protocols/finsudpmaster.c deleted file mode 100644 index bada5ed..0000000 --- a/comm/protocols/finsudpmaster.c +++ /dev/null @@ -1,239 +0,0 @@ -/* - * @file finsudpmaster.c - * @brief 欧姆龙FINS UDP客户端主站实现 - * - * 轮询机制: - * - myRtumSTIdx: 0~19 轮转索引,对应 myRtumST[20] - * - **奇数索引**: 读操作,从PLC读取数据存储到 1400 + (idx*20) + i - * - **偶数索引**: 写操作,从 1400 + (idx*20) + i 读取数据写入PLC - * - 每次主循环调用 update_timeout_fins() 递增超时计数 - * - 超时计数 > 500 时发送下一帧,接收后重置超时为 490 - */ - -#include "finsudpmaster.h" -#include "socket.h" -#include "wizchip_conf.h" -#include "rtuMaster.h" -#include "main.h" -#include - -// ============================================================================ -// 全局变量 -// ============================================================================ - -uint8_t myRtumSTIdx = 0; // 轮询索引 (0~19) -uint8_t omrfins_buf[1024]; // FINS收发缓冲区 (最大1024字节) - -// 读响应固定头,只有匹配这个头才会被处理 -// 格式: ICV(2) + RSV(2) + GATEWAY(1) + len(2) + cmd(1) + ... -uint8_t readrx[14] = { - 0xc0, 0x00, 0x02, 0x00, 0x0A, 0x00, 0x00, - 0x01, 0x00, 0x00, 0x01, 0x01, 0x00, 0x40 -}; - -// 预定义的请求模板 -uint8_t send_read[18] = { // 读请求模板 - 0x80, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x0a, - 0x00, 0x00, 0x01, 0x01, 0x82, 0x00, 0x64, 0x00, - 0x00, 0x0a -}; -uint8_t write_send[58] = { // 写请求模板 (最大20点 = 18 + 20*2 = 58字节) - 0x80, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x0b, - 0x00, 0x00, 0x01, 0x02, 0x82, 0x00, 0x64, 0x00, - 0x00, 0x02 -}; - -uint16_t fins_timeout = 0; // 超时计数,由主循环递增 - -// ============================================================================ -// 公共接口 -// ============================================================================ - -/** - * @brief 处理接收到的FINS读响应 - * @param size: 接收数据长度 - * @param local_node: 本地节点号,填充到响应头比较 - * @return true: 处理成功,false: 不是有效的读响应 - * @note 只有读响应需要存储数据,写响应不需要处理 - */ -_Bool handleReadRecv(uint16_t size, uint16_t local_node) { - // 1. 设置本地节点号,然后比对前14字节确认是读响应 - readrx[4] = (uint8_t)local_node; - for (int i = 0; i < 14; i++) { - if (readrx[i] != omrfins_buf[i]) { - return false; // 不匹配,不是读响应 - } - } - - // 2. 获取上一次发送对应的索引 - // 因为发送后索引立即+1,所以响应对应发送前的索引 - uint16_t prevIdx; - if (myRtumSTIdx == 0) { - prevIdx = 19; // 绕回 - } else { - prevIdx = myRtumSTIdx - 1; - } - - // 3. 验证索引: 读必须是奇数索引 - if ((prevIdx % 2 == 1) != (memcmp(readrx, readrx, 7) == 0)) { - return false; // 不匹配,丢弃 - } - - // 4. 获取参数,检查长度合法性 - uint16_t pointNum = get_register(myRtumST[prevIdx].size); - if (pointNum > 20 || pointNum * 2 + 14 != size) { - return false; // 长度不匹配或超出最大限制,丢弃 - } - - // 5. 解析响应数据,存储到寄存器映射 - // FINS使用大端序: 高字节在前,低字节在后 - for (int i = 0; i < pointNum; i++) { - uint8_t byte_h = omrfins_buf[i * 2 + 14]; - uint8_t byte_l = omrfins_buf[i * 2 + 15]; - uint16_t value = ((uint16_t)byte_h << 8) | byte_l; - // 存储地址: 1400 + (索引*20) + 偏移 - set_register(1400 + (20 * prevIdx) + i, value); - } - - return true; -} - -/** - * @brief 构建FINS请求帧 - * @param local_node: 本地节点号 - * @return 发送长度,0表示不发送(参数非法) - * @note 奇数索引 -> 读操作,偶数索引 -> 写操作 - */ -uint16_t handleSend(uint16_t local_node) { - uint16_t sendsize = 0; - uint16_t slave_id = get_register(myRtumST[myRtumSTIdx].slave_id); - uint16_t plc_address = get_register(myRtumST[myRtumSTIdx].plc_address); - uint16_t pointNum = get_register(myRtumST[myRtumSTIdx].size); - - // 参数合法性检查 - if (slave_id == 0 || slave_id >= 127 || pointNum == 0 || pointNum > 20) { - return 0; - } - - // ========== 奇数索引: 读操作 ========== - if (myRtumSTIdx % 2 == 1) { - send_read[7] = (uint8_t)local_node; - send_read[13] = (plc_address >> 8) & 0xFF; - send_read[14] = plc_address & 0xFF; - send_read[17] = (uint8_t)pointNum; - sendsize = 18; // 读请求固定18字节 - - // 拷贝到发送缓冲区,带边界检查 - for (int i = 0; i < sendsize && i < sizeof(omrfins_buf); i++) { - omrfins_buf[i] = send_read[i]; - } - } - // ========== 偶数索引: 写操作 ========== - else { - sendsize = (pointNum * 2) + 18; - // 边界检查,防止越界 - if (sendsize > sizeof(write_send) || sendsize > sizeof(omrfins_buf)) { - return 0; - } - - write_send[7] = (uint8_t)local_node; - write_send[13] = (plc_address >> 8) & 0xFF; - write_send[14] = plc_address & 0xFF; - write_send[17] = (uint8_t)pointNum; - - // 填充数据,FINS大端序: 高字节在前 - for (int i = 0; i < pointNum; i++) { - uint16_t value = get_register(1400 + (20 * myRtumSTIdx) + i); - write_send[i * 2 + 18] = (value >> 8) & 0xFF; - write_send[i * 2 + 19] = value & 0xFF; - } - - // 拷贝到发送缓冲区 - for (int i = 0; i < sendsize; i++) { - omrfins_buf[i] = write_send[i]; - } - } - - // 索引轮转,下次处理下一个通道 - myRtumSTIdx = (myRtumSTIdx + 1) % 20; - return sendsize; -} - -/** - * @brief 超时计数,由主循环每次调用递增 - */ -void update_timeout_fins(void) { - if (fins_timeout < 0xffff) { - fins_timeout++; - } -} - -/** - * @brief FINS UDP客户端主函数,W5500socket主循环处理 - * @param sn: W5500 socket编号 - * @param destip: 目标IP地址 - * @param destport: 目标端口 - * @param local_node: 本地节点号 - * @return 0/正表示正常,负表示错误 - */ -int32_t loopback_udpc_omrfins(uint8_t sn, uint8_t *destip, uint16_t destport, uint16_t local_node) { - int32_t ret; - uint16_t size = 0, sentsize = 0; - static uint16_t any_port = 50000; // 本地端口,自动递增 - - switch (getSn_SR(sn)) { - // ========== socket已连接: 收发数据 ========== - case SOCK_UDP: - // 1. 接收响应 - if ((size = getSn_RX_RSR(sn)) > 0) { - // 边界保护,不超过缓冲区 - if (size > sizeof(omrfins_buf)) { - size = sizeof(omrfins_buf); - } - ret = recvfrom(sn, omrfins_buf, size, destip, (uint16_t*) &destport); - if (ret <= 0) { - return ret; - } else { - comm_count++; - handleReadRecv(ret, local_node); // 处理响应 - fins_timeout = 490; // 重置超时 - } - } - - // 2. 超时到了,发送下一个请求 - size = 0; - if (fins_timeout > 500) { - size = handleSend(local_node); // 构建请求 - if (size == 0) { - fins_timeout = 1000; // 参数非法,等待下一次 - } - } - - // 3. 发送请求(分片发送,直到发完) - sentsize = 0; - while (size != 0 && sentsize != size) { - ret = sendto(sn, omrfins_buf + sentsize, size - sentsize, destip, destport); - if (ret < 0) { - return ret; - } - sentsize += ret; - } - break; - - // ========== socket未打开: 新建socket ========== - case SOCK_CLOSED: - // 端口绕回,超过最大值后重置 - if (any_port == 0xffff) { - any_port = 50000; - } - if ((ret = socket(sn, Sn_MR_UDP, any_port++, 0x00)) != sn) { - return ret; - } - break; - - default: - break; - } - - return 1; -} diff --git a/comm/protocols/modbustcpslave.c b/comm/protocols/modbustcpslave.c deleted file mode 100644 index 3cf83af..0000000 --- a/comm/protocols/modbustcpslave.c +++ /dev/null @@ -1,317 +0,0 @@ -/* - * @file modbustcpslave.c - * @brief Modbus TCP从站服务 + Modbus TCP转RTU转发 - */ - -#include "modbustcpslave.h" -#include "socket.h" -#include "wizchip_conf.h" -#include "modbusSlave.h" -#include "modbus_crc.h" -#include "usart.h" -#include -#include "gpio.h" - -// ============================================================================ -// 全局变量 -// ============================================================================ - -uint8_t loopback_tcps_modbus_rxbuf[1024]; -uint8_t loopback_tcps_modbus_txbuf[1024]; - -// ============================================================================ -// 工具函数 -// ============================================================================ - -/** - * @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) { - // TCP长度字段 - 去掉MBAP头中的UnitID之前的长度 - uint16_t len = ((tcp_buf[4] << 8) | tcp_buf[5]) - 1; - // 从UnitID开始拷贝 - memcpy(rtu_buf, &tcp_buf[6], len + 1); - // 计算CRC16并添加到末尾 - uint16_t crc = crc16(rtu_buf, len + 1); - rtu_buf[len + 1] = crc & 0xFF; - rtu_buf[len + 2] = (crc >> 8) & 0xFF; - return len + 3; // 返回RTU总长度 -} - -/** - * @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) { - // 校验CRC - uint16_t crc_calc = crc16(rtu_buf, rtu_len - 2); - uint16_t crc_recv = rtu_buf[rtu_len - 2] | (rtu_buf[rtu_len - 1] << 8); - if (crc_calc != crc_recv) { - return 0; // CRC错误 - } - - // 拷贝原MBAP头 - memcpy(tcp_buf, rx_buf, 6); - // Unit ID - tcp_buf[6] = rtu_buf[0]; - // 功能码+数据 - memcpy(&tcp_buf[7], &rtu_buf[1], rtu_len - 3); - - // 设置长度 - uint16_t pdu_len = rtu_len - 3; - uint16_t mbap_len = pdu_len + 1; // +1 包含UnitID - tcp_buf[4] = (mbap_len >> 8) & 0xFF; - tcp_buf[5] = mbap_len & 0xFF; - - return 7 + pdu_len; // MBAP(7) + PDU -} - -// ============================================================================ -// 状态机定义 -// ============================================================================ - -enum { - STATE_IDLE, // 空闲,等待TCP请求 - STATE_WAIT_RTU // 已经转发RTU,等待RS485响应 -} modbus_state = STATE_IDLE; - -// ============================================================================ -// 公共接口 -// ============================================================================ - -/** - * @brief Modbus TCP服务主函数,W5500socket主循环处理 - * @param sn: socket编号 - * @param port: 监听端口 (通常502) - * @return 0/正表示正常,负表示错误 - */ -int32_t loopback_tcps_modbus(uint8_t sn, uint16_t port) { - int32_t ret; - uint16_t size = 0, sentsize = 0; - -#ifdef _LOOPBACK_DEBUG_ - uint8_t destip[4]; - uint16_t destport; -#endif - - switch (getSn_SR(sn)) { - case SOCK_ESTABLISHED: - if (getSn_IR(sn) & Sn_IR_CON) { -#ifdef _LOOPBACK_DEBUG_ - getSn_DIPR(sn, destip); - destport = getSn_DPORT(sn); - printf("%d:Connected - %d.%d.%d.%d : %d\r\n", sn, destip[0], - destip[1], destip[2], destip[3], destport); -#endif - setSn_IR(sn, Sn_IR_CON); - } - - // 接收请求 - if ((size = getSn_RX_RSR(sn)) > 0) { - if (size > DATA_BUF_SIZE) { - size = DATA_BUF_SIZE; - } - ret = recv(sn, loopback_tcps_modbus_rxbuf, size); - if (ret <= 0) { - return ret; - } - - // 处理Modbus TCP请求 - uint16_t rxbuf_size = handleModbusTcp(loopback_tcps_modbus_rxbuf, loopback_tcps_modbus_txbuf); - if (rxbuf_size > 0) { - sentsize = 0; - // 分片发送直到完成 - while (rxbuf_size != sentsize) { - ret = send(sn, loopback_tcps_modbus_txbuf + sentsize, rxbuf_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:Listen, TCP server loopback, port [%d]\r\n", sn, port); -#endif - if ((ret = listen(sn)) != SOCK_OK) { - return ret; - } - break; - - case SOCK_CLOSED: -#ifdef _LOOPBACK_DEBUG_ - //printf("%d:TCP server loopback start\r\n",sn); -#endif - if ((ret = socket(sn, Sn_MR_TCP, port, 0x00)) != sn) { - return ret; - } -#ifdef _LOOPBACK_DEBUG_ - //printf("%d:Socket opened\r\n",sn); -#endif - break; - - default: - break; - } - return 1; -} - -/** - * @brief Modbus TCP转RTU转发,TCP请求转RS485RTU,RTU响应转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) { - int32_t ret; - uint16_t size = 0, sentsize = 0; - -#ifdef _LOOPBACK_DEBUG_ - uint8_t destip[4]; - uint16_t destport; -#endif - - switch (getSn_SR(sn)) { - case SOCK_ESTABLISHED: - if (getSn_IR(sn) & Sn_IR_CON) { -#ifdef _LOOPBACK_DEBUG_ - getSn_DIPR(sn, destip); - destport = getSn_DPORT(sn); - printf("%d:Connected - %d.%d.%d.%d : %d\r\n", sn, destip[0], destip[1], destip[2], - destip[3], destport); -#endif - setSn_IR(sn, Sn_IR_CON); - } - - uint16_t rxbuf_size = 0; - uint8_t sendbuf[1024]; - - switch (modbus_state) { - case STATE_WAIT_RTU: - // RTU响应接收完成,转TCP返回 - if (rtu_rx->done) { - rxbuf_size = rtu_to_tcp(rtu_rx->buf, sendbuf, rtu_rx->size, buf); - } - // 超时也回到空闲 - if (rtu_rx->done || *timeout > 1000) { - rtu_rx->done = 0; - modbus_state = STATE_IDLE; - } - // 同时检查是否有新的TCP请求 - if ((size = getSn_RX_RSR(sn)) > 0) { - ret = recv(sn, buf, size); - if (ret <= 0) { - return ret; - } - } - break; - - case STATE_IDLE: - if ((size = getSn_RX_RSR(sn)) > 0) { - if (size > DATA_BUF_SIZE) { - size = DATA_BUF_SIZE; - } - ret = recv(sn, buf, size); - if (ret <= 0) { - return ret; - } - - // UnitID匹配本地从站地址,本地处理 - if (buf[6] == get_slaveid()) { - rxbuf_size = handleModbusTcp(buf, sendbuf); - } - // 不匹配,转发到RS485RTU - else { - uint8_t rtu_tx[256]; - uint16_t rtu_tx_len = tcp_to_rtu(buf, rtu_tx); - RE_SET; // 485芯片设置为发送 - HAL_UART_Transmit_DMA(&huart1, rtu_tx, rtu_tx_len); - *timeout = 0; - rtu_rx->done = 0; - modbus_state = STATE_WAIT_RTU; - } - } - break; - - default: - break; - } - - // 发送响应 - if (rxbuf_size > 0) { - sentsize = 0; - while (rxbuf_size != sentsize) { - ret = send(sn, sendbuf + sentsize, rxbuf_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:Listen, TCP server loopback, port [%d]\r\n", sn, port); -#endif - if ((ret = listen(sn)) != SOCK_OK) { - return ret; - } - break; - - case SOCK_CLOSED: -#ifdef _LOOPBACK_DEBUG_ - //printf("%d:TCP server loopback start\r\n",sn); -#endif - if ((ret = socket(sn, Sn_MR_TCP, port, 0x00)) != sn) { - return ret; - } -#ifdef _LOOPBACK_DEBUG_ - //printf("%d:Socket opened\r\n",sn); -#endif - break; - - default: - break; - } - return 1; -} diff --git a/comm/protocols/modbustcpslave.h b/comm/protocols/modbustcpslave.h deleted file mode 100644 index 7b0ac18..0000000 --- a/comm/protocols/modbustcpslave.h +++ /dev/null @@ -1,82 +0,0 @@ -/** - * @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 diff --git a/comm/protocols/s7tcpmaster.c b/comm/protocols/s7tcpmaster.c deleted file mode 100644 index 2cc538d..0000000 --- a/comm/protocols/s7tcpmaster.c +++ /dev/null @@ -1,438 +0,0 @@ -/* - * @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 - * - 需要先建立TCP连接,然后完成COTP连接协商和S7Comm参数协商 - * - 协商完成后进入正常轮询读写 - */ - -#include "s7tcpmaster.h" -#include "socket.h" -#include "wizchip_conf.h" -#include "rtuMaster.h" -#include "main.h" -#include - -// ============================================================================ -// 结构体定义 -// ============================================================================ - -// 24位大端存储 -typedef union { - uint8_t bytes[3]; - struct { - uint8_t byte0; // 最高字节 - uint8_t byte1; // 中间字节 - uint8_t byte2; // 最低字节 - }; -} s7_uint24_t; - -// 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]; - s7_uint24_t start_address; - }; -} 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]; - s7_uint24_t start_address; - uint8_t padding5[2]; - uint8_t databyte_size_t8[2]; - uint8_t data[800]; - }; -} s7WriteFrame; - -// ============================================================================ -// 全局变量 -// ============================================================================ - -uint8_t s7_txbuf[1024]; // 发送缓冲区 -uint8_t s7_rxbuf[1024]; // 接收缓冲区 -uint16_t s7_idx = 0; // 轮询索引 (0~19,和FINS/SLMP一致) -uint16_t s7_curr_idx; // 当前处理的索引 -uint16_t s7_addr; // 当前读写地址 -uint16_t s7_size; // 当前读写点数 -uint16_t s7Timegap = 0; // 超时计数 -uint8_t s7_rx_done = 1; -uint8_t s7_comm_step = 0; // 协商步骤: 0=发送connect, 1=发送comm-set, 2=读写轮询 -uint8_t s7_read_write_flag = 0; // 0=读,1=写 - -// 预定义的协商报文 -uint8_t s7_comm1[] = { 0x03, 0x00, 0x00, 0x16, 0x11, 0xE0, 0x00, 0x00, 0x00, 0x01, 0x00, 0xC0, 0x01, 0x0A, 0xC1, 0x02, 0x01, 0x00, 0xC2, 0x02, 0x03, 0x02 }; -uint8_t s7_comm2[] = { 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 }; -uint8_t s7_read[] = { 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 }; -uint8_t s7_write[] = { 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, 0xff, 0x00, 0xff, 0x00, 0xff }; - -uint16_t s7_comm1_size = sizeof(s7_comm1); -uint16_t s7_comm2_size = sizeof(s7_comm2); -uint16_t s7_read_size = sizeof(s7_read); -uint16_t s7_write_size = sizeof(s7_write); - -// 静态初始化读写帧 -s7ReadFrame s7_readframe = { - .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 } -}; - -s7WriteFrame s7_writeframe = { - .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 } -}; - -uint8_t s7_write_to_buffer[1024] = { 0 }; - -// ============================================================================ -// 内部工具函数 -// ============================================================================ - -// 大端转换16位 -static void s7_to_big_endian_16(uint16_t value, uint8_t *dest) { - dest[0] = (uint8_t)(value >> 8); // 高字节在前 - dest[1] = (uint8_t)(value & 0xFF); // 低字节在后 -} - -// 大端转换24位 -static void s7_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); // 最低字节 -} - -// ============================================================================ -// 公共接口 -// ============================================================================ - -/** - * @brief 准备写帧,填充数据 - * @param writebyte_size: 写字节数 - * @return 帧长度 - */ -static uint16_t s7_prepare_write_frame(uint16_t db_id, uint32_t start_addr, uint16_t writebyte_size) { - if (writebyte_size == 0) { - return 0; - } - - uint16_t frame_size = 35 + writebyte_size; - s7_to_big_endian_16(frame_size, s7_writeframe.frame_size); - s7_to_big_endian_16(4 + writebyte_size, s7_writeframe.dataframe_size); - s7_to_big_endian_16(writebyte_size, s7_writeframe.data_size); - s7_to_big_endian_16(db_id, s7_writeframe.db_id); - s7_to_big_endian_24(start_addr * 8, s7_writeframe.start_address); - s7_to_big_endian_16(writebyte_size * 8, s7_writeframe.databyte_size_t8); - - // 拷贝数据到frame - for (uint16_t i = 0; i < writebyte_size; i++) { - s7_writeframe.data[i] = s7_write_to_buffer[i]; - } - - return frame_size; -} - -/** - * @brief 处理接收到的S7响应 - * @param size: 接收长度 - * @return true: 处理成功,false: 不是有效的读响应 - */ -_Bool s7_handle_recv(uint16_t size, uint16_t *byte_offset) { - // 协商阶段不需要处理 - if (s7_comm_step < 2) { - return true; - } - - // 轮询阶段,只有读响应需要存储数据 - if (s7_read_write_flag == 1) { - return true; // 写响应不需要处理 - } - - // 检查长度,最小读响应长度至少27字节 - if (size < 27) { - return false; - } - - uint16_t prevIdx; - if (s7_idx == 0) { - prevIdx = 19; - } else { - prevIdx = s7_idx - 1; - } - - // 验证索引:读必须是奇数 - if (prevIdx % 2 != 1) { - return false; - } - - uint16_t reg_count = get_register(myRtumST[prevIdx].size); - // 每个寄存器2字节 - uint16_t byte_count = reg_count * 2; - - // 存储数据:大端?不对,S7读回来是大端,每个寄存器两个字节高字节在前 - // 存储到寄存器映射,我们使用little-endian存储,所以交换顺序 - for (uint16_t i = 0; i < reg_count; i++) { - if (*byte_offset + 25 + i*2 + 1 >= size) { - break; // 超出接收长度,停止 - } - uint8_t byte_h = s7_rxbuf[25 + i*2 + *byte_offset]; - uint8_t byte_l = s7_rxbuf[25 + i*2 + 1 + *byte_offset]; - if (get_register(1004) == 10) { - // 字节序交换 - set_register(1000 + (20 * prevIdx) + i, (byte_l) | (byte_h << 8)); - } else { - // 原始大端 - set_register(1000 + (20 * prevIdx) + i, (byte_h << 8) | byte_l); - } - } - return true; -} - -/** - * @brief 构建S7请求帧,返回发送长度 - * @return 发送长度,0表示不发送 - */ -uint16_t s7_build_send(void) { - uint16_t sendsize = 0; - - // 协商阶段,先走连接协商 - if (s7_comm_step == 0) { - // 发送COTP连接请求 - memcpy(s7_txbuf, s7_comm1, s7_comm1_size); - sendsize = s7_comm1_size; - s7_comm_step++; - return sendsize; - } - - if (s7_comm_step == 1) { - // 发送S7参数协商 - memcpy(s7_txbuf, s7_comm2, s7_comm2_size); - sendsize = s7_comm2_size; - s7_comm_step++; - return sendsize; - } - - // 协商完成,进入正常读写轮询 - uint16_t slave_id = get_register(myRtumST[s7_idx].slave_id); - uint16_t plc_address = get_register(myRtumST[s7_idx].plc_address); - uint16_t pointNum = get_register(myRtumST[s7_idx].size); - - // 参数检查 - if (slave_id == 0 || slave_id >= 127 || pointNum == 0 || pointNum > 20) { - sendsize = 0; - } else { - // 奇数索引 -> 读操作 - if (s7_idx % 2 == 1) { - s7_read_write_flag = 0; - s7_to_big_endian_16(get_register(DBID1_IDX), s7_readframe.db_id); - s7_to_big_endian_24(get_register(START1_IDX) * 8, s7_readframe.start_address); - s7_to_big_endian_16(get_register(SIZE1_IDX), s7_readframe.read_size); - memcpy(s7_txbuf, s7_readframe.frame, s7_read_size); - sendsize = s7_read_size; - } - // 偶数索引 -> 写操作 - else { - s7_read_write_flag = 1; - // 从寄存器映射读取数据到缓冲区 - get_register_range_to_u8(get_register(FROMMOD_IDX), get_register(SIZE2_IDX), s7_write_to_buffer); - uint16_t bytes = get_register(SIZE2_IDX) * 2; - sendsize = s7_prepare_write_frame(get_register(DBID2_IDX), get_register(START2_IDX), bytes); - memcpy(s7_txbuf, s7_writeframe.frame, sendsize); - } - } - - // 索引轮转,和FINS/SLMP完全一致 - s7_idx = (s7_idx + 1) % 20; - return sendsize; -} - -/** - * @brief 超时计数,由主循环每次调用递增 - */ -void update_timeout_s7(void) { - if (s7Timegap < 0xffff) { - s7Timegap++; - } -} - -/** - * @brief S7 TCP客户端主函数,W5500socket主循环处理 - * @param sn: socket编号 - * @param recvbuf: 接收缓冲区(其实我们用自己的s7_rxbuf) - * @param destip: 目标IP - * @param destport: 目标端口 - * @return 0/正表示正常,负表示错误 - */ -int32_t loopback_tcpc_s7(uint8_t sn, uint8_t *recvbuf, uint8_t *destip, uint16_t destport) { - int32_t ret; - uint16_t size = 0, sentsize = 0; - static uint16_t any_port = 50000; - uint16_t byte_offset = 25; // 数据起始偏移 - - uint8_t sr_status = getSn_SR(sn); - switch (sr_status) { - case SOCK_ESTABLISHED: - if (getSn_IR(sn) & Sn_IR_CON) { -#ifdef _LOOPBACK_DEBUG_S7_ - uint8_t destip[4]; - uint16_t destport; - getSn_DIPR(sn, destip); - destport = getSn_DPORT(sn); - 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); - } - - // 接收响应 - if ((s7_rx_done == 1 || client_wait_timeout == 0) && s7Timegap == 0) { - sentsize = 0; - if (s7_comm_step == 0) { - memcpy(s7_txbuf, s7_comm1, s7_comm1_size); - sentsize = s7_comm1_size; - } else if (s7_comm_step == 1) { - memcpy(s7_txbuf, s7_comm2, s7_comm2_size); - sentsize = s7_comm2_size; - } else { - if (s7_read_write_flag == 0) { - // S7 -> MODBUS 读 - s7_read_write_flag = 1; - if (get_register(SIZE1_IDX) == 0) { - sentsize = 0; - } else { - s7_to_big_endian_16(get_register(DBID1_IDX), s7_readframe.db_id); - s7_to_big_endian_24(get_register(START1_IDX) * 8, s7_readframe.start_address); - s7_to_big_endian_16(get_register(SIZE1_IDX), s7_readframe.read_size); - memcpy(s7_txbuf, s7_readframe.frame, s7_read_size); - sentsize = s7_read_size; - } - - } else { - // MODBUS -> S7 写 - s7_read_write_flag = 0; - get_register_range_to_u8(get_register(FROMMOD_IDX), get_register(SIZE2_IDX), s7_write_to_buffer); - uint16_t write_bytes = get_register(SIZE2_IDX) * 2; - uint16_t frame_size = s7_prepare_write_frame(get_register(DBID2_IDX), get_register(START2_IDX), write_bytes); - memcpy(s7_txbuf, s7_writeframe.frame, frame_size); - sentsize = frame_size; - } - } - - if (sentsize != 0) { - s7_rx_done = 0; - client_wait_timeout = 2000; - } else { - s7_rx_done = 1; - client_wait_timeout = 50; - } - -#ifdef _LOOPBACK_DEBUG_S7_ - if (get_register(1900) > 0) { - printf("TX step %d -> ", s7_comm_step); - if (sentsize > 0) { - for (int i = 0; i < sentsize; i++) { - printf("0x%x ", s7_txbuf[i]); - } - printf("\r\n"); - } - } -#endif - - // 发送 - sentsize = 0; - while (sentsize != size && sentsize != sentsize) { - ret = send(sn, s7_txbuf + sentsize, sentsize - sentsize); - if (ret < 0) { - close(sn); - return ret; - } - sentsize += ret; - } - } - - // 接收 - if (s7_rx_done == 0) { - uint16_t clientrxsize = 0; - if ((clientrxsize = getSn_RX_RSR(sn)) > 0) { - if (clientrxsize > sizeof(s7_rxbuf)) { - clientrxsize = sizeof(s7_rxbuf); - } - int16_t ret = recv(sn, s7_rxbuf, clientrxsize); -#ifdef _LOOPBACK_DEBUG_S7_ - if (get_register(1900) > 0) { - printf("RX step %d -> ", s7_comm_step); - for (int i = 0; i < ret; i++) { - printf("0x%x ", s7_rxbuf[i]); - } - printf("\r\n"); - } -#endif - if (ret > 0) { - if (s7_comm_step < 2) { - s7_comm_step++; - } else { - // 处理读写响应 - s7_handle_recv(ret, &byte_offset); - } - s7_rx_done = 1; - } else { - return ret; - } - } - } - break; - - case SOCK_CLOSE_WAIT: -#ifdef _LOOPBACK_DEBUG_S7_ - //printf("%d:CloseWait\r\n",sn); -#endif - if ((ret = disconnect(sn)) != SOCK_OK) { - return ret; - } -#ifdef _LOOPBACK_DEBUG_S7_ - printf("%d:Socket Closed\r\n", sn); -#endif - break; - - case SOCK_INIT: -#ifdef _LOOPBACK_DEBUG_S7_ - 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; - } - break; - - case SOCK_CLOSED: - s7_comm_step = 0; - close(sn); - // 端口绕回处理 - 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_S7_ - //printf("%d:TCP client loopback start\r\n",sn); - //printf("%d:Socket opened\r\n",sn); -#endif - break; - - default: - break; - } - return 1; -} diff --git a/comm/protocols/s7tcpmaster.h b/comm/protocols/s7tcpmaster.h deleted file mode 100644 index af9a924..0000000 --- a/comm/protocols/s7tcpmaster.h +++ /dev/null @@ -1,65 +0,0 @@ -/** - * @file s7tcpmaster.h - * @brief 西门子S7Comm TCP客户端主站头文件 - */ -#ifndef S7TCPMASTER_H -#define S7TCPMASTER_H - -#ifdef __cplusplus -extern "C" { -#endif - -#include -#include - -// ============================================================================ -// 全局变量 -// ============================================================================ - -extern uint8_t s7_txbuf[1024]; -extern uint8_t s7_rxbuf[1024]; -extern uint16_t s7_idx; -extern uint16_t s7_addr; -extern uint16_t s7_size; -extern uint16_t s7Timegap; -extern uint16_t client_wait_timeout; -extern uint16_t comm_count; - -// ============================================================================ -// 接口函数 -// ============================================================================ - -/** - * @brief 处理接收到的S7响应 - * @param size: 接收长度 - * @param byte_offset: 数据字节偏移 - * @return true: 处理成功,false: 不是有效的读响应 - */ -_Bool s7_handle_recv(uint16_t size, uint16_t *byte_offset); - -/** - * @brief 构建S7请求帧,返回发送长度 - * @return 发送长度,0表示不发送 - */ -uint16_t s7_build_send(void); - -/** - * @brief 超时计数,由主循环每次调用递增 - */ -void update_timeout_s7(void); - -/** - * @brief S7 TCP客户端主函数,W5500socket主循环处理 - * @param sn: socket编号 - * @param recvbuf: 接收缓冲区 - * @param destip: 目标IP地址 - * @param destport: 目标端口 - * @return 0/正表示正常,负表示错误 - */ -int32_t loopback_tcpc_s7(uint8_t sn, uint8_t *recvbuf, uint8_t *destip, uint16_t destport); - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/comm/rtuMaster.c b/comm/rtuMaster.c deleted file mode 100644 index 7bce4ce..0000000 --- a/comm/rtuMaster.c +++ /dev/null @@ -1,170 +0,0 @@ -#include "w5500/modbusSlave.h" -#include "w5500/modbus_crc.h" -#include "usart.h" -#include "gpio.h" -#include "rtuMaster.h" - -rtumST readST[10] = { { .slave_id = 0, .slave_address = 1, .plc_address = 2, .size = 3 }, { .slave_id = 4, .slave_address = 5, .plc_address = 6, .size = 7 }, { - .slave_id = 8, .slave_address = 9, .plc_address = 10, .size = 11 }, { .slave_id = 12, .slave_address = 13, .plc_address = 14, .size = 15 }, { - .slave_id = 16, .slave_address = 17, .plc_address = 18, .size = 19 }, { .slave_id = 20, .slave_address = 21, .plc_address = 22, .size = 23 }, { - .slave_id = 24, .slave_address = 25, .plc_address = 26, .size = 27 }, { .slave_id = 28, .slave_address = 29, .plc_address = 30, .size = 31 }, { - .slave_id = 32, .slave_address = 33, .plc_address = 34, .size = 35 }, { .slave_id = 36, .slave_address = 37, .plc_address = 38, .size = 39 } }; - -rtumST writeST[10] = { { .slave_id = 40, .slave_address = 41, .plc_address = 42, .size = 43 }, { .slave_id = 44, .slave_address = 45, .plc_address = 46, .size = - 47 }, { .slave_id = 48, .slave_address = 49, .plc_address = 50, .size = 51 }, { .slave_id = 52, .slave_address = 53, .plc_address = 54, .size = 55 }, { - .slave_id = 56, .slave_address = 57, .plc_address = 58, .size = 59 }, { .slave_id = 60, .slave_address = 61, .plc_address = 62, .size = 63 }, { - .slave_id = 64, .slave_address = 65, .plc_address = 66, .size = 67 }, { .slave_id = 68, .slave_address = 69, .plc_address = 70, .size = 71 }, { - .slave_id = 72, .slave_address = 73, .plc_address = 74, .size = 75 }, { .slave_id = 76, .slave_address = 77, .plc_address = 78, .size = 79 } }; - -rtumST myRtumST[20]; - -RtuMaster master = { .localStartIdx = 1000 }; - -void initRtuMaster() { - for (int i = 0; i < 10; i++) { - myRtumST[i * 2] = readST[i]; - myRtumST[i * 2 + 1] = writeST[i]; - } - - if (master.isMaster) { - RE_RESET; - HAL_UARTEx_ReceiveToIdle_DMA(&huart1, master.rxbuf, 255); - } - HAL_GPIO_WritePin(comm485_GPIO_Port, comm485_Pin, GPIO_PIN_SET); -} - -typedef union { - uint16_t val16; - uint8_t bytes[2]; -} Uint16To8; -Uint16To8 cvt; - -static uint8_t idx = 0; -static uint16_t slave_id, slave_address, size; - -void RTU_Master_Loop() { - if (master.isMaster) { - for (int j = 0; j < 20; j++) { - slave_id = get_register(myRtumST[j].slave_id); - slave_address = get_register(myRtumST[j].slave_address); - size = get_register(myRtumST[j].size); - if (slave_id == master.localSlaveId) { - set_register(120, j); - set_register(121, slave_id); - set_register(122, slave_address); - set_register(123, size); - if (j % 2 == 0) { - for (int i = 0; i < size; i++) { - set_register(j * 20 + master.localStartIdx + i, get_register(slave_address + i)); - } - } else { - for (int i = 0; i < size; i++) { - set_register(slave_address + i, get_register(j * 20 + master.localStartIdx + i)); - } - } - } - } - - if (master.timeout >= 1000) { - slave_id = get_register(myRtumST[idx].slave_id); - slave_address = get_register(myRtumST[idx].slave_address); - size = get_register(myRtumST[idx].size); - - if (slave_id == 0 || slave_id >= 127 || size > 20 || size == 0 || slave_id != master.localSlaveId) { - master.txsize = 0; - } else { - if (idx % 2 == 0) { - master.txbuf[0] = slave_id; - master.txbuf[1] = 0x03; - cvt.val16 = slave_address; - master.txbuf[2] = cvt.bytes[1]; - master.txbuf[3] = cvt.bytes[0]; - cvt.val16 = size; - master.txbuf[4] = cvt.bytes[1]; - master.txbuf[5] = cvt.bytes[0]; - cvt.val16 = crc16(master.txbuf, 6); - master.txbuf[6] = cvt.bytes[0]; - master.txbuf[7] = cvt.bytes[1]; - master.txsize = 8; - } else { - master.txbuf[0] = slave_id; - master.txbuf[1] = 0x10; - cvt.val16 = slave_address; - master.txbuf[2] = cvt.bytes[1]; - master.txbuf[3] = cvt.bytes[0]; - cvt.val16 = size; - master.txbuf[4] = cvt.bytes[1]; - master.txbuf[5] = cvt.bytes[0]; - master.txbuf[6] = size * 2; - - for (uint8_t i = 0; i < size; i++) { - cvt.val16 = get_register(idx * 20 + master.localStartIdx + i); - master.txbuf[2 * i + 7] = cvt.bytes[1]; - master.txbuf[2 * i + 8] = cvt.bytes[0]; - } - - cvt.val16 = crc16(master.txbuf, size * 2 + 7); - master.txbuf[size * 2 + 7] = cvt.bytes[0]; - master.txbuf[size * 2 + 8] = cvt.bytes[1]; - master.txsize = 2 * size + 9; - } - } - - if (master.txsize > 0) { - HAL_GPIO_WritePin(re485_GPIO_Port, re485_Pin, GPIO_PIN_SET); - HAL_UART_Transmit_DMA(&huart1, master.txbuf, master.txsize); - master.timeout = 1; - } else { - master.timeout = 1000; - } - - idx = (idx + 1) % 20; - } - - if (master.rxdone) { - cvt.bytes[0] = master.rxbuf[master.rxsize - 2]; - cvt.bytes[1] = master.rxbuf[master.rxsize - 1]; - if (crc16(master.rxbuf, master.rxsize - 2) != cvt.val16) { - return; - } - if (master.rxbuf[1] == 0x03) { - uint16_t size = master.rxbuf[2] / 2; - size = size >= 20 ? 20 : size; - for (int i = 0; i < size; i++) { - cvt.bytes[0] = master.rxbuf[2 * i + 4]; - cvt.bytes[1] = master.rxbuf[2 * i + 3]; - if (idx == 0) { - set_register(master.localStartIdx + i + (20 * 19), cvt.val16); - } else { - set_register(master.localStartIdx + i + (20 * (idx - 1)), cvt.val16); - } - - } - } - master.rxdone = 0; - master.timeout = 950; - } - } else { - if (master.rxdone) { - HAL_GPIO_TogglePin(comm485_GPIO_Port, comm485_Pin); - handleModbusRtu_NEW(master.rxbuf, master.rxbuf, master.rxsize, &huart1); - master.rxdone = 0; - } - } - -} - - -void HAL_UART_TxCpltCallback(UART_HandleTypeDef *huart) { - if (huart == &huart1) { - RE_RESET; - HAL_UARTEx_ReceiveToIdle_DMA(&huart1, master.rxbuf, 255); - } -} - -void HAL_UARTEx_RxEventCallback(UART_HandleTypeDef *huart, uint16_t Size) { - if (huart == &huart1) { - master.rxdone = 1; - master.rxsize = Size; - } -} diff --git a/comm/rtuMaster.h b/comm/rtuMaster.h deleted file mode 100644 index fbc38d1..0000000 --- a/comm/rtuMaster.h +++ /dev/null @@ -1,41 +0,0 @@ -/* - * rtuMaster.h - * - * Created on: Mar 26, 2026 - * Author: 18896 - */ - -#ifndef RTUMASTER_H_ -#define RTUMASTER_H_ - -#define RE_SET HAL_GPIO_WritePin(re485_GPIO_Port, re485_Pin, GPIO_PIN_SET) -#define RE_RESET HAL_GPIO_WritePin(re485_GPIO_Port, re485_Pin, GPIO_PIN_RESET) - -typedef struct { - uint16_t slave_id; - uint16_t slave_address; - uint16_t plc_address; - uint16_t size; -} rtumST; - -typedef struct { - uint8_t plc_type; - _Bool isMaster; - _Bool rxdone; - uint16_t rxsize, txsize; - uint16_t timeout; - uint8_t rxbuf[255]; - uint8_t txbuf[255]; - uint16_t localSlaveId; - uint16_t localStartIdx; -} RtuMaster; - -extern rtumST readST[10]; -extern rtumST writeST[10]; -extern rtumST myRtumST[20]; -extern RtuMaster master; - -void initRtuMaster(); -void RTU_Master_Loop(); - -#endif /* RTUMASTER_H_ */ diff --git a/comm/slmpMaster.c b/comm/slmpMaster.c deleted file mode 100644 index e4bf78e..0000000 --- a/comm/slmpMaster.c +++ /dev/null @@ -1,37 +0,0 @@ -/* - * smlMaster.c - * - * Created on: Apr 15, 2025 - * Author: 18896 - */ -#include "main.h" -#include "slmpMaster.h" - -SLMPSTATUS slmp_master_status = slmp_writeRxDone; -uint8_t readRespHeader[7] = { 0xD0, 0x00, 0x00, 0xFF, 0xFF, 0x03, 0x00 }; -SMLPFrame frame = { .frameStruct.header = 0x0050, .frameStruct.taget = 0xff00, .frameStruct.index = 0x03FF, .frameStruct.subIdx = 0x00, .frameStruct.timeout = 0x0004, .frameStruct.subCmd = 0x0000, .frameStruct.DM = 0xA8 }; - -uint24_t u32_to_u24(uint32_t val) { - uint24_t r; - r.byte0 = val & 0xFF; - r.byte1 = (val >> 8) & 0xFF; - r.byte2 = (val >> 16) & 0xFF; - return r; -} - -uint16_t handleSMLP_ReadTX(uint32_t start, uint16_t size) { - frame.frameStruct.cmd = 0x0401; - frame.frameStruct.requestSize = 0x000c; - frame.frameStruct.start = u32_to_u24(start); - frame.frameStruct.size = size; - return 21; -} - -uint16_t handleSLMP_WriteTX(uint32_t start, uint16_t size) { - frame.frameStruct.cmd = 0x1401; - frame.frameStruct.requestSize = 0x000C + (size * 2); - frame.frameStruct.start = u32_to_u24(start); - frame.frameStruct.size = size; - return size * 2 + 21; -} - diff --git a/comm/slmpMaster.h b/comm/slmpMaster.h deleted file mode 100644 index e295490..0000000 --- a/comm/slmpMaster.h +++ /dev/null @@ -1,53 +0,0 @@ -/* - * smlpMaster.h - * - * Created on: Apr 15, 2025 - * Author: 18896 - */ - -#ifndef SLMPMASTER_H_ -#define SLMPMASTER_H_ - -#define SLMP_HEAD_SIZE 9 - -typedef enum { - slmp_read, slmp_readRxDone, slmp_write, slmp_writeRxDone,readySend -} SLMPSTATUS; - -typedef struct { - uint8_t byte0; - uint8_t byte1; - uint8_t byte2; -} uint24_t; - -uint24_t u32_to_u24(uint32_t val); - -typedef union { - struct __attribute__((__packed__)){ - uint16_t header; - uint16_t taget; - uint16_t index; - uint8_t subIdx; - uint16_t requestSize; - uint16_t timeout; - uint16_t cmd; - uint16_t subCmd; - uint24_t start; - uint8_t DM; - uint16_t size; - } frameStruct; - uint8_t frameU8[21]; -} SMLPFrame; - - - - -extern SLMPSTATUS slmp_master_status; -extern uint8_t readRespHeader[7]; -extern SMLPFrame frame; - -uint16_t handleSMLP_ReadTX(uint32_t start, uint16_t size); - -uint16_t handleSLMP_WriteTX(uint32_t start, uint16_t size); - -#endif /* SLMPMASTER_H_ */ diff --git a/protocols/common.c b/protocols/common.c new file mode 100644 index 0000000..76d4825 --- /dev/null +++ b/protocols/common.c @@ -0,0 +1,8 @@ +/* + * common.c + * + * Created on: Apr 3, 2026 + * Author: 18896 + */ + + diff --git a/protocols/common.h b/protocols/common.h new file mode 100644 index 0000000..c34bf3a --- /dev/null +++ b/protocols/common.h @@ -0,0 +1,14 @@ +/* + * common.h + * + * Created on: Apr 3, 2026 + * Author: 18896 + */ + +#ifndef W5500_PROTOCOLS_COMMON_H_ +#define W5500_PROTOCOLS_COMMON_H_ + +#define W5500_COMM_LED_TOGGLE_CNT 50 +#define W5500_COMM_LED_OFF_TIMEMS 2000 + +#endif /* W5500_PROTOCOLS_COMMON_H_ */ diff --git a/protocols/finsudpmaster.c b/protocols/finsudpmaster.c new file mode 100644 index 0000000..e4b6262 --- /dev/null +++ b/protocols/finsudpmaster.c @@ -0,0 +1,211 @@ +/* + * @file finsudpmaster.c + * @brief 欧姆龙FINS UDP客户端主站实现 + * + * 轮询机制: + * - myRtumSTIdx: 0~19 轮转索引,对应 myRtumST[20] + * - **奇数索引**: 读操作,从PLC读取数据存储到 + (idx*20) + i + * - **偶数索引**: 写操作,从 + (idx*20) + i 读取数据写入PLC + * - 每次主循环调用 update_timeout_fins() 递增超时计数 + * - 超时计数 > 500 时发送下一帧,接收后重置超时为 490 + */ + +#include "finsudpmaster.h" +#include "socket.h" +#include "wizchip_conf.h" +#include "rtuMaster.h" +#include "modbusSlave.h" +#include "main.h" +#include "common.h" +#include + +static uint8_t comm_count; +static uint8_t myRtumSTIdx = 0; // 轮询索引 (0~19) +static uint8_t prevReadIdx = 0; +static uint8_t comm_buf[1024]; // FINS收发缓冲区 (最大1024字节) +static uint16_t timeout = 0; // 超时计数,由主循环递增 +static uint16_t commled_off_timeout = 0; + +// 读响应固定头,只有匹配这个头才会被处理 +// 格式: ICV(2) + RSV(2) + GATEWAY(1) + len(2) + cmd(1) + ... +uint8_t readrx[14] = { 0xc0, 0x00, 0x02, 0x00, 0x0A, 0x00, 0x00, 0x01, 0x00, 0x00, 0x01, 0x01, 0x00, 0x40 }; + +// 预定义的请求模板 +uint8_t send_read[18] = { // 读请求模板 + 0x80, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x01, 0x01, 0x82, 0x00, 0x64, 0x00, 0x00, 0x0a }; +uint8_t write_send[58] = { // 写请求模板 (最大20点 = 18 + 20*2 = 58字节) + 0x80, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x01, 0x02, 0x82, 0x00, 0x64, 0x00, 0x00, 0x02 }; + +// ============================================================================ +// 公共接口 +// ============================================================================ + +/** + * @brief 处理接收到的FINS读响应 + * @param size: 接收数据长度 + * @param local_node: 本地节点号,填充到响应头比较 + * @return true: 处理成功,false: 不是有效的读响应 + * @note 只有读响应需要存储数据,写响应不需要处理 + */ +_Bool handleReadRecv(uint16_t size, uint16_t local_node) { + // 1. 设置本地节点号,然后比对前14字节确认是读响应 + readrx[4] = (uint8_t) local_node; + for (int i = 0; i < 14; i++) { + if (readrx[i] != comm_buf[i]) { + return false; // 不匹配,不是读响应 + } + } + + uint16_t pointNum = get_register(myRtumST[prevReadIdx].size); + + // 5. 解析响应数据,存储到寄存器映射 + // FINS使用大端序: 高字节在前,低字节在后 + for (int i = 0; i < pointNum; i++) { + uint8_t byte_h = comm_buf[i * 2 + 14]; + uint8_t byte_l = comm_buf[i * 2 + 15]; + uint16_t value = ((uint16_t) byte_h << 8) | byte_l; + // 存储地址: + (索引*20) + 偏移 + set_register(master.localStartIdx + (20 * prevReadIdx) + i, value); + } + + return true; +} + +/** + * @brief 构建FINS请求帧 + * @param local_node: 本地节点号 + * @return 发送长度,0表示不发送(参数非法) + * @note 奇数索引 -> 读操作,偶数索引 -> 写操作 + */ +uint16_t handleSend(uint16_t local_node) { + uint16_t sendsize = 0; + uint16_t slave_id = get_register(myRtumST[myRtumSTIdx].slave_id); + uint16_t plc_address = get_register(myRtumST[myRtumSTIdx].plc_address); + uint16_t pointNum = get_register(myRtumST[myRtumSTIdx].size); + + // ====================== + // 无效 → 索引+1 → 下一个 + // ====================== + if (slave_id == 0 || slave_id >= 127 || pointNum == 0 || pointNum > 20) { + myRtumSTIdx = (myRtumSTIdx + 1) % 20; + return 0; + } + + // ====================== + // 奇数 = 读 + // ====================== + if (myRtumSTIdx % 2 == 1) { + send_read[7] = (uint8_t) local_node; + send_read[13] = (plc_address >> 8) & 0xFF; + send_read[14] = plc_address & 0xFF; + send_read[17] = (uint8_t) pointNum; + sendsize = 18; + memcpy(comm_buf, send_read, sendsize); + prevReadIdx = myRtumSTIdx; + } + // ====================== + // 偶数 = 写 + // ====================== + else { + sendsize = 18 + pointNum * 2; + write_send[7] = (uint8_t) local_node; + write_send[13] = (plc_address >> 8) & 0xFF; + write_send[14] = plc_address & 0xFF; + write_send[17] = (uint8_t) pointNum; + + for (int i = 0; i < pointNum; i++) { + uint16_t value = get_register(master.localStartIdx + 20 * myRtumSTIdx + i); + write_send[18 + i * 2] = (value >> 8) & 0xFF; + write_send[19 + i * 2] = value & 0xFF; + } + memcpy(comm_buf, write_send, sendsize); + } + + // ====================== + // 有效发送完成 → 下一个 + // ====================== + myRtumSTIdx = (myRtumSTIdx + 1) % 20; + return sendsize; +} + +/** + * @brief 超时计数,由主循环每次调用递增 + */ +void update_timeout_fins(void) { + if (timeout < 0xffff) { + timeout++; + } + if (commled_off_timeout < 0xffff) { + commled_off_timeout++; + } +} + +/** + * @brief FINS UDP客户端主函数,W5500socket主循环处理 + * @param sn: W5500 socket编号 + * @param destip: 目标IP地址 + * @param destport: 目标端口 + * @param local_node: 本地节点号 + * @return 0/正表示正常,负表示错误 + */ +int32_t loopback_udpc_omrfins(uint8_t sn, uint8_t *destip, uint16_t destport, uint16_t local_node) { + 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; + + switch (getSn_SR(sn)) { + case SOCK_UDP: + // 接收 + if ((size = getSn_RX_RSR(sn)) > 0) { + if (size > sizeof(comm_buf)) + size = sizeof(comm_buf); + ret = recvfrom(sn, comm_buf, size, destip, (uint16_t*) &destport); + if (ret > 0) { + commled_off_timeout = 0; + comm_count++; + handleReadRecv(ret, local_node); + timeout = 490; + } + } + + // 超时触发发送 + size = 0; + if (timeout > 500) { + size = handleSend(local_node); + if (size == 0) { + // 无效通道,快速跳过 + timeout = 499; + } else { + // 有效发送,重置超时 + timeout = 0; + } + } + + // 发送 + sentsize = 0; + while (size != 0 && sentsize < size) { + ret = sendto(sn, comm_buf + sentsize, size - sentsize, destip, destport); + if (ret < 0) + break; + sentsize += ret; + } + break; + + case SOCK_CLOSED: + if (any_port == 0xFFFF) + any_port = 50000; + socket(sn, Sn_MR_UDP, any_port++, 0x00); + break; + + default: + break; + } + return 1; +} diff --git a/comm/protocols/finsudpmaster.h b/protocols/finsudpmaster.h similarity index 86% rename from comm/protocols/finsudpmaster.h rename to protocols/finsudpmaster.h index d1ba3a1..d0875ff 100644 --- a/comm/protocols/finsudpmaster.h +++ b/protocols/finsudpmaster.h @@ -16,10 +16,6 @@ extern "C" { // 全局变量 // ============================================================================ -extern uint8_t myRtumSTIdx; // 当前轮询索引 (0~19) -extern uint8_t omrfins_buf[1024]; // FINS收发缓冲区 -extern uint16_t fins_timeout; // 超时计数,由主循环递增 -extern uint16_t comm_count; // 通信计数 // ============================================================================ // 接口函数 diff --git a/protocols/modbustcpslave.c b/protocols/modbustcpslave.c new file mode 100644 index 0000000..19f5759 --- /dev/null +++ b/protocols/modbustcpslave.c @@ -0,0 +1,121 @@ +/* + * @file modbustcpslave.c + * @brief Modbus TCP从站服务 + Modbus TCP转RTU转发 + */ + +#include "modbustcpslave.h" +#include "socket.h" +#include "wizchip_conf.h" +#include "modbusSlave.h" +#include "common.h" +// ============================================================================ +// 全局变量 +// ============================================================================ + +uint8_t loopback_tcps_modbus_rxbuf[1024]; +uint8_t loopback_tcps_modbus_txbuf[1024]; + +static uint16_t commled_off_timeout = 0; +static uint8_t comm_count; + +void update_modbusTCP_timeout() { + if (commled_off_timeout < 0xffff) { + commled_off_timeout++; + } +} + +/** + * @brief Modbus TCP服务主函数,W5500socket主循环处理 + * @param sn: socket编号 + * @param port: 监听端口 (通常502) + * @return 0/正表示正常,负表示错误 + */ +int32_t loopback_tcps_modbus(uint8_t sn, uint16_t port) { + + int32_t ret; + uint16_t size = 0, sentsize = 0; + +#ifdef _LOOPBACK_DEBUG_ + uint8_t destip[4]; + uint16_t destport; +#endif + + switch (getSn_SR(sn)) { + case SOCK_ESTABLISHED: + if (getSn_IR(sn) & Sn_IR_CON) { +#ifdef _LOOPBACK_DEBUG_ + getSn_DIPR(sn, destip); + destport = getSn_DPORT(sn); + printf("%d:Connected - %d.%d.%d.%d : %d\r\n", sn, destip[0], + destip[1], destip[2], destip[3], destport); +#endif + setSn_IR(sn, Sn_IR_CON); + } + + // 接收请求 + if ((size = getSn_RX_RSR(sn)) > 0) { + comm_count++; + commled_off_timeout = 0; + if (size > DATA_BUF_SIZE) { + size = DATA_BUF_SIZE; + } + ret = recv(sn, loopback_tcps_modbus_rxbuf, size); + if (ret <= 0) { + return ret; + } + + // 处理Modbus TCP请求 + uint16_t rxbuf_size = handleModbusTcp(loopback_tcps_modbus_rxbuf, loopback_tcps_modbus_txbuf); + if (rxbuf_size > 0) { + sentsize = 0; + // 分片发送直到完成 + while (rxbuf_size != sentsize) { + ret = send(sn, loopback_tcps_modbus_txbuf + sentsize, rxbuf_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:Listen, TCP server loopback, port [%d]\r\n", sn, port); +#endif + if ((ret = listen(sn)) != SOCK_OK) { + return ret; + } + break; + + case SOCK_CLOSED: +#ifdef _LOOPBACK_DEBUG_ + //printf("%d:TCP server loopback start\r\n",sn); +#endif + if ((ret = socket(sn, Sn_MR_TCP, port, 0x00)) != sn) { + return ret; + } +#ifdef _LOOPBACK_DEBUG_ + //printf("%d:Socket opened\r\n",sn); +#endif + break; + + default: + break; + } + return 1; +} diff --git a/protocols/modbustcpslave.h b/protocols/modbustcpslave.h new file mode 100644 index 0000000..496a74e --- /dev/null +++ b/protocols/modbustcpslave.h @@ -0,0 +1,38 @@ +/** + * @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 + + + +// ============================================================================ +// 接口函数 +// ============================================================================ + +/** + * @brief Modbus TCP服务主函数,W5500socket主循环处理 + * @param sn: socket编号 + * @param port: 监听端口 (通常502) + * @return 0/正表示正常,负表示错误 + */ +int32_t loopback_tcps_modbus(uint8_t sn, uint16_t port); +void update_modbusTCP_timeout(); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/protocols/s7tcpmaster.c b/protocols/s7tcpmaster.c new file mode 100644 index 0000000..f61aabf --- /dev/null +++ b/protocols/s7tcpmaster.c @@ -0,0 +1,113 @@ +/* + * @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 + * - 需要先建立TCP连接,然后完成COTP连接协商和S7Comm参数协商 + * - 协商完成后进入正常轮询读写 + */ + +#include "s7tcpmaster.h" +#include "socket.h" +#include "wizchip_conf.h" +#include "rtuMaster.h" +#include "main.h" +#include + +static uint8_t buf[1024]; + +int32_t loopback_tcpc_s7(uint8_t sn,uint8_t *destip, uint16_t destport) { + int32_t ret; // return value for SOCK_ERRORs + uint16_t size = 0, sentsize = 0; + + // 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)) { + 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' + } + + ////////////////////////////////////////////////////////////////////////////////////////////// + // 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) + } + ret = recv(sn, buf, size); // Data Receive process (H/W Rx socket buffer -> User's buffer) + + if (ret <= 0) { + return ret; // If the received data length <= 0, receive failed and process end + } + size = (uint16_t) ret; + sentsize = 0; + + // 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; + } + sentsize += ret; // Don't care SOCKERR_BUSY, because it is zero. + } + } + ////////////////////////////////////////////////////////////////////////////////////////////// + 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) + } + break; + + 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 + } +#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; +} + diff --git a/protocols/s7tcpmaster.h b/protocols/s7tcpmaster.h new file mode 100644 index 0000000..d94c1f7 --- /dev/null +++ b/protocols/s7tcpmaster.h @@ -0,0 +1,22 @@ +/** + * @file s7tcpmaster.h + * @brief 西门子S7Comm TCP客户端主站头文件 + */ +#ifndef S7TCPMASTER_H +#define S7TCPMASTER_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include + + +int32_t loopback_tcpc_s7(uint8_t sn, uint8_t *destip, uint16_t destport); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/comm/protocols/slmptcpmaster.c b/protocols/slmptcpmaster.c similarity index 55% rename from comm/protocols/slmptcpmaster.c rename to protocols/slmptcpmaster.c index f5e5794..b58867f 100644 --- a/comm/protocols/slmptcpmaster.c +++ b/protocols/slmptcpmaster.c @@ -3,9 +3,9 @@ * @brief 三菱SLMP协议TCP客户端主站实现 * * 轮询机制 (和欧姆龙FINS完全一致): - * - slmp_idx: 0~9 轮转索引,对应 readST[10] / writeST[10] - * - **奇数索引**: 读操作,从PLC读取数据存储到 1200 + (idx*20) + i - * - **偶数索引**: 写操作,从 1000 + (idx*20) + i 读取数据写入PLC + * - myRtumSTIdx: 0~9 轮转索引,对应 readST[10] / writeST[10] + * - **奇数索引**: 读操作,从PLC读取数据存储到 + (idx*20) + i + * - **偶数索引**: 写操作,从 + (idx*20) + i 读取数据写入PLC * - 每次主循环调用 update_timeout_slmp() 递增超时计数 * - 超时计数 > 1000 时发送下一帧,接收后重置超时为 900 */ @@ -14,7 +14,9 @@ #include "socket.h" #include "wizchip_conf.h" #include "rtuMaster.h" +#include "modbusSlave.h" #include "main.h" +#include "common.h" #include // ============================================================================ @@ -33,18 +35,18 @@ typedef union { // SLMP请求帧联合体,支持结构化访问和字节访问 typedef union { - struct __attribute__((__packed__)){ - uint16_t header; // 固定值: 0x0050 - uint16_t target; // 固定值: 0xff00 - uint16_t index; // 固定值: 0x03FF - uint8_t subIdx; // 固定值: 0x00 - uint16_t requestSize; // 请求数据长度 - uint16_t timeout; // 超时: 0x0004 (4秒) - uint16_t cmd; // 命令码: 0x0401=读,0x1401=写 - uint16_t subCmd; // 子命令: 固定0x0000 - slmp_uint24_t start; // 起始地址 (24位小端) - uint8_t dm; // 软元件类型: 0xA8 = D寄存器 - uint16_t size; // 读写点数 + struct __attribute__((__packed__)) { + uint16_t header; // 固定值: 0x0050 + uint16_t target; // 固定值: 0xff00 + uint16_t index; // 固定值: 0x03FF + uint8_t subIdx; // 固定值: 0x00 + uint16_t requestSize; // 请求数据长度 + uint16_t timeout; // 超时: 0x0004 (4秒) + uint16_t cmd; // 命令码: 0x0401=读,0x1401=写 + uint16_t subCmd; // 子命令: 固定0x0000 + slmp_uint24_t start; // 起始地址 (24位小端) + uint8_t dm; // 软元件类型: 0xA8 = D寄存器 + uint16_t size; // 读写点数 } frameStruct; uint8_t frameU8[21]; // 按字节访问,帧头最大21字节 } SLMPFrame; @@ -53,26 +55,18 @@ typedef union { // 全局变量 // ============================================================================ -uint8_t slmp_txbuf[1024]; // 发送缓冲区 (最大1024字节) -uint8_t slmp_rxbuf[1024]; // 接收缓冲区 (最大1024字节) -uint16_t slmp_read_resp_header[7] = { 0xD0, 0x00, 0x00, 0xFF, 0xFF, 0x03, 0x00 }; - // 读响应固定头,用于识别读响应 -uint16_t slmp_idx = 0; // 当前轮询索引 (0~9) -uint16_t slmp_curr_idx; // 当前正在处理的索引 -uint16_t slmp_addr; // 当前请求的起始地址 -uint16_t slmp_size; // 当前请求的点数 -uint16_t slmpTimegap = 0; // 超时间隔计数,由主循环递增 +uint16_t slmp_read_resp_header[7] = { 0xD0, 0x00, 0x00, 0xFF, 0xFF, 0x03, 0x00 }; + +static uint8_t myRtumSTIdx = 0; // 轮询索引 (0~19) +static uint8_t prevReadIdx = 0; +static uint8_t comm_buf[1024]; // FINS收发缓冲区 (最大1024字节) +static uint16_t timeout = 0; // 超时计数,由主循环递增 +static uint16_t commled_off_timeout = 0; +static uint8_t comm_count; // SLMP帧静态初始化,固定值填充 -static SLMPFrame slmp_frame = { - .frameStruct.header = 0x0050, - .frameStruct.target = 0xff00, - .frameStruct.index = 0x03FF, - .frameStruct.subIdx = 0x00, - .frameStruct.timeout = 0x0004, - .frameStruct.subCmd = 0x0000, - .frameStruct.dm = 0xA8 -}; +static SLMPFrame slmp_frame = { .frameStruct.header = 0x0050, .frameStruct.target = 0xff00, .frameStruct.index = 0x03FF, .frameStruct.subIdx = 0x00, + .frameStruct.timeout = 0x0004, .frameStruct.subCmd = 0x0000, .frameStruct.dm = 0xA8 }; // ============================================================================ // 内部工具函数 @@ -101,40 +95,27 @@ static slmp_uint24_t u32_to_slmp24(uint32_t val) { * @return true: 处理成功,false: 不是有效的读响应 * @note 只有读响应需要存储数据,写响应不需要处理 */ -_Bool slmp_handle_recv(uint16_t size) { - // 1. 识别读响应: 比对前7字节响应头 - if (memcmp(slmp_rxbuf, slmp_read_resp_header, 7) != 0) { - return false; // 不是读响应(是写响应),直接忽略 - } +_Bool handleReadRecvSLMP(uint16_t size) { - // 2. 获取上一次发送对应的索引 - // 因为发送后索引立即+1,所以响应对应发送前的索引 - uint16_t prevIdx; - if (slmp_idx == 0) { - prevIdx = 19; // 绕回 (0~19共20个索引,和FINS一致) - } else { - prevIdx = slmp_idx - 1; + for (int i = 0; i < 7; i++) { + if (comm_buf[i] != slmp_read_resp_header[i]) { + return false; + } } - - // 3. 验证索引: 读必须是奇数索引 - if (prevIdx % 2 != 1) { - return false; // 不匹配,丢弃 - } - // 4. 获取参数,检查长度合法性 - uint16_t pointNum = get_register(myRtumST[prevIdx].size); - if (pointNum > 20 || pointNum * 2 + 11 != size) { - return false; // 长度不匹配或超出最大限制,丢弃 + uint16_t pointNum = get_register(myRtumST[prevReadIdx].size); + if (size != pointNum * 2 + 11) { + return false; } // 5. 解析响应数据,存储到寄存器映射 // SLMP数据使用小端序: 低字节在前,高字节在后 for (int i = 0; i < pointNum; i++) { - uint8_t byte_l = slmp_rxbuf[i * 2 + 11]; - uint8_t byte_h = slmp_rxbuf[i * 2 + 12]; - uint16_t value = ((uint16_t)byte_l) | (((uint16_t)byte_h) << 8); - // 存储地址: 1200 + (索引*20) + 偏移 (和FINS一致) - set_register(1200 + (20 * prevIdx) + i, value); + uint8_t byte_l = comm_buf[i * 2 + 11]; + uint8_t byte_h = comm_buf[i * 2 + 12]; + uint16_t value = ((uint16_t) byte_l) | (((uint16_t) byte_h) << 8); + // 存储地址: + (索引*20) + 偏移 (和FINS一致) + set_register(master.localStartIdx + (20 * prevReadIdx) + i, value); } return true; @@ -144,25 +125,23 @@ _Bool slmp_handle_recv(uint16_t size) { * @brief 构建SLMP请求帧 * @return 发送长度,0表示不发送(参数非法) * @note 和FINS完全一致: 使用myRtumST[20],奇数索引读,偶数索引写 - * 读: 存储到 1200 + (idx*20) + i - * 写: 从 1200 + (idx*20) + i 读取 + * 读: 存储到 + (idx*20) + i + * 写: 从 + (idx*20) + i 读取 */ -uint16_t slmp_build_send(void) { +uint16_t handleSendSLMP(void) { uint16_t sendsize = 0; - uint16_t slave_id = get_register(myRtumST[slmp_idx].slave_id); - uint16_t plc_address = get_register(myRtumST[slmp_idx].plc_address); - uint16_t pointNum = get_register(myRtumST[slmp_idx].size); + uint16_t slave_id = get_register(myRtumST[myRtumSTIdx].slave_id); + uint16_t plc_address = get_register(myRtumST[myRtumSTIdx].plc_address); + uint16_t pointNum = get_register(myRtumST[myRtumSTIdx].size); // 参数合法性检查 - if (slave_id < 0x01 || slave_id > 0xF7 || pointNum == 0 || pointNum > 20) { + if (slave_id < 0x01 || slave_id > 0xF7 || pointNum == 0 || pointNum > 20 || (plc_address + pointNum) >= 8000) { + myRtumSTIdx = (myRtumSTIdx + 1) % 20; return 0; } - if ((plc_address + pointNum) >= 8000) { - return 0; // 地址越界 - } // ========== 奇数索引: 读操作 ========== - if (slmp_idx % 2 == 1) { + if (myRtumSTIdx % 2 == 1) { // 构建读请求帧 slmp_frame.frameStruct.cmd = 0x0401; // 读命令码 slmp_frame.frameStruct.requestSize = 0x000C; // 请求长度固定12字节 @@ -171,14 +150,16 @@ uint16_t slmp_build_send(void) { sendsize = 21; // 读请求只有帧头,固定21字节 // 拷贝帧头到发送缓冲区,带边界检查 - for (int i = 0; i < sendsize && i < sizeof(slmp_txbuf); i++) { - slmp_txbuf[i] = slmp_frame.frameU8[i]; + for (int i = 0; i < sendsize && i < sizeof(comm_buf); i++) { + comm_buf[i] = slmp_frame.frameU8[i]; } + + prevReadIdx = myRtumSTIdx; } // ========== 偶数索引: 写操作 ========== else { sendsize = 21 + (pointNum * 2); // 帧头21字节 + 数据2字节*点数 - if (sendsize > sizeof(slmp_txbuf)) { + if (sendsize > sizeof(comm_buf)) { return 0; // 超出缓冲区,安全保护 } @@ -190,19 +171,19 @@ uint16_t slmp_build_send(void) { // 填充数据: 从寄存器映射读取,SLMP小端序,低字节在前 for (int i = 0; i < pointNum; i++) { - uint16_t value = get_register(1200 + (20 * slmp_idx) + i); - slmp_txbuf[i * 2 + 21] = value & 0xFF; // 低字节在前 - slmp_txbuf[i * 2 + 22] = (value >> 8) & 0xFF; // 高字节在后 + uint16_t value = get_register(master.localStartIdx + (20 * myRtumSTIdx) + i); + comm_buf[i * 2 + 21] = value & 0xFF; // 低字节在前 + comm_buf[i * 2 + 22] = (value >> 8) & 0xFF; // 高字节在后 } // 拷贝帧头到发送缓冲区 - for (int i = 0; i < 21 && i < sizeof(slmp_txbuf); i++) { - slmp_txbuf[i] = slmp_frame.frameU8[i]; + for (int i = 0; i < 21 && i < sizeof(comm_buf); i++) { + comm_buf[i] = slmp_frame.frameU8[i]; } } // 索引轮转,下次处理下一个通道 (和FINS完全一样) - slmp_idx = (slmp_idx + 1) % 20; + myRtumSTIdx = (myRtumSTIdx + 1) % 20; return sendsize; } @@ -211,8 +192,11 @@ uint16_t slmp_build_send(void) { * @note 和FINS完全一致 */ void update_timeout_slmp(void) { - if (slmpTimegap < 0xffff) { - slmpTimegap++; + if (timeout < 0xffff) { + timeout++; + } + if (commled_off_timeout < 0xffff) { + commled_off_timeout++; } } @@ -224,6 +208,13 @@ void update_timeout_slmp(void) { * @return int32_t: 0/正表示正常,负表示错误 */ int32_t loopback_tcpc_slmp(uint8_t sn, uint8_t *destip, uint16_t destport) { + 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; // 本地端口,自动递增 @@ -239,32 +230,35 @@ int32_t loopback_tcpc_slmp(uint8_t sn, uint8_t *destip, uint16_t destport) { // 1. 接收响应 if ((size = getSn_RX_RSR(sn)) > 0) { // 边界保护,不超过缓冲区 - if (size > sizeof(slmp_rxbuf)) { - size = sizeof(slmp_rxbuf); + if (size > sizeof(comm_buf)) { + size = sizeof(comm_buf); } - ret = recv(sn, slmp_rxbuf, size); - if (ret <= 0) { - return ret; - } else { + ret = recv(sn, comm_buf, size); + if (ret > 0) { + commled_off_timeout = 0; comm_count++; - slmp_handle_recv(ret); // 处理响应 - slmpTimegap = 900; // 重置超时 + handleReadRecvSLMP(size); + timeout = 490; } } - // 2. 超时到了,发送下一个请求 + // 超时触发发送 size = 0; - if (slmpTimegap > 1000) { - size = slmp_build_send(); // 构建请求 + if (timeout > 500) { + size = handleSendSLMP(); if (size == 0) { - slmpTimegap = 1000; // 参数非法,等待下一次 + // 无效通道,快速跳过 + timeout = 499; + } else { + // 有效发送,重置超时 + timeout = 0; } } // 3. 发送请求(分片发送,直到发完) sentsize = 0; while (size != 0 && sentsize != size) { - ret = send(sn, slmp_txbuf + sentsize, size - sentsize); + ret = send(sn, comm_buf + sentsize, size - sentsize); if (ret < 0) { close(sn); return ret; @@ -273,21 +267,21 @@ int32_t loopback_tcpc_slmp(uint8_t sn, uint8_t *destip, uint16_t destport) { } break; - // ========== 对方关闭连接 ========== + // ========== 对方关闭连接 ========== case SOCK_CLOSE_WAIT: if ((ret = disconnect(sn)) != SOCK_OK) { return ret; } break; - // ========== 初始化: 发起连接 ========== + // ========== 初始化: 发起连接 ========== case SOCK_INIT: if ((ret = connect(sn, destip, destport)) != SOCK_OK) { return ret; } break; - // ========== socket未打开: 新建socket ========== + // ========== socket未打开: 新建socket ========== case SOCK_CLOSED: close(sn); // 端口绕回,超过最大值后重置 diff --git a/comm/protocols/slmptcpmaster.h b/protocols/slmptcpmaster.h similarity index 75% rename from comm/protocols/slmptcpmaster.h rename to protocols/slmptcpmaster.h index fbd263c..f3f7c6b 100644 --- a/comm/protocols/slmptcpmaster.h +++ b/protocols/slmptcpmaster.h @@ -16,13 +16,7 @@ extern "C" { // 全局变量 // ============================================================================ -extern uint8_t slmp_txbuf[1024]; // 发送缓冲区 -extern uint8_t slmp_rxbuf[1024]; // 接收缓冲区 -extern uint16_t slmp_idx; // 当前轮询索引 (0~9) -extern uint16_t slmp_addr; // 当前请求起始地址 -extern uint16_t slmp_size; // 当前请求点数 -extern uint16_t slmpTimegap; // 超时计数,由主循环递增 -extern uint16_t comm_count; // 通信计数 + // ============================================================================ // 接口函数