-
-
Notifications
You must be signed in to change notification settings - Fork 32.1k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Clean up OpenUV config flow #17349
Merged
Merged
Clean up OpenUV config flow #17349
Changes from 6 commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
a0f3715
Cleaned up OpenUV config flow
bachya a63c95e
Added proper listener removal
bachya 6e71810
Added proper exception
bachya a1d31fe
Unnecessary exception message
bachya fe7704a
Moved API key error to correct place
bachya 851ff3f
Member-requested changes (part 1)
bachya 31d25ad
Hound
bachya 2782afa
Member-requested changes (part 2)
bachya 478fd17
Cleanup
bachya b4f6010
Fixed tests
bachya File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -14,13 +14,14 @@ | |
ATTR_ATTRIBUTION, CONF_API_KEY, CONF_BINARY_SENSORS, CONF_ELEVATION, | ||
CONF_LATITUDE, CONF_LONGITUDE, CONF_MONITORED_CONDITIONS, | ||
CONF_SCAN_INTERVAL, CONF_SENSORS) | ||
from homeassistant.exceptions import ConfigEntryNotReady | ||
from homeassistant.helpers import aiohttp_client, config_validation as cv | ||
from homeassistant.helpers.dispatcher import async_dispatcher_send | ||
from homeassistant.helpers.entity import Entity | ||
from homeassistant.helpers.event import async_track_time_interval | ||
|
||
from .config_flow import configured_instances | ||
from .const import DOMAIN | ||
from .const import DEFAULT_SCAN_INTERVAL, DOMAIN | ||
|
||
REQUIREMENTS = ['pyopenuv==1.0.4'] | ||
_LOGGER = logging.getLogger(__name__) | ||
|
@@ -31,7 +32,6 @@ | |
DATA_UV = 'uv' | ||
|
||
DEFAULT_ATTRIBUTION = 'Data provided by OpenUV' | ||
DEFAULT_SCAN_INTERVAL = timedelta(minutes=30) | ||
|
||
NOTIFICATION_ID = 'openuv_notification' | ||
NOTIFICATION_TITLE = 'OpenUV Component Setup' | ||
|
@@ -85,18 +85,17 @@ | |
}) | ||
|
||
CONFIG_SCHEMA = vol.Schema({ | ||
DOMAIN: | ||
vol.Schema({ | ||
vol.Required(CONF_API_KEY): cv.string, | ||
vol.Optional(CONF_ELEVATION): float, | ||
vol.Optional(CONF_LATITUDE): cv.latitude, | ||
vol.Optional(CONF_LONGITUDE): cv.longitude, | ||
vol.Optional(CONF_BINARY_SENSORS, default={}): | ||
BINARY_SENSOR_SCHEMA, | ||
vol.Optional(CONF_SENSORS, default={}): SENSOR_SCHEMA, | ||
vol.Optional(CONF_SCAN_INTERVAL, default=DEFAULT_SCAN_INTERVAL): | ||
cv.time_period, | ||
}) | ||
DOMAIN: vol.Schema({ | ||
vol.Required(CONF_API_KEY): cv.string, | ||
vol.Optional(CONF_ELEVATION): float, | ||
vol.Optional(CONF_LATITUDE): cv.latitude, | ||
vol.Optional(CONF_LONGITUDE): cv.longitude, | ||
vol.Optional(CONF_BINARY_SENSORS, default={}): | ||
BINARY_SENSOR_SCHEMA, | ||
vol.Optional(CONF_SENSORS, default={}): SENSOR_SCHEMA, | ||
vol.Optional(CONF_SCAN_INTERVAL, default=DEFAULT_SCAN_INTERVAL): | ||
cv.time_period, | ||
}) | ||
}, extra=vol.ALLOW_EXTRA) | ||
|
||
|
||
|
@@ -110,27 +109,26 @@ async def async_setup(hass, config): | |
return True | ||
|
||
conf = config[DOMAIN] | ||
latitude = conf.get(CONF_LATITUDE, hass.config.latitude) | ||
longitude = conf.get(CONF_LONGITUDE, hass.config.longitude) | ||
elevation = conf.get(CONF_ELEVATION, hass.config.elevation) | ||
latitude = conf.get(CONF_LATITUDE) | ||
longitude = conf.get(CONF_LONGITUDE) | ||
|
||
identifier = '{0}, {1}'.format(latitude, longitude) | ||
if identifier in configured_instances(hass): | ||
return True | ||
|
||
if identifier not in configured_instances(hass): | ||
hass.async_add_job( | ||
hass.config_entries.flow.async_init( | ||
DOMAIN, | ||
context={'source': SOURCE_IMPORT}, | ||
data={ | ||
CONF_API_KEY: conf[CONF_API_KEY], | ||
CONF_LATITUDE: latitude, | ||
CONF_LONGITUDE: longitude, | ||
CONF_ELEVATION: elevation, | ||
CONF_BINARY_SENSORS: conf[CONF_BINARY_SENSORS], | ||
CONF_SENSORS: conf[CONF_SENSORS], | ||
})) | ||
|
||
hass.data[DOMAIN][CONF_SCAN_INTERVAL] = conf[CONF_SCAN_INTERVAL] | ||
hass.async_create_task( | ||
hass.config_entries.flow.async_init( | ||
DOMAIN, | ||
context={'source': SOURCE_IMPORT}, | ||
data={ | ||
CONF_API_KEY: conf[CONF_API_KEY], | ||
CONF_LATITUDE: latitude, | ||
CONF_LONGITUDE: longitude, | ||
CONF_ELEVATION: conf.get(CONF_ELEVATION), | ||
CONF_BINARY_SENSORS: conf[CONF_BINARY_SENSORS], | ||
CONF_SENSORS: conf[CONF_SENSORS], | ||
CONF_SCAN_INTERVAL: conf[CONF_SCAN_INTERVAL], | ||
})) | ||
|
||
return True | ||
|
||
|
@@ -145,56 +143,50 @@ async def async_setup_entry(hass, config_entry): | |
openuv = OpenUV( | ||
Client( | ||
config_entry.data[CONF_API_KEY], | ||
config_entry.data.get(CONF_LATITUDE, hass.config.latitude), | ||
config_entry.data.get(CONF_LONGITUDE, hass.config.longitude), | ||
config_entry.data[CONF_LATITUDE], | ||
config_entry.data[CONF_LONGITUDE], | ||
websession, | ||
altitude=config_entry.data.get( | ||
CONF_ELEVATION, hass.config.elevation)), | ||
altitude=config_entry.data[CONF_ELEVATION]), | ||
config_entry.data.get(CONF_BINARY_SENSORS, {}).get( | ||
CONF_MONITORED_CONDITIONS, list(BINARY_SENSORS)), | ||
config_entry.data.get(CONF_SENSORS, {}).get( | ||
CONF_MONITORED_CONDITIONS, list(SENSORS))) | ||
await openuv.async_update() | ||
hass.data[DOMAIN][DATA_OPENUV_CLIENT][config_entry.entry_id] = openuv | ||
except OpenUvError as err: | ||
_LOGGER.error('An error occurred: %s', str(err)) | ||
hass.components.persistent_notification.create( | ||
'Error: {0}<br />' | ||
'You will need to restart hass after fixing.' | ||
''.format(err), | ||
title=NOTIFICATION_TITLE, | ||
notification_id=NOTIFICATION_ID) | ||
return False | ||
_LOGGER.error('Config entry failed: %s', err) | ||
raise ConfigEntryNotReady | ||
|
||
for component in ('binary_sensor', 'sensor'): | ||
hass.async_create_task(hass.config_entries.async_forward_entry_setup( | ||
config_entry, component)) | ||
|
||
async def refresh_sensors(event_time): | ||
async def refresh(event_time): | ||
"""Refresh OpenUV data.""" | ||
_LOGGER.debug('Refreshing OpenUV data') | ||
await openuv.async_update() | ||
async_dispatcher_send(hass, TOPIC_UPDATE) | ||
|
||
hass.data[DOMAIN][DATA_OPENUV_LISTENER][ | ||
config_entry.entry_id] = async_track_time_interval( | ||
hass, refresh_sensors, | ||
hass.data[DOMAIN].get(CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL)) | ||
hass, | ||
refresh, | ||
timedelta(seconds=config_entry.data[CONF_SCAN_INTERVAL])) | ||
|
||
return True | ||
|
||
|
||
async def async_unload_entry(hass, config_entry): | ||
"""Unload an OpenUV config entry.""" | ||
for component in ('binary_sensor', 'sensor'): | ||
await hass.config_entries.async_forward_entry_unload( | ||
config_entry, component) | ||
|
||
hass.data[DOMAIN][DATA_OPENUV_CLIENT].pop(config_entry.entry_id) | ||
|
||
remove_listener = hass.data[DOMAIN][DATA_OPENUV_LISTENER].pop( | ||
config_entry.entry_id) | ||
remove_listener() | ||
|
||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. blank line contains whitespace |
||
for component in ('binary_sensor', 'sensor'): | ||
await hass.config_entries.async_forward_entry_unload( | ||
config_entry, component) | ||
|
||
return True | ||
|
||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -7,10 +7,11 @@ | |
from homeassistant import config_entries | ||
from homeassistant.core import callback | ||
from homeassistant.const import ( | ||
CONF_API_KEY, CONF_ELEVATION, CONF_LATITUDE, CONF_LONGITUDE) | ||
CONF_API_KEY, CONF_ELEVATION, CONF_LATITUDE, CONF_LONGITUDE, | ||
CONF_SCAN_INTERVAL) | ||
from homeassistant.helpers import aiohttp_client, config_validation as cv | ||
|
||
from .const import DOMAIN | ||
from .const import DEFAULT_SCAN_INTERVAL, DOMAIN | ||
|
||
|
||
@callback | ||
|
@@ -31,7 +32,19 @@ class OpenUvFlowHandler(config_entries.ConfigFlow): | |
|
||
def __init__(self): | ||
"""Initialize the config flow.""" | ||
pass | ||
self.data_schema = OrderedDict() | ||
self.data_schema[vol.Required(CONF_API_KEY)] = str | ||
self.data_schema[vol.Optional(CONF_LATITUDE)] = cv.latitude | ||
self.data_schema[vol.Optional(CONF_LONGITUDE)] = cv.longitude | ||
self.data_schema[vol.Optional(CONF_ELEVATION)] = vol.Coerce(float) | ||
|
||
async def _show_form(self, errors=None): | ||
"""Show the form to the user.""" | ||
return self.async_show_form( | ||
step_id='user', | ||
data_schema=vol.Schema(self.data_schema), | ||
errors=errors if errors else {}, | ||
) | ||
|
||
async def async_step_import(self, import_config): | ||
"""Import a config entry from configuration.yaml.""" | ||
|
@@ -41,34 +54,37 @@ async def async_step_user(self, user_input=None): | |
"""Handle the start of the config flow.""" | ||
from pyopenuv.util import validate_api_key | ||
|
||
errors = {} | ||
|
||
if user_input is not None: | ||
identifier = '{0}, {1}'.format( | ||
user_input.get(CONF_LATITUDE, self.hass.config.latitude), | ||
user_input.get(CONF_LONGITUDE, self.hass.config.longitude)) | ||
|
||
if identifier in configured_instances(self.hass): | ||
errors['base'] = 'identifier_exists' | ||
else: | ||
websession = aiohttp_client.async_get_clientsession(self.hass) | ||
api_key_validation = await validate_api_key( | ||
user_input[CONF_API_KEY], websession) | ||
if api_key_validation: | ||
return self.async_create_entry( | ||
title=identifier, | ||
data=user_input, | ||
) | ||
errors['base'] = 'invalid_api_key' | ||
|
||
data_schema = OrderedDict() | ||
data_schema[vol.Required(CONF_API_KEY)] = str | ||
data_schema[vol.Optional(CONF_LATITUDE)] = cv.latitude | ||
data_schema[vol.Optional(CONF_LONGITUDE)] = cv.longitude | ||
data_schema[vol.Optional(CONF_ELEVATION)] = vol.Coerce(float) | ||
|
||
return self.async_show_form( | ||
step_id='user', | ||
data_schema=vol.Schema(data_schema), | ||
errors=errors, | ||
) | ||
if not user_input: | ||
return await self._show_form() | ||
|
||
latitude = user_input.get(CONF_LATITUDE) | ||
if not latitude: | ||
latitude = self.hass.config.latitude | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Maybe move defaults to form schema? |
||
longitude = user_input.get(CONF_LONGITUDE) | ||
if not longitude: | ||
longitude = self.hass.config.longitude | ||
elevation = user_input.get(CONF_ELEVATION) | ||
if not elevation: | ||
elevation = self.hass.config.elevation | ||
|
||
identifier = '{0}, {1}'.format(latitude, longitude) | ||
if identifier in configured_instances(self.hass): | ||
return await self._show_form({CONF_LATITUDE: 'identifier_exists'}) | ||
|
||
websession = aiohttp_client.async_get_clientsession(self.hass) | ||
api_key_validation = await validate_api_key( | ||
user_input[CONF_API_KEY], websession) | ||
|
||
if not api_key_validation: | ||
return await self._show_form({CONF_API_KEY: 'invalid_api_key'}) | ||
|
||
scan_interval = user_input.get( | ||
CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL) | ||
user_input.update({ | ||
CONF_LATITUDE: latitude, | ||
CONF_LONGITUDE: longitude, | ||
CONF_ELEVATION: elevation, | ||
CONF_SCAN_INTERVAL: scan_interval.seconds, | ||
}) | ||
|
||
return self.async_create_entry(title=identifier, data=user_input) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,3 +1,6 @@ | ||
"""Define constants for the OpenUV component.""" | ||
from datetime import timedelta | ||
|
||
DOMAIN = 'openuv' | ||
|
||
DEFAULT_SCAN_INTERVAL = timedelta(minutes=30) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Unsubscribe this listener before unloading the platforms. Otherwise there could perhaps be a race condition and another update come in before we disconnect the update callbacks in the platforms.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Even if we do this, there could perhaps be a race if the state update has already been scheduled?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Does 851ff3f address what you were thinking?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yes, but I'm not sure it actually prevents anything. I was thinking about the problem you described earlier, and that a scheduled update could be the cause.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Got it. Let me experiment with removing the dispatcher altogether and see if that clears up my prior issue.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I tried commenting all out all references to the dispatcher, but when I remove the config entry, I'm back to getting this weird exception:
I don't understand what listener the config entry is trying to remove?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
FYI, tracking this issue separately: #17370.