File: gsm_at.cc

package info (click to toggle)
gsmlib 1.10+20120414.gita5e5ae9a-0.3
  • links: PTS
  • area: main
  • in suites: buster, stretch
  • size: 3,468 kB
  • ctags: 1,907
  • sloc: cpp: 12,315; sh: 11,376; ansic: 2,366; makefile: 263; sed: 93
file content (450 lines) | stat: -rw-r--r-- 11,686 bytes parent folder | download | duplicates (2)
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
// *************************************************************************
// * GSM TA/ME library
// *
// * File:    gsm_at.cc
// *
// * Purpose: Utility classes for AT command sequence handling
// *
// * Author:  Peter Hofmann (software@pxh.de)
// *
// * Created: 3.5.1999
// *************************************************************************

#ifdef HAVE_CONFIG_H
#include <gsm_config.h>
#endif
#include <gsmlib/gsm_at.h>
#include <gsmlib/gsm_nls.h>
#include <gsmlib/gsm_util.h>
#include <gsmlib/gsm_error.h>
#include <gsmlib/gsm_event.h>
#include <gsmlib/gsm_me_ta.h>
#include <ctype.h>
#include <sstream>
#include <string>

using namespace gsmlib;

// GsmAt members

bool GsmAt::matchResponse(std::string answer, std::string responseToMatch)
{
  if (answer.substr(0, responseToMatch.length()) == responseToMatch)
    return true;
  else
    // some TAs omit the ':' at the end of the response
    if (_meTa.getCapabilities()._omitsColon &&
        responseToMatch[responseToMatch.length() - 1] == ':' &&
        answer.substr(0, responseToMatch.length() - 1) == 
        responseToMatch.substr(0, responseToMatch.length() - 1))
      return true;
  return false;
}

std::string GsmAt::cutResponse(std::string answer, std::string responseToMatch)
{
  if (answer.substr(0, responseToMatch.length()) == responseToMatch)
    return normalize(answer.substr(responseToMatch.length(),
                                   answer.length() -
                                   responseToMatch.length()));
  else
    // some TAs omit the ':' at the end of the response
    if (_meTa.getCapabilities()._omitsColon &&
        responseToMatch[responseToMatch.length() - 1] == ':' &&
        answer.substr(0, responseToMatch.length() - 1) == 
        responseToMatch.substr(0, responseToMatch.length() - 1))
      return normalize(answer.substr(responseToMatch.length() - 1,
                                     answer.length() -
                                     responseToMatch.length() + 1));
  assert(0);
  return "";
}

void GsmAt::throwCmeException(std::string s) throw(GsmException)
{
  if (matchResponse(s, "ERROR"))
    throw GsmException(_("unspecified ME/TA error"), ChatError);

  bool meError = matchResponse(s, "+CME ERROR:");
  if (meError)
    s = cutResponse(s, "+CME ERROR:");
  else
    s = cutResponse(s, "+CMS ERROR:");
  std::istringstream is(s.c_str());
  int error;
  is >> error;
  throw GsmException(_("ME/TA error '") +
                     (meError ? getMEErrorText(error) :
                      getSMSErrorText(error)) +
                     "' " +
                     stringPrintf(_("(code %s)"), s.c_str()),
                     ChatError, error);
}

GsmAt::GsmAt(MeTa &meTa) :
  _meTa(meTa), _port(meTa.getPort()), _eventHandler(NULL)
{
}

std::string GsmAt::chat(std::string atCommand, std::string response,
			bool ignoreErrors, bool acceptEmptyResponse)
  throw(GsmException)
{
  std::string dummy;
  return chat(atCommand, response, dummy, ignoreErrors, false,
              acceptEmptyResponse);
}

