RTU Modbus从站的Python脚本

时间:2019-01-23 17:28:36

标签: python raspberry-pi modbus pymodbus minimalmodbus

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

我的用例是实现基于Raspberry pi的RTU modbus从站并连接到modbus主站。

当主服务器请求寄存器值时,我希望这个基于树莓派的从服务器填充并向主服务器发送响应。

我对这个协议和环境不熟悉,我找不到我们有modbus从属客户端的任何python脚本或库。

我在串行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' b'\ x00 \ x02 \ xe6f \ x1e \ x03 \ x00 \ t \ x00 \ x01Vg \ x1e \ x03 \ x00 \ n'

任何人都可以向我指出要寻找的正确方向,或者是否实施了类似的脚本。

先谢谢了。

1 个答案:

答案 0 :(得分:1)

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')