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."""
    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 Exception as e:
        print(f"Exception while reading register {register_address}: {e}")
        return None


def write_register(client, register_address, value):
    """Writes data to the Modbus server."""
    try:
        result = client.write_register(register_address, value, slave=1)
        if result.isError():
            print(f"Error writing to register {register_address}")
            return False
        return True
    except Exception as e:
        print(f"Exception while writing to register {register_address}: {e}")
        return False


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

    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}.")

        # Read and write register 20
        print(f"Reading register 20...")
        value = read_register(client, 20)
        if value is not None:
            print(f"Register 20 value: {value[0]}")

            print(f"Writing 1 to register 20...")
            if write_register(client, 20, 1):
                print("Successfully wrote to register 20.")

                # Verify the write by reading again
                print(f"Reading register 20 again...")
                value = read_register(client, 20)
                if value is not None:
                    print(f"Register 20 new value: {value[0]}")


            else:
                print("Failed to write to register 20.")



        else:
            print("Failed to read register 20 before writing.")

    except Exception as e:
        print(f"Unexpected error occurred: {e}")
    finally:
        client.close()
        print("Modbus client connection closed.")


if __name__ == "__main__":
    main()
