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




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


def write_register(client, register_address, value):
    """
    Writes data to a Modbus register.

    :param client: An instance of ModbusClient
    :param register_address: The address of the register to write
    :param value: The value to write to the register
    :return: True if the write was successful, False otherwise
    """
    try:
        result = client.write_register(register_address, value, slave=1)
        if result.isError():
            print(f"Error writing value {value} to register {register_address}: {result}")
            return False
        return True
    except Exception as e:
        print(f"Error writing value {value} to register {register_address}: {e}")
        return False


def main():
    # Modbus client configuration
    client = ModbusClient(
        method="rtu",
        port="/dev/ttyUSB0",  # Ensure the correct port for your setup
        stopbits=serial.STOPBITS_ONE,
        bytesize=serial.EIGHTBITS,
        parity=serial.PARITY_NONE,
        baudrate=38400,
        timeout=1,  # Timeout in seconds
        strict=False,
    )

    # 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:
        # Define the register address and value
        register_address = 60  # Address to read/write
        write_value = 900  # Value to write to the register

        # Step 1: Read the register value
        print(f"Reading register {register_address}...")
        read_data = read_register(client, register_address)
        if read_data is not None:
            print(f"Register {register_address} value before write: {read_data[0]}")

        # Step 2: Write a value to the register
        print(f"Writing value {write_value} to register {register_address}...")
        if write_register(client, register_address, write_value):
            print(f"Successfully wrote value {write_value} to register {register_address}.")
        else:
            print(f"Failed to write value {write_value} to register {register_address}.")

        # Step 3: Read the register again to confirm the write
        print(f"Reading register {register_address} after write...")
        read_data = read_register(client, register_address)
        if read_data is not None:
            print(f"Register {register_address} value after write: {read_data[0]}")

    except KeyboardInterrupt:
        print("\nStopping operation...")
    finally:
        client.close()
        print("Modbus client connection closed.")


if __name__ == "__main__":
    main()
