__init__.py 19 KB

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