__init__.py 17 KB

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