__init__.py 19 KB

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