1
0

__init__.py 3.8 KB

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