暂存
This commit is contained in:
@ -74,6 +74,15 @@ extern "C" {
|
||||
比如:设备A烧录时改为 0x01,设备B烧录时改为 0x02
|
||||
========================================================= */
|
||||
#define MY_DEVICE_ID 0x02
|
||||
|
||||
/* =========================================================
|
||||
🚀 开发调试开关
|
||||
TEST_A701:
|
||||
- 1: 测试环境 (A701室/本地测试),使用 192.168.6.x 网段
|
||||
- 0: 生产环境 (实船/现场部署),使用 192.168.0.x 网段
|
||||
========================================================= */
|
||||
#define TEST_A701 1
|
||||
|
||||
/* USER CODE END EM */
|
||||
|
||||
/* Exported functions prototypes ---------------------------------------------*/
|
||||
|
||||
50
Core/Inc/modbus_tcp_client.h
Normal file
50
Core/Inc/modbus_tcp_client.h
Normal file
@ -0,0 +1,50 @@
|
||||
/**
|
||||
******************************************************************************
|
||||
* @file modbus_tcp_client.h
|
||||
* @brief Modbus TCP 客户端模块头文件 (基于 W5500)
|
||||
******************************************************************************
|
||||
*/
|
||||
|
||||
#ifndef __MODBUS_TCP_CLIENT_H
|
||||
#define __MODBUS_TCP_CLIENT_H
|
||||
|
||||
#include <stdint.h>
|
||||
#include <stdbool.h>
|
||||
#include "main.h"
|
||||
|
||||
/* Modbus TCP 配置 */
|
||||
#if TEST_A701
|
||||
#define MODBUS_SERVER_IP {192, 168, 6, 4} /* A701 测试服务器 */
|
||||
#else
|
||||
#define MODBUS_SERVER_IP {192, 168, 0, 1} /* 现场生产服务器 */
|
||||
#endif
|
||||
|
||||
#define MODBUS_SERVER_PORT 502
|
||||
#define MODBUS_UNIT_ID 1
|
||||
#define MODBUS_POLL_INTERVAL 2000 /* 轮询间隔 (ms) */
|
||||
|
||||
/* 寄存器定义 */
|
||||
#define TARGET_REG_ADDR 30 /* 逻辑 40031 */
|
||||
|
||||
/* 客户端状态枚举 */
|
||||
typedef enum {
|
||||
MODBUS_STATE_IDLE,
|
||||
MODBUS_STATE_CONNECTING,
|
||||
MODBUS_STATE_SEND_QUERY,
|
||||
MODBUS_STATE_WAIT_RESPONSE,
|
||||
MODBUS_STATE_PROCESS_DATA,
|
||||
MODBUS_STATE_ERROR_RETRY
|
||||
} modbus_client_state_t;
|
||||
|
||||
/**
|
||||
* @brief 初始化 Modbus TCP 客户端
|
||||
* @param sn: W5500 Socket 编号
|
||||
*/
|
||||
void ModbusTCP_Client_Init(uint8_t sn);
|
||||
|
||||
/**
|
||||
* @brief Modbus TCP 客户端任务处理 (主循环调用)
|
||||
*/
|
||||
void ModbusTCP_Client_Task(void);
|
||||
|
||||
#endif
|
||||
@ -47,6 +47,7 @@
|
||||
#include "wiz_interface.h"
|
||||
#include "wizchip_conf.h"
|
||||
#include "loopback.h"
|
||||
#include "modbus_tcp_client.h"
|
||||
#endif
|
||||
extern void wiz_timer_handler(void);
|
||||
#if (RF433_MODE == RF433_MODE_TX) || (RF433_MODE == RF433_MODE_BOTH)
|
||||
@ -263,8 +264,16 @@ int main(void)
|
||||
|
||||
printf("[DEBUG] 4. 进入 network_init()\r\n");
|
||||
network_init(ethernet_buf, &default_net_info);
|
||||
printf("[DEBUG] 5. network_init() 成功返回!\r\n");
|
||||
printf("wizchip UDP example started\r\n");
|
||||
printf("[DEBUG] 5. network_init() 成功返回!\n");
|
||||
|
||||
printf("--- Socket Status Diagnostic ---\n");
|
||||
for (int i=0; i<8; i++) {
|
||||
printf("Socket %d SR: 0x%02X\n", i, getSn_SR(i));
|
||||
}
|
||||
printf("--------------------------------\n");
|
||||
|
||||
printf("Modbus TCP Client starting\n");
|
||||
ModbusTCP_Client_Init(1); // 暂时使用 Socket 1 进行测试,避开可能被污染的 Socket 0
|
||||
#endif
|
||||
/* ======================================= */
|
||||
|
||||
@ -307,9 +316,9 @@ int main(void)
|
||||
rf433_rx_app_task();
|
||||
#endif
|
||||
|
||||
/* W5500 UDP回环任务 */
|
||||
/* W5500 UDP回环任务(为了测试 PING 功能,放到了单独的 Socket 2) */
|
||||
#if USE_W5500
|
||||
loopback_udps(SOCKET_ID, ethernet_buf, local_port);
|
||||
loopback_udps(2, ethernet_buf, local_port);
|
||||
#endif
|
||||
|
||||
|
||||
@ -389,9 +398,8 @@ int main(void)
|
||||
}
|
||||
#endif
|
||||
|
||||
// (D) W5500 以太网轮询处理 (Type 0x55)
|
||||
#if USE_W5500
|
||||
loopback_udps(SOCKET_ID, ethernet_buf, local_port);
|
||||
ModbusTCP_Client_Task();
|
||||
#endif
|
||||
|
||||
/* USER CODE END WHILE */
|
||||
|
||||
175
Core/Src/modbus_tcp_client.c
Normal file
175
Core/Src/modbus_tcp_client.c
Normal file
@ -0,0 +1,175 @@
|
||||
/**
|
||||
******************************************************************************
|
||||
* @file modbus_tcp_client.c
|
||||
* @brief Modbus TCP 客户端模块实现 (针对寄存器 40031 轮询)
|
||||
******************************************************************************
|
||||
*/
|
||||
|
||||
#include "modbus_tcp_client.h"
|
||||
#include "socket.h"
|
||||
#include "wizchip_conf.h"
|
||||
#include "main.h"
|
||||
#include "debug_log.h"
|
||||
#include <string.h>
|
||||
|
||||
/* 私有变量 */
|
||||
static uint8_t g_sn = 0;
|
||||
static modbus_client_state_t g_state = MODBUS_STATE_IDLE;
|
||||
static uint32_t g_last_tick = 0;
|
||||
static uint16_t g_transaction_id = 0;
|
||||
|
||||
/* 服务器信息 */
|
||||
static uint8_t dest_ip[4] = MODBUS_SERVER_IP;
|
||||
static uint16_t dest_port = MODBUS_SERVER_PORT;
|
||||
|
||||
/**
|
||||
* @brief 构造 Modbus TCP 请求包 (FC 03)
|
||||
*/
|
||||
static uint16_t build_read_request(uint8_t *buf, uint16_t addr, uint16_t qty)
|
||||
{
|
||||
g_transaction_id++;
|
||||
|
||||
/* MBAP Header */
|
||||
buf[0] = (uint8_t)(g_transaction_id >> 8);
|
||||
buf[1] = (uint8_t)(g_transaction_id & 0xFF);
|
||||
buf[2] = 0x00; /* Protocol ID (0 for Modbus) */
|
||||
buf[3] = 0x00;
|
||||
buf[4] = 0x00; /* Length (6 bytes follow UnitID) */
|
||||
buf[5] = 0x06;
|
||||
buf[6] = MODBUS_UNIT_ID;
|
||||
|
||||
/* PDU */
|
||||
buf[7] = 0x03; /* Function Code: Read Holding Registers */
|
||||
buf[8] = (uint8_t)(addr >> 8);
|
||||
buf[9] = (uint8_t)(addr & 0xFF);
|
||||
buf[10] = (uint8_t)(qty >> 8);
|
||||
buf[11] = (uint8_t)(qty & 0xFF);
|
||||
|
||||
return 12;
|
||||
}
|
||||
|
||||
void ModbusTCP_Client_Init(uint8_t sn)
|
||||
{
|
||||
g_sn = sn;
|
||||
g_state = MODBUS_STATE_IDLE;
|
||||
g_last_tick = HAL_GetTick();
|
||||
|
||||
/* 动态重新加载配置,防止静态初始化带来的宏定义未生效问题 */
|
||||
uint8_t ip[4] = MODBUS_SERVER_IP;
|
||||
dest_ip[0] = ip[0]; dest_ip[1] = ip[1]; dest_ip[2] = ip[2]; dest_ip[3] = ip[3];
|
||||
dest_port = MODBUS_SERVER_PORT;
|
||||
|
||||
LOG_INFO("MODBUS", "Client initialized on Socket %d, Target: %d.%d.%d.%d:%d",
|
||||
sn, dest_ip[0], dest_ip[1], dest_ip[2], dest_ip[3], dest_port);
|
||||
}
|
||||
|
||||
void ModbusTCP_Client_Task(void)
|
||||
{
|
||||
uint8_t tmp_buf[128]; // 临时接收缓存
|
||||
uint16_t len; // 接收长度
|
||||
int32_t ret; // 返回值
|
||||
|
||||
switch (g_state) // 客户端状态机切换
|
||||
{
|
||||
case MODBUS_STATE_IDLE: // 空闲状态
|
||||
if (HAL_GetTick() - g_last_tick >= MODBUS_POLL_INTERVAL) { // 检查轮询间隔 (2秒)
|
||||
g_state = MODBUS_STATE_CONNECTING; // 切换到连接状态
|
||||
}
|
||||
break;
|
||||
|
||||
case MODBUS_STATE_CONNECTING: // 连接中状态
|
||||
{
|
||||
uint8_t sr = getSn_SR(g_sn);
|
||||
switch(sr) // 获取当前 Socket 状态
|
||||
{
|
||||
case SOCK_CLOSED: // 如果 Socket 已关闭
|
||||
// 打开 TCP 模式的 Socket,分配随机本地端口以避免冲突
|
||||
if (socket(g_sn, Sn_MR_TCP, 50000 + (HAL_GetTick() % 10000), 0x00) == g_sn) {
|
||||
LOG_DEBUG("MODBUS", "Socket opened");
|
||||
}
|
||||
break;
|
||||
|
||||
case SOCK_INIT: // Socket 初始化成功,开始连接
|
||||
LOG_INFO("MODBUS", "Connecting to %d.%d.%d.%d:%d",
|
||||
dest_ip[0], dest_ip[1], dest_ip[2], dest_ip[3], dest_port);
|
||||
ret = connect(g_sn, dest_ip, dest_port); // 发起连接请求
|
||||
if (ret != SOCK_OK) {
|
||||
LOG_ERROR("MODBUS", "Connect failed: %d", ret);
|
||||
close(g_sn);
|
||||
g_state = MODBUS_STATE_IDLE;
|
||||
g_last_tick = HAL_GetTick();
|
||||
}
|
||||
break;
|
||||
|
||||
case SOCK_ESTABLISHED: // 连接已建立
|
||||
LOG_INFO("MODBUS", "TCP Connected!");
|
||||
g_state = MODBUS_STATE_SEND_QUERY; // 切换到发送请求状态
|
||||
break;
|
||||
|
||||
case SOCK_CLOSE_WAIT: // 对方已关闭连接
|
||||
disconnect(g_sn); // 本地断开连接
|
||||
break;
|
||||
|
||||
default:
|
||||
if (HAL_GetTick() % 5000 == 0) { // 每 5 秒打印一次未处理的状态
|
||||
LOG_WARN("MODBUS", "Unhandled socket state: 0x%02X", sr);
|
||||
}
|
||||
break;
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case MODBUS_STATE_SEND_QUERY: // 发送查询请求状态
|
||||
len = build_read_request(tmp_buf, TARGET_REG_ADDR, 1); // 构造 Modbus TCP FC03 报文
|
||||
ret = send(g_sn, tmp_buf, len); // 发送 TCP 数据
|
||||
if (ret > 0) { // 发送成功
|
||||
LOG_DEBUG("MODBUS", "Request sent (TID: %d)", g_transaction_id);
|
||||
g_state = MODBUS_STATE_WAIT_RESPONSE; // 切换到等待响应状态
|
||||
g_last_tick = HAL_GetTick(); // 更新计时器
|
||||
} else { // 发送失败
|
||||
LOG_ERROR("MODBUS", "Send failed, reconnecting...");
|
||||
close(g_sn); // 关闭 Socket
|
||||
g_state = MODBUS_STATE_IDLE; // 返回空闲重试
|
||||
}
|
||||
break;
|
||||
|
||||
case MODBUS_STATE_WAIT_RESPONSE: // 等待响应状态
|
||||
if ((len = getSn_RX_RSR(g_sn)) > 0) { // 检查是否有数据到达
|
||||
if (len > sizeof(tmp_buf)) len = sizeof(tmp_buf); // 防止缓存溢出
|
||||
ret = recv(g_sn, tmp_buf, len); // 接收数据
|
||||
if (ret > 0) { // 接收成功
|
||||
g_state = MODBUS_STATE_PROCESS_DATA; // 切换到处理数据状态
|
||||
}
|
||||
} else if (HAL_GetTick() - g_last_tick > 3000) { // 等待超时 (3秒)
|
||||
LOG_WARN("MODBUS", "Response timeout");
|
||||
close(g_sn); // 关闭连接
|
||||
g_state = MODBUS_STATE_IDLE; // 返回空闲重试
|
||||
}
|
||||
break;
|
||||
|
||||
case MODBUS_STATE_PROCESS_DATA: // 处理数据状态
|
||||
/* 校验响应 (检查 MBAP 长度、功能码等) */
|
||||
if (len >= 9 && tmp_buf[7] == 0x03) { // 基本校验
|
||||
uint16_t reg_val = (tmp_buf[9] << 8) | tmp_buf[10]; // 提取寄存器值
|
||||
LOG_INFO("MODBUS", "Read Register %d OK: 0x%04X", TARGET_REG_ADDR + 40001, reg_val);
|
||||
|
||||
/* 🚀 关键步骤:通过 433 无线转发结果 */
|
||||
uint8_t payload[2]; // 构造 433 负载
|
||||
payload[0] = tmp_buf[9]; // 寄存器高位
|
||||
payload[1] = tmp_buf[10]; // 寄存器低位
|
||||
RF433_SendPacket(PROTO_TYPE_NET, payload, 2); // 打包并通过无线发出
|
||||
|
||||
g_state = MODBUS_STATE_IDLE; // 处理完成,返回空闲
|
||||
g_last_tick = HAL_GetTick(); // 记录本次完成时间
|
||||
} else { // 响应格式非法
|
||||
LOG_ERROR("MODBUS", "Invalid response format");
|
||||
g_state = MODBUS_STATE_IDLE; // 返回空闲
|
||||
g_last_tick = HAL_GetTick(); // 更新计时
|
||||
}
|
||||
break;
|
||||
|
||||
default: // 异常保护
|
||||
g_state = MODBUS_STATE_IDLE;
|
||||
break;
|
||||
}
|
||||
}
|
||||
4268
MDK-ARM/JLinkLog.txt
4268
MDK-ARM/JLinkLog.txt
File diff suppressed because it is too large
Load Diff
@ -1,6 +1,7 @@
|
||||
|
||||
/*
|
||||
* UVISION generated file: DO NOT EDIT!
|
||||
* Generated by: uVision version 5.43.1.0
|
||||
* Auto generated Run-Time-Environment Component Configuration File
|
||||
* *** Do not modify ! ***
|
||||
*
|
||||
* Project: 'project'
|
||||
* Target: 'project'
|
||||
@ -16,5 +17,4 @@
|
||||
#define CMSIS_device_header "stm32f10x.h"
|
||||
|
||||
|
||||
|
||||
#endif /* RTE_COMPONENTS_H */
|
||||
|
||||
File diff suppressed because one or more lines are too long
@ -10,14 +10,14 @@
|
||||
<TargetName>project</TargetName>
|
||||
<ToolsetNumber>0x4</ToolsetNumber>
|
||||
<ToolsetName>ARM-ADS</ToolsetName>
|
||||
<pCCUsed>5060960::V5.06 update 7 (build 960)::.\ARMCC</pCCUsed>
|
||||
<pCCUsed>5060750::V5.06 update 6 (build 750)::ARMCC</pCCUsed>
|
||||
<uAC6>0</uAC6>
|
||||
<TargetOption>
|
||||
<TargetCommonOption>
|
||||
<Device>STM32F103C8</Device>
|
||||
<Vendor>STMicroelectronics</Vendor>
|
||||
<PackID>Keil.STM32F1xx_DFP.2.4.1</PackID>
|
||||
<PackURL>https://www.keil.com/pack/</PackURL>
|
||||
<PackID>Keil.STM32F1xx_DFP.1.1.0</PackID>
|
||||
<PackURL>http://www.keil.com/pack/</PackURL>
|
||||
<Cpu>IRAM(0x20000000-0x20004FFF) IROM(0x8000000-0x800FFFF) CLOCK(8000000) CPUTYPE("Cortex-M3") TZ</Cpu>
|
||||
<FlashUtilSpec></FlashUtilSpec>
|
||||
<StartupFile></StartupFile>
|
||||
@ -81,7 +81,7 @@
|
||||
</BeforeMake>
|
||||
<AfterMake>
|
||||
<RunUserProg1>0</RunUserProg1>
|
||||
<RunUserProg2>1</RunUserProg2>
|
||||
<RunUserProg2>0</RunUserProg2>
|
||||
<UserProg1Name></UserProg1Name>
|
||||
<UserProg2Name></UserProg2Name>
|
||||
<UserProg1Dos16Mode>0</UserProg1Dos16Mode>
|
||||
@ -184,9 +184,6 @@
|
||||
<hadXRAM>0</hadXRAM>
|
||||
<uocXRam>0</uocXRam>
|
||||
<RvdsVP>0</RvdsVP>
|
||||
<RvdsMve>0</RvdsMve>
|
||||
<RvdsCdeCp>0</RvdsCdeCp>
|
||||
<nBranchProt>0</nBranchProt>
|
||||
<hadIRAM2>0</hadIRAM2>
|
||||
<hadIROM2>0</hadIROM2>
|
||||
<StupSel>8</StupSel>
|
||||
@ -353,7 +350,7 @@
|
||||
<NoWarn>0</NoWarn>
|
||||
<uSurpInc>0</uSurpInc>
|
||||
<useXO>0</useXO>
|
||||
<ClangAsOpt>1</ClangAsOpt>
|
||||
<uClangAs>0</uClangAs>
|
||||
<VariousControls>
|
||||
<MiscControls></MiscControls>
|
||||
<Define></Define>
|
||||
@ -414,6 +411,11 @@
|
||||
<FileType>1</FileType>
|
||||
<FilePath>../Core/Src/main.c</FilePath>
|
||||
</File>
|
||||
<File>
|
||||
<FileName>modbus_tcp_client.c</FileName>
|
||||
<FileType>1</FileType>
|
||||
<FilePath>../Core/Src/modbus_tcp_client.c</FilePath>
|
||||
</File>
|
||||
<File>
|
||||
<FileName>gpio.c</FileName>
|
||||
<FileType>1</FileType>
|
||||
@ -783,14 +785,4 @@
|
||||
<files/>
|
||||
</RTE>
|
||||
|
||||
<LayerInfo>
|
||||
<Layers>
|
||||
<Layer>
|
||||
<LayName>project</LayName>
|
||||
<LayTarg>0</LayTarg>
|
||||
<LayPrjMark>1</LayPrjMark>
|
||||
</Layer>
|
||||
</Layers>
|
||||
</LayerInfo>
|
||||
|
||||
</Project>
|
||||
|
||||
@ -4,6 +4,7 @@
|
||||
"project\rf433_rx_app.o"
|
||||
"project\rf433_tx_app.o"
|
||||
"project\main.o"
|
||||
"project\modbus_tcp_client.o"
|
||||
"project\gpio.o"
|
||||
"project\spi.o"
|
||||
"project\usart.o"
|
||||
|
||||
@ -7,7 +7,6 @@ LR_IROM1 0x08000000 0x00010000 { ; load region size_region
|
||||
*.o (RESET, +First)
|
||||
*(InRoot$$Sections)
|
||||
.ANY (+RO)
|
||||
.ANY (+XO)
|
||||
}
|
||||
RW_IRAM1 0x20000000 0x00005000 { ; RW data
|
||||
.ANY (+RW +ZI)
|
||||
|
||||
16
MDK-ARM/project/project_sct.Bak
Normal file
16
MDK-ARM/project/project_sct.Bak
Normal file
@ -0,0 +1,16 @@
|
||||
; *************************************************************
|
||||
; *** Scatter-Loading Description File generated by uVision ***
|
||||
; *************************************************************
|
||||
|
||||
LR_IROM1 0x08000000 0x00010000 { ; load region size_region
|
||||
ER_IROM1 0x08000000 0x00010000 { ; load address = execution address
|
||||
*.o (RESET, +First)
|
||||
*(InRoot$$Sections)
|
||||
.ANY (+RO)
|
||||
.ANY (+XO)
|
||||
}
|
||||
RW_IRAM1 0x20000000 0x00005000 { ; RW data
|
||||
.ANY (+RW +ZI)
|
||||
}
|
||||
}
|
||||
|
||||
@ -461,11 +461,11 @@ ARM Macro Assembler Page 8
|
||||
|
||||
Command Line: --debug --xref --diag_suppress=9931 --cpu=Cortex-M3 --apcs=interw
|
||||
ork --depend=project\startup_stm32f103xb.d -oproject\startup_stm32f103xb.o -I.\
|
||||
RTE\_project -IC:\Users\xtell\AppData\Local\Arm\Packs\ARM\CMSIS\6.2.0\CMSIS\Cor
|
||||
e\Include -IC:\Users\xtell\AppData\Local\Arm\Packs\Keil\STM32F1xx_DFP\2.4.1\Dev
|
||||
ice\Include --predefine="__MICROLIB SETA 1" --predefine="__UVISION_VERSION SETA
|
||||
543" --predefine="STM32F10X_MD SETA 1" --predefine="_RTE_ SETA 1" --list=start
|
||||
up_stm32f103xb.lst startup_stm32f103xb.s
|
||||
RTE\_project -IC:\Keil_v5\ARM\PACK\ARM\CMSIS\5.4.0\CMSIS\Core\Include -IC:\Keil
|
||||
_v5\ARM\PACK\Keil\STM32F1xx_DFP\1.1.0\Device\Include --predefine="__MICROLIB SE
|
||||
TA 1" --predefine="__UVISION_VERSION SETA 525" --predefine="_RTE_ SETA 1" --pre
|
||||
define="STM32F10X_MD SETA 1" --list=startup_stm32f103xb.lst startup_stm32f103xb
|
||||
.s
|
||||
|
||||
|
||||
|
||||
|
||||
@ -4,6 +4,7 @@
|
||||
#include "wizchip_conf.h"
|
||||
#include "wiz_interface.h"
|
||||
#include "loopback.h"
|
||||
#include "main.h"
|
||||
|
||||
/*wizchip->STM32 Hardware Pin define*/
|
||||
// wizchip_SCS ---> STM32_GPIOD7
|
||||
@ -16,12 +17,16 @@
|
||||
/* Define network information */
|
||||
wiz_NetInfo default_net_info = {
|
||||
.mac = {0x00, 0x08, 0xdc, 0x12, 0x22, 0x12},
|
||||
.ip = {192, 168, 6, 212},
|
||||
#if TEST_A701
|
||||
.ip = {192, 168, 6, 7},
|
||||
.gw = {192, 168, 6, 1},
|
||||
#else
|
||||
.ip = {192, 168, 0, 5},
|
||||
.gw = {192, 168, 0, 1},
|
||||
#endif
|
||||
.sn = {255, 255, 255, 0},
|
||||
.dns = {8, 8, 8, 8},
|
||||
.dhcp = NETINFO_STATIC
|
||||
//.dhcp = NETINFO_STATIC //static ip
|
||||
};
|
||||
uint16_t local_port = 8000;
|
||||
uint8_t ethernet_buf[ETHERNET_BUF_MAX_SIZE] = {0};
|
||||
|
||||
BIN
docs/temp.zip
Normal file
BIN
docs/temp.zip
Normal file
Binary file not shown.
2
docs/xlsx_temp/[Content_Types].xml
Normal file
2
docs/xlsx_temp/[Content_Types].xml
Normal file
@ -0,0 +1,2 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/docProps/app.xml" ContentType="application/vnd.openxmlformats-officedocument.extended-properties+xml"/><Override PartName="/docProps/core.xml" ContentType="application/vnd.openxmlformats-package.core-properties+xml"/><Override PartName="/docProps/custom.xml" ContentType="application/vnd.openxmlformats-officedocument.custom-properties+xml"/><Override PartName="/xl/customStorage/customStorage.xml" ContentType="application/vnd.wps-officedocument.customStorage+xml"/><Override PartName="/xl/sharedStrings.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml"/><Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"/><Override PartName="/xl/theme/theme1.xml" ContentType="application/vnd.openxmlformats-officedocument.theme+xml"/><Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/><Override PartName="/xl/worksheets/sheet1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/></Types>
|
||||
2
docs/xlsx_temp/_rels/.rels
Normal file
2
docs/xlsx_temp/_rels/.rels
Normal file
@ -0,0 +1,2 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/><Relationship Id="rId3" Type="http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties" Target="docProps/core.xml"/><Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties" Target="docProps/app.xml"/><Relationship Id="rId4" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties" Target="docProps/custom.xml"/></Relationships>
|
||||
2
docs/xlsx_temp/docProps/app.xml
Normal file
2
docs/xlsx_temp/docProps/app.xml
Normal file
@ -0,0 +1,2 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<Properties xmlns="http://schemas.openxmlformats.org/officeDocument/2006/extended-properties" xmlns:vt="http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes"><Application>Microsoft Excel</Application><HeadingPairs><vt:vector size="2" baseType="variant"><vt:variant><vt:lpstr>工作表</vt:lpstr></vt:variant><vt:variant><vt:i4>1</vt:i4></vt:variant></vt:vector></HeadingPairs><TitlesOfParts><vt:vector size="1" baseType="lpstr"><vt:lpstr>外部通讯协议</vt:lpstr></vt:vector></TitlesOfParts></Properties>
|
||||
2
docs/xlsx_temp/docProps/core.xml
Normal file
2
docs/xlsx_temp/docProps/core.xml
Normal file
@ -0,0 +1,2 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<cp:coreProperties xmlns:cp="http://schemas.openxmlformats.org/package/2006/metadata/core-properties" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:dcmitype="http://purl.org/dc/dcmitype/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><dc:creator>lkl</dc:creator><cp:lastModifiedBy>lkl</cp:lastModifiedBy><dcterms:created xsi:type="dcterms:W3CDTF">2015-06-05T18:19:00Z</dcterms:created><dcterms:modified xsi:type="dcterms:W3CDTF">2026-05-09T04:21:37Z</dcterms:modified></cp:coreProperties>
|
||||
2
docs/xlsx_temp/docProps/custom.xml
Normal file
2
docs/xlsx_temp/docProps/custom.xml
Normal file
@ -0,0 +1,2 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<Properties xmlns="http://schemas.openxmlformats.org/officeDocument/2006/custom-properties" xmlns:vt="http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes"><property fmtid="{D5CDD505-2E9C-101B-9397-08002B2CF9AE}" pid="2" name="KSOProductBuildVer"><vt:lpwstr>2052-12.8.2.21549</vt:lpwstr></property><property fmtid="{D5CDD505-2E9C-101B-9397-08002B2CF9AE}" pid="3" name="ICV"><vt:lpwstr>32722E1FC28F465CAD8A47F6421DC308_13</vt:lpwstr></property></Properties>
|
||||
2
docs/xlsx_temp/xl/_rels/workbook.xml.rels
Normal file
2
docs/xlsx_temp/xl/_rels/workbook.xml.rels
Normal file
@ -0,0 +1,2 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId5" Type="http://www.wps.cn/officeDocument/2023/relationships/customStorage" Target="customStorage/customStorage.xml"/><Relationship Id="rId4" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/><Relationship Id="rId3" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings" Target="sharedStrings.xml"/><Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme" Target="theme/theme1.xml"/><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/></Relationships>
|
||||
2
docs/xlsx_temp/xl/customStorage/customStorage.xml
Normal file
2
docs/xlsx_temp/xl/customStorage/customStorage.xml
Normal file
@ -0,0 +1,2 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<customStorage xmlns="https://web.wps.cn/et/2018/main"><book/><sheets/></customStorage>
|
||||
2
docs/xlsx_temp/xl/sharedStrings.xml
Normal file
2
docs/xlsx_temp/xl/sharedStrings.xml
Normal file
@ -0,0 +1,2 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" count="419" uniqueCount="29"><si><t>Details</t></si><si><t>Address</t></si><si><t>Name</t></si><si><t>Bits</t></si><si><t>Write/Read</t></si><si><t>Definition</t></si><si><t>Type:Modbus TCP</t></si><si><t>备用</t></si><si><t>Write</t></si><si><t>IP Address:192.168.0.1</t></si><si><t>Port:502</t></si><si><t>Modbus ID:1</t></si><si><t>Modbus Offset:1</t></si><si><t>舵机舱浸水报警</t></si><si><t>Read</t></si><si><t>设备舱浸水报警</t></si><si><r><rPr><sz val="10.5"/><color theme="1"/><rFont val="宋体"/><charset val="134"/></rPr><t>机舱</t></r><r><rPr><sz val="10.5"/><color theme="1"/><rFont val="Calibri"/><charset val="134"/></rPr><t>1</t></r><r><rPr><sz val="10.5"/><color theme="1"/><rFont val="宋体"/><charset val="134"/></rPr><t>浸水报警</t></r></si><si><r><rPr><sz val="10.5"/><color theme="1"/><rFont val="宋体"/><charset val="134"/></rPr><t>机舱</t></r><r><rPr><sz val="10.5"/><color theme="1"/><rFont val="Calibri"/><charset val="134"/></rPr><t>2</t></r><r><rPr><sz val="10.5"/><color theme="1"/><rFont val="宋体"/><charset val="134"/></rPr><t>浸水报警</t></r></si><si><t>监控室浸水报警</t></si><si><t>电池舱浸水报警</t></si><si><t>船员舱浸水报警</t></si><si><r><rPr><sz val="10.5"/><color theme="1"/><rFont val="Calibri"/><charset val="134"/></rPr><t>2</t></r><r><rPr><sz val="10.5"/><color theme="1"/><rFont val="宋体"/><charset val="134"/></rPr><t>号通道浸水报警</t></r></si><si><t>艏侧推舱浸水报警</t></si><si><t>艏尖舱浸水报警</t></si><si><t>电池舱温度报警</t></si><si><t>电池舱可燃气体报警</t></si><si><t>机舱可燃气体报警</t></si><si><t>火灾报警</t></si><si><t>水密门报警</t></si></sst>
|
||||
2
docs/xlsx_temp/xl/styles.xml
Normal file
2
docs/xlsx_temp/xl/styles.xml
Normal file
File diff suppressed because one or more lines are too long
2
docs/xlsx_temp/xl/theme/theme1.xml
Normal file
2
docs/xlsx_temp/xl/theme/theme1.xml
Normal file
File diff suppressed because one or more lines are too long
2
docs/xlsx_temp/xl/workbook.xml
Normal file
2
docs/xlsx_temp/xl/workbook.xml
Normal file
@ -0,0 +1,2 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:dbsheet="http://web.wps.cn/et/2021/dbsheet"><fileVersion appName="xl" lastEdited="3" lowestEdited="5" rupBuild="9302"/><workbookPr/><bookViews><workbookView windowWidth="29870" windowHeight="15280"/></bookViews><sheets><sheet name="外部通讯协议" sheetId="2" r:id="rId1"/></sheets><definedNames><definedName name="_xlnm._FilterDatabase" localSheetId="0" hidden="1">外部通讯协议!#REF!</definedName></definedNames><calcPr calcId="191029"/><extLst><ext uri="{B58B0392-4F1F-4190-BB64-5DF3571DCE5F}" xmlns:xcalcf="http://schemas.microsoft.com/office/spreadsheetml/2018/calcfeatures"><xcalcf:calcFeatures><xcalcf:feature name="microsoft.com:RD"/><xcalcf:feature name="microsoft.com:Single"/><xcalcf:feature name="microsoft.com:FV"/><xcalcf:feature name="microsoft.com:CNMTM"/><xcalcf:feature name="microsoft.com:LET_WF"/><xcalcf:feature name="microsoft.com:LAMBDA_WF"/><xcalcf:feature name="microsoft.com:ARRAYTEXT_WF"/></xcalcf:calcFeatures></ext></extLst></workbook>
|
||||
2
docs/xlsx_temp/xl/worksheets/sheet1.xml
Normal file
2
docs/xlsx_temp/xl/worksheets/sheet1.xml
Normal file
File diff suppressed because one or more lines are too long
BIN
docs/多功能巡逻船阀门遥控系统 通讯协议(至无人值守系统)20260509.xlsx
Normal file
BIN
docs/多功能巡逻船阀门遥控系统 通讯协议(至无人值守系统)20260509.xlsx
Normal file
Binary file not shown.
62
python3/modbus_client_sim.py
Normal file
62
python3/modbus_client_sim.py
Normal file
@ -0,0 +1,62 @@
|
||||
import socket
|
||||
import struct
|
||||
import time
|
||||
|
||||
# 配置信息
|
||||
SERVER_IP = '127.0.0.1' # 模拟本地回路
|
||||
PORT = 502
|
||||
UNIT_ID = 1
|
||||
REG_ADDR = 30 # 逻辑 40031
|
||||
|
||||
def poll_register():
|
||||
# 1. 构造 Modbus TCP 请求 (Function Code 03)
|
||||
tid = 0x0001
|
||||
pid = 0x0000
|
||||
length = 6 # 后续字节长度 (UnitID 1 + PDU 5)
|
||||
uid = UNIT_ID
|
||||
|
||||
fc = 0x03
|
||||
addr = REG_ADDR
|
||||
qty = 1
|
||||
|
||||
# [MBAP Header] + [PDU]
|
||||
request = struct.pack('>HHHB', tid, pid, length, uid) + \
|
||||
struct.pack('>BHH', fc, addr, qty)
|
||||
|
||||
try:
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
||||
s.settimeout(2.0)
|
||||
s.connect((SERVER_IP, PORT))
|
||||
print(f"[TX] 发送请求: {request.hex(' ')}")
|
||||
s.sendall(request)
|
||||
|
||||
# 2. 接收响应
|
||||
response = s.recv(1024)
|
||||
if not response:
|
||||
print("[!] 服务器关闭了连接")
|
||||
return
|
||||
|
||||
print(f"[RX] 收到响应: {response.hex(' ')}")
|
||||
|
||||
if len(response) >= 9: # MBAP(7) + FC(1) + ByteCount(1)
|
||||
# 解析响应
|
||||
header = response[:7]
|
||||
pdu = response[7:]
|
||||
|
||||
res_tid, res_pid, res_len, res_uid = struct.unpack('>HHHB', header)
|
||||
res_fc = pdu[0]
|
||||
byte_count = pdu[1]
|
||||
reg_value = struct.unpack('>H', pdu[2:4])[0]
|
||||
|
||||
print(f"[+] 解析成功!")
|
||||
print(f" - 事务ID: {res_tid}")
|
||||
print(f" - 寄存器 {REG_ADDR} 的值: {hex(reg_value)} ({reg_value})")
|
||||
else:
|
||||
print("[!] 响应长度不足")
|
||||
|
||||
except Exception as e:
|
||||
print(f"[!] 连接错误: {e}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
print("[*] Python Modbus TCP 客户端模拟启动...")
|
||||
poll_register()
|
||||
122
python3/modbus_server_sim.py
Normal file
122
python3/modbus_server_sim.py
Normal file
@ -0,0 +1,122 @@
|
||||
import socket
|
||||
import struct
|
||||
import sys
|
||||
import msvcrt
|
||||
import datetime
|
||||
|
||||
# 配置信息
|
||||
HOST = '0.0.0.0' # 监听所有接口
|
||||
PORT = 502 # Modbus TCP 标准端口
|
||||
UNIT_ID = 1 # 目标 Unit ID
|
||||
|
||||
# 模拟寄存器存储 (30号地址 -> 40031逻辑地址)
|
||||
registers = {
|
||||
30: 0xABCD # 初始模拟值
|
||||
}
|
||||
|
||||
def get_time():
|
||||
"""获取当前格式化时间"""
|
||||
return datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
|
||||
|
||||
def handle_client(conn, addr):
|
||||
print(f"[{get_time()}] [*] 客户端已连接: {addr}")
|
||||
conn.settimeout(1.0)
|
||||
while True:
|
||||
try:
|
||||
data = conn.recv(1024)
|
||||
if not data:
|
||||
break
|
||||
|
||||
# 记录接收到的原始报文
|
||||
print(f"[{get_time()}] [RAW] 收到原始报文: {data.hex(' ')}")
|
||||
|
||||
if len(data) < 7:
|
||||
print(f"[{get_time()}] [!] 报文长度不足 7 字节")
|
||||
continue
|
||||
|
||||
tid, pid, length, uid = struct.unpack('>HHHB', data[:7])
|
||||
pdu = data[7:]
|
||||
|
||||
if len(pdu) < 5:
|
||||
print(f"[{get_time()}] [!] PDU 长度不足")
|
||||
continue
|
||||
|
||||
func_code = pdu[0]
|
||||
if func_code == 0x03:
|
||||
start_addr, qty = struct.unpack('>HH', pdu[1:5])
|
||||
print(f"[{get_time()}] [REQ] 读取保持寄存器: 起始地址={start_addr}, 数量={qty}, UnitID={uid}")
|
||||
|
||||
payload = b''
|
||||
for i in range(qty):
|
||||
val = registers.get(start_addr + i, 0)
|
||||
payload += struct.pack('>H', val)
|
||||
|
||||
resp_pdu = struct.pack('B', func_code) + struct.pack('B', len(payload)) + payload
|
||||
resp_length = len(resp_pdu) + 1
|
||||
resp_header = struct.pack('>HHHB', tid, pid, resp_length, uid)
|
||||
|
||||
conn.sendall(resp_header + resp_pdu)
|
||||
print(f"[{get_time()}] [RES] 已发送响应: {payload.hex(' ')}")
|
||||
else:
|
||||
print(f"[{get_time()}] [!] 不支持的功能码: {func_code}")
|
||||
|
||||
except socket.timeout:
|
||||
# 检查是否有退出按键
|
||||
if msvcrt.kbhit():
|
||||
if msvcrt.getch().decode('utf-8', errors='ignore').lower() == 'q':
|
||||
return True
|
||||
continue
|
||||
except Exception as e:
|
||||
print(f"[{get_time()}] [!] 错误: {e}")
|
||||
break
|
||||
conn.close()
|
||||
print(f"[{get_time()}] [*] 客户端连接已断开: {addr}")
|
||||
return False
|
||||
|
||||
def main():
|
||||
# 从命令行参数获取寄存器 30 的初始值
|
||||
if len(sys.argv) > 1:
|
||||
try:
|
||||
val_str = sys.argv[1]
|
||||
if val_str.startswith('0x'):
|
||||
registers[30] = int(val_str, 16)
|
||||
else:
|
||||
registers[30] = int(val_str)
|
||||
except ValueError:
|
||||
print(f"[!] 警告: 无效的参数 '{sys.argv[1]}',使用默认值 {hex(registers[30])}")
|
||||
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
||||
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||
s.settimeout(1.0)
|
||||
|
||||
try:
|
||||
s.bind((HOST, PORT))
|
||||
except PermissionError:
|
||||
print(f"[!] 错误: 无法绑定 {PORT} 端口。请尝试使用管理员权限运行。")
|
||||
return
|
||||
|
||||
s.listen()
|
||||
print(f"[{get_time()}] [*] Modbus TCP 模拟服务端启动,监听 {PORT} 端口...")
|
||||
print(f"[{get_time()}] [*] 寄存器 30 (40031) 当前值: {hex(registers[30])}")
|
||||
print("[*] 提示: 随时按下 'q' 键退出程序")
|
||||
|
||||
should_exit = False
|
||||
while not should_exit:
|
||||
if msvcrt.kbhit():
|
||||
if msvcrt.getch().decode('utf-8', errors='ignore').lower() == 'q':
|
||||
print("\n[*] 检测到 'q' 键,正在退出...")
|
||||
break
|
||||
|
||||
try:
|
||||
conn, addr = s.accept()
|
||||
should_exit = handle_client(conn, addr)
|
||||
except socket.timeout:
|
||||
continue
|
||||
except KeyboardInterrupt:
|
||||
print("\n[*] 正在停止服务端...")
|
||||
break
|
||||
|
||||
s.close()
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user