From a21dccb3b60e9fc4eacd71edc066bb265784bd16 Mon Sep 17 00:00:00 2001 From: Nick Kleiner Date: Mon, 9 Nov 2026 08:16:16 -0500 Subject: [PATCH 1/3] Updated devices to support more custom UI construction. Updated demo files to reflect these changes. --- PyAres/Demo/Devices/device_test.py | 23 +- PyAres/Demo/Devices/environmental_chamber.py | 219 +++++++++++++++++++ PyAres/Demo/Devices/failure_test_device.py | 6 +- PyAres/Demo/Devices/hotplate.py | 219 ++++++++++++++----- PyAres/Demo/Devices/liquid_pump.py | 216 ++++++++++++++++++ PyAres/Demo/Devices/random_number_device.py | 14 +- PyAres/Demo/Devices/rotary_mixer.py | 13 +- PyAres/Device/__init__.py | 2 + PyAres/Device/device_models.py | 71 ++++-- PyAres/Device/device_service.py | 87 +++++--- PyAres/Utils/ares_device_command_utils.py | 24 +- PyAres/Utils/ares_widget_type_utils.py | 10 + 12 files changed, 786 insertions(+), 118 deletions(-) create mode 100644 PyAres/Demo/Devices/environmental_chamber.py create mode 100644 PyAres/Demo/Devices/liquid_pump.py create mode 100644 PyAres/Utils/ares_widget_type_utils.py diff --git a/PyAres/Demo/Devices/device_test.py b/PyAres/Demo/Devices/device_test.py index a21a0ed..0fd11ec 100644 --- a/PyAres/Demo/Devices/device_test.py +++ b/PyAres/Demo/Devices/device_test.py @@ -1,5 +1,5 @@ from PyAres import * -from typing import Dict +from PyAres.Device.device_models import StateItem import pint import time @@ -14,11 +14,17 @@ def set_temperature(self, temperature: float): return DeviceCommandResponse(None, status_code=StatusCode.COMMAND_SUCCESS) def get_temperature(self): - return DeviceCommandResponse(self.temperature, status_code=StatusCode.COMMAND_SUCCESS) + return DeviceCommandResponse(self.temperature, status_code=StatusCode.COMMAND_FAILED) - def get_device_state(self) -> Dict: - state_dict = { "temperature": self.temperature } - return state_dict + def get_device_state(self) -> list[StateItem]: + return [ + StateItem( + name="Current Temperature", + value=self.temperature, + index=0, + display_on_UI=True, + ) + ] def enter_safe_mode(self): self.temperature = 0 @@ -30,13 +36,14 @@ def enter_safe_mode(self): device_name = "Demo Device" description = "A device to demonstrate the PyAres device capabilities" version = "1.0.0" - device_service = AresDeviceService(device.enter_safe_mode, device.get_device_state, device_name, description, version, False) + device_service = AresDeviceService(device.enter_safe_mode, device.get_device_state, device_name, description, version, False, port=7101) # Create the "Set Temperature" Command quantity_schema = QuantitySchema(ureg.degree_Celsius, 40.0, 125.0) - parameter_schema = DeviceSchemaEntry(AresDataType.QUANTITY, "A numeric temperature value", quantity_schema=quantity_schema) + ui_schema = WidgetDescriptor(WidgetType.NUMERIC_INPUT) + parameter_schema = DeviceSchemaEntry(AresDataType.QUANTITY, "A numeric temperature value", quantity_schema=quantity_schema, user_interface_description=ui_schema) input_schema = { "temperature": parameter_schema } - set_temp_descriptor = DeviceCommandDescriptor("Set Temperature", "Set's the temperature of the demo device to the provided value.", input_schema, {}) + set_temp_descriptor = DeviceCommandDescriptor("Set Temperature", "Set's the temperature of the demo device to the provided value.", input_schema, {}, render_in_ui=True) device_service.add_new_command(set_temp_descriptor, device.set_temperature) # Create the "Get Temperature" Command diff --git a/PyAres/Demo/Devices/environmental_chamber.py b/PyAres/Demo/Devices/environmental_chamber.py new file mode 100644 index 0000000..e4e66b7 --- /dev/null +++ b/PyAres/Demo/Devices/environmental_chamber.py @@ -0,0 +1,219 @@ +"""A simulated environmental chamber with temperature and humidity control. + +The chamber is intentionally small but models two useful device behaviors for +examples: readings move gradually toward their setpoints, and invalid requests +return a structured :class:`DeviceCommandResponse` instead of raising an +exception. +""" + +from threading import RLock +from time import monotonic + +from PyAres import ( + AresDataType, + AresDeviceService, + DeviceCommandDescriptor, + DeviceCommandResponse, + DeviceSchemaEntry, + StatusCode, + WidgetDescriptor, + WidgetType, +) +from PyAres.Device.device_models import StateItem + + +class VirtualEnvironmentalChamber: + """Simulate a benchtop chamber with independent temperature and humidity.""" + + AMBIENT_TEMPERATURE = 22.0 + AMBIENT_HUMIDITY = 45.0 + MIN_TEMPERATURE = 4.0 + MAX_TEMPERATURE = 80.0 + MIN_HUMIDITY = 10.0 + MAX_HUMIDITY = 90.0 + TEMPERATURE_RATE = 3.0 # degrees C per second + HUMIDITY_RATE = 8.0 # percentage points per second + + def __init__(self) -> None: + self._lock = RLock() + self._last_update = monotonic() + self._target_temperature = self.AMBIENT_TEMPERATURE + self._target_humidity = self.AMBIENT_HUMIDITY + self._temperature = self.AMBIENT_TEMPERATURE + self._humidity = self.AMBIENT_HUMIDITY + self._door_open = False + + def _update_readings(self) -> None: + now = monotonic() + elapsed = max(0.0, now - self._last_update) + self._last_update = now + + temperature_change = self.TEMPERATURE_RATE * elapsed + humidity_change = self.HUMIDITY_RATE * elapsed + self._temperature += max( + -temperature_change, + min(temperature_change, self._target_temperature - self._temperature), + ) + self._humidity += max( + -humidity_change, + min(humidity_change, self._target_humidity - self._humidity), + ) + + @staticmethod + def _out_of_range(value: float, minimum: float, maximum: float) -> bool: + return not minimum <= value <= maximum + + def set_conditions(self, temperature: float, humidity: float): + """Set chamber targets after validating both requested conditions.""" + with self._lock: + if self._out_of_range(temperature, self.MIN_TEMPERATURE, self.MAX_TEMPERATURE): + return DeviceCommandResponse( + None, + error_string=( + f"Temperature must be between {self.MIN_TEMPERATURE} and " + f"{self.MAX_TEMPERATURE} °C." + ), + status_code=StatusCode.OUT_OF_RANGE, + ) + if self._out_of_range(humidity, self.MIN_HUMIDITY, self.MAX_HUMIDITY): + return DeviceCommandResponse( + None, + error_string=( + f"Humidity must be between {self.MIN_HUMIDITY} and " + f"{self.MAX_HUMIDITY}%." + ), + status_code=StatusCode.OUT_OF_RANGE, + ) + if self._door_open: + return DeviceCommandResponse( + None, + error_string="Close the chamber door before changing conditions.", + status_code=StatusCode.INVALID_COMMAND, + ) + + self._update_readings() + self._target_temperature = float(temperature) + self._target_humidity = float(humidity) + return DeviceCommandResponse(None, status_code=StatusCode.COMMAND_SUCCESS) + + def set_door(self, open: bool): + """Open or close the simulated chamber door.""" + with self._lock: + self._update_readings() + self._door_open = bool(open) + if self._door_open: + # An open door makes the chamber move back toward ambient. + self._target_temperature = self.AMBIENT_TEMPERATURE + self._target_humidity = self.AMBIENT_HUMIDITY + return DeviceCommandResponse(None, status_code=StatusCode.COMMAND_SUCCESS) + + def read_conditions(self): + """Read current conditions and the active targets.""" + with self._lock: + self._update_readings() + return DeviceCommandResponse( + { + "temperature": self._temperature, + "humidity": self._humidity, + "target_temperature": self._target_temperature, + "target_humidity": self._target_humidity, + "door_open": self._door_open, + }, + status_code=StatusCode.COMMAND_SUCCESS, + ) + + def get_state(self) -> list[StateItem]: + with self._lock: + self._update_readings() + return [ + StateItem("Temperature", self._temperature, 0, True), + StateItem("Humidity", self._humidity, 1, True), + StateItem("Door Open", self._door_open, 2, True), + ] + + def safe_mode(self) -> None: + """Return the chamber to safe ambient conditions.""" + with self._lock: + self._update_readings() + self._target_temperature = self.AMBIENT_TEMPERATURE + self._target_humidity = self.AMBIENT_HUMIDITY + self._door_open = False + print("[Hardware] SAFE MODE: Chamber targets reset to ambient conditions.") + + +def _build_service() -> AresDeviceService: + chamber = VirtualEnvironmentalChamber() + service = AresDeviceService( + chamber.safe_mode, + chamber.get_state, + "Virtual Environmental Chamber", + "A simulated chamber for temperature and humidity experiments", + "1.0.0", + port=7104, + ) + + numeric_input = WidgetDescriptor(WidgetType.NUMERIC_INPUT) + set_conditions = DeviceCommandDescriptor( + "Set Conditions", + "Set the chamber temperature and relative humidity targets.", + { + "temperature": DeviceSchemaEntry( + AresDataType.NUMBER, + "Target temperature", + "°C", + min_number_value=chamber.MIN_TEMPERATURE, + max_number_value=chamber.MAX_TEMPERATURE, + user_interface_description=numeric_input, + ), + "humidity": DeviceSchemaEntry( + AresDataType.NUMBER, + "Target relative humidity", + "%", + min_number_value=chamber.MIN_HUMIDITY, + max_number_value=chamber.MAX_HUMIDITY, + user_interface_description=numeric_input, + ), + }, + {}, + render_in_ui=True, + ) + service.add_new_command(set_conditions, chamber.set_conditions) + + door_command = DeviceCommandDescriptor( + "Set Door", + "Open or close the chamber door.", + { + "open": DeviceSchemaEntry( + AresDataType.BOOLEAN, + "Whether the door is open", + user_interface_description=WidgetDescriptor(WidgetType.BOOLEAN_TOGGLE), + ) + }, + {}, + render_in_ui=True, + ) + service.add_new_command(door_command, chamber.set_door) + + condition_schema = { + "temperature": DeviceSchemaEntry(AresDataType.NUMBER, "Current temperature", "°C"), + "humidity": DeviceSchemaEntry(AresDataType.NUMBER, "Current relative humidity", "%"), + "target_temperature": DeviceSchemaEntry(AresDataType.NUMBER, "Temperature target", "°C"), + "target_humidity": DeviceSchemaEntry(AresDataType.NUMBER, "Humidity target", "%"), + "door_open": DeviceSchemaEntry(AresDataType.BOOLEAN, "Whether the door is open"), + } + service.add_new_command( + DeviceCommandDescriptor( + "Read Conditions", + "Read current chamber conditions and targets.", + {}, + condition_schema, + render_in_ui=True, + ), + chamber.read_conditions, + ) + return service + + +if __name__ == "__main__": + print("Virtual Environmental Chamber Service Running...") + _build_service().start() diff --git a/PyAres/Demo/Devices/failure_test_device.py b/PyAres/Demo/Devices/failure_test_device.py index d369ec0..096ad02 100644 --- a/PyAres/Demo/Devices/failure_test_device.py +++ b/PyAres/Demo/Devices/failure_test_device.py @@ -1,6 +1,7 @@ import random from PyAres import AresDeviceService, AresDataType, DeviceCommandDescriptor, DeviceSchemaEntry +from PyAres.Device.device_models import StateItem class FailureTestDevice: @@ -18,8 +19,9 @@ def maybe_fail(self): print("[Test Device] Command succeeded and returned 20.") return {"number": 20} - def get_state(self): - return {} + def get_state(self) -> list[StateItem]: + """This test device has no state to report.""" + return [] def safe_mode(self): print("[Test Device] Safe mode triggered.") diff --git a/PyAres/Demo/Devices/hotplate.py b/PyAres/Demo/Devices/hotplate.py index 3e662c0..aa11e16 100644 --- a/PyAres/Demo/Devices/hotplate.py +++ b/PyAres/Demo/Devices/hotplate.py @@ -1,84 +1,195 @@ +"""A multi-burner virtual hotplate device. + +This demo intentionally models a little more of a real device than simply +storing the requested value: each burner has an independent setpoint and its +sensor value approaches that setpoint over time with a small amount of noise. +""" + +from random import Random +from threading import RLock +from time import monotonic from PyAres import * +from PyAres.Device.device_models import StateItem + -# --- PART 1: The Simulated Hardware --- class VirtualHotplate: - def __init__(self): - self.target_temp = 25.0 # Start at room temp - - def set_temperature(self, temp: float): - """Simulates setting the heater.""" - print(f"[Hardware] Heating to {temp}°C...") - response = DeviceCommandResponse(None, status_code=StatusCode.COMMAND_SUCCESS) - self.target_temp = temp - return response + """Simulated four-burner hotplate with independent temperature control.""" + + AMBIENT_TEMP = 25.0 + MIN_TEMP = AMBIENT_TEMP + MAX_TEMP = 300.0 + HEATING_RATE = 18.0 # degrees C per second when far from the setpoint + COOLING_RATE = 8.0 + SENSOR_NOISE = 0.35 + + def __init__(self, burner_count: int = 4): + if burner_count < 1: + raise ValueError("A hotplate must have at least one burner") + + self._lock = RLock() + self._random = Random() + self._last_update = monotonic() + self._burners = { + burner: {"target_temp": self.AMBIENT_TEMP, "current_temp": self.AMBIENT_TEMP} + for burner in range(1, burner_count + 1) + } + + @property + def burner_count(self) -> int: + return len(self._burners) + + def _update_temperatures(self) -> None: + """Advance the thermal simulation and refresh each sensor reading.""" + now = monotonic() + elapsed = max(0.0, now - self._last_update) + self._last_update = now + + for burner in self._burners.values(): + target = burner["target_temp"] + current = burner["current_temp"] + rate = self.HEATING_RATE if target > current else self.COOLING_RATE + maximum_change = rate * elapsed + difference = target - current + change = max(-maximum_change, min(maximum_change, difference)) + burner["current_temp"] = current + change + + def _validate_burner(self, burner: int) -> bool: + return burner in self._burners + + def set_temperature(self, burner: int, temp: float): + """Set one burner's target temperature; its sensor changes gradually.""" + with self._lock: + if not self._validate_burner(burner): + return DeviceCommandResponse( + None, + error_string=f"Burner must be between 1 and {self.burner_count}.", + status_code=StatusCode.INVALID_COMMAND, + ) + if not self.MIN_TEMP <= temp <= self.MAX_TEMP: + return DeviceCommandResponse( + None, + error_string=f"Temperature must be between {self.MIN_TEMP} and {self.MAX_TEMP} °C.", + status_code=StatusCode.OUT_OF_RANGE, + ) + + self._update_temperatures() + self._burners[burner]["target_temp"] = float(temp) + print(f"[Hardware] Burner {burner} target set to {temp:.1f}°C.") + return DeviceCommandResponse(None, status_code=StatusCode.COMMAND_SUCCESS) def get_temperature(self): - """Simulates reading the sensor.""" - response = DeviceCommandResponse({ "current_temp": self.target_temp }, status_code=StatusCode.COMMAND_SUCCESS) - # In a real device, you'd read a serial port here. - print("[Hardware] Retrieving the current temperature...") - return response + """Read all burners, including independent targets and current readings.""" + with self._lock: + self._update_temperatures() + readings = {} + for burner_number, values in self._burners.items(): + # Noise is applied to the reading, not the simulated thermal state, + # so successive reads vary without randomly walking away. + readings[f"burner_{burner_number}"] = { + "target_temp": values["target_temp"], + "current_temp": max( + self.AMBIENT_TEMP, + values["current_temp"] + self._random.uniform(-self.SENSOR_NOISE, self.SENSOR_NOISE), + ), + } + print("[Hardware] Retrieving temperatures for all burners...") + return DeviceCommandResponse(readings, status_code=StatusCode.COMMAND_SUCCESS) - def get_state(self): - """Required: Tells ARES the current status for logging.""" - return { "current_temp": self.target_temp } + def get_state(self) -> list[StateItem]: + """Return ordered, UI-visible state items for ARES logging and display.""" + with self._lock: + self._update_temperatures() + state_items = [] + for burner_number, values in self._burners.items(): + item_index = (burner_number - 1) * 2 + state_items.extend( + [ + StateItem( + name=f"Burner {burner_number} Target Temperature", + value=values["target_temp"], + index=item_index, + display_on_UI=True, + ), + StateItem( + name=f"Burner {burner_number} Current Temperature", + value=values["current_temp"], + index=item_index + 1, + display_on_UI=True, + ), + ] + ) + return state_items def safe_mode(self): - """Required: A safety fallback (e.g., turn off heat).""" - print("[Hardware] SAFE MODE TRIGGERED: Heater off.") - self.target_temp = 0.0 + """Turn every heater off and let the burners return to room temperature.""" + with self._lock: + self._update_temperatures() + for burner in self._burners.values(): + burner["target_temp"] = self.AMBIENT_TEMP + print("[Hardware] SAFE MODE TRIGGERED: All heaters off.") + + +def _temperature_schema() -> DeviceSchemaEntry: + return DeviceSchemaEntry(AresDataType.NUMBER, "Temperature", "Celsius") + -# --- PART 2: The Ares Service Wrapper --- if __name__ == "__main__": - # 1. Initialize the hardware - my_hotplate = VirtualHotplate() + my_hotplate = VirtualHotplate(burner_count=4) - # 2. Define the Service Info service = AresDeviceService( my_hotplate.safe_mode, my_hotplate.get_state, - "My Virtual Hotplate", # Device Name - "A simulated lab hotplate", # Description - "1.0.0" # Version + "Virtual Four-Burner Hotplate", + "A simulated hotplate with independent thermal sensors and setpoints", + "2.0.0", ) - # 3. Define Command: Set Temperature - # This schema tells ARES to draw a Number Input box in the UI - input_schema = { - "temp": DeviceSchemaEntry(AresDataType.NUMBER, "Target Temperature", "Celsius") + burner_ui = WidgetDescriptor(WidgetType.DROPDOWN) + temperature_ui = WidgetDescriptor(WidgetType.NUMERIC_SLIDER, slider_step_size=0.5) + set_input_schema = { + "burner": DeviceSchemaEntry( + AresDataType.INT, + "Burner number", + constraints=list(range(1, my_hotplate.burner_count + 1)), + user_interface_description=burner_ui, + ), + "temp": DeviceSchemaEntry( + AresDataType.NUMBER, + "Target temperature", + "Celsius", + min_number_value=my_hotplate.MIN_TEMP, + max_number_value=my_hotplate.MAX_TEMP, + user_interface_description=temperature_ui, + ), } set_cmd = DeviceCommandDescriptor( - "Set Temp", - "Sets the hotplate target temperature", - input_schema, - {} # No output expected + "Set Burner Temperature", + "Set the target temperature for one burner.", + set_input_schema, + {}, + render_in_ui=True, ) service.add_new_command(set_cmd, my_hotplate.set_temperature) - # 4. Define Command: Get Temperature - # This schema tells ARES to expect a struct back - output_schema = { - "output": DeviceSchemaEntry( + burner_output_schema = { + f"burner_{burner}": DeviceSchemaEntry( AresDataType.STRUCT, - "Current temperature output", + f"Burner {burner} temperatures", struct_schema={ - "current_temp": DeviceSchemaEntry( - AresDataType.NUMBER, - "Current Temperature", - "Celsius" - ) - } + "target_temp": _temperature_schema(), + "current_temp": _temperature_schema(), + }, ) + for burner in range(1, my_hotplate.burner_count + 1) } get_cmd = DeviceCommandDescriptor( - "Get Temp", - "Reads the current temperature", - {}, # No input needed - output_schema + "Get Burner Temperatures", + "Read target and simulated current temperatures for every burner.", + {}, + burner_output_schema, + render_in_ui=True, ) service.add_new_command(get_cmd, my_hotplate.get_temperature) - # 5. Start the Service - # This will block and listen for ARES connections - print("Virtual Hotplate Service Running...") + print("Virtual Four-Burner Hotplate Service Running...") service.start() diff --git a/PyAres/Demo/Devices/liquid_pump.py b/PyAres/Demo/Devices/liquid_pump.py new file mode 100644 index 0000000..45e8d6a --- /dev/null +++ b/PyAres/Demo/Devices/liquid_pump.py @@ -0,0 +1,216 @@ +"""A simulated precision liquid pump for ARES device demos. + +The pump exposes a small stateful API: a priming command, a volume-delivery +command, and a status readback. Delivery is modeled as an instantaneous demo +operation while retaining totals so planners and analyzers can observe useful +state over multiple commands. +""" + +from threading import RLock + +from PyAres import ( + AresDataType, + AresDeviceService, + DeviceCommandDescriptor, + DeviceCommandResponse, + DeviceSchemaEntry, + StatusCode, + WidgetDescriptor, + WidgetType, +) +from PyAres.Device.device_models import StateItem + + +class VirtualLiquidPump: + """Simulated pump with bounded flow and cumulative delivered volume.""" + + MIN_FLOW_RATE = 0.1 + MAX_FLOW_RATE = 25.0 + MAX_SINGLE_VOLUME = 100.0 + + def __init__(self) -> None: + self._lock = RLock() + self._primed = False + self._running = False + self._flow_rate = 5.0 + self._delivered_volume = 0.0 + self._last_fluid = "water" + + def prime(self, fluid: str): + """Prime the pump with a named fluid before dispensing.""" + fluid = fluid.strip() + if not fluid: + return DeviceCommandResponse( + None, + error_string="Fluid name cannot be empty.", + status_code=StatusCode.INVALID_COMMAND, + ) + + with self._lock: + self._primed = True + self._last_fluid = fluid + print(f"[Hardware] Pump primed with {fluid}.") + return DeviceCommandResponse(None, status_code=StatusCode.COMMAND_SUCCESS) + + def dispense(self, volume: float, flow_rate: float): + """Dispense a volume in milliliters at the requested rate.""" + with self._lock: + if not self._primed: + return DeviceCommandResponse( + None, + error_string="Prime the pump before dispensing.", + status_code=StatusCode.INVALID_COMMAND, + ) + if not 0 < volume <= self.MAX_SINGLE_VOLUME: + return DeviceCommandResponse( + None, + error_string=f"Volume must be greater than 0 and at most {self.MAX_SINGLE_VOLUME} mL.", + status_code=StatusCode.OUT_OF_RANGE, + ) + if not self.MIN_FLOW_RATE <= flow_rate <= self.MAX_FLOW_RATE: + return DeviceCommandResponse( + None, + error_string=( + f"Flow rate must be between {self.MIN_FLOW_RATE} and " + f"{self.MAX_FLOW_RATE} mL/s." + ), + status_code=StatusCode.OUT_OF_RANGE, + ) + + self._running = True + self._flow_rate = float(flow_rate) + self._delivered_volume += float(volume) + self._running = False + print(f"[Hardware] Dispensed {volume:.2f} mL at {flow_rate:.2f} mL/s.") + return DeviceCommandResponse( + {"dispensed_volume": float(volume), "total_volume": self._delivered_volume}, + status_code=StatusCode.COMMAND_SUCCESS, + ) + + def stop(self): + """Stop an active dispense operation.""" + with self._lock: + was_running = self._running + self._running = False + return DeviceCommandResponse( + {"was_running": was_running}, + status_code=StatusCode.COMMAND_SUCCESS, + ) + + def get_status(self): + with self._lock: + return DeviceCommandResponse( + { + "primed": self._primed, + "running": self._running, + "fluid": self._last_fluid, + "flow_rate": self._flow_rate, + "total_volume": self._delivered_volume, + }, + status_code=StatusCode.COMMAND_SUCCESS, + ) + + def get_state(self) -> list[StateItem]: + with self._lock: + return [ + StateItem("Pump Primed", self._primed, 0, True), + StateItem("Pump Running", self._running, 1, True), + StateItem("Fluid", self._last_fluid, 2, True), + StateItem("Total Delivered Volume", self._delivered_volume, 3, True), + ] + + def safe_mode(self) -> None: + with self._lock: + self._running = False + self._primed = False + print("[Hardware] SAFE MODE: Pump stopped and unprimed.") + + +def _build_service() -> AresDeviceService: + pump = VirtualLiquidPump() + service = AresDeviceService( + pump.safe_mode, + pump.get_state, + "Virtual Precision Liquid Pump", + "A simulated pump for repeatable liquid dispensing demonstrations", + "1.0.0", + port=7105, + ) + + fluid_command = DeviceCommandDescriptor( + "Prime Pump", + "Prime the pump with the named fluid.", + { + "fluid": DeviceSchemaEntry( + AresDataType.STRING, + "Fluid name", + user_interface_description=WidgetDescriptor(WidgetType.STRING_INPUT), + ) + }, + {}, + render_in_ui=True, + ) + service.add_new_command(fluid_command, pump.prime) + + dispense_output = { + "dispensed_volume": DeviceSchemaEntry(AresDataType.NUMBER, "Volume dispensed", "mL"), + "total_volume": DeviceSchemaEntry(AresDataType.NUMBER, "Cumulative volume", "mL"), + } + dispense_command = DeviceCommandDescriptor( + "Dispense", + "Dispense a controlled volume of the primed fluid.", + { + "volume": DeviceSchemaEntry( + AresDataType.NUMBER, + "Volume to dispense", + "mL", + min_number_value=0.1, + max_number_value=pump.MAX_SINGLE_VOLUME, + user_interface_description=WidgetDescriptor(WidgetType.NUMERIC_INPUT), + ), + "flow_rate": DeviceSchemaEntry( + AresDataType.NUMBER, + "Dispense flow rate", + "mL/s", + min_number_value=pump.MIN_FLOW_RATE, + max_number_value=pump.MAX_FLOW_RATE, + user_interface_description=WidgetDescriptor(WidgetType.NUMERIC_SLIDER, slider_step_size=0.1), + ), + }, + dispense_output, + render_in_ui=True, + ) + service.add_new_command(dispense_command, pump.dispense) + + service.add_new_command( + DeviceCommandDescriptor( + "Stop Pump", + "Stop any active dispensing operation.", + {}, + {"was_running": DeviceSchemaEntry(AresDataType.BOOLEAN, "Whether the pump was running")}, + render_in_ui=True, + ), + pump.stop, + ) + service.add_new_command( + DeviceCommandDescriptor( + "Get Pump Status", + "Read pump priming, flow, and cumulative volume status.", + {}, + { + "primed": DeviceSchemaEntry(AresDataType.BOOLEAN, "Whether the pump is primed"), + "running": DeviceSchemaEntry(AresDataType.BOOLEAN, "Whether the pump is running"), + "fluid": DeviceSchemaEntry(AresDataType.STRING, "Primed fluid name"), + "flow_rate": DeviceSchemaEntry(AresDataType.NUMBER, "Current flow rate", "mL/s"), + "total_volume": DeviceSchemaEntry(AresDataType.NUMBER, "Cumulative volume", "mL"), + }, + render_in_ui=True, + ), + pump.get_status, + ) + return service + + +if __name__ == "__main__": + print("Virtual Precision Liquid Pump Service Running...") + _build_service().start() diff --git a/PyAres/Demo/Devices/random_number_device.py b/PyAres/Demo/Devices/random_number_device.py index 7bbc53a..740fffe 100644 --- a/PyAres/Demo/Devices/random_number_device.py +++ b/PyAres/Demo/Devices/random_number_device.py @@ -1,6 +1,7 @@ import random from PyAres import AresDeviceService, AresDataType, DeviceSchemaEntry, DeviceCommandDescriptor, DeviceCommandResponse, StatusCode +from PyAres.Device.device_models import StateItem # --- PART 1: The Simulated Hardware --- @@ -16,8 +17,15 @@ def generate_number(self): return response def get_state(self): - """Required: Tells ARES the current status for logging.""" - return {"last_number": self.last_number} + """Return the latest generated value as an ARES state item.""" + return [ + StateItem( + name="Last Generated Number", + value=self.last_number, + index=0, + display_on_UI=True, + ) + ] def safe_mode(self): """Required: A safety fallback.""" @@ -36,7 +44,7 @@ def safe_mode(self): "My Virtual Random Number Device", "A simulated device that generates random numbers", "1.0.0", - port=7101 + port=7102 ) # 3. Define Command: Generate Number diff --git a/PyAres/Demo/Devices/rotary_mixer.py b/PyAres/Demo/Devices/rotary_mixer.py index 1d41342..a9d6519 100644 --- a/PyAres/Demo/Devices/rotary_mixer.py +++ b/PyAres/Demo/Devices/rotary_mixer.py @@ -1,4 +1,5 @@ from PyAres import * +from PyAres.Device.device_models import StateItem class RotaryMixer: def __init__(self, speed): @@ -18,8 +19,14 @@ def get_speed(): return DeviceCommandResponse(mixer.speed, status_code=StatusCode.COMMAND_SUCCESS) def get_status(): - # Return a dictionary matching your state schema - return { "rpm": mixer.speed } + return [ + StateItem( + name="Mixer Speed", + value=mixer.speed, + index=0, + display_on_UI=True, + ) + ] def safe_mode(): print("Stopping motor immediately!") @@ -31,7 +38,7 @@ def safe_mode(): "Rotary Mixer", "High-speed mixer control", "1.0.0", - port=7101 + port=7103 ) # 3. Define the 'Set Speed' Command diff --git a/PyAres/Device/__init__.py b/PyAres/Device/__init__.py index dc4fd30..6b7afcf 100644 --- a/PyAres/Device/__init__.py +++ b/PyAres/Device/__init__.py @@ -2,4 +2,6 @@ from .device_models import DeviceSchemaEntry from .device_models import StatusCode from .device_models import DeviceCommandResponse +from .device_models import WidgetDescriptor +from .device_models import WidgetType from .device_service import AresDeviceService \ No newline at end of file diff --git a/PyAres/Device/device_models.py b/PyAres/Device/device_models.py index b1ee00a..37c6696 100644 --- a/PyAres/Device/device_models.py +++ b/PyAres/Device/device_models.py @@ -1,8 +1,32 @@ from enum import Enum -from dataclasses import dataclass, field -from typing import Dict, Union, Optional, Any +from dataclasses import dataclass +from typing import Dict, Union, Optional, Any, List from ..Models import ares_data_models +class WidgetType(Enum): + WIDGET_UNSPECIFIED = 0 + NUMERIC_INPUT = 1 + NUMERIC_SLIDER = 2 + BOOLEAN_TOGGLE = 3 + STRING_INPUT = 4 + DROPDOWN = 5 + READ_ONLY = 6 + +class WidgetDescriptor: + """ A class for defining how an input parameter is displayed in the ARES UI """ + + def __init__(self, widget_type: WidgetType, slider_step_size: Optional[float] = 1.0): + """ + Initializes a new User Interface Widget for taking in an input parameter for a command displayed on the ARES dashboard + + Args: + widget_type (WidgetType): The type of widget you want generated for this input. + slider_step_size (Optional[float]): An optional float value that sets the step size of a slider widget. + """ + + self.widget_type = widget_type + self.slider_step_size = slider_step_size + class DeviceSchemaEntry: """ A class that describes an input or output parameter for a device command """ @@ -15,7 +39,8 @@ def __init__(self, type: ares_data_models.AresDataType, struct_schema: Optional[Dict[str, 'DeviceSchemaEntry']] = None, list_element_schema: Optional['DeviceSchemaEntry'] = None, min_number_value: Optional[float] = None, - max_number_value: Optional[float] = None): + max_number_value: Optional[float] = None, + user_interface_description: Optional[WidgetDescriptor] = None): """ Initializes a new DeviceSchemaEntry @@ -30,6 +55,7 @@ def __init__(self, type: ares_data_models.AresDataType, list_element_schema (DeviceSchemaEntry): Optional schema for list elements min_number_value (float): Optional minimum value for numeric types max_number_value (float): Optional maximum value for numeric types + user_interface_description (WidgetDescriptor): Optional UI component identifier for the client renderer """ self.type = type @@ -42,10 +68,11 @@ def __init__(self, type: ares_data_models.AresDataType, self.list_element_schema = list_element_schema self.min_number_value = min_number_value self.max_number_value = max_number_value + self.user_interface_description = user_interface_description class DeviceCommandDescriptor: """ A class that contains all the necessary information to describe a device command """ - def __init__(self, name: str, description: str, input_schema: Dict[str, DeviceSchemaEntry], output_schema: Dict[str, DeviceSchemaEntry]): + def __init__(self, name: str, description: str, input_schema: Dict[str, DeviceSchemaEntry], output_schema: Dict[str, DeviceSchemaEntry], render_in_ui: bool = False): """ Initializes a new instance of the device command descriptor class. @@ -54,25 +81,37 @@ def __init__(self, name: str, description: str, input_schema: Dict[str, DeviceSc description (str): The description of this device command. input_schema (list[ares_data_models.AresDataType]): A dictionary that defines the input parameters to the device command. output_schema (list[ares_data_models.AresDataType]): A dictionary that defines the output parameters to the device command. + render_in_ui (bool): A boolean value that defaults to false, if set to true means the command will be usable via the dashboard in ARES """ self.name = name self.description = description self.input_schema = input_schema self.output_schema = output_schema + self.render_in_UI = render_in_ui class StatusCode(Enum): - STATUS_UNSPECIFIED = 0 - COMMAND_SUCCESS = 1 - SUCCESS_WITH_WARNINGS = 2 - COMMAND_FAILED = 3 - INVALID_COMMAND = 4 - HARDWARE_FAULT = 5 - EMERGENCY_STOP = 6 - OUT_OF_RANGE = 7 - PARAMETERS_UNACHIEVEABLE = 8 + STATUS_UNSPECIFIED = 0 + COMMAND_SUCCESS = 1 + SUCCESS_WITH_WARNINGS = 2 + COMMAND_FAILED = 3 + INVALID_COMMAND = 4 + HARDWARE_FAULT = 5 + EMERGENCY_STOP = 6 + OUT_OF_RANGE = 7 + PARAMETERS_UNACHIEVEABLE = 8 @dataclass class DeviceCommandResponse: - response: Union[Dict[str, Any], Any] - error_string: str = "" - status_code: StatusCode = StatusCode.STATUS_UNSPECIFIED + response: Union[Dict[str, Any], Any] + error_string: str = "" + status_code: StatusCode = StatusCode.STATUS_UNSPECIFIED + +@dataclass +class StateItem: + """ An individual state item on an ARES device, used to represent one piece of the state data """ + + def __init__(self, name: str, value: Any, index: int = -1, display_on_UI: bool = False): + self.name = name + self.value = value + self.display_on_UI = display_on_UI + self.index = index \ No newline at end of file diff --git a/PyAres/Device/device_service.py b/PyAres/Device/device_service.py index 4dd5a35..a79eb1d 100644 --- a/PyAres/Device/device_service.py +++ b/PyAres/Device/device_service.py @@ -2,7 +2,7 @@ import inspect import time import warnings -from typing import Dict, Callable, Awaitable, Union, Any, Optional +from typing import Dict, Callable, Awaitable, Union, Any, Optional, List from ares_datamodel.device.remote import ares_remote_device_service_pb2 as device_service from ares_datamodel.device.remote import ares_remote_device_service_pb2_grpc as device_service_grpc @@ -13,7 +13,7 @@ from ares_datamodel import ares_struct_pb2 from google.protobuf import empty_pb2 -from .device_models import DeviceCommandDescriptor +from .device_models import DeviceCommandDescriptor, StateItem from ..Models import Limits from .device_models import DeviceCommandDescriptor, DeviceCommandResponse from ..Utils import ares_device_command_utils @@ -28,7 +28,7 @@ EnterSafeModeMethod = Callable[[], None] AllowedReturns = Union[DeviceCommandResponse, Dict[str, Any], Any] DeviceCommandMethod = Callable[..., AllowedReturns] -DeviceStateMethod = Callable[[], Dict[str, Any]] +DeviceStateMethod = Callable[[], Union[Dict[str, Any], List[StateItem]]] class AresDeviceServiceWrapper(AresServiceWrapperBase, device_service_grpc.AresRemoteDeviceServiceServicer): """ @@ -47,7 +47,6 @@ def __init__(self, device_name: str, description: str, version: str, timeout: in self._update_device_state = update_device_state self._setting_schema: Dict[str, ares_data_schema_pb2.AresValueSchema] = {} self._current_settings: Dict[str, ares_struct_pb2.AresStruct] = {} - self._state_schema: Dict[str, ares_data_schema_pb2.AresValueSchema] = {} self._commands: list[DeviceCommandDescriptor] = [] self._command_methods: Dict[str, Callable] = {} @@ -190,19 +189,14 @@ def SetSettings(self, request: device_service.SetSettingsRequest, context) -> em return empty_pb2.Empty() def GetStateSchema(self, request, context) -> device_service.StateSchemaResponse: - response = device_service.StateSchemaResponse() - for key, value in self._state_schema.items(): - settings_entry = response.schema.fields[key] - settings_entry.type = value.type - settings_entry.optional = value.optional + """Return an empty schema for protocol compatibility. - if len(value.string_choices.strings) != 0: - settings_entry.string_choices.strings.extend(value.string_choices.strings) - - elif len(value.number_choices.numbers) != 0: - settings_entry.number_choices.numbers.extend(value.number_choices.numbers) - - return response + PyAres deliberately treats device state as flexible runtime telemetry rather + than requiring devices to register a rigid state schema. The RPC remains + implemented so clients that probe the endpoint receive a valid response + instead of an UNIMPLEMENTED error. + """ + return device_service.StateSchemaResponse() def GetState(self, request, context) -> device_service.DeviceStateResponse: response = self._update_device_state() @@ -210,14 +204,26 @@ def GetState(self, request, context) -> device_service.DeviceStateResponse: response = response.__await__() proto_response = device_service.DeviceStateResponse() - proto_response.state = ares_struct_pb2.AresStruct() - if not isinstance(response, Dict): - print("State Response was invalid. All state responses should be returned in the form of a dictionary.") + if isinstance(response, Dict): + proto_response.state = ares_struct_pb2.AresStruct() + for key, value in response.items(): + ares_struct_utils.add_value_to_struct(proto_response.state, key, ares_value_utils.create_ares_value(value)) + + elif isinstance(response, List[StateItem]): + for item in response: + proto_state_entry = device_service.StateEntry() + + proto_state_entry.value.CopyFrom(ares_value_utils.create_ares_value(item.value)) + proto_state_entry.name = proto_state_entry.name + proto_state_entry.display_in_ui = item.display_on_UI + proto_state_entry.index = item.index + + proto_response.device_state_data.append(proto_state_entry) + + else: + print("State Response was invalid. All state responses should be returned in the form of a dictionary or a list of state items.") return proto_response - - for key, value in response.items(): - ares_struct_utils.add_value_to_struct(proto_response.state, key, ares_value_utils.create_ares_value(value)) return proto_response @@ -239,12 +245,37 @@ def GetStateStream(self, request: device_service.DeviceStateStreamRequest, conte proto_response = device_service.DeviceStateResponse() - if not isinstance(response, Dict): - print("State Response was invalid. All state responses should be returned in the form of a dictionary.") - return proto_response + if isinstance(response, Dict): + proto_response.state = ares_struct_pb2.AresStruct() + for key, value in response.items(): + ares_struct_utils.add_value_to_struct(proto_response.state, key, ares_value_utils.create_ares_value(value)) + + elif isinstance(response, List): + for item in response: + if isinstance(item, StateItem): + try: + print("Why is nothing working") + proto_state_entry = device_service.StateEntry() + + proto_state_entry.value.CopyFrom(ares_value_utils.create_ares_value(item.value)) + proto_state_entry.name = item.name + proto_state_entry.display_in_ui = item.display_on_UI + proto_state_entry.index = item.index - for key, value in response.items(): - ares_struct_utils.add_value_to_struct(proto_response.state, key, ares_value_utils.create_ares_value(value)) + proto_response.device_state_data.append(proto_state_entry) + + except Exception as e: + print("SOMETHING BROKEN :(") + print(e) + + else: + print("Malformed State Data Received: All items in list must be StateItems") + + + + else: + print("State Response was invalid. All state responses should be returned in the form of a dictionary or a list of state items.") + return proto_response yield proto_response time.sleep(delay) @@ -369,4 +400,4 @@ def start(self, wait_for_termination: bool = True): def stop(self): """ Stops the service, terminating the connection. """ print("Stopping Ares Device Service...") - self.get_server().stop(0).wait() + self.get_server().stop(0).wait() \ No newline at end of file diff --git a/PyAres/Utils/ares_device_command_utils.py b/PyAres/Utils/ares_device_command_utils.py index 67080c2..dad9f44 100644 --- a/PyAres/Utils/ares_device_command_utils.py +++ b/PyAres/Utils/ares_device_command_utils.py @@ -1,12 +1,11 @@ -from typing import Union - from ..Device import DeviceCommandDescriptor from ..Device import DeviceSchemaEntry -from ares_datamodel.device import device_command_descriptor_pb2 +from ares_datamodel.device import device_command_descriptor_pb2, device_command_ui_descriptor_pb2 from ares_datamodel import ares_data_schema_pb2, ares_data_type_pb2 from ares_datamodel import to_quantity_schema -from . import ares_data_type_utils +from . import ares_data_type_utils, ares_widget_type_utils +import warnings def python_command_description_to_proto(python_description: DeviceCommandDescriptor) -> device_command_descriptor_pb2.DeviceCommandDescriptor: proto_description = device_command_descriptor_pb2.DeviceCommandDescriptor() @@ -28,6 +27,23 @@ def python_command_description_to_proto(python_description: DeviceCommandDescrip for key, value in python_description.output_schema.items(): proto_description.output_schema.struct_schema.fields[key].CopyFrom(python_device_schema_entry_to_proto(value)) + if python_description.render_in_UI: + for key, value in python_description.input_schema.items(): + if value.user_interface_description is not None: + converted_widget = ares_widget_type_utils.python_ares_outcome_to_proto_ares_outcome(value.user_interface_description.widget_type) + new_widget = device_command_ui_descriptor_pb2.WidgetDescriptor(associated_input=key, widget_type=converted_widget) + + if value.user_interface_description.slider_step_size is not None: + new_widget.slider_step_size = value.user_interface_description.slider_step_size + + proto_description.widget_descriptors.append(new_widget) + + else: + for key, value in python_description.input_schema.items(): + if value.user_interface_description is not None: + warnings.warn(f"A description was provided for the command {python_description.name} but rendering in the UI is disabled." + + "Please set 'render_in_UI' to True if you want to render this command in your UI") + proto_description.name = python_description.name proto_description.description = python_description.description diff --git a/PyAres/Utils/ares_widget_type_utils.py b/PyAres/Utils/ares_widget_type_utils.py new file mode 100644 index 0000000..84cda58 --- /dev/null +++ b/PyAres/Utils/ares_widget_type_utils.py @@ -0,0 +1,10 @@ +from ..Device.device_models import WidgetType +from ares_datamodel.device import ares_ui_widget_enum_pb2 + +def python_ares_outcome_to_proto_ares_outcome(py_value: WidgetType) -> int: + """ A method to convert from the python AresDataType class to the protobuf version """ + return py_value.value + +def proto_ares_outcome_to_python_ares_outcome(proto_value: ares_ui_widget_enum_pb2.WidgetType) -> WidgetType: + """ A method to convert from the protobuf AresDataType class to the python version """ + return WidgetType(proto_value) \ No newline at end of file From 690eec328b005d83c2b2ce441688b0372be810f8 Mon Sep 17 00:00:00 2001 From: Nick Kleiner Date: Mon, 9 Nov 2026 09:53:05 -0500 Subject: [PATCH 2/3] Removed old debug statements. Fixed incorrect assignment of item names --- PyAres/Device/device_service.py | 7 +++---- PyAres/__init__.py | 2 ++ 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/PyAres/Device/device_service.py b/PyAres/Device/device_service.py index a79eb1d..719c48d 100644 --- a/PyAres/Device/device_service.py +++ b/PyAres/Device/device_service.py @@ -210,12 +210,12 @@ def GetState(self, request, context) -> device_service.DeviceStateResponse: for key, value in response.items(): ares_struct_utils.add_value_to_struct(proto_response.state, key, ares_value_utils.create_ares_value(value)) - elif isinstance(response, List[StateItem]): + elif isinstance(response, list) and all(isinstance(item, StateItem) for item in response): for item in response: proto_state_entry = device_service.StateEntry() proto_state_entry.value.CopyFrom(ares_value_utils.create_ares_value(item.value)) - proto_state_entry.name = proto_state_entry.name + proto_state_entry.name = item.name proto_state_entry.display_in_ui = item.display_on_UI proto_state_entry.index = item.index @@ -254,7 +254,6 @@ def GetStateStream(self, request: device_service.DeviceStateStreamRequest, conte for item in response: if isinstance(item, StateItem): try: - print("Why is nothing working") proto_state_entry = device_service.StateEntry() proto_state_entry.value.CopyFrom(ares_value_utils.create_ares_value(item.value)) @@ -400,4 +399,4 @@ def start(self, wait_for_termination: bool = True): def stop(self): """ Stops the service, terminating the connection. """ print("Stopping Ares Device Service...") - self.get_server().stop(0).wait() \ No newline at end of file + self.get_server().stop(0).wait() diff --git a/PyAres/__init__.py b/PyAres/__init__.py index ca63d2c..d71b64c 100644 --- a/PyAres/__init__.py +++ b/PyAres/__init__.py @@ -16,6 +16,8 @@ from .Device import DeviceSchemaEntry from .Device import DeviceCommandResponse from .Device import StatusCode +from .Device import WidgetDescriptor +from .Device import WidgetType from .Models import AresDataType from .Models import Outcome from .Models import AresSchemaEntry From 3eba3d42b7647af41387fb15ecb79fa25e5ad0a4 Mon Sep 17 00:00:00 2001 From: Nick Kleiner Date: Mon, 9 Nov 2026 15:29:59 -0500 Subject: [PATCH 3/3] Fixed a failing unit test --- PyAres/Device/device_service.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/PyAres/Device/device_service.py b/PyAres/Device/device_service.py index 719c48d..24a54aa 100644 --- a/PyAres/Device/device_service.py +++ b/PyAres/Device/device_service.py @@ -206,7 +206,6 @@ def GetState(self, request, context) -> device_service.DeviceStateResponse: proto_response = device_service.DeviceStateResponse() if isinstance(response, Dict): - proto_response.state = ares_struct_pb2.AresStruct() for key, value in response.items(): ares_struct_utils.add_value_to_struct(proto_response.state, key, ares_value_utils.create_ares_value(value)) @@ -246,7 +245,6 @@ def GetStateStream(self, request: device_service.DeviceStateStreamRequest, conte proto_response = device_service.DeviceStateResponse() if isinstance(response, Dict): - proto_response.state = ares_struct_pb2.AresStruct() for key, value in response.items(): ares_struct_utils.add_value_to_struct(proto_response.state, key, ares_value_utils.create_ares_value(value))