1
0

__init__.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  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 ssl
  21. import typing
  22. import aiomqtt
  23. from switchbot_mqtt._actors import _ButtonAutomator, _CurtainMotor
  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. async def _listen(
  31. *,
  32. mqtt_client: aiomqtt.Client,
  33. topic_callbacks: typing.Iterable[typing.Tuple[str, typing.Callable]],
  34. mqtt_topic_prefix: str,
  35. retry_count: int,
  36. device_passwords: typing.Dict[str, str],
  37. fetch_device_info: bool,
  38. ) -> None:
  39. async with mqtt_client.messages() as messages:
  40. await mqtt_client.publish(
  41. topic=mqtt_topic_prefix + _MQTT_AVAILABILITY_TOPIC,
  42. payload=_MQTT_BIRTH_PAYLOAD,
  43. retain=True,
  44. )
  45. async for message in messages:
  46. for topic, callback in topic_callbacks:
  47. if message.topic.matches(topic):
  48. await callback(
  49. mqtt_client=mqtt_client,
  50. message=message,
  51. mqtt_topic_prefix=mqtt_topic_prefix,
  52. retry_count=retry_count,
  53. device_passwords=device_passwords,
  54. fetch_device_info=fetch_device_info,
  55. )
  56. def _log_mqtt_connected(mqtt_client: aiomqtt.Client) -> None:
  57. if _LOGGER.getEffectiveLevel() <= logging.DEBUG:
  58. mqtt_socket = (
  59. # aiomqtt neither exposes instance of paho.mqtt.client.Client nor socket publicly.
  60. # level condition to avoid accessing protected `mqtt_client._client` in production.
  61. # pylint: disable=protected-access
  62. mqtt_client._client.socket()
  63. )
  64. (mqtt_broker_host, mqtt_broker_port, *_) = mqtt_socket.getpeername()
  65. # https://github.com/sbtinstruments/aiomqtt/blob/v1.2.1/aiomqtt/client.py#L1089
  66. _LOGGER.debug(
  67. "connected to MQTT broker %s:%d",
  68. (
  69. f"[{mqtt_broker_host}]"
  70. if mqtt_socket.family == socket.AF_INET6
  71. else mqtt_broker_host
  72. ),
  73. mqtt_broker_port,
  74. )
  75. async def _run( # pylint: disable=too-many-arguments
  76. *,
  77. mqtt_host: str,
  78. mqtt_port: int,
  79. mqtt_disable_tls: bool,
  80. mqtt_username: typing.Optional[str],
  81. mqtt_password: typing.Optional[str],
  82. mqtt_topic_prefix: str,
  83. retry_count: int,
  84. device_passwords: typing.Dict[str, str],
  85. fetch_device_info: bool,
  86. ) -> None:
  87. _LOGGER.info(
  88. "connecting to MQTT broker %s:%d (TLS %s)",
  89. mqtt_host,
  90. mqtt_port,
  91. "disabled" if mqtt_disable_tls else "enabled",
  92. )
  93. if mqtt_password is not None and mqtt_username is None:
  94. raise ValueError("Missing MQTT username")
  95. async with aiomqtt.Client( # raises aiomqtt.MqttError
  96. hostname=mqtt_host,
  97. port=mqtt_port,
  98. # > The settings [...] usually represent a higher security level than
  99. # > when calling the SSLContext constructor directly.
  100. # https://web.archive.org/web/20230714183106/https://docs.python.org/3/library/ssl.html
  101. tls_context=None if mqtt_disable_tls else ssl.create_default_context(),
  102. username=None if mqtt_username is None else mqtt_username,
  103. password=None if mqtt_password is None else mqtt_password,
  104. will=aiomqtt.Will(
  105. topic=mqtt_topic_prefix + _MQTT_AVAILABILITY_TOPIC,
  106. payload=_MQTT_LAST_WILL_PAYLOAD,
  107. retain=True,
  108. ),
  109. ) as mqtt_client:
  110. _log_mqtt_connected(mqtt_client=mqtt_client)
  111. topic_callbacks: typing.List[typing.Tuple[str, typing.Callable]] = []
  112. for actor_class in (_ButtonAutomator, _CurtainMotor):
  113. async for topic, callback in actor_class.mqtt_subscribe(
  114. mqtt_client=mqtt_client,
  115. mqtt_topic_prefix=mqtt_topic_prefix,
  116. fetch_device_info=fetch_device_info,
  117. ):
  118. topic_callbacks.append((topic, callback))
  119. await _listen(
  120. mqtt_client=mqtt_client,
  121. topic_callbacks=topic_callbacks,
  122. mqtt_topic_prefix=mqtt_topic_prefix,
  123. retry_count=retry_count,
  124. device_passwords=device_passwords,
  125. fetch_device_info=fetch_device_info,
  126. )