# Display a runtext with double-buffering.
from samplebase import SampleBase
from rgbmatrix import graphics
import time
from google.transit import gtfs_realtime_pb2
import urllib
import time
from operator import itemgetter
import threading
class RunText(SampleBase):
def __init__(self, *args, **kwargs):
super(RunText, self).__init__(*args, **kwargs)
def run(self):
global a_data
global f_data
state = False
offscreen_canvas = self.matrix.CreateFrameCanvas()
font = graphics.Font()
font.LoadFont("../../../fonts/5x8.bdf")
pos = offscreen_canvas.width
time_since_refresh = 0
time_since_state = 0
while True:
if state == True:
master_data = a_data
color = graphics.Color(0,57,166)
if state == False:
master_data = f_data
color = graphics.Color(100,39,10)
sorted_arrivals = sorted(master_data, key=itemgetter('arrival_time'))
offscreen_canvas = self.matrix.SwapOnVSync(offscreen_canvas)
offscreen_canvas.Clear()
# Current UNIX time
current_time = time.time()
i = 0
count = 0
while count < 4:
arrival = sorted_arrivals[i]
route_id = arrival['route_id']
arrival_time = arrival['arrival_time']
direction = arrival['direction']
minutes = int((arrival_time-current_time)/60)
i += 1
# ignore if train is at station
if minutes <= 0:
continue
graphics.DrawText(offscreen_canvas, font, 1, 7+(8*count), color, route_id)
graphics.DrawText(offscreen_canvas, font, 7, 7+(8*count), graphics.Color(255,255,255), direction)
offset = 11
if minutes >= 10:
offset += 5
graphics.DrawText(offscreen_canvas, font, offscreen_canvas.width - offset, 7+(8*count), graphics.Color(127,255,0), str(minutes) + "m")
count += 1
if time_since_refresh > 800:
f_data = getArrivals(station_codes, 21)
a_data = getArrivals(station_codes, 26)
time_since_refresh = 0
if time_since_state > 8:
state = not state
time_since_state = 0
time_since_refresh += 0.5
time_since_state += 0.5
time.sleep(0.5)
def getArrivals(station_codes, feed_id):
feed = gtfs_realtime_pb2.FeedMessage()
# get ACE routes
response = urllib.urlopen('http://datamine.mta.info/mta_esi.php?key=84167bd227ea2855b51d24072b701861&feed_id=' + str(feed_id))
feed.ParseFromString(response.read())
arrivals = []
for entity in feed.entity:
if entity.HasField('trip_update'):
for stop_time_update in entity.trip_update.stop_time_update:
if (stop_time_update.HasField('stop_id') and stop_time_update.stop_id in station_codes):
route_id = entity.trip_update.trip.route_id
arrival_time = stop_time_update.arrival.time
direction = stop_time_update.stop_id[-1:]
if direction == 'N':
direction = 'Uptown'
if direction == 'S':
direction = 'Downtown'
arrivals.append({'route_id': route_id, 'arrival_time': arrival_time, 'direction': direction})
return arrivals
# Main function
if __name__ == "__main__":
# W 4 Station Codes
# http://mtaapi.herokuapp.com/stations
station_codes = ["A32N","A32S","D20S","D20N"]
f_data = getArrivals(station_codes, 21)
a_data = getArrivals(station_codes, 26)
run_text = RunText()
if (not run_text.process()):
run_text.print_help()
No comments:
Post a Comment