__init__.py 19 KB

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