-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathArgusProbe_Beamlogic.py
executable file
·331 lines (267 loc) · 10 KB
/
ArgusProbe_Beamlogic.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
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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
"""
Argus probe for the Beamlogic Site Analyzer Lite
http://www.beamlogic.com/products/802154-site-analyzer.aspx
"""
import time
import struct
import socket
import threading
import json
import Queue
import traceback
import datetime
import paho.mqtt.publish
import ArgusVersion
#============================ helpers =========================================
def currentUtcTime():
return time.strftime("%a, %d %b %Y %H:%M:%S UTC", time.gmtime())
def logCrash(threadName, err):
output = []
output += ["============================================================="]
output += [currentUtcTime()]
output += [""]
output += ["CRASH in Thread {0}!".format(threadName)]
output += [""]
output += ["=== exception type ==="]
output += [str(type(err))]
output += [""]
output += ["=== traceback ==="]
output += [traceback.format_exc()]
output = '\n'.join(output)
print output
#============================ classes =========================================
class RxSnifferThread(threading.Thread):
"""
Thread which attaches to the sniffer and parses incoming frames.
"""
PCAP_GLOBALHEADER_LEN = 24 # 4+2+2+4+4+4+4
PCAP_PACKETHEADER_LEN = 16 # 4+4+4+4
BEAMLOGIC_HEADER_LEN = 20 # 1+8+1+1+4+4+1
PIPE_SNIFFER = r'\\.\pipe\analyzer'
def __init__(self, txMqttThread):
# store params
self.txMqttThread = txMqttThread
# local variables
self.dataLock = threading.Lock()
self.rxBuffer = []
self.doneReceivingGlobalHeader = False
self.doneReceivingPacketHeader = False
# start the thread
threading.Thread.__init__(self)
self.name = 'RxSnifferThread'
self.start()
def run(self):
try:
time.sleep(1) # let the banners print
while True:
try:
with open(self.PIPE_SNIFFER, 'rb') as sniffer:
while True:
b = ord(sniffer.read(1))
self._newByte(b)
except IOError:
print "WARNING: Could not read from pipe at \"{0}\".".format(
self.PIPE_SNIFFER
)
print "Is SiteAnalyzerAdapter running?"
time.sleep(1)
except Exception as err:
logCrash(self.name, err)
#======================== public ==========================================
#======================== private =========================================
def _newByte(self, b):
"""
Just received a byte from the sniffer
"""
with self.dataLock:
self.rxBuffer += [b]
# PCAP global header
if not self.doneReceivingGlobalHeader:
if len(self.rxBuffer) == self.PCAP_GLOBALHEADER_LEN:
self.doneReceivingGlobalHeader = True
self.rxBuffer = []
# PCAP packet header
elif not self.doneReceivingPacketHeader:
if len(self.rxBuffer) == self.PCAP_PACKETHEADER_LEN:
self.doneReceivingPacketHeader = True
self.packetHeader = self._parsePcapPacketHeader(self.rxBuffer)
assert self.packetHeader['incl_len'] == self.packetHeader['orig_len']
self.rxBuffer = []
# PCAP packet bytes
else:
if len(self.rxBuffer) == self.packetHeader['incl_len']:
self.doneReceivingPacketHeader = False
self._newFrame(self.rxBuffer)
self.rxBuffer = []
def _parsePcapPacketHeader(self, header):
"""
Parse a PCAP packet header
Per https://wiki.wireshark.org/Development/LibpcapFileFormat:
typedef struct pcaprec_hdr_s {
guint32 ts_sec; /* timestamp seconds */
guint32 ts_usec; /* timestamp microseconds */
guint32 incl_len; /* number of octets of packet saved in file */
guint32 orig_len; /* actual length of packet */
} pcaprec_hdr_t;
"""
assert len(header) == self.PCAP_PACKETHEADER_LEN
returnVal = {}
(
returnVal['ts_sec'],
returnVal['ts_usec'],
returnVal['incl_len'],
returnVal['orig_len'],
) = struct.unpack('<IIII', ''.join([chr(b) for b in header]))
return returnVal
def _newFrame(self, frame):
"""
Just received a full frame from the sniffer
"""
# transform frame
frame = self._transformFrame(frame)
# publish frame
self.txMqttThread.publishFrame(frame)
def _transformFrame(self, frame):
"""
Replace BeamLogic header by ZEP header.
"""
beamlogic = self._parseBeamlogicHeader(frame[:self.BEAMLOGIC_HEADER_LEN])
ieee154 = frame[self.BEAMLOGIC_HEADER_LEN:beamlogic['Length']+self.BEAMLOGIC_HEADER_LEN]
zep = self._formatZep(
channel = beamlogic['Channel'],
timestamp = beamlogic['TimeStamp'],
length = beamlogic['Length'],
rssi = beamlogic['RSSI']
)
return zep+ieee154
def _parseBeamlogicHeader(self, header):
"""
Parse a Beamlogic header
uint64 TimeStamp
uint8 Channel
uint8 RSSI
uint32 GpsLat
uint32 GpsLong
"""
assert len(header) == self.BEAMLOGIC_HEADER_LEN
returnVal = {}
(
returnVal['Reserved'],
returnVal['TimeStamp'],
returnVal['Channel'],
returnVal['RSSI'],
returnVal['GpsLat'],
returnVal['GpsLong'],
returnVal['Length'],
) = struct.unpack('<BQBBIIB', ''.join([chr(b) for b in header]))
return returnVal
def _formatZep(self, channel, timestamp, length, rssi):
return [
0x45, 0x58, # Preamble
0x02, # Version
0x01, # Type (Data)
channel, # Channel ID
0x00, 0x01, # Device ID
0x01, # CRC/LQI Mode
0xff, # LQI Val
] + \
[ # NTP Timestamp
ord(b) for b in struct.pack('>Q', self._get_ntp_timestamp())
] + \
[ # Sequence number
0x02, 0x02, 0x02, 0x02] + \
[ # Reserved Beam logic Timestamp (1/3 of us)
ord(b) for b in struct.pack('>Q', timestamp)] + \
[ # Reserved
rssi,
0x00
] + \
[
length,
]
@staticmethod
def _get_ntp_timestamp():
diff = datetime.datetime.utcnow() - datetime.datetime(1900, 1, 1, 0, 0, 0)
return diff.days * 24 * 60 * 60 + diff.seconds
class TxMqttThread(threading.Thread):
"""
Thread which publishes sniffed frames to the MQTT broker.
"""
MQTT_BROKER_HOST = 'argus.paris.inria.fr'
MQTT_BROKER_PORT = 1883
MQTT_BROKER_TOPIC = 'inria-paris/beamlogic'
def __init__(self):
# local variables
self.txQueue = Queue.Queue(maxsize=100)
# start the thread
threading.Thread.__init__(self)
self.name = 'TxMqttThread'
self.start()
def run(self):
try:
while True:
# wait for first frame
msgs = [self.txQueue.get(), ]
# get other frames (if any)
try:
while True:
msgs += [self.txQueue.get(block=False)]
except Queue.Empty:
pass
# add topic
msgs = [
{
'topic': 'argus/{0}'.format(self.MQTT_BROKER_TOPIC),
'payload': m,
} for m in msgs
]
# publish
try:
paho.mqtt.publish.multiple(
msgs,
hostname = self.MQTT_BROKER_HOST,
port = self.MQTT_BROKER_PORT,
)
except Exception as err:
print "WARNING publication to {0}:{1} over MQTT failed ({2})".format(
self.MQTT_BROKER_HOST,
self.MQTT_BROKER_PORT,
str(type(err)),
)
except Exception as err:
logCrash(self.name, err)
#======================== public ==========================================
def publishFrame(self, frame):
msg = {
'description': 'zep',
'device': 'Beamlogic',
'bytes': ''.join(['{0:02x}'.format(b) for b in frame]),
}
try:
self.txQueue.put(json.dumps(msg), block=False)
except Queue.Full:
print "WARNING transmit queue to MQTT broker full. Dropping frame."
#======================== private =========================================
class CliThread(object):
def __init__(self):
try:
print 'ArgusProbe (for BeamLogic sniffer) {0}.{1}.{2}.{3} - (c) OpenWSN project'.format(
ArgusVersion.VERSION[0],
ArgusVersion.VERSION[1],
ArgusVersion.VERSION[2],
ArgusVersion.VERSION[3],
)
while True:
user_input = raw_input('>')
print user_input,
except Exception as err:
logCrash('CliThread', err)
#============================ main ============================================
def main():
# parse parameters
# start thread
txMqttThread = TxMqttThread()
rxSnifferThread = RxSnifferThread(txMqttThread)
cliThread = CliThread()
if __name__ == "__main__":
main()