# python -m pip install pyModbusTCP for Windows # sudo pip3 install pyModbusTCP for Raspbian # https://pypi.org/project/pyModbusTCP/ import struct from pyModbusTCP.client import ModbusClient from time import sleep import sys print (sys.version) print() AKD = ["192.168.0.1", "192.168.0.2", "192.168.0.3"] client = [0,0,0] def padded_hex(i, l): given_int = i given_len = l hex_result = hex(given_int)[2:] # remove '0x' from beginning of str num_hex_chars = len(hex_result) extra_zeros = '0' * (given_len - num_hex_chars) # may not get used.. return ('0x' + hex_result if num_hex_chars == given_len else '?' * given_len if num_hex_chars > given_len else '0x' + extra_zeros + hex_result if num_hex_chars < given_len else None) def GetValue(_rr): word0=padded_hex(_rr[0],4) word1=padded_hex(_rr[1],4) word2=padded_hex(_rr[2],4) word3=padded_hex(_rr[3],4) val1=word0[2:len(word0)]+word1[2:len(word1)]+word2[2:len(word2)]+word3[2:len(word3)] val2=int(val1,16) return -(val2 & 0x80000000) | (val2 & 0x7fffffff) ADDR_PL_FB = 588 for i in range(0,3): client[i] = ModbusClient(host=AKD[i], port=502, auto_open=True, auto_close = True, timeout=1, unit_id=i) while True: for i in range(0,3): rr = client[i].read_holding_registers(ADDR_PL_FB, 4) if rr: pos=GetValue(rr) print("Pos" + str(i) +"=" + str(pos)) print() sleep(1)