-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlorawan.c
3056 lines (2631 loc) · 112 KB
/
lorawan.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) 2016 Microchip Technology Inc. and its subsidiaries
* (Microchip). All rights reserved.
*
* You are permitted to use the software and its derivatives with Microchip
* products. See the license agreement accompanying this software, if any, for
* more info about your rights and obligations.
*
* SOFTWARE AND DOCUMENTATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF
* MERCHANTABILITY, TITLE, NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR
* PURPOSE. IN NO EVENT SHALL MICROCHIP, SMSC, OR ITS LICENSORS BE LIABLE OR
* OBLIGATED UNDER CONTRACT, NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH
* OF WARRANTY, OR OTHER LEGAL EQUITABLE THEORY FOR ANY DIRECT OR INDIRECT
* DAMAGES OR EXPENSES INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL,
* INDIRECT OR CONSEQUENTIAL DAMAGES, OR OTHER SIMILAR COSTS. To the fullest
* extend allowed by law, Microchip and its licensors liability will not exceed
* the amount of fees, if any, that you paid directly to Microchip to use this
* software.
*************************************************************************
*
* lorawan.c
*
* LoRaWAN file
*
******************************************************************************/
/****************************** INCLUDES **************************************/
#include "lorawan_private.h"
#include "lorawan.h"
#include "lorawan_aes.h"
#include "lorawan_aes_cmac.h"
#include "lorawan_defs.h"
#include "AES.h"
#include "radio_driver_SX1276.h"
#include "sw_timer.h"
#include "interrupt_manager_lora_addons.h"
#include <math.h>
#include <stdint.h>
#include "lorawan_ru.h"
#include "shell.h"
#include "eeprom.h"
/****************************** VARIABLES *************************************/
//CID = LinkCheckReq = 2
//CID = LinkADRAns = 3
//CID = DutyCycleAns = 4
//CID = RX2SetupAns = 5
//CID = DevStatusAns = 6
//CID = NewChannelAns = 7
//CID = RXTimingSetupAns = 8
// Index in macEndDevCmdReplyLen = CID - 2
static const uint8_t macEndDevCmdReplyLen[] = {1, 2, 1, 2, 3, 2, 1};
LoRa_t loRa;
uint8_t macBuffer[MAXIMUM_BUFFER_LENGTH];
uint8_t radioBuffer[MAXIMUM_BUFFER_LENGTH];
static uint8_t aesBuffer[AES_BLOCKSIZE];
RxAppData_t rxPayload;
Profile_t devices[MAX_EEPROM_RECORDS];
Profile_t joinServer;
uint8_t js_number;
uint8_t dev_number;
uint8_t number_of_devices;
uint8_t JoinNonce[3];
uint32_t NetID,NwkID,NwkID_mask;
uint8_t NwkID_type;
uint8_t DevAddr[4]={0xFF,0xFF,0xFF,0xFF};
extern const uint8_t maxPayloadSize[];
extern ChannelParams_t Channels[];
extern const uint8_t rxWindowSize[];
extern const int8_t rxWindowOffset[];
extern uint8_t mode;
extern uint8_t b[128];
extern uint8_t tt0;
extern uint32_t tt0_value;
extern uint32_t EEPROM_types;
extern uint32_t DenyTransmit, DenyReceive;
/************************ FUNCTION PROTOTYPES *************************/
static void UpdateReceiveDelays (uint8_t delay);
static uint8_t LORAWAN_GetMaxPayloadSize (void);
static void AssemblePacket (bool confirmed, uint8_t port, uint8_t *buffer, uint16_t bufferLength);
static void AssembleAckPacket (uint8_t dev_nimber);
static bool FindSmallestDataRate (void);
static uint8_t* ExecuteLinkCheck (uint8_t *ptr);
static uint8_t* ExecuteRxTimingSetup (uint8_t *ptr);
static uint8_t PrepareJoinRequestFrame (void);
static uint8_t PrepareJoinAcceptFrame (uint8_t dev_number);
static void PrepareSessionKeys (uint8_t* sessionKey, uint8_t* appNonce, uint8_t* networkId, uint8_t* joinNonce);
static void DeviceComputeSessionKeys (JoinAccept_t *joinAcceptBuffer);
static void NetworkComputeSessionKeys (uint8_t dn);
static uint8_t CountfOptsLength (void);
static void IncludeMacCommandsResponse (uint8_t* macBuffer, uint8_t* pBufferIndex, uint8_t bIncludeInFopts );
static void UpdateJoinInProgress(uint8_t state);
static void CheckFlags (Hdr_t* hdr);
static uint8_t CheckMcastFlags (Hdr_t* hdr);
static void AssembleEncryptionBlock (uint8_t dir, uint32_t frameCounter, uint8_t blockId, uint8_t firstByte, uint8_t multicastStatus);
static uint32_t ExtractMic (uint8_t *buffer, uint8_t bufferLength);
static uint32_t ComputeMic ( uint8_t *key, uint8_t* buffer, uint8_t bufferLength);
static void EncryptFRMPayload (uint8_t* buffer, uint8_t bufferLength, uint8_t dir, uint32_t frameCounter, uint8_t* key, uint8_t macBufferIndex, uint8_t* bufferToBeEncrypted, uint8_t multicastStatus);
static uint8_t* MacExecuteCommands (uint8_t *buffer, uint8_t fOptsLen);
static void SetReceptionNotOkState (void);
static void ConfigureRadioRx(uint8_t dataRate, uint32_t freq);
extern void UpdateCfList (uint8_t bufferLength, JoinAccept_t *joinAccept);
uint8_t localDioStatus;
extern GenericEui_t JoinEui, DevEui;
/****************************** PUBLIC FUNCTIONS ******************************/
void LORAWAN_SetActivationType(ActivationType_t activationTypeNew)
{
loRa.activationParameters.activationType = activationTypeNew;
}
LorawanError_t LORAWAN_Join(ActivationType_t activationTypeNew)
{
uint8_t bufferIndex;
LorawanError_t result;
if (loRa.macStatus.macPause == ENABLED)
{
return MAC_PAUSED; // Any further transmissions or receptions cannot occur is macPaused is enabled.
}
if (loRa.macStatus.silentImmediately == ENABLED)
{
return SILENT_IMMEDIATELY_ACTIVE;
}
if (loRa.macStatus.macState != IDLE)
{
return MAC_STATE_NOT_READY_FOR_TRANSMISSION;
}
loRa.activationParameters.activationType = activationTypeNew;
if (OTAA == activationTypeNew)
{
//OTAA
send_chars("Start joining Procedure... ");
if ( (loRa.macKeys.deviceEui == 0) || (loRa.macKeys.joinEui == 0) || (loRa.macKeys.applicationKey == 0) )
{
return KEYS_NOT_INITIALIZED;
}
else
{
bufferIndex = PrepareJoinRequestFrame ();
result = SelectChannelForTransmission (0);
if (result == OK)
{
if (RADIO_Transmit(macBuffer, bufferIndex) == OK)
{
UpdateJoinInProgress(TRANSMISSION_OCCURRING);
return OK;
}
else
{
return MAC_STATE_NOT_READY_FOR_TRANSMISSION;
}
}
else
{
return result;
}
}
}
else
{
//ABP
if ( (loRa.macKeys.applicationSessionKey == 0) || (loRa.macKeys.networkSessionKey == 0) || (loRa.macKeys.deviceAddress == 0) )
{
return KEYS_NOT_INITIALIZED;
}
else
{
UpdateJoinInProgress(ABP_DELAY);
SwTimerSetTimeout(loRa.abpJoinTimerId, MS_TO_TICKS_SHORT(ABP_TIMEOUT_MS));
SwTimerStart(loRa.abpJoinTimerId);
return OK;
}
}
}
LorawanError_t LORAWAN_Send (TransmissionType_t confirmed, uint8_t port, void *buffer, uint8_t bufferLength)
{
LorawanError_t result;
if (loRa.macStatus.macPause == ENABLED)
{
return MAC_PAUSED; // Any further transmissions or receptions cannot occur is macPaused is enabled.
}
if (loRa.macStatus.silentImmediately == ENABLED) // The server decided that any further uplink transmission is not possible from this end device.
{
return SILENT_IMMEDIATELY_ACTIVE;
}
if (loRa.macStatus.networkJoined == DISABLED) //The network needs to be joined before sending
{
return NETWORK_NOT_JOINED;
}
if ( (port < FPORT_MIN) && (bufferLength != 0) ) //Port number should be <= 1 if there is data to send. If port number is 0, it indicates only Mac commands are inside FRM Payload
{
return INVALID_PARAMETER;
}
//validate date length using MaxPayloadSize
if (bufferLength > LORAWAN_GetMaxPayloadSize ())
{
return INVALID_BUFFER_LENGTH;
}
if (loRa.fCntUp.value == UINT32_MAX)
{
// Inform application about rejoin in status
loRa.macStatus.rejoinNeeded = 1;
return FRAME_COUNTER_ERROR_REJOIN_NEEDED;
}
if ((loRa.macStatus.macState != IDLE) && (CLASS_A == loRa.deviceClass))
{
return MAC_STATE_NOT_READY_FOR_TRANSMISSION;
}
result = SelectChannelForTransmission (1);
if (result != OK)
{
return result;
}
else
{
if (CLASS_C == loRa.deviceClass)
{
RADIO_ReceiveStop();
}
AssemblePacket (confirmed, port, buffer, bufferLength);
if (RADIO_Transmit (&macBuffer[16], (uint8_t)loRa.lastPacketLength) == OK)
{
loRa.fCntUp.value ++; // the uplink frame counter increments for every new transmission (it does not increment for a retransmission)
if (CNF == confirmed)
{
loRa.lorawanMacStatus.ackRequiredFromNextDownlinkMessage = ENABLED;
}
loRa.lorawanMacStatus.synchronization = ENABLED; //set the synchronization flag because one packet was sent (this is a guard for the the RxAppData of the user)
loRa.macStatus.macState = TRANSMISSION_OCCURRING; // set the state of MAC to transmission occurring. No other packets can be sent afterwards
}
else
{
return MAC_STATE_NOT_READY_FOR_TRANSMISSION;
}
}
return OK;
}
//Set and get functions
LorawanError_t LORAWAN_SetMcast(bool status)
{
if (CLASS_A == loRa.deviceClass)
{
return INVALID_CLASS; // it works only for Class B and Class C
}
// Only ABP shall be checked
if (CLASS_C == loRa.deviceClass)
{
if(ENABLED == status)
{
if ((0 == loRa.macKeys.mcastApplicationSessionKey) ||
(0 == loRa.macKeys.mcastNetworkSessionKey) ||
(0 == loRa.macKeys.mcastDeviceAddress) )
{
return MCAST_PARAM_ERROR;
}
loRa.macStatus.mcastEnable = ENABLED;
}
else
{
loRa.macStatus.mcastEnable = DISABLED;
}
}
return OK;
}
bool LORAWAN_GetMcast(void)
{
return loRa.macStatus.mcastEnable;
}
void LORAWAN_SetMcastDeviceAddress (uint32_t mcastDeviceAddressNew)
{
loRa.activationParameters.mcastDeviceAddress.value = mcastDeviceAddressNew;
loRa.macKeys.mcastDeviceAddress = 1;
}
uint32_t LORAWAN_GetMcastDeviceAddress (void)
{
return loRa.activationParameters.mcastDeviceAddress.value;
}
void LORAWAN_SetMcastNetworkSessionKey (uint8_t *mcastNetworkSessionKeyNew)
{
memcpy(loRa.activationParameters.mcastNetworkSessionKey, mcastNetworkSessionKeyNew, 16);
loRa.macKeys.mcastNetworkSessionKey = 1;
}
void LORAWAN_SetMcastApplicationSessionKey (uint8_t *mcastApplicationSessionKeyNew)
{
memcpy( loRa.activationParameters.mcastApplicationSessionKey, mcastApplicationSessionKeyNew, 16);
loRa.macKeys.mcastApplicationSessionKey = 1;
}
void LORAWAN_GetMcastApplicationSessionKey (uint8_t *mcastApplicationSessionKey)
{
if (mcastApplicationSessionKey != NULL)
{
memcpy (mcastApplicationSessionKey, loRa.activationParameters.mcastApplicationSessionKey, 16);
}
}
void LORAWAN_GetMcastNetworkSessionKey (uint8_t *mcastNetworkSessionKey)
{
if (mcastNetworkSessionKey != NULL)
{
memcpy(mcastNetworkSessionKey, loRa.activationParameters.mcastNetworkSessionKey, sizeof(loRa.activationParameters.mcastNetworkSessionKey) );
}
}
void LORAWAN_SetDeviceEui (GenericEui_t *deviceEuiNew)
{
if (deviceEuiNew != NULL)
{
memcpy(loRa.activationParameters.deviceEui.buffer, deviceEuiNew, sizeof(loRa.activationParameters.deviceEui) );
loRa.macKeys.deviceEui = 1;
loRa.macStatus.networkJoined = DISABLED; // this is a guard against overwriting any of the addresses after one join was already done. If any of the addresses change, rejoin is needed
printVar("loRa.activationParameters.deviceEui=",PAR_EUI64,&loRa.activationParameters.deviceEui,true,true);
}
}
void LORAWAN_GetDeviceEui (GenericEui_t *deviceEui)
{
memcpy(deviceEui->buffer, loRa.activationParameters.deviceEui.buffer, sizeof(loRa.activationParameters.deviceEui) );
}
void LORAWAN_SetApplicationEui (GenericEui_t *applicationEuiNew)
{
if (applicationEuiNew != NULL)
{
memcpy(loRa.activationParameters.applicationEui.buffer, applicationEuiNew->buffer, 8);
loRa.macKeys.applicationEui = 1;
loRa.macStatus.networkJoined = DISABLED; // this is a guard against overwriting any of the addresses after one join was already done. If any of the addresses change, rejoin is needed
}
}
void LORAWAN_GetApplicationEui (GenericEui_t *applicationEui)
{
memcpy (applicationEui, loRa.activationParameters.applicationEui.buffer, sizeof(loRa.activationParameters.applicationEui) );
}
void LORAWAN_SetJoinEui (GenericEui_t *joinEuiNew)
{
if (joinEuiNew != NULL)
{
if(euicmp(&(loRa.activationParameters.joinEui),joinEuiNew))
{
memcpy(loRa.activationParameters.joinEui.buffer, joinEuiNew->buffer, 8);
loRa.macStatus.networkJoined = DISABLED; // this is a guard against overwriting any of the addresses after one join was already done. If any of the addresses change, rejoin is needed
if(euicmpnz(joinEuiNew))
{
loRa.macKeys.joinEui = 1;
}
else
{
loRa.macKeys.joinEui = 0;
}
}
else
{
if(euicmpnz(joinEuiNew))
{
loRa.macKeys.joinEui = 1;
}
else
{
loRa.macKeys.joinEui = 0;
loRa.macStatus.networkJoined = DISABLED; // this is a guard against overwriting any of the addresses after one join was already done. If any of the addresses change, rejoin is needed
}
}
}
printVar("loRa.activationParameters.joinEui=",PAR_EUI64,&(loRa.activationParameters.joinEui),true,true);
}
void LORAWAN_GetJoinEui (GenericEui_t *joinEui)
{
memcpy (joinEui->buffer, loRa.activationParameters.joinEui.buffer, sizeof(loRa.activationParameters.joinEui) );
}
void LORAWAN_SetDeviceAddress (uint32_t deviceAddressNew)
{
loRa.activationParameters.deviceAddress.value = deviceAddressNew;
loRa.macKeys.deviceAddress = 1;
loRa.macStatus.networkJoined = DISABLED; // this is a guard against overwriting any of the addresses after one join was already done. If any of the addresses change, rejoin is needed
}
uint32_t LORAWAN_GetDeviceAddress (void)
{
return loRa.activationParameters.deviceAddress.value;
}
void LORAWAN_SetNetworkSessionKey (uint8_t *networkSessionKeyNew)
{
if (networkSessionKeyNew != NULL)
{
memcpy(loRa.activationParameters.networkSessionKey, networkSessionKeyNew, 16);
loRa.macKeys.networkSessionKey = 1;
loRa.macStatus.networkJoined = DISABLED; // this is a guard against overwriting any of the addresses after one join was already done. If any of the addresses change, rejoin is needed
}
}
void LORAWAN_GetNetworkSessionKey (uint8_t *networkSessionKey)
{
memcpy (networkSessionKey, loRa.activationParameters.networkSessionKey, sizeof(loRa.activationParameters.networkSessionKey) );
}
void LORAWAN_SetApplicationSessionKey (uint8_t *applicationSessionKeyNew)
{
if (applicationSessionKeyNew != NULL)
{
memcpy( loRa.activationParameters.applicationSessionKey, applicationSessionKeyNew, 16);
loRa.macKeys.applicationSessionKey = 1;
loRa.macStatus.networkJoined = DISABLED; // this is a guard against overwriting any of the addresses after one join was already done. If any of the addresses change, rejoin is needed
}
}
void LORAWAN_GetApplicationSessionKey (uint8_t *applicationSessionKey)
{
memcpy (applicationSessionKey, loRa.activationParameters.applicationSessionKey, sizeof(loRa.activationParameters.applicationSessionKey) );
}
void LORAWAN_SetApplicationKey (uint8_t *applicationKeyNew)
{
if (applicationKeyNew != NULL)
{
memcpy( loRa.activationParameters.applicationKey, applicationKeyNew, 16);
loRa.macKeys.applicationKey = 1;
loRa.macStatus.networkJoined = DISABLED; // this is a guard against overwriting any of the addresses after one join was already done. If any of the addresses change, rejoin is needed
printVar("loRa.activationParameters.applicationKey=",PAR_KEY128,applicationKeyNew,true,true);
}
}
void LORAWAN_GetApplicationKey (uint8_t *applicationKey)
{
memcpy (applicationKey, loRa.activationParameters.applicationKey, sizeof(loRa.activationParameters.applicationKey) );
}
void LORAWAN_SetAdr (bool status)
{
loRa.macStatus.adr = status;
loRa.adrAckCnt = DISABLED;
loRa.lorawanMacStatus.adrAckRequest = DISABLED; // this flag should only be on when ADR is set and the adr ack counter is bigger than adr ack limit
}
bool LORAWAN_GetAdr (void)
{
return loRa.macStatus.adr;
}
LorawanError_t LORAWAN_SetCurrentDataRate (uint8_t valueNew)
{
// the current data rate cannot be smaller than the minimum data rate defined for all the channels or bigger than the maximum data rate defined for all the channels
if ( (valueNew < loRa.minDataRate) || (valueNew > loRa.maxDataRate) || (ValidateDataRate(valueNew) != OK) )
{
return INVALID_PARAMETER;
}
else
{
UpdateCurrentDataRate (valueNew);
return OK;
}
}
uint8_t LORAWAN_GetCurrentDataRate (void)
{
return loRa.currentDataRate;
}
LorawanError_t LORAWAN_SetTxPower (uint8_t txPowerNew)
{
LorawanError_t result = OK;
if (ValidateTxPower (txPowerNew) == OK)
{
UpdateTxPower (txPowerNew);
}
else
{
result = INVALID_PARAMETER;
}
return result;
}
uint8_t LORAWAN_GetTxPower (void)
{
return loRa.txPower;
}
uint8_t LORAWAN_GetSyncWord (void)
{
return loRa.syncWord;
}
void LORAWAN_SetSyncWord (uint8_t syncWord)
{
loRa.syncWord = syncWord;
}
void LORAWAN_SetUplinkCounter (uint32_t ctr)
{
loRa.fCntUp.value = ctr;
}
uint32_t LORAWAN_GetUplinkCounter (void)
{
return loRa.fCntUp.value;
}
void LORAWAN_SetDownlinkCounter (uint32_t ctr)
{
loRa.fCntDown.value = ctr;
}
uint32_t LORAWAN_GetDownlinkCounter (void)
{
return loRa.fCntDown.value;
}
// Set and get functions for protocol parameters
void LORAWAN_SetReceiveDelay1 (uint16_t receiveDelay1New)
{
loRa.protocolParameters.receiveDelay1 = receiveDelay1New;
loRa.protocolParameters.receiveDelay2 = loRa.protocolParameters.receiveDelay1 + 1000; // 1 second after receive delay 1
}
uint16_t LORAWAN_GetReceiveDelay1 (void)
{
return loRa.protocolParameters.receiveDelay1;
}
uint16_t LORAWAN_GetReceiveDelay2 (void)
{
return loRa.protocolParameters.receiveDelay2;
}
void LORAWAN_SetJoinAcceptDelay1 (uint16_t joinAcceptDelay1New)
{
loRa.protocolParameters.joinAcceptDelay1 = joinAcceptDelay1New;
}
uint16_t LORAWAN_GetJoinAcceptDelay1 (void)
{
return loRa.protocolParameters.joinAcceptDelay1;
}
void LORAWAN_SetJoinAcceptDelay2 (uint16_t joinAcceptDelay2New)
{
loRa.protocolParameters.joinAcceptDelay2 = joinAcceptDelay2New;
}
uint16_t LORAWAN_GetJoinAcceptDelay2 (void)
{
return loRa.protocolParameters.joinAcceptDelay2;
}
void LORAWAN_SetMaxFcntGap (uint16_t maxFcntGapNew)
{
loRa.protocolParameters.maxFcntGap = maxFcntGapNew;
}
uint16_t LORAWAN_GetMaxFcntGap (void)
{
return loRa.protocolParameters.maxFcntGap;
}
void LORAWAN_SetAdrAckLimit (uint8_t adrAckLimitNew)
{
loRa.protocolParameters.adrAckLimit = adrAckLimitNew;
}
uint8_t LORAWAN_GetAdrAckLimit (void)
{
return loRa.protocolParameters.adrAckLimit;
}
void LORAWAN_SetAdrAckDelay(uint8_t adrAckDelayNew)
{
loRa.protocolParameters.adrAckDelay = adrAckDelayNew;
}
uint8_t LORAWAN_GetAdrAckDelay (void)
{
return loRa.protocolParameters.adrAckDelay;
}
void LORAWAN_SetAckTimeout(uint16_t ackTimeoutNew)
{
loRa.protocolParameters.ackTimeout = ackTimeoutNew;
}
uint16_t LORAWAN_GetAckTimeout (void)
{
return loRa.protocolParameters.ackTimeout;
}
void LORAWAN_SetClass (LoRaClass_t deviceClass)
{
loRa.deviceClass = deviceClass;
loRa.macStatus.mcastEnable = 0;
if (CLASS_C == deviceClass)
{
RADIO_SetWatchdogTimeout(0);
}
else if (deviceClass == CLASS_A)
{
loRa.macStatus.macState = IDLE;
RADIO_SetWatchdogTimeout(WATCHDOG_DEFAULT_TIME);
RADIO_ReceiveStop();
}
}
LoRaClass_t LORAWAN_GetClass (void)
{
return loRa.deviceClass;
}
void LORAWAN_SetMcastDownCounter(uint32_t newCnt)
{
loRa.fMcastCntDown.value = newCnt;
}
uint32_t LORAWAN_GetMcastDownCounter()
{
return loRa.fMcastCntDown.value;
}
void LORAWAN_SetNumberOfRetransmissions (uint8_t numberRetransmissions)
{
loRa.maxRepetitionsConfirmedUplink = numberRetransmissions;
}
// for confirmed frames, default value is 8. The number of retransmissions includes also the first transmission
uint8_t LORAWAN_GetNumberOfRetransmissions (void)
{
return loRa.maxRepetitionsConfirmedUplink;
}
void LORAWAN_GetReceiveWindow2Parameters (uint32_t* frequency, uint8_t* dataRate)
{
*dataRate = loRa.receiveWindow2Parameters.dataRate;
*frequency = loRa.receiveWindow2Parameters.frequency;
}
// battery Level: 0 - external power source, 1-254 level, 255: the end device was not able to measure the battery level
// default value for battery is 255 - the end device was not able to measure the battery level
void LORAWAN_SetBattery (uint8_t batteryLevelNew)
{
loRa.batteryLevel = batteryLevelNew;
}
// the LORAWAN_GetPrescaler function returns the prescaler value that is sent by the server to the end device via the Mac Command
// not user configurable
uint16_t LORAWAN_GetPrescaler (void)
{
return loRa.prescaler;
}
// if status is enabled, responses to ACK and MAC commands will be sent immediately
void LORAWAN_SetAutomaticReply (bool status)
{
loRa.macStatus.automaticReply = status;
}
bool LORAWAN_GetAutomaticReply (void)
{
return loRa.macStatus.automaticReply;
}
// not user configurable
uint32_t LORAWAN_GetStatus (void)
{
uint32_t status = loRa.macStatus.value;
loRa.macStatus.channelsModified = DISABLED;
loRa.macStatus.txPowerModified = DISABLED;
loRa.macStatus.nbRepModified = DISABLED;
loRa.macStatus.prescalerModified = DISABLED;
loRa.macStatus.secondReceiveWindowModified = DISABLED;
loRa.macStatus.rxTimingSetup = DISABLED;
return status;
}
// not user configurable
uint8_t LORAWAN_GetLinkCheckMargin (void)
{
return loRa.linkCheckMargin;
}
// not user configurable
uint8_t LORAWAN_GetLinkCheckGwCnt (void)
{
return loRa.linkCheckGwCnt;
}
/* This function is called when there is a need to send data outside the MAC layer
It can be called when MAC is in idle, before RX1, between RX1 and RX2 or retransmission delay state
It will return how much time other transmissions can occur*/
uint32_t LORAWAN_Pause (void)
{
uint32_t timeToPause;
switch (loRa.macStatus.macState)
{
case IDLE:
{
timeToPause = UINT32_MAX;
} break;
case BEFORE_RX1:
{
if (loRa.lorawanMacStatus.joining == ENABLED)
{
timeToPause = TICKS_TO_MS(SwTimerReadValue (loRa.joinAccept1TimerId));
}
else if (loRa.macStatus.networkJoined == ENABLED)
{
timeToPause = TICKS_TO_MS(SwTimerReadValue (loRa.receiveWindow1TimerId));
}
} break;
case BETWEEN_RX1_RX2:
{
if (loRa.lorawanMacStatus.joining == ENABLED)
{
timeToPause = SwTimerReadValue (loRa.joinAccept2TimerId);
}
else if (loRa.macStatus.networkJoined == ENABLED)
{
timeToPause = SwTimerReadValue (loRa.receiveWindow2TimerId);
}
timeToPause = TICKS_TO_MS(timeToPause);
} break;
case RETRANSMISSION_DELAY:
{
timeToPause = SwTimerReadValue (loRa.ackTimeoutTimerId);
timeToPause = TICKS_TO_MS(timeToPause);
} break;
default:
{
timeToPause = 0;
} break;
}
if (timeToPause >= 200)
{
timeToPause = timeToPause - 50; //this is a guard in case of non-syncronization
loRa.macStatus.macPause = ENABLED;
}
else
{
timeToPause = 0;
loRa.macStatus.macPause = DISABLED;
}
return timeToPause;
}
void LORAWAN_Resume (void)
{
loRa.macStatus.macPause = DISABLED;
}
// period will be in seconds
void LORAWAN_LinkCheckConfigure (uint16_t period)
{
uint8_t iCtr;
loRa.periodForLinkCheck = period * 1000UL;
// max link check period is 18 hours, period 0 means disabling the link check mechanism, default is disabled
if (period == 0)
{
SwTimerStop(loRa.linkCheckTimerId); // stop the link check timer
loRa.macStatus.linkCheck = DISABLED;
for(iCtr = 0; iCtr < loRa.crtMacCmdIndex; iCtr ++)
{
if(loRa.macCommands[iCtr].receivedCid == LINK_CHECK_CID)
{
//disable the link check mechanism
//Mark this CID as invalid
loRa.macCommands[iCtr].receivedCid = INVALID_VALUE;
loRa.crtMacCmdIndex --;
}
}
}
else
{
loRa.macStatus.linkCheck = ENABLED;
// if network is joined, the timer can start, otherwise after the network is joined the link check timer will start counting automatially
if (loRa.macStatus.networkJoined == ENABLED)
{
SwTimerSetTimeout(loRa.linkCheckTimerId, MS_TO_TICKS(loRa.periodForLinkCheck));
SwTimerStart(loRa.linkCheckTimerId);
}
}
}
// if LORAWAN_ForceEnable is sent, the Silent Immediately bit sent by the end device is discarded and transmission is possible again
void LORAWAN_ForceEnable (void)
{
loRa.macStatus.silentImmediately = DISABLED;
}
void LORAWAN_ReceiveWindow1Callback (uint8_t param)
{
uint32_t freq;
send_chars("RW1 ");
if(loRa.macStatus.macPause == DISABLED)
{
if (CLASS_C == loRa.deviceClass)
{
RADIO_ReceiveStop();
}
if (loRa.receiveWindow1Parameters.dataRate >= loRa.offset)
{
loRa.receiveWindow1Parameters.dataRate = loRa.receiveWindow1Parameters.dataRate - loRa.offset;
}
else
{
loRa.receiveWindow1Parameters.dataRate = DR0;
}
freq = GetRx1Freq();
loRa.macStatus.macState = RX1_OPEN;
RADIO_ReleaseData();
ConfigureRadioRx(loRa.receiveWindow1Parameters.dataRate, freq);
tt0_value=60000;
SwTimerSetTimeout(tt0,MS_TO_TICKS(tt0_value));
SwTimerStart(tt0);
RADIO_ReceiveStart(3*rxWindowSize[loRa.receiveWindow1Parameters.dataRate]);
// RADIO_SetWatchdogTimeout(5000);
// RADIO_ReceiveStart(0);
}
}
void LORAWAN_Receive(void)
{
uint8_t i;
RADIO_ReceiveStop();
RADIO_ReleaseData();
RADIO_SetWatchdogTimeout(0);
set_s("CHANNEL",&i);
if(mode!=MODE_REC && i!=0xFF)
{
ConfigureRadioRx(loRa.currentDataRate, Channels[i].frequency);
}
if(RADIO_ReceiveStart(0)==ERR_NONE)
{
loRa.macStatus.macState=RXCONT;
};
}
/*void LORAWAN_SendDownAckCallback (uint8_t param)
{
uint32_t freq;
if(loRa.macStatus.macPause == DISABLED)
{
RADIO_ReceiveStop();
send_chars(" Receiving stopped\r\n");
AssembleAckPacket (param);
SelectChannelForTransmission(1);
RADIO_SetWatchdogTimeout(5000);
if (RADIO_Transmit (&macBuffer[16], loRa.lastPacketLength) == OK)
{
printVar("Ack transmission begin payload length=",PAR_UI8,&loRa.lastPacketLength,false,true);
devices[param].fCntDown.value++; // the downlink frame counter increments for every new transmission (it does not increment for a retransmission)
loRa.lorawanMacStatus.synchronization = ENABLED; //set the synchronization flag because one packet was sent (this is a guard for the the RxAppData of the user)
loRa.macStatus.macState = TRANSMISSION_OCCURRING; // set the state of MAC to transmission occurring. No other packets can be sent afterwards
devices[param].macStatus.macState = TRANSMISSION_OCCURRING;
}
else
{
send_chars("Transmission not ready\r\n");
loRa.macStatus.macState = IDLE;
devices[param].macStatus.macState = MAC_STATE_NOT_READY_FOR_TRANSMISSION;
}
}
}*/
/*void LORAWAN_SendJoinAcceptCallback (uint8_t param)
{
uint32_t freq;
if(loRa.macStatus.macPause == DISABLED)
{
if(loRa.macStatus.macState==RXCONT)
{
RADIO_ReceiveStop();
send_chars(" Receiving stopped\r\n");
}
SelectChannelForTransmission(0);
RADIO_SetWatchdogTimeout(5000);
printVar("Join Accept transmission for device ",PAR_UI8,¶m,false,false);
if (RADIO_Transmit (devices[param].macBuffer, devices[param].bufferIndex) == OK)
{
printVar(" begin, payload length=",PAR_UI8,&devices[param].bufferIndex,false,true);
loRa.macStatus.macState = TRANSMISSION_OCCURRING; // set the state of MAC to transmission occurring. No other packets can be sent afterwards
}
else
{
send_chars("Transmission not ready\r\n");
loRa.macStatus.macState = MAC_STATE_NOT_READY_FOR_TRANSMISSION;
}
}
}*/
__reentrant void LORAWAN_ReceiveWindow2Callback(uint8_t param)
{
// Make sure the radio is not currently receiving (because a long packet is being received on RX window 1
send_chars("RW2 ");
if (loRa.macStatus.macPause == DISABLED)
{
if((RADIO_GetStatus() & RADIO_FLAG_RECEIVING) == 0)
{
loRa.macStatus.macState = RX2_OPEN;
RADIO_ReceiveStop();
RADIO_ReleaseData();
ConfigureRadioRx(loRa.receiveWindow2Parameters.dataRate, loRa.receiveWindow2Parameters.frequency);
if (CLASS_A == loRa.deviceClass)
{
if (RADIO_ReceiveStart(rxWindowSize[loRa.receiveWindow2Parameters.dataRate]) != OK)