|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import asyncio |
| 4 | +import dataclasses |
| 5 | +import logging |
| 6 | +from collections.abc import Coroutine |
| 7 | +from typing import Callable, Self |
| 8 | +from urllib.parse import urlparse |
| 9 | + |
| 10 | +import aiomqtt |
| 11 | +from aiomqtt import TLSParameters |
| 12 | + |
| 13 | +from roborock import RoborockException, UserData |
| 14 | +from roborock.protocol import MessageParser, md5hex |
| 15 | + |
| 16 | +from .containers import DeviceData |
| 17 | + |
| 18 | +LOGGER = logging.getLogger(__name__) |
| 19 | + |
| 20 | + |
| 21 | +@dataclasses.dataclass |
| 22 | +class ClientWrapper: |
| 23 | + publish_function: Coroutine[None] |
| 24 | + unsubscribe_function: Coroutine[None] |
| 25 | + subscribe_function: Coroutine[None] |
| 26 | + |
| 27 | + |
| 28 | +class RoborockMqttManager: |
| 29 | + client_wrappers: dict[str, ClientWrapper] = {} |
| 30 | + _instance: Self = None |
| 31 | + |
| 32 | + def __new__(cls) -> RoborockMqttManager: |
| 33 | + if cls._instance is None: |
| 34 | + cls._instance = super().__new__(cls) |
| 35 | + return cls._instance |
| 36 | + |
| 37 | + async def connect(self, user_data: UserData): |
| 38 | + # Add some kind of lock so we don't try to connect if we are already trying to connect the same account. |
| 39 | + if user_data.rriot.u not in self.client_wrappers: |
| 40 | + loop = asyncio.get_event_loop() |
| 41 | + loop.create_task(self._new_connect(user_data)) |
| 42 | + |
| 43 | + async def _new_connect(self, user_data: UserData): |
| 44 | + rriot = user_data.rriot |
| 45 | + mqtt_user = rriot.u |
| 46 | + hashed_user = md5hex(mqtt_user + ":" + rriot.k)[2:10] |
| 47 | + url = urlparse(rriot.r.m) |
| 48 | + if not isinstance(url.hostname, str): |
| 49 | + raise RoborockException("Url parsing returned an invalid hostname") |
| 50 | + mqtt_host = str(url.hostname) |
| 51 | + mqtt_port = url.port |
| 52 | + |
| 53 | + mqtt_password = rriot.s |
| 54 | + hashed_password = md5hex(mqtt_password + ":" + rriot.k)[16:] |
| 55 | + LOGGER.debug("Connecting to %s for %s", mqtt_host, mqtt_user) |
| 56 | + |
| 57 | + async with aiomqtt.Client( |
| 58 | + hostname=mqtt_host, |
| 59 | + port=mqtt_port, |
| 60 | + username=hashed_user, |
| 61 | + password=hashed_password, |
| 62 | + keepalive=60, |
| 63 | + tls_params=TLSParameters(), |
| 64 | + ) as client: |
| 65 | + # TODO: Handle logic for when client loses connection |
| 66 | + LOGGER.info("Connected to %s for %s", mqtt_host, mqtt_user) |
| 67 | + callbacks: dict[str, Callable] = {} |
| 68 | + device_map = {} |
| 69 | + |
| 70 | + async def publish(device: DeviceData, payload: bytes): |
| 71 | + await client.publish(f"rr/m/i/{mqtt_user}/{hashed_user}/{device.device.duid}", payload=payload) |
| 72 | + |
| 73 | + async def subscribe(device: DeviceData, callback): |
| 74 | + LOGGER.debug(f"Subscribing to rr/m/o/{mqtt_user}/{hashed_user}/{device.device.duid}") |
| 75 | + await client.subscribe(f"rr/m/o/{mqtt_user}/{hashed_user}/{device.device.duid}") |
| 76 | + LOGGER.debug(f"Subscribed to rr/m/o/{mqtt_user}/{hashed_user}/{device.device.duid}") |
| 77 | + callbacks[device.device.duid] = callback |
| 78 | + device_map[device.device.duid] = device |
| 79 | + return |
| 80 | + |
| 81 | + async def unsubscribe(device: DeviceData): |
| 82 | + await client.unsubscribe(f"rr/m/o/{mqtt_user}/{hashed_user}/{device.device.duid}") |
| 83 | + |
| 84 | + self.client_wrappers[user_data.rriot.u] = ClientWrapper( |
| 85 | + publish_function=publish, unsubscribe_function=unsubscribe, subscribe_function=subscribe |
| 86 | + ) |
| 87 | + async for message in client.messages: |
| 88 | + try: |
| 89 | + device_id = message.topic.value.split("/")[-1] |
| 90 | + device = device_map[device_id] |
| 91 | + message = MessageParser.parse(message.payload, device.device.local_key) |
| 92 | + callbacks[device_id](message) |
| 93 | + except Exception: |
| 94 | + ... |
| 95 | + |
| 96 | + async def disconnect(self, user_data: UserData): |
| 97 | + await self.client_wrappers[user_data.rriot.u].disconnect() |
| 98 | + |
| 99 | + async def subscribe(self, user_data: UserData, device: DeviceData, callback): |
| 100 | + if user_data.rriot.u not in self.client_wrappers: |
| 101 | + await self.connect(user_data) |
| 102 | + # add some kind of lock to make sure we don't subscribe until the connection is successful |
| 103 | + await asyncio.sleep(2) |
| 104 | + await self.client_wrappers[user_data.rriot.u].subscribe_function(device, callback) |
| 105 | + |
| 106 | + async def unsubscribe(self): |
| 107 | + pass |
| 108 | + |
| 109 | + async def publish(self, user_data: UserData, device, payload: bytes): |
| 110 | + LOGGER.debug("Publishing topic for %s, Message: %s", device.device.duid, payload) |
| 111 | + if user_data.rriot.u not in self.client_wrappers: |
| 112 | + await self.connect(user_data) |
| 113 | + await self.client_wrappers[user_data.rriot.u].publish_function(device, payload) |
0 commit comments