44 lines
1.3 KiB
Python
44 lines
1.3 KiB
Python
from pymodbus.client.sync import ModbusTcpClient as ModbusClient
|
|
from pymodbus.exceptions import ModbusIOException
|
|
from time import sleep
|
|
|
|
|
|
client = ModbusClient('172.16.2.157')
|
|
|
|
try:
|
|
client.connect()
|
|
|
|
processImage = client.read_holding_registers(0x1010, 4)
|
|
if isinstance(processImage, ModbusIOException):
|
|
raise Exception(processImage)
|
|
|
|
if len(processImage.registers) != 4:
|
|
raise Exception("Unexpected number of registers in process image ({})".format(len(processImage.registers)))
|
|
|
|
(analogOutputBits, analogInputBits, digitalOutputBits, digitalInputBits) = processImage.registers
|
|
print(f"AO: {analogOutputBits}, AI: {analogInputBits}, DO: {digitalOutputBits}, DI: {digitalInputBits}")
|
|
|
|
while True:
|
|
reg = client.read_input_registers(0, analogInputBits // 8)
|
|
if isinstance(reg, ModbusIOException):
|
|
raise Exception(reg)
|
|
print(reg.registers)
|
|
|
|
reg = client.read_discrete_inputs(0, digitalInputBits)
|
|
if isinstance(reg, ModbusIOException):
|
|
raise Exception(reg)
|
|
print(reg.bits)
|
|
|
|
reg = client.read_coils(0, digitalOutputBits)
|
|
if isinstance(reg, ModbusIOException):
|
|
raise Exception(reg)
|
|
print(reg.bits)
|
|
|
|
sleep(0.1)
|
|
|
|
except Exception as e:
|
|
print("Exception: {}".format(e))
|
|
finally:
|
|
client.close()
|
|
|