_base.py 11 KB

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