Search code examples
pythonserial-portmodbusmodbus-tcppymodbus

How to read/write a device's register connected to a gateway with pymodbus via TCP


I have to read and write a sensor using pymodbus. I'm not directly connected to the sensor, but I'm connected via TCP to a gateway and the gateway is connected via serial to the sensor.
I established a connection with the gateway in this way:

client = ModbusClient("192.168.127.254", 502)
connection = client.connect()

The connection with the gateway works because the socket is open. But I can't read from the sensor in this way:

if connection:
    request = client.read_holding_registers(0x00, 8, unit=1)
    data = validator(request)
    print(data)

    request = client.read_holding_registers(0x00, 8, unit=1)  
    data = validator(request)
    print(data)

    client.close()

How can I connect with the specify sensor connected to the gateway (id: 230, baud rate: 9600, parity: None, interface: RS-4852 wire)?

PS: The gateway is a Moxa MGate MB3170


Solution

  • First you should know about your modbus slave register tables(your sensor) and know about it functions codes if read function code is 0x3 you should use Read Holding Registers and if function code is 0x4 you should use Read Input Registers functions

    after that you should find your require register address , ex:temp register address is 0x05 and number of bytes is 2 and your sensor id is 230 and requirement function code is 0x3

    read_holding_registers(0x05 , 2, unit=230)