-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpredictor.py
executable file
·46 lines (39 loc) · 1.33 KB
/
predictor.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import urllib.request
import json
import time
import datetime
class predictor:
__data = None
__last_fetch = 0.0
def __get_data(self):
data = None
try:
print('fetching data')
url = 'https://api-v3.mbta.com/predictions?filter[stop]=place-grnst&filter[direction_id]=0'
connection = urllib.request.urlopen(url)
data = json.loads(connection.read())
connection.close()
except:
print("error fetching feed")
finally:
if data is None:
raise ValueError('Network Error')
return data
def get_train_times(self):
currentTime = time.time()
if currentTime - self.__last_fetch > 15:
self.__data = self.__get_data()
self.__last_fetch = currentTime
ret = {
"alert":"",
"trains":[],
"time":0
}
for train in self.__data["data"]:
traindatetime = train["attributes"]["departure_time"]
if traindatetime:
traintimestamp = time.mktime(datetime.datetime.strptime(traindatetime, "%Y-%m-%dT%H:%M:%S%z").timetuple())
returntime = int(traintimestamp - currentTime)
ret["trains"].append(returntime)
ret["time"] = currentTime
return ret