From 61f1ec394b8df68ca2b74cb597dc1d708719a9c5 Mon Sep 17 00:00:00 2001 From: Moustachauve <2206577+Moustachauve@users.noreply.github.com> Date: Sun, 15 Nov 2026 23:57:15 -0500 Subject: [PATCH 1/4] Fix Gateway hilo_id and GraphQL connectionStatus subscription updates Home Assistant relies on device `Disconnected` updates and `hilo_id` callbacks from GraphQL to mark entities unavailable when devices or the Zigbee Gateway go offline, but several schema and mapping bugs prevented those updates from reaching `HiloDevice` instances. Populate `hilo_id` on the Gateway device, request the missing Gateway identity fields in device subscriptions, and align `onAnyLocationUpdated` and reconnect resyncs with Hilo's Digital-Twin schema so Gateway and device connection state changes reliably update device availability and notify subscription callbacks. --- pyhilo/device/graphql_value_mapper.py | 72 ++--- pyhilo/devices.py | 15 +- pyhilo/graphql.py | 155 ++++++----- tests/test_graphql.py | 371 ++++++++++++++++++++++++++ tests/test_graphql_value_mapper.py | 128 ++++++++- 5 files changed, 628 insertions(+), 113 deletions(-) create mode 100644 tests/test_graphql.py diff --git a/pyhilo/device/graphql_value_mapper.py b/pyhilo/device/graphql_value_mapper.py index 08e2caf..728a835 100644 --- a/pyhilo/device/graphql_value_mapper.py +++ b/pyhilo/device/graphql_value_mapper.py @@ -1,3 +1,4 @@ +from collections.abc import Mapping from datetime import datetime, timezone from typing import Any, Dict @@ -11,36 +12,58 @@ class GraphqlValueMapper: OnState = "on" + @staticmethod + def is_gateway_payload(device: Mapping[str, object]) -> bool: + if device.get("__typename") == "Gateway": + return True + device_type = device.get("deviceType") + return isinstance(device_type, str) and device_type.lower() in ( + "gateway", + "hub", + ) + def map_query_values(self, values: list[Dict[str, Any]]) -> list[Dict[str, Any]]: readings: list[Dict[str, Any]] = [] for device in values: - if device.get("deviceType") is not None: - reading = self._map_devices_values(device) - readings.extend(reading) + readings.extend(self._map_devices_values(device)) return readings def map_device_subscription_values( self, device: Dict[str, Any] ) -> list[Dict[str, Any]]: - readings: list[Dict[str, Any]] = [] - if device.get("deviceType") is not None: - reading = self._map_devices_values(device) - readings.extend(reading) - return readings + return self._map_devices_values(device) def map_location_subscription_values( self, values: Dict[str, Any] ) -> list[Dict[str, Any]]: readings: list[Dict[str, Any]] = [] - for device in values.get("devices", []): - if device.get("deviceType") is not None: - reading = self._map_devices_values(device) - readings.extend(reading) + for device in values.get("devices") or []: + if device.get("__typename") == "BasicDevice" or not device.get("hiloId"): + continue + readings.extend(self._map_basic_device(device)) + if self.is_gateway_payload(device): + readings.append( + self.build_attribute( + device["hiloId"], + "onlineStatus", + device.get("connectionStatus"), + ) + ) return readings def _map_devices_values(self, device: Dict[str, Any]) -> list[Dict[str, Any]]: + # Digital-Twin returns BasicDevice stubs with connectionStatus=null for + # unmigrated SignalR-managed devices (e.g. weather stations, smoke detectors). + if device.get("__typename") == "BasicDevice" or not device.get("hiloId"): + return [] attributes: list[Dict[str, Any]] = self._map_basic_device(device) - match device["deviceType"].lower(): + if self.is_gateway_payload(device): + attributes.extend(self._build_gateway(device)) + return attributes + device_type = device.get("deviceType") + if not isinstance(device_type, str): + return [] + match device_type.lower(): case "tstat": attributes.extend(self._build_thermostat(device)) case "cee": # Water Heater @@ -55,8 +78,6 @@ def _map_devices_values(self, device: Dict[str, Any]) -> list[Dict[str, Any]]: attributes.extend(self._build_charging_point(device)) case "meter": # Smart Meter attributes.extend(self._build_smart_meter(device)) - case "hub": # Gateway - attributes.extend(self._build_gateway(device)) case "colorbulb": attributes.extend(self._build_light(device)) case "whitebulb": @@ -66,7 +87,7 @@ def _map_devices_values(self, device: Dict[str, Any]) -> list[Dict[str, Any]]: case "switch": attributes.extend(self._build_switch(device)) case _: - pass + return [] return attributes def _map_to_device_reading( @@ -82,13 +103,6 @@ def _build_smart_meter(self, device: Dict[str, Any]) -> list[Dict[str, Any]]: device["hiloId"], "ZigbeeChannel", device["zigBeeChannel"] ) ) - attributes.append( - self.build_attribute( - device["hiloId"], - "Disconnected", - device["connectionStatus"] == "DISCONNECTED", - ), - ) if device.get("power") is not None: attributes.append(self._map_power(device)) return attributes @@ -97,21 +111,19 @@ def _build_gateway(self, device: Dict[str, Any]) -> list[Dict[str, Any]]: attributes = [] attributes.append( self.build_attribute( - device["hiloId"], "LastStatusTime", device["lastConnectionTime"] + device["hiloId"], "onlineStatus", device.get("connectionStatus") ) ) attributes.append( self.build_attribute( - device["hiloId"], "Version", device["controllerSoftwareVersion"] + device["hiloId"], "LastStatusTime", device["lastConnectionTime"] ) ) attributes.append( self.build_attribute( - device["hiloId"], - "Disconnected", - device["connectionStatus"] == "DISCONNECTED", + device["hiloId"], "Version", device["controllerSoftwareVersion"] ) - ) # Offline + ) attributes.append( self.build_attribute( device["hiloId"], @@ -455,7 +467,7 @@ def _map_basic_device(self, device: Dict[str, Any]) -> list[Dict[str, Any]]: self.build_attribute( device["hiloId"], "Disconnected", - device["connectionStatus"] == "DISCONNECTED", + device.get("connectionStatus") != "CONNECTED", ), ] diff --git a/pyhilo/devices.py b/pyhilo/devices.py index b43c83f..0e22f34 100644 --- a/pyhilo/devices.py +++ b/pyhilo/devices.py @@ -59,10 +59,11 @@ def _map_readings_to_devices( if device_identifier == 0: device_identifier = reading.hilo_id device = self.find_device(device_identifier) - # If device_id was 0 and hilo_id lookup failed, this is likely - # a gateway reading that arrives before GatewayValuesReceived - # assigns the real ID. Fall back to the gateway device. - if device is None and reading.device_id == 0: + # If device_id was 0 and hilo_id is empty, this is a SignalR + # gateway reading arriving before GatewayValuesReceived assigns + # the real ID. Never route an unmatched non-empty hilo_id to the + # gateway, as it belongs to a different device. + if device is None and reading.device_id == 0 and not reading.hilo_id: device = next((d for d in self.devices if d.type == "Gateway"), None) if device: device.update_readings(reading) @@ -71,7 +72,9 @@ def _map_readings_to_devices( updated_devices.append(device) else: LOG.warning( - f"Unable to find device {reading.device_id} for reading {reading}" + "Unable to find device %s for reading %s", + device_identifier or reading.device_id, + reading, ) return updated_devices @@ -79,6 +82,8 @@ def find_device(self, device_identifier: int | str) -> HiloDevice | None: """Makes sure the devices received have an identifier, this means some need to be hardcoded like the unknown power meter. """ + if not device_identifier: + return None if isinstance(device_identifier, int): return next((d for d in self.devices if d.id == device_identifier), None) return next((d for d in self.devices if d.hilo_id == device_identifier), None) diff --git a/pyhilo/graphql.py b/pyhilo/graphql.py index 1ffe3c9..4e221d0 100644 --- a/pyhilo/graphql.py +++ b/pyhilo/graphql.py @@ -45,6 +45,7 @@ def _create_ssl_context() -> ssl.SSLContext: lastUpdate lastUpdateVersion devices { + __typename deviceType hiloId physicalAddress @@ -285,7 +286,11 @@ def _create_ssl_context() -> ssl.SSLContext: operationId status device { + __typename ... on Gateway { + deviceType + hiloId + physicalAddress connectionStatus controllerSoftwareVersion lastConnectionTime @@ -516,33 +521,21 @@ def _create_ssl_context() -> ssl.SSLContext: } }""" - SUBSCRIPTION_LOCATION_UPDATED: str = """subscription onAnyLocationUpdated($locationHiloId: String!){ + SUBSCRIPTION_LOCATION_UPDATED: str = """subscription onAnyLocationUpdated($locationHiloId: String!) { onAnyLocationUpdated(locationHiloId: $locationHiloId) { - locationHiloId - deviceType transmissionTime operationId location { - ...on Container { + devices { + __typename hiloId - devices { - deviceType - hiloId - physicalAddress - connectionStatus - ... on BasicChargeController { - connectionStatus - } - ... on LowVoltageThermostat { - connectionStatus - } - } + connectionStatus } } } }""" - async def call_get_location_query(self, location_hilo_id: str) -> None: + async def call_get_location_query(self, location_hilo_id: str) -> list[str]: """This functions calls the digital-twin and requests location id""" access_token = await self._get_access_token() url = f"https://{PLATFORM_HOST}/api/digital-twin/v3/graphql" @@ -568,7 +561,7 @@ async def call_get_location_query(self, location_hilo_id: str) -> None: response_json = response.json() except Exception as e: LOG.error("Error parsing response: %s", e) - return + return [] if "errors" in response_json: for error in response_json["errors"]: @@ -582,25 +575,29 @@ async def call_get_location_query(self, location_hilo_id: str) -> None: response_json = response.json() except Exception as e: LOG.error("Error parsing response on retry: %s", e) - return + return [] break if "errors" in response_json: LOG.error("GraphQL errors: %s", response_json["errors"]) - return + return [] if "data" in response_json: devices = ( response_json["data"].get("getLocation", {}).get("devices", []) ) gateways = [ - d for d in devices if d.get("deviceType") in ("Gateway", "Hub") + d + for d in devices + if isinstance(d, dict) and self.mapper.is_gateway_payload(d) ] LOG.debug( "Gateway devices in getLocation response: %s", json.dumps(gateways, indent=2), ) - self._handle_query_result(response_json["data"]) + return self._handle_query_result(response_json["data"]) + + return [] async def subscribe_to_device_updated( self, @@ -650,9 +647,9 @@ def _parse_sse_message(self, sse: Any) -> Optional[Dict[str, Any]]: def _handle_sse_message( self, data: Dict[str, Any], - handler: Callable[[Dict[str, Any]], str], + handler: Callable[[dict[str, object]], list[str]], callback: Optional[Callable[[str], None]], - ) -> tuple: + ) -> tuple[bool, bool]: """Dispatch a parsed SSE message. Returns (retry_apq, had_success).""" if "errors" in data: if any( @@ -661,20 +658,21 @@ def _handle_sse_message( return True, False LOG.error("GraphQL Subscription Errors: %s", data["errors"]) return False, False - if "data" in data: + if "data" in data and isinstance(data["data"], dict): LOG.debug("Received subscription result %s", data["data"]) - handler_result = handler(data["data"]) + hilo_ids = handler(data["data"]) if callback: - callback(handler_result) + for hilo_id in hilo_ids: + callback(hilo_id) return False, True return False, False async def _drain_sse_events( self, event_source: Any, - handler: Callable[[Dict[str, Any]], str], + handler: Callable[[dict[str, object]], list[str]], callback: Optional[Callable[[str], None]], - ) -> tuple: + ) -> tuple[bool, bool]: """Read events until the stream closes. Returns (retry_apq, had_success).""" had_success = False sse_iter = event_source.aiter_sse() @@ -707,9 +705,9 @@ async def _run_sse_connection( url: str, headers: Dict[str, str], payload: Dict[str, Any], - handler: Callable[[Dict[str, Any]], str], + handler: Callable[[dict[str, object]], list[str]], callback: Optional[Callable[[str], None]], - ) -> tuple: + ) -> tuple[bool, bool]: """Open one SSE connection and drain it. Returns (retry_apq, had_success).""" async with httpx.AsyncClient( http2=True, timeout=None, verify=self._ssl_context @@ -723,7 +721,7 @@ async def _listen_to_sse( self, query: str, variables: Dict[str, Any], - handler: Callable[[Dict[str, Any]], str], + handler: Callable[[dict[str, object]], list[str]], callback: Optional[Callable[[str], None]] = None, location_hilo_id: Optional[str] = None, ) -> None: @@ -752,6 +750,7 @@ async def _listen_to_sse( "SSE connection closed by server. Reconnecting in 5 seconds..." ) await asyncio.sleep(5) + await self._resync_after_reconnect(location_hilo_id, callback) except asyncio.TimeoutError: # Keepalive timeout: the connection was recently live, so start @@ -765,15 +764,7 @@ async def _listen_to_sse( backoff_delay = min(backoff_delay * 2, self._BACKOFF_MAX) if "query" in payload: del payload["query"] - if location_hilo_id: - try: - await self.call_get_location_query(location_hilo_id) - LOG.debug("call_get_location_query success after reconnect") - except Exception as e2: - LOG.error( - "exception while RE-connecting, retrying: %s", - e2, - ) + await self._resync_after_reconnect(location_hilo_id, callback) except Exception as e: LOG.debug( @@ -785,35 +776,50 @@ async def _listen_to_sse( backoff_delay = min(backoff_delay * 2, self._BACKOFF_MAX) if "query" in payload: del payload["query"] - if location_hilo_id: - try: - await self.call_get_location_query(location_hilo_id) - LOG.debug("call_get_location_query success after reconnect") - except Exception as e2: - LOG.error( - "exception while RE-connecting, retrying: %s", - e2, - ) + await self._resync_after_reconnect(location_hilo_id, callback) + + async def _resync_after_reconnect( + self, + location_hilo_id: Optional[str], + callback: Optional[Callable[[str], None]], + ) -> None: + if not location_hilo_id: + return + try: + hilo_ids = await self.call_get_location_query(location_hilo_id) + LOG.debug("call_get_location_query success after reconnect") + except Exception as err: + LOG.error("exception while RE-connecting, retrying: %s", err) + return + if callback: + for hilo_id in hilo_ids: + callback(hilo_id) async def _get_access_token(self) -> str: """Get the access token.""" return await self._api.async_get_access_token() - def _handle_query_result(self, result: Dict[str, Any]) -> None: + def _handle_query_result(self, result: Dict[str, Any]) -> list[str]: """Handle the result of the GraphQL query for location and devices.""" devices_values: List[Dict[str, Any]] = result["getLocation"]["devices"] for raw_device in devices_values: - if raw_device.get("deviceType") in ("Gateway", "Hub"): - if self._devices.find_device(1) is None: + if self.mapper.is_gateway_payload(raw_device): + existing_gw = self._devices.find_device(1) or next( + (d for d in self._devices.devices if d.type == "Gateway"), None + ) + if existing_gw is None: gw = self._build_gateway_dict(raw_device) LOG.debug("Creating gateway device from GraphQL: %s", gw) - gw_dev = self._devices.generate_device(gw) - if gw_dev not in self._devices.devices: - self._devices.devices.append(gw_dev) + self._devices.devices.append(self._devices.generate_device(gw)) + elif not existing_gw.hilo_id and isinstance( + hilo_id := raw_device.get("hiloId"), str + ): + existing_gw.hilo_id = hilo_id attributes = self.mapper.map_query_values(devices_values) - self._devices.parse_values_received(attributes) + updated_devices = self._devices.parse_values_received(attributes) + return [device.hilo_id for device in updated_devices if device.hilo_id] def _build_gateway_dict(self, raw_device: Dict[str, Any]) -> Dict[str, Any]: """Build a dictionary representing the gateway device from raw GraphQL data.""" @@ -829,6 +835,7 @@ def _build_gateway_dict(self, raw_device: Dict[str, Any]) -> Dict[str, Any]: "type": "Gateway", "category": "Gateway", "id": 1, + "hilo_id": hilo_id, "identifier": mac, "sdi": mac, "provider": 1, @@ -847,20 +854,34 @@ def _build_gateway_dict(self, raw_device: Dict[str, Any]) -> Dict[str, Any]: "disconnected": {"value": connection_status != "CONNECTED"}, } - def _handle_device_subscription_result(self, result: Dict[str, Any]) -> str: + def _handle_device_subscription_result( + self, result: dict[str, object] + ) -> list[str]: """Handle the result of the GraphQL subscription for device updates.""" - device_value: Dict[str, Any] = result["onAnyDeviceUpdated"]["device"] + on_device = result.get("onAnyDeviceUpdated") + if not isinstance(on_device, dict): + return [] + device_value = on_device.get("device") + if not isinstance(device_value, dict): + return [] attributes = self.mapper.map_device_subscription_values(device_value) - updated_device = self._devices.parse_values_received(attributes) + updated_devices = self._devices.parse_values_received(attributes) # callback to update the device in the UI - LOG.debug("Device updated: %s", updated_device) - return str(device_value.get("hiloId")) + LOG.debug("Device updated: %s", updated_devices) + return [device.hilo_id for device in updated_devices if device.hilo_id] - def _handle_location_subscription_result(self, result: Dict[str, Any]) -> str: + def _handle_location_subscription_result( + self, result: dict[str, object] + ) -> list[str]: """Handle the result of the GraphQL subscription for location updates.""" - location_value: Dict[str, Any] = result["onAnyLocationUpdated"]["location"] + on_location = result.get("onAnyLocationUpdated") + if not isinstance(on_location, dict): + return [] + location_value = on_location.get("location") + if not isinstance(location_value, dict): + return [] attributes = self.mapper.map_location_subscription_values(location_value) - updated_device = self._devices.parse_values_received(attributes) + updated_devices = self._devices.parse_values_received(attributes) # callback to update the device in the UI - LOG.debug("Device updated: %s", updated_device) - return str(location_value.get("hiloId")) + LOG.debug("Device updated: %s", updated_devices) + return [device.hilo_id for device in updated_devices if device.hilo_id] diff --git a/tests/test_graphql.py b/tests/test_graphql.py new file mode 100644 index 0000000..091e769 --- /dev/null +++ b/tests/test_graphql.py @@ -0,0 +1,371 @@ +"""Tests for GraphQlHelper Gateway creation and subscription result routing.""" + +from __future__ import annotations + +import re +from unittest.mock import AsyncMock, MagicMock, patch + +import pytest + +from pyhilo import API +from pyhilo.devices import Devices +from pyhilo.graphql import GraphQlHelper + +GATEWAY_HILO_ID = "urn:hilo:ihub:AA11BB22CC33:0" +TSTAT_HILO_ID = "urn:hilo:philo:1a2b3c4d5e6f0001:0" +SWITCH_HILO_ID = "urn:hilo:philo:9a8b7c6d5e4f0002:0" + + +def _make_helper() -> tuple[GraphQlHelper, Devices]: + api = API(session=MagicMock(), auth=MagicMock()) + devices = Devices(api) + devices.location_id = 42 + devices.location_hilo_id = "urn:hilo:crm:00000-abcdef:0" + return GraphQlHelper(api, devices), devices + + +def _gateway_payload( + connection_status: str, + device_type: str | None = "Gateway", + typename: str | None = "Gateway", +) -> dict[str, object]: + payload: dict[str, object] = { + "deviceType": device_type, + "hiloId": GATEWAY_HILO_ID, + "physicalAddress": "AA11BB22CC33", + "connectionStatus": connection_status, + "controllerSoftwareVersion": "1.2.3", + "lastConnectionTime": "2026-11-11T12:00:00Z", + "willBeConnectedToSmartMeter": True, + "zigBeeChannel": 15, + "zigBeePairingModeEnhanced": False, + "smartMeterZigBeeChannel": 24, + "smartMeterPairingStatus": True, + } + if typename is not None: + payload["__typename"] = typename + return payload + + +@pytest.mark.parametrize( + ("typename", "device_type", "connection_status", "expected_available"), + [ + pytest.param(None, "Gateway", "CONNECTED", True, id="gateway-connected"), + pytest.param(None, "Gateway", "DISCONNECTED", False, id="gateway-disconnected"), + pytest.param(None, "hub", "CONNECTED", True, id="lowercase-hub-connected"), + pytest.param( + None, "gateway", "DISCONNECTED", False, id="lowercase-gateway-offline" + ), + pytest.param( + "Gateway", None, "CONNECTED", True, id="typename-only-null-device-type" + ), + pytest.param( + "Gateway", + "ihub", + "DISCONNECTED", + False, + id="typename-with-unrecognized-device-type", + ), + ], +) +def test_gateway_query_populates_hilo_id_and_availability( + typename: str | None, + device_type: str | None, + connection_status: str, + expected_available: bool, +) -> None: + """getLocation creates the Gateway with its real hilo_id across typename and deviceType forms.""" + helper, devices = _make_helper() + payload = _gateway_payload( + connection_status, device_type=device_type, typename=typename + ) + + updated_ids = helper._handle_query_result({"getLocation": {"devices": [payload]}}) + + gateway = devices.find_device(GATEWAY_HILO_ID) + assert gateway is not None + assert updated_ids == [GATEWAY_HILO_ID] + assert gateway.hilo_id == GATEWAY_HILO_ID + assert gateway.identifier == "AA11BB22CC33" + assert gateway.available is expected_available + assert gateway.get_value("online_status") == connection_status + + +def test_gateway_query_does_not_duplicate_when_gateway_id_changed() -> None: + """Re-running getLocation after SignalR updates gateway.id refreshes it in place.""" + helper, devices = _make_helper() + helper._handle_query_result( + {"getLocation": {"devices": [_gateway_payload("CONNECTED")]}} + ) + gateway = devices.find_device(GATEWAY_HILO_ID) + assert gateway is not None + gateway.id = 98765 + + helper._handle_query_result( + {"getLocation": {"devices": [_gateway_payload("DISCONNECTED")]}} + ) + + gateways = [d for d in devices.all if d.type == "Gateway"] + assert len(gateways) == 1 + assert gateway.available is False + + +def test_gateway_query_backfills_hilo_id_on_existing_gateway() -> None: + """An existing Gateway without hilo_id gets its hilo_id populated by getLocation.""" + helper, devices = _make_helper() + existing_gw = devices.generate_device( + { + "id": 1, + "name": "Hilo Gateway", + "type": "Gateway", + "provider": 1, + "supportedAttributes": "Disconnected", + "settableAttributes": "", + "Disconnected": {"value": False}, + } + ) + devices.devices.append(existing_gw) + + helper._handle_query_result( + {"getLocation": {"devices": [_gateway_payload("DISCONNECTED")]}} + ) + + assert existing_gw.hilo_id == GATEWAY_HILO_ID + assert existing_gw.available is False + + +def test_gateway_device_subscription_updates_availability_and_notifies_callback() -> ( + None +): + """onAnyDeviceUpdated updates Gateway availability and passes its hilo_id to callback.""" + helper, devices = _make_helper() + helper._handle_query_result( + {"getLocation": {"devices": [_gateway_payload("CONNECTED")]}} + ) + gateway = devices.find_device(GATEWAY_HILO_ID) + assert gateway is not None + assert gateway.available is True + + notified: list[str] = [] + sse_payload: dict[str, object] = { + "data": { + "onAnyDeviceUpdated": { + "device": _gateway_payload( + "DISCONNECTED", device_type=None, typename="Gateway" + ), + } + } + } + + retry, had_success = helper._handle_sse_message( + sse_payload, helper._handle_device_subscription_result, notified.append + ) + + assert (retry, had_success) == (False, True) + assert gateway.available is False + assert gateway.get_value("online_status") == "DISCONNECTED" + assert notified == [GATEWAY_HILO_ID] + + +def test_device_subscription_skips_callback_for_unmapped_device() -> None: + """onAnyDeviceUpdated does not invoke callback when no device was updated.""" + helper, _ = _make_helper() + notified: list[str] = [] + sse_payload: dict[str, object] = { + "data": { + "onAnyDeviceUpdated": { + "device": {}, + } + } + } + + retry, had_success = helper._handle_sse_message( + sse_payload, helper._handle_device_subscription_result, notified.append + ) + + assert (retry, had_success) == (False, True) + assert notified == [] + + +def test_unknown_hilo_id_reading_does_not_overwrite_gateway_availability() -> None: + """GraphQL readings for an unknown hiloId must not fall back to the Gateway device.""" + helper, devices = _make_helper() + helper._handle_query_result( + {"getLocation": {"devices": [_gateway_payload("CONNECTED")]}} + ) + gateway = devices.find_device(GATEWAY_HILO_ID) + assert gateway is not None + assert gateway.available is True + + notified: list[str] = [] + sse_payload: dict[str, object] = { + "data": { + "onAnyLocationUpdated": { + "transmissionTime": "2026-11-11T12:05:00Z", + "operationId": "00000000-0000-0000-0000-000000000011", + "location": { + "devices": [ + { + "__typename": "BasicSwitch", + "hiloId": "urn:hilo:philo:unpaired-switch:0", + "connectionStatus": "DISCONNECTED", + } + ] + }, + } + } + } + + helper._handle_sse_message( + sse_payload, helper._handle_location_subscription_result, notified.append + ) + + assert gateway.available is True + assert notified == [] + + +def test_signalr_zero_device_id_without_hilo_id_falls_back_to_gateway() -> None: + """SignalR readings with deviceId=0 and no hiloId route to the Gateway, not other unset-hilo_id devices.""" + helper, devices = _make_helper() + legacy_sensor = devices.generate_device( + { + "id": 500, + "name": "Weather Station", + "type": "IndoorWeatherStation", + "provider": 2, + "supportedAttributes": "Disconnected", + "settableAttributes": "", + "Disconnected": {"value": False}, + } + ) + devices.devices.append(legacy_sensor) + helper._handle_query_result( + {"getLocation": {"devices": [_gateway_payload("CONNECTED")]}} + ) + gateway = devices.find_device(GATEWAY_HILO_ID) + assert gateway is not None + + updated = devices.parse_values_received( + [ + { + "deviceId": 0, + "timeStampUTC": "2026-11-11T12:00:00Z", + "attribute": "Disconnected", + "value": True, + } + ] + ) + + assert updated == [gateway] + assert gateway.available is False + assert legacy_sensor.available is True + + +async def test_resync_after_reconnect_notifies_callback_with_updated_hilo_ids() -> None: + """SSE reconnect state resync forwards updated device hilo_ids to callback.""" + helper, _ = _make_helper() + notified: list[str] = [] + + with patch.object( + helper, + "call_get_location_query", + new=AsyncMock(return_value=[GATEWAY_HILO_ID, TSTAT_HILO_ID]), + ): + await helper._resync_after_reconnect( + "urn:hilo:crm:00000-abcdef:0", notified.append + ) + + assert notified == [GATEWAY_HILO_ID, TSTAT_HILO_ID] + + +def test_subscription_device_updated_gateway_fragment_requests_identity_fields() -> ( + None +): + """The Gateway inline fragment in SUBSCRIPTION_DEVICE_UPDATED must include deviceType and hiloId.""" + match = re.search( + r"\.\.\.\s*on\s+Gateway\s*\{([^}]*)\}", + GraphQlHelper.SUBSCRIPTION_DEVICE_UPDATED, + ) + assert match is not None + fields = set(match.group(1).split()) + assert {"deviceType", "hiloId", "physicalAddress", "connectionStatus"} <= fields + + +def test_location_subscription_updates_devices_and_dispatches_each_hilo_id() -> None: + """onAnyLocationUpdated updates each device's availability and invokes callback per hilo_id.""" + helper, devices = _make_helper() + helper._handle_query_result( + {"getLocation": {"devices": [_gateway_payload("CONNECTED")]}} + ) + gateway = devices.find_device(GATEWAY_HILO_ID) + assert gateway is not None + tstat = devices.generate_device( + { + "id": 100, + "hilo_id": TSTAT_HILO_ID, + "name": "Living Room", + "type": "Thermostat", + "provider": 1, + "supportedAttributes": "Disconnected, CurrentTemperature", + "settableAttributes": "", + "Disconnected": {"value": False}, + } + ) + switch = devices.generate_device( + { + "id": 101, + "hilo_id": SWITCH_HILO_ID, + "name": "Porch Light", + "type": "LightSwitch", + "provider": 1, + "supportedAttributes": "Disconnected, OnOff", + "settableAttributes": "OnOff", + "Disconnected": {"value": True}, + } + ) + devices.devices.extend([tstat, switch]) + + notified: list[str] = [] + sse_payload: dict[str, object] = { + "data": { + "onAnyLocationUpdated": { + "transmissionTime": "2026-11-11T12:05:00Z", + "operationId": "00000000-0000-0000-0000-000000000010", + "location": { + "devices": [ + { + "__typename": "Gateway", + "hiloId": GATEWAY_HILO_ID, + "connectionStatus": "DISCONNECTED", + }, + { + "__typename": "BasicThermostat", + "hiloId": TSTAT_HILO_ID, + "connectionStatus": "DISCONNECTED", + }, + { + "__typename": "BasicSwitch", + "hiloId": SWITCH_HILO_ID, + "connectionStatus": "CONNECTED", + }, + { + "__typename": "BasicDevice", + "hiloId": "urn:hilo:netatmo:station:0", + "connectionStatus": None, + }, + ] + }, + } + } + } + + retry, had_success = helper._handle_sse_message( + sse_payload, helper._handle_location_subscription_result, notified.append + ) + + assert (retry, had_success) == (False, True) + assert gateway.available is False + assert gateway.get_value("online_status") == "DISCONNECTED" + assert tstat.available is False + assert switch.available is True + assert notified == [GATEWAY_HILO_ID, TSTAT_HILO_ID, SWITCH_HILO_ID] diff --git a/tests/test_graphql_value_mapper.py b/tests/test_graphql_value_mapper.py index fb667b0..6cea2c3 100644 --- a/tests/test_graphql_value_mapper.py +++ b/tests/test_graphql_value_mapper.py @@ -25,10 +25,10 @@ def test_smart_meter_maps_zigbee_channel() -> None: assert channel == [24] -def _hub(connection_status: str) -> dict: +def _hub(connection_status: str | None, device_type: str = "Hub") -> dict[str, object]: return { "hiloId": "hub-1", - "deviceType": "Hub", + "deviceType": device_type, "connectionStatus": connection_status, "lastConnectionTime": "2026-11-01T12:00:00Z", "controllerSoftwareVersion": "1.0.0", @@ -38,9 +38,9 @@ def _hub(connection_status: str) -> dict: } -def _disconnected_values(device: dict) -> set[bool]: +def _disconnected_values(device: dict[str, object]) -> list[bool]: attributes = GraphqlValueMapper().map_device_subscription_values(device) - return {a["value"] for a in attributes if a["attribute"] == "Disconnected"} + return [a["value"] for a in attributes if a["attribute"] == "Disconnected"] @pytest.mark.parametrize( @@ -55,12 +55,16 @@ def _disconnected_values(device: dict) -> set[bool]: True, id="tstat-disconnected", ), + pytest.param( + "onAnyDeviceUpdated-tstat.json", None, True, id="tstat-null-status" + ), pytest.param( "onAnyDeviceUpdated-cee.json", "CONNECTED", False, id="cee-connected" ), pytest.param( "onAnyDeviceUpdated-cee.json", "DISCONNECTED", True, id="cee-disconnected" ), + pytest.param("onAnyDeviceUpdated-cee.json", None, True, id="cee-null-status"), pytest.param( "onAnyDeviceUpdated-meter.json", "CONNECTED", False, id="meter-connected" ), @@ -70,16 +74,78 @@ def _disconnected_values(device: dict) -> set[bool]: True, id="meter-disconnected", ), + pytest.param( + "onAnyDeviceUpdated-meter.json", None, True, id="meter-null-status" + ), ], ) def test_device_disconnected_follows_connection_status( - filename: str, connection_status: str, expected: bool + filename: str, connection_status: str | None, expected: bool ) -> None: - """Hilo reports connectionStatus as a string; DISCONNECTED maps to Disconnected=True.""" + """Only CONNECTED maps to Disconnected=False; DISCONNECTED or null maps to True.""" device = _device(filename) device["connectionStatus"] = connection_status - assert _disconnected_values(device) == {expected} + assert _disconnected_values(device) == [expected] + + +def test_device_disconnected_when_connection_status_absent() -> None: + """Payloads omitting connectionStatus default to Disconnected=True.""" + device = _device("onAnyDeviceUpdated-tstat.json") + del device["connectionStatus"] + + assert _disconnected_values(device) == [True] + + +@pytest.mark.parametrize( + ("device_type", "connection_status", "expected"), + [ + pytest.param("Hub", "CONNECTED", False, id="hub-connected"), + pytest.param("Hub", "DISCONNECTED", True, id="hub-disconnected"), + pytest.param("Hub", None, True, id="hub-null-status"), + pytest.param("Gateway", "CONNECTED", False, id="gateway-connected"), + pytest.param("Gateway", "DISCONNECTED", True, id="gateway-disconnected"), + pytest.param("Gateway", None, True, id="gateway-null-status"), + ], +) +def test_hub_disconnected_follows_connection_status( + device_type: str, connection_status: str | None, expected: bool +) -> None: + """The gateway's Disconnected attribute is derived for both Hub and Gateway types.""" + assert _disconnected_values(_hub(connection_status, device_type)) == [expected] + + +@pytest.mark.parametrize( + "device_entry", + [ + pytest.param( + { + "__typename": "BasicDevice", + "deviceType": "IndoorWeatherStation", + "hiloId": "urn:hilo:netatmo:station:0", + "connectionStatus": None, + }, + id="basic-device-stub", + ), + pytest.param( + { + "deviceType": "IndoorWeatherStation", + "hiloId": "urn:hilo:netatmo:station:0", + "connectionStatus": None, + }, + id="unrecognized-device-type", + ), + pytest.param( + {"deviceType": "Tstat", "connectionStatus": "DISCONNECTED"}, + id="missing-hilo-id", + ), + ], +) +def test_query_values_skips_unmigrated_or_incomplete_devices( + device_entry: dict[str, object], +) -> None: + """getLocation skips BasicDevice stubs, unknown deviceType values, and missing hiloId.""" + assert GraphqlValueMapper().map_query_values([device_entry]) == [] @pytest.mark.parametrize( @@ -87,13 +153,53 @@ def test_device_disconnected_follows_connection_status( [ pytest.param("CONNECTED", False, id="connected"), pytest.param("DISCONNECTED", True, id="disconnected"), + pytest.param(None, True, id="null-status"), ], ) -def test_hub_disconnected_follows_connection_status( - connection_status: str, expected: bool +def test_location_subscription_maps_connection_status( + connection_status: str | None, expected: bool +) -> None: + """Location updates only carry hiloId and connectionStatus without full device fields.""" + payload: dict[str, object] = { + "devices": [ + { + "__typename": "BasicThermostat", + "hiloId": "urn:hilo:philo:1a2b3c4d5e6f0001:0", + "connectionStatus": connection_status, + } + ] + } + + attributes = GraphqlValueMapper().map_location_subscription_values(payload) + + by_name = {a["attribute"]: a["value"] for a in attributes} + assert by_name == {"Unpaired": False, "Disconnected": expected} + + +@pytest.mark.parametrize( + "device_entry", + [ + pytest.param( + { + "__typename": "BasicDevice", + "hiloId": "urn:hilo:netatmo:station:0", + "connectionStatus": None, + }, + id="basic-device-stub", + ), + pytest.param( + {"__typename": "BasicThermostat", "connectionStatus": "DISCONNECTED"}, + id="missing-hilo-id", + ), + ], +) +def test_location_subscription_skips_ignored_entries( + device_entry: dict[str, object], ) -> None: - """The gateway's Disconnected attribute is derived from the string status.""" - assert _disconnected_values(_hub(connection_status)) == {expected} + """Unmigrated BasicDevice stubs and entries missing hiloId produce no readings.""" + payload: dict[str, object] = {"devices": [device_entry]} + + assert GraphqlValueMapper().map_location_subscription_values(payload) == [] @pytest.mark.parametrize( From 05e5ee03509fda8f3394fad5587cd69150249429 Mon Sep 17 00:00:00 2001 From: Moustachauve <2206577+Moustachauve@users.noreply.github.com> Date: Mon, 16 Nov 2026 00:44:12 -0500 Subject: [PATCH 2/4] Narrow PR scope to Gateway hilo_id and device subscription updates Keep this change small and focused on Gateway identity and `onAnyDeviceUpdated` / reconnect-resync availability updates by deferring `onAnyLocationUpdated` schema changes to a separate PR, preserving `connectionStatus == "DISCONNECTED"` matching, and removing defensive type-narrowing branches and redundant test cases. --- pyhilo/device/graphql_value_mapper.py | 57 ++---- pyhilo/devices.py | 2 +- pyhilo/graphql.py | 92 ++++----- tests/test_graphql.py | 285 ++++++-------------------- tests/test_graphql_value_mapper.py | 112 +--------- 5 files changed, 120 insertions(+), 428 deletions(-) diff --git a/pyhilo/device/graphql_value_mapper.py b/pyhilo/device/graphql_value_mapper.py index 728a835..dda7f43 100644 --- a/pyhilo/device/graphql_value_mapper.py +++ b/pyhilo/device/graphql_value_mapper.py @@ -1,4 +1,3 @@ -from collections.abc import Mapping from datetime import datetime, timezone from typing import Any, Dict @@ -12,58 +11,36 @@ class GraphqlValueMapper: OnState = "on" - @staticmethod - def is_gateway_payload(device: Mapping[str, object]) -> bool: - if device.get("__typename") == "Gateway": - return True - device_type = device.get("deviceType") - return isinstance(device_type, str) and device_type.lower() in ( - "gateway", - "hub", - ) - def map_query_values(self, values: list[Dict[str, Any]]) -> list[Dict[str, Any]]: readings: list[Dict[str, Any]] = [] for device in values: - readings.extend(self._map_devices_values(device)) + if device.get("deviceType") is not None: + reading = self._map_devices_values(device) + readings.extend(reading) return readings def map_device_subscription_values( self, device: Dict[str, Any] ) -> list[Dict[str, Any]]: - return self._map_devices_values(device) + readings: list[Dict[str, Any]] = [] + if device.get("deviceType") is not None: + reading = self._map_devices_values(device) + readings.extend(reading) + return readings def map_location_subscription_values( self, values: Dict[str, Any] ) -> list[Dict[str, Any]]: readings: list[Dict[str, Any]] = [] - for device in values.get("devices") or []: - if device.get("__typename") == "BasicDevice" or not device.get("hiloId"): - continue - readings.extend(self._map_basic_device(device)) - if self.is_gateway_payload(device): - readings.append( - self.build_attribute( - device["hiloId"], - "onlineStatus", - device.get("connectionStatus"), - ) - ) + for device in values.get("devices", []): + if device.get("deviceType") is not None: + reading = self._map_devices_values(device) + readings.extend(reading) return readings def _map_devices_values(self, device: Dict[str, Any]) -> list[Dict[str, Any]]: - # Digital-Twin returns BasicDevice stubs with connectionStatus=null for - # unmigrated SignalR-managed devices (e.g. weather stations, smoke detectors). - if device.get("__typename") == "BasicDevice" or not device.get("hiloId"): - return [] attributes: list[Dict[str, Any]] = self._map_basic_device(device) - if self.is_gateway_payload(device): - attributes.extend(self._build_gateway(device)) - return attributes - device_type = device.get("deviceType") - if not isinstance(device_type, str): - return [] - match device_type.lower(): + match device["deviceType"].lower(): case "tstat": attributes.extend(self._build_thermostat(device)) case "cee": # Water Heater @@ -78,6 +55,8 @@ def _map_devices_values(self, device: Dict[str, Any]) -> list[Dict[str, Any]]: attributes.extend(self._build_charging_point(device)) case "meter": # Smart Meter attributes.extend(self._build_smart_meter(device)) + case "hub" | "gateway": # Gateway + attributes.extend(self._build_gateway(device)) case "colorbulb": attributes.extend(self._build_light(device)) case "whitebulb": @@ -87,7 +66,7 @@ def _map_devices_values(self, device: Dict[str, Any]) -> list[Dict[str, Any]]: case "switch": attributes.extend(self._build_switch(device)) case _: - return [] + pass return attributes def _map_to_device_reading( @@ -111,7 +90,7 @@ def _build_gateway(self, device: Dict[str, Any]) -> list[Dict[str, Any]]: attributes = [] attributes.append( self.build_attribute( - device["hiloId"], "onlineStatus", device.get("connectionStatus") + device["hiloId"], "onlineStatus", device["connectionStatus"] ) ) attributes.append( @@ -467,7 +446,7 @@ def _map_basic_device(self, device: Dict[str, Any]) -> list[Dict[str, Any]]: self.build_attribute( device["hiloId"], "Disconnected", - device.get("connectionStatus") != "CONNECTED", + device["connectionStatus"] == "DISCONNECTED", ), ] diff --git a/pyhilo/devices.py b/pyhilo/devices.py index 0e22f34..5355623 100644 --- a/pyhilo/devices.py +++ b/pyhilo/devices.py @@ -73,7 +73,7 @@ def _map_readings_to_devices( else: LOG.warning( "Unable to find device %s for reading %s", - device_identifier or reading.device_id, + device_identifier, reading, ) return updated_devices diff --git a/pyhilo/graphql.py b/pyhilo/graphql.py index 4e221d0..0ff41e5 100644 --- a/pyhilo/graphql.py +++ b/pyhilo/graphql.py @@ -45,7 +45,6 @@ def _create_ssl_context() -> ssl.SSLContext: lastUpdate lastUpdateVersion devices { - __typename deviceType hiloId physicalAddress @@ -286,7 +285,6 @@ def _create_ssl_context() -> ssl.SSLContext: operationId status device { - __typename ... on Gateway { deviceType hiloId @@ -521,15 +519,27 @@ def _create_ssl_context() -> ssl.SSLContext: } }""" - SUBSCRIPTION_LOCATION_UPDATED: str = """subscription onAnyLocationUpdated($locationHiloId: String!) { + SUBSCRIPTION_LOCATION_UPDATED: str = """subscription onAnyLocationUpdated($locationHiloId: String!){ onAnyLocationUpdated(locationHiloId: $locationHiloId) { + locationHiloId + deviceType transmissionTime operationId location { - devices { - __typename + ...on Container { hiloId - connectionStatus + devices { + deviceType + hiloId + physicalAddress + connectionStatus + ... on BasicChargeController { + connectionStatus + } + ... on LowVoltageThermostat { + connectionStatus + } + } } } } @@ -589,7 +599,7 @@ async def call_get_location_query(self, location_hilo_id: str) -> list[str]: gateways = [ d for d in devices - if isinstance(d, dict) and self.mapper.is_gateway_payload(d) + if (d.get("deviceType") or "").lower() in ("gateway", "hub") ] LOG.debug( "Gateway devices in getLocation response: %s", @@ -647,9 +657,9 @@ def _parse_sse_message(self, sse: Any) -> Optional[Dict[str, Any]]: def _handle_sse_message( self, data: Dict[str, Any], - handler: Callable[[dict[str, object]], list[str]], + handler: Callable[[Dict[str, Any]], str], callback: Optional[Callable[[str], None]], - ) -> tuple[bool, bool]: + ) -> tuple: """Dispatch a parsed SSE message. Returns (retry_apq, had_success).""" if "errors" in data: if any( @@ -658,21 +668,20 @@ def _handle_sse_message( return True, False LOG.error("GraphQL Subscription Errors: %s", data["errors"]) return False, False - if "data" in data and isinstance(data["data"], dict): + if "data" in data: LOG.debug("Received subscription result %s", data["data"]) - hilo_ids = handler(data["data"]) - if callback: - for hilo_id in hilo_ids: - callback(hilo_id) + handler_result = handler(data["data"]) + if callback and handler_result: + callback(handler_result) return False, True return False, False async def _drain_sse_events( self, event_source: Any, - handler: Callable[[dict[str, object]], list[str]], + handler: Callable[[Dict[str, Any]], str], callback: Optional[Callable[[str], None]], - ) -> tuple[bool, bool]: + ) -> tuple: """Read events until the stream closes. Returns (retry_apq, had_success).""" had_success = False sse_iter = event_source.aiter_sse() @@ -705,9 +714,9 @@ async def _run_sse_connection( url: str, headers: Dict[str, str], payload: Dict[str, Any], - handler: Callable[[dict[str, object]], list[str]], + handler: Callable[[Dict[str, Any]], str], callback: Optional[Callable[[str], None]], - ) -> tuple[bool, bool]: + ) -> tuple: """Open one SSE connection and drain it. Returns (retry_apq, had_success).""" async with httpx.AsyncClient( http2=True, timeout=None, verify=self._ssl_context @@ -721,7 +730,7 @@ async def _listen_to_sse( self, query: str, variables: Dict[str, Any], - handler: Callable[[dict[str, object]], list[str]], + handler: Callable[[Dict[str, Any]], str], callback: Optional[Callable[[str], None]] = None, location_hilo_id: Optional[str] = None, ) -> None: @@ -804,18 +813,11 @@ def _handle_query_result(self, result: Dict[str, Any]) -> list[str]: devices_values: List[Dict[str, Any]] = result["getLocation"]["devices"] for raw_device in devices_values: - if self.mapper.is_gateway_payload(raw_device): - existing_gw = self._devices.find_device(1) or next( - (d for d in self._devices.devices if d.type == "Gateway"), None - ) - if existing_gw is None: + if (raw_device.get("deviceType") or "").lower() in ("gateway", "hub"): + if not any(d.type == "Gateway" for d in self._devices.devices): gw = self._build_gateway_dict(raw_device) LOG.debug("Creating gateway device from GraphQL: %s", gw) self._devices.devices.append(self._devices.generate_device(gw)) - elif not existing_gw.hilo_id and isinstance( - hilo_id := raw_device.get("hiloId"), str - ): - existing_gw.hilo_id = hilo_id attributes = self.mapper.map_query_values(devices_values) updated_devices = self._devices.parse_values_received(attributes) @@ -854,34 +856,20 @@ def _build_gateway_dict(self, raw_device: Dict[str, Any]) -> Dict[str, Any]: "disconnected": {"value": connection_status != "CONNECTED"}, } - def _handle_device_subscription_result( - self, result: dict[str, object] - ) -> list[str]: + def _handle_device_subscription_result(self, result: Dict[str, Any]) -> str: """Handle the result of the GraphQL subscription for device updates.""" - on_device = result.get("onAnyDeviceUpdated") - if not isinstance(on_device, dict): - return [] - device_value = on_device.get("device") - if not isinstance(device_value, dict): - return [] + device_value: Dict[str, Any] = result["onAnyDeviceUpdated"]["device"] attributes = self.mapper.map_device_subscription_values(device_value) - updated_devices = self._devices.parse_values_received(attributes) + updated_device = self._devices.parse_values_received(attributes) # callback to update the device in the UI - LOG.debug("Device updated: %s", updated_devices) - return [device.hilo_id for device in updated_devices if device.hilo_id] + LOG.debug("Device updated: %s", updated_device) + return updated_device[0].hilo_id if updated_device else "" - def _handle_location_subscription_result( - self, result: dict[str, object] - ) -> list[str]: + def _handle_location_subscription_result(self, result: Dict[str, Any]) -> str: """Handle the result of the GraphQL subscription for location updates.""" - on_location = result.get("onAnyLocationUpdated") - if not isinstance(on_location, dict): - return [] - location_value = on_location.get("location") - if not isinstance(location_value, dict): - return [] + location_value: Dict[str, Any] = result["onAnyLocationUpdated"]["location"] attributes = self.mapper.map_location_subscription_values(location_value) - updated_devices = self._devices.parse_values_received(attributes) + updated_device = self._devices.parse_values_received(attributes) # callback to update the device in the UI - LOG.debug("Device updated: %s", updated_devices) - return [device.hilo_id for device in updated_devices if device.hilo_id] + LOG.debug("Device updated: %s", updated_device) + return str(location_value.get("hiloId")) diff --git a/tests/test_graphql.py b/tests/test_graphql.py index 091e769..385a3ce 100644 --- a/tests/test_graphql.py +++ b/tests/test_graphql.py @@ -1,35 +1,35 @@ -"""Tests for GraphQlHelper Gateway creation and subscription result routing.""" +"""Tests for GraphQlHelper Gateway creation and device subscription updates.""" from __future__ import annotations -import re +import ssl from unittest.mock import AsyncMock, MagicMock, patch import pytest -from pyhilo import API +from pyhilo import API, HiloDevice from pyhilo.devices import Devices from pyhilo.graphql import GraphQlHelper GATEWAY_HILO_ID = "urn:hilo:ihub:AA11BB22CC33:0" -TSTAT_HILO_ID = "urn:hilo:philo:1a2b3c4d5e6f0001:0" -SWITCH_HILO_ID = "urn:hilo:philo:9a8b7c6d5e4f0002:0" def _make_helper() -> tuple[GraphQlHelper, Devices]: - api = API(session=MagicMock(), auth=MagicMock()) + auth = MagicMock() + auth.async_get_access_token = AsyncMock(return_value="token") + api = API(session=MagicMock(), auth=auth) devices = Devices(api) devices.location_id = 42 devices.location_hilo_id = "urn:hilo:crm:00000-abcdef:0" - return GraphQlHelper(api, devices), devices + helper = GraphQlHelper(api, devices) + helper._ssl_context = MagicMock(spec=ssl.SSLContext) + return helper, devices def _gateway_payload( - connection_status: str, - device_type: str | None = "Gateway", - typename: str | None = "Gateway", + connection_status: str, device_type: str = "Gateway" ) -> dict[str, object]: - payload: dict[str, object] = { + return { "deviceType": device_type, "hiloId": GATEWAY_HILO_ID, "physicalAddress": "AA11BB22CC33", @@ -42,45 +42,34 @@ def _gateway_payload( "smartMeterZigBeeChannel": 24, "smartMeterPairingStatus": True, } - if typename is not None: - payload["__typename"] = typename - return payload + + +def _make_helper_with_gateway() -> tuple[GraphQlHelper, Devices, HiloDevice]: + helper, devices = _make_helper() + helper._handle_query_result( + {"getLocation": {"devices": [_gateway_payload("CONNECTED")]}} + ) + gateway = devices.find_device(GATEWAY_HILO_ID) + assert gateway is not None + return helper, devices, gateway @pytest.mark.parametrize( - ("typename", "device_type", "connection_status", "expected_available"), + ("connection_status", "expected_available"), [ - pytest.param(None, "Gateway", "CONNECTED", True, id="gateway-connected"), - pytest.param(None, "Gateway", "DISCONNECTED", False, id="gateway-disconnected"), - pytest.param(None, "hub", "CONNECTED", True, id="lowercase-hub-connected"), - pytest.param( - None, "gateway", "DISCONNECTED", False, id="lowercase-gateway-offline" - ), - pytest.param( - "Gateway", None, "CONNECTED", True, id="typename-only-null-device-type" - ), - pytest.param( - "Gateway", - "ihub", - "DISCONNECTED", - False, - id="typename-with-unrecognized-device-type", - ), + pytest.param("CONNECTED", True, id="connected"), + pytest.param("DISCONNECTED", False, id="disconnected"), ], ) def test_gateway_query_populates_hilo_id_and_availability( - typename: str | None, - device_type: str | None, - connection_status: str, - expected_available: bool, + connection_status: str, expected_available: bool ) -> None: - """getLocation creates the Gateway with its real hilo_id across typename and deviceType forms.""" + """getLocation creates the Gateway with its real hilo_id and availability.""" helper, devices = _make_helper() - payload = _gateway_payload( - connection_status, device_type=device_type, typename=typename - ) - updated_ids = helper._handle_query_result({"getLocation": {"devices": [payload]}}) + updated_ids = helper._handle_query_result( + {"getLocation": {"devices": [_gateway_payload(connection_status)]}} + ) gateway = devices.find_device(GATEWAY_HILO_ID) assert gateway is not None @@ -93,66 +82,27 @@ def test_gateway_query_populates_hilo_id_and_availability( def test_gateway_query_does_not_duplicate_when_gateway_id_changed() -> None: """Re-running getLocation after SignalR updates gateway.id refreshes it in place.""" - helper, devices = _make_helper() - helper._handle_query_result( - {"getLocation": {"devices": [_gateway_payload("CONNECTED")]}} - ) - gateway = devices.find_device(GATEWAY_HILO_ID) - assert gateway is not None + helper, devices, gateway = _make_helper_with_gateway() gateway.id = 98765 helper._handle_query_result( {"getLocation": {"devices": [_gateway_payload("DISCONNECTED")]}} ) - gateways = [d for d in devices.all if d.type == "Gateway"] - assert len(gateways) == 1 + assert [d for d in devices.all if d.type == "Gateway"] == [gateway] assert gateway.available is False -def test_gateway_query_backfills_hilo_id_on_existing_gateway() -> None: - """An existing Gateway without hilo_id gets its hilo_id populated by getLocation.""" - helper, devices = _make_helper() - existing_gw = devices.generate_device( - { - "id": 1, - "name": "Hilo Gateway", - "type": "Gateway", - "provider": 1, - "supportedAttributes": "Disconnected", - "settableAttributes": "", - "Disconnected": {"value": False}, - } - ) - devices.devices.append(existing_gw) - - helper._handle_query_result( - {"getLocation": {"devices": [_gateway_payload("DISCONNECTED")]}} - ) - - assert existing_gw.hilo_id == GATEWAY_HILO_ID - assert existing_gw.available is False - - def test_gateway_device_subscription_updates_availability_and_notifies_callback() -> ( None ): """onAnyDeviceUpdated updates Gateway availability and passes its hilo_id to callback.""" - helper, devices = _make_helper() - helper._handle_query_result( - {"getLocation": {"devices": [_gateway_payload("CONNECTED")]}} - ) - gateway = devices.find_device(GATEWAY_HILO_ID) - assert gateway is not None - assert gateway.available is True - + helper, _, gateway = _make_helper_with_gateway() notified: list[str] = [] sse_payload: dict[str, object] = { "data": { "onAnyDeviceUpdated": { - "device": _gateway_payload( - "DISCONNECTED", device_type=None, typename="Gateway" - ), + "device": _gateway_payload("DISCONNECTED", device_type="Hub"), } } } @@ -167,57 +117,25 @@ def test_gateway_device_subscription_updates_availability_and_notifies_callback( assert notified == [GATEWAY_HILO_ID] -def test_device_subscription_skips_callback_for_unmapped_device() -> None: - """onAnyDeviceUpdated does not invoke callback when no device was updated.""" - helper, _ = _make_helper() - notified: list[str] = [] - sse_payload: dict[str, object] = { - "data": { - "onAnyDeviceUpdated": { - "device": {}, - } - } - } - - retry, had_success = helper._handle_sse_message( - sse_payload, helper._handle_device_subscription_result, notified.append - ) - - assert (retry, had_success) == (False, True) - assert notified == [] - - def test_unknown_hilo_id_reading_does_not_overwrite_gateway_availability() -> None: """GraphQL readings for an unknown hiloId must not fall back to the Gateway device.""" - helper, devices = _make_helper() - helper._handle_query_result( - {"getLocation": {"devices": [_gateway_payload("CONNECTED")]}} - ) - gateway = devices.find_device(GATEWAY_HILO_ID) - assert gateway is not None - assert gateway.available is True - + helper, _, gateway = _make_helper_with_gateway() notified: list[str] = [] sse_payload: dict[str, object] = { "data": { - "onAnyLocationUpdated": { - "transmissionTime": "2026-11-11T12:05:00Z", - "operationId": "00000000-0000-0000-0000-000000000011", - "location": { - "devices": [ - { - "__typename": "BasicSwitch", - "hiloId": "urn:hilo:philo:unpaired-switch:0", - "connectionStatus": "DISCONNECTED", - } - ] - }, + "onAnyDeviceUpdated": { + "device": { + "deviceType": "Switch", + "hiloId": "urn:hilo:philo:unpaired-switch:0", + "connectionStatus": "DISCONNECTED", + "state": "OFF", + } } } } helper._handle_sse_message( - sse_payload, helper._handle_location_subscription_result, notified.append + sse_payload, helper._handle_device_subscription_result, notified.append ) assert gateway.available is True @@ -261,111 +179,22 @@ def test_signalr_zero_device_id_without_hilo_id_falls_back_to_gateway() -> None: assert legacy_sensor.available is True -async def test_resync_after_reconnect_notifies_callback_with_updated_hilo_ids() -> None: - """SSE reconnect state resync forwards updated device hilo_ids to callback.""" - helper, _ = _make_helper() - notified: list[str] = [] - - with patch.object( - helper, - "call_get_location_query", - new=AsyncMock(return_value=[GATEWAY_HILO_ID, TSTAT_HILO_ID]), - ): - await helper._resync_after_reconnect( - "urn:hilo:crm:00000-abcdef:0", notified.append - ) - - assert notified == [GATEWAY_HILO_ID, TSTAT_HILO_ID] - - -def test_subscription_device_updated_gateway_fragment_requests_identity_fields() -> ( - None -): - """The Gateway inline fragment in SUBSCRIPTION_DEVICE_UPDATED must include deviceType and hiloId.""" - match = re.search( - r"\.\.\.\s*on\s+Gateway\s*\{([^}]*)\}", - GraphQlHelper.SUBSCRIPTION_DEVICE_UPDATED, - ) - assert match is not None - fields = set(match.group(1).split()) - assert {"deviceType", "hiloId", "physicalAddress", "connectionStatus"} <= fields - - -def test_location_subscription_updates_devices_and_dispatches_each_hilo_id() -> None: - """onAnyLocationUpdated updates each device's availability and invokes callback per hilo_id.""" - helper, devices = _make_helper() - helper._handle_query_result( - {"getLocation": {"devices": [_gateway_payload("CONNECTED")]}} - ) - gateway = devices.find_device(GATEWAY_HILO_ID) - assert gateway is not None - tstat = devices.generate_device( - { - "id": 100, - "hilo_id": TSTAT_HILO_ID, - "name": "Living Room", - "type": "Thermostat", - "provider": 1, - "supportedAttributes": "Disconnected, CurrentTemperature", - "settableAttributes": "", - "Disconnected": {"value": False}, - } - ) - switch = devices.generate_device( - { - "id": 101, - "hilo_id": SWITCH_HILO_ID, - "name": "Porch Light", - "type": "LightSwitch", - "provider": 1, - "supportedAttributes": "Disconnected, OnOff", - "settableAttributes": "OnOff", - "Disconnected": {"value": True}, - } - ) - devices.devices.extend([tstat, switch]) - - notified: list[str] = [] - sse_payload: dict[str, object] = { - "data": { - "onAnyLocationUpdated": { - "transmissionTime": "2026-11-11T12:05:00Z", - "operationId": "00000000-0000-0000-0000-000000000010", - "location": { - "devices": [ - { - "__typename": "Gateway", - "hiloId": GATEWAY_HILO_ID, - "connectionStatus": "DISCONNECTED", - }, - { - "__typename": "BasicThermostat", - "hiloId": TSTAT_HILO_ID, - "connectionStatus": "DISCONNECTED", - }, - { - "__typename": "BasicSwitch", - "hiloId": SWITCH_HILO_ID, - "connectionStatus": "CONNECTED", - }, - { - "__typename": "BasicDevice", - "hiloId": "urn:hilo:netatmo:station:0", - "connectionStatus": None, - }, - ] - }, - } - } +async def test_resync_after_reconnect_updates_gateway_and_notifies_callback() -> None: + """SSE reconnect resync parses getLocation and forwards updated hilo_ids to callback.""" + helper, devices, gateway = _make_helper_with_gateway() + response = MagicMock() + response.raise_for_status = MagicMock() + response.json.return_value = { + "data": {"getLocation": {"devices": [_gateway_payload("DISCONNECTED")]}} } + client = AsyncMock() + client.post = AsyncMock(return_value=response) + client_cm = AsyncMock() + client_cm.__aenter__.return_value = client - retry, had_success = helper._handle_sse_message( - sse_payload, helper._handle_location_subscription_result, notified.append - ) + notified: list[str] = [] + with patch("pyhilo.graphql.httpx.AsyncClient", return_value=client_cm): + await helper._resync_after_reconnect(devices.location_hilo_id, notified.append) - assert (retry, had_success) == (False, True) assert gateway.available is False - assert gateway.get_value("online_status") == "DISCONNECTED" - assert tstat.available is False - assert switch.available is True - assert notified == [GATEWAY_HILO_ID, TSTAT_HILO_ID, SWITCH_HILO_ID] + assert notified == [GATEWAY_HILO_ID] diff --git a/tests/test_graphql_value_mapper.py b/tests/test_graphql_value_mapper.py index 6cea2c3..a406ac0 100644 --- a/tests/test_graphql_value_mapper.py +++ b/tests/test_graphql_value_mapper.py @@ -25,7 +25,7 @@ def test_smart_meter_maps_zigbee_channel() -> None: assert channel == [24] -def _hub(connection_status: str | None, device_type: str = "Hub") -> dict[str, object]: +def _hub(connection_status: str, device_type: str = "Hub") -> dict[str, object]: return { "hiloId": "hub-1", "deviceType": device_type, @@ -55,16 +55,12 @@ def _disconnected_values(device: dict[str, object]) -> list[bool]: True, id="tstat-disconnected", ), - pytest.param( - "onAnyDeviceUpdated-tstat.json", None, True, id="tstat-null-status" - ), pytest.param( "onAnyDeviceUpdated-cee.json", "CONNECTED", False, id="cee-connected" ), pytest.param( "onAnyDeviceUpdated-cee.json", "DISCONNECTED", True, id="cee-disconnected" ), - pytest.param("onAnyDeviceUpdated-cee.json", None, True, id="cee-null-status"), pytest.param( "onAnyDeviceUpdated-meter.json", "CONNECTED", False, id="meter-connected" ), @@ -74,134 +70,34 @@ def _disconnected_values(device: dict[str, object]) -> list[bool]: True, id="meter-disconnected", ), - pytest.param( - "onAnyDeviceUpdated-meter.json", None, True, id="meter-null-status" - ), ], ) def test_device_disconnected_follows_connection_status( - filename: str, connection_status: str | None, expected: bool + filename: str, connection_status: str, expected: bool ) -> None: - """Only CONNECTED maps to Disconnected=False; DISCONNECTED or null maps to True.""" + """Hilo reports connectionStatus as a string; DISCONNECTED maps to Disconnected=True.""" device = _device(filename) device["connectionStatus"] = connection_status assert _disconnected_values(device) == [expected] -def test_device_disconnected_when_connection_status_absent() -> None: - """Payloads omitting connectionStatus default to Disconnected=True.""" - device = _device("onAnyDeviceUpdated-tstat.json") - del device["connectionStatus"] - - assert _disconnected_values(device) == [True] - - @pytest.mark.parametrize( ("device_type", "connection_status", "expected"), [ pytest.param("Hub", "CONNECTED", False, id="hub-connected"), pytest.param("Hub", "DISCONNECTED", True, id="hub-disconnected"), - pytest.param("Hub", None, True, id="hub-null-status"), pytest.param("Gateway", "CONNECTED", False, id="gateway-connected"), pytest.param("Gateway", "DISCONNECTED", True, id="gateway-disconnected"), - pytest.param("Gateway", None, True, id="gateway-null-status"), ], ) def test_hub_disconnected_follows_connection_status( - device_type: str, connection_status: str | None, expected: bool + device_type: str, connection_status: str, expected: bool ) -> None: """The gateway's Disconnected attribute is derived for both Hub and Gateway types.""" assert _disconnected_values(_hub(connection_status, device_type)) == [expected] -@pytest.mark.parametrize( - "device_entry", - [ - pytest.param( - { - "__typename": "BasicDevice", - "deviceType": "IndoorWeatherStation", - "hiloId": "urn:hilo:netatmo:station:0", - "connectionStatus": None, - }, - id="basic-device-stub", - ), - pytest.param( - { - "deviceType": "IndoorWeatherStation", - "hiloId": "urn:hilo:netatmo:station:0", - "connectionStatus": None, - }, - id="unrecognized-device-type", - ), - pytest.param( - {"deviceType": "Tstat", "connectionStatus": "DISCONNECTED"}, - id="missing-hilo-id", - ), - ], -) -def test_query_values_skips_unmigrated_or_incomplete_devices( - device_entry: dict[str, object], -) -> None: - """getLocation skips BasicDevice stubs, unknown deviceType values, and missing hiloId.""" - assert GraphqlValueMapper().map_query_values([device_entry]) == [] - - -@pytest.mark.parametrize( - ("connection_status", "expected"), - [ - pytest.param("CONNECTED", False, id="connected"), - pytest.param("DISCONNECTED", True, id="disconnected"), - pytest.param(None, True, id="null-status"), - ], -) -def test_location_subscription_maps_connection_status( - connection_status: str | None, expected: bool -) -> None: - """Location updates only carry hiloId and connectionStatus without full device fields.""" - payload: dict[str, object] = { - "devices": [ - { - "__typename": "BasicThermostat", - "hiloId": "urn:hilo:philo:1a2b3c4d5e6f0001:0", - "connectionStatus": connection_status, - } - ] - } - - attributes = GraphqlValueMapper().map_location_subscription_values(payload) - - by_name = {a["attribute"]: a["value"] for a in attributes} - assert by_name == {"Unpaired": False, "Disconnected": expected} - - -@pytest.mark.parametrize( - "device_entry", - [ - pytest.param( - { - "__typename": "BasicDevice", - "hiloId": "urn:hilo:netatmo:station:0", - "connectionStatus": None, - }, - id="basic-device-stub", - ), - pytest.param( - {"__typename": "BasicThermostat", "connectionStatus": "DISCONNECTED"}, - id="missing-hilo-id", - ), - ], -) -def test_location_subscription_skips_ignored_entries( - device_entry: dict[str, object], -) -> None: - """Unmigrated BasicDevice stubs and entries missing hiloId produce no readings.""" - payload: dict[str, object] = {"devices": [device_entry]} - - assert GraphqlValueMapper().map_location_subscription_values(payload) == [] - - @pytest.mark.parametrize( ("ambient_humidity", "expected"), [ From 31a6591a74703798c3cbc2cec0e089b1d6ef0fae Mon Sep 17 00:00:00 2001 From: Moustachauve <2206577+Moustachauve@users.noreply.github.com> Date: Mon, 16 Nov 2026 01:04:40 -0500 Subject: [PATCH 3/4] Extract _is_gateway helper in GraphQlHelper Deduplicate the case-insensitive Gateway `deviceType` check shared by `call_get_location_query` and `_handle_query_result` so the two call sites cannot drift apart. --- pyhilo/graphql.py | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/pyhilo/graphql.py b/pyhilo/graphql.py index 0ff41e5..16553ce 100644 --- a/pyhilo/graphql.py +++ b/pyhilo/graphql.py @@ -1,4 +1,5 @@ import asyncio +from collections.abc import Mapping import hashlib import json import ssl @@ -596,11 +597,7 @@ async def call_get_location_query(self, location_hilo_id: str) -> list[str]: devices = ( response_json["data"].get("getLocation", {}).get("devices", []) ) - gateways = [ - d - for d in devices - if (d.get("deviceType") or "").lower() in ("gateway", "hub") - ] + gateways = [d for d in devices if self._is_gateway(d)] LOG.debug( "Gateway devices in getLocation response: %s", json.dumps(gateways, indent=2), @@ -808,12 +805,17 @@ async def _get_access_token(self) -> str: """Get the access token.""" return await self._api.async_get_access_token() + @staticmethod + def _is_gateway(raw_device: Mapping[str, object]) -> bool: + """Return whether a raw GraphQL device payload represents a gateway.""" + return str(raw_device.get("deviceType") or "").lower() in ("gateway", "hub") + def _handle_query_result(self, result: Dict[str, Any]) -> list[str]: """Handle the result of the GraphQL query for location and devices.""" devices_values: List[Dict[str, Any]] = result["getLocation"]["devices"] for raw_device in devices_values: - if (raw_device.get("deviceType") or "").lower() in ("gateway", "hub"): + if self._is_gateway(raw_device): if not any(d.type == "Gateway" for d in self._devices.devices): gw = self._build_gateway_dict(raw_device) LOG.debug("Creating gateway device from GraphQL: %s", gw) From d35af0dcae297712a68aa0375bd1985cfc6aeedf Mon Sep 17 00:00:00 2001 From: Moustachauve <2206577+Moustachauve@users.noreply.github.com> Date: Mon, 16 Nov 2026 22:47:58 -0500 Subject: [PATCH 4/4] Simplify PR to Gateway hilo_id and subscription callback fixes Remove the obsolete device_id == 0 Gateway fallback in Devices now that the Gateway populates hilo_id directly, revert unrelated Smart Meter and Gateway id-mutation changes to main, and drop the corresponding redundant tests. --- pyhilo/device/graphql_value_mapper.py | 9 ++++- pyhilo/devices.py | 9 +---- pyhilo/graphql.py | 18 ++++----- tests/test_graphql.py | 54 +-------------------------- tests/test_graphql_value_mapper.py | 24 ++++++------ 5 files changed, 30 insertions(+), 84 deletions(-) diff --git a/pyhilo/device/graphql_value_mapper.py b/pyhilo/device/graphql_value_mapper.py index dda7f43..c41ae4c 100644 --- a/pyhilo/device/graphql_value_mapper.py +++ b/pyhilo/device/graphql_value_mapper.py @@ -55,7 +55,7 @@ def _map_devices_values(self, device: Dict[str, Any]) -> list[Dict[str, Any]]: attributes.extend(self._build_charging_point(device)) case "meter": # Smart Meter attributes.extend(self._build_smart_meter(device)) - case "hub" | "gateway": # Gateway + case "hub": # Gateway attributes.extend(self._build_gateway(device)) case "colorbulb": attributes.extend(self._build_light(device)) @@ -82,6 +82,13 @@ def _build_smart_meter(self, device: Dict[str, Any]) -> list[Dict[str, Any]]: device["hiloId"], "ZigbeeChannel", device["zigBeeChannel"] ) ) + attributes.append( + self.build_attribute( + device["hiloId"], + "Disconnected", + device["connectionStatus"] == "DISCONNECTED", + ), + ) if device.get("power") is not None: attributes.append(self._map_power(device)) return attributes diff --git a/pyhilo/devices.py b/pyhilo/devices.py index 5355623..d8ef990 100644 --- a/pyhilo/devices.py +++ b/pyhilo/devices.py @@ -58,14 +58,7 @@ def _map_readings_to_devices( device_identifier: Union[int, str] = reading.device_id if device_identifier == 0: device_identifier = reading.hilo_id - device = self.find_device(device_identifier) - # If device_id was 0 and hilo_id is empty, this is a SignalR - # gateway reading arriving before GatewayValuesReceived assigns - # the real ID. Never route an unmatched non-empty hilo_id to the - # gateway, as it belongs to a different device. - if device is None and reading.device_id == 0 and not reading.hilo_id: - device = next((d for d in self.devices if d.type == "Gateway"), None) - if device: + if device := self.find_device(device_identifier): device.update_readings(reading) LOG.debug("%s Received %s", device, reading) if device not in updated_devices: diff --git a/pyhilo/graphql.py b/pyhilo/graphql.py index 16553ce..e5644c6 100644 --- a/pyhilo/graphql.py +++ b/pyhilo/graphql.py @@ -1,5 +1,4 @@ import asyncio -from collections.abc import Mapping import hashlib import json import ssl @@ -597,7 +596,9 @@ async def call_get_location_query(self, location_hilo_id: str) -> list[str]: devices = ( response_json["data"].get("getLocation", {}).get("devices", []) ) - gateways = [d for d in devices if self._is_gateway(d)] + gateways = [ + d for d in devices if d.get("deviceType") in ("Gateway", "Hub") + ] LOG.debug( "Gateway devices in getLocation response: %s", json.dumps(gateways, indent=2), @@ -805,21 +806,18 @@ async def _get_access_token(self) -> str: """Get the access token.""" return await self._api.async_get_access_token() - @staticmethod - def _is_gateway(raw_device: Mapping[str, object]) -> bool: - """Return whether a raw GraphQL device payload represents a gateway.""" - return str(raw_device.get("deviceType") or "").lower() in ("gateway", "hub") - def _handle_query_result(self, result: Dict[str, Any]) -> list[str]: """Handle the result of the GraphQL query for location and devices.""" devices_values: List[Dict[str, Any]] = result["getLocation"]["devices"] for raw_device in devices_values: - if self._is_gateway(raw_device): - if not any(d.type == "Gateway" for d in self._devices.devices): + if raw_device.get("deviceType") in ("Gateway", "Hub"): + if self._devices.find_device(1) is None: gw = self._build_gateway_dict(raw_device) LOG.debug("Creating gateway device from GraphQL: %s", gw) - self._devices.devices.append(self._devices.generate_device(gw)) + gw_dev = self._devices.generate_device(gw) + if gw_dev not in self._devices.devices: + self._devices.devices.append(gw_dev) attributes = self.mapper.map_query_values(devices_values) updated_devices = self._devices.parse_values_received(attributes) diff --git a/tests/test_graphql.py b/tests/test_graphql.py index 385a3ce..8918f75 100644 --- a/tests/test_graphql.py +++ b/tests/test_graphql.py @@ -27,7 +27,7 @@ def _make_helper() -> tuple[GraphQlHelper, Devices]: def _gateway_payload( - connection_status: str, device_type: str = "Gateway" + connection_status: str, device_type: str = "Hub" ) -> dict[str, object]: return { "deviceType": device_type, @@ -80,19 +80,6 @@ def test_gateway_query_populates_hilo_id_and_availability( assert gateway.get_value("online_status") == connection_status -def test_gateway_query_does_not_duplicate_when_gateway_id_changed() -> None: - """Re-running getLocation after SignalR updates gateway.id refreshes it in place.""" - helper, devices, gateway = _make_helper_with_gateway() - gateway.id = 98765 - - helper._handle_query_result( - {"getLocation": {"devices": [_gateway_payload("DISCONNECTED")]}} - ) - - assert [d for d in devices.all if d.type == "Gateway"] == [gateway] - assert gateway.available is False - - def test_gateway_device_subscription_updates_availability_and_notifies_callback() -> ( None ): @@ -102,7 +89,7 @@ def test_gateway_device_subscription_updates_availability_and_notifies_callback( sse_payload: dict[str, object] = { "data": { "onAnyDeviceUpdated": { - "device": _gateway_payload("DISCONNECTED", device_type="Hub"), + "device": _gateway_payload("DISCONNECTED", device_type="hub"), } } } @@ -142,43 +129,6 @@ def test_unknown_hilo_id_reading_does_not_overwrite_gateway_availability() -> No assert notified == [] -def test_signalr_zero_device_id_without_hilo_id_falls_back_to_gateway() -> None: - """SignalR readings with deviceId=0 and no hiloId route to the Gateway, not other unset-hilo_id devices.""" - helper, devices = _make_helper() - legacy_sensor = devices.generate_device( - { - "id": 500, - "name": "Weather Station", - "type": "IndoorWeatherStation", - "provider": 2, - "supportedAttributes": "Disconnected", - "settableAttributes": "", - "Disconnected": {"value": False}, - } - ) - devices.devices.append(legacy_sensor) - helper._handle_query_result( - {"getLocation": {"devices": [_gateway_payload("CONNECTED")]}} - ) - gateway = devices.find_device(GATEWAY_HILO_ID) - assert gateway is not None - - updated = devices.parse_values_received( - [ - { - "deviceId": 0, - "timeStampUTC": "2026-11-11T12:00:00Z", - "attribute": "Disconnected", - "value": True, - } - ] - ) - - assert updated == [gateway] - assert gateway.available is False - assert legacy_sensor.available is True - - async def test_resync_after_reconnect_updates_gateway_and_notifies_callback() -> None: """SSE reconnect resync parses getLocation and forwards updated hilo_ids to callback.""" helper, devices, gateway = _make_helper_with_gateway() diff --git a/tests/test_graphql_value_mapper.py b/tests/test_graphql_value_mapper.py index a406ac0..fb667b0 100644 --- a/tests/test_graphql_value_mapper.py +++ b/tests/test_graphql_value_mapper.py @@ -25,10 +25,10 @@ def test_smart_meter_maps_zigbee_channel() -> None: assert channel == [24] -def _hub(connection_status: str, device_type: str = "Hub") -> dict[str, object]: +def _hub(connection_status: str) -> dict: return { "hiloId": "hub-1", - "deviceType": device_type, + "deviceType": "Hub", "connectionStatus": connection_status, "lastConnectionTime": "2026-11-01T12:00:00Z", "controllerSoftwareVersion": "1.0.0", @@ -38,9 +38,9 @@ def _hub(connection_status: str, device_type: str = "Hub") -> dict[str, object]: } -def _disconnected_values(device: dict[str, object]) -> list[bool]: +def _disconnected_values(device: dict) -> set[bool]: attributes = GraphqlValueMapper().map_device_subscription_values(device) - return [a["value"] for a in attributes if a["attribute"] == "Disconnected"] + return {a["value"] for a in attributes if a["attribute"] == "Disconnected"} @pytest.mark.parametrize( @@ -79,23 +79,21 @@ def test_device_disconnected_follows_connection_status( device = _device(filename) device["connectionStatus"] = connection_status - assert _disconnected_values(device) == [expected] + assert _disconnected_values(device) == {expected} @pytest.mark.parametrize( - ("device_type", "connection_status", "expected"), + ("connection_status", "expected"), [ - pytest.param("Hub", "CONNECTED", False, id="hub-connected"), - pytest.param("Hub", "DISCONNECTED", True, id="hub-disconnected"), - pytest.param("Gateway", "CONNECTED", False, id="gateway-connected"), - pytest.param("Gateway", "DISCONNECTED", True, id="gateway-disconnected"), + pytest.param("CONNECTED", False, id="connected"), + pytest.param("DISCONNECTED", True, id="disconnected"), ], ) def test_hub_disconnected_follows_connection_status( - device_type: str, connection_status: str, expected: bool + connection_status: str, expected: bool ) -> None: - """The gateway's Disconnected attribute is derived for both Hub and Gateway types.""" - assert _disconnected_values(_hub(connection_status, device_type)) == [expected] + """The gateway's Disconnected attribute is derived from the string status.""" + assert _disconnected_values(_hub(connection_status)) == {expected} @pytest.mark.parametrize(