我正在研究pymodbus。
尝试从多个单元(多个从机)读取数据时,它会提供数据,但当其中一个从机没有响应或关闭时,其他从机在一段时间后也会显示错误。
请帮忙。
谢谢你
from pymodbus.client.sync import ModbusSerialClient as ModbusClient
from pymodbus.constants import Endian
from pymodbus.payload import BinaryPayloadDecoder
from pymodbus.exceptions import ModbusIOException
from pymodbus.exceptions import ConnectionException
def length(x):
client = ModbusClient(method='rtu', port='/dev/ttyUSB0', timeout=2, stopbits = 1, bytesize = 8, parity='N', baudrate = 9600)
client.connect()
rr = client.read_holding_registers(address=1, count=4, unit=x);
decoder = BinaryPayloadDecoder.fromRegisters(rr.registers, Endian.Big, wordorder=Endian.Big);
a=str(decoder.decode_32bit_float());
c = int (float(a))
client.close()
print("length",c)
client = ModbusClient(method='rtu', port='/dev/ttyUSB0', timeout=2, stopbits = 1, bytesize = 8, parity='N', baudrate = 9600)
client.connect()
rr = client.read_holding_registers(address=7, count=4, unit=x);
decoder = BinaryPayloadDecoder.fromRegisters(rr.registers, Endian.Big, wordorder=Endian.Big);
b=str(decoder.decode_32bit_float());
d = int (float(b))
client.close()
print("speed",d)
print(x)
return c,d
最佳答案
我用pymodbus中的.isError()
方法改进了您的代码,如下所示:
from pymodbus.client.sync import ModbusSerialClient as ModbusClient
from pymodbus.constants import Endian
from pymodbus.payload import BinaryPayloadDecoder
def error_checker(instance):
if not instance.isError():
'''.isError() implemented in pymodbus 1.4.0 and above.'''
decoder = BinaryPayloadDecoder.fromRegisters(
instance.registers, byteorder=Endian.Big, wordorder=Endian.Big
)
return decoder.decode_32bit_float()
else:
# Error handling.
return None
def length(x):
client = ModbusClient(
method='rtu',
port='/dev/ttyUSB0',
timeout=2, stopbits=1, bytesize=8, parity='N', baudrate=9600
)
try:
client.connect()
rr = client.read_holding_registers(address=1, count=4, unit=x)
c = error_checker(rr)
print("length: ", c)
rr = client.read_holding_registers(address=7, count=4, unit=x)
d = error_checker(rr)
print("speed: ", d)
return c, d
except Exception as exc:
print(exc)
finally:
client.close()