Skip to content

Commit

Permalink
add steps to options flow
Browse files Browse the repository at this point in the history
  • Loading branch information
firstof9 committed Mar 18, 2023
1 parent 882ebc6 commit fc41dc5
Show file tree
Hide file tree
Showing 4 changed files with 94 additions and 36 deletions.
1 change: 0 additions & 1 deletion custom_components/__init__.py
Original file line number Diff line number Diff line change
@@ -1,2 +1 @@
"""For testing"""

66 changes: 43 additions & 23 deletions custom_components/nws_alerts/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

""" NWS Alerts """
import logging
from datetime import timedelta
Expand All @@ -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__)

Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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"]
Expand All @@ -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
Expand Down
43 changes: 36 additions & 7 deletions custom_components/nws_alerts/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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:
Expand All @@ -59,6 +69,7 @@ def _get_default(key):
}
)


async def _get_zone_list(self) -> list | None:
"""Return list of zone by lat/lon"""

Expand All @@ -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

Expand Down Expand Up @@ -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
Expand All @@ -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."""
Expand All @@ -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."""
Expand Down Expand Up @@ -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."""

Expand Down
20 changes: 15 additions & 5 deletions custom_components/nws_alerts/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -149,4 +159,4 @@ def device_info(self) -> DeviceInfo:
identifiers={(DOMAIN, self._config.entry_id)},
manufacturer="NWS",
name="NWS Alerts",
)
)

0 comments on commit fc41dc5

Please sign in to comment.