base.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. # switchbot-mqtt - MQTT client controlling SwitchBot button & curtain automators,
  2. # compatible with home-assistant.io's MQTT Switch & Cover platform
  3. #
  4. # Copyright (C) 2020 Fabian Peter Hammerle <fabian@hammerle.me>
  5. #
  6. # This program is free software: you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation, either version 3 of the License, or
  9. # any later version.
  10. #
  11. # This program is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with this program. If not, see <https://www.gnu.org/licenses/>.
  18. # > Even with __all__ set appropriately, internal interfaces (packages,
  19. # > modules, classes, functions, attributes or other names) should still be
  20. # > prefixed with a single leading underscore. An interface is also considered
  21. # > internal if any containing namespace (package, module or class) is
  22. # > considered internal.
  23. # https://peps.python.org/pep-0008/#public-and-internal-interfaces
  24. from __future__ import annotations # PEP563 (default in python>=3.10)
  25. import abc
  26. import logging
  27. import typing
  28. import aiomqtt
  29. import bleak
  30. import bleak.backends.device
  31. import switchbot
  32. from switchbot_mqtt._utils import (
  33. _join_mqtt_topic_levels,
  34. _mac_address_valid,
  35. _MQTTTopicLevel,
  36. _MQTTTopicPlaceholder,
  37. _parse_mqtt_topic,
  38. )
  39. _LOGGER = logging.getLogger(__name__)
  40. class _MQTTControlledActor(abc.ABC):
  41. MQTT_COMMAND_TOPIC_LEVELS: typing.Tuple[_MQTTTopicLevel, ...] = NotImplemented
  42. _MQTT_UPDATE_DEVICE_INFO_TOPIC_LEVELS: typing.Tuple[
  43. _MQTTTopicLevel, ...
  44. ] = NotImplemented
  45. MQTT_STATE_TOPIC_LEVELS: typing.Tuple[_MQTTTopicLevel, ...] = NotImplemented
  46. _MQTT_BATTERY_PERCENTAGE_TOPIC_LEVELS: typing.Tuple[
  47. _MQTTTopicLevel, ...
  48. ] = NotImplemented
  49. @classmethod
  50. def get_mqtt_update_device_info_topic(cls, *, prefix: str, mac_address: str) -> str:
  51. return _join_mqtt_topic_levels(
  52. topic_prefix=prefix,
  53. topic_levels=cls._MQTT_UPDATE_DEVICE_INFO_TOPIC_LEVELS,
  54. mac_address=mac_address,
  55. )
  56. @classmethod
  57. def get_mqtt_battery_percentage_topic(cls, *, prefix: str, mac_address: str) -> str:
  58. return _join_mqtt_topic_levels(
  59. topic_prefix=prefix,
  60. topic_levels=cls._MQTT_BATTERY_PERCENTAGE_TOPIC_LEVELS,
  61. mac_address=mac_address,
  62. )
  63. @abc.abstractmethod
  64. def __init__(
  65. self,
  66. *,
  67. device: bleak.backends.device.BLEDevice,
  68. retry_count: int,
  69. password: typing.Optional[str],
  70. ) -> None:
  71. # alternative: pySwitchbot >=0.10.0 provides SwitchbotDevice.get_mac()
  72. self._mac_address = device.address
  73. self._basic_device_info: typing.Optional[typing.Dict[str, typing.Any]] = None
  74. @abc.abstractmethod
  75. def _get_device(self) -> switchbot.SwitchbotDevice:
  76. raise NotImplementedError()
  77. async def _report_battery_level(
  78. self, mqtt_client: aiomqtt.Client, mqtt_topic_prefix: str
  79. ) -> None:
  80. assert self._basic_device_info is not None
  81. # > battery: Percentage of battery that is left.
  82. # https://www.home-assistant.io/integrations/sensor/#device-class
  83. await self._mqtt_publish(
  84. topic_prefix=mqtt_topic_prefix,
  85. topic_levels=self._MQTT_BATTERY_PERCENTAGE_TOPIC_LEVELS,
  86. payload=str(self._basic_device_info["battery"]).encode(),
  87. mqtt_client=mqtt_client,
  88. )
  89. async def _update_and_report_device_info(
  90. self, mqtt_client: aiomqtt.Client, mqtt_topic_prefix: str
  91. ) -> None:
  92. self._basic_device_info = await self._get_device().get_basic_info()
  93. if self._basic_device_info is None:
  94. _LOGGER.error(
  95. "failed to retrieve basic device info from %s", self._mac_address
  96. )
  97. else:
  98. await self._report_battery_level(
  99. mqtt_client=mqtt_client, mqtt_topic_prefix=mqtt_topic_prefix
  100. )
  101. @classmethod
  102. async def _init_from_topic(
  103. cls,
  104. *,
  105. topic: aiomqtt.Topic,
  106. mqtt_topic_prefix: str,
  107. expected_topic_levels: typing.Collection[_MQTTTopicLevel],
  108. retry_count: int,
  109. device_passwords: typing.Dict[str, str],
  110. ) -> typing.Optional[_MQTTControlledActor]:
  111. try:
  112. mac_address = _parse_mqtt_topic(
  113. topic=topic.value,
  114. expected_prefix=mqtt_topic_prefix,
  115. expected_levels=expected_topic_levels,
  116. )[_MQTTTopicPlaceholder.MAC_ADDRESS]
  117. except ValueError as exc:
  118. _LOGGER.warning(str(exc), exc_info=False)
  119. return None
  120. if not _mac_address_valid(mac_address):
  121. _LOGGER.warning("invalid mac address %s", mac_address)
  122. return None
  123. # SwitchbotBaseDevice.__init__ expects BLEDevice
  124. device = await bleak.BleakScanner.find_device_by_address(mac_address)
  125. if device is None:
  126. _LOGGER.error(
  127. "failed to find bluetooth low energy device with mac address %s",
  128. mac_address,
  129. )
  130. return None
  131. return cls(
  132. device=device,
  133. retry_count=retry_count,
  134. password=device_passwords.get(mac_address, None),
  135. )
  136. @classmethod
  137. async def _mqtt_update_device_info_callback(
  138. # pylint: disable=duplicate-code; other callbacks with same params
  139. cls,
  140. *,
  141. mqtt_client: aiomqtt.Client,
  142. message: aiomqtt.Message,
  143. mqtt_topic_prefix: str,
  144. retry_count: int,
  145. device_passwords: typing.Dict[str, str],
  146. fetch_device_info: bool,
  147. ) -> None:
  148. # pylint: disable=unused-argument; callback
  149. # https://github.com/eclipse/paho.mqtt.python/blob/v1.5.0/src/paho/mqtt/client.py#L469
  150. _LOGGER.debug("received topic=%s payload=%r", message.topic, message.payload)
  151. if message.retain:
  152. _LOGGER.info("ignoring retained message")
  153. return
  154. actor = await cls._init_from_topic(
  155. topic=message.topic,
  156. mqtt_topic_prefix=mqtt_topic_prefix,
  157. expected_topic_levels=cls._MQTT_UPDATE_DEVICE_INFO_TOPIC_LEVELS,
  158. retry_count=retry_count,
  159. device_passwords=device_passwords,
  160. )
  161. if actor:
  162. # pylint: disable=protected-access; own instance
  163. await actor._update_and_report_device_info(
  164. mqtt_client=mqtt_client, mqtt_topic_prefix=mqtt_topic_prefix
  165. )
  166. @abc.abstractmethod
  167. async def execute_command( # pylint: disable=duplicate-code; implementations
  168. self,
  169. *,
  170. mqtt_message_payload: bytes,
  171. mqtt_client: aiomqtt.Client,
  172. update_device_info: bool,
  173. mqtt_topic_prefix: str,
  174. ) -> None:
  175. raise NotImplementedError()
  176. @classmethod
  177. async def _mqtt_command_callback(
  178. # pylint: disable=duplicate-code; other callbacks with same params
  179. cls,
  180. *,
  181. mqtt_client: aiomqtt.Client,
  182. message: aiomqtt.Message,
  183. mqtt_topic_prefix: str,
  184. retry_count: int,
  185. device_passwords: typing.Dict[str, str],
  186. fetch_device_info: bool,
  187. ) -> None:
  188. # pylint: disable=unused-argument; callback
  189. # https://github.com/eclipse/paho.mqtt.python/blob/v1.5.0/src/paho/mqtt/client.py#L469
  190. _LOGGER.debug("received topic=%s payload=%r", message.topic, message.payload)
  191. if message.retain:
  192. _LOGGER.info("ignoring retained message")
  193. return
  194. actor = await cls._init_from_topic(
  195. topic=message.topic,
  196. mqtt_topic_prefix=mqtt_topic_prefix,
  197. expected_topic_levels=cls.MQTT_COMMAND_TOPIC_LEVELS,
  198. retry_count=retry_count,
  199. device_passwords=device_passwords,
  200. )
  201. if actor:
  202. assert isinstance(message.payload, bytes), message.payload
  203. await actor.execute_command(
  204. mqtt_message_payload=message.payload,
  205. mqtt_client=mqtt_client,
  206. update_device_info=fetch_device_info,
  207. mqtt_topic_prefix=mqtt_topic_prefix,
  208. )
  209. @classmethod
  210. def _get_mqtt_message_callbacks(
  211. cls,
  212. *,
  213. enable_device_info_update_topic: bool,
  214. ) -> typing.Dict[typing.Tuple[_MQTTTopicLevel, ...], typing.Callable]:
  215. # returning dict because `paho.mqtt.client.Client.message_callback_add` overwrites
  216. # callbacks with same topic pattern
  217. # https://github.com/eclipse/paho.mqtt.python/blob/v1.6.1/src/paho/mqtt/client.py#L2304
  218. # https://github.com/eclipse/paho.mqtt.python/blob/v1.6.1/src/paho/mqtt/matcher.py#L19
  219. callbacks = {cls.MQTT_COMMAND_TOPIC_LEVELS: cls._mqtt_command_callback}
  220. if enable_device_info_update_topic:
  221. callbacks[
  222. cls._MQTT_UPDATE_DEVICE_INFO_TOPIC_LEVELS
  223. ] = cls._mqtt_update_device_info_callback
  224. return callbacks
  225. @classmethod
  226. async def mqtt_subscribe(
  227. cls,
  228. *,
  229. mqtt_client: aiomqtt.Client,
  230. mqtt_topic_prefix: str,
  231. fetch_device_info: bool,
  232. ) -> typing.AsyncIterator[typing.Tuple[str, typing.Callable]]:
  233. for topic_levels, callback in cls._get_mqtt_message_callbacks(
  234. enable_device_info_update_topic=fetch_device_info
  235. ).items():
  236. topic = _join_mqtt_topic_levels(
  237. topic_prefix=mqtt_topic_prefix,
  238. topic_levels=topic_levels,
  239. mac_address="+",
  240. )
  241. _LOGGER.info("subscribing to MQTT topic %r", topic)
  242. await mqtt_client.subscribe(topic)
  243. yield (topic, callback)
  244. async def _mqtt_publish(
  245. self,
  246. *,
  247. topic_prefix: str,
  248. topic_levels: typing.Iterable[_MQTTTopicLevel],
  249. payload: bytes,
  250. mqtt_client: aiomqtt.Client,
  251. ) -> None:
  252. topic = _join_mqtt_topic_levels(
  253. topic_prefix=topic_prefix,
  254. topic_levels=topic_levels,
  255. mac_address=self._mac_address,
  256. )
  257. # https://pypi.org/project/paho-mqtt/#publishing
  258. _LOGGER.debug("publishing topic=%s payload=%r", topic, payload)
  259. try:
  260. await mqtt_client.publish(topic=topic, payload=payload, retain=True)
  261. except aiomqtt.MqttCodeError as exc:
  262. _LOGGER.error(
  263. "Failed to publish MQTT message on topic %s: aiomqtt.MqttCodeError %s",
  264. topic,
  265. exc,
  266. )
  267. async def report_state(
  268. self,
  269. state: bytes,
  270. mqtt_client: aiomqtt.Client,
  271. mqtt_topic_prefix: str,
  272. ) -> None:
  273. await self._mqtt_publish(
  274. topic_prefix=mqtt_topic_prefix,
  275. topic_levels=self.MQTT_STATE_TOPIC_LEVELS,
  276. payload=state,
  277. mqtt_client=mqtt_client,
  278. )