Use voluptuous for transport sensors (#2867)

This commit is contained in:
Fabian Affolter 2016-08-19 09:12:56 +02:00 committed by Paulus Schoutsen
parent 2a563e1604
commit 0abc50e844
3 changed files with 53 additions and 40 deletions

View File

@ -9,7 +9,7 @@ from datetime import timedelta
import voluptuous as vol import voluptuous as vol
from homeassistant.const import (CONF_PLATFORM) from homeassistant.components.sensor import PLATFORM_SCHEMA
import homeassistant.helpers.config_validation as cv import homeassistant.helpers.config_validation as cv
from homeassistant.util import Throttle from homeassistant.util import Throttle
from homeassistant.helpers.entity import Entity from homeassistant.helpers.entity import Entity
@ -23,10 +23,9 @@ ICON = 'mdi:train'
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
PLATFORM_SCHEMA = vol.Schema({ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_PLATFORM): 'deutsche_bahn',
vol.Required(CONF_START): cv.string,
vol.Required(CONF_DESTINATION): cv.string, vol.Required(CONF_DESTINATION): cv.string,
vol.Required(CONF_START): cv.string,
}) })
# Return cached results if last scan was less then this time ago. # Return cached results if last scan was less then this time ago.
@ -47,7 +46,7 @@ class DeutscheBahnSensor(Entity):
def __init__(self, start, goal): def __init__(self, start, goal):
"""Initialize the sensor.""" """Initialize the sensor."""
self._name = start + ' to ' + goal self._name = '{} to {}'.format(start, goal)
self.data = SchieneData(start, goal) self.data = SchieneData(start, goal)
self.update() self.update()

View File

