Minor updates (#17437)

This commit is contained in:
Fabian Affolter 2018-10-14 17:10:46 +02:00 committed by Daniel Høyer Iversen
parent 5ac0469ef9
commit daf48a3b1f
4 changed files with 63 additions and 65 deletions

View File

@ -1,33 +1,34 @@
""" """
Geo Location component. Geo Location component.
This component covers platforms that deal with external events that contain
a geo location related to the installed HA instance.
For more details about this component, please refer to the documentation at For more details about this component, please refer to the documentation at
https://home-assistant.io/components/geo_location/ https://home-assistant.io/components/geo_location/
""" """
import logging
from datetime import timedelta from datetime import timedelta
import logging
from typing import Optional from typing import Optional
from homeassistant.const import ATTR_LATITUDE, ATTR_LONGITUDE from homeassistant.const import ATTR_LATITUDE, ATTR_LONGITUDE
from homeassistant.helpers.config_validation import PLATFORM_SCHEMA # noqa
from homeassistant.helpers.entity import Entity from homeassistant.helpers.entity import Entity
from homeassistant.helpers.entity_component import EntityComponent from homeassistant.helpers.entity_component import EntityComponent
from homeassistant.helpers.config_validation import PLATFORM_SCHEMA # noqa
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
ATTR_DISTANCE = 'distance' ATTR_DISTANCE = 'distance'
ATTR_SOURCE = 'source' ATTR_SOURCE = 'source'
DOMAIN = 'geo_location' DOMAIN = 'geo_location'
ENTITY_ID_FORMAT = DOMAIN + '.{}' ENTITY_ID_FORMAT = DOMAIN + '.{}'
GROUP_NAME_ALL_EVENTS = 'All Geo Location Events' GROUP_NAME_ALL_EVENTS = 'All Geo Location Events'
SCAN_INTERVAL = timedelta(seconds=60) SCAN_INTERVAL = timedelta(seconds=60)
async def async_setup(hass, config): async def async_setup(hass, config):
"""Set up this component.""" """Set up the Geo Location component."""
component = EntityComponent( component = EntityComponent(
_LOGGER, DOMAIN, hass, SCAN_INTERVAL, GROUP_NAME_ALL_EVENTS) _LOGGER, DOMAIN, hass, SCAN_INTERVAL, GROUP_NAME_ALL_EVENTS)
await component.async_setup(config) await component.async_setup(config)

View File

@ -4,10 +4,10 @@ Demo platform for the geo location component.
For more details about this platform, please refer to the documentation For more details about this platform, please refer to the documentation
https://home-assistant.io/components/demo/ https://home-assistant.io/components/demo/
""" """
import logging
import random
from datetime import timedelta from datetime import timedelta
from math import pi, cos, sin, radians import logging
from math import cos, pi, radians, sin
import random
from typing import Optional from typing import Optional
from homeassistant.components.geo_location import GeoLocationEvent from homeassistant.components.geo_location import GeoLocationEvent
@ -16,7 +16,7 @@ from homeassistant.helpers.event import track_time_interval
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
AVG_KM_PER_DEGREE = 111.0 AVG_KM_PER_DEGREE = 111.0
DEFAULT_UNIT_OF_MEASUREMENT = "km" DEFAULT_UNIT_OF_MEASUREMENT = 'km'
DEFAULT_UPDATE_INTERVAL = timedelta(minutes=1) DEFAULT_UPDATE_INTERVAL = timedelta(minutes=1)
MAX_RADIUS_IN_KM = 50 MAX_RADIUS_IN_KM = 50
NUMBER_OF_DEMO_DEVICES = 5 NUMBER_OF_DEMO_DEVICES = 5

View File

@ -1,24 +1,20 @@
""" """
Generic GeoJSON events platform. Generic GeoJSON events platform.
Retrieves current events (typically incidents or alerts) in GeoJSON format, and
displays information on events filtered by distance to the HA instance's
location.
For more details about this platform, please refer to the documentation at For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/geo_location/geo_json_events/ https://home-assistant.io/components/geo_location/geo_json_events/
""" """
import logging
from datetime import timedelta from datetime import timedelta
import logging
from typing import Optional from typing import Optional
import voluptuous as vol import voluptuous as vol
from homeassistant.components.geo_location import (
PLATFORM_SCHEMA, GeoLocationEvent)
from homeassistant.const import (
CONF_RADIUS, CONF_SCAN_INTERVAL, CONF_URL, EVENT_HOMEASSISTANT_START)
import homeassistant.helpers.config_validation as cv import homeassistant.helpers.config_validation as cv
from homeassistant.components.geo_location import GeoLocationEvent
from homeassistant.const import CONF_RADIUS, CONF_URL, CONF_SCAN_INTERVAL, \
EVENT_HOMEASSISTANT_START
from homeassistant.components.geo_location import PLATFORM_SCHEMA
from homeassistant.helpers.event import track_time_interval from homeassistant.helpers.event import track_time_interval
REQUIREMENTS = ['geojson_client==0.1'] REQUIREMENTS = ['geojson_client==0.1']
@ -28,15 +24,15 @@ _LOGGER = logging.getLogger(__name__)
ATTR_EXTERNAL_ID = 'external_id' ATTR_EXTERNAL_ID = 'external_id'
DEFAULT_RADIUS_IN_KM = 20.0 DEFAULT_RADIUS_IN_KM = 20.0
DEFAULT_UNIT_OF_MEASUREMENT = "km" DEFAULT_UNIT_OF_MEASUREMENT = 'km'
SCAN_INTERVAL = timedelta(minutes=5) SCAN_INTERVAL = timedelta(minutes=5)
SOURCE = 'geo_json_events' SOURCE = 'geo_json_events'
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_URL): cv.string, vol.Required(CONF_URL): cv.string,
vol.Optional(CONF_RADIUS, default=DEFAULT_RADIUS_IN_KM): vol.Optional(CONF_RADIUS, default=DEFAULT_RADIUS_IN_KM): vol.Coerce(float),
vol.Coerce(float),
}) })
@ -56,7 +52,8 @@ class GeoJsonFeedManager:
"""Initialize the GeoJSON Feed Manager.""" """Initialize the GeoJSON Feed Manager."""
from geojson_client.generic_feed import GenericFeed from geojson_client.generic_feed import GenericFeed
self._hass = hass self._hass = hass
self._feed = GenericFeed((hass.config.latitude, hass.config.longitude), self._feed = GenericFeed(
(hass.config.latitude, hass.config.longitude),
filter_radius=radius_in_km, url=url) filter_radius=radius_in_km, url=url)
self._add_entities = add_entities self._add_entities = add_entities
self._scan_interval = scan_interval self._scan_interval = scan_interval
@ -68,8 +65,8 @@ class GeoJsonFeedManager:
def _init_regular_updates(self): def _init_regular_updates(self):
"""Schedule regular updates at the specified interval.""" """Schedule regular updates at the specified interval."""
track_time_interval(self._hass, lambda now: self._update(), track_time_interval(
self._scan_interval) self._hass, lambda now: self._update(), self._scan_interval)
def _update(self): def _update(self):
"""Update the feed and then update connected entities.""" """Update the feed and then update connected entities."""
@ -82,11 +79,11 @@ class GeoJsonFeedManager:
keep_entries = self._update_or_remove_entities(feed_entries) keep_entries = self._update_or_remove_entities(feed_entries)
self._generate_new_entities(keep_entries) self._generate_new_entities(keep_entries)
elif status == geojson_client.UPDATE_OK_NO_DATA: elif status == geojson_client.UPDATE_OK_NO_DATA:
_LOGGER.debug("Update successful, but no data received from %s", _LOGGER.debug(
self._feed) "Update successful, but no data received from %s", self._feed)
else: else:
_LOGGER.warning("Update not successful, no data received from %s", _LOGGER.warning(
self._feed) "Update not successful, no data received from %s", self._feed)
# Remove all entities. # Remove all entities.
self._update_or_remove_entities([]) self._update_or_remove_entities([])

