__init__.py 12 KB

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