File: gsm_unix_serial.cc

package info (click to toggle)
gsmlib 1.10+20120414.gita5e5ae9a-0.3
  • links: PTS
  • area: main
  • in suites: bullseye, buster, sid, stretch
  • size: 3,468 kB
  • ctags: 1,907
  • sloc: cpp: 12,315; sh: 11,376; ansic: 2,366; makefile: 263; sed: 93
file content (454 lines) | stat: -rw-r--r-- 10,899 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
451
452
453
454
// *************************************************************************
// * GSM TA/ME library
// *
// * File:    gsm_unix_port.cc
// *
// * Purpose: UNIX serial port implementation
// *
// * Author:  Peter Hofmann (software@pxh.de)
// *
// * Created: 10.5.1999
// *************************************************************************

#ifdef HAVE_CONFIG_H
#include <gsm_config.h>
#endif
#include <gsmlib/gsm_nls.h>
#include <gsmlib/gsm_unix_serial.h>
#include <gsmlib/gsm_util.h>
#include <termios.h>
#include <fcntl.h>
#include <iostream>
#include <sstream>
#include <cassert>
#include <errno.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <signal.h>
#include <pthread.h>
#include <cstring>

using namespace gsmlib;

static const int holdoff[] = {2000000, 1000000, 400000};
static const int holdoffArraySize = sizeof(holdoff) / sizeof(int);
  
// alarm handling for socket read/write
// the timerMtx is necessary since several threads cannot use the
// timer indepently of each other

static pthread_mutex_t timerMtx = PTHREAD_MUTEX_INITIALIZER;

// for non-GNU systems, define alarm()
#ifndef HAVE_ALARM
unsigned int alarm(unsigned int seconds)
{
  struct itimerval old, newt;
  newt.it_interval.tv_usec = 0;
  newt.it_interval.tv_sec = 0;
  newt.it_value.tv_usec = 0;
  newt.it_value.tv_sec = (long int)seconds;
  if (setitimer(ITIMER_REAL, &newt, &old) < 0)
    return 0;
  else
    return old.it_value.tv_sec;
}
#endif

// this routine is called in case of a timeout
static void catchAlarm(int)
{
  // do nothing
}

// start timer
static void startTimer()
{
  pthread_mutex_lock(&timerMtx);
  struct sigaction newAction;
  newAction.sa_handler = catchAlarm;
  newAction.sa_flags = 0;
  sigaction(SIGALRM, &newAction, NULL);
  alarm(1);
}

// reset timer
static void stopTimer()
{
  alarm(0);
  sigaction(SIGALRM, NULL, NULL);
  pthread_mutex_unlock(&timerMtx);
}

// UnixSerialPort members

void UnixSerialPort::throwModemException(std::string message) throw(GsmException)
{
  std::ostringstream os;
  os << message << " (errno: " << errno << "/" << strerror(errno) << ")"
     << std::ends;
  throw GsmException(os.str(), OSError, errno);
}

void UnixSerialPort::putBack(unsigned char c)
{
  assert(_oldChar == -1);
  _oldChar = c;
}

int UnixSerialPort::readByte() throw(GsmException)
{
  if (_oldChar != -1)
  {
    int result = _oldChar;
    _oldChar = -1;
    return result;
  }

  unsigned char c;
  int timeElapsed = 0;
  struct timeval oneSecond;
  bool readDone = false;

  while (!readDone && timeElapsed < _timeoutVal)
  {
    if (interrupted())
      throwModemException(_("interrupted when reading from TA"));

    // setup fd_set data structure for select()
    fd_set fdSet;
    oneSecond.tv_sec = 1;
    oneSecond.tv_usec = 0;
    FD_ZERO(&fdSet);
    FD_SET(_fd, &fdSet);

    switch (select(FD_SETSIZE, &fdSet, NULL, NULL, &oneSecond))
    {
    case 1:
      {
	int res = read(_fd, &c, 1);
	if (res != 1)
	  throwModemException(_("end of file when reading from TA"));
	else
	  readDone = true;
	break;
      }
    case 0:
      ++timeElapsed;
      break;
    default:
      if (errno != EINTR)
        throwModemException(_("reading from TA"));
      break;
    }
  }
  if (!readDone)
    throwModemException(_("timeout when reading from TA"));

#ifndef NDEBUG
  if (debugLevel() >= 2)
  {
    // some useful debugging code
    if (c == LF)
      std::cerr << "<LF>";
    else if (c == CR)
      std::cerr << "<CR>";
    else
      std::cerr << "<'" << (char) c << "'>";
    std::cerr.flush();
  }
#endif
  return c;
}

