client = ModbusTcpClient('MyDevice.lan') # Create client object client.connect() # connect to device, reconnect automatically client.write_coil(1, True, slave=1) # set information in device result = client.read_coils(2, 3, slave=1) # get information from device print(result.bits[0]) # use information client.close() # Disconnect device
简单函数调用不论是读、写还是诊断调用的返回结果都是统一的,常用诊断方式如下所示:
1 2 3 4 5 6 7 8
try: res = await client.read_coils(1, 1, slave=1) except ModbusException as exc: _logger.error(f"ERROR: exception in pymodbus {exc}") raise exc if res.isError(): _logger.error("ERROR: pymodbus returned an error!") raise ModbusException(txt)