config_flow.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import voluptuous as vol
  2. from homeassistant import config_entries
  3. from homeassistant.const import CONF_NAME, CONF_HOST
  4. from homeassistant.core import callback, HomeAssistant
  5. from . import DOMAIN, individual_config_schema, TuyaLocalDevice
  6. from .const import CONF_DEVICE_ID, CONF_LOCAL_KEY
  7. class ConfigFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
  8. VERSION = 1
  9. CONNECTION_CLASS = config_entries.CONN_CLASS_LOCAL_POLL
  10. async def async_step_user(self, user_input=None):
  11. errors = {}
  12. if user_input is not None:
  13. await self.async_set_unique_id(user_input[CONF_DEVICE_ID])
  14. self._abort_if_unique_id_configured()
  15. connect_success = await async_test_connection(user_input, self.hass)
  16. if connect_success:
  17. title = user_input[CONF_NAME]
  18. del user_input[CONF_NAME]
  19. return self.async_create_entry(title=title, data=user_input)
  20. else:
  21. errors["base"] = "connection"
  22. return self.async_show_form(
  23. step_id="user", data_schema=vol.Schema(individual_config_schema(user_input or {})), errors=errors
  24. )
  25. @staticmethod
  26. @callback
  27. def async_get_options_flow(config_entry):
  28. return OptionsFlowHandler(config_entry)
  29. class OptionsFlowHandler(config_entries.OptionsFlow):
  30. def __init__(self, config_entry):
  31. """Initialize options flow."""
  32. self.config_entry = config_entry
  33. async def async_step_init(self, user_input=None):
  34. return await self.async_step_user(user_input)
  35. async def async_step_user(self, user_input=None):
  36. """Manage the options."""
  37. errors = {}
  38. config = {**self.config_entry.data, **self.config_entry.options}
  39. if user_input is not None:
  40. config = {**config, **user_input}
  41. connect_success = await async_test_connection(config, self.hass)
  42. if connect_success:
  43. return self.async_create_entry(title="", data=user_input)
  44. else:
  45. errors["base"] = "connection"
  46. return self.async_show_form(
  47. step_id="user",
  48. data_schema=vol.Schema(
  49. individual_config_schema(defaults=config, options_only=True)
  50. ),
  51. errors=errors
  52. )
  53. async def async_test_connection(config: dict, hass: HomeAssistant):
  54. device = TuyaLocalDevice("Test", config[CONF_DEVICE_ID], config[CONF_HOST], config[CONF_LOCAL_KEY], hass)
  55. await device.async_refresh()
  56. return device.get_property("1") is not None or device.get_property("3") is not None