View File

@ -1,27 +1,24 @@
""" """
NSW Rural Fire Service Feed platform. NSW Rural Fire Service Feed platform.
Retrieves current events (bush fires, grass fires, etc.) in GeoJSON format,
and displays information on events filtered by distance and category to the
HA instance's location.
For more details about this platform, please refer to the documentation at For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/geo_location/nsw_rural_fire_service_feed/ https://home-assistant.io/components/geo_location/nsw_rural_fire_service_feed/
""" """
import logging
from datetime import timedelta from datetime import timedelta
import logging
from typing import Optional from typing import Optional
import voluptuous as vol import voluptuous as vol
import homeassistant.helpers.config_validation as cv from homeassistant.components.geo_location import (
from homeassistant.components.geo_location import GeoLocationEvent, \ PLATFORM_SCHEMA, GeoLocationEvent)
PLATFORM_SCHEMA from homeassistant.const import (
from homeassistant.const import CONF_RADIUS, CONF_SCAN_INTERVAL, \ ATTR_ATTRIBUTION, ATTR_LOCATION, CONF_RADIUS, CONF_SCAN_INTERVAL,
EVENT_HOMEASSISTANT_START, ATTR_ATTRIBUTION EVENT_HOMEASSISTANT_START)
from homeassistant.core import callback from homeassistant.core import callback
from homeassistant.helpers.dispatcher import dispatcher_send, \ import homeassistant.helpers.config_validation as cv
async_dispatcher_connect from homeassistant.helpers.dispatcher import (
async_dispatcher_connect, dispatcher_send)
from homeassistant.helpers.event import track_time_interval from homeassistant.helpers.event import track_time_interval
REQUIREMENTS = ['geojson_client==0.1'] REQUIREMENTS = ['geojson_client==0.1']
@ -32,7 +29,6 @@ ATTR_CATEGORY = 'category'
ATTR_COUNCIL_AREA = 'council_area' ATTR_COUNCIL_AREA = 'council_area'
ATTR_EXTERNAL_ID = 'external_id' ATTR_EXTERNAL_ID = 'external_id'
ATTR_FIRE = 'fire' ATTR_FIRE = 'fire'
ATTR_LOCATION = 'location'
ATTR_PUBLICATION_DATE = 'publication_date' ATTR_PUBLICATION_DATE = 'publication_date'
ATTR_RESPONSIBLE_AGENCY = 'responsible_agency' ATTR_RESPONSIBLE_AGENCY = 'responsible_agency'
ATTR_SIZE = 'size' ATTR_SIZE = 'size'
@ -42,7 +38,7 @@ ATTR_TYPE = 'type'
CONF_CATEGORIES = 'categories' CONF_CATEGORIES = 'categories'
DEFAULT_RADIUS_IN_KM = 20.0 DEFAULT_RADIUS_IN_KM = 20.0
DEFAULT_UNIT_OF_MEASUREMENT = "km" DEFAULT_UNIT_OF_MEASUREMENT = 'km'
SCAN_INTERVAL = timedelta(minutes=5) SCAN_INTERVAL = timedelta(minutes=5)
@ -51,14 +47,17 @@ SIGNAL_UPDATE_ENTITY = 'nsw_rural_fire_service_feed_update_{}'
SOURCE = 'nsw_rural_fire_service_feed' SOURCE = 'nsw_rural_fire_service_feed'
VALID_CATEGORIES = ['Emergency Warning', 'Watch and Act', 'Advice', VALID_CATEGORIES = [
'Not Applicable'] 'Advice',
'Emergency Warning',
'Not Applicable',
'Watch and Act',
]
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Optional(CONF_RADIUS, default=DEFAULT_RADIUS_IN_KM):
vol.Coerce(float),
vol.Optional(CONF_CATEGORIES, default=[]): vol.Optional(CONF_CATEGORIES, default=[]):
vol.All(cv.ensure_list, [vol.In(VALID_CATEGORIES)]) vol.All(cv.ensure_list, [vol.In(VALID_CATEGORIES)]),
vol.Optional(CONF_RADIUS, default=DEFAULT_RADIUS_IN_KM): vol.Coerce(float),
}) })
@ -68,8 +67,8 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
radius_in_km = config[CONF_RADIUS] radius_in_km = config[CONF_RADIUS]
categories = config.get(CONF_CATEGORIES) categories = config.get(CONF_CATEGORIES)
# Initialize the entity manager. # Initialize the entity manager.
feed = NswRuralFireServiceFeedManager(hass, add_entities, scan_interval, feed = NswRuralFireServiceFeedManager(
radius_in_km, categories) hass, add_entities, scan_interval, radius_in_km, categories)
def start_feed_manager(event): def start_feed_manager(event):
"""Start feed manager.""" """Start feed manager."""
@ -86,11 +85,11 @@ class NswRuralFireServiceFeedManager:
"""Initialize the GeoJSON Feed Manager.""" """Initialize the GeoJSON Feed Manager."""
from geojson_client.nsw_rural_fire_service_feed \ from geojson_client.nsw_rural_fire_service_feed \
import NswRuralFireServiceFeed import NswRuralFireServiceFeed
self._hass = hass self._hass = hass
self._feed = NswRuralFireServiceFeed((hass.config.latitude, self._feed = NswRuralFireServiceFeed(
hass.config.longitude), (hass.config.latitude, hass.config.longitude),
filter_radius=radius_in_km, filter_radius=radius_in_km, filter_categories=categories)
filter_categories=categories)
self._add_entities = add_entities self._add_entities = add_entities
self._scan_interval = scan_interval self._scan_interval = scan_interval
self.feed_entries = {} self.feed_entries = {}
@ -103,12 +102,13 @@ class NswRuralFireServiceFeedManager:
def _init_regular_updates(self): def _init_regular_updates(self):
"""Schedule regular updates at the specified interval.""" """Schedule regular updates at the specified interval."""
track_time_interval(self._hass, lambda now: self._update(), track_time_interval(
self._scan_interval) self._hass, lambda now: self._update(), self._scan_interval)
def _update(self): def _update(self):
"""Update the feed and then update connected entities.""" """Update the feed and then update connected entities."""
import geojson_client import geojson_client
status, feed_entries = self._feed.update() status, feed_entries = self._feed.update()
if status == geojson_client.UPDATE_OK: if status == geojson_client.UPDATE_OK:
_LOGGER.debug("Data retrieved %s", feed_entries) _LOGGER.debug("Data retrieved %s", feed_entries)
@ -127,11 +127,11 @@ class NswRuralFireServiceFeedManager:
self._managed_external_ids) self._managed_external_ids)
self._generate_new_entities(create_external_ids) self._generate_new_entities(create_external_ids)
elif status == geojson_client.UPDATE_OK_NO_DATA: elif status == geojson_client.UPDATE_OK_NO_DATA:
_LOGGER.debug("Update successful, but no data received from %s", _LOGGER.debug(
self._feed) "Update successful, but no data received from %s", self._feed)
else: else:
_LOGGER.warning("Update not successful, no data received from %s", _LOGGER.warning(
self._feed) "Update not successful, no data received from %s", self._feed)
# Remove all entities. # Remove all entities.
self._remove_entities(self._managed_external_ids.copy()) self._remove_entities(self._managed_external_ids.copy())
@ -150,16 +150,16 @@ class NswRuralFireServiceFeedManager:
"""Update entities.""" """Update entities."""
for external_id in external_ids: for external_id in external_ids:
_LOGGER.debug("Existing entity found %s", external_id) _LOGGER.debug("Existing entity found %s", external_id)
dispatcher_send(self._hass, dispatcher_send(
SIGNAL_UPDATE_ENTITY.format(external_id)) self._hass, SIGNAL_UPDATE_ENTITY.format(external_id))
def _remove_entities(self, external_ids): def _remove_entities(self, external_ids):
"""Remove entities.""" """Remove entities."""
for external_id in external_ids: for external_id in external_ids:
_LOGGER.debug("Entity not current anymore %s", external_id) _LOGGER.debug("Entity not current anymore %s", external_id)
self._managed_external_ids.remove(external_id) self._managed_external_ids.remove(external_id)
dispatcher_send(self._hass, dispatcher_send(
SIGNAL_DELETE_ENTITY.format(external_id)) self._hass, SIGNAL_DELETE_ENTITY.format(external_id))
class NswRuralFireServiceLocationEvent(GeoLocationEvent): class NswRuralFireServiceLocationEvent(GeoLocationEvent):