# -*- coding: utf-8 -*-
#!/usr/bin/env python

from twisted.internet import reactor, protocol
from pymodbus.client.async import ModbusClientProtocol
from pymodbus.payload import BinaryPayloadDecoder
from pymodbus.constants import Endian

def process(response):
    import pudb; pudb.set_trace()
    decoder = BinaryPayloadDecoder.fromRegisters(
        response.registers,
        byteorder=Endian.Little,
        wordorder=Endian.Little
    )
    print 'From decoder (byteorder=LE, wordorder=LE): ',
    print decoder.decode_32bit_uint()
    # >>> 117460641

    # let's try with BigEndian for byteorder:
    decoder = BinaryPayloadDecoder.fromRegisters(
        response.registers,
        byteorder=Endian.Big,
        wordorder=Endian.Little
    )
    print 'From decoder (byteorder=BE, wordorder=LE): ',
    print decoder.decode_32bit_uint()
    # >>> 500046
    #      ^--- this works now, even though the
    #           byteorder should originally be LE,
    #           however it is reversed by:
    #           https://github.com/riptideio/pymodbus/blob/4ed1f1a9750bc931c100ed24f5cc0fc032ab5f4d/pymodbus/payload.py#L252

def test_cb(client):
    rr = client.read_holding_registers(40000, 2, unit=0x0)
    rr.addCallback(process)


if __name__ == "__main__":
    defer = protocol.ClientCreator(
        reactor, ModbusClientProtocol).connectTCP('localhost', 5020)
    defer.addCallback(test_cb)
    reactor.run()
