DN23E08_modbus/src/hardware.py

70 lines
2.2 KiB
Python

from pymodbus.client import ModbusSerialClient
class Hardware:
"""
Represents the hardware interface and syncs with the Modbus device.
"""
def __init__(self, client: ModbusSerialClient, slave_id: int):
"""
Initialize to default values.
Args:
client (ModbusSerialClient): The Modbus client for communication.
slave_id (int): The slave ID of the Modbus device.
"""
self.client = client
self.slave_id = slave_id
self.relay_0 = False
self.relay_1 = False
self.leds = [False for i in range(32)]
self.button_0 = False
self.button_1 = False
self.button_2 = False
self.button_3 = False
def sync_hardware_state(self) -> None:
"""
Update the hardware state by writing to coils and reading discrete inputs.
"""
try:
self.client.write_coils(0, [self.relay_0, self.relay_1], slave=self.slave_id)
self.client.write_coils(8, self.leds, slave=self.slave_id)
input_response = self.client.read_discrete_inputs(8, 4, slave=self.slave_id)
if not input_response.isError():
self.button_0 = input_response.bits[0]
self.button_1 = input_response.bits[1]
self.button_2 = input_response.bits[2]
self.button_3 = input_response.bits[3]
except Exception as e:
print(f"Modbus error: {e}")
def set_relay_0(self, value: bool) -> None:
"""Set the state of relay 0."""
self.relay_0 = value
def set_relay_1(self, value: bool) -> None:
"""Set the state of relay 1."""
self.relay_1 = value
def set_led(self, index: int, value: bool) -> None:
"""Set the state of an LED."""
self.leds[index] = value
def get_button_0(self) -> bool:
"""Get the state of button 0."""
return self.button_0
def get_button_1(self) -> bool:
"""Get the state of button 1."""
return self.button_1
def get_button_2(self) -> bool:
"""Get the state of button 2."""
return self.button_2
def get_button_3(self) -> bool:
"""Get the state of button 3."""
return self.button_3