-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathalert-iflows-decoder.py
More file actions
executable file
·144 lines (108 loc) · 4.34 KB
/
Copy pathalert-iflows-decoder.py
File metadata and controls
executable file
·144 lines (108 loc) · 4.34 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
#! /usr/bin/env /usr/bin/python
import sys, json, datetime, pytz, pymongo,time
from time import gmtime, strftime
class SystemVars():
firstRecordPrinted = False
def getCompletePacket():
BDFPacket = []
readCount = 0
while readCount < 4:
log('before readline')
line = sys.stdin.readline().rstrip()
if len(line) <= 0:
log("no more lines")
doExit(0)
reversedLine = line[::-1] # this is 'extended slice syntax'
if reversedLine[:2] == '01':
log('found {0} byte of station id'.format(readCount + 1))
if readCount < 2:
readCount += 1
BDFPacket.append(reversedLine[2:])
else:
log('skipping unexpected byte in bitstream')
readCount = 0
BDFPacket = []
continue
if reversedLine[:2] == '11':
log('fount {0} byte of value'.format(str(readCount - 1)))
if 2 <= readCount < 4:
readCount += 1
BDFPacket.append(reversedLine[2:])
else:
log('skipping unexpeted byte in bitstream')
readCount = 0
BDFPacket = []
continue
if readCount == 4:
#print('complete packet!')
return BDFPacket
def getJSON(station, value):
tz = pytz.timezone(strftime('%Z', gmtime()))
bdf = {
'stationID': station,
'value': value,
'datetime': datetime.datetime.now(tz=tz)
}
return bdf
def outputJson(station, value):
if SystemVars.firstRecordPrinted:
print(",")
print(json.dumps(getJSON(station, value), indent=2, sort_keys=True))
SystemVars.firstRecordPrinted = True
def outputText(station, value):
print("stationID: " + str(station))
print("value: " + str(value))
def insertToMongo(station, value):
col = db.receivedStations
col.insert(getJSON(station, value))
log('inserted mongo record stationID:{station}, value:{value}'.format(station=station, value=value))
from optparse import OptionParser
commandLineOptions = OptionParser()
commandLineOptions.set_usage("""
A decoder for ALERT(Automated Local Evaluation in Real Time) Binary Data Format (BDF) packets.
INPUT : one 8-bit binary string per line, as output from minimidem (http://www.whence.com/minimodem/minimodem.1.html),
read from stdin
OUTPUT : StationID and Value, to stdout (JSON or plain), also inserts to MongoDB
EXAMPLE: cat <some-binary-stream-file.txt> | {0}
""".format(sys.argv[0]))
commandLineOptions.add_option("--json-output", action="store_true", dest="jsonOutput", default=False,
help="Output JSON. Doesn't work with verbose.")
commandLineOptions.add_option("--verbose", action="store_true", dest="verbose", default=False,
help="Verbose logging. Only works with text output (the default).")
commandLineOptions.add_option("--mongo", action="store_true", dest="useMongo", default=False,
help="insert JSON data into a localhost mongodb instance")
commandLineOptions.add_option("--startup-delay", action="store", type="int", dest="startDelay", default=10,
help="wait N SECONDS before reading from stdin. Gives time for the pipes to get setup correctly")
(options, args) = commandLineOptions.parse_args()
def log(message):
if options.verbose and not options.jsonOutput:
print(message)
def doExit(code):
if options.jsonOutput:
print(']}')
exit(code)
mongoClient = None
db = None
if options.useMongo:
mongoClient = pymongo.MongoClient()
db = mongoClient.urbanDrainage
if sys.stdin.isatty():
commandLineOptions.print_usage()
commandLineOptions.print_help()
doExit(1)
else:
time.sleep(options.startDelay)
if options.jsonOutput:
print('{ "stations" : [ ')
while True:
packet = getCompletePacket()
stationBinaryStr = packet[2][-1] + packet[1] + packet[0]
valueBinaryStr = packet[3] + packet[2][:-1]
stationID = int(stationBinaryStr, 2)
stationValue = int(valueBinaryStr, 2)
if options.jsonOutput:
outputJson(stationID, stationValue)
elif options.useMongo:
insertToMongo(stationID, stationValue)
else:
outputText(stationID, stationValue)