__init__.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. # switchbot-mqtt - MQTT client controlling SwitchBot button automators,
  2. # compatible with home-assistant.io's MQTT Switch 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 argparse
  19. import enum
  20. import logging
  21. import re
  22. import typing
  23. import paho.mqtt.client
  24. import switchbot
  25. _LOGGER = logging.getLogger(__name__)
  26. class _SwitchbotAction(enum.Enum):
  27. ON = 1
  28. OFF = 2
  29. class _SwitchbotState(enum.Enum):
  30. ON = 1
  31. OFF = 2
  32. # https://www.home-assistant.io/docs/mqtt/discovery/#switches
  33. _MQTT_TOPIC_PREFIX_LEVELS = ["homeassistant", "switch", "switchbot"]
  34. _MQTT_TOPIC_MAC_ADDRESS_PLACEHOLDER = "{mac_address}"
  35. _MQTT_SET_TOPIC_LEVELS = _MQTT_TOPIC_PREFIX_LEVELS + [
  36. _MQTT_TOPIC_MAC_ADDRESS_PLACEHOLDER,
  37. "set",
  38. ]
  39. _MQTT_SET_TOPIC = "/".join(_MQTT_SET_TOPIC_LEVELS).replace(
  40. _MQTT_TOPIC_MAC_ADDRESS_PLACEHOLDER, "+"
  41. )
  42. _MQTT_STATE_TOPIC = "/".join(
  43. _MQTT_TOPIC_PREFIX_LEVELS + [_MQTT_TOPIC_MAC_ADDRESS_PLACEHOLDER, "state"]
  44. )
  45. # https://www.home-assistant.io/integrations/switch.mqtt/#state_off
  46. _MQTT_STATE_PAYLOAD_MAPPING = {_SwitchbotState.ON: b"ON", _SwitchbotState.OFF: b"OFF"}
  47. _MAC_ADDRESS_REGEX = re.compile(r"^[0-9a-f]{2}(:[0-9a-f]{2}){5}$")
  48. def _mac_address_valid(mac_address: str) -> bool:
  49. return _MAC_ADDRESS_REGEX.match(mac_address.lower()) is not None
  50. def _mqtt_on_connect(
  51. mqtt_client: paho.mqtt.client.Client,
  52. user_data: typing.Any,
  53. flags: typing.Dict,
  54. return_code: int,
  55. ) -> None:
  56. # pylint: disable=unused-argument; callback
  57. # https://github.com/eclipse/paho.mqtt.python/blob/v1.5.0/src/paho/mqtt/client.py#L441
  58. assert return_code == 0, return_code # connection accepted
  59. mqtt_broker_host, mqtt_broker_port = mqtt_client.socket().getpeername()
  60. _LOGGER.debug("connected to MQTT broker %s:%d", mqtt_broker_host, mqtt_broker_port)
  61. # https://www.home-assistant.io/docs/mqtt/discovery/#discovery_prefix
  62. mqtt_client.subscribe(_MQTT_SET_TOPIC)
  63. def _report_state(
  64. mqtt_client: paho.mqtt.client.Client,
  65. switchbot_mac_address: str,
  66. switchbot_state: _SwitchbotState,
  67. ) -> None:
  68. # https://pypi.org/project/paho-mqtt/#publishing
  69. topic = _MQTT_STATE_TOPIC.replace(
  70. _MQTT_TOPIC_MAC_ADDRESS_PLACEHOLDER, switchbot_mac_address
  71. )
  72. payload = _MQTT_STATE_PAYLOAD_MAPPING[switchbot_state]
  73. _LOGGER.debug("publishing topic=%s payload=%r", topic, payload)
  74. message_info: paho.mqtt.client.MQTTMessageInfo = mqtt_client.publish(
  75. topic=topic, payload=payload, retain=True,
  76. )
  77. if message_info.rc != paho.mqtt.client.MQTT_ERR_SUCCESS:
  78. _LOGGER.error("failed to publish state (rc=%d)", message_info.rc)
  79. def _send_command(
  80. mqtt_client: paho.mqtt.client.Client,
  81. switchbot_mac_address: str,
  82. action: _SwitchbotAction,
  83. ) -> None:
  84. switchbot_device = switchbot.Switchbot(mac=switchbot_mac_address)
  85. if action == _SwitchbotAction.ON:
  86. if not switchbot_device.turn_on():
  87. _LOGGER.error("failed to turn on switchbot %s", switchbot_mac_address)
  88. else:
  89. _LOGGER.info("switchbot %s turned on", switchbot_mac_address)
  90. _report_state(
  91. mqtt_client=mqtt_client,
  92. switchbot_mac_address=switchbot_mac_address,
  93. switchbot_state=_SwitchbotState.ON,
  94. )
  95. else:
  96. assert action == _SwitchbotAction.OFF, action
  97. if not switchbot_device.turn_off():
  98. _LOGGER.error("failed to turn off switchbot %s", switchbot_mac_address)
  99. else:
  100. _LOGGER.info("switchbot %s turned off", switchbot_mac_address)
  101. _report_state(
  102. mqtt_client=mqtt_client,
  103. switchbot_mac_address=switchbot_mac_address,
  104. switchbot_state=_SwitchbotState.OFF,
  105. )
  106. def _mqtt_on_message(
  107. mqtt_client: paho.mqtt.client.Client,
  108. user_data: typing.Any,
  109. message: paho.mqtt.client.MQTTMessage,
  110. ) -> None:
  111. # pylint: disable=unused-argument; callback
  112. # https://github.com/eclipse/paho.mqtt.python/blob/v1.5.0/src/paho/mqtt/client.py#L469
  113. _LOGGER.debug("received topic=%s payload=%r", message.topic, message.payload)
  114. if message.retain:
  115. _LOGGER.info("ignoring retained message")
  116. return
  117. topic_split = message.topic.split("/")
  118. if len(topic_split) != len(_MQTT_SET_TOPIC_LEVELS):
  119. _LOGGER.warning("unexpected topic %s", message.topic)
  120. return
  121. switchbot_mac_address = None
  122. for given_part, expected_part in zip(topic_split, _MQTT_SET_TOPIC_LEVELS):
  123. if expected_part == _MQTT_TOPIC_MAC_ADDRESS_PLACEHOLDER:
  124. switchbot_mac_address = given_part
  125. elif expected_part != given_part:
  126. _LOGGER.warning("unexpected topic %s", message.topic)
  127. return
  128. assert switchbot_mac_address
  129. if not _mac_address_valid(switchbot_mac_address):
  130. _LOGGER.warning("invalid mac address %s", switchbot_mac_address)
  131. return
  132. # https://www.home-assistant.io/integrations/switch.mqtt/#payload_off
  133. if message.payload.lower() == b"on":
  134. action = _SwitchbotAction.ON
  135. elif message.payload.lower() == b"off":
  136. action = _SwitchbotAction.OFF
  137. else:
  138. _LOGGER.warning("unexpected payload %r", message.payload)
  139. return
  140. _send_command(
  141. mqtt_client=mqtt_client,
  142. switchbot_mac_address=switchbot_mac_address,
  143. action=action,
  144. )
  145. def _run(
  146. mqtt_host: str,
  147. mqtt_port: int,
  148. mqtt_username: typing.Optional[str],
  149. mqtt_password: typing.Optional[str],
  150. ) -> None:
  151. # https://pypi.org/project/paho-mqtt/
  152. mqtt_client = paho.mqtt.client.Client()
  153. mqtt_client.on_connect = _mqtt_on_connect
  154. mqtt_client.on_message = _mqtt_on_message
  155. _LOGGER.info(
  156. "connecting to MQTT broker %s:%d", mqtt_host, mqtt_port,
  157. )
  158. if mqtt_username:
  159. mqtt_client.username_pw_set(username=mqtt_username, password=mqtt_password)
  160. elif mqtt_password:
  161. raise ValueError("Missing MQTT username")
  162. mqtt_client.connect(host=mqtt_host, port=mqtt_port)
  163. mqtt_client.loop_forever()
  164. def _main() -> None:
  165. logging.basicConfig(
  166. level=logging.DEBUG,
  167. format="%(asctime)s:%(levelname)s:%(message)s",
  168. datefmt="%Y-%m-%dT%H:%M:%S%z",
  169. )
  170. argparser = argparse.ArgumentParser(
  171. description="MQTT client controlling SwitchBot button automators, "
  172. "compatible with home-assistant.io's MQTT Switch platform"
  173. )
  174. argparser.add_argument("--mqtt-host", type=str, required=True)
  175. argparser.add_argument("--mqtt-port", type=int, default=1883)
  176. argparser.add_argument("--mqtt-username", type=str)
  177. argparser.add_argument("--mqtt-password", type=str)
  178. args = argparser.parse_args()
  179. _run(
  180. mqtt_host=args.mqtt_host,
  181. mqtt_port=args.mqtt_port,
  182. mqtt_username=args.mqtt_username,
  183. mqtt_password=args.mqtt_password,
  184. )