Add HVV integration (Hamburg public transportation) (#31564)
Co-authored-by: springstan <46536646+springstan@users.noreply.github.com> Co-authored-by: Martin Hjelmare <marhje52@gmail.com>
This commit is contained in:
21 files changed
+1211
No files matched your search
@@ -0,0 +1,52 @@
|
||||
"""The HVV integration."""
|
||||
import asyncio
|
||||
|
||||
from homeassistant.components.sensor import DOMAIN as DOMAIN_SENSOR
|
||||
from homeassistant.config_entries import ConfigEntry
|
||||
from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers import aiohttp_client
|
||||
|
||||
from .const import DOMAIN
|
||||
from .hub import GTIHub
|
||||
|
||||
PLATFORMS = [DOMAIN_SENSOR]
|
||||
|
||||
|
||||
async def async_setup(hass: HomeAssistant, config: dict):
|
||||
"""Set up the HVV component."""
|
||||
return True
|
||||
|
||||
|
||||
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
|
||||
"""Set up HVV from a config entry."""
|
||||
|
||||
hub = GTIHub(
|
||||
entry.data[CONF_HOST],
|
||||
entry.data[CONF_USERNAME],
|
||||
entry.data[CONF_PASSWORD],
|
||||
aiohttp_client.async_get_clientsession(hass),
|
||||
)
|
||||
|
||||
hass.data.setdefault(DOMAIN, {})
|
||||
hass.data[DOMAIN][entry.entry_id] = hub
|
||||
|
||||
for component in PLATFORMS:
|
||||
hass.async_create_task(
|
||||
hass.config_entries.async_forward_entry_setup(entry, component)
|
||||
)
|
||||
|
||||
return True
|
||||
|
||||
|
||||
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry):
|
||||
"""Unload a config entry."""
|
||||
unload_ok = all(
|
||||
await asyncio.gather(
|
||||
*[
|
||||
hass.config_entries.async_forward_entry_unload(entry, component)
|
||||
for component in PLATFORMS
|
||||
]
|
||||
)
|
||||
)
|
||||
return unload_ok
|
||||
@@ -0,0 +1,218 @@
|
||||
"""Config flow for HVV integration."""
|
||||
import logging
|
||||
|
||||
from pygti.auth import GTI_DEFAULT_HOST
|
||||
from pygti.exceptions import CannotConnect, InvalidAuth
|
||||
import voluptuous as vol
|
||||
|
||||
from homeassistant import config_entries
|
||||
from homeassistant.const import CONF_HOST, CONF_OFFSET, CONF_PASSWORD, CONF_USERNAME
|
||||
from homeassistant.core import callback
|
||||
from homeassistant.helpers import aiohttp_client
|
||||
import homeassistant.helpers.config_validation as cv
|
||||
|
||||
from .const import ( # pylint:disable=unused-import
|
||||
CONF_FILTER,
|
||||
CONF_REAL_TIME,
|
||||
CONF_STATION,
|
||||
DOMAIN,
|
||||
)
|
||||
from .hub import GTIHub
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
SCHEMA_STEP_USER = vol.Schema(
|
||||
{
|
||||
vol.Required(CONF_HOST, default=GTI_DEFAULT_HOST): str,
|
||||
vol.Required(CONF_USERNAME): str,
|
||||
vol.Required(CONF_PASSWORD): str,
|
||||
}
|
||||
)
|
||||
|
||||
SCHEMA_STEP_STATION = vol.Schema({vol.Required(CONF_STATION): str})
|
||||
|
||||
SCHEMA_STEP_OPTIONS = vol.Schema(
|
||||
{
|
||||
vol.Required(CONF_FILTER): vol.In([]),
|
||||
vol.Required(CONF_OFFSET, default=0): vol.All(int, vol.Range(min=0)),
|
||||
vol.Optional(CONF_REAL_TIME, default=True): bool,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
|
||||
"""Handle a config flow for HVV."""
|
||||
|
||||
VERSION = 1
|
||||
CONNECTION_CLASS = config_entries.CONN_CLASS_CLOUD_POLL
|
||||
|
||||
def __init__(self):
|
||||
"""Initialize component."""
|
||||
self.hub = None
|
||||
self.data = None
|
||||
self.stations = {}
|
||||
|
||||
async def async_step_user(self, user_input=None):
|
||||
"""Handle the initial step."""
|
||||
errors = {}
|
||||
|
||||
if user_input is not None:
|
||||
session = aiohttp_client.async_get_clientsession(self.hass)
|
||||
self.hub = GTIHub(
|
||||
user_input[CONF_HOST],
|
||||
user_input[CONF_USERNAME],
|
||||
user_input[CONF_PASSWORD],
|
||||
session,
|
||||
)
|
||||
|
||||
try:
|
||||
response = await self.hub.authenticate()
|
||||
_LOGGER.debug("Init gti: %r", response)
|
||||
except CannotConnect:
|
||||
errors["base"] = "cannot_connect"
|
||||
except InvalidAuth:
|
||||
errors["base"] = "invalid_auth"
|
||||
|
||||
if not errors:
|
||||
self.data = user_input
|
||||
return await self.async_step_station()
|
||||
|
||||
return self.async_show_form(
|
||||
step_id="user", data_schema=SCHEMA_STEP_USER, errors=errors
|
||||
)
|
||||
|
||||
async def async_step_station(self, user_input=None):
|
||||
"""Handle the step where the user inputs his/her station."""
|
||||
if user_input is not None:
|
||||
|
||||
errors = {}
|
||||
|
||||
check_name = await self.hub.gti.checkName(
|
||||
{"theName": {"name": user_input[CONF_STATION]}, "maxList": 20}
|
||||
)
|
||||
|
||||
stations = check_name.get("results")
|
||||
|
||||
self.stations = {
|
||||
f"{station.get('name')}": station
|
||||
for station in stations
|
||||
if station.get("type") == "STATION"
|
||||
}
|
||||
|
||||
if not self.stations:
|
||||
errors["base"] = "no_results"
|
||||
|
||||
return self.async_show_form(
|
||||
step_id="station", data_schema=SCHEMA_STEP_STATION, errors=errors
|
||||
)
|
||||
|
||||
# schema
|
||||
|
||||
return await self.async_step_station_select()
|
||||
|
||||
return self.async_show_form(step_id="station", data_schema=SCHEMA_STEP_STATION)
|
||||
|
||||
async def async_step_station_select(self, user_input=None):
|
||||
"""Handle the step where the user inputs his/her station."""
|
||||
|
||||
schema = vol.Schema({vol.Required(CONF_STATION): vol.In(list(self.stations))})
|
||||
|
||||
if user_input is None:
|
||||
return self.async_show_form(step_id="station_select", data_schema=schema)
|
||||
|
||||
self.data.update({"station": self.stations[user_input[CONF_STATION]]})
|
||||
|
||||
title = self.data[CONF_STATION]["name"]
|
||||
|
||||
return self.async_create_entry(title=title, data=self.data)
|
||||
|
||||
@staticmethod
|
||||
@callback
|
||||
def async_get_options_flow(config_entry):
|
||||
"""Get options flow."""
|
||||
return OptionsFlowHandler(config_entry)
|
||||
|
||||
|
||||
class OptionsFlowHandler(config_entries.OptionsFlow):
|
||||
"""Options flow handler."""
|
||||
|
||||
def __init__(self, config_entry):
|
||||
"""Initialize HVV Departures options flow."""
|
||||
self.config_entry = config_entry
|
||||
self.options = dict(config_entry.options)
|
||||
self.departure_filters = {}
|
||||
self.hub = None
|
||||
|
||||
async def async_step_init(self, user_input=None):
|
||||
"""Manage the options."""
|
||||
errors = {}
|
||||
if not self.departure_filters:
|
||||
|
||||
departure_list = {}
|
||||
self.hub = self.hass.data[DOMAIN][self.config_entry.entry_id]
|
||||
|
||||
try:
|
||||
departure_list = await self.hub.gti.departureList(
|
||||
{
|
||||
"station": self.config_entry.data[CONF_STATION],
|
||||
"time": {"date": "heute", "time": "jetzt"},
|
||||
"maxList": 5,
|
||||
"maxTimeOffset": 200,
|
||||
"useRealtime": True,
|
||||
"returnFilters": True,
|
||||
}
|
||||
)
|
||||
except CannotConnect:
|
||||
errors["base"] = "cannot_connect"
|
||||
except InvalidAuth:
|
||||
errors["base"] = "invalid_auth"
|
||||
|
||||
if not errors:
|
||||
self.departure_filters = {
|
||||
str(i): departure_filter
|
||||
for i, departure_filter in enumerate(departure_list.get("filter"))
|
||||
}
|
||||
|
||||
if user_input is not None and not errors:
|
||||
|
||||
options = {
|
||||
CONF_FILTER: [
|
||||
self.departure_filters[x] for x in user_input[CONF_FILTER]
|
||||
],
|
||||
CONF_OFFSET: user_input[CONF_OFFSET],
|
||||
CONF_REAL_TIME: user_input[CONF_REAL_TIME],
|
||||
}
|
||||
|
||||
return self.async_create_entry(title="", data=options)
|
||||
|
||||
if CONF_FILTER in self.config_entry.options:
|
||||
old_filter = [
|
||||
i
|
||||
for (i, f) in self.departure_filters.items()
|
||||
if f in self.config_entry.options.get(CONF_FILTER)
|
||||
]
|
||||
else:
|
||||
old_filter = []
|
||||
|
||||
return self.async_show_form(
|
||||
step_id="init",
|
||||
data_schema=vol.Schema(
|
||||
{
|
||||
vol.Optional(CONF_FILTER, default=old_filter): cv.multi_select(
|
||||
{
|
||||
key: f"{departure_filter['serviceName']}, {departure_filter['label']}"
|
||||
for key, departure_filter in self.departure_filters.items()
|
||||
}
|
||||
),
|
||||
vol.Required(
|
||||
CONF_OFFSET,
|
||||
default=self.config_entry.options.get(CONF_OFFSET, 0),
|
||||
): vol.All(int, vol.Range(min=0)),
|
||||
vol.Optional(
|
||||
CONF_REAL_TIME,
|
||||
default=self.config_entry.options.get(CONF_REAL_TIME, True),
|
||||
): bool,
|
||||
}
|
||||
),
|
||||
errors=errors,
|
||||
)
|
||||
@@ -0,0 +1,10 @@
|
||||
"""Constants for the HVV Departure integration."""
|
||||
|
||||
DOMAIN = "hvv_departures"
|
||||
DEFAULT_NAME = DOMAIN
|
||||
MANUFACTURER = "HVV"
|
||||
ATTRIBUTION = "Data provided by www.hvv.de"
|
||||
|
||||
CONF_STATION = "station"
|
||||
CONF_REAL_TIME = "real_time"
|
||||
CONF_FILTER = "filter"
|
||||
@@ -0,0 +1,20 @@
|
||||
"""Hub."""
|
||||
|
||||
from pygti.gti import GTI, Auth
|
||||
|
||||
|
||||
class GTIHub:
|
||||
"""GTI Hub."""
|
||||
|
||||
def __init__(self, host, username, password, session):
|
||||
"""Initialize."""
|
||||
self.host = host
|
||||
self.username = username
|
||||
self.password = password
|
||||
|
||||
self.gti = GTI(Auth(session, self.username, self.password, self.host))
|
||||
|
||||
async def authenticate(self):
|
||||
"""Test if we can authenticate with the host."""
|
||||
|
||||
return await self.gti.init()
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"domain": "hvv_departures",
|
||||
"name": "HVV Departures",
|
||||
"config_flow": true,
|
||||
"documentation": "https://www.home-assistant.io/integrations/hvv_departures",
|
||||
"requirements": [
|
||||
"pygti==0.6.0"
|
||||
],
|
||||
"codeowners": [
|
||||
"@vigonotion"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
"""Sensor platform for hvv."""
|
||||
from datetime import timedelta
|
||||
import logging
|
||||
|
||||
from aiohttp import ClientConnectorError
|
||||
from pygti.exceptions import InvalidAuth
|
||||
|
||||
from homeassistant.const import ATTR_ATTRIBUTION, ATTR_ID, DEVICE_CLASS_TIMESTAMP
|
||||
from homeassistant.helpers import aiohttp_client
|
||||
from homeassistant.helpers.entity import Entity
|
||||
from homeassistant.util import Throttle
|
||||
from homeassistant.util.dt import utcnow
|
||||
|
||||
from .const import ATTRIBUTION, CONF_STATION, DOMAIN, MANUFACTURER
|
||||
|
||||
MIN_TIME_BETWEEN_UPDATES = timedelta(minutes=1)
|
||||
MAX_LIST = 20
|
||||
MAX_TIME_OFFSET = 360
|
||||
ICON = "mdi:bus"
|
||||
UNIT_OF_MEASUREMENT = "min"
|
||||
|
||||
ATTR_DEPARTURE = "departure"
|
||||
ATTR_LINE = "line"
|
||||
ATTR_ORIGIN = "origin"
|
||||
ATTR_DIRECTION = "direction"
|
||||
ATTR_TYPE = "type"
|
||||
ATTR_DELAY = "delay"
|
||||
ATTR_NEXT = "next"
|
||||
|
||||
PARALLEL_UPDATES = 0
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def async_setup_entry(hass, config_entry, async_add_devices):
|
||||
"""Set up the sensor platform."""
|
||||
hub = hass.data[DOMAIN][config_entry.entry_id]
|
||||
|
||||
session = aiohttp_client.async_get_clientsession(hass)
|
||||
|
||||
sensor = HVVDepartureSensor(hass, config_entry, session, hub)
|
||||
async_add_devices([sensor], True)
|
||||
|
||||
|
||||
class HVVDepartureSensor(Entity):
|
||||
"""HVVDepartureSensor class."""
|
||||
|
||||
def __init__(self, hass, config_entry, session, hub):
|
||||
"""Initialize."""
|
||||
self.config_entry = config_entry
|
||||
self.station_name = self.config_entry.data[CONF_STATION]["name"]
|
||||
self.attr = {ATTR_ATTRIBUTION: ATTRIBUTION}
|
||||
self._available = False
|
||||
self._state = None
|
||||
self._name = f"Departures at {self.station_name}"
|
||||
self._last_error = None
|
||||
|
||||
self.gti = hub.gti
|
||||
|
||||
@Throttle(MIN_TIME_BETWEEN_UPDATES)
|
||||
async def async_update(self, **kwargs):
|
||||
"""Update the sensor."""
|
||||
|
||||
departure_time = utcnow() + timedelta(
|
||||
minutes=self.config_entry.options.get("offset", 0)
|
||||
)
|
||||
|
||||
payload = {
|
||||
"station": self.config_entry.data[CONF_STATION],
|
||||
"time": {
|
||||
"date": departure_time.strftime("%d.%m.%Y"),
|
||||
"time": departure_time.strftime("%H:%M"),
|
||||
},
|
||||
"maxList": MAX_LIST,
|
||||
"maxTimeOffset": MAX_TIME_OFFSET,
|
||||
"useRealtime": self.config_entry.options.get("realtime", False),
|
||||
}
|
||||
|
||||
if "filter" in self.config_entry.options:
|
||||
payload.update({"filter": self.config_entry.options["filter"]})
|
||||
|
||||
try:
|
||||
data = await self.gti.departureList(payload)
|
||||
except InvalidAuth as error:
|
||||
if self._last_error != InvalidAuth:
|
||||
_LOGGER.error("Authentication failed: %r", error)
|
||||
self._last_error = InvalidAuth
|
||||
self._available = False
|
||||
except ClientConnectorError as error:
|
||||
if self._last_error != ClientConnectorError:
|
||||
_LOGGER.warning("Network unavailable: %r", error)
|
||||
self._last_error = ClientConnectorError
|
||||
self._available = False
|
||||
except Exception as error: # pylint: disable=broad-except
|
||||
if self._last_error != error:
|
||||
_LOGGER.error("Error occurred while fetching data: %r", error)
|
||||
self._last_error = error
|
||||
self._available = False
|
||||
|
||||
if not (data["returnCode"] == "OK" and data.get("departures")):
|
||||
self._available = False
|
||||
return
|
||||
|
||||
if self._last_error == ClientConnectorError:
|
||||
_LOGGER.debug("Network available again")
|
||||
|
||||
self._last_error = None
|
||||
|
||||
departure = data["departures"][0]
|
||||
line = departure["line"]
|
||||
delay = departure.get("delay", 0)
|
||||
self._available = True
|
||||
self._state = (
|
||||
departure_time
|
||||
+ timedelta(minutes=departure["timeOffset"])
|
||||
+ timedelta(seconds=delay)
|
||||
).isoformat()
|
||||
|
||||
self.attr.update(
|
||||
{
|
||||
ATTR_LINE: line["name"],
|
||||
ATTR_ORIGIN: line["origin"],
|
||||
ATTR_DIRECTION: line["direction"],
|
||||
ATTR_TYPE: line["type"]["shortInfo"],
|
||||
ATTR_ID: line["id"],
|
||||
ATTR_DELAY: delay,
|
||||
}
|
||||
)
|
||||
|
||||
departures = []
|
||||
for departure in data["departures"]:
|
||||
line = departure["line"]
|
||||
delay = departure.get("delay", 0)
|
||||
departures.append(
|
||||
{
|
||||
ATTR_DEPARTURE: departure_time
|
||||
+ timedelta(minutes=departure["timeOffset"])
|
||||
+ timedelta(seconds=delay),
|
||||
ATTR_LINE: line["name"],
|
||||
ATTR_ORIGIN: line["origin"],
|
||||
ATTR_DIRECTION: line["direction"],
|
||||
ATTR_TYPE: line["type"]["shortInfo"],
|
||||
ATTR_ID: line["id"],
|
||||
ATTR_DELAY: delay,
|
||||
}
|
||||
)
|
||||
self.attr[ATTR_NEXT] = departures
|
||||
|
||||
@property
|
||||
def unique_id(self):
|
||||
"""Return a unique ID to use for this sensor."""
|
||||
station_id = self.config_entry.data[CONF_STATION]["id"]
|
||||
station_type = self.config_entry.data[CONF_STATION]["type"]
|
||||
|
||||
return f"{self.config_entry.entry_id}-{station_id}-{station_type}"
|
||||
|
||||
@property
|
||||
def device_info(self):
|
||||
"""Return the device info for this sensor."""
|
||||
return {
|
||||
"identifiers": {
|
||||
(
|
||||
DOMAIN,
|
||||
self.config_entry.entry_id,
|
||||
self.config_entry.data[CONF_STATION]["id"],
|
||||
self.config_entry.data[CONF_STATION]["type"],
|
||||
)
|
||||
},
|
||||
"name": self._name,
|
||||
"manufacturer": MANUFACTURER,
|
||||
}
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
"""Return the name of the sensor."""
|
||||
return self._name
|
||||
|
||||
@property
|
||||
def state(self):
|
||||
"""Return the state of the sensor."""
|
||||
return self._state
|
||||
|
||||
@property
|
||||
def icon(self):
|
||||
"""Return the icon of the sensor."""
|
||||
return ICON
|
||||
|
||||
@property
|
||||
def available(self):
|
||||
"""Return True if entity is available."""
|
||||
return self._available
|
||||
|
||||
@property
|
||||
def device_class(self):
|
||||
"""Return the class of this device, from component DEVICE_CLASSES."""
|
||||
return DEVICE_CLASS_TIMESTAMP
|
||||
|
||||
@property
|
||||
def device_state_attributes(self):
|
||||
"""Return the state attributes."""
|
||||
return self.attr
|
||||
@@ -0,0 +1,48 @@
|
||||
{
|
||||
"title": "HVV Departures",
|
||||
"config": {
|
||||
"step": {
|
||||
"user": {
|
||||
"title": "Connect to the HVV API",
|
||||
"data": {
|
||||
"host": "Host",
|
||||
"username": "Username",
|
||||
"password": "Password"
|
||||
}
|
||||
},
|
||||
"station": {
|
||||
"title": "Enter Station/Address",
|
||||
"data": {
|
||||
"station": "Station/Address"
|
||||
}
|
||||
},
|
||||
"station_select": {
|
||||
"title": "Select Station/Address",
|
||||
"data": {
|
||||
"station": "Station/Address"
|
||||
}
|
||||
}
|
||||
},
|
||||
"error": {
|
||||
"cannot_connect": "Failed to connect, please try again",
|
||||
"invalid_auth": "Invalid authentication",
|
||||
"no_results": "No results. Try with a different station/address"
|
||||
},
|
||||
"abort": {
|
||||
"already_configured": "Device is already configured"
|
||||
}
|
||||
},
|
||||
"options": {
|
||||
"step": {
|
||||
"init": {
|
||||
"title": "Options",
|
||||
"description": "Change options for this departure sensor",
|
||||
"data": {
|
||||
"filter": "Select lines",
|
||||
"offset": "Offset (minutes)",
|
||||
"real_time": "Use real time data"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
{
|
||||
"config": {
|
||||
"abort": {
|
||||
"already_configured": "Device is already configured"
|
||||
},
|
||||
"error": {
|
||||
"cannot_connect": "Failed to connect, please try again",
|
||||
"invalid_auth": "Invalid authentication",
|
||||
"no_results": "No results. Try with a different station/address"
|
||||
},
|
||||
"step": {
|
||||
"station": {
|
||||
"data": {
|
||||
"station": "Station/Address"
|
||||
},
|
||||
"title": "Enter Station/Address"
|
||||
},
|
||||
"station_select": {
|
||||
"data": {
|
||||
"station": "Station/Address"
|
||||
},
|
||||
"title": "Select Station/Address"
|
||||
},
|
||||
"user": {
|
||||
"data": {
|
||||
"host": "Host",
|
||||
"password": "Password",
|
||||
"username": "Username"
|
||||
},
|
||||
"title": "Connect to the HVV API"
|
||||
}
|
||||
}
|
||||
},
|
||||
"options": {
|
||||
"step": {
|
||||
"init": {
|
||||
"data": {
|
||||
"filter": "Select lines",
|
||||
"offset": "Offset (minutes)",
|
||||
"real_time": "Use real time data"
|
||||
},
|
||||
"description": "Change options for this departure sensor",
|
||||
"title": "Options"
|
||||
}
|
||||
}
|
||||
},
|
||||
"title": "HVV Departures"
|
||||
}
|
||||
Reference in new issue
Block a user