1

我有一个可以使用 pymodbus 库处理 Modbus 事务的 python 脚本。出于故障排除目的,我想打印发送和接收到设备的原始字节,最好是十六进制格式。

这是简化的代码,请参阅底部的注释以获取我想要的示例。我使用了 TCP 客户端,但希望它也可以在 ModbusSerialClient 上工作。

from pymodbus.client.sync import ModbusTcpClient

ipAddress = '10.130.14.174'
registerToRead = 3000

client = ModbusTcpClient(ipAddress, port=502)
connection = client.connect()

response = client.read_holding_registers(registerToRead, 1, unit=1)

print(response.registers)

# Would like to get something like:
# OUT: [00h] [00h] [00h] [00h] [00h] [06h] [01h] [03h] [0Bh] [B8h] [00h] [01h] 
# IN : [00h] [00h] [00h] [00h] [00h] [05h] [01h] [03h] [02h] [00h] [FFh] 

我试过response.encode()了,但只回来了b'\x02\x00\xff'

4

1 回答 1

2

要获取原始帧,您只需在调试模式下运行请求。

那将是这样的:

from pymodbus.client.sync import ModbusTcpClient
import logging
FORMAT = ('%(asctime)-15s %(threadName)-15s '
          '%(levelname)-8s %(module)-15s:%(lineno)-8s %(message)s')
logging.basicConfig(format=FORMAT)
log = logging.getLogger()
log.setLevel(logging.DEBUG)

ipAddress = '10.130.14.174'
registerToRead = 3000

client = ModbusTcpClient(ipAddress, port=502)
connection = client.connect()

response = client.read_holding_registers(registerToRead, 1, unit=1)

如果您现在从 Python 控制台运行此代码,您应该会看到与此类似的内容:

2019-10-08 13:10:42,872 MainThread      DEBUG    transaction    :111      Current transaction state - TRANSACTION_COMPLETE
2019-10-08 13:10:42,872 MainThread      DEBUG    transaction    :116      Running transaction 3
2019-10-08 13:10:42,872 MainThread      DEBUG    transaction    :215      SEND: 0x0 0x3 0x0 0x0 0x0 0x6 0x1 0x3 0x0 0x1 0x0 0x1
2019-10-08 13:10:42,872 MainThread      DEBUG    sync           :73       New Transaction state 'SENDING'
2019-10-08 13:10:42,872 MainThread      DEBUG    transaction    :224      Changing transaction state from 'SENDING' to 'WAITING FOR REPLY'
2019-10-08 13:10:42,873 MainThread      DEBUG    transaction    :300      Changing transaction state from 'WAITING FOR REPLY' to 'PROCESSING REPLY'
2019-10-08 13:10:42,873 MainThread      DEBUG    transaction    :229      RECV: 0x0 0x3 0x0 0x0 0x0 0x5 0x1 0x3 0x2 0x0 0x14
2019-10-08 13:10:42,873 MainThread      DEBUG    socket_framer  :147      Processing: 0x0 0x3 0x0 0x0 0x0 0x5 0x1 0x3 0x2 0x0 0x14
2019-10-08 13:10:42,873 MainThread      DEBUG    factory        :266      Factory Response[ReadHoldingRegistersResponse: 3]
2019-10-08 13:10:42,873 MainThread      DEBUG    transaction    :379      Adding transaction 3
2019-10-08 13:10:42,873 MainThread      DEBUG    transaction    :390      Getting transaction 3
2019-10-08 13:10:42,873 MainThread      DEBUG    transaction    :189      Changing transaction state from 'PROCESSING REPLY' to 'TRANSACTION_COMPLETE'
>>> 

如果你想要更多细节或者你需要处理多个框架,我建议安装非常强大的Wireshark 。如果您需要对 Modbus over serial 执行相同操作,可以尝试SerialPCAP

编辑:这可能是您目前不需要的东西,但如果您无法访问 Modbus 串行链路的任一侧,您可以点击总线或使用软件嗅探器,正如我在此处此处此处所解释的那样.

对于 Modbus TCP,如果您无法访问链路的任一侧或网络交换机,我不知道有任何简单的技术可以使用 Wireshark 监控流量。

于 2019-10-08T11:19:30.393 回答