diff --git a/pyhilo/device/graphql_value_mapper.py b/pyhilo/device/graphql_value_mapper.py index 08e2caf..c41ae4c 100644 --- a/pyhilo/device/graphql_value_mapper.py +++ b/pyhilo/device/graphql_value_mapper.py @@ -97,21 +97,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["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"], diff --git a/pyhilo/devices.py b/pyhilo/devices.py index b43c83f..d8ef990 100644 --- a/pyhilo/devices.py +++ b/pyhilo/devices.py @@ -58,20 +58,16 @@ 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 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: - 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: 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, + reading, ) return updated_devices @@ -79,6 +75,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..e5644c6 100644 --- a/pyhilo/graphql.py +++ b/pyhilo/graphql.py @@ -286,6 +286,9 @@ def _create_ssl_context() -> ssl.SSLContext: status device { ... on Gateway { + deviceType + hiloId + physicalAddress connectionStatus controllerSoftwareVersion lastConnectionTime @@ -542,7 +545,7 @@ def _create_ssl_context() -> ssl.SSLContext: } }""" - 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 +571,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,12 +585,12 @@ 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 = ( @@ -600,7 +603,9 @@ async def call_get_location_query(self, location_hilo_id: str) -> None: "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, @@ -664,7 +669,7 @@ def _handle_sse_message( if "data" in data: LOG.debug("Received subscription result %s", data["data"]) handler_result = handler(data["data"]) - if callback: + if callback and handler_result: callback(handler_result) return False, True return False, False @@ -752,6 +757,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 +771,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,21 +783,30 @@ 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"] @@ -813,7 +820,8 @@ def _handle_query_result(self, result: Dict[str, Any]) -> None: self._devices.devices.append(gw_dev) 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 +837,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, @@ -854,7 +863,7 @@ def _handle_device_subscription_result(self, result: Dict[str, Any]) -> str: updated_device = 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")) + return updated_device[0].hilo_id if updated_device else "" def _handle_location_subscription_result(self, result: Dict[str, Any]) -> str: """Handle the result of the GraphQL subscription for location updates.""" diff --git a/tests/test_graphql.py b/tests/test_graphql.py new file mode 100644 index 0000000..8918f75 --- /dev/null +++ b/tests/test_graphql.py @@ -0,0 +1,150 @@ +"""Tests for GraphQlHelper Gateway creation and device subscription updates.""" + +from __future__ import annotations + +import ssl +from unittest.mock import AsyncMock, MagicMock, patch + +import pytest + +from pyhilo import API, HiloDevice +from pyhilo.devices import Devices +from pyhilo.graphql import GraphQlHelper + +GATEWAY_HILO_ID = "urn:hilo:ihub:AA11BB22CC33:0" + + +def _make_helper() -> tuple[GraphQlHelper, Devices]: + 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" + helper = GraphQlHelper(api, devices) + helper._ssl_context = MagicMock(spec=ssl.SSLContext) + return helper, devices + + +def _gateway_payload( + connection_status: str, device_type: str = "Hub" +) -> dict[str, object]: + return { + "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, + } + + +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( + ("connection_status", "expected_available"), + [ + pytest.param("CONNECTED", True, id="connected"), + pytest.param("DISCONNECTED", False, id="disconnected"), + ], +) +def test_gateway_query_populates_hilo_id_and_availability( + connection_status: str, expected_available: bool +) -> None: + """getLocation creates the Gateway with its real hilo_id and availability.""" + helper, devices = _make_helper() + + updated_ids = helper._handle_query_result( + {"getLocation": {"devices": [_gateway_payload(connection_status)]}} + ) + + 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_device_subscription_updates_availability_and_notifies_callback() -> ( + None +): + """onAnyDeviceUpdated updates Gateway availability and passes its hilo_id to callback.""" + helper, _, gateway = _make_helper_with_gateway() + notified: list[str] = [] + sse_payload: dict[str, object] = { + "data": { + "onAnyDeviceUpdated": { + "device": _gateway_payload("DISCONNECTED", device_type="hub"), + } + } + } + + 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_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, _, gateway = _make_helper_with_gateway() + notified: list[str] = [] + sse_payload: dict[str, object] = { + "data": { + "onAnyDeviceUpdated": { + "device": { + "deviceType": "Switch", + "hiloId": "urn:hilo:philo:unpaired-switch:0", + "connectionStatus": "DISCONNECTED", + "state": "OFF", + } + } + } + } + + helper._handle_sse_message( + sse_payload, helper._handle_device_subscription_result, notified.append + ) + + assert gateway.available is True + assert notified == [] + + +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 + + 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 gateway.available is False + assert notified == [GATEWAY_HILO_ID]