I'm trying to reach a modbus server and read registers. I know that it's possible because another software can read the values from the same IP, same Port and same registers. But when i try to read
DEBUG:pymodbus.logging:Connection to Modbus server established. Socket ('xxx.xxx.x.xx', xxxxx)
DEBUG:pymodbus.logging:Processing: 0x0 0x1 0x0 0x0 0x0 0x3 0x1 0x80 0x5
DEBUG:pymodbus.logging:decode PDU failed for function code 128
WARNING:pymodbus.logging:Unable to decode frame Modbus Error: Unknown response 128
Modbus I/O Error: Modbus Error: [Input/Output] Unable to decode request
I'm getting this error every time.
I'm pretty sure that the error cause is the code. Because I've tried different modbus devices with different IP's each time I've faced the same error.
Here is my code.
def read_macbat():
num_regs = 8
client = ModbusTcpClient(host=MACBAT_HOST, port=MACBAT_PORT, timeout=TIMEOUT)
for attempt in range(1, MAX_RETRIES + 1):
try:
if client.connect():
response = client.read_holding_registers(address=10042, count=num_regs)
print(response)
if not response.isError():
print(f"Attempt {attempt}: Successfully read registers.")
print(f"Register Values: {response.registers}")
client.close()
return response.registers
else:
print(f"Attempt {attempt}: Error reading registers.")
client.close()
else:
print(f"Attempt {attempt}: Failed to connect to Modbus counter.")
if attempt < MAX_RETRIES:
print(f"Retrying in {RETRY_DELAY} seconds...")
time.sleep(RETRY_DELAY)
except ModbusIOException as e:
print(f"Modbus I/O Error: {e}")
print("Max retries reached. Could not read registers.")
return None
I know, I don't have much in hand but if you have any ideas I'm open to them.