1
0

__init__.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  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. _QueueLogHandler,
  32. )
  33. _LOGGER = logging.getLogger(__name__)
  34. # "homeassistant" for historic reason, may be parametrized in future
  35. _MQTT_TOPIC_LEVELS_PREFIX: typing.List[_MQTTTopicLevel] = ["homeassistant"]
  36. class _MQTTCallbackUserdata:
  37. # pylint: disable=too-few-public-methods; @dataclasses.dataclass when python_requires>=3.7
  38. def __init__(
  39. self,
  40. *,
  41. retry_count: int,
  42. device_passwords: typing.Dict[str, str],
  43. fetch_device_info: bool,
  44. ) -> None:
  45. self.retry_count = retry_count
  46. self.device_passwords = device_passwords
  47. self.fetch_device_info = fetch_device_info
  48. def __eq__(self, other: object) -> bool:
  49. return isinstance(other, type(self)) and vars(self) == vars(other)
  50. class _MQTTControlledActor(abc.ABC):
  51. MQTT_COMMAND_TOPIC_LEVELS: typing.List[_MQTTTopicLevel] = NotImplemented
  52. MQTT_STATE_TOPIC_LEVELS: typing.List[_MQTTTopicLevel] = NotImplemented
  53. _MQTT_BATTERY_PERCENTAGE_TOPIC_LEVELS: typing.List[_MQTTTopicLevel] = NotImplemented
  54. @classmethod
  55. def get_mqtt_battery_percentage_topic(cls, mac_address: str) -> str:
  56. return _join_mqtt_topic_levels(
  57. topic_levels=cls._MQTT_BATTERY_PERCENTAGE_TOPIC_LEVELS,
  58. mac_address=mac_address,
  59. )
  60. @abc.abstractmethod
  61. def __init__(
  62. self, *, mac_address: str, retry_count: int, password: typing.Optional[str]
  63. ) -> None:
  64. # alternative: pySwitchbot >=0.10.0 provides SwitchbotDevice.get_mac()
  65. self._mac_address = mac_address
  66. @abc.abstractmethod
  67. def _get_device(self) -> switchbot.SwitchbotDevice:
  68. raise NotImplementedError()
  69. def _update_device_info(self) -> None:
  70. log_queue: queue.Queue[logging.LogRecord] = queue.Queue(maxsize=0)
  71. logging.getLogger("switchbot").addHandler(_QueueLogHandler(log_queue))
  72. try:
  73. self._get_device().update()
  74. # pySwitchbot>=v0.10.1 catches bluepy.btle.BTLEManagementError :(
  75. # https://github.com/Danielhiversen/pySwitchbot/blob/0.10.1/switchbot/__init__.py#L141
  76. while not log_queue.empty():
  77. log_record = log_queue.get()
  78. if log_record.exc_info:
  79. exc: typing.Optional[BaseException] = log_record.exc_info[1]
  80. if (
  81. isinstance(exc, bluepy.btle.BTLEManagementError)
  82. and exc.emsg == "Permission Denied"
  83. ):
  84. raise exc
  85. except bluepy.btle.BTLEManagementError as exc:
  86. if (
  87. exc.emsg == "Permission Denied"
  88. and exc.message == "Failed to execute management command 'le on'"
  89. ):
  90. raise PermissionError(
  91. "bluepy-helper failed to enable low energy mode"
  92. " due to insufficient permissions."
  93. "\nSee https://github.com/IanHarvey/bluepy/issues/313#issuecomment-428324639"
  94. ", https://github.com/fphammerle/switchbot-mqtt/pull/31#issuecomment-846383603"
  95. ", and https://github.com/IanHarvey/bluepy/blob/v/1.3.0/bluepy"
  96. "/bluepy-helper.c#L1260."
  97. "\nInsecure workaround:"
  98. "\n1. sudo apt-get install --no-install-recommends libcap2-bin"
  99. f"\n2. sudo setcap cap_net_admin+ep {shlex.quote(bluepy.btle.helperExe)}"
  100. "\n3. restart switchbot-mqtt"
  101. "\nIn docker-based setups, you could use"
  102. " `sudo docker run --cap-drop ALL --cap-add NET_ADMIN --user 0 …`"
  103. " (seriously insecure)."
  104. ) from exc
  105. raise
  106. def _report_battery_level(self, mqtt_client: paho.mqtt.client.Client) -> None:
  107. # > battery: Percentage of battery that is left.
  108. # https://www.home-assistant.io/integrations/sensor/#device-class
  109. self._mqtt_publish(
  110. topic_levels=self._MQTT_BATTERY_PERCENTAGE_TOPIC_LEVELS,
  111. payload=str(self._get_device().get_battery_percent()).encode(),
  112. mqtt_client=mqtt_client,
  113. )
  114. def _update_and_report_device_info(
  115. self, mqtt_client: paho.mqtt.client.Client
  116. ) -> None:
  117. self._update_device_info()
  118. self._report_battery_level(mqtt_client=mqtt_client)
  119. @abc.abstractmethod
  120. def execute_command(
  121. self,
  122. mqtt_message_payload: bytes,
  123. mqtt_client: paho.mqtt.client.Client,
  124. update_device_info: bool,
  125. ) -> None:
  126. raise NotImplementedError()
  127. @classmethod
  128. def _mqtt_command_callback(
  129. cls,
  130. mqtt_client: paho.mqtt.client.Client,
  131. userdata: _MQTTCallbackUserdata,
  132. message: paho.mqtt.client.MQTTMessage,
  133. ) -> None:
  134. # pylint: disable=unused-argument; callback
  135. # https://github.com/eclipse/paho.mqtt.python/blob/v1.5.0/src/paho/mqtt/client.py#L469
  136. _LOGGER.debug("received topic=%s payload=%r", message.topic, message.payload)
  137. if message.retain:
  138. _LOGGER.info("ignoring retained message")
  139. return
  140. topic_split = message.topic.split("/")
  141. if len(topic_split) != len(cls.MQTT_COMMAND_TOPIC_LEVELS):
  142. _LOGGER.warning("unexpected topic %s", message.topic)
  143. return
  144. mac_address = None
  145. for given_part, expected_part in zip(
  146. topic_split, cls.MQTT_COMMAND_TOPIC_LEVELS
  147. ):
  148. if expected_part == _MQTTTopicPlaceholder.MAC_ADDRESS:
  149. mac_address = given_part
  150. elif expected_part != given_part:
  151. _LOGGER.warning("unexpected topic %s", message.topic)
  152. return
  153. assert mac_address
  154. if not _mac_address_valid(mac_address):
  155. _LOGGER.warning("invalid mac address %s", mac_address)
  156. return
  157. actor = cls(
  158. mac_address=mac_address,
  159. retry_count=userdata.retry_count,
  160. password=userdata.device_passwords.get(mac_address, None),
  161. )
  162. actor.execute_command(
  163. mqtt_message_payload=message.payload,
  164. mqtt_client=mqtt_client,
  165. # consider calling update+report method directly when adding support for battery levels
  166. update_device_info=userdata.fetch_device_info,
  167. )
  168. @classmethod
  169. def mqtt_subscribe(cls, mqtt_client: paho.mqtt.client.Client) -> None:
  170. command_topic = "/".join(
  171. "+" if isinstance(l, _MQTTTopicPlaceholder) else l
  172. for l in cls.MQTT_COMMAND_TOPIC_LEVELS
  173. )
  174. _LOGGER.info("subscribing to MQTT topic %r", command_topic)
  175. mqtt_client.subscribe(command_topic)
  176. mqtt_client.message_callback_add(
  177. sub=command_topic,
  178. callback=cls._mqtt_command_callback,
  179. )
  180. def _mqtt_publish(
  181. self,
  182. *,
  183. topic_levels: typing.List[_MQTTTopicLevel],
  184. payload: bytes,
  185. mqtt_client: paho.mqtt.client.Client,
  186. ) -> None:
  187. topic = _join_mqtt_topic_levels(
  188. topic_levels=topic_levels, mac_address=self._mac_address
  189. )
  190. # https://pypi.org/project/paho-mqtt/#publishing
  191. _LOGGER.debug("publishing topic=%s payload=%r", topic, payload)
  192. message_info: paho.mqtt.client.MQTTMessageInfo = mqtt_client.publish(
  193. topic=topic, payload=payload, retain=True
  194. )
  195. # wait before checking status?
  196. if message_info.rc != paho.mqtt.client.MQTT_ERR_SUCCESS:
  197. _LOGGER.error(
  198. "Failed to publish MQTT message on topic %s (rc=%d)",
  199. topic,
  200. message_info.rc,
  201. )
  202. def report_state(self, state: bytes, mqtt_client: paho.mqtt.client.Client) -> None:
  203. self._mqtt_publish(
  204. topic_levels=self.MQTT_STATE_TOPIC_LEVELS,
  205. payload=state,
  206. mqtt_client=mqtt_client,
  207. )
  208. class _ButtonAutomator(_MQTTControlledActor):
  209. # https://www.home-assistant.io/integrations/switch.mqtt/
  210. MQTT_COMMAND_TOPIC_LEVELS = _MQTT_TOPIC_LEVELS_PREFIX + [
  211. "switch",
  212. "switchbot",
  213. _MQTTTopicPlaceholder.MAC_ADDRESS,
  214. "set",
  215. ]
  216. MQTT_STATE_TOPIC_LEVELS = _MQTT_TOPIC_LEVELS_PREFIX + [
  217. "switch",
  218. "switchbot",
  219. _MQTTTopicPlaceholder.MAC_ADDRESS,
  220. "state",
  221. ]
  222. _MQTT_BATTERY_PERCENTAGE_TOPIC_LEVELS = _MQTT_TOPIC_LEVELS_PREFIX + [
  223. "switch",
  224. "switchbot",
  225. _MQTTTopicPlaceholder.MAC_ADDRESS,
  226. "battery-percentage",
  227. ]
  228. # for downward compatibility (will be removed in v3):
  229. _MQTT_BATTERY_PERCENTAGE_TOPIC_LEVELS_LEGACY = _MQTT_TOPIC_LEVELS_PREFIX + [
  230. "cover",
  231. "switchbot",
  232. _MQTTTopicPlaceholder.MAC_ADDRESS,
  233. "battery-percentage",
  234. ]
  235. def __init__(
  236. self, *, mac_address: str, retry_count: int, password: typing.Optional[str]
  237. ) -> None:
  238. self.__device = switchbot.Switchbot(
  239. mac=mac_address, password=password, retry_count=retry_count
  240. )
  241. super().__init__(
  242. mac_address=mac_address, retry_count=retry_count, password=password
  243. )
  244. def _get_device(self) -> switchbot.SwitchbotDevice:
  245. return self.__device
  246. def _report_battery_level(self, mqtt_client: paho.mqtt.client.Client) -> None:
  247. super()._report_battery_level(mqtt_client=mqtt_client)
  248. # kept for downward compatibility (will be removed in v3)
  249. self._mqtt_publish(
  250. topic_levels=self._MQTT_BATTERY_PERCENTAGE_TOPIC_LEVELS_LEGACY,
  251. payload=str(self._get_device().get_battery_percent()).encode(),
  252. mqtt_client=mqtt_client,
  253. )
  254. def execute_command(
  255. self,
  256. mqtt_message_payload: bytes,
  257. mqtt_client: paho.mqtt.client.Client,
  258. update_device_info: bool,
  259. ) -> None:
  260. # https://www.home-assistant.io/integrations/switch.mqtt/#payload_on
  261. if mqtt_message_payload.lower() == b"on":
  262. if not self.__device.turn_on():
  263. _LOGGER.error("failed to turn on switchbot %s", self._mac_address)
  264. else:
  265. _LOGGER.info("switchbot %s turned on", self._mac_address)
  266. # https://www.home-assistant.io/integrations/switch.mqtt/#state_on
  267. self.report_state(mqtt_client=mqtt_client, state=b"ON")
  268. if update_device_info:
  269. self._update_and_report_device_info(mqtt_client)
  270. # https://www.home-assistant.io/integrations/switch.mqtt/#payload_off
  271. elif mqtt_message_payload.lower() == b"off":
  272. if not self.__device.turn_off():
  273. _LOGGER.error("failed to turn off switchbot %s", self._mac_address)
  274. else:
  275. _LOGGER.info("switchbot %s turned off", self._mac_address)
  276. self.report_state(mqtt_client=mqtt_client, state=b"OFF")
  277. if update_device_info:
  278. self._update_and_report_device_info(mqtt_client)
  279. else:
  280. _LOGGER.warning(
  281. "unexpected payload %r (expected 'ON' or 'OFF')", mqtt_message_payload
  282. )
  283. class _CurtainMotor(_MQTTControlledActor):
  284. # https://www.home-assistant.io/integrations/cover.mqtt/
  285. MQTT_COMMAND_TOPIC_LEVELS = _MQTT_TOPIC_LEVELS_PREFIX + [
  286. "cover",
  287. "switchbot-curtain",
  288. _MQTTTopicPlaceholder.MAC_ADDRESS,
  289. "set",
  290. ]
  291. MQTT_STATE_TOPIC_LEVELS = _MQTT_TOPIC_LEVELS_PREFIX + [
  292. "cover",
  293. "switchbot-curtain",
  294. _MQTTTopicPlaceholder.MAC_ADDRESS,
  295. "state",
  296. ]
  297. _MQTT_BATTERY_PERCENTAGE_TOPIC_LEVELS = _MQTT_TOPIC_LEVELS_PREFIX + [
  298. "cover",
  299. "switchbot-curtain",
  300. _MQTTTopicPlaceholder.MAC_ADDRESS,
  301. "battery-percentage",
  302. ]
  303. _MQTT_POSITION_TOPIC_LEVELS = _MQTT_TOPIC_LEVELS_PREFIX + [
  304. "cover",
  305. "switchbot-curtain",
  306. _MQTTTopicPlaceholder.MAC_ADDRESS,
  307. "position",
  308. ]
  309. @classmethod
  310. def get_mqtt_position_topic(cls, mac_address: str) -> str:
  311. return _join_mqtt_topic_levels(
  312. topic_levels=cls._MQTT_POSITION_TOPIC_LEVELS, mac_address=mac_address
  313. )
  314. def __init__(
  315. self, *, mac_address: str, retry_count: int, password: typing.Optional[str]
  316. ) -> None:
  317. # > The position of the curtain is saved in self._pos with 0 = open and 100 = closed.
  318. # https://github.com/Danielhiversen/pySwitchbot/blob/0.10.0/switchbot/__init__.py#L150
  319. self.__device = switchbot.SwitchbotCurtain(
  320. mac=mac_address,
  321. password=password,
  322. retry_count=retry_count,
  323. reverse_mode=True,
  324. )
  325. super().__init__(
  326. mac_address=mac_address, retry_count=retry_count, password=password
  327. )
  328. def _get_device(self) -> switchbot.SwitchbotDevice:
  329. return self.__device
  330. def _report_position(self, mqtt_client: paho.mqtt.client.Client) -> None:
  331. # > position_closed integer (Optional, default: 0)
  332. # > position_open integer (Optional, default: 100)
  333. # https://www.home-assistant.io/integrations/cover.mqtt/#position_closed
  334. # SwitchbotCurtain.get_position() returns a cached value within [0, 100].
  335. # SwitchbotCurtain.open() and .close() update the position optimistically,
  336. # SwitchbotCurtain.update() fetches the real position via bluetooth.
  337. # https://github.com/Danielhiversen/pySwitchbot/blob/0.10.0/switchbot/__init__.py#L202
  338. self._mqtt_publish(
  339. topic_levels=self._MQTT_POSITION_TOPIC_LEVELS,
  340. payload=str(int(self.__device.get_position())).encode(),
  341. mqtt_client=mqtt_client,
  342. )
  343. def _update_and_report_device_info( # pylint: disable=arguments-differ; report_position is optional
  344. self, mqtt_client: paho.mqtt.client.Client, *, report_position: bool = True
  345. ) -> None:
  346. super()._update_and_report_device_info(mqtt_client)
  347. if report_position:
  348. self._report_position(mqtt_client=mqtt_client)
  349. def execute_command(
  350. self,
  351. mqtt_message_payload: bytes,
  352. mqtt_client: paho.mqtt.client.Client,
  353. update_device_info: bool,
  354. ) -> None:
  355. # https://www.home-assistant.io/integrations/cover.mqtt/#payload_open
  356. report_device_info, report_position = False, False
  357. if mqtt_message_payload.lower() == b"open":
  358. if not self.__device.open():
  359. _LOGGER.error("failed to open switchbot curtain %s", self._mac_address)
  360. else:
  361. _LOGGER.info("switchbot curtain %s opening", self._mac_address)
  362. # > state_opening string (Optional, default: opening)
  363. # https://www.home-assistant.io/integrations/cover.mqtt/#state_opening
  364. self.report_state(mqtt_client=mqtt_client, state=b"opening")
  365. report_device_info = update_device_info
  366. elif mqtt_message_payload.lower() == b"close":
  367. if not self.__device.close():
  368. _LOGGER.error("failed to close switchbot curtain %s", self._mac_address)
  369. else:
  370. _LOGGER.info("switchbot curtain %s closing", self._mac_address)
  371. # https://www.home-assistant.io/integrations/cover.mqtt/#state_closing
  372. self.report_state(mqtt_client=mqtt_client, state=b"closing")
  373. report_device_info = update_device_info
  374. elif mqtt_message_payload.lower() == b"stop":
  375. if not self.__device.stop():
  376. _LOGGER.error("failed to stop switchbot curtain %s", self._mac_address)
  377. else:
  378. _LOGGER.info("switchbot curtain %s stopped", self._mac_address)
  379. # no "stopped" state mentioned at
  380. # https://www.home-assistant.io/integrations/cover.mqtt/#configuration-variables
  381. # https://community.home-assistant.io/t/mqtt-how-to-remove-retained-messages/79029/2
  382. self.report_state(mqtt_client=mqtt_client, state=b"")
  383. report_device_info = update_device_info
  384. report_position = True
  385. else:
  386. _LOGGER.warning(
  387. "unexpected payload %r (expected 'OPEN', 'CLOSE', or 'STOP')",
  388. mqtt_message_payload,
  389. )
  390. if report_device_info:
  391. self._update_and_report_device_info(
  392. mqtt_client=mqtt_client, report_position=report_position
  393. )
  394. def _mqtt_on_connect(
  395. mqtt_client: paho.mqtt.client.Client,
  396. userdata: _MQTTCallbackUserdata,
  397. flags: typing.Dict,
  398. return_code: int,
  399. ) -> None:
  400. # pylint: disable=unused-argument; callback
  401. # https://github.com/eclipse/paho.mqtt.python/blob/v1.5.0/src/paho/mqtt/client.py#L441
  402. assert return_code == 0, return_code # connection accepted
  403. mqtt_broker_host, mqtt_broker_port = mqtt_client.socket().getpeername()
  404. _LOGGER.debug("connected to MQTT broker %s:%d", mqtt_broker_host, mqtt_broker_port)
  405. _ButtonAutomator.mqtt_subscribe(mqtt_client=mqtt_client)
  406. _CurtainMotor.mqtt_subscribe(mqtt_client=mqtt_client)
  407. def _run(
  408. *,
  409. mqtt_host: str,
  410. mqtt_port: int,
  411. mqtt_username: typing.Optional[str],
  412. mqtt_password: typing.Optional[str],
  413. retry_count: int,
  414. device_passwords: typing.Dict[str, str],
  415. fetch_device_info: bool,
  416. ) -> None:
  417. # https://pypi.org/project/paho-mqtt/
  418. mqtt_client = paho.mqtt.client.Client(
  419. userdata=_MQTTCallbackUserdata(
  420. retry_count=retry_count,
  421. device_passwords=device_passwords,
  422. fetch_device_info=fetch_device_info,
  423. )
  424. )
  425. mqtt_client.on_connect = _mqtt_on_connect
  426. _LOGGER.info("connecting to MQTT broker %s:%d", mqtt_host, mqtt_port)
  427. if mqtt_username:
  428. mqtt_client.username_pw_set(username=mqtt_username, password=mqtt_password)
  429. elif mqtt_password:
  430. raise ValueError("Missing MQTT username")
  431. mqtt_client.connect(host=mqtt_host, port=mqtt_port)
  432. # https://github.com/eclipse/paho.mqtt.python/blob/master/src/paho/mqtt/client.py#L1740
  433. mqtt_client.loop_forever()