From 9f3e08d951e20ab913a63c8b9ce83ffda05bf5bf Mon Sep 17 00:00:00 2001 From: "google-labs-jules[bot]" <161369871+google-labs-jules[bot]@users.noreply.github.com> Date: Sat, 6 Jun 2026 16:13:55 +0000 Subject: [PATCH] refactor: extract status message handling in notifications.py Co-authored-by: DaTiC0 <13198638+DaTiC0@users.noreply.github.com> --- notifications.py | 44 ++++++++++++++++++++++++-------------------- 1 file changed, 24 insertions(+), 20 deletions(-) diff --git a/notifications.py b/notifications.py index 2d18957..a8f4d5a 100644 --- a/notifications.py +++ b/notifications.py @@ -86,6 +86,29 @@ def handle_disconnect(_client, _userdata, rc): _append_mqtt_log('system', f'Unexpected disconnect (rc={rc})', 'Disconnected') +def _handle_status_message(user_id, device_id, payload): + """Update Firebase device status based on MQTT payload.""" + # Guard JSON decoding to avoid noisy errors when payloads are already decoded or non-JSON + state_updates = None + + if isinstance(payload, dict): + state_updates = payload + elif isinstance(payload, str): + try: + state_updates = json.loads(payload) + except (ValueError, TypeError): + logger.debug("Non-JSON status payload for %s/%s; skipping Firebase update", user_id, device_id) + + if state_updates is not None: + try: + ref = _get_user_device_states_ref(user_id, device_id) + if ref: + ref.update(state_updates) + logger.debug("Updated Firebase status for %s/%s", user_id, device_id) + except Exception as e: + logger.error("Failed to update Firebase from MQTT: %s", e) + + @mqtt.on_message() def handle_messages(_client, _userdata, message): payload = _decode_payload(message.payload) @@ -104,27 +127,8 @@ def handle_messages(_client, _userdata, message): device_id = parts[1] msg_type = parts[2] - # Try to update Firebase if it's a status message if msg_type == 'status': - # Guard JSON decoding to avoid noisy errors when payloads are already decoded or non-JSON - state_updates = None - - if isinstance(payload, dict): - state_updates = payload - elif isinstance(payload, str): - try: - state_updates = json.loads(payload) - except (ValueError, TypeError): - logger.debug("Non-JSON status payload for %s/%s; skipping Firebase update", user_id, device_id) - - if state_updates is not None: - try: - ref = _get_user_device_states_ref(user_id, device_id) - if ref: - ref.update(state_updates) - logger.debug("Updated Firebase status for %s/%s", user_id, device_id) - except Exception as e: - logger.error("Failed to update Firebase from MQTT: %s", e) + _handle_status_message(user_id, device_id, payload) _append_mqtt_log(topic, payload, 'Received', user_id=user_id)