Search code examples
pythonpython-3.xmodbusmodbus-tcp

ModbusTcpClient: How to read long integer values from Input registers in python


I am trying to get data from a sensor using ModbusTcpClient as below

client = ModbusTcpClient('xx.xx.xx.xx', port=502)
connection = client.connect()
request = client.read_input_registers(220,2, unit=51, debug=False)
result = request.registers
print(result)

With this result i am getting a list of unsigned decimal. How can i convert this to long int or swapped long

The result i am getting from the above code

2023-04-24 12:18:59,856 MainThread      DEBUG    transaction    :297      RECV: 0x0 0x2 0x0 0x0 0x0 0x7 0x33 0x4 0x4 0x0 0x28 0x8a 0x23
2023-04-24 12:18:59,857 MainThread      DEBUG    socket_framer  :147      Processing: 0x0 0x2 0x0 0x0 0x0 0x7 0x33 0x4 0x4 0x0 0x28 0x8a 0x23
2023-04-24 12:18:59,857 MainThread      DEBUG    factory        :266      Factory Response[ReadInputRegistersResponse: 4]
2023-04-24 12:18:59,858 MainThread      DEBUG    transaction    :454      Adding transaction 2
2023-04-24 12:18:59,859 MainThread      DEBUG    transaction    :465      Getting transaction 2
2023-04-24 12:18:59,859 MainThread      DEBUG    transaction    :224      Changing transaction state from 'PROCESSING REPLY' to 'TRANSACTION_COMPLETE'
[40, 35363]

But i need the [40, 35363] to be shown as swapped long as 2656849

Thanks,

Edit:

I have answered with my code below


Solution

  • So i achieved this by the following code,

    client = ModbusTcpClient('xx.xx.xx.xx', port=502)
    connection = client.connect()
    request = client.read_input_registers(220,2, unit=51, debug=False)
    result = request.registers
    
    decoder = BinaryPayloadDecoder.fromRegisters(request.registers, byteorder=Endian.Big, wordorder=Endian.Big)
    active_power_w = decoder.decode_32bit_int()
    print(active_power_w)
    

    Hope this helps...!