__init__.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  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 logging
  19. import socket
  20. import typing
  21. import paho.mqtt.client
  22. from switchbot_mqtt._actors import _ButtonAutomator, _CurtainMotor
  23. from switchbot_mqtt._actors.base import _MQTTCallbackUserdata
  24. _LOGGER = logging.getLogger(__name__)
  25. _MQTT_AVAILABILITY_TOPIC = "switchbot-mqtt/status"
  26. # for backward compatability, will be removed in next major release:
  27. _MQTT_AVAILABILITY_TOPIC_LEGACY = "switchbot_mqtt/status"
  28. # "online" and "offline" to match home assistant's default settings
  29. # https://www.home-assistant.io/integrations/switch.mqtt/#payload_available
  30. _MQTT_BIRTH_PAYLOAD = "online"
  31. _MQTT_LAST_WILL_PAYLOAD = "offline"
  32. def _mqtt_on_connect(
  33. mqtt_client: paho.mqtt.client.Client,
  34. userdata: _MQTTCallbackUserdata,
  35. flags: typing.Dict[str, int],
  36. return_code: int,
  37. ) -> None:
  38. # pylint: disable=unused-argument; callback
  39. # https://github.com/eclipse/paho.mqtt.python/blob/v1.5.0/src/paho/mqtt/client.py#L441
  40. assert return_code == 0, return_code # connection accepted
  41. mqtt_broker_host, mqtt_broker_port, *_ = mqtt_client.socket().getpeername()
  42. # https://www.rfc-editor.org/rfc/rfc5952#section-6
  43. _LOGGER.debug(
  44. "connected to MQTT broker %s:%d",
  45. f"[{mqtt_broker_host}]"
  46. if mqtt_client.socket().family == socket.AF_INET6
  47. else mqtt_broker_host,
  48. mqtt_broker_port,
  49. )
  50. for topic in (_MQTT_AVAILABILITY_TOPIC, _MQTT_AVAILABILITY_TOPIC_LEGACY):
  51. mqtt_client.publish(
  52. topic=userdata.mqtt_topic_prefix + topic,
  53. payload=_MQTT_BIRTH_PAYLOAD,
  54. retain=True,
  55. )
  56. _ButtonAutomator.mqtt_subscribe(mqtt_client=mqtt_client, settings=userdata)
  57. _CurtainMotor.mqtt_subscribe(mqtt_client=mqtt_client, settings=userdata)
  58. def _run(
  59. *,
  60. mqtt_host: str,
  61. mqtt_port: int,
  62. mqtt_disable_tls: bool,
  63. mqtt_username: typing.Optional[str],
  64. mqtt_password: typing.Optional[str],
  65. mqtt_topic_prefix: str,
  66. retry_count: int,
  67. device_passwords: typing.Dict[str, str],
  68. fetch_device_info: bool,
  69. ) -> None:
  70. # https://pypi.org/project/paho-mqtt/
  71. mqtt_client = paho.mqtt.client.Client(
  72. userdata=_MQTTCallbackUserdata(
  73. retry_count=retry_count,
  74. device_passwords=device_passwords,
  75. fetch_device_info=fetch_device_info,
  76. mqtt_topic_prefix=mqtt_topic_prefix,
  77. )
  78. )
  79. mqtt_client.on_connect = _mqtt_on_connect
  80. _LOGGER.info(
  81. "connecting to MQTT broker %s:%d (TLS %s)",
  82. mqtt_host,
  83. mqtt_port,
  84. "disabled" if mqtt_disable_tls else "enabled",
  85. )
  86. if not mqtt_disable_tls:
  87. mqtt_client.tls_set(ca_certs=None) # enable tls trusting default system certs
  88. if mqtt_username:
  89. mqtt_client.username_pw_set(username=mqtt_username, password=mqtt_password)
  90. elif mqtt_password:
  91. raise ValueError("Missing MQTT username")
  92. for topic in (_MQTT_AVAILABILITY_TOPIC, _MQTT_AVAILABILITY_TOPIC_LEGACY):
  93. mqtt_client.will_set(
  94. topic=mqtt_topic_prefix + topic,
  95. payload=_MQTT_LAST_WILL_PAYLOAD,
  96. retain=True,
  97. )
  98. mqtt_client.connect(host=mqtt_host, port=mqtt_port)
  99. # https://github.com/eclipse/paho.mqtt.python/blob/master/src/paho/mqtt/client.py#L1740
  100. mqtt_client.loop_forever()