GeoNet NZ Quakes Sensor (#26078)
* working version of status sensor * changed unit of measurement * align naming with feed source * simplified sensor name * fix potential issue during initialisation * fixed tests * changed icon to constant * added tests for new sensor * split tests for geolocation vs sensor * fixed lint * fixed pylint * fixed test * removed config entry id from attributes * moved entity manager to component * fix issue with multiple config entries overriding each other's data * creating async tasks instead of awaiting each unloading * moved manager to component * correctly triggering update only when this component is loaded * fixed tests after major code refactorings * fixed pylint * moved actual creation of new events to geolocation platform * changed all timestamps to utc * changed the way platforms are setup and manager is updated * simplify assert statement * changed the way waiting for unloading platforms
This commit is contained in:
1 parent
fa79ef1220
commit
13bb2ea35a
7 files changed
+474
-169
No files matched your search
@@ -1,27 +1,47 @@
|
||||
"""The GeoNet NZ Quakes integration."""
|
||||
import voluptuous as vol
|
||||
import asyncio
|
||||
import logging
|
||||
from datetime import timedelta
|
||||
|
||||
import voluptuous as vol
|
||||
from aio_geojson_geonetnz_quakes import GeonetnzQuakesFeedManager
|
||||
|
||||
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
|
||||
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 (
|
||||
PLATFORMS,
|
||||
CONF_MINIMUM_MAGNITUDE,
|
||||
CONF_MMI,
|
||||
DEFAULT_FILTER_TIME_INTERVAL,
|
||||
DEFAULT_MINIMUM_MAGNITUDE,
|
||||
DEFAULT_MMI,
|
||||
DEFAULT_RADIUS,
|
||||
DEFAULT_SCAN_INTERVAL,
|
||||
DOMAIN,
|
||||
FEED,
|
||||
SIGNAL_DELETE_ENTITY,
|
||||
SIGNAL_NEW_GEOLOCATION,
|
||||
SIGNAL_STATUS,
|
||||
SIGNAL_UPDATE_ENTITY,
|
||||
)
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
CONFIG_SCHEMA = vol.Schema(
|
||||
{
|
||||
DOMAIN: vol.Schema(
|
||||
@@ -81,13 +101,20 @@ async def async_setup(hass, config):
|
||||
|
||||
async def async_setup_entry(hass, config_entry):
|
||||
"""Set up the GeoNet NZ Quakes component as config entry."""
|
||||
hass.data[DOMAIN] = {}
|
||||
hass.data[DOMAIN][FEED] = {}
|
||||
|
||||
hass.async_create_task(
|
||||
hass.config_entries.async_forward_entry_setup(config_entry, "geo_location")
|
||||
)
|
||||
if DOMAIN not in hass.data:
|
||||
hass.data[DOMAIN] = {}
|
||||
if FEED not in hass.data[DOMAIN]:
|
||||
hass.data[DOMAIN][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 = GeonetnzQuakesFeedEntityManager(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
|
||||
|
||||
|
||||
@@ -95,7 +122,114 @@ async def async_unload_entry(hass, config_entry):
|
||||
"""Unload an GeoNet NZ Quakes component config entry."""
|
||||
manager = hass.data[DOMAIN][FEED].pop(config_entry.entry_id)
|
||||
await manager.async_stop()
|
||||
|
||||
await hass.config_entries.async_forward_entry_unload(config_entry, "geo_location")
|
||||
|
||||
await asyncio.wait(
|
||||
[
|
||||
hass.config_entries.async_forward_entry_unload(config_entry, domain)
|
||||
for domain in PLATFORMS
|
||||
]
|
||||
)
|
||||
return True
|
||||
|
||||
|
||||
class GeonetnzQuakesFeedEntityManager:
|
||||
"""Feed Entity Manager for GeoNet NZ Quakes 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 = GeonetnzQuakesFeedManager(
|
||||
websession,
|
||||
self._generate_entity,
|
||||
self._update_entity,
|
||||
self._remove_entity,
|
||||
coordinates,
|
||||
mmi=config_entry.data[CONF_MMI],
|
||||
filter_radius=radius_in_km,
|
||||
filter_minimum_magnitude=config_entry.data[CONF_MINIMUM_MAGNITUDE],
|
||||
filter_time=DEFAULT_FILTER_TIME_INTERVAL,
|
||||
status_callback=self._status_update,
|
||||
)
|
||||
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._status_info = None
|
||||
self.listeners = []
|
||||
|
||||
async def async_init(self):
|
||||
"""Schedule initial and regular updates based on configured time interval."""
|
||||
|
||||
for domain in PLATFORMS:
|
||||
self._hass.async_create_task(
|
||||
self._hass.config_entries.async_forward_entry_setup(
|
||||
self._config_entry, domain
|
||||
)
|
||||
)
|
||||
|
||||
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_GEOLOCATION.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 status_info(self):
|
||||
"""Return latest status update info received."""
|
||||
return self._status_info
|
||||
|
||||
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):
|
||||
"""Remove entity."""
|
||||
async_dispatcher_send(self._hass, SIGNAL_DELETE_ENTITY.format(external_id))
|
||||
|
||||
async def _status_update(self, status_info):
|
||||
"""Propagate status update."""
|
||||
_LOGGER.debug("Status update received: %s", status_info)
|
||||
self._status_info = status_info
|
||||
async_dispatcher_send(self._hass, SIGNAL_STATUS.format(self._config_entry_id))
|
||||
@@ -3,12 +3,21 @@ from datetime import timedelta
|
||||
|
||||
DOMAIN = "geonetnz_quakes"
|
||||
|
||||
PLATFORMS = ("sensor", "geo_location")
|
||||
|
||||
CONF_MINIMUM_MAGNITUDE = "minimum_magnitude"
|
||||
CONF_MMI = "mmi"
|
||||
|
||||
FEED = "feed"
|
||||
|
||||
DEFAULT_FILTER_TIME_INTERVAL = timedelta(days=7)
|
||||
DEFAULT_MINIMUM_MAGNITUDE = 0.0
|
||||
DEFAULT_MMI = 3
|
||||
DEFAULT_RADIUS = 50.0
|
||||
DEFAULT_SCAN_INTERVAL = timedelta(minutes=5)
|
||||
|
||||
SIGNAL_DELETE_ENTITY = "geonetnz_quakes_delete_{}"
|
||||
SIGNAL_UPDATE_ENTITY = "geonetnz_quakes_update_{}"
|
||||
SIGNAL_STATUS = "geonetnz_quakes_status_{}"
|
||||
|
||||
SIGNAL_NEW_GEOLOCATION = "geonetnz_quakes_new_geolocation_{}"
|
||||
@@ -1,33 +1,20 @@
|
||||
"""Geolocation support for GeoNet NZ Quakes Feeds."""
|
||||
from datetime import timedelta
|
||||
import logging
|
||||
from typing import Optional
|
||||
|
||||
from aio_geojson_geonetnz_quakes import GeonetnzQuakesFeedManager
|
||||
|
||||
from homeassistant.components.geo_location import GeolocationEvent
|
||||
from homeassistant.const import (
|
||||
ATTR_ATTRIBUTION,
|
||||
CONF_LATITUDE,
|
||||
CONF_LONGITUDE,
|
||||
CONF_RADIUS,
|
||||
CONF_SCAN_INTERVAL,
|
||||
CONF_UNIT_SYSTEM,
|
||||
CONF_UNIT_SYSTEM_IMPERIAL,
|
||||
LENGTH_KILOMETERS,
|
||||
LENGTH_MILES,
|
||||
ATTR_TIME,
|
||||
)
|
||||
from homeassistant.core import callback
|
||||
from homeassistant.helpers import aiohttp_client
|
||||
from homeassistant.helpers.dispatcher import (
|
||||
async_dispatcher_connect,
|
||||
async_dispatcher_send,
|
||||
)
|
||||
from homeassistant.helpers.event import async_track_time_interval
|
||||
from homeassistant.util.unit_system import IMPERIAL_SYSTEM, METRIC_SYSTEM
|
||||
from homeassistant.helpers.dispatcher import async_dispatcher_connect
|
||||
from homeassistant.util.unit_system import IMPERIAL_SYSTEM
|
||||
|
||||
from .const import CONF_MINIMUM_MAGNITUDE, CONF_MMI, DOMAIN, FEED
|
||||
from .const import DOMAIN, FEED, SIGNAL_DELETE_ENTITY, SIGNAL_UPDATE_ENTITY
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
@@ -39,111 +26,27 @@ ATTR_MMI = "mmi"
|
||||
ATTR_PUBLICATION_DATE = "publication_date"
|
||||
ATTR_QUALITY = "quality"
|
||||
|
||||
DEFAULT_FILTER_TIME_INTERVAL = timedelta(days=7)
|
||||
|
||||
SIGNAL_DELETE_ENTITY = "geonetnz_quakes_delete_{}"
|
||||
SIGNAL_UPDATE_ENTITY = "geonetnz_quakes_update_{}"
|
||||
|
||||
SOURCE = "geonetnz_quakes"
|
||||
|
||||
|
||||
async def async_setup_entry(hass, entry, async_add_entities):
|
||||
"""Set up the GeoNet NZ Quakes Feed platform."""
|
||||
radius = entry.data[CONF_RADIUS]
|
||||
unit_system = entry.data[CONF_UNIT_SYSTEM]
|
||||
if unit_system == CONF_UNIT_SYSTEM_IMPERIAL:
|
||||
radius = METRIC_SYSTEM.length(radius, LENGTH_MILES)
|
||||
manager = GeonetnzQuakesFeedEntityManager(
|
||||
hass,
|
||||
async_add_entities,
|
||||
entry.data[CONF_SCAN_INTERVAL],
|
||||
entry.data[CONF_LATITUDE],
|
||||
entry.data[CONF_LONGITUDE],
|
||||
entry.data[CONF_MMI],
|
||||
radius,
|
||||
unit_system,
|
||||
entry.data[CONF_MINIMUM_MAGNITUDE],
|
||||
manager = hass.data[DOMAIN][FEED][entry.entry_id]
|
||||
|
||||
@callback
|
||||
def async_add_geolocation(feed_manager, external_id, unit_system):
|
||||
"""Add gelocation entity from feed."""
|
||||
new_entity = GeonetnzQuakesEvent(feed_manager, external_id, unit_system)
|
||||
_LOGGER.debug("Adding geolocation %s", new_entity)
|
||||
async_add_entities([new_entity], True)
|
||||
|
||||
manager.listeners.append(
|
||||
async_dispatcher_connect(
|
||||
hass, manager.async_event_new_entity(), async_add_geolocation
|
||||
)
|
||||
)
|
||||
hass.data[DOMAIN][FEED][entry.entry_id] = manager
|
||||
await manager.async_init()
|
||||
|
||||
|
||||
class GeonetnzQuakesFeedEntityManager:
|
||||
"""Feed Entity Manager for GeoNet NZ Quakes feed."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
hass,
|
||||
async_add_entities,
|
||||
scan_interval,
|
||||
latitude,
|
||||
longitude,
|
||||
mmi,
|
||||
radius_in_km,
|
||||
unit_system,
|
||||
minimum_magnitude,
|
||||
):
|
||||
"""Initialize the Feed Entity Manager."""
|
||||
self._hass = hass
|
||||
coordinates = (latitude, longitude)
|
||||
websession = aiohttp_client.async_get_clientsession(hass)
|
||||
self._feed_manager = GeonetnzQuakesFeedManager(
|
||||
websession,
|
||||
self._generate_entity,
|
||||
self._update_entity,
|
||||
self._remove_entity,
|
||||
coordinates,
|
||||
mmi=mmi,
|
||||
filter_radius=radius_in_km,
|
||||
filter_minimum_magnitude=minimum_magnitude,
|
||||
filter_time=DEFAULT_FILTER_TIME_INTERVAL,
|
||||
)
|
||||
self._async_add_entities = async_add_entities
|
||||
self._scan_interval = timedelta(seconds=scan_interval)
|
||||
self._unit_system = unit_system
|
||||
self._track_time_remove_callback = None
|
||||
|
||||
async def async_init(self):
|
||||
"""Schedule regular updates based on configured time interval."""
|
||||
|
||||
async def update(event_time):
|
||||
"""Update."""
|
||||
await self.async_update()
|
||||
|
||||
await self.async_update()
|
||||
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."""
|
||||
if self._track_time_remove_callback:
|
||||
self._track_time_remove_callback()
|
||||
_LOGGER.debug("Feed entity manager stopped")
|
||||
|
||||
def get_entry(self, external_id):
|
||||
"""Get feed entry by external id."""
|
||||
return self._feed_manager.feed_entries.get(external_id)
|
||||
|
||||
async def _generate_entity(self, external_id):
|
||||
"""Generate new entity."""
|
||||
new_entity = GeonetnzQuakesEvent(self, external_id, self._unit_system)
|
||||
# Add new entities to HA.
|
||||
self._async_add_entities([new_entity], True)
|
||||
|
||||
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):
|
||||
"""Remove entity."""
|
||||
async_dispatcher_send(self._hass, SIGNAL_DELETE_ENTITY.format(external_id))
|
||||
hass.async_create_task(manager.async_update())
|
||||
_LOGGER.debug("Geolocation setup done")
|
||||
|
||||
|
||||
class GeonetnzQuakesEvent(GeolocationEvent):
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
"""Feed Entity Manager Sensor support for GeoNet NZ Quakes Feeds."""
|
||||
import logging
|
||||
from typing import Optional
|
||||
|
||||
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 .const import DOMAIN, FEED, SIGNAL_STATUS
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
ATTR_STATUS = "status"
|
||||
ATTR_LAST_UPDATE = "last_update"
|
||||
ATTR_LAST_UPDATE_SUCCESSFUL = "last_update_successful"
|
||||
ATTR_LAST_TIMESTAMP = "last_timestamp"
|
||||
ATTR_CREATED = "created"
|
||||
ATTR_UPDATED = "updated"
|
||||
ATTR_REMOVED = "removed"
|
||||
|
||||
DEFAULT_ICON = "mdi:pulse"
|
||||
DEFAULT_UNIT_OF_MEASUREMENT = "quakes"
|
||||
|
||||
|
||||
async def async_setup_entry(hass, entry, async_add_entities):
|
||||
"""Set up the GeoNet NZ Quakes Feed platform."""
|
||||
manager = hass.data[DOMAIN][FEED][entry.entry_id]
|
||||
sensor = GeonetnzQuakesSensor(entry.entry_id, entry.title, manager)
|
||||
async_add_entities([sensor])
|
||||
_LOGGER.debug("Sensor setup done")
|
||||
|
||||
|
||||
class GeonetnzQuakesSensor(Entity):
|
||||
"""This is a status sensor for the GeoNet NZ Quakes integration."""
|
||||
|
||||
def __init__(self, config_entry_id, config_title, manager):
|
||||
"""Initialize entity."""
|
||||
self._config_entry_id = config_entry_id
|
||||
self._config_title = config_title
|
||||
self._manager = manager
|
||||
self._status = None
|
||||
self._last_update = None
|
||||
self._last_update_successful = None
|
||||
self._last_timestamp = None
|
||||
self._total = None
|
||||
self._created = None
|
||||
self._updated = None
|
||||
self._removed = None
|
||||
self._remove_signal_status = None
|
||||
|
||||
async def async_added_to_hass(self):
|
||||
"""Call when entity is added to hass."""
|
||||
self._remove_signal_status = async_dispatcher_connect(
|
||||
self.hass,
|
||||
SIGNAL_STATUS.format(self._config_entry_id),
|
||||
self._update_status_callback,
|
||||
)
|
||||
_LOGGER.debug("Waiting for updates %s", self._config_entry_id)
|
||||
# First update is manual because of how the feed entity manager is updated.
|
||||
await self.async_update()
|
||||
|
||||
async def async_will_remove_from_hass(self) -> None:
|
||||
"""Call when entity will be removed from hass."""
|
||||
if self._remove_signal_status:
|
||||
self._remove_signal_status()
|
||||
|
||||
@callback
|
||||
def _update_status_callback(self):
|
||||
"""Call status update method."""
|
||||
_LOGGER.debug("Received status update for %s", self._config_entry_id)
|
||||
self.async_schedule_update_ha_state(True)
|
||||
|
||||
@property
|
||||
def should_poll(self):
|
||||
"""No polling needed for GeoNet NZ Quakes status sensor."""
|
||||
return False
|
||||
|
||||
async def async_update(self):
|
||||
"""Update this entity from the data held in the feed manager."""
|
||||
_LOGGER.debug("Updating %s", self._config_entry_id)
|
||||
if self._manager:
|
||||
status_info = self._manager.status_info()
|
||||
if status_info:
|
||||
self._update_from_status_info(status_info)
|
||||
|
||||
def _update_from_status_info(self, status_info):
|
||||
"""Update the internal state from the provided information."""
|
||||
self._status = status_info.status
|
||||
self._last_update = (
|
||||
dt.as_utc(status_info.last_update) if status_info.last_update else None
|
||||
)
|
||||
self._last_update_successful = (
|
||||
dt.as_utc(status_info.last_update_successful)
|
||||
if status_info.last_update_successful
|
||||
else None
|
||||
)
|
||||
self._last_timestamp = status_info.last_timestamp
|
||||
self._total = status_info.total
|
||||
self._created = status_info.created
|
||||
self._updated = status_info.updated
|
||||
self._removed = status_info.removed
|
||||
|
||||
@property
|
||||
def state(self):
|
||||
"""Return the state of the sensor."""
|
||||
return self._total
|
||||
|
||||
@property
|
||||
def name(self) -> Optional[str]:
|
||||
"""Return the name of the entity."""
|
||||
return f"GeoNet NZ Quakes ({self._config_title})"
|
||||
|
||||
@property
|
||||
def icon(self):
|
||||
"""Return the icon to use in the frontend, if any."""
|
||||
return DEFAULT_ICON
|
||||
|
||||
@property
|
||||
def unit_of_measurement(self):
|
||||
"""Return the unit of measurement."""
|
||||
return DEFAULT_UNIT_OF_MEASUREMENT
|
||||
|
||||
@property
|
||||
def device_state_attributes(self):
|
||||
"""Return the device state attributes."""
|
||||
attributes = {}
|
||||
for key, value in (
|
||||
(ATTR_STATUS, self._status),
|
||||
(ATTR_LAST_UPDATE, self._last_update),
|
||||
(ATTR_LAST_UPDATE_SUCCESSFUL, self._last_update_successful),
|
||||
(ATTR_LAST_TIMESTAMP, self._last_timestamp),
|
||||
(ATTR_CREATED, self._created),
|
||||
(ATTR_UPDATED, self._updated),
|
||||
(ATTR_REMOVED, self._removed),
|
||||
):
|
||||
if value or isinstance(value, bool):
|
||||
attributes[key] = value
|
||||
return attributes
|
||||
Reference in new issue
Block a user