Skip to content

Commit

Permalink
refactor: use reconfig flow (#85)
Browse files Browse the repository at this point in the history
* refactor: use reconfig flow

* linting
  • Loading branch information
firstof9 authored Dec 6, 2024
1 parent 281bfa9 commit 621081e
Show file tree
Hide file tree
Showing 4 changed files with 183 additions and 528 deletions.
19 changes: 1 addition & 18 deletions custom_components/openei/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,27 +40,10 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
hass.data.setdefault(DOMAIN, {})
_LOGGER.info(STARTUP_MESSAGE)

updated_config = entry.data.copy()

_LOGGER.debug("config_entry: %s", updated_config)

if CONF_SENSOR in updated_config.keys() and updated_config[CONF_SENSOR] == "(none)":
updated_config.pop(CONF_SENSOR, None)

if CONF_MANUAL_PLAN not in updated_config.keys():
updated_config[CONF_MANUAL_PLAN] = ""

if CONF_PLAN not in updated_config.keys():
updated_config[CONF_PLAN] = ""

if not any([updated_config[CONF_MANUAL_PLAN], updated_config[CONF_PLAN]]):
if CONF_MANUAL_PLAN not in entry.data.keys() and CONF_PLAN not in entry.data.keys():
_LOGGER.error("Plan configuration missing.")
raise ConfigEntryNotReady

_LOGGER.debug("updated_config: %s", updated_config)
if updated_config != entry.data:
hass.config_entries.async_update_entry(entry, data=updated_config)

entry.add_update_listener(update_listener)

coordinator = OpenEIDataUpdateCoordinator(hass, config=entry)
Expand Down
135 changes: 65 additions & 70 deletions custom_components/openei/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ def __init__(self):
"""Initialize."""
self._data = {}
self._errors = {}
self._entry = {}

async def async_step_user(self, user_input=None):
"""Handle a flow initialized by the user."""
Expand All @@ -61,6 +62,8 @@ async def async_step_user_3(self, user_input=None):
self._errors = {}

if user_input is not None:
if user_input[CONF_SENSOR] == "(none)":
user_input.pop(CONF_SENSOR, None)
self._data.update(user_input)
return self.async_create_entry(
title=self._data[CONF_UTILITY], data=self._data
Expand Down Expand Up @@ -103,77 +106,69 @@ async def _show_config_form_3(self, user_input): # pylint: disable=unused-argum
errors=self._errors,
)

async def async_step_reconfigure(self, user_input: dict[str, Any] | None = None):
"""Add reconfigure step to allow to reconfigure a config entry."""
self._entry = self.hass.config_entries.async_get_entry(self.context["entry_id"])
assert self._entry
self._data = dict(self._entry.data)
self._errors = {}

if user_input is not None:
self._data.update(user_input)
return await self.async_step_reconfig_2()
return await self._show_reconfig_form(user_input)

async def _show_reconfig_form(self, user_input):
"""Show the configuration form to edit configuration data."""
return self.async_show_form(
step_id="reconfigure",
data_schema=_get_schema_step_1(user_input, self._data),
errors=self._errors,
)

async def async_step_reconfig_2(self, user_input: dict[str, Any] | None = None):
"""Add reconfigure step to allow to reconfigure a config entry."""
self._errors = {}

if user_input is not None:
self._data.update(user_input)
return await self.async_step_reconfig_3()
return await self._show_reconfig_2()

async def _show_reconfig_2(self):
"""Show the configuration form to edit configuration data."""
defaults = {}
utility_list = await _get_utility_list(self.hass, self._data)
_LOGGER.debug("Utility list: %s", utility_list)
return self.async_show_form(
step_id="reconfig_2",
data_schema=_get_schema_step_2(self._data, defaults, utility_list),
errors=self._errors,
)

async def async_step_reconfig_3(self, user_input: dict[str, Any] | None = None):
"""Add reconfigure step to allow to reconfigure a config entry."""
self._errors = {}

# class OpenEIOptionsFlowHandler(config_entries.OptionsFlow):
# """Blueprint config flow options handler."""

# def __init__(self, config_entry):
# """Initialize OpenEI options flow."""
# self.config_entry = config_entry
# self._data = dict(config_entry.data)
# self._errors = {}

# async def async_step_init(self, user_input=None): # pylint: disable=unused-argument
# """Manage the options."""
# return await self.async_step_user()

# async def async_step_user(self, user_input=None):
# """Handle a flow initialized by the user."""
# if user_input is not None:
# if user_input[CONF_LOCATION] == '""':
# user_input[CONF_LOCATION] = ""
# self._data.update(user_input)
# return await self.async_step_user_2()

# return await self._show_config_form(user_input)

# async def async_step_user_2(self, user_input=None):
# """Handle a flow initialized by the user."""
# _LOGGER.debug("data: %s", self._data)
# if user_input is not None:
# self._data.update(user_input)
# return await self.async_step_user_3()

# return await self._show_config_form_2(user_input)

# async def async_step_user_3(self, user_input=None):
# """Handle a flow initialized by the user."""
# _LOGGER.debug("data: %s", self._data)
# if user_input is not None:
# if user_input[CONF_MANUAL_PLAN] == '""':
# user_input[CONF_MANUAL_PLAN] = ""
# self._data.update(user_input)
# return self.async_create_entry(title="", data=self._data)

# return await self._show_config_form_3(user_input)

# async def _show_config_form(self, user_input: Optional[Dict[str, Any]]):
# """Show the configuration form to edit location data."""
# return self.async_show_form(
# step_id="user",
# data_schema=_get_schema_step_1(user_input, self._data),
# errors=self._errors,
# )

# async def _show_config_form_2(self, user_input: Optional[Dict[str, Any]]):
# """Show the configuration form to edit location data."""
# utility_list = await _get_utility_list(self.hass, self._data)
# return self.async_show_form(
# step_id="user_2",
# data_schema=_get_schema_step_2(user_input, self._data, utility_list),
# errors=self._errors,
# )

# async def _show_config_form_3(self, user_input: Optional[Dict[str, Any]]):
# """Show the configuration form to edit location data."""
# plan_list = await _get_plan_list(self.hass, self._data)
# return self.async_show_form(
# step_id="user_3",
# data_schema=_get_schema_step_3(
# self.hass, user_input, self._data, plan_list
# ),
# errors=self._errors,
# )
if user_input is not None:
if user_input[CONF_SENSOR] == "(none)":
user_input.pop(CONF_SENSOR, None)
self._data.update(user_input)
self.hass.config_entries.async_update_entry(self._entry, data=self._data)
await self.hass.config_entries.async_reload(self._entry.entry_id)
_LOGGER.debug("%s reconfigured.", DOMAIN)
return self.async_abort(reason="reconfigure_successful")
return await self._show_reconfig_3()

async def _show_reconfig_3(self):
"""Show the configuration form to edit configuration data."""
defaults = {}
plan_list = await _get_plan_list(self.hass, self._data)
return self.async_show_form(
step_id="reconfig_3",
data_schema=_get_schema_step_3(self.hass, self._data, defaults, plan_list),
errors=self._errors,
)


def _get_schema_step_1(
Expand Down
30 changes: 13 additions & 17 deletions custom_components/openei/translations/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,42 +25,38 @@
"sensor": "Energy sensor for Tier plans (optional)",
"manual_plan": "Manually enter plan from OpenEI website (optional)"
}
}
},
"error": {
"auth": "Username/Password is wrong."
},
"abort": {
"single_instance_allowed": "Only a single configuration of Blueprint is allowed."
}
},
"options": {
"step": {
"user": {
},
"reconfigure": {
"title": "OpenEI (Step 1)",
"description": "If you do not have an API Key yet you can get one here: https://openei.org/services/api/signup/ \n\nEnter \"\" in address to clear it and use latitude and longitude from Home Assistant.",
"description": "If you do not have an API Key yet you can get one here: https://openei.org/services/api/signup/\n\nOmit address to use latitude and longitude from Home Assistant.",
"data": {
"api_key": "API Key",
"radius": "Radius in miles (optional)",
"location": "City,State or Zip Code (optional)"
}
},
"user_2": {
"reconfig_2": {
"title": "OpenEI (Step 2)",
"description": "Select your utility company.\n\nIf you are entering a plan manually please select 'Not Listed'",
"data": {
"utility": "Utility Company"
}
},
"user_3": {
"reconfig_3": {
"title": "OpenEI (Step 3)",
"description": "Select your plan from the list. If you are unsure, check your utility bill.\n\nManual plan will override the selected rate plan.\n\nEnter \"\" to clear the manual plan.",
"description": "Select your plan from the list. If you are unsure, check your utility bill.\n\nManual plan will override the selected rate plan.",
"data": {
"rate_plan": "Rate Plan",
"sensor": "Energy sensor for Tier plans (optional)",
"manual_plan": "Manually enter plan from OpenEI website (optional)"
}
}
}
},
"error": {
"auth": "Username/Password is wrong."
},
"abort": {
"single_instance_allowed": "Only a single configuration of Blueprint is allowed."
}
}
}
Loading

0 comments on commit 621081e

Please sign in to comment.