UnixSerialPort::UnixSerialPort(std::string device, speed_t lineSpeed,
				       std::string initString, bool swHandshake)
  throw(GsmException) :
  _oldChar(-1), _timeoutVal(TIMEOUT_SECS)
{
  struct termios t;

  // open device
  _fd = open(device.c_str(), O_RDWR | O_NOCTTY | O_NONBLOCK);
  if (_fd == -1)
    throwModemException(stringPrintf(_("opening device '%s'"),
                                     device.c_str()));

  // switch off non-blocking mode
  int fdFlags;
  if ((fdFlags = fcntl(_fd, F_GETFL)) == -1)
    {
      close(_fd);
      throwModemException(_("getting file status flags failed"));
    }
  fdFlags &= ~O_NONBLOCK;
  if (fcntl(_fd, F_SETFL, fdFlags) == -1)
    {
      close(_fd);
      throwModemException(_("switching of non-blocking mode failed"));
    }

  long int saveTimeoutVal = _timeoutVal;
  _timeoutVal = 3;
  int initTries = holdoffArraySize;
  while (initTries-- > 0)
    {
      // flush all pending output
      tcflush(_fd, TCOFLUSH);
      
      // toggle DTR to reset modem
      int mctl = TIOCM_DTR;
      if (ioctl(_fd, TIOCMBIC, &mctl) < 0) {
	close(_fd);
	throwModemException(_("clearing DTR failed"));
      }
      // the waiting time for DTR toggling is increased with each loop
      usleep(holdoff[initTries]);
      if (ioctl(_fd, TIOCMBIS, &mctl) < 0) {
	close(_fd);
	throwModemException(_("setting DTR failed"));
      }
      // get line modes
      if (tcgetattr(_fd, &t) < 0) {
	close(_fd);
	throwModemException(stringPrintf(_("tcgetattr device '%s'"),
					 device.c_str()));
      }
      
      // set line speed
      cfsetispeed(&t, lineSpeed);
      cfsetospeed(&t, lineSpeed);
      
      // set the device to a sane state
      t.c_iflag |= IGNPAR | (swHandshake ? IXON | IXOFF : 0);
      t.c_iflag &= ~(INPCK | ISTRIP | IMAXBEL |
		     (swHandshake ? 0 : IXON |  IXOFF)
		     | IXANY | IGNCR | ICRNL | IMAXBEL | INLCR | IGNBRK);
      t.c_oflag &= ~(OPOST);
      // be careful, only touch "known" flags
      t.c_cflag &= ~(CSIZE | CSTOPB | PARENB | PARODD |
		     (swHandshake ? CRTSCTS : 0 ));
      t.c_cflag |= CS8 | CREAD | HUPCL | (swHandshake ? 0 : CRTSCTS) | CLOCAL;
      t.c_lflag &= ~(ECHO | ECHOE | ECHOPRT | ECHOK | ECHOKE | ECHONL |
		     ECHOCTL | ISIG | IEXTEN | TOSTOP | FLUSHO | ICANON);
      t.c_lflag |= NOFLSH;
      t.c_cc[VMIN] = 1;
      t.c_cc[VTIME] = 0;
      
      t.c_cc[VSUSP] = 0;
      
      // write back
      if(tcsetattr (_fd, TCSANOW, &t) < 0)
	{
	  close(_fd);
	  throwModemException(stringPrintf(_("tcsetattr device '%s'"),
					   device.c_str()));
	}
      // the waiting time for writing to the ME/TA is increased with each loop
      usleep(holdoff[initTries]);
      
      // flush all pending input
      tcflush(_fd, TCIFLUSH);
      
      try
	{
	  // reset modem
	  putLine("ATZ");
	  bool foundOK = false;
	  int readTries = 5;
	  while (readTries-- > 0)
	    {
	      // for the first call getLine() waits only 3 seconds
	      // because of _timeoutVal = 3
	      std::string s = getLine();
	      if (s.find("OK") != std::string::npos ||
		  s.find("CABLE: GSM") != std::string::npos)
		{
		  foundOK = true;
		  readTries = 0;        // found OK, exit loop
		}
	      else if (s.find("ERROR") != std::string::npos)
		readTries = 0;        // error, exit loop
	    }
	  
	  // set getLine/putLine timeout back to old value
	  _timeoutVal = saveTimeoutVal;
	  
	  if (foundOK)
	    {
	      // init modem
	      readTries = 5;
	      putLine("AT" + initString);
	      while (readTries-- > 0)
		{
		  std::string s = getLine();
		  if (s.find("OK") != std::string::npos ||
		      s.find("CABLE: GSM") != std::string::npos)
		    return;                 // found OK, return
		}
	    }
	}
      catch (GsmException &e)
	{
	  _timeoutVal = saveTimeoutVal;
	  if (initTries == 0) {
	    close(_fd);
	    throw e;
	  }
	}
    }
  // no response after 3 tries
  close(_fd);
  throw GsmException(stringPrintf(_("reset modem failed '%s'"),
                                  device.c_str()), OtherError);
}

