-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLMIC-node.cpp
1094 lines (938 loc) · 38.8 KB
/
LMIC-node.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
/*******************************************************************************
*
* File: LMIC-node.cpp
*
* Function: LMIC-node main application file.
*
* Copyright: Copyright (c) 2021 Leonel Lopes Parente
* Copyright (c) 2018 Terry Moore, MCCI
* Copyright (c) 2015 Thomas Telkamp and Matthijs Kooijman
*
* Permission is hereby granted, free of charge, to anyone
* obtaining a copy of this document and accompanying files to do,
* whatever they want with them without any restriction, including,
* but not limited to, copying, modification and redistribution.
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT ANY WARRANTY.
*
* License: MIT License. See accompanying LICENSE file.
*
* Author: Leonel Lopes Parente
*
* Description: To get LMIC-node up and running no changes need to be made
* to any source code. Only configuration is required
* in platform-io.ini and lorawan-keys.h.
*
* If you want to modify the code e.g. to add your own sensors,
* that can be done in the two area's that start with
* USER CODE BEGIN and end with USER CODE END. There's no need
* to change code in other locations (unless you have a reason).
* See README.md for documentation and how to use LMIC-node.
*
* LMIC-node uses the concepts from the original ttn-otaa.ino
* and ttn-abp.ino examples provided with the LMIC libraries.
* LMIC-node combines both OTAA and ABP support in a single example,
* supports multiple LMIC libraries, contains several improvements
* and enhancements like display support, support for downlinks,
* separates LoRaWAN keys from source code into a separate keyfile,
* provides formatted output to serial port and display
* and supports many popular development boards out of the box.
* To get a working node up and running only requires some configuration.
* No programming or customization of source code required.
*
* Dependencies: External libraries:
* MCCI LoRaWAN LMIC library https://github.com/mcci-catena/arduino-lmic
* IBM LMIC framework https://github.com/matthijskooijman/arduino-lmic
* U8g2 https://github.com/olikraus/u8g2
* EasyLed https://github.com/lnlp/EasyLed
*
******************************************************************************/
#include "LMIC-node.h"
#include "sensordata.h"
// █ █ █▀▀ █▀▀ █▀▄ █▀▀ █▀█ █▀▄ █▀▀ █▀▄ █▀▀ █▀▀ ▀█▀ █▀█
// █ █ ▀▀█ █▀▀ █▀▄ █ █ █ █ █ █▀▀ █▀▄ █▀▀ █ █ █ █ █
// ▀▀▀ ▀▀▀ ▀▀▀ ▀ ▀ ▀▀▀ ▀▀▀ ▀▀ ▀▀▀ ▀▀ ▀▀▀ ▀▀▀ ▀▀▀ ▀ ▀
const uint8_t payloadBufferLength = 17; // Adjust to fit max payload length
// Pin mappings for LoRa tranceiver
const lmic_pinmap lmic_pins = {
.nss = 18,
.rxtx = LMIC_UNUSED_PIN,
.rst = 14, // See remark about LORA_RST above.
.dio = { /*dio0*/ 26, /*dio1*/ 33, /*dio2*/ 32 }
#ifdef MCCI_LMIC
,
.rxtx_rx_active = 0,
.rssi_cal = 10,
.spi_freq = 8000000 /* 8 MHz */
#endif
};
bool boardInit(InitType initType)
{
// This function is used to perform board specific initializations.
// Required as part of standard template.
// InitType::Hardware Must be called at start of setup() before anything else.
// InitType::PostInitSerial Must be called after initSerial() before other initializations.
bool success = true;
switch (initType)
{
case InitType::Hardware:
// Note: Serial port and display are not yet initialized and cannot be used use here.
#ifdef USE_DISPLAY
// Initialize I2C Wire object with GPIO pins the display is connected to.
// These pins will be remembered and will not change if any library
// later calls Wire.begin() without parameters.
Wire.begin(4, 15);
#endif
break;
case InitType::PostInitSerial:
// Note: If enabled Serial port and display are already initialized here.
// No actions required for this board.
break;
}
return success;
}
#if defined(USE_SERIAL) || defined(USE_DISPLAY)
#ifdef MCCI_LMIC
static const char * const lmicEventNames[] = { LMIC_EVENT_NAME_TABLE__INIT };
static const char * const lmicErrorNames[] = { LMIC_ERROR_NAME__INIT };
#else
static const char * const lmicEventNames[] = { LEGACY_LMIC_EVENT_NAME_TABLE__INIT };
#endif
void printChars(Print& printer, char ch, uint8_t count, bool linefeed = false)
{
for (uint8_t i = 0; i < count; ++i)
{
printer.print(ch);
}
if (linefeed)
{
printer.println();
}
}
void printSpaces(Print& printer, uint8_t count, bool linefeed = false)
{
printChars(printer, ' ', count, linefeed);
}
void printHex(Print& printer, uint8_t* bytes, size_t length = 1, bool linefeed = false, char separator = 0)
{
for (size_t i = 0; i < length; ++i)
{
if (i > 0 && separator != 0)
{
printer.print(separator);
}
if (bytes[i] <= 0x0F)
{
printer.print('0');
}
printer.print(bytes[i], HEX);
}
if (linefeed)
{
printer.println();
}
}
void setTxIndicatorsOn(bool on = true)
{
if (on)
{
#ifdef USE_LED
led.on();
#endif
#ifdef USE_DISPLAY
displayTxSymbol(true);
#endif
}
else
{
#ifdef USE_LED
led.off();
#endif
#ifdef USE_DISPLAY
displayTxSymbol(false);
#endif
}
}
#endif // USE_SERIAL || USE_DISPLAY
// █ █ █▀▀ █▀▀ █▀▄ █▀▀ █▀█ █▀▄ █▀▀ █▀▀ █▀█ █▀▄
// █ █ ▀▀█ █▀▀ █▀▄ █ █ █ █ █ █▀▀ █▀▀ █ █ █ █
// ▀▀▀ ▀▀▀ ▀▀▀ ▀ ▀ ▀▀▀ ▀▀▀ ▀▀ ▀▀▀ ▀▀▀ ▀ ▀ ▀▀
uint8_t payloadBuffer[payloadBufferLength];
static osjob_t doWorkJob;
uint32_t doWorkIntervalSeconds = DO_WORK_INTERVAL_SECONDS; // Change value in platformio.ini
// Note: LoRa module pin mappings are defined in the Board Support Files.
// Set LoRaWAN keys defined in lorawan-keys.h.
#ifdef OTAA_ACTIVATION
static const u1_t PROGMEM DEVEUI[8] = { OTAA_DEVEUI } ;
static const u1_t PROGMEM APPEUI[8] = { OTAA_APPEUI };
static const u1_t PROGMEM APPKEY[16] = { OTAA_APPKEY };
// Below callbacks are used by LMIC for reading above values.
void os_getDevEui (u1_t* buf) { memcpy_P(buf, DEVEUI, 8); }
void os_getArtEui (u1_t* buf) { memcpy_P(buf, APPEUI, 8); }
void os_getDevKey (u1_t* buf) { memcpy_P(buf, APPKEY, 16); }
#else
// ABP activation
static const u4_t DEVADDR = ABP_DEVADDR ;
static const PROGMEM u1_t NWKSKEY[16] = { ABP_NWKSKEY };
static const u1_t PROGMEM APPSKEY[16] = { ABP_APPSKEY };
// Below callbacks are not used be they must be defined.
void os_getDevEui (u1_t* buf) { }
void os_getArtEui (u1_t* buf) { }
void os_getDevKey (u1_t* buf) { }
#endif
int16_t getSnrTenfold()
{
// Returns ten times the SNR (dB) value of the last received packet.
// Ten times to prevent the use of float but keep 1 decimal digit accuracy.
// Calculation per SX1276 datasheet rev.7 §6.4, SX1276 datasheet rev.4 §6.4.
// LMIC.snr contains value of PacketSnr, which is 4 times the actual SNR value.
return (LMIC.snr * 10) / 4;
}
int16_t getRssi(int8_t snr)
{
// Returns correct RSSI (dBm) value of the last received packet.
// Calculation per SX1276 datasheet rev.7 §5.5.5, SX1272 datasheet rev.4 §5.5.5.
#define RSSI_OFFSET 64
#define SX1276_FREQ_LF_MAX 525000000 // per datasheet 6.3
#define SX1272_RSSI_ADJUST -139
#define SX1276_RSSI_ADJUST_LF -164
#define SX1276_RSSI_ADJUST_HF -157
int16_t rssi;
#ifdef MCCI_LMIC
rssi = LMIC.rssi - RSSI_OFFSET;
#else
int16_t rssiAdjust;
#ifdef CFG_sx1276_radio
if (LMIC.freq > SX1276_FREQ_LF_MAX)
{
rssiAdjust = SX1276_RSSI_ADJUST_HF;
}
else
{
rssiAdjust = SX1276_RSSI_ADJUST_LF;
}
#else
// CFG_sx1272_radio
rssiAdjust = SX1272_RSSI_ADJUST;
#endif
// Revert modification (applied in lmic/radio.c) to get PacketRssi.
int16_t packetRssi = LMIC.rssi + 125 - RSSI_OFFSET;
if (snr < 0)
{
rssi = rssiAdjust + packetRssi + snr;
}
else
{
rssi = rssiAdjust + (16 * packetRssi) / 15;
}
#endif
return rssi;
}
void printEvent(ostime_t timestamp,
const char * const message,
PrintTarget target = PrintTarget::All,
bool clearDisplayStatusRow = true,
bool eventLabel = false)
{
#ifdef USE_DISPLAY
if (target == PrintTarget::All || target == PrintTarget::Display)
{
display.clearLine(TIME_ROW);
display.setCursor(COL_0, TIME_ROW);
display.print(F("Time:"));
display.print(timestamp);
display.clearLine(EVENT_ROW);
if (clearDisplayStatusRow)
{
display.clearLine(STATUS_ROW);
}
display.setCursor(COL_0, EVENT_ROW);
display.print(message);
}
#endif
#ifdef USE_SERIAL
// Create padded/indented output without using printf().
// printf() is not default supported/enabled in each Arduino core.
// Not using printf() will save memory for memory constrainted devices.
String timeString(timestamp);
uint8_t len = timeString.length();
uint8_t zerosCount = TIMESTAMP_WIDTH > len ? TIMESTAMP_WIDTH - len : 0;
if (target == PrintTarget::All || target == PrintTarget::Serial)
{
printChars(Serial, '0', zerosCount);
Serial.print(timeString);
Serial.print(": ");
if (eventLabel)
{
Serial.print(F("Event: "));
}
Serial.println(message);
}
#endif
}
void printEvent(ostime_t timestamp,
ev_t ev,
PrintTarget target = PrintTarget::All,
bool clearDisplayStatusRow = true)
{
#if defined(USE_DISPLAY) || defined(USE_SERIAL)
printEvent(timestamp, lmicEventNames[ev], target, clearDisplayStatusRow, true);
#endif
}
void printFrameCounters(PrintTarget target = PrintTarget::All)
{
#ifdef USE_DISPLAY
if (target == PrintTarget::Display || target == PrintTarget::All)
{
display.clearLine(FRMCNTRS_ROW);
display.setCursor(COL_0, FRMCNTRS_ROW);
display.print(F("Up:"));
display.print(LMIC.seqnoUp);
display.print(F(" Dn:"));
display.print(LMIC.seqnoDn);
}
#endif
#ifdef USE_SERIAL
if (target == PrintTarget::Serial || target == PrintTarget::All)
{
printSpaces(Serial, MESSAGE_INDENT);
Serial.print(F("Up: "));
Serial.print(LMIC.seqnoUp);
Serial.print(F(", Down: "));
Serial.println(LMIC.seqnoDn);
}
#endif
}
void printSessionKeys()
{
#if defined(USE_SERIAL) && defined(MCCI_LMIC)
u4_t networkId = 0;
devaddr_t deviceAddress = 0;
u1_t networkSessionKey[16];
u1_t applicationSessionKey[16];
LMIC_getSessionKeys(&networkId, &deviceAddress,
networkSessionKey, applicationSessionKey);
printSpaces(Serial, MESSAGE_INDENT);
Serial.print(F("Network Id: "));
Serial.println(networkId, DEC);
printSpaces(Serial, MESSAGE_INDENT);
Serial.print(F("Device Address: "));
Serial.println(deviceAddress, HEX);
printSpaces(Serial, MESSAGE_INDENT);
Serial.print(F("Application Session Key: "));
printHex(Serial, applicationSessionKey, 16, true, '-');
printSpaces(Serial, MESSAGE_INDENT);
Serial.print(F("Network Session Key: "));
printHex(Serial, networkSessionKey, 16, true, '-');
#endif
}
void printDownlinkInfo(void)
{
#if defined(USE_SERIAL) || defined(USE_DISPLAY)
uint8_t dataLength = LMIC.dataLen;
// bool ackReceived = LMIC.txrxFlags & TXRX_ACK;
int16_t snrTenfold = getSnrTenfold();
int8_t snr = snrTenfold / 10;
int8_t snrDecimalFraction = snrTenfold % 10;
int16_t rssi = getRssi(snr);
uint8_t fPort = 0;
if (LMIC.txrxFlags & TXRX_PORT)
{
fPort = LMIC.frame[LMIC.dataBeg -1];
}
#ifdef USE_DISPLAY
display.clearLine(EVENT_ROW);
display.setCursor(COL_0, EVENT_ROW);
display.print(F("RX P:"));
display.print(fPort);
if (dataLength != 0)
{
display.print(" Len:");
display.print(LMIC.dataLen);
}
display.clearLine(STATUS_ROW);
display.setCursor(COL_0, STATUS_ROW);
display.print(F("RSSI"));
display.print(rssi);
display.print(F(" SNR"));
display.print(snr);
display.print(".");
display.print(snrDecimalFraction);
#endif
#ifdef USE_SERIAL
printSpaces(Serial, MESSAGE_INDENT);
Serial.println(F("Downlink received"));
printSpaces(Serial, MESSAGE_INDENT);
Serial.print(F("RSSI: "));
Serial.print(rssi);
Serial.print(F(" dBm, SNR: "));
Serial.print(snr);
Serial.print(".");
Serial.print(snrDecimalFraction);
Serial.println(F(" dB"));
printSpaces(Serial, MESSAGE_INDENT);
Serial.print(F("Port: "));
Serial.println(fPort);
if (dataLength != 0)
{
printSpaces(Serial, MESSAGE_INDENT);
Serial.print(F("Length: "));
Serial.println(LMIC.dataLen);
printSpaces(Serial, MESSAGE_INDENT);
Serial.print(F("Data: "));
printHex(Serial, LMIC.frame+LMIC.dataBeg, LMIC.dataLen, true, ' ');
}
#endif
#endif
}
void printHeader(void)
{
#ifdef USE_DISPLAY
display.clear();
display.setCursor(COL_0, HEADER_ROW);
display.print(F("LMIC-node"));
#ifdef ABP_ACTIVATION
display.drawString(ABPMODE_COL, HEADER_ROW, "ABP");
#endif
#ifdef CLASSIC_LMIC
display.drawString(CLMICSYMBOL_COL, HEADER_ROW, "*");
#endif
display.drawString(COL_0, DEVICEID_ROW, deviceId);
display.setCursor(COL_0, INTERVAL_ROW);
display.print(F("Interval:"));
display.print(doWorkIntervalSeconds);
display.print("s");
#endif
#ifdef USE_SERIAL
Serial.println(F("\n\nLMIC-node\n"));
Serial.print(F("Device-id: "));
Serial.println(deviceId);
Serial.print(F("LMIC library: "));
#ifdef MCCI_LMIC
Serial.println(F("MCCI"));
#else
Serial.println(F("Classic [Deprecated]"));
#endif
Serial.print(F("Activation: "));
#ifdef OTAA_ACTIVATION
Serial.println(F("OTAA"));
#else
Serial.println(F("ABP"));
#endif
#if defined(LMIC_DEBUG_LEVEL) && LMIC_DEBUG_LEVEL > 0
Serial.print(F("LMIC debug: "));
Serial.println(LMIC_DEBUG_LEVEL);
#endif
Serial.print(F("Interval: "));
Serial.print(doWorkIntervalSeconds);
Serial.println(F(" seconds"));
if (activationMode == ActivationMode::OTAA)
{
Serial.println();
}
#endif
}
#ifdef ABP_ACTIVATION
void setAbpParameters(dr_t dataRate = DefaultABPDataRate, s1_t txPower = DefaultABPTxPower)
{
// Set static session parameters. Instead of dynamically establishing a session
// by joining the network, precomputed session parameters are be provided.
#ifdef PROGMEM
// On AVR, these values are stored in flash and only copied to RAM
// once. Copy them to a temporary buffer here, LMIC_setSession will
// copy them into a buffer of its own again.
uint8_t appskey[sizeof(APPSKEY)];
uint8_t nwkskey[sizeof(NWKSKEY)];
memcpy_P(appskey, APPSKEY, sizeof(APPSKEY));
memcpy_P(nwkskey, NWKSKEY, sizeof(NWKSKEY));
LMIC_setSession (0x1, DEVADDR, nwkskey, appskey);
#else
// If not running an AVR with PROGMEM, just use the arrays directly
LMIC_setSession (0x1, DEVADDR, NWKSKEY, APPSKEY);
#endif
#if defined(CFG_eu868)
// Set up the channels used by the Things Network, which corresponds
// to the defaults of most gateways. Without this, only three base
// channels from the LoRaWAN specification are used, which certainly
// works, so it is good for debugging, but can overload those
// frequencies, so be sure to configure the full frequency range of
// your network here (unless your network autoconfigures them).
// Setting up channels should happen after LMIC_setSession, as that
// configures the minimal channel set. The LMIC doesn't let you change
// the three basic settings, but we show them here.
LMIC_setupChannel(0, 868100000, DR_RANGE_MAP(DR_SF12, DR_SF7), BAND_CENTI); // g-band
LMIC_setupChannel(1, 868300000, DR_RANGE_MAP(DR_SF12, DR_SF7B), BAND_CENTI); // g-band
LMIC_setupChannel(2, 868500000, DR_RANGE_MAP(DR_SF12, DR_SF7), BAND_CENTI); // g-band
LMIC_setupChannel(3, 867100000, DR_RANGE_MAP(DR_SF12, DR_SF7), BAND_CENTI); // g-band
LMIC_setupChannel(4, 867300000, DR_RANGE_MAP(DR_SF12, DR_SF7), BAND_CENTI); // g-band
LMIC_setupChannel(5, 867500000, DR_RANGE_MAP(DR_SF12, DR_SF7), BAND_CENTI); // g-band
LMIC_setupChannel(6, 867700000, DR_RANGE_MAP(DR_SF12, DR_SF7), BAND_CENTI); // g-band
LMIC_setupChannel(7, 867900000, DR_RANGE_MAP(DR_SF12, DR_SF7), BAND_CENTI); // g-band
LMIC_setupChannel(8, 868800000, DR_RANGE_MAP(DR_FSK, DR_FSK), BAND_MILLI); // g2-band
// TTN defines an additional channel at 869.525Mhz using SF9 for class B
// devices' ping slots. LMIC does not have an easy way to define set this
// frequency and support for class B is spotty and untested, so this
// frequency is not configured here.
#elif defined(CFG_us915) || defined(CFG_au915)
// NA-US and AU channels 0-71 are configured automatically
// but only one group of 8 should (a subband) should be active
// TTN recommends the second sub band, 1 in a zero based count.
// https://github.com/TheThingsNetwork/gateway-conf/blob/master/US-global_conf.json
LMIC_selectSubBand(1);
#elif defined(CFG_as923)
// Set up the channels used in your country. Only two are defined by default,
// and they cannot be changed. Use BAND_CENTI to indicate 1% duty cycle.
// LMIC_setupChannel(0, 923200000, DR_RANGE_MAP(DR_SF12, DR_SF7), BAND_CENTI);
// LMIC_setupChannel(1, 923400000, DR_RANGE_MAP(DR_SF12, DR_SF7), BAND_CENTI);
// ... extra definitions for channels 2..n here
#elif defined(CFG_kr920)
// Set up the channels used in your country. Three are defined by default,
// and they cannot be changed. Duty cycle doesn't matter, but is conventionally
// BAND_MILLI.
// LMIC_setupChannel(0, 922100000, DR_RANGE_MAP(DR_SF12, DR_SF7), BAND_MILLI);
// LMIC_setupChannel(1, 922300000, DR_RANGE_MAP(DR_SF12, DR_SF7), BAND_MILLI);
// LMIC_setupChannel(2, 922500000, DR_RANGE_MAP(DR_SF12, DR_SF7), BAND_MILLI);
// ... extra definitions for channels 3..n here.
#elif defined(CFG_in866)
// Set up the channels used in your country. Three are defined by default,
// and they cannot be changed. Duty cycle doesn't matter, but is conventionally
// BAND_MILLI.
// LMIC_setupChannel(0, 865062500, DR_RANGE_MAP(DR_SF12, DR_SF7), BAND_MILLI);
// LMIC_setupChannel(1, 865402500, DR_RANGE_MAP(DR_SF12, DR_SF7), BAND_MILLI);
// LMIC_setupChannel(2, 865985000, DR_RANGE_MAP(DR_SF12, DR_SF7), BAND_MILLI);
// ... extra definitions for channels 3..n here.
#endif
// Disable link check validation
LMIC_setLinkCheckMode(0);
// TTN uses SF9 for its RX2 window.
LMIC.dn2Dr = DR_SF9;
// Set data rate and transmit power (note: txpow is possibly ignored by the library)
LMIC_setDrTxpow(dataRate, txPower);
}
#endif //ABP_ACTIVATION
void initLmic(bit_t adrEnabled = 1,
dr_t abpDataRate = DefaultABPDataRate,
s1_t abpTxPower = DefaultABPTxPower)
{
// ostime_t timestamp = os_getTime();
// Initialize LMIC runtime environment
os_init();
// Reset MAC state
LMIC_reset();
#ifdef ABP_ACTIVATION
setAbpParameters(abpDataRate, abpTxPower);
#endif
// Enable or disable ADR (data rate adaptation).
// Should be turned off if the device is not stationary (mobile).
// 1 is on, 0 is off.
LMIC_setAdrMode(adrEnabled);
if (activationMode == ActivationMode::OTAA)
{
#if defined(CFG_us915) || defined(CFG_au915)
// NA-US and AU channels 0-71 are configured automatically
// but only one group of 8 should (a subband) should be active
// TTN recommends the second sub band, 1 in a zero based count.
// https://github.com/TheThingsNetwork/gateway-conf/blob/master/US-global_conf.json
LMIC_selectSubBand(1);
#endif
}
// Relax LMIC timing if defined
#if defined(LMIC_CLOCK_ERROR_PPM)
uint32_t clockError = 0;
#if LMIC_CLOCK_ERROR_PPM > 0
#if defined(MCCI_LMIC) && LMIC_CLOCK_ERROR_PPM > 4000
// Allow clock error percentage to be > 0.4%
#define LMIC_ENABLE_arbitrary_clock_error 1
#endif
clockError = (LMIC_CLOCK_ERROR_PPM / 100) * (MAX_CLOCK_ERROR / 100) / 100;
LMIC_setClockError(clockError);
#endif
#ifdef USE_SERIAL
serial.print(F("Clock Error: "));
serial.print(LMIC_CLOCK_ERROR_PPM);
serial.print(" ppm (");
serial.print(clockError);
serial.println(")");
#endif
#endif
#ifdef MCCI_LMIC
// Register a custom eventhandler and don't use default onEvent() to enable
// additional features (e.g. make EV_RXSTART available). User data pointer is omitted.
LMIC_registerEventCb(&onLmicEvent, nullptr);
#endif
}
#ifdef MCCI_LMIC
void onLmicEvent(void *pUserData, ev_t ev)
#else
void onEvent(ev_t ev)
#endif
{
// LMIC event handler
ostime_t timestamp = os_getTime();
switch (ev)
{
#ifdef MCCI_LMIC
// Only supported in MCCI LMIC library:
case EV_RXSTART:
// Do not print anything for this event or it will mess up timing.
break;
case EV_TXSTART:
setTxIndicatorsOn();
printEvent(timestamp, ev);
break;
case EV_JOIN_TXCOMPLETE:
case EV_TXCANCELED:
setTxIndicatorsOn(false);
printEvent(timestamp, ev);
break;
#endif
case EV_JOINED:
setTxIndicatorsOn(false);
printEvent(timestamp, ev);
printSessionKeys();
// Disable link check validation.
// Link check validation is automatically enabled
// during join, but because slow data rates change
// max TX size, it is not used in this example.
LMIC_setLinkCheckMode(0);
// The doWork job has probably run already (while
// the node was still joining) and have rescheduled itself.
// Cancel the next scheduled doWork job and re-schedule
// for immediate execution to prevent that any uplink will
// have to wait until the current doWork interval ends.
os_clearCallback(&doWorkJob);
os_setCallback(&doWorkJob, doWorkCallback);
break;
case EV_TXCOMPLETE:
// Transmit completed, includes waiting for RX windows.
setTxIndicatorsOn(false);
printEvent(timestamp, ev);
printFrameCounters();
// Check if downlink was received
if (LMIC.dataLen != 0 || LMIC.dataBeg != 0)
{
uint8_t fPort = 0;
if (LMIC.txrxFlags & TXRX_PORT)
{
fPort = LMIC.frame[LMIC.dataBeg -1];
}
printDownlinkInfo();
processDownlink(timestamp, fPort, LMIC.frame + LMIC.dataBeg, LMIC.dataLen);
}
break;
// Below events are printed only.
case EV_SCAN_TIMEOUT:
case EV_BEACON_FOUND:
case EV_BEACON_MISSED:
case EV_BEACON_TRACKED:
case EV_RFU1: // This event is defined but not used in code
case EV_JOINING:
case EV_JOIN_FAILED:
case EV_REJOIN_FAILED:
case EV_LOST_TSYNC:
case EV_RESET:
case EV_RXCOMPLETE:
case EV_LINK_DEAD:
case EV_LINK_ALIVE:
#ifdef MCCI_LMIC
// Only supported in MCCI LMIC library:
case EV_SCAN_FOUND: // This event is defined but not used in code
#endif
printEvent(timestamp, ev);
break;
default:
printEvent(timestamp, "Unknown Event");
break;
}
}
static void doWorkCallback(osjob_t* job)
{
// Event hander for doWorkJob. Gets called by the LMIC scheduler.
// The actual work is performed in function processWork() which is called below.
ostime_t timestamp = os_getTime();
#ifdef USE_SERIAL
Serial.println();
printEvent(timestamp, "doWork job started", PrintTarget::Serial);
#endif
// Do the work that needs to be performed.
processWork(timestamp);
// This job must explicitly reschedule itself for the next run.
ostime_t startAt = timestamp + sec2osticks((int64_t)doWorkIntervalSeconds);
os_setTimedCallback(&doWorkJob, startAt, doWorkCallback);
}
lmic_tx_error_t scheduleUplink(uint8_t fPort, uint8_t* data, uint8_t dataLength, bool confirmed = false)
{
// This function is called from the processWork() function to schedule
// transmission of an uplink message that was prepared by processWork().
// Transmission will be performed at the next possible time
ostime_t timestamp = os_getTime();
printEvent(timestamp, "Packet queued");
lmic_tx_error_t retval = LMIC_setTxData2(fPort, data, dataLength, confirmed ? 1 : 0);
timestamp = os_getTime();
if (retval == LMIC_ERROR_SUCCESS)
{
#ifdef CLASSIC_LMIC
// For MCCI_LMIC this will be handled in EV_TXSTART
setTxIndicatorsOn();
#endif
}
else
{
String errmsg;
#ifdef USE_SERIAL
errmsg = "LMIC Error: ";
#ifdef MCCI_LMIC
errmsg.concat(lmicErrorNames[abs(retval)]);
#else
errmsg.concat(retval);
#endif
printEvent(timestamp, errmsg.c_str(), PrintTarget::Serial);
#endif
#ifdef USE_DISPLAY
errmsg = "LMIC Err: ";
errmsg.concat(retval);
printEvent(timestamp, errmsg.c_str(), PrintTarget::Display);
#endif
}
return retval;
}
// █ █ █▀▀ █▀▀ █▀▄ █▀▀ █▀█ █▀▄ █▀▀ █▀▄ █▀▀ █▀▀ ▀█▀ █▀█
// █ █ ▀▀█ █▀▀ █▀▄ █ █ █ █ █ █▀▀ █▀▄ █▀▀ █ █ █ █ █
// ▀▀▀ ▀▀▀ ▀▀▀ ▀ ▀ ▀▀▀ ▀▀▀ ▀▀ ▀▀▀ ▀▀ ▀▀▀ ▀▀▀ ▀▀▀ ▀ ▀
void preparePayload()
{
#ifdef USE_SERIAL
Serial.print(F("Temperature = "));
Serial.print(temperature);
Serial.println(" *C");
Serial.print(F("Humidity = "));
Serial.print(humidity);
Serial.println(" %");
Serial.print(F("Pressure = "));
Serial.print(pressure);
Serial.println(" hPa");
Serial.println();
Serial.println(String(millis() / 1000) + "s:PM2.5=" + String(levelP25) + ", PM10=" + String(levelP10));
#endif
uint8_t battery_level = 100; //PWR.getBatteryLevel();
uint16_t temp = temperature * 100;
uint16_t humi = humidity * 100;
uint32_t pres = pressure * 100;
uint32_t lvlP25 = levelP25 * 100;
uint32_t lvlP10 = levelP10 * 100;
payloadBuffer[0] = temp >> 8;
payloadBuffer[1] = temp;
payloadBuffer[2] = humi >> 8;
payloadBuffer[3] = humi;
payloadBuffer[4] = pres >> 24;
payloadBuffer[5] = pres >> 16;
payloadBuffer[6] = pres >> 8;
payloadBuffer[7] = pres;
payloadBuffer[8] = lvlP25 >> 24;
payloadBuffer[9] = lvlP25 >> 16;
payloadBuffer[10] = lvlP25 >> 8;
payloadBuffer[11] = lvlP25;
payloadBuffer[12] = lvlP10 >> 24;
payloadBuffer[13] = lvlP10 >> 16;
payloadBuffer[14] = lvlP10 >> 8;
payloadBuffer[15] = lvlP10;
payloadBuffer[16] = battery_level;
}
static volatile uint16_t counter_ = 0;
uint16_t getCounterValue()
{
// Increments counter and returns the new value.
delay(50); // Fake this takes some time
return ++counter_;
}
void resetCounter()
{
// Reset counter to 0
counter_ = 0;
}
void processWork(ostime_t doWorkJobTimeStamp)
{
// This function is called from the doWorkCallback()
// callback function when the doWork job is executed.
// Uses globals: payloadBuffer and LMIC data structure.
// This is where the main work is performed like
// reading sensor and GPS data and schedule uplink
// messages if anything needs to be transmitted.
// Skip processWork if using OTAA and still joining.
if (LMIC.devaddr != 0)
{
// Collect input data.
// For simplicity LMIC-node uses a counter to simulate a sensor.
// The counter is increased automatically by getCounterValue()
// and can be reset with a 'reset counter' command downlink message.
uint16_t counterValue = getCounterValue();
ostime_t timestamp = os_getTime();
#ifdef USE_DISPLAY
// Interval and Counter values are combined on a single row.
// This allows to keep the 3rd row empty which makes the
// information better readable on the small display.
display.clearLine(INTERVAL_ROW);
display.setCursor(COL_0, INTERVAL_ROW);
display.print("I:");
display.print(doWorkIntervalSeconds);
display.print("s");
display.print(" Ctr:");
display.print(counterValue);
#endif
#ifdef USE_SERIAL
printEvent(timestamp, "Input data collected", PrintTarget::Serial);
printSpaces(Serial, MESSAGE_INDENT);
Serial.print(F("COUNTER value: "));
Serial.println(counterValue);
#endif
// For simplicity LMIC-node will try to send an uplink
// message every time processWork() is executed.
// Schedule uplink message if possible
if (LMIC.opmode & OP_TXRXPEND)
{
// TxRx is currently pending, do not send.
#ifdef USE_SERIAL
printEvent(timestamp, "Uplink not scheduled because TxRx pending", PrintTarget::Serial);
#endif
#ifdef USE_DISPLAY
printEvent(timestamp, "UL not scheduled", PrintTarget::Display);
#endif
}
else
{
// Prepare uplink payload.
uint8_t fPort = 3;
//payloadBuffer[0] = counterValue >> 8;
//payloadBuffer[1] = counterValue & 0xFF;
preparePayload();
uint8_t payloadLength = 17;
scheduleUplink(fPort, payloadBuffer, payloadLength);
}
}
}
void processDownlink(ostime_t txCompleteTimestamp, uint8_t fPort, uint8_t* data, uint8_t dataLength)
{
// This function is called from the onEvent() event handler
// on EV_TXCOMPLETE when a downlink message was received.
// Implements a 'reset counter' command that can be sent via a downlink message.
// To send the reset counter command to the node, send a downlink message
// (e.g. from the TTN Console) with single byte value resetCmd on port cmdPort.
const uint8_t cmdPort = 100;
const uint8_t resetCmd= 0xC0;
if (fPort == cmdPort && dataLength == 1 && data[0] == resetCmd)
{
#ifdef USE_SERIAL
printSpaces(Serial, MESSAGE_INDENT);
Serial.println(F("Reset cmd received"));
#endif
ostime_t timestamp = os_getTime();
resetCounter();
printEvent(timestamp, "Counter reset", PrintTarget::All, false);
}
}
#ifdef USE_SERIAL
bool initSerial(unsigned long speed = 115200, int16_t timeoutSeconds = 0)
{
// Initializes the serial port.
// Optionally waits for serial port to be ready.
// Will display status and progress on display (if enabled)
// which can be useful for tracing (e.g. ATmega328u4) serial port issues.
// A negative timeoutSeconds value will wait indefinitely.
// A value of 0 (default) will not wait.
// Returns: true when serial port ready,
// false when not ready.
Serial.begin(speed);
#if WAITFOR_SERIAL_S != 0
if (timeoutSeconds != 0)
{
bool indefinite = (timeoutSeconds < 0);
uint16_t secondsLeft = timeoutSeconds;
#ifdef USE_DISPLAY
display.setCursor(0, ROW_1);
display.print(F("Waiting for"));
display.setCursor(0, ROW_2);
display.print(F("serial port"));
#endif
while (!serial && (indefinite || secondsLeft > 0))
{
if (!indefinite)
{
#ifdef USE_DISPLAY