Skip to content

Commit ac476db

Browse files
authored
Merge pull request #295 from dvd-dev/docstrings
Adding some docstrings/comments
2 parents 725ad81 + 4581a81 commit ac476db

File tree

6 files changed

+44
-3
lines changed

6 files changed

+44
-3
lines changed

pyhilo/api.py

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -393,6 +393,7 @@ async def refresh_ws_token(self) -> None:
393393
await self.websocket_manager.refresh_token(self.websocket_manager.challengehub)
394394

395395
async def get_websocket_params(self) -> None:
396+
"""Retrieves and constructs WebSocket connection parameters from the negotiation endpoint."""
396397
uri = parse.urlparse(self.ws_url)
397398
LOG.debug("Getting websocket params")
398399
LOG.debug(f"Getting uri {uri}")
@@ -415,10 +416,11 @@ async def get_websocket_params(self) -> None:
415416
"available_transports": transport_dict,
416417
"full_ws_url": self.full_ws_url,
417418
}
418-
LOG.debug("Calling set_state websocket_params")
419+
LOG.debug("Calling set_state from get_websocket_params")
419420
await set_state(self._state_yaml, "websocket", websocket_dict)
420421

421422
async def fb_install(self, fb_id: str) -> None:
423+
"""Registers a Firebase installation and stores the authentication token state."""
422424
LOG.debug("Posting firebase install")
423425
body = {
424426
"fid": fb_id,
@@ -441,7 +443,7 @@ async def fb_install(self, fb_id: str) -> None:
441443
raise RequestError(err) from err
442444
LOG.debug(f"FB Install data: {resp}")
443445
auth_token = resp.get("authToken", {})
444-
LOG.debug("Calling set_state fb_install")
446+
LOG.debug("Calling set_state from fb_install")
445447
await set_state(
446448
self._state_yaml,
447449
"firebase",
@@ -493,6 +495,7 @@ async def android_register(self) -> None:
493495
)
494496

495497
async def get_location_ids(self) -> tuple[int, str]:
498+
"""Gets location id from an API call"""
496499
url = f"{API_AUTOMATION_ENDPOINT}/Locations"
497500
LOG.debug(f"LocationId URL is {url}")
498501
req: list[dict[str, Any]] = await self.async_request("get", url)
@@ -516,6 +519,7 @@ async def _set_device_attribute(
516519
key: DeviceAttribute,
517520
value: Union[str, float, int, None],
518521
) -> None:
522+
"""Sets device attributes"""
519523
url = self._get_url(f"Devices/{device.id}/Attributes", device.location_id)
520524
LOG.debug(f"Device Attribute URL is {url}")
521525
await self.async_request("put", url, json={key.hilo_attribute: value})
@@ -611,7 +615,7 @@ async def get_gd_events(
611615
}
612616
}
613617
"""
614-
618+
# ic-dev21 need to check but this is probably dead code
615619
url = self._get_url("Events", location_id, True)
616620
if not event_id:
617621
url += "?active=true"
@@ -645,6 +649,7 @@ async def get_seasons(self, location_id: int) -> dict[str, Any]:
645649
return cast(dict[str, Any], await self.async_request("get", url))
646650

647651
async def get_gateway(self, location_id: int) -> dict[str, Any]:
652+
"""Gets info about the Hilo hub (gateway)"""
648653
url = self._get_url("Gateways/Info", location_id)
649654
LOG.debug(f"Gateway URL is {url}")
650655
req = await self.async_request("get", url)

pyhilo/devices.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111

1212
class Devices:
1313
def __init__(self, api: API):
14+
"""Initialize."""
1415
self._api = api
1516
self.devices: list[HiloDevice] = []
1617
self.location_id: int = 0
@@ -37,6 +38,9 @@ def attributes_list(self) -> list[Union[int, dict[int, list[str]]]]:
3738
]
3839

3940
def parse_values_received(self, values: list[dict[str, Any]]) -> list[HiloDevice]:
41+
"""Places value received in a dict while removing null attributes,
42+
this returns values to be mapped to devices.
43+
"""
4044
readings = []
4145
for val in values:
4246
val["device_attribute"] = self._api.dev_atts(
@@ -48,6 +52,7 @@ def parse_values_received(self, values: list[dict[str, Any]]) -> list[HiloDevice
4852
def _map_readings_to_devices(
4953
self, readings: list[DeviceReading]
5054
) -> list[HiloDevice]:
55+
"""Uses the dict from parse_values_received to map the values to devices."""
5156
updated_devices = []
5257
for reading in readings:
5358
device_identifier = reading.device_id
@@ -65,11 +70,15 @@ def _map_readings_to_devices(
6570
return updated_devices
6671

6772
def find_device(self, device_identifier: int | str) -> HiloDevice:
73+
"""Makes sure the devices received have an identifier, this means some need to be hardcoded
74+
like the unknown power meter.
75+
"""
6876
if isinstance(device_identifier, int):
6977
return next((d for d in self.devices if d.id == device_identifier), None)
7078
return next((d for d in self.devices if d.hilo_id == device_identifier), None)
7179

7280
def generate_device(self, device: dict) -> HiloDevice:
81+
"""Generate all devices from the list received."""
7382
device["location_id"] = self.location_id
7483
if dev := self.find_device(device["id"]):
7584
dev.update(**device)
@@ -101,6 +110,7 @@ async def update(self) -> None:
101110
async def update_devicelist_from_signalr(
102111
self, values: list[dict[str, Any]]
103112
) -> list[HiloDevice]:
113+
#ic-dev21 not sure if this is dead code?
104114
new_devices = []
105115
for raw_device in values:
106116
LOG.debug(f"Generating device {raw_device}")

pyhilo/event.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ class Event:
2525
recovery_end: datetime
2626

2727
def __init__(self, **event: dict[str, Any]):
28+
"""Initialize."""
2829
self._convert_phases(cast(dict[str, Any], event.get("phases")))
2930
params: dict[str, Any] = event.get("parameters", {})
3031
devices: list[dict[str, Any]] = params.get("devices", [])
@@ -79,6 +80,7 @@ def should_check_for_allowed_wh(self) -> bool:
7980
return 1800 <= time_since_preheat_start <= 2700 and not already_has_allowed_wh
8081

8182
def as_dict(self) -> dict[str, Any]:
83+
"""Formats the information received as a dictionary"""
8284
rep = {k: getattr(self, k) for k in self.dict_items}
8385
rep["phases"] = {k: getattr(self, k) for k in self.phases_list}
8486
rep["state"] = self.state
@@ -134,6 +136,7 @@ def invalid(self) -> bool:
134136

135137
@property
136138
def current_phase_times(self) -> dict[str, datetime]:
139+
"""Defines timestamps for Hilo Challenge"""
137140
if self.state in ["completed", "off", "scheduled", "unknown"]:
138141
return {}
139142
phase_timestamp = self._phase_time_mapping.get(self.state, self.state)

pyhilo/graphql.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -529,6 +529,7 @@ async def async_init(self) -> None:
529529
}"""
530530

