Yang
Yang

Reputation: 189

Can I read Modbus RS485 data received on a slave computer with Python?

I am working on a slave computer and want to save the data transmitted from the master via Modbus RS485, into a text file. The master computer constantly send writing and reading request to the slave computer I am working on, below is a picture captured by serial port monitor.

enter image description here

I just found with minimalmodbus you can read registers. But it seems to only work if you are a master device. Can I do something similar but on a slave computer? http://minimalmodbus.readthedocs.io/en/master/usage.html

#!/usr/bin/env python
import minimalmodbus

instrument = minimalmodbus.Instrument('/dev/ttyUSB1', 1) # port name, slave 
#address (in decimal)

## Read temperature (PV = ProcessValue) ##
temperature = instrument.read_register(289, 1) # Registernumber, number of 
#decimals
print temperature

## Change temperature setpoint (SP) ##
NEW_TEMPERATURE = 95
instrument.write_register(24, NEW_TEMPERATURE, 1) # Registernumber, value, 
#number of decimals for storage

Upvotes: 1

Views: 9881

Answers (2)

luc
luc

Reputation: 43096

modbus-tk makes possible to write your own modbus slave.

Here is an example running a RTU server with 100 holding registers starting at adress 0 :

import sys

import modbus_tk
import modbus_tk.defines as cst
from modbus_tk import modbus_rtu
import serial


PORT = 0
#PORT = '/dev/ptyp5'

def main():
    """main"""
    logger = modbus_tk.utils.create_logger(name="console", record_format="%(message)s")

    #Create the server
    server = modbus_rtu.RtuServer(serial.Serial(PORT))

    try:
        logger.info("running...")
        logger.info("enter 'quit' for closing the server")

        server.start()

        slave_1 = server.add_slave(1)
        slave_1.add_block('0', cst.HOLDING_REGISTERS, 0, 100)
        while True:
            cmd = sys.stdin.readline()
            args = cmd.split(' ')

            if cmd.find('quit') == 0:
                sys.stdout.write('bye-bye\r\n')
                break

    finally:
        server.stop()

if __name__ == "__main__":
    main()

I hope it helps

Upvotes: 2

Gsk
Gsk

Reputation: 2945

You may want to manage serial port directly.

For doing this, you can use the pyserial module and you must know how Modbus Protocol works.

A base configuration could be:

import serial

port = '/dev/ttyUSB1'
serial_comunication = serial.Serial(port, baudrate=4800, timeout=0.75)
serial_comunication.write(b'frame')
answer = serial_comunication.read(255)
serial_comunication.close()
print answer.decode()

Upvotes: 0

Related Questions