config_flow.py 20 KB

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