__init__.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. # https://www.home-assistant.io/docs/mqtt/discovery/#discovery_prefix
  23. _HOME_ASSISTANT_DEFAULT_DISCOVERY_PREFIX = "homeassistant"
  24. _LOGGER = logging.getLogger(__name__)
  25. def _mqtt_on_connect(
  26. mqtt_client: paho.mqtt.client.Client,
  27. userdata: typing.Any,
  28. flags: typing.Dict,
  29. return_code: int,
  30. ) -> None:
  31. # pylint: disable=unused-argument; callback
  32. # https://github.com/eclipse/paho.mqtt.python/blob/v1.5.0/src/paho/mqtt/client.py#L441
  33. assert return_code == 0, return_code # connection accepted
  34. mqtt_broker_host, mqtt_broker_port = mqtt_client.socket().getpeername()
  35. _LOGGER.debug("connected to MQTT broker %s:%d", mqtt_broker_host, mqtt_broker_port)
  36. def _main() -> None:
  37. logging.basicConfig(
  38. level=logging.DEBUG,
  39. format="%(asctime)s:%(levelname)s:%(message)s",
  40. datefmt="%Y-%m-%dT%H:%M:%S%z",
  41. )
  42. argparser = argparse.ArgumentParser(
  43. "MQTT client controlling SwitchBot button automators, "
  44. "compatible with home-assistant.io's MQTT Switch platform"
  45. )
  46. argparser.add_argument("--mqtt-host", type=str, required=True)
  47. argparser.add_argument("--mqtt-port", type=int, default=1883)
  48. args = argparser.parse_args()
  49. # https://pypi.org/project/paho-mqtt/
  50. mqtt_client = paho.mqtt.client.Client()
  51. mqtt_client.on_connect = _mqtt_on_connect
  52. _LOGGER.info(
  53. "connecting to MQTT broker %s:%d", args.mqtt_host, args.mqtt_port,
  54. )
  55. mqtt_client.connect(host=args.mqtt_host, port=args.mqtt_port)
  56. mqtt_client.loop_forever()