__init__.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  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 typing
  20. import bluepy.btle
  21. import paho.mqtt.client
  22. import switchbot
  23. from switchbot_mqtt._actors._base import _MQTTControlledActor
  24. from switchbot_mqtt._utils import (
  25. _join_mqtt_topic_levels,
  26. _MQTTTopicLevel,
  27. _MQTTTopicPlaceholder,
  28. )
  29. _LOGGER = logging.getLogger(__name__)
  30. # "homeassistant" for historic reason, may be parametrized in future
  31. _TOPIC_LEVELS_PREFIX: typing.List[_MQTTTopicLevel] = ["homeassistant"]
  32. _BUTTON_TOPIC_LEVELS_PREFIX = _TOPIC_LEVELS_PREFIX + [
  33. "switch",
  34. "switchbot",
  35. _MQTTTopicPlaceholder.MAC_ADDRESS,
  36. ]
  37. _CURTAIN_TOPIC_LEVELS_PREFIX = _TOPIC_LEVELS_PREFIX + [
  38. "cover",
  39. "switchbot-curtain",
  40. _MQTTTopicPlaceholder.MAC_ADDRESS,
  41. ]
  42. class _ButtonAutomator(_MQTTControlledActor):
  43. # https://www.home-assistant.io/integrations/switch.mqtt/
  44. MQTT_COMMAND_TOPIC_LEVELS = _BUTTON_TOPIC_LEVELS_PREFIX + ["set"]
  45. _MQTT_UPDATE_DEVICE_INFO_TOPIC_LEVELS = _BUTTON_TOPIC_LEVELS_PREFIX + [
  46. "request-device-info"
  47. ]
  48. MQTT_STATE_TOPIC_LEVELS = _BUTTON_TOPIC_LEVELS_PREFIX + ["state"]
  49. _MQTT_BATTERY_PERCENTAGE_TOPIC_LEVELS = _BUTTON_TOPIC_LEVELS_PREFIX + [
  50. "battery-percentage"
  51. ]
  52. # for downward compatibility (will be removed in v3):
  53. _MQTT_BATTERY_PERCENTAGE_TOPIC_LEVELS_LEGACY = _TOPIC_LEVELS_PREFIX + [
  54. "cover",
  55. "switchbot",
  56. _MQTTTopicPlaceholder.MAC_ADDRESS,
  57. "battery-percentage",
  58. ]
  59. def __init__(
  60. self, *, mac_address: str, retry_count: int, password: typing.Optional[str]
  61. ) -> None:
  62. self.__device = switchbot.Switchbot(
  63. mac=mac_address, password=password, retry_count=retry_count
  64. )
  65. super().__init__(
  66. mac_address=mac_address, retry_count=retry_count, password=password
  67. )
  68. def _get_device(self) -> switchbot.SwitchbotDevice:
  69. return self.__device
  70. def _report_battery_level(self, mqtt_client: paho.mqtt.client.Client) -> None:
  71. super()._report_battery_level(mqtt_client=mqtt_client)
  72. # kept for downward compatibility (will be removed in v3)
  73. self._mqtt_publish(
  74. topic_levels=self._MQTT_BATTERY_PERCENTAGE_TOPIC_LEVELS_LEGACY,
  75. payload=str(self._get_device().get_battery_percent()).encode(),
  76. mqtt_client=mqtt_client,
  77. )
  78. def execute_command(
  79. self,
  80. mqtt_message_payload: bytes,
  81. mqtt_client: paho.mqtt.client.Client,
  82. update_device_info: bool,
  83. ) -> None:
  84. # https://www.home-assistant.io/integrations/switch.mqtt/#payload_on
  85. if mqtt_message_payload.lower() == b"on":
  86. if not self.__device.turn_on():
  87. _LOGGER.error("failed to turn on switchbot %s", self._mac_address)
  88. else:
  89. _LOGGER.info("switchbot %s turned on", self._mac_address)
  90. # https://www.home-assistant.io/integrations/switch.mqtt/#state_on
  91. self.report_state(mqtt_client=mqtt_client, state=b"ON")
  92. if update_device_info:
  93. self._update_and_report_device_info(mqtt_client)
  94. # https://www.home-assistant.io/integrations/switch.mqtt/#payload_off
  95. elif mqtt_message_payload.lower() == b"off":
  96. if not self.__device.turn_off():
  97. _LOGGER.error("failed to turn off switchbot %s", self._mac_address)
  98. else:
  99. _LOGGER.info("switchbot %s turned off", self._mac_address)
  100. self.report_state(mqtt_client=mqtt_client, state=b"OFF")
  101. if update_device_info:
  102. self._update_and_report_device_info(mqtt_client)
  103. else:
  104. _LOGGER.warning(
  105. "unexpected payload %r (expected 'ON' or 'OFF')", mqtt_message_payload
  106. )
  107. class _CurtainMotor(_MQTTControlledActor):
  108. # https://www.home-assistant.io/integrations/cover.mqtt/
  109. MQTT_COMMAND_TOPIC_LEVELS = _CURTAIN_TOPIC_LEVELS_PREFIX + ["set"]
  110. _MQTT_UPDATE_DEVICE_INFO_TOPIC_LEVELS = _CURTAIN_TOPIC_LEVELS_PREFIX + [
  111. "request-device-info"
  112. ]
  113. MQTT_STATE_TOPIC_LEVELS = _CURTAIN_TOPIC_LEVELS_PREFIX + ["state"]
  114. _MQTT_BATTERY_PERCENTAGE_TOPIC_LEVELS = _CURTAIN_TOPIC_LEVELS_PREFIX + [
  115. "battery-percentage"
  116. ]
  117. _MQTT_POSITION_TOPIC_LEVELS = _CURTAIN_TOPIC_LEVELS_PREFIX + ["position"]
  118. @classmethod
  119. def get_mqtt_position_topic(cls, mac_address: str) -> str:
  120. return _join_mqtt_topic_levels(
  121. topic_levels=cls._MQTT_POSITION_TOPIC_LEVELS, mac_address=mac_address
  122. )
  123. def __init__(
  124. self, *, mac_address: str, retry_count: int, password: typing.Optional[str]
  125. ) -> None:
  126. # > The position of the curtain is saved in self._pos with 0 = open and 100 = closed.
  127. # https://github.com/Danielhiversen/pySwitchbot/blob/0.10.0/switchbot/__init__.py#L150
  128. self.__device = switchbot.SwitchbotCurtain(
  129. mac=mac_address,
  130. password=password,
  131. retry_count=retry_count,
  132. reverse_mode=True,
  133. )
  134. super().__init__(
  135. mac_address=mac_address, retry_count=retry_count, password=password
  136. )
  137. def _get_device(self) -> switchbot.SwitchbotDevice:
  138. return self.__device
  139. def _report_position(self, mqtt_client: paho.mqtt.client.Client) -> None:
  140. # > position_closed integer (Optional, default: 0)
  141. # > position_open integer (Optional, default: 100)
  142. # https://www.home-assistant.io/integrations/cover.mqtt/#position_closed
  143. # SwitchbotCurtain.get_position() returns a cached value within [0, 100].
  144. # SwitchbotCurtain.open() and .close() update the position optimistically,
  145. # SwitchbotCurtain.update() fetches the real position via bluetooth.
  146. # https://github.com/Danielhiversen/pySwitchbot/blob/0.10.0/switchbot/__init__.py#L202
  147. self._mqtt_publish(
  148. topic_levels=self._MQTT_POSITION_TOPIC_LEVELS,
  149. payload=str(int(self.__device.get_position())).encode(),
  150. mqtt_client=mqtt_client,
  151. )
  152. def _update_and_report_device_info( # pylint: disable=arguments-differ; report_position is optional
  153. self, mqtt_client: paho.mqtt.client.Client, *, report_position: bool = True
  154. ) -> None:
  155. super()._update_and_report_device_info(mqtt_client)
  156. if report_position:
  157. self._report_position(mqtt_client=mqtt_client)
  158. def execute_command(
  159. self,
  160. mqtt_message_payload: bytes,
  161. mqtt_client: paho.mqtt.client.Client,
  162. update_device_info: bool,
  163. ) -> None:
  164. # https://www.home-assistant.io/integrations/cover.mqtt/#payload_open
  165. report_device_info, report_position = False, False
  166. if mqtt_message_payload.lower() == b"open":
  167. if not self.__device.open():
  168. _LOGGER.error("failed to open switchbot curtain %s", self._mac_address)
  169. else:
  170. _LOGGER.info("switchbot curtain %s opening", self._mac_address)
  171. # > state_opening string (Optional, default: opening)
  172. # https://www.home-assistant.io/integrations/cover.mqtt/#state_opening
  173. self.report_state(mqtt_client=mqtt_client, state=b"opening")
  174. report_device_info = update_device_info
  175. elif mqtt_message_payload.lower() == b"close":
  176. if not self.__device.close():
  177. _LOGGER.error("failed to close switchbot curtain %s", self._mac_address)
  178. else:
  179. _LOGGER.info("switchbot curtain %s closing", self._mac_address)
  180. # https://www.home-assistant.io/integrations/cover.mqtt/#state_closing
  181. self.report_state(mqtt_client=mqtt_client, state=b"closing")
  182. report_device_info = update_device_info
  183. elif mqtt_message_payload.lower() == b"stop":
  184. if not self.__device.stop():
  185. _LOGGER.error("failed to stop switchbot curtain %s", self._mac_address)
  186. else:
  187. _LOGGER.info("switchbot curtain %s stopped", self._mac_address)
  188. # no "stopped" state mentioned at
  189. # https://www.home-assistant.io/integrations/cover.mqtt/#configuration-variables
  190. # https://community.home-assistant.io/t/mqtt-how-to-remove-retained-messages/79029/2
  191. self.report_state(mqtt_client=mqtt_client, state=b"")
  192. report_device_info = update_device_info
  193. report_position = True
  194. else:
  195. _LOGGER.warning(
  196. "unexpected payload %r (expected 'OPEN', 'CLOSE', or 'STOP')",
  197. mqtt_message_payload,
  198. )
  199. if report_device_info:
  200. self._update_and_report_device_info(
  201. mqtt_client=mqtt_client, report_position=report_position
  202. )