config_flow.py 23 KB

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