__init__.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  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 aiomqtt
  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. _BUTTON_TOPIC_LEVELS_PREFIX = (
  31. "switch",
  32. "switchbot",
  33. _MQTTTopicPlaceholder.MAC_ADDRESS,
  34. )
  35. _CURTAIN_TOPIC_LEVELS_PREFIX = (
  36. "cover",
  37. "switchbot-curtain",
  38. _MQTTTopicPlaceholder.MAC_ADDRESS,
  39. )
  40. class _ButtonAutomator(_MQTTControlledActor):
  41. # https://www.home-assistant.io/integrations/switch.mqtt/
  42. MQTT_COMMAND_TOPIC_LEVELS = _BUTTON_TOPIC_LEVELS_PREFIX + ("set",)
  43. _MQTT_UPDATE_DEVICE_INFO_TOPIC_LEVELS = _BUTTON_TOPIC_LEVELS_PREFIX + (
  44. "request-device-info",
  45. )
  46. MQTT_STATE_TOPIC_LEVELS = _BUTTON_TOPIC_LEVELS_PREFIX + ("state",)
  47. _MQTT_BATTERY_PERCENTAGE_TOPIC_LEVELS = _BUTTON_TOPIC_LEVELS_PREFIX + (
  48. "battery-percentage",
  49. )
  50. def __init__(
  51. self, *, mac_address: str, retry_count: int, password: typing.Optional[str]
  52. ) -> None:
  53. self.__device = switchbot.Switchbot(
  54. mac=mac_address, password=password, retry_count=retry_count
  55. )
  56. super().__init__(
  57. mac_address=mac_address, retry_count=retry_count, password=password
  58. )
  59. def _get_device(self) -> switchbot.SwitchbotDevice:
  60. return self.__device
  61. async def execute_command(
  62. self,
  63. *,
  64. mqtt_message_payload: bytes,
  65. mqtt_client: aiomqtt.Client,
  66. update_device_info: bool,
  67. mqtt_topic_prefix: str,
  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. await self.report_state(
  77. mqtt_client=mqtt_client,
  78. mqtt_topic_prefix=mqtt_topic_prefix,
  79. state=b"ON",
  80. )
  81. if update_device_info:
  82. await self._update_and_report_device_info(
  83. mqtt_client, mqtt_topic_prefix
  84. )
  85. # https://www.home-assistant.io/integrations/switch.mqtt/#payload_off
  86. elif mqtt_message_payload.lower() == b"off":
  87. if not self.__device.turn_off():
  88. _LOGGER.error("failed to turn off switchbot %s", self._mac_address)
  89. else:
  90. _LOGGER.info("switchbot %s turned off", self._mac_address)
  91. await self.report_state(
  92. mqtt_client=mqtt_client,
  93. mqtt_topic_prefix=mqtt_topic_prefix,
  94. state=b"OFF",
  95. )
  96. if update_device_info:
  97. await self._update_and_report_device_info(
  98. mqtt_client, mqtt_topic_prefix
  99. )
  100. else:
  101. _LOGGER.warning(
  102. "unexpected payload %r (expected 'ON' or 'OFF')", mqtt_message_payload
  103. )
  104. class _CurtainMotor(_MQTTControlledActor):
  105. # https://www.home-assistant.io/integrations/cover.mqtt/
  106. MQTT_COMMAND_TOPIC_LEVELS = _CURTAIN_TOPIC_LEVELS_PREFIX + ("set",)
  107. _MQTT_SET_POSITION_TOPIC_LEVELS: typing.Tuple[
  108. _MQTTTopicLevel, ...
  109. ] = _CURTAIN_TOPIC_LEVELS_PREFIX + (
  110. "position",
  111. "set-percent",
  112. )
  113. _MQTT_UPDATE_DEVICE_INFO_TOPIC_LEVELS = _CURTAIN_TOPIC_LEVELS_PREFIX + (
  114. "request-device-info",
  115. )
  116. MQTT_STATE_TOPIC_LEVELS = _CURTAIN_TOPIC_LEVELS_PREFIX + ("state",)
  117. _MQTT_BATTERY_PERCENTAGE_TOPIC_LEVELS = _CURTAIN_TOPIC_LEVELS_PREFIX + (
  118. "battery-percentage",
  119. )
  120. _MQTT_POSITION_TOPIC_LEVELS = _CURTAIN_TOPIC_LEVELS_PREFIX + ("position",)
  121. @classmethod
  122. def get_mqtt_position_topic(cls, prefix: str, mac_address: str) -> str:
  123. return _join_mqtt_topic_levels(
  124. topic_prefix=prefix,
  125. topic_levels=cls._MQTT_POSITION_TOPIC_LEVELS,
  126. mac_address=mac_address,
  127. )
  128. def __init__(
  129. self, *, mac_address: str, retry_count: int, password: typing.Optional[str]
  130. ) -> None:
  131. # > The position of the curtain is saved in self._pos with 0 = open and 100 = closed.
  132. # https://github.com/Danielhiversen/pySwitchbot/blob/0.10.0/switchbot/__init__.py#L150
  133. self.__device = switchbot.SwitchbotCurtain(
  134. mac=mac_address,
  135. password=password,
  136. retry_count=retry_count,
  137. reverse_mode=True,
  138. )
  139. super().__init__(
  140. mac_address=mac_address, retry_count=retry_count, password=password
  141. )
  142. def _get_device(self) -> switchbot.SwitchbotDevice:
  143. return self.__device
  144. async def _report_position(
  145. self,
  146. mqtt_client: aiomqtt.Client, # pylint: disable=duplicate-code; similar param list
  147. mqtt_topic_prefix: str,
  148. ) -> None:
  149. # > position_closed integer (Optional, default: 0)
  150. # > position_open integer (Optional, default: 100)
  151. # https://www.home-assistant.io/integrations/cover.mqtt/#position_closed
  152. # SwitchbotCurtain.get_position() returns a cached value within [0, 100].
  153. # SwitchbotCurtain.open() and .close() update the position optimistically,
  154. # SwitchbotCurtain.update() fetches the real position via bluetooth.
  155. # https://github.com/Danielhiversen/pySwitchbot/blob/0.10.0/switchbot/__init__.py#L202
  156. await self._mqtt_publish(
  157. topic_prefix=mqtt_topic_prefix,
  158. topic_levels=self._MQTT_POSITION_TOPIC_LEVELS,
  159. payload=str(int(self.__device.get_position())).encode(),
  160. mqtt_client=mqtt_client,
  161. )
  162. async def _update_and_report_device_info( # pylint: disable=arguments-differ; report_position is optional
  163. self,
  164. mqtt_client: aiomqtt.Client,
  165. mqtt_topic_prefix: str,
  166. *,
  167. report_position: bool = True,
  168. ) -> None:
  169. await super()._update_and_report_device_info(mqtt_client, mqtt_topic_prefix)
  170. if report_position:
  171. await self._report_position(
  172. mqtt_client=mqtt_client, mqtt_topic_prefix=mqtt_topic_prefix
  173. )
  174. async def execute_command(
  175. self,
  176. *,
  177. mqtt_message_payload: bytes,
  178. mqtt_client: aiomqtt.Client,
  179. update_device_info: bool,
  180. mqtt_topic_prefix: str,
  181. ) -> None:
  182. # https://www.home-assistant.io/integrations/cover.mqtt/#payload_open
  183. report_device_info, report_position = False, False
  184. if mqtt_message_payload.lower() == b"open":
  185. if not self.__device.open():
  186. _LOGGER.error("failed to open switchbot curtain %s", self._mac_address)
  187. else:
  188. _LOGGER.info("switchbot curtain %s opening", self._mac_address)
  189. # > state_opening string (Optional, default: opening)
  190. # https://www.home-assistant.io/integrations/cover.mqtt/#state_opening
  191. await self.report_state(
  192. mqtt_client=mqtt_client,
  193. mqtt_topic_prefix=mqtt_topic_prefix,
  194. state=b"opening",
  195. )
  196. report_device_info = update_device_info
  197. elif mqtt_message_payload.lower() == b"close":
  198. if not self.__device.close():
  199. _LOGGER.error("failed to close switchbot curtain %s", self._mac_address)
  200. else:
  201. _LOGGER.info("switchbot curtain %s closing", self._mac_address)
  202. # https://www.home-assistant.io/integrations/cover.mqtt/#state_closing
  203. await self.report_state(
  204. mqtt_client=mqtt_client,
  205. mqtt_topic_prefix=mqtt_topic_prefix,
  206. state=b"closing",
  207. )
  208. report_device_info = update_device_info
  209. elif mqtt_message_payload.lower() == b"stop":
  210. if not self.__device.stop():
  211. _LOGGER.error("failed to stop switchbot curtain %s", self._mac_address)
  212. else:
  213. _LOGGER.info("switchbot curtain %s stopped", self._mac_address)
  214. # no "stopped" state mentioned at
  215. # https://www.home-assistant.io/integrations/cover.mqtt/#configuration-variables
  216. # https://community.home-assistant.io/t/mqtt-how-to-remove-retained-messages/79029/2
  217. await self.report_state(
  218. mqtt_client=mqtt_client,
  219. mqtt_topic_prefix=mqtt_topic_prefix,
  220. state=b"",
  221. )
  222. report_device_info = update_device_info
  223. report_position = True
  224. else:
  225. _LOGGER.warning(
  226. "unexpected payload %r (expected 'OPEN', 'CLOSE', or 'STOP')",
  227. mqtt_message_payload,
  228. )
  229. if report_device_info:
  230. await self._update_and_report_device_info(
  231. mqtt_client=mqtt_client,
  232. mqtt_topic_prefix=mqtt_topic_prefix,
  233. report_position=report_position,
  234. )
  235. @classmethod
  236. async def _mqtt_set_position_callback(
  237. cls,
  238. *,
  239. mqtt_client: aiomqtt.Client,
  240. message: aiomqtt.Message,
  241. mqtt_topic_prefix: str,
  242. retry_count: int,
  243. device_passwords: typing.Dict[str, str],
  244. fetch_device_info: bool,
  245. ) -> None:
  246. # pylint: disable=unused-argument; callback
  247. # https://github.com/eclipse/paho.mqtt.python/blob/v1.6.1/src/paho/mqtt/client.py#L3556
  248. _LOGGER.debug("received topic=%s payload=%r", message.topic, message.payload)
  249. if message.retain:
  250. _LOGGER.info("ignoring retained message on topic %s", message.topic)
  251. return
  252. actor = cls._init_from_topic(
  253. topic=message.topic,
  254. mqtt_topic_prefix=mqtt_topic_prefix,
  255. expected_topic_levels=cls._MQTT_SET_POSITION_TOPIC_LEVELS,
  256. retry_count=retry_count,
  257. device_passwords=device_passwords,
  258. )
  259. if not actor:
  260. return # warning in _init_from_topic
  261. assert isinstance(message.payload, bytes), message.payload
  262. position_percent = int(message.payload.decode(), 10)
  263. if position_percent < 0 or position_percent > 100:
  264. _LOGGER.warning("invalid position %u%%, ignoring message", position_percent)
  265. return
  266. # pylint: disable=protected-access; own instance
  267. if actor._get_device().set_position(position_percent):
  268. _LOGGER.info(
  269. "set position of switchbot curtain %s to %u%%",
  270. actor._mac_address,
  271. position_percent,
  272. )
  273. else:
  274. _LOGGER.error(
  275. "failed to set position of switchbot curtain %s", actor._mac_address
  276. )
  277. @classmethod
  278. def _get_mqtt_message_callbacks(
  279. # pylint: disable=duplicate-code; param list in parent class
  280. cls,
  281. *,
  282. enable_device_info_update_topic: bool,
  283. ) -> typing.Dict[typing.Tuple[_MQTTTopicLevel, ...], typing.Callable]:
  284. callbacks = super()._get_mqtt_message_callbacks(
  285. enable_device_info_update_topic=enable_device_info_update_topic
  286. )
  287. callbacks[cls._MQTT_SET_POSITION_TOPIC_LEVELS] = cls._mqtt_set_position_callback
  288. return callbacks