__init__.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  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. _MQTT_TOPIC_LEVELS_PREFIX: typing.List[_MQTTTopicLevel] = ["homeassistant"]
  32. class _ButtonAutomator(_MQTTControlledActor):
  33. # https://www.home-assistant.io/integrations/switch.mqtt/
  34. MQTT_COMMAND_TOPIC_LEVELS = _MQTT_TOPIC_LEVELS_PREFIX + [
  35. "switch",
  36. "switchbot",
  37. _MQTTTopicPlaceholder.MAC_ADDRESS,
  38. "set",
  39. ]
  40. MQTT_STATE_TOPIC_LEVELS = _MQTT_TOPIC_LEVELS_PREFIX + [
  41. "switch",
  42. "switchbot",
  43. _MQTTTopicPlaceholder.MAC_ADDRESS,
  44. "state",
  45. ]
  46. _MQTT_BATTERY_PERCENTAGE_TOPIC_LEVELS = _MQTT_TOPIC_LEVELS_PREFIX + [
  47. "switch",
  48. "switchbot",
  49. _MQTTTopicPlaceholder.MAC_ADDRESS,
  50. "battery-percentage",
  51. ]
  52. # for downward compatibility (will be removed in v3):
  53. _MQTT_BATTERY_PERCENTAGE_TOPIC_LEVELS_LEGACY = _MQTT_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 = _MQTT_TOPIC_LEVELS_PREFIX + [
  110. "cover",
  111. "switchbot-curtain",
  112. _MQTTTopicPlaceholder.MAC_ADDRESS,
  113. "set",
  114. ]
  115. MQTT_STATE_TOPIC_LEVELS = _MQTT_TOPIC_LEVELS_PREFIX + [
  116. "cover",
  117. "switchbot-curtain",
  118. _MQTTTopicPlaceholder.MAC_ADDRESS,
  119. "state",
  120. ]
  121. _MQTT_BATTERY_PERCENTAGE_TOPIC_LEVELS = _MQTT_TOPIC_LEVELS_PREFIX + [
  122. "cover",
  123. "switchbot-curtain",
  124. _MQTTTopicPlaceholder.MAC_ADDRESS,
  125. "battery-percentage",
  126. ]
  127. _MQTT_POSITION_TOPIC_LEVELS = _MQTT_TOPIC_LEVELS_PREFIX + [
  128. "cover",
  129. "switchbot-curtain",
  130. _MQTTTopicPlaceholder.MAC_ADDRESS,
  131. "position",
  132. ]
  133. @classmethod
  134. def get_mqtt_position_topic(cls, mac_address: str) -> str:
  135. return _join_mqtt_topic_levels(
  136. topic_levels=cls._MQTT_POSITION_TOPIC_LEVELS, mac_address=mac_address
  137. )
  138. def __init__(
  139. self, *, mac_address: str, retry_count: int, password: typing.Optional[str]
  140. ) -> None:
  141. # > The position of the curtain is saved in self._pos with 0 = open and 100 = closed.
  142. # https://github.com/Danielhiversen/pySwitchbot/blob/0.10.0/switchbot/__init__.py#L150
  143. self.__device = switchbot.SwitchbotCurtain(
  144. mac=mac_address,
  145. password=password,
  146. retry_count=retry_count,
  147. reverse_mode=True,
  148. )
  149. super().__init__(
  150. mac_address=mac_address, retry_count=retry_count, password=password
  151. )
  152. def _get_device(self) -> switchbot.SwitchbotDevice:
  153. return self.__device
  154. def _report_position(self, mqtt_client: paho.mqtt.client.Client) -> None:
  155. # > position_closed integer (Optional, default: 0)
  156. # > position_open integer (Optional, default: 100)
  157. # https://www.home-assistant.io/integrations/cover.mqtt/#position_closed
  158. # SwitchbotCurtain.get_position() returns a cached value within [0, 100].
  159. # SwitchbotCurtain.open() and .close() update the position optimistically,
  160. # SwitchbotCurtain.update() fetches the real position via bluetooth.
  161. # https://github.com/Danielhiversen/pySwitchbot/blob/0.10.0/switchbot/__init__.py#L202
  162. self._mqtt_publish(
  163. topic_levels=self._MQTT_POSITION_TOPIC_LEVELS,
  164. payload=str(int(self.__device.get_position())).encode(),
  165. mqtt_client=mqtt_client,
  166. )
  167. def _update_and_report_device_info( # pylint: disable=arguments-differ; report_position is optional
  168. self, mqtt_client: paho.mqtt.client.Client, *, report_position: bool = True
  169. ) -> None:
  170. super()._update_and_report_device_info(mqtt_client)
  171. if report_position:
  172. self._report_position(mqtt_client=mqtt_client)
  173. def execute_command(
  174. self,
  175. mqtt_message_payload: bytes,
  176. mqtt_client: paho.mqtt.client.Client,
  177. update_device_info: bool,
  178. ) -> None:
  179. # https://www.home-assistant.io/integrations/cover.mqtt/#payload_open
  180. report_device_info, report_position = False, False
  181. if mqtt_message_payload.lower() == b"open":
  182. if not self.__device.open():
  183. _LOGGER.error("failed to open switchbot curtain %s", self._mac_address)
  184. else:
  185. _LOGGER.info("switchbot curtain %s opening", self._mac_address)
  186. # > state_opening string (Optional, default: opening)
  187. # https://www.home-assistant.io/integrations/cover.mqtt/#state_opening
  188. self.report_state(mqtt_client=mqtt_client, state=b"opening")
  189. report_device_info = update_device_info
  190. elif mqtt_message_payload.lower() == b"close":
  191. if not self.__device.close():
  192. _LOGGER.error("failed to close switchbot curtain %s", self._mac_address)
  193. else:
  194. _LOGGER.info("switchbot curtain %s closing", self._mac_address)
  195. # https://www.home-assistant.io/integrations/cover.mqtt/#state_closing
  196. self.report_state(mqtt_client=mqtt_client, state=b"closing")
  197. report_device_info = update_device_info
  198. elif mqtt_message_payload.lower() == b"stop":
  199. if not self.__device.stop():
  200. _LOGGER.error("failed to stop switchbot curtain %s", self._mac_address)
  201. else:
  202. _LOGGER.info("switchbot curtain %s stopped", self._mac_address)
  203. # no "stopped" state mentioned at
  204. # https://www.home-assistant.io/integrations/cover.mqtt/#configuration-variables
  205. # https://community.home-assistant.io/t/mqtt-how-to-remove-retained-messages/79029/2
  206. self.report_state(mqtt_client=mqtt_client, state=b"")
  207. report_device_info = update_device_info
  208. report_position = True
  209. else:
  210. _LOGGER.warning(
  211. "unexpected payload %r (expected 'OPEN', 'CLOSE', or 'STOP')",
  212. mqtt_message_payload,
  213. )
  214. if report_device_info:
  215. self._update_and_report_device_info(
  216. mqtt_client=mqtt_client, report_position=report_position
  217. )