__init__.py 11 KB

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