From 5817bb556392442062c4e657a5593ebed1a22b9d Mon Sep 17 00:00:00 2001 From: Dan Raper Date: Mon, 15 Apr 2024 17:37:35 +0100 Subject: [PATCH] Fix options flow, add unique ID to config entry, cache coordinator data (#2) * Fix options flow * Add unique id to config entry * Cache API response to avoid sensors showing unknown * Bump version --- custom_components/o2/config_flow.py | 17 ++++++++++------- custom_components/o2/const.py | 2 +- custom_components/o2/coordinator.py | 5 ++++- 3 files changed, 15 insertions(+), 9 deletions(-) diff --git a/custom_components/o2/config_flow.py b/custom_components/o2/config_flow.py index e60f6eb..c7ab082 100644 --- a/custom_components/o2/config_flow.py +++ b/custom_components/o2/config_flow.py @@ -20,6 +20,10 @@ class O2ConfigFlow(ConfigFlow, domain=DOMAIN): async def async_step_user(self, info): errors = {} if info is not None: + # Abort if entry already exists + await self.async_set_unique_id(info["email"]) + self._abort_if_unique_id_configured() + # Validate credentials session = O2ApiClient( info["email"], @@ -33,7 +37,7 @@ async def async_step_user(self, info): if len(errors) == 0: return self.async_create_entry( - title="O2 Account", + title=info['email'], data=info ) @@ -57,12 +61,11 @@ async def async_step_init(self, options): if options is not None: data = dict(self._config_entry.data) # Validate credentials - session = O2ApiClient( - info["email"], - info["password"] - ) - if "password" in options: + session = O2ApiClient( + options["email"], + options["password"] + ) try: await self.hass.async_add_executor_job(session.create_session) except: @@ -78,7 +81,7 @@ async def async_step_init(self, options): # Update data data.update(options) self.hass.config_entries.async_update_entry( - self._config_entry, data=data + self._config_entry, data=data, title=data['email'] ) # Update options diff --git a/custom_components/o2/const.py b/custom_components/o2/const.py index 73d7890..394c918 100644 --- a/custom_components/o2/const.py +++ b/custom_components/o2/const.py @@ -2,7 +2,7 @@ CONFIG_VERSION = 1 ENTITY_TYPES = ["sensor"] USER_AGENT = "dan-r-homeassistant-o2" -INTEGRATION_VERSION = "0.1.0" +INTEGRATION_VERSION = "0.1.1" DATA_COORDINATOR = "coordinator" DATA_APICLIENT = "apiclient" diff --git a/custom_components/o2/coordinator.py b/custom_components/o2/coordinator.py index 85886d7..6d7f49f 100644 --- a/custom_components/o2/coordinator.py +++ b/custom_components/o2/coordinator.py @@ -17,6 +17,7 @@ def __init__(self, hass, config): update_interval=timedelta(minutes=30), ) self._hass = hass + self._data = None async def _async_update_data(self): """Fetch data from API.""" @@ -24,7 +25,9 @@ async def _async_update_data(self): try: data = await self._hass.async_add_executor_job(client.get_allowances) + self._data = data + return data except BaseException: _LOGGER.warning("Error communicating with API") - return False + return self._data