forked from things-nyc/arduino-lmic
-
Notifications
You must be signed in to change notification settings - Fork 212
/
lmic.c
2171 lines (1877 loc) · 76.4 KB
/
lmic.c
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
/*
* Copyright (c) 2014-2016 IBM Corporation.
* All rights reserved.
*
* Copyright (c) 2016-2018 MCCI Corporation.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the <organization> nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
//! \file
#define LMIC_DR_LEGACY 0
#include "lmic_bandplan.h"
#if defined(DISABLE_BEACONS) && !defined(DISABLE_PING)
#error Ping needs beacon tracking
#endif
DEFINE_LMIC;
// Fwd decls.
static void engineUpdate(void);
#if !defined(DISABLE_BEACONS)
static void startScan (void);
#endif
static inline void initTxrxFlags(const char *func, u1_t mask) {
LMIC_DEBUG2_PARAMETER(func);
#if LMIC_DEBUG_LEVEL > 1
LMIC_DEBUG_PRINTF("%"LMIC_PRId_ostime_t": %s txrxFlags %#02x --> %02x\n", os_getTime(), func, LMIC.txrxFlags, mask);
#endif
LMIC.txrxFlags = mask;
}
static inline void orTxrxFlags(const char *func, u1_t mask) {
initTxrxFlags(func, LMIC.txrxFlags | mask);
}
// ================================================================================
// BEG OS - default implementations for certain OS suport functions
#if !defined(HAS_os_calls)
#if !defined(os_rlsbf2)
u2_t os_rlsbf2 (xref2cu1_t buf) {
return (u2_t)((u2_t)buf[0] | ((u2_t)buf[1]<<8));
}
#endif
#if !defined(os_rlsbf4)
u4_t os_rlsbf4 (xref2cu1_t buf) {
return (u4_t)((u4_t)buf[0] | ((u4_t)buf[1]<<8) | ((u4_t)buf[2]<<16) | ((u4_t)buf[3]<<24));
}
#endif
#if !defined(os_rmsbf4)
u4_t os_rmsbf4 (xref2cu1_t buf) {
return (u4_t)((u4_t)buf[3] | ((u4_t)buf[2]<<8) | ((u4_t)buf[1]<<16) | ((u4_t)buf[0]<<24));
}
#endif
#if !defined(os_wlsbf2)
void os_wlsbf2 (xref2u1_t buf, u2_t v) {
buf[0] = v;
buf[1] = v>>8;
}
#endif
#if !defined(os_wlsbf4)
void os_wlsbf4 (xref2u1_t buf, u4_t v) {
buf[0] = v;
buf[1] = v>>8;
buf[2] = v>>16;
buf[3] = v>>24;
}
#endif
#if !defined(os_wmsbf4)
void os_wmsbf4 (xref2u1_t buf, u4_t v) {
buf[3] = v;
buf[2] = v>>8;
buf[1] = v>>16;
buf[0] = v>>24;
}
#endif
#if !defined(os_getBattLevel)
u1_t os_getBattLevel (void) {
return MCMD_DEVS_BATT_NOINFO;
}
#endif
#if !defined(os_crc16)
// New CRC-16 CCITT(XMODEM) checksum for beacons:
u2_t os_crc16 (xref2cu1_t data, uint len) {
u2_t remainder = 0;
u2_t polynomial = 0x1021;
for( uint i = 0; i < len; i++ ) {
remainder ^= data[i] << 8;
for( u1_t bit = 8; bit > 0; bit--) {
if( (remainder & 0x8000) )
remainder = (remainder << 1) ^ polynomial;
else
remainder <<= 1;
}
}
return remainder;
}
#endif
#endif // !HAS_os_calls
// END OS - default implementations for certain OS suport functions
// ================================================================================
// ================================================================================
// BEG AES
static void micB0 (u4_t devaddr, u4_t seqno, int dndir, int len) {
os_clearMem(AESaux,16);
AESaux[0] = 0x49;
AESaux[5] = dndir?1:0;
AESaux[15] = len;
os_wlsbf4(AESaux+ 6,devaddr);
os_wlsbf4(AESaux+10,seqno);
}
static int aes_verifyMic (xref2cu1_t key, u4_t devaddr, u4_t seqno, int dndir, xref2u1_t pdu, int len) {
micB0(devaddr, seqno, dndir, len);
os_copyMem(AESkey,key,16);
return os_aes(AES_MIC, pdu, len) == os_rmsbf4(pdu+len);
}
static void aes_appendMic (xref2cu1_t key, u4_t devaddr, u4_t seqno, int dndir, xref2u1_t pdu, int len) {
micB0(devaddr, seqno, dndir, len);
os_copyMem(AESkey,key,16);
// MSB because of internal structure of AES
os_wmsbf4(pdu+len, os_aes(AES_MIC, pdu, len));
}
static void aes_appendMic0 (xref2u1_t pdu, int len) {
os_getDevKey(AESkey);
os_wmsbf4(pdu+len, os_aes(AES_MIC|AES_MICNOAUX, pdu, len)); // MSB because of internal structure of AES
}
static int aes_verifyMic0 (xref2u1_t pdu, int len) {
os_getDevKey(AESkey);
return os_aes(AES_MIC|AES_MICNOAUX, pdu, len) == os_rmsbf4(pdu+len);
}
static void aes_encrypt (xref2u1_t pdu, int len) {
os_getDevKey(AESkey);
os_aes(AES_ENC, pdu, len);
}
static void aes_cipher (xref2cu1_t key, u4_t devaddr, u4_t seqno, int dndir, xref2u1_t payload, int len) {
if( len <= 0 )
return;
os_clearMem(AESaux, 16);
AESaux[0] = AESaux[15] = 1; // mode=cipher / dir=down / block counter=1
AESaux[5] = dndir?1:0;
os_wlsbf4(AESaux+ 6,devaddr);
os_wlsbf4(AESaux+10,seqno);
os_copyMem(AESkey,key,16);
os_aes(AES_CTR, payload, len);
}
static void aes_sessKeys (u2_t devnonce, xref2cu1_t artnonce, xref2u1_t nwkkey, xref2u1_t artkey) {
os_clearMem(nwkkey, 16);
nwkkey[0] = 0x01;
os_copyMem(nwkkey+1, artnonce, LEN_ARTNONCE+LEN_NETID);
os_wlsbf2(nwkkey+1+LEN_ARTNONCE+LEN_NETID, devnonce);
os_copyMem(artkey, nwkkey, 16);
artkey[0] = 0x02;
os_getDevKey(AESkey);
os_aes(AES_ENC, nwkkey, 16);
os_getDevKey(AESkey);
os_aes(AES_ENC, artkey, 16);
}
// END AES
// ================================================================================
// ================================================================================
// BEG LORA
static CONST_TABLE(u1_t, SENSITIVITY)[7][3] = {
// ------------bw----------
// 125kHz 250kHz 500kHz
{ 141-109, 141-109, 141-109 }, // FSK
{ 141-127, 141-124, 141-121 }, // SF7
{ 141-129, 141-126, 141-123 }, // SF8
{ 141-132, 141-129, 141-126 }, // SF9
{ 141-135, 141-132, 141-129 }, // SF10
{ 141-138, 141-135, 141-132 }, // SF11
{ 141-141, 141-138, 141-135 } // SF12
};
int getSensitivity (rps_t rps) {
return -141 + TABLE_GET_U1_TWODIM(SENSITIVITY, getSf(rps), getBw(rps));
}
ostime_t calcAirTime (rps_t rps, u1_t plen) {
u1_t bw = getBw(rps); // 0,1,2 = 125,250,500kHz
u1_t sf = getSf(rps); // 0=FSK, 1..6 = SF7..12
if( sf == FSK ) {
return (plen+/*preamble*/5+/*syncword*/3+/*len*/1+/*crc*/2) * /*bits/byte*/8
* (s4_t)OSTICKS_PER_SEC / /*kbit/s*/50000;
}
u1_t sfx = 4*(sf+(7-SF7));
u1_t q = sfx - (sf >= SF11 ? 8 : 0);
int tmp = 8*plen - sfx + 28 + (getNocrc(rps)?0:16) - (getIh(rps)?20:0);
if( tmp > 0 ) {
tmp = (tmp + q - 1) / q;
tmp *= getCr(rps)+5;
tmp += 8;
} else {
tmp = 8;
}
tmp = (tmp<<2) + /*preamble*/49 /* 4 * (8 + 4.25) */;
// bw = 125000 = 15625 * 2^3
// 250000 = 15625 * 2^4
// 500000 = 15625 * 2^5
// sf = 7..12
//
// osticks = tmp * OSTICKS_PER_SEC * 1<<sf / bw
//
// 3 => counter reduced divisor 125000/8 => 15625
// 2 => counter 2 shift on tmp
sfx = sf+(7-SF7) - (3+2) - bw;
int div = 15625;
if( sfx > 4 ) {
// prevent 32bit signed int overflow in last step
div >>= sfx-4;
sfx = 4;
}
// Need 32bit arithmetic for this last step
return (((ostime_t)tmp << sfx) * OSTICKS_PER_SEC + div/2) / div;
}
// END LORA
// ================================================================================
// Adjust DR for TX retries
// - indexed by retry count
// - return steps to lower DR
static CONST_TABLE(u1_t, DRADJUST)[2+TXCONF_ATTEMPTS] = {
// normal frames - 1st try / no retry
0,
// confirmed frames
0,0,1,0,1,0,1,0,0
};
// Table below defines the size of one symbol as
// symtime = 256us * 2^T(sf,bw)
// 256us is called one symunit.
// SF:
// BW: |__7___8___9__10__11__12
// 125kHz | 2 3 4 5 6 7
// 250kHz | 1 2 3 4 5 6
// 500kHz | 0 1 2 3 4 5
//
#if !defined(DISABLE_BEACONS)
static ostime_t calcRxWindow (u1_t secs, dr_t dr) {
ostime_t rxoff, err;
if( secs==0 ) {
// aka 128 secs (next becaon)
rxoff = LMIC.drift;
err = LMIC.lastDriftDiff;
} else {
// scheduled RX window within secs into current beacon period
rxoff = (LMIC.drift * (ostime_t)secs) >> BCN_INTV_exp;
err = (LMIC.lastDriftDiff * (ostime_t)secs) >> BCN_INTV_exp;
}
u1_t rxsyms = MINRX_SYMS;
err += (ostime_t)LMIC.maxDriftDiff * LMIC.missedBcns;
LMIC.rxsyms = MINRX_SYMS + (err / dr2hsym(dr));
return (rxsyms-PAMBL_SYMS) * dr2hsym(dr) + rxoff;
}
// Setup beacon RX parameters assuming we have an error of ms (aka +/-(ms/2))
static void calcBcnRxWindowFromMillis (u1_t ms, bit_t ini) {
if( ini ) {
LMIC.drift = 0;
LMIC.maxDriftDiff = 0;
LMIC.missedBcns = 0;
LMIC.bcninfo.flags |= BCN_NODRIFT|BCN_NODDIFF;
}
ostime_t hsym = dr2hsym(DR_BCN);
LMIC.bcnRxsyms = MINRX_SYMS + ms2osticksCeil(ms) / hsym;
LMIC.bcnRxtime = LMIC.bcninfo.txtime + BCN_INTV_osticks - (LMIC.bcnRxsyms-PAMBL_SYMS) * hsym;
}
#endif // !DISABLE_BEACONS
#if !defined(DISABLE_PING)
// Setup scheduled RX window (ping/multicast slot)
static void rxschedInit (xref2rxsched_t rxsched) {
os_clearMem(AESkey,16);
os_clearMem(LMIC.frame+8,8);
os_wlsbf4(LMIC.frame, LMIC.bcninfo.time);
os_wlsbf4(LMIC.frame+4, LMIC.devaddr);
os_aes(AES_ENC,LMIC.frame,16);
u1_t intvExp = rxsched->intvExp;
ostime_t off = os_rlsbf2(LMIC.frame) & (0x0FFF >> (7 - intvExp)); // random offset (slot units)
rxsched->rxbase = (LMIC.bcninfo.txtime +
BCN_RESERVE_osticks +
ms2osticks(BCN_SLOT_SPAN_ms * off)); // random offset osticks
rxsched->slot = 0;
rxsched->rxtime = rxsched->rxbase - calcRxWindow(/*secs BCN_RESERVE*/2+(1<<intvExp),rxsched->dr);
rxsched->rxsyms = LMIC.rxsyms;
}
static bit_t rxschedNext (xref2rxsched_t rxsched, ostime_t cando) {
again:
if( rxsched->rxtime - cando >= 0 )
return 1;
u1_t slot;
if( (slot=rxsched->slot) >= 128 )
return 0;
u1_t intv = 1<<rxsched->intvExp;
if( (rxsched->slot = (slot += (intv))) >= 128 )
return 0;
rxsched->rxtime = rxsched->rxbase
+ ((BCN_WINDOW_osticks * (ostime_t)slot) >> BCN_INTV_exp)
- calcRxWindow(/*secs BCN_RESERVE*/2+slot+intv,rxsched->dr);
rxsched->rxsyms = LMIC.rxsyms;
goto again;
}
#endif // !DISABLE_PING)
ostime_t LMICcore_rndDelay (u1_t secSpan) {
u2_t r = os_getRndU2();
ostime_t delay = r;
if( delay > OSTICKS_PER_SEC )
delay = r % (u2_t)OSTICKS_PER_SEC;
if( secSpan > 0 )
delay += ((u1_t)r % secSpan) * OSTICKS_PER_SEC;
return delay;
}
static void txDelay (ostime_t reftime, u1_t secSpan) {
reftime += LMICcore_rndDelay(secSpan);
if( LMIC.globalDutyRate == 0 || (reftime - LMIC.globalDutyAvail) > 0 ) {
LMIC.globalDutyAvail = reftime;
LMIC.opmode |= OP_RNDTX;
}
}
void LMICcore_setDrJoin (u1_t reason, u1_t dr) {
LMIC_EV_PARAMETER(reason);
EV(drChange, INFO, (e_.reason = reason,
e_.deveui = MAIN::CDEV->getEui(),
e_.dr = dr|DR_PAGE,
e_.txpow = LMIC.adrTxPow,
e_.prevdr = LMIC.datarate|DR_PAGE,
e_.prevtxpow = LMIC.adrTxPow));
LMIC.datarate = dr;
DO_DEVDB(LMIC.datarate,datarate);
}
static void setDrTxpow (u1_t reason, u1_t dr, s1_t pow) {
LMIC_EV_PARAMETER(reason);
EV(drChange, INFO, (e_.reason = reason,
e_.deveui = MAIN::CDEV->getEui(),
e_.dr = dr|DR_PAGE,
e_.txpow = pow,
e_.prevdr = LMIC.datarate|DR_PAGE,
e_.prevtxpow = LMIC.adrTxPow));
if( pow != KEEP_TXPOW )
LMIC.adrTxPow = pow;
if( LMIC.datarate != dr ) {
LMIC.datarate = dr;
DO_DEVDB(LMIC.datarate,datarate);
LMIC.opmode |= OP_NEXTCHNL;
}
}
#if !defined(DISABLE_PING)
void LMIC_stopPingable (void) {
LMIC.opmode &= ~(OP_PINGABLE|OP_PINGINI);
}
void LMIC_setPingable (u1_t intvExp) {
// Change setting
LMIC.ping.intvExp = (intvExp & 0x7);
LMIC.opmode |= OP_PINGABLE;
// App may call LMIC_enableTracking() explicitely before
// Otherwise tracking is implicitly enabled here
if( (LMIC.opmode & (OP_TRACK|OP_SCAN)) == 0 && LMIC.bcninfoTries == 0 )
LMIC_enableTracking(0);
}
#endif // !DISABLE_PING
static void runEngineUpdate (xref2osjob_t osjob) {
LMIC_API_PARAMETER(osjob);
engineUpdate();
}
static void reportEvent (ev_t ev) {
EV(devCond, INFO, (e_.reason = EV::devCond_t::LMIC_EV,
e_.eui = MAIN::CDEV->getEui(),
e_.info = ev));
ON_LMIC_EVENT(ev);
engineUpdate();
}
static void runReset (xref2osjob_t osjob) {
LMIC_API_PARAMETER(osjob);
// Disable session
LMIC_reset();
#if !defined(DISABLE_JOIN)
LMIC_startJoining();
#endif // !DISABLE_JOIN
reportEvent(EV_RESET);
}
static void stateJustJoined (void) {
LMIC.seqnoDn = LMIC.seqnoUp = 0;
LMIC.rejoinCnt = 0;
LMIC.dnConf = LMIC.adrChanged = LMIC.ladrAns = LMIC.devsAns = 0;
#if !defined(DISABLE_MCMD_SNCH_REQ)
LMIC.snchAns = 0;
#endif
#if !defined(DISABLE_MCMD_DN2P_SET)
LMIC.dn2Ans = 0;
#endif
LMIC.moreData = 0;
#if !defined(DISABLE_MCMD_DCAP_REQ)
LMIC.dutyCapAns = 0;
#endif
#if !defined(DISABLE_MCMD_PING_SET) && !defined(DISABLE_PING)
LMIC.pingSetAns = 0;
#endif
LMIC.upRepeat = 0;
LMIC.adrAckReq = LINK_CHECK_INIT;
LMIC.dn2Dr = DR_DNW2;
LMIC.dn2Freq = FREQ_DNW2;
#if !defined(DISABLE_BEACONS)
LMIC.bcnChnl = CHNL_BCN;
#endif
#if !defined(DISABLE_PING)
LMIC.ping.freq = FREQ_PING;
LMIC.ping.dr = DR_PING;
#endif
}
// ================================================================================
// Decoding frames
#if !defined(DISABLE_BEACONS)
// Decode beacon - do not overwrite bcninfo unless we have a match!
static int decodeBeacon (void) {
ASSERT(LMIC.dataLen == LEN_BCN); // implicit header RX guarantees this
xref2u1_t d = LMIC.frame;
if(! LMICbandplan_isValidBeacon1(d))
return 0; // first (common) part fails CRC check
// First set of fields is ok
u4_t bcnnetid = os_rlsbf4(&d[OFF_BCN_NETID]) & 0xFFFFFF;
if( bcnnetid != LMIC.netid )
return -1; // not the beacon we're looking for
LMIC.bcninfo.flags &= ~(BCN_PARTIAL|BCN_FULL);
// Match - update bcninfo structure
LMIC.bcninfo.snr = LMIC.snr;
LMIC.bcninfo.rssi = LMIC.rssi;
LMIC.bcninfo.txtime = LMIC.rxtime - AIRTIME_BCN_osticks;
LMIC.bcninfo.time = os_rlsbf4(&d[OFF_BCN_TIME]);
LMIC.bcninfo.flags |= BCN_PARTIAL;
// Check 2nd set
if( os_rlsbf2(&d[OFF_BCN_CRC2]) != os_crc16(d,OFF_BCN_CRC2) )
return 1;
// Second set of fields is ok
LMIC.bcninfo.lat = (s4_t)os_rlsbf4(&d[OFF_BCN_LAT-1]) >> 8; // read as signed 24-bit
LMIC.bcninfo.lon = (s4_t)os_rlsbf4(&d[OFF_BCN_LON-1]) >> 8; // ditto
LMIC.bcninfo.info = d[OFF_BCN_INFO];
LMIC.bcninfo.flags |= BCN_FULL;
return 2;
}
#endif // !DISABLE_BEACONS
// scan mac commands starting at opts[] for olen, return count of bytes consumed.
static int
scan_mac_cmds(
const uint8_t *opts,
int olen
) {
int oidx = 0;
while( oidx < olen ) {
switch( opts[oidx] ) {
case MCMD_LCHK_ANS: {
//int gwmargin = opts[oidx+1];
//int ngws = opts[oidx+2];
oidx += 3;
continue;
}
case MCMD_LADR_REQ: {
u1_t p1 = opts[oidx+1]; // txpow + DR
u2_t chmap = os_rlsbf2(&opts[oidx+2]);// list of enabled channels
u1_t chpage = opts[oidx+4] & MCMD_LADR_CHPAGE_MASK; // channel page
u1_t uprpt = opts[oidx+4] & MCMD_LADR_REPEAT_MASK; // up repeat count
oidx += 5;
// TODO([email protected]): LoRaWAN 1.1 requires us to process multiple
// LADR requests, and only update if all pass. So this should check
// ladrAns == 0, and only initialize if so. Need to repeat ACKs, so
// we need to count the number we see.
LMIC.ladrAns = 0x80 | // Include an answer into next frame up
MCMD_LADR_ANS_POWACK | MCMD_LADR_ANS_CHACK | MCMD_LADR_ANS_DRACK;
if( !LMICbandplan_mapChannels(chpage, chmap) )
LMIC.ladrAns &= ~MCMD_LADR_ANS_CHACK;
dr_t dr = (dr_t)(p1>>MCMD_LADR_DR_SHIFT);
if( !validDR(dr) ) {
LMIC.ladrAns &= ~MCMD_LADR_ANS_DRACK;
EV(specCond, ERR, (e_.reason = EV::specCond_t::BAD_MAC_CMD,
e_.eui = MAIN::CDEV->getEui(),
e_.info = Base::lsbf4(&d[pend]),
e_.info2 = Base::msbf4(&opts[oidx-4])));
}
// TODO([email protected]): see above; this needs to move outside the
// txloop. And we need to have "consistent" answers for the block
// of contiguous commands (whatever that means), and ignore the
// data rate, NbTrans (uprpt) and txPow until the last one.
#if LMIC_DEBUG_LEVEL > 0
LMIC_DEBUG_PRINTF("%"LMIC_PRId_ostime_t": LinkAdrReq: p1:%02x chmap:%04x chpage:%02x uprt:%02x ans:%02x\n",
os_getTime(), p1, chmap, chpage, uprpt, LMIC.ladrAns
);
#endif /* LMIC_DEBUG_LEVEL */
if( (LMIC.ladrAns & 0x7F) == (MCMD_LADR_ANS_POWACK | MCMD_LADR_ANS_CHACK | MCMD_LADR_ANS_DRACK) ) {
// Nothing went wrong - use settings
LMIC.upRepeat = uprpt;
setDrTxpow(DRCHG_NWKCMD, dr, pow2dBm(p1));
}
LMIC.adrChanged = 1; // Trigger an ACK to NWK
continue;
}
case MCMD_DEVS_REQ: {
LMIC.devsAns = 1;
// LMIC.snr is SNR time 4, convert to real SNR; rounding towards zero.
const int snr = (LMIC.snr + 2) / 4;
// per [1.02] 5.5. the margin is the SNR.
LMIC.devAnsMargin = (u1_t)(0b00111111 & (snr <= -32 ? -32 : snr >= 31 ? 31 : snr));
oidx += 1;
continue;
}
case MCMD_DN2P_SET: {
#if !defined(DISABLE_MCMD_DN2P_SET)
dr_t dr = (dr_t)(opts[oidx+1] & 0x0F);
u1_t rx1DrOffset = (u1_t)((opts[oidx+1] & 0x70) >> 4);
u4_t freq = LMICbandplan_convFreq(&opts[oidx+2]);
LMIC.dn2Ans = 0x80; // answer pending
if( validDR(dr) )
LMIC.dn2Ans |= MCMD_DN2P_ANS_DRACK;
if( freq != 0 )
LMIC.dn2Ans |= MCMD_DN2P_ANS_CHACK;
if (rx1DrOffset <= 3)
LMIC.dn2Ans |= MCMD_DN2P_ANS_RX1DrOffsetAck;
if( LMIC.dn2Ans == (0x80|MCMD_DN2P_ANS_DRACK|MCMD_DN2P_ANS_CHACK| MCMD_DN2P_ANS_RX1DrOffsetAck) ) {
LMIC.dn2Dr = dr;
LMIC.dn2Freq = freq;
LMIC.rx1DrOffset = rx1DrOffset;
DO_DEVDB(LMIC.dn2Dr,dn2Dr);
DO_DEVDB(LMIC.dn2Freq,dn2Freq);
}
#endif // !DISABLE_MCMD_DN2P_SET
oidx += 5;
continue;
}
case MCMD_DCAP_REQ: {
#if !defined(DISABLE_MCMD_DCAP_REQ)
u1_t cap = opts[oidx+1];
// A value cap=0xFF means device is OFF unless enabled again manually.
if( cap==0xFF )
LMIC.opmode |= OP_SHUTDOWN; // stop any sending
LMIC.globalDutyRate = cap & 0xF;
LMIC.globalDutyAvail = os_getTime();
DO_DEVDB(cap,dutyCap);
LMIC.dutyCapAns = 1;
oidx += 2;
#endif // !DISABLE_MCMD_DCAP_REQ
continue;
}
case MCMD_SNCH_REQ: {
#if !defined(DISABLE_MCMD_SNCH_REQ)
u1_t chidx = opts[oidx+1]; // channel
u4_t freq = LMICbandplan_convFreq(&opts[oidx+2]); // freq
u1_t drs = opts[oidx+5]; // datarate span
LMIC.snchAns = 0x80;
if( freq != 0 && LMIC_setupChannel(chidx, freq, DR_RANGE_MAP(drs&0xF,drs>>4), -1) )
LMIC.snchAns |= MCMD_SNCH_ANS_DRACK|MCMD_SNCH_ANS_FQACK;
#endif // !DISABLE_MCMD_SNCH_REQ
oidx += 6;
continue;
}
case MCMD_PING_SET: {
#if !defined(DISABLE_MCMD_PING_SET) && !defined(DISABLE_PING)
u4_t freq = LMICbandplan_convFreq(&opts[oidx+1]);
u1_t flags = 0x80;
if( freq != 0 ) {
flags |= MCMD_PING_ANS_FQACK;
LMIC.ping.freq = freq;
DO_DEVDB(LMIC.ping.intvExp, pingIntvExp);
DO_DEVDB(LMIC.ping.freq, pingFreq);
DO_DEVDB(LMIC.ping.dr, pingDr);
}
LMIC.pingSetAns = flags;
#endif // !DISABLE_MCMD_PING_SET && !DISABLE_PING
oidx += 4;
continue;
}
case MCMD_BCNI_ANS: {
#if !defined(DISABLE_MCMD_BCNI_ANS) && !defined(DISABLE_BEACONS)
// Ignore if tracking already enabled
if( (LMIC.opmode & OP_TRACK) == 0 ) {
LMIC.bcnChnl = opts[oidx+3];
// Enable tracking - bcninfoTries
LMIC.opmode |= OP_TRACK;
// Cleared later in txComplete handling - triggers EV_BEACON_FOUND
ASSERT(LMIC.bcninfoTries!=0);
// Setup RX parameters
LMIC.bcninfo.txtime = (LMIC.rxtime
+ ms2osticks(os_rlsbf2(&opts[oidx+1]) * MCMD_BCNI_TUNIT)
+ ms2osticksCeil(MCMD_BCNI_TUNIT/2)
- BCN_INTV_osticks);
LMIC.bcninfo.flags = 0; // txtime above cannot be used as reference (BCN_PARTIAL|BCN_FULL cleared)
calcBcnRxWindowFromMillis(MCMD_BCNI_TUNIT,1); // error of +/-N ms
EV(lostFrame, INFO, (e_.reason = EV::lostFrame_t::MCMD_BCNI_ANS,
e_.eui = MAIN::CDEV->getEui(),
e_.lostmic = Base::lsbf4(&d[pend]),
e_.info = (LMIC.missedBcns |
(osticks2us(LMIC.bcninfo.txtime + BCN_INTV_osticks
- LMIC.bcnRxtime) << 8)),
e_.time = MAIN::CDEV->ostime2ustime(LMIC.bcninfo.txtime + BCN_INTV_osticks)));
}
#endif // !DISABLE_MCMD_BCNI_ANS && !DISABLE_BEACONS
oidx += 4;
continue;
} /* end case */
case MCMD_TxParamSetupReq: {
#if LMIC_ENABLE_TxParamSetupReq
uint8_t txParam;
txParam = opts[oidx+1];
// we don't allow unrecognized bits to come through
txParam &= (MCMD_TxParam_RxDWELL_MASK|
MCMD_TxParam_TxDWELL_MASK|
MCMD_TxParam_MaxEIRP_MASK);
LMIC.txParam = txParam;
LMIC.txParamSetupAns = 1;
#endif // LMIC_ENABLE_TxParamSetupReq
oidx += 2;
continue;
} /* end case */
case MCMD_DeviceTimeAns: {
#if LMIC_ENABLE_DeviceTimeReq
// don't process a spurious downlink.
if ( LMIC.txDeviceTimeReqState == lmic_RequestTimeState_rx ) {
// remember that it's time to notify the client.
LMIC.txDeviceTimeReqState = lmic_RequestTimeState_success;
// the network time is linked to the time of the last TX.
LMIC.localDeviceTime = LMIC.txend;
// save the network time.
// The first 4 bytes contain the seconds since the GPS epoch
// (i.e January the 6th 1980 at 00:00:00 UTC).
// Note: as per the LoRaWAN specs, the octet order for all
// multi-octet fields is little endian
// Note: the casts are necessary, because opts is an array of
// single byte values, and they might overflow when shifted
LMIC.netDeviceTime = ( (lmic_gpstime_t) opts[oidx + 1] ) |
(((lmic_gpstime_t) opts[oidx + 2]) << 8) |
(((lmic_gpstime_t) opts[oidx + 3]) << 16) |
(((lmic_gpstime_t) opts[oidx + 4]) << 24);
// The 5th byte contains the fractional seconds in 2^-8 second steps
LMIC.netDeviceTimeFrac = opts[oidx + 5];
#if LMIC_DEBUG_LEVEL > 0
LMIC_DEBUG_PRINTF("%"LMIC_PRId_ostime_t": MAC command DeviceTimeAns received: seconds_since_gps_epoch=%"PRIu32", fractional_seconds=%d\n", os_getTime(), LMIC.netDeviceTime, LMIC.netDeviceTimeFrac);
#endif
}
#endif // LMIC_ENABLE_DeviceTimeReq
oidx += 6;
continue;
} /* end case */
} /* end switch */
/* unrecognized mac commands fall out of switch to here */
EV(specCond, ERR, (e_.reason = EV::specCond_t::BAD_MAC_CMD,
e_.eui = MAIN::CDEV->getEui(),
e_.info = Base::lsbf4(&d[pend]),
e_.info2 = Base::msbf4(&opts[oidx])));
/* stop processing options */
break;
} /* end while */
return oidx;
}
static bit_t decodeFrame (void) {
xref2u1_t d = LMIC.frame;
u1_t hdr = d[0];
u1_t ftype = hdr & HDR_FTYPE;
int dlen = LMIC.dataLen;
#if LMIC_DEBUG_LEVEL > 0
const char *window = (LMIC.txrxFlags & TXRX_DNW1) ? "RX1" : ((LMIC.txrxFlags & TXRX_DNW2) ? "RX2" : "Other");
#endif
if( dlen < OFF_DAT_OPTS+4 ||
(hdr & HDR_MAJOR) != HDR_MAJOR_V1 ||
(ftype != HDR_FTYPE_DADN && ftype != HDR_FTYPE_DCDN) ) {
// Basic sanity checks failed
EV(specCond, WARN, (e_.reason = EV::specCond_t::UNEXPECTED_FRAME,
e_.eui = MAIN::CDEV->getEui(),
e_.info = dlen < 4 ? 0 : os_rlsbf4(&d[dlen-4]),
e_.info2 = hdr + (dlen<<8)));
norx:
#if LMIC_DEBUG_LEVEL > 0
LMIC_DEBUG_PRINTF("%"LMIC_PRId_ostime_t": Invalid downlink, window=%s\n", os_getTime(), window);
#endif
LMIC.dataLen = 0;
return 0;
}
// Validate exact frame length
// Note: device address was already read+evaluated in order to arrive here.
int fct = d[OFF_DAT_FCT];
u4_t addr = os_rlsbf4(&d[OFF_DAT_ADDR]);
u4_t seqno = os_rlsbf2(&d[OFF_DAT_SEQNO]);
int olen = fct & FCT_OPTLEN;
int ackup = (fct & FCT_ACK) != 0 ? 1 : 0; // ACK last up frame
int poff = OFF_DAT_OPTS+olen;
int pend = dlen-4; // MIC
if( addr != LMIC.devaddr ) {
EV(specCond, WARN, (e_.reason = EV::specCond_t::ALIEN_ADDRESS,
e_.eui = MAIN::CDEV->getEui(),
e_.info = addr,
e_.info2 = LMIC.devaddr));
goto norx;
}
if( poff > pend ) {
EV(specCond, ERR, (e_.reason = EV::specCond_t::CORRUPTED_FRAME,
e_.eui = MAIN::CDEV->getEui(),
e_.info = 0x1000000 + (poff-pend) + (fct<<8) + (dlen<<16)));
goto norx;
}
int port = -1;
int replayConf = 0;
if( pend > poff )
port = d[poff++];
seqno = LMIC.seqnoDn + (u2_t)(seqno - LMIC.seqnoDn);
if( !aes_verifyMic(LMIC.nwkKey, LMIC.devaddr, seqno, /*dn*/1, d, pend) ) {
EV(spe3Cond, ERR, (e_.reason = EV::spe3Cond_t::CORRUPTED_MIC,
e_.eui1 = MAIN::CDEV->getEui(),
e_.info1 = Base::lsbf4(&d[pend]),
e_.info2 = seqno,
e_.info3 = LMIC.devaddr));
goto norx;
}
if( seqno < LMIC.seqnoDn ) {
if( (s4_t)seqno > (s4_t)LMIC.seqnoDn ) {
EV(specCond, INFO, (e_.reason = EV::specCond_t::DNSEQNO_ROLL_OVER,
e_.eui = MAIN::CDEV->getEui(),
e_.info = LMIC.seqnoDn,
e_.info2 = seqno));
goto norx;
}
if( seqno != LMIC.seqnoDn-1 || !LMIC.dnConf || ftype != HDR_FTYPE_DCDN ) {
EV(specCond, INFO, (e_.reason = EV::specCond_t::DNSEQNO_OBSOLETE,
e_.eui = MAIN::CDEV->getEui(),
e_.info = LMIC.seqnoDn,
e_.info2 = seqno));
goto norx;
}
// Replay of previous sequence number allowed only if
// previous frame and repeated both requested confirmation
replayConf = 1;
}
else {
if( seqno > LMIC.seqnoDn ) {
EV(specCond, INFO, (e_.reason = EV::specCond_t::DNSEQNO_SKIP,
e_.eui = MAIN::CDEV->getEui(),
e_.info = LMIC.seqnoDn,
e_.info2 = seqno));
}
LMIC.seqnoDn = seqno+1; // next number to be expected
DO_DEVDB(LMIC.seqnoDn,seqnoDn);
// DN frame requested confirmation - provide ACK once with next UP frame
LMIC.dnConf = (ftype == HDR_FTYPE_DCDN ? FCT_ACK : 0);
}
if( LMIC.dnConf || (fct & FCT_MORE) )
LMIC.opmode |= OP_POLL;
// We heard from network
LMIC.adrChanged = LMIC.rejoinCnt = 0;
if( LMIC.adrAckReq != LINK_CHECK_OFF )
LMIC.adrAckReq = LINK_CHECK_INIT;
int m = LMIC.rssi - RSSI_OFF - getSensitivity(LMIC.rps);
// for legacy reasons, LMIC.margin is set to the unsigned sensitivity. It can never be negative.
// it's only computed for legacy clients
LMIC.margin = m < 0 ? 0 : m > 254 ? 254 : m;
#if LMIC_DEBUG_LEVEL > 0
// Process OPTS
LMIC_DEBUG_PRINTF("%"LMIC_PRId_ostime_t": process options (olen=%#x)\n", os_getTime(), olen);
#endif
xref2u1_t opts = &d[OFF_DAT_OPTS];
int oidx = scan_mac_cmds(opts, olen);
if( oidx != olen ) {
EV(specCond, ERR, (e_.reason = EV::specCond_t::CORRUPTED_FRAME,
e_.eui = MAIN::CDEV->getEui(),
e_.info = 0x1000000 + (oidx) + (olen<<8)));
}
if( !replayConf ) {
// Handle payload only if not a replay
// Decrypt payload - if any
if( port >= 0 && pend-poff > 0 ) {
aes_cipher(port <= 0 ? LMIC.nwkKey : LMIC.artKey, LMIC.devaddr, seqno, /*dn*/1, d+poff, pend-poff);
if (port == 0) {
// this is a mac command. scan the options.
#if LMIC_DEBUG_LEVEL > 0
LMIC_DEBUG_PRINTF("%"LMIC_PRId_ostime_t": process mac commands for port 0 (olen=%#x)\n", os_getTime(), pend-poff);
#endif
int optendindex = scan_mac_cmds(d+poff, pend-poff);
if (optendindex != pend-poff) {
#if LMIC_DEBUG_LEVEL > 0
LMIC_DEBUG_PRINTF(
"%"LMIC_PRId_ostime_t": error processing mac commands for port 0 "
"(len=%#x, optendindex=%#x)\n",
os_getTime(), pend-poff, optendindex
);
#endif
}
}
} // end decrypt payload
EV(dfinfo, DEBUG, (e_.deveui = MAIN::CDEV->getEui(),
e_.devaddr = LMIC.devaddr,
e_.seqno = seqno,
e_.flags = (port < 0 ? EV::dfinfo_t::NOPORT : 0) | EV::dfinfo_t::DN,
e_.mic = Base::lsbf4(&d[pend]),
e_.hdr = d[LORA::OFF_DAT_HDR],
e_.fct = d[LORA::OFF_DAT_FCT],
e_.port = port,
e_.plen = dlen,
e_.opts.length = olen,
memcpy(&e_.opts[0], opts, olen)));
} else {
EV(specCond, INFO, (e_.reason = EV::specCond_t::DNSEQNO_REPLAY,
e_.eui = MAIN::CDEV->getEui(),
e_.info = Base::lsbf4(&d[pend]),
e_.info2 = seqno));
}
if( // NWK acks but we don't have a frame pending
(ackup && LMIC.txCnt == 0) ||
// We sent up confirmed and we got a response in DNW1/DNW2
// BUT it did not carry an ACK - this should never happen
// Do not resend and assume frame was not ACKed.
(!ackup && LMIC.txCnt != 0) ) {
EV(specCond, ERR, (e_.reason = EV::specCond_t::SPURIOUS_ACK,
e_.eui = MAIN::CDEV->getEui(),
e_.info = seqno,
e_.info2 = ackup));
#if LMIC_DEBUG_LEVEL > 1
LMIC_DEBUG_PRINTF("%"LMIC_PRId_ostime_t": ??ack error ack=%d txCnt=%d\n", os_getTime(), ackup, LMIC.txCnt);
#endif
}
if( LMIC.txCnt != 0 ) // we requested an ACK
orTxrxFlags(__func__, ackup ? TXRX_ACK : TXRX_NACK);
if( port <= 0 ) {
orTxrxFlags(__func__, TXRX_NOPORT);
LMIC.dataBeg = poff;
LMIC.dataLen = 0;
} else {
orTxrxFlags(__func__, TXRX_PORT);
LMIC.dataBeg = poff;
LMIC.dataLen = pend-poff;
}
#if LMIC_DEBUG_LEVEL > 0
LMIC_DEBUG_PRINTF("%"LMIC_PRId_ostime_t": Received downlink, window=%s, port=%d, ack=%d, txrxFlags=%#x\n", os_getTime(), window, port, ackup, LMIC.txrxFlags);
#endif
return 1;
}
// ================================================================================
// TX/RX transaction support
static void setupRx2 (void) {
initTxrxFlags(__func__, TXRX_DNW2);
LMIC.rps = dndr2rps(LMIC.dn2Dr);
LMIC.freq = LMIC.dn2Freq;
LMIC.dataLen = 0;
os_radio(RADIO_RX);
}
static void schedRx12 (ostime_t delay, osjobcb_t func, u1_t dr) {
ostime_t hsym = dr2hsym(dr);
LMIC.rxsyms = MINRX_SYMS;
// If a clock error is specified, compensate for it by extending the
// receive window
if (LMIC.clockError != 0) {
// Calculate how much the clock will drift maximally after delay has
// passed. This indicates the amount of time we can be early
// _or_ late.
ostime_t drift = (int64_t)delay * LMIC.clockError / MAX_CLOCK_ERROR;
// Increase the receive window by twice the maximum drift (to
// compensate for a slow or a fast clock).
// decrease the rxtime to compensate for. Note that hsym is a
// *half* symbol time, so the factor 2 is hidden. First check if
// this would overflow (which can happen if the drift is very
// high, or the symbol time is low at high datarates).
if ((255 - LMIC.rxsyms) * hsym < drift)
LMIC.rxsyms = 255;
else
LMIC.rxsyms += drift / hsym;
}
// Center the receive window on the center of the expected preamble
// (again note that hsym is half a sumbol time, so no /2 needed)
LMIC.rxtime = LMIC.txend + delay + PAMBL_SYMS * hsym - LMIC.rxsyms * hsym;
LMIC_X_DEBUG_PRINTF("%"LMIC_PRId_ostime_t": sched Rx12 %"LMIC_PRId_ostime_t"\n", os_getTime(), LMIC.rxtime - RX_RAMPUP);
os_setTimedCallback(&LMIC.osjob, LMIC.rxtime - RX_RAMPUP, func);