pythonmodbusrs485pymodbus3minimalmodbus

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

Solution

  • 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