/
rn2xx3.cpp
789 lines (673 loc) · 17.1 KB
/
rn2xx3.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
/*
* A library for controlling a Microchip rn2xx3 LoRa radio.
*
* @Author JP Meijers
* @Author Nicolas Schteinschraber
* @Date 18/12/2015
*
*/
#include "Arduino.h"
#include "rn2xx3.h"
extern "C" {
#include <string.h>
#include <stdlib.h>
}
/*
@param serial Needs to be an already opened Stream ({Software/Hardware}Serial) to write to and read from.
*/
rn2xx3::rn2xx3(Stream& serial):
_serial(serial)
{
_serial.setTimeout(2000);
}
//TODO: change to a boolean
void rn2xx3::autobaud()
{
String response = "";
// Try a maximum of 10 times with a 1 second delay
for (uint8_t i=0; i<10 && response==""; i++)
{
delay(1000);
_serial.write((byte)0x00);
_serial.write(0x55);
_serial.println();
// we could use sendRawCommand(F("sys get ver")); here
_serial.println("sys get ver");
response = _serial.readStringUntil('\n');
}
}
String rn2xx3::sysver()
{
String ver = sendRawCommand(F("sys get ver"));
ver.trim();
return ver;
}
RN2xx3_t rn2xx3::configureModuleType()
{
String version = sysver();
String model = version.substring(2,6);
switch (model.toInt()) {
case 2903:
_moduleType = RN2903;
break;
case 2483:
_moduleType = RN2483;
break;
default:
_moduleType = RN_NA;
break;
}
return _moduleType;
}
String rn2xx3::hweui()
{
return (sendRawCommand(F("sys get hweui")));
}
String rn2xx3::appeui()
{
return ( sendRawCommand(F("mac get appeui") ));
}
String rn2xx3::appkey()
{
// We can't read back from module, we send the one
// we have memorized if it has been set
return _appskey;
}
String rn2xx3::deveui()
{
return (sendRawCommand(F("mac get deveui")));
}
bool rn2xx3::init()
{
if(_appskey=="0") //appskey variable is set by both OTAA and ABP
{
return false;
}
else if(_otaa==true)
{
return initOTAA(_appeui, _appskey);
}
else
{
return initABP(_devAddr, _appskey, _nwkskey);
}
}
bool rn2xx3::initOTAA(String AppEUI, String AppKey, String DevEUI)
{
_otaa = true;
_nwkskey = "0";
String receivedData;
//clear serial buffer
while(_serial.available())
_serial.read();
// detect which model radio we are using
configureModuleType();
// reset the module - this will clear all keys set previously
switch (_moduleType)
{
case RN2903:
sendRawCommand(F("mac reset"));
break;
case RN2483:
sendRawCommand(F("mac reset 868"));
break;
default:
// we shouldn't go forward with the init
return false;
}
// If the Device EUI was given as a parameter, use it
// otherwise use the Hardware EUI.
if (DevEUI.length() == 16)
{
_deveui = DevEUI;
}
else
{
String addr = sendRawCommand(F("sys get hweui"));
if( addr.length() == 16 )
{
_deveui = addr;
}
// else fall back to the hard coded value in the header file
}
sendRawCommand("mac set deveui "+_deveui);
// A valid length App EUI was given. Use it.
if ( AppEUI.length() == 16 )
{
_appeui = AppEUI;
sendRawCommand("mac set appeui "+_appeui);
}
// A valid length App Key was give. Use it.
if ( AppKey.length() == 32 )
{
_appskey = AppKey; //reuse the same variable as for ABP
sendRawCommand("mac set appkey "+_appskey);
}
if (_moduleType == RN2903)
{
sendRawCommand(F("mac set pwridx 5"));
}
else
{
sendRawCommand(F("mac set pwridx 1"));
}
// TTN does not yet support Adaptive Data Rate.
// Using it is also only necessary in limited situations.
// Therefore disable it by default.
sendRawCommand(F("mac set adr off"));
// Switch off automatic replies, because this library can not
// handle more than one mac_rx per tx. See RN2483 datasheet,
// 2.4.8.14, page 27 and the scenario on page 19.
sendRawCommand(F("mac set ar off"));
// Semtech and TTN both use a non default RX2 window freq and SF.
// Maybe we should not specify this for other networks.
// if (_moduleType == RN2483)
// {
// sendRawCommand(F("mac set rx2 3 869525000"));
// }
// Disabled for now because an OTAA join seems to work fine without.
_serial.setTimeout(30000);
sendRawCommand(F("mac save"));
bool joined = false;
// Only try twice to join, then return and let the user handle it.
for(int i=0; i<2 && !joined; i++)
{
sendRawCommand(F("mac join otaa"));
// Parse 2nd response
receivedData = _serial.readStringUntil('\n');
if(receivedData.startsWith("accepted"))
{
joined=true;
delay(1000);
}
else
{
delay(1000);
}
}
_serial.setTimeout(2000);
return joined;
}
bool rn2xx3::initOTAA(uint8_t * AppEUI, uint8_t * AppKey, uint8_t * DevEUI)
{
String app_eui;
String dev_eui;
String app_key;
char buff[3];
app_eui="";
for (uint8_t i=0; i<8; i++)
{
sprintf(buff, "%02X", AppEUI[i]);
app_eui += String (buff);
}
dev_eui = "0";
if (DevEUI) //==0
{
dev_eui = "";
for (uint8_t i=0; i<8; i++)
{
sprintf(buff, "%02X", DevEUI[i]);
dev_eui += String (buff);
}
}
app_key="";
for (uint8_t i=0; i<16; i++)
{
sprintf(buff, "%02X", AppKey[i]);
app_key += String (buff);
}
return initOTAA(app_eui, app_key, dev_eui);
}
bool rn2xx3::initABP(String devAddr, String AppSKey, String NwkSKey)
{
_otaa = false;
_devAddr = devAddr;
_appskey = AppSKey;
_nwkskey = NwkSKey;
String receivedData;
//clear serial buffer
while(_serial.available())
_serial.read();
configureModuleType();
switch (_moduleType) {
case RN2903:
sendRawCommand(F("mac reset"));
break;
case RN2483:
sendRawCommand(F("mac reset 868"));
// sendRawCommand(F("mac set rx2 3 869525000"));
// In the past we set the downlink channel here,
// but setFrequencyPlan is a better place to do it.
break;
default:
// we shouldn't go forward with the init
return false;
}
sendRawCommand("mac set nwkskey "+_nwkskey);
sendRawCommand("mac set appskey "+_appskey);
sendRawCommand("mac set devaddr "+_devAddr);
sendRawCommand(F("mac set adr off"));
// Switch off automatic replies, because this library can not
// handle more than one mac_rx per tx. See RN2483 datasheet,
// 2.4.8.14, page 27 and the scenario on page 19.
sendRawCommand(F("mac set ar off"));
if (_moduleType == RN2903)
{
sendRawCommand("mac set pwridx 5");
}
else
{
sendRawCommand(F("mac set pwridx 1"));
}
sendRawCommand(F("mac set dr 5")); //0= min, 7=max
_serial.setTimeout(60000);
sendRawCommand(F("mac save"));
sendRawCommand(F("mac join abp"));
receivedData = _serial.readStringUntil('\n');
_serial.setTimeout(2000);
delay(1000);
if(receivedData.startsWith("accepted"))
{
return true;
//with abp we can always join successfully as long as the keys are valid
}
else
{
return false;
}
}
TX_RETURN_TYPE rn2xx3::tx(String data)
{
return txUncnf(data); //we are unsure which mode we're in. Better not to wait for acks.
}
TX_RETURN_TYPE rn2xx3::txBytes(const byte* data, uint8_t size)
{
char msgBuffer[size*2 + 1];
char buffer[3];
for (unsigned i=0; i<size; i++)
{
sprintf(buffer, "%02X", data[i]);
memcpy(&msgBuffer[i*2], &buffer, sizeof(buffer));
}
String dataToTx(msgBuffer);
return txCommand("mac tx uncnf 1 ", dataToTx, false);
}
TX_RETURN_TYPE rn2xx3::txCnf(String data)
{
return txCommand("mac tx cnf 1 ", data, true);
}
TX_RETURN_TYPE rn2xx3::txUncnf(String data)
{
return txCommand("mac tx uncnf 1 ", data, true);
}
TX_RETURN_TYPE rn2xx3::txCommand(String command, String data, bool shouldEncode)
{
bool send_success = false;
uint8_t busy_count = 0;
uint8_t retry_count = 0;
//clear serial buffer
while(_serial.available())
_serial.read();
while(!send_success)
{
//retransmit a maximum of 10 times
retry_count++;
if(retry_count>10)
{
return TX_FAIL;
}
_serial.print(command);
if(shouldEncode)
{
sendEncoded(data);
}
else
{
_serial.print(data);
}
_serial.println();
String receivedData = _serial.readStringUntil('\n');
//TODO: Debug print on receivedData
if(receivedData.startsWith("ok"))
{
_serial.setTimeout(30000);
receivedData = _serial.readStringUntil('\n');
_serial.setTimeout(2000);
//TODO: Debug print on receivedData
if(receivedData.startsWith("mac_tx_ok"))
{
//SUCCESS!!
send_success = true;
return TX_SUCCESS;
}
else if(receivedData.startsWith("mac_rx"))
{
//example: mac_rx 1 54657374696E6720313233
_rxMessenge = receivedData.substring(receivedData.indexOf(' ', 7)+1);
send_success = true;
return TX_WITH_RX;
}
else if(receivedData.startsWith("mac_err"))
{
init();
}
else if(receivedData.startsWith("invalid_data_len"))
{
//this should never happen if the prototype worked
send_success = true;
return TX_FAIL;
}
else if(receivedData.startsWith("radio_tx_ok"))
{
//SUCCESS!!
send_success = true;
return TX_SUCCESS;
}
else if(receivedData.startsWith("radio_err"))
{
//This should never happen. If it does, something major is wrong.
init();
}
else
{
//unknown response
//init();
}
}
else if(receivedData.startsWith("invalid_param"))
{
//should not happen if we typed the commands correctly
send_success = true;
return TX_FAIL;
}
else if(receivedData.startsWith("not_joined"))
{
init();
}
else if(receivedData.startsWith("no_free_ch"))
{
//retry
delay(1000);
}
else if(receivedData.startsWith("silent"))
{
init();
}
else if(receivedData.startsWith("frame_counter_err_rejoin_needed"))
{
init();
}
else if(receivedData.startsWith("busy"))
{
busy_count++;
// Not sure if this is wise. At low data rates with large packets
// this can perhaps cause transmissions at more than 1% duty cycle.
// Need to calculate the correct constant value.
// But it is wise to have this check and re-init in case the
// lorawan stack in the RN2xx3 hangs.
if(busy_count>=10)
{
init();
}
else
{
delay(1000);
}
}
else if(receivedData.startsWith("mac_paused"))
{
init();
}
else if(receivedData.startsWith("invalid_data_len"))
{
//should not happen if the prototype worked
send_success = true;
return TX_FAIL;
}
else
{
//unknown response after mac tx command
init();
}
}
return TX_FAIL; //should never reach this
}
void rn2xx3::sendEncoded(String input)
{
char working;
char buffer[3];
for (unsigned i=0; i<input.length(); i++)
{
working = input.charAt(i);
sprintf(buffer, "%02x", int(working));
_serial.print(buffer);
}
}
String rn2xx3::base16encode(String input)
{
char charsOut[input.length()*2+1];
char charsIn[input.length()+1];
input.trim();
input.toCharArray(charsIn, input.length()+1);
unsigned i = 0;
for(i = 0; i<input.length()+1; i++)
{
if(charsIn[i] == '\0') break;
int value = int(charsIn[i]);
char buffer[3];
sprintf(buffer, "%02x", value);
charsOut[2*i] = buffer[0];
charsOut[2*i+1] = buffer[1];
}
charsOut[2*i] = '\0';
String toReturn = String(charsOut);
return toReturn;
}
String rn2xx3::getRx() {
return _rxMessenge;
}
int rn2xx3::getSNR()
{
String snr = sendRawCommand(F("radio get snr"));
snr.trim();
return snr.toInt();
}
String rn2xx3::base16decode(String input)
{
char charsIn[input.length()+1];
char charsOut[input.length()/2+1];
input.trim();
input.toCharArray(charsIn, input.length()+1);
unsigned i = 0;
for(i = 0; i<input.length()/2+1; i++)
{
if(charsIn[i*2] == '\0') break;
if(charsIn[i*2+1] == '\0') break;
char toDo[2];
toDo[0] = charsIn[i*2];
toDo[1] = charsIn[i*2+1];
int out = strtoul(toDo, 0, 16);
if(out<128)
{
charsOut[i] = char(out);
}
}
charsOut[i] = '\0';
return charsOut;
}
void rn2xx3::setDR(int dr)
{
if(dr>=0 && dr<=5)
{
delay(100);
while(_serial.available())
_serial.read();
_serial.print("mac set dr ");
_serial.println(dr);
_serial.readStringUntil('\n');
}
}
void rn2xx3::sleep(long msec)
{
_serial.print("sys sleep ");
_serial.println(msec);
}
String rn2xx3::sendRawCommand(String command)
{
delay(100);
while(_serial.available())
_serial.read();
_serial.println(command);
String ret = _serial.readStringUntil('\n');
ret.trim();
//TODO: Add debug print
return ret;
}
RN2xx3_t rn2xx3::moduleType()
{
return _moduleType;
}
bool rn2xx3::setFrequencyPlan(FREQ_PLAN fp)
{
bool returnValue;
switch (fp)
{
case SINGLE_CHANNEL_EU:
{
if(_moduleType == RN2483)
{
//mac set rx2 <dataRate> <frequency>
//sendRawCommand(F("mac set rx2 5 868100000")); //use this for "strict" one channel gateways
sendRawCommand(F("mac set rx2 3 869525000")); //use for "non-strict" one channel gateways
sendRawCommand(F("mac set ch dcycle 0 99")); //1% duty cycle for this channel
sendRawCommand(F("mac set ch dcycle 1 65535")); //almost never use this channel
sendRawCommand(F("mac set ch dcycle 2 65535")); //almost never use this channel
returnValue = true;
}
else
{
returnValue = false;
}
break;
}
case TTN_EU:
{
if(_moduleType == RN2483)
{
/*
* The <dutyCycle> value that needs to be configured can be
* obtained from the actual duty cycle X (in percentage)
* using the following formula: <dutyCycle> = (100/X) – 1
*
* 10% -> 9
* 1% -> 99
* 0.33% -> 299
* 8 channels, total of 1% duty cycle:
* 0.125% per channel -> 799
*
* Most of the TTN_EU frequency plan was copied from:
* https://github.com/TheThingsNetwork/arduino-device-lib
*/
//RX window 2
sendRawCommand(F("mac set rx2 3 869525000"));
//channel 0
sendRawCommand(F("mac set ch dcycle 0 799"));
//channel 1
sendRawCommand(F("mac set ch drrange 1 0 6"));
sendRawCommand(F("mac set ch dcycle 1 799"));
//channel 2
sendRawCommand(F("mac set ch dcycle 2 799"));
//channel 3
sendRawCommand(F("mac set ch freq 3 867100000"));
sendRawCommand(F("mac set ch drrange 3 0 5"));
sendRawCommand(F("mac set ch dcycle 3 799"));
sendRawCommand(F("mac set ch status 3 on"));
//channel 4
sendRawCommand(F("mac set ch freq 4 867300000"));
sendRawCommand(F("mac set ch drrange 4 0 5"));
sendRawCommand(F("mac set ch dcycle 4 799"));
sendRawCommand(F("mac set ch status 4 on"));
//channel 5
sendRawCommand(F("mac set ch freq 5 867500000"));
sendRawCommand(F("mac set ch drrange 5 0 5"));
sendRawCommand(F("mac set ch dcycle 5 799"));
sendRawCommand(F("mac set ch status 5 on"));
//channel 6
sendRawCommand(F("mac set ch freq 6 867700000"));
sendRawCommand(F("mac set ch drrange 6 0 5"));
sendRawCommand(F("mac set ch dcycle 6 799"));
sendRawCommand(F("mac set ch status 6 on"));
//channel 7
sendRawCommand(F("mac set ch freq 7 867900000"));
sendRawCommand(F("mac set ch drrange 7 0 5"));
sendRawCommand(F("mac set ch dcycle 7 799"));
sendRawCommand(F("mac set ch status 7 on"));
returnValue = true;
}
else
{
returnValue = false;
}
break;
}
case TTN_US:
{
/*
* Most of the TTN_US frequency plan was copied from:
* https://github.com/TheThingsNetwork/arduino-device-lib
*/
if(_moduleType == RN2903)
{
for(int channel=0; channel<72; channel++)
{
// Build command string. First init, then add int.
String command = F("mac set ch status ");
command += channel;
if(channel>=8 && channel<16)
{
sendRawCommand(command+F(" on"));
}
else
{
sendRawCommand(command+F(" off"));
}
}
returnValue = true;
}
else
{
returnValue = false;
}
break;
}
case DEFAULT_EU:
{
if(_moduleType == RN2483)
{
//fix duty cycle - 1% = 0.33% per channel
sendRawCommand(F("mac set ch dcycle 0 799"));
sendRawCommand(F("mac set ch dcycle 1 799"));
sendRawCommand(F("mac set ch dcycle 2 799"));
//disable non-default channels
sendRawCommand(F("mac set ch status 3 on"));
sendRawCommand(F("mac set ch status 4 on"));
sendRawCommand(F("mac set ch status 5 on"));
sendRawCommand(F("mac set ch status 6 on"));
sendRawCommand(F("mac set ch status 7 on"));
returnValue = true;
}
else
{
returnValue = false;
}
break;
}
default:
{
//set default channels 868.1, 868.3 and 868.5?
returnValue = false; //well we didn't do anything, so yes, false
break;
}
}
return returnValue;
}