/
LoRaMac.c
3314 lines (2874 loc) · 112 KB
/
LoRaMac.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
/*!
* \file LoRaMac.c
*
* \brief LoRa MAC layer implementation
*
* \copyright Revised BSD License, see section \ref LICENSE.
*
* \code
* ______ _
* / _____) _ | |
* ( (____ _____ ____ _| |_ _____ ____| |__
* \____ \| ___ | (_ _) ___ |/ ___) _ \
* _____) ) ____| | | || |_| ____( (___| | | |
* (______/|_____)_|_|_| \__)_____)\____)_| |_|
* (C)2013-2017 Semtech
*
* ___ _____ _ ___ _ _____ ___ ___ ___ ___
* / __|_ _/_\ / __| |/ / __/ _ \| _ \/ __| __|
* \__ \ | |/ _ \ (__| ' <| _| (_) | / (__| _|
* |___/ |_/_/ \_\___|_|\_\_| \___/|_|_\\___|___|
* embedded.connectivity.solutions===============
*
* \endcode
*
* \author Miguel Luis ( Semtech )
*
* \author Gregory Cristian ( Semtech )
*
* \author Daniel Jaeckle ( STACKFORCE )
*/
#include <string.h>
#include <assert.h>
#include "os/mynewt.h"
#include "os/os.h"
#include "node/lora.h"
#include "node/utilities.h"
#include "node/mac/LoRaMacCrypto.h"
#include "node/mac/LoRaMac.h"
#include "node/mac/LoRaMacTest.h"
#include "hal/hal_timer.h"
#include "node/lora_priv.h"
#include "lora/utilities.h"
#if MYNEWT_VAL(LORA_MAC_TIMER_NUM) == -1
#error "Must define a Lora MAC timer number"
#else
#define LORA_MAC_TIMER_NUM MYNEWT_VAL(LORA_MAC_TIMER_NUM)
#endif
/* The lora mac timer counts in 1 usec increments */
#define LORA_MAC_TIMER_FREQ 1000000
/*!
* Maximum PHY layer payload size
*/
#define LORAMAC_PHY_MAXPAYLOAD 255
/*!
* Maximum MAC commands buffer size
*/
#define LORA_MAC_CMD_BUF_LEN 128
/*!
* Maximum length of the fOpts field
*/
#define LORA_MAC_COMMAND_MAX_FOPTS_LENGTH 15
/*!
* LoRaMac region.
*/
static LoRaMacRegion_t LoRaMacRegion;
/*!
* Device IEEE EUI
*/
static uint8_t *LoRaMacDevEui;
/*!
* Application IEEE EUI
*/
static uint8_t *LoRaMacAppEui;
/*!
* AES encryption/decryption cipher application key
*/
static uint8_t *LoRaMacAppKey;
/*!
* AES encryption/decryption cipher network session key
*/
static uint8_t LoRaMacNwkSKey[16];
/*!
* AES encryption/decryption cipher application session key
*/
static uint8_t LoRaMacAppSKey[16];
/*!
* Multicast channels linked list
*/
static MulticastParams_t *MulticastChannels = NULL;
/*!
* Actual device class
*/
static DeviceClass_t LoRaMacDeviceClass;
/*!
* Buffer containing the data to be sent or received.
*/
static uint8_t LoRaMacBuffer[LORAMAC_PHY_MAXPAYLOAD];
/*!
* Length of packet in LoRaMacBuffer
*/
static uint16_t LoRaMacBufferPktLen;
/*!
* Buffer containing the upper layer data.
*/
static uint8_t LoRaMacRxPayload[LORAMAC_PHY_MAXPAYLOAD];
/*!
* IsPacketCounterFixed enables the MIC field tests by fixing the
* UpLinkCounter value
*/
static bool IsUpLinkCounterFixed = false;
/*!
* LoRaMac ADR control status
*/
static bool AdrCtrlOn = false;
/*!
* Contains the current MacCommandsBuffer index
*/
static uint8_t MacCommandsBufferIndex;
/*!
* Contains the current MacCommandsBuffer index for MAC commands to repeat
*/
static uint8_t MacCommandsBufferToRepeatIndex;
/*!
* Buffer containing the MAC layer commands
*/
static uint8_t MacCommandsBuffer[LORA_MAC_CMD_BUF_LEN];
/*!
* Buffer containing the MAC layer commands which must be repeated
*/
static uint8_t MacCommandsBufferToRepeat[LORA_MAC_CMD_BUF_LEN];
/*!
* LoRaMac parameters
*/
LoRaMacParams_t LoRaMacParams;
/*!
* LoRaMac default parameters
*/
LoRaMacParams_t LoRaMacParamsDefaults;
/*!
* Enables/Disables duty cycle management (Test only)
*/
static bool DutyCycleOn;
/*!
* LoRaMac internal states
*/
enum eLoRaMacState
{
LORAMAC_IDLE = 0x00000000,
LORAMAC_TX_RUNNING = 0x00000001,
LORAMAC_RX = 0x00000002,
LORAMAC_ACK_REQ = 0x00000004,
LORAMAC_ACK_RETRY = 0x00000008,
LORAMAC_TX_DELAYED = 0x00000010,
LORAMAC_TX_CONFIG = 0x00000020,
LORAMAC_RX_ABORT = 0x00000040,
};
/*!
* LoRaMac internal state
*/
uint32_t LoRaMacState;
/*!
* LoRaMac upper layer callback functions
*/
static LoRaMacCallback_t *LoRaMacCallbacks;
/*!
* Radio events function pointer
*/
static RadioEvents_t RadioEvents;
/*!
* LoRaMac duty cycle delayed Tx timer
*/
static struct hal_timer TxDelayedTimer;
/*!
* LoRaMac reception windows timers
*/
static struct hal_timer RxWindowTimer1;
static struct hal_timer RxWindowTimer2;
/*!
* LoRaMac Rx windows configuration
*/
static RxConfigParams_t RxWindow1Config;
static RxConfigParams_t RxWindow2Config;
/* Lengths of MAC commands */
static const uint8_t
g_lora_mac_cmd_lens[LORA_MAC_MAX_MAC_CMD_CID + 1] = {0, 0, 1, 2, 1, 2, 3, 2, 1};
/* Radio events */
struct os_event g_lora_mac_radio_tx_timeout_event;
struct os_event g_lora_mac_radio_tx_event;
struct os_event g_lora_mac_radio_rx_event;
struct os_event g_lora_mac_radio_rx_err_event;
struct os_event g_lora_mac_radio_rx_timeout_event;
struct os_event g_lora_mac_rtx_timeout_event;
struct os_event g_lora_mac_rx_win1_event;
struct os_event g_lora_mac_rx_win2_event;
struct os_event g_lora_mac_tx_delay_timeout_event;
static void lora_mac_rx_on_window2(void);
static uint8_t lora_mac_extract_mac_cmds(uint8_t max_cmd_bytes, uint8_t *buf);
static void
lora_mac_rx_disable(void)
{
struct os_eventq *evq;
/* Disable reception (if not receiving) */
Radio.RxDisable();
/* Remove all possible receive related events */
evq = lora_node_mac_evq_get();
os_eventq_remove(evq, &g_lora_mac_radio_rx_event);
os_eventq_remove(evq, &g_lora_mac_radio_rx_err_event);
os_eventq_remove(evq, &g_lora_mac_radio_rx_timeout_event);
}
/**
* lora mac rtx timer stop
*
* Stops the retransmission timer. Removes any enqueued event (if on queue).
*/
static void
lora_mac_rtx_timer_stop(void)
{
os_cputime_timer_stop(&g_lora_mac_data.rtx_timer);
os_eventq_remove(lora_node_mac_evq_get(), &g_lora_mac_rtx_timeout_event);
}
/**
* lora mac rx win2 stop
*
* Stops the receive window timer. Removes any enqueued event (if on queue)
*
*/
static void
lora_mac_rx_win2_stop(void)
{
if (LoRaMacDeviceClass == CLASS_A) {
hal_timer_stop(&RxWindowTimer2);
lora_enter_low_power();
os_eventq_remove(lora_node_mac_evq_get(), &g_lora_mac_rx_win2_event);
lora_node_log(LORA_NODE_LOG_RX_WIN2_CANCEL, 0, 0, 0);
}
}
/*!
* \brief Function to be executed on Radio Tx Done event
*/
static void
OnRadioTxDone(void)
{
os_eventq_put(lora_node_mac_evq_get(), &g_lora_mac_radio_tx_event);
}
/**
* Processes radio received done interrupt
*
* Posts received packet event to MAC task for processing.
*
* Context: ISR
*
*/
static void
OnRadioRxDone(uint8_t *payload, uint16_t size, int16_t rssi, int8_t snr)
{
/*
* TODO: for class C devices we may need to handle this differently as
* the device is continuously listening I believe and it may be possible
* to get a receive done event before the previous one has been handled.
*/
/* The ISR fills out the payload pointer, size, rssi and snr of rx pdu */
g_lora_mac_data.rxpkt.rxdinfo.rssi = rssi;
g_lora_mac_data.rxpkt.rxdinfo.snr = snr;
g_lora_mac_data.rxbuf = payload;
g_lora_mac_data.rxbufsize = size;
os_eventq_put(lora_node_mac_evq_get(), &g_lora_mac_radio_rx_event);
}
/**
* Radio transmit timeout event
*
* Context: ISR
*/
static void
OnRadioTxTimeout(void)
{
os_eventq_put(lora_node_mac_evq_get(), &g_lora_mac_radio_tx_timeout_event);
}
/*!
* \brief Function executed on Radio Rx error event
*/
static void
OnRadioRxError(void)
{
os_eventq_put(lora_node_mac_evq_get(), &g_lora_mac_radio_rx_err_event);
}
/*!
* \brief Function executed on Radio Rx Timeout event
*/
static void
OnRadioRxTimeout(void)
{
os_eventq_put(lora_node_mac_evq_get(), &g_lora_mac_radio_rx_timeout_event);
}
/*!
* \brief Function executed on duty cycle delayed Tx timer event
*/
static void
OnTxDelayedTimerEvent(void *unused)
{
os_eventq_put(lora_node_mac_evq_get(), &g_lora_mac_tx_delay_timeout_event);
}
/*!
* \brief Function executed on first Rx window timer event
*/
static void
OnRxWindow1TimerEvent(void *unused)
{
os_eventq_put(lora_node_mac_evq_get(), &g_lora_mac_rx_win1_event);
}
/*!
* \brief Function executed on second Rx window timer event
*/
static void
OnRxWindow2TimerEvent(void *unused)
{
os_eventq_put(lora_node_mac_evq_get(), &g_lora_mac_rx_win2_event);
}
/*!
* \brief Function executed when rtx timer expires. The rtx timer is used
* for packet re-transmissions.
*
* Context: Interrupt and MAC
*/
static void
lora_mac_rtx_timer_cb(void *unused)
{
os_eventq_put(lora_node_mac_evq_get(), &g_lora_mac_rtx_timeout_event);
}
/*!
* \brief Initializes and opens the reception window
*
* \param [IN] rxContinuous Set to true, if the RX is in continuous mode
* \param [IN] maxRxWindow Maximum RX window timeout
*/
static void RxWindowSetup(bool rxContinuous, uint32_t maxRxWindow);
/*!
* \brief Adds a new MAC command to be sent.
*
* \Remark MAC layer internal function
*
* \param [in] cmd MAC command to be added
* [MOTE_MAC_LINK_CHECK_REQ,
* MOTE_MAC_LINK_ADR_ANS,
* MOTE_MAC_DUTY_CYCLE_ANS,
* MOTE_MAC_RX2_PARAM_SET_ANS,
* MOTE_MAC_DEV_STATUS_ANS
* MOTE_MAC_NEW_CHANNEL_ANS]
* \param [in] p1 1st parameter ( optional depends on the command )
* \param [in] p2 2nd parameter ( optional depends on the command )
*
* \retval status Function status [0: OK, 1: Unknown command, 2: Buffer full]
*/
static LoRaMacStatus_t AddMacCommand( uint8_t cmd, uint8_t p1, uint8_t p2 );
/*!
* \brief Parses the MAC commands which must be repeated.
*
* \Remark MAC layer internal function
*
* \param [IN] cmdBufIn Buffer which stores the MAC commands to send
* \param [IN] length Length of the input buffer to parse
* \param [OUT] cmdBufOut Buffer which stores the MAC commands which must be
* repeated.
*
* \retval Size of the MAC commands to repeat.
*/
static uint8_t ParseMacCommandsToRepeat( uint8_t* cmdBufIn, uint8_t length, uint8_t* cmdBufOut );
/*!
* \brief Validates if the payload fits into the frame, taking the datarate
* into account.
*
* \details Refer to chapter 4.3.2 of the LoRaWAN specification, v1.0
*
* \param lenN Length of the application payload. The length depends on the
* datarate and is region specific
*
* \param datarate Current datarate
*
* \param fOptsLen Length of the fOpts field
*
* \retval [false: payload does not fit into the frame, true: payload fits into
* the frame]
*/
static bool ValidatePayloadLength(uint8_t lenN, int8_t datarate, uint8_t fOptsLen);
/*!
* \brief Decodes MAC commands in the fOpts field and in the payload
*/
static void ProcessMacCommands(uint8_t *payload, uint8_t macIndex, uint8_t commandsSize, uint8_t snr);
/*!
* \brief LoRaMAC layer generic send frame
*
* \param [IN] macHdr MAC header field
* \param [IN] fPort MAC payload port
* \param [IN] m mbuf containing MAC payload
* \retval status Status of the operation.
*/
LoRaMacStatus_t Send(LoRaMacHeader_t *macHdr, uint8_t fPort, struct os_mbuf *m);
/*!
* \brief LoRaMAC layer frame buffer initialization
*
* \param [IN] macHdr MAC header field
* \param [IN] fCtrl MAC frame control field
* \param [IN] fOpts MAC commands buffer
* \param [IN] fPort MAC payload port
* \param [IN] om mbuf with MAC payload
* \retval status Status of the operation.
*/
LoRaMacStatus_t PrepareFrame(LoRaMacHeader_t *macHdr, LoRaMacFrameCtrl_t *fCtrl,
uint8_t fPort, struct os_mbuf *om);
/*
* \brief Schedules the frame according to the duty cycle
*
* \retval Status of the operation
*/
static LoRaMacStatus_t ScheduleTx(void);
/*
* \brief Calculates the back-off time for the band of a channel.
*
* \param [IN] channel The last Tx channel index
*/
static void CalculateBackOff( uint8_t channel );
/*!
* \brief LoRaMAC layer prepared frame buffer transmission with channel specification
*
* \remark PrepareFrame must be called at least once before calling this
* function.
*
* \param [IN] channel Channel to transmit on
* \retval status Status of the operation.
*/
LoRaMacStatus_t SendFrameOnChannel( uint8_t channel );
/*!
* \brief Sets the radio in continuous transmission mode
*
* \remark Uses the radio parameters set on the previous transmission.
*
* \param [IN] timeout Time in seconds while the radio is kept in continuous wave mode
* \retval status Status of the operation.
*/
LoRaMacStatus_t SetTxContinuousWave(uint16_t timeout);
/*!
* \brief Sets the radio in continuous transmission mode
*
* \remark Uses the radio parameters set on the previous transmission.
*
* \param [IN] timeout Time in seconds while the radio is kept in continuous wave mode
* \param [IN] frequency RF frequency to be set.
* \param [IN] power RF output power to be set.
* \retval status Status of the operation.
*/
LoRaMacStatus_t SetTxContinuousWave1( uint16_t timeout, uint32_t frequency, uint8_t power );
/*
* XXX: TODO
*
* Need to understand how to handle mac commands that are waiting to be
* transmitted. We do not want to constantly transmit them but if we dont
* get a downlink packet for commands that we need to repeat until we hear
* a downlink.
*/
/**
* Called to send MCPS confirmations
*/
static void
lora_mac_send_mcps_confirm(LoRaMacEventInfoStatus_t status)
{
/* We are no longer running a tx service */
LoRaMacState &= ~LORAMAC_TX_RUNNING;
if (LM_F_IS_MCPS_REQ()) {
assert(g_lora_mac_data.curtx != NULL);
g_lora_mac_data.curtx->status = status;
if (g_lora_mac_data.cur_tx_mbuf) {
lora_app_mcps_confirm(g_lora_mac_data.cur_tx_mbuf);
}
LM_F_IS_MCPS_REQ() = 0;
}
}
/**
* Called to send join confirmations
*/
static void
lora_mac_send_join_confirm(LoRaMacEventInfoStatus_t status, uint8_t attempts)
{
LoRaMacState &= ~LORAMAC_TX_RUNNING;
lora_app_join_confirm(status, attempts);
LM_F_IS_JOINING() = 0;
}
static void
lora_mac_join_accept_rxd(uint8_t *payload, uint16_t size)
{
uint32_t temp;
uint32_t mic;
uint32_t micRx;
ApplyCFListParams_t apply_cf_list;
STATS_INC(lora_mac_stats, join_accept_rx);
if (LM_F_IS_JOINED()) {
STATS_INC(lora_mac_stats, already_joined);
return;
}
/*
* XXX: This is odd, but if we receive a join accept and we are not
* joined but have not started the join process not sure what to
* do. Guess we will just ignore this packet.
*/
if (!LM_F_IS_JOINING()) {
return;
}
/* XXX: check for too small frame! */
LoRaMacJoinDecrypt(payload + 1, size - 1, LoRaMacAppKey,
LoRaMacRxPayload + 1);
LoRaMacRxPayload[0] = payload[0];
LoRaMacJoinComputeMic(LoRaMacRxPayload, size - LORAMAC_MFR_LEN,
LoRaMacAppKey, &mic);
micRx = ( uint32_t )LoRaMacRxPayload[size - LORAMAC_MFR_LEN];
micRx |= ( ( uint32_t )LoRaMacRxPayload[size - LORAMAC_MFR_LEN + 1] << 8 );
micRx |= ( ( uint32_t )LoRaMacRxPayload[size - LORAMAC_MFR_LEN + 2] << 16 );
micRx |= ( ( uint32_t )LoRaMacRxPayload[size - LORAMAC_MFR_LEN + 3] << 24 );
if (micRx == mic) {
LoRaMacJoinComputeSKeys(LoRaMacAppKey, LoRaMacRxPayload + 1,
g_lora_mac_data.dev_nonce, LoRaMacNwkSKey,
LoRaMacAppSKey);
temp = ( uint32_t )LoRaMacRxPayload[4];
temp |= ( ( uint32_t )LoRaMacRxPayload[5] << 8 );
temp |= ( ( uint32_t )LoRaMacRxPayload[6] << 16 );
g_lora_mac_data.netid = temp;
temp = ( uint32_t )LoRaMacRxPayload[7];
temp |= ( ( uint32_t )LoRaMacRxPayload[8] << 8 );
temp |= ( ( uint32_t )LoRaMacRxPayload[9] << 16 );
temp |= ( ( uint32_t )LoRaMacRxPayload[10] << 24 );
g_lora_mac_data.dev_addr = temp;
// DLSettings
LoRaMacParams.Rx1DrOffset = ( LoRaMacRxPayload[11] >> 4 ) & 0x07;
LoRaMacParams.Rx2Channel.Datarate = LoRaMacRxPayload[11] & 0x0F;
// RxDelay
LoRaMacParams.ReceiveDelay1 = ( LoRaMacRxPayload[12] & 0x0F );
if (LoRaMacParams.ReceiveDelay1 == 0) {
LoRaMacParams.ReceiveDelay1 = 1;
}
LoRaMacParams.ReceiveDelay1 *= 1000;
LoRaMacParams.ReceiveDelay2 = LoRaMacParams.ReceiveDelay1 + 1000;
// Apply CF list
apply_cf_list.Payload = &LoRaMacRxPayload[13];
// Size of the regular payload is 12. Plus 1 byte MHDR and 4 bytes MIC
apply_cf_list.Size = size - 17;
RegionApplyCFList(LoRaMacRegion, &apply_cf_list);
/* We are now joined */
STATS_INC(lora_mac_stats, joins);
/* Stop window 2 if class A device */
lora_mac_rx_win2_stop();
LM_F_IS_JOINED() = 1;
g_lora_mac_data.uplink_cntr = 0;
g_lora_mac_data.nb_rep_cntr = 0;
/* XXX: why not increment this when sending it? Now
it is done on both success and fail */
++g_lora_mac_data.cur_join_attempt;
lora_mac_send_join_confirm(LORAMAC_EVENT_INFO_STATUS_OK,
g_lora_mac_data.cur_join_attempt);
} else {
STATS_INC(lora_mac_stats, rx_mic_failures);
}
}
static void
lora_mac_confirmed_tx_fail(struct lora_pkt_info *txi)
{
GetPhyParams_t getPhy;
PhyParam_t phyParam;
LoRaMacStatus_t rc;
LoRaMacEventInfoStatus_t status;
STATS_INC(lora_mac_stats, confirmed_tx_fail);
/* XXX: how does this work in conjunction with ADR? Will the server
* tell me to use a higher data rate if we fall back erroneously?
* Need to understand. This is a bad retry mechanism
*/
if (g_lora_mac_data.ack_timeout_retries_cntr < g_lora_mac_data.ack_timeout_retries) {
g_lora_mac_data.ack_timeout_retries_cntr++;
if ((g_lora_mac_data.ack_timeout_retries_cntr % 2) == 1) {
getPhy.Attribute = PHY_NEXT_LOWER_TX_DR;
getPhy.UplinkDwellTime = LoRaMacParams.UplinkDwellTime;
getPhy.Datarate = LoRaMacParams.ChannelsDatarate;
phyParam = RegionGetPhyParam( LoRaMacRegion, &getPhy );
LoRaMacParams.ChannelsDatarate = phyParam.Value;
}
/* Attempt to transmit */
rc = ScheduleTx();
if (rc != LORAMAC_STATUS_OK) {
// The DR is not applicable for the payload size
LM_F_NODE_ACK_REQ() = 0;
txi->txdinfo.retries = g_lora_mac_data.ack_timeout_retries_cntr;
txi->txdinfo.datarate = LoRaMacParams.ChannelsDatarate;
g_lora_mac_data.uplink_cntr++;
if (rc == LORAMAC_STATUS_LENGTH_ERROR) {
status = LORAMAC_EVENT_INFO_STATUS_TX_DR_PAYLOAD_SIZE_ERROR;
} else {
status = LORAMAC_EVENT_INFO_STATUS_ERROR;
}
lora_mac_send_mcps_confirm(status);
}
} else {
/* XXX: This seems to be a bit suspect. Why is this done after a
confirmed transmission failure? */
RegionInitDefaults(LoRaMacRegion, INIT_TYPE_RESTORE);
g_lora_mac_data.uplink_cntr++;
LM_F_NODE_ACK_REQ() = 0;
txi->txdinfo.retries = g_lora_mac_data.ack_timeout_retries_cntr;
lora_mac_send_mcps_confirm(LORAMAC_EVENT_INFO_STATUS_TX_RETRIES_EXCEEDED);
}
}
static void
lora_mac_confirmed_tx_success(struct lora_pkt_info *txi)
{
STATS_INC(lora_mac_stats, confirmed_tx_good);
g_lora_mac_data.uplink_cntr++;
LM_F_NODE_ACK_REQ() = 0;
txi->txdinfo.ack_rxd = true;
txi->txdinfo.retries = g_lora_mac_data.ack_timeout_retries_cntr;
lora_mac_send_mcps_confirm(LORAMAC_EVENT_INFO_STATUS_OK);
}
static void
lora_mac_join_req_tx_fail(void)
{
/* Add to Join Request trials if not joined */
++g_lora_mac_data.cur_join_attempt;
/* Have we exceeded the number of join request attempts */
if (g_lora_mac_data.cur_join_attempt >= g_lora_mac_data.max_join_attempt) {
/* Join was a failure */
STATS_INC(lora_mac_stats, join_failures);
lora_mac_send_join_confirm(LORAMAC_EVENT_INFO_STATUS_JOIN_FAIL,
g_lora_mac_data.cur_join_attempt);
} else {
/* XXX: see if we want to do this. Not sure it is needed. I added
this but probably should be modified */
/* Add some transmit delay between join request transmissions */
LoRaMacState |= LORAMAC_TX_DELAYED;
os_cputime_timer_stop(&TxDelayedTimer);
os_cputime_timer_relative(&TxDelayedTimer,
randr(0, MYNEWT_VAL(LORA_JOIN_REQ_RAND_DELAY * 1000)));
}
}
static void
lora_mac_unconfirmed_tx_done(struct lora_pkt_info *txi, int stop_tx)
{
STATS_INC(lora_mac_stats, unconfirmed_tx);
/*
* XXX: this might be wrong, but if we cannot schedule the transmission
* we will just hand up the frame even though we have not attempted
* it the requisite number of times
*/
/* Unconfirmed frames get repeated N times. */
if (stop_tx ||
(g_lora_mac_data.nb_rep_cntr >= LoRaMacParams.ChannelsNbRep) ||
(ScheduleTx() != LORAMAC_STATUS_OK)) {
txi->txdinfo.retries = g_lora_mac_data.nb_rep_cntr;
g_lora_mac_data.nb_rep_cntr = 0;
g_lora_mac_data.adr_ack_cntr++;
g_lora_mac_data.uplink_cntr++;
lora_mac_send_mcps_confirm(LORAMAC_EVENT_INFO_STATUS_OK);
}
}
/**
* lora mac tx service done
*
* The term "tx service" is a made-up term (not in the specification). A tx
* service starts when a frame is transmitted and ends when another frame can
* be sent (not including duty-cycle limitations).
*
* @param rxd_confirmation A boolean flag denoting the following:
* -> A confirmed frame was sent and an acknowledgement was received
* -> An unconfirmed frame was sent and a frame was received in either window
* if the device is a class A device or a frame was received in window 1 if
* class C.
*/
static void
lora_mac_tx_service_done(int rxd_confirmation)
{
struct lora_pkt_info *txi;
/* A sanity check to make sure things are in the proper state */
if (!LM_F_IS_JOINING() && !LM_F_IS_MCPS_REQ()) {
assert((LoRaMacState & LORAMAC_TX_RUNNING) == 0);
goto chk_txq;
}
if (LM_F_IS_JOINING()) {
lora_mac_join_req_tx_fail();
} else {
txi = g_lora_mac_data.curtx;
assert(txi != NULL);
if (LM_F_NODE_ACK_REQ()) {
if (rxd_confirmation) {
lora_mac_confirmed_tx_success(txi);
} else {
lora_mac_confirmed_tx_fail(txi);
}
} else {
lora_mac_unconfirmed_tx_done(txi, rxd_confirmation);
}
}
/* For now, always post an event to check the transmit queue for activity */
chk_txq:
lora_node_chk_txq();
}
static void
lora_mac_process_radio_tx(struct os_event *ev)
{
uint32_t timeout;
GetPhyParams_t getPhy;
PhyParam_t phyParam;
SetBandTxDoneParams_t txDone;
lora_exit_low_power();
if (LoRaMacDeviceClass != CLASS_C) {
Radio.Sleep( );
} else {
lora_mac_rx_on_window2();
}
/* XXX: We need to time this more accurately */
uint32_t curTime = hal_timer_read(LORA_MAC_TIMER_NUM);
/* Always start receive window 1 */
hal_timer_start_at(&RxWindowTimer1,
curTime + (g_lora_mac_data.rx_win1_delay * 1000));
/* Only start receive window 2 if not a class C device */
if (LoRaMacDeviceClass != CLASS_C) {
hal_timer_start_at(&RxWindowTimer2,
curTime + (g_lora_mac_data.rx_win2_delay * 1000));
}
/* Set flag if tx is a join request and increment tx request stats. */
if (LM_F_IS_JOINING()) {
STATS_INC(lora_mac_stats, join_req_tx);
LM_F_LAST_TX_IS_JOIN_REQ() = 1;
} else {
LM_F_LAST_TX_IS_JOIN_REQ() = 0;
}
if (LM_F_NODE_ACK_REQ()) {
getPhy.Attribute = PHY_ACK_TIMEOUT;
phyParam = RegionGetPhyParam(LoRaMacRegion, &getPhy);
os_cputime_timer_stop(&g_lora_mac_data.rtx_timer);
os_cputime_timer_relative(&g_lora_mac_data.rtx_timer,
((g_lora_mac_data.rx_win2_delay + phyParam.Value) * 1000));
} else {
/*
* For unconfirmed transmisson for class C devices,
* we want to make sure we listen for the second rx
* window before moving on to another transmission.
*/
if (LoRaMacDeviceClass == CLASS_C) {
timeout = (g_lora_mac_data.rx_win2_delay * 1000);
/* XXX: work-around for now. Must insure that we give enough
* time to hear a complete join accept in window 2 so we add
* 2 seconds here
*/
if (LM_F_LAST_TX_IS_JOIN_REQ()) {
timeout += (2000 * 1000);
} else {
timeout += (uint32_t)((RxWindow2Config.tsymbol * 1000) *
RxWindow2Config.WindowTimeout);
}
os_cputime_timer_stop(&g_lora_mac_data.rtx_timer);
os_cputime_timer_relative(&g_lora_mac_data.rtx_timer, timeout);
}
}
// Store last Tx channel
g_lora_mac_data.last_tx_chan = g_lora_mac_data.cur_chan;
// Update last tx done time for the current channel
txDone.Channel = g_lora_mac_data.cur_chan;
txDone.Joined = LM_F_IS_JOINED();
txDone.LastTxDoneTime = timer_get_current_time();
RegionSetBandTxDone(LoRaMacRegion, &txDone);
// Update Aggregated last tx done time
g_lora_mac_data.aggr_last_tx_done_time = txDone.LastTxDoneTime;
if (!LM_F_NODE_ACK_REQ()) {
g_lora_mac_data.nb_rep_cntr++;
}
lora_node_log(LORA_NODE_LOG_TX_DONE, g_lora_mac_data.cur_chan,
LoRaMacBufferPktLen, curTime);
}
/**
* Process the radio receive event.
*
* Context: MAC task
*
* @param ev
*/
static void
lora_mac_process_radio_rx(struct os_event *ev)
{
LoRaMacHeader_t macHdr;
LoRaMacFrameCtrl_t fCtrl;
LoRaMacRxSlot_t entry_rx_slot;
struct lora_pkt_info *rxi;
bool skipIndication = false;
bool send_indicate = false;
GetPhyParams_t getPhy;
PhyParam_t phyParam;
uint8_t *payload;
uint16_t size;
int8_t snr;
uint8_t hdrlen;
uint32_t address = 0;
uint8_t appPayloadStartIndex = 0;
uint8_t port = 0xFF;
uint8_t frameLen;
uint32_t mic = 0;
uint32_t micRx;
uint16_t sequenceCounter = 0;
uint16_t sequenceCounterPrev = 0;
uint16_t sequenceCounterDiff = 0;
uint32_t downLinkCounter = 0;
MulticastParams_t *curMulticastParams = NULL;
uint8_t *nwkSKey = LoRaMacNwkSKey;
uint8_t *appSKey = LoRaMacAppSKey;
uint8_t multicast = 0;
/*
* XXX: what if window 2 timeout event already enqueued? If we
* receive a frame with a valid MIC we are supposed to not receive
* on window 2. We stop the timer below but what if event has been
* processed?
*/
/* Put radio to sleep if not class C */
if (LoRaMacDeviceClass != CLASS_C) {
Radio.Sleep( );
}
STATS_INC(lora_mac_stats, rx_frames);
/* Payload, size and snr are filled in by radio rx ISR */
payload = g_lora_mac_data.rxbuf;
size = g_lora_mac_data.rxbufsize;
rxi = &g_lora_mac_data.rxpkt;
snr = rxi->rxdinfo.snr;
/* Reset rest of global indication element */
rxi->port = 0;
entry_rx_slot = g_lora_mac_data.rx_slot;
rxi->rxdinfo.rxslot = entry_rx_slot;
rxi->rxdinfo.multicast = 0;
rxi->rxdinfo.frame_pending = 0;
rxi->rxdinfo.rxdata = false;
rxi->rxdinfo.ack_rxd = false;
rxi->rxdinfo.downlink_cntr = 0;
/* Get the MHDR from the received frame */
macHdr.Value = payload[0];
hdrlen = 1;
lora_node_log(LORA_NODE_LOG_RX_DONE, g_lora_mac_data.cur_chan, size,
(entry_rx_slot << 8) | macHdr.Value);
switch (macHdr.Bits.MType) {
case FRAME_TYPE_JOIN_ACCEPT:
lora_mac_join_accept_rxd(payload, size);
break;
case FRAME_TYPE_DATA_CONFIRMED_DOWN:
case FRAME_TYPE_DATA_UNCONFIRMED_DOWN:
/* If not joined I do not know why we would accept a frame */
if (!LM_F_IS_JOINED()) {
goto process_rx_done;
}
address = payload[hdrlen++];
address |= ((uint32_t)payload[hdrlen++] << 8);
address |= ((uint32_t)payload[hdrlen++] << 16);
address |= ((uint32_t)payload[hdrlen++] << 24) ;
if (address != g_lora_mac_data.dev_addr) {
curMulticastParams = MulticastChannels;
while (curMulticastParams != NULL) {
if (address == curMulticastParams->Address) {
multicast = 1;
nwkSKey = curMulticastParams->NwkSKey;
appSKey = curMulticastParams->AppSKey;
downLinkCounter = curMulticastParams->DownLinkCounter;
break;
}
curMulticastParams = curMulticastParams->Next;
}
if (multicast == 0) {
/* XXX: stat */
/* We are not the destination of this frame. */
goto process_rx_done;
}
} else {
multicast = 0;