Skip to content

Commit 7690d56

Browse files
authored
feat: add device name to logs (#100)
1 parent c791a0c commit 7690d56

File tree

4 files changed

+45
-28
lines changed

4 files changed

+45
-28
lines changed

roborock/api.py

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@
6464
RoborockMessageProtocol,
6565
)
6666
from .roborock_typing import DeviceProp, DockSummary, RoborockCommand
67-
from .util import RepeatableTask, get_running_loop_or_create_one, unpack_list
67+
from .util import RepeatableTask, RoborockLoggerAdapter, get_running_loop_or_create_one, unpack_list
6868

6969
_LOGGER = logging.getLogger(__name__)
7070
KEEPALIVE = 60
@@ -166,6 +166,7 @@ def __init__(self, endpoint: str, device_info: DeviceData) -> None:
166166
self._last_disconnection = self.time_func()
167167
self.keep_alive = KEEPALIVE
168168
self._diagnostic_data: dict[str, dict[str, Any]] = {}
169+
self._logger = RoborockLoggerAdapter(device_info.device.name, _LOGGER)
169170
cache = device_cache.get(device_info.device.duid)
170171
if not cache:
171172
cache = {
@@ -240,13 +241,13 @@ def on_message_received(self, messages: list[RoborockMessage]) -> None:
240241
else:
241242
try:
242243
data_protocol = RoborockDataProtocol(int(data_point_number))
243-
_LOGGER.debug(f"Got device update for {data_protocol.name}: {data_point}")
244+
self._logger.debug(f"Got device update for {data_protocol.name}: {data_point}")
244245
if data_protocol in ROBOROCK_DATA_STATUS_PROTOCOL:
245246
_cls: Type[Status] = ModelStatus.get(
246247
self.device_info.model, S7MaxVStatus
247248
) # Default to S7 MAXV if we don't have the data
248249
if self.cache[CacheableAttribute.status].value is None:
249-
_LOGGER.debug(
250+
self._logger.debug(
250251
f"Got status update({data_protocol.name}) before get_status was called."
251252
)
252253
self.cache[CacheableAttribute.status]._value = {}
@@ -257,7 +258,7 @@ def on_message_received(self, messages: list[RoborockMessage]) -> None:
257258
listener(CacheableAttribute.status, status)
258259
elif data_protocol in ROBOROCK_DATA_CONSUMABLE_PROTOCOL:
259260
if self.cache[CacheableAttribute.consumable].value is None:
260-
_LOGGER.debug(
261+
self._logger.debug(
261262
f"Got consumable update({data_protocol.name}) before get_status was called."
262263
)
263264
self.cache[CacheableAttribute.consumable]._value = {}
@@ -270,7 +271,7 @@ def on_message_received(self, messages: list[RoborockMessage]) -> None:
270271
except ValueError:
271272
pass
272273
dps = {data_point_number: data_point}
273-
_LOGGER.debug(f"Got unknown data point {dps}")
274+
self._logger.debug(f"Got unknown data point {dps}")
274275
elif data.payload and protocol == RoborockMessageProtocol.MAP_RESPONSE:
275276
payload = data.payload[0:24]
276277
[endpoint, _, request_id, _] = struct.unpack("<8s8sH6s", payload)
@@ -287,13 +288,13 @@ def on_message_received(self, messages: list[RoborockMessage]) -> None:
287288
if queue:
288289
queue.resolve((data.payload, None))
289290
except Exception as ex:
290-
_LOGGER.exception(ex)
291+
self._logger.exception(ex)
291292

292293
def on_connection_lost(self, exc: Optional[Exception]) -> None:
293294
self._last_disconnection = self.time_func()
294-
_LOGGER.info("Roborock client disconnected")
295+
self._logger.info("Roborock client disconnected")
295296
if exc is not None:
296-
_LOGGER.warning(exc)
297+
self._logger.warning(exc)
297298

298299
def should_keepalive(self) -> bool:
299300
now = self.time_func()

roborock/cloud_api.py

Lines changed: 15 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
from .roborock_future import RoborockFuture
1818
from .roborock_message import RoborockMessage, RoborockMessageProtocol
1919
from .roborock_typing import RoborockCommand
20+
from .util import RoborockLoggerAdapter
2021

2122
_LOGGER = logging.getLogger(__name__)
2223
CONNECT_REQUEST_ID = 0
@@ -34,6 +35,7 @@ def __init__(self, user_data: UserData, device_info: DeviceData) -> None:
3435
endpoint = base64.b64encode(Utils.md5(rriot.k.encode())[8:14]).decode()
3536
RoborockClient.__init__(self, endpoint, device_info)
3637
mqtt.Client.__init__(self, protocol=mqtt.MQTTv5)
38+
self._logger = RoborockLoggerAdapter(device_info.device.name, _LOGGER)
3739
self._mqtt_user = rriot.u
3840
self._hashed_user = md5hex(self._mqtt_user + ":" + rriot.k)[2:10]
3941
url = urlparse(rriot.r.m)
@@ -57,20 +59,20 @@ def on_connect(self, *args, **kwargs):
5759
connection_queue = self._waiting_queue.get(CONNECT_REQUEST_ID)
5860
if rc != mqtt.MQTT_ERR_SUCCESS:
5961
message = f"Failed to connect ({mqtt.error_string(rc)})"
60-
_LOGGER.error(message)
62+
self._logger.error(message)
6163
if connection_queue:
6264
connection_queue.resolve((None, VacuumError(message)))
6365
return
64-
_LOGGER.info(f"Connected to mqtt {self._mqtt_host}:{self._mqtt_port}")
66+
self._logger.info(f"Connected to mqtt {self._mqtt_host}:{self._mqtt_port}")
6567
topic = f"rr/m/o/{self._mqtt_user}/{self._hashed_user}/{self.device_info.device.duid}"
6668
(result, mid) = self.subscribe(topic)
6769
if result != 0:
6870
message = f"Failed to subscribe ({mqtt.error_string(rc)})"
69-
_LOGGER.error(message)
71+
self._logger.error(message)
7072
if connection_queue:
7173
connection_queue.resolve((None, VacuumError(message)))
7274
return
73-
_LOGGER.info(f"Subscribed to topic {topic}")
75+
self._logger.info(f"Subscribed to topic {topic}")
7476
if connection_queue:
7577
connection_queue.resolve((True, None))
7678

@@ -80,7 +82,7 @@ def on_message(self, *args, **kwargs):
8082
messages, _ = MessageParser.parse(msg.payload, local_key=self.device_info.device.local_key)
8183
super().on_message_received(messages)
8284
except Exception as ex:
83-
_LOGGER.exception(ex)
85+
self._logger.exception(ex)
8486

8587
def on_disconnect(self, *args, **kwargs):
8688
_, __, rc, ___ = args
@@ -93,26 +95,26 @@ def on_disconnect(self, *args, **kwargs):
9395
if connection_queue:
9496
connection_queue.resolve((True, None))
9597
except Exception as ex:
96-
_LOGGER.exception(ex)
98+
self._logger.exception(ex)
9799

98100
def update_client_id(self):
99101
self._client_id = mqtt.base62(uuid.uuid4().int, padding=22)
100102

101103
def sync_stop_loop(self) -> None:
102104
if self._thread:
103-
_LOGGER.info("Stopping mqtt loop")
105+
self._logger.info("Stopping mqtt loop")
104106
super().loop_stop()
105107

106108
def sync_start_loop(self) -> None:
107109
if not self._thread or not self._thread.is_alive():
108110
self.sync_stop_loop()
109-
_LOGGER.info("Starting mqtt loop")
111+
self._logger.info("Starting mqtt loop")
110112
super().loop_start()
111113

112114
def sync_disconnect(self) -> bool:
113115
rc = mqtt.MQTT_ERR_AGAIN
114116
if self.is_connected():
115-
_LOGGER.info("Disconnecting from mqtt")
117+
self._logger.info("Disconnecting from mqtt")
116118
rc = super().disconnect()
117119
if rc not in [mqtt.MQTT_ERR_SUCCESS, mqtt.MQTT_ERR_NO_CONN]:
118120
raise RoborockException(f"Failed to disconnect ({mqtt.error_string(rc)})")
@@ -123,7 +125,7 @@ def sync_connect(self) -> bool:
123125
if should_connect:
124126
if self._mqtt_port is None or self._mqtt_host is None:
125127
raise RoborockException("Mqtt information was not entered. Cannot connect.")
126-
_LOGGER.info("Connecting to mqtt")
128+
self._logger.info("Connecting to mqtt")
127129
super().connect(host=self._mqtt_host, port=self._mqtt_port, keepalive=KEEPALIVE)
128130
self.sync_start_loop()
129131
return should_connect
@@ -162,7 +164,7 @@ async def send_message(self, roborock_message: RoborockMessage):
162164

163165
local_key = self.device_info.device.local_key
164166
msg = MessageParser.build(roborock_message, local_key, False)
165-
_LOGGER.debug(f"id={request_id} Requesting method {method} with {params}")
167+
self._logger.debug(f"id={request_id} Requesting method {method} with {params}")
166168
self._send_msg_raw(msg)
167169
(response, err) = await self._async_response(request_id, response_protocol)
168170
self._diagnostic_data[method if method is not None else "unknown"] = {
@@ -173,9 +175,9 @@ async def send_message(self, roborock_message: RoborockMessage):
173175
if err:
174176
raise CommandVacuumError(method, err) from err
175177
if response_protocol == RoborockMessageProtocol.MAP_RESPONSE:
176-
_LOGGER.debug(f"id={request_id} Response from {method}: {len(response)} bytes")
178+
self._logger.debug(f"id={request_id} Response from {method}: {len(response)} bytes")
177179
else:
178-
_LOGGER.debug(f"id={request_id} Response from {method}: {response}")
180+
self._logger.debug(f"id={request_id} Response from {method}: {response}")
179181
return response
180182

181183
async def _send_command(

roborock/local_api.py

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
from .protocol import MessageParser
1414
from .roborock_message import MessageRetry, RoborockMessage, RoborockMessageProtocol
1515
from .roborock_typing import RoborockCommand
16+
from .util import RoborockLoggerAdapter
1617

1718
_LOGGER = logging.getLogger(__name__)
1819

@@ -29,6 +30,7 @@ def __init__(self, device_data: DeviceData):
2930
self.transport: Transport | None = None
3031
self._mutex = Lock()
3132
self.keep_alive_task: TimerHandle | None = None
33+
self._logger = RoborockLoggerAdapter(device_data.device.name, _LOGGER)
3234

3335
def data_received(self, message):
3436
if self.remaining:
@@ -58,11 +60,11 @@ async def async_connect(self) -> None:
5860
if not self.is_connected():
5961
self.sync_disconnect()
6062
async with async_timeout.timeout(QUEUE_TIMEOUT):
61-
_LOGGER.info(f"Connecting to {self.host}")
63+
self._logger.info(f"Connecting to {self.host}")
6264
self.transport, _ = await self.event_loop.create_connection( # type: ignore
6365
lambda: self, self.host, 58867
6466
)
65-
_LOGGER.info(f"Connected to {self.host}")
67+
self._logger.info(f"Connected to {self.host}")
6668
should_ping = True
6769
except BaseException as e:
6870
raise RoborockConnectionException(f"Failed connecting to {self.host}") from e
@@ -72,7 +74,7 @@ async def async_connect(self) -> None:
7274

7375
def sync_disconnect(self) -> None:
7476
if self.transport and self.event_loop.is_running():
75-
_LOGGER.debug(f"Disconnecting from {self.host}")
77+
self._logger.debug(f"Disconnecting from {self.host}")
7678
self.transport.close()
7779
if self.keep_alive_task:
7880
self.keep_alive_task.cancel()
@@ -104,7 +106,7 @@ async def hello(self):
104106
)
105107
)
106108
except Exception as e:
107-
_LOGGER.error(e)
109+
self._logger.error(e)
108110

109111
async def ping(self):
110112
request_id = 2
@@ -149,7 +151,7 @@ async def send_message(self, roborock_message: RoborockMessage):
149151
local_key = self.device_info.device.local_key
150152
msg = MessageParser.build(roborock_message, local_key=local_key)
151153
if method:
152-
_LOGGER.debug(f"id={request_id} Requesting method {method} with {params}")
154+
self._logger.debug(f"id={request_id} Requesting method {method} with {params}")
153155
# Send the command to the Roborock device
154156
self._send_msg_raw(msg)
155157
(response, err) = await self._async_response(request_id, response_protocol)
@@ -161,7 +163,7 @@ async def send_message(self, roborock_message: RoborockMessage):
161163
if err:
162164
raise CommandVacuumError(method, err) from err
163165
if roborock_message.protocol == RoborockMessageProtocol.GENERAL_REQUEST:
164-
_LOGGER.debug(f"id={request_id} Response from method {roborock_message.get_method()}: {response}")
166+
self._logger.debug(f"id={request_id} Response from method {roborock_message.get_method()}: {response}")
165167
if response == "retry":
166168
retry_id = roborock_message.get_retry_id()
167169
return self.send_command(

roborock/util.py

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,10 @@
33
import asyncio
44
import datetime
55
import functools
6+
import logging
67
from asyncio import AbstractEventLoop, TimerHandle
7-
from typing import Callable, Coroutine, Optional, Tuple, TypeVar
8+
from collections.abc import MutableMapping
9+
from typing import Any, Callable, Coroutine, Optional, Tuple, TypeVar
810

911
from roborock import RoborockException
1012

@@ -97,3 +99,13 @@ def cancel(self):
9799
async def reset(self):
98100
self.cancel()
99101
return await self._run_task()
102+
103+
104+
class RoborockLoggerAdapter(logging.LoggerAdapter):
105+
def __init__(self, prefix: str, logger: logging.Logger) -> None:
106+
107+
super().__init__(logger, {})
108+
self.prefix = prefix
109+
110+
def process(self, msg: str, kwargs: MutableMapping[str, Any]) -> tuple[str, MutableMapping[str, Any]]:
111+
return "[%s] %s" % (self.prefix, msg), kwargs

0 commit comments

Comments
 (0)