Skip to content

Commit 21777d1

Browse files
authored
Merge pull request #323 from dvd-dev/style_guideline
Style guideline
2 parents 6dc2ccd + 03ec09c commit 21777d1

File tree

8 files changed

+55
-43
lines changed

8 files changed

+55
-43
lines changed

pyhilo/api.py

Lines changed: 17 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -140,7 +140,7 @@ async def async_get_access_token(self) -> str:
140140
await self._oauth_session.async_ensure_token_valid()
141141

142142
access_token = str(self._oauth_session.token["access_token"])
143-
LOG.debug(f"Websocket access token is {access_token}")
143+
LOG.debug("Websocket access token is %s", access_token)
144144

145145
return str(self._oauth_session.token["access_token"])
146146

@@ -246,8 +246,9 @@ async def _async_request(
246246
data: dict[str, Any] = {}
247247
url = parse.urljoin(f"https://{host}", endpoint)
248248
if self.log_traces:
249-
LOG.debug(f"[TRACE] Headers: {kwargs['headers']}")
250-
LOG.debug(f"[TRACE] Async request: {method} {url}")
249+
LOG.debug("[TRACE] Headers: %s", kwargs["headers"])
250+
LOG.debug("[TRACE] Async request: %s %s", method, url)
251+
251252
async with self.session.request(method, url, **kwargs) as resp:
252253
if "application/json" in resp.headers.get("content-type", ""):
253254
try:
@@ -396,7 +397,7 @@ async def get_websocket_params(self) -> None:
396397
"""Retrieves and constructs WebSocket connection parameters from the negotiation endpoint."""
397398
uri = parse.urlparse(self.ws_url)
398399
LOG.debug("Getting websocket params")
399-
LOG.debug(f"Getting uri {uri}")
400+
LOG.debug("Getting uri %s", uri)
400401
resp: dict[str, Any] = await self.async_request(
401402
"post",
402403
f"{uri.path}negotiate?{uri.query}",
@@ -407,7 +408,7 @@ async def get_websocket_params(self) -> None:
407408
)
408409
conn_id: str = resp.get("connectionId", "")
409410
self.full_ws_url = f"{self.ws_url}&id={conn_id}&access_token={self.ws_token}"
410-
LOG.debug(f"Getting full ws URL {self.full_ws_url}")
411+
LOG.debug("Getting full ws URL %s", self.full_ws_url)
411412
transport_dict: list[WebsocketTransportsDict] = resp.get(
412413
"availableTransports", []
413414
)
@@ -441,7 +442,7 @@ async def fb_install(self, fb_id: str) -> None:
441442
if err.status in (401, 403):
442443
raise InvalidCredentialsError("Invalid credentials") from err
443444
raise RequestError(err) from err
444-
LOG.debug(f"FB Install data: {resp}")
445+
LOG.debug("FB Install data: %s", resp)
445446
auth_token = resp.get("authToken", {})
446447
LOG.debug("Calling set_state from fb_install")
447448
await set_state(
@@ -479,7 +480,7 @@ async def android_register(self) -> None:
479480
if err.status in (401, 403):
480481
raise InvalidCredentialsError("Invalid credentials") from err
481482
raise RequestError(err) from err
482-
LOG.debug(f"Android client register: {resp}")
483+
LOG.debug("Android client register: %s", resp)
483484
msg: str = resp.get("message", "")
484485
if msg.startswith("Error="):
485486
LOG.error(f"Android registration error: {msg}")
@@ -497,14 +498,14 @@ async def android_register(self) -> None:
497498
async def get_location_ids(self) -> tuple[int, str]:
498499
"""Gets location id from an API call"""
499500
url = f"{API_AUTOMATION_ENDPOINT}/Locations"
500-
LOG.debug(f"LocationId URL is {url}")
501+
LOG.debug("LocationId URL is %s", url)
501502
req: list[dict[str, Any]] = await self.async_request("get", url)
502503
return (req[0]["id"], req[0]["locationHiloId"])
503504

504505
async def get_devices(self, location_id: int) -> list[dict[str, Any]]:
505506
"""Get list of all devices"""
506507
url = self._get_url("Devices", location_id)
507-
LOG.debug(f"Devices URL is {url}")
508+
LOG.debug("Devices URL is %s", url)
508509
devices: list[dict[str, Any]] = await self.async_request("get", url)
509510
devices.append(await self.get_gateway(location_id))
510511
# Now it's time to add devices coming from external sources like hass
@@ -521,7 +522,7 @@ async def _set_device_attribute(
521522
) -> None:
522523
"""Sets device attributes"""
523524
url = self._get_url(f"Devices/{device.id}/Attributes", device.location_id)
524-
LOG.debug(f"Device Attribute URL is {url}")
525+
LOG.debug("Device Attribute URL is %s", url)
525526
await self.async_request("put", url, json={key.hilo_attribute: value})
526527

527528
async def get_event_notifications(self, location_id: int) -> dict[str, Any]:
@@ -549,7 +550,7 @@ async def get_event_notifications(self, location_id: int) -> dict[str, Any]:
549550
"viewed": false
550551
}"""
551552
url = self._get_url(None, location_id, events=True)
552-
LOG.debug(f"Event Notifications URL is {url}")
553+
LOG.debug("Event Notifications URL is %s", url)
553554
return cast(dict[str, Any], await self.async_request("get", url))
554555

555556
async def get_gd_events(
@@ -622,7 +623,7 @@ async def get_gd_events(
622623
else:
623624
url += f"/{event_id}"
624625

625-
LOG.debug(f"get_gd_events URL is {url}")
626+
LOG.debug("get_gd_events URL is %s", url)
626627
return cast(dict[str, Any], await self.async_request("get", url))
627628

628629
async def get_seasons(self, location_id: int) -> dict[str, Any]:
@@ -645,13 +646,13 @@ async def get_seasons(self, location_id: int) -> dict[str, Any]:
645646
]
646647
"""
647648
url = self._get_url("Seasons", location_id, challenge=True)
648-
LOG.debug(f"Seasons URL is {url}")
649+
LOG.debug("Seasons URL is %s", url)
649650
return cast(dict[str, Any], await self.async_request("get", url))
650651

651652
async def get_gateway(self, location_id: int) -> dict[str, Any]:
652653
"""Gets info about the Hilo hub (gateway)"""
653654
url = self._get_url("Gateways/Info", location_id)
654-
LOG.debug(f"Gateway URL is {url}")
655+
LOG.debug("Gateway URL is %s", url)
655656
req = await self.async_request("get", url)
656657
saved_attrs = [
657658
"zigBeePairingActivated",
@@ -694,7 +695,7 @@ async def get_weather(self, location_id: int) -> dict[str, Any]:
694695
]
695696
"""
696697
url = self._get_url("Weather", location_id)
697-
LOG.debug(f"Weather URL is {url}")
698+
LOG.debug("Weather URL is %s", url)
698699
response = await self.async_request("get", url)
699-
LOG.debug(f"Weather API response: {response}")
700+
LOG.debug("Weather API response: %s", response)
700701
return cast(dict[str, Any], await self.async_request("get", url))

pyhilo/device/light.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
class Light(HiloDevice):
1111
def __init__(self, api: API, **kwargs: dict[str, Union[str, int]]):
1212
super().__init__(api, **kwargs) # type: ignore
13-
LOG.debug(f"Setting up Light device: {self.name}")
13+
LOG.debug("Setting up Light device: %s", self.name)
1414

1515
@property
1616
def brightness(self) -> float:

pyhilo/device/sensor.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
class Sensor(HiloDevice):
1111
def __init__(self, api: API, **kwargs: dict[str, Union[str, int]]):
1212
super().__init__(api, **kwargs) # type: ignore
13-
LOG.debug(f"Setting up Sensor device: {self.name}")
13+
LOG.debug("Setting up Sensor device: %s", self.name)
1414

1515
@property
1616
def state(self) -> str:

pyhilo/device/switch.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
class Switch(HiloDevice):
1111
def __init__(self, api: API, **kwargs: dict[str, Union[str, int]]):
1212
super().__init__(api, **kwargs) # type: ignore
13-
LOG.debug(f"Setting up Switch device: {self.name}")
13+
LOG.debug("Setting up Switch device: %s", self.name)
1414

1515
@property
1616
def state(self) -> str:

pyhilo/devices.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ def _map_readings_to_devices(
6060
device_identifier = reading.hilo_id
6161
if device := self.find_device(device_identifier):
6262
device.update_readings(reading)
63-
LOG.debug(f"{device} Received {reading}")
63+
LOG.debug("%s Received %s", device, reading)
6464
if device not in updated_devices:
6565
updated_devices.append(device)
6666
else:
@@ -96,14 +96,14 @@ async def update(self) -> None:
9696
fresh_devices = await self._api.get_devices(self.location_id)
9797
generated_devices = []
9898
for raw_device in fresh_devices:
99-
LOG.debug(f"Generating device {raw_device}")
99+
LOG.debug("Generating device %s", raw_device)
100100
dev = self.generate_device(raw_device)
101101
generated_devices.append(dev)
102102
if dev not in self.devices:
103103
self.devices.append(dev)
104104
for device in self.devices:
105105
if device not in generated_devices:
106-
LOG.debug(f"Device unpaired {device}")
106+
LOG.debug("Device unpaired %s", device)
107107
# Don't do anything with unpaired device for now.
108108
# self.devices.remove(device)
109109

@@ -113,7 +113,7 @@ async def update_devicelist_from_signalr(
113113
# ic-dev21 not sure if this is dead code?
114114
new_devices = []
115115
for raw_device in values:
116-
LOG.debug(f"Generating device {raw_device}")
116+
LOG.debug("Generating device %s", raw_device)
117117
dev = self.generate_device(raw_device)
118118
if dev not in self.devices:
119119
self.devices.append(dev)

pyhilo/event.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ def __init__(self, **event: dict[str, Any]):
6767

6868
def update_wh(self, used_wH: float) -> None:
6969
"""This function is used to update the used_kWh attribute during a Hilo Challenge Event"""
70-
LOG.debug(f"Updating Wh: {used_wH}")
70+
LOG.debug("Updating Wh: %s", used_wH)
7171
self.used_kWh = round(used_wH / 1000, 2)
7272
self.last_update = datetime.now(timezone.utc).astimezone()
7373

pyhilo/graphql.py

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -562,14 +562,16 @@ async def subscribe_to_device_updated(
562562
query, variable_values={"locationHiloId": location_hilo_id}
563563
):
564564
LOG.debug(
565-
f"subscribe_to_device_updated: Received subscription result {result}"
565+
"subscribe_to_device_updated: Received subscription result %s",
566+
result,
566567
)
567568
device_hilo_id = self._handle_device_subscription_result(result)
568569
if callback:
569570
callback(device_hilo_id)
570571
except Exception as e:
571572
LOG.debug(
572-
f"subscribe_to_device_updated: Connection lost: {e}. Reconnecting in 5 seconds..."
573+
"subscribe_to_device_updated: Connection lost: %s. Reconnecting in 5 seconds...",
574+
e,
573575
)
574576
await asyncio.sleep(5)
575577
try:
@@ -580,7 +582,8 @@ async def subscribe_to_device_updated(
580582

581583
except Exception as e2:
582584
LOG.error(
583-
f"subscribe_to_device_updated, exception while reconnecting, retrying: {e2}"
585+
"subscribe_to_device_updated, exception while reconnecting, retrying: %s",
586+
e2,
584587
)
585588

586589
async def subscribe_to_location_updated(
@@ -597,7 +600,7 @@ async def subscribe_to_location_updated(
597600
async for result in session.subscribe(
598601
query, variable_values={"locationHiloId": location_hilo_id}
599602
):
600-
LOG.debug(f"Received subscription result {result}")
603+
LOG.debug("Received subscription result %s", result)
601604
device_hilo_id = self._handle_location_subscription_result(result)
602605
callback(device_hilo_id)
603606
except asyncio.CancelledError:
@@ -620,13 +623,13 @@ def _handle_device_subscription_result(self, result: Dict[str, Any]) -> str:
620623
attributes = self.mapper.map_device_subscription_values(devices_values)
621624
updated_device = self._devices.parse_values_received(attributes)
622625
# callback to update the device in the UI
623-
LOG.debug(f"Device updated: {updated_device}")
626+
LOG.debug("Device updated: %s", updated_device)
624627
return devices_values.get("hiloId")
625628

626629
def _handle_location_subscription_result(self, result: Dict[str, Any]) -> str:
627630
devices_values: list[any] = result["onAnyLocationUpdated"]["location"]
628631
attributes = self.mapper.map_location_subscription_values(devices_values)
629632
updated_device = self._devices.parse_values_received(attributes)
630633
# callback to update the device in the UI
631-
LOG.debug(f"Device updated: {updated_device}")
634+
LOG.debug("Device updated: %s", updated_device)
632635
return devices_values.get("hiloId")

pyhilo/websocket.py

Lines changed: 21 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -214,18 +214,22 @@ async def _async_send_json(self, payload: dict[str, Any]) -> None:
214214

215215
if self._api.log_traces:
216216
LOG.debug(
217-
f"[TRACE] Sending data to websocket {self._api.endpoint} : {json.dumps(payload)}"
217+
"[TRACE] Sending data to websocket %s : %s",
218+
self._api.endpoint,
219+
json.dumps(payload),
218220
)
219221
# Hilo added a control character (chr(30)) at the end of each payload they send.
220222
# They also expect this char to be there at the end of every payload we send them.
221-
LOG.debug(f"WebsocketClient _async_send_json payload: {payload}")
223+
LOG.debug("WebsocketClient _async_send_json payload: %s", payload)
222224
await self._client.send_str(json.dumps(payload) + chr(30))
223225

224226
def _parse_message(self, msg: dict[str, Any]) -> None:
225227
"""Parse an incoming message."""
226228
if self._api.log_traces:
227229
LOG.debug(
228-
f"[TRACE] Received message on websocket(_parse_message) {self._api.endpoint}: {msg}"
230+
"[TRACE] Received message on websocket(_parse_message) %s: %s",
231+
self._api.endpoint,
232+
msg,
229233
)
230234
if msg.get("type") == SignalRMsgType.PING:
231235
schedule_callback(self._async_pong)
@@ -272,7 +276,7 @@ async def async_connect(self) -> None:
272276

273277
LOG.info("Websocket: Connecting to server %s", self._api.endpoint)
274278
if self._api.log_traces:
275-
LOG.debug(f"[TRACE] Websocket URL: {self._api.full_ws_url}")
279+
LOG.debug("[TRACE] Websocket URL: %s", self._api.full_ws_url)
276280
headers = {
277281
"Sec-WebSocket-Extensions": "permessage-deflate; client_max_window_bits",
278282
"Pragma": "no-cache",
@@ -396,9 +400,13 @@ async def async_invoke(
396400
except asyncio.TimeoutError:
397401
return
398402
self._ready_event.clear()
399-
LOG.debug(
400-
f"async_invoke invoke argument: {arg}, invocationId: {inv_id}, target: {target}, type: {type}"
401-
)
403+
LOG.debug(
404+
"async_invoke invoke argument: %s, invocationId: %s, target: %s, type: %s",
405+
arg,
406+
inv_id,
407+
target,
408+
type,
409+
)
402410
await self._async_send_json(
403411
{
404412
"arguments": arg,
@@ -481,9 +489,9 @@ async def _negotiate(self, config: WebsocketConfig) -> Tuple[str, str]:
481489
Returns:
482490
Tuple containing the websocket URL and access token
483491
"""
484-
LOG.debug(f"Getting websocket url for {config.endpoint}")
492+
LOG.debug("Getting websocket url for %s", config.endpoint)
485493
url = f"{config.endpoint}/negotiate"
486-
LOG.debug(f"Negotiate URL is {url}")
494+
LOG.debug("Negotiate URL is %s", url)
487495

488496
resp = await self.async_request("post", url)
489497
ws_url = resp.get("url")
@@ -513,8 +521,8 @@ async def _get_websocket_params(self, config: WebsocketConfig) -> None:
513521
config: The websocket configuration to get parameters for
514522
"""
515523
uri = parse.urlparse(config.url)
516-
LOG.debug(f"Getting websocket params for {config.endpoint}")
517-
LOG.debug(f"Getting uri {uri}")
524+
LOG.debug("Getting websocket params for %s", config.endpoint)
525+
LOG.debug("Getting uri %s", uri)
518526

519527
resp = await self.async_request(
520528
"post",
@@ -529,7 +537,7 @@ async def _get_websocket_params(self, config: WebsocketConfig) -> None:
529537
config.full_ws_url = (
530538
f"{config.url}&id={config.connection_id}&access_token={config.token}"
531539
)
532-
LOG.debug(f"Getting full ws URL {config.full_ws_url}")
540+
LOG.debug("Getting full ws URL %s", config.full_ws_url)
533541

534542
transport_dict = resp.get("availableTransports", [])
535543
websocket_dict = {
@@ -544,5 +552,5 @@ async def _get_websocket_params(self, config: WebsocketConfig) -> None:
544552
if config.endpoint == AUTOMATION_DEVICEHUB_ENDPOINT
545553
else "websocketChallenges"
546554
)
547-
LOG.debug(f"Calling set_state {state_key}_params")
555+
LOG.debug("Calling set_state %s_params", state_key)
548556
await self._set_state(self._state_yaml, state_key, websocket_dict)

0 commit comments

Comments
 (0)