forked from feuerrot/aseag-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain
More file actions
executable file
·160 lines (136 loc) · 4 KB
/
main
File metadata and controls
executable file
·160 lines (136 loc) · 4 KB
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
#!/usr/bin/env python3
import json
import http.client
import datetime
import sys
import os
DEBUG=False
defaultstop = 100636
stopfile = os.path.dirname(os.path.realpath(__file__)) + "/stops"
baseurl = "ivu.aseag.de"
url_s = "/interfaces/ura/stream_V1"
url_i = "/interfaces/ura/instant_V1"
filter = "?ReturnList=StopPointName,StopID,StopPointState,StopPointIndicator,Latitude,Longitude,VisitNumber,TripID,VehicleID,LineID,LineName,DirectionID,DestinationName,DestinationText,EstimatedTime,BaseVersion"
filter_s = "&StopID={}"
filter_l = "&LineID={}"
usage = 'Usage: {} [Stop] [BusIDs]'
infotext = "Haltestelle: {}\nHaltestellenID: {}\nLinienfilter: {}"
empty = "Das Problem an dem System, ja, ist das System, ja!"
if len(sys.argv) == 1 and defaultstop == 0:
print(usage.format(__file__))
exit(0)
def tstodatetime(ts):
return datetime.datetime.fromtimestamp(ts*(10**(-3)))
def tstodate(ts): #timestamp to date
return tstodatetime(ts).strftime('%Y-%m-%d %H:%M:%S')
def tstotime(ts): #timestamp to time
return tstodatetime(ts).strftime('%H:%M:%S')
def tsfilter(ts):
return tstodatetime(ts) >= datetime.datetime.now() - datetime.timedelta(minutes = 5)
def file2dict(fn): #file(name) to dict
rtn = dict()
with open(fn, 'r') as fh:
for line in fh:
(number, name) = line.split(' ', 1)
rtn[int(number)] = name.strip()
return rtn
def debug(text):
if DEBUG:
print(text)
stops = file2dict(stopfile)
def lookup_stop_by_name(name):
found = []
for elem in stops.items():
if DEBUG:
print(elem)
print(elem[1])
if name.lower() in elem[1].lower():
found.append(elem)
debug(found)
if len(found) == 1:
return found[0][0]
elif len(found) == 0:
print("{} is not a valid stop name".format(name))
exit(3)
else:
print("Found more than one match:")
for i in found:
print("{}".format(i[1]))
exit(4)
def parseargv(): #parses argv, returns StopID and LineID
query_stop = defaultstop
query_ids = []
argc = len(sys.argv)
if argc > 1:
for elem in sys.argv:
if (elem == __file__):
continue
if (len(elem) == 6 and elem.isdigit()):
query_stop = int(elem)
elif (1 <= len(elem) <= 3 and elem.isdigit()):
query_ids.append(elem)
elif elem == 'debug':
global DEBUG
DEBUG=True
elif elem.isprintable():
query_stop = lookup_stop_by_name(elem)
else:
print("Unknown parameter {!r}".format(elem))
query_ids.sort(key=int)
return (query_stop, query_ids)
def getjson(data):
(stop, ids) = data
stop_filter = filter_s.format(stop)
if (ids == []):
line_filter = ""
else:
line_filter = filter_l.format(",".join(ids))
url = "{}{}{}{}".format(url_i,filter,stop_filter,line_filter)
debug("URL: {}{}".format(baseurl, url))
connection = http.client.HTTPConnection(baseurl)
connection.request("GET", url)
response = connection.getresponse()
encoding = response.headers.get_content_charset()
jsondata = response.read().splitlines()
return (jsondata, encoding)
def parsejson(data):
(jsondata, encoding) = data
output = []
for line in jsondata:
linelist = json.loads(line.decode(encoding))
if (linelist[0] == 1):
output.append((linelist[15],linelist[8],linelist[12]))
output.sort(key=lambda tup: tup[0])
return output
# See: http://stackoverflow.com/questions/480214/how-do-you-remove-duplicates-from-a-list-in-python-whilst-preserving-order
def deduplication(data):
(jsondata, encoding) = data
seen = set()
seen_add = seen.add
jsondata = [x for x in jsondata if not (x in seen or seen_add(x))]
return (jsondata, encoding)
def info(data):
(stop, ids) = data
try:
halt = stops[stop].strip()
except:
print("Error: Invalid StopID")
exit(1)
haltid = stop
linien = " ".join(ids)
out = infotext.format(halt, haltid, linien)
debug(out)
data = parseargv()
debug('=== Start')
info(data)
debug('=== Get JSON')
jsondata = deduplication(getjson(data))
debug('=== Parse JSON')
output = parsejson(jsondata)
debug('=== Output')
if output == []:
debug(empty)
exit(2)
for line in output:
if tsfilter(line[0]):
print("{} {:>3} {}".format(tstotime(line[0]), line[1], line[2]))