config_flow.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  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.config_entries import (
  8. CONN_CLASS_LOCAL_PUSH,
  9. ConfigEntry,
  10. ConfigFlow,
  11. OptionsFlow,
  12. )
  13. from homeassistant.const import CONF_HOST, CONF_NAME
  14. from homeassistant.core import HomeAssistant, callback
  15. from homeassistant.data_entry_flow import FlowResult
  16. from homeassistant.helpers.selector import (
  17. QrCodeSelector,
  18. QrCodeSelectorConfig,
  19. QrErrorCorrectionLevel,
  20. SelectOptionDict,
  21. SelectSelector,
  22. SelectSelectorConfig,
  23. SelectSelectorMode,
  24. )
  25. from . import DOMAIN
  26. from .cloud import Cloud
  27. from .const import (
  28. API_PROTOCOL_VERSIONS,
  29. CONF_DEVICE_CID,
  30. CONF_DEVICE_ID,
  31. CONF_LOCAL_KEY,
  32. CONF_POLL_ONLY,
  33. CONF_PROTOCOL_VERSION,
  34. CONF_TYPE,
  35. CONF_USER_CODE,
  36. DATA_STORE,
  37. )
  38. from .device import TuyaLocalDevice
  39. from .helpers.config import get_device_id
  40. from .helpers.device_config import get_config
  41. from .helpers.log import log_json
  42. _LOGGER = logging.getLogger(__name__)
  43. class ConfigFlowHandler(ConfigFlow, domain=DOMAIN):
  44. VERSION = 13
  45. MINOR_VERSION = 15
  46. CONNECTION_CLASS = CONN_CLASS_LOCAL_PUSH
  47. device = None
  48. data = {}
  49. __qr_code: str | None = None
  50. __cloud_devices: dict[str, Any] = {}
  51. __cloud_device: dict[str, Any] | None = None
  52. def __init__(self) -> None:
  53. """Initialize the config flow."""
  54. self.cloud = None
  55. def init_cloud(self):
  56. if self.cloud is None:
  57. self.cloud = Cloud(self.hass)
  58. async def async_step_user(self, user_input=None):
  59. errors = {}
  60. if self.hass.data.get(DOMAIN) is None:
  61. self.hass.data[DOMAIN] = {}
  62. if self.hass.data[DOMAIN].get(DATA_STORE) is None:
  63. self.hass.data[DOMAIN][DATA_STORE] = {}
  64. if user_input is not None:
  65. mode = user_input.get("setup_mode")
  66. if mode == "cloud" or mode == "cloud_fresh_login":
  67. self.init_cloud()
  68. try:
  69. if mode == "cloud_fresh_login":
  70. # Force a fresh login
  71. self.cloud.logout()
  72. if self.cloud.is_authenticated:
  73. self.__cloud_devices = await self.cloud.async_get_devices()
  74. return await self.async_step_choose_device()
  75. except Exception as e:
  76. # Re-authentication is needed.
  77. _LOGGER.warning("Connection test failed with %s %s", type(e), e)
  78. _LOGGER.warning("Re-authentication is required.")
  79. return await self.async_step_cloud()
  80. if mode == "manual":
  81. return await self.async_step_local()
  82. # Build form
  83. fields: OrderedDict[vol.Marker, Any] = OrderedDict()
  84. fields[vol.Required("setup_mode")] = SelectSelector(
  85. SelectSelectorConfig(
  86. options=["cloud", "manual", "cloud_fresh_login"],
  87. mode=SelectSelectorMode.LIST,
  88. translation_key="setup_mode",
  89. )
  90. )
  91. return self.async_show_form(
  92. step_id="user",
  93. data_schema=vol.Schema(fields),
  94. errors=errors or {},
  95. last_step=False,
  96. )
  97. async def async_step_cloud(
  98. self, user_input: dict[str, Any] | None = None
  99. ) -> FlowResult:
  100. """Step user."""
  101. errors = {}
  102. placeholders = {}
  103. self.init_cloud()
  104. if user_input is not None:
  105. response = await self.cloud.async_get_qr_code(user_input[CONF_USER_CODE])
  106. if response:
  107. self.__qr_code = response
  108. return await self.async_step_scan()
  109. errors["base"] = "login_error"
  110. placeholders = self.cloud.last_error
  111. else:
  112. user_input = {}
  113. return self.async_show_form(
  114. step_id="cloud",
  115. data_schema=vol.Schema(
  116. {
  117. vol.Required(
  118. CONF_USER_CODE, default=user_input.get(CONF_USER_CODE, "")
  119. ): str,
  120. }
  121. ),
  122. errors=errors,
  123. description_placeholders=placeholders,
  124. )
  125. async def async_step_scan(
  126. self, user_input: dict[str, Any] | None = None
  127. ) -> FlowResult:
  128. """Step scan."""
  129. if user_input is None:
  130. return self.async_show_form(
  131. step_id="scan",
  132. data_schema=vol.Schema(
  133. {
  134. vol.Optional("QR"): QrCodeSelector(
  135. config=QrCodeSelectorConfig(
  136. data=f"tuyaSmart--qrLogin?token={self.__qr_code}",
  137. scale=5,
  138. error_correction_level=QrErrorCorrectionLevel.QUARTILE,
  139. )
  140. )
  141. }
  142. ),
  143. )
  144. self.init_cloud()
  145. if not await self.cloud.async_login():
  146. # Try to get a new QR code on failure
  147. response = await self.cloud.async_get_qr_code()
  148. errors = {"base": "login_error"}
  149. placeholders = self.cloud.last_error
  150. if response:
  151. self.__qr_code = response
  152. return self.async_show_form(
  153. step_id="scan",
  154. errors=errors,
  155. data_schema=vol.Schema(
  156. {
  157. vol.Optional("QR"): QrCodeSelector(
  158. config=QrCodeSelectorConfig(
  159. data=f"tuyaSmart--qrLogin?token={self.__qr_code}",
  160. scale=5,
  161. error_correction_level=QrErrorCorrectionLevel.QUARTILE,
  162. )
  163. )
  164. }
  165. ),
  166. description_placeholders=placeholders,
  167. )
  168. self.__cloud_devices = await self.cloud.async_get_devices()
  169. return await self.async_step_choose_device()
  170. async def async_step_choose_device(self, user_input=None):
  171. errors = {}
  172. if user_input is not None:
  173. device_choice = self.__cloud_devices[user_input["device_id"]]
  174. if device_choice["ip"] != "":
  175. # This is a directly addable device.
  176. if user_input["hub_id"] == "None":
  177. device_choice["ip"] = ""
  178. self.__cloud_device = device_choice
  179. return await self.async_step_search()
  180. else:
  181. # Show error if user selected a hub.
  182. errors["base"] = "does_not_need_hub"
  183. # Fall through to reshow the form.
  184. else:
  185. # This is an indirectly addressable device. Need to know which hub it is connected to.
  186. if user_input["hub_id"] != "None":
  187. hub_choice = self.__cloud_devices[user_input["hub_id"]]
  188. # Populate node_id or uuid and local_key from the child
  189. # device to pass on complete information to the local step.
  190. hub_choice["ip"] = ""
  191. hub_choice[CONF_DEVICE_CID] = (
  192. device_choice["node_id"] or device_choice["uuid"]
  193. )
  194. if device_choice.get(CONF_LOCAL_KEY):
  195. hub_choice[CONF_LOCAL_KEY] = device_choice[CONF_LOCAL_KEY]
  196. # Communicate the sub device product id to help match the
  197. # correect device config in the next step.
  198. hub_choice["product_id"] = device_choice["product_id"]
  199. self.__cloud_device = hub_choice
  200. return await self.async_step_search()
  201. else:
  202. # Show error if user did not select a hub.
  203. errors["base"] = "needs_hub"
  204. # Fall through to reshow the form.
  205. device_list = []
  206. for key in self.__cloud_devices.keys():
  207. device_entry = self.__cloud_devices[key]
  208. if device_entry.get("exists"):
  209. continue
  210. if device_entry[CONF_LOCAL_KEY] != "":
  211. if device_entry["online"]:
  212. device_list.append(
  213. SelectOptionDict(
  214. value=key,
  215. label=f"{device_entry['name']} ({device_entry['product_name']})",
  216. )
  217. )
  218. else:
  219. device_list.append(
  220. SelectOptionDict(
  221. value=key,
  222. label=f"{device_entry['name']} ({device_entry['product_name']}) OFFLINE",
  223. )
  224. )
  225. _LOGGER.debug(f"Device count: {len(device_list)}")
  226. if len(device_list) == 0:
  227. return self.async_abort(reason="no_devices")
  228. device_selector = SelectSelector(
  229. SelectSelectorConfig(options=device_list, mode=SelectSelectorMode.DROPDOWN)
  230. )
  231. hub_list = []
  232. hub_list.append(SelectOptionDict(value="None", label="None"))
  233. for key in self.__cloud_devices.keys():
  234. hub_entry = self.__cloud_devices[key]
  235. if hub_entry["is_hub"]:
  236. hub_list.append(
  237. SelectOptionDict(
  238. value=key,
  239. label=f"{hub_entry['name']} ({hub_entry['product_name']})",
  240. )
  241. )
  242. _LOGGER.debug(f"Hub count: {len(hub_list) - 1}")
  243. hub_selector = SelectSelector(
  244. SelectSelectorConfig(options=hub_list, mode=SelectSelectorMode.DROPDOWN)
  245. )
  246. # Build form
  247. fields: OrderedDict[vol.Marker, Any] = OrderedDict()
  248. fields[vol.Required("device_id")] = device_selector
  249. fields[vol.Required("hub_id")] = hub_selector
  250. return self.async_show_form(
  251. step_id="choose_device",
  252. data_schema=vol.Schema(fields),
  253. errors=errors or {},
  254. last_step=False,
  255. )
  256. async def async_step_search(self, user_input=None):
  257. if user_input is not None:
  258. # Current IP is the WAN IP which is of no use. Need to try and discover to the local IP.
  259. # This scan will take 18s with the default settings. If we cannot find the device we
  260. # will just leave the IP address blank and hope the user can discover the IP by other
  261. # means such as router device IP assignments.
  262. _LOGGER.debug(
  263. f"Scanning network to get IP address for {self.__cloud_device.get('id', 'DEVICE_KEY_UNAVAILABLE')}."
  264. )
  265. self.__cloud_device["ip"] = ""
  266. try:
  267. local_device = await self.hass.async_add_executor_job(
  268. scan_for_device, self.__cloud_device.get("id")
  269. )
  270. except OSError:
  271. local_device = {"ip": None, "version": ""}
  272. if local_device.get("ip"):
  273. _LOGGER.debug(f"Found: {local_device}")
  274. self.__cloud_device["ip"] = local_device.get("ip")
  275. self.__cloud_device["version"] = local_device.get("version")
  276. if not self.__cloud_device.get(CONF_DEVICE_CID):
  277. self.__cloud_device["local_product_id"] = local_device.get(
  278. "productKey"
  279. )
  280. else:
  281. _LOGGER.warning(
  282. f"Could not find device: {self.__cloud_device.get('id', 'DEVICE_KEY_UNAVAILABLE')}"
  283. )
  284. return await self.async_step_local()
  285. return self.async_show_form(
  286. step_id="search", data_schema=vol.Schema({}), errors={}, last_step=False
  287. )
  288. async def async_step_local(self, user_input=None):
  289. errors = {}
  290. devid_opts = {}
  291. host_opts = {"default": ""}
  292. key_opts = {}
  293. proto_opts = {"default": 3.3}
  294. polling_opts = {"default": False}
  295. devcid_opts = {}
  296. if self.__cloud_device is not None:
  297. # We already have some or all of the device settings from the cloud flow. Set them into the defaults.
  298. devid_opts = {"default": self.__cloud_device.get("id")}
  299. host_opts = {"default": self.__cloud_device.get("ip")}
  300. key_opts = {"default": self.__cloud_device.get(CONF_LOCAL_KEY)}
  301. if self.__cloud_device.get("version"):
  302. proto_opts = {"default": float(self.__cloud_device.get("version"))}
  303. if self.__cloud_device.get(CONF_DEVICE_CID):
  304. devcid_opts = {"default": self.__cloud_device.get(CONF_DEVICE_CID)}
  305. if user_input is not None:
  306. self.device = await async_test_connection(user_input, self.hass)
  307. if self.device:
  308. self.data = user_input
  309. if self.__cloud_device:
  310. if self.__cloud_device.get("product_id"):
  311. self.device.set_detected_product_id(
  312. self.__cloud_device.get("product_id")
  313. )
  314. if self.__cloud_device.get("local_product_id"):
  315. self.device.set_detected_product_id(
  316. self.__cloud_device.get("local_product_id")
  317. )
  318. await self.async_set_unique_id(
  319. user_input.get(CONF_DEVICE_CID, user_input[CONF_DEVICE_ID])
  320. )
  321. self._abort_if_unique_id_configured()
  322. return await self.async_step_select_type()
  323. else:
  324. errors["base"] = "connection"
  325. devid_opts["default"] = user_input[CONF_DEVICE_ID]
  326. host_opts["default"] = user_input[CONF_HOST]
  327. key_opts["default"] = user_input[CONF_LOCAL_KEY]
  328. if CONF_DEVICE_CID in user_input:
  329. devcid_opts["default"] = user_input[CONF_DEVICE_CID]
  330. proto_opts["default"] = user_input[CONF_PROTOCOL_VERSION]
  331. polling_opts["default"] = user_input[CONF_POLL_ONLY]
  332. return self.async_show_form(
  333. step_id="local",
  334. data_schema=vol.Schema(
  335. {
  336. vol.Required(CONF_DEVICE_ID, **devid_opts): str,
  337. vol.Required(CONF_HOST, **host_opts): str,
  338. vol.Required(CONF_LOCAL_KEY, **key_opts): str,
  339. vol.Required(
  340. CONF_PROTOCOL_VERSION,
  341. **proto_opts,
  342. ): vol.In(["auto"] + API_PROTOCOL_VERSIONS),
  343. vol.Required(CONF_POLL_ONLY, **polling_opts): bool,
  344. vol.Optional(CONF_DEVICE_CID, **devcid_opts): str,
  345. }
  346. ),
  347. errors=errors,
  348. )
  349. async def async_step_select_type(self, user_input=None):
  350. if user_input is not None:
  351. self.data[CONF_TYPE] = user_input[CONF_TYPE]
  352. return await self.async_step_choose_entities()
  353. types = []
  354. best_match = 0
  355. best_matching_type = None
  356. for type in await self.device.async_possible_types():
  357. types.append(type.config_type)
  358. q = type.match_quality(
  359. self.device._get_cached_state(),
  360. self.device._product_ids,
  361. )
  362. if q > best_match:
  363. best_match = q
  364. best_matching_type = type.config_type
  365. best_match = int(best_match)
  366. dps = self.device._get_cached_state()
  367. if self.__cloud_device:
  368. _LOGGER.warning(
  369. "Adding %s device with product id %s",
  370. self.__cloud_device.get("product_name", "UNKNOWN"),
  371. self.__cloud_device.get("product_id", "UNKNOWN"),
  372. )
  373. if self.__cloud_device.get("local_product_id") and self.__cloud_device.get(
  374. "local_product_id"
  375. ) != self.__cloud_device.get("product_id"):
  376. _LOGGER.warning(
  377. "Local product id differs from cloud: %s",
  378. self.__cloud_device.get("local_product_id"),
  379. )
  380. try:
  381. self.init_cloud()
  382. model = await self.cloud.async_get_datamodel(
  383. self.__cloud_device.get("id"),
  384. )
  385. if model:
  386. _LOGGER.warning(
  387. "Cloud device spec:\n%s",
  388. log_json(model),
  389. )
  390. except Exception as e:
  391. _LOGGER.warning("Unable to fetch data model from cloud: %s", e)
  392. _LOGGER.warning(
  393. "Device matches %s with quality of %d%%. DPS: %s",
  394. best_matching_type,
  395. best_match,
  396. log_json(dps),
  397. )
  398. _LOGGER.warning(
  399. "Include the previous log messages with any new device request to https://github.com/make-all/tuya-local/issues/",
  400. )
  401. if types:
  402. return self.async_show_form(
  403. step_id="select_type",
  404. data_schema=vol.Schema(
  405. {
  406. vol.Required(
  407. CONF_TYPE,
  408. default=best_matching_type,
  409. ): vol.In(types),
  410. }
  411. ),
  412. )
  413. else:
  414. return self.async_abort(reason="not_supported")
  415. async def async_step_choose_entities(self, user_input=None):
  416. if user_input is not None:
  417. title = user_input[CONF_NAME]
  418. del user_input[CONF_NAME]
  419. return self.async_create_entry(
  420. title=title, data={**self.data, **user_input}
  421. )
  422. config = await self.hass.async_add_executor_job(
  423. get_config,
  424. self.data[CONF_TYPE],
  425. )
  426. schema = {vol.Required(CONF_NAME, default=config.name): str}
  427. return self.async_show_form(
  428. step_id="choose_entities",
  429. data_schema=vol.Schema(schema),
  430. )
  431. @staticmethod
  432. @callback
  433. def async_get_options_flow(config_entry: ConfigEntry):
  434. return OptionsFlowHandler()
  435. class OptionsFlowHandler(OptionsFlow):
  436. def __init__(self):
  437. """Initialize options flow."""
  438. pass
  439. async def async_step_init(self, user_input=None):
  440. return await self.async_step_user(user_input)
  441. async def async_step_user(self, user_input=None):
  442. """Manage the options."""
  443. errors = {}
  444. config = {**self.config_entry.data, **self.config_entry.options}
  445. if user_input is not None:
  446. config = {**config, **user_input}
  447. device = await async_test_connection(config, self.hass)
  448. if device:
  449. return self.async_create_entry(title="", data=user_input)
  450. else:
  451. errors["base"] = "connection"
  452. schema = {
  453. vol.Required(
  454. CONF_LOCAL_KEY,
  455. default=config.get(CONF_LOCAL_KEY, ""),
  456. ): str,
  457. vol.Required(CONF_HOST, default=config.get(CONF_HOST, "")): str,
  458. vol.Required(
  459. CONF_PROTOCOL_VERSION,
  460. default=config.get(CONF_PROTOCOL_VERSION, "auto"),
  461. ): vol.In(["auto"] + API_PROTOCOL_VERSIONS),
  462. vol.Required(
  463. CONF_POLL_ONLY, default=config.get(CONF_POLL_ONLY, False)
  464. ): bool,
  465. }
  466. cfg = await self.hass.async_add_executor_job(
  467. get_config,
  468. config[CONF_TYPE],
  469. )
  470. if cfg is None:
  471. return self.async_abort(reason="not_supported")
  472. return self.async_show_form(
  473. step_id="user",
  474. data_schema=vol.Schema(schema),
  475. errors=errors,
  476. )
  477. def create_test_device(hass: HomeAssistant, config: dict):
  478. """Set up a tuya device based on passed in config."""
  479. subdevice_id = config.get(CONF_DEVICE_CID)
  480. device = TuyaLocalDevice(
  481. "Test",
  482. config[CONF_DEVICE_ID],
  483. config[CONF_HOST],
  484. config[CONF_LOCAL_KEY],
  485. config[CONF_PROTOCOL_VERSION],
  486. subdevice_id,
  487. hass,
  488. True,
  489. )
  490. return device
  491. async def async_test_connection(config: dict, hass: HomeAssistant):
  492. domain_data = hass.data.get(DOMAIN)
  493. existing = domain_data.get(get_device_id(config)) if domain_data else None
  494. if existing and existing.get("device"):
  495. _LOGGER.info("Pausing existing device to test new connection parameters")
  496. existing["device"].pause()
  497. await asyncio.sleep(5)
  498. try:
  499. device = await hass.async_add_executor_job(
  500. create_test_device,
  501. hass,
  502. config,
  503. )
  504. await device.async_refresh()
  505. retval = device if device.has_returned_state else None
  506. except Exception as e:
  507. _LOGGER.warning("Connection test failed with %s %s", type(e), e)
  508. retval = None
  509. if existing and existing.get("device"):
  510. _LOGGER.info("Restarting device after test")
  511. existing["device"].resume()
  512. return retval
  513. def scan_for_device(id):
  514. return tinytuya.find_device(dev_id=id)