-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathSparkFun_u-blox_SARA-R5_Arduino_Library.cpp
6932 lines (5965 loc) · 199 KB
/
SparkFun_u-blox_SARA-R5_Arduino_Library.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
/*
Arduino library for the u-blox SARA-R5 LTE-M / NB-IoT modules with secure cloud, as used on the SparkFun MicroMod Asset Tracker
By: Paul Clark
October 19th 2020
Based extensively on the:
Arduino Library for the SparkFun LTE CAT M1/NB-IoT Shield - SARA-R4
Written by Jim Lindblom @ SparkFun Electronics, September 5, 2018
This Arduino library provides mechanisms to initialize and use
the SARA-R5 module over either a SoftwareSerial or hardware serial port.
Please see LICENSE.md for the license information
*/
#include <SparkFun_u-blox_SARA-R5_Arduino_Library.h>
SARA_R5::SARA_R5(int powerPin, int resetPin, uint8_t maxInitTries)
{
#ifdef SARA_R5_SOFTWARE_SERIAL_ENABLED
_softSerial = nullptr;
#endif
_hardSerial = nullptr;
_baud = 0;
_resetPin = resetPin;
_powerPin = powerPin;
_invertPowerPin = false;
_maxInitTries = maxInitTries;
_socketListenCallback = nullptr;
_socketReadCallback = nullptr;
_socketReadCallbackPlus = nullptr;
_socketCloseCallback = nullptr;
_gpsRequestCallback = nullptr;
_simStateReportCallback = nullptr;
_psdActionRequestCallback = nullptr;
_pingRequestCallback = nullptr;
_httpCommandRequestCallback = nullptr;
_mqttCommandRequestCallback = nullptr;
_registrationCallback = nullptr;
_epsRegistrationCallback = nullptr;
_debugAtPort = nullptr;
_debugPort = nullptr;
_printDebug = false;
_lastRemoteIP = {0, 0, 0, 0};
_lastLocalIP = {0, 0, 0, 0};
for (int i = 0; i < SARA_R5_NUM_SOCKETS; i++)
_lastSocketProtocol[i] = 0; // Set to zero initially. Will be set to TCP/UDP by socketOpen etc.
_autoTimeZoneForBegin = true;
_bufferedPollReentrant = false;
_pollReentrant = false;
_saraResponseBacklogLength = 0;
_saraRXBuffer = nullptr;
_pruneBuffer = nullptr;
_saraResponseBacklog = nullptr;
}
SARA_R5::~SARA_R5(void) {
if (nullptr != _saraRXBuffer) {
delete[] _saraRXBuffer;
_saraRXBuffer = nullptr;
}
if (nullptr != _pruneBuffer) {
delete[] _pruneBuffer;
_pruneBuffer = nullptr;
}
if (nullptr != _saraResponseBacklog) {
delete[] _saraResponseBacklog;
_saraResponseBacklog = nullptr;
}
}
#ifdef SARA_R5_SOFTWARE_SERIAL_ENABLED
bool SARA_R5::begin(SoftwareSerial &softSerial, unsigned long baud)
{
if (nullptr == _saraRXBuffer)
{
_saraRXBuffer = new char[_RXBuffSize];
if (nullptr == _saraRXBuffer)
{
if (_printDebug == true)
_debugPort->println(F("begin: not enough memory for _saraRXBuffer!"));
return false;
}
}
memset(_saraRXBuffer, 0, _RXBuffSize);
if (nullptr == _pruneBuffer)
{
_pruneBuffer = new char[_RXBuffSize];
if (nullptr == _pruneBuffer)
{
if (_printDebug == true)
_debugPort->println(F("begin: not enough memory for _pruneBuffer!"));
return false;
}
}
memset(_pruneBuffer, 0, _RXBuffSize);
if (nullptr == _saraResponseBacklog)
{
_saraResponseBacklog = new char[_RXBuffSize];
if (nullptr == _saraResponseBacklog)
{
if (_printDebug == true)
_debugPort->println(F("begin: not enough memory for _saraResponseBacklog!"));
return false;
}
}
memset(_saraResponseBacklog, 0, _RXBuffSize);
SARA_R5_error_t err;
_softSerial = &softSerial;
err = init(baud);
if (err == SARA_R5_ERROR_SUCCESS)
{
return true;
}
return false;
}
#endif
bool SARA_R5::begin(HardwareSerial &hardSerial, unsigned long baud)
{
if (nullptr == _saraRXBuffer)
{
_saraRXBuffer = new char[_RXBuffSize];
if (nullptr == _saraRXBuffer)
{
if (_printDebug == true)
_debugPort->println(F("begin: not enough memory for _saraRXBuffer!"));
return false;
}
}
memset(_saraRXBuffer, 0, _RXBuffSize);
if (nullptr == _pruneBuffer)
{
_pruneBuffer = new char[_RXBuffSize];
if (nullptr == _pruneBuffer)
{
if (_printDebug == true)
_debugPort->println(F("begin: not enough memory for _pruneBuffer!"));
return false;
}
}
memset(_pruneBuffer, 0, _RXBuffSize);
if (nullptr == _saraResponseBacklog)
{
_saraResponseBacklog = new char[_RXBuffSize];
if (nullptr == _saraResponseBacklog)
{
if (_printDebug == true)
_debugPort->println(F("begin: not enough memory for _saraResponseBacklog!"));
return false;
}
}
memset(_saraResponseBacklog, 0, _RXBuffSize);
SARA_R5_error_t err;
_hardSerial = &hardSerial;
err = init(baud);
if (err == SARA_R5_ERROR_SUCCESS)
{
return true;
}
return false;
}
//Calling this function with nothing sets the debug port to Serial
//You can also call it with other streams like Serial1, SerialUSB, etc.
void SARA_R5::enableDebugging(Print &debugPort)
{
_debugPort = &debugPort;
_printDebug = true;
}
//Calling this function with nothing sets the debug port to Serial
//You can also call it with other streams like Serial1, SerialUSB, etc.
void SARA_R5::enableAtDebugging(Print &debugPort)
{
_debugAtPort = &debugPort;
_printAtDebug = true;
}
// This function was originally written by Matthew Menze for the LTE Shield (SARA-R4) library
// See: https://github.com/sparkfun/SparkFun_LTE_Shield_Arduino_Library/pull/8
// It does the same job as ::poll but also processed any 'old' data stored in the backlog first
// It also has a built-in timeout - which ::poll does not
bool SARA_R5::bufferedPoll(void)
{
if (_bufferedPollReentrant == true) // Check for reentry (i.e. bufferedPoll has been called from inside a callback)
return false;
_bufferedPollReentrant = true;
int avail = 0;
char c = 0;
bool handled = false;
unsigned long timeIn = millis();
char *event;
int backlogLen = _saraResponseBacklogLength;
memset(_saraRXBuffer, 0, _RXBuffSize); // Clear _saraRXBuffer
// Does the backlog contain any data? If it does, copy it into _saraRXBuffer and then clear the backlog
if (_saraResponseBacklogLength > 0)
{
//The backlog also logs reads from other tasks like transmitting.
if (_printDebug == true)
{
_debugPort->print(F("bufferedPoll: backlog found! backlogLen is "));
_debugPort->println(_saraResponseBacklogLength);
}
memcpy(_saraRXBuffer + avail, _saraResponseBacklog, _saraResponseBacklogLength);
avail += _saraResponseBacklogLength;
memset(_saraResponseBacklog, 0, _RXBuffSize); // Clear the backlog making sure it is NULL-terminated
_saraResponseBacklogLength = 0;
}
if ((hwAvailable() > 0) || (backlogLen > 0)) // If either new data is available, or backlog had data.
{
//Check for incoming serial data. Copy it into the backlog
// Important note:
// On ESP32, Serial.available only provides an update every ~120 bytes during the reception of long messages:
// https://gitter.im/espressif/arduino-esp32?at=5e25d6370a1cf54144909c85
// Be aware that if a long message is being received, the code below will timeout after _rxWindowMillis = 2 millis.
// At 115200 baud, hwAvailable takes ~120 * 10 / 115200 = 10.4 millis before it indicates that data is being received.
while (((millis() - timeIn) < _rxWindowMillis) && (avail < _RXBuffSize))
{
if (hwAvailable() > 0) //hwAvailable can return -1 if the serial port is NULL
{
c = readChar();
// bufferedPoll is only interested in the URCs.
// The URCs are all readable.
// strtok does not like NULL characters.
// So we need to make sure no NULL characters are added to _saraRXBuffer
if (c == '\0')
c = '0'; // Convert any NULLs to ASCII Zeros
_saraRXBuffer[avail++] = c;
timeIn = millis();
} else {
yield();
}
}
// _saraRXBuffer now contains the backlog (if any) and the new serial data (if any)
// A health warning about strtok:
// strtok will convert any delimiters it finds ("\r\n" in our case) into NULL characters.
// Also, be very careful that you do not use strtok within an strtok while loop.
// The next call of strtok(NULL, ...) in the outer loop will use the pointer saved from the inner loop!
// In our case, strtok is also used in pruneBacklog, which is called by waitForRespone or sendCommandWithResponse,
// which is called by the parse functions called by processURCEvent...
// The solution is to use strtok_r - the reentrant version of strtok
char *preservedEvent;
event = strtok_r(_saraRXBuffer, "\r\n", &preservedEvent); // Look for an 'event' (_saraRXBuffer contains something ending in \r\n)
if (event != nullptr)
if (_printDebug == true)
_debugPort->println(F("bufferedPoll: event(s) found! ===>"));
while (event != nullptr) // Keep going until all events have been processed
{
if (_printDebug == true)
{
_debugPort->print(F("bufferedPoll: start of event: "));
_debugPort->println(event);
}
//Process the event
bool latestHandled = processURCEvent((const char *)event);
if (latestHandled) {
if ((true == _printAtDebug) && (nullptr != event)) {
_debugAtPort->print(event);
}
handled = true; // handled will be true if latestHandled has ever been true
}
if ((_saraResponseBacklogLength > 0) && ((avail + _saraResponseBacklogLength) < _RXBuffSize)) // Has any new data been added to the backlog?
{
if (_printDebug == true)
{
_debugPort->println(F("bufferedPoll: new backlog added!"));
}
memcpy(_saraRXBuffer + avail, _saraResponseBacklog, _saraResponseBacklogLength);
avail += _saraResponseBacklogLength;
memset(_saraResponseBacklog, 0, _RXBuffSize); //Clear out the backlog buffer again.
_saraResponseBacklogLength = 0;
}
//Walk through any remaining events
event = strtok_r(nullptr, "\r\n", &preservedEvent);
if (_printDebug == true)
_debugPort->println(F("bufferedPoll: end of event")); //Just to denote end of processing event.
if (event == nullptr)
if (_printDebug == true)
_debugPort->println(F("bufferedPoll: <=== end of event(s)!"));
}
}
_bufferedPollReentrant = false;
return handled;
} // /bufferedPoll
// Parse incoming URC's - the associated parse functions pass the data to the user via the callbacks (if defined)
bool SARA_R5::processURCEvent(const char *event)
{
{ // URC: +UUSORD (Read Socket Data)
int socket, length;
char *searchPtr = strstr(event, SARA_R5_READ_SOCKET_URC);
if (searchPtr != nullptr)
{
searchPtr += strlen(SARA_R5_READ_SOCKET_URC); // Move searchPtr to first character - probably a space
while (*searchPtr == ' ') searchPtr++; // Skip spaces
int ret = sscanf(searchPtr, "%d,%d", &socket, &length);
if (ret == 2)
{
if (_printDebug == true)
_debugPort->println(F("processReadEvent: read socket data"));
// From the SARA_R5 AT Commands Manual:
// "For the UDP socket type the URC +UUSORD: <socket>,<length> notifies that a UDP packet has been received,
// either when buffer is empty or after a UDP packet has been read and one or more packets are stored in the
// buffer."
// So we need to check if this is a TCP socket or a UDP socket:
// If UDP, we call parseSocketReadIndicationUDP.
// Otherwise, we call parseSocketReadIndication.
if (_lastSocketProtocol[socket] == SARA_R5_UDP)
{
if (_printDebug == true)
_debugPort->println(F("processReadEvent: received +UUSORD but socket is UDP. Calling parseSocketReadIndicationUDP"));
parseSocketReadIndicationUDP(socket, length);
}
else
parseSocketReadIndication(socket, length);
return true;
}
}
}
{ // URC: +UUSORF (Receive From command (UDP only))
int socket, length;
char *searchPtr = strstr(event, SARA_R5_READ_UDP_SOCKET_URC);
if (searchPtr != nullptr)
{
searchPtr += strlen(SARA_R5_READ_UDP_SOCKET_URC); // Move searchPtr to first character - probably a space
while (*searchPtr == ' ') searchPtr++; // skip spaces
int ret = sscanf(searchPtr, "%d,%d", &socket, &length);
if (ret == 2)
{
if (_printDebug == true)
_debugPort->println(F("processReadEvent: UDP receive"));
parseSocketReadIndicationUDP(socket, length);
return true;
}
}
}
{ // URC: +UUSOLI (Set Listening Socket)
int socket = 0;
int listenSocket = 0;
unsigned int port = 0;
unsigned int listenPort = 0;
IPAddress remoteIP = {0,0,0,0};
IPAddress localIP = {0,0,0,0};
int remoteIPstore[4] = {0,0,0,0};
int localIPstore[4] = {0,0,0,0};
char *searchPtr = strstr(event, SARA_R5_LISTEN_SOCKET_URC);
if (searchPtr != nullptr)
{
searchPtr += strlen(SARA_R5_LISTEN_SOCKET_URC); // Move searchPtr to first character - probably a space
while (*searchPtr == ' ') searchPtr++; // skip spaces
int ret = sscanf(searchPtr,
"%d,\"%d.%d.%d.%d\",%u,%d,\"%d.%d.%d.%d\",%u",
&socket,
&remoteIPstore[0], &remoteIPstore[1], &remoteIPstore[2], &remoteIPstore[3],
&port, &listenSocket,
&localIPstore[0], &localIPstore[1], &localIPstore[2], &localIPstore[3],
&listenPort);
for (int i = 0; i <= 3; i++)
{
if (ret >= 5)
remoteIP[i] = (uint8_t)remoteIPstore[i];
if (ret >= 11)
localIP[i] = (uint8_t)localIPstore[i];
}
if (ret >= 5)
{
if (_printDebug == true)
_debugPort->println(F("processReadEvent: socket listen"));
parseSocketListenIndication(listenSocket, localIP, listenPort, socket, remoteIP, port);
return true;
}
}
}
{ // URC: +UUSOCL (Close Socket)
int socket;
char *searchPtr = strstr(event, SARA_R5_CLOSE_SOCKET_URC);
if (searchPtr != nullptr)
{
searchPtr += strlen(SARA_R5_CLOSE_SOCKET_URC); // Move searchPtr to first character - probably a space
while (*searchPtr == ' ') searchPtr++; // skip spaces
int ret = sscanf(searchPtr, "%d", &socket);
if (ret == 1)
{
if (_printDebug == true)
_debugPort->println(F("processReadEvent: socket close"));
if ((socket >= 0) && (socket <= 6))
{
if (_socketCloseCallback != nullptr)
{
_socketCloseCallback(socket);
}
}
return true;
}
}
}
{ // URC: +UULOC (Localization information - CellLocate and hybrid positioning)
ClockData clck;
PositionData gps;
SpeedData spd;
unsigned long uncertainty;
int scanNum;
int latH, lonH, alt;
unsigned int speedU, cogU;
char latL[10], lonL[10];
int dateStore[5];
// Maybe we should also scan for +UUGIND and extract the activated gnss system?
// This assumes the ULOC response type is "0" or "1" - as selected by gpsRequest detailed
char *searchPtr = strstr(event, SARA_R5_GNSS_REQUEST_LOCATION_URC);
if (searchPtr != nullptr)
{
searchPtr += strlen(SARA_R5_GNSS_REQUEST_LOCATION_URC); // Move searchPtr to first character - probably a space
while (*searchPtr == ' ') searchPtr++; // skip spaces
scanNum = sscanf(searchPtr,
"%d/%d/%d,%d:%d:%d.%d,%d.%[^,],%d.%[^,],%d,%lu,%u,%u,%*s",
&dateStore[0], &dateStore[1], &clck.date.year,
&dateStore[2], &dateStore[3], &dateStore[4], &clck.time.ms,
&latH, latL, &lonH, lonL, &alt, &uncertainty,
&speedU, &cogU);
clck.date.day = dateStore[0];
clck.date.month = dateStore[1];
clck.time.hour = dateStore[2];
clck.time.minute = dateStore[3];
clck.time.second = dateStore[4];
if (scanNum >= 13)
{
// Found a Location string!
if (_printDebug == true)
{
_debugPort->println(F("processReadEvent: location"));
}
if (latH >= 0)
gps.lat = (float)latH + ((float)atol(latL) / pow(10, strlen(latL)));
else
gps.lat = (float)latH - ((float)atol(latL) / pow(10, strlen(latL)));
if (lonH >= 0)
gps.lon = (float)lonH + ((float)atol(lonL) / pow(10, strlen(lonL)));
else
gps.lon = (float)lonH - ((float)atol(lonL) / pow(10, strlen(lonL)));
gps.alt = (float)alt;
if (scanNum >= 15) // If detailed response, get speed data
{
spd.speed = (float)speedU;
spd.cog = (float)cogU;
}
// if (_printDebug == true)
// {
// _debugPort->print(F("processReadEvent: location: lat: "));
// _debugPort->print(gps.lat, 7);
// _debugPort->print(F(" lon: "));
// _debugPort->print(gps.lon, 7);
// _debugPort->print(F(" alt: "));
// _debugPort->print(gps.alt, 2);
// _debugPort->print(F(" speed: "));
// _debugPort->print(spd.speed, 2);
// _debugPort->print(F(" cog: "));
// _debugPort->println(spd.cog, 2);
// }
if (_gpsRequestCallback != nullptr)
{
_gpsRequestCallback(clck, gps, spd, uncertainty);
}
return true;
}
}
}
{ // URC: +UUSIMSTAT (SIM Status)
SARA_R5_sim_states_t state;
int scanNum;
int stateStore;
char *searchPtr = strstr(event, SARA_R5_SIM_STATE_URC);
if (searchPtr != nullptr)
{
searchPtr += strlen(SARA_R5_SIM_STATE_URC); // Move searchPtr to first character - probably a space
while (*searchPtr == ' ') searchPtr++; // skip spaces
scanNum = sscanf(searchPtr, "%d", &stateStore);
if (scanNum == 1)
{
if (_printDebug == true)
_debugPort->println(F("processReadEvent: SIM status"));
state = (SARA_R5_sim_states_t)stateStore;
if (_simStateReportCallback != nullptr)
{
_simStateReportCallback(state);
}
return true;
}
}
}
{ // URC: +UUPSDA (Packet Switched Data Action)
int result;
IPAddress remoteIP = {0, 0, 0, 0};
int scanNum;
int remoteIPstore[4];
char *searchPtr = strstr(event, SARA_R5_MESSAGE_PDP_ACTION_URC);
if (searchPtr != nullptr)
{
searchPtr += strlen(SARA_R5_MESSAGE_PDP_ACTION_URC); // Move searchPtr to first character - probably a space
while (*searchPtr == ' ') searchPtr++; // skip spaces
scanNum = sscanf(searchPtr, "%d,\"%d.%d.%d.%d\"",
&result, &remoteIPstore[0], &remoteIPstore[1], &remoteIPstore[2], &remoteIPstore[3]);
if (scanNum == 5)
{
if (_printDebug == true)
_debugPort->println(F("processReadEvent: packet switched data action"));
for (int i = 0; i <= 3; i++)
{
remoteIP[i] = (uint8_t)remoteIPstore[i];
}
if (_psdActionRequestCallback != nullptr)
{
_psdActionRequestCallback(result, remoteIP);
}
return true;
}
}
}
{ // URC: +UUHTTPCR (HTTP Command Result)
int profile, command, result;
int scanNum;
char *searchPtr = strstr(event, SARA_R5_HTTP_COMMAND_URC);
if (searchPtr != nullptr)
{
searchPtr += strlen(SARA_R5_HTTP_COMMAND_URC); // Move searchPtr to first character - probably a space
while (*searchPtr == ' ') searchPtr++; // skip spaces
scanNum = sscanf(searchPtr, "%d,%d,%d", &profile, &command, &result);
if (scanNum == 3)
{
if (_printDebug == true)
_debugPort->println(F("processReadEvent: HTTP command result"));
if ((profile >= 0) && (profile < SARA_R5_NUM_HTTP_PROFILES))
{
if (_httpCommandRequestCallback != nullptr)
{
_httpCommandRequestCallback(profile, command, result);
}
}
return true;
}
}
}
{ // URC: +UUMQTTC (MQTT Command Result)
int command, result;
int scanNum;
int qos = -1;
String topic;
char *searchPtr = strstr(event, SARA_R5_MQTT_COMMAND_URC);
if (searchPtr != nullptr)
{
searchPtr += strlen(SARA_R5_MQTT_COMMAND_URC); // Move searchPtr to first character - probably a space
while (*searchPtr == ' ')
{
searchPtr++; // skip spaces
}
scanNum = sscanf(searchPtr, "%d,%d", &command, &result);
if ((scanNum == 2) && (command == SARA_R5_MQTT_COMMAND_SUBSCRIBE))
{
char topicC[100] = "";
scanNum = sscanf(searchPtr, "%*d,%*d,%d,\"%[^\"]\"", &qos, topicC);
topic = topicC;
}
if ((scanNum == 2) || (scanNum == 4))
{
if (_printDebug == true)
{
_debugPort->println(F("processReadEvent: MQTT command result"));
}
if (_mqttCommandRequestCallback != nullptr)
{
_mqttCommandRequestCallback(command, result);
}
return true;
}
}
}
{ // URC: +UUFTPCR (FTP Command Result)
int ftpCmd;
int ftpResult;
int scanNum;
char *searchPtr = strstr(event, SARA_R5_FTP_COMMAND_URC);
if (searchPtr != nullptr)
{
searchPtr += strlen(SARA_R5_FTP_COMMAND_URC); // Move searchPtr to first character - probably a space
while (*searchPtr == ' ')
{
searchPtr++; // skip spaces
}
scanNum = sscanf(searchPtr, "%d,%d", &ftpCmd, &ftpResult);
if (scanNum == 2 && _ftpCommandRequestCallback != nullptr)
{
_ftpCommandRequestCallback(ftpCmd, ftpResult);
return true;
}
}
}
{ // URC: +UUPING (Ping Result)
int retry = 0;
int p_size = 0;
int ttl = 0;
String remote_host = "";
IPAddress remoteIP = {0, 0, 0, 0};
long rtt = 0;
int scanNum;
// Try to extract the UUPING retries and payload size
char *searchPtr = strstr(event, SARA_R5_PING_COMMAND_URC);
if (searchPtr != nullptr)
{
searchPtr += strlen(SARA_R5_PING_COMMAND_URC); // Move searchPtr to first character - probably a space
while (*searchPtr == ' ') searchPtr++; // skip spaces
scanNum = sscanf(searchPtr, "%d,%d,", &retry, &p_size);
if (scanNum == 2)
{
if (_printDebug == true)
{
_debugPort->println(F("processReadEvent: ping"));
}
searchPtr = strchr(++searchPtr, '\"'); // Search to the first quote
// Extract the remote host name, stop at the next quote
while ((*(++searchPtr) != '\"') && (*searchPtr != '\0'))
{
remote_host.concat(*(searchPtr));
}
if (*searchPtr != '\0') // Make sure we found a quote
{
int remoteIPstore[4];
scanNum = sscanf(searchPtr, "\",\"%d.%d.%d.%d\",%d,%ld",
&remoteIPstore[0], &remoteIPstore[1], &remoteIPstore[2], &remoteIPstore[3], &ttl, &rtt);
for (int i = 0; i <= 3; i++)
{
remoteIP[i] = (uint8_t)remoteIPstore[i];
}
if (scanNum == 6) // Make sure we extracted enough data
{
if (_pingRequestCallback != nullptr)
{
_pingRequestCallback(retry, p_size, remote_host, remoteIP, ttl, rtt);
}
}
}
return true;
}
}
}
{ // URC: +CREG
int status = 0;
unsigned int lac = 0, ci = 0, Act = 0;
char *searchPtr = strstr(event, SARA_R5_REGISTRATION_STATUS_URC);
if (searchPtr != nullptr)
{
searchPtr += strlen(SARA_R5_REGISTRATION_STATUS_URC); // Move searchPtr to first character - probably a space
while (*searchPtr == ' ') searchPtr++; // skip spaces
int scanNum = sscanf(searchPtr, "%d,\"%4x\",\"%4x\",%d", &status, &lac, &ci, &Act);
if (scanNum == 4)
{
if (_printDebug == true)
_debugPort->println(F("processReadEvent: CREG"));
if (_registrationCallback != nullptr)
{
_registrationCallback((SARA_R5_registration_status_t)status, lac, ci, Act);
}
return true;
}
}
}
{ // URC: +CEREG
int status = 0;
unsigned int tac = 0, ci = 0, Act = 0;
char *searchPtr = strstr(event, SARA_R5_EPSREGISTRATION_STATUS_URC);
if (searchPtr != nullptr)
{
searchPtr += strlen(SARA_R5_EPSREGISTRATION_STATUS_URC); // Move searchPtr to first character - probably a space
while (*searchPtr == ' ') searchPtr++; // skip spaces
int scanNum = sscanf(searchPtr, "%d,\"%4x\",\"%4x\",%d", &status, &tac, &ci, &Act);
if (scanNum == 4)
{
if (_printDebug == true)
_debugPort->println(F("processReadEvent: CEREG"));
if (_epsRegistrationCallback != nullptr)
{
_epsRegistrationCallback((SARA_R5_registration_status_t)status, tac, ci, Act);
}
return true;
}
}
}
// NOTE: When adding new URC messages, remember to update pruneBacklog too!
return false;
}
// This is the original poll function.
// It is 'blocking' - it does not return when serial data is available until it receives a `\n`.
// ::bufferedPoll is the new improved version. It processes any data in the backlog and includes a timeout.
bool SARA_R5::poll(void)
{
if (_pollReentrant == true) // Check for reentry (i.e. poll has been called from inside a callback)
return false;
_pollReentrant = true;
int avail = 0;
char c = 0;
bool handled = false;
memset(_saraRXBuffer, 0, _RXBuffSize); // Clear _saraRXBuffer
if (hwAvailable() > 0) //hwAvailable can return -1 if the serial port is NULL
{
while (c != '\n') // Copy characters into _saraRXBuffer. Stop at the first new line
{
if (hwAvailable() > 0) //hwAvailable can return -1 if the serial port is NULL
{
c = readChar();
_saraRXBuffer[avail++] = c;
} else {
yield();
}
}
// Now search for all supported URC's
handled = processURCEvent(_saraRXBuffer);
if (handled && (true == _printAtDebug)) {
_debugAtPort->write(_saraRXBuffer, avail);
}
if ((handled == false) && (strlen(_saraRXBuffer) > 2))
{
if (_printDebug == true)
{
_debugPort->print(F("poll: "));
_debugPort->println(_saraRXBuffer);
}
}
else
{
}
}
_pollReentrant = false;
return handled;
}
void SARA_R5::setSocketListenCallback(void (*socketListenCallback)(int, IPAddress, unsigned int, int, IPAddress, unsigned int))
{
_socketListenCallback = socketListenCallback;
}
void SARA_R5::setSocketReadCallback(void (*socketReadCallback)(int, String))
{
_socketReadCallback = socketReadCallback;
}
void SARA_R5::setSocketReadCallbackPlus(void (*socketReadCallbackPlus)(int, const char *, int, IPAddress, int)) // socket, data, length, remoteAddress, remotePort
{
_socketReadCallbackPlus = socketReadCallbackPlus;
}
void SARA_R5::setSocketCloseCallback(void (*socketCloseCallback)(int))
{
_socketCloseCallback = socketCloseCallback;
}
void SARA_R5::setGpsReadCallback(void (*gpsRequestCallback)(ClockData time,
PositionData gps, SpeedData spd, unsigned long uncertainty))
{
_gpsRequestCallback = gpsRequestCallback;
}
void SARA_R5::setSIMstateReportCallback(void (*simStateReportCallback)(SARA_R5_sim_states_t state))
{
_simStateReportCallback = simStateReportCallback;
}
void SARA_R5::setPSDActionCallback(void (*psdActionRequestCallback)(int result, IPAddress ip))
{
_psdActionRequestCallback = psdActionRequestCallback;
}
void SARA_R5::setPingCallback(void (*pingRequestCallback)(int retry, int p_size, String remote_hostname, IPAddress ip, int ttl, long rtt))
{
_pingRequestCallback = pingRequestCallback;
}
void SARA_R5::setHTTPCommandCallback(void (*httpCommandRequestCallback)(int profile, int command, int result))
{
_httpCommandRequestCallback = httpCommandRequestCallback;
}
void SARA_R5::setMQTTCommandCallback(void (*mqttCommandRequestCallback)(int command, int result))
{
_mqttCommandRequestCallback = mqttCommandRequestCallback;
}
void SARA_R5::setFTPCommandCallback(void (*ftpCommandRequestCallback)(int command, int result))
{
_ftpCommandRequestCallback = ftpCommandRequestCallback;
}
SARA_R5_error_t SARA_R5::setRegistrationCallback(void (*registrationCallback)(SARA_R5_registration_status_t status, unsigned int lac, unsigned int ci, int Act))
{
_registrationCallback = registrationCallback;
char *command = sara_r5_calloc_char(strlen(SARA_R5_REGISTRATION_STATUS) + 3);
if (command == nullptr)
return SARA_R5_ERROR_OUT_OF_MEMORY;
sprintf(command, "%s=%d", SARA_R5_REGISTRATION_STATUS, 2/*enable URC with location*/);
SARA_R5_error_t err = sendCommandWithResponse(command, SARA_R5_RESPONSE_OK_OR_ERROR,
nullptr, SARA_R5_STANDARD_RESPONSE_TIMEOUT);
free(command);
return err;
}
SARA_R5_error_t SARA_R5::setEpsRegistrationCallback(void (*registrationCallback)(SARA_R5_registration_status_t status, unsigned int tac, unsigned int ci, int Act))
{
_epsRegistrationCallback = registrationCallback;
char *command = sara_r5_calloc_char(strlen(SARA_R5_EPSREGISTRATION_STATUS) + 3);
if (command == nullptr)
return SARA_R5_ERROR_OUT_OF_MEMORY;
sprintf(command, "%s=%d", SARA_R5_EPSREGISTRATION_STATUS, 2/*enable URC with location*/);
SARA_R5_error_t err = sendCommandWithResponse(command, SARA_R5_RESPONSE_OK_OR_ERROR,
nullptr, SARA_R5_STANDARD_RESPONSE_TIMEOUT);
free(command);
return err;
}
size_t SARA_R5::write(uint8_t c)
{
return hwWrite(c);
}
size_t SARA_R5::write(const char *str)
{
return hwPrint(str);
}
size_t SARA_R5::write(const char *buffer, size_t size)
{
return hwWriteData(buffer, size);
}
SARA_R5_error_t SARA_R5::at(void)
{
SARA_R5_error_t err;
err = sendCommandWithResponse(nullptr, SARA_R5_RESPONSE_OK, nullptr,
SARA_R5_STANDARD_RESPONSE_TIMEOUT);
return err;
}
SARA_R5_error_t SARA_R5::enableEcho(bool enable)
{
SARA_R5_error_t err;
char *command;
command = sara_r5_calloc_char(strlen(SARA_R5_COMMAND_ECHO) + 2);
if (command == nullptr)
return SARA_R5_ERROR_OUT_OF_MEMORY;
sprintf(command, "%s%d", SARA_R5_COMMAND_ECHO, enable ? 1 : 0);
err = sendCommandWithResponse(command, SARA_R5_RESPONSE_OK,
nullptr, SARA_R5_STANDARD_RESPONSE_TIMEOUT);
free(command);
return err;
}
String SARA_R5::getManufacturerID(void)
{
char *response;
char idResponse[16] = {0x00}; // E.g. u-blox
SARA_R5_error_t err;
response = sara_r5_calloc_char(minimumResponseAllocation);
err = sendCommandWithResponse(SARA_R5_COMMAND_MANU_ID,
SARA_R5_RESPONSE_OK_OR_ERROR, response, SARA_R5_STANDARD_RESPONSE_TIMEOUT);
if (err == SARA_R5_ERROR_SUCCESS)
{
if (sscanf(response, "\r\n%15s\r\n", idResponse) != 1)
{
memset(idResponse, 0, 16);
}
}
free(response);
return String(idResponse);
}
String SARA_R5::getModelID(void)
{
char *response;
char idResponse[32] = {0x00}; // E.g. SARA-R510M8Q
SARA_R5_error_t err;
response = sara_r5_calloc_char(minimumResponseAllocation);
err = sendCommandWithResponse(SARA_R5_COMMAND_MODEL_ID,
SARA_R5_RESPONSE_OK_OR_ERROR, response, SARA_R5_STANDARD_RESPONSE_TIMEOUT);
if (err == SARA_R5_ERROR_SUCCESS)
{
if (sscanf(response, "\r\n%31s\r\n", idResponse) != 1)
{
memset(idResponse, 0, 16);
}
}
free(response);
return String(idResponse);
}
String SARA_R5::getFirmwareVersion(void)
{
char *response;
char idResponse[16] = {0x00}; // E.g. 11.40
SARA_R5_error_t err;
response = sara_r5_calloc_char(minimumResponseAllocation);
err = sendCommandWithResponse(SARA_R5_COMMAND_FW_VER_ID,
SARA_R5_RESPONSE_OK_OR_ERROR, response, SARA_R5_STANDARD_RESPONSE_TIMEOUT);
if (err == SARA_R5_ERROR_SUCCESS)
{
if (sscanf(response, "\r\n%15s\r\n", idResponse) != 1)
{
memset(idResponse, 0, 16);
}
}
free(response);
return String(idResponse);
}
String SARA_R5::getSerialNo(void)
{
char *response;
char idResponse[32] = {0x00}; // E.g. 357520070120767