python-hilo 2026.11.2__tar.gz → 2026.12.1__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {python_hilo-2026.11.2 → python_hilo-2026.12.1}/.github/workflows/release-drafter.yml +1 -1
- {python_hilo-2026.11.2 → python_hilo-2026.12.1}/.github/workflows/tests.yaml +2 -2
- {python_hilo-2026.11.2 → python_hilo-2026.12.1}/PKG-INFO +1 -1
- {python_hilo-2026.11.2 → python_hilo-2026.12.1}/pyhilo/api.py +19 -2
- {python_hilo-2026.11.2 → python_hilo-2026.12.1}/pyhilo/const.py +1 -1
- {python_hilo-2026.11.2 → python_hilo-2026.12.1}/pyhilo/device/graphql_value_mapper.py +15 -10
- {python_hilo-2026.11.2 → python_hilo-2026.12.1}/pyhilo/devices.py +6 -8
- {python_hilo-2026.11.2 → python_hilo-2026.12.1}/pyhilo/event.py +57 -2
- {python_hilo-2026.11.2 → python_hilo-2026.12.1}/pyhilo/graphql.py +53 -55
- {python_hilo-2026.11.2 → python_hilo-2026.12.1}/pyproject.toml +1 -1
- {python_hilo-2026.11.2 → python_hilo-2026.12.1}/tests/test_api_auth.py +36 -1
- python_hilo-2026.12.1/tests/test_event.py +179 -0
- python_hilo-2026.12.1/tests/test_graphql.py +240 -0
- {python_hilo-2026.11.2 → python_hilo-2026.12.1}/tests/test_graphql_value_mapper.py +65 -0
- {python_hilo-2026.11.2 → python_hilo-2026.12.1}/uv.lock +71 -53
- {python_hilo-2026.11.2 → python_hilo-2026.12.1}/.bandit.yaml +0 -0
- {python_hilo-2026.11.2 → python_hilo-2026.12.1}/.devcontainer/devcontainer-lock.json +0 -0
- {python_hilo-2026.11.2 → python_hilo-2026.12.1}/.devcontainer/devcontainer.json +0 -0
- {python_hilo-2026.11.2 → python_hilo-2026.12.1}/.editorconfig +0 -0
- {python_hilo-2026.11.2 → python_hilo-2026.12.1}/.gitattributes +0 -0
- {python_hilo-2026.11.2 → python_hilo-2026.12.1}/.github/ISSUE_TEMPLATE/feature_request.md +0 -0
- {python_hilo-2026.11.2 → python_hilo-2026.12.1}/.github/ISSUE_TEMPLATE/issue.md +0 -0
- {python_hilo-2026.11.2 → python_hilo-2026.12.1}/.github/dependabot.yml +0 -0
- {python_hilo-2026.11.2 → python_hilo-2026.12.1}/.github/labels.yml +0 -0
- {python_hilo-2026.11.2 → python_hilo-2026.12.1}/.github/release-drafter.yml +0 -0
- {python_hilo-2026.11.2 → python_hilo-2026.12.1}/.github/workflows/labeler.yml +0 -0
- {python_hilo-2026.11.2 → python_hilo-2026.12.1}/.gitignore +0 -0
- {python_hilo-2026.11.2 → python_hilo-2026.12.1}/.pre-commit-config.yaml +0 -0
- {python_hilo-2026.11.2 → python_hilo-2026.12.1}/AGENTS.md +0 -0
- {python_hilo-2026.11.2 → python_hilo-2026.12.1}/LICENSE +0 -0
- {python_hilo-2026.11.2 → python_hilo-2026.12.1}/README.md +0 -0
- {python_hilo-2026.11.2 → python_hilo-2026.12.1}/doc/README.md +0 -0
- {python_hilo-2026.11.2 → python_hilo-2026.12.1}/doc/graphql/onAnyDeviceUpdated-cee.json +0 -0
- {python_hilo-2026.11.2 → python_hilo-2026.12.1}/doc/graphql/onAnyDeviceUpdated-meter.json +0 -0
- {python_hilo-2026.11.2 → python_hilo-2026.12.1}/doc/graphql/onAnyDeviceUpdated-tstat.json +0 -0
- {python_hilo-2026.11.2 → python_hilo-2026.12.1}/doc/postman/hilo-prod.postman_environment.json +0 -0
- {python_hilo-2026.11.2 → python_hilo-2026.12.1}/doc/postman/hilo.postman_collection.json +0 -0
- {python_hilo-2026.11.2 → python_hilo-2026.12.1}/doc/rest/location_weather.json +0 -0
- {python_hilo-2026.11.2 → python_hilo-2026.12.1}/doc/rest/season_events_ch_2025.json +0 -0
- {python_hilo-2026.11.2 → python_hilo-2026.12.1}/doc/rest/season_events_ch_2026_empty.json +0 -0
- {python_hilo-2026.11.2 → python_hilo-2026.12.1}/doc/rest/season_events_hilo_2024.json +0 -0
- {python_hilo-2026.11.2 → python_hilo-2026.12.1}/doc/rest/seasons_summary.json +0 -0
- {python_hilo-2026.11.2 → python_hilo-2026.12.1}/doc/signalr/challengehub/ChallengeAdded.json +0 -0
- {python_hilo-2026.11.2 → python_hilo-2026.12.1}/doc/signalr/challengehub/EventAdded.json +0 -0
- {python_hilo-2026.11.2 → python_hilo-2026.12.1}/doc/signalr/challengehub/EventCHConsumptionUpdatedValuesReceived-during-event.json +0 -0
- {python_hilo-2026.11.2 → python_hilo-2026.12.1}/doc/signalr/challengehub/EventCHConsumptionUpdatedValuesReceived.json +0 -0
- {python_hilo-2026.11.2 → python_hilo-2026.12.1}/doc/signalr/challengehub/EventCHDetailsInitialValuesReceived.json +0 -0
- {python_hilo-2026.11.2 → python_hilo-2026.12.1}/doc/signalr/challengehub/EventCHDetailsUpdatedValuesReceived.json +0 -0
- {python_hilo-2026.11.2 → python_hilo-2026.12.1}/doc/signalr/challengehub/EventFlexConsumptionUpdatedValuesReceived.json +0 -0
- {python_hilo-2026.11.2 → python_hilo-2026.12.1}/doc/signalr/challengehub/EventFlexDetailsInitialValuesReceived.json +0 -0
- {python_hilo-2026.11.2 → python_hilo-2026.12.1}/doc/signalr/challengehub/EventFlexDetailsUpdatedValuesReceived.json +0 -0
- {python_hilo-2026.11.2 → python_hilo-2026.12.1}/doc/signalr/challengehub/legacy-pre-2025/ChallengeAdded.json +0 -0
- {python_hilo-2026.11.2 → python_hilo-2026.12.1}/doc/signalr/challengehub/legacy-pre-2025/ChallengeConsumptionUpdatedValuesReceived.json +0 -0
- {python_hilo-2026.11.2 → python_hilo-2026.12.1}/doc/signalr/challengehub/legacy-pre-2025/ChallengeDetailsInitialValuesReceived.json +0 -0
- {python_hilo-2026.11.2 → python_hilo-2026.12.1}/doc/signalr/challengehub/legacy-pre-2025/ChallengeListInitialValuesReceived.json +0 -0
- {python_hilo-2026.11.2 → python_hilo-2026.12.1}/doc/signalr/challengehub/legacy-pre-2025/ChallengeListUpdatedValuesReceived.json +0 -0
- {python_hilo-2026.11.2 → python_hilo-2026.12.1}/doc/signalr/devicehub/DeviceListInitialValuesReceived.json +0 -0
- {python_hilo-2026.11.2 → python_hilo-2026.12.1}/pyhilo/__init__.py +0 -0
- {python_hilo-2026.11.2 → python_hilo-2026.12.1}/pyhilo/auth.py +0 -0
- {python_hilo-2026.11.2 → python_hilo-2026.12.1}/pyhilo/device/__init__.py +0 -0
- {python_hilo-2026.11.2 → python_hilo-2026.12.1}/pyhilo/device/climate.py +0 -0
- {python_hilo-2026.11.2 → python_hilo-2026.12.1}/pyhilo/device/light.py +0 -0
- {python_hilo-2026.11.2 → python_hilo-2026.12.1}/pyhilo/device/sensor.py +0 -0
- {python_hilo-2026.11.2 → python_hilo-2026.12.1}/pyhilo/device/switch.py +0 -0
- {python_hilo-2026.11.2 → python_hilo-2026.12.1}/pyhilo/exceptions.py +0 -0
- {python_hilo-2026.11.2 → python_hilo-2026.12.1}/pyhilo/oauth2helper.py +0 -0
- {python_hilo-2026.11.2 → python_hilo-2026.12.1}/pyhilo/signalr.py +0 -0
- {python_hilo-2026.11.2 → python_hilo-2026.12.1}/pyhilo/util/__init__.py +0 -0
- {python_hilo-2026.11.2 → python_hilo-2026.12.1}/pyhilo/util/state.py +0 -0
- {python_hilo-2026.11.2 → python_hilo-2026.12.1}/tests/__init__.py +0 -0
- {python_hilo-2026.11.2 → python_hilo-2026.12.1}/tests/test_climate.py +0 -0
- {python_hilo-2026.11.2 → python_hilo-2026.12.1}/tests/test_device.py +0 -0
- {python_hilo-2026.11.2 → python_hilo-2026.12.1}/tests/test_signalr.py +0 -0
- {python_hilo-2026.11.2 → python_hilo-2026.12.1}/tests/test_util.py +0 -0
- {python_hilo-2026.11.2 → python_hilo-2026.12.1}/tests/test_util_state.py +0 -0
|
@@ -24,7 +24,7 @@ jobs:
|
|
|
24
24
|
python-version: ${{ env.DEFAULT_PYTHON }}
|
|
25
25
|
|
|
26
26
|
- name: Install uv
|
|
27
|
-
uses: astral-sh/setup-uv@v10.
|
|
27
|
+
uses: astral-sh/setup-uv@v10.4.1
|
|
28
28
|
|
|
29
29
|
- name: Install dependencies
|
|
30
30
|
run: uv sync --group dev
|
|
@@ -51,7 +51,7 @@ jobs:
|
|
|
51
51
|
python-version: ${{ matrix.python-version }}
|
|
52
52
|
|
|
53
53
|
- name: Install uv
|
|
54
|
-
uses: astral-sh/setup-uv@v10.
|
|
54
|
+
uses: astral-sh/setup-uv@v10.4.1
|
|
55
55
|
|
|
56
56
|
- name: Install dependencies
|
|
57
57
|
run: uv sync --python ${{ matrix.python-version }} --group test
|
|
@@ -2,6 +2,7 @@ from __future__ import annotations
|
|
|
2
2
|
|
|
3
3
|
import asyncio
|
|
4
4
|
import base64
|
|
5
|
+
from collections.abc import Mapping
|
|
5
6
|
from datetime import datetime, timedelta
|
|
6
7
|
import json
|
|
7
8
|
import random
|
|
@@ -48,6 +49,20 @@ from pyhilo.exceptions import InvalidCredentialsError, RequestError
|
|
|
48
49
|
from pyhilo.signalr import SignalRHub, SignalRManager
|
|
49
50
|
from pyhilo.util.state import AndroidDeviceDict, StateDict, get_state, set_state
|
|
50
51
|
|
|
52
|
+
_TRACE_REDACTED_KEYS = frozenset(
|
|
53
|
+
{"authorization", "ocp-apim-subscription-key", "accesstoken"}
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _redact_trace(values: object) -> object:
|
|
58
|
+
"""Mask credentials so users can share trace logs when reporting issues."""
|
|
59
|
+
if not isinstance(values, Mapping):
|
|
60
|
+
return values
|
|
61
|
+
return {
|
|
62
|
+
key: "***" if str(key).lower() in _TRACE_REDACTED_KEYS else value
|
|
63
|
+
for key, value in values.items()
|
|
64
|
+
}
|
|
65
|
+
|
|
51
66
|
|
|
52
67
|
class API:
|
|
53
68
|
"""An API object to interact with the Hilo cloud.
|
|
@@ -288,7 +303,7 @@ class API:
|
|
|
288
303
|
data: dict[str, Any] = {}
|
|
289
304
|
url = parse.urljoin(f"https://{host}", endpoint)
|
|
290
305
|
if self.log_traces:
|
|
291
|
-
LOG.debug("[TRACE] Headers: %s", kwargs["headers"])
|
|
306
|
+
LOG.debug("[TRACE] Headers: %s", _redact_trace(kwargs["headers"]))
|
|
292
307
|
LOG.debug("[TRACE] Async request: %s %s", method, url)
|
|
293
308
|
|
|
294
309
|
async with self.session.request(method, url, **kwargs) as resp:
|
|
@@ -302,7 +317,9 @@ class API:
|
|
|
302
317
|
else:
|
|
303
318
|
data = {"message": await resp.text()}
|
|
304
319
|
if self.log_traces:
|
|
305
|
-
LOG.debug(
|
|
320
|
+
LOG.debug(
|
|
321
|
+
"[TRACE] Data received from /%s: %s", endpoint, _redact_trace(data)
|
|
322
|
+
)
|
|
306
323
|
resp.raise_for_status()
|
|
307
324
|
return data
|
|
308
325
|
|
|
@@ -11,7 +11,7 @@ INSTANCE_ID: Final = str(uuid.uuid4())[24:]
|
|
|
11
11
|
LOG: Final = logging.getLogger(__package__)
|
|
12
12
|
DEFAULT_STATE_FILE: Final = "hilo_state.yaml"
|
|
13
13
|
REQUEST_RETRY: Final = 9
|
|
14
|
-
PYHILO_VERSION: Final = "2026.
|
|
14
|
+
PYHILO_VERSION: Final = "2026.12.01"
|
|
15
15
|
# TODO: Find a way to keep previous line in sync with pyproject.toml automatically
|
|
16
16
|
|
|
17
17
|
CONTENT_TYPE_FORM: Final = "application/x-www-form-urlencoded"
|
|
@@ -32,10 +32,17 @@ class GraphqlValueMapper:
|
|
|
32
32
|
self, values: Dict[str, Any]
|
|
33
33
|
) -> list[Dict[str, Any]]:
|
|
34
34
|
readings: list[Dict[str, Any]] = []
|
|
35
|
-
for device in values
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
35
|
+
for device in values["devices"]:
|
|
36
|
+
# Unmigrated SignalR devices appear as BasicDevice stubs with null status.
|
|
37
|
+
if device.get("__typename") == "BasicDevice":
|
|
38
|
+
continue
|
|
39
|
+
readings.extend(self._map_basic_device(device))
|
|
40
|
+
if device.get("__typename") == "Gateway":
|
|
41
|
+
readings.append(
|
|
42
|
+
self.build_attribute(
|
|
43
|
+
device["hiloId"], "onlineStatus", device["connectionStatus"]
|
|
44
|
+
)
|
|
45
|
+
)
|
|
39
46
|
return readings
|
|
40
47
|
|
|
41
48
|
def _map_devices_values(self, device: Dict[str, Any]) -> list[Dict[str, Any]]:
|
|
@@ -97,21 +104,19 @@ class GraphqlValueMapper:
|
|
|
97
104
|
attributes = []
|
|
98
105
|
attributes.append(
|
|
99
106
|
self.build_attribute(
|
|
100
|
-
device["hiloId"], "
|
|
107
|
+
device["hiloId"], "onlineStatus", device["connectionStatus"]
|
|
101
108
|
)
|
|
102
109
|
)
|
|
103
110
|
attributes.append(
|
|
104
111
|
self.build_attribute(
|
|
105
|
-
device["hiloId"], "
|
|
112
|
+
device["hiloId"], "LastStatusTime", device["lastConnectionTime"]
|
|
106
113
|
)
|
|
107
114
|
)
|
|
108
115
|
attributes.append(
|
|
109
116
|
self.build_attribute(
|
|
110
|
-
device["hiloId"],
|
|
111
|
-
"Disconnected",
|
|
112
|
-
device["connectionStatus"] == "DISCONNECTED",
|
|
117
|
+
device["hiloId"], "Version", device["controllerSoftwareVersion"]
|
|
113
118
|
)
|
|
114
|
-
)
|
|
119
|
+
)
|
|
115
120
|
attributes.append(
|
|
116
121
|
self.build_attribute(
|
|
117
122
|
device["hiloId"],
|
|
@@ -58,20 +58,16 @@ class Devices:
|
|
|
58
58
|
device_identifier: Union[int, str] = reading.device_id
|
|
59
59
|
if device_identifier == 0:
|
|
60
60
|
device_identifier = reading.hilo_id
|
|
61
|
-
device
|
|
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):
|
|
68
62
|
device.update_readings(reading)
|
|
69
63
|
LOG.debug("%s Received %s", device, reading)
|
|
70
64
|
if device not in updated_devices:
|
|
71
65
|
updated_devices.append(device)
|
|
72
66
|
else:
|
|
73
67
|
LOG.warning(
|
|
74
|
-
|
|
68
|
+
"Unable to find device %s for reading %s",
|
|
69
|
+
device_identifier,
|
|
70
|
+
reading,
|
|
75
71
|
)
|
|
76
72
|
return updated_devices
|
|
77
73
|
|
|
@@ -79,6 +75,8 @@ class Devices:
|
|
|
79
75
|
"""Makes sure the devices received have an identifier, this means some need to be hardcoded
|
|
80
76
|
like the unknown power meter.
|
|
81
77
|
"""
|
|
78
|
+
if not device_identifier:
|
|
79
|
+
return None
|
|
82
80
|
if isinstance(device_identifier, int):
|
|
83
81
|
return next((d for d in self.devices if d.id == device_identifier), None)
|
|
84
82
|
return next((d for d in self.devices if d.hilo_id == device_identifier), None)
|
|
@@ -3,13 +3,22 @@
|
|
|
3
3
|
from datetime import datetime, timedelta, timezone
|
|
4
4
|
import logging
|
|
5
5
|
import re
|
|
6
|
-
from typing import Any, cast
|
|
6
|
+
from typing import Any, TypedDict, cast
|
|
7
7
|
|
|
8
8
|
from pyhilo.util import camel_to_snake, from_utc_timestamp
|
|
9
9
|
|
|
10
10
|
LOG = logging.getLogger(__package__)
|
|
11
11
|
|
|
12
12
|
|
|
13
|
+
class OptOutDevice(TypedDict):
|
|
14
|
+
"""A device leaving Hilo's control, e.g. when its setpoint is changed during an event."""
|
|
15
|
+
|
|
16
|
+
id: int
|
|
17
|
+
eventDateUtc: str
|
|
18
|
+
triggerTypeId: int
|
|
19
|
+
triggerApplicationId: int | None
|
|
20
|
+
|
|
21
|
+
|
|
13
22
|
class Event:
|
|
14
23
|
"""This class is used to populate the data of a Hilo Challenge Event, contains datetime info and consumption data"""
|
|
15
24
|
|
|
@@ -38,7 +47,11 @@ class Event:
|
|
|
38
47
|
self.period: str = (cast(str, event.get("period", "")) or "").lower()
|
|
39
48
|
self.event_id: int = cast(int, event["id"])
|
|
40
49
|
self.total_devices: int = len(devices)
|
|
41
|
-
self.
|
|
50
|
+
self._opt_out_device_ids: set[int] = {x["id"] for x in devices if x["optOut"]}
|
|
51
|
+
self.opt_out_devices: int = 0
|
|
52
|
+
self._record_opt_outs(
|
|
53
|
+
cast(list[OptOutDevice], event.get("optOutDevices") or [])
|
|
54
|
+
)
|
|
42
55
|
self.pre_heat_devices: int = len([x for x in devices if x["preheat"]])
|
|
43
56
|
self.progress: str = cast(str, event.get("progress", "unknown"))
|
|
44
57
|
self.mode: str = cast(str, params.get("mode", "Unknown"))
|
|
@@ -68,6 +81,48 @@ class Event:
|
|
|
68
81
|
"reward",
|
|
69
82
|
]
|
|
70
83
|
|
|
84
|
+
def update(self, data: dict[str, Any]) -> None:
|
|
85
|
+
"""Update the event in place from a partial Hilo message.
|
|
86
|
+
|
|
87
|
+
Hilo sends partial updates: a field it isn't changing is either
|
|
88
|
+
missing or None (an opt-out notice carries only the opted-out
|
|
89
|
+
devices, with progress, parameters, etc. set to None). Only the
|
|
90
|
+
fields that carry a value are applied; everything else keeps its
|
|
91
|
+
current value. Consumption progress arrives in separate messages
|
|
92
|
+
handled by update_wh().
|
|
93
|
+
"""
|
|
94
|
+
if (phases := data.get("phases")) is not None:
|
|
95
|
+
self._convert_phases(phases)
|
|
96
|
+
if (progress := data.get("progress")) is not None:
|
|
97
|
+
self.progress = progress
|
|
98
|
+
if (participating := data.get("isParticipating")) is not None:
|
|
99
|
+
self.participating = participating
|
|
100
|
+
if (configurable := data.get("isConfigurable")) is not None:
|
|
101
|
+
self.configurable = configurable
|
|
102
|
+
if (period := data.get("period")) is not None:
|
|
103
|
+
self.period = period.lower()
|
|
104
|
+
if (params := data.get("parameters")) is not None:
|
|
105
|
+
devices: list[dict[str, Any]] = params.get("devices", [])
|
|
106
|
+
self.total_devices = len(devices)
|
|
107
|
+
self._opt_out_device_ids.update(x["id"] for x in devices if x["optOut"])
|
|
108
|
+
self.pre_heat_devices = len([x for x in devices if x["preheat"]])
|
|
109
|
+
self.mode = params.get("mode", self.mode)
|
|
110
|
+
self._record_opt_outs(data.get("optOutDevices") or [])
|
|
111
|
+
if (reward := data.get("reward")) is not None:
|
|
112
|
+
self.reward = reward
|
|
113
|
+
consumption: dict[str, Any] = data.get("consumption") or {}
|
|
114
|
+
# Hilo reports a baseline of 0 until it has computed one; skip it so
|
|
115
|
+
# a known baseline is never wiped.
|
|
116
|
+
if allowed_wH := consumption.get("baselineWh"):
|
|
117
|
+
self.update_allowed_wh(allowed_wH)
|
|
118
|
+
self.last_update = datetime.now(timezone.utc).astimezone()
|
|
119
|
+
|
|
120
|
+
def _record_opt_outs(self, opt_outs: list[OptOutDevice]) -> None:
|
|
121
|
+
# Hilo emits an entry each time a device is taken over, so the same
|
|
122
|
+
# device can appear many times; count each device once.
|
|
123
|
+
self._opt_out_device_ids.update(x["id"] for x in opt_outs)
|
|
124
|
+
self.opt_out_devices = len(self._opt_out_device_ids)
|
|
125
|
+
|
|
71
126
|
def update_wh(self, used_wH: float) -> None:
|
|
72
127
|
"""This function is used to update the used_kWh attribute during a Hilo Challenge Event"""
|
|
73
128
|
LOG.debug("Updating Wh: %s", used_wH)
|
|
@@ -286,6 +286,9 @@ class GraphQlHelper:
|
|
|
286
286
|
status
|
|
287
287
|
device {
|
|
288
288
|
... on Gateway {
|
|
289
|
+
deviceType
|
|
290
|
+
hiloId
|
|
291
|
+
physicalAddress
|
|
289
292
|
connectionStatus
|
|
290
293
|
controllerSoftwareVersion
|
|
291
294
|
lastConnectionTime
|
|
@@ -516,33 +519,21 @@ class GraphQlHelper:
|
|
|
516
519
|
}
|
|
517
520
|
}"""
|
|
518
521
|
|
|
519
|
-
SUBSCRIPTION_LOCATION_UPDATED: str = """subscription onAnyLocationUpdated($locationHiloId: String!){
|
|
522
|
+
SUBSCRIPTION_LOCATION_UPDATED: str = """subscription onAnyLocationUpdated($locationHiloId: String!) {
|
|
520
523
|
onAnyLocationUpdated(locationHiloId: $locationHiloId) {
|
|
521
|
-
locationHiloId
|
|
522
|
-
deviceType
|
|
523
524
|
transmissionTime
|
|
524
525
|
operationId
|
|
525
526
|
location {
|
|
526
|
-
|
|
527
|
+
devices {
|
|
528
|
+
__typename
|
|
527
529
|
hiloId
|
|
528
|
-
|
|
529
|
-
deviceType
|
|
530
|
-
hiloId
|
|
531
|
-
physicalAddress
|
|
532
|
-
connectionStatus
|
|
533
|
-
... on BasicChargeController {
|
|
534
|
-
connectionStatus
|
|
535
|
-
}
|
|
536
|
-
... on LowVoltageThermostat {
|
|
537
|
-
connectionStatus
|
|
538
|
-
}
|
|
539
|
-
}
|
|
530
|
+
connectionStatus
|
|
540
531
|
}
|
|
541
532
|
}
|
|
542
533
|
}
|
|
543
534
|
}"""
|
|
544
535
|
|
|
545
|
-
async def call_get_location_query(self, location_hilo_id: str) ->
|
|
536
|
+
async def call_get_location_query(self, location_hilo_id: str) -> list[str]:
|
|
546
537
|
"""This functions calls the digital-twin and requests location id"""
|
|
547
538
|
access_token = await self._get_access_token()
|
|
548
539
|
url = f"https://{PLATFORM_HOST}/api/digital-twin/v3/graphql"
|
|
@@ -568,7 +559,7 @@ class GraphQlHelper:
|
|
|
568
559
|
response_json = response.json()
|
|
569
560
|
except Exception as e:
|
|
570
561
|
LOG.error("Error parsing response: %s", e)
|
|
571
|
-
return
|
|
562
|
+
return []
|
|
572
563
|
|
|
573
564
|
if "errors" in response_json:
|
|
574
565
|
for error in response_json["errors"]:
|
|
@@ -582,12 +573,12 @@ class GraphQlHelper:
|
|
|
582
573
|
response_json = response.json()
|
|
583
574
|
except Exception as e:
|
|
584
575
|
LOG.error("Error parsing response on retry: %s", e)
|
|
585
|
-
return
|
|
576
|
+
return []
|
|
586
577
|
break
|
|
587
578
|
|
|
588
579
|
if "errors" in response_json:
|
|
589
580
|
LOG.error("GraphQL errors: %s", response_json["errors"])
|
|
590
|
-
return
|
|
581
|
+
return []
|
|
591
582
|
|
|
592
583
|
if "data" in response_json:
|
|
593
584
|
devices = (
|
|
@@ -600,7 +591,9 @@ class GraphQlHelper:
|
|
|
600
591
|
"Gateway devices in getLocation response: %s",
|
|
601
592
|
json.dumps(gateways, indent=2),
|
|
602
593
|
)
|
|
603
|
-
self._handle_query_result(response_json["data"])
|
|
594
|
+
return self._handle_query_result(response_json["data"])
|
|
595
|
+
|
|
596
|
+
return []
|
|
604
597
|
|
|
605
598
|
async def subscribe_to_device_updated(
|
|
606
599
|
self,
|
|
@@ -650,7 +643,7 @@ class GraphQlHelper:
|
|
|
650
643
|
def _handle_sse_message(
|
|
651
644
|
self,
|
|
652
645
|
data: Dict[str, Any],
|
|
653
|
-
handler: Callable[[Dict[str, Any]], str],
|
|
646
|
+
handler: Callable[[Dict[str, Any]], list[str]],
|
|
654
647
|
callback: Optional[Callable[[str], None]],
|
|
655
648
|
) -> tuple:
|
|
656
649
|
"""Dispatch a parsed SSE message. Returns (retry_apq, had_success)."""
|
|
@@ -663,16 +656,17 @@ class GraphQlHelper:
|
|
|
663
656
|
return False, False
|
|
664
657
|
if "data" in data:
|
|
665
658
|
LOG.debug("Received subscription result %s", data["data"])
|
|
666
|
-
|
|
659
|
+
hilo_ids = handler(data["data"])
|
|
667
660
|
if callback:
|
|
668
|
-
|
|
661
|
+
for hilo_id in hilo_ids:
|
|
662
|
+
callback(hilo_id)
|
|
669
663
|
return False, True
|
|
670
664
|
return False, False
|
|
671
665
|
|
|
672
666
|
async def _drain_sse_events(
|
|
673
667
|
self,
|
|
674
668
|
event_source: Any,
|
|
675
|
-
handler: Callable[[Dict[str, Any]], str],
|
|
669
|
+
handler: Callable[[Dict[str, Any]], list[str]],
|
|
676
670
|
callback: Optional[Callable[[str], None]],
|
|
677
671
|
) -> tuple:
|
|
678
672
|
"""Read events until the stream closes. Returns (retry_apq, had_success)."""
|
|
@@ -707,7 +701,7 @@ class GraphQlHelper:
|
|
|
707
701
|
url: str,
|
|
708
702
|
headers: Dict[str, str],
|
|
709
703
|
payload: Dict[str, Any],
|
|
710
|
-
handler: Callable[[Dict[str, Any]], str],
|
|
704
|
+
handler: Callable[[Dict[str, Any]], list[str]],
|
|
711
705
|
callback: Optional[Callable[[str], None]],
|
|
712
706
|
) -> tuple:
|
|
713
707
|
"""Open one SSE connection and drain it. Returns (retry_apq, had_success)."""
|
|
@@ -723,7 +717,7 @@ class GraphQlHelper:
|
|
|
723
717
|
self,
|
|
724
718
|
query: str,
|
|
725
719
|
variables: Dict[str, Any],
|
|
726
|
-
handler: Callable[[Dict[str, Any]], str],
|
|
720
|
+
handler: Callable[[Dict[str, Any]], list[str]],
|
|
727
721
|
callback: Optional[Callable[[str], None]] = None,
|
|
728
722
|
location_hilo_id: Optional[str] = None,
|
|
729
723
|
) -> None:
|
|
@@ -752,6 +746,7 @@ class GraphQlHelper:
|
|
|
752
746
|
"SSE connection closed by server. Reconnecting in 5 seconds..."
|
|
753
747
|
)
|
|
754
748
|
await asyncio.sleep(5)
|
|
749
|
+
await self._resync_after_reconnect(location_hilo_id, callback)
|
|
755
750
|
|
|
756
751
|
except asyncio.TimeoutError:
|
|
757
752
|
# Keepalive timeout: the connection was recently live, so start
|
|
@@ -765,15 +760,7 @@ class GraphQlHelper:
|
|
|
765
760
|
backoff_delay = min(backoff_delay * 2, self._BACKOFF_MAX)
|
|
766
761
|
if "query" in payload:
|
|
767
762
|
del payload["query"]
|
|
768
|
-
|
|
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
|
-
)
|
|
763
|
+
await self._resync_after_reconnect(location_hilo_id, callback)
|
|
777
764
|
|
|
778
765
|
except Exception as e:
|
|
779
766
|
LOG.debug(
|
|
@@ -785,21 +772,30 @@ class GraphQlHelper:
|
|
|
785
772
|
backoff_delay = min(backoff_delay * 2, self._BACKOFF_MAX)
|
|
786
773
|
if "query" in payload:
|
|
787
774
|
del payload["query"]
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
775
|
+
await self._resync_after_reconnect(location_hilo_id, callback)
|
|
776
|
+
|
|
777
|
+
async def _resync_after_reconnect(
|
|
778
|
+
self,
|
|
779
|
+
location_hilo_id: Optional[str],
|
|
780
|
+
callback: Optional[Callable[[str], None]],
|
|
781
|
+
) -> None:
|
|
782
|
+
if not location_hilo_id:
|
|
783
|
+
return
|
|
784
|
+
try:
|
|
785
|
+
hilo_ids = await self.call_get_location_query(location_hilo_id)
|
|
786
|
+
LOG.debug("call_get_location_query success after reconnect")
|
|
787
|
+
except Exception as err:
|
|
788
|
+
LOG.error("exception while RE-connecting, retrying: %s", err)
|
|
789
|
+
return
|
|
790
|
+
if callback:
|
|
791
|
+
for hilo_id in hilo_ids:
|
|
792
|
+
callback(hilo_id)
|
|
797
793
|
|
|
798
794
|
async def _get_access_token(self) -> str:
|
|
799
795
|
"""Get the access token."""
|
|
800
796
|
return await self._api.async_get_access_token()
|
|
801
797
|
|
|
802
|
-
def _handle_query_result(self, result: Dict[str, Any]) ->
|
|
798
|
+
def _handle_query_result(self, result: Dict[str, Any]) -> list[str]:
|
|
803
799
|
"""Handle the result of the GraphQL query for location and devices."""
|
|
804
800
|
devices_values: List[Dict[str, Any]] = result["getLocation"]["devices"]
|
|
805
801
|
|
|
@@ -813,7 +809,8 @@ class GraphQlHelper:
|
|
|
813
809
|
self._devices.devices.append(gw_dev)
|
|
814
810
|
|
|
815
811
|
attributes = self.mapper.map_query_values(devices_values)
|
|
816
|
-
self._devices.parse_values_received(attributes)
|
|
812
|
+
updated_devices = self._devices.parse_values_received(attributes)
|
|
813
|
+
return [device.hilo_id for device in updated_devices if device.hilo_id]
|
|
817
814
|
|
|
818
815
|
def _build_gateway_dict(self, raw_device: Dict[str, Any]) -> Dict[str, Any]:
|
|
819
816
|
"""Build a dictionary representing the gateway device from raw GraphQL data."""
|
|
@@ -829,6 +826,7 @@ class GraphQlHelper:
|
|
|
829
826
|
"type": "Gateway",
|
|
830
827
|
"category": "Gateway",
|
|
831
828
|
"id": 1,
|
|
829
|
+
"hilo_id": hilo_id,
|
|
832
830
|
"identifier": mac,
|
|
833
831
|
"sdi": mac,
|
|
834
832
|
"provider": 1,
|
|
@@ -847,20 +845,20 @@ class GraphQlHelper:
|
|
|
847
845
|
"disconnected": {"value": connection_status != "CONNECTED"},
|
|
848
846
|
}
|
|
849
847
|
|
|
850
|
-
def _handle_device_subscription_result(self, result: Dict[str, Any]) -> str:
|
|
848
|
+
def _handle_device_subscription_result(self, result: Dict[str, Any]) -> list[str]:
|
|
851
849
|
"""Handle the result of the GraphQL subscription for device updates."""
|
|
852
850
|
device_value: Dict[str, Any] = result["onAnyDeviceUpdated"]["device"]
|
|
853
851
|
attributes = self.mapper.map_device_subscription_values(device_value)
|
|
854
|
-
|
|
852
|
+
updated_devices = self._devices.parse_values_received(attributes)
|
|
855
853
|
# callback to update the device in the UI
|
|
856
|
-
LOG.debug("Device updated: %s",
|
|
857
|
-
return
|
|
854
|
+
LOG.debug("Device updated: %s", updated_devices)
|
|
855
|
+
return [device.hilo_id for device in updated_devices if device.hilo_id]
|
|
858
856
|
|
|
859
|
-
def _handle_location_subscription_result(self, result: Dict[str, Any]) -> str:
|
|
857
|
+
def _handle_location_subscription_result(self, result: Dict[str, Any]) -> list[str]:
|
|
860
858
|
"""Handle the result of the GraphQL subscription for location updates."""
|
|
861
859
|
location_value: Dict[str, Any] = result["onAnyLocationUpdated"]["location"]
|
|
862
860
|
attributes = self.mapper.map_location_subscription_values(location_value)
|
|
863
|
-
|
|
861
|
+
updated_devices = self._devices.parse_values_received(attributes)
|
|
864
862
|
# callback to update the device in the UI
|
|
865
|
-
LOG.debug("Device updated: %s",
|
|
866
|
-
return
|
|
863
|
+
LOG.debug("Device updated: %s", updated_devices)
|
|
864
|
+
return [device.hilo_id for device in updated_devices if device.hilo_id]
|
|
@@ -8,7 +8,7 @@ from unittest.mock import AsyncMock, MagicMock
|
|
|
8
8
|
import pytest
|
|
9
9
|
|
|
10
10
|
from pyhilo import API, AbstractAuth
|
|
11
|
-
from pyhilo.const import API_HOSTNAME
|
|
11
|
+
from pyhilo.const import API_HOSTNAME, SUBSCRIPTION_KEY
|
|
12
12
|
|
|
13
13
|
URN = "urn:hilo:crm:abc-123"
|
|
14
14
|
|
|
@@ -133,3 +133,38 @@ async def test_deprecated_oauth_session_still_works(
|
|
|
133
133
|
assert await api.async_get_access_token() == TOKEN
|
|
134
134
|
oauth_session.async_ensure_token_valid.assert_awaited_once()
|
|
135
135
|
assert api.urn == URN
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
@pytest.mark.parametrize(
|
|
139
|
+
"secret",
|
|
140
|
+
[
|
|
141
|
+
pytest.param(TOKEN, id="bearer_token"),
|
|
142
|
+
pytest.param(SUBSCRIPTION_KEY, id="subscription_key"),
|
|
143
|
+
],
|
|
144
|
+
)
|
|
145
|
+
async def test_trace_logs_redact_request_credentials(
|
|
146
|
+
mock_session: MagicMock, caplog: pytest.LogCaptureFixture, secret: str
|
|
147
|
+
) -> None:
|
|
148
|
+
auth = AsyncMock(spec=AbstractAuth)
|
|
149
|
+
auth.async_get_access_token.return_value = TOKEN
|
|
150
|
+
api = API(session=mock_session, auth=auth, log_traces=True)
|
|
151
|
+
|
|
152
|
+
with caplog.at_level(logging.DEBUG):
|
|
153
|
+
await api._async_request("get", "/endpoint")
|
|
154
|
+
|
|
155
|
+
assert secret not in caplog.text
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
async def test_trace_logs_redact_signalr_negotiate_token(
|
|
159
|
+
mock_session: MagicMock, caplog: pytest.LogCaptureFixture
|
|
160
|
+
) -> None:
|
|
161
|
+
response = mock_session.request.return_value.__aenter__.return_value
|
|
162
|
+
response.json.return_value = {"url": "https://hub", "accessToken": "hub-token"}
|
|
163
|
+
auth = AsyncMock(spec=AbstractAuth)
|
|
164
|
+
auth.async_get_access_token.return_value = TOKEN
|
|
165
|
+
api = API(session=mock_session, auth=auth, log_traces=True)
|
|
166
|
+
|
|
167
|
+
with caplog.at_level(logging.DEBUG):
|
|
168
|
+
await api._async_request("post", "/DeviceHub/negotiate")
|
|
169
|
+
|
|
170
|
+
assert "hub-token" not in caplog.text
|