@ -7,12 +7,14 @@ https://home-assistant.io/components/sensor.google_travel_time/
from datetime import datetime from datetime import datetime
from datetime import timedelta from datetime import timedelta
import logging import logging
import voluptuous as vol import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.helpers.entity import Entity from homeassistant.helpers.entity import Entity
from homeassistant.const import ( from homeassistant.const import (
CONF_API_KEY, EVENT_HOMEASSISTANT_START, ATTR_LATITUDE, ATTR_LONGITUDE) CONF_API_KEY, CONF_NAME, EVENT_HOMEASSISTANT_START, ATTR_LATITUDE,
ATTR_LONGITUDE)
from homeassistant.util import Throttle from homeassistant.util import Throttle
import homeassistant.helpers.config_validation as cv import homeassistant.helpers.config_validation as cv
import homeassistant.helpers.location as location import homeassistant.helpers.location as location
@ -25,12 +27,12 @@ REQUIREMENTS = ['googlemaps==2.4.4']
# Return cached results if last update was less then this time ago # Return cached results if last update was less then this time ago
MIN_TIME_BETWEEN_UPDATES = timedelta(minutes=5) MIN_TIME_BETWEEN_UPDATES = timedelta(minutes=5)
DEFAULT_NAME = 'Google Travel Time'
CONF_ORIGIN = 'origin' CONF_ORIGIN = 'origin'
CONF_DESTINATION = 'destination' CONF_DESTINATION = 'destination'
CONF_TRAVEL_MODE = 'travel_mode' CONF_TRAVEL_MODE = 'travel_mode'
CONF_OPTIONS = 'options' CONF_OPTIONS = 'options'
CONF_MODE = 'mode' CONF_MODE = 'mode'
CONF_NAME = 'name'
ALL_LANGUAGES = ['ar', 'bg', 'bn', 'ca', 'cs', 'da', 'de', 'el', 'en', 'es', ALL_LANGUAGES = ['ar', 'bg', 'bn', 'ca', 'cs', 'da', 'de', 'el', 'en', 'es',
'eu', 'fa', 'fi', 'fr', 'gl', 'gu', 'hi', 'hr', 'hu', 'id', 'eu', 'fa', 'fi', 'fr', 'gl', 'gu', 'hi', 'hr', 'hu', 'id',
@ -40,35 +42,33 @@ ALL_LANGUAGES = ['ar', 'bg', 'bn', 'ca', 'cs', 'da', 'de', 'el', 'en', 'es',
'zh-CN', 'zh-TW'] 'zh-CN', 'zh-TW']
TRANSIT_PREFS = ['less_walking', 'fewer_transfers'] TRANSIT_PREFS = ['less_walking', 'fewer_transfers']
TRAVEL_MODE = ['driving', 'walking', 'bicycling', 'transit']
AVOID = ['tolls', 'highways', 'ferries', 'indoor']
TRANSPORT_TYPE = ['bus', 'subway', 'train', 'tram', 'rail']
TRAVEL_MODEL = ['best_guess', 'pessimistic', 'optimistic']
UNITS = ['metric', 'imperial']
PLATFORM_SCHEMA = vol.Schema({ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required('platform'): 'google_travel_time', vol.Required(CONF_API_KEY): cv.string,
vol.Optional(CONF_NAME): vol.Coerce(str), vol.Required(CONF_DESTINATION): cv.string,
vol.Required(CONF_API_KEY): vol.Coerce(str), vol.Required(CONF_ORIGIN): cv.string,
vol.Required(CONF_ORIGIN): vol.Coerce(str), vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Required(CONF_DESTINATION): vol.Coerce(str), vol.Optional(CONF_TRAVEL_MODE): vol.In(TRAVEL_MODE),
vol.Optional(CONF_TRAVEL_MODE):
vol.In(["driving", "walking", "bicycling", "transit"]),
vol.Optional(CONF_OPTIONS, default={CONF_MODE: 'driving'}): vol.All( vol.Optional(CONF_OPTIONS, default={CONF_MODE: 'driving'}): vol.All(
dict, vol.Schema({ dict, vol.Schema({
vol.Optional(CONF_MODE, default='driving'): vol.Optional(CONF_MODE, default='driving'): vol.In(TRAVEL_MODE),
vol.In(["driving", "walking", "bicycling", "transit"]),
vol.Optional('language'): vol.In(ALL_LANGUAGES), vol.Optional('language'): vol.In(ALL_LANGUAGES),
vol.Optional('avoid'): vol.In(['tolls', 'highways', vol.Optional('avoid'): vol.In(AVOID),
'ferries', 'indoor']), vol.Optional('units'): vol.In(UNITS),
vol.Optional('units'): vol.In(['metric', 'imperial']),
vol.Exclusive('arrival_time', 'time'): cv.string, vol.Exclusive('arrival_time', 'time'): cv.string,
vol.Exclusive('departure_time', 'time'): cv.string, vol.Exclusive('departure_time', 'time'): cv.string,
vol.Optional('traffic_model'): vol.In(['best_guess', vol.Optional('traffic_model'): vol.In(TRAVEL_MODEL),
'pessimistic', vol.Optional('transit_mode'): vol.In(TRANSPORT_TYPE),
'optimistic']),
vol.Optional('transit_mode'): vol.In(['bus', 'subway', 'train',
'tram', 'rail']),
vol.Optional('transit_routing_preference'): vol.In(TRANSIT_PREFS) vol.Optional('transit_routing_preference'): vol.In(TRANSIT_PREFS)
})) }))
}) })
TRACKABLE_DOMAINS = ["device_tracker", "sensor", "zone"] TRACKABLE_DOMAINS = ['device_tracker', 'sensor', 'zone']
def convert_time_to_utc(timestr): def convert_time_to_utc(timestr):
@ -81,10 +81,10 @@ def convert_time_to_utc(timestr):
def setup_platform(hass, config, add_devices_callback, discovery_info=None): def setup_platform(hass, config, add_devices_callback, discovery_info=None):
"""Setup the travel time platform.""" """Setup the Google travel time platform."""
# pylint: disable=too-many-locals # pylint: disable=too-many-locals
def run_setup(event): def run_setup(event):
"""Delay the setup until home assistant is fully initialized. """Delay the setup until Home Assistant is fully initialized.
This allows any entities to be created already This allows any entities to be created already
""" """
@ -122,7 +122,7 @@ def setup_platform(hass, config, add_devices_callback, discovery_info=None):
# pylint: disable=too-many-instance-attributes # pylint: disable=too-many-instance-attributes
class GoogleTravelTimeSensor(Entity): class GoogleTravelTimeSensor(Entity):
"""Representation of a tavel time sensor.""" """Representation of a Google travel time sensor."""
# pylint: disable=too-many-arguments # pylint: disable=too-many-arguments
def __init__(self, hass, name, api_key, origin, destination, options): def __init__(self, hass, name, api_key, origin, destination, options):
@ -130,6 +130,7 @@ class GoogleTravelTimeSensor(Entity):
self._hass = hass self._hass = hass
self._name = name self._name = name
self._options = options self._options = options
self._unit_of_measurement = 'min'
self._matrix = None self._matrix = None
self.valid_api_connection = True self.valid_api_connection = True
@ -192,7 +193,7 @@ class GoogleTravelTimeSensor(Entity):
@property @property
def unit_of_measurement(self): def unit_of_measurement(self):
"""Return the unit this state is expressed in.""" """Return the unit this state is expressed in."""
return "min" return self._unit_of_measurement
@Throttle(MIN_TIME_BETWEEN_UPDATES) @Throttle(MIN_TIME_BETWEEN_UPDATES)
def update(self): def update(self):

