-
Notifications
You must be signed in to change notification settings - Fork 1
/
atchannel.c
1388 lines (1098 loc) · 35.3 KB
/
atchannel.c
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
/* ST-Ericsson U300 RIL
**
** Copyright (C) ST-Ericsson AB 2008-2009
** Copyright 2006, The Android Open Source Project
**
** 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.
**
** Based on reference-ril by The Android Open Source Project.
**
** Modified for ST-Ericsson U300 modems.
** Author: Christian Bejram <[email protected]>
*/
#include "atchannel.h"
#include "at_tok.h"
#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <ctype.h>
#include <stdlib.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/time.h>
#include <time.h>
#include <unistd.h>
#include <stdarg.h>
#include <poll.h>
#define LOG_NDEBUG 0
#define LOG_TAG "AT"
#include <utils/Log.h>
#ifdef HAVE_ANDROID_OS
/* For IOCTL's */
#include <linux/omap_csmi.h>
#endif /*HAVE_ANDROID_OS*/
#include "misc.h"
#define MAX_AT_RESPONSE (8 * 1024)
#define HANDSHAKE_RETRY_COUNT 8
#define HANDSHAKE_TIMEOUT_MSEC 250
#define DEFAULT_AT_TIMEOUT_MSEC (3 * 60 * 1000)
#define BUFFSIZE 512
struct atcontext {
pthread_t tid_reader;
int fd; /* fd of the AT channel. */
int readerCmdFds[2];
int isInitialized;
ATUnsolHandler unsolHandler;
/* For input buffering. */
char ATBuffer[MAX_AT_RESPONSE+1];
char *ATBufferCur;
int readCount;
/*
* For current pending command, these are protected by commandmutex.
*
* The mutex and cond struct is memset in the getAtChannel() function,
* so no initializer should be needed.
*/
pthread_mutex_t requestmutex;
pthread_mutex_t commandmutex;
pthread_cond_t requestcond;
pthread_cond_t commandcond;
ATCommandType type;
const char *responsePrefix;
const char *smsPDU;
ATResponse *response;
void (*onTimeout)(void);
void (*onReaderClosed)(void);
int readerClosed;
int timeoutMsec;
};
static struct atcontext *s_defaultAtContext = NULL;
static va_list empty = {0};
static pthread_key_t key;
static pthread_once_t key_once = PTHREAD_ONCE_INIT;
static int writeCtrlZ (const char *s);
static int writeline (const char *s);
static void onReaderClosed(void);
static void make_key(void)
{
(void) pthread_key_create(&key, NULL);
}
/**
* Set the atcontext pointer. Useful for sub-threads that needs to hold
* the same state information.
*
* The caller IS responsible for freeing any memory already allocated
* for any previous atcontexts.
*/
static void setAtContext(struct atcontext *ac)
{
(void) pthread_once(&key_once, make_key);
(void) pthread_setspecific(key, ac);
}
static void ac_free(void)
{
struct atcontext *ac = NULL;
(void) pthread_once(&key_once, make_key);
if ((ac = pthread_getspecific(key)) != NULL) {
free(ac);
LOGD("%s() freed current thread AT context", __func__);
} else {
LOGW("%s() No AT context exist for current thread, cannot free it",
__func__);
}
}
static int initializeAtContext(void)
{
struct atcontext *ac = NULL;
if (pthread_once(&key_once, make_key)) {
LOGE("%s() Pthread_once failed!", __func__);
goto error;
}
ac = pthread_getspecific(key);
if (ac == NULL) {
ac = malloc(sizeof(struct atcontext));
if (ac == NULL) {
LOGE("%s() Failed to allocate memory", __func__);
goto error;
}
memset(ac, 0, sizeof(struct atcontext));
ac->fd = -1;
ac->readerCmdFds[0] = -1;
ac->readerCmdFds[1] = -1;
ac->ATBufferCur = ac->ATBuffer;
if (pipe(ac->readerCmdFds)) {
LOGE("%s() Failed to create pipe: %s", __func__, strerror(errno));
goto error;
}
pthread_mutex_init(&ac->commandmutex, NULL);
pthread_mutex_init(&ac->requestmutex, NULL);
pthread_cond_init(&ac->requestcond, NULL);
pthread_cond_init(&ac->commandcond, NULL);
ac->timeoutMsec = DEFAULT_AT_TIMEOUT_MSEC;
if (pthread_setspecific(key, ac)) {
LOGE("%s() Calling pthread_setspecific failed!", __func__);
goto error;
}
}
LOGI("Initialized new AT Context!");
return 0;
error:
LOGE("%s() Failed initializing new AT Context!", __func__);
free(ac);
return -1;
}
static struct atcontext *getAtContext(void)
{
struct atcontext *ac = NULL;
(void) pthread_once(&key_once, make_key);
if ((ac = pthread_getspecific(key)) == NULL) {
if (s_defaultAtContext) {
LOGW("WARNING! external thread use default AT Context");
ac = s_defaultAtContext;
} else {
LOGE("WARNING! %s() called from external thread with "
"no defaultAtContext set!! This IS a bug! "
"A crash is probably nearby!", __func__);
}
}
return ac;
}
/**
* This function will make the current at thread the default channel,
* meaning that calls from a thread that is not a queuerunner will
* be executed in this context.
*/
void at_make_default_channel(void)
{
struct atcontext *ac = getAtContext();
if (ac->isInitialized)
s_defaultAtContext = ac;
}
#if AT_DEBUG
void AT_DUMP(const char* prefix, const char* buff, int len)
{
if (len < 0)
len = strlen(buff);
LOGD("%.*s", len, buff);
}
#endif
#ifndef HAVE_ANDROID_OS
int pthread_cond_timeout_np(pthread_cond_t *cond,
pthread_mutex_t * mutex,
unsigned msecs)
{
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
ts.tv_sec += msecs / 1000;
ts.tv_nsec += (msecs % 1000) * 1000000;
return pthread_cond_timedwait(cond, mutex, &ts);
}
#endif /*HAVE_ANDROID_OS*/
static void sleepMsec(long long msec)
{
struct timespec ts;
int err;
ts.tv_sec = (msec / 1000);
ts.tv_nsec = (msec % 1000) * 1000 * 1000;
do {
err = nanosleep (&ts, &ts);
} while (err < 0 && errno == EINTR);
}
/** Add an intermediate response to sp_response. */
static void addIntermediate(const char *line)
{
ATLine *p_new;
struct atcontext *ac = getAtContext();
p_new = (ATLine *) malloc(sizeof(ATLine));
p_new->line = strdup(line);
/* Note: This adds to the head of the list, so the list will
be in reverse order of lines received. the order is flipped
again before passing on to the command issuer. */
p_new->p_next = ac->response->p_intermediates;
ac->response->p_intermediates = p_new;
}
/**
* Returns 1 if line is a final response indicating error.
* See 27.007 annex B.
* WARNING: NO CARRIER and others are sometimes unsolicited.
*/
static const char * s_finalResponsesError[] = {
"ERROR",
"+CMS ERROR:",
"+CME ERROR:",
"NO CARRIER", /* Sometimes! */
"NO ANSWER",
"NO DIALTONE",
};
static int isFinalResponseError(const char *line)
{
size_t i;
for (i = 0 ; i < NUM_ELEMS(s_finalResponsesError) ; i++) {
if (strStartsWith(line, s_finalResponsesError[i])) {
return 1;
}
}
return 0;
}
/**
* Returns 1 if line is a final response indicating success.
* See 27.007 annex B.
* WARNING: NO CARRIER and others are sometimes unsolicited.
*/
static const char * s_finalResponsesSuccess[] = {
"OK",
"CONNECT" /* Some stacks start up data on another channel. */
};
static int isFinalResponseSuccess(const char *line)
{
size_t i;
for (i = 0 ; i < NUM_ELEMS(s_finalResponsesSuccess) ; i++) {
if (strStartsWith(line, s_finalResponsesSuccess[i])) {
return 1;
}
}
return 0;
}
/**
* Returns 1 if line is the first line in (what will be) a two-line
* SMS unsolicited response.
*/
static const char * s_smsUnsoliciteds[] = {
"+CMT:",
"+CDS:",
"+CBM:"
};
static int isSMSUnsolicited(const char *line)
{
size_t i;
for (i = 0 ; i < NUM_ELEMS(s_smsUnsoliciteds) ; i++) {
if (strStartsWith(line, s_smsUnsoliciteds[i])) {
return 1;
}
}
return 0;
}
/** Assumes s_commandmutex is held. */
static void handleFinalResponse(const char *line)
{
struct atcontext *ac = getAtContext();
ac->response->finalResponse = strdup(line);
pthread_cond_signal(&ac->commandcond);
}
static void handleUnsolicited(const char *line)
{
struct atcontext *ac = getAtContext();
if (ac->unsolHandler != NULL) {
ac->unsolHandler(line, NULL);
}
}
static void processLine(const char *line)
{
struct atcontext *ac = getAtContext();
pthread_mutex_lock(&ac->commandmutex);
if (ac->response == NULL) {
/* No command pending. */
handleUnsolicited(line);
} else if (isFinalResponseSuccess(line)) {
ac->response->success = 1;
handleFinalResponse(line);
} else if (isFinalResponseError(line)) {
ac->response->success = 0;
handleFinalResponse(line);
} else if (ac->smsPDU != NULL && 0 == strcmp(line, "> ")) {
/* See eg. TS 27.005 4.3.
Commands like AT+CMGS have a "> " prompt. */
writeCtrlZ(ac->smsPDU);
ac->smsPDU = NULL;
} else switch (ac->type) {
case NO_RESULT:
handleUnsolicited(line);
break;
case NUMERIC:
if (ac->response->p_intermediates == NULL
&& isdigit(line[0])) {
addIntermediate(line);
} else {
/* Either we already have an intermediate response or
the line doesn't begin with a digit. */
handleUnsolicited(line);
}
break;
case SINGLELINE:
if (ac->response->p_intermediates == NULL
&& strStartsWith (line, ac->responsePrefix)) {
addIntermediate(line);
} else {
/* We already have an intermediate response. */
handleUnsolicited(line);
}
break;
case MULTILINE:
if (strStartsWith (line, ac->responsePrefix)) {
addIntermediate(line);
} else {
handleUnsolicited(line);
}
break;
default: /* This should never be reached */
LOGE("%s() Unsupported AT command type %d", __func__, ac->type);
handleUnsolicited(line);
break;
}
pthread_mutex_unlock(&ac->commandmutex);
}
/**
* Returns a pointer to the end of the next line,
* special-cases the "> " SMS prompt.
*
* returns NULL if there is no complete line.
*/
static char * findNextEOL(char *cur)
{
if (cur[0] == '>' && cur[1] == ' ' && cur[2] == '\0') {
/* SMS prompt character...not \r terminated */
return cur+2;
}
/* Find next newline */
while (*cur != '\0' && *cur != '\r' && *cur != '\n') cur++;
return *cur == '\0' ? NULL : cur;
}
/**
* Reads a line from the AT channel, returns NULL on timeout.
* Assumes it has exclusive read access to the FD.
*
* This line is valid only until the next call to readline.
*
* This function exists because as of writing, android libc does not
* have buffered stdio.
*/
static const char *readline(void)
{
ssize_t count;
char *p_read = NULL;
char *p_eol = NULL;
char *ret = NULL;
struct atcontext *ac = getAtContext();
read(ac->fd,NULL,0);
/* This is a little odd. I use *s_ATBufferCur == 0 to mean
* "buffer consumed completely". If it points to a character,
* then the buffer continues until a \0.
*/
if (*ac->ATBufferCur == '\0') {
/* Empty buffer. */
ac->ATBufferCur = ac->ATBuffer;
*ac->ATBufferCur = '\0';
p_read = ac->ATBuffer;
} else { /* *s_ATBufferCur != '\0' */
/* There's data in the buffer from the last read. */
/* skip over leading newlines */
while (*ac->ATBufferCur == '\r' || *ac->ATBufferCur == '\n')
ac->ATBufferCur++;
p_eol = findNextEOL(ac->ATBufferCur);
if (p_eol == NULL) {
/* A partial line. Move it up and prepare to read more. */
size_t len;
len = strlen(ac->ATBufferCur);
memmove(ac->ATBuffer, ac->ATBufferCur, len + 1);
p_read = ac->ATBuffer + len;
ac->ATBufferCur = ac->ATBuffer;
}
/* Otherwise, (p_eol !- NULL) there is a complete line
that will be returned from the while () loop below. */
}
while (p_eol == NULL) {
int err;
struct pollfd pfds[2];
/* This condition should be synchronized with the read function call
* size argument below.
*/
if (0 >= MAX_AT_RESPONSE - (p_read - ac->ATBuffer) - 2) {
LOGE("%s() ERROR: Input line exceeded buffer", __func__);
/* Ditch buffer and start over again. */
ac->ATBufferCur = ac->ATBuffer;
*ac->ATBufferCur = '\0';
p_read = ac->ATBuffer;
}
/* If our fd is invalid, we are probably closed. Return. */
if (ac->fd < 0)
return NULL;
pfds[0].fd = ac->fd;
pfds[0].events = POLLIN | POLLERR;
pfds[1].fd = ac->readerCmdFds[0];
pfds[1].events = POLLIN;
err = poll(pfds, 2, -1);
if (err < 0) {
LOGE("%s() poll: error: %s", __func__, strerror(errno));
return NULL;
}
if (pfds[1].revents & POLLIN) {
char buf[10];
/* Just drain it. We don't care, this is just for waking up. */
read(pfds[1].fd, &buf, 1);
continue;
}
if (pfds[0].revents & POLLERR) {
LOGE("%s() POLLERR event! Returning...", __func__);
return NULL;
}
if (!(pfds[0].revents & POLLIN))
continue;
do
/* The size argument should be synchronized to the ditch buffer
* condition above.
*/
count = read(ac->fd, p_read,
MAX_AT_RESPONSE - (p_read - ac->ATBuffer) - 2);
while (count < 0 && errno == EINTR);
if (count > 0) {
AT_DUMP( "<< ", p_read, count );
ac->readCount += count;
/* Implementation requires extra EOS or EOL to get it right if
* there are no trailing newlines in the read buffer. Adding extra
* EOS does not harm even if there actually were trailing EOLs.
*/
p_read[count] = '\0';
p_read[count+1] = '\0';
/* Skip over leading newlines. */
while (*ac->ATBufferCur == '\r' || *ac->ATBufferCur == '\n')
ac->ATBufferCur++;
p_eol = findNextEOL(ac->ATBufferCur);
p_read += count;
} else if (count <= 0) {
/* Read error encountered or EOF reached. */
if (count == 0)
LOGD("%s() atchannel: EOF reached.", __func__);
else
LOGD("%s() atchannel: read error %s", __func__, strerror(errno));
return NULL;
}
}
/* A full line in the buffer. Place a \0 over the \r and return. */
ret = ac->ATBufferCur;
*p_eol = '\0';
/* The extra EOS added after read takes care of the case when there is no
* valid data after p_eol.
*/
ac->ATBufferCur = p_eol + 1; /* This will always be <= p_read,
and there will be a \0 at *p_read. */
LOGI("AT(%d)< %s", ac->fd, ret);
return ret;
}
static void onReaderClosed(void)
{
struct atcontext *ac = getAtContext();
if (ac->onReaderClosed != NULL && ac->readerClosed == 0) {
pthread_mutex_lock(&ac->commandmutex);
ac->readerClosed = 1;
pthread_cond_signal(&ac->commandcond);
pthread_mutex_unlock(&ac->commandmutex);
ac->onReaderClosed();
}
}
static void *readerLoop(void *arg)
{
struct atcontext *ac = NULL;
LOGI("Entering readerloop!");
setAtContext((struct atcontext *) arg);
ac = getAtContext();
for (;;) {
const char * line;
line = readline();
if (line == NULL)
break;
if(isSMSUnsolicited(line)) {
char *line1;
const char *line2;
/* The scope of string returned by 'readline()' is valid only
until next call to 'readline()' hence making a copy of line
before calling readline again. */
line1 = strdup(line);
line2 = readline();
if (line2 == NULL) {
free(line1);
break;
}
if (ac->unsolHandler != NULL)
ac->unsolHandler(line1, line2);
free(line1);
} else
processLine(line);
}
onReaderClosed();
LOGI("Exiting readerloop!");
return NULL;
}
/**
* Sends string s to the radio with a \r appended.
* Returns AT_ERROR_* on error, 0 on success.
*
* This function exists because as of writing, android libc does not
* have buffered stdio.
*/
static int writeline (const char *s)
{
size_t cur = 0;
size_t len = strlen(s);
ssize_t written;
struct atcontext *ac = getAtContext();
if (ac->fd < 0 || ac->readerClosed > 0) {
return AT_ERROR_CHANNEL_CLOSED;
}
LOGD("AT(%d)> %s", ac->fd, s);
AT_DUMP( ">> ", s, strlen(s) );
/* The main string. */
while (cur < len) {
do {
written = write (ac->fd, s + cur, len - cur);
} while (written < 0 && errno == EINTR);
if (written < 0) {
return AT_ERROR_GENERIC;
}
cur += written;
}
/* The \r */
do {
written = write (ac->fd, "\r" , 1);
} while ((written < 0 && errno == EINTR) || (written == 0));
if (written < 0) {
return AT_ERROR_GENERIC;
}
return 0;
}
static int writeCtrlZ (const char *s)
{
size_t cur = 0;
size_t len = strlen(s);
ssize_t written;
struct atcontext *ac = getAtContext();
if (ac->fd < 0 || ac->readerClosed > 0)
return AT_ERROR_CHANNEL_CLOSED;
LOGD("AT> %s^Z\n", s);
AT_DUMP( ">* ", s, strlen(s) );
/* The main string. */
while (cur < len) {
do {
written = write (ac->fd, s + cur, len - cur);
} while (written < 0 && errno == EINTR);
if (written < 0)
return AT_ERROR_GENERIC;
cur += written;
}
/* the ^Z */
do {
written = write (ac->fd, "\032" , 1);
} while ((written < 0 && errno == EINTR) || (written == 0));
if (written < 0)
return AT_ERROR_GENERIC;
return 0;
}
static void clearPendingCommand(void)
{
struct atcontext *ac = getAtContext();
if (ac->response != NULL)
at_response_free(ac->response);
ac->response = NULL;
ac->responsePrefix = NULL;
ac->smsPDU = NULL;
}
static int merror(int type, int error)
{
switch(type) {
case AT_ERROR :
return AT_ERROR_BASE + error;
case CME_ERROR :
return CME_ERROR_BASE + error;
case CMS_ERROR:
return CMS_ERROR_BASE + error;
case GENERIC_ERROR:
return GENERIC_ERROR_BASE + error;
default:
return GENERIC_ERROR_UNSPECIFIED;
}
}
static AT_Error at_get_error(const ATResponse *p_response)
{
int ret;
int err;
char *p_cur;
if (p_response == NULL)
return merror(GENERIC_ERROR, GENERIC_ERROR_UNSPECIFIED);
if (p_response->success > 0)
return AT_NOERROR;
if (p_response->finalResponse == NULL)
return AT_ERROR_INVALID_RESPONSE;
if (isFinalResponseSuccess(p_response->finalResponse))
return AT_NOERROR;
p_cur = p_response->finalResponse;
err = at_tok_start(&p_cur);
if (err < 0)
return merror(GENERIC_ERROR, GENERIC_ERROR_UNSPECIFIED);
err = at_tok_nextint(&p_cur, &ret);
if (err < 0)
return merror(GENERIC_ERROR, GENERIC_ERROR_UNSPECIFIED);
if(strStartsWith(p_response->finalResponse, "+CME ERROR:"))
return merror(CME_ERROR, ret);
else if (strStartsWith(p_response->finalResponse, "+CMS ERROR:"))
return merror(CMS_ERROR, ret);
else if (strStartsWith(p_response->finalResponse, "ERROR:"))
return merror(GENERIC_ERROR, GENERIC_ERROR_RESPONSE);
else if (strStartsWith(p_response->finalResponse, "+NO CARRIER:"))
return merror(GENERIC_ERROR, GENERIC_NO_CARRIER_RESPONSE);
else if (strStartsWith(p_response->finalResponse, "+NO ANSWER:"))
return merror(GENERIC_ERROR, GENERIC_NO_ANSWER_RESPONSE);
else if (strStartsWith(p_response->finalResponse, "+NO DIALTONE:"))
return merror(GENERIC_ERROR, GENERIC_NO_DIALTONE_RESPONSE);
else
return merror(GENERIC_ERROR, GENERIC_ERROR_UNSPECIFIED);
}
/**
* Starts AT handler on stream "fd'.
* returns 0 on success, -1 on error.
*/
int at_open(int fd, ATUnsolHandler h)
{
int ret;
pthread_attr_t attr;
struct atcontext *ac = NULL;
if (initializeAtContext()) {
LOGE("%s() InitializeAtContext failed!", __func__);
goto error;
}
ac = getAtContext();
ac->fd = fd;
ac->isInitialized = 1;
ac->unsolHandler = h;
ac->readerClosed = 0;
ac->responsePrefix = NULL;
ac->smsPDU = NULL;
ac->response = NULL;
pthread_attr_init (&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
ret = pthread_create(&ac->tid_reader, &attr, readerLoop, ac);
if (ret < 0) {
perror ("pthread_create");
goto error;
}
return 0;
error:
ac_free();
return -1;
}
/* FIXME is it ok to call this from the reader and the command thread? */
void at_close(void)
{
struct atcontext *ac = getAtContext();
if (ac->fd >= 0) {
if (close(ac->fd) != 0)
LOGE("%s() FAILED to close fd %d!", __func__, ac->fd);
}
ac->fd = -1;
pthread_mutex_lock(&ac->commandmutex);
ac->readerClosed = 1;
pthread_cond_signal(&ac->commandcond);
pthread_mutex_unlock(&ac->commandmutex);
/* Kick readerloop. */
write(ac->readerCmdFds[1], "x", 1);
}
static ATResponse *at_response_new(void)
{
return (ATResponse *) calloc(1, sizeof(ATResponse));
}
void at_response_free(ATResponse *p_response)
{
ATLine *p_line;
if (p_response == NULL) return;
p_line = p_response->p_intermediates;
while (p_line != NULL) {
ATLine *p_toFree;
p_toFree = p_line;
p_line = p_line->p_next;
free(p_toFree->line);
free(p_toFree);
}
free (p_response->finalResponse);
free (p_response);
}
/**
* The line reader places the intermediate responses in reverse order,
* here we flip them back.
*/
static void reverseIntermediates(ATResponse *p_response)
{
ATLine *pcur,*pnext;
pcur = p_response->p_intermediates;
p_response->p_intermediates = NULL;
while (pcur != NULL) {
pnext = pcur->p_next;
pcur->p_next = p_response->p_intermediates;
p_response->p_intermediates = pcur;
pcur = pnext;
}
}
/**
* Internal send_command implementation.
* Doesn't lock or call the timeout callback.
*
* timeoutMsec == 0 means infinite timeout.
*/
static int at_send_command_full_nolock (const char *command, ATCommandType type,
const char *responsePrefix, const char *smspdu,
long long timeoutMsec, ATResponse **pp_outResponse)
{
int err = AT_NOERROR;
struct atcontext *ac = getAtContext();
/* Default to NULL, to allow caller to free securely even if
* no response will be set below */
if (pp_outResponse != NULL)
*pp_outResponse = NULL;
/* FIXME This is to prevent future problems due to calls from other threads; should be revised. */
while (pthread_mutex_trylock(&ac->requestmutex) == EBUSY)
pthread_cond_wait(&ac->requestcond, &ac->commandmutex);
if(ac->response != NULL) {
err = AT_ERROR_COMMAND_PENDING;
goto finally;
}
ac->type = type;
ac->responsePrefix = responsePrefix;
ac->smsPDU = smspdu;
ac->response = at_response_new();
if (ac->response == NULL) {
err = AT_ERROR_MEMORY_ALLOCATION;
goto finally;
}
err = writeline (command);
if (err != AT_NOERROR)
goto finally;
while (ac->response->finalResponse == NULL && ac->readerClosed == 0) {
if (timeoutMsec != 0)
err = pthread_cond_timeout_np(&ac->commandcond, &ac->commandmutex, timeoutMsec);
else
err = pthread_cond_wait(&ac->commandcond, &ac->commandmutex);
if (err == ETIMEDOUT) {
err = AT_ERROR_TIMEOUT;
goto finally;
}
}
if (ac->response->success == 0) {
err = at_get_error(ac->response);
}
if (pp_outResponse == NULL)
at_response_free(ac->response);
else {
/* Line reader stores intermediate responses in reverse order. */
reverseIntermediates(ac->response);
*pp_outResponse = ac->response;
}
ac->response = NULL;