1
0

__init__.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586
  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 abc
  19. import argparse
  20. import collections
  21. import enum
  22. import json
  23. import logging
  24. import pathlib
  25. import queue
  26. import re
  27. import shlex
  28. import typing
  29. import bluepy.btle
  30. import paho.mqtt.client
  31. import switchbot
  32. _LOGGER = logging.getLogger(__name__)
  33. _MAC_ADDRESS_REGEX = re.compile(r"^[0-9a-f]{2}(:[0-9a-f]{2}){5}$")
  34. class _MQTTTopicPlaceholder(enum.Enum):
  35. MAC_ADDRESS = "MAC_ADDRESS"
  36. _MQTTTopicLevel = typing.Union[str, _MQTTTopicPlaceholder]
  37. # "homeassistant" for historic reason, may be parametrized in future
  38. _MQTT_TOPIC_LEVELS_PREFIX: typing.List[_MQTTTopicLevel] = ["homeassistant"]
  39. def _join_mqtt_topic_levels(
  40. topic_levels: typing.List[_MQTTTopicLevel], mac_address: str
  41. ) -> str:
  42. return "/".join(
  43. mac_address if l == _MQTTTopicPlaceholder.MAC_ADDRESS else typing.cast(str, l)
  44. for l in topic_levels
  45. )
  46. def _mac_address_valid(mac_address: str) -> bool:
  47. return _MAC_ADDRESS_REGEX.match(mac_address.lower()) is not None
  48. class _QueueLogHandler(logging.Handler):
  49. """
  50. logging.handlers.QueueHandler drops exc_info
  51. """
  52. # TypeError: 'type' object is not subscriptable
  53. def __init__(self, log_queue: "queue.Queue[logging.LogRecord]") -> None:
  54. self.log_queue = log_queue
  55. super().__init__()
  56. def emit(self, record: logging.LogRecord) -> None:
  57. self.log_queue.put(record)
  58. class _MQTTCallbackUserdata:
  59. # pylint: disable=too-few-public-methods; @dataclasses.dataclass when python_requires>=3.7
  60. def __init__(
  61. self,
  62. *,
  63. retry_count: int,
  64. device_passwords: typing.Dict[str, str],
  65. fetch_device_info: bool,
  66. ) -> None:
  67. self.retry_count = retry_count
  68. self.device_passwords = device_passwords
  69. self.fetch_device_info = fetch_device_info
  70. def __eq__(self, other: object) -> bool:
  71. return isinstance(other, type(self)) and vars(self) == vars(other)
  72. class _MQTTControlledActor(abc.ABC):
  73. MQTT_COMMAND_TOPIC_LEVELS: typing.List[_MQTTTopicLevel] = NotImplemented
  74. MQTT_STATE_TOPIC_LEVELS: typing.List[_MQTTTopicLevel] = NotImplemented
  75. _MQTT_BATTERY_PERCENTAGE_TOPIC_LEVELS: typing.List[_MQTTTopicLevel] = NotImplemented
  76. @classmethod
  77. def get_mqtt_battery_percentage_topic(cls, mac_address: str) -> str:
  78. return _join_mqtt_topic_levels(
  79. topic_levels=cls._MQTT_BATTERY_PERCENTAGE_TOPIC_LEVELS,
  80. mac_address=mac_address,
  81. )
  82. @abc.abstractmethod
  83. def __init__(
  84. self, *, mac_address: str, retry_count: int, password: typing.Optional[str]
  85. ) -> None:
  86. # alternative: pySwitchbot >=0.10.0 provides SwitchbotDevice.get_mac()
  87. self._mac_address = mac_address
  88. @abc.abstractmethod
  89. def _get_device(self) -> switchbot.SwitchbotDevice:
  90. raise NotImplementedError()
  91. def _update_device_info(self) -> None:
  92. log_queue: queue.Queue[logging.LogRecord] = queue.Queue(maxsize=0)
  93. logging.getLogger("switchbot").addHandler(_QueueLogHandler(log_queue))
  94. try:
  95. self._get_device().update()
  96. # pySwitchbot>=v0.10.1 catches bluepy.btle.BTLEManagementError :(
  97. # https://github.com/Danielhiversen/pySwitchbot/blob/0.10.1/switchbot/__init__.py#L141
  98. while not log_queue.empty():
  99. log_record = log_queue.get()
  100. if log_record.exc_info:
  101. exc: typing.Optional[BaseException] = log_record.exc_info[1]
  102. if (
  103. isinstance(exc, bluepy.btle.BTLEManagementError)
  104. and exc.emsg == "Permission Denied"
  105. ):
  106. raise exc
  107. except bluepy.btle.BTLEManagementError as exc:
  108. if (
  109. exc.emsg == "Permission Denied"
  110. and exc.message == "Failed to execute management command 'le on'"
  111. ):
  112. raise PermissionError(
  113. "bluepy-helper failed to enable low energy mode"
  114. " due to insufficient permissions."
  115. "\nSee https://github.com/IanHarvey/bluepy/issues/313#issuecomment-428324639"
  116. ", https://github.com/fphammerle/switchbot-mqtt/pull/31#issuecomment-846383603"
  117. ", and https://github.com/IanHarvey/bluepy/blob/v/1.3.0/bluepy"
  118. "/bluepy-helper.c#L1260."
  119. "\nInsecure workaround:"
  120. "\n1. sudo apt-get install --no-install-recommends libcap2-bin"
  121. f"\n2. sudo setcap cap_net_admin+ep {shlex.quote(bluepy.btle.helperExe)}"
  122. "\n3. restart switchbot-mqtt"
  123. "\nIn docker-based setups, you could use"
  124. " `sudo docker run --cap-drop ALL --cap-add NET_ADMIN --user 0 …`"
  125. " (seriously insecure)."
  126. ) from exc
  127. raise
  128. def _report_battery_level(self, mqtt_client: paho.mqtt.client.Client) -> None:
  129. # > battery: Percentage of battery that is left.
  130. # https://www.home-assistant.io/integrations/sensor/#device-class
  131. self._mqtt_publish(
  132. topic_levels=self._MQTT_BATTERY_PERCENTAGE_TOPIC_LEVELS,
  133. payload=str(self._get_device().get_battery_percent()).encode(),
  134. mqtt_client=mqtt_client,
  135. )
  136. def _update_and_report_device_info(
  137. self, mqtt_client: paho.mqtt.client.Client
  138. ) -> None:
  139. self._update_device_info()
  140. self._report_battery_level(mqtt_client=mqtt_client)
  141. @abc.abstractmethod
  142. def execute_command(
  143. self,
  144. mqtt_message_payload: bytes,
  145. mqtt_client: paho.mqtt.client.Client,
  146. update_device_info: bool,
  147. ) -> None:
  148. raise NotImplementedError()
  149. @classmethod
  150. def _mqtt_command_callback(
  151. cls,
  152. mqtt_client: paho.mqtt.client.Client,
  153. userdata: _MQTTCallbackUserdata,
  154. message: paho.mqtt.client.MQTTMessage,
  155. ) -> None:
  156. # pylint: disable=unused-argument; callback
  157. # https://github.com/eclipse/paho.mqtt.python/blob/v1.5.0/src/paho/mqtt/client.py#L469
  158. _LOGGER.debug("received topic=%s payload=%r", message.topic, message.payload)
  159. if message.retain:
  160. _LOGGER.info("ignoring retained message")
  161. return
  162. topic_split = message.topic.split("/")
  163. if len(topic_split) != len(cls.MQTT_COMMAND_TOPIC_LEVELS):
  164. _LOGGER.warning("unexpected topic %s", message.topic)
  165. return
  166. mac_address = None
  167. for given_part, expected_part in zip(
  168. topic_split, cls.MQTT_COMMAND_TOPIC_LEVELS
  169. ):
  170. if expected_part == _MQTTTopicPlaceholder.MAC_ADDRESS:
  171. mac_address = given_part
  172. elif expected_part != given_part:
  173. _LOGGER.warning("unexpected topic %s", message.topic)
  174. return
  175. assert mac_address
  176. if not _mac_address_valid(mac_address):
  177. _LOGGER.warning("invalid mac address %s", mac_address)
  178. return
  179. actor = cls(
  180. mac_address=mac_address,
  181. retry_count=userdata.retry_count,
  182. password=userdata.device_passwords.get(mac_address, None),
  183. )
  184. actor.execute_command(
  185. mqtt_message_payload=message.payload,
  186. mqtt_client=mqtt_client,
  187. # consider calling update+report method directly when adding support for battery levels
  188. update_device_info=userdata.fetch_device_info,
  189. )
  190. @classmethod
  191. def mqtt_subscribe(cls, mqtt_client: paho.mqtt.client.Client) -> None:
  192. command_topic = "/".join(
  193. "+" if isinstance(l, _MQTTTopicPlaceholder) else l
  194. for l in cls.MQTT_COMMAND_TOPIC_LEVELS
  195. )
  196. _LOGGER.info("subscribing to MQTT topic %r", command_topic)
  197. mqtt_client.subscribe(command_topic)
  198. mqtt_client.message_callback_add(
  199. sub=command_topic,
  200. callback=cls._mqtt_command_callback,
  201. )
  202. def _mqtt_publish(
  203. self,
  204. *,
  205. topic_levels: typing.List[_MQTTTopicLevel],
  206. payload: bytes,
  207. mqtt_client: paho.mqtt.client.Client,
  208. ) -> None:
  209. topic = _join_mqtt_topic_levels(
  210. topic_levels=topic_levels, mac_address=self._mac_address
  211. )
  212. # https://pypi.org/project/paho-mqtt/#publishing
  213. _LOGGER.debug("publishing topic=%s payload=%r", topic, payload)
  214. message_info: paho.mqtt.client.MQTTMessageInfo = mqtt_client.publish(
  215. topic=topic, payload=payload, retain=True
  216. )
  217. # wait before checking status?
  218. if message_info.rc != paho.mqtt.client.MQTT_ERR_SUCCESS:
  219. _LOGGER.error(
  220. "Failed to publish MQTT message on topic %s (rc=%d)",
  221. topic,
  222. message_info.rc,
  223. )
  224. def report_state(self, state: bytes, mqtt_client: paho.mqtt.client.Client) -> None:
  225. self._mqtt_publish(
  226. topic_levels=self.MQTT_STATE_TOPIC_LEVELS,
  227. payload=state,
  228. mqtt_client=mqtt_client,
  229. )
  230. class _ButtonAutomator(_MQTTControlledActor):
  231. # https://www.home-assistant.io/integrations/switch.mqtt/
  232. MQTT_COMMAND_TOPIC_LEVELS = _MQTT_TOPIC_LEVELS_PREFIX + [
  233. "switch",
  234. "switchbot",
  235. _MQTTTopicPlaceholder.MAC_ADDRESS,
  236. "set",
  237. ]
  238. MQTT_STATE_TOPIC_LEVELS = _MQTT_TOPIC_LEVELS_PREFIX + [
  239. "switch",
  240. "switchbot",
  241. _MQTTTopicPlaceholder.MAC_ADDRESS,
  242. "state",
  243. ]
  244. _MQTT_BATTERY_PERCENTAGE_TOPIC_LEVELS = _MQTT_TOPIC_LEVELS_PREFIX + [
  245. "switch",
  246. "switchbot",
  247. _MQTTTopicPlaceholder.MAC_ADDRESS,
  248. "battery-percentage",
  249. ]
  250. # for downward compatibility (will be removed in v3):
  251. _MQTT_BATTERY_PERCENTAGE_TOPIC_LEVELS_LEGACY = _MQTT_TOPIC_LEVELS_PREFIX + [
  252. "cover",
  253. "switchbot",
  254. _MQTTTopicPlaceholder.MAC_ADDRESS,
  255. "battery-percentage",
  256. ]
  257. def __init__(
  258. self, *, mac_address: str, retry_count: int, password: typing.Optional[str]
  259. ) -> None:
  260. self.__device = switchbot.Switchbot(
  261. mac=mac_address, password=password, retry_count=retry_count
  262. )
  263. super().__init__(
  264. mac_address=mac_address, retry_count=retry_count, password=password
  265. )
  266. def _get_device(self) -> switchbot.SwitchbotDevice:
  267. return self.__device
  268. def _report_battery_level(self, mqtt_client: paho.mqtt.client.Client) -> None:
  269. super()._report_battery_level(mqtt_client=mqtt_client)
  270. # kept for downward compatibility (will be removed in v3)
  271. self._mqtt_publish(
  272. topic_levels=self._MQTT_BATTERY_PERCENTAGE_TOPIC_LEVELS_LEGACY,
  273. payload=str(self._get_device().get_battery_percent()).encode(),
  274. mqtt_client=mqtt_client,
  275. )
  276. def execute_command(
  277. self,
  278. mqtt_message_payload: bytes,
  279. mqtt_client: paho.mqtt.client.Client,
  280. update_device_info: bool,
  281. ) -> None:
  282. # https://www.home-assistant.io/integrations/switch.mqtt/#payload_on
  283. if mqtt_message_payload.lower() == b"on":
  284. if not self.__device.turn_on():
  285. _LOGGER.error("failed to turn on switchbot %s", self._mac_address)
  286. else:
  287. _LOGGER.info("switchbot %s turned on", self._mac_address)
  288. # https://www.home-assistant.io/integrations/switch.mqtt/#state_on
  289. self.report_state(mqtt_client=mqtt_client, state=b"ON")
  290. if update_device_info:
  291. self._update_and_report_device_info(mqtt_client)
  292. # https://www.home-assistant.io/integrations/switch.mqtt/#payload_off
  293. elif mqtt_message_payload.lower() == b"off":
  294. if not self.__device.turn_off():
  295. _LOGGER.error("failed to turn off switchbot %s", self._mac_address)
  296. else:
  297. _LOGGER.info("switchbot %s turned off", self._mac_address)
  298. self.report_state(mqtt_client=mqtt_client, state=b"OFF")
  299. if update_device_info:
  300. self._update_and_report_device_info(mqtt_client)
  301. else:
  302. _LOGGER.warning(
  303. "unexpected payload %r (expected 'ON' or 'OFF')", mqtt_message_payload
  304. )
  305. class _CurtainMotor(_MQTTControlledActor):
  306. # https://www.home-assistant.io/integrations/cover.mqtt/
  307. MQTT_COMMAND_TOPIC_LEVELS = _MQTT_TOPIC_LEVELS_PREFIX + [
  308. "cover",
  309. "switchbot-curtain",
  310. _MQTTTopicPlaceholder.MAC_ADDRESS,
  311. "set",
  312. ]
  313. MQTT_STATE_TOPIC_LEVELS = _MQTT_TOPIC_LEVELS_PREFIX + [
  314. "cover",
  315. "switchbot-curtain",
  316. _MQTTTopicPlaceholder.MAC_ADDRESS,
  317. "state",
  318. ]
  319. _MQTT_BATTERY_PERCENTAGE_TOPIC_LEVELS = _MQTT_TOPIC_LEVELS_PREFIX + [
  320. "cover",
  321. "switchbot-curtain",
  322. _MQTTTopicPlaceholder.MAC_ADDRESS,
  323. "battery-percentage",
  324. ]
  325. _MQTT_POSITION_TOPIC_LEVELS = _MQTT_TOPIC_LEVELS_PREFIX + [
  326. "cover",
  327. "switchbot-curtain",
  328. _MQTTTopicPlaceholder.MAC_ADDRESS,
  329. "position",
  330. ]
  331. @classmethod
  332. def get_mqtt_position_topic(cls, mac_address: str) -> str:
  333. return _join_mqtt_topic_levels(
  334. topic_levels=cls._MQTT_POSITION_TOPIC_LEVELS, mac_address=mac_address
  335. )
  336. def __init__(
  337. self, *, mac_address: str, retry_count: int, password: typing.Optional[str]
  338. ) -> None:
  339. # > The position of the curtain is saved in self._pos with 0 = open and 100 = closed.
  340. # https://github.com/Danielhiversen/pySwitchbot/blob/0.10.0/switchbot/__init__.py#L150
  341. self.__device = switchbot.SwitchbotCurtain(
  342. mac=mac_address,
  343. password=password,
  344. retry_count=retry_count,
  345. reverse_mode=True,
  346. )
  347. super().__init__(
  348. mac_address=mac_address, retry_count=retry_count, password=password
  349. )
  350. def _get_device(self) -> switchbot.SwitchbotDevice:
  351. return self.__device
  352. def _report_position(self, mqtt_client: paho.mqtt.client.Client) -> None:
  353. # > position_closed integer (Optional, default: 0)
  354. # > position_open integer (Optional, default: 100)
  355. # https://www.home-assistant.io/integrations/cover.mqtt/#position_closed
  356. # SwitchbotCurtain.get_position() returns a cached value within [0, 100].
  357. # SwitchbotCurtain.open() and .close() update the position optimistically,
  358. # SwitchbotCurtain.update() fetches the real position via bluetooth.
  359. # https://github.com/Danielhiversen/pySwitchbot/blob/0.10.0/switchbot/__init__.py#L202
  360. self._mqtt_publish(
  361. topic_levels=self._MQTT_POSITION_TOPIC_LEVELS,
  362. payload=str(int(self.__device.get_position())).encode(),
  363. mqtt_client=mqtt_client,
  364. )
  365. def _update_and_report_device_info( # pylint: disable=arguments-differ; report_position is optional
  366. self, mqtt_client: paho.mqtt.client.Client, *, report_position: bool = True
  367. ) -> None:
  368. super()._update_and_report_device_info(mqtt_client)
  369. if report_position:
  370. self._report_position(mqtt_client=mqtt_client)
  371. def execute_command(
  372. self,
  373. mqtt_message_payload: bytes,
  374. mqtt_client: paho.mqtt.client.Client,
  375. update_device_info: bool,
  376. ) -> None:
  377. # https://www.home-assistant.io/integrations/cover.mqtt/#payload_open
  378. report_device_info, report_position = False, False
  379. if mqtt_message_payload.lower() == b"open":
  380. if not self.__device.open():
  381. _LOGGER.error("failed to open switchbot curtain %s", self._mac_address)
  382. else:
  383. _LOGGER.info("switchbot curtain %s opening", self._mac_address)
  384. # > state_opening string (Optional, default: opening)
  385. # https://www.home-assistant.io/integrations/cover.mqtt/#state_opening
  386. self.report_state(mqtt_client=mqtt_client, state=b"opening")
  387. report_device_info = update_device_info
  388. elif mqtt_message_payload.lower() == b"close":
  389. if not self.__device.close():
  390. _LOGGER.error("failed to close switchbot curtain %s", self._mac_address)
  391. else:
  392. _LOGGER.info("switchbot curtain %s closing", self._mac_address)
  393. # https://www.home-assistant.io/integrations/cover.mqtt/#state_closing
  394. self.report_state(mqtt_client=mqtt_client, state=b"closing")
  395. report_device_info = update_device_info
  396. elif mqtt_message_payload.lower() == b"stop":
  397. if not self.__device.stop():
  398. _LOGGER.error("failed to stop switchbot curtain %s", self._mac_address)
  399. else:
  400. _LOGGER.info("switchbot curtain %s stopped", self._mac_address)
  401. # no "stopped" state mentioned at
  402. # https://www.home-assistant.io/integrations/cover.mqtt/#configuration-variables
  403. # https://community.home-assistant.io/t/mqtt-how-to-remove-retained-messages/79029/2
  404. self.report_state(mqtt_client=mqtt_client, state=b"")
  405. report_device_info = update_device_info
  406. report_position = True
  407. else:
  408. _LOGGER.warning(
  409. "unexpected payload %r (expected 'OPEN', 'CLOSE', or 'STOP')",
  410. mqtt_message_payload,
  411. )
  412. if report_device_info:
  413. self._update_and_report_device_info(
  414. mqtt_client=mqtt_client, report_position=report_position
  415. )
  416. def _mqtt_on_connect(
  417. mqtt_client: paho.mqtt.client.Client,
  418. userdata: _MQTTCallbackUserdata,
  419. flags: typing.Dict,
  420. return_code: int,
  421. ) -> None:
  422. # pylint: disable=unused-argument; callback
  423. # https://github.com/eclipse/paho.mqtt.python/blob/v1.5.0/src/paho/mqtt/client.py#L441
  424. assert return_code == 0, return_code # connection accepted
  425. mqtt_broker_host, mqtt_broker_port = mqtt_client.socket().getpeername()
  426. _LOGGER.debug("connected to MQTT broker %s:%d", mqtt_broker_host, mqtt_broker_port)
  427. _ButtonAutomator.mqtt_subscribe(mqtt_client=mqtt_client)
  428. _CurtainMotor.mqtt_subscribe(mqtt_client=mqtt_client)
  429. def _run(
  430. *,
  431. mqtt_host: str,
  432. mqtt_port: int,
  433. mqtt_username: typing.Optional[str],
  434. mqtt_password: typing.Optional[str],
  435. retry_count: int,
  436. device_passwords: typing.Dict[str, str],
  437. fetch_device_info: bool,
  438. ) -> None:
  439. # https://pypi.org/project/paho-mqtt/
  440. mqtt_client = paho.mqtt.client.Client(
  441. userdata=_MQTTCallbackUserdata(
  442. retry_count=retry_count,
  443. device_passwords=device_passwords,
  444. fetch_device_info=fetch_device_info,
  445. )
  446. )
  447. mqtt_client.on_connect = _mqtt_on_connect
  448. _LOGGER.info("connecting to MQTT broker %s:%d", mqtt_host, mqtt_port)
  449. if mqtt_username:
  450. mqtt_client.username_pw_set(username=mqtt_username, password=mqtt_password)
  451. elif mqtt_password:
  452. raise ValueError("Missing MQTT username")
  453. mqtt_client.connect(host=mqtt_host, port=mqtt_port)
  454. # https://github.com/eclipse/paho.mqtt.python/blob/master/src/paho/mqtt/client.py#L1740
  455. mqtt_client.loop_forever()
  456. def _main() -> None:
  457. argparser = argparse.ArgumentParser(
  458. description="MQTT client controlling SwitchBot button automators, "
  459. "compatible with home-assistant.io's MQTT Switch platform"
  460. )
  461. argparser.add_argument("--mqtt-host", type=str, required=True)
  462. argparser.add_argument("--mqtt-port", type=int, default=1883)
  463. argparser.add_argument("--mqtt-username", type=str)
  464. password_argument_group = argparser.add_mutually_exclusive_group()
  465. password_argument_group.add_argument("--mqtt-password", type=str)
  466. password_argument_group.add_argument(
  467. "--mqtt-password-file",
  468. type=pathlib.Path,
  469. metavar="PATH",
  470. dest="mqtt_password_path",
  471. help="stripping trailing newline",
  472. )
  473. argparser.add_argument(
  474. "--device-password-file",
  475. type=pathlib.Path,
  476. metavar="PATH",
  477. dest="device_password_path",
  478. help="path to json file mapping mac addresses of switchbot devices to passwords, e.g. "
  479. + json.dumps({"11:22:33:44:55:66": "password", "aa:bb:cc:dd:ee:ff": "secret"}),
  480. )
  481. argparser.add_argument(
  482. "--retries",
  483. dest="retry_count",
  484. type=int,
  485. default=switchbot.DEFAULT_RETRY_COUNT,
  486. help="Maximum number of attempts to send a command to a SwitchBot device"
  487. " (default: %(default)d)",
  488. )
  489. argparser.add_argument(
  490. "--fetch-device-info",
  491. action="store_true",
  492. help="Report devices' battery level on topic"
  493. f" {_ButtonAutomator.get_mqtt_battery_percentage_topic(mac_address='MAC_ADDRESS')}"
  494. " or, respectively,"
  495. f" {_CurtainMotor.get_mqtt_battery_percentage_topic(mac_address='MAC_ADDRESS')}"
  496. " after every command. Additionally report curtain motors' position on"
  497. f" topic {_CurtainMotor.get_mqtt_position_topic(mac_address='MAC_ADDRESS')}"
  498. " after executing stop commands.",
  499. )
  500. argparser.add_argument("--debug", action="store_true")
  501. args = argparser.parse_args()
  502. # https://github.com/fphammerle/python-cc1101/blob/26d8122661fc4587ecc7c73df55b92d05cf98fe8/cc1101/_cli.py#L51
  503. logging.basicConfig(
  504. level=logging.DEBUG if args.debug else logging.INFO,
  505. format="%(asctime)s:%(levelname)s:%(name)s:%(funcName)s:%(message)s"
  506. if args.debug
  507. else "%(message)s",
  508. datefmt="%Y-%m-%dT%H:%M:%S%z",
  509. )
  510. _LOGGER.debug("args=%r", args)
  511. if args.mqtt_password_path:
  512. # .read_text() replaces \r\n with \n
  513. mqtt_password = args.mqtt_password_path.read_bytes().decode()
  514. if mqtt_password.endswith("\r\n"):
  515. mqtt_password = mqtt_password[:-2]
  516. elif mqtt_password.endswith("\n"):
  517. mqtt_password = mqtt_password[:-1]
  518. else:
  519. mqtt_password = args.mqtt_password
  520. if args.device_password_path:
  521. device_passwords = json.loads(args.device_password_path.read_text())
  522. else:
  523. device_passwords = {}
  524. _run(
  525. mqtt_host=args.mqtt_host,
  526. mqtt_port=args.mqtt_port,
  527. mqtt_username=args.mqtt_username,
  528. mqtt_password=mqtt_password,
  529. retry_count=args.retry_count,
  530. device_passwords=device_passwords,
  531. fetch_device_info=args.fetch_device_info,
  532. )