RTU Modbus的Python脚本

2024-09-29 23:31:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在为一个系统的自动化测试用例工作,需要一个自动化的modbus输入设备。在

我这里的用例是实现一个基于Raspberry pi的RTU modbus从站,并连接到modbus主机。在

我希望这个基于raspberry pi的从设备在主设备请求寄存器值时填充并向master发送响应。在

我是新的协议和环境,我不能找到任何python脚本或库,我们有一个modbus从客户端。在

我遇到了下面的串行python代码,我可以成功地解码来自主机的modbus请求

import serial
import time

receiver = serial.Serial(     
     port='/dev/ttyUSB0',        
     baudrate = 115200,
     parity=serial.PARITY_NONE,
     stopbits=serial.STOPBITS_ONE,
     bytesize=serial.EIGHTBITS,
     timeout=1
     )

while 1:
      x = receiver.readline()
      print x

我在这里面临的问题是这个代码块只是打印一系列串行位,我不知道如何从这些串行位解码modbus数据包。。。在

输出: b'\x1e\x03\x00\x19\x00\x01W\xa2\x1e\x10\x00\x0f\x00\x01\x02\x03+\xb7\x1e\x03\x00\n' b'\x00\x02\xe6f\x1e\x03\x00\t\x00\x01Vg\x1e\x10\x00\x10\x00\x01\x02\x01,(\xbd\x1e\x03\x00\n' b'\x00\x02\xe6f\x1e\x03\x00\t\x00\x01Vg\x1e\x10\x00\x11\x00\x01\x02\x03(\t\x1e\x03\x00\n' b'\x00\x02\xe6f\x1e\x03\x00\t\x00\x01Vg\x1e\x10\x00\x12\x00\x01\x02\x01,)\x1e\x03\x00\n' b'\x00\x02\xe6f\x1e\x03\x00\t\x00\x01Vg\x1e\x03\x00\n' \x03\x00\xf\xx00\xf\xx00\xf\xxx03

有谁能给我指出正确的方向,寻找什么或有类似的脚本实现。在

提前谢谢。在


Tags: 代码脚本serialpi解码modbusx10xf
1条回答
网友
1楼 · 发布于 2024-09-29 23:31:02

Pymodbus库有几个服务器/从机/响应程序(通常设备是服务器/从设备)和主/客户机/请求程序的示例。Modbus协议中的程序是这样的:服务器/从机必须从主/客户端发出请求,然后对其作出响应。在


以下是Modbus RTU客户端(主)代码段,可通过pymodbus库从Modbus RTU服务器(从机)或Modbus设备读取:

from pymodbus.client.sync import ModbusSerialClient

client = ModbusSerialClient(
    method='rtu',
    port='/dev/ttyUSB0',
    baudrate=115200,
    timeout=3,
    parity='N',
    stopbits=1,
    bytesize=8
)

if client.connect():  # Trying for connect to Modbus Server/Slave
    '''Reading from a holding register with the below content.'''
    res = client.read_holding_registers(address=1, count=1, unit=1)

    '''Reading from a discrete register with the below content.'''
    # res = client.read_discrete_inputs(address=1, count=1, unit=1)

    if not res.isError():
        print(res.registers)
    else:
        print(res)

else:
    print('Cannot connect to the Modbus Server/Slave')

相关问题 更多 >

    热门问题