__init__.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  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 logging
  23. import pathlib
  24. import re
  25. import typing
  26. import paho.mqtt.client
  27. import switchbot
  28. _LOGGER = logging.getLogger(__name__)
  29. _MAC_ADDRESS_REGEX = re.compile(r"^[0-9a-f]{2}(:[0-9a-f]{2}){5}$")
  30. class _MQTTTopicPlaceholder(enum.Enum):
  31. MAC_ADDRESS = "MAC_ADDRESS"
  32. _MQTTTopicLevel = typing.Union[str, _MQTTTopicPlaceholder]
  33. # "homeassistant" for historic reason, may be parametrized in future
  34. _MQTT_TOPIC_LEVELS_PREFIX = ["homeassistant"] # type: typing.List[_MQTTTopicLevel]
  35. def _mac_address_valid(mac_address: str) -> bool:
  36. return _MAC_ADDRESS_REGEX.match(mac_address.lower()) is not None
  37. class _MQTTCallbackUserdata:
  38. # pylint: disable=too-few-public-methods; @dataclasses.dataclass when python_requires>=3.7
  39. def __init__(
  40. self, retry_count: int, device_passwords: typing.Dict[str, str]
  41. ) -> None:
  42. self.retry_count = retry_count
  43. self.device_passwords = device_passwords
  44. def __eq__(self, other: object) -> bool:
  45. return isinstance(other, type(self)) and vars(self) == vars(other)
  46. class _MQTTControlledActor(abc.ABC):
  47. MQTT_COMMAND_TOPIC_LEVELS = NotImplemented # type: typing.List[_MQTTTopicLevel]
  48. MQTT_STATE_TOPIC_LEVELS = NotImplemented # type: typing.List[_MQTTTopicLevel]
  49. @abc.abstractmethod
  50. def __init__(
  51. self, mac_address: str, retry_count: int, password: typing.Optional[str]
  52. ) -> None:
  53. self._mac_address = mac_address
  54. @abc.abstractmethod
  55. def execute_command(
  56. self, mqtt_message_payload: bytes, mqtt_client: paho.mqtt.client.Client
  57. ) -> None:
  58. raise NotImplementedError()
  59. @classmethod
  60. def _mqtt_command_callback(
  61. cls,
  62. mqtt_client: paho.mqtt.client.Client,
  63. userdata: _MQTTCallbackUserdata,
  64. message: paho.mqtt.client.MQTTMessage,
  65. ) -> None:
  66. # pylint: disable=unused-argument; callback
  67. # https://github.com/eclipse/paho.mqtt.python/blob/v1.5.0/src/paho/mqtt/client.py#L469
  68. _LOGGER.debug("received topic=%s payload=%r", message.topic, message.payload)
  69. if message.retain:
  70. _LOGGER.info("ignoring retained message")
  71. return
  72. topic_split = message.topic.split("/")
  73. if len(topic_split) != len(cls.MQTT_COMMAND_TOPIC_LEVELS):
  74. _LOGGER.warning("unexpected topic %s", message.topic)
  75. return
  76. mac_address = None
  77. for given_part, expected_part in zip(
  78. topic_split, cls.MQTT_COMMAND_TOPIC_LEVELS
  79. ):
  80. if expected_part == _MQTTTopicPlaceholder.MAC_ADDRESS:
  81. mac_address = given_part
  82. elif expected_part != given_part:
  83. _LOGGER.warning("unexpected topic %s", message.topic)
  84. return
  85. assert mac_address
  86. if not _mac_address_valid(mac_address):
  87. _LOGGER.warning("invalid mac address %s", mac_address)
  88. return
  89. actor = cls(
  90. mac_address=mac_address,
  91. retry_count=userdata.retry_count,
  92. password=userdata.device_passwords.get(mac_address, None),
  93. )
  94. actor.execute_command(
  95. mqtt_message_payload=message.payload, mqtt_client=mqtt_client
  96. )
  97. @classmethod
  98. def mqtt_subscribe(cls, mqtt_client: paho.mqtt.client.Client) -> None:
  99. command_topic = "/".join(
  100. "+" if isinstance(l, _MQTTTopicPlaceholder) else l
  101. for l in cls.MQTT_COMMAND_TOPIC_LEVELS
  102. )
  103. _LOGGER.info("subscribing to MQTT topic %r", command_topic)
  104. mqtt_client.subscribe(command_topic)
  105. mqtt_client.message_callback_add(
  106. sub=command_topic,
  107. callback=cls._mqtt_command_callback,
  108. )
  109. def _mqtt_publish(
  110. self,
  111. topic_levels: typing.List[_MQTTTopicLevel],
  112. payload: bytes,
  113. mqtt_client: paho.mqtt.client.Client,
  114. ) -> None:
  115. topic = "/".join(
  116. self._mac_address
  117. if l == _MQTTTopicPlaceholder.MAC_ADDRESS
  118. else typing.cast(str, l)
  119. for l in topic_levels
  120. )
  121. # https://pypi.org/project/paho-mqtt/#publishing
  122. _LOGGER.debug("publishing topic=%s payload=%r", topic, payload)
  123. message_info = mqtt_client.publish(
  124. topic=topic, payload=payload, retain=True
  125. ) # type: paho.mqtt.client.MQTTMessageInfo
  126. # wait before checking status?
  127. if message_info.rc != paho.mqtt.client.MQTT_ERR_SUCCESS:
  128. _LOGGER.error(
  129. "Failed to publish MQTT message on topic %s (rc=%d)",
  130. topic,
  131. message_info.rc,
  132. )
  133. def report_state(self, state: bytes, mqtt_client: paho.mqtt.client.Client) -> None:
  134. self._mqtt_publish(
  135. topic_levels=self.MQTT_STATE_TOPIC_LEVELS,
  136. payload=state,
  137. mqtt_client=mqtt_client,
  138. )
  139. class _ButtonAutomator(_MQTTControlledActor):
  140. # https://www.home-assistant.io/integrations/switch.mqtt/
  141. MQTT_COMMAND_TOPIC_LEVELS = _MQTT_TOPIC_LEVELS_PREFIX + [
  142. "switch",
  143. "switchbot",
  144. _MQTTTopicPlaceholder.MAC_ADDRESS,
  145. "set",
  146. ]
  147. MQTT_STATE_TOPIC_LEVELS = _MQTT_TOPIC_LEVELS_PREFIX + [
  148. "switch",
  149. "switchbot",
  150. _MQTTTopicPlaceholder.MAC_ADDRESS,
  151. "state",
  152. ]
  153. def __init__(
  154. self, mac_address: str, retry_count: int, password: typing.Optional[None]
  155. ) -> None:
  156. self._device = switchbot.Switchbot(
  157. mac=mac_address, password=password, retry_count=retry_count
  158. )
  159. super().__init__(
  160. mac_address=mac_address, retry_count=retry_count, password=password
  161. )
  162. def execute_command(
  163. self, mqtt_message_payload: bytes, mqtt_client: paho.mqtt.client.Client
  164. ) -> None:
  165. # https://www.home-assistant.io/integrations/switch.mqtt/#payload_on
  166. if mqtt_message_payload.lower() == b"on":
  167. if not self._device.turn_on():
  168. _LOGGER.error("failed to turn on switchbot %s", self._mac_address)
  169. else:
  170. _LOGGER.info("switchbot %s turned on", self._mac_address)
  171. # https://www.home-assistant.io/integrations/switch.mqtt/#state_on
  172. self.report_state(mqtt_client=mqtt_client, state=b"ON")
  173. # https://www.home-assistant.io/integrations/switch.mqtt/#payload_off
  174. elif mqtt_message_payload.lower() == b"off":
  175. if not self._device.turn_off():
  176. _LOGGER.error("failed to turn off switchbot %s", self._mac_address)
  177. else:
  178. _LOGGER.info("switchbot %s turned off", self._mac_address)
  179. self.report_state(mqtt_client=mqtt_client, state=b"OFF")
  180. else:
  181. _LOGGER.warning(
  182. "unexpected payload %r (expected 'ON' or 'OFF')", mqtt_message_payload
  183. )
  184. class _CurtainMotor(_MQTTControlledActor):
  185. # https://www.home-assistant.io/integrations/cover.mqtt/
  186. MQTT_COMMAND_TOPIC_LEVELS = _MQTT_TOPIC_LEVELS_PREFIX + [
  187. "cover",
  188. "switchbot-curtain",
  189. _MQTTTopicPlaceholder.MAC_ADDRESS,
  190. "set",
  191. ]
  192. MQTT_STATE_TOPIC_LEVELS = _MQTT_TOPIC_LEVELS_PREFIX + [
  193. "cover",
  194. "switchbot-curtain",
  195. _MQTTTopicPlaceholder.MAC_ADDRESS,
  196. "state",
  197. ]
  198. def __init__(
  199. self, mac_address: str, retry_count: int, password: typing.Optional[None]
  200. ) -> None:
  201. self._device = switchbot.SwitchbotCurtain(
  202. mac=mac_address, password=password, retry_count=retry_count
  203. )
  204. super().__init__(
  205. mac_address=mac_address, retry_count=retry_count, password=password
  206. )
  207. def execute_command(
  208. self, mqtt_message_payload: bytes, mqtt_client: paho.mqtt.client.Client
  209. ) -> None:
  210. # https://www.home-assistant.io/integrations/cover.mqtt/#payload_open
  211. if mqtt_message_payload.lower() == b"open":
  212. if not self._device.open():
  213. _LOGGER.error("failed to open switchbot curtain %s", self._mac_address)
  214. else:
  215. _LOGGER.info("switchbot curtain %s opening", self._mac_address)
  216. # > state_opening string (Optional, default: opening)
  217. # https://www.home-assistant.io/integrations/cover.mqtt/#state_opening
  218. self.report_state(mqtt_client=mqtt_client, state=b"opening")
  219. elif mqtt_message_payload.lower() == b"close":
  220. if not self._device.close():
  221. _LOGGER.error("failed to close switchbot curtain %s", self._mac_address)
  222. else:
  223. _LOGGER.info("switchbot curtain %s closing", self._mac_address)
  224. # https://www.home-assistant.io/integrations/cover.mqtt/#state_closing
  225. self.report_state(mqtt_client=mqtt_client, state=b"closing")
  226. elif mqtt_message_payload.lower() == b"stop":
  227. if not self._device.stop():
  228. _LOGGER.error("failed to stop switchbot curtain %s", self._mac_address)
  229. else:
  230. _LOGGER.info("switchbot curtain %s stopped", self._mac_address)
  231. # no "stopped" state mentioned at
  232. # https://www.home-assistant.io/integrations/cover.mqtt/#configuration-variables
  233. # https://community.home-assistant.io/t/mqtt-how-to-remove-retained-messages/79029/2
  234. self.report_state(mqtt_client=mqtt_client, state=b"")
  235. else:
  236. _LOGGER.warning(
  237. "unexpected payload %r (expected 'OPEN', 'CLOSE', or 'STOP')",
  238. mqtt_message_payload,
  239. )
  240. def _mqtt_on_connect(
  241. mqtt_client: paho.mqtt.client.Client,
  242. userdata: _MQTTCallbackUserdata,
  243. flags: typing.Dict,
  244. return_code: int,
  245. ) -> None:
  246. # pylint: disable=unused-argument; callback
  247. # https://github.com/eclipse/paho.mqtt.python/blob/v1.5.0/src/paho/mqtt/client.py#L441
  248. assert return_code == 0, return_code # connection accepted
  249. mqtt_broker_host, mqtt_broker_port = mqtt_client.socket().getpeername()
  250. _LOGGER.debug("connected to MQTT broker %s:%d", mqtt_broker_host, mqtt_broker_port)
  251. _ButtonAutomator.mqtt_subscribe(mqtt_client=mqtt_client)
  252. _CurtainMotor.mqtt_subscribe(mqtt_client=mqtt_client)
  253. def _run(
  254. mqtt_host: str,
  255. mqtt_port: int,
  256. mqtt_username: typing.Optional[str],
  257. mqtt_password: typing.Optional[str],
  258. retry_count: int,
  259. ) -> None:
  260. # https://pypi.org/project/paho-mqtt/
  261. mqtt_client = paho.mqtt.client.Client(
  262. userdata=_MQTTCallbackUserdata(retry_count=retry_count, device_passwords={})
  263. )
  264. mqtt_client.on_connect = _mqtt_on_connect
  265. _LOGGER.info("connecting to MQTT broker %s:%d", mqtt_host, mqtt_port)
  266. if mqtt_username:
  267. mqtt_client.username_pw_set(username=mqtt_username, password=mqtt_password)
  268. elif mqtt_password:
  269. raise ValueError("Missing MQTT username")
  270. mqtt_client.connect(host=mqtt_host, port=mqtt_port)
  271. # https://github.com/eclipse/paho.mqtt.python/blob/master/src/paho/mqtt/client.py#L1740
  272. mqtt_client.loop_forever()
  273. def _main() -> None:
  274. logging.basicConfig(
  275. level=logging.DEBUG,
  276. format="%(asctime)s:%(levelname)s:%(name)s:%(message)s",
  277. datefmt="%Y-%m-%dT%H:%M:%S%z",
  278. )
  279. argparser = argparse.ArgumentParser(
  280. description="MQTT client controlling SwitchBot button automators, "
  281. "compatible with home-assistant.io's MQTT Switch platform"
  282. )
  283. argparser.add_argument("--mqtt-host", type=str, required=True)
  284. argparser.add_argument("--mqtt-port", type=int, default=1883)
  285. argparser.add_argument("--mqtt-username", type=str)
  286. password_argument_group = argparser.add_mutually_exclusive_group()
  287. password_argument_group.add_argument("--mqtt-password", type=str)
  288. password_argument_group.add_argument(
  289. "--mqtt-password-file",
  290. type=pathlib.Path,
  291. metavar="PATH",
  292. dest="mqtt_password_path",
  293. help="stripping trailing newline",
  294. )
  295. argparser.add_argument(
  296. "--retries",
  297. dest="retry_count",
  298. type=int,
  299. default=switchbot.DEFAULT_RETRY_COUNT,
  300. help="Maximum number of attempts to send a command to a SwitchBot device"
  301. " (default: %(default)d)",
  302. )
  303. args = argparser.parse_args()
  304. if args.mqtt_password_path:
  305. # .read_text() replaces \r\n with \n
  306. mqtt_password = args.mqtt_password_path.read_bytes().decode()
  307. if mqtt_password.endswith("\r\n"):
  308. mqtt_password = mqtt_password[:-2]
  309. elif mqtt_password.endswith("\n"):
  310. mqtt_password = mqtt_password[:-1]
  311. else:
  312. mqtt_password = args.mqtt_password
  313. _run(
  314. mqtt_host=args.mqtt_host,
  315. mqtt_port=args.mqtt_port,
  316. mqtt_username=args.mqtt_username,
  317. mqtt_password=mqtt_password,
  318. retry_count=args.retry_count,
  319. )