_base.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  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. import abc
  19. import logging
  20. import queue
  21. import shlex
  22. import typing
  23. import bluepy.btle
  24. import paho.mqtt.client
  25. import switchbot
  26. from switchbot_mqtt._utils import (
  27. _join_mqtt_topic_levels,
  28. _mac_address_valid,
  29. _MQTTTopicLevel,
  30. _MQTTTopicPlaceholder,
  31. _parse_mqtt_topic,
  32. _QueueLogHandler,
  33. )
  34. _LOGGER = logging.getLogger(__name__)
  35. class _MQTTCallbackUserdata:
  36. # pylint: disable=too-few-public-methods; @dataclasses.dataclass when python_requires>=3.7
  37. def __init__(
  38. self,
  39. *,
  40. retry_count: int,
  41. device_passwords: typing.Dict[str, str],
  42. fetch_device_info: bool,
  43. ) -> None:
  44. self.retry_count = retry_count
  45. self.device_passwords = device_passwords
  46. self.fetch_device_info = fetch_device_info
  47. def __eq__(self, other: object) -> bool:
  48. return isinstance(other, type(self)) and vars(self) == vars(other)
  49. class _MQTTControlledActor(abc.ABC):
  50. MQTT_COMMAND_TOPIC_LEVELS: typing.List[_MQTTTopicLevel] = NotImplemented
  51. MQTT_STATE_TOPIC_LEVELS: typing.List[_MQTTTopicLevel] = NotImplemented
  52. _MQTT_BATTERY_PERCENTAGE_TOPIC_LEVELS: typing.List[_MQTTTopicLevel] = NotImplemented
  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. @abc.abstractmethod
  119. def execute_command(
  120. self,
  121. mqtt_message_payload: bytes,
  122. mqtt_client: paho.mqtt.client.Client,
  123. update_device_info: bool,
  124. ) -> None:
  125. raise NotImplementedError()
  126. @classmethod
  127. def _mqtt_command_callback(
  128. cls,
  129. mqtt_client: paho.mqtt.client.Client,
  130. userdata: _MQTTCallbackUserdata,
  131. message: paho.mqtt.client.MQTTMessage,
  132. ) -> None:
  133. # pylint: disable=unused-argument; callback
  134. # https://github.com/eclipse/paho.mqtt.python/blob/v1.5.0/src/paho/mqtt/client.py#L469
  135. _LOGGER.debug("received topic=%s payload=%r", message.topic, message.payload)
  136. if message.retain:
  137. _LOGGER.info("ignoring retained message")
  138. return
  139. try:
  140. mac_address = _parse_mqtt_topic(
  141. topic=message.topic, expected_levels=cls.MQTT_COMMAND_TOPIC_LEVELS
  142. )[_MQTTTopicPlaceholder.MAC_ADDRESS]
  143. except ValueError as exc:
  144. _LOGGER.warning(str(exc), exc_info=False)
  145. return
  146. if not _mac_address_valid(mac_address):
  147. _LOGGER.warning("invalid mac address %s", mac_address)
  148. return
  149. actor = cls(
  150. mac_address=mac_address,
  151. retry_count=userdata.retry_count,
  152. password=userdata.device_passwords.get(mac_address, None),
  153. )
  154. actor.execute_command(
  155. mqtt_message_payload=message.payload,
  156. mqtt_client=mqtt_client,
  157. # consider calling update+report method directly when adding support for battery levels
  158. update_device_info=userdata.fetch_device_info,
  159. )
  160. @classmethod
  161. def mqtt_subscribe(cls, mqtt_client: paho.mqtt.client.Client) -> None:
  162. command_topic = "/".join(
  163. "+" if isinstance(l, _MQTTTopicPlaceholder) else l
  164. for l in cls.MQTT_COMMAND_TOPIC_LEVELS
  165. )
  166. _LOGGER.info("subscribing to MQTT topic %r", command_topic)
  167. mqtt_client.subscribe(command_topic)
  168. mqtt_client.message_callback_add(
  169. sub=command_topic,
  170. callback=cls._mqtt_command_callback,
  171. )
  172. def _mqtt_publish(
  173. self,
  174. *,
  175. topic_levels: typing.List[_MQTTTopicLevel],
  176. payload: bytes,
  177. mqtt_client: paho.mqtt.client.Client,
  178. ) -> None:
  179. topic = _join_mqtt_topic_levels(
  180. topic_levels=topic_levels, mac_address=self._mac_address
  181. )
  182. # https://pypi.org/project/paho-mqtt/#publishing
  183. _LOGGER.debug("publishing topic=%s payload=%r", topic, payload)
  184. message_info: paho.mqtt.client.MQTTMessageInfo = mqtt_client.publish(
  185. topic=topic, payload=payload, retain=True
  186. )
  187. # wait before checking status?
  188. if message_info.rc != paho.mqtt.client.MQTT_ERR_SUCCESS:
  189. _LOGGER.error(
  190. "Failed to publish MQTT message on topic %s (rc=%d)",
  191. topic,
  192. message_info.rc,
  193. )
  194. def report_state(self, state: bytes, mqtt_client: paho.mqtt.client.Client) -> None:
  195. self._mqtt_publish(
  196. topic_levels=self.MQTT_STATE_TOPIC_LEVELS,
  197. payload=state,
  198. mqtt_client=mqtt_client,
  199. )