Skip to content

Commit

Permalink
Further tune on local stops
Browse files Browse the repository at this point in the history
- reduce showing tomorrow slots for today
  • Loading branch information
vingerha committed Mar 22, 2024
1 parent 4e18b20 commit f625f79
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 28 deletions.
21 changes: 10 additions & 11 deletions custom_components/gtfs2/gtfs_helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -720,7 +720,6 @@ def get_local_stops_next_departures(self):
tomorrow_calendar_date_where = f"AND (calendar_date_today.date = date('now'))"
time_range = str('+' + str(self._data.get("timerange", DEFAULT_LOCAL_STOP_TIMERANGE)) + ' minute')
radius = self._data.get("radius", DEFAULT_LOCAL_STOP_RADIUS) / 130000
_LOGGER.debug("Time Range: %s", time_range)
if not latitude or not latitude:
_LOGGER.error("No latitude and/or longitude for : %s", self._data['device_tracker_id'])
return []
Expand All @@ -729,9 +728,7 @@ def get_local_stops_next_departures(self):
tomorrow_name = tomorrow.strftime("%A").lower()
tomorrow_select = f"calendar.{tomorrow_name} AS tomorrow,"
tomorrow_calendar_date_where = f"AND (calendar_date_today.date = date('now') or calendar_date_today.date = :tomorrow)"
tomorrow_select2 = f"'0' AS tomorrow,"
_LOGGER.debug("today: %s", now.strftime("%A").lower())
_LOGGER.debug("today: %s", tomorrow.strftime("%A").lower())
tomorrow_select2 = f"CASE WHEN date('now') < calendar_date_today.date THEN '1' else '0' END as tomorrow,"
sql_query = f"""
SELECT * FROM (
SELECT stop.stop_id, stop.stop_name,stop.stop_lat as latitude, stop.stop_lon as longitude, trip.trip_id, trip.trip_headsign, trip.direction_id, time(st.departure_time) as departure_time,
Expand Down Expand Up @@ -800,7 +797,9 @@ def get_local_stops_next_departures(self):
local_stops_list = []
prev_stop_id = ""
prev_entry = entry = {}
# params for getting rt data


# Set elements for realtime retrieval via local file.
if self._realtime:
self._rt_group = "trip"
self._rt_data = {
Expand All @@ -810,29 +809,29 @@ def get_local_stops_next_departures(self):
}
check = get_gtfs_rt(self.hass,DEFAULT_PATH_RT,self._rt_data)
# check if local file created
if not check:
if check != "ok":
_LOGGER.error("Could not download RT data from: %s", self._trip_update_url)
return False
else:
# use local file created as new url
self._trip_update_url = "file://" + DEFAULT_PATH_RT + "/" + self._data["name"] + "_localstop.rt"



for row_cursor in result:
row = row_cursor._asdict()
_LOGGER.debug("Row: %s", row)
_LOGGER.debug("Row from query: %s", row)
if row["stop_id"] != prev_stop_id and prev_stop_id != "":
local_stops_list.append(prev_entry)
timetable = []
entry = {"stop_id": row['stop_id'], "stop_name": row['stop_name'], "latitude": row['latitude'], "longitude": row['longitude'], "departure": timetable}
self._icon = ICONS.get(row['route_type'], ICON)
if row["today"] == 1 or row["today_cd"] == 1:
if row["today"] == 1 or (row["today_cd"] == 1 and row["start_date"] == row["calendar_date"]):
self._trip_id = row["trip_id"]
self._direction = str(row["direction_id"])
self._route = row['route_id']
self._route_id = row['route_id']
self._stop_id = row['stop_id']
departure_rt = "-"
# Find RT if configured
if self._realtime:
self._get_next_service = {}
_LOGGER.debug("Find rt for local stop route: %s - direction: %s - stop: %s", self._route , self._direction, self._stop_id)
Expand All @@ -847,7 +846,7 @@ def get_local_stops_next_departures(self):
"tomorrow" in row
and row["tomorrow"] == 1
and row["today"] == 0
and tomorrow_date <= row["end_date"]
#and tomorrow_date <= row["end_date"]
and now_time > row["departure_time"]
):
timetable.append({"departure": row["departure_time"], "date": tomorrow_date, "stop_name": row['stop_name'], "route": row["route_short_name"], "route_long": row["route_long_name"], "headsign": row["trip_headsign"], "trip_id": row["trip_id"], "direction_id": row["direction_id"], "icon": self._icon})
Expand Down
29 changes: 12 additions & 17 deletions custom_components/gtfs2/gtfs_rt_helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,14 +66,10 @@ def get_gtfs_feed_entities(url: str, headers, label: str):
if url.startswith('file'):
requests_session = requests.session()
requests_session.mount('file://', LocalFileAdapter())
response = requests_session.get(url)
_LOGGER.debug("Requests from file %s", response)

response = requests_session.get(url)
else:
response = requests.get(url, headers=headers, timeout=20)
_LOGGER.debug("Requests from url %s", response)


if response.status_code == 200:
_LOGGER.debug("Successfully updated %s", label)
else:
Expand Down Expand Up @@ -158,7 +154,7 @@ def get_rt_route_trip_statuses(self):
url=self._trip_update_url, headers=self._headers, label="trip data"
)
self._feed_entities = feed_entities
_LOGGER.debug("Departure times searching for all route: %s, type: %s", self._route_id, self._rt_group)
_LOGGER.debug("Search departure times for route: %s, type: %s", self._route_id, self._rt_group)
for entity in feed_entities:
if entity.HasField("trip_update"):

Expand Down Expand Up @@ -186,16 +182,12 @@ def get_rt_route_trip_statuses(self):
if ((self._rt_group == "route" and route_id == self._route_id and direction_id == self._direction) or
(self._rt_group == "trip" and trip_id == self._trip_id )):

_LOGGER.debug("Entity found params, group: %s, route_id: %s, direction_id: %s, trip_id: %s", self._rt_group, route_id, direction_id, self._trip_id)
_LOGGER.debug("Entity found params - group: %s, route_id: %s, direction_id: %s, trip_id: %s", self._rt_group, route_id, direction_id, self._trip_id)
_LOGGER.debug("Entity found: %s", entity.trip_update.trip)
_LOGGER.debug("Departure times before stop sel.: %s", departure_times)
for stop in entity.trip_update.stop_time_update:
_LOGGER.debug("Departure times, find self_stop_id: %s, in stop: %s", self._stop_id, stop.stop_id)
stop_id = stop.stop_id

# Use stop arrival time;
# fall back on departure time if not available
if stop_id == self._stop_id:
_LOGGER.debug("Stop found: %s", stop)
if route_id not in departure_times:
departure_times[route_id] = {}

Expand All @@ -205,19 +197,23 @@ def get_rt_route_trip_statuses(self):
if not departure_times[route_id][direction_id].get(
stop_id
):
departure_times[route_id][direction_id][stop_id] = []
departure_times[route_id][direction_id][stop_id] = []

# Use stop arrival time;
# fall back on departure time if not available
if stop.arrival.time == 0:
stop_time = stop.departure.time
else:
stop_time = stop.arrival.time

# Ignore arrival times in the past
_LOGGER.debug("Due in minutes: %s", due_in_minutes(datetime.fromtimestamp(stop_time)))

if due_in_minutes(datetime.fromtimestamp(stop_time)) >= 0:
departure_times[route_id][direction_id][
stop_id
].append(dt_util.as_utc(datetime.fromtimestamp(stop_time)))
_LOGGER.debug("Departure times: %s", departure_times)
else:
_LOGGER.debug("Not using realtime stop data for old due-in-minutes: %s", due_in_minutes(datetime.fromtimestamp(stop_time)))

# Sort by arrival time
for route in departure_times:
Expand Down Expand Up @@ -339,17 +335,16 @@ def get_gtfs_rt(hass, path, data):
return "ok"

class LocalFileAdapter(requests.adapters.HTTPAdapter):
"""Used to allow requests.get for local file"""
def build_response_from_file(self, request):
file_path = request.url[7:]
with open(file_path, 'rb') as file:
buff = bytearray(os.path.getsize(file_path))
file.readinto(buff)
resp = Resp(buff)
r = self.build_response(request, resp)

return r

def send(self, request, stream=False, timeout=None,
verify=True, cert=None, proxies=None):

return self.build_response_from_file(request)

0 comments on commit f625f79

Please sign in to comment.