__init__.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  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 _MQTTCallbackUserdata, _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.Tuple[_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. def __init__(
  53. self, *, mac_address: str, retry_count: int, password: typing.Optional[str]
  54. ) -> None:
  55. self.__device = switchbot.Switchbot(
  56. mac=mac_address, password=password, retry_count=retry_count
  57. )
  58. super().__init__(
  59. mac_address=mac_address, retry_count=retry_count, password=password
  60. )
  61. def _get_device(self) -> switchbot.SwitchbotDevice:
  62. return self.__device
  63. def execute_command(
  64. self,
  65. mqtt_message_payload: bytes,
  66. mqtt_client: paho.mqtt.client.Client,
  67. update_device_info: bool,
  68. ) -> None:
  69. # https://www.home-assistant.io/integrations/switch.mqtt/#payload_on
  70. if mqtt_message_payload.lower() == b"on":
  71. if not self.__device.turn_on():
  72. _LOGGER.error("failed to turn on switchbot %s", self._mac_address)
  73. else:
  74. _LOGGER.info("switchbot %s turned on", self._mac_address)
  75. # https://www.home-assistant.io/integrations/switch.mqtt/#state_on
  76. self.report_state(mqtt_client=mqtt_client, state=b"ON")
  77. if update_device_info:
  78. self._update_and_report_device_info(mqtt_client)
  79. # https://www.home-assistant.io/integrations/switch.mqtt/#payload_off
  80. elif mqtt_message_payload.lower() == b"off":
  81. if not self.__device.turn_off():
  82. _LOGGER.error("failed to turn off switchbot %s", self._mac_address)
  83. else:
  84. _LOGGER.info("switchbot %s turned off", self._mac_address)
  85. self.report_state(mqtt_client=mqtt_client, state=b"OFF")
  86. if update_device_info:
  87. self._update_and_report_device_info(mqtt_client)
  88. else:
  89. _LOGGER.warning(
  90. "unexpected payload %r (expected 'ON' or 'OFF')", mqtt_message_payload
  91. )
  92. class _CurtainMotor(_MQTTControlledActor):
  93. # https://www.home-assistant.io/integrations/cover.mqtt/
  94. MQTT_COMMAND_TOPIC_LEVELS = _CURTAIN_TOPIC_LEVELS_PREFIX + ("set",)
  95. _MQTT_SET_POSITION_TOPIC_LEVELS = tuple(_CURTAIN_TOPIC_LEVELS_PREFIX) + (
  96. "position",
  97. "set-percent",
  98. )
  99. _MQTT_UPDATE_DEVICE_INFO_TOPIC_LEVELS = _CURTAIN_TOPIC_LEVELS_PREFIX + (
  100. "request-device-info",
  101. )
  102. MQTT_STATE_TOPIC_LEVELS = _CURTAIN_TOPIC_LEVELS_PREFIX + ("state",)
  103. _MQTT_BATTERY_PERCENTAGE_TOPIC_LEVELS = _CURTAIN_TOPIC_LEVELS_PREFIX + (
  104. "battery-percentage",
  105. )
  106. _MQTT_POSITION_TOPIC_LEVELS = _CURTAIN_TOPIC_LEVELS_PREFIX + ("position",)
  107. @classmethod
  108. def get_mqtt_position_topic(cls, mac_address: str) -> str:
  109. return _join_mqtt_topic_levels(
  110. topic_levels=cls._MQTT_POSITION_TOPIC_LEVELS, mac_address=mac_address
  111. )
  112. def __init__(
  113. self, *, mac_address: str, retry_count: int, password: typing.Optional[str]
  114. ) -> None:
  115. # > The position of the curtain is saved in self._pos with 0 = open and 100 = closed.
  116. # https://github.com/Danielhiversen/pySwitchbot/blob/0.10.0/switchbot/__init__.py#L150
  117. self.__device = switchbot.SwitchbotCurtain(
  118. mac=mac_address,
  119. password=password,
  120. retry_count=retry_count,
  121. reverse_mode=True,
  122. )
  123. super().__init__(
  124. mac_address=mac_address, retry_count=retry_count, password=password
  125. )
  126. def _get_device(self) -> switchbot.SwitchbotDevice:
  127. return self.__device
  128. def _report_position(self, mqtt_client: paho.mqtt.client.Client) -> None:
  129. # > position_closed integer (Optional, default: 0)
  130. # > position_open integer (Optional, default: 100)
  131. # https://www.home-assistant.io/integrations/cover.mqtt/#position_closed
  132. # SwitchbotCurtain.get_position() returns a cached value within [0, 100].
  133. # SwitchbotCurtain.open() and .close() update the position optimistically,
  134. # SwitchbotCurtain.update() fetches the real position via bluetooth.
  135. # https://github.com/Danielhiversen/pySwitchbot/blob/0.10.0/switchbot/__init__.py#L202
  136. self._mqtt_publish(
  137. topic_levels=self._MQTT_POSITION_TOPIC_LEVELS,
  138. payload=str(int(self.__device.get_position())).encode(),
  139. mqtt_client=mqtt_client,
  140. )
  141. def _update_and_report_device_info( # pylint: disable=arguments-differ; report_position is optional
  142. self, mqtt_client: paho.mqtt.client.Client, *, report_position: bool = True
  143. ) -> None:
  144. super()._update_and_report_device_info(mqtt_client)
  145. if report_position:
  146. self._report_position(mqtt_client=mqtt_client)
  147. def execute_command(
  148. self,
  149. mqtt_message_payload: bytes,
  150. mqtt_client: paho.mqtt.client.Client,
  151. update_device_info: bool,
  152. ) -> None:
  153. # https://www.home-assistant.io/integrations/cover.mqtt/#payload_open
  154. report_device_info, report_position = False, False
  155. if mqtt_message_payload.lower() == b"open":
  156. if not self.__device.open():
  157. _LOGGER.error("failed to open switchbot curtain %s", self._mac_address)
  158. else:
  159. _LOGGER.info("switchbot curtain %s opening", self._mac_address)
  160. # > state_opening string (Optional, default: opening)
  161. # https://www.home-assistant.io/integrations/cover.mqtt/#state_opening
  162. self.report_state(mqtt_client=mqtt_client, state=b"opening")
  163. report_device_info = update_device_info
  164. elif mqtt_message_payload.lower() == b"close":
  165. if not self.__device.close():
  166. _LOGGER.error("failed to close switchbot curtain %s", self._mac_address)
  167. else:
  168. _LOGGER.info("switchbot curtain %s closing", self._mac_address)
  169. # https://www.home-assistant.io/integrations/cover.mqtt/#state_closing
  170. self.report_state(mqtt_client=mqtt_client, state=b"closing")
  171. report_device_info = update_device_info
  172. elif mqtt_message_payload.lower() == b"stop":
  173. if not self.__device.stop():
  174. _LOGGER.error("failed to stop switchbot curtain %s", self._mac_address)
  175. else:
  176. _LOGGER.info("switchbot curtain %s stopped", self._mac_address)
  177. # no "stopped" state mentioned at
  178. # https://www.home-assistant.io/integrations/cover.mqtt/#configuration-variables
  179. # https://community.home-assistant.io/t/mqtt-how-to-remove-retained-messages/79029/2
  180. self.report_state(mqtt_client=mqtt_client, state=b"")
  181. report_device_info = update_device_info
  182. report_position = True
  183. else:
  184. _LOGGER.warning(
  185. "unexpected payload %r (expected 'OPEN', 'CLOSE', or 'STOP')",
  186. mqtt_message_payload,
  187. )
  188. if report_device_info:
  189. self._update_and_report_device_info(
  190. mqtt_client=mqtt_client, report_position=report_position
  191. )
  192. @classmethod
  193. def _mqtt_set_position_callback(
  194. cls,
  195. mqtt_client: paho.mqtt.client.Client,
  196. userdata: _MQTTCallbackUserdata,
  197. message: paho.mqtt.client.MQTTMessage,
  198. ) -> None:
  199. # pylint: disable=unused-argument; callback
  200. # https://github.com/eclipse/paho.mqtt.python/blob/v1.6.1/src/paho/mqtt/client.py#L3556
  201. _LOGGER.debug("received topic=%s payload=%r", message.topic, message.payload)
  202. if message.retain:
  203. _LOGGER.info("ignoring retained message on topic %s", message.topic)
  204. return
  205. actor = cls._init_from_topic(
  206. userdata=userdata,
  207. topic=message.topic,
  208. expected_topic_levels=cls._MQTT_SET_POSITION_TOPIC_LEVELS,
  209. )
  210. if not actor:
  211. return # warning in _init_from_topic
  212. position_percent = int(message.payload.decode(), 10)
  213. if position_percent < 0 or position_percent > 100:
  214. _LOGGER.warning("invalid position %u%%, ignoring message", position_percent)
  215. return
  216. # pylint: disable=protected-access; own instance
  217. if actor._get_device().set_position(position_percent):
  218. _LOGGER.info(
  219. "set position of switchbot curtain %s to %u%%",
  220. actor._mac_address,
  221. position_percent,
  222. )
  223. else:
  224. _LOGGER.error(
  225. "failed to set position of switchbot curtain %s", actor._mac_address
  226. )
  227. @classmethod
  228. def _get_mqtt_message_callbacks(
  229. cls,
  230. *,
  231. enable_device_info_update_topic: bool,
  232. ) -> typing.Dict[typing.Tuple[_MQTTTopicLevel, ...], typing.Callable]:
  233. callbacks = super()._get_mqtt_message_callbacks(
  234. enable_device_info_update_topic=enable_device_info_update_topic
  235. )
  236. callbacks[cls._MQTT_SET_POSITION_TOPIC_LEVELS] = cls._mqtt_set_position_callback
  237. return callbacks