std::string GsmAt::chat(std::string atCommand, std::string response, std::string &pdu,
			bool ignoreErrors, bool expectPdu,
			bool acceptEmptyResponse) throw(GsmException)
{
  std::string s;
  bool gotOk = false;           // special handling for empty SMS entries

  // send AT command
  putLine("AT" + atCommand);
  // and gobble up CR/LF (and possibly echoed characters if echo can't be
  // switched off)
  // Also, some mobiles (e.g., Sony Ericsson K800i) respond to commands
  // like "at+cmgf=0" with "+CMGF: 0" on success as well as the "OK"
  // status -- so gobble that (but not if that sort of response was expected)
  // FIXME: this is a gross hack, should be done via capabilities or sth
  std::string::size_type loc = atCommand.find( "=", 1 );
  std::string expect;
  if (loc != std::string::npos) {
    expect = atCommand;
    expect.replace(loc, 1, " ");
    expect.insert(loc, ":");
  } else {
    expect = "";
  }
  do
    {
      s = normalize(getLine());
    }
  while (s.length() == 0 || s == "AT" + atCommand || 
         ((response.length() == 0 || !matchResponse(s, response)) &&
          (expect.length() > 0 && matchResponse(s, expect))));

  // handle errors
  if (matchResponse(s, "+CME ERROR:") || matchResponse(s, "+CMS ERROR:"))
    {
      if (ignoreErrors)
	return "";
      else
	throwCmeException(s);
    }
  if (matchResponse(s, "ERROR"))
    {
      if (ignoreErrors)
	return "";
      else
	throw GsmException(_("ME/TA error '<unspecified>' (code not known)"), 
			   ChatError, -1);
    }

  // return if response is "OK" and caller says this is OK
  if (acceptEmptyResponse && s == "OK")
    return "";

  // handle PDU if one is expected
  if (expectPdu)
    {
      std::string ps;
      do
	{
	  ps = normalize(getLine());
	}
      while (ps.length() == 0 && ps != "OK");
      if (ps == "OK")
	gotOk = true;
      else
	{
	  pdu = ps;
	  // remove trailing zero added by some devices (e.g. Falcom A2-1)
	  if (pdu.length() > 0 && pdu[pdu.length() - 1] == 0)
	    pdu.erase(pdu.length() - 1);
	}
    }

  // handle expected response
  if (response.length() == 0)   // no response expected
    {
      if (s == "OK") return "";
      // else fall through to error
    }
  else
    {
      std::string result;
      // some TA/TEs don't prefix their response with the response string
      // as proscribed by the standard: just handle either case
      if (matchResponse(s, response))
	result = cutResponse(s, response);
      else
	result = s;

      if (gotOk)
	return result;
      else
	{
	  // get the final "OK"
	  do
	    {
	      s = normalize(getLine());
	    }
	  while (s.length() == 0);

	  if (s == "OK") return result;
	  // else fall through to error
	}
    }
  throw GsmException(
		     stringPrintf(_("unexpected response '%s' when sending 'AT%s'"),
				  s.c_str(), atCommand.c_str()),
		     ChatError);
}

std::vector<std::string> GsmAt::chatv(std::string atCommand, std::string response,
				      bool ignoreErrors) throw(GsmException)
{
  std::string s;
  std::vector<std::string> result;

  // send AT command
  putLine("AT" + atCommand);
  // and gobble up CR/LF (and possibly echoed characters if echo can't be
  // switched off)
  do
    {
      s = normalize(getLine());
    }
  while (s.length() == 0 || s == "AT" + atCommand);

  // handle errors
  if (matchResponse(s, "+CME ERROR:") || matchResponse(s, "+CMS ERROR:"))
    {
      if (ignoreErrors)
	return result;
      else
	throwCmeException(s);
    }
  if (matchResponse(s, "ERROR"))
    {
      if (ignoreErrors)
	return result;
      else
	throw GsmException(_("ME/TA error '<unspecified>' (code not known)"), 
			   ChatError, -1);
    }
  // push all lines that are not empty
  // cut response prefix if it is there
  // stop when an OK line is read
  while (1)
    {
      if (s == "OK")
	return result;
      // some TA/TEs don't prefix their response with the response string
      // as proscribed by the standard: just handle either case
      if (response.length() != 0 && matchResponse(s, response))
	result.push_back(cutResponse(s, response));
      else
	result.push_back(s);
      // get next line
      do
	{
	  s = normalize(getLine());
	}
      while (s.length() == 0);
      reportProgress();
    }

  // never reached
  assert(0);
  return result;
}

std::string GsmAt::normalize(std::string s)
{
  size_t start = 0, end = s.length();
  bool changed = true;

  while (start < end && changed)
    {
      changed = false;
      if (isspace(s[start]))
	{
	  ++start;
	  changed = true;
	}
      else
	if (isspace(s[end - 1]))
	  {
	    --end;
	    changed = true;
	  }
    }
  return s.substr(start, end - start);
}

