_base.py 9.9 KB

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