You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Siemens Logo! 8与pymodbus连接后写入线圈报错求助

问题:Siemens Logo! 8与pymodbus连接后写入线圈报错WinError 10054

环境与配置

  • 设备:Siemens Logo! 8
  • 配置工具:Siemens Logo!Soft Comfort
  • 已做配置:
    • 配置网络输入(尝试过Unit ID 255,Modbus类型设为“DI”)
    • 测试过PC端两种接口配置(附配置截图)
  • 测试代码:
import time
from pymodbus.client import ModbusTcpClient

client = ModbusTcpClient('192.168.0.3')
print(client.connect())
while True:
    time.sleep(1)
    print(client.write_coil(1, True))
    time.sleep(1)
    print(client.write_coil(1, False))
  • 执行输出:
True
Modbus Error: [Input/Output] [WinError 10054] An existing connection was forcibly closed by the remote host
Modbus Error: [Input/Output] [WinError 10054] An existing connection was forcibly closed by the remote host

解决方案与排查步骤

1. 纠正Modbus操作类型与地址映射错误

你配置的是网络输入(DI,离散输入),但代码中尝试写入线圈(Coil)——线圈对应设备的数字输出(DO),而离散输入是只读属性,设备收到写入只读寄存器的请求后会直接断开连接,这是报错的核心原因。

  • 若要测试写入操作,需在Logo!Soft Comfort中配置网络输出(DO),并对应正确的Modbus线圈地址。
  • 参考Logo! 8的Modbus地址映射规则:
    • 数字输出(Q点)对应Modbus线圈为0-based地址,比如Q0.0对应地址0,Q0.1对应地址1,以此类推。
    • 离散输入(I点)对应Modbus离散输入寄存器,仅能通过read_discrete_inputs方法读取,无法写入。

2. 明确指定Modbus Unit ID

pymodbus默认使用Unit ID 1,但你尝试过Unit ID 255(广播地址),需在代码中明确指定与Logo!配置匹配的Unit ID:

# 假设Logo!配置的Unit ID为1,Q0.0对应线圈地址0
print(client.write_coil(0, True, unit=1))

注意:广播地址(255)通常仅支持读操作,不支持写入,建议使用设备配置的具体Unit ID(范围1~247)。

3. 检查Logo!的Modbus TCP写入权限

在Logo!Soft Comfort中确认已启用Modbus TCP的写入权限:

  • 进入Logo!网络配置页面,找到Modbus TCP设置项。
  • 确保“允许写入”选项已勾选,部分设备默认仅开启只读权限。

4. 优化代码的连接与错误处理

加入连接状态检查和异常捕获,避免因连接中断导致的重复报错:

import time
from pymodbus.client import ModbusTcpClient

client = ModbusTcpClient('192.168.0.3', port=502)  # 明确指定Modbus默认端口502
if client.connect():
    print("连接成功")
else:
    print("连接失败,请检查网络配置")
    exit()

try:
    while True:
        # 每次操作前检查连接状态,断开则尝试重连
        if not client.is_socket_open():
            print("连接已断开,尝试重连...")
            client.connect()
        
        # 写入Q0.0(线圈地址0,Unit ID 1)
        response = client.write_coil(0, True, unit=1)
        print("写入成功" if not response.isError() else f"写入失败:{response}")
        time.sleep(1)
        
        response = client.write_coil(0, False, unit=1)
        print("写入成功" if not response.isError() else f"写入失败:{response}")
        time.sleep(1)
except KeyboardInterrupt:
    client.close()
    print("程序终止")

5. 网络与防火墙排查

  • 确认PC与Logo!处于同一网段,执行ping 192.168.0.3测试连通性。
  • 关闭PC防火墙,或允许Python程序通过防火墙(避免端口502被拦截)。
  • 检查Logo!的Modbus TCP连接数限制,部分设备仅支持有限的并发连接。

内容的提问来源于stack exchange,提问作者Engensmax

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 03:50:25