config_flow.py 19 KB

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