GeoNet NZ Volcanic Alert Level sensor (#26901)
* first version of new integration * moved icon to shared consts * added unit tests * transformed from geolocation to sensor integration * alert level is now the state of the sensor * adopted unit tests * fixed comment * keep all sensors registered even if the feed update fails intermittently * bumped version of upstream library * bumped version of integration library * regenerated requirements * bumped version of integration library * bumped version of integration library * fixed generated file * removed commented out code * regenerated config flow file * update to latest integration library version * simplified code * removed debug log statement * simplified code structure * defined constant * use core interfaces * moved test and fixture * sorted imports * simplified patching * moved fixture to central config file
This commit is contained in:
1 parent
8439e597ce
commit
4e9e9efa43
16 files changed
+844
No files matched your search
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"config": {
|
||||
"error": {
|
||||
"identifier_exists": "Location already registered"
|
||||
},
|
||||
"step": {
|
||||
"user": {
|
||||
"data": {
|
||||
"radius": "Radius"
|
||||
},
|
||||
"title": "Fill in your filter details."
|
||||
}
|
||||
},
|
||||
"title": "GeoNet NZ Volcano"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
"""The GeoNet NZ Volcano integration."""
|
||||
import asyncio
|
||||
import logging
|
||||
from datetime import timedelta, datetime
|
||||
from typing import Optional
|
||||
|
||||
import voluptuous as vol
|
||||
from aio_geojson_geonetnz_volcano import GeonetnzVolcanoFeedManager
|
||||
|
||||
from homeassistant.core import callback
|
||||
from homeassistant.util.unit_system import METRIC_SYSTEM
|
||||
from homeassistant.config_entries import SOURCE_IMPORT
|
||||
from homeassistant.const import (
|
||||
CONF_LATITUDE,
|
||||
CONF_LONGITUDE,
|
||||
CONF_RADIUS,
|
||||
CONF_SCAN_INTERVAL,
|
||||
CONF_UNIT_SYSTEM_IMPERIAL,
|
||||
CONF_UNIT_SYSTEM,
|
||||
LENGTH_MILES,
|
||||
)
|
||||
from homeassistant.helpers import config_validation as cv, aiohttp_client
|
||||
from homeassistant.helpers.dispatcher import async_dispatcher_send
|
||||
from homeassistant.helpers.event import async_track_time_interval
|
||||
|
||||
from .config_flow import configured_instances
|
||||
from .const import (
|
||||
DEFAULT_RADIUS,
|
||||
DEFAULT_SCAN_INTERVAL,
|
||||
DOMAIN,
|
||||
FEED,
|
||||
SIGNAL_NEW_SENSOR,
|
||||
SIGNAL_UPDATE_ENTITY,
|
||||
)
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
CONFIG_SCHEMA = vol.Schema(
|
||||
{
|
||||
DOMAIN: vol.Schema(
|
||||
{
|
||||
vol.Optional(CONF_LATITUDE): cv.latitude,
|
||||
vol.Optional(CONF_LONGITUDE): cv.longitude,
|
||||
vol.Optional(CONF_RADIUS, default=DEFAULT_RADIUS): vol.Coerce(float),
|
||||
vol.Optional(
|
||||
CONF_SCAN_INTERVAL, default=DEFAULT_SCAN_INTERVAL
|
||||
): cv.time_period,
|
||||
}
|
||||
)
|
||||
},
|
||||
extra=vol.ALLOW_EXTRA,
|
||||
)
|
||||
|
||||
|
||||
async def async_setup(hass, config):
|
||||
"""Set up the GeoNet NZ Volcano component."""
|
||||
if DOMAIN not in config:
|
||||
return True
|
||||
|
||||
conf = config[DOMAIN]
|
||||
|
||||
latitude = conf.get(CONF_LATITUDE, hass.config.latitude)
|
||||
longitude = conf.get(CONF_LONGITUDE, hass.config.longitude)
|
||||
scan_interval = conf[CONF_SCAN_INTERVAL]
|
||||
|
||||
identifier = f"{latitude}, {longitude}"
|
||||
if identifier in configured_instances(hass):
|
||||
return True
|
||||
|
||||
hass.async_create_task(
|
||||
hass.config_entries.flow.async_init(
|
||||
DOMAIN,
|
||||
context={"source": SOURCE_IMPORT},
|
||||
data={
|
||||
CONF_LATITUDE: latitude,
|
||||
CONF_LONGITUDE: longitude,
|
||||
CONF_RADIUS: conf[CONF_RADIUS],
|
||||
CONF_SCAN_INTERVAL: scan_interval,
|
||||
},
|
||||
)
|
||||
)
|
||||
|
||||
return True
|
||||
|
||||
|
||||
async def async_setup_entry(hass, config_entry):
|
||||
"""Set up the GeoNet NZ Volcano component as config entry."""
|
||||
hass.data.setdefault(DOMAIN, {})
|
||||
hass.data[DOMAIN].setdefault(FEED, {})
|
||||
|
||||
radius = config_entry.data[CONF_RADIUS]
|
||||
unit_system = config_entry.data[CONF_UNIT_SYSTEM]
|
||||
if unit_system == CONF_UNIT_SYSTEM_IMPERIAL:
|
||||
radius = METRIC_SYSTEM.length(radius, LENGTH_MILES)
|
||||
# Create feed entity manager for all platforms.
|
||||
manager = GeonetnzVolcanoFeedEntityManager(hass, config_entry, radius, unit_system)
|
||||
hass.data[DOMAIN][FEED][config_entry.entry_id] = manager
|
||||
_LOGGER.debug("Feed entity manager added for %s", config_entry.entry_id)
|
||||
await manager.async_init()
|
||||
return True
|
||||
|
||||
|
||||
async def async_unload_entry(hass, config_entry):
|
||||
"""Unload an GeoNet NZ Volcano component config entry."""
|
||||
manager = hass.data[DOMAIN][FEED].pop(config_entry.entry_id)
|
||||
await manager.async_stop()
|
||||
await asyncio.wait(
|
||||
[hass.config_entries.async_forward_entry_unload(config_entry, "sensor")]
|
||||
)
|
||||
return True
|
||||
|
||||
|
||||
class GeonetnzVolcanoFeedEntityManager:
|
||||
"""Feed Entity Manager for GeoNet NZ Volcano feed."""
|
||||
|
||||
def __init__(self, hass, config_entry, radius_in_km, unit_system):
|
||||
"""Initialize the Feed Entity Manager."""
|
||||
self._hass = hass
|
||||
self._config_entry = config_entry
|
||||
coordinates = (
|
||||
config_entry.data[CONF_LATITUDE],
|
||||
config_entry.data[CONF_LONGITUDE],
|
||||
)
|
||||
websession = aiohttp_client.async_get_clientsession(hass)
|
||||
self._feed_manager = GeonetnzVolcanoFeedManager(
|
||||
websession,
|
||||
self._generate_entity,
|
||||
self._update_entity,
|
||||
self._remove_entity,
|
||||
coordinates,
|
||||
filter_radius=radius_in_km,
|
||||
)
|
||||
self._config_entry_id = config_entry.entry_id
|
||||
self._scan_interval = timedelta(seconds=config_entry.data[CONF_SCAN_INTERVAL])
|
||||
self._unit_system = unit_system
|
||||
self._track_time_remove_callback = None
|
||||
self.listeners = []
|
||||
|
||||
async def async_init(self):
|
||||
"""Schedule initial and regular updates based on configured time interval."""
|
||||
|
||||
self._hass.async_create_task(
|
||||
self._hass.config_entries.async_forward_entry_setup(
|
||||
self._config_entry, "sensor"
|
||||
)
|
||||
)
|
||||
|
||||
async def update(event_time):
|
||||
"""Update."""
|
||||
await self.async_update()
|
||||
|
||||
# Trigger updates at regular intervals.
|
||||
self._track_time_remove_callback = async_track_time_interval(
|
||||
self._hass, update, self._scan_interval
|
||||
)
|
||||
|
||||
_LOGGER.debug("Feed entity manager initialized")
|
||||
|
||||
async def async_update(self):
|
||||
"""Refresh data."""
|
||||
await self._feed_manager.update()
|
||||
_LOGGER.debug("Feed entity manager updated")
|
||||
|
||||
async def async_stop(self):
|
||||
"""Stop this feed entity manager from refreshing."""
|
||||
for unsub_dispatcher in self.listeners:
|
||||
unsub_dispatcher()
|
||||
self.listeners = []
|
||||
if self._track_time_remove_callback:
|
||||
self._track_time_remove_callback()
|
||||
_LOGGER.debug("Feed entity manager stopped")
|
||||
|
||||
@callback
|
||||
def async_event_new_entity(self):
|
||||
"""Return manager specific event to signal new entity."""
|
||||
return SIGNAL_NEW_SENSOR.format(self._config_entry_id)
|
||||
|
||||
def get_entry(self, external_id):
|
||||
"""Get feed entry by external id."""
|
||||
return self._feed_manager.feed_entries.get(external_id)
|
||||
|
||||
def last_update(self) -> Optional[datetime]:
|
||||
"""Return the last update of this feed."""
|
||||
return self._feed_manager.last_update
|
||||
|
||||
def last_update_successful(self) -> Optional[datetime]:
|
||||
"""Return the last successful update of this feed."""
|
||||
return self._feed_manager.last_update_successful
|
||||
|
||||
async def _generate_entity(self, external_id):
|
||||
"""Generate new entity."""
|
||||
async_dispatcher_send(
|
||||
self._hass,
|
||||
self.async_event_new_entity(),
|
||||
self,
|
||||
external_id,
|
||||
self._unit_system,
|
||||
)
|
||||
|
||||
async def _update_entity(self, external_id):
|
||||
"""Update entity."""
|
||||
async_dispatcher_send(self._hass, SIGNAL_UPDATE_ENTITY.format(external_id))
|
||||
|
||||
async def _remove_entity(self, external_id):
|
||||
"""Ignore removing entity."""
|
||||
@@ -0,0 +1,74 @@
|
||||
"""Config flow to configure the GeoNet NZ Volcano integration."""
|
||||
import logging
|
||||
|
||||
import voluptuous as vol
|
||||
|
||||
from homeassistant import config_entries
|
||||
from homeassistant.const import (
|
||||
CONF_LATITUDE,
|
||||
CONF_LONGITUDE,
|
||||
CONF_RADIUS,
|
||||
CONF_SCAN_INTERVAL,
|
||||
CONF_UNIT_SYSTEM,
|
||||
CONF_UNIT_SYSTEM_IMPERIAL,
|
||||
CONF_UNIT_SYSTEM_METRIC,
|
||||
)
|
||||
from homeassistant.core import callback
|
||||
from homeassistant.helpers import config_validation as cv
|
||||
|
||||
from .const import DEFAULT_RADIUS, DEFAULT_SCAN_INTERVAL, DOMAIN
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@callback
|
||||
def configured_instances(hass):
|
||||
"""Return a set of configured GeoNet NZ Volcano instances."""
|
||||
return set(
|
||||
f"{entry.data[CONF_LATITUDE]}, {entry.data[CONF_LONGITUDE]}"
|
||||
for entry in hass.config_entries.async_entries(DOMAIN)
|
||||
)
|
||||
|
||||
|
||||
class GeonetnzVolcanoFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
|
||||
"""Handle a GeoNet NZ Volcano config flow."""
|
||||
|
||||
CONNECTION_CLASS = config_entries.CONN_CLASS_CLOUD_POLL
|
||||
|
||||
async def _show_form(self, errors=None):
|
||||
"""Show the form to the user."""
|
||||
data_schema = vol.Schema(
|
||||
{vol.Optional(CONF_RADIUS, default=DEFAULT_RADIUS): cv.positive_int}
|
||||
)
|
||||
|
||||
return self.async_show_form(
|
||||
step_id="user", data_schema=data_schema, errors=errors or {}
|
||||
)
|
||||
|
||||
async def async_step_import(self, import_config):
|
||||
"""Import a config entry from configuration.yaml."""
|
||||
return await self.async_step_user(import_config)
|
||||
|
||||
async def async_step_user(self, user_input=None):
|
||||
"""Handle the start of the config flow."""
|
||||
if not user_input:
|
||||
return await self._show_form()
|
||||
|
||||
latitude = user_input.get(CONF_LATITUDE, self.hass.config.latitude)
|
||||
user_input[CONF_LATITUDE] = latitude
|
||||
longitude = user_input.get(CONF_LONGITUDE, self.hass.config.longitude)
|
||||
user_input[CONF_LONGITUDE] = longitude
|
||||
|
||||
identifier = f"{user_input[CONF_LATITUDE]}, {user_input[CONF_LONGITUDE]}"
|
||||
if identifier in configured_instances(self.hass):
|
||||
return await self._show_form({"base": "identifier_exists"})
|
||||
|
||||
if self.hass.config.units.name == CONF_UNIT_SYSTEM_IMPERIAL:
|
||||
user_input[CONF_UNIT_SYSTEM] = CONF_UNIT_SYSTEM_IMPERIAL
|
||||
else:
|
||||
user_input[CONF_UNIT_SYSTEM] = CONF_UNIT_SYSTEM_METRIC
|
||||
|
||||
scan_interval = user_input.get(CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL)
|
||||
user_input[CONF_SCAN_INTERVAL] = scan_interval.seconds
|
||||
|
||||
return self.async_create_entry(title=identifier, data=user_input)
|
||||
@@ -0,0 +1,19 @@
|
||||
"""Define constants for the GeoNet NZ Volcano integration."""
|
||||
from datetime import timedelta
|
||||
|
||||
DOMAIN = "geonetnz_volcano"
|
||||
|
||||
FEED = "feed"
|
||||
|
||||
ATTR_ACTIVITY = "activity"
|
||||
ATTR_DISTANCE = "distance"
|
||||
ATTR_EXTERNAL_ID = "external_id"
|
||||
ATTR_HAZARDS = "hazards"
|
||||
|
||||
# Icon alias "mdi:mountain" not working.
|
||||
DEFAULT_ICON = "mdi:image-filter-hdr"
|
||||
DEFAULT_RADIUS = 50.0
|
||||
DEFAULT_SCAN_INTERVAL = timedelta(minutes=5)
|
||||
|
||||
SIGNAL_NEW_SENSOR = "geonetnz_volcano_new_sensor_{}"
|
||||
SIGNAL_UPDATE_ENTITY = "geonetnz_volcano_update_{}"
|
||||
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"domain": "geonetnz_volcano",
|
||||
"name": "GeoNet NZ Volcano",
|
||||
"config_flow": true,
|
||||
"documentation": "https://www.home-assistant.io/components/geonetnz_volcano",
|
||||
"requirements": [
|
||||
"aio_geojson_geonetnz_volcano==0.5"
|
||||
],
|
||||
"dependencies": [],
|
||||
"codeowners": [
|
||||
"@exxamalte"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
"""Feed Entity Manager Sensor support for GeoNet NZ Volcano Feeds."""
|
||||
import logging
|
||||
from typing import Optional
|
||||
|
||||
from homeassistant.const import (
|
||||
CONF_UNIT_SYSTEM_IMPERIAL,
|
||||
LENGTH_KILOMETERS,
|
||||
ATTR_ATTRIBUTION,
|
||||
ATTR_LONGITUDE,
|
||||
ATTR_LATITUDE,
|
||||
)
|
||||
from homeassistant.core import callback
|
||||
from homeassistant.helpers.dispatcher import async_dispatcher_connect
|
||||
from homeassistant.helpers.entity import Entity
|
||||
from homeassistant.util import dt
|
||||
from homeassistant.util.unit_system import IMPERIAL_SYSTEM
|
||||
|
||||
from .const import (
|
||||
ATTR_ACTIVITY,
|
||||
ATTR_DISTANCE,
|
||||
ATTR_EXTERNAL_ID,
|
||||
ATTR_HAZARDS,
|
||||
DEFAULT_ICON,
|
||||
DOMAIN,
|
||||
FEED,
|
||||
SIGNAL_UPDATE_ENTITY,
|
||||
)
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
ATTR_LAST_UPDATE = "feed_last_update"
|
||||
ATTR_LAST_UPDATE_SUCCESSFUL = "feed_last_update_successful"
|
||||
|
||||
|
||||
async def async_setup_entry(hass, entry, async_add_entities):
|
||||
"""Set up the GeoNet NZ Volcano Feed platform."""
|
||||
manager = hass.data[DOMAIN][FEED][entry.entry_id]
|
||||
|
||||
@callback
|
||||
def async_add_sensor(feed_manager, external_id, unit_system):
|
||||
"""Add sensor entity from feed."""
|
||||
new_entity = GeonetnzVolcanoSensor(
|
||||
entry.entry_id, feed_manager, external_id, unit_system
|
||||
)
|
||||
_LOGGER.debug("Adding sensor %s", new_entity)
|
||||
async_add_entities([new_entity], True)
|
||||
|
||||
manager.listeners.append(
|
||||
async_dispatcher_connect(
|
||||
hass, manager.async_event_new_entity(), async_add_sensor
|
||||
)
|
||||
)
|
||||
hass.async_create_task(manager.async_update())
|
||||
_LOGGER.debug("Sensor setup done")
|
||||
|
||||
|
||||
class GeonetnzVolcanoSensor(Entity):
|
||||
"""This represents an external event with GeoNet NZ Volcano feed data."""
|
||||
|
||||
def __init__(self, config_entry_id, feed_manager, external_id, unit_system):
|
||||
"""Initialize entity with data from feed entry."""
|
||||
self._config_entry_id = config_entry_id
|
||||
self._feed_manager = feed_manager
|
||||
self._external_id = external_id
|
||||
self._unit_system = unit_system
|
||||
self._title = None
|
||||
self._distance = None
|
||||
self._latitude = None
|
||||
self._longitude = None
|
||||
self._attribution = None
|
||||
self._alert_level = None
|
||||
self._activity = None
|
||||
self._hazards = None
|
||||
self._feed_last_update = None
|
||||
self._feed_last_update_successful = None
|
||||
self._remove_signal_update = None
|
||||
|
||||
async def async_added_to_hass(self):
|
||||
"""Call when entity is added to hass."""
|
||||
self._remove_signal_update = async_dispatcher_connect(
|
||||
self.hass,
|
||||
SIGNAL_UPDATE_ENTITY.format(self._external_id),
|
||||
self._update_callback,
|
||||
)
|
||||
|
||||
async def async_will_remove_from_hass(self) -> None:
|
||||
"""Call when entity will be removed from hass."""
|
||||
if self._remove_signal_update:
|
||||
self._remove_signal_update()
|
||||
|
||||
@callback
|
||||
def _update_callback(self):
|
||||
"""Call update method."""
|
||||
self.async_schedule_update_ha_state(True)
|
||||
|
||||
@property
|
||||
def should_poll(self):
|
||||
"""No polling needed for GeoNet NZ Volcano feed location events."""
|
||||
return False
|
||||
|
||||
async def async_update(self):
|
||||
"""Update this entity from the data held in the feed manager."""
|
||||
_LOGGER.debug("Updating %s", self._external_id)
|
||||
feed_entry = self._feed_manager.get_entry(self._external_id)
|
||||
last_update = self._feed_manager.last_update()
|
||||
last_update_successful = self._feed_manager.last_update_successful()
|
||||
if feed_entry:
|
||||
self._update_from_feed(feed_entry, last_update, last_update_successful)
|
||||
|
||||
def _update_from_feed(self, feed_entry, last_update, last_update_successful):
|
||||
"""Update the internal state from the provided feed entry."""
|
||||
self._title = feed_entry.title
|
||||
# Convert distance if not metric system.
|
||||
if self._unit_system == CONF_UNIT_SYSTEM_IMPERIAL:
|
||||
self._distance = round(
|
||||
IMPERIAL_SYSTEM.length(feed_entry.distance_to_home, LENGTH_KILOMETERS),
|
||||
1,
|
||||
)
|
||||
else:
|
||||
self._distance = round(feed_entry.distance_to_home, 1)
|
||||
self._latitude = round(feed_entry.coordinates[0], 5)
|
||||
self._longitude = round(feed_entry.coordinates[1], 5)
|
||||
self._attribution = feed_entry.attribution
|
||||
self._alert_level = feed_entry.alert_level
|
||||
self._activity = feed_entry.activity
|
||||
self._hazards = feed_entry.hazards
|
||||
self._feed_last_update = dt.as_utc(last_update) if last_update else None
|
||||
self._feed_last_update_successful = (
|
||||
dt.as_utc(last_update_successful) if last_update_successful else None
|
||||
)
|
||||
|
||||
@property
|
||||
def state(self):
|
||||
"""Return the state of the sensor."""
|
||||
return self._alert_level
|
||||
|
||||
@property
|
||||
def icon(self):
|
||||
"""Return the icon to use in the frontend, if any."""
|
||||
return DEFAULT_ICON
|
||||
|
||||
@property
|
||||
def name(self) -> Optional[str]:
|
||||
"""Return the name of the entity."""
|
||||
return f"Volcano {self._title}"
|
||||
|
||||
@property
|
||||
def unit_of_measurement(self):
|
||||
"""Return the unit of measurement."""
|
||||
return "alert level"
|
||||
|
||||
@property
|
||||
def device_state_attributes(self):
|
||||
"""Return the device state attributes."""
|
||||
attributes = {}
|
||||
for key, value in (
|
||||
(ATTR_EXTERNAL_ID, self._external_id),
|
||||
(ATTR_ATTRIBUTION, self._attribution),
|
||||
(ATTR_ACTIVITY, self._activity),
|
||||
(ATTR_HAZARDS, self._hazards),
|
||||
(ATTR_LONGITUDE, self._longitude),
|
||||
(ATTR_LATITUDE, self._latitude),
|
||||
(ATTR_DISTANCE, self._distance),
|
||||
(ATTR_LAST_UPDATE, self._feed_last_update),
|
||||
(ATTR_LAST_UPDATE_SUCCESSFUL, self._feed_last_update_successful),
|
||||
):
|
||||
if value or isinstance(value, bool):
|
||||
attributes[key] = value
|
||||
return attributes
|
||||
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"config": {
|
||||
"title": "GeoNet NZ Volcano",
|
||||
"step": {
|
||||
"user": {
|
||||
"title": "Fill in your filter details.",
|
||||
"data": {
|
||||
"radius": "Radius"
|
||||
}
|
||||
}
|
||||
},
|
||||
"error": {
|
||||
"identifier_exists": "Location already registered"
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user