std::string UnixSerialPort::getLine() throw(GsmException)
{
  std::string result;
  int c;
  while ((c = readByte()) >= 0)
  {
    while (c == CR)
      c = readByte();
    if (c == LF)
      break;
    result += c;
  }

#ifndef NDEBUG
  if (debugLevel() >= 1)
    std::cerr << "<-- " << result << std::endl;
#endif

  return result;
}

void UnixSerialPort::putLine(std::string line, bool carriageReturn)
  throw(GsmException)
{
#ifndef NDEBUG
  if (debugLevel() >= 1)
    std::cerr << "--> " << line << std::endl;
#endif

  if (carriageReturn) line += CR;
  const char *l = line.c_str();
  
  int timeElapsed = 0;
  struct timeval oneSecond;

  ssize_t bytesWritten = 0;
  while (bytesWritten < (ssize_t)line.length() && timeElapsed < _timeoutVal)
  {
    if (interrupted())
      throwModemException(_("interrupted when writing to TA"));

    // setup fd_set data structure for select()
    fd_set fdSet;
    oneSecond.tv_sec = 1;
    oneSecond.tv_usec = 0;
    FD_ZERO(&fdSet);
    FD_SET(_fd, &fdSet);

    switch (select(FD_SETSIZE, NULL, &fdSet, NULL, &oneSecond))
      {
      case 1:
	{
	  ssize_t bw = write(_fd, l + bytesWritten, line.length() - bytesWritten);
	  if (bw < 0)
	    throwModemException(_("writing to TA"));
	  bytesWritten += bw;
	  break;
	}
      case 0:
	++timeElapsed;
	break;
      default:
	if (errno != EINTR)
	  throwModemException(_("writing to TA"));
	break;
      }
  }
  
  while (timeElapsed < _timeoutVal)
  {
    if (interrupted())
      throwModemException(_("interrupted when writing to TA"));
    startTimer();
    int res = tcdrain(_fd);     // wait for output to be read by TA
    stopTimer();
    if (res == 0)
      break;
    else
    {
      assert(errno == EINTR);
      ++timeElapsed;
    }
  }
  if (timeElapsed >= _timeoutVal)
    throwModemException(_("timeout when writing to TA"));

  // echo CR LF must be removed by higher layer functions in gsm_at because
  // in order to properly handle unsolicited result codes from the ME/TA
}

bool UnixSerialPort::wait(GsmTime timeout) throw(GsmException)
{
  fd_set fds;
  FD_ZERO(&fds);
  FD_SET(_fd, &fds);
  return select(FD_SETSIZE, &fds, NULL, NULL, timeout) != 0;
}

// set timeout for read or write in seconds.
void UnixSerialPort::setTimeOut(unsigned int timeout)
{
  _timeoutVal = timeout;
}

UnixSerialPort::~UnixSerialPort()
{
  if (_fd != -1)
    close(_fd);
}

speed_t gsmlib::baudRateStrToSpeed(std::string baudrate) throw(GsmException)
{
  if (baudrate == "300")
    return B300;
  else if (baudrate == "600")
    return B600;
  else if (baudrate == "1200")
    return B1200;
  else if (baudrate == "2400")
    return B2400;
  else if (baudrate == "4800")
    return B4800;
  else if (baudrate == "9600")
    return B9600;
  else if (baudrate == "19200")
    return B19200;
  else if (baudrate == "38400")
    return B38400;
#ifdef B57600
  else if (baudrate == "57600")
    return B57600;
#endif
#ifdef B115200
  else if (baudrate == "115200")
    return B115200;
#endif
#ifdef B230400
  else if (baudrate == "230400")
    return B230400;
#endif
#ifdef B460800
  else if (baudrate == "460800")
    return B460800;
#endif
  else
    throw GsmException(stringPrintf(_("unknown baudrate '%s'"),
                                    baudrate.c_str()), ParameterError);
}