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. # "homeassistant/" for historic reasons.
  49. # will be parametrized via command-line argument in the future.
  50. mqtt_topic_prefix: str = "homeassistant/"
  51. class _MQTTControlledActor(abc.ABC):
  52. MQTT_COMMAND_TOPIC_LEVELS: typing.Tuple[_MQTTTopicLevel, ...] = NotImplemented
  53. _MQTT_UPDATE_DEVICE_INFO_TOPIC_LEVELS: typing.Tuple[
  54. _MQTTTopicLevel, ...
  55. ] = NotImplemented
  56. MQTT_STATE_TOPIC_LEVELS: typing.Tuple[_MQTTTopicLevel, ...] = NotImplemented
  57. _MQTT_BATTERY_PERCENTAGE_TOPIC_LEVELS: typing.Tuple[
  58. _MQTTTopicLevel, ...
  59. ] = NotImplemented
  60. @classmethod
  61. def get_mqtt_update_device_info_topic(cls, *, prefix: str, mac_address: str) -> str:
  62. return _join_mqtt_topic_levels(
  63. topic_prefix=prefix,
  64. topic_levels=cls._MQTT_UPDATE_DEVICE_INFO_TOPIC_LEVELS,
  65. mac_address=mac_address,
  66. )
  67. @classmethod
  68. def get_mqtt_battery_percentage_topic(cls, *, prefix: str, mac_address: str) -> str:
  69. return _join_mqtt_topic_levels(
  70. topic_prefix=prefix,
  71. topic_levels=cls._MQTT_BATTERY_PERCENTAGE_TOPIC_LEVELS,
  72. mac_address=mac_address,
  73. )
  74. @abc.abstractmethod
  75. def __init__(
  76. self, *, mac_address: str, retry_count: int, password: typing.Optional[str]
  77. ) -> None:
  78. # alternative: pySwitchbot >=0.10.0 provides SwitchbotDevice.get_mac()
  79. self._mac_address = mac_address
  80. @abc.abstractmethod
  81. def _get_device(self) -> switchbot.SwitchbotDevice:
  82. raise NotImplementedError()
  83. def _update_device_info(self) -> None:
  84. log_queue: queue.Queue[logging.LogRecord] = queue.Queue(maxsize=0)
  85. logging.getLogger("switchbot").addHandler(_QueueLogHandler(log_queue))
  86. try:
  87. self._get_device().update()
  88. # pySwitchbot>=v0.10.1 catches bluepy.btle.BTLEManagementError :(
  89. # https://github.com/Danielhiversen/pySwitchbot/blob/0.10.1/switchbot/__init__.py#L141
  90. # pySwitchbot<0.11.0 WARNING, >=0.11.0 ERROR
  91. while not log_queue.empty():
  92. log_record = log_queue.get()
  93. if log_record.exc_info:
  94. exc: typing.Optional[BaseException] = log_record.exc_info[1]
  95. if (
  96. isinstance(exc, bluepy.btle.BTLEManagementError)
  97. and exc.emsg == "Permission Denied"
  98. ):
  99. raise exc
  100. except bluepy.btle.BTLEManagementError as exc:
  101. if (
  102. exc.emsg == "Permission Denied"
  103. and exc.message == "Failed to execute management command 'le on'"
  104. ):
  105. raise PermissionError(
  106. "bluepy-helper failed to enable low energy mode"
  107. " due to insufficient permissions."
  108. "\nSee https://github.com/IanHarvey/bluepy/issues/313#issuecomment-428324639"
  109. ", https://github.com/fphammerle/switchbot-mqtt/pull/31#issuecomment-846383603"
  110. ", and https://github.com/IanHarvey/bluepy/blob/v/1.3.0/bluepy"
  111. "/bluepy-helper.c#L1260."
  112. "\nInsecure workaround:"
  113. "\n1. sudo apt-get install --no-install-recommends libcap2-bin"
  114. f"\n2. sudo setcap cap_net_admin+ep {shlex.quote(bluepy.btle.helperExe)}"
  115. "\n3. restart switchbot-mqtt"
  116. "\nIn docker-based setups, you could use"
  117. " `sudo docker run --cap-drop ALL --cap-add NET_ADMIN --user 0 …`"
  118. " (seriously insecure)."
  119. ) from exc
  120. raise
  121. def _report_battery_level(
  122. self, mqtt_client: paho.mqtt.client.Client, mqtt_topic_prefix: str
  123. ) -> None:
  124. # > battery: Percentage of battery that is left.
  125. # https://www.home-assistant.io/integrations/sensor/#device-class
  126. self._mqtt_publish(
  127. topic_prefix=mqtt_topic_prefix,
  128. topic_levels=self._MQTT_BATTERY_PERCENTAGE_TOPIC_LEVELS,
  129. payload=str(self._get_device().get_battery_percent()).encode(),
  130. mqtt_client=mqtt_client,
  131. )
  132. def _update_and_report_device_info(
  133. self, mqtt_client: paho.mqtt.client.Client, mqtt_topic_prefix: str
  134. ) -> None:
  135. self._update_device_info()
  136. self._report_battery_level(
  137. mqtt_client=mqtt_client, mqtt_topic_prefix=mqtt_topic_prefix
  138. )
  139. @classmethod
  140. def _init_from_topic(
  141. cls,
  142. topic: str,
  143. expected_topic_levels: typing.Collection[_MQTTTopicLevel],
  144. settings: _MQTTCallbackUserdata,
  145. ) -> typing.Optional[_MQTTControlledActor]:
  146. try:
  147. mac_address = _parse_mqtt_topic(
  148. topic=topic,
  149. expected_prefix=settings.mqtt_topic_prefix,
  150. expected_levels=expected_topic_levels,
  151. )[_MQTTTopicPlaceholder.MAC_ADDRESS]
  152. except ValueError as exc:
  153. _LOGGER.warning(str(exc), exc_info=False)
  154. return None
  155. if not _mac_address_valid(mac_address):
  156. _LOGGER.warning("invalid mac address %s", mac_address)
  157. return None
  158. return cls(
  159. mac_address=mac_address,
  160. retry_count=settings.retry_count,
  161. password=settings.device_passwords.get(mac_address, None),
  162. )
  163. @classmethod
  164. def _mqtt_update_device_info_callback(
  165. cls,
  166. mqtt_client: paho.mqtt.client.Client,
  167. userdata: _MQTTCallbackUserdata,
  168. message: paho.mqtt.client.MQTTMessage,
  169. ) -> None:
  170. # pylint: disable=unused-argument; callback
  171. # https://github.com/eclipse/paho.mqtt.python/blob/v1.5.0/src/paho/mqtt/client.py#L469
  172. _LOGGER.debug("received topic=%s payload=%r", message.topic, message.payload)
  173. if message.retain:
  174. _LOGGER.info("ignoring retained message")
  175. return
  176. actor = cls._init_from_topic(
  177. topic=message.topic,
  178. expected_topic_levels=cls._MQTT_UPDATE_DEVICE_INFO_TOPIC_LEVELS,
  179. settings=userdata,
  180. )
  181. if actor:
  182. # pylint: disable=protected-access; own instance
  183. actor._update_and_report_device_info(
  184. mqtt_client=mqtt_client, mqtt_topic_prefix=userdata.mqtt_topic_prefix
  185. )
  186. @abc.abstractmethod
  187. def execute_command(
  188. self,
  189. *,
  190. mqtt_message_payload: bytes,
  191. mqtt_client: paho.mqtt.client.Client,
  192. update_device_info: bool,
  193. mqtt_topic_prefix: str,
  194. ) -> None:
  195. raise NotImplementedError()
  196. @classmethod
  197. def _mqtt_command_callback(
  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. )