from pymodbus.client import ModbusSerialClient as ModbusClient
from pymodbus.exceptions import ModbusIOException
import serial


def read_register(client, register_address, count=1):
    """
    Reads data from the Modbus server.

    :param client: An instance of ModbusClient
    :param register_address: The address of the register to read
    :param count: Number of registers to read
    :return: List of register values or None if there was an error
    """
    try:
        result = client.read_holding_registers(register_address, count=count, slave=1)
        if result.isError():
            print(f"Error reading register {register_address}")
            return None
        return result.registers
    except ModbusIOException as modbus_error:
        print(f"Modbus IO Exception while reading register {register_address}: {modbus_error}")
        return None
    except Exception as e:
        print(f"Exception while reading register {register_address}: {e}")
        return None


def main():
    # Modbus client configuration
    client = ModbusClient(
        method="rtu",
        port="COM4",  # Change this to the appropriate port
        stopbits=serial.STOPBITS_ONE,
        bytesize=serial.EIGHTBITS,
        parity=serial.PARITY_NONE,
        baudrate=38400,
        timeout=1,  # Timeout in seconds
    )

    # Attempt to connect to the Modbus server
    if client.connect():
        print("Modbus client connected successfully.")
    else:
        print("Failed to connect to Modbus client.")
        return

    try:
        # Read registers 30 and 60
        for register_address in [30, 60]:
            print(f"Reading register {register_address}...")
            value = read_register(client, register_address)
            if value is not None:
                print(f"Register {register_address} value: {value[0]}")
            else:
                print(f"Failed to read register {register_address}.")
    except Exception as e:
        print(f"Unexpected error occurred: {e}")
    finally:
        client.close()
        print("Modbus client connection closed.")


if __name__ == "__main__":
    main()
