1 """Sensor platform for hvv."""
3 from datetime
import timedelta
7 from aiohttp
import ClientConnectorError
8 from pygti.exceptions
import InvalidAuth
20 from .const
import ATTRIBUTION, CONF_REAL_TIME, CONF_STATION, DOMAIN, MANUFACTURER
26 ATTR_DEPARTURE =
"departure"
28 ATTR_ORIGIN =
"origin"
29 ATTR_DIRECTION =
"direction"
33 ATTR_CANCELLED =
"cancelled"
39 _LOGGER = logging.getLogger(__name__)
44 config_entry: ConfigEntry,
45 async_add_entities: AddEntitiesCallback,
47 """Set up the sensor platform."""
48 hub = hass.data[DOMAIN][config_entry.entry_id]
50 session = aiohttp_client.async_get_clientsession(hass)
57 """HVVDepartureSensor class."""
59 _attr_attribution = ATTRIBUTION
60 _attr_device_class = SensorDeviceClass.TIMESTAMP
61 _attr_translation_key =
"departures"
62 _attr_has_entity_name =
True
63 _attr_available =
False
65 def __init__(self, hass, config_entry, session, hub):
74 station_id = config_entry.data[CONF_STATION][
"id"]
75 station_type = config_entry.data[CONF_STATION][
"type"]
76 self.
_attr_unique_id_attr_unique_id = f
"{config_entry.entry_id}-{station_id}-{station_type}"
78 entry_type=DeviceEntryType.SERVICE,
82 config_entry.entry_id,
83 config_entry.data[CONF_STATION][
"id"],
84 config_entry.data[CONF_STATION][
"type"],
87 manufacturer=MANUFACTURER,
88 name=config_entry.data[CONF_STATION][
"name"],
91 @Throttle(MIN_TIME_BETWEEN_UPDATES)
93 """Update the sensor."""
95 minutes=self.
config_entryconfig_entry.options.get(CONF_OFFSET, 0)
98 departure_time_tz_berlin = departure_time.astimezone(BERLIN_TIME_ZONE)
100 station = self.
config_entryconfig_entry.data[CONF_STATION]
103 "station": {
"id": station[
"id"],
"type": station[
"type"]},
105 "date": departure_time_tz_berlin.strftime(
"%d.%m.%Y"),
106 "time": departure_time_tz_berlin.strftime(
"%H:%M"),
109 "maxTimeOffset": MAX_TIME_OFFSET,
110 "useRealtime": self.
config_entryconfig_entry.options.get(CONF_REAL_TIME,
False),
114 payload.update({
"filter": self.
config_entryconfig_entry.options[
"filter"]})
117 data = await self.
gtigti.departureList(payload)
118 except InvalidAuth
as error:
120 _LOGGER.error(
"Authentication failed: %r", error)
123 except ClientConnectorError
as error:
124 if self.
_last_error_last_error != ClientConnectorError:
125 _LOGGER.warning(
"Network unavailable: %r", error)
128 except Exception
as error:
130 _LOGGER.error(
"Error occurred while fetching data: %r", error)
134 if not (data[
"returnCode"] ==
"OK" and data.get(
"departures")):
138 if self.
_last_error_last_error == ClientConnectorError:
139 _LOGGER.debug(
"Network available again")
143 departure = data[
"departures"][0]
144 line = departure[
"line"]
145 delay = departure.get(
"delay", 0)
146 cancelled = departure.get(
"cancelled",
False)
147 extra = departure.get(
"extra",
False)
151 +
timedelta(minutes=departure[
"timeOffset"])
157 ATTR_LINE: line[
"name"],
158 ATTR_ORIGIN: line[
"origin"],
159 ATTR_DIRECTION: line[
"direction"],
160 ATTR_TYPE: line[
"type"][
"shortInfo"],
163 ATTR_CANCELLED: cancelled,
169 for departure
in data[
"departures"]:
170 line = departure[
"line"]
171 delay = departure.get(
"delay", 0)
172 cancelled = departure.get(
"cancelled",
False)
173 extra = departure.get(
"extra",
False)
176 ATTR_DEPARTURE: departure_time
177 +
timedelta(minutes=departure[
"timeOffset"])
179 ATTR_LINE: line[
"name"],
180 ATTR_ORIGIN: line[
"origin"],
181 ATTR_DIRECTION: line[
"direction"],
182 ATTR_TYPE: line[
"type"][
"shortInfo"],
185 ATTR_CANCELLED: cancelled,
_attr_extra_state_attributes
def __init__(self, hass, config_entry, session, hub)
None async_update(self, **Any kwargs)
None async_setup_entry(HomeAssistant hass, ConfigEntry config_entry, AddEntitiesCallback async_add_entities)
IssData update(pyiss.ISS iss)
zoneinfo.ZoneInfo|None get_time_zone(str time_zone_str)