forked from nickn17/evDash
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SIM800L.cpp
958 lines (840 loc) · 29.2 KB
/
SIM800L.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
/********************************************************************************
* Arduino-SIM800L-driver *
* ---------------------- *
* Arduino driver for GSM/GPRS module SIMCom SIM800L to make HTTP/S connections *
* with GET and POST methods *
* Author: Olivier Staquet *
* Last version available on https://github.com/ostaquet/Arduino-SIM800L-driver *
********************************************************************************
* MIT License
*
* Copyright (c) 2019 Olivier Staquet
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* 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 WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*******************************************************************************/
#include "SIM800L.h"
/**
* AT commands required (const char in PROGMEM to save memory usage)
*/
const char AT_CMD_BASE[] PROGMEM = "AT"; // Basic AT command to check the link
const char AT_CMD_CSQ[] PROGMEM = "AT+CSQ"; // Check the signal strengh
const char AT_CMD_ATI[] PROGMEM = "ATI"; // Output version of the module
const char AT_CMD_GMR[] PROGMEM = "AT+GMR"; // Output version of the firmware
const char AT_CMD_SIM_CARD[] PROGMEM = "AT+CCID"; // Get Sim Card version
const char AT_CMD_CFUN_TEST[] PROGMEM = "AT+CFUN?"; // Check the current power mode
const char AT_CMD_CFUN0[] PROGMEM = "AT+CFUN=0"; // Switch minimum power mode
const char AT_CMD_CFUN1[] PROGMEM = "AT+CFUN=1"; // Switch normal power mode
const char AT_CMD_CFUN4[] PROGMEM = "AT+CFUN=4"; // Switch sleep power mode
const char AC_CMD_CSCLK0[] PROGMEM = "AT+CSCLK=0"; // AT+CSCLK=0 command
const char AC_CMD_CSCLK2[] PROGMEM = "AT+CSCLK=2"; // AT+CSCLK=2 command
const char AT_CMD_CREG_TEST[] PROGMEM = "AT+CREG?"; // Check the network registration status
const char AT_CMD_SAPBR_GPRS[] PROGMEM = "AT+SAPBR=3,1,\"Contype\",\"GPRS\""; // Configure the GPRS bearer
const char AT_CMD_SAPBR_APN[] PROGMEM = "AT+SAPBR=3,1,\"APN\","; // Configure the APN for the GPRS
const char AT_CMD_SAPBR1[] PROGMEM = "AT+SAPBR=1,1"; // Connect GPRS
const char AT_CMD_SAPBR2[] PROGMEM = "AT+SAPBR=2,1";
const char AT_CMD_SAPBR0[] PROGMEM = "AT+SAPBR=0,1"; // Disconnect GPRS
const char AT_CMD_HTTPINIT[] PROGMEM = "AT+HTTPINIT"; // Init HTTP connection
const char AT_CMD_HTTPPARA_CID[] PROGMEM = "AT+HTTPPARA=\"CID\",1"; // Connect HTTP through GPRS bearer
const char AT_CMD_HTTPPARA_URL[] PROGMEM = "AT+HTTPPARA=\"URL\","; // Define the URL to connect in HTTP
const char AT_CMD_HTTPPARA_USERDATA[] PROGMEM = "AT+HTTPPARA=\"USERDATA\","; // Define the header(s)
const char AT_CMD_HTTPPARA_CONTENT[] PROGMEM = "AT+HTTPPARA=\"CONTENT\","; // Define the content type for the HTTP POST
const char AT_CMD_HTTPSSL_Y[] PROGMEM = "AT+HTTPSSL=1"; // Enable SSL for HTTP connection
const char AT_CMD_HTTPSSL_N[] PROGMEM = "AT+HTTPSSL=0"; // Disable SSL for HTTP connection
const char AT_CMD_HTTPACTION0[] PROGMEM = "AT+HTTPACTION=0"; // Launch HTTP GET action
const char AT_CMD_HTTPACTION1[] PROGMEM = "AT+HTTPACTION=1"; // Launch HTTP POST action
const char AT_CMD_HTTPREAD[] PROGMEM = "AT+HTTPREAD"; // Start reading HTTP return data
const char AT_CMD_HTTPTERM[] PROGMEM = "AT+HTTPTERM"; // Terminate HTTP connection
const char AT_RSP_OK[] PROGMEM = "OK"; // Expected answer OK
const char AT_RSP_DOWNLOAD[] PROGMEM = "DOWNLOAD"; // Expected answer DOWNLOAD
const char AT_RSP_HTTPREAD[] PROGMEM = "+HTTPREAD: "; // Expected answer HTTPREAD
const char AT_RSP_SAPBR[] PROGMEM = "+SAPBR: 1,1,"; // Expected answer SAPBR:1,1
/**
* Constructor; Init the driver, communication with the module and shared
* buffer used by the driver (to avoid multiples allocation)
*/
SIM800L::SIM800L(Stream* _stream, uint8_t _pinRst, uint16_t _internalBufferSize, uint16_t _recvBufferSize, Stream* _debugStream) {
// Store local variables
stream = _stream;
enableDebug = _debugStream != NULL;
debugStream = _debugStream;
pinReset = _pinRst;
if(pinReset != RESET_PIN_NOT_USED) {
// Setup the reset pin and force a reset of the module
pinMode(pinReset, OUTPUT);
reset();
}
// Prepare internal buffers
if(enableDebug) {
debugStream->print(F("SIM800L : Prepare internal buffer of "));
debugStream->print(_internalBufferSize);
debugStream->println(F(" bytes"));
}
internalBufferSize = _internalBufferSize;
internalBuffer = (char*) malloc(internalBufferSize);
if(enableDebug) {
debugStream->print(F("SIM800L : Prepare reception buffer of "));
debugStream->print(_recvBufferSize);
debugStream->println(F(" bytes"));
}
recvBufferSize = _recvBufferSize;
recvBuffer = (char *) malloc(recvBufferSize);
}
/**
* Destructor; cleanup the memory allocated by the driver
*/
SIM800L::~SIM800L() {
free(internalBuffer);
free(recvBuffer);
}
/**
* Do HTTP/S POST to a specific URL
*/
uint16_t SIM800L::doPost(const char* url, const char* contentType, const char* payload, uint16_t clientWriteTimeoutMs, uint16_t serverReadTimeoutMs) {
return doPost(url, NULL, contentType, payload, clientWriteTimeoutMs , serverReadTimeoutMs);
}
/**
* Do HTTP/S POST to a specific URL with headers
*/
uint16_t SIM800L::doPost(const char* url, const char* headers, const char* contentType, const char* payload, uint16_t clientWriteTimeoutMs, uint16_t serverReadTimeoutMs) {
// Cleanup the receive buffer
initRecvBuffer();
dataSize = 0;
// Initiate HTTP/S session with the module
uint16_t initRC = initiateHTTP(url, headers);
if(initRC > 0) {
return initRC;
}
// Define the content type
sendCommand_P(AT_CMD_HTTPPARA_CONTENT, contentType);
if(!readResponseCheckAnswer_P(DEFAULT_TIMEOUT, AT_RSP_OK)) {
if(enableDebug) debugStream->println(F("SIM800L : doPost() - Unable to define the content type"));
return 702;
}
// Prepare to send the payload
char* tmpBuf = (char*)malloc(30);
sprintf(tmpBuf, "AT+HTTPDATA=%d,%d", strlen(payload), clientWriteTimeoutMs);
sendCommand(tmpBuf);
free(tmpBuf);
if(!readResponseCheckAnswer_P(DEFAULT_TIMEOUT, AT_RSP_DOWNLOAD)) {
if(enableDebug) debugStream->println(F("SIM800L : doPost() - Unable to send payload to module"));
return 707;
}
// Write the payload on the module
if(enableDebug) {
debugStream->print(F("SIM800L : doPost() - Payload to send : "));
debugStream->println(payload);
}
purgeSerial();
stream->write(payload);
stream->flush();
delay(500);
// Start HTTP POST action
sendCommand_P(AT_CMD_HTTPACTION1);
if(!readResponseCheckAnswer_P(DEFAULT_TIMEOUT, AT_RSP_OK)) {
if(enableDebug) debugStream->println(F("SIM800L : doPost() - Unable to initiate POST action"));
return 703;
}
// Wait answer from the server
if(!readResponse(serverReadTimeoutMs)) {
if(enableDebug) debugStream->println(F("SIM800L : doPost() - Server timeout"));
return 408;
}
// Extract status information
int16_t idxBase = strIndex(internalBuffer, "+HTTPACTION: 1,");
if(idxBase < 0) {
if(enableDebug) debugStream->println(F("SIM800L : doPost() - Invalid answer on HTTP POST"));
return 703;
}
// Get the HTTP return code
uint16_t httpRC = 0;
httpRC += (internalBuffer[idxBase + 15] - '0') * 100;
httpRC += (internalBuffer[idxBase + 16] - '0') * 10;
httpRC += (internalBuffer[idxBase + 17] - '0') * 1;
if(enableDebug) {
debugStream->print(F("SIM800L : doPost() - HTTP status "));
debugStream->println(httpRC);
}
if(httpRC == 200) {
// Get the size of the data to receive
dataSize = 0;
for(uint16_t i = 0; (internalBuffer[idxBase + 19 + i] - '0') >= 0 && (internalBuffer[idxBase + 19 + i] - '0') <= 9; i++) {
if(i != 0) {
dataSize = dataSize * 10;
}
dataSize += (internalBuffer[idxBase + 19 + i] - '0');
}
if(enableDebug) {
debugStream->print(F("SIM800L : doPost() - Data size received of "));
debugStream->print(dataSize);
debugStream->println(F(" bytes"));
}
// Ask for reading and detect the start of the reading...
sendCommand_P(AT_CMD_HTTPREAD);
if(!readResponseCheckAnswer_P(DEFAULT_TIMEOUT, AT_RSP_HTTPREAD, 2)) {
return 705;
}
// Read number of bytes defined in the dataSize
for(uint16_t i = 0; i < dataSize && i < recvBufferSize; i++) {
while(!stream->available());
if(stream->available()) {
// Load the next char
recvBuffer[i] = stream->read();
// If the character is CR or LF, ignore it (it's probably part of the module communication schema)
if((recvBuffer[i] == '\r') || (recvBuffer[i] == '\n')) {
i--;
}
}
}
if(recvBufferSize < dataSize) {
dataSize = recvBufferSize;
if(enableDebug) {
debugStream->println(F("SIM800L : doPost() - Buffer overflow while loading data from HTTP. Keep only first bytes..."));
}
}
// We are expecting a final OK
if(!readResponseCheckAnswer_P(DEFAULT_TIMEOUT, AT_RSP_OK)) {
if(enableDebug) debugStream->println(F("SIM800L : doPost() - Invalid end of data while reading HTTP result from the module"));
return 705;
}
if(enableDebug) {
debugStream->print(F("SIM800L : doPost() - Received from HTTP POST : "));
debugStream->println(recvBuffer);
}
}
// Terminate HTTP/S session
uint16_t termRC = terminateHTTP();
if(termRC > 0) {
return termRC;
}
return httpRC;
}
/**
* Do HTTP/S GET on a specific URL
*/
uint16_t SIM800L::doGet(const char* url, uint16_t serverReadTimeoutMs) {
return doGet(url, NULL, serverReadTimeoutMs);
}
/**
* Do HTTP/S GET on a specific URL with headers
*/
uint16_t SIM800L::doGet(const char* url, const char* headers, uint16_t serverReadTimeoutMs) {
// Cleanup the receive buffer
initRecvBuffer();
dataSize = 0;
// Initiate HTTP/S session
uint16_t initRC = initiateHTTP(url, headers);
if(initRC > 0) {
return initRC;
}
// Start HTTP GET action
sendCommand_P(AT_CMD_HTTPACTION0);
if(!readResponseCheckAnswer_P(DEFAULT_TIMEOUT, AT_RSP_OK)) {
if(enableDebug) debugStream->println(F("SIM800L : doGet() - Unable to initiate GET action"));
return 703;
}
// Wait answer from the server
if(!readResponse(serverReadTimeoutMs)) {
if(enableDebug) debugStream->println(F("SIM800L : doGet() - Server timeout"));
return 408;
}
// Extract status information
int16_t idxBase = strIndex(internalBuffer, "+HTTPACTION: 0,");
if(idxBase < 0) {
if(enableDebug) debugStream->println(F("SIM800L : doGet() - Invalid answer on HTTP GET"));
return 703;
}
// Get the HTTP return code
uint16_t httpRC = 0;
httpRC += (internalBuffer[idxBase + 15] - '0') * 100;
httpRC += (internalBuffer[idxBase + 16] - '0') * 10;
httpRC += (internalBuffer[idxBase + 17] - '0') * 1;
if(enableDebug) {
debugStream->print(F("SIM800L : doGet() - HTTP status "));
debugStream->println(httpRC);
}
if(httpRC == 200) {
// Get the size of the data to receive
dataSize = 0;
for(uint16_t i = 0; (internalBuffer[idxBase + 19 + i] - '0') >= 0 && (internalBuffer[idxBase + 19 + i] - '0') <= 9; i++) {
if(i != 0) {
dataSize = dataSize * 10;
}
dataSize += (internalBuffer[idxBase + 19 + i] - '0');
}
if(enableDebug) {
debugStream->print(F("SIM800L : doGet() - Data size received of "));
debugStream->print(dataSize);
debugStream->println(F(" bytes"));
}
// Ask for reading and detect the start of the reading...
sendCommand_P(AT_CMD_HTTPREAD);
if(!readResponseCheckAnswer_P(DEFAULT_TIMEOUT, AT_RSP_HTTPREAD, 2)) {
return 705;
}
// Read number of bytes defined in the dataSize
for(uint16_t i = 0; i < dataSize && i < recvBufferSize; i++) {
while(!stream->available());
if(stream->available()) {
// Load the next char
recvBuffer[i] = stream->read();
// If the character is CR or LF, ignore it (it's probably part of the module communication schema)
if((recvBuffer[i] == '\r') || (recvBuffer[i] == '\n')) {
i--;
}
}
}
if(recvBufferSize < dataSize) {
dataSize = recvBufferSize;
if(enableDebug) {
debugStream->println(F("SIM800L : doGet() - Buffer overflow while loading data from HTTP. Keep only first bytes..."));
}
}
// We are expecting a final OK
if(!readResponseCheckAnswer_P(DEFAULT_TIMEOUT, AT_RSP_OK)) {
if(enableDebug) debugStream->println(F("SIM800L : doGet() - Invalid end of data while reading HTTP result from the module"));
return 705;
}
if(enableDebug) {
debugStream->print(F("SIM800L : doGet() - Received from HTTP GET : "));
debugStream->println(recvBuffer);
}
}
// Terminate HTTP/S session
uint16_t termRC = terminateHTTP();
if(termRC > 0) {
return termRC;
}
return httpRC;
}
/**
* Meta method to initiate the HTTP/S session on the module
*/
uint16_t SIM800L::initiateHTTP(const char* url, const char* headers) {
// Init HTTP connection
sendCommand_P(AT_CMD_HTTPINIT);
if(!readResponseCheckAnswer_P(DEFAULT_TIMEOUT, AT_RSP_OK)) {
if(enableDebug) debugStream->println(F("SIM800L : initiateHTTP() - Unable to init HTTP"));
return 701;
}
// Use the GPRS bearer
sendCommand_P(AT_CMD_HTTPPARA_CID);
if(!readResponseCheckAnswer_P(DEFAULT_TIMEOUT, AT_RSP_OK)) {
if(enableDebug) debugStream->println(F("SIM800L : initiateHTTP() - Unable to define bearer"));
return 702;
}
// Define URL to look for
sendCommand_P(AT_CMD_HTTPPARA_URL, url);
if(!readResponseCheckAnswer_P(DEFAULT_TIMEOUT, AT_RSP_OK)) {
if(enableDebug) debugStream->println(F("SIM800L : initiateHTTP() - Unable to define the URL"));
return 702;
}
// Set Headers
if (headers != NULL) {
sendCommand_P(AT_CMD_HTTPPARA_USERDATA, headers);
if(!readResponseCheckAnswer_P(DEFAULT_TIMEOUT, AT_RSP_OK)) {
if(enableDebug) debugStream->println(F("SIM800L : initiateHTTP() - Unable to define Headers"));
return 702;
}
}
// Check if the firmware support HTTPSSL command
bool isSupportSSL = false;
char* version = getVersion();
int16_t rIdx = strIndex(version, "R");
if(rIdx > 0) {
uint8_t releaseInt = (version[rIdx + 1] - '0') * 10 + (version[rIdx + 2] - '0');
// The release should be greater or equals to 14 to support SSL stack
if(releaseInt >= 14) {
isSupportSSL = true;
if(enableDebug) debugStream->println(F("SIM800L : initiateHTTP() - Support of SSL enabled"));
} else {
isSupportSSL = false;
if(enableDebug) debugStream->println(F("SIM800L : initiateHTTP() - Support of SSL disabled (SIM800L firware below R14)"));
}
}
// Send HTTPSSL command only if the version is greater or equals to 14
if(isSupportSSL) {
// HTTP or HTTPS
if(strIndex(url, "https://") == 0) {
sendCommand_P(AT_CMD_HTTPSSL_Y);
if(!readResponseCheckAnswer_P(DEFAULT_TIMEOUT, AT_RSP_OK)) {
if(enableDebug) debugStream->println(F("SIM800L : initiateHTTP() - Unable to switch to HTTPS"));
return 702;
}
} else {
sendCommand_P(AT_CMD_HTTPSSL_N);
if(!readResponseCheckAnswer_P(DEFAULT_TIMEOUT, AT_RSP_OK)) {
if(enableDebug) debugStream->println(F("SIM800L : initiateHTTP() - Unable to switch to HTTP"));
return 702;
}
}
}
return 0;
}
/**
* Meta method to terminate the HTTP/S session on the module
*/
uint16_t SIM800L::terminateHTTP() {
// Close HTTP connection
sendCommand_P(AT_CMD_HTTPTERM);
if(!readResponseCheckAnswer_P(DEFAULT_TIMEOUT, AT_RSP_OK)) {
if(enableDebug) debugStream->println(F("SIM800L : terminateHTTP() - Unable to close HTTP session"));
return 706;
}
return 0;
}
/**
* Force a reset of the module
*/
void SIM800L::reset() {
if(pinReset != RESET_PIN_NOT_USED)
{
// Some logging
if(enableDebug) debugStream->println(F("SIM800L : Reset"));
// Reset the device
digitalWrite(pinReset, HIGH);
delay(500);
digitalWrite(pinReset, LOW);
delay(500);
digitalWrite(pinReset, HIGH);
delay(1000);
} else {
// Some logging
if(enableDebug) debugStream->println(F("SIM800L : Reset requested but reset pin undefined"));
if(enableDebug) debugStream->println(F("SIM800L : No reset"));
}
// Purge the serial
stream->flush();
while (stream->available()) {
stream->read();
}
}
/**
* Return the size of data received after the last successful HTTP connection
*/
uint16_t SIM800L::getDataSizeReceived() {
return dataSize;
}
/**
* Return the buffer of data received after the last successful HTTP connection
*/
char* SIM800L::getDataReceived() {
return recvBuffer;
}
/**
* Status function: Check if AT command works
*/
bool SIM800L::isReady() {
sendCommand_P(AT_CMD_BASE);
return readResponseCheckAnswer_P(DEFAULT_TIMEOUT, AT_RSP_OK);
}
/**
* Status function: Check the power mode
*/
PowerMode SIM800L::getPowerMode() {
sendCommand_P(AT_CMD_CFUN_TEST);
if(readResponse(DEFAULT_TIMEOUT)) {
// Check if there is an error
int16_t errIdx = strIndex(internalBuffer, "ERROR");
if(errIdx > 0) {
return POW_ERROR;
}
// Extract the value
int16_t idx = strIndex(internalBuffer, "+CFUN: ");
char value = internalBuffer[idx + 7];
// Prepare the clear output
switch(value) {
case '0' : return MINIMUM;
case '1' : return NORMAL;
case '4' : return SLEEP;
default : return POW_UNKNOWN;
}
}
return POW_ERROR;
}
/**
* Status function: Get version of the module
*/
char* SIM800L::getVersion() {
sendCommand_P(AT_CMD_ATI);
if(readResponse(DEFAULT_TIMEOUT)) {
// Extract the value
int16_t idx = strIndex(internalBuffer, "SIM");
int16_t idxEnd = strIndex(internalBuffer, "\r", idx+1);
// Store it on the recv buffer (not used at the moment)
initRecvBuffer();
for(uint16_t i = 0; i < idxEnd - idx; i++) {
recvBuffer[i] = internalBuffer[idx + i];
}
return getDataReceived();
} else {
return NULL;
}
}
/**
* Status function: Get firmware version
*/
char* SIM800L::getFirmware() {
sendCommand_P(AT_CMD_GMR);
if(readResponse(DEFAULT_TIMEOUT)) {
// Extract the value
int16_t idx = strIndex(internalBuffer, "AT+GMR") + 9;
int16_t idxEnd = strIndex(internalBuffer, "\r", idx+1);
// Store it on the recv buffer (not used at the moment)
initRecvBuffer();
for(uint16_t i = 0; i < idxEnd - idx; i++) {
recvBuffer[i] = internalBuffer[idx + i];
}
return getDataReceived();
} else {
return NULL;
}
}
/**
* Status function: Requests the simcard number
*/
char* SIM800L::getSimCardNumber() {
sendCommand_P(AT_CMD_SIM_CARD);
if(readResponse(DEFAULT_TIMEOUT)) {
int16_t idx = strIndex(internalBuffer, "AT+CCID") + 10;
int16_t idxEnd = strIndex(internalBuffer, "\r", idx+1);
// Store it on the recv buffer (not used at the moment)
initRecvBuffer();
for(uint16_t i = 0; i < idxEnd - idx; i++) {
recvBuffer[i] = internalBuffer[idx + i];
}
return getDataReceived();
} else {
return NULL;
}
}
/**
* Status function: Check if the module is registered on the network
*/
NetworkRegistration SIM800L::getRegistrationStatus() {
sendCommand_P(AT_CMD_CREG_TEST);
if(readResponse(DEFAULT_TIMEOUT)) {
// Check if there is an error
int16_t errIdx = strIndex(internalBuffer, "ERROR");
if(errIdx > 0) {
return NET_ERROR;
}
// Extract the value
int16_t idx = strIndex(internalBuffer, "+CREG: ");
char value = internalBuffer[idx + 9];
// Prepare the clear output
switch(value) {
case '0' : return NOT_REGISTERED;
case '1' : return REGISTERED_HOME;
case '2' : return SEARCHING;
case '3' : return DENIED;
case '5' : return REGISTERED_ROAMING;
default : return NET_UNKNOWN;
}
}
return NET_ERROR;
}
/**
* Setup the GPRS connectivity
* As input, give the APN string of the operator
*/
bool SIM800L::setupGPRS(const char* apn) {
// Prepare the GPRS connection as the bearer
sendCommand_P(AT_CMD_SAPBR_GPRS);
if(!readResponseCheckAnswer_P(20000, AT_RSP_OK)) {
return false;
}
// Set the config of the bearer with the APN
sendCommand_P(AT_CMD_SAPBR_APN, apn);
return readResponseCheckAnswer_P(20000, AT_RSP_OK);
}
/**
* Open the GPRS connectivity
*/
bool SIM800L::connectGPRS() {
sendCommand_P(AT_CMD_SAPBR1);
// Timout is max 85 seconds according to SIM800 specifications
// We will wait for 65s to be within uint16_t
return readResponseCheckAnswer_P(65000, AT_RSP_OK);
}
/**
* Check if GPRS is connected
*/
bool SIM800L::isConnectedGPRS() {
sendCommand_P(AT_CMD_SAPBR2);
return readResponseCheckAnswer_P(65000, AT_RSP_SAPBR);
}
/**
* Close the GPRS connectivity
*/
bool SIM800L::disconnectGPRS() {
sendCommand_P(AT_CMD_SAPBR0);
// Timout is max 65 seconds according to SIM800 specifications
return readResponseCheckAnswer_P(65000, AT_RSP_OK);
}
/**
* Define the power mode
* Available : MINIMUM, NORMAL, SLEEP
* Return true is the mode is correctly switched
*/
bool SIM800L::setPowerMode(PowerMode powerMode) {
// Check if the power mode requested is not ERROR or UNKNOWN
if(powerMode == POW_ERROR || powerMode == POW_UNKNOWN) {
return false;
}
// Check the current power mode
PowerMode currentPowerMode = getPowerMode();
// If the current power mode is undefined, abord
if(currentPowerMode == POW_ERROR || currentPowerMode == POW_UNKNOWN) {
return false;
}
// If the current power mode is the same that the requested power mode, say it's OK
if(currentPowerMode == powerMode) {
return true;
}
// If SLEEP or MINIMUM, only NORMAL is allowed
if((currentPowerMode == SLEEP || currentPowerMode == MINIMUM) && (powerMode != NORMAL)) {
return false;
}
// Send the command
char value;
switch(powerMode) {
case MINIMUM :
sendCommand_P(AT_CMD_CFUN0);
break;
case SLEEP :
sendCommand_P(AT_CMD_CFUN4);
break;
case NORMAL :
default :
sendCommand_P(AT_CMD_CFUN1);
}
// Read but don't care about the result
purgeSerial();
// Check the current power mode
currentPowerMode = getPowerMode();
// If the current power mode is the same that the requested power mode, say it's OK
return currentPowerMode == powerMode;
}
void SIM800L::exitSleepMode() {
sendCommand_P(AC_CMD_CSCLK0);
purgeSerial();
}
void SIM800L::enterSleepMode() {
sendCommand_P(AC_CMD_CSCLK2);
purgeSerial();
}
/**
* Status function: Check the strengh of the signal
*/
uint8_t SIM800L::getSignal() {
sendCommand_P(AT_CMD_CSQ);
if(readResponse(DEFAULT_TIMEOUT)) {
int16_t idxBase = strIndex(internalBuffer, "AT+CSQ");
if(idxBase != 0) {
return 0;
}
int16_t idxEnd = strIndex(internalBuffer, ",", idxBase);
uint8_t value = internalBuffer[idxEnd - 1] - '0';
if(internalBuffer[idxEnd - 2] != ' ') {
value += (internalBuffer[idxEnd - 2] - '0') * 10;
}
if(value > 31) {
return 0;
}
return value;
}
return 0;
}
/*****************************************************************************************
* HELPERS
*****************************************************************************************/
/**
* Find string "findStr" in another string "str"
* Returns true if found, false elsewhere
*/
int16_t SIM800L::strIndex(const char* str, const char* findStr, uint16_t startIdx) {
int16_t firstIndex = -1;
int16_t sizeMatch = 0;
for(int16_t i = startIdx; i < strlen(str); i++) {
if(sizeMatch >= strlen(findStr)) {
break;
}
if(str[i] == findStr[sizeMatch]) {
if(firstIndex < 0) {
firstIndex = i;
}
sizeMatch++;
} else {
firstIndex = -1;
sizeMatch = 0;
}
}
if(sizeMatch >= strlen(findStr)) {
return firstIndex;
} else {
return -1;
}
}
/**
* Init internal buffer
*/
void SIM800L::initInternalBuffer() {
for(uint16_t i = 0; i < internalBufferSize; i++) {
internalBuffer[i] = '\0';
}
}
/**
* Init recv buffer
*/
void SIM800L::initRecvBuffer() {
// Cleanup the receive buffer
for(uint16_t i = 0; i < recvBufferSize; i++) {
recvBuffer[i] = 0;
}
}
/*****************************************************************************************
* LOW LEVEL FUNCTIONS TO COMMUNICATE WITH THE SIM800L MODULE
*****************************************************************************************/
/**
* Send AT command to the module
*/
void SIM800L::sendCommand(const char* command) {
if(enableDebug) {
debugStream->print(F("SIM800L : Send \""));
debugStream->print(command);
debugStream->println(F("\""));
}
purgeSerial();
stream->write(command);
stream->write("\r\n");
purgeSerial();
}
/**
* Send AT command coming from the PROGMEM
*/
void SIM800L::sendCommand_P(const char* command) {
char cmdBuff[32];
strcpy_P(cmdBuff, command);
sendCommand(cmdBuff);
}
/**
* Send AT command to the module with a parameter
*/
void SIM800L::sendCommand(const char* command, const char* parameter) {
if(enableDebug) {
debugStream->print(F("SIM800L : Send \""));
debugStream->print(command);
debugStream->print(F("\""));
debugStream->print(parameter);
debugStream->print(F("\""));
debugStream->println(F("\""));
}
purgeSerial();
stream->write(command);
stream->write("\"");
stream->write(parameter);
stream->write("\"");
stream->write("\r\n");
purgeSerial();
}
/**
* Send AT command coming from the PROGMEM with a parameter
*/
void SIM800L::sendCommand_P(const char* command, const char* parameter) {
char cmdBuff[32];
strcpy_P(cmdBuff, command);
sendCommand(cmdBuff, parameter);
}
/**
* Purge the serial data
*/
void SIM800L::purgeSerial() {
stream->flush();
while (stream->available()) {
stream->read();
}
stream->flush();
}
/**
* Read from module and expect a specific answer (timeout in millisec)
*/
bool SIM800L::readResponseCheckAnswer_P(uint16_t timeout, const char* expectedAnswer, uint8_t crlfToWait) {
if(readResponse(timeout, crlfToWait)) {
// Prepare the local expected answer
char rspBuff[16];
strcpy_P(rspBuff, expectedAnswer);
// Check if it's the expected answer
int16_t idx = strIndex(internalBuffer, rspBuff);
if(idx > 0) {
return true;
}
}
return false;
}
/**
* Read from the module for a specific number of CRLF
* True if we have some data
*/
bool SIM800L::readResponse(uint16_t timeout, uint8_t crlfToWait) {
uint16_t currentSizeResponse = 0;
bool seenCR = false;
uint8_t countCRLF = 0;
// First of all, cleanup the buffer
initInternalBuffer();
uint32_t timerStart = millis();
while(1) {
// While there is data available on the buffer, read it until the max size of the response
if(stream->available()) {
// Load the next char
internalBuffer[currentSizeResponse] = stream->read();
// Detect end of transmission (CRLF)
if(internalBuffer[currentSizeResponse] == '\r') {
seenCR = true;
} else if (internalBuffer[currentSizeResponse] == '\n' && seenCR) {
countCRLF++;
if(countCRLF == crlfToWait) {
if(enableDebug) debugStream->println(F("SIM800L : End of transmission"));
break;
}
} else {
seenCR = false;
}
// Prepare for next read
currentSizeResponse++;
// Avoid buffer overflow
if(currentSizeResponse == internalBufferSize) {
if(enableDebug) debugStream->println(F("SIM800L : Received maximum buffer size"));
break;
}
}
// If timeout, abord the reading
if(millis() - timerStart > timeout) {
if(enableDebug) debugStream->println(F("SIM800L : Receive timeout"));
// Timeout, return false to parent function
return false;
}
}
if(enableDebug) {
debugStream->print(F("SIM800L : Receive \""));
debugStream->print(internalBuffer);
debugStream->println(F("\""));
}
// If we are here, it's OK ;-)
return true;
}