From c02964e95c861403a25e43c272f3aa7a872bbb54 Mon Sep 17 00:00:00 2001 From: Arksine Date: Sun, 9 May 2021 20:01:35 -0400 Subject: [PATCH] power: add endpoint for toggling a single device A single endpoint that can be used to both toggle and retrieve device state is useful for interoperability with home automation software. The previous endpoints will remain as they are still useful for batch operations. Signed-off-by: Eric Callahan --- moonraker/components/power.py | 29 +++++++++++++++++++++++++---- 1 file changed, 25 insertions(+), 4 deletions(-) diff --git a/moonraker/components/power.py b/moonraker/components/power.py index 1f1107b..13f73b5 100644 --- a/moonraker/components/power.py +++ b/moonraker/components/power.py @@ -53,13 +53,16 @@ class PrinterPower: self._handle_list_devices) self.server.register_endpoint( "/machine/device_power/status", ['GET'], - self._handle_power_request) + self._handle_batch_power_request) self.server.register_endpoint( "/machine/device_power/on", ['POST'], - self._handle_power_request) + self._handle_batch_power_request) self.server.register_endpoint( "/machine/device_power/off", ['POST'], - self._handle_power_request) + self._handle_batch_power_request) + self.server.register_endpoint( + "/machine/device_power/device", ['GET', 'POST'], + self._handle_single_power_request) self.server.register_remote_method( "set_device_power", self.set_device_power) self.server.register_event_handler( @@ -95,7 +98,23 @@ class PrinterPower: output = {"devices": dev_list} return output - async def _handle_power_request(self, web_request): + async def _handle_single_power_request(self, web_request): + dev_name = web_request.get_str('device') + req_action = web_request.get_action() + if dev_name not in self.devices: + raise self.server.error(f"No valid device named {dev_name}") + dev = self.devices[dev_name] + if req_action == 'GET': + action = "status" + elif req_action == "POST": + action = web_request.get_str('action').lower() + if action not in ["on", "off", "toggle"]: + raise self.server.error( + f"Invalid requested action '{action}'") + result = await self._process_request(dev, action) + return {dev_name: result} + + async def _handle_batch_power_request(self, web_request): args = web_request.get_args() ep = web_request.get_endpoint() if not args: @@ -115,6 +134,8 @@ class PrinterPower: if asyncio.iscoroutine(ret): await ret dev_info = device.get_device_info() + if req == "toggle": + req = "on" if dev_info['status'] == "off" else "off" if req in ["on", "off"]: cur_state = dev_info['status'] if req == cur_state: