Skip to content

Instantly share code, notes, and snippets.

@joeycastillo
Created June 26, 2019 23:13
Show Gist options
  • Save joeycastillo/cce7a48e46cf2678f6d22954cf4f8e62 to your computer and use it in GitHub Desktop.
Save joeycastillo/cce7a48e46cf2678f6d22954cf4f8e62 to your computer and use it in GitHub Desktop.
#!/path/to/venv/bin/python3
from google.transit import gtfs_realtime_pb2
import requests
import time
import os
import json
from dotenv import load_dotenv, find_dotenv
from protobuf_to_dict import protobuf_to_dict
# You should have a .env file in the same directory as this script with your MTA API key set as follows:
# API_KEY=00112233445566778899AABBCCDDEEFF
# Get an API key here: https://datamine.mta.info/user/register
# In the URL below, feed_id=2 is the L train.
# List of feeds: https://datamine.mta.info/list-of-feeds
load_dotenv(find_dotenv())
api_key = os.environ['API_KEY']
feed = gtfs_realtime_pb2.FeedMessage()
response = requests.get('http://datamine.mta.info/mta_esi.php?key={}&feed_id=2'.format(api_key))
feed.ParseFromString(response.content)
subway_feed = protobuf_to_dict(feed)
realtime_data = subway_feed['entity']
collected_times = []
def station_time_lookup(train_data, station):
for trains in train_data:
if trains.get('trip_update', False) != False:
unique_train_schedule = trains['trip_update']
unique_arrival_times = unique_train_schedule.get('stop_time_update', list())
for scheduled_arrivals in unique_arrival_times:
if scheduled_arrivals.get('stop_id', False) == station:
time_data = scheduled_arrivals['arrival']
unique_time = time_data['time']
if unique_time != None:
collected_times.append(unique_time)
# Run the above function for the station ID for Bedford Ave (Manhattan-bound is N, Brooklyn bound is S)
# List of stations: https://gist.github.com/konecnyna/07f0436ff8b4a89d9f814938b12a3c25
station_time_lookup(realtime_data, 'L08N')
collected_times.sort()
# output is just the current timestamp and a list of timestamps for upcoming trains
output = json.dumps({"time": int(time.time()), "data": collected_times}, indent=2)
print("Content-type: application/json; charset=utf-8")
print("Content-Length: {}\n".format(len(output)))
print(output, end='')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment