-
Notifications
You must be signed in to change notification settings - Fork 0
/
loraComE5.cpp
903 lines (827 loc) · 29.7 KB
/
loraComE5.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
/**
* This file is part of Wio Helium Monitor.
*
* Wio Helium Monitor is free software created by Paul Pinault aka disk91.
* You can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* Wio Helium Monitor is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Wio LoRaWan Field Tester. If not, see <https://www.gnu.org/licenses/>.
*
* Author : Paul Pinault (disk91.com)
*/
#include <Arduino.h>
#include "config.h"
#include "loraCom.h"
#include "SoftwareSerial.h"
// Manage soft serial lines
#define SS1_RX BCM3 //BCM3 - TX on LoRa side
#define SS1_TX BCM2 //BCM2 - Rx on LoRa side
#define SS2_RX BCM27 //BCM27 - TX on LoRa side
#define SS2_TX BCM22 //BCM22 - Rx on LoRa side
#define DEFAULT_TIMEOUT 2000
#define PASSTHROUGH_TIMEOUT 15000
#define JOIN_TIMEOUT 12000
#define SEND_TIMEOUT_BASE 5000
#define MAX_RESP_BUF_SZ 64
enum Serials { HARDWARE, SOFT1, SOFT2 };
SoftwareSerial SSerial2(SS2_RX,SS2_TX);
SoftwareSerial SSerial1(SS1_RX,SS1_TX);
typedef struct {
char bufOkResp[MAX_RESP_BUF_SZ];
char bufErrResp[MAX_RESP_BUF_SZ];
char bufEnding[MAX_RESP_BUF_SZ];
char bufResponse[2*MAX_RESP_BUF_SZ];
bool withEndingCondition;
uint16_t respIndex;
bool runningCommand;
uint32_t startTime;
uint32_t elapsedTime;
uint32_t maxDuration;
bool statusCommand;
bool isJoining;
bool hasJoined;
int8_t lastDr;
int8_t lastPower;
int8_t lastRetry;
bool hasAcked;
bool downlinkPending;
uint32_t lastSendMs;
uint32_t estimatedDCMs;
bool (*lineProcessing)(void);
uint8_t currentSeqId; // simplified
float lastRssi;
float lastSnr;
uint8_t tmpInt8;
e_state cState; // Current State (Joined / NotJoined)
enum Serials _serial;
} loraE5_t;
loraE5_t loraContext;
bool processATResponse();
/**
* Execute an AT command with a timeout
* Search for okResp or errResp to determine is the command is a success or a fail
* When ending is defined, it search for this sentence to consider end of response
* Can be executed as a sync or async command.
* okResp and errResp can use joker char with '*'
* The okResp / errResp surch is a startsWith operation
* When lineProcessing function is given, each of the line are transmitted to a custom function for processing, when return true, processing is stopped (like for ending)
*/
bool sendATCommand(const char * cmd, const char * okResp, const char * errResp, const char * ending, uint32_t timeoutMs, bool async, bool (*lineProcessing)(void) ) {
if ( loraContext.runningCommand ) {
LOGLN(("LoRa already processing"));
return false;
}
loraContext.runningCommand = true;
loraContext.startTime = millis();
loraContext.maxDuration = timeoutMs;
strcpy(loraContext.bufOkResp,okResp);
strcpy(loraContext.bufErrResp,errResp);
if ( ending != NULL && strlen(ending) > 0 ) {
strcpy(loraContext.bufEnding,ending);
loraContext.withEndingCondition = true;
} else {
loraContext.withEndingCondition = false;
}
loraContext.respIndex = 0;
loraContext.lineProcessing = lineProcessing;
switch ( loraContext._serial ) {
case HARDWARE:
SERIALE5.printf("%s\r\n",cmd);
break;
case SOFT1:
SSerial1.printf("%s\r\n",cmd);
break;
case SOFT2:
SSerial2.printf("%s\r\n",cmd);
break;
}
LOGLORALN((cmd));
bool done = false;
if ( !async ) {
while ( ! processATResponse() );
return loraContext.statusCommand;
}
return true;
}
// compare str with a ref string and return true when
// str starts with ref. Case sensitive. ref can contain
// a joker char *
bool startsWith(const char * str, const char * ref) {
if ( strlen(str) >= strlen(ref) ) {
// possible
int i;
for ( i = 0 ; i < strlen(ref) ; i++ ) {
if ( ref[i] != '*' && str[i] != ref[i] ) {
break;
}
}
return ( i == strlen(ref) );
}
return false;
}
// search for index of char after the ref string in the str
// return -1 when not found
int indexOf(const char * str, const char * ref) {
int sStr = strlen(str);
int sRef = strlen(ref);
int e;
for ( int d = 0 ; d < (sStr - sRef) ; d++ ) {
if ( str[d] == ref[0] ) {
for ( e = 1 ; e < sRef ; e++ ) {
if ( str[d+e] != ref[e] ) {
break;
}
}
if ( e == sRef ) {
return d+e;
}
}
}
return -1;
}
/**
* Process command response
* return true when nothing more to be done
*/
bool processATResponse() {
// nothing to be done
if ( !loraContext.runningCommand ) return true;
// manage timeout
uint32_t duration = millis() - loraContext.startTime; // overflow after 50D. risk taken.
if ( duration > loraContext.maxDuration ) {
loraContext.runningCommand = false;
loraContext.statusCommand = false;
LOGLN(("LoRa timeout"));
return true;
}
// process serial line response
while ( (loraContext._serial == HARDWARE && SERIALE5.available() > 0)
|| (loraContext._serial == SOFT1 && SSerial1.available() > 0)
|| (loraContext._serial == SOFT2 && SSerial2.available() > 0)
) {
char c;
switch ( loraContext._serial ) {
case HARDWARE:
c = SERIALE5.read();
break;
case SOFT1:
c = SSerial1.read();
break;
case SOFT2:
c = SSerial2.read();
break;
}
if ( (c == '\0' || c == '\r' || c == '\n' ) ) {
if ( loraContext.respIndex > 0 ) {
// process line response
loraContext.bufResponse[loraContext.respIndex] = '\0';
LOGLORALN((loraContext.bufResponse));
int i;
if ( loraContext.lineProcessing != NULL ) {
if ( loraContext.lineProcessing() ) {
loraContext.runningCommand = false;
loraContext.respIndex = 0;
return true;
}
}
if ( strlen(loraContext.bufErrResp) > 0 && startsWith(loraContext.bufResponse,loraContext.bufErrResp) ) {
// Error String found
if ( ! loraContext.withEndingCondition ) {
loraContext.runningCommand = false;
}
loraContext.statusCommand = false;
loraContext.respIndex = 0;
LOGLN(("LoRa Error"));
return !loraContext.withEndingCondition;
}
if ( strlen(loraContext.bufOkResp) > 0 && startsWith(loraContext.bufResponse,loraContext.bufOkResp) ) {
// Success String found
if ( ! loraContext.withEndingCondition ) {
loraContext.runningCommand = false;
}
loraContext.statusCommand = true;
loraContext.respIndex = 0;
return !loraContext.withEndingCondition;
}
if ( loraContext.withEndingCondition && startsWith(loraContext.bufResponse,loraContext.bufEnding) ) {
// this is the end
loraContext.runningCommand = false;
loraContext.respIndex = 0;
return true;
}
}
loraContext.respIndex = 0;
} else {
if ( c >=32 && c <=127 ) {
if ( loraContext.respIndex < 2*MAX_RESP_BUF_SZ ) {
loraContext.bufResponse[loraContext.respIndex] = c;
loraContext.respIndex++;
} else {
LOGLN(("Response size overflow"));
loraContext.respIndex = 0;
}
}
}
}
return false;
}
bool loraE5Setup() {
char _cmd[128];
uint32_t start = millis();
switch ( loraContext._serial ) {
case HARDWARE:
SERIALE5.begin(9600);
while ( !SERIALE5 && (millis() - start) < 1000 );
break;
case SOFT1:
SSerial1.end();
SSerial1.begin(9600);
while ( !SSerial1 && (millis() - start) < 1000 );
break;
case SOFT2:
SSerial2.end();
SSerial2.begin(9600);
while ( !SSerial2 && (millis() - start) < 1000 );
break;
}
if ( (millis() - start) >= 1000 ) {
LOGLN(("Failed to connect to E5"));
return false;
}
loraContext.runningCommand = false;
loraContext.hasJoined = false;
loraContext.isJoining = false;
loraContext.lastDr = -1;
loraContext.lastPower = -100;
loraContext.lastRetry = -1;
loraContext.currentSeqId = 1;
loraContext.downlinkPending = false;
if ( ! sendATCommand("AT","+AT: OK","","",DEFAULT_TIMEOUT,false, NULL) ) {
// retry
if ( ! sendATCommand("AT","+AT: OK","","",DEFAULT_TIMEOUT,false, NULL) ) {
// error message
LOGLN(("Failed to contact E5"));
return false;
}
}
sendATCommand("AT+UART=TIMEOUT,0","+UART: TIMEOUT","","",DEFAULT_TIMEOUT,false, NULL);
// Setup region
if ( loraConf.zone == ZONE_EU868 ) {
sendATCommand("AT+DR=EU868","+DR: EU868","+DR: ERR","",DEFAULT_TIMEOUT,false,NULL);
sendATCommand("AT+CH=3,867.1,0,5","+CH: 3,8671","+CH: ERR","",DEFAULT_TIMEOUT,false,NULL);
sendATCommand("AT+CH=4,867.3,0,5","+CH: 4,8673","+CH: ERR","",DEFAULT_TIMEOUT,false,NULL);
sendATCommand("AT+CH=5,867.5,0,5","+CH: 5,8675","+CH: ERR","",DEFAULT_TIMEOUT,false,NULL);
sendATCommand("AT+CH=6,867.7,0,5","+CH: 6,8677","+CH: ERR","",DEFAULT_TIMEOUT,false,NULL);
sendATCommand("AT+CH=7,867.9,0,5","+CH: 7,8679","+CH: ERR","",DEFAULT_TIMEOUT,false,NULL);
sendATCommand("AT+LW=DC,OFF","+LW: DC, OFF","+LW: ERR","",DEFAULT_TIMEOUT,false,NULL); // manually managed to avoid conflicts
sendATCommand("AT+LW=JDC,OFF","+LW: JDC, OFF","+LW: ERR","",DEFAULT_TIMEOUT,false,NULL); // manually managed to avoid conflicts
} else if ( loraConf.zone == ZONE_US915 ) {
sendATCommand("AT+DR=US915","+DR: US915","+DR: ERR","",DEFAULT_TIMEOUT,false,NULL);
// unvalidate the subband other than 2
for ( int i=0 ; i < 72 ; i++ ) {
if ( i < 8 || i > 15 ) {
sprintf(_cmd,"AT+CH=%d,OFF",i);
sendATCommand(_cmd,"+CH: CH","+CH: ERR","",DEFAULT_TIMEOUT,false,NULL);
}
}
} else if ( loraConf.zone == ZONE_AS923_1 ) {
/* According to https://github.com/helium/router
923.6 MHz
923.8 MHz
924.0 MHz
924.2 MHz
924.4 MHz
*/
sendATCommand("AT+DR=AS923","+DR: AS923","+DR: ERR","",DEFAULT_TIMEOUT,false,NULL);
sendATCommand("AT+CH=0,923.2,0,5","+CH: 0,9232","+CH: ERR","",DEFAULT_TIMEOUT,false,NULL);
sendATCommand("AT+CH=1,923.4,0,5","+CH: 1,9234","+CH: ERR","",DEFAULT_TIMEOUT,false,NULL);
sendATCommand("AT+CH=2,923.6,0,5","+CH: 2,9236","+CH: ERR","",DEFAULT_TIMEOUT,false,NULL);
sendATCommand("AT+CH=3,923.8,0,5","+CH: 3,9238","+CH: ERR","",DEFAULT_TIMEOUT,false,NULL);
sendATCommand("AT+CH=4,924.0,0,5","+CH: 4,9240","+CH: ERR","",DEFAULT_TIMEOUT,false,NULL);
sendATCommand("AT+CH=5,924.2,0,5","+CH: 5,9242","+CH: ERR","",DEFAULT_TIMEOUT,false,NULL);
sendATCommand("AT+CH=6,924.4,0,5","+CH: 6,9244","+CH: ERR","",DEFAULT_TIMEOUT,false,NULL);
sendATCommand("AT+RXWIN2=923.2,DR2","+RXWIN2: 9232","+RXWIN2: ERR","",DEFAULT_TIMEOUT,false,NULL);
} else if ( loraConf.zone == ZONE_AS923_2 ) {
sendATCommand("AT+DR=AS923","+DR: AS923","+DR: ERR","",DEFAULT_TIMEOUT,false,NULL);
sendATCommand("AT+CH=0,921.4,0,5","+CH: 0,9214","+CH: ERR","",DEFAULT_TIMEOUT,false,NULL);
sendATCommand("AT+CH=1,921.6,0,5","+CH: 1,9216","+CH: ERR","",DEFAULT_TIMEOUT,false,NULL);
sendATCommand("AT+CH=2,921.8,0,5","+CH: 2,9218","+CH: ERR","",DEFAULT_TIMEOUT,false,NULL);
sendATCommand("AT+CH=3,922.0,0,5","+CH: 3,9220","+CH: ERR","",DEFAULT_TIMEOUT,false,NULL);
sendATCommand("AT+CH=4,922.2,0,5","+CH: 4,9222","+CH: ERR","",DEFAULT_TIMEOUT,false,NULL);
sendATCommand("AT+CH=5,922.4,0,5","+CH: 5,9224","+CH: ERR","",DEFAULT_TIMEOUT,false,NULL);
sendATCommand("AT+CH=6,922.6,0,5","+CH: 6,9226","+CH: ERR","",DEFAULT_TIMEOUT,false,NULL);
sendATCommand("AT+RXWIN2=921.4,DR2","+RXWIN2: 9214","+RXWIN2: ERR","",DEFAULT_TIMEOUT,false,NULL);
} else if ( loraConf.zone == ZONE_AS923_3 ) {
sendATCommand("AT+DR=AS923","+DR: AS923","+DR: ERR","",DEFAULT_TIMEOUT,false,NULL);
sendATCommand("AT+CH=0,916.6,0,5","+CH: 0,9166","+CH: ERR","",DEFAULT_TIMEOUT,false,NULL);
sendATCommand("AT+CH=1,916.8,0,5","+CH: 1,9168","+CH: ERR","",DEFAULT_TIMEOUT,false,NULL);
sendATCommand("AT+CH=2,917.0,0,5","+CH: 2,9170","+CH: ERR","",DEFAULT_TIMEOUT,false,NULL);
sendATCommand("AT+CH=3,917.2,0,5","+CH: 3,9172","+CH: ERR","",DEFAULT_TIMEOUT,false,NULL);
sendATCommand("AT+CH=4,917.4,0,5","+CH: 4,9174","+CH: ERR","",DEFAULT_TIMEOUT,false,NULL);
sendATCommand("AT+CH=5,917.6,0,5","+CH: 5,9176","+CH: ERR","",DEFAULT_TIMEOUT,false,NULL);
sendATCommand("AT+CH=6,917.8,0,5","+CH: 6,9178","+CH: ERR","",DEFAULT_TIMEOUT,false,NULL);
sendATCommand("AT+RXWIN2=916.6,DR2","+RXWIN2: 9166","+RXWIN2: ERR","",DEFAULT_TIMEOUT,false,NULL);
} else if ( loraConf.zone == ZONE_AS923_4 ) {
sendATCommand("AT+DR=AS923","+DR: AS923","+DR: ERR","",DEFAULT_TIMEOUT,false,NULL);
sendATCommand("AT+CH=0,917.3,0,5","+CH: 0,9173","+CH: ERR","",DEFAULT_TIMEOUT,false,NULL);
sendATCommand("AT+CH=1,917.5,0,5","+CH: 1,9175","+CH: ERR","",DEFAULT_TIMEOUT,false,NULL);
sendATCommand("AT+CH=2,917.7,0,5","+CH: 2,9177","+CH: ERR","",DEFAULT_TIMEOUT,false,NULL);
sendATCommand("AT+CH=3,917.9,0,5","+CH: 3,9179","+CH: ERR","",DEFAULT_TIMEOUT,false,NULL);
sendATCommand("AT+CH=4,918.1,0,5","+CH: 4,9181","+CH: ERR","",DEFAULT_TIMEOUT,false,NULL);
sendATCommand("AT+CH=5,918.3,0,5","+CH: 5,9183","+CH: ERR","",DEFAULT_TIMEOUT,false,NULL);
sendATCommand("AT+CH=6,918.5,0,5","+CH: 6,9185","+CH: ERR","",DEFAULT_TIMEOUT,false,NULL);
sendATCommand("AT+RXWIN2=917.3,DR2","+RXWIN2: 9173","+RXWIN2: ERR","",DEFAULT_TIMEOUT,false,NULL);
} else if ( loraConf.zone == ZONE_KR920 ) {
sendATCommand("AT+DR=KR920","+DR: KR920","+DR: ERR","",DEFAULT_TIMEOUT,false,NULL);
} else if ( loraConf.zone == ZONE_IN865 ) {
sendATCommand("AT+DR=IN865","+DR: IN865","+DR: ERR","",DEFAULT_TIMEOUT,false,NULL);
} else if ( loraConf.zone == ZONE_AU915 ) {
sendATCommand("AT+DR=AU915","+DR: AU915","+DR: ERR","",DEFAULT_TIMEOUT,false,NULL);
// unvalidate the subband other than 2
for ( int i=0 ; i < 72 ; i++ ) {
if ( i < 8 || i > 15 ) {
sprintf(_cmd,"AT+CH=%d,OFF",i);
sendATCommand(_cmd,"+CH: CH","+CH: ERR","",DEFAULT_TIMEOUT,false,NULL);
}
}
} else {
LOGLN(("Invalid Zone selected"));
return false;
}
sendATCommand("AT+ADR=OFF","+ADR: OFF","+ADR: ON","",DEFAULT_TIMEOUT,false,NULL);
// Setup Ids
sprintf(_cmd,"AT+ID=DevEUI,%02X%02X%02X%02X%02X%02X%02X%02X",
loraConf.deveui[0],
loraConf.deveui[1],
loraConf.deveui[2],
loraConf.deveui[3],
loraConf.deveui[4],
loraConf.deveui[5],
loraConf.deveui[6],
loraConf.deveui[7]
);
sendATCommand(_cmd,"+ID: DevEui","+ID: ERR","",DEFAULT_TIMEOUT,false,NULL);
sprintf(_cmd,"AT+ID=AppEUI,%02X%02X%02X%02X%02X%02X%02X%02X",
loraConf.appeui[0],
loraConf.appeui[1],
loraConf.appeui[2],
loraConf.appeui[3],
loraConf.appeui[4],
loraConf.appeui[5],
loraConf.appeui[6],
loraConf.appeui[7]
);
sendATCommand(_cmd,"+ID: AppEui","+ID: ERR","",DEFAULT_TIMEOUT,false,NULL);
sprintf(_cmd,"AT+KEY=APPKEY,%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
loraConf.appkey[0],
loraConf.appkey[1],
loraConf.appkey[2],
loraConf.appkey[3],
loraConf.appkey[4],
loraConf.appkey[5],
loraConf.appkey[6],
loraConf.appkey[7],
loraConf.appkey[8],
loraConf.appkey[9],
loraConf.appkey[10],
loraConf.appkey[11],
loraConf.appkey[12],
loraConf.appkey[13],
loraConf.appkey[14],
loraConf.appkey[15]
);
sendATCommand(_cmd,"+KEY: APPKEY","+KEY: ERR","",DEFAULT_TIMEOUT,false,NULL);
sendATCommand("AT+MODE=LWOTAA","+MODE: LWOTAA","+MODE: ERR","",DEFAULT_TIMEOUT,false,NULL);
return true;
}
// copy a float number into dst string
bool extractNumber(const char * src, char *dst, int maxSz) {
int idx = 0;
for ( idx = 0 ; idx < maxSz-1 ; idx ++ ) {
if ( src[idx] != ',' && src[idx] != ' ' && src[idx] != '\0' ) {
dst[idx] = src[idx];
} else {
break;
}
}
if ( idx < maxSz-1 ) {
dst[idx] = '\0';
return true;
}
return false;
}
// copy a hex string into a table
// returns the hexbyte in dst tab and the number of data in sz
// sz is also the max capacity of dst
// stops when non hexchar found
bool extractHexStr(const char * src, uint8_t * dst, uint8_t * sz) {
uint8_t tNum = 0;
uint8_t tSz = 0;
for ( int i = 0 ; ; i++ ) {
if ( src[i] >= '0' && src[i] <= '9' ) {
tNum += src[i] - '0';
} else if ( src[i] >= 'a' && src[i] <= 'f' ) {
tNum += 10 + src[i] - 'a';
} else if ( src[i] >= 'A' && src[i] <= 'F' ) {
tNum += 10 + src[i] - 'A';
} else break;
if ( (i & 1) == 0 ) {
// 1st digit
tNum *= 16;
} else {
// 2nd digit - store
dst[tSz] = tNum;
tNum = 0;
tSz++;
if (tSz >= *sz) break;
}
}
*sz = tSz;
return true;
}
// estimate DutyCycle duration for a single transmission in ms of pause
uint32_t interFrameDutyCycleEstimate(uint8_t _dr, uint8_t retries) {
if ( loraConf.zone == ZONE_EU868 ) {
// EU868
// 1% based on SF and data size (10 Bytes)
// @TODO also consider ack
// @TODO make this more generic considering payload size
if ( retries == 0 ) retries = 1;
switch (_dr) {
case 7: return retries*6200;
case 8: return retries*11300;
case 9: return retries*20600;
case 10: return retries*37100;
case 11: return retries*82300;
case 12: return retries*148300;
default:
LOGLN(("Invalid SF"));
return 200000;
}
} else {
// No Duty Cycle zones, set a minimum time
return NONDCZONE_DUTYCYCLE_MS;
}
}
// estimate Tx duration with AT interface
uint32_t txDurationEstimate(uint8_t _dr) {
switch (_dr) {
case 7: return 1500;
case 8: return 1600;
case 9: return 1800;
case 10: return 2000;
case 11: return 2500;
case 12: return 3000;
default:
LOGLN(("Invalid SF"));
return 2000;
}
}
// ---------------------------------------------------------------------
// Manage transmission response asynchronously
// example :
// 12:23:29.618 -> AT+CMSGHEX=20591A02324505490C07
// 12:23:29.721 -> +CMSGHEX: Start
// 12:23:29.721 -> +CMSGHEX: Wait ACK
// 12:23:33.559 -> +CMSGHEX: ACK Received
// 12:23:33.592 -> +CMSGHEX: PORT: 2; RX: "3E9999010101"
// 12:23:33.627 -> +CMSGHEX: RXWIN1, RSSI -84, SNR 6.0
// 12:23:33.627 -> +CMSGHEX: Done
bool processTx(void) {
if ( startsWith(loraContext.bufResponse,"+CMSGHEX: RXWIN*, RSSI") ) {
int s = indexOf(loraContext.bufResponse,"RSSI ");
loraContext.lastRssi = 0.0;
loraContext.lastSnr = 0.0;
if ( s > 0 ) {
char sRssi[10];
if ( extractNumber(&loraContext.bufResponse[s], sRssi,10) ) {
loraContext.lastRssi = atof(sRssi);
}
}
s = indexOf(loraContext.bufResponse,"SNR ");
if ( s > 0 ) {
char sSnr[10];
if ( extractNumber(&loraContext.bufResponse[s], sSnr,10) ) {
loraContext.lastSnr = atof(sSnr);
}
}
loraContext.hasAcked = true;
} else if (startsWith(loraContext.bufResponse,"+CMSGHEX: Done")) {
loraContext.elapsedTime = millis() - loraContext.startTime;
if ( loraContext.hasAcked ) {
uint8_t retries = loraContext.elapsedTime / txDurationEstimate(loraContext.lastDr); // really approximative approach
if ( loraContext.downlinkPending ) {
loraContext.cState = EMPTY_DWNLINK;
} else {
loraContext.cState = JOINED;
}
loraContext.estimatedDCMs = interFrameDutyCycleEstimate(loraContext.lastDr, retries);
} else {
loraContext.cState = JOINED;
}
// update the Duty cycle based on real retry estimate
loraContext.currentSeqId = (loraContext.currentSeqId + 1) & 0xFF ;
} else if ( startsWith(loraContext.bufResponse,"+CMSGHEX: FPEND") ) {
// downlink pending
loraContext.downlinkPending = true;
} else if ( startsWith(loraContext.bufResponse,"+CMSGHEX: PORT: *; RX: ") ) {
// downlink content
int s = indexOf(loraContext.bufResponse,"PORT: ");
int port=0;
if ( s > 0 ) {
char sPort[10];
if ( extractNumber(&loraContext.bufResponse[s], sPort,10) ) {
port = atoi(sPort);
}
}
s = indexOf(loraContext.bufResponse,"RX: \"");
if ( s > 0 ) {
uint8_t downlink[32];
uint8_t sz = 32;
if ( extractHexStr(&loraContext.bufResponse[s], downlink, &sz) ) {
/*
Process downlink
*/
}
}
} else {
// unprocessed lines
}
return false;
}
void do_sendE5(uint8_t port, uint8_t * data, uint8_t sz, uint8_t _dr, uint8_t pwr, bool acked, uint8_t retries ) {
char _cmd[128];
if ( loraContext.lastPower != pwr ) {
// set power (E5 automatically set to max if higher than max allowed)
sprintf(_cmd,"AT+POWER=%d",pwr);
if ( sendATCommand(_cmd,"+POWER:","+POWER: ERR","",DEFAULT_TIMEOUT,false,NULL) ) {
loraContext.lastPower = pwr;
} else {
LOGLN(("Failed to change Power"));
return;
}
}
if ( loraContext.lastDr != _dr ) {
// set dr ( for real dr is not dr but SF)
boolean retDr = true;
if ( loraConf.zone == ZONE_EU868
|| loraConf.zone == ZONE_AS923_1 || loraConf.zone == ZONE_AS923_2 || loraConf.zone == ZONE_AS923_3 || loraConf.zone == ZONE_AS923_4
|| loraConf.zone == ZONE_KR920 || loraConf.zone == ZONE_IN865 || loraConf.zone == ZONE_AU915 ) {
// DR0 - SF12 / DR5 - SF7
switch (_dr) {
case 7:
retDr = sendATCommand("AT+DR=DR5","+DR: ***** DR5","+DR: ERR","",DEFAULT_TIMEOUT,false,NULL);
break;
case 8:
retDr = sendATCommand("AT+DR=DR4","+DR: ***** DR4","+DR: ERR","",DEFAULT_TIMEOUT,false,NULL);
break;
case 9:
retDr = sendATCommand("AT+DR=DR3","+DR: ***** DR3","+DR: ERR","",DEFAULT_TIMEOUT,false,NULL);
break;
case 10:
retDr = sendATCommand("AT+DR=DR2","+DR: ***** DR2","+DR: ERR","",DEFAULT_TIMEOUT,false,NULL);
break;
case 11:
retDr = sendATCommand("AT+DR=DR1","+DR: ***** DR1","+DR: ERR","",DEFAULT_TIMEOUT,false,NULL);
break;
case 12:
retDr = sendATCommand("AT+DR=DR0","+DR: ***** DR0","+DR: ERR","",DEFAULT_TIMEOUT,false,NULL);
break;
default:
LOGLN(("Invalid SF"));
return;
}
} else if ( loraConf.zone == ZONE_US915 ) {
// DR0 - SF10 / DR3 - SF7
switch (_dr) {
case 7:
retDr = sendATCommand("AT+DR=DR3","+DR: ***** DR3","+DR: ERR","",DEFAULT_TIMEOUT,false,NULL);
break;
case 8:
retDr = sendATCommand("AT+DR=DR2","+DR: ***** DR2","+DR: ERR","",DEFAULT_TIMEOUT,false,NULL);
break;
case 9:
retDr = sendATCommand("AT+DR=DR1","+DR: ***** DR1","+DR: ERR","",DEFAULT_TIMEOUT,false,NULL);
break;
case 10:
case 11:
case 12:
retDr = sendATCommand("AT+DR=DR0","+DR: ***** DR0","+DR: ERR","",DEFAULT_TIMEOUT,false,NULL);
break;
default:
LOGLN(("Invalid SF"));
return;
}
} else {
retDr = false;
}
if ( ! retDr ) {
LOGLN(("Failed to change SF"));
return;
} else {
loraContext.lastDr = _dr;
}
}
if ( loraContext.lastRetry != retries ) {
// set retries
sprintf(_cmd,"AT+RETRY=%d",retries+1);
if ( sendATCommand(_cmd,"+RETRY:","+RETRY: ERR","",DEFAULT_TIMEOUT,false,NULL) ) {
loraContext.lastRetry = retries;
} else {
LOGLN(("Failed to change Retry"));
return;
}
}
// Set Pport
sprintf(_cmd,"AT+PORT=%d",port);
if ( !sendATCommand(_cmd,"+PORT:","+PORT: ERR","",DEFAULT_TIMEOUT,false,NULL) ) {
LOGLN(("Invalid Port"));
return;
}
loraContext.lastSendMs = millis();
if ( ! loraContext.hasJoined ) {
// we first need to join the network
// make it simple, the first frame will be lost during join
// 1% based on SF and data size (24 Bytes)
// @TODO also consider ack
switch (_dr) {
case 7: loraContext.estimatedDCMs = 8200; break;
case 8: loraContext.estimatedDCMs = 14400; break;
case 9: loraContext.estimatedDCMs = 26700; break;
case 10: loraContext.estimatedDCMs = 49400; break;
case 11: loraContext.estimatedDCMs = 106900; break;
case 12: loraContext.estimatedDCMs = 197400; break;
default:
LOGLN(("Invalid SF"));
return;
}
sendATCommand("AT+JOIN","+JOIN: Network joined","+JOIN: Join failed","+JOIN: Done",JOIN_TIMEOUT,true,NULL);
loraContext.isJoining = true;
loraContext.cState = JOINING;
} else {
loraContext.estimatedDCMs = interFrameDutyCycleEstimate(_dr,1);
if (acked) {
sprintf(_cmd,"AT+CMSGHEX=");
loraContext.estimatedDCMs *= (retries+1);
} else {
sprintf(_cmd,"AT+MSGHEX=");
}
int k = strlen(_cmd);
for ( int i = 0 ; i < sz && k < 115 ; i++ ) {
sprintf(&_cmd[k],"%02X",data[i]);
k+=2;
}
loraContext.hasAcked = false;
loraContext.downlinkPending = false;
loraContext.cState = IN_TX;
if (acked) {
sendATCommand(_cmd,"+CMSGHEX: Done","","",SEND_TIMEOUT_BASE*(retries+1),true,processTx);
} else {
sendATCommand(_cmd,"+MSGHEX: Done","","",SEND_TIMEOUT_BASE,true,processTx);
}
}
}
bool processPassThrough(void) {
Serial.println(loraContext.bufResponse);
return false;
}
void loraLoopE5() {
// --- LoRa E5 passthrough
// allow to send AT command from Serial line
static char _buffer[64];
static uint8_t _bufferIdx = 0;
while ( Serial.available() && _bufferIdx < 64 ) {
_buffer[_bufferIdx] = Serial.read();
if ( _buffer[_bufferIdx] == '\r' || _buffer[_bufferIdx] == '\n' ) {
_buffer[_bufferIdx] = '\0';
if ( _bufferIdx > 1 ) {
if ( ! sendATCommand(_buffer,"","","",PASSTHROUGH_TIMEOUT,true,processPassThrough)) {
Serial.println("Busy");
}
}
_bufferIdx=0;
} else {
_bufferIdx++;
}
}
if ( _bufferIdx == 64 ) _bufferIdx = 0;
// ---- end of passthrough
if ( processATResponse() ) {
// process command ended
// Was a join
if ( loraContext.isJoining ) {
loraContext.isJoining = false;
if ( loraContext.statusCommand ) {
// Joined
LOGLN(("Joined network"));
loraContext.hasJoined = true;
loraContext.cState = JOINED;
} else {
// Failed to join
LOGLN(("Failed to join network"));
loraContext.hasJoined = false;
loraContext.cState = JOIN_FAILED;
}
}
}
}
boolean isLoRaE5Connected() {
return ( loraContext.cState >= JOINED );
}
boolean canLoraSleep(void) {
return !loraContext.runningCommand;
}
boolean canLoRaSend(){
if ( loraContext.runningCommand || nextPossibleSendMs() > 0 ) {
return false;
}
return true;
}
uint32_t nextPossibleSendMs(){
int32_t delta = (loraContext.lastSendMs + loraContext.estimatedDCMs) - millis();
if ( delta > 0 ) return delta;
return 0;
}
bool loraE5QuickSetup() {
uint32_t start = millis();
switch ( loraContext._serial ) {
case HARDWARE:
SERIALE5.begin(9600);
while ( !SERIALE5 && (millis() - start) < 1000 );
break;
case SOFT1:
SSerial1.begin(9600);
while ( !SSerial1 && (millis() - start) < 1000 );
break;
case SOFT2:
SSerial2.begin(9600);
while ( !SSerial2 && (millis() - start) < 1000 );
break;
}
if ( (millis() - start) >= 1000 ) return false;
loraContext.runningCommand = false;
if ( ! sendATCommand("AT","+AT: OK","","",DEFAULT_TIMEOUT,false, NULL) ) {
// retry
if ( ! sendATCommand("AT","+AT: OK","","",DEFAULT_TIMEOUT,false, NULL) ) {
return false;
}
}
return true;
}
bool storeOneByte(uint8_t adr, uint8_t v) {
char _cmd[128];
sprintf(_cmd,"AT+EEPROM=%02X,%02X", adr, v);
return sendATCommand(_cmd,"+EEPROM: ","","",DEFAULT_TIMEOUT,false,NULL);
}
bool processRead(void) {
if ( startsWith(loraContext.bufResponse,"+EEPROM: **, **") ) {
int s = indexOf(loraContext.bufResponse,"PROM: ");
if ( s > 0 ) {
uint8_t values[1];
uint8_t sz = 1;
if ( extractHexStr(&loraContext.bufResponse[s+4], values,&sz) ) {
loraContext.tmpInt8 = values[0];
return true;
}
}
}
return false;
}
bool readOneByte(uint8_t adr, uint8_t * v) {
char _cmd[128];
sprintf(_cmd,"AT+EEPROM=%02X",adr);
if ( sendATCommand(_cmd,"+EEPROM: ","","",DEFAULT_TIMEOUT,false,processRead) ) {
*v = loraContext.tmpInt8;
return true;
}
return false;
}
bool detectLoRaE5SerialPort() {
loraContext._serial = HARDWARE;
if ( loraE5QuickSetup() ) {
LOGLN(("LoRa-E5 found on HW-Serial"));
return true;
}
loraContext._serial = SOFT1;
if ( loraE5QuickSetup() ) {
LOGLN(("LoRa-E5 found on SS-Serial1"));
SSerial1.end();
return true;
}
loraContext._serial = SOFT2;
if ( loraE5QuickSetup() ) {
LOGLN(("LoRa-E5 found on SS-Serial2"));
SSerial2.end();
return true;
}
loraContext._serial = HARDWARE;
return false;
}