From b70d071dc52fa179710134e023c34ac0c8caebbe Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Wed, 26 Jun 2024 20:15:06 +0200 Subject: [PATCH] feat: improve websocket error handling (#128) * feat: pass existing data to _handle_ws_error instead of creating it again * feat: cleanup duplicate code in _handle_ws_error * fix: remove unreachable code * fix: remove unreachable code * chore: format --- src/uiprotect/data/bootstrap.py | 34 ++++++++++++++++++--------------- 1 file changed, 19 insertions(+), 15 deletions(-) diff --git a/src/uiprotect/data/bootstrap.py b/src/uiprotect/data/bootstrap.py index b157690e..e04b81ae 100644 --- a/src/uiprotect/data/bootstrap.py +++ b/src/uiprotect/data/bootstrap.py @@ -560,34 +560,38 @@ def _make_ws_packet_message( model_type, action, data, ignore_stats, is_ping_back ) except (ValidationError, ValueError) as err: - self._handle_ws_error(action, err) + self._handle_ws_error(action_action, model_type, action, err) _LOGGER.debug( "Unexpected bootstrap model type deviceadoptedfor update: %s", model_key ) return None - def _handle_ws_error(self, action: dict[str, Any], err: Exception) -> None: + def _handle_ws_error( + self, + action_action: str, + model_type: ModelType, + action: dict[str, Any], + err: Exception, + ) -> None: msg = "" - if action["modelKey"] == "event": - msg = f"Validation error processing event: {action['id']}. Ignoring event." + device_id: str = action["id"] + if model_type is ModelType.EVENT: + msg = f"Validation error processing event: {device_id}. Ignoring event." else: - try: - model_type = ModelType.from_string(action["modelKey"]) - device_id: str = action["id"] - task = asyncio.create_task(self.refresh_device(model_type, device_id)) - self._refresh_tasks.add(task) - task.add_done_callback(self._refresh_tasks.discard) - except (ValueError, IndexError): - msg = f"{action['action']} packet caused invalid state. Unable to refresh device." - else: - msg = f"{action['action']} packet caused invalid state. Refreshing device: {model_type} {device_id}" + task = asyncio.create_task(self.refresh_device(model_type, device_id)) + self._refresh_tasks.add(task) + task.add_done_callback(self._refresh_tasks.discard) + msg = ( + f"{action_action} packet caused invalid state. " + f"Refreshing device: {model_type} {device_id}" + ) _LOGGER.debug("%s Error: %s", msg, err) async def refresh_device(self, model_type: ModelType, device_id: str) -> None: """Refresh a device in the bootstrap.""" try: - if model_type == ModelType.NVR: + if model_type is ModelType.NVR: device: ProtectModelWithId = await self._api.get_nvr() else: device = await self._api.get_device(model_type, device_id)