531531
async def call_get_location_query(self, location_hilo_id: str) -> None:
532+
"""This functions calls the digital-twin and requests location id"""
532533
access_token = await self._get_access_token()
533534
transport = AIOHTTPTransport(
534535
url="https://platform.hiloenergie.com/api/digital-twin/v3/graphql",
@@ -594,6 +595,7 @@ async def _get_access_token(self) -> str:
594595
return await self._api.async_get_access_token()
595596

596597
def _handle_query_result(self, result: Dict[str, Any]) -> None:
598+
"""This receives query results and maps them to the proper device."""
597599
devices_values: list[any] = result["getLocation"]["devices"]
598600
attributes = self.mapper.map_query_values(devices_values)
599601
self._devices.parse_values_received(attributes)

pyhilo/oauth2helper.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,10 +17,12 @@ def __init__(self) -> None:
1717

1818
# Ref : https://blog.sanghviharshit.com/reverse-engineering-private-api-oauth-code-flow-with-pkce/
1919
def _get_code_verifier(self) -> str:
20+
"""Generates a random cryptographic key string to be used as a code verifier in PKCE."""
2021
code = base64.urlsafe_b64encode(os.urandom(40)).decode("utf-8")
2122
return re.sub("[^a-zA-Z0-9]+", "", code)
2223

2324
def _get_code_challenge(self, verifier: str) -> str:
25+
"""Generates a SHA-256 code challenge for PKCE"""
2426
sha_verifier = hashlib.sha256(verifier.encode("utf-8")).digest()
2527
code = base64.urlsafe_b64encode(sha_verifier).decode("utf-8")
2628
return code.replace("=", "")

pyhilo/websocket.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -311,6 +311,7 @@ async def async_connect(self) -> None:
311311
schedule_callback(callback)
312312

313313
async def _clean_queue(self) -> None:
314+
"""Removes queued tasks."""
314315
for task in self._queued_tasks:
315316
task.cancel()
316317

@@ -368,6 +369,24 @@ async def _async_pong(self) -> None:
368369
async def async_invoke(
369370
self, arg: list, target: str, inv_id: int, inv_type: WSMsgType = WSMsgType.TEXT
370371
) -> None:
372+
"""
373+
Sends an invocation message over the WebSocket connection.
374+
375+
Waits for the WebSocket to be ready if it is not already, then sends a message
376+
containing the target method, arguments, and invocation ID.
377+
378+
Args:
379+
arg (list): The list of arguments to send with the invocation.
380+
target (str): The name of the method or action being invoked on the server.
381+
inv_id (int): A unique identifier for this invocation message.
382+
inv_type (WSMsgType, optional): The WebSocket message type. Defaults to WSMsgType.TEXT.
383+
384+
Returns:
385+
None
386+
387+
Notes:
388+
If the WebSocket is not ready within 10 seconds, the invocation is skipped.
389+
"""
371390
if not self._ready:
372391
LOG.warning(
373392
f"Delaying invoke {target} {inv_id} {arg}: Websocket not ready."

0 commit comments

Comments
 (0)