forked from ARMmbed/mbed-os
-
Notifications
You must be signed in to change notification settings - Fork 19
/
ATHandler.cpp
1582 lines (1366 loc) · 39.9 KB
/
ATHandler.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
/*
* Copyright (c) 2017, Arm Limited and affiliates.
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <ctype.h>
#include <stdio.h>
#include <limits.h>
#include <errno.h>
#include "ATHandler.h"
#include "mbed_poll.h"
#include "FileHandle.h"
#include "mbed_debug.h"
#include "rtos/ThisThread.h"
#include "rtos/Kernel.h"
#include "CellularUtil.h"
#include "SingletonPtr.h"
#include "ScopedLock.h"
using namespace mbed;
using namespace events;
using namespace mbed_cellular_util;
using namespace std::chrono_literals;
#include "CellularLog.h"
#if defined(MBED_CONF_CELLULAR_DEBUG_AT) && (MBED_CONF_CELLULAR_DEBUG_AT) && defined(MBED_CONF_MBED_TRACE_ENABLE) && MBED_CONF_MBED_TRACE_ENABLE
#define DEBUG_AT_ENABLED 1
#else
#define DEBUG_AT_ENABLED 0
#endif
// URCs should be handled fast, if you add debug traces within URC processing then you also need to increase this time
#define PROCESS_URC_TIME 20ms
// Suppress logging of very big packet payloads, maxlen is approximate due to write/read are cached
#define DEBUG_MAXLEN 60
#define DEBUG_END_MARK "..\r"
const char *mbed::OK = "OK\r\n";
const uint8_t OK_LENGTH = 4;
const char *mbed::CRLF = "\r\n";
const uint8_t CRLF_LENGTH = 2;
const char *CME_ERROR = "+CME ERROR:";
const uint8_t CME_ERROR_LENGTH = 11;
const char *CMS_ERROR = "+CMS ERROR:";
const uint8_t CMS_ERROR_LENGTH = 11;
const char *ERROR_ = "ERROR\r\n";
const uint8_t ERROR_LENGTH = 7;
const uint8_t MAX_RESP_LENGTH = CMS_ERROR_LENGTH;
const char DEFAULT_DELIMITER = ',';
static const uint8_t map_3gpp_errors[][2] = {
{ 103, 3 }, { 106, 6 }, { 107, 7 }, { 108, 8 }, { 111, 11 }, { 112, 12 }, { 113, 13 }, { 114, 14 },
{ 115, 15 }, { 122, 22 }, { 125, 25 }, { 172, 95 }, { 173, 96 }, { 174, 97 }, { 175, 99 }, { 176, 111 },
{ 177, 8 }, { 126, 26 }, { 127, 27 }, { 128, 28 }, { 129, 29 }, { 130, 30 }, { 131, 31 }, { 132, 32 },
{ 133, 33 }, { 134, 34 }, { 140, 40 }, { 141, 41 }, { 142, 42 }, { 143, 43 }, { 144, 44 }, { 145, 45 },
{ 146, 46 }, { 178, 65 }, { 179, 66 }, { 180, 48 }, { 181, 83 }, { 171, 49 },
};
ATHandler::ATHandler(FileHandle *fh, EventQueue &queue, uint32_t timeout, const char *output_delimiter, uint16_t send_delay) :
ATHandler(fh, queue, mbed::chrono::milliseconds_u32(timeout), output_delimiter, std::chrono::duration<uint16_t, std::milli>(send_delay))
{
}
ATHandler::ATHandler(FileHandle *fh, EventQueue &queue, mbed::chrono::milliseconds_u32 timeout, const char *output_delimiter, std::chrono::duration<uint16_t, std::milli> send_delay) :
#if defined AT_HANDLER_MUTEX && defined MBED_CONF_RTOS_PRESENT
_oobCv(_fileHandleMutex),
#endif
_fileHandle(fh),
_queue(queue),
_last_err(NSAPI_ERROR_OK),
_last_3gpp_error(0),
_oob_string_max_length(0),
_oobs(NULL),
_at_timeout(timeout),
_previous_at_timeout(timeout),
_at_send_delay(send_delay),
_last_response_stop(0s),
_ref_count(1),
_is_fh_usable(false),
_stop_tag(NULL),
_delimiter(DEFAULT_DELIMITER),
_prefix_matched(false),
_urc_matched(false),
_error_found(false),
_max_resp_length(MAX_RESP_LENGTH),
_debug_on(DEBUG_AT_ENABLED),
_cmd_start(false),
_use_delimiter(true),
_start_time(),
_event_id(0)
{
clear_error();
if (output_delimiter) {
_output_delimiter = new char[strlen(output_delimiter) + 1];
memcpy(_output_delimiter, output_delimiter, strlen(output_delimiter) + 1);
} else {
_output_delimiter = NULL;
}
reset_buffer();
memset(_recv_buff, 0, sizeof(_recv_buff));
memset(_info_resp_prefix, 0, sizeof(_info_resp_prefix));
_current_scope = NotSet;
set_tag(&_resp_stop, OK);
set_tag(&_info_stop, CRLF);
set_tag(&_elem_stop, ")");
set_is_filehandle_usable(true);
}
ATHandler::~ATHandler()
{
ScopedLock <ATHandler> lock(*this);
set_is_filehandle_usable(false);
_fileHandle = NULL;
if (_event_id != 0 && _queue.cancel(_event_id)) {
_event_id = 0;
}
while (_event_id != 0) {
#if defined AT_HANDLER_MUTEX && defined MBED_CONF_RTOS_PRESENT
_oobCv.wait();
#else
// Cancel will always work in a single threaded environment
MBED_ASSERT(false);
#endif // AT_HANDLER_MUTEX
}
while (_oobs) {
struct oob_t *oob = _oobs;
_oobs = oob->next;
delete oob;
}
if (_output_delimiter) {
delete [] _output_delimiter;
}
}
bool ATHandler::ok_to_proceed()
{
if (_last_err != NSAPI_ERROR_OK) {
return false;
}
if (!_is_fh_usable) {
_last_err = NSAPI_ERROR_BUSY;
return false;
}
return true;
}
void ATHandler::set_debug(bool debug_on)
{
_debug_on = debug_on;
}
bool ATHandler::get_debug() const
{
return _debug_on;
}
FileHandle *ATHandler::get_file_handle()
{
return _fileHandle;
}
void ATHandler::set_is_filehandle_usable(bool usable)
{
ScopedLock<ATHandler> lock(*this);
if (_fileHandle) {
if (usable) {
_fileHandle->set_blocking(false);
_fileHandle->sigio(Callback<void()>(this, &ATHandler::event));
} else {
_fileHandle->set_blocking(true); // set back to default state
_fileHandle->sigio(nullptr);
}
_is_fh_usable = usable;
}
}
void ATHandler::set_urc_handler(const char *prefix, Callback<void()> callback)
{
if (!callback) {
remove_urc_handler(prefix);
return;
}
if (find_urc_handler(prefix)) {
tr_warn("URC already added with prefix: %s", prefix);
return;
}
struct oob_t *oob = new struct oob_t;
size_t prefix_len = strlen(prefix);
if (prefix_len > _oob_string_max_length) {
_oob_string_max_length = prefix_len;
if (_oob_string_max_length > _max_resp_length) {
_max_resp_length = _oob_string_max_length;
}
}
oob->prefix = prefix;
oob->prefix_len = prefix_len;
oob->cb = callback;
oob->next = _oobs;
_oobs = oob;
}
void ATHandler::remove_urc_handler(const char *prefix)
{
struct oob_t *current = _oobs;
struct oob_t *prev = NULL;
while (current) {
if (strcmp(prefix, current->prefix) == 0) {
if (prev) {
prev->next = current->next;
} else {
_oobs = current->next;
}
delete current;
break;
}
prev = current;
current = prev->next;
}
}
bool ATHandler::find_urc_handler(const char *prefix)
{
struct oob_t *oob = _oobs;
while (oob) {
if (strcmp(prefix, oob->prefix) == 0) {
return true;
}
oob = oob->next;
}
return false;
}
void ATHandler::event()
{
if (_event_id == 0) {
_event_id = _queue.call(callback(this, &ATHandler::process_oob));
}
}
void ATHandler::lock()
{
#if defined AT_HANDLER_MUTEX && defined MBED_CONF_RTOS_PRESENT
_fileHandleMutex.lock();
#endif
clear_error();
_start_time = rtos::Kernel::Clock::now();
}
void ATHandler::unlock()
{
if (_is_fh_usable && (_fileHandle->readable() || (_recv_pos < _recv_len))) {
_event_id = _queue.call(callback(this, &ATHandler::process_oob));
}
#if defined AT_HANDLER_MUTEX && defined MBED_CONF_RTOS_PRESENT
_fileHandleMutex.unlock();
#endif
}
nsapi_error_t ATHandler::unlock_return_error()
{
nsapi_error_t err = _last_err;
unlock();
return err;
}
void ATHandler::set_at_timeout(uint32_t timeout_milliseconds, bool default_timeout)
{
set_at_timeout(mbed::chrono::milliseconds_u32(timeout_milliseconds), default_timeout);
}
void ATHandler::set_at_timeout(mbed::chrono::milliseconds_u32 timeout, bool default_timeout)
{
lock();
if (default_timeout) {
_previous_at_timeout = timeout;
_at_timeout = timeout;
} else if (timeout != _at_timeout) {
_previous_at_timeout = _at_timeout;
_at_timeout = timeout;
}
unlock();
}
void ATHandler::restore_at_timeout()
{
lock();
if (_previous_at_timeout != _at_timeout) {
_at_timeout = _previous_at_timeout;
}
unlock();
}
void ATHandler::process_oob()
{
ScopedLock<ATHandler> lock(*this);
if (!_is_fh_usable) {
tr_debug("process_oob, filehandle is not usable, return...");
_event_id = 0;
#if defined AT_HANDLER_MUTEX && defined MBED_CONF_RTOS_PRESENT
_oobCv.notify_all();
#endif
return;
}
if (_fileHandle->readable() || (_recv_pos < _recv_len)) {
tr_debug("AT OoB readable %d, len %u", _fileHandle->readable(), _recv_len - _recv_pos);
_current_scope = NotSet;
auto timeout = _at_timeout;
while (true) {
_at_timeout = timeout;
if (match_urc()) {
if (!(_fileHandle->readable() || (_recv_pos < _recv_len))) {
break; // we have nothing to read anymore
}
} else if (mem_str(_recv_buff, _recv_len, CRLF, CRLF_LENGTH)) { // If no match found, look for CRLF and consume everything up to CRLF
_at_timeout = PROCESS_URC_TIME;
consume_to_tag(CRLF, true);
} else {
_at_timeout = PROCESS_URC_TIME;
if (!fill_buffer()) {
reset_buffer(); // consume anything that could not be handled
break;
}
}
_start_time = rtos::Kernel::Clock::now();
}
_at_timeout = timeout;
tr_debug("AT OoB done");
}
_event_id = 0;
#if defined AT_HANDLER_MUTEX && defined MBED_CONF_RTOS_PRESENT
_oobCv.notify_all();
#endif
}
void ATHandler::reset_buffer()
{
_recv_pos = 0;
_recv_len = 0;
}
void ATHandler::rewind_buffer()
{
if (_recv_pos > 0 && _recv_len >= _recv_pos) {
_recv_len -= _recv_pos;
// move what is not read to beginning of buffer
memmove(_recv_buff, _recv_buff + _recv_pos, _recv_len);
_recv_pos = 0;
}
}
int ATHandler::poll_timeout(bool wait_for_timeout)
{
std::chrono::duration<int, std::milli> timeout;
if (wait_for_timeout) {
auto now = rtos::Kernel::Clock::now();
if (now >= _start_time + _at_timeout) {
timeout = 0s;
} else if (_start_time + _at_timeout - now > timeout.max()) {
timeout = timeout.max();
} else {
timeout = _start_time + _at_timeout - now;
}
} else {
timeout = 0s;
}
return timeout.count();
}
bool ATHandler::fill_buffer(bool wait_for_timeout)
{
// Reset buffer when full
if (sizeof(_recv_buff) == _recv_len) {
tr_warn("AT overflow");
debug_print(_recv_buff, _recv_len, AT_ERR);
reset_buffer();
}
pollfh fhs;
fhs.fh = _fileHandle;
fhs.events = POLLIN;
int count = poll(&fhs, 1, poll_timeout(wait_for_timeout));
if (count > 0 && (fhs.revents & POLLIN)) {
ssize_t len = _fileHandle->read(_recv_buff + _recv_len, sizeof(_recv_buff) - _recv_len);
if (len > 0) {
debug_print(_recv_buff + _recv_len, len, AT_RX);
_recv_len += len;
return true;
}
}
return false;
}
int ATHandler::get_char()
{
if (_recv_pos == _recv_len) {
reset_buffer(); // try to read as much as possible
if (!fill_buffer()) {
tr_warn("AT timeout");
set_error(NSAPI_ERROR_DEVICE_ERROR);
return -1; // timeout to read
}
}
return _recv_buff[_recv_pos++];
}
void ATHandler::skip_param(uint32_t count)
{
if (!ok_to_proceed() || !_stop_tag || _stop_tag->found) {
return;
}
for (uint32_t i = 0; (i < count && !_stop_tag->found); i++) {
size_t match_pos = 0;
while (true) {
int c = get_char();
if (c == -1) {
set_error(NSAPI_ERROR_DEVICE_ERROR);
return;
} else if (c == _delimiter) {
break;
} else if (_stop_tag->len && c == _stop_tag->tag[match_pos]) {
match_pos++;
if (match_pos == _stop_tag->len) {
_stop_tag->found = true;
break;
}
} else if (match_pos) {
match_pos = 0;
if (c == _stop_tag->tag[match_pos]) {
match_pos++;
}
}
}
}
return;
}
void ATHandler::skip_param(ssize_t len, uint32_t count)
{
if (!ok_to_proceed() || !_stop_tag || _stop_tag->found) {
return;
}
for (uint32_t i = 0; i < count; i++) {
ssize_t read_len = 0;
while (read_len < len) {
int c = get_char();
if (c == -1) {
set_error(NSAPI_ERROR_DEVICE_ERROR);
return;
}
read_len++;
}
}
return;
}
ssize_t ATHandler::read_bytes(uint8_t *buf, size_t len)
{
if (!ok_to_proceed()) {
return -1;
}
bool debug_on = _debug_on;
bool disabled_debug = false;
if (len > DEBUG_MAXLEN) {
_debug_on = false;
disabled_debug = true;
}
size_t read_len = 0;
for (; read_len < len; read_len++) {
int c = get_char();
if (c == -1) {
set_error(NSAPI_ERROR_DEVICE_ERROR);
_debug_on = debug_on;
return -1;
}
buf[read_len] = c;
}
#if DEBUG_AT_ENABLED
if (debug_on && disabled_debug) {
tr_info("read_bytes trace suppressed (total length %d)", read_len);
}
#else
(void)disabled_debug; // Remove compiler warning
#endif
_debug_on = debug_on;
return read_len;
}
ssize_t ATHandler::read_string(char *buf, size_t size, bool read_even_stop_tag)
{
if (!ok_to_proceed() || !_stop_tag || (_stop_tag->found && read_even_stop_tag == false)) {
return -1;
}
unsigned int len = 0;
size_t match_pos = 0;
bool delimiter_found = false;
bool inside_quotes = false;
for (; len < (size - 1 + match_pos); len++) {
int c = get_char();
if (c == -1) {
set_error(NSAPI_ERROR_DEVICE_ERROR);
return -1;
} else if (c == _delimiter && !inside_quotes) {
buf[len] = '\0';
delimiter_found = true;
break;
} else if (c == '\"') {
match_pos = 0;
len--;
inside_quotes = !inside_quotes;
continue;
} else if (_stop_tag->len && c == _stop_tag->tag[match_pos]) {
match_pos++;
if (match_pos == _stop_tag->len) {
_stop_tag->found = true;
// remove tag from string if it was matched
len -= (_stop_tag->len - 1);
buf[len] = '\0';
break;
}
} else if (match_pos) {
match_pos = 0;
if (c == _stop_tag->tag[match_pos]) {
match_pos++;
}
}
buf[len] = c;
}
if (len && (len == size - 1 + match_pos)) {
buf[len] = '\0';
}
// Consume to delimiter or stop_tag
if (!delimiter_found && !_stop_tag->found) {
match_pos = 0;
while (1) {
int c = get_char();
if (c == -1) {
set_error(NSAPI_ERROR_DEVICE_ERROR);
break;
} else if (c == _delimiter) {
break;
} else if (_stop_tag->len && c == _stop_tag->tag[match_pos]) {
match_pos++;
if (match_pos == _stop_tag->len) {
_stop_tag->found = true;
break;
}
}
}
}
return len;
}
ssize_t ATHandler::read_hex_string(char *buf, size_t size)
{
if (!ok_to_proceed() || !_stop_tag || _stop_tag->found) {
return -1;
}
size_t match_pos = 0;
consume_char('\"');
if (_last_err) {
return -1;
}
size_t read_idx = 0;
size_t buf_idx = 0;
char hexbuf[2];
bool debug_on = _debug_on;
bool disabled_debug = false;
if (size > DEBUG_MAXLEN) {
_debug_on = false;
disabled_debug = true;
}
for (; read_idx < size * 2 + match_pos; read_idx++) {
int c = get_char();
if (match_pos) {
buf_idx++;
} else {
buf_idx = read_idx / 2;
}
if (c == -1) {
set_error(NSAPI_ERROR_DEVICE_ERROR);
return -1;
}
if (c == _delimiter) {
break;
} else if (c == '\"') {
match_pos = 0;
read_idx--;
continue;
} else if (_stop_tag->len && c == _stop_tag->tag[match_pos]) {
match_pos++;
if (match_pos == _stop_tag->len) {
_stop_tag->found = true;
// remove tag from string if it was matched
buf_idx -= (_stop_tag->len - 1);
break;
}
} else if (match_pos) {
match_pos = 0;
if (c == _stop_tag->tag[match_pos]) {
match_pos++;
}
}
if (match_pos) {
buf[buf_idx] = c;
} else {
hexbuf[read_idx % 2] = c;
if (read_idx % 2 == 1) {
hex_to_char(hexbuf, *(buf + buf_idx));
}
}
}
if (read_idx && (read_idx == size * 2 + match_pos)) {
buf_idx++;
}
#if DEBUG_AT_ENABLED
if (debug_on && disabled_debug) {
tr_info("read_hex_string trace suppressed (total length %d)", buf_idx);
}
#else
(void)disabled_debug; // Remove compiler warning
#endif
_debug_on = debug_on;
return buf_idx;
}
int32_t ATHandler::read_int()
{
if (!ok_to_proceed() || !_stop_tag || _stop_tag->found) {
return -1;
}
char buff[MBED_CONF_CELLULAR_AT_HANDLER_BUFFER_SIZE];
if (read_string(buff, sizeof(buff)) == 0) {
return -1;
}
errno = 0;
long result = std::strtol(buff, NULL, 10);
if ((result == LONG_MIN || result == LONG_MAX) && errno == ERANGE) {
return -1; // overflow/underflow
}
if (result < 0) {
return -1; // negative values are unsupported
}
if (*buff == '\0') {
return -1; // empty string
}
return (int32_t) result;
}
void ATHandler::set_delimiter(char delimiter)
{
_delimiter = delimiter;
}
void ATHandler::set_default_delimiter()
{
_delimiter = DEFAULT_DELIMITER;
}
void ATHandler::use_delimiter(bool use_delimiter)
{
_use_delimiter = use_delimiter;
}
void ATHandler::set_tag(tag_t *tag_dst, const char *tag_seq)
{
if (tag_seq) {
size_t tag_len = strlen(tag_seq);
memcpy(tag_dst->tag, tag_seq, tag_len);
tag_dst->tag[tag_len] = '\0';
tag_dst->len = tag_len;
tag_dst->found = false;
} else {
_stop_tag = NULL;
}
}
void ATHandler::set_stop_tag(const char *stop_tag_seq)
{
if (_last_err || !_stop_tag) {
return;
}
set_tag(_stop_tag, stop_tag_seq);
}
void ATHandler::set_scope(ScopeType scope_type)
{
if (_current_scope != scope_type) {
_current_scope = scope_type;
switch (_current_scope) {
case RespType:
_stop_tag = &_resp_stop;
_stop_tag->found = false;
break;
case InfoType:
_stop_tag = &_info_stop;
_stop_tag->found = false;
consume_char(' ');
break;
case ElemType:
_stop_tag = &_elem_stop;
_stop_tag->found = false;
break;
case NotSet:
_stop_tag = NULL;
return;
default:
break;
}
}
}
// should match from recv_pos?
bool ATHandler::match(const char *str, size_t size)
{
rewind_buffer();
if ((_recv_len - _recv_pos) < size) {
return false;
}
if (str && memcmp(_recv_buff + _recv_pos, str, size) == 0) {
// consume matching part
_recv_pos += size;
return true;
}
return false;
}
bool ATHandler::match_urc()
{
rewind_buffer();
size_t prefix_len = 0;
for (struct oob_t *oob = _oobs; oob; oob = oob->next) {
prefix_len = oob->prefix_len;
if (_recv_len >= prefix_len) {
if (match(oob->prefix, prefix_len)) {
set_scope(InfoType);
if (oob->cb) {
oob->cb();
}
information_response_stop();
return true;
}
}
}
return false;
}
bool ATHandler::match_error()
{
if (match(CME_ERROR, CME_ERROR_LENGTH)) {
at_error(true, DeviceErrorTypeErrorCME);
return true;
} else if (match(CMS_ERROR, CMS_ERROR_LENGTH)) {
at_error(true, DeviceErrorTypeErrorCMS);
return true;
} else if (match(ERROR_, ERROR_LENGTH)) {
at_error(false, DeviceErrorTypeNoError);
return true;
}
return false;
}
void ATHandler::clear_error()
{
_last_err = NSAPI_ERROR_OK;
_last_at_err.errCode = 0;
_last_at_err.errType = DeviceErrorTypeNoError;
_last_3gpp_error = 0;
}
nsapi_error_t ATHandler::get_last_error() const
{
return _last_err;
}
device_err_t ATHandler::get_last_device_error() const
{
return _last_at_err;
}
void ATHandler::set_error(nsapi_error_t err)
{
if (err != NSAPI_ERROR_OK) {
tr_debug("AT error %d", err);
}
if (_last_err == NSAPI_ERROR_OK) {
_last_err = err;
}
}
int ATHandler::get_3gpp_error()
{
return _last_3gpp_error;
}
void ATHandler::set_3gpp_error(int err, DeviceErrorType error_type)
{
if (_last_3gpp_error) { // don't overwrite likely root cause error
return;
}
if (error_type == DeviceErrorTypeErrorCMS && err < 128) {
// CMS errors 0-127 maps straight to 3GPP errors
_last_3gpp_error = err;
} else {
for (size_t i = 0; i < sizeof(map_3gpp_errors) / sizeof(map_3gpp_errors[0]); i++) {
if (map_3gpp_errors[i][0] == err) {
_last_3gpp_error = map_3gpp_errors[i][1];
tr_error("AT3GPP error code %d", get_3gpp_error());
break;
}
}
}
}
void ATHandler::at_error(bool error_code_expected, DeviceErrorType error_type)
{
if (error_code_expected && (error_type == DeviceErrorTypeErrorCMS || error_type == DeviceErrorTypeErrorCME)) {
set_scope(InfoType);
int32_t err = read_int();
if (err != -1) {
set_3gpp_error(err, error_type);
_last_at_err.errCode = err;
_last_at_err.errType = error_type;
tr_warn("AT error code %ld", err);
} else {
tr_warn("ATHandler ERROR reading failed");
}
}
set_error(NSAPI_ERROR_DEVICE_ERROR);
}
void ATHandler::resp(const char *prefix, bool check_urc)
{
_prefix_matched = false;
_urc_matched = false;
_error_found = false;
while (!get_last_error()) {
(void)match(CRLF, CRLF_LENGTH);
if (match(OK, OK_LENGTH)) {
set_scope(RespType);
_stop_tag->found = true;
return;
}
if (match_error()) {
_error_found = true;
return;
}
if (prefix && strlen(prefix) && match(prefix, strlen(prefix))) {
_prefix_matched = true;
return;
}
if (check_urc && match_urc()) {
_urc_matched = true;
clear_error();
continue;
}
// If no match found, look for CRLF and consume everything up to and including CRLF
if (mem_str(_recv_buff, _recv_len, CRLF, CRLF_LENGTH)) {
// If no prefix, return on CRLF - means data to read
if (!prefix || (prefix && !strlen(prefix))) {
return;
}
consume_to_tag(CRLF, true);
} else {
// If no prefix, no CRLF and no more chance to match for OK, ERROR or URC(since max resp length is already in buffer)
// return so data could be read
if ((!prefix || (prefix && !strlen(prefix))) && ((_recv_len - _recv_pos) >= _max_resp_length)) {
return;
}
if (!fill_buffer()) {
// if we don't get any match and no data within timeout, set an error to indicate need for recovery
set_error(NSAPI_ERROR_DEVICE_ERROR);
}
}
}
return;
// something went wrong so application need to recover and retry
}
void ATHandler::resp_start(const char *prefix, bool stop)
{
if (!ok_to_proceed()) {
return;
}
set_scope(NotSet);
// Try get as much data as possible
rewind_buffer();
(void)fill_buffer(false);
if (prefix) {
MBED_ASSERT(strlen(prefix) < MBED_CONF_CELLULAR_AT_HANDLER_BUFFER_SIZE);
strcpy(_info_resp_prefix, prefix); // copy prefix so we can later use it without having to provide again for info_resp
}
set_scope(RespType);
resp(prefix, true);
if (!stop && prefix && _prefix_matched) {
set_scope(InfoType);
}
}
// check urc because of error as urc
bool ATHandler::info_resp()
{
if (!ok_to_proceed() || _resp_stop.found) {
return false;
}
if (_prefix_matched) {
_prefix_matched = false;
return true;
}
// If coming here after another info response was started(looping), stop the previous one.
// Trying to handle stopping in this level instead of doing it in upper level.
if (get_scope() == InfoType) {
information_response_stop();
}
resp(_info_resp_prefix, false);
if (_prefix_matched) {
set_scope(InfoType);
_prefix_matched = false;
return true;
}