This repository has been archived by the owner on Dec 23, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
SlimLoRa.cpp
1776 lines (1441 loc) · 49.6 KB
/
SlimLoRa.cpp
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) 2018-2021 Hendrik Hagendorn
* Copyright (c) 2015-2016 Ideetron B.V. - AES routines
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http:// www.gnu.org/licenses/>.
*/
#include <avr/pgmspace.h>
#include <Arduino.h>
#include <SPI.h>
#include "SlimLoRa.h"
#if LORAWAN_OTAA_ENABLED
extern const uint8_t DevEUI[8];
extern const uint8_t JoinEUI[8];
extern const uint8_t NwkKey[16];
extern const uint8_t AppKey[16];
#else
extern const uint8_t NwkSKey[16];
extern const uint8_t AppSKey[16];
extern const uint8_t DevAddr[4];
#endif
static SPISettings spi_settings = SPISettings(4000000, MSBFIRST, SPI_MODE0);
// Frequency band for europe
const uint8_t PROGMEM SlimLoRa::kFrequencyTable[9][3] = {
{ 0xD9, 0x06, 0x8B }, // Channel 0 868.100 MHz / 61.035 Hz = 14222987 = 0xD9068B
{ 0xD9, 0x13, 0x58 }, // Channel 1 868.300 MHz / 61.035 Hz = 14226264 = 0xD91358
{ 0xD9, 0x20, 0x24 }, // Channel 2 868.500 MHz / 61.035 Hz = 14229540 = 0xD92024
{ 0xD8, 0xC6, 0x8B }, // Channel 3 867.100 MHz / 61.035 Hz = 14206603 = 0xD8C68B
{ 0xD8, 0xD3, 0x58 }, // Channel 4 867.300 MHz / 61.035 Hz = 14209880 = 0xD8D358
{ 0xD8, 0xE0, 0x24 }, // Channel 5 867.500 MHz / 61.035 Hz = 14213156 = 0xD8E024
{ 0xD8, 0xEC, 0xF1 }, // Channel 6 867.700 MHz / 61.035 Hz = 14216433 = 0xD8ECF1
{ 0xD8, 0xF9, 0xBE }, // Channel 7 867.900 MHz / 61.035 Hz = 14219710 = 0xD8F9BE
{ 0xD9, 0x61, 0xBE } // Downlink 869.525 MHz / 61.035 Hz = 14246334 = 0xD961BE
};
// Data rate
const uint8_t PROGMEM SlimLoRa::kDataRateTable[7][3] = {
// bw sf agc
{ 0x72, 0xC4, 0x0C }, // SF12BW125
{ 0x72, 0xB4, 0x0C }, // SF11BW125
{ 0x72, 0xA4, 0x04 }, // SF10BW125
{ 0x72, 0x94, 0x04 }, // SF9BW125
{ 0x72, 0x84, 0x04 }, // SF8BW125
{ 0x72, 0x74, 0x04 }, // SF7BW125
{ 0x82, 0x74, 0x04 } // SF7BW250
};
// Half symbol times
const uint16_t PROGMEM SlimLoRa::kDRMicrosPerHalfSymbol[7] = {
((128 << 7) * MICROS_PER_SECOND + 500000) / 1000000, // SF12BW125
((128 << 6) * MICROS_PER_SECOND + 500000) / 1000000, // SF11BW125
((128 << 5) * MICROS_PER_SECOND + 500000) / 1000000, // SF10BW125
((128 << 4) * MICROS_PER_SECOND + 500000) / 1000000, // SF9BW125
((128 << 3) * MICROS_PER_SECOND + 500000) / 1000000, // SF8BW125
((128 << 2) * MICROS_PER_SECOND + 500000) / 1000000, // SF7BW125
((128 << 1) * MICROS_PER_SECOND + 500000) / 1000000 // SF7BW250
};
// S table for AES encryption
const uint8_t PROGMEM SlimLoRa::kSTable[16][16] = {
{0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76},
{0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0},
{0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15},
{0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75},
{0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84},
{0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF},
{0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0xA8},
{0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, 0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2},
{0xCD, 0x0C, 0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73},
{0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14, 0xDE, 0x5E, 0x0B, 0xDB},
{0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C, 0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79},
{0xE7, 0xC8, 0x37, 0x6D, 0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08},
{0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F, 0x4B, 0xBD, 0x8B, 0x8A},
{0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E, 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E},
{0xE1, 0xF8, 0x98, 0x11, 0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF},
{0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16}
};
TinyLoRa::TinyLoRa(uint8_t pin_nss) {
pin_nss_ = pin_nss;
}
void SlimLoRa::Begin() {
uint8_t detect_optimize;
SPI.begin();
pinMode(pin_nss_, OUTPUT);
// Sleep
RfmWrite(RFM_REG_OP_MODE, 0x00);
// LoRa mode
RfmWrite(RFM_REG_OP_MODE, 0x80);
// PA_BOOST pin / +16 dBm output power
RfmWrite(RFM_REG_PA_CONFIG, 0xFE);
// Preamble length: 8 symbols
// 0x0008 + 4 = 12
RfmWrite(RFM_REG_PREAMBLE_MSB, 0x00);
RfmWrite(RFM_REG_PREAMBLE_LSB, 0x08);
// LoRa sync word
RfmWrite(RFM_REG_SYNC_WORD, 0x34);
// Errata Note - 2.3 Receiver Spurious Reception
detect_optimize = RfmRead(RFM_REG_DETECT_OPTIMIZE);
RfmWrite(RFM_REG_DETECT_OPTIMIZE, (detect_optimize & 0x78) | 0x03);
RfmWrite(RFM_REG_IF_FREQ_1, 0x00);
RfmWrite(RFM_REG_IF_FREQ_2, 0x40);
// FIFO pointers
RfmWrite(RFM_REG_FIFO_TX_BASE_ADDR, 0x80);
RfmWrite(RFM_REG_FIFO_RX_BASE_ADDR, 0x00);
// Init MAC state
has_joined_ = GetHasJoined();
tx_frame_counter_ = GetTxFrameCounter();
rx_frame_counter_ = GetRxFrameCounter();
rx2_data_rate_ = GetRx2DataRate();
rx1_delay_micros_ = GetRx1Delay() * MICROS_PER_SECOND;
}
/**
* Function for receiving a packet using the RFM
*
* @param packet Pointer to RX packet array.
* @param packet_max_length Maximum number of bytes to read from RX packet.
* @param channel The frequency table channel index.
* @param dri The data rate table index.
* @param rx_microsstamp Listen until rx_microsstamp elapsed.
* @return The packet length or an error code.
*/
int8_t SlimLoRa::RfmReceivePacket(uint8_t *packet, uint8_t packet_max_length, uint8_t channel, uint8_t dri, uint32_t rx_microsstamp) {
uint8_t modem_config_3, irq_flags, packet_length, read_length;
// Wait for start time
wait_until(rx_microsstamp - LORAWAN_RX_SETUP_MICROS);
// Switch RFM to standby
RfmWrite(RFM_REG_OP_MODE, 0x81);
// Invert IQ
RfmWrite(RFM_REG_INVERT_IQ, 0x66);
RfmWrite(RFM_REG_INVERT_IQ_2, 0x19);
// Set SPI pointer to start of Rx part in FiFo
RfmWrite(RFM_REG_FIFO_ADDR_PTR, 0x00);
// Channel
RfmWrite(RFM_REG_FR_MSB, pgm_read_byte(&(kFrequencyTable[channel][0])));
RfmWrite(RFM_REG_FR_MID, pgm_read_byte(&(kFrequencyTable[channel][1])));
RfmWrite(RFM_REG_FR_LSB, pgm_read_byte(&(kFrequencyTable[channel][2])));
// Bandwidth / Coding Rate / Implicit Header Mode
RfmWrite(RFM_REG_MODEM_CONFIG_1, pgm_read_byte(&(kDataRateTable[dri][0])));
// Spreading Factor / Tx Continuous Mode / Crc
RfmWrite(RFM_REG_MODEM_CONFIG_2, pgm_read_byte(&(kDataRateTable[dri][1])));
// Automatic Gain Control / Low Data Rate Optimize
modem_config_3 = pgm_read_byte(&(kDataRateTable[dri][2]));
if (dri == SF12BW125 || dri == SF11BW125) {
modem_config_3 |= 0x08;
}
RfmWrite(RFM_REG_MODEM_CONFIG_3, modem_config_3);
// Rx timeout
RfmWrite(RFM_REG_SYMB_TIMEOUT_LSB, rx_symbols_);
// Clear interrupts
RfmWrite(RFM_REG_IRQ_FLAGS, 0xFF);
// Wait for rx time
wait_until(rx_microsstamp);
// Switch RFM to Rx
RfmWrite(RFM_REG_OP_MODE, 0x86);
// Wait for RxDone or RxTimeout
do {
irq_flags = RfmRead(RFM_REG_IRQ_FLAGS);
} while (!(irq_flags & 0xC0));
packet_length = RfmRead(RFM_REG_RX_NB_BYTES);
RfmWrite(RFM_REG_FIFO_ADDR_PTR, RfmRead(RFM_REG_FIFO_RX_CURRENT_ADDR));
if (packet_max_length < packet_length) {
read_length = packet_max_length;
} else {
read_length = packet_length;
}
for (uint8_t i = 0; i < read_length; i++) {
packet[i] = RfmRead(RFM_REG_FIFO);
}
// SNR
last_packet_snr_ = (int8_t) RfmRead(RFM_REG_PKT_SNR_VALUE) / 4;
// Clear interrupts
RfmWrite(RFM_REG_IRQ_FLAGS, 0xFF);
// Switch RFM to sleep
RfmWrite(RFM_REG_OP_MODE, 0x00);
switch (irq_flags & 0xC0) {
case RFM_STATUS_RX_TIMEOUT:
return RFM_ERROR_RX_TIMEOUT;
case RFM_STATUS_RX_DONE_CRC_ERROR:
return RFM_ERROR_CRC;
case RFM_STATUS_RX_DONE:
return packet_length;
}
return RFM_ERROR_UNKNOWN;
}
/**
* Senda a packet using the RFM.
*
* @param packet Pointer to TX packet array.
* @param packet_length Length of the TX packet.
* @param channel The frequency table channel index.
* @param dri The data rate table index.
*/
void SlimLoRa::RfmSendPacket(uint8_t *packet, uint8_t packet_length, uint8_t channel, uint8_t dri) {
uint8_t modem_config_3;
// Switch RFM to standby
RfmWrite(RFM_REG_OP_MODE, 0x81);
// Don't invert IQ
RfmWrite(RFM_REG_INVERT_IQ, 0x27);
RfmWrite(RFM_REG_INVERT_IQ_2, 0x1D);
// Channel
RfmWrite(RFM_REG_FR_MSB, pgm_read_byte(&(kFrequencyTable[channel][0])));
RfmWrite(RFM_REG_FR_MID, pgm_read_byte(&(kFrequencyTable[channel][1])));
RfmWrite(RFM_REG_FR_LSB, pgm_read_byte(&(kFrequencyTable[channel][2])));
// Bandwidth / Coding Rate / Implicit Header Mode
RfmWrite(RFM_REG_MODEM_CONFIG_1, pgm_read_byte(&(kDataRateTable[dri][0])));
// Spreading Factor / Tx Continuous Mode / Crc
RfmWrite(RFM_REG_MODEM_CONFIG_2, pgm_read_byte(&(kDataRateTable[dri][1])));
// Automatic Gain Control / Low Data Rate Optimize
modem_config_3 = pgm_read_byte(&(kDataRateTable[dri][2]));
if (dri == SF12BW125 || dri == SF11BW125) {
modem_config_3 |= 0x08;
}
RfmWrite(RFM_REG_MODEM_CONFIG_3, modem_config_3);
// Set payload length to the right length
RfmWrite(RFM_REG_PAYLOAD_LENGTH, packet_length);
// Set SPI pointer to start of Tx part in FiFo
RfmWrite(RFM_REG_FIFO_ADDR_PTR, 0x80);
// Write Payload to FiFo
for (uint8_t i = 0; i < packet_length; i++) {
RfmWrite(RFM_REG_FIFO, *packet);
packet++;
}
// Switch RFM to Tx
RfmWrite(RFM_REG_OP_MODE, 0x83);
// Wait for TxDone in the RegIrqFlags register
while ((RfmRead(RFM_REG_IRQ_FLAGS) & RFM_STATUS_TX_DONE) != RFM_STATUS_TX_DONE);
ATOMIC_BLOCK(ATOMIC_FORCEON) {
tx_done_micros_ = micros();
}
// Clear interrupt
RfmWrite(RFM_REG_IRQ_FLAGS, 0xFF);
// Switch RFM to sleep
RfmWrite(RFM_REG_OP_MODE, 0x00);
// Saves memory cycles, at worst 10 lost packets
if (++tx_frame_counter_ % 10) {
SetTxFrameCounter(tx_frame_counter_);
}
adr_ack_counter_++;
}
/**
* Writes a value to a register of the RFM.
*
* @param address Address of the register to be written.
* @param data Data to be written.
*/
void SlimLoRa::RfmWrite(uint8_t address, uint8_t data) {
SPI.beginTransaction(RFM_spisettings);
// Set NSS pin Low to start communication
digitalWrite(pin_nss_, LOW);
// Send addres with MSB 1 to write
SPI.transfer(address | 0x80);
// Send Data
SPI.transfer(data);
// Set NSS pin High to end communication
digitalWrite(pin_nss_, HIGH);
SPI.endTransaction();
}
/**
* Reads a value from a register of the RFM.
*
* @param address Address of the register to be read.
* @return The value of the register.
*/
uint8_t SlimLoRa::RfmRead(uint8_t address) {
uint8_t data;
SPI.beginTransaction(RFM_spisettings);
// Set NSS pin low to start SPI communication
digitalWrite(pin_nss_, LOW);
// Send Address
SPI.transfer(address);
// Receive
data = SPI.transfer(0x00);
// Set NSS high to end communication
digitalWrite(pin_nss_, HIGH);
SPI.endTransaction();
// Return received data
return data;
}
/**
* Calculates the clock drift adjustment(+-5%).
*/
uint32_t SlimLoRa::CaluclateDriftAdjustment(uint32_t delay, uint16_t micros_per_half_symbol) {
// Clock drift
uint32_t drift = delay * 5 / 100;
delay -= drift;
if ((255 - rx_symbols_) * micros_per_half_symbol < drift) {
rx_symbols_ = 255;
} else {
rx_symbols_ = 6 + drift / micros_per_half_symbol;
}
return delay;
}
/**
* Calculates the centered RX window offest.
*/
int32_t SlimLoRa::CalculateRxWindowOffset(int16_t micros_per_half_symbol) {
const uint16_t micros_per_symbol = 2 * micros_per_half_symbol;
uint8_t rx_symbols = ((2 * LORAWAN_RX_MIN_SYMBOLS - 8) * micros_per_symbol + 2 * LORAWAN_RX_ERROR_MICROS + micros_per_symbol - 1) / micros_per_symbol;
if (rx_symbols < LORAWAN_RX_MIN_SYMBOLS) {
rx_symbols = LORAWAN_RX_MIN_SYMBOLS;
}
rx_symbols_ = rx_symbols;
return (8 - rx_symbols) * micros_per_half_symbol - LORAWAN_RX_MARGIN_MICROS;
}
/**
* Calculates the RX delay for a given data rate.
*
* @return The RX delay in micros.
*/
uint32_t SlimLoRa::CalculateRxDelay(uint8_t data_rate, uint32_t delay) {
uint16_t micros_per_half_symbol;
int32_t offset;
micros_per_half_symbol = pgm_read_word(&(kDRMicrosPerHalfSymbol[data_rate]));
offset = CalculateRxWindowOffset(micros_per_half_symbol);
return CaluclateDriftAdjustment(delay + offset, micros_per_half_symbol);
}
/**
* Enables/disables the ADR mechanism.
*/
void SlimLoRa::SetAdrEnabled(bool enabled) {
adr_enabled_ = enabled;
}
#if LORAWAN_OTAA_ENABLED
/**
* Check if the device joined a LoRaWAN network.
*/
bool SlimLoRa::HasJoined() {
return has_joined_;
}
/**
* Constructs a LoRaWAN JoinRequest packet and sends it.
*
* @return 0 or an error code.
*/
int8_t SlimLoRa::Join() {
uint8_t packet[1 + LORAWAN_JOIN_REQUEST_SIZE + 4];
uint8_t packet_length;
uint16_t dev_nonce;
uint8_t mic[4];
packet[0] = LORAWAN_MTYPE_JOIN_REQUEST;
packet[1] = JoinEUI[7];
packet[2] = JoinEUI[6];
packet[3] = JoinEUI[5];
packet[4] = JoinEUI[4];
packet[5] = JoinEUI[3];
packet[6] = JoinEUI[2];
packet[7] = JoinEUI[1];
packet[8] = JoinEUI[0];
packet[9] = DevEUI[7];
packet[10] = DevEUI[6];
packet[11] = DevEUI[5];
packet[12] = DevEUI[4];
packet[13] = DevEUI[3];
packet[14] = DevEUI[2];
packet[15] = DevEUI[1];
packet[16] = DevEUI[0];
dev_nonce = GetDevNonce();
SetDevNonce(++dev_nonce);
packet[17] = dev_nonce & 0xFF;
packet[18] = dev_nonce++ >> 8;
packet_length = 1 + LORAWAN_JOIN_REQUEST_SIZE;
#if LORAWAN_V1_1_ENABLED
CalculateMic(NwkKey, packet, NULL, mic, packet_length);
#else
CalculateMic(AppKey, packet, NULL, mic, packet_length);
#endif // LORAWAN_V1_1_ENABLED
for (uint8_t i = 0; i < 4; i++) {
packet[i + packet_length] = mic[i];
}
packet_length += 4;
channel_ = pseudo_byte_ & 0x01;
RfmSendPacket(packet, packet_length, channel_, data_rate_, true);
if (!ProcessJoinAccept(1)) {
return 0;
}
return ProcessJoinAccept(2);
}
/**
* Validates the calculated 4-byte MIC against the received 4-byte MIC.
*
* @param cmic Calculated 4-byte MIC.
* @param rmic Received 4-byte MIC.
*/
bool SlimLoRa::CheckMic(uint8_t *cmic, uint8_t *rmic) {
return cmic[0] == rmic[0] && cmic[1] == rmic[1]
&& cmic[2] == rmic[2] && cmic[3] == rmic[3];
}
/**
* Processes LoRaWAN 1.0 JoinAccept message.
*
* @param packet Received JoinAccept packet bytes.
* @param packet_length Length of the received packet.
* @return True if MIC validation succeeded, else false.
*/
bool SlimLoRa::ProcessJoinAccept1_0(uint8_t *packet, uint8_t packet_length) {
uint8_t buffer[16], mic[4];
uint8_t packet_length_no_mic = packet_length - 4;
uint16_t dev_nonce;
CalculateMic(AppKey, packet, NULL, mic, packet_length_no_mic);
if (!CheckMic(mic, packet + packet_length_no_mic)) {
return false;
}
dev_nonce = GetDevNonce();
// Derive AppSKey, FNwkSIntKey, SNwkSIntKey, NwkSEncKey
for (uint8_t i = 1; i <= 2; i++) {
memset(buffer, 0, 16);
buffer[0] = i;
// JoinNonce
buffer[1] = packet[1];
buffer[2] = packet[2];
buffer[3] = packet[3];
// NetID
buffer[4] = packet[4];
buffer[5] = packet[5];
buffer[6] = packet[6];
// DevNonce
buffer[7] = dev_nonce & 0xFF;
buffer[8] = dev_nonce >> 8;
AesEncrypt(AppKey, buffer);
if (i == 1) {
SetFNwkSIntKey(buffer);
SetSNwkSIntKey(buffer);
SetNwkSEncKey(buffer);
} else {
SetAppSKey(buffer);
}
}
return true;
}
#if LORAWAN_V1_1_ENABLED
/**
* Processes a LoRaWAN 1.1 JoiNAccept message.
*
* @param packet Received JoinAccept packet bytes.
* @param packet_length Length of the received packet.
* @return True if MIC validation succeeded, else false.
*/
bool SlimLoRa::ProcessJoinAccept1_1(uint8_t *packet, uint8_t packet_length) {
uint8_t buffer[40] = { 0 }, mic[4];
uint8_t packet_length_no_mic = packet_length - 4;
uint16_t dev_nonce;
// JoinReqType | JoinEUI | DevNonce | MHDR | JoinNonce | NetID | DevAddr | DLSettings | RxDelay | CFList
buffer[0] = 0xFF; // TODO: JoinReqType
// JoinEUI
buffer[1] = JoinEUI[7];
buffer[2] = JoinEUI[6];
buffer[3] = JoinEUI[5];
buffer[4] = JoinEUI[4];
buffer[5] = JoinEUI[3];
buffer[6] = JoinEUI[2];
buffer[7] = JoinEUI[1];
buffer[8] = JoinEUI[0];
// DevNonce
buffer[9] = dev_nonce & 0xFF;
buffer[10] = dev_nonce >> 8;
// MHDR
buffer[11] = packet[0];
// JoinNonce
buffer[12] = packet[1];
buffer[13] = packet[2];
buffer[14] = packet[3];
// NetID
buffer[15] = packet[4];
buffer[16] = packet[5];
buffer[17] = packet[6];
// DevAddr
buffer[18] = packet[7];
buffer[19] = packet[8];
buffer[20] = packet[9];
buffer[21] = packet[10];
// DLSettings
buffer[22] = packet[11];
// RxDelay
buffer[23] = packet[12];
if (packet_length > 17) {
// CFList
for (uint8_t i = 0; i < 16; i++) {
buffer[24 + i] = packet[13 + i];
}
//CalculateMic(JSIntKey, buffer, NULL, mic, 40);
} else {
//CalculateMic(JSIntKey, buffer, NULL, mic, 24);
}
if (!CheckMic(mic, packet + packet_length_no_mic)) {
return false;
}
dev_nonce = GetDevNonce();
// Derive AppSKey, FNwkSIntKey, SNwkSIntKey and NwkSEncKey
for (uint8_t i = 1; i <= 4; i++) {
memset(buffer, 0, 16);
buffer[0] = i;
// JoinNonce
buffer[1] = packet[1];
buffer[2] = packet[2];
buffer[3] = packet[3];
// JoinEUI
buffer[4] = JoinEUI[7];
buffer[5] = JoinEUI[6];
buffer[6] = JoinEUI[5];
buffer[7] = JoinEUI[4];
buffer[8] = JoinEUI[3];
buffer[9] = JoinEUI[2];
buffer[10] = JoinEUI[1];
buffer[11] = JoinEUI[0];
// DevNonce
buffer[12] = dev_nonce & 0xFF;
buffer[13] = dev_nonce >> 8;
if (i == 2) {
AesEncrypt(AppKey, buffer);
} else {
AesEncrypt(NwkKey, buffer);
}
switch (i) {
case 1:
SetFNwkSIntKey(buffer);
break;
case 2:
SetAppSKey(buffer);
break;
case 3:
SetSNwkSIntKey(buffer);
break;
case 4:
SetNwkSEncKey(buffer);
break;
}
}
return true;
}
#endif // LORAWAN_V1_1_ENABLED
/**
* Listens for and processes a LoRaWAN JoinAccept message.
*
* @param window Index of the receive window [1,2].
* @return 0 if successful, else error code.
*/
int8_t SlimLoRa::ProcessJoinAccept(uint8_t window) {
int8_t result;
uint32_t rx_delay;
uint8_t packet[1 + LORAWAN_JOIN_ACCEPT_MAX_SIZE + 4];
int8_t packet_length;
bool mic_valid = false;
uint8_t dev_addr[4];
uint32_t join_nonce;
if (window == 1) {
rx_delay = CalculateRxDelay(data_rate_, LORAWAN_JOIN_ACCEPT_DELAY1_MICROS);
packet_length = RfmReceivePacket(packet, sizeof(packet), channel_, data_rate_, tx_done_micros_ + rx_delay);
} else {
rx_delay = CalculateRxDelay(rx2_data_rate_, LORAWAN_JOIN_ACCEPT_DELAY2_MICROS);
packet_length = RfmReceivePacket(packet, sizeof(packet), 8, rx2_data_rate_, tx_done_micros_ + rx_delay);
}
if (packet_length <= 0) {
result = LORAWAN_ERROR_NO_PACKET_RECEIVED;
goto end;
}
if (packet_length > 1 + LORAWAN_JOIN_ACCEPT_MAX_SIZE + 4) {
result = LORAWAN_ERROR_SIZE_EXCEEDED;
goto end;
}
if (packet[0] != LORAWAN_MTYPE_JOIN_ACCEPT) {
result = LORAWAN_ERROR_UNEXPECTED_MTYPE;
goto end;
}
#if LORAWAN_V1_1_ENABLED
AesEncrypt(NwkKey, packet + 1);
#else
AesEncrypt(AppKey, packet + 1);
#endif // LORAWAN_V1_1_ENABLED
if (packet_length > 17) {
#if LORAWAN_V1_1_ENABLED
AesEncrypt(NwkKey, packet + 17);
#else
AesEncrypt(AppKey, packet + 17);
#endif // LORAWAN_V1_1_ENABLED
}
// Check JoinNonce validity
join_nonce = packet[1] | packet[2] << 8 | (uint32_t) packet[3] << 16;
if (GetJoinNonce() >= join_nonce) {
result = LORAWAN_ERROR_INVALID_JOIN_NONCE;
goto end;
}
// Check OptNeg flag
if (packet[11] & 0x80) {
// LoRaWAN1.1+
#if LORAWAN_V1_1_ENABLED
mic_valid = ProcessJoinAccept1_1(packet, packet_length);
#endif // LORAWAN_V1_1_ENABLED
} else {
// LoRaWAN1.0
mic_valid = ProcessJoinAccept1_0(packet, packet_length);
}
if (!mic_valid) {
has_joined_ = false;
result = LORAWAN_ERROR_INVALID_MIC;
goto end;
}
SetJoinNonce(join_nonce);
dev_addr[0] = packet[10];
dev_addr[1] = packet[9];
dev_addr[2] = packet[8];
dev_addr[3] = packet[7];
SetDevAddr(dev_addr);
rx1_data_rate_offset_ = (packet[11] & 0x70) >> 4;
SetRx1DataRateOffset(rx1_data_rate_offset_);
rx2_data_rate_ = packet[11] & 0xF;
SetRx2DataRate(rx2_data_rate_);
SetRx1Delay(packet[12] & 0xF);
rx1_delay_micros_ = GetRx1Delay() * MICROS_PER_SECOND;
tx_frame_counter_ = 0;
SetTxFrameCounter(0);
rx_frame_counter_ = 0;
SetRxFrameCounter(0);
adr_ack_counter_ = 0;
has_joined_ = true;
#if LORAWAN_KEEP_SESSION
SetHasJoined(true);
#endif // LORAWAN_KEEP_SESSION
result = 0;
end:
return result;
}
#endif // LORAWAN_OTAA_ENABLED
/**
* Processes frame options of downlink packets.
*
* @param options Pointer to the start of the frame options section.
* @param f_options_length Length of the frame options section.
*/
void SlimLoRa::ProcessFrameOptions(uint8_t *options, uint8_t f_options_length) {
uint8_t status, new_rx1_dr_offset, new_rx2_dr, tx_power;
if (f_options_length == 0) {
return;
}
for (uint8_t i = 0; i < f_options_length; i++) {
switch (options[i]) {
case LORAWAN_FOPT_LINK_CHECK_ANS:
i += LORAWAN_FOPT_LINK_CHECK_ANS_SIZE;
break;
case LORAWAN_FOPT_LINK_ADR_REQ:
status = 0x1;
new_rx2_dr = options[i + 1] >> 4;
tx_power = options[i + 1] & 0xF;
if (new_rx2_dr == 0xF || (new_rx2_dr >= SF12BW125 && new_rx2_dr <= SF7BW250)) { // Reversed table index
status |= 0x2;
}
if (tx_power == 0xF || tx_power <= LORAWAN_EU868_TX_POWER_MAX) {
status |= 0x4;
}
if (status == 0x7) {
if (new_rx2_dr != 0xF) {
data_rate_ = new_rx2_dr;
}
if (tx_power != 0xF) {
RfmWrite(RFM_REG_PA_CONFIG, 0xF0 | (14 - tx_power * 2));
}
}
pending_fopts_.fopts[pending_fopts_.length++] = LORAWAN_FOPT_LINK_ADR_ANS;
pending_fopts_.fopts[pending_fopts_.length++] = status;
i += LORAWAN_FOPT_LINK_ADR_REQ_SIZE;
break;
case LORAWAN_FOPT_DUTY_CYCLE_REQ:
i += LORAWAN_FOPT_DUTY_CYCLE_REQ_SIZE;
break;
case LORAWAN_FOPT_RX_PARAM_SETUP_REQ:
status = 0x1;
new_rx1_dr_offset = (options[i + 1] & 0x70) >> 4;
new_rx2_dr = options[i + 1] & 0xF;
if (new_rx1_dr_offset <= LORAWAN_EU868_RX1_DR_OFFSET_MAX) {
status |= 0x4;
}
if (new_rx2_dr >= SF12BW125 && new_rx2_dr <= SF7BW250) { // Reversed table index
status |= 0x2;
}
if (status == 0x7) {
rx1_data_rate_offset_ = new_rx1_dr_offset;
SetRx1DataRateOffset(rx1_data_rate_offset_);
rx2_data_rate_ = new_rx2_dr;
SetRx2DataRate(rx2_data_rate_);
}
sticky_fopts_.fopts[sticky_fopts_.length++] = LORAWAN_FOPT_RX_PARAM_SETUP_ANS;
sticky_fopts_.fopts[sticky_fopts_.length++] = status;
i += LORAWAN_FOPT_RX_PARAM_SETUP_REQ_SIZE;
break;
case LORAWAN_FOPT_DEV_STATUS_REQ:
pending_fopts_.fopts[pending_fopts_.length++] = LORAWAN_FOPT_DEV_STATUS_ANS;
// TODO: Battery level
pending_fopts_.fopts[pending_fopts_.length++] = 0xFF;
pending_fopts_.fopts[pending_fopts_.length++] = (last_packet_snr_ & 0x80) >> 2 | last_packet_snr_ & 0x1F;
i += LORAWAN_FOPT_DEV_STATUS_REQ_SIZE;
break;
case LORAWAN_FOPT_NEW_CHANNEL_REQ:
i += LORAWAN_FOPT_NEW_CHANNEL_REQ_SIZE;
break;
case LORAWAN_FOPT_RX_TIMING_SETUP_REQ:
SetRx1Delay(options[i + 1] & 0xF);
rx1_delay_micros_ = GetRx1Delay() * MICROS_PER_SECOND;
sticky_fopts_.fopts[sticky_fopts_.length++] = LORAWAN_FOPT_RX_TIMING_SETUP_ANS;
i += LORAWAN_FOPT_RX_TIMING_SETUP_REQ_SIZE;
break;
case LORAWAN_FOPT_TX_PARAM_SETUP_REQ:
i += LORAWAN_FOPT_TX_PARAM_SETUP_REQ_SIZE;
break;
case LORAWAN_FOPT_DL_CHANNEL_REQ:
i += LORAWAN_FOPT_DL_CHANNEL_REQ_SIZE;
break;
case LORAWAN_FOPT_DEVICE_TIME_ANS:
i += LORAWAN_FOPT_DEVICE_TIME_ANS_SIZE;
break;
default:
return;
}
}
}
/**
* Listens for and processes LoRaWAN downlink packets.
*
* @param window Receive window index [1,2].
* @return 0 if successful, else error code.
*/
int8_t SlimLoRa::ProcessDownlink(uint8_t window) {
int8_t result;
uint8_t rx1_offset_dr;
uint32_t rx_delay;
uint8_t packet[64];
int8_t packet_length;
uint8_t f_options_length, port, payload_length;
uint16_t frame_counter;
uint8_t mic[4];
#if LORAWAN_OTAA_ENABLED
uint8_t dev_addr[4];
GetDevAddr(dev_addr);
#endif // LORAWAN_OTAA_ENABLED
if (window == 1) {
rx1_offset_dr = data_rate_ + rx1_data_rate_offset_; // Reversed table index
if (rx1_offset_dr > SF7BW125) {
rx1_offset_dr = SF7BW125;
}
rx_delay = CalculateRxDelay(rx1_offset_dr, rx1_delay_micros_);
packet_length = RfmReceivePacket(packet, sizeof(packet), channel_, rx1_offset_dr, tx_done_micros_ + rx_delay);
} else {
rx_delay = CalculateRxDelay(rx2_data_rate_, rx1_delay_micros_ + MICROS_PER_SECOND);
packet_length = RfmReceivePacket(packet, sizeof(packet), 8, rx2_data_rate_, tx_done_micros_ + rx_delay);
}
if (packet_length <= 0) {
result = LORAWAN_ERROR_NO_PACKET_RECEIVED;
goto end;
}
if (packet_length > sizeof(packet)) {
result = LORAWAN_ERROR_SIZE_EXCEEDED;
goto end;
}
if (packet[0] != LORAWAN_MTYPE_UNCONFIRMED_DATA_DOWN
&& packet[0] != LORAWAN_MTYPE_CONFIRMED_DATA_DOWN) {
result = LORAWAN_ERROR_UNEXPECTED_MTYPE;
goto end;
}
frame_counter = packet[7] << 8 | packet[6];
if (frame_counter < rx_frame_counter_) {
result = LORAWAN_ERROR_INVALID_FRAME_COUNTER;
goto end;
}
#if LORAWAN_OTAA_ENABLED
if (!(packet[4] == dev_addr[0] && packet[3] == dev_addr[1]
&& packet[2] == dev_addr[2] && packet[1] == dev_addr[3])) {
result = LORAWAN_ERROR_UNEXPECTED_DEV_ADDR;
goto end;
}
#else
if (!(packet[4] == DevAddr[0] && packet[3] == DevAddr[1]
&& packet[2] == DevAddr[2] && packet[1] == DevAddr[3])) {
result = LORAWAN_ERROR_UNEXPECTED_DEV_ADDR;
goto end;
}
#endif // LORAWAN_OTAA_ENABLED
// Check MIC
CalculateMessageMic(packet, mic, packet_length - 4, frame_counter, LORAWAN_DIRECTION_DOWN);
if (!CheckMic(mic, &packet[packet_length - 4])) {
return LORAWAN_ERROR_INVALID_MIC;
}
// Clear sticky fopts
memset(sticky_fopts_.fopts, 0, sticky_fopts_.length);
sticky_fopts_.length = 0;
// Saves memory cycles, we could loose more than 3 packets if we don't receive a packet at all
rx_frame_counter_ = frame_counter + 1;
if (rx_frame_counter_ % 3) {
SetRxFrameCounter(rx_frame_counter_);
}
// Reset ADR acknowledge counter
adr_ack_counter_ = 0;
// Parse MAC commands from payload if packet on port 0
port = packet[8 + f_options_length];
if (port == 0) {
payload_length = packet_length - 8 - f_options_length - 4;
EncryptPayload(&packet[8 + f_options_length + 1], payload_length, frame_counter, LORAWAN_DIRECTION_DOWN);
ProcessFrameOptions(&packet[8 + f_options_length + 1], payload_length);
} else {
// Process MAC commands
f_options_length = packet[5] & 0xF;
ProcessFrameOptions(&packet[8], f_options_length);
}
result = 0;
end:
return result;
}
/**
* Constructs a LoRaWAN packet and transmits it.