Skip to content

Commit

Permalink
Align
Browse files Browse the repository at this point in the history
  • Loading branch information
vingerha committed Nov 11, 2023
1 parent 7ecc4b5 commit c90384f
Show file tree
Hide file tree
Showing 10 changed files with 62 additions and 37 deletions.
8 changes: 2 additions & 6 deletions custom_components/gtfs2/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,19 +37,15 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
hass.data.setdefault(DOMAIN, {})

coordinator = GTFSUpdateCoordinator(hass, entry)

coordinator_rt = GTFSRealtimeUpdateCoordinator(hass, entry)

await coordinator.async_config_entry_first_refresh()
#await coordinator.async_config_entry_first_refresh()

await coordinator_rt.async_config_entry_first_refresh()

hass.data[DOMAIN][entry.entry_id] = {
"coordinator": coordinator,
}

entry.async_on_unload(entry.add_update_listener(update_listener))

await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)

return True
Expand Down
5 changes: 3 additions & 2 deletions custom_components/gtfs2/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ async def async_step_source(self, user_input: dict | None = None) -> FlowResult:
data_schema=vol.Schema(
{
vol.Required("file"): str,
vol.Required("extract_from"): vol.In({"zip": "Existing Zipfile with same name", "url": "URL below"}),
vol.Required("extract_from"): vol.In({"zip": "Use gtfs2/zipfile with above name, without extension", "url": "Use URL below, leave 'na' if using zip"}),
vol.Required("url", default="na"): str,
},
),
Expand Down Expand Up @@ -246,6 +246,7 @@ async def async_step_init(
) -> FlowResult:
"""Manage the options."""
if user_input is not None:
user_input['real_time'] = False
if user_input['real_time']:
self._user_inputs.update(user_input)
_LOGGER.debug(f"GTFS Options with realtime: {self._user_inputs}")
Expand All @@ -260,7 +261,7 @@ async def async_step_init(
data_schema=vol.Schema(
{
vol.Optional("refresh_interval", default=self.config_entry.options.get("refresh_interval", DEFAULT_REFRESH_INTERVAL)): int,
vol.Required("real_time"): vol.In({False: "No", True: "Yes"}),
# vol.Required("real_time"): vol.In({False: "No", True: "Yes"}),
}
),
)
Expand Down
3 changes: 0 additions & 3 deletions custom_components/gtfs2/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -236,6 +236,3 @@
WHEELCHAIR_BOARDING_DEFAULT = STATE_UNKNOWN
WHEELCHAIR_BOARDING_OPTIONS = {1: True, 2: False}


# Realtime specifics
DEFAULT_REFRESH_INTERVAL_RT = 1
8 changes: 4 additions & 4 deletions custom_components/gtfs2/coordinator.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from homeassistant.core import HomeAssistant
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator

from .const import DEFAULT_PATH, DEFAULT_REFRESH_INTERVAL, DEFAULT_REFRESH_INTERVAL_RT
from .const import DEFAULT_PATH, DEFAULT_REFRESH_INTERVAL
from .gtfs_helper import get_gtfs, get_next_departure, check_datasource_index
from .gtfs_rt_helper import get_rt_route_statuses, get_next_services

Expand Down Expand Up @@ -92,7 +92,7 @@ async def _async_update_data(self) -> dict[str, str]:
#add real_time if setup


if options["real_time"]:
if "real_time" in options:

"""Initialize the info object."""
self._trip_update_url = options["trip_update_url"]
Expand All @@ -115,7 +115,7 @@ async def _async_update_data(self) -> dict[str, str]:
self._get_next_service = await self.hass.async_add_executor_job(get_next_services, self)
_LOGGER.debug("GTFS RT: Realtime next service: %s", self._get_next_service)
else:
_LOGGER.debug("GTFS RT: Issue with options")

_LOGGER.error("GTFS RT: Issue with entity options")
return "---"

