1
0

__init__.py 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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. _availability_topic_with_prefix = userdata.mqtt_topic_prefix + _MQTT_AVAILABILITY_TOPIC
  49. mqtt_client.publish(topic=_availability_topic_with_prefix,payload=_MQTT_BIRTH_PAYLOAD)
  50. _ButtonAutomator.mqtt_subscribe(mqtt_client=mqtt_client, settings=userdata)
  51. _CurtainMotor.mqtt_subscribe(mqtt_client=mqtt_client, settings=userdata)
  52. def _run(
  53. *,
  54. mqtt_host: str,
  55. mqtt_port: int,
  56. mqtt_disable_tls: bool,
  57. mqtt_username: typing.Optional[str],
  58. mqtt_password: typing.Optional[str],
  59. mqtt_topic_prefix: str,
  60. retry_count: int,
  61. device_passwords: typing.Dict[str, str],
  62. fetch_device_info: bool,
  63. ) -> None:
  64. # https://pypi.org/project/paho-mqtt/
  65. mqtt_client = paho.mqtt.client.Client(
  66. userdata=_MQTTCallbackUserdata(
  67. retry_count=retry_count,
  68. device_passwords=device_passwords,
  69. fetch_device_info=fetch_device_info,
  70. mqtt_topic_prefix=mqtt_topic_prefix,
  71. )
  72. )
  73. mqtt_client.on_connect = _mqtt_on_connect
  74. _LOGGER.info(
  75. "connecting to MQTT broker %s:%d (TLS %s)",
  76. mqtt_host,
  77. mqtt_port,
  78. "disabled" if mqtt_disable_tls else "enabled",
  79. )
  80. if not mqtt_disable_tls:
  81. mqtt_client.tls_set(ca_certs=None) # enable tls trusting default system certs
  82. if mqtt_username:
  83. mqtt_client.username_pw_set(username=mqtt_username, password=mqtt_password)
  84. elif mqtt_password:
  85. raise ValueError("Missing MQTT username")
  86. _availability_topic_with_prefix = mqtt_topic_prefix + _MQTT_AVAILABILITY_TOPIC
  87. mqtt_client.will_set(topic=_availability_topic_with_prefix,payload=_MQTT_LAST_WILL_PAYLOAD)
  88. mqtt_client.connect(host=mqtt_host, port=mqtt_port)
  89. # https://github.com/eclipse/paho.mqtt.python/blob/master/src/paho/mqtt/client.py#L1740
  90. mqtt_client.loop_forever()