std::string GsmAt::sendPdu(std::string atCommand, std::string response, std::string pdu,
                      bool acceptEmptyResponse) throw(GsmException)
{
  std::string s;
  bool errorCondition;
  bool retry = false;
  int tries = 5;                // How many error conditions do we accept

  int c;
  do
    {
      errorCondition = false;
      putLine("AT" + atCommand);
      do
	{
	  retry = false;
	  try
	    {
	      do
		{
		  // read first of two bytes "> "
		  c = readByte();
		}
	      // there have been reports that some phones give spurious CRs
	      // LF separates CDSI messages if there are more than one
	      while (c == CR || c == LF);
	    }
	  catch (GsmException &e)
	    {
	      c = '-';
	      errorCondition = true;  // TA does not expect PDU anymore, retry
	    }

	  if (c == '+' || c == 'E') // error or unsolicited result code
	    {
	      _port->putBack(c);
	      s = normalize(getLine());
	      errorCondition = (s != "");

	      retry = ! errorCondition;
	    }
	}
      while (retry);
    }
  while (errorCondition && tries--);

  if (! errorCondition)
    {

      if (c != '>' || readByte() != ' ')
	throw GsmException(_("unexpected character in PDU handshake"),
			   ChatError);

      putLine(pdu + "\032", false); // write pdu followed by CTRL-Z

      // some phones (Ericcson T68, T39) send spurious zero characters after
      // accepting the PDU
      c = readByte();
      if (c != 0)
	_port->putBack(c);

      // loop while empty lines (maybe with a zero, Ericsson T39m)
      // or an echo of the pdu (with or without CTRL-Z)
      // is read
      do
	{
	  s = normalize(getLine());
	}
      while (s.length() == 0 || s == pdu || s == (pdu + "\032") ||
	     (s.length() == 1 && s[0] == 0));
    }

  // handle errors
  if (matchResponse(s, "+CME ERROR:") || matchResponse(s, "+CMS ERROR:"))
    throwCmeException(s);
  if (matchResponse(s, "ERROR"))
    throw GsmException(_("ME/TA error '<unspecified>' (code not known)"), 
                       ChatError, -1);

  // return if response is "OK" and caller says this is OK
  if (acceptEmptyResponse && s == "OK")
    return "";

  if (matchResponse(s, response))
    {
      std::string result = cutResponse(s, response);
      // get the final "OK"
      do
	{
	  s = normalize(getLine());
	}
      while (s.length() == 0);

      if (s == "OK") return result;
      // else fall through to error
    }
  throw GsmException(
		     stringPrintf(_("unexpected response '%s' when sending 'AT%s'"),
				  s.c_str(), atCommand.c_str()),
		     ChatError);
}

std::string GsmAt::getLine() throw(GsmException)
{
  if (_eventHandler == (GsmEvent*)NULL)
    return _port->getLine();
  else
    {
      bool eventOccurred;
      std::string result;
      do
	{
	  eventOccurred = false;
	  result = _port->getLine();
	  std::string s = normalize(result);
	  if (matchResponse(s, "+CMT:") ||
	      matchResponse(s, "+CBM:") ||
	      matchResponse(s, "+CDS:") ||
	      matchResponse(s, "+CMTI:") ||
	      matchResponse(s, "+CBMI:") ||
	      matchResponse(s, "+CDSI:") ||
	      matchResponse(s, "RING") ||
	      matchResponse(s, "NO CARRIER") ||
	      // hack: the +CLIP? sequence returns +CLIP: n,m
	      // which is NOT an unsolicited result code
	      (matchResponse(s, "+CLIP:") && s.length() > 10))
	    {
	      _eventHandler->dispatch(s, *this);
	      eventOccurred = true;
	    }
	}
      while (eventOccurred);
      return result;
    }
}

void GsmAt::putLine(std::string line,
                    bool carriageReturn) throw(GsmException)
{
  _port->putLine(line, carriageReturn);
  // remove empty echo line
  if (carriageReturn)
    getLine();
}

bool GsmAt::wait(GsmTime timeout) throw(GsmException)
{
  return _port->wait(timeout);
}

int GsmAt::readByte() throw(GsmException)
{
  return _port->readByte();
}

GsmEvent *GsmAt::setEventHandler(GsmEvent *newHandler)
{
  GsmEvent *result = _eventHandler;
  _eventHandler = newHandler;
  return result;
}