[Solved] Python script for RTU Modbus Slave

I am working on a automation test case for a system and need a automated modbus input device.

My use case here is to implement a Raspberry pi based RTU modbus slave and connected to a modbus master.

I want this raspberry pi based slave to populate and send a response to master when ever master requests for a register value.

I am new to this protocol and environment, I am not able to find any python script or libraries where we have a modbus slave client.

I came across this below Serial python code and I could sucessfully decode modbus requests from the Master,

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

Problem I am facing here is this block of code just prints a seris of serial bits and I am not sure how to decode modbus packets from these…

OUTPUT:
b’x1ex03x00x19x00x01Wxa2x1ex10x00x0fx00x01x02x03 +xb7x1ex03x00n’
b’x00x02xe6fx1ex03x00tx00x01Vgx1ex10x00x10x00x01x02x01,(xbdx1ex03x00n’
b’x00x02xe6fx1ex03x00tx00x01Vgx1ex10x00x11x00x01x02x03 (tx1ex03x00n’
b’x00x02xe6fx1ex03x00tx00x01Vgx1ex10x00x12x00x01x02x01,)_x1ex03x00n’
b’x00x02xe6fx1ex03x00tx00x01Vgx1ex03x00n’
b’x00x02xe6fx1ex03x00tx00x01Vgx1ex03x00n’

Can anyone please point me to the right direction on what to look for or is there similar script implemented.

Thanks in advance.

Enquirer: vkrm

||

Solution #1:

Pymodbus library has several examples for server/slave/responder (usually devices are a server/slave) and master/client/requester. The procedure in the Modbus protocol is such that the server/slave must give a request from the master/client side, then response to it.


Here is a Modbus RTU client (master) snippet code to read from a Modbus RTU server (slave) or a Modbus device by the pymodbus library:

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

Respondent: Benyamin Jafari

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Leave a Reply

Your email address will not be published.