base.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  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 dataclasses
  27. import logging
  28. import queue
  29. import shlex
  30. import typing
  31. import bluepy.btle
  32. import paho.mqtt.client
  33. import switchbot
  34. from switchbot_mqtt._utils import (
  35. _join_mqtt_topic_levels,
  36. _mac_address_valid,
  37. _MQTTTopicLevel,
  38. _MQTTTopicPlaceholder,
  39. _parse_mqtt_topic,
  40. _QueueLogHandler,
  41. )
  42. _LOGGER = logging.getLogger(__name__)
  43. @dataclasses.dataclass
  44. class _MQTTCallbackUserdata:
  45. retry_count: int
  46. device_passwords: typing.Dict[str, str]
  47. fetch_device_info: bool
  48. mqtt_topic_prefix: str
  49. class _MQTTControlledActor(abc.ABC):
  50. MQTT_COMMAND_TOPIC_LEVELS: typing.Tuple[_MQTTTopicLevel, ...] = NotImplemented
  51. _MQTT_UPDATE_DEVICE_INFO_TOPIC_LEVELS: typing.Tuple[
  52. _MQTTTopicLevel, ...
  53. ] = NotImplemented
  54. MQTT_STATE_TOPIC_LEVELS: typing.Tuple[_MQTTTopicLevel, ...] = NotImplemented
  55. _MQTT_BATTERY_PERCENTAGE_TOPIC_LEVELS: typing.Tuple[
  56. _MQTTTopicLevel, ...
  57. ] = NotImplemented
  58. @classmethod
  59. def get_mqtt_update_device_info_topic(cls, *, prefix: str, mac_address: str) -> str:
  60. return _join_mqtt_topic_levels(
  61. topic_prefix=prefix,
  62. topic_levels=cls._MQTT_UPDATE_DEVICE_INFO_TOPIC_LEVELS,
  63. mac_address=mac_address,
  64. )
  65. @classmethod
  66. def get_mqtt_battery_percentage_topic(cls, *, prefix: str, mac_address: str) -> str:
  67. return _join_mqtt_topic_levels(
  68. topic_prefix=prefix,
  69. topic_levels=cls._MQTT_BATTERY_PERCENTAGE_TOPIC_LEVELS,
  70. mac_address=mac_address,
  71. )
  72. @abc.abstractmethod
  73. def __init__(
  74. self, *, mac_address: str, retry_count: int, password: typing.Optional[str]
  75. ) -> None:
  76. # alternative: pySwitchbot >=0.10.0 provides SwitchbotDevice.get_mac()
  77. self._mac_address = mac_address
  78. @abc.abstractmethod
  79. def _get_device(self) -> switchbot.SwitchbotDevice:
  80. raise NotImplementedError()
  81. def _update_device_info(self) -> None:
  82. log_queue: queue.Queue[logging.LogRecord] = queue.Queue(maxsize=0)
  83. logging.getLogger("switchbot").addHandler(_QueueLogHandler(log_queue))
  84. try:
  85. self._get_device().update()
  86. # pySwitchbot>=v0.10.1 catches bluepy.btle.BTLEManagementError :(
  87. # https://github.com/Danielhiversen/pySwitchbot/blob/0.10.1/switchbot/__init__.py#L141
  88. # pySwitchbot<0.11.0 WARNING, >=0.11.0 ERROR
  89. while not log_queue.empty():
  90. log_record = log_queue.get()
  91. if log_record.exc_info:
  92. exc: typing.Optional[BaseException] = log_record.exc_info[1]
  93. if (
  94. isinstance(exc, bluepy.btle.BTLEManagementError)
  95. and exc.emsg == "Permission Denied"
  96. ):
  97. raise exc
  98. except bluepy.btle.BTLEManagementError as exc:
  99. if (
  100. exc.emsg == "Permission Denied"
  101. and exc.message == "Failed to execute management command 'le on'"
  102. ):
  103. raise PermissionError(
  104. "bluepy-helper failed to enable low energy mode"
  105. " due to insufficient permissions."
  106. "\nSee https://github.com/IanHarvey/bluepy/issues/313#issuecomment-428324639"
  107. ", https://github.com/fphammerle/switchbot-mqtt/pull/31#issuecomment-846383603"
  108. ", and https://github.com/IanHarvey/bluepy/blob/v/1.3.0/bluepy"
  109. "/bluepy-helper.c#L1260."
  110. "\nInsecure workaround:"
  111. "\n1. sudo apt-get install --no-install-recommends libcap2-bin"
  112. f"\n2. sudo setcap cap_net_admin+ep {shlex.quote(bluepy.btle.helperExe)}"
  113. "\n3. restart switchbot-mqtt"
  114. "\nIn docker-based setups, you could use"
  115. " `sudo docker run --cap-drop ALL --cap-add NET_ADMIN --user 0 …`"
  116. " (seriously insecure)."
  117. ) from exc
  118. raise
  119. def _report_battery_level(
  120. self, mqtt_client: paho.mqtt.client.Client, mqtt_topic_prefix: str
  121. ) -> None:
  122. # > battery: Percentage of battery that is left.
  123. # https://www.home-assistant.io/integrations/sensor/#device-class
  124. self._mqtt_publish(
  125. topic_prefix=mqtt_topic_prefix,
  126. topic_levels=self._MQTT_BATTERY_PERCENTAGE_TOPIC_LEVELS,
  127. payload=str(self._get_device().get_battery_percent()).encode(),
  128. mqtt_client=mqtt_client,
  129. )
  130. def _update_and_report_device_info(
  131. self, mqtt_client: paho.mqtt.client.Client, mqtt_topic_prefix: str
  132. ) -> None:
  133. self._update_device_info()
  134. self._report_battery_level(
  135. mqtt_client=mqtt_client, mqtt_topic_prefix=mqtt_topic_prefix
  136. )
  137. @classmethod
  138. def _init_from_topic(
  139. cls,
  140. topic: str,
  141. expected_topic_levels: typing.Collection[_MQTTTopicLevel],
  142. settings: _MQTTCallbackUserdata,
  143. ) -> typing.Optional[_MQTTControlledActor]:
  144. try:
  145. mac_address = _parse_mqtt_topic(
  146. topic=topic,
  147. expected_prefix=settings.mqtt_topic_prefix,
  148. expected_levels=expected_topic_levels,
  149. )[_MQTTTopicPlaceholder.MAC_ADDRESS]
  150. except ValueError as exc:
  151. _LOGGER.warning(str(exc), exc_info=False)
  152. return None
  153. if not _mac_address_valid(mac_address):
  154. _LOGGER.warning("invalid mac address %s", mac_address)
  155. return None
  156. return cls(
  157. mac_address=mac_address,
  158. retry_count=settings.retry_count,
  159. password=settings.device_passwords.get(mac_address, None),
  160. )
  161. @classmethod
  162. def _mqtt_update_device_info_callback(
  163. cls,
  164. mqtt_client: paho.mqtt.client.Client,
  165. userdata: _MQTTCallbackUserdata,
  166. message: paho.mqtt.client.MQTTMessage,
  167. ) -> None:
  168. # pylint: disable=unused-argument; callback
  169. # https://github.com/eclipse/paho.mqtt.python/blob/v1.5.0/src/paho/mqtt/client.py#L469
  170. _LOGGER.debug("received topic=%s payload=%r", message.topic, message.payload)
  171. if message.retain:
  172. _LOGGER.info("ignoring retained message")
  173. return
  174. actor = cls._init_from_topic(
  175. topic=message.topic,
  176. expected_topic_levels=cls._MQTT_UPDATE_DEVICE_INFO_TOPIC_LEVELS,
  177. settings=userdata,
  178. )
  179. if actor:
  180. # pylint: disable=protected-access; own instance
  181. actor._update_and_report_device_info(
  182. mqtt_client=mqtt_client, mqtt_topic_prefix=userdata.mqtt_topic_prefix
  183. )
  184. @abc.abstractmethod
  185. def execute_command(
  186. self,
  187. *,
  188. mqtt_message_payload: bytes,
  189. mqtt_client: paho.mqtt.client.Client,
  190. update_device_info: bool,
  191. mqtt_topic_prefix: str,
  192. ) -> None:
  193. raise NotImplementedError()
  194. @classmethod
  195. def _mqtt_command_callback(
  196. cls,
  197. mqtt_client: paho.mqtt.client.Client,
  198. userdata: _MQTTCallbackUserdata,
  199. message: paho.mqtt.client.MQTTMessage,
  200. ) -> None:
  201. # pylint: disable=unused-argument; callback
  202. # https://github.com/eclipse/paho.mqtt.python/blob/v1.5.0/src/paho/mqtt/client.py#L469
  203. _LOGGER.debug("received topic=%s payload=%r", message.topic, message.payload)
  204. if message.retain:
  205. _LOGGER.info("ignoring retained message")
  206. return
  207. actor = cls._init_from_topic(
  208. topic=message.topic,
  209. expected_topic_levels=cls.MQTT_COMMAND_TOPIC_LEVELS,
  210. settings=userdata,
  211. )
  212. if actor:
  213. actor.execute_command(
  214. mqtt_message_payload=message.payload,
  215. mqtt_client=mqtt_client,
  216. update_device_info=userdata.fetch_device_info,
  217. mqtt_topic_prefix=userdata.mqtt_topic_prefix,
  218. )
  219. @classmethod
  220. def _get_mqtt_message_callbacks(
  221. cls,
  222. *,
  223. enable_device_info_update_topic: bool,
  224. ) -> typing.Dict[typing.Tuple[_MQTTTopicLevel, ...], typing.Callable]:
  225. # returning dict because `paho.mqtt.client.Client.message_callback_add` overwrites
  226. # callbacks with same topic pattern
  227. # https://github.com/eclipse/paho.mqtt.python/blob/v1.6.1/src/paho/mqtt/client.py#L2304
  228. # https://github.com/eclipse/paho.mqtt.python/blob/v1.6.1/src/paho/mqtt/matcher.py#L19
  229. callbacks = {cls.MQTT_COMMAND_TOPIC_LEVELS: cls._mqtt_command_callback}
  230. if enable_device_info_update_topic:
  231. callbacks[
  232. cls._MQTT_UPDATE_DEVICE_INFO_TOPIC_LEVELS
  233. ] = cls._mqtt_update_device_info_callback
  234. return callbacks
  235. @classmethod
  236. def mqtt_subscribe(
  237. cls, *, mqtt_client: paho.mqtt.client.Client, settings: _MQTTCallbackUserdata
  238. ) -> None:
  239. for topic_levels, callback in cls._get_mqtt_message_callbacks(
  240. enable_device_info_update_topic=settings.fetch_device_info
  241. ).items():
  242. topic = _join_mqtt_topic_levels(
  243. topic_prefix=settings.mqtt_topic_prefix,
  244. topic_levels=topic_levels,
  245. mac_address="+",
  246. )
  247. _LOGGER.info("subscribing to MQTT topic %r", topic)
  248. mqtt_client.subscribe(topic)
  249. mqtt_client.message_callback_add(sub=topic, callback=callback)
  250. def _mqtt_publish(
  251. self,
  252. *,
  253. topic_prefix: str,
  254. topic_levels: typing.Iterable[_MQTTTopicLevel],
  255. payload: bytes,
  256. mqtt_client: paho.mqtt.client.Client,
  257. ) -> None:
  258. topic = _join_mqtt_topic_levels(
  259. topic_prefix=topic_prefix,
  260. topic_levels=topic_levels,
  261. mac_address=self._mac_address,
  262. )
  263. # https://pypi.org/project/paho-mqtt/#publishing
  264. _LOGGER.debug("publishing topic=%s payload=%r", topic, payload)
  265. message_info: paho.mqtt.client.MQTTMessageInfo = mqtt_client.publish(
  266. topic=topic, payload=payload, retain=True
  267. )
  268. # wait before checking status?
  269. if message_info.rc != paho.mqtt.client.MQTT_ERR_SUCCESS:
  270. _LOGGER.error(
  271. "Failed to publish MQTT message on topic %s (rc=%d)",
  272. topic,
  273. message_info.rc,
  274. )
  275. def report_state(
  276. self,
  277. state: bytes,
  278. mqtt_client: paho.mqtt.client.Client,
  279. mqtt_topic_prefix: str,
  280. ) -> None:
  281. self._mqtt_publish(
  282. topic_prefix=mqtt_topic_prefix,
  283. topic_levels=self.MQTT_STATE_TOPIC_LEVELS,
  284. payload=state,
  285. mqtt_client=mqtt_client,
  286. )