Skip to content

Commit 66709ac

Browse files
authored
Merge pull request #499 from Moustachauve/fix/gateway-location-graphql-status
Fix Gateway hilo_id and GraphQL device subscription updates
2 parents 5d4ab86 + d35af0d commit 66709ac

4 files changed

Lines changed: 196 additions & 41 deletions

File tree

‎pyhilo/device/graphql_value_mapper.py‎

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -97,21 +97,19 @@ def _build_gateway(self, device: Dict[str, Any]) -> list[Dict[str, Any]]:
9797
attributes = []
9898
attributes.append(
9999
self.build_attribute(
100-
device["hiloId"], "LastStatusTime", device["lastConnectionTime"]
100+
device["hiloId"], "onlineStatus", device["connectionStatus"]
101101
)
102102
)
103103
attributes.append(
104104
self.build_attribute(
105-
device["hiloId"], "Version", device["controllerSoftwareVersion"]
105+
device["hiloId"], "LastStatusTime", device["lastConnectionTime"]
106106
)
107107
)
108108
attributes.append(
109109
self.build_attribute(
110-
device["hiloId"],
111-
"Disconnected",
112-
device["connectionStatus"] == "DISCONNECTED",
110+
device["hiloId"], "Version", device["controllerSoftwareVersion"]
113111
)
114-
) # Offline
112+
)
115113
attributes.append(
116114
self.build_attribute(
117115
device["hiloId"],

‎pyhilo/devices.py‎

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -58,27 +58,25 @@ def _map_readings_to_devices(
5858
device_identifier: Union[int, str] = reading.device_id
5959
if device_identifier == 0:
6060
device_identifier = reading.hilo_id
61-
device = self.find_device(device_identifier)
62-
# If device_id was 0 and hilo_id lookup failed, this is likely
63-
# a gateway reading that arrives before GatewayValuesReceived
64-
# assigns the real ID. Fall back to the gateway device.
65-
if device is None and reading.device_id == 0:
66-
device = next((d for d in self.devices if d.type == "Gateway"), None)
67-
if device:
61+
if device := self.find_device(device_identifier):
6862
device.update_readings(reading)
6963
LOG.debug("%s Received %s", device, reading)
7064
if device not in updated_devices:
7165
updated_devices.append(device)
7266
else:
7367
LOG.warning(
74-
f"Unable to find device {reading.device_id} for reading {reading}"
68+
"Unable to find device %s for reading %s",
69+
device_identifier,
70+
reading,
7571
)
7672
return updated_devices
7773

7874
def find_device(self, device_identifier: int | str) -> HiloDevice | None:
7975
"""Makes sure the devices received have an identifier, this means some need to be hardcoded
8076
like the unknown power meter.
8177
"""
78+
if not device_identifier:
79+
return None
8280
if isinstance(device_identifier, int):
8381
return next((d for d in self.devices if d.id == device_identifier), None)
8482
return next((d for d in self.devices if d.hilo_id == device_identifier), None)

‎pyhilo/graphql.py‎

Lines changed: 36 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -286,6 +286,9 @@ def _create_ssl_context() -> ssl.SSLContext:
286286
status
287287
device {
288288
... on Gateway {
289+
deviceType
290+
hiloId
291+
physicalAddress
289292
connectionStatus
290293
controllerSoftwareVersion
291294
lastConnectionTime
@@ -542,7 +545,7 @@ def _create_ssl_context() -> ssl.SSLContext:
542545
}
543546
}"""
544547

545-
async def call_get_location_query(self, location_hilo_id: str) -> None:
548+
async def call_get_location_query(self, location_hilo_id: str) -> list[str]:
546549
"""This functions calls the digital-twin and requests location id"""
547550
access_token = await self._get_access_token()
548551
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:
568571
response_json = response.json()
569572
except Exception as e:
570573
LOG.error("Error parsing response: %s", e)
571-
return
574+
return []
572575

573576
if "errors" in response_json:
574577
for error in response_json["errors"]:
@@ -582,12 +585,12 @@ async def call_get_location_query(self, location_hilo_id: str) -> None:
582585
response_json = response.json()
583586
except Exception as e:
584587
LOG.error("Error parsing response on retry: %s", e)
585-
return
588+
return []
586589
break
587590

588591
if "errors" in response_json:
589592
LOG.error("GraphQL errors: %s", response_json["errors"])
590-
return
593+
return []
591594

592595
if "data" in response_json:
593596
devices = (
@@ -600,7 +603,9 @@ async def call_get_location_query(self, location_hilo_id: str) -> None:
600603
"Gateway devices in getLocation response: %s",
601604
json.dumps(gateways, indent=2),
602605
)
603-
self._handle_query_result(response_json["data"])
606+
return self._handle_query_result(response_json["data"])
607+
608+
return []
604609

605610
async def subscribe_to_device_updated(
606611
self,
@@ -664,7 +669,7 @@ def _handle_sse_message(
664669
if "data" in data:
665670
LOG.debug("Received subscription result %s", data["data"])
666671
handler_result = handler(data["data"])
667-
if callback:
672+
if callback and handler_result:
668673
callback(handler_result)
669674
return False, True
670675
return False, False
@@ -752,6 +757,7 @@ async def _listen_to_sse(
752757
"SSE connection closed by server. Reconnecting in 5 seconds..."
753758
)
754759
await asyncio.sleep(5)
760+
await self._resync_after_reconnect(location_hilo_id, callback)
755761

756762
except asyncio.TimeoutError:
757763
# Keepalive timeout: the connection was recently live, so start
@@ -765,15 +771,7 @@ async def _listen_to_sse(
765771
backoff_delay = min(backoff_delay * 2, self._BACKOFF_MAX)
766772
if "query" in payload:
767773
del payload["query"]
768-
if location_hilo_id:
769-
try:
770-
await self.call_get_location_query(location_hilo_id)
771-
LOG.debug("call_get_location_query success after reconnect")
772-
except Exception as e2:
773-
LOG.error(
774-
"exception while RE-connecting, retrying: %s",
775-
e2,
776-
)
774+
await self._resync_after_reconnect(location_hilo_id, callback)
777775

778776
except Exception as e:
779777
LOG.debug(
@@ -785,21 +783,30 @@ async def _listen_to_sse(
785783
backoff_delay = min(backoff_delay * 2, self._BACKOFF_MAX)
786784
if "query" in payload:
787785
del payload["query"]
788-
if location_hilo_id:
789-
try:
790-
await self.call_get_location_query(location_hilo_id)
791-
LOG.debug("call_get_location_query success after reconnect")
792-
except Exception as e2:
793-
LOG.error(
794-
"exception while RE-connecting, retrying: %s",
795-
e2,
796-
)
786+
await self._resync_after_reconnect(location_hilo_id, callback)
787+
788+
async def _resync_after_reconnect(
789+
self,
790+
location_hilo_id: Optional[str],
791+
callback: Optional[Callable[[str], None]],
792+
) -> None:
793+
if not location_hilo_id:
794+
return
795+
try:
796+
hilo_ids = await self.call_get_location_query(location_hilo_id)
797+
LOG.debug("call_get_location_query success after reconnect")
798+
except Exception as err:
799+
LOG.error("exception while RE-connecting, retrying: %s", err)
800+
return
801+
if callback:
802+
for hilo_id in hilo_ids:
803+
callback(hilo_id)
797804

798805
async def _get_access_token(self) -> str:
799806
"""Get the access token."""
800807
return await self._api.async_get_access_token()
801808

802-
def _handle_query_result(self, result: Dict[str, Any]) -> None:
809+
def _handle_query_result(self, result: Dict[str, Any]) -> list[str]:
803810
"""Handle the result of the GraphQL query for location and devices."""
804811
devices_values: List[Dict[str, Any]] = result["getLocation"]["devices"]
805812

@@ -813,7 +820,8 @@ def _handle_query_result(self, result: Dict[str, Any]) -> None:
813820
self._devices.devices.append(gw_dev)
814821

815822
attributes = self.mapper.map_query_values(devices_values)
816-
self._devices.parse_values_received(attributes)
823+
updated_devices = self._devices.parse_values_received(attributes)
824+
return [device.hilo_id for device in updated_devices if device.hilo_id]
817825

818826
def _build_gateway_dict(self, raw_device: Dict[str, Any]) -> Dict[str, Any]:
819827
"""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]:
829837
"type": "Gateway",
830838
"category": "Gateway",
831839
"id": 1,
840+
"hilo_id": hilo_id,
832841
"identifier": mac,
833842
"sdi": mac,
834843
"provider": 1,
@@ -854,7 +863,7 @@ def _handle_device_subscription_result(self, result: Dict[str, Any]) -> str:
854863
updated_device = self._devices.parse_values_received(attributes)
855864
# callback to update the device in the UI
856865
LOG.debug("Device updated: %s", updated_device)
857-
return str(device_value.get("hiloId"))
866+
return updated_device[0].hilo_id if updated_device else ""
858867

859868
def _handle_location_subscription_result(self, result: Dict[str, Any]) -> str:
860869
"""Handle the result of the GraphQL subscription for location updates."""

‎tests/test_graphql.py‎

Lines changed: 150 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,150 @@
1+
"""Tests for GraphQlHelper Gateway creation and device subscription updates."""
2+
3+
from __future__ import annotations
4+
5+
import ssl
6+
from unittest.mock import AsyncMock, MagicMock, patch
7+
8+
import pytest
9+
10+
from pyhilo import API, HiloDevice
11+
from pyhilo.devices import Devices
12+
from pyhilo.graphql import GraphQlHelper
13+
14+
GATEWAY_HILO_ID = "urn:hilo:ihub:AA11BB22CC33:0"
15+
16+
17+
def _make_helper() -> tuple[GraphQlHelper, Devices]:
18+
auth = MagicMock()
19+
auth.async_get_access_token = AsyncMock(return_value="token")
20+
api = API(session=MagicMock(), auth=auth)
21+
devices = Devices(api)
22+
devices.location_id = 42
23+
devices.location_hilo_id = "urn:hilo:crm:00000-abcdef:0"
24+
helper = GraphQlHelper(api, devices)
25+
helper._ssl_context = MagicMock(spec=ssl.SSLContext)
26+
return helper, devices
27+
28+
29+
def _gateway_payload(
30+
connection_status: str, device_type: str = "Hub"
31+
) -> dict[str, object]:
32+
return {
33+
"deviceType": device_type,
34+
"hiloId": GATEWAY_HILO_ID,
35+
"physicalAddress": "AA11BB22CC33",
36+
"connectionStatus": connection_status,
37+
"controllerSoftwareVersion": "1.2.3",
38+
"lastConnectionTime": "2026-11-11T12:00:00Z",
39+
"willBeConnectedToSmartMeter": True,
40+
"zigBeeChannel": 15,
41+
"zigBeePairingModeEnhanced": False,
42+
"smartMeterZigBeeChannel": 24,
43+
"smartMeterPairingStatus": True,
44+
}
45+
46+
47+
def _make_helper_with_gateway() -> tuple[GraphQlHelper, Devices, HiloDevice]:
48+
helper, devices = _make_helper()
49+
helper._handle_query_result(
50+
{"getLocation": {"devices": [_gateway_payload("CONNECTED")]}}
51+
)
52+
gateway = devices.find_device(GATEWAY_HILO_ID)
53+
assert gateway is not None
54+
return helper, devices, gateway
55+
56+
57+
@pytest.mark.parametrize(
58+
("connection_status", "expected_available"),
59+
[
60+
pytest.param("CONNECTED", True, id="connected"),
61+
pytest.param("DISCONNECTED", False, id="disconnected"),
62+
],
63+
)
64+
def test_gateway_query_populates_hilo_id_and_availability(
65+
connection_status: str, expected_available: bool
66+
) -> None:
67+
"""getLocation creates the Gateway with its real hilo_id and availability."""
68+
helper, devices = _make_helper()
69+
70+
updated_ids = helper._handle_query_result(
71+
{"getLocation": {"devices": [_gateway_payload(connection_status)]}}
72+
)
73+
74+
gateway = devices.find_device(GATEWAY_HILO_ID)
75+
assert gateway is not None
76+
assert updated_ids == [GATEWAY_HILO_ID]
77+
assert gateway.hilo_id == GATEWAY_HILO_ID
78+
assert gateway.identifier == "AA11BB22CC33"
79+
assert gateway.available is expected_available
80+
assert gateway.get_value("online_status") == connection_status
81+
82+
83+
def test_gateway_device_subscription_updates_availability_and_notifies_callback() -> (
84+
None
85+
):
86+
"""onAnyDeviceUpdated updates Gateway availability and passes its hilo_id to callback."""
87+
helper, _, gateway = _make_helper_with_gateway()
88+
notified: list[str] = []
89+
sse_payload: dict[str, object] = {
90+
"data": {
91+
"onAnyDeviceUpdated": {
92+
"device": _gateway_payload("DISCONNECTED", device_type="hub"),
93+
}
94+
}
95+
}
96+
97+
retry, had_success = helper._handle_sse_message(
98+
sse_payload, helper._handle_device_subscription_result, notified.append
99+
)
100+
101+
assert (retry, had_success) == (False, True)
102+
assert gateway.available is False
103+
assert gateway.get_value("online_status") == "DISCONNECTED"
104+
assert notified == [GATEWAY_HILO_ID]
105+
106+
107+
def test_unknown_hilo_id_reading_does_not_overwrite_gateway_availability() -> None:
108+
"""GraphQL readings for an unknown hiloId must not fall back to the Gateway device."""
109+
helper, _, gateway = _make_helper_with_gateway()
110+
notified: list[str] = []
111+
sse_payload: dict[str, object] = {
112+
"data": {
113+
"onAnyDeviceUpdated": {
114+
"device": {
115+
"deviceType": "Switch",
116+
"hiloId": "urn:hilo:philo:unpaired-switch:0",
117+
"connectionStatus": "DISCONNECTED",
118+
"state": "OFF",
119+
}
120+
}
121+
}
122+
}
123+
124+
helper._handle_sse_message(
125+
sse_payload, helper._handle_device_subscription_result, notified.append
126+
)
127+
128+
assert gateway.available is True
129+
assert notified == []
130+
131+
132+
async def test_resync_after_reconnect_updates_gateway_and_notifies_callback() -> None:
133+
"""SSE reconnect resync parses getLocation and forwards updated hilo_ids to callback."""
134+
helper, devices, gateway = _make_helper_with_gateway()
135+
response = MagicMock()
136+
response.raise_for_status = MagicMock()
137+
response.json.return_value = {
138+
"data": {"getLocation": {"devices": [_gateway_payload("DISCONNECTED")]}}
139+
}
140+
client = AsyncMock()
141+
client.post = AsyncMock(return_value=response)
142+
client_cm = AsyncMock()
143+
client_cm.__aenter__.return_value = client
144+
145+
notified: list[str] = []
146+
with patch("pyhilo.graphql.httpx.AsyncClient", return_value=client_cm):
147+
await helper._resync_after_reconnect(devices.location_hilo_id, notified.append)
148+
149+
assert gateway.available is False
150+
assert notified == [GATEWAY_HILO_ID]

0 commit comments

Comments
 (0)