__init__.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  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 logging
  20. import re
  21. import typing
  22. import paho.mqtt.client
  23. import switchbot
  24. _LOGGER = logging.getLogger(__name__)
  25. _MQTT_TOPIC_MAC_ADDRESS_PLACEHOLDER = "{mac_address}"
  26. _MQTT_SET_TOPIC_PATTERN = [
  27. "homeassistant",
  28. "switch",
  29. "switchbot",
  30. _MQTT_TOPIC_MAC_ADDRESS_PLACEHOLDER,
  31. "set",
  32. ] # TODO parametrize
  33. _MQTT_SET_TOPIC = "/".join(_MQTT_SET_TOPIC_PATTERN).replace(
  34. _MQTT_TOPIC_MAC_ADDRESS_PLACEHOLDER, "+"
  35. )
  36. _MAC_ADDRESS_REGEX = re.compile(r"^[0-9a-f]{2}(:[0-9a-f]{2}){5}$")
  37. def _mac_address_valid(mac_address: str) -> bool:
  38. return _MAC_ADDRESS_REGEX.match(mac_address.lower()) is not None
  39. def _mqtt_on_connect(
  40. mqtt_client: paho.mqtt.client.Client,
  41. user_data: typing.Any,
  42. flags: typing.Dict,
  43. return_code: int,
  44. ) -> None:
  45. # pylint: disable=unused-argument; callback
  46. # https://github.com/eclipse/paho.mqtt.python/blob/v1.5.0/src/paho/mqtt/client.py#L441
  47. assert return_code == 0, return_code # connection accepted
  48. mqtt_broker_host, mqtt_broker_port = mqtt_client.socket().getpeername()
  49. _LOGGER.debug("connected to MQTT broker %s:%d", mqtt_broker_host, mqtt_broker_port)
  50. # https://www.home-assistant.io/docs/mqtt/discovery/#discovery_prefix
  51. mqtt_client.subscribe(_MQTT_SET_TOPIC)
  52. def _mqtt_on_message(
  53. mqtt_client: paho.mqtt.client.Client,
  54. user_data: typing.Any,
  55. message: paho.mqtt.client.MQTTMessage,
  56. ) -> None:
  57. # pylint: disable=unused-argument; callback
  58. # https://github.com/eclipse/paho.mqtt.python/blob/v1.5.0/src/paho/mqtt/client.py#L469
  59. _LOGGER.debug("received topic=%s payload=%r", message.topic, message.payload)
  60. if message.retain:
  61. _LOGGER.info("ignoring retained message")
  62. return
  63. topic_split = message.topic.split("/")
  64. if len(topic_split) != len(_MQTT_SET_TOPIC_PATTERN):
  65. _LOGGER.warning("unexpected topic %s", message.topic)
  66. return
  67. switchbot_mac_address = None
  68. for given_part, expected_part in zip(topic_split, _MQTT_SET_TOPIC_PATTERN):
  69. if expected_part == _MQTT_TOPIC_MAC_ADDRESS_PLACEHOLDER:
  70. switchbot_mac_address = given_part
  71. elif expected_part != given_part:
  72. _LOGGER.warning("unexpected topic %s", message.topic)
  73. return
  74. assert switchbot_mac_address
  75. if not _mac_address_valid(switchbot_mac_address):
  76. _LOGGER.warning("invalid mac address %s", switchbot_mac_address)
  77. return
  78. switchbot_device = switchbot.Switchbot(mac=switchbot_mac_address)
  79. if message.payload.lower() == b"on":
  80. if not switchbot_device.turn_on():
  81. _LOGGER.error("failed to turn on switchbot %s", switchbot_mac_address)
  82. else:
  83. _LOGGER.info("switchbot %s turned on", switchbot_mac_address)
  84. elif message.payload.lower() == b"off":
  85. if not switchbot_device.turn_off():
  86. _LOGGER.error("failed to turn off switchbot %s", switchbot_mac_address)
  87. else:
  88. _LOGGER.info("switchbot %s turned off", switchbot_mac_address)
  89. else:
  90. _LOGGER.warning("unexpected payload %r", message.payload)
  91. def _main() -> None:
  92. logging.basicConfig(
  93. level=logging.DEBUG,
  94. format="%(asctime)s:%(levelname)s:%(message)s",
  95. datefmt="%Y-%m-%dT%H:%M:%S%z",
  96. )
  97. argparser = argparse.ArgumentParser(
  98. "MQTT client controlling SwitchBot button automators, "
  99. "compatible with home-assistant.io's MQTT Switch platform"
  100. )
  101. argparser.add_argument("--mqtt-host", type=str, required=True)
  102. argparser.add_argument("--mqtt-port", type=int, default=1883)
  103. args = argparser.parse_args()
  104. # https://pypi.org/project/paho-mqtt/
  105. mqtt_client = paho.mqtt.client.Client()
  106. mqtt_client.on_connect = _mqtt_on_connect
  107. mqtt_client.on_message = _mqtt_on_message
  108. _LOGGER.info(
  109. "connecting to MQTT broker %s:%d", args.mqtt_host, args.mqtt_port,
  110. )
  111. mqtt_client.connect(host=args.mqtt_host, port=args.mqtt_port)
  112. mqtt_client.loop_forever()