Skip to content

Commit

Permalink
Adding option to extract rt-trip data locally
Browse files Browse the repository at this point in the history
Note: Use of local rt-trip still to be built
  • Loading branch information
vingerha committed Dec 4, 2023
1 parent 1254004 commit 0d50d19
Show file tree
Hide file tree
Showing 6 changed files with 89 additions and 9 deletions.
27 changes: 25 additions & 2 deletions custom_components/gtfs2/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,11 @@
from datetime import timedelta

from .const import DOMAIN, PLATFORMS, DEFAULT_PATH, DEFAULT_REFRESH_INTERVAL
from homeassistant.const import CONF_HOST
from .coordinator import GTFSUpdateCoordinator
import voluptuous as vol
from .gtfs_helper import get_gtfs
from .gtfs_rt_helper import get_gtfs_rt_trip

_LOGGER = logging.getLogger(__name__)

Expand Down Expand Up @@ -107,19 +109,40 @@ async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
hass.data[DOMAIN].pop(entry.entry_id)

return unload_ok


async def async_remove_entry(hass: HomeAssistant, entry: ConfigEntry) -> None:
"""Remove a config entry."""
await hass.async_add_executor_job(_remove_token_file, hass, entry.data[CONF_HOST])
if DOMAIN in hass.data:
hass.data[DOMAIN].pop(entry.entry_id, None)
if not hass.data[DOMAIN]:
hass.data.pop(DOMAIN)

def setup(hass, config):
"""Setup the service example component."""
"""Setup the service component."""

def update_gtfs(call):
"""My GTFS service."""
_LOGGER.debug("Updating GTFS with: %s", call.data)
get_gtfs(hass, DEFAULT_PATH, call.data, True)
return True

def download_gtfs_rt_trip(call: ServiceCall):
"""My GTFS service."""
_LOGGER.debug("Updating GTFS with: %s", call.data)
_LOGGER.debug("Updating GTFS with entity: %s", dir(call))
_LOGGER.debug("Updating GTFS with entity2: %s", dir(call.context))
_LOGGER.debug("Updating GTFS with entity3: %s", call.return_response)
_LOGGER.debug("Updating GTFS with entity4: %s", call.service)


get_gtfs_rt_trip(hass, DEFAULT_PATH, call.data)
return True

hass.services.register(
DOMAIN, "update_gtfs", update_gtfs)
hass.services.register(
DOMAIN, "download_gtfs_rt_trip", download_gtfs_rt_trip)
return True

async def update_listener(hass: HomeAssistant, entry: ConfigEntry):
Expand Down
7 changes: 3 additions & 4 deletions custom_components/gtfs2/coordinator.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,10 +123,9 @@ async def _async_update_data(self) -> dict[str, str]:
self._headers = None
self._headers = None
self.info = {}
try:
self._route_id = self._data["next_departure"]["route_id"]
except Exception as ex: # pylint: disable=broad-except
_LOGGER.error("Error getting entity route_id for realtime data, for origin: %s with error: %s", data["origin"], ex)
self._route_id = self._data["next_departure"].get("route_id", None)
if self._route_id == None:
_LOGGER.debug("GTFS RT: no route_id in sensor data, using route_id from config_entry")
self._route_id = data["route"].split(": ")[0]
self._stop_id = data["origin"].split(": ")[0]
self._destination_id = data["destination"].split(": ")[0]
Expand Down
16 changes: 15 additions & 1 deletion custom_components/gtfs2/gtfs_rt_helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -396,7 +396,6 @@ def get_rt_alerts(self):
label="alerts",
)
for entity in feed_entities:
_LOGGER.debug("RT Alert entity: %s", entity)
if entity.HasField("alert"):
for x in entity.alert.informed_entity:
if x.HasField("stop_id"):
Expand Down Expand Up @@ -428,6 +427,21 @@ def update_geojson(self):
_LOGGER.debug("GTFS RT geojson file: %s", file)
with open(file, "w") as outfile:
json.dump(self.geojson, outfile)

def get_gtfs_rt_trip(hass, path, data):
"""Get gtfs rt trip data"""
_LOGGER.debug("Getting gtfs rt trip with data: %s", data)
gtfs_dir = hass.config.path(path)
os.makedirs(gtfs_dir, exist_ok=True)
url = data["url"]
file = data["entity_id"][0].split('.')[1] + "_rt.trip"
try:
r = requests.get(url, allow_redirects=True)
open(os.path.join(gtfs_dir, file), "wb").write(r.content)
except Exception as ex: # pylint: disable=broad-except
_LOGGER.error("The given URL or GTFS data file/folder was not found")
return "no_data_file"
return None



2 changes: 1 addition & 1 deletion custom_components/gtfs2/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -346,7 +346,7 @@ def _update_attrs(self): # noqa: C901 PLR0911
if "destination_stop_time" in self._departure:
_LOGGER.debug("Destination_stop_time %s", self._departure["destination_stop_time"])
else:
_LOGGER.warning("No destination_stop_time")
_LOGGER.debug("No destination_stop_time, possibly no service today")
prefix = "destination_stop"
if self._departure:
self.append_keys(self._departure["destination_stop_time"], prefix)
Expand Down
30 changes: 30 additions & 0 deletions custom_components/gtfs2/services.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,33 @@ update_gtfs:
example: "https://path-to-my-zip-file-location/filename.zip"
selector:
text:
download_gtfs_rt_trip:
name: Downloads GTFS RealTime Trip Data
description: Stored in gtfs2 folder
fields:
entity_id:
name: Name of the transport service
description: the existing one will be overwitten
required: false
example: "mytransportservice"
selector:
entity:
multiple: false
domain: sensor
integration: gtfs2
url:
name: URL
description: provide the full path to the zip file itself
required: true
default: "na"
example: "https://path-to-my-rt-trip-data"
selector:
text:
file:
name: Name of the file, without extension
description: the existing one will be overwitten
required: true
example: "mytransportservice"
selector:
text:

16 changes: 15 additions & 1 deletion custom_components/gtfs2/translations/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,20 @@
"description": "provide the full path to the zip file itself"
}
}
},
"download_gtfs_rt_trip": {
"name": "Retrieves a GTFS rt trip datasource locally",
"description": "",
"fields": {
"file": {
"name": "Name of the transport service",
"description": "the existing one will be overwitten"
},
"url": {
"name": "URL",
"description": "provide the full path"
}
}
}
}
}
}

0 comments on commit 0d50d19

Please sign in to comment.