4
0

config_flow.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678
  1. import asyncio
  2. import logging
  3. from collections import OrderedDict
  4. from typing import Any
  5. import tinytuya
  6. import voluptuous as vol
  7. from homeassistant import config_entries
  8. from homeassistant.const import CONF_HOST, CONF_NAME
  9. from homeassistant.core import HomeAssistant, callback
  10. from homeassistant.data_entry_flow import FlowResult
  11. from homeassistant.helpers.selector import (
  12. QrCodeSelector,
  13. QrCodeSelectorConfig,
  14. QrErrorCorrectionLevel,
  15. SelectOptionDict,
  16. SelectSelector,
  17. SelectSelectorConfig,
  18. SelectSelectorMode,
  19. )
  20. from tuya_sharing import (
  21. CustomerDevice,
  22. LoginControl,
  23. Manager,
  24. SharingDeviceListener,
  25. SharingTokenListener,
  26. )
  27. from . import DOMAIN
  28. from .const import (
  29. API_PROTOCOL_VERSIONS,
  30. CONF_DEVICE_CID,
  31. CONF_DEVICE_ID,
  32. CONF_ENDPOINT,
  33. CONF_LOCAL_KEY,
  34. CONF_POLL_ONLY,
  35. CONF_PROTOCOL_VERSION,
  36. CONF_TERMINAL_ID,
  37. CONF_TYPE,
  38. CONF_USER_CODE,
  39. DATA_STORE,
  40. TUYA_CLIENT_ID,
  41. TUYA_RESPONSE_CODE,
  42. TUYA_RESPONSE_MSG,
  43. TUYA_RESPONSE_QR_CODE,
  44. TUYA_RESPONSE_RESULT,
  45. TUYA_RESPONSE_SUCCESS,
  46. TUYA_SCHEMA,
  47. )
  48. from .device import TuyaLocalDevice
  49. from .helpers.config import get_device_id
  50. from .helpers.device_config import get_config
  51. from .helpers.log import log_json
  52. _LOGGER = logging.getLogger(__name__)
  53. HUB_CATEGORIES = [
  54. "wgsxj", # Gateway camera
  55. "lyqwg", # Router
  56. "bywg", # IoT edge gateway
  57. "zigbee", # Gateway
  58. "wg2", # Gateway
  59. "dgnzk", # Multi-function controller
  60. "videohub", # Videohub
  61. "xnwg", # Virtual gateway
  62. "qtyycp", # Voice gateway composite solution
  63. "alexa_yywg", # Gateway with Alexa
  64. "gywg", # Industrial gateway
  65. "cnwg", # Energy gateway
  66. "wnykq", # Smart IR
  67. ]
  68. class ConfigFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
  69. VERSION = 13
  70. MINOR_VERSION = 3
  71. CONNECTION_CLASS = config_entries.CONN_CLASS_LOCAL_PUSH
  72. device = None
  73. data = {}
  74. __user_code: str
  75. __qr_code: str
  76. __authentication: dict
  77. __cloud_devices: dict
  78. __cloud_device: dict
  79. def __init__(self) -> None:
  80. """Initialize the config flow."""
  81. self.__login_control = LoginControl()
  82. self.__cloud_devices = {}
  83. self.__cloud_device = None
  84. async def async_step_user(self, user_input=None):
  85. errors = {}
  86. if self.hass.data.get(DOMAIN) is None:
  87. self.hass.data[DOMAIN] = {}
  88. if self.hass.data[DOMAIN].get(DATA_STORE) is None:
  89. self.hass.data[DOMAIN][DATA_STORE] = {}
  90. self.__authentication = self.hass.data[DOMAIN][DATA_STORE].get(
  91. "authentication", None
  92. )
  93. if user_input is not None:
  94. if user_input["setup_mode"] == "cloud":
  95. try:
  96. if self.__authentication is not None:
  97. self.__cloud_devices = await self.load_device_info()
  98. return await self.async_step_choose_device(None)
  99. except Exception as e:
  100. # Re-authentication is needed.
  101. _LOGGER.warning("Connection test failed with %s %s", type(e), e)
  102. _LOGGER.warning("Re-authentication is required.")
  103. return await self.async_step_cloud(None)
  104. if user_input["setup_mode"] == "manual":
  105. return await self.async_step_local(None)
  106. # Build form
  107. fields: OrderedDict[vol.Marker, Any] = OrderedDict()
  108. fields[vol.Required("setup_mode")] = SelectSelector(
  109. SelectSelectorConfig(
  110. options=["cloud", "manual"],
  111. mode=SelectSelectorMode.LIST,
  112. translation_key="setup_mode",
  113. )
  114. )
  115. return self.async_show_form(
  116. step_id="user",
  117. data_schema=vol.Schema(fields),
  118. errors=errors or {},
  119. last_step=False,
  120. )
  121. async def async_step_cloud(
  122. self, user_input: dict[str, Any] | None = None
  123. ) -> FlowResult:
  124. """Step user."""
  125. errors = {}
  126. placeholders = {}
  127. if user_input is not None:
  128. success, response = await self.__async_get_qr_code(
  129. user_input[CONF_USER_CODE]
  130. )
  131. if success:
  132. return await self.async_step_scan(None)
  133. errors["base"] = "login_error"
  134. placeholders = {
  135. TUYA_RESPONSE_MSG: response.get(TUYA_RESPONSE_MSG, "Unknown error"),
  136. TUYA_RESPONSE_CODE: response.get(TUYA_RESPONSE_CODE, "0"),
  137. }
  138. else:
  139. user_input = {}
  140. return self.async_show_form(
  141. step_id="cloud",
  142. data_schema=vol.Schema(
  143. {
  144. vol.Required(
  145. CONF_USER_CODE, default=user_input.get(CONF_USER_CODE, "")
  146. ): str,
  147. }
  148. ),
  149. errors=errors,
  150. description_placeholders=placeholders,
  151. )
  152. async def async_step_scan(
  153. self, user_input: dict[str, Any] | None = None
  154. ) -> FlowResult:
  155. """Step scan."""
  156. if user_input is None:
  157. return self.async_show_form(
  158. step_id="scan",
  159. data_schema=vol.Schema(
  160. {
  161. vol.Optional("QR"): QrCodeSelector(
  162. config=QrCodeSelectorConfig(
  163. data=f"tuyaSmart--qrLogin?token={self.__qr_code}",
  164. scale=5,
  165. error_correction_level=QrErrorCorrectionLevel.QUARTILE,
  166. )
  167. )
  168. }
  169. ),
  170. )
  171. ret, info = await self.hass.async_add_executor_job(
  172. self.__login_control.login_result,
  173. self.__qr_code,
  174. TUYA_CLIENT_ID,
  175. self.__user_code,
  176. )
  177. if not ret:
  178. # Try to get a new QR code on failure
  179. await self.__async_get_qr_code(self.__user_code)
  180. return self.async_show_form(
  181. step_id="scan",
  182. errors={"base": "login_error"},
  183. data_schema=vol.Schema(
  184. {
  185. vol.Optional("QR"): QrCodeSelector(
  186. config=QrCodeSelectorConfig(
  187. data=f"tuyaSmart--qrLogin?token={self.__qr_code}",
  188. scale=5,
  189. error_correction_level=QrErrorCorrectionLevel.QUARTILE,
  190. )
  191. )
  192. }
  193. ),
  194. description_placeholders={
  195. TUYA_RESPONSE_MSG: info.get(TUYA_RESPONSE_MSG, "Unknown error"),
  196. TUYA_RESPONSE_CODE: info.get(TUYA_RESPONSE_CODE, 0),
  197. },
  198. )
  199. # Now that we have successfully logged in we can query for devices for the account.
  200. self.__authentication = {
  201. "user_code": info[CONF_TERMINAL_ID],
  202. "terminal_id": info[CONF_TERMINAL_ID],
  203. "endpoint": info[CONF_ENDPOINT],
  204. "token_info": {
  205. "t": info["t"],
  206. "uid": info["uid"],
  207. "expire_time": info["expire_time"],
  208. "access_token": info["access_token"],
  209. "refresh_token": info["refresh_token"],
  210. },
  211. }
  212. self.hass.data[DOMAIN][DATA_STORE]["authentication"] = self.__authentication
  213. _LOGGER.debug(f"domain_data is {self.hass.data[DOMAIN]}")
  214. self.__cloud_devices = await self.load_device_info()
  215. return await self.async_step_choose_device(None)
  216. async def load_device_info(self) -> dict:
  217. token_listener = TokenListener(self.hass)
  218. manager = Manager(
  219. TUYA_CLIENT_ID,
  220. self.__authentication["user_code"],
  221. self.__authentication["terminal_id"],
  222. self.__authentication["endpoint"],
  223. self.__authentication["token_info"],
  224. token_listener,
  225. )
  226. listener = DeviceListener(self.hass, manager)
  227. manager.add_device_listener(listener)
  228. # Get all devices from Tuya
  229. await self.hass.async_add_executor_job(manager.update_device_cache)
  230. # Register known device IDs
  231. cloud_devices = {}
  232. domain_data = self.hass.data.get(DOMAIN)
  233. for device in manager.device_map.values():
  234. cloud_device = {
  235. # TODO - Use constants throughout
  236. "category": device.category,
  237. "id": device.id,
  238. "ip": device.ip, # This will be the WAN IP address so not usable.
  239. CONF_LOCAL_KEY: device.local_key
  240. if hasattr(device, CONF_LOCAL_KEY)
  241. else "",
  242. "name": device.name,
  243. "node_id": device.node_id if hasattr(device, "node_id") else "",
  244. "online": device.online,
  245. "product_id": device.product_id,
  246. "product_name": device.product_name,
  247. "uid": device.uid,
  248. "uuid": device.uuid,
  249. "support_local": device.support_local, # What does this mean?
  250. CONF_DEVICE_CID: None,
  251. "version": None,
  252. }
  253. _LOGGER.debug(f"Found device: {cloud_device}")
  254. existing_id = domain_data.get(cloud_device["id"]) if domain_data else None
  255. existing_uuid = (
  256. domain_data.get(cloud_device["uuid"]) if domain_data else None
  257. )
  258. if existing_id or existing_uuid:
  259. _LOGGER.debug("Device is already registered.")
  260. continue
  261. _LOGGER.debug(f"Adding device: {cloud_device['id']}")
  262. cloud_devices[cloud_device["id"]] = cloud_device
  263. return cloud_devices
  264. async def async_step_choose_device(self, user_input=None):
  265. errors = {}
  266. if user_input is not None:
  267. device_choice = self.__cloud_devices[user_input["device_id"]]
  268. if device_choice["ip"] != "":
  269. # This is a directly addable device.
  270. if user_input["hub_id"] == "None":
  271. device_choice["ip"] = ""
  272. self.__cloud_device = device_choice
  273. return await self.async_step_search(None)
  274. else:
  275. # Show error if user selected a hub.
  276. errors["base"] = "does_not_need_hub"
  277. # Fall through to reshow the form.
  278. else:
  279. # This is an indirectly addressable device. Need to know which hub it is connected to.
  280. if user_input["hub_id"] != "None":
  281. hub_choice = self.__cloud_devices[user_input["hub_id"]]
  282. # Populate uuid and local_key from the child device to pass on complete information to the local step.
  283. hub_choice["ip"] = ""
  284. hub_choice[CONF_DEVICE_CID] = device_choice["uuid"]
  285. hub_choice[CONF_LOCAL_KEY] = device_choice[CONF_LOCAL_KEY]
  286. self.__cloud_device = hub_choice
  287. return await self.async_step_search(None)
  288. else:
  289. # Show error if user did not select a hub.
  290. errors["base"] = "needs_hub"
  291. # Fall through to reshow the form.
  292. device_list = []
  293. for key in self.__cloud_devices.keys():
  294. device_entry = self.__cloud_devices[key]
  295. if device_entry[CONF_LOCAL_KEY] != "":
  296. if device_entry["online"]:
  297. device_list.append(
  298. SelectOptionDict(
  299. value=key,
  300. label=f"{device_entry['name']} ({device_entry['product_name']})",
  301. )
  302. )
  303. else:
  304. device_list.append(
  305. SelectOptionDict(
  306. value=key,
  307. label=f"{device_entry['name']} ({device_entry['product_name']}) OFFLINE",
  308. )
  309. )
  310. _LOGGER.debug(f"Device count: {len(device_list)}")
  311. if len(device_list) == 0:
  312. return self.async_abort(reason="no_devices")
  313. device_selector = SelectSelector(
  314. SelectSelectorConfig(options=device_list, mode=SelectSelectorMode.DROPDOWN)
  315. )
  316. hub_list = []
  317. hub_list.append(SelectOptionDict(value="None", label="None"))
  318. for key in self.__cloud_devices.keys():
  319. hub_entry = self.__cloud_devices[key]
  320. if (
  321. hub_entry[CONF_LOCAL_KEY] == ""
  322. or hub_entry["category"] in HUB_CATEGORIES
  323. ):
  324. hub_list.append(
  325. SelectOptionDict(
  326. value=key,
  327. label=f"{hub_entry['name']} ({hub_entry['product_name']})",
  328. )
  329. )
  330. _LOGGER.debug(f"Hub count: {len(hub_list) - 1}")
  331. hub_selector = SelectSelector(
  332. SelectSelectorConfig(options=hub_list, mode=SelectSelectorMode.DROPDOWN)
  333. )
  334. # Build form
  335. fields: OrderedDict[vol.Marker, Any] = OrderedDict()
  336. fields[vol.Required("device_id")] = device_selector
  337. fields[vol.Required("hub_id")] = hub_selector
  338. return self.async_show_form(
  339. step_id="choose_device",
  340. data_schema=vol.Schema(fields),
  341. errors=errors or {},
  342. last_step=False,
  343. )
  344. async def async_step_search(self, user_input=None):
  345. if user_input is not None:
  346. # Current IP is the WAN IP which is of no use. Need to try and discover to the local IP.
  347. # This scan will take 18s with the default settings. If we cannot find the device we
  348. # will just leave the IP address blank and hope the user can discover the IP by other
  349. # means such as router device IP assignments.
  350. _LOGGER.debug(
  351. f"Scanning network to get IP address for {self.__cloud_device['id']}."
  352. )
  353. self.__cloud_device["ip"] = ""
  354. try:
  355. local_device = await self.hass.async_add_executor_job(
  356. scan_for_device, self.__cloud_device["id"]
  357. )
  358. except OSError:
  359. local_device = {"ip": None, "version": ""}
  360. if local_device["ip"] is not None:
  361. _LOGGER.debug(f"Found: {local_device}")
  362. self.__cloud_device["ip"] = local_device["ip"]
  363. self.__cloud_device["version"] = local_device["version"]
  364. else:
  365. _LOGGER.warn(f"Could not find device: {self.__cloud_device['id']}")
  366. return await self.async_step_local(None)
  367. return self.async_show_form(
  368. step_id="search", data_schema=vol.Schema({}), errors={}, last_step=False
  369. )
  370. async def async_step_local(self, user_input=None):
  371. errors = {}
  372. devid_opts = {}
  373. host_opts = {"default": ""}
  374. key_opts = {}
  375. proto_opts = {"default": 3.3}
  376. polling_opts = {"default": False}
  377. devcid_opts = {}
  378. if self.__cloud_device is not None:
  379. # We already have some or all of the device settings from the cloud flow. Set them into the defaults.
  380. devid_opts = {"default": self.__cloud_device["id"]}
  381. host_opts = {"default": self.__cloud_device["ip"]}
  382. key_opts = {"default": self.__cloud_device[CONF_LOCAL_KEY]}
  383. if self.__cloud_device["version"] is not None:
  384. proto_opts = {"default": float(self.__cloud_device["version"])}
  385. if self.__cloud_device[CONF_DEVICE_CID] is not None:
  386. devcid_opts = {"default": self.__cloud_device[CONF_DEVICE_CID]}
  387. if user_input is not None:
  388. self.device = await async_test_connection(user_input, self.hass)
  389. if self.device:
  390. self.data = user_input
  391. return await self.async_step_select_type()
  392. else:
  393. errors["base"] = "connection"
  394. devid_opts["default"] = user_input[CONF_DEVICE_ID]
  395. host_opts["default"] = user_input[CONF_HOST]
  396. key_opts["default"] = user_input[CONF_LOCAL_KEY]
  397. if CONF_DEVICE_CID in user_input:
  398. devcid_opts["default"] = user_input[CONF_DEVICE_CID]
  399. proto_opts["default"] = user_input[CONF_PROTOCOL_VERSION]
  400. polling_opts["default"] = user_input[CONF_POLL_ONLY]
  401. return self.async_show_form(
  402. step_id="local",
  403. data_schema=vol.Schema(
  404. {
  405. vol.Required(CONF_DEVICE_ID, **devid_opts): str,
  406. vol.Required(CONF_HOST, **host_opts): str,
  407. vol.Required(CONF_LOCAL_KEY, **key_opts): str,
  408. vol.Required(
  409. CONF_PROTOCOL_VERSION,
  410. **proto_opts,
  411. ): vol.In(["auto"] + API_PROTOCOL_VERSIONS),
  412. vol.Required(CONF_POLL_ONLY, **polling_opts): bool,
  413. vol.Optional(CONF_DEVICE_CID, **devcid_opts): str,
  414. }
  415. ),
  416. errors=errors,
  417. )
  418. async def async_step_select_type(self, user_input=None):
  419. if user_input is not None:
  420. self.data[CONF_TYPE] = user_input[CONF_TYPE]
  421. return await self.async_step_choose_entities()
  422. types = []
  423. best_match = 0
  424. best_matching_type = None
  425. async for type in self.device.async_possible_types():
  426. types.append(type.config_type)
  427. q = type.match_quality(self.device._get_cached_state())
  428. if q > best_match:
  429. best_match = q
  430. best_matching_type = type.config_type
  431. best_match = int(best_match)
  432. dps = self.device._get_cached_state()
  433. _LOGGER.warning(
  434. "Device matches %s with quality of %d%%. DPS: %s",
  435. best_matching_type,
  436. best_match,
  437. log_json(dps),
  438. )
  439. _LOGGER.warning(
  440. "Report this to https://github.com/make-all/tuya-local/issues/",
  441. )
  442. if types:
  443. return self.async_show_form(
  444. step_id="select_type",
  445. data_schema=vol.Schema(
  446. {
  447. vol.Required(
  448. CONF_TYPE,
  449. default=best_matching_type,
  450. ): vol.In(types),
  451. }
  452. ),
  453. )
  454. else:
  455. return self.async_abort(reason="not_supported")
  456. async def async_step_choose_entities(self, user_input=None):
  457. if user_input is not None:
  458. title = user_input[CONF_NAME]
  459. del user_input[CONF_NAME]
  460. return self.async_create_entry(
  461. title=title, data={**self.data, **user_input}
  462. )
  463. config = get_config(self.data[CONF_TYPE])
  464. schema = {vol.Required(CONF_NAME, default=config.name): str}
  465. return self.async_show_form(
  466. step_id="choose_entities",
  467. data_schema=vol.Schema(schema),
  468. )
  469. @staticmethod
  470. @callback
  471. def async_get_options_flow(config_entry):
  472. return OptionsFlowHandler(config_entry)
  473. async def __async_get_qr_code(self, user_code: str) -> tuple[bool, dict[str, Any]]:
  474. """Get the QR code."""
  475. response = await self.hass.async_add_executor_job(
  476. self.__login_control.qr_code,
  477. TUYA_CLIENT_ID,
  478. TUYA_SCHEMA,
  479. user_code,
  480. )
  481. if success := response.get(TUYA_RESPONSE_SUCCESS, False):
  482. self.__user_code = user_code
  483. self.__qr_code = response[TUYA_RESPONSE_RESULT][TUYA_RESPONSE_QR_CODE]
  484. return success, response
  485. class OptionsFlowHandler(config_entries.OptionsFlow):
  486. def __init__(self, config_entry):
  487. """Initialize options flow."""
  488. self.config_entry = config_entry
  489. async def async_step_init(self, user_input=None):
  490. return await self.async_step_user(user_input)
  491. async def async_step_user(self, user_input=None):
  492. """Manage the options."""
  493. errors = {}
  494. config = {**self.config_entry.data, **self.config_entry.options}
  495. if user_input is not None:
  496. config = {**config, **user_input}
  497. device = await async_test_connection(config, self.hass)
  498. if device:
  499. return self.async_create_entry(title="", data=user_input)
  500. else:
  501. errors["base"] = "connection"
  502. schema = {
  503. vol.Required(
  504. CONF_LOCAL_KEY,
  505. default=config.get(CONF_LOCAL_KEY, ""),
  506. ): str,
  507. vol.Required(CONF_HOST, default=config.get(CONF_HOST, "")): str,
  508. vol.Required(
  509. CONF_PROTOCOL_VERSION,
  510. default=config.get(CONF_PROTOCOL_VERSION, "auto"),
  511. ): vol.In(["auto"] + API_PROTOCOL_VERSIONS),
  512. vol.Required(
  513. CONF_POLL_ONLY, default=config.get(CONF_POLL_ONLY, False)
  514. ): bool,
  515. vol.Optional(
  516. CONF_DEVICE_CID,
  517. default=config.get(CONF_DEVICE_CID, ""),
  518. ): str,
  519. }
  520. cfg = get_config(config[CONF_TYPE])
  521. if cfg is None:
  522. return self.async_abort(reason="not_supported")
  523. return self.async_show_form(
  524. step_id="user",
  525. data_schema=vol.Schema(schema),
  526. errors=errors,
  527. )
  528. async def async_test_connection(config: dict, hass: HomeAssistant):
  529. domain_data = hass.data.get(DOMAIN)
  530. existing = domain_data.get(get_device_id(config)) if domain_data else None
  531. if existing:
  532. _LOGGER.info("Pausing existing device to test new connection parameters")
  533. existing["device"].pause()
  534. await asyncio.sleep(5)
  535. try:
  536. subdevice_id = config.get(CONF_DEVICE_CID)
  537. device = TuyaLocalDevice(
  538. "Test",
  539. config[CONF_DEVICE_ID],
  540. config[CONF_HOST],
  541. config[CONF_LOCAL_KEY],
  542. config[CONF_PROTOCOL_VERSION],
  543. subdevice_id,
  544. hass,
  545. True,
  546. )
  547. await device.async_refresh()
  548. retval = device if device.has_returned_state else None
  549. except Exception as e:
  550. _LOGGER.warning("Connection test failed with %s %s", type(e), e)
  551. retval = None
  552. if existing:
  553. _LOGGER.info("Restarting device after test")
  554. existing["device"].resume()
  555. return retval
  556. def scan_for_device(id):
  557. return tinytuya.find_device(dev_id=id)
  558. class DeviceListener(SharingDeviceListener):
  559. """Device Update Listener."""
  560. def __init__(
  561. self,
  562. hass: HomeAssistant,
  563. manager: Manager,
  564. ) -> None:
  565. """Init DeviceListener."""
  566. self.hass = hass
  567. self.manager = manager
  568. def update_device(self, device: CustomerDevice) -> None:
  569. """Update device status."""
  570. _LOGGER.debug(
  571. "Received update for device %s: %s",
  572. device.id,
  573. self.manager.device_map[device.id].status,
  574. )
  575. def add_device(self, device: CustomerDevice) -> None:
  576. """Add device added listener."""
  577. _LOGGER.debug(
  578. "Received add device %s: %s",
  579. device.id,
  580. self.manager.device_map[device.id].status,
  581. )
  582. def remove_device(self, device_id: str) -> None:
  583. """Add device removed listener."""
  584. _LOGGER.debug(
  585. "Received remove device %s: %s",
  586. device_id,
  587. self.manager.device_map[device_id].status,
  588. )
  589. class TokenListener(SharingTokenListener):
  590. """Token listener for upstream token updates."""
  591. def __init__(
  592. self,
  593. hass: HomeAssistant,
  594. ) -> None:
  595. """Init TokenListener."""
  596. self.hass = hass
  597. def update_token(self, token_info: dict[str, Any]) -> None:
  598. """Update token info in config entry."""
  599. _LOGGER.debug("update_token")