1
0

__init__.py 4.4 KB

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