Skip to content

Commit dffee84

Browse files
committed
Code komplett umgeschrieben, kein pickle mehr.
1 parent f7e33e0 commit dffee84

File tree

3 files changed

+1137
-40
lines changed

3 files changed

+1137
-40
lines changed

haltestellen.pickle

-104 Bytes
Binary file not shown.

main

Lines changed: 77 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -3,61 +3,98 @@ import json
33
import http.client
44
import datetime
55
import sys
6-
import pickle
76
import os
87

9-
def tstodate(ts):
8+
DEBUG=False
9+
defaultstop = "100636"
10+
11+
stopfile = os.path.dirname(os.path.realpath(__file__)) + "/stops"
12+
baseurl = "ivu.aseag.de"
13+
url_s = "/interfaces/ura/stream_V1"
14+
url_i = "/interfaces/ura/instant_V1"
15+
filter = "?ReturnList=StopPointName,StopID,StopPointState,StopPointIndicator,Latitude,Longitude,VisitNumber,TripID,VehicleID,LineID,LineName,DirectionID,DestinationName,DestinationText,EstimatedTime,BaseVersion"
16+
filter_s = "&StopID={}"
17+
filter_l = "&LineID={}"
18+
19+
if len(sys.argv) == 1:
20+
print('Usage: {} [Stop] [Bus IDs]'.format(__file__))
21+
22+
def tstodate(ts): #timestamp to date
1023
return datetime.datetime.fromtimestamp(ts*(10**(-3))).strftime('%Y-%m-%d %H:%M:%S')
1124

12-
def tstotime(ts):
25+
def tstotime(ts): #timestamp to time
1326
return datetime.datetime.fromtimestamp(ts*(10**(-3))).strftime('%H:%M:%S')
1427

15-
haltestellenfile= open(os.path.dirname(os.path.realpath(__file__)) + "/haltestellen.pickle",'rb')
16-
baseurl = "ivu.aseag.de"
17-
baseurl_stream = "/interfaces/ura/stream_V1"
18-
baseurl_instant = "/interfaces/ura/instant_V1"
19-
url_filter = "?ReturnList=StopPointName,StopID,StopCode1,StopCode2,StopPointState,StopPointType,StopPointIndicator,Towards,Bearing,Latitude,Longitude,VisitNumber,TripID,VehicleID,RegistrationNumber,LineID,LineName,DirectionID,DestinationText,DestinationName,EstimatedTime,MessageUUID,MessageText,MessageType,MessagePriority,BaseVersion"
20-
url_filter_stop = "&StopID="
28+
def file2dict(fn): #file(name) to dict
29+
rtn = dict()
30+
with open(fn, 'r') as fh:
31+
for line in fh:
32+
(number, name) = line.split(' ', 1)
33+
rtn[number] = name
34+
return rtn
35+
36+
def debug(text):
37+
if DEBUG:
38+
print(text)
39+
40+
stops = file2dict(stopfile)
2141

22-
haltestellen = pickle.load(haltestellenfile)
42+
def parseargv(): #parses argv, returns StopID and LineID
43+
query_stop = defaultstop
44+
query_ids = []
45+
argc = len(sys.argv)
46+
if argc > 1:
47+
for elem in sys.argv:
48+
if (elem == __file__):
49+
continue
50+
if (len(elem) == 6 and elem.isdigit()):
51+
query_stop = elem
52+
elif (1 <= len(elem) <= 3 and elem.isdigit()):
53+
query_ids.append(elem)
54+
else:
55+
print("Wait, what?: {}".format(elem))
56+
query_ids.sort(key=int)
57+
return (query_stop, query_ids)
2358

24-
try:
25-
tmp = sys.argv[1]
26-
if tmp in haltestellen:
27-
haltestelle = str(haltestellen[tmp])
59+
def getjson():
60+
(stop, ids) = parseargv()
61+
stop_filter = filter_s.format(stop)
62+
if (ids == []):
63+
line_filter = ""
2864
else:
29-
haltestelle = tmp
30-
except:
31-
haltestelle = "100636"
65+
line_filter = filter_l.format(",".join(ids))
66+
url = "{}{}{}{}".format(url_i,filter,stop_filter,line_filter)
3267

33-
try:
34-
busfilter = sys.argv[2]
35-
except:
36-
busfilter = None
68+
connection = http.client.HTTPConnection(baseurl)
69+
connection.request("GET", url)
3770

38-
jsondecoder = json.JSONDecoder()
71+
response = connection.getresponse()
72+
encoding = response.headers.get_content_charset()
73+
jsondata = response.read().splitlines()
3974

40-
connection = http.client.HTTPConnection(baseurl)
41-
connection.request("GET", baseurl_instant + url_filter + url_filter_stop + haltestelle)
75+
return (jsondata, encoding)
4276

43-
response = connection.getresponse()
44-
encoding = response.headers.get_content_charset()
77+
def parsejson(data):
78+
(jsondata, encoding) = data
79+
output = []
80+
for line in jsondata:
81+
linelist = json.loads(line.decode(encoding))
82+
if (linelist[0] == 1):
83+
output.append((linelist[15],linelist[8],linelist[12]))
84+
output.sort(key=lambda tup: tup[0])
85+
return output
4586

46-
info = response.read().splitlines()
4787

48-
ausgabe = []
88+
debug('=== Start')
89+
(query_stop, query_ids) = parseargv()
90+
debug("Haltestelle: {}\nHaltestellenID: {}\nLinien: {}".format(stops[query_stop].strip(),query_stop," ".join(query_ids)))
4991

50-
for line in info:
51-
linearray = json.loads(line.decode(encoding))
92+
debug('=== Get JSON')
93+
jsondata = getjson()
5294

53-
#Es ist nur eine Fahrplaninfo, wenn das erste Feld 0 ist
54-
if (linearray[0] == 1):
55-
# 21 = Zeit, 13 = Busnummer, 16 = Ziel
56-
formatinput = (linearray[21], linearray[13], linearray[16])
57-
ausgabe.append(formatinput)
95+
debug('=== Parse JSON')
96+
output = parsejson(jsondata)
5897

59-
#Sortierung nach der Zeit
60-
ausgabe.sort(key=lambda tup: tup[0])
61-
for elem in ausgabe:
62-
if (busfilter == None or busfilter == elem[1]):
63-
print("%s %s %s" % (tstotime(elem[0]), elem[1], elem[2]))
98+
debug('=== Output')
99+
for line in output:
100+
print("{} {} {}".format(tstotime(line[0]), line[1], line[2]))

0 commit comments

Comments
 (0)