-
Notifications
You must be signed in to change notification settings - Fork 35
/
ieee15dot4.py
507 lines (409 loc) · 18.1 KB
/
ieee15dot4.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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
#!/usr/bin/env python
"""
ieee15dot4 - a python module defining IEEE 802.15.4 MAC frames
Copyright (c) 2014, Andrew Dodd ([email protected])
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software Foundation,
Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
"""
import binascii
import struct
from datetime import datetime
#http://stackoverflow.com/questions/36932/how-can-i-represent-an-enum-in-python
# Usage: Numbers = enum('ZERO', 'ONE', 'TWO')
# Numbers = enum(ONE=1, TWO=2, THREE='three')
# Numbers.ONE
# Numbers.fromValue['three']
def enum(*sequential, **named):
"""Build a new type that mocks an ENUM"""
enums = dict(list(zip(sequential, list(range(len(sequential))))), **named)
reverse = dict((value, key) for key, value in list(enums.items()))
enums['fromValue'] = reverse
return type('Enum', (), enums)
def checkAndUnpack(fmt, buffer, offset, default):
"""Checks that there are enough bytes in the buffer before unpacking
This function uses the provided format string to check if there are
enough bytes to unpack from the buffer. If not it returns the default
provided."""
if len(buffer[offset:]) < struct.calcsize(fmt):
return default
return struct.unpack_from(fmt, buffer, offset)
class FrameType(object):
BEACON = 0
DATA = 1
ACK = 2
MAC_CMD = 3
LLDN = 4
MULTIPURPOSE = 5
UNKNOWN = 255
MASK = 7
@staticmethod
def classify(value):
maskedValue = (FrameType.MASK & value)
if maskedValue is FrameType.BEACON:
return FrameType.BEACON
if maskedValue is FrameType.DATA:
return FrameType.DATA
if maskedValue is FrameType.ACK:
return FrameType.ACK
if maskedValue is FrameType.MAC_CMD:
return FrameType.MAC_CMD
if maskedValue is FrameType.LLDN:
return FrameType.LLDN
if maskedValue is FrameType.MULTIPURPOSE:
FrameType.MULTIPURPOSE
return FrameType.UNKNOWN
@staticmethod
def toString(value):
if value is FrameType.BEACON:
return "Beacon"
if value is FrameType.DATA:
return "Data"
if value is FrameType.ACK:
return "Acknowledgment"
if value is FrameType.MAC_CMD:
return "MAC Command"
if value is FrameType.LLDN:
return "LLDN"
if value is FrameType.MULTIPURPOSE:
return "Multipurpose"
return "Unknown"
class AddressingMode(object):
NONE = 0
SIMPLE = 1
SHORT = 2
EXTENDED = 3
UNKNOWN = 255
MASK = 3
@staticmethod
def classify(value):
if (AddressingMode.NONE == (AddressingMode.MASK & value)):
return AddressingMode.NONE
if (AddressingMode.SIMPLE == (AddressingMode.MASK & value)):
return AddressingMode.SIMPLE
if (AddressingMode.SHORT == (AddressingMode.MASK & value)):
return AddressingMode.SHORT
if (AddressingMode.EXTENDED == (AddressingMode.MASK & value)):
return AddressingMode.EXTENDED
return AddressingMode.UNKNOWN
@staticmethod
def toString(value):
if (AddressingMode.NONE == value):
return "None"
if (AddressingMode.SIMPLE == value):
return "Simple"
if (AddressingMode.SHORT == value):
return "Short"
if (AddressingMode.EXTENDED == value):
return "Extended"
raise ValueError(value)
class FCF(object):
def __init__(self, frametype, securityEnabled, framePending, ackRequested,
panIDCompression, destAddressingMode, frameVersion,
sourceAddressingMode):
self.frametype = frametype
self.securityEnabled = securityEnabled
self.framePending = framePending
self.ackRequested = ackRequested
self.panIdCompression = panIDCompression
self.destAddressingMode = destAddressingMode
self.frameVersion = frameVersion
self.sourceAddressingMode = sourceAddressingMode
@staticmethod
def parse(fcf):
return FCF(
FrameType.classify(fcf), # FrameType.MASK & value
bool((fcf >> 3) & 0x01),
bool((fcf >> 4) & 0x01),
bool((fcf >> 5) & 0x01),
bool((fcf >> 6) & 0x01),
# 7-9: reserved
AddressingMode.classify(fcf >> 10),
(fcf >> 12) & 0x03,
AddressingMode.classify(fcf >> 14))
class SFS(object):
def __init__(self, beaconOrder, superframeOrder, finalCAPSlot, ble,
isPANCoordinator, isAssociationPermitted):
self.beaconOrder = beaconOrder
self.superframeOrder = superframeOrder
self.finalCAPSlot = finalCAPSlot
self.ble = ble
self.isPANCoordinator = isPANCoordinator
self.isAssociationPermitted = isAssociationPermitted
def __repr__(self, *args, **kwargs):
return "SFS[BO[{}] SO[{}]]".format(self.beaconOrder,
self.superframeOrder)
@staticmethod
def parse(sfs):
return SFS(0x0F & sfs, 0x0F & (sfs >> 4), 0x0F & (sfs >> 8),
bool(0x01 & (sfs >> 12)), bool(0x01 & (sfs >> 14)),
bool(0x01 & (sfs >> 15)))
class SimpleAddress(object):
def __init__(self, panId, simpleAddress):
self.panId = panId
self.address = simpleAddress
def __repr__(self, *args, **kwargs):
return "PAN[{:x}] SimpleAddr[{:x}]".format(self.panId, self.address)
class ShortAddress(object):
def __init__(self, panId, shortAddress):
self.panId = panId
self.address = shortAddress
def __repr__(self, *args, **kwargs):
return "PAN[{:x}] ShortAddr[{:x}]".format(self.panId, self.address)
class ExtendedAddress(object):
def __init__(self, panId, extAddress):
self.panId = panId
self.address = extAddress
def __repr__(self, *args, **kwargs):
return "PAN[{:x}] ExtAddr[{:x}]".format(self.panId, self.address)
class AddressingFields(object):
def __init__(self, length, destinationAddress, sourceAddress):
self.length = length
self.destinationAddress = destinationAddress
self.sourceAddress = sourceAddress
def __repr__(self, *args, **kwargs):
output = []
if self.destinationAddress is not None:
output.append("Destination[{}]".format(self.destinationAddress))
if self.sourceAddress is not None:
output.append("Source[{}]".format(self.sourceAddress))
return "Addresses[{}]".format(" ".join(output))
@staticmethod
def parse(fcf, byteStreamAtAddresses):
length = 0
if fcf.destAddressingMode is AddressingMode.NONE:
destinationAddress = None
else:
(destPANId, ) = struct.unpack_from("<H", byteStreamAtAddresses,
length)
length += 2
if fcf.destAddressingMode is AddressingMode.SIMPLE:
(destSimpleId, ) = struct.unpack_from("<B", byteStreamAtAddresses,
length)
destinationAddress = SimpleAddress(destPANId, destSimpleId)
length += 1
if fcf.destAddressingMode is AddressingMode.SHORT:
(destShortId, ) = struct.unpack_from("<H", byteStreamAtAddresses,
length)
destinationAddress = ShortAddress(destPANId, destShortId)
length += 2
if fcf.destAddressingMode is AddressingMode.EXTENDED:
(destExtId, ) = struct.unpack_from("<Q", byteStreamAtAddresses,
length)
destinationAddress = ExtendedAddress(destPANId, destExtId)
length += 8
if fcf.sourceAddressingMode is AddressingMode.NONE:
sourceAddress = None
else:
if False is fcf.panIdCompression:
(srcPANId, ) = struct.unpack_from("<H", byteStreamAtAddresses,
length)
length += 2
else:
if fcf.destAddressingMode is AddressingMode.NONE:
print("error, pan compression but no destination address!")
destPANId = None
srcPANId = destPANId
if fcf.sourceAddressingMode is AddressingMode.SIMPLE:
(srcSimpleId, ) = struct.unpack_from("<B", byteStreamAtAddresses,
length)
sourceAddress = SimpleAddress(srcPANId, srcSimpleId)
length += 1
if fcf.sourceAddressingMode is AddressingMode.SHORT:
(srcShortId, ) = struct.unpack_from("<H", byteStreamAtAddresses,
length)
sourceAddress = ShortAddress(srcPANId, srcShortId)
length += 2
if fcf.sourceAddressingMode is AddressingMode.EXTENDED:
(srcExtId, ) = struct.unpack_from("<Q", byteStreamAtAddresses,
length)
sourceAddress = ExtendedAddress(srcPANId, srcExtId)
length += 8
return AddressingFields(length, destinationAddress, sourceAddress)
class IEEE15dot4Frame(object):
def __init__(self, timestamp, fcf, sequenceNumber, addressing, msdu, *args,
**kwargs):
self.time = datetime.now()
self.timestamp = timestamp
self.fcf = fcf
self.sequenceNumber = sequenceNumber
self.addressing = addressing
self.msdu = msdu
def __repr__(self, *args, **kwargs):
output = []
output.append("{} -".format(FrameType.toString(self.fcf.frametype)))
output.append("Time[{}]".format(self.time))
output.append("TS[{}]".format(self.timestamp))
output.append("{}".format(self.addressing))
output.append("MSDU[{}]".format(binascii.hexlify(self.msdu)))
return " ".join(output)
class IEEE15dot4AckFrame(IEEE15dot4Frame):
def __init__(self, *args, **kwargs):
super(IEEE15dot4AckFrame, self).__init__(*args, **kwargs)
def __repr__(self, *args, **kwargs):
output = []
output.append("{} -".format(FrameType.toString(self.fcf.frametype)))
output.append("SeqNum[{}]".format(self.sequenceNumber))
return " ".join(output)
class IEEE15dot4BeaconFrame(IEEE15dot4Frame):
def __init__(self, sfs, gts, pendingShortAddresses, pendingExtAddresses,
beaconPayload, *args, **kwargs):
super(IEEE15dot4BeaconFrame, self).__init__(*args, **kwargs)
self.sfs = sfs
self.gts = gts
self.pendingShortAddresses = pendingShortAddresses
self.pendingExtAddresses = pendingExtAddresses
self.beaconPayload = beaconPayload
def __repr__(self, *args, **kwargs):
output = []
output.append("{} -".format(FrameType.toString(self.fcf.frametype)))
output.append("Time[{}]".format(self.time))
output.append("TS[{}]".format(self.timestamp))
output.append("{}".format(self.sfs))
output.append("{}".format(self.addressing))
if len(self.pendingShortAddresses) > 0:
addresses = [
"{:x}".format(addr) for addr in self.pendingShortAddresses
]
output.append("PendingShort[{}]".format(",".join(addresses)))
if len(self.pendingExtAddresses) > 0:
addresses = [
"{:x}".format(addr) for addr in self.pendingExtAddresses
]
output.append("PendingExt[{}]".format(",".join(addresses)))
output.append("Payload[{}]".format(binascii.hexlify(
self.beaconPayload)))
return " ".join(output)
CommandFrameType = enum(AssociationRequest=1,
AssociationResponse=2,
DisassociationNotification=3,
DataRequest=4,
PANIdConflictNotification=5,
OrphanNotification=6,
BeaconRequest=7,
CoordinatorRealignment=8,
GTSRequest=9)
class IEEE15dot4CommandFrame(IEEE15dot4Frame):
def __init__(self, commandId, payload, *args, **kwargs):
super(IEEE15dot4CommandFrame, self).__init__(*args, **kwargs)
self.commandId = commandId
self.command = CommandFrameType.fromValue[commandId]
self.additionalInfo = {}
if self.commandId is CommandFrameType.AssociationRequest:
fmt = "<B"
(capabilityInfo, ) = checkAndUnpack(fmt, payload, 0, (0))
self.additionalInfo["allocateAddress"] = bool(
0x01 & (capabilityInfo >> 7))
self.additionalInfo["securityCapable"] = bool(
0x01 & (capabilityInfo >> 6))
self.additionalInfo["rxOnWhenIdle"] = bool(0x01
& (capabilityInfo >> 3))
self.additionalInfo["isPowered"] = bool(0x01
& (capabilityInfo >> 2))
self.additionalInfo["isFullFunctionDevice"] = bool(
0x01 & (capabilityInfo >> 1))
elif self.commandId is CommandFrameType.AssociationResponse:
fmt = "<HB"
(shortAddress,
associationStatus) = checkAndUnpack(fmt, payload, 0, (0))
self.additionalInfo["shortAddress"] = shortAddress
self.additionalInfo["associationStatus"] = {
0: "Successful",
1: "PAN At Capacity",
2: "PAN Access Denied",
}.get(associationStatus, "Reserved")
elif self.commandId is CommandFrameType.DisassociationNotification:
fmt = "<B"
(disassociationReason, ) = checkAndUnpack(fmt, payload, 0, (0))
self.additionalInfo["disassociationReason"] = {
0: "Reserved",
1: "Coord requested leave",
2: "Device requested leave",
}.get(disassociationReason, "Reserved")
elif self.commandId is CommandFrameType.CoordinatorRealignment:
fmt = "<HHBH"
(
panId,
coordShortAddress,
channelNumber,
shortAddress,
) = checkAndUnpack(fmt, payload, 0, (0))
# NB: Channel Page not decoded
self.additionalInfo["panId"] = panId
self.additionalInfo["coordShortAddress"] = coordShortAddress
self.additionalInfo["channelNumber"] = channelNumber
self.additionalInfo["shortAddress"] = shortAddress
def __repr__(self, *args, **kwargs):
output = []
output.append("{} -".format(FrameType.toString(self.fcf.frametype)))
output.append("Time[{}]".format(self.time))
output.append("SeqNum[{}]".format(self.sequenceNumber))
output.append("{}".format(self.addressing))
output.append("Command[{}]".format(self.command))
output.append("AdditionalInfo[{}]".format(self.additionalInfo))
return " ".join(output)
class IEEE15dot4FrameFactory(object):
@staticmethod
def parse(packet):
byteStream = packet.get_macPDU()
offset = 0
(fcfVal, seqNum) = struct.unpack_from("<HB", byteStream, offset)
offset += 3
fcf = FCF.parse(fcfVal)
addressingFields = AddressingFields.parse(fcf, byteStream[offset:])
offset += addressingFields.length
frame = IEEE15dot4Frame(packet.get_timestamp(), fcf, seqNum,
addressingFields, byteStream[offset:])
if fcf.frametype is FrameType.ACK:
return IEEE15dot4AckFrame(**frame.__dict__)
elif fcf.frametype is FrameType.BEACON:
return IEEE15dot4FrameFactory.__parseBeacon(frame)
elif fcf.frametype is FrameType.MAC_CMD:
return IEEE15dot4FrameFactory.__parseMACCommand(frame)
return frame
@staticmethod
def __parseBeacon(frame, **kwargs):
byteStream = frame.msdu
offset = 0
fmt = "<HB"
(superframeSpecification,
gts) = checkAndUnpack(fmt, byteStream, offset, (0, 0))
offset += struct.calcsize(fmt)
fmt = "<B"
(pendingAddressesSpec, ) = checkAndUnpack(fmt, byteStream, offset, (0))
offset += struct.calcsize(fmt)
pendingShortCount = 0x07 & pendingAddressesSpec
pendingExtCount = 0x07 & (pendingAddressesSpec >> 4)
pendingShortAddresses = []
pendingExtAddresses = []
fmt = "<H"
for i in range(pendingShortCount):
(nextShortAddress, ) = checkAndUnpack(fmt, byteStream, offset, (0))
offset += struct.calcsize(fmt)
pendingShortAddresses.append(nextShortAddress)
fmt = "<Q"
for i in range(pendingExtCount):
(nextExtAddress, ) = checkAndUnpack(fmt, byteStream, offset, (0))
offset += struct.calcsize(fmt)
pendingExtAddresses.append(nextExtAddress)
return IEEE15dot4BeaconFrame(SFS.parse(superframeSpecification), gts,
pendingShortAddresses,
pendingExtAddresses, byteStream[offset:],
**frame.__dict__)
@staticmethod
def __parseMACCommand(frame, **kwargs):
byteStream = frame.msdu
offset = 0
fmt = "<B"
(commandId, ) = checkAndUnpack(fmt, byteStream, offset, (0, 0))
offset += struct.calcsize(fmt)
return IEEE15dot4CommandFrame(commandId, byteStream[offset:],
**frame.__dict__)