__init__.py 21 KB

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