forked from tanupoo/lorawan-parser
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lorawan_parser.py
executable file
·1547 lines (1479 loc) · 51.3 KB
/
lorawan_parser.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
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import sys
import re
import argparse
import binascii
from lorawan_cipher import lorawan_aes128_cmac
from lorawan_cipher import lorawan_aes128_encrypt
from lorawan_cipher import lorawan_frmp_encryption
from lorawan_cipher import lorawan_frmp_integrity
from lorawan_a2b_hex import a2b_hex
import textwrap
# NOTE:
# In LoRaWAN, the network byte order is little endian.
# Each 2, 4, 8 bytes field must be read as little endian.
# Assumption:
# LoRaWAN wire format is in little endian.
# Convention:
# variable_x: a bytearray
# variable_i: a int
# variable_b: a bit string
# variable_o: a dict
# buf, payload, phy_pdu, *key, devaddr, mic*: a byte array.
#
# however, no postfix usually means that the variable is in bytearray.
# so, needs to understand the context.
MSGDIR_DOWN = 1
MSGDIR_UP = 0
MSGDIR_UNKNOWN = 99
__MIC_SIZE = 4
opt = type("DEFAULT_OPTION",(object,),{"debug_level":0, "verbose":False})
__parse_only = False
#====
def formx(v, form=None):
"""
convert a value into a string with a type of value.
"""
if isinstance(v, int) and form == "hz":
return "{} kHz".format(v)
elif isinstance(v, int) and form == "sec":
return "{} sec".format(v)
elif isinstance(v, int) and form == "pff":
if v == 0:
return "Connected to an external power source."
elif v == 255:
return "No ability to measure the level."
else:
return "{} %".format((v-1)/253*100)
elif isinstance(v, int):
return "x {:02x}".format(v)
elif isinstance(v, (bytes,bytearray)):
return "x {}".format(v.hex())
elif isinstance(v, str) and form == "bin":
return "b {}".format(v)
else:
raise ValueError("ERROR: unsupported arg for formx, {} type={}"
.format(v,type(v)))
def x2bin(v):
"""
convert a value into a binary string
v: int, bytes, bytearray
bytes, bytearray must be in *big* endian.
"""
if isinstance(v, int):
bits = bin(v)
size = 8
elif isinstance(v, (bytes,bytearray)):
bits = bin(int.from_bytes(v, "big"))
size = len(v)*8
return bits[2:].zfill(size)
def x2int(v):
"""
convert a value into an int.
v: bit string, bytes, bytearray
bytes, bytearray must be in little endian.
"""
if isinstance(v, str) and set(v) in [{"0"},{"1"},{"0","1"}]:
return int(v, 2)
elif isinstance(v, (bytes, bytearray)):
return int.from_bytes(v, "little")
def print_detail(text):
"""
mainly print description for MAC Command.
"""
if not opt.verbose:
return
indent = 10
bullet = "* DETAIL:"
bullet_len = 1 + len(bullet)
print(textwrap.fill(text, width=75,
initial_indent="{}{}".format(" "*indent, bullet),
subsequent_indent="{}".format(" "*(indent+bullet_len))))
def print_vt(tag, v_wire=None, v_bits=None, indent=0):
"""
print a value with tag as a title.
tag: string.
v_wire: string or None, usually wire format in bytes.
v_bits: string or None, usually bits.
"""
if __parse_only is True:
return
bullet = " "*(2*indent) + "#"*(2+indent)
print("{} {}".format(bullet, tag), end="")
if v_wire not in ["", None]:
print(" : {}".format(v_wire), end="")
if opt.verbose and v_bits not in ["", None]:
print(" [{}]".format(v_bits), end="")
print("")
def print_v(tag, v_host=None, v_wire=None, indent=1, debug=False):
"""
print a value with tag.
tag: string.
v_host: string of human readable, or None.
v_wire: string in the wire, or None.
indent: 1, 2, or 3
"""
if __parse_only is True:
return
if debug and opt.debug_level == 0:
# ignore print_d() when the -d option is not specified.
return
print("{}".format(" "*indent), end="")
if debug:
print("- DEBUG: ", end="")
print("{}".format(tag), end="")
if v_host not in ["", None]:
print(" : {}".format(v_host), end="")
if opt.verbose and v_wire not in ["", None]:
print(" [{}]".format(v_wire), end="")
print("")
def print_d(tag, v_host, v_wire=None, indent=1):
print_v(tag, v_host, v_wire=v_wire, indent=indent, debug=True)
def print_w(msg):
if opt.verbose:
print("WARNING: {}".format(msg))
#====
def parse_macsubcmd_dwelltime(b):
return "No Limit" if b == "0" else "400 ms"
def parse_macsubcmd_Frequency(freq_x, indent=3):
"""
frequency encoding parser
freq_x: 3 bytes
it is called by:
- parse_maccmd_NewChannelReq()
- parse_maccmd_PingSlotChannelReq()
"""
if len(freq_x) != 3:
raise ValueError("length of freq_x must be 3 bytes, but {}."
.format(len(freq_x)))
freq_i = x2int(freq_x)
if freq_i == 0:
print_v("Frequency", "disabled", formx(freq_x), indent=indent)
else:
print_v("Frequency", formx(freq_i,"hz"), formx(freq_x), indent=indent)
def parse_macsubcmd_DeviceMode_class(class_i):
"""
class_i: 1 byte
"""
if class_i == 0x00:
print_v("Class", "A", formx(class_i), indent=3)
elif class_i == 0x01:
print_v("Class", "RFU", formx(class_i), indent=3)
elif class_i == 0x02:
print_v("Class", "C", formx(class_i), indent=3)
else:
print_v("Class", "Unknown", formx(class_i), indent=3)
def parse_macsubcmd_ServDev_LoRaWAN_version(ver_x):
Dev_LoRaWAN_version_b = x2bin(ver_x)
rfu_b = Dev_LoRaWAN_version_b[0:4]
Minor_b = Dev_LoRaWAN_version_b[4:8]
Minor_i = x2int(Minor_b)
if Minor_i == 1:
vs = "LoRaWAN x.1"
else:
vs = "RFU"
print_v("Dev_LoRaWAN_version", formx(ver_x),
formx(Dev_LoRaWAN_version_b,"bin"), indent=3)
print_v("RFU", formx(rfu_b,"bin"), indent=3)
print_v("Minor", vs, formx(Minor_b,"bin"), indent=4)
#===
def parse_maccmd_ResetInd(mac_cmd):
parse_macsubcmd_ServDev_LoRaWAN_version(mac_cmd[0:1])
print_detail("IS SUPPORTED BY V1.1 OR LATER.")
print_detail("""
This MAC command is only available to ABP devices activated on a LoRaWAN1.1
compatible network server. LoRaWAN1.0 servers do not implement this MAC
command OTA devices MUST NOT implement this command. The network server SHALL
ignore the ResetInd command coming from an OTA device.
With the ResetInd command, an ABP end-device indicates to the network
that it has been re-initialized and
that he has switched back to its default MAC & radio parameters
""")
def parse_maccmd_ResetConf(mac_cmd):
parse_macsubcmd_ServDev_LoRaWAN_version(mac_cmd[0:1])
print_detail("IS SUPPORTED BY V1.1 OR LATER.")
print_detail("""
The server's version carried by the ResetConf must be the same
than the device's version. Any other value is invalid.
""")
def parse_maccmd_LinkCheckReq(mac_cmd):
# zero length
pass
def parse_maccmd_LinkCheckAns(mac_cmd):
Margin_x = mac_cmd[0:1]
GwCnt_x = mac_cmd[1:2]
# Margin
Margin_i = x2int(Margin_x)
print_v("Margin", Margin_i, formx(Margin_x), indent=3)
print_detail("""
The demodulation margin (Margin) is an 8-bit unsigned integer
in the range of 0..254
indicating the link margin in dB of the last successfully
received LinkCheckReq command.
A value of 0 means that the frame was received at the demodulation floor
(0 dB or no 948 margin)
""")
# GwCnt
GwCnt_i = x2int(GwCnt_x)
print_v("GwCnt", GwCnt_i, formx(GwCnt_x), indent=3)
print_detail("""
The gateway count (GwCnt) is the number of gateways that successfully
received the last LinkCheckReq command.
""")
def parse_maccmd_LinkADRReq(mac_cmd):
DataRate_TXPower_x = mac_cmd[0:1]
ChMask_x = mac_cmd[1:3]
Redundancy_x = mac_cmd[3:4]
# DataRate_TXPower
DataRate_TXPower_b = x2bin(DataRate_TXPower_x)
datarate_b = DataRate_TXPower_b[0:4]
txpower_b = DataRate_TXPower_b[4:8]
datarate_i = x2int(datarate_b)
txpower_i = x2int(txpower_b)
print_v("DataRate_TXPower", formx(DataRate_TXPower_x),
formx(DataRate_TXPower_b,"bin"), indent=3)
print_v("DataRate", datarate_i, formx(datarate_b,"bin"), indent=4)
print_v("TXPower", txpower_i, formx(txpower_b,"bin"), indent=4)
print_detail("""
REGION SPECIFIC.
A value 0xF (15 in decimal format) of either DataRate or TXPower
means that the device MUST
ignore that field, and keep the current parameter value.
""")
# ChMask
ChMask_b = x2bin(ChMask_x)
print_v("ChMask", formx(ChMask_x), formx(ChMask_b,"bin"), indent=3)
for i in range(16):
if ChMask_b[i]== "1":
print_v("CH {}".format(i), "use", indent=4)
print_detail("""
The channel mask (ChMask) encodes the channels usable for uplink access.
A bit in the ChMask field set to 1 means that the corresponding channel
can be used for uplink transmissions if this channel allows the data rate
currently used by the end-device.
A bit set to 0 means the corresponding channels should be avoided.
""")
# Redundancy
Redundancy_b = x2bin(Redundancy_x)
rfu_b = Redundancy_b[0:1]
ChMaskCntl_b = Redundancy_b[1:4]
NbTrans_b = Redundancy_b[4:8]
NbTrans_i = x2int(NbTrans_b)
print_v("Redundancy", formx(Redundancy_x), formx(Redundancy_b,"bin"),
indent=3)
print_v("RFU", formx(rfu_b,"bin"), indent=4)
print_v("ChMaskCntl", formx(ChMaskCntl_b,"bin"), indent=4)
print_detail("""
REGION SPECIFIC.
The channel mask control (ChMaskCntl) field controls the
interpretation of the previously
defined ChMask bit mask.
""")
print_v("NbTrans", NbTrans_i, formx(NbTrans_b,"bin"), indent=4)
print_detail("""
The NbTrans field is the number of transmissions for each uplink message.
""")
def parse_maccmd_LinkADRAns(mac_cmd):
Status_x = mac_cmd[0]
Status_b = x2bin(Status_x)
rfu_b = Status_b[0:5]
Power_ACK_b = Status_b[5]
Data_rate_ACK_b = Status_b[6]
Channel_mask_ACK_b = Status_b[7]
print_v("Status", formx(Status_x), formx(Status_b,"bin"), indent=3)
print_v("RFU", formx(rfu_b,"bin"), indent=4)
print_v("Power ACK", Power_ACK_b, indent=4)
if Power_ACK_b == "0":
print_detail("""
The device is unable to operate at or below the requested power level.. The
command was discarded and the end-device state was not
changed.
""")
else:
print_detail("""
The device is able to operate at or below the requested power level,, or the
TXPower field of the request was set to 15, meaning it
shall be ignored
""")
print_v("Data_rate_ACK", Data_rate_ACK_b, indent=4)
if Data_rate_ACK_b == "0":
print_detail("""
The data rate requested is unknown to the end-device or is
not possible given the channel mask provided (not supported
by any of the enabled channels). The command was discarded
and the end-device state was not changed.
""")
else:
print_detail("""
The data rate was successfully set or the DataRate field of
the request was set to 15, meaning it was ignored
""")
print_v("Channel_mask_ACK", Channel_mask_ACK_b, indent=4)
if Channel_mask_ACK_b == "0":
print_detail("""
The channel mask sent enables a yet undefined channel or the channel mask
required all channels to be disabled. The command was
discarded and the end- device state was not changed.
""")
else:
print_detail("""
The channel mask sent was successfully interpreted. All currently defined
channel states were set according to the mask.
""")
def parse_maccmd_DutyCycleReq(mac_cmd):
DutyCyclePL_x = mac_cmd[0:1]
DutyCyclePL_b = x2bin(DutyCyclePL_x)
rfu_b = DutyCyclePL_b[0:4]
MaxDCycle_b = DutyCyclePL_b[4:8]
duty_cycle = ("No duty cycle" if MaxDCycle_b == "0000" else
1./(2**x2int(MaxDCycle_b)))
print_v("DutyCyclePL", indent=3)
print_v("RFU", formx(rfu_b,"bin"), indent=4)
print_v("MaxDCycle", x2bin(DutyCyclePL_x), formx(MaxDCycle_b,"bin"),
indent=4)
print_v("Aggregated duty cycle", duty_cycle, indent=4)
print_detail("""
A value of 0 corresponds to "no duty cycle limitation"
except the one set by the regional regulation.
""")
def parse_maccmd_DutyCycleAns(mac_cmd):
# zero length
pass
def parse_maccmd_RXParamSetupReq(mac_cmd):
DLsettings_x = mac_cmd[0:1]
Frequency_x = mac_cmd[1:4]
# DLsettings
DLsettings_b = x2bin(DLsettings_x)
rfu_b = DLsettings_b[0:1]
RX1DRoffset_b = DLsettings_b[1:4]
RX2DataRate_b = DLsettings_b[4:8]
RX1DRoffset_i = x2int(RX1DRoffset_b)
RX2DataRate_i = x2int(RX2DataRate_b)
print_v("DLsettings", indent=3)
print_v("RFU", formx(rfu_b,"bin"), indent=4)
print_v("RX1DRoffset", RX1DRoffset_i, formx(RX1DRoffset_b,"bin"), indent=4)
print_detail("""
The RX1DRoffset field sets the offset between the uplink data
rate and the downlink data
rate used to communicate with the end-device on the first
reception slot (RX1). As a default
this offset is 0. The offset is used to take into account
maximum power density constraints
for base stations in some regions and to balance the
uplink and downlink radio link margins.
""")
print_v("RX2DataRate", RX2DataRate_i, formx(RX2DataRate_b,"bin"), indent=4)
print_detail("""
The RX2DataRate field defines the data rate of a downlink using the second
receive window following the same convention as the
LinkADRReq command (0 means DR0/125kHz for example).
""")
# Frequency
parse_macsubcmd_Frequency(Frequency_x)
print_detail("""
The frequency (Freq) field corresponds to the frequency of
the channel used for the second receive window, whereby
the frequency is coded following
the convention defined in the NewChannelReq command.
""")
def parse_maccmd_RXParamSetupAns(mac_cmd):
Status_x = mac_cmd[0:1]
# Status
Status_b = x2bin(Status_x)
rfu_b = Status_b[0:5]
RX1DRoffset_ACK_b = Status_b[5:6]
RX2Datarate_ACK_b = Status_b[6:7]
Channel_ACK_b = Status_b[7:8]
print_v("Status", formx(Status_x), formx(Status_b,"bin"), indent=3)
print_v("RFU", formx(rfu_b,"bin"), indent=4)
print_v("RX1DRoffset ACK", formx(RX1DRoffset_ACK_b,"bin"), indent=4)
if RX1DRoffset_ACK_b == "0":
print_detail("""
the uplink/downlink data rate offset for RX1 slot is not in the allowed range.
""")
else:
print_detail("""
RX1DRoffset was successfully set.
""")
#
print_v("RX2 Data rate ACK", formx(RX2Datarate_ACK_b,"bin"), indent=4)
if RX2Datarate_ACK_b == "0":
print_detail("""
The data rate requested is unknown to the end-device.
""")
else:
print_detail("""
RX2 slot channel was successfully set.
""")
#
print_v("Channel ACK", formx(Channel_ACK_b,"bin"), indent=4)
if Channel_ACK_b == "0":
print_detail("""
The frequency requested is not usable by the end-device.
""")
else:
print_detail("""
RX2 slot channel was successfully set.
""")
def parse_maccmd_DevStatusReq(mac_cmd):
# zero length
pass
def parse_maccmd_DevStatusAns(mac_cmd):
Battery_x = mac_cmd[0:1]
Margin_x = mac_cmd[1:2]
# Battery
Battery_i = x2int(Battery_x)
print_v("Battery", formx(Battery_i,"pff"), formx(Battery_i), indent=3)
# Margin
Status_b = x2bin(Margin_x)
rfu_b = Status_b[0:2]
Margin_b = Status_b[2:8]
Margin_i = int(Margin_b,2) if Margin_b[0] == "0" else ~int(Margin_b,2)+32
print_v("Margin", formx(Margin_x), formx(Status_b,"bin"), indent=3)
print_v("RFU", formx(rfu_b,"bin"), indent=4)
print_v("Margin", Margin_i, formx(Margin_b,"bin"), indent=4)
print_detail("""
The margin (Margin) is the demodulation signal-to-noise ratio in dB rounded to
the nearest
integer value for the last successfully received
DevStatusReq command. It is a signed
integer of 6 bits with a minimum value of -32 and a
maximum value of 31.
""")
def parse_maccmd_NewChannelReq(mac_cmd):
ChIndex_x = mac_cmd[0:1]
ChIndex_i = x2int(ChIndex_x)
print_v("ChIndex", ChIndex_i, formx(ChIndex_x), indent=3)
print_detail("""
The channel index (ChIndex) is the index of the channel being created or
modified.
Depending on the region and frequency band used, in
certain regions (cf [PHY]) the LoRaWAN specification imposes default
channels which must be common to all devices and
cannot be modified by the NewChannelReq command.
If the number of default channels is N,
the default channels go from 0 to N-1,
and the acceptable range for ChIndex is N to 15.
A device must be able to handle at least 16 different
channel definitions. In certain region the
device may have to store more than 16 channel definitions.
""")
parse_macsubcmd_Frequency(mac_cmd[1:4])
print_detail("""
If the number of default channels is
N, the default channels go from 0 to N-1, and the
acceptable range for ChIndex is N to 15. A
device must be able to handle at least 16 different
channel definitions. In certain region the
device may have to store more than 16 channel definitions.
""")
#
DrRange_x = mac_cmd[4:5]
DrRange_b = x2bin(DrRange_x)
MaxDR_b = DrRange_b[0:4]
MaxDR_i = x2int(MaxDR_b)
MinDR_b = DrRange_b[4:8]
MinDR_i = x2int(MinDR_b)
print_v("DrRange", formx(DrRange_x), formx(DrRange_b,"bin"), indent=3)
print_v("MaxDR", MaxDR_i, formx(MaxDR_b,"bin"), indent=4)
print_v("MinDR", MinDR_i, formx(MinDR_b,"bin"), indent=4)
print_detail("""
the minimum data rate (MinDR) subfield
designate the lowest uplink data rate allowed on this channel.
Similarly, the maximum data rate
(MaxDR) designates the highest uplink data rate.
""")
def parse_maccmd_NewChannelAns(mac_cmd):
Status_x = mac_cmd[0:1]
Status_b = x2bin(Status_x)
rfu_b = Status_b[0:6]
Data_rate_range_ok_b = Status_b[6:7]
Channel_frequency_ok_b = Status_b[7:8]
print_v("Status", formx(Status_x), formx(Status_b,"bin"), indent=3)
print_v("RFU", formx(rfu_b,"bin"), indent=4)
print_v("Data rate range ok", formx(Data_rate_range_ok_b,"bin"), indent=4)
if Data_rate_range_ok_b == "0":
print_detail("""
The designated data rate range exceeds the ones currently defined
for this end-device.
""")
else:
print_detail("""
The data rate range is compatible with the possibilities of the end-device.
""")
print_v("Channel frequency ok", formx(Channel_frequency_ok_b,"bin"),
indent=4)
if Channel_frequency_ok_b == "0":
print_detail("""
The device cannot use this frequency.
""")
else:
print_detail("""
The device is able to use this frequency.
""")
def parse_maccmd_RXTimingSetupReq(mac_cmd):
Settings_x = mac_cmd[0:1]
Settings_b = x2bin(Settings_x)
rfu_b = Settings_b[0:4]
Del_b = Settings_b[4:8]
Del_i = 1 if Del_b == "0" else int(Del_b,2)
print_v("Settings", formx(Settings_x), formx(Settings_b,"bin"), indent=3)
print_v("RFU", formx(rfu_b,"bin"), indent=4)
print_v("Delay", "{} sec".format(Del_i), formx(Del_b,"bin"), indent=4)
print_detail("""
The delay (Delay) field specifies the delay in second.
the value of 0 and 1 indicates 1 (s).
the value of 15 indicates 15 (s).
""")
def parse_maccmd_RXTimingSetupAns(mac_cmd):
# zero length
pass
def parse_maccmd_TxParamSetupReq(mac_cmd):
DwellTime_x = mac_cmd[0:1]
DwellTime_b = x2bin(DwellTime_x)
rfu_b = DwellTime_b[0:2]
DownlinkDwellTime_b = DwellTime_b[2:3]
UplinkDwellTime_b = DwellTime_b[3:4]
MaxEIRP_b = DwellTime_b[4:8]
MaxEIRP_i = [8,10,12,13,14,16,18,20,
21,24,26,27,29,30,33,36][x2int(MaxEIRP_b)]
print_v("DwellTime", formx(DwellTime_x), indent=3)
print_v("RFU", formx(rfu_b,"bin"), indent=4)
print_v("DownlinkDwellTime", parse_macsubcmd_dwelltime(DownlinkDwellTime_b),
formx(DownlinkDwellTime_b,"bin"), indent=4)
print_v("UplinkDwellTime", parse_macsubcmd_dwelltime(UplinkDwellTime_b),
formx(UplinkDwellTime_b,"bin"), indent=4)
print_v("MaxEIRP", MaxEIRP_i, formx(MaxEIRP_b,"bin"), indent=4)
def parse_maccmd_TxParamSetupAns(mac_cmd):
# zero length
pass
def parse_maccmd_DlChannelReq(mac_cmd):
ChIndex_x = mac_cmd[0:1]
print_detail("""
The channel index (ChIndex) is the index of the
channel whose downlink frequency is
modified.
""")
parse_macsubcmd_Frequency(mac_cmd[1:4])
def parse_maccmd_DlChannelAns(mac_cmd):
Status_x = mac_cmd[0:1]
Status_b = x2bin(Status_x)
rfu_b = Status_b[0:6]
Uplink_frequency_exists_b = Status_b[6:7]
Channel_frequency_ok_b = Status_b[7:8]
print_v("Status", formx(Status_x), formx(Status_b,"bin"), indent=3)
print_v("RFU", formx(rfu_b,"bin"), indent=4)
print_v("Uplink frequency exists", formx(Uplink_frequency_exists_b,"bin"),
indent=4)
if Uplink_frequency_exists_b == "0":
print_detail("""
The uplink frequency is not defined for this channel, the downlink frequency
can only be set for a channel that already has
a valid uplink frequency
""")
else:
print_detail("""
The uplink frequency of the channel is valid.
""")
print_v("Channel frequency ok", formx(Channel_frequency_ok_b,"bin"),
indent=4)
if Channel_frequency_ok_b == "0":
print_detail("""
The device cannot use this frequency.
""")
else:
print_detail("""
The device is able to use this frequency.
""")
#
# Class B Mac Command Parsers
#
def parse_maccmd_PingSlotInfoReq(mac_cmd):
PingSlotParam_x = mac_cmd[0]
PingSlotParam_b = x2bin(PingSlotParam_x)
rfu_b = PingSlotParam_b[0:5]
Periodicity_b = PingSlotParam_b[5:8]
Periodicity_i = int(Periodicity_b,2)
print_v("PingSlotParam", formx(PingSlotParam_x), indent=3)
print_v("RFU", formx(rfu_b,"bin"), indent=4)
print_v("Periodicity", Periodicity_i, formx(Periodicity_b,"bin"), indent=4)
print_v("pingSlotPeriod", formx(2**Periodicity_i,"sec"), indent=5)
print_detail("""
Periodicity = 0 means that the end-device opens a ping slot every second.
Periodicity = 7, every 128 seconds which is the maximum ping period
supported by the LoRaWAN Class B specification.
""")
def parse_maccmd_PingSlotInfoAns(mac_cmd):
# zero length
pass
def parse_maccmd_PingSlotChannelReq(mac_cmd):
parse_macsubcmd_Frequency(mac_cmd[0:3])
DR_x = mac_cmd[3:4]
DR_b = x2bin(DR_x)
rfu_b = DR_b[0:4]
datarate_b = DR_b[4:8]
datarate_i = int(datarate_i, 2)
print_v("DataRate", formx(DR_x), indent=3)
print_v("RFU", formx(rfu_b,"bin"), indent=4)
print_v("data rate", datarate_i, formx(datarate_b,"bin"), indent=4)
print_detail("""
The “data rate” subfield is the index of the Data Rate used
for the ping-slot downlinks.
""")
def parse_maccmd_PingSlotChannelAns(mac_cmd):
Status_x = mac_cmd[0:1]
Status_b = x2bin(Status_x)
rfu_b = Status_b[0:6]
datarate_ok_b = Status_b[6:7]
chfreq_ok_b = Status_b[7:8]
print_v("Status", formx(Status_b,"bin"), formx(Status_x), indent=3)
print_v("RFU", formx(rfu_b,"bin"), indent=4)
print_v("data rate ok", formx(datarate_ok_b,"bin"), indent=4)
print_v("ch freq ok", formx(chfreq_ok_b,"bin"), indent=4)
print_detail("""
for data rate ok,
if 0, Data rate ok: The designated data rate is not defined for this end device,
the previous data rate is kept.
if 1, The data rate is compatible with the possibilities of the end device
The device cannot receiveon this frequency
This frequency can be used by the end-device
If either of those 2 bits equals 0, the command did not succeed and the
ping-slot parameters have not been modified.
""")
def parse_maccmd_BeaconTimingReq(mac_cmd):
print_detail("""
DEPRECATED.
The network may answer only a limited number of requests per a given time
period. An end-device must not expect that BeaconTimingReq is answered
immediately with a BeaconTimingAns. Class A end-devices wanting to switch
to Class B should not transmit more than one BeaconTimingReq per hour.
""")
def parse_maccmd_BeaconTimingAns(mac_cmd):
print_detail("""
DEPRECATED.
""")
Delay_x = mac_cmd[0:2]
Delay_i = x2int(Delay_x)
print_v("Delay", Delay_i, formx(Delay_x), indent=3)
print_detail("""
If the remaining time between the end of the
current downlink frame and the start of the next beacon frame is noted RTime
then: 30 ms x (Delay+1) > RTime >= 30 ms x Delay
""")
Channel_x = mac_cmd[2:3]
Channel_i = int(Channel_x, 16)
print_v("Channel", Channel_i, formx(Channel_x), indent=3)
print_detail("""
In networks where the beacon uses alternatively several channels,
the "Channel" field is the index of the beaconing channel
on which the next beacon will be broadcasted.
For networks where the beacon broadcast frequency is fixed then this field
content is 0.
""")
def parse_maccmd_BeaconFreqReq(mac_cmd):
print_detail("""
to modify the frequency on which this 2181 end-device expects the beacon.
""")
Frequency_x = mac_cmd[0:3]
Frequency_i = x2int(Frequency_x)
print_v("Frequency:", formx(Frequency_i, "hz"), formx(Frequency_x),
indent=3)
print_detail("""
Frequency is a 24bits unsigned integer. The actual beacon
channel frequency in Hz is 100 x frequ. This allows defining
the beacon channel anywhere between 100 MHz to 1.67 GHz
by 100 Hz step. The end-device has to check that the frequency
is actually allowed by its radio hardware and return an error otherwise.
A valid non-zero Frequency will force the device to listen
to the beacon on a fixed frequency channel even if the default
behavior specifies a frequency hopping beacon (i.e US ISM band).
A value of 0 instructs the end-device to use the default
beacon frequency plan as defined in the "Beacon physical layer" section.
Where applicable the device resumes frequency hopping beacon search.
""")
def parse_maccmd_BeaconFreqAns(mac_cmd):
print_detail("""
answer to modification the frequency on which this end-device expects the beacon.
""")
Status_x = mac_cmd[0:1]
Status_b = x2bin(Status_x)
rfu_b = Status_b[0:6]
ok_b = Status_b[7:8]
print_v("Status:", formx(Status_x), formx(Status_b,"bin"), indent=3)
print_v("RFU:", formx(rfu_b,"bin"), indent=4)
print_v("Beacon frequency ok:", ok_b, formx(ok_b,"bin"), indent=4)
print_detail("""
Bit=0: The device cannot use this frequency, the previous beacon frequency is
kept.
Bit=1: The beacon frequency has been changed
""")
#
# Class C Mac Command Parsers
#
def parse_maccmd_DeviceModeInd(mac_cmd):
parse_macsubcmd_DeviceMode_class(mac_cmd[0])
def parse_maccmd_DeviceModeConf(mac_cmd):
parse_macsubcmd_DeviceMode_class(mac_cmd[0])
"""
Table for MAC Command Parser
name: MAC command name
size: command size in octet.
parser: function name.
"""
mac_cmd_tab = {
# Class A Mac Command
0x01: {
MSGDIR_UP: {
"name": "ResetInd",
"size": 1,
"parser": parse_maccmd_ResetInd
},
MSGDIR_DOWN: {
"name": "ResetConf",
"size": 1,
"parser": parse_maccmd_ResetConf
}
},
0x02: {
MSGDIR_UP: {
"name": "LinkCheckReq",
"size": 0,
"parser": parse_maccmd_LinkCheckReq
},
MSGDIR_DOWN: {
"name": "LinkCheckAns",
"size": 2,
"parser": parse_maccmd_LinkCheckAns
}
},
0x03: {
MSGDIR_UP: {
"name": "LinkADRAns",
"size": 1,
"parser": parse_maccmd_LinkADRAns
},
MSGDIR_DOWN: {
"name": "LinkADRReq",
"size": 4,
"parser": parse_maccmd_LinkADRReq
}
},
0x04: {
MSGDIR_UP: {
"name": "DutyCycleAns",
"size": 0,
"parser": parse_maccmd_DutyCycleAns
},
MSGDIR_DOWN: {
"name": "DutyCycleReq",
"size": 1,
"parser": parse_maccmd_DutyCycleReq
}
},
0x05: {
MSGDIR_UP: {
"name": "RXParamSetupAns",
"size": 1,
"parser": parse_maccmd_RXParamSetupAns
},
MSGDIR_DOWN: {
"name": "RXParamSetupReq",
"size": 4,
"parser": parse_maccmd_RXParamSetupReq
}
},
0x06: {
MSGDIR_UP: {
"name": "DevStatusAns",
"size": 2,
"parser": parse_maccmd_DevStatusAns
},
MSGDIR_DOWN: {
"name": "DevStatusReq",
"size": 0,
"parser": parse_maccmd_DevStatusReq
}
},
0x07: {
MSGDIR_UP: {
"name": "NewChannelAns",
"size": 1,
"parser": parse_maccmd_NewChannelAns
},
MSGDIR_DOWN: {
"name": "NewChannelReq",
"size": 5,
"parser": parse_maccmd_NewChannelReq
}
},
0x08: {
MSGDIR_UP: {
"name": "RXTimingSetupAns",
"size": 0,
"parser": parse_maccmd_RXTimingSetupAns
},
MSGDIR_DOWN: {
"name": "RXTimingSetupReq",
"size": 1,
"parser": parse_maccmd_RXTimingSetupReq
}
},
0x09: {
MSGDIR_UP: {
"name": "TxParamSetupAns",
"size": 0,
"parser": parse_maccmd_TxParamSetupAns
},
MSGDIR_DOWN: {
"name": "TxParamSetupReq",
"size": 1,
"parser": parse_maccmd_TxParamSetupReq
}
},
0x0a: {
MSGDIR_UP: {
"name": "DlChannelAns",
"size": 1,
"parser": parse_maccmd_DlChannelAns
},
MSGDIR_DOWN: {
"name": "DlChannelReq",
"size": 4,
"parser": parse_maccmd_DlChannelReq
}
},
# Class B Mac Command
0x10: {
MSGDIR_UP: {
"name": "PingSlotInfoReq",
"size": 1,
"parser": parse_maccmd_PingSlotInfoReq
},
MSGDIR_DOWN: {
"name": "PingSlotInfoAns",
"size": 0,
"parser": parse_maccmd_PingSlotInfoAns
}
},
0x11: {
MSGDIR_UP: {
"name": "PingSlotChannelAns",
"size": 4,
"parser": parse_maccmd_PingSlotChannelAns
},
MSGDIR_DOWN: {
"name": "PingSlotChannelReq",
"size": 4,
"parser": parse_maccmd_PingSlotChannelReq
}
},
0x12: {
MSGDIR_UP: {
"name": "BeaconTimingReq",
"size": 0,
"parser": parse_maccmd_BeaconTimingReq
},
MSGDIR_DOWN: {
"name": "BeaconTimingAns",
"size": 3,
"parser": parse_maccmd_BeaconTimingAns
}
},
0x13: {
MSGDIR_UP: {
"name": "BeaconFreqAns",
"size": 1,
"parser": parse_maccmd_BeaconFreqAns
},
MSGDIR_DOWN: {
"name": "BeaconFreqReq",
"size": 3,
"parser": parse_maccmd_BeaconFreqReq
}
},
# Class C Mac Command
0x20: {
MSGDIR_UP: {
"name": "DeviceModeInd",
"size": 1,
"parser": parse_maccmd_DeviceModeInd
},
MSGDIR_DOWN: {
"name": "DeviceModeConf",
"size": 1,
"parser": parse_maccmd_DeviceModeConf
}
}
}
def parse_mac_cmd(mac_cmds, msg_dir, version):
offset = 0
n_cmd = 0
dir_str = "Up" if msg_dir == 0 else "Down"
if opt.verbose:
print_vt("MAC Command (No. CMD CID DIR [MSG])")
else:
print_vt("MAC Command (No. CMD CID DIR)")
while offset < len(mac_cmds):
cid = mac_cmds[offset]
a = mac_cmd_tab.get(cid)
if a is not None:
t = mac_cmd_tab[cid][msg_dir]
offset += 1
n_cmd += 1
cmd = mac_cmds[offset:1+offset+t["size"]]
if t["size"] == 0:
print_v("{}. {}".format(n_cmd,t["name"]),
"0x{:02x} {}link".format(cid,dir_str), indent=2)
else:
print_v("{}. {}".format(n_cmd,t["name"]),
"0x{:02x} {}link".format(cid,dir_str), formx(cmd),
indent=2)
# call a parser for a mac command.
t["parser"](cmd)
offset += t["size"]
else:
print_w("looks a proprietary MAC command #{}.".format(
mac_cmds[offset]))
# just stop to parse all.
return
def parse_fhdr(payload, msg_dir, version, upper_fcnt=b"\x00\x00"):
"""
FHDR Parser.
- payload: mac payload (MHDR is not included) in bytes.
- FHDR format is:
4 | 1 | 2 | 0...15
DevAddr | FCtrl | FCnt | FOpts
"""
devaddr = payload[0:4][::-1]
fctrl_x = payload[4:5]
fcnt_x = payload[5:7][::-1]