return self._get_next_service
18 changes: 15 additions & 3 deletions custom_components/gtfs2/gtfs_helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ def get_next_departure(self):
tomorrow_order = f"calendar.{tomorrow_name} DESC,"

sql_query = f"""
SELECT trip.trip_id, trip.route_id,route.route_long_name,
SELECT trip.trip_id, trip.route_id,trip.trip_headsign,route.route_long_name,
time(origin_stop_time.arrival_time) AS origin_arrival_time,
time(origin_stop_time.departure_time) AS origin_depart_time,
date(origin_stop_time.departure_time) AS origin_depart_date,
Expand Down Expand Up @@ -93,7 +93,7 @@ def get_next_departure(self):
AND calendar.start_date <= :today
AND calendar.end_date >= :today
UNION ALL
SELECT trip.trip_id, trip.route_id,route.route_long_name,
SELECT trip.trip_id, trip.route_id,trip.trip_headsign,route.route_long_name,
time(origin_stop_time.arrival_time) AS origin_arrival_time,
time(origin_stop_time.departure_time) AS origin_depart_time,
date(origin_stop_time.departure_time) AS origin_depart_date,
Expand Down Expand Up @@ -211,7 +211,7 @@ def get_next_departure(self):
_LOGGER.debug(
"Timetable Remaining Departures on this Start/Stop: %s", timetable_remaining
)

# create upcoming timetable with line info
timetable_remaining_line = []
for key2, value in sorted(timetable.items()):
if datetime.datetime.strptime(key2, "%Y-%m-%d %H:%M:%S") > now:
Expand All @@ -222,6 +222,17 @@ def get_next_departure(self):
"Timetable Remaining Departures on this Start/Stop, per line: %s",
timetable_remaining_line,
)
# create upcoming timetable with headsign
timetable_remaining_headsign = []
for key2, value in sorted(timetable.items()):
if datetime.datetime.strptime(key2, "%Y-%m-%d %H:%M:%S") > now:
timetable_remaining_headsign.append(
str(key2) + " (" + str(value["trip_headsign"]) + ")"
)
_LOGGER.debug(
"Timetable Remaining Departures on this Start/Stop, with headsign: %s",
timetable_remaining_headsign,
)

# Format arrival and departure dates and times, accounting for the
# possibility of times crossing over midnight.
Expand Down Expand Up @@ -286,6 +297,7 @@ def get_next_departure(self):
"destination_stop_time": destination_stop_time,
"next_departures": timetable_remaining,
"next_departures_lines": timetable_remaining_line,
"next_departures_headsign": timetable_remaining_headsign,
}


Expand Down
4 changes: 2 additions & 2 deletions custom_components/gtfs2/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,6 @@
"documentation": "https://github.com/vingerha/gtfs2",
"iot_class": "local_polling",
"issue_tracker": "https://github.com/vingerha/gtfs2/issues",
"requirements": ["pygtfs==0.1.9","gtfs-realtime-bindings==1.0.0"],
"version": "0.1.2"
"requirements": ["pygtfs==0.1.9"],
"version": "0.1.5"
}
47 changes: 33 additions & 14 deletions custom_components/gtfs2/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
from homeassistant.util import slugify
import homeassistant.util.dt as dt_util

from .coordinator import GTFSRealtimeUpdateCoordinator

from .const import (
ATTR_ARRIVAL,
ATTR_BICYCLE,
Expand Down Expand Up @@ -64,22 +66,18 @@ async def async_setup_entry(
) -> None:
"""Initialize the setup."""
coordinator: GTFSUpdateCoordinator = hass.data[DOMAIN][config_entry.entry_id][
"coordinator"
"coordinator"
]

await coordinator.async_config_entry_first_refresh()

coordinator_rt: GTFSRealtimeUpdateCoordinator = hass.data[DOMAIN][config_entry.entry_id][
"coordinator"
]

await coordinator_rt.async_config_entry_first_refresh()

sensors = [
GTFSDepartureSensor(coordinator),
]

async_add_entities(sensors, False)




class GTFSDepartureSensor(CoordinatorEntity, SensorEntity):
Expand Down Expand Up @@ -375,6 +373,14 @@ def _update_attrs(self): # noqa: C901 PLR0911
self._attributes["next_departures_lines"] = self._departure[
"next_departures_lines"
][:10]

# Add next departures with their headsign
prefix = "next_departures_headsign"
self._attributes["next_departures_headsign"] = []
if self._next_departures:
self._attributes["next_departures_headsign"] = self._departure[
"next_departures_headsign"
][:10]

self._attributes["updated_at"] = dt_util.now().replace(tzinfo=None)
self._attr_extra_state_attributes = self._attributes
Expand Down Expand Up @@ -406,23 +412,36 @@ def remove_keys(self, prefix: str) -> None:
}


class GTFSRealtimeDepartureSensor(CoordinatorEntity, SensorEntity):
class GTFSRealtimeDepartureSensor(CoordinatorEntity):
"""Implementation of a GTFS departure sensor."""

def __init__(self, coordinator) -> None:
def __init__(self, coordinator: GTFSRealtimeUpdateCoordinator) -> None:
"""Initialize the GTFSsensor."""
super().__init__(coordinator)
self._name = coordinator.data["name"] + "_rt"
self._attributes: dict[str, Any] = {}

self._attr_unique_id = f"gtfs-{self._name}_rt"
self._attr_device_info = DeviceInfo(
name=f"GTFS - {self._name}",
entry_type=DeviceEntryType.SERVICE,
identifiers={(DOMAIN, f"GTFS - {self._name}_rt")},
manufacturer="GTFS",
model=self._name,
)
_LOGGER.debug("GTFS RT Sensor: coordinator data: %s", coordinator.data )
self._attributes = self._update_attrs()
self._coordinator = coordinator
self._attributes = self._update_attrs_rt()
self._attr_extra_state_attributes = self._attributes

@callback
def _handle_coordinator_update(self) -> None:
"""Handle updated data from the coordinator."""
self._update_attrs()
self._update_attrs_rt()
super()._handle_coordinator_update()

def _update_attrs(self): # noqa: C901 PLR0911
_LOGGER.debug(f"GTFS RT Sensor update attr DATA: {self.coordinator}")
self._attributes["next_departure_realtime"] = self.coordinator
def _update_attrs_rt(self): # noqa: C901 PLR0911
_LOGGER.debug(f"GTFS RT Sensor update attr DATA: {self._coordinator.data}")
self._attr_native_value = coordinator.data
self._attributes["next_departure_realtime"] = self._coordinator.data
return self._attributes
2 changes: 1 addition & 1 deletion custom_components/gtfs2/strings.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
"file": "New datasource name",
"url": "external url to gtfs data file"
},
"description": "NOTE: with a new url: this may take minutes after submit"
"description": "NOTE: with a new url/zip, this may take a long time after submit"
},
"remove": {
"data": {
Expand Down
2 changes: 1 addition & 1 deletion custom_components/gtfs2/translations/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
"file": "New datasource name",
"url": "external url to gtfs data (zip) file"
},
"description": "NOTE: with a new url, this may take quite a bit of time, \n depending on file-size and system performance"
"description": "NOTE: with a new url/zip, this may take quite a bit of time, \n depending on file-size and system performance"
},
"route": {
"data": {
Expand Down
2 changes: 1 addition & 1 deletion custom_components/gtfs2/translations/fr.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
"file": "Nom de la nouvelle source de données",
"url": "URL externe vers le fichier (zip) des données GTFS"
},
"description": "REMARQUE : avec une nouvelle URL, cela peut prendre du temps après la soumission, selon la taille du fichier et performance du serveur"
"description": "REMARQUE: avec une nouvelle URL/zip, cela peut prendre du temps après la soumission, \n selon la taille du fichier et performance du serveur"
},
"route": {
"data": {
Expand Down

0 comments on commit c90384f

Please sign in to comment.