__init__.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  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.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_SET_POSITION_TOPIC_LEVELS = tuple(_CURTAIN_TOPIC_LEVELS_PREFIX) + (
  111. "position",
  112. "set-percent",
  113. )
  114. _MQTT_UPDATE_DEVICE_INFO_TOPIC_LEVELS = _CURTAIN_TOPIC_LEVELS_PREFIX + [
  115. "request-device-info"
  116. ]
  117. MQTT_STATE_TOPIC_LEVELS = _CURTAIN_TOPIC_LEVELS_PREFIX + ["state"]
  118. _MQTT_BATTERY_PERCENTAGE_TOPIC_LEVELS = _CURTAIN_TOPIC_LEVELS_PREFIX + [
  119. "battery-percentage"
  120. ]
  121. _MQTT_POSITION_TOPIC_LEVELS = _CURTAIN_TOPIC_LEVELS_PREFIX + ["position"]
  122. @classmethod
  123. def get_mqtt_position_topic(cls, mac_address: str) -> str:
  124. return _join_mqtt_topic_levels(
  125. topic_levels=cls._MQTT_POSITION_TOPIC_LEVELS, mac_address=mac_address
  126. )
  127. def __init__(
  128. self, *, mac_address: str, retry_count: int, password: typing.Optional[str]
  129. ) -> None:
  130. # > The position of the curtain is saved in self._pos with 0 = open and 100 = closed.
  131. # https://github.com/Danielhiversen/pySwitchbot/blob/0.10.0/switchbot/__init__.py#L150
  132. self.__device = switchbot.SwitchbotCurtain(
  133. mac=mac_address,
  134. password=password,
  135. retry_count=retry_count,
  136. reverse_mode=True,
  137. )
  138. super().__init__(
  139. mac_address=mac_address, retry_count=retry_count, password=password
  140. )
  141. def _get_device(self) -> switchbot.SwitchbotDevice:
  142. return self.__device
  143. def _report_position(self, mqtt_client: paho.mqtt.client.Client) -> None:
  144. # > position_closed integer (Optional, default: 0)
  145. # > position_open integer (Optional, default: 100)
  146. # https://www.home-assistant.io/integrations/cover.mqtt/#position_closed
  147. # SwitchbotCurtain.get_position() returns a cached value within [0, 100].
  148. # SwitchbotCurtain.open() and .close() update the position optimistically,
  149. # SwitchbotCurtain.update() fetches the real position via bluetooth.
  150. # https://github.com/Danielhiversen/pySwitchbot/blob/0.10.0/switchbot/__init__.py#L202
  151. self._mqtt_publish(
  152. topic_levels=self._MQTT_POSITION_TOPIC_LEVELS,
  153. payload=str(int(self.__device.get_position())).encode(),
  154. mqtt_client=mqtt_client,
  155. )
  156. def _update_and_report_device_info( # pylint: disable=arguments-differ; report_position is optional
  157. self, mqtt_client: paho.mqtt.client.Client, *, report_position: bool = True
  158. ) -> None:
  159. super()._update_and_report_device_info(mqtt_client)
  160. if report_position:
  161. self._report_position(mqtt_client=mqtt_client)
  162. def execute_command(
  163. self,
  164. mqtt_message_payload: bytes,
  165. mqtt_client: paho.mqtt.client.Client,
  166. update_device_info: bool,
  167. ) -> None:
  168. # https://www.home-assistant.io/integrations/cover.mqtt/#payload_open
  169. report_device_info, report_position = False, False
  170. if mqtt_message_payload.lower() == b"open":
  171. if not self.__device.open():
  172. _LOGGER.error("failed to open switchbot curtain %s", self._mac_address)
  173. else:
  174. _LOGGER.info("switchbot curtain %s opening", self._mac_address)
  175. # > state_opening string (Optional, default: opening)
  176. # https://www.home-assistant.io/integrations/cover.mqtt/#state_opening
  177. self.report_state(mqtt_client=mqtt_client, state=b"opening")
  178. report_device_info = update_device_info
  179. elif mqtt_message_payload.lower() == b"close":
  180. if not self.__device.close():
  181. _LOGGER.error("failed to close switchbot curtain %s", self._mac_address)
  182. else:
  183. _LOGGER.info("switchbot curtain %s closing", self._mac_address)
  184. # https://www.home-assistant.io/integrations/cover.mqtt/#state_closing
  185. self.report_state(mqtt_client=mqtt_client, state=b"closing")
  186. report_device_info = update_device_info
  187. elif mqtt_message_payload.lower() == b"stop":
  188. if not self.__device.stop():
  189. _LOGGER.error("failed to stop switchbot curtain %s", self._mac_address)
  190. else:
  191. _LOGGER.info("switchbot curtain %s stopped", self._mac_address)
  192. # no "stopped" state mentioned at
  193. # https://www.home-assistant.io/integrations/cover.mqtt/#configuration-variables
  194. # https://community.home-assistant.io/t/mqtt-how-to-remove-retained-messages/79029/2
  195. self.report_state(mqtt_client=mqtt_client, state=b"")
  196. report_device_info = update_device_info
  197. report_position = True
  198. else:
  199. _LOGGER.warning(
  200. "unexpected payload %r (expected 'OPEN', 'CLOSE', or 'STOP')",
  201. mqtt_message_payload,
  202. )
  203. if report_device_info:
  204. self._update_and_report_device_info(
  205. mqtt_client=mqtt_client, report_position=report_position
  206. )
  207. @classmethod
  208. def _mqtt_set_position_callback(
  209. cls,
  210. mqtt_client: paho.mqtt.client.Client,
  211. userdata: _MQTTCallbackUserdata,
  212. message: paho.mqtt.client.MQTTMessage,
  213. ) -> None:
  214. # pylint: disable=unused-argument; callback
  215. # https://github.com/eclipse/paho.mqtt.python/blob/v1.6.1/src/paho/mqtt/client.py#L3556
  216. _LOGGER.debug("received topic=%s payload=%r", message.topic, message.payload)
  217. if message.retain:
  218. _LOGGER.info("ignoring retained message on topic %s", message.topic)
  219. return
  220. actor = cls._init_from_topic(
  221. userdata=userdata,
  222. topic=message.topic,
  223. expected_topic_levels=cls._MQTT_SET_POSITION_TOPIC_LEVELS,
  224. )
  225. if not actor:
  226. return # warning in _init_from_topic
  227. position_percent = int(message.payload.decode(), 10)
  228. if position_percent < 0 or position_percent > 100:
  229. _LOGGER.warning("invalid position %u%%, ignoring message", position_percent)
  230. return
  231. # pylint: disable=protected-access; own instance
  232. if actor._get_device().set_position(position_percent):
  233. _LOGGER.info(
  234. "set position of switchbot curtain %s to %u%%",
  235. actor._mac_address,
  236. position_percent,
  237. )
  238. else:
  239. _LOGGER.error(
  240. "failed to set position of switchbot curtain %s", actor._mac_address
  241. )
  242. @classmethod
  243. def _get_mqtt_message_callbacks(
  244. cls,
  245. *,
  246. enable_device_info_update_topic: bool,
  247. ) -> typing.Dict[typing.Tuple[_MQTTTopicLevel, ...], typing.Callable]:
  248. callbacks = super()._get_mqtt_message_callbacks(
  249. enable_device_info_update_topic=enable_device_info_update_topic
  250. )
  251. callbacks[cls._MQTT_SET_POSITION_TOPIC_LEVELS] = cls._mqtt_set_position_callback
  252. return callbacks