From fc41dc5a945fd0257ab7a993bd07476ecca1123a Mon Sep 17 00:00:00 2001 From: "firstof9@gmail.com" Date: Fri, 17 Mar 2023 17:49:53 -0700 Subject: [PATCH] add steps to options flow --- custom_components/__init__.py | 1 - custom_components/nws_alerts/__init__.py | 66 ++++++++++++++------- custom_components/nws_alerts/config_flow.py | 43 +++++++++++--- custom_components/nws_alerts/sensor.py | 20 +++++-- 4 files changed, 94 insertions(+), 36 deletions(-) diff --git a/custom_components/__init__.py b/custom_components/__init__.py index fab6099..9d18c38 100644 --- a/custom_components/__init__.py +++ b/custom_components/__init__.py @@ -1,2 +1 @@ """For testing""" - diff --git a/custom_components/nws_alerts/__init__.py b/custom_components/nws_alerts/__init__.py index 4532ac6..ea25c41 100644 --- a/custom_components/nws_alerts/__init__.py +++ b/custom_components/nws_alerts/__init__.py @@ -1,4 +1,3 @@ - """ NWS Alerts """ import logging from datetime import timedelta @@ -10,14 +9,26 @@ from homeassistant.const import CONF_NAME from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_registry import ( - async_entries_for_config_entry, async_get) -from homeassistant.helpers.update_coordinator import (DataUpdateCoordinator, - UpdateFailed) - -from .const import (API_ENDPOINT, CONF_GPS_LOC, CONF_INTERVAL, CONF_TIMEOUT, - CONF_ZONE_ID, COORDINATOR, DEFAULT_INTERVAL, - DEFAULT_TIMEOUT, DOMAIN, ISSUE_URL, PLATFORMS, USER_AGENT, - VERSION) + async_entries_for_config_entry, + async_get, +) +from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed + +from .const import ( + API_ENDPOINT, + CONF_GPS_LOC, + CONF_INTERVAL, + CONF_TIMEOUT, + CONF_ZONE_ID, + COORDINATOR, + DEFAULT_INTERVAL, + DEFAULT_TIMEOUT, + DOMAIN, + ISSUE_URL, + PLATFORMS, + USER_AGENT, + VERSION, +) _LOGGER = logging.getLogger(__name__) @@ -150,7 +161,7 @@ async def async_get_state(config) -> dict: _LOGGER.debug("getting state for %s from %s" % (zone_id, url)) elif CONF_GPS_LOC in config: gps_loc = config[CONF_GPS_LOC] - _LOGGER.debug("getting state for %s from %s" % (gps_loc, url)) + _LOGGER.debug("getting state for %s from %s" % (gps_loc, url)) async with aiohttp.ClientSession() as session: async with session.get(url, headers=headers) as r: @@ -193,7 +204,7 @@ async def async_get_alerts(zone_id: str = "", gps_loc: str = "") -> dict: url = "%s/alerts/active?zone=%s" % (API_ENDPOINT, zone_id) _LOGGER.debug("getting alert for %s from %s" % (zone_id, url)) elif gps_loc != "": - url = '%s/alerts/active?point=%s' % (API_ENDPOINT, gps_loc) + url = "%s/alerts/active?point=%s" % (API_ENDPOINT, gps_loc) _LOGGER.debug("getting alert for %s from %s" % (gps_loc, url)) async with aiohttp.ClientSession() as session: @@ -221,7 +232,7 @@ async def async_get_alerts(zone_id: str = "", gps_loc: str = "") -> dict: id = alert["id"] type = alert["properties"]["messageType"] - status = alert['properties']['status'] + status = alert["properties"]["status"] description = alert["properties"]["description"] instruction = alert["properties"]["instruction"] severity = alert["properties"]["severity"] @@ -239,34 +250,43 @@ async def async_get_alerts(zone_id: str = "", gps_loc: str = "") -> dict: display_desc += ( "\n>\nHeadline: %s\nStatus: %s\nMessage Type: %s\nSeverity: %s\nCertainty: %s\nExpires: %s\nDescription: %s\nInstruction: %s" - % (headline, status, type, severity, certainty, expires, description, instruction) + % ( + headline, + status, + type, + severity, + certainty, + expires, + description, + instruction, + ) ) if event_id != "": - event_id += ' - ' + event_id += " - " event_id += id - + if message_type != "": - message_type += ' - ' + message_type += " - " message_type += type - + if event_status != "": - event_status += ' - ' + event_status += " - " event_status += status - + if event_severity != "": - event_severity += ' - ' + event_severity += " - " event_severity += severity - + if event_expires != "": - event_expires += ' - ' + event_expires += " - " event_expires += expires - + if headlines: num_headlines = len(headlines) i = 0 diff --git a/custom_components/nws_alerts/config_flow.py b/custom_components/nws_alerts/config_flow.py index ffb2e18..a5ce293 100644 --- a/custom_components/nws_alerts/config_flow.py +++ b/custom_components/nws_alerts/config_flow.py @@ -11,9 +11,18 @@ from homeassistant.core import callback from homeassistant.data_entry_flow import FlowResult -from .const import (API_ENDPOINT, CONF_GPS_LOC, CONF_INTERVAL, CONF_TIMEOUT, - CONF_ZONE_ID, DEFAULT_INTERVAL, DEFAULT_NAME, - DEFAULT_TIMEOUT, DOMAIN, USER_AGENT) +from .const import ( + API_ENDPOINT, + CONF_GPS_LOC, + CONF_INTERVAL, + CONF_TIMEOUT, + CONF_ZONE_ID, + DEFAULT_INTERVAL, + DEFAULT_NAME, + DEFAULT_TIMEOUT, + DOMAIN, + USER_AGENT, +) JSON_FEATURES = "features" JSON_PROPERTIES = "properties" @@ -41,6 +50,7 @@ def _get_default(key): } ) + def _get_schema_gps(hass: Any, user_input: list, default_dict: list) -> Any: """Gets a schema using the default_dict as a backup.""" if user_input is None: @@ -59,6 +69,7 @@ def _get_default(key): } ) + async def _get_zone_list(self) -> list | None: """Return list of zone by lat/lon""" @@ -84,7 +95,7 @@ async def _get_zone_list(self) -> list | None: zone_list.append(data[JSON_FEATURES][x][JSON_PROPERTIES][JSON_ID]) x += 1 _LOGGER.debug("Zones list: %s", zone_list) - zone_list = ",".join(str(x) for x in zone_list) # convert list to str + zone_list = ",".join(str(x) for x in zone_list) # convert list to str return zone_list return None @@ -115,7 +126,7 @@ async def async_step_user( ) -> FlowResult: """Handle the flow initialized by the user.""" return self.async_show_menu(step_id="user", menu_options=MENU_OPTIONS) - + async def async_step_gps_loc(self, user_input={}): """Handle a flow initialized by the user.""" lat = self.hass.config.latitude @@ -126,7 +137,7 @@ async def async_step_gps_loc(self, user_input={}): if user_input is not None: self._data.update(user_input) return self.async_create_entry(title=self._data[CONF_NAME], data=self._data) - return await self._show_config_gps_loc(user_input) + return await self._show_config_gps_loc(user_input) async def _show_config_gps_loc(self, user_input): """Show the configuration form to edit location data.""" @@ -143,7 +154,7 @@ async def _show_config_gps_loc(self, user_input): step_id="gps_loc", data_schema=_get_schema_gps(self.hass, user_input, defaults), errors=self._errors, - ) + ) async def async_step_zone(self, user_input={}): """Handle a flow initialized by the user.""" @@ -194,6 +205,24 @@ async def async_step_init(self, user_input=None): return self.async_create_entry(title="", data=self._data) return await self._show_options_form(user_input) + async def async_step_gps_loc(self, user_input={}): + """Handle a flow initialized by the user.""" + self._errors = {} + + if user_input is not None: + self._data.update(user_input) + return self.async_create_entry(title=self._data[CONF_NAME], data=self._data) + return await self._show_options_form(user_input) + + async def async_step_zone(self, user_input={}): + """Handle a flow initialized by the user.""" + self._errors = {} + + if user_input is not None: + self._data.update(user_input) + return self.async_create_entry(title=self._data[CONF_NAME], data=self._data) + return await self._show_options_form(user_input) + async def _show_options_form(self, user_input): """Show the configuration form to edit location data.""" diff --git a/custom_components/nws_alerts/sensor.py b/custom_components/nws_alerts/sensor.py index c190088..1461157 100644 --- a/custom_components/nws_alerts/sensor.py +++ b/custom_components/nws_alerts/sensor.py @@ -13,9 +13,19 @@ from homeassistant.util import slugify from . import AlertsDataUpdateCoordinator -from .const import (ATTRIBUTION, CONF_GPS_LOC, CONF_INTERVAL, CONF_TIMEOUT, - CONF_ZONE_ID, COORDINATOR, DEFAULT_ICON, DEFAULT_INTERVAL, - DEFAULT_NAME, DEFAULT_TIMEOUT, DOMAIN) +from .const import ( + ATTRIBUTION, + CONF_GPS_LOC, + CONF_INTERVAL, + CONF_TIMEOUT, + CONF_ZONE_ID, + COORDINATOR, + DEFAULT_ICON, + DEFAULT_INTERVAL, + DEFAULT_NAME, + DEFAULT_TIMEOUT, + DOMAIN, +) # --------------------------------------------------------- # API Documentation @@ -54,7 +64,7 @@ async def async_setup_platform(hass, config, async_add_entities, discovery_info= elif CONF_GPS_LOC in config: config.entry_id = slugify(f"{config.get(CONF_GPS_LOC)}") elif CONF_GPS_LOC and CONF_ZONE_ID not in config: - raise ValueError("GPS or Zone needs to be configured.") + raise ValueError("GPS or Zone needs to be configured.") config.data = config # Setup the data coordinator @@ -149,4 +159,4 @@ def device_info(self) -> DeviceInfo: identifiers={(DOMAIN, self._config.entry_id)}, manufacturer="NWS", name="NWS Alerts", - ) \ No newline at end of file + )