Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 11 additions & 4 deletions pyhilo/device/graphql_value_mapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,17 @@ 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["devices"]:
# Unmigrated SignalR devices appear as BasicDevice stubs with null status.
if device.get("__typename") == "BasicDevice":
continue
readings.extend(self._map_basic_device(device))
if device.get("__typename") == "Gateway":
readings.append(
self.build_attribute(
device["hiloId"], "onlineStatus", device["connectionStatus"]
)
)
return readings

def _map_devices_values(self, device: Dict[str, Any]) -> list[Dict[str, Any]]:
Expand Down
51 changes: 20 additions & 31 deletions pyhilo/graphql.py
Original file line number Diff line number Diff line change
Expand Up @@ -519,27 +519,15 @@ 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
}
}
}
Expand Down Expand Up @@ -655,7 +643,7 @@ 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, Any]], list[str]],
callback: Optional[Callable[[str], None]],
) -> tuple:
"""Dispatch a parsed SSE message. Returns (retry_apq, had_success)."""
Expand All @@ -668,16 +656,17 @@ def _handle_sse_message(
return False, False
if "data" in data:
LOG.debug("Received subscription result %s", data["data"])
handler_result = handler(data["data"])
if callback and handler_result:
callback(handler_result)
hilo_ids = handler(data["data"])
if callback:
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, Any]], list[str]],
callback: Optional[Callable[[str], None]],
) -> tuple:
"""Read events until the stream closes. Returns (retry_apq, had_success)."""
Expand Down Expand Up @@ -712,7 +701,7 @@ 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, Any]], list[str]],
callback: Optional[Callable[[str], None]],
) -> tuple:
"""Open one SSE connection and drain it. Returns (retry_apq, had_success)."""
Expand All @@ -728,7 +717,7 @@ async def _listen_to_sse(
self,
query: str,
variables: Dict[str, Any],
handler: Callable[[Dict[str, Any]], str],
handler: Callable[[Dict[str, Any]], list[str]],
callback: Optional[Callable[[str], None]] = None,
location_hilo_id: Optional[str] = None,
) -> None:
Expand Down Expand Up @@ -856,20 +845,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, Any]) -> str:
def _handle_device_subscription_result(self, result: Dict[str, Any]) -> list[str]:
"""Handle the result of the GraphQL subscription for device updates."""
device_value: Dict[str, Any] = result["onAnyDeviceUpdated"]["device"]
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 updated_device[0].hilo_id if updated_device else ""
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, Any]) -> list[str]:
"""Handle the result of the GraphQL subscription for location updates."""
location_value: Dict[str, Any] = result["onAnyLocationUpdated"]["location"]
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]
90 changes: 90 additions & 0 deletions tests/test_graphql.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
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]:
Expand Down Expand Up @@ -148,3 +150,91 @@ async def test_resync_after_reconnect_updates_gateway_and_notifies_callback() ->

assert gateway.available is False
assert notified == [GATEWAY_HILO_ID]


def test_location_subscription_updates_devices_and_notifies_each_hilo_id() -> None:
"""onAnyLocationUpdated updates device availability and invokes callback per hilo_id."""
helper, devices, gateway = _make_helper_with_gateway()
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},
}
)
weather_station = devices.generate_device(
{
"id": 102,
"hilo_id": "urn:hilo:netatmo:station:0",
"name": "Weather Station",
"type": "IndoorWeatherStation",
"provider": 2,
"supportedAttributes": "Disconnected",
"settableAttributes": "",
"Disconnected": {"value": True},
}
)
devices.devices.extend([tstat, switch, weather_station])

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 weather_station.available is False
assert notified == [GATEWAY_HILO_ID, TSTAT_HILO_ID, SWITCH_HILO_ID]
65 changes: 65 additions & 0 deletions tests/test_graphql_value_mapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,3 +124,68 @@ def test_thermostat_humidity_absent_field() -> None:
attributes = GraphqlValueMapper().map_device_subscription_values(device)

assert not [a for a in attributes if a["attribute"] == "Humidity"]


@pytest.mark.parametrize(
("connection_status", "expected"),
[
pytest.param("CONNECTED", False, id="connected"),
pytest.param("DISCONNECTED", True, id="disconnected"),
],
)
def test_location_subscription_maps_connection_status(
connection_status: str, expected: bool
) -> None:
"""Location updates only carry __typename, hiloId, and connectionStatus."""
payload: dict[str, object] = {
"devices": [
{
"__typename": "BasicThermostat",
"hiloId": "urn:hilo:philo:1a2b3c4d5e6f0001:0",
"connectionStatus": connection_status,
}
]
}

attributes = GraphqlValueMapper().map_location_subscription_values(payload)

assert {a["attribute"]: a["value"] for a in attributes} == {
"Unpaired": False,
"Disconnected": expected,
}


def test_location_subscription_skips_basic_device() -> None:
"""Unmigrated SignalR BasicDevice stubs produce no location update readings."""
payload: dict[str, object] = {
"devices": [
{
"__typename": "BasicDevice",
"hiloId": "urn:hilo:netatmo:station:0",
"connectionStatus": None,
}
]
}

assert GraphqlValueMapper().map_location_subscription_values(payload) == []


def test_location_subscription_maps_gateway_online_status() -> None:
"""Gateway entries in location updates also emit onlineStatus."""
payload: dict[str, object] = {
"devices": [
{
"__typename": "Gateway",
"hiloId": "hub-1",
"connectionStatus": "DISCONNECTED",
}
]
}

attributes = GraphqlValueMapper().map_location_subscription_values(payload)

assert {a["attribute"]: a["value"] for a in attributes} == {
"Unpaired": False,
"Disconnected": True,
"onlineStatus": "DISCONNECTED",
}