View File

@ -8,34 +8,49 @@ import logging
from datetime import timedelta from datetime import timedelta
import requests import requests
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import CONF_NAME
import homeassistant.util.dt as dt_util import homeassistant.util.dt as dt_util
from homeassistant.helpers.entity import Entity from homeassistant.helpers.entity import Entity
from homeassistant.util import Throttle from homeassistant.util import Throttle
import homeassistant.helpers.config_validation as cv
_LOGGER = logging.getLogger(__name__)
_RESOURCE = 'http://transport.opendata.ch/v1/' _RESOURCE = 'http://transport.opendata.ch/v1/'
DEFAULT_NAME = 'Next Departure'
ATTR_DEPARTURE_TIME1 = 'Next departure' ATTR_DEPARTURE_TIME1 = 'Next departure'
ATTR_DEPARTURE_TIME2 = 'Next on departure' ATTR_DEPARTURE_TIME2 = 'Next on departure'
ATTR_START = 'Start' ATTR_START = 'Start'
ATTR_TARGET = 'Destination' ATTR_TARGET = 'Destination'
ATTR_REMAINING_TIME = 'Remaining time' ATTR_REMAINING_TIME = 'Remaining time'
CONF_START = 'from'
CONF_DESTINATION = 'to'
ICON = 'mdi:bus' ICON = 'mdi:bus'
TIME_STR_FORMAT = "%H:%M" TIME_STR_FORMAT = "%H:%M"
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_DESTINATION): cv.string,
vol.Required(CONF_START): cv.string,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
})
_LOGGER = logging.getLogger(__name__)
# Return cached results if last scan was less then this time ago. # Return cached results if last scan was less then this time ago.
MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=60) MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=60)
def setup_platform(hass, config, add_devices, discovery_info=None): def setup_platform(hass, config, add_devices, discovery_info=None):
"""Get the Swiss public transport sensor.""" """Get the Swiss public transport sensor."""
name = config.get(CONF_NAME)
# journal contains [0] Station ID start, [1] Station ID destination # journal contains [0] Station ID start, [1] Station ID destination
# [2] Station name start, and [3] Station name destination # [2] Station name start, and [3] Station name destination
journey = [config.get('from'), config.get('to')] journey = [config.get(CONF_START), config.get(CONF_DESTINATION)]
try: try:
for location in [config.get('from', None), config.get('to', None)]: for location in [config.get(CONF_START), config.get(CONF_DESTINATION)]:
# transport.opendata.ch doesn't play nice with requests.Session # transport.opendata.ch doesn't play nice with requests.Session
result = requests.get(_RESOURCE + 'locations?query=%s' % location, result = requests.get(_RESOURCE + 'locations?query=%s' % location,
timeout=10) timeout=10)
@ -46,20 +61,18 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
"Check your settings and/or the availability of opendata.ch") "Check your settings and/or the availability of opendata.ch")
return False return False
dev = []
data = PublicTransportData(journey) data = PublicTransportData(journey)
dev.append(SwissPublicTransportSensor(data, journey)) add_devices([SwissPublicTransportSensor(data, journey, name)])
add_devices(dev)
# pylint: disable=too-few-public-methods # pylint: disable=too-few-public-methods
class SwissPublicTransportSensor(Entity): class SwissPublicTransportSensor(Entity):
"""Implementation of an Swiss public transport sensor.""" """Implementation of an Swiss public transport sensor."""
def __init__(self, data, journey): def __init__(self, data, journey, name):
"""Initialize the sensor.""" """Initialize the sensor."""
self.data = data self.data = data
self._name = 'Next Departure' self._name = name
self._from = journey[2] self._from = journey[2]
self._to = journey[3] self._to = journey[3]
self.update() self.update()
@ -123,7 +136,7 @@ class PublicTransportData(object):
'to=' + self.destination + '&' + 'to=' + self.destination + '&' +
'fields[]=connections/from/departureTimestamp/&' + 'fields[]=connections/from/departureTimestamp/&' +
'fields[]=connections/', 'fields[]=connections/',
timeout=30) timeout=10)
connections = response.json()['connections'][:2] connections = response.json()['connections'][:2]
try: try: