base.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  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. # pylint: disable=duplicate-code; other callbacks with same params
  164. cls,
  165. mqtt_client: paho.mqtt.client.Client,
  166. userdata: _MQTTCallbackUserdata,
  167. message: paho.mqtt.client.MQTTMessage,
  168. ) -> None:
  169. # pylint: disable=unused-argument; callback
  170. # https://github.com/eclipse/paho.mqtt.python/blob/v1.5.0/src/paho/mqtt/client.py#L469
  171. _LOGGER.debug("received topic=%s payload=%r", message.topic, message.payload)
  172. if message.retain:
  173. _LOGGER.info("ignoring retained message")
  174. return
  175. actor = cls._init_from_topic(
  176. topic=message.topic,
  177. expected_topic_levels=cls._MQTT_UPDATE_DEVICE_INFO_TOPIC_LEVELS,
  178. settings=userdata,
  179. )
  180. if actor:
  181. # pylint: disable=protected-access; own instance
  182. actor._update_and_report_device_info(
  183. mqtt_client=mqtt_client, mqtt_topic_prefix=userdata.mqtt_topic_prefix
  184. )
  185. @abc.abstractmethod
  186. def execute_command( # pylint: disable=duplicate-code; implementations
  187. self,
  188. *,
  189. mqtt_message_payload: bytes,
  190. mqtt_client: paho.mqtt.client.Client,
  191. update_device_info: bool,
  192. mqtt_topic_prefix: str,
  193. ) -> None:
  194. raise NotImplementedError()
  195. @classmethod
  196. def _mqtt_command_callback(
  197. # pylint: disable=duplicate-code; other callbacks with same params
  198. cls,
  199. mqtt_client: paho.mqtt.client.Client,
  200. userdata: _MQTTCallbackUserdata,
  201. message: paho.mqtt.client.MQTTMessage,
  202. ) -> None:
  203. # pylint: disable=unused-argument; callback
  204. # https://github.com/eclipse/paho.mqtt.python/blob/v1.5.0/src/paho/mqtt/client.py#L469
  205. _LOGGER.debug("received topic=%s payload=%r", message.topic, message.payload)
  206. if message.retain:
  207. _LOGGER.info("ignoring retained message")
  208. return
  209. actor = cls._init_from_topic(
  210. topic=message.topic,
  211. expected_topic_levels=cls.MQTT_COMMAND_TOPIC_LEVELS,
  212. settings=userdata,
  213. )
  214. if actor:
  215. actor.execute_command(
  216. mqtt_message_payload=message.payload,
  217. mqtt_client=mqtt_client,
  218. update_device_info=userdata.fetch_device_info,
  219. mqtt_topic_prefix=userdata.mqtt_topic_prefix,
  220. )
  221. @classmethod
  222. def _get_mqtt_message_callbacks(
  223. cls,
  224. *,
  225. enable_device_info_update_topic: bool,
  226. ) -> typing.Dict[typing.Tuple[_MQTTTopicLevel, ...], typing.Callable]:
  227. # returning dict because `paho.mqtt.client.Client.message_callback_add` overwrites
  228. # callbacks with same topic pattern
  229. # https://github.com/eclipse/paho.mqtt.python/blob/v1.6.1/src/paho/mqtt/client.py#L2304
  230. # https://github.com/eclipse/paho.mqtt.python/blob/v1.6.1/src/paho/mqtt/matcher.py#L19
  231. callbacks = {cls.MQTT_COMMAND_TOPIC_LEVELS: cls._mqtt_command_callback}
  232. if enable_device_info_update_topic:
  233. callbacks[
  234. cls._MQTT_UPDATE_DEVICE_INFO_TOPIC_LEVELS
  235. ] = cls._mqtt_update_device_info_callback
  236. return callbacks
  237. @classmethod
  238. def mqtt_subscribe(
  239. cls, *, mqtt_client: paho.mqtt.client.Client, settings: _MQTTCallbackUserdata
  240. ) -> None:
  241. for topic_levels, callback in cls._get_mqtt_message_callbacks(
  242. enable_device_info_update_topic=settings.fetch_device_info
  243. ).items():
  244. topic = _join_mqtt_topic_levels(
  245. topic_prefix=settings.mqtt_topic_prefix,
  246. topic_levels=topic_levels,
  247. mac_address="+",
  248. )
  249. _LOGGER.info("subscribing to MQTT topic %r", topic)
  250. mqtt_client.subscribe(topic)
  251. mqtt_client.message_callback_add(sub=topic, callback=callback)
  252. def _mqtt_publish(
  253. self,
  254. *,
  255. topic_prefix: str,
  256. topic_levels: typing.Iterable[_MQTTTopicLevel],
  257. payload: bytes,
  258. mqtt_client: paho.mqtt.client.Client,
  259. ) -> None:
  260. topic = _join_mqtt_topic_levels(
  261. topic_prefix=topic_prefix,
  262. topic_levels=topic_levels,
  263. mac_address=self._mac_address,
  264. )
  265. # https://pypi.org/project/paho-mqtt/#publishing
  266. _LOGGER.debug("publishing topic=%s payload=%r", topic, payload)
  267. message_info: paho.mqtt.client.MQTTMessageInfo = mqtt_client.publish(
  268. topic=topic, payload=payload, retain=True
  269. )
  270. # wait before checking status?
  271. if message_info.rc != paho.mqtt.client.MQTT_ERR_SUCCESS:
  272. _LOGGER.error(
  273. "Failed to publish MQTT message on topic %s (rc=%d)",
  274. topic,
  275. message_info.rc,
  276. )
  277. def report_state(
  278. self,
  279. state: bytes,
  280. mqtt_client: paho.mqtt.client.Client,
  281. mqtt_topic_prefix: str,
  282. ) -> None:
  283. self._mqtt_publish(
  284. topic_prefix=mqtt_topic_prefix,
  285. topic_levels=self.MQTT_STATE_TOPIC_LEVELS,
  286. payload=state,
  287. mqtt_client=mqtt_client,
  288. )