__init__.py 16 KB

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