from pymodbus.client import ModbusSerialClient
from pymodbus.exceptions import ModbusException

# Configure the serial client
client = ModbusSerialClient(
    port='COM5',
    baudrate=9600,
    bytesize=8,
    parity='N',
    stopbits=1,
    timeout=1
)

def read_holding_registers(unit=1, address=0, count=10):
    try:
        if not client.connect():
            print("Failed to connect to COM11")
            return

        print(f"Reading {count} holding registers from unit {unit}, starting at {address}...")

        # Use 'unit' instead of 'slave'
        result = client.read_holding_registers(
            address=address,
            count=count,
            unit=unit  # <-- Changed from 'slave' to 'unit'
        )

        if result.isError():
            print(f"Modbus error: {result}")
        else:
            print("Registers:", result.registers)

    except ModbusException as e:
        print(f"Modbus exception: {e}")
    except Exception as e:
        print(f"Unexpected error: {e}")
    finally:
        client.close()

# Run example
if __name__ == "__main__":
    read_holding_registers(unit=1, address=0, count=5)