subrascasse

Sub Rascasse: an iPhone dive log for Subsurface cloud storage, with a pure-Swift git client (GPL-2.0)
git clone https://git.schurger.org/subrascasse.git
Log | Files | Refs | README | LICENSE

serial_posix.c (24684B)


      1 /*
      2  * libdivecomputer
      3  *
      4  * Copyright (C) 2008 Jef Driesen
      5  *
      6  * This library is free software; you can redistribute it and/or
      7  * modify it under the terms of the GNU Lesser General Public
      8  * License as published by the Free Software Foundation; either
      9  * version 2.1 of the License, or (at your option) any later version.
     10  *
     11  * This library is distributed in the hope that it will be useful,
     12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
     13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
     14  * Lesser General Public License for more details.
     15  *
     16  * You should have received a copy of the GNU Lesser General Public
     17  * License along with this library; if not, write to the Free Software
     18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
     19  * MA 02110-1301 USA
     20  */
     21 
     22 #ifdef HAVE_CONFIG_H
     23 #include "config.h"
     24 #endif
     25 
     26 #include <stdlib.h> // malloc, free
     27 #include <string.h>	// strerror
     28 #include <errno.h>	// errno
     29 #include <unistd.h>	// open, close, read, write
     30 #include <fcntl.h>	// fcntl
     31 #include <termios.h>	// tcgetattr, tcsetattr, cfsetispeed, cfsetospeed, tcflush, tcsendbreak
     32 #include <sys/ioctl.h>	// ioctl
     33 #include <sys/select.h>	// select
     34 #ifdef HAVE_LINUX_SERIAL_H
     35 #include <linux/serial.h>
     36 #endif
     37 #ifdef HAVE_IOKIT_SERIAL_IOSS_H
     38 #include <IOKit/serial/ioss.h>
     39 #endif
     40 #include <sys/types.h>
     41 #include <dirent.h>
     42 #include <fnmatch.h>
     43 
     44 #ifndef TIOCINQ
     45 #define TIOCINQ FIONREAD
     46 #endif
     47 
     48 #ifdef ENABLE_PTY
     49 #define NOPTY (errno != EINVAL && errno != ENOTTY)
     50 #else
     51 #define NOPTY 1
     52 #endif
     53 
     54 #include <libdivecomputer/serial.h>
     55 
     56 #include "common-private.h"
     57 #include "context-private.h"
     58 #include "iostream-private.h"
     59 #include "iterator-private.h"
     60 #include "platform.h"
     61 #include "timer.h"
     62 
     63 #define DIRNAME "/dev"
     64 
     65 static dc_status_t dc_serial_iterator_next (dc_iterator_t *iterator, void *item);
     66 static dc_status_t dc_serial_iterator_free (dc_iterator_t *iterator);
     67 
     68 static dc_status_t dc_serial_set_timeout (dc_iostream_t *iostream, int timeout);
     69 static dc_status_t dc_serial_set_break (dc_iostream_t *iostream, unsigned int value);
     70 static dc_status_t dc_serial_set_dtr (dc_iostream_t *iostream, unsigned int value);
     71 static dc_status_t dc_serial_set_rts (dc_iostream_t *iostream, unsigned int value);
     72 static dc_status_t dc_serial_get_lines (dc_iostream_t *iostream, unsigned int *value);
     73 static dc_status_t dc_serial_get_available (dc_iostream_t *iostream, size_t *value);
     74 static dc_status_t dc_serial_configure (dc_iostream_t *iostream, unsigned int baudrate, unsigned int databits, dc_parity_t parity, dc_stopbits_t stopbits, dc_flowcontrol_t flowcontrol);
     75 static dc_status_t dc_serial_poll (dc_iostream_t *iostream, int timeout);
     76 static dc_status_t dc_serial_read (dc_iostream_t *iostream, void *data, size_t size, size_t *actual);
     77 static dc_status_t dc_serial_write (dc_iostream_t *iostream, const void *data, size_t size, size_t *actual);
     78 static dc_status_t dc_serial_ioctl (dc_iostream_t *iostream, unsigned int request, void *data, size_t size);
     79 static dc_status_t dc_serial_flush (dc_iostream_t *iostream);
     80 static dc_status_t dc_serial_purge (dc_iostream_t *iostream, dc_direction_t direction);
     81 static dc_status_t dc_serial_sleep (dc_iostream_t *iostream, unsigned int milliseconds);
     82 static dc_status_t dc_serial_close (dc_iostream_t *iostream);
     83 
     84 struct dc_serial_device_t {
     85 	char name[256];
     86 };
     87 
     88 typedef struct dc_serial_iterator_t {
     89 	dc_iterator_t base;
     90 	dc_descriptor_t *descriptor;
     91 	DIR *dp;
     92 } dc_serial_iterator_t;
     93 
     94 typedef struct dc_serial_t {
     95 	dc_iostream_t base;
     96 	/*
     97 	 * The file descriptor corresponding to the serial port.
     98 	 */
     99 	int fd;
    100 	int timeout;
    101 	dc_timer_t *timer;
    102 	/*
    103 	 * Serial port settings are saved into this variable immediately
    104 	 * after the port is opened. These settings are restored when the
    105 	 * serial port is closed.
    106 	 */
    107 	struct termios tty;
    108 } dc_serial_t;
    109 
    110 static const dc_iterator_vtable_t dc_serial_iterator_vtable = {
    111 	sizeof(dc_serial_iterator_t),
    112 	dc_serial_iterator_next,
    113 	dc_serial_iterator_free,
    114 };
    115 
    116 static const dc_iostream_vtable_t dc_serial_vtable = {
    117 	sizeof(dc_serial_t),
    118 	dc_serial_set_timeout, /* set_timeout */
    119 	dc_serial_set_break, /* set_break */
    120 	dc_serial_set_dtr, /* set_dtr */
    121 	dc_serial_set_rts, /* set_rts */
    122 	dc_serial_get_lines, /* get_lines */
    123 	dc_serial_get_available, /* get_available */
    124 	dc_serial_configure, /* configure */
    125 	dc_serial_poll, /* poll */
    126 	dc_serial_read, /* read */
    127 	dc_serial_write, /* write */
    128 	dc_serial_ioctl, /* ioctl */
    129 	dc_serial_flush, /* flush */
    130 	dc_serial_purge, /* purge */
    131 	dc_serial_sleep, /* sleep */
    132 	dc_serial_close, /* close */
    133 };
    134 
    135 static dc_status_t
    136 syserror(int errcode)
    137 {
    138 	switch (errcode) {
    139 	case EINVAL:
    140 		return DC_STATUS_INVALIDARGS;
    141 	case ENOMEM:
    142 		return DC_STATUS_NOMEMORY;
    143 	case ENOENT:
    144 		return DC_STATUS_NODEVICE;
    145 	case EACCES:
    146 	case EBUSY:
    147 		return DC_STATUS_NOACCESS;
    148 	default:
    149 		return DC_STATUS_IO;
    150 	}
    151 }
    152 
    153 const char *
    154 dc_serial_device_get_name (dc_serial_device_t *device)
    155 {
    156 	if (device == NULL || device->name[0] == '\0')
    157 		return NULL;
    158 
    159 	return device->name;
    160 }
    161 
    162 void
    163 dc_serial_device_free (dc_serial_device_t *device)
    164 {
    165 	free (device);
    166 }
    167 
    168 dc_status_t
    169 dc_serial_iterator_new (dc_iterator_t **out, dc_context_t *context, dc_descriptor_t *descriptor)
    170 {
    171 	dc_status_t status = DC_STATUS_SUCCESS;
    172 	dc_serial_iterator_t *iterator = NULL;
    173 
    174 	if (out == NULL)
    175 		return DC_STATUS_INVALIDARGS;
    176 
    177 	iterator = (dc_serial_iterator_t *) dc_iterator_allocate (context, &dc_serial_iterator_vtable);
    178 	if (iterator == NULL) {
    179 		SYSERROR (context, ENOMEM);
    180 		return DC_STATUS_NOMEMORY;
    181 	}
    182 
    183 	iterator->dp = opendir (DIRNAME);
    184 	if (iterator->dp == NULL) {
    185 		int errcode = errno;
    186 		SYSERROR (context, errcode);
    187 		status = syserror (errcode);
    188 		goto error_free;
    189 	}
    190 
    191 	iterator->descriptor = descriptor;
    192 
    193 	*out = (dc_iterator_t *) iterator;
    194 
    195 	return DC_STATUS_SUCCESS;
    196 
    197 error_free:
    198 	dc_iterator_deallocate ((dc_iterator_t *) iterator);
    199 	return status;
    200 }
    201 
    202 static dc_status_t
    203 dc_serial_iterator_next (dc_iterator_t *abstract, void *out)
    204 {
    205 	dc_serial_iterator_t *iterator = (dc_serial_iterator_t *) abstract;
    206 	dc_serial_device_t *device = NULL;
    207 
    208 	struct dirent *ep = NULL;
    209 	const char *patterns[] = {
    210 #if defined (__APPLE__)
    211 		"tty.*",
    212 #else
    213 		"ttyS*",
    214 		"ttyUSB*",
    215 		"ttyACM*",
    216 		"rfcomm*",
    217 #endif
    218 		NULL
    219 	};
    220 
    221 	while ((ep = readdir (iterator->dp)) != NULL) {
    222 		for (size_t i = 0; patterns[i] != NULL; ++i) {
    223 			if (fnmatch (patterns[i], ep->d_name, 0) != 0)
    224 				continue;
    225 
    226 			char filename[sizeof(device->name)];
    227 			int n = dc_platform_snprintf (filename, sizeof (filename), "%s/%s", DIRNAME, ep->d_name);
    228 			if (n < 0 || (size_t) n >= sizeof (filename)) {
    229 				return DC_STATUS_NOMEMORY;
    230 			}
    231 
    232 			if (!dc_descriptor_filter (iterator->descriptor, DC_TRANSPORT_SERIAL, filename)) {
    233 				continue;
    234 			}
    235 
    236 			device = (dc_serial_device_t *) malloc (sizeof(dc_serial_device_t));
    237 			if (device == NULL) {
    238 				SYSERROR (abstract->context, ENOMEM);
    239 				return DC_STATUS_NOMEMORY;
    240 			}
    241 
    242 			strncpy(device->name, filename, sizeof(device->name));
    243 
    244 			*(dc_serial_device_t **) out = device;
    245 
    246 			return DC_STATUS_SUCCESS;
    247 		}
    248 	}
    249 
    250 	return DC_STATUS_DONE;
    251 }
    252 
    253 static dc_status_t
    254 dc_serial_iterator_free (dc_iterator_t *abstract)
    255 {
    256 	dc_serial_iterator_t *iterator = (dc_serial_iterator_t *) abstract;
    257 
    258 	closedir (iterator->dp);
    259 
    260 	return DC_STATUS_SUCCESS;
    261 }
    262 
    263 dc_status_t
    264 dc_serial_open (dc_iostream_t **out, dc_context_t *context, const char *name)
    265 {
    266 	dc_status_t status = DC_STATUS_SUCCESS;
    267 	dc_serial_t *device = NULL;
    268 
    269 	if (out == NULL || name == NULL)
    270 		return DC_STATUS_INVALIDARGS;
    271 
    272 	INFO (context, "Open: name=%s", name);
    273 
    274 	// Allocate memory.
    275 	device = (dc_serial_t *) dc_iostream_allocate (context, &dc_serial_vtable, DC_TRANSPORT_SERIAL);
    276 	if (device == NULL) {
    277 		SYSERROR (context, ENOMEM);
    278 		return DC_STATUS_NOMEMORY;
    279 	}
    280 
    281 	// Default to blocking reads.
    282 	device->timeout = -1;
    283 
    284 	// Create a high resolution timer.
    285 	status = dc_timer_new (&device->timer);
    286 	if (status != DC_STATUS_SUCCESS) {
    287 		ERROR (context, "Failed to create a high resolution timer.");
    288 		goto error_free;
    289 	}
    290 
    291 	// Open the device in non-blocking mode, to return immediately
    292 	// without waiting for the modem connection to complete.
    293 	device->fd = open (name, O_RDWR | O_NOCTTY | O_NONBLOCK);
    294 	if (device->fd == -1) {
    295 		int errcode = errno;
    296 		SYSERROR (context, errcode);
    297 		status = syserror (errcode);
    298 		goto error_timer_free;
    299 	}
    300 
    301 #ifndef ENABLE_PTY
    302 	// Enable exclusive access mode.
    303 	if (ioctl (device->fd, TIOCEXCL, NULL) != 0) {
    304 		int errcode = errno;
    305 		SYSERROR (context, errcode);
    306 		status = syserror (errcode);
    307 		goto error_close;
    308 	}
    309 #endif
    310 
    311 	// Retrieve the current terminal attributes, to
    312 	// be able to restore them when closing the device.
    313 	// It is also used to check if the obtained
    314 	// file descriptor represents a terminal device.
    315 	if (tcgetattr (device->fd, &device->tty) != 0) {
    316 		int errcode = errno;
    317 		SYSERROR (context, errcode);
    318 		status = syserror (errcode);
    319 		goto error_close;
    320 	}
    321 
    322 	*out = (dc_iostream_t *) device;
    323 
    324 	return DC_STATUS_SUCCESS;
    325 
    326 error_close:
    327 	close (device->fd);
    328 error_timer_free:
    329 	dc_timer_free (device->timer);
    330 error_free:
    331 	dc_iostream_deallocate ((dc_iostream_t *) device);
    332 	return status;
    333 }
    334 
    335 static dc_status_t
    336 dc_serial_close (dc_iostream_t *abstract)
    337 {
    338 	dc_status_t status = DC_STATUS_SUCCESS;
    339 	dc_serial_t *device = (dc_serial_t *) abstract;
    340 
    341 	// Restore the initial terminal attributes.
    342 	if (tcsetattr (device->fd, TCSANOW, &device->tty) != 0) {
    343 		int errcode = errno;
    344 		SYSERROR (abstract->context, errcode);
    345 		dc_status_set_error(&status, syserror (errcode));
    346 	}
    347 
    348 #ifndef ENABLE_PTY
    349 	// Disable exclusive access mode.
    350 	if (ioctl (device->fd, TIOCNXCL, NULL)) {
    351 		int errcode = errno;
    352 		SYSERROR (abstract->context, errcode);
    353 		dc_status_set_error(&status, syserror (errcode));
    354 	}
    355 #endif
    356 
    357 	// Close the device.
    358 	if (close (device->fd) != 0) {
    359 		int errcode = errno;
    360 		SYSERROR (abstract->context, errcode);
    361 		dc_status_set_error(&status, syserror (errcode));
    362 	}
    363 
    364 	dc_timer_free (device->timer);
    365 
    366 	return status;
    367 }
    368 
    369 static dc_status_t
    370 dc_serial_configure (dc_iostream_t *abstract, unsigned int baudrate, unsigned int databits, dc_parity_t parity, dc_stopbits_t stopbits, dc_flowcontrol_t flowcontrol)
    371 {
    372 	dc_serial_t *device = (dc_serial_t *) abstract;
    373 
    374 	// Retrieve the current settings.
    375 	struct termios tty;
    376 	memset (&tty, 0, sizeof (tty));
    377 	if (tcgetattr (device->fd, &tty) != 0) {
    378 		int errcode = errno;
    379 		SYSERROR (abstract->context, errcode);
    380 		return syserror (errcode);
    381 	}
    382 
    383 	// Setup raw input/output mode without echo.
    384 	tty.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | ICRNL);
    385 	tty.c_oflag &= ~(OPOST);
    386 	tty.c_lflag &= ~(ICANON | ECHO | ISIG | IEXTEN);
    387 
    388 	// Enable the receiver (CREAD) and ignore modem control lines (CLOCAL).
    389 	tty.c_cflag |= (CLOCAL | CREAD);
    390 
    391     // VMIN is the minimum number of characters for non-canonical read
    392     // and VTIME is the timeout in deciseconds for non-canonical read.
    393     // Setting both of these parameters to zero implies that a read
    394     // will return immediately, only giving the currently available
    395     // characters (non-blocking read behaviour). However, a non-blocking
    396     // read (or write) can also be achieved by using O_NONBLOCK.
    397     // But together with VMIN = 1, it becomes possible to recognize
    398     // the difference between a timeout and modem disconnect (EOF)
    399     // when read() returns zero.
    400 	tty.c_cc[VMIN] = 1;
    401 	tty.c_cc[VTIME] = 0;
    402 
    403 	// Set the baud rate.
    404 	int custom = 0;
    405 	speed_t baud = 0;
    406 	switch (baudrate) {
    407 	case 0: baud = B0; break;
    408 	case 50: baud = B50; break;
    409 	case 75: baud = B75; break;
    410 	case 110: baud = B110; break;
    411 	case 134: baud = B134; break;
    412 	case 150: baud = B150; break;
    413 	case 200: baud = B200; break;
    414 	case 300: baud = B300; break;
    415 	case 600: baud = B600; break;
    416 	case 1200: baud = B1200; break;
    417 	case 1800: baud = B1800; break;
    418 	case 2400: baud = B2400; break;
    419 	case 4800: baud = B4800; break;
    420 	case 9600: baud = B9600; break;
    421 	case 19200: baud = B19200; break;
    422 	case 38400: baud = B38400; break;
    423 #ifdef B57600
    424 	case 57600: baud = B57600; break;
    425 #endif
    426 #ifdef B115200
    427 	case 115200: baud = B115200; break;
    428 #endif
    429 #ifdef B230400
    430 	case 230400: baud = B230400; break;
    431 #endif
    432 #ifdef B460800
    433 	case 460800: baud = B460800; break;
    434 #endif
    435 #ifdef B500000
    436 	case 500000: baud = B500000; break;
    437 #endif
    438 #ifdef B576000
    439 	case 576000: baud = B576000; break;
    440 #endif
    441 #ifdef B921600
    442 	case 921600: baud = B921600; break;
    443 #endif
    444 #ifdef B1000000
    445 	case 1000000: baud = B1000000; break;
    446 #endif
    447 #ifdef B1152000
    448 	case 1152000: baud = B1152000; break;
    449 #endif
    450 #ifdef B1500000
    451 	case 1500000: baud = B1500000; break;
    452 #endif
    453 #ifdef B2000000
    454 	case 2000000: baud = B2000000; break;
    455 #endif
    456 #ifdef B2500000
    457 	case 2500000: baud = B2500000; break;
    458 #endif
    459 #ifdef B3000000
    460 	case 3000000: baud = B3000000; break;
    461 #endif
    462 #ifdef B3500000
    463 	case 3500000: baud = B3500000; break;
    464 #endif
    465 #ifdef B4000000
    466 	case 4000000: baud = B4000000; break;
    467 #endif
    468 	default:
    469 		baud = B38400; /* Required for custom baudrates on linux. */
    470 		custom = 1;
    471 		break;
    472 	}
    473 	if (cfsetispeed (&tty, baud) != 0 ||
    474 		cfsetospeed (&tty, baud) != 0) {
    475 		int errcode = errno;
    476 		SYSERROR (abstract->context, errcode);
    477 		return syserror (errcode);
    478 	}
    479 
    480 	// Set the character size.
    481 	tty.c_cflag &= ~CSIZE;
    482 	switch (databits) {
    483 	case 5:
    484 		tty.c_cflag |= CS5;
    485 		break;
    486 	case 6:
    487 		tty.c_cflag |= CS6;
    488 		break;
    489 	case 7:
    490 		tty.c_cflag |= CS7;
    491 		break;
    492 	case 8:
    493 		tty.c_cflag |= CS8;
    494 		break;
    495 	default:
    496 		return DC_STATUS_INVALIDARGS;
    497 	}
    498 
    499 	// Set the parity type.
    500 #ifdef CMSPAR
    501 	tty.c_cflag &= ~(PARENB | PARODD | CMSPAR);
    502 #else
    503 	tty.c_cflag &= ~(PARENB | PARODD);
    504 #endif
    505 	tty.c_iflag &= ~(IGNPAR | PARMRK | INPCK);
    506 	switch (parity) {
    507 	case DC_PARITY_NONE:
    508 		tty.c_iflag |= IGNPAR;
    509 		break;
    510 	case DC_PARITY_EVEN:
    511 		tty.c_cflag |= PARENB;
    512 		tty.c_iflag |= INPCK;
    513 		break;
    514 	case DC_PARITY_ODD:
    515 		tty.c_cflag |= (PARENB | PARODD);
    516 		tty.c_iflag |= INPCK;
    517 		break;
    518 #ifdef CMSPAR
    519 	case DC_PARITY_MARK:
    520 		tty.c_cflag |= (PARENB | PARODD | CMSPAR);
    521 		tty.c_iflag |= INPCK;
    522 		break;
    523 	case DC_PARITY_SPACE:
    524 		tty.c_cflag |= (PARENB | CMSPAR);
    525 		tty.c_iflag |= INPCK;
    526 		break;
    527 #endif
    528 	default:
    529 		return DC_STATUS_INVALIDARGS;
    530 	}
    531 
    532 	// Set the number of stop bits.
    533 	switch (stopbits) {
    534 	case DC_STOPBITS_ONE:
    535 		tty.c_cflag &= ~CSTOPB;
    536 		break;
    537 	case DC_STOPBITS_TWO:
    538 		tty.c_cflag |= CSTOPB;
    539 		break;
    540 	default:
    541 		return DC_STATUS_INVALIDARGS;
    542 	}
    543 
    544 	// Set the flow control.
    545 	switch (flowcontrol) {
    546 	case DC_FLOWCONTROL_NONE:
    547 		#ifdef CRTSCTS
    548 			tty.c_cflag &= ~CRTSCTS;
    549 		#endif
    550 		tty.c_iflag &= ~(IXON | IXOFF | IXANY);
    551 		break;
    552 	case DC_FLOWCONTROL_HARDWARE:
    553 		#ifdef CRTSCTS
    554 			tty.c_cflag |= CRTSCTS;
    555 			tty.c_iflag &= ~(IXON | IXOFF | IXANY);
    556 			break;
    557 		#else
    558 			return DC_STATUS_UNSUPPORTED;
    559 		#endif
    560 	case DC_FLOWCONTROL_SOFTWARE:
    561 		#ifdef CRTSCTS
    562 			tty.c_cflag &= ~CRTSCTS;
    563 		#endif
    564 		tty.c_iflag |= (IXON | IXOFF);
    565 		break;
    566 	default:
    567 		return DC_STATUS_INVALIDARGS;
    568 	}
    569 
    570 	// Apply the new settings.
    571 	if (tcsetattr (device->fd, TCSANOW, &tty) != 0 && NOPTY) {
    572 		int errcode = errno;
    573 		SYSERROR (abstract->context, errcode);
    574 		return syserror (errcode);
    575 	}
    576 
    577 	// Configure a custom baudrate if necessary.
    578 	if (custom) {
    579 #if defined(TIOCGSERIAL) && defined(TIOCSSERIAL) && !defined(__ANDROID__)
    580 		// Get the current settings.
    581 		struct serial_struct ss;
    582 		if (ioctl (device->fd, TIOCGSERIAL, &ss) != 0 && NOPTY) {
    583 			int errcode = errno;
    584 			SYSERROR (abstract->context, errcode);
    585 			return syserror (errcode);
    586 		}
    587 
    588 		// Set the custom divisor.
    589 		ss.custom_divisor = ss.baud_base / baudrate;
    590 		ss.flags &= ~ASYNC_SPD_MASK;
    591 		ss.flags |= ASYNC_SPD_CUST;
    592 
    593 		// Apply the new settings.
    594 		if (ioctl (device->fd, TIOCSSERIAL, &ss) != 0 && NOPTY) {
    595 			int errcode = errno;
    596 			SYSERROR (abstract->context, errcode);
    597 			return syserror (errcode);
    598 		}
    599 #elif defined(IOSSIOSPEED)
    600 		speed_t speed = baudrate;
    601 		if (ioctl (device->fd, IOSSIOSPEED, &speed) != 0 && NOPTY) {
    602 			int errcode = errno;
    603 			SYSERROR (abstract->context, errcode);
    604 			return syserror (errcode);
    605 		}
    606 #else
    607 		// Custom baudrates are not supported.
    608 		return DC_STATUS_UNSUPPORTED;
    609 #endif
    610 	}
    611 
    612 	return DC_STATUS_SUCCESS;
    613 }
    614 
    615 static dc_status_t
    616 dc_serial_set_timeout (dc_iostream_t *abstract, int timeout)
    617 {
    618 	dc_serial_t *device = (dc_serial_t *) abstract;
    619 
    620 	device->timeout = timeout;
    621 
    622 	return DC_STATUS_SUCCESS;
    623 }
    624 
    625 static dc_status_t
    626 dc_serial_set_latency (dc_iostream_t *abstract, unsigned int milliseconds)
    627 {
    628 	dc_serial_t *device = (dc_serial_t *) abstract;
    629 
    630 #if defined(TIOCGSERIAL) && defined(TIOCSSERIAL) && !defined(__ANDROID__)
    631 	// Get the current settings.
    632 	struct serial_struct ss;
    633 	if (ioctl (device->fd, TIOCGSERIAL, &ss) != 0 && NOPTY) {
    634 		int errcode = errno;
    635 		SYSERROR (abstract->context, errcode);
    636 		return syserror (errcode);
    637 	}
    638 
    639 	// Set or clear the low latency flag.
    640 	if (milliseconds == 0) {
    641 		ss.flags |= ASYNC_LOW_LATENCY;
    642 	} else {
    643 		ss.flags &= ~ASYNC_LOW_LATENCY;
    644 	}
    645 
    646 	// Apply the new settings.
    647 	if (ioctl (device->fd, TIOCSSERIAL, &ss) != 0 && NOPTY) {
    648 		int errcode = errno;
    649 		SYSERROR (abstract->context, errcode);
    650 		return syserror (errcode);
    651 	}
    652 #elif defined(IOSSDATALAT)
    653 	// Set the receive latency in microseconds. Serial drivers use this
    654 	// value to determine how often to dequeue characters received by
    655 	// the hardware. A value of zero restores the default value.
    656 	unsigned long usec = (milliseconds == 0 ? 1 : milliseconds * 1000);
    657 	if (ioctl (device->fd, IOSSDATALAT, &usec) != 0 && NOPTY) {
    658 		int errcode = errno;
    659 		SYSERROR (abstract->context, errcode);
    660 		return syserror (errcode);
    661 	}
    662 #endif
    663 
    664 	return DC_STATUS_SUCCESS;
    665 }
    666 
    667 static dc_status_t
    668 dc_serial_poll (dc_iostream_t *abstract, int timeout)
    669 {
    670 	dc_serial_t *device = (dc_serial_t *) abstract;
    671 	int rc = 0;
    672 
    673 	do {
    674 		fd_set fds;
    675 		FD_ZERO (&fds);
    676 		FD_SET (device->fd, &fds);
    677 
    678 		struct timeval tv, *ptv = NULL;
    679 		if (timeout > 0) {
    680 			tv.tv_sec  = (timeout / 1000);
    681 			tv.tv_usec = (timeout % 1000) * 1000;
    682 			ptv = &tv;
    683 		} else if (timeout == 0) {
    684 			tv.tv_sec  = 0;
    685 			tv.tv_usec = 0;
    686 			ptv = &tv;
    687 		}
    688 
    689 		rc = select (device->fd + 1, &fds, NULL, NULL, ptv);
    690 	} while (rc < 0 && errno == EINTR);
    691 
    692 	if (rc < 0) {
    693 		int errcode = errno;
    694 		SYSERROR (abstract->context, errcode);
    695 		return syserror (errcode);
    696 	} else if (rc == 0) {
    697 		return DC_STATUS_TIMEOUT;
    698 	} else {
    699 		return DC_STATUS_SUCCESS;
    700 	}
    701 }
    702 
    703 static dc_status_t
    704 dc_serial_read (dc_iostream_t *abstract, void *data, size_t size, size_t *actual)
    705 {
    706 	dc_status_t status = DC_STATUS_SUCCESS;
    707 	dc_serial_t *device = (dc_serial_t *) abstract;
    708 	size_t nbytes = 0;
    709 
    710 	// The absolute target time.
    711 	dc_usecs_t target = 0;
    712 
    713 	int init = 1;
    714 	while (nbytes < size) {
    715 		fd_set fds;
    716 		FD_ZERO (&fds);
    717 		FD_SET (device->fd, &fds);
    718 
    719 		struct timeval tv, *ptv = NULL;
    720 		if (device->timeout > 0) {
    721 			dc_usecs_t timeout = 0;
    722 
    723 			dc_usecs_t now = 0;
    724 			status = dc_timer_now (device->timer, &now);
    725 			if (status != DC_STATUS_SUCCESS) {
    726 				goto out;
    727 			}
    728 
    729 			if (init) {
    730 				// Calculate the initial timeout.
    731 				timeout = (dc_usecs_t) device->timeout * 1000;
    732 				// Calculate the target time.
    733 				target = now + timeout;
    734 				init = 0;
    735 			} else {
    736 				// Calculate the remaining timeout.
    737 				if (now < target) {
    738 					timeout = target - now;
    739 				} else {
    740 					timeout = 0;
    741 				}
    742 			}
    743 			tv.tv_sec  = timeout / 1000000;
    744 			tv.tv_usec = timeout % 1000000;
    745 			ptv = &tv;
    746 		} else if (device->timeout == 0) {
    747 			tv.tv_sec  = 0;
    748 			tv.tv_usec = 0;
    749 			ptv = &tv;
    750 		}
    751 
    752 		int rc = select (device->fd + 1, &fds, NULL, NULL, ptv);
    753 		if (rc < 0) {
    754 			int errcode = errno;
    755 			if (errcode == EINTR)
    756 				continue; // Retry.
    757 			SYSERROR (abstract->context, errcode);
    758 			status = syserror (errcode);
    759 			goto out;
    760 		} else if (rc == 0) {
    761 			break; // Timeout.
    762 		}
    763 
    764 		ssize_t n = read (device->fd, (char *) data + nbytes, size - nbytes);
    765 		if (n < 0) {
    766 			int errcode = errno;
    767 			if (errcode == EINTR || errcode == EAGAIN)
    768 				continue; // Retry.
    769 			SYSERROR (abstract->context, errcode);
    770 			status = syserror (errcode);
    771 			goto out;
    772 		} else if (n == 0) {
    773 			 break; // EOF.
    774 		}
    775 
    776 		nbytes += n;
    777 	}
    778 
    779 	if (nbytes != size) {
    780 		status = DC_STATUS_TIMEOUT;
    781 	}
    782 
    783 out:
    784 	if (actual)
    785 		*actual = nbytes;
    786 
    787 	return status;
    788 }
    789 
    790 static dc_status_t
    791 dc_serial_write (dc_iostream_t *abstract, const void *data, size_t size, size_t *actual)
    792 {
    793 	dc_status_t status = DC_STATUS_SUCCESS;
    794 	dc_serial_t *device = (dc_serial_t *) abstract;
    795 	size_t nbytes = 0;
    796 
    797 	while (nbytes < size) {
    798 		fd_set fds;
    799 		FD_ZERO (&fds);
    800 		FD_SET (device->fd, &fds);
    801 
    802 		int rc = select (device->fd + 1, NULL, &fds, NULL, NULL);
    803 		if (rc < 0) {
    804 			int errcode = errno;
    805 			if (errcode == EINTR)
    806 				continue; // Retry.
    807 			SYSERROR (abstract->context, errcode);
    808 			status = syserror (errcode);
    809 			goto out;
    810 		} else if (rc == 0) {
    811 			break; // Timeout.
    812 		}
    813 
    814 		ssize_t n = write (device->fd, (const char *) data + nbytes, size - nbytes);
    815 		if (n < 0) {
    816 			int errcode = errno;
    817 			if (errcode == EINTR || errcode == EAGAIN)
    818 				continue; // Retry.
    819 			SYSERROR (abstract->context, errcode);
    820 			status = syserror (errcode);
    821 			goto out;
    822 		} else if (n == 0) {
    823 			 break; // EOF.
    824 		}
    825 
    826 		nbytes += n;
    827 	}
    828 
    829 	// Wait until all data has been transmitted.
    830 #ifdef __ANDROID__
    831 	/* Android is missing tcdrain, so use ioctl version instead */
    832 	while (ioctl (device->fd, TCSBRK, 1) != 0) {
    833 #else
    834 	while (tcdrain (device->fd) != 0) {
    835 #endif
    836 		int errcode = errno;
    837 		if (errcode != EINTR ) {
    838 			SYSERROR (abstract->context, errcode);
    839 			status = syserror (errcode);
    840 			goto out;
    841 		}
    842 	}
    843 
    844 out:
    845 	if (actual)
    846 		*actual = nbytes;
    847 
    848 	return status;
    849 }
    850 
    851 static dc_status_t
    852 dc_serial_ioctl (dc_iostream_t *abstract, unsigned int request, void *data, size_t size)
    853 {
    854 	switch (request) {
    855 	case DC_IOCTL_SERIAL_SET_LATENCY:
    856 		return dc_serial_set_latency (abstract, *(unsigned int *) data);
    857 	default:
    858 		return DC_STATUS_UNSUPPORTED;
    859 	}
    860 }
    861 
    862 static dc_status_t
    863 dc_serial_purge (dc_iostream_t *abstract, dc_direction_t direction)
    864 {
    865 	dc_serial_t *device = (dc_serial_t *) abstract;
    866 
    867 	int flags = 0;
    868 
    869 	switch (direction) {
    870 	case DC_DIRECTION_INPUT:
    871 		flags = TCIFLUSH;
    872 		break;
    873 	case DC_DIRECTION_OUTPUT:
    874 		flags = TCOFLUSH;
    875 		break;
    876 	case DC_DIRECTION_ALL:
    877 		flags = TCIOFLUSH;
    878 		break;
    879 	default:
    880 		return DC_STATUS_INVALIDARGS;
    881 	}
    882 
    883 	if (tcflush (device->fd, flags) != 0) {
    884 		int errcode = errno;
    885 		SYSERROR (abstract->context, errcode);
    886 		return syserror (errcode);
    887 	}
    888 
    889 	return DC_STATUS_SUCCESS;
    890 }
    891 
    892 static dc_status_t
    893 dc_serial_flush (dc_iostream_t *abstract)
    894 {
    895 	return DC_STATUS_SUCCESS;
    896 }
    897 
    898 static dc_status_t
    899 dc_serial_set_break (dc_iostream_t *abstract, unsigned int level)
    900 {
    901 	dc_serial_t *device = (dc_serial_t *) abstract;
    902 
    903 	unsigned long action = (level ? TIOCSBRK : TIOCCBRK);
    904 
    905 	if (ioctl (device->fd, action, NULL) != 0 && NOPTY) {
    906 		int errcode = errno;
    907 		SYSERROR (abstract->context, errcode);
    908 		return syserror (errcode);
    909 	}
    910 
    911 	return DC_STATUS_SUCCESS;
    912 }
    913 
    914 static dc_status_t
    915 dc_serial_set_dtr (dc_iostream_t *abstract, unsigned int level)
    916 {
    917 	dc_serial_t *device = (dc_serial_t *) abstract;
    918 
    919 	unsigned long action = (level ? TIOCMBIS : TIOCMBIC);
    920 
    921 	int value = TIOCM_DTR;
    922 	if (ioctl (device->fd, action, &value) != 0 && NOPTY) {
    923 		int errcode = errno;
    924 		SYSERROR (abstract->context, errcode);
    925 		return syserror (errcode);
    926 	}
    927 
    928 	return DC_STATUS_SUCCESS;
    929 }
    930 
    931 static dc_status_t
    932 dc_serial_set_rts (dc_iostream_t *abstract, unsigned int level)
    933 {
    934 	dc_serial_t *device = (dc_serial_t *) abstract;
    935 
    936 	unsigned long action = (level ? TIOCMBIS : TIOCMBIC);
    937 
    938 	int value = TIOCM_RTS;
    939 	if (ioctl (device->fd, action, &value) != 0 && NOPTY) {
    940 		int errcode = errno;
    941 		SYSERROR (abstract->context, errcode);
    942 		return syserror (errcode);
    943 	}
    944 
    945 	return DC_STATUS_SUCCESS;
    946 }
    947 
    948 static dc_status_t
    949 dc_serial_get_available (dc_iostream_t *abstract, size_t *value)
    950 {
    951 	dc_serial_t *device = (dc_serial_t *) abstract;
    952 
    953 	int bytes = 0;
    954 	if (ioctl (device->fd, TIOCINQ, &bytes) != 0) {
    955 		int errcode = errno;
    956 		SYSERROR (abstract->context, errcode);
    957 		return syserror (errcode);
    958 	}
    959 
    960 	if (value)
    961 		*value = bytes;
    962 
    963 	return DC_STATUS_SUCCESS;
    964 }
    965 
    966 static dc_status_t
    967 dc_serial_get_lines (dc_iostream_t *abstract, unsigned int *value)
    968 {
    969 	dc_serial_t *device = (dc_serial_t *) abstract;
    970 	unsigned int lines = 0;
    971 
    972 	int status = 0;
    973 	if (ioctl (device->fd, TIOCMGET, &status) != 0) {
    974 		int errcode = errno;
    975 		SYSERROR (abstract->context, errcode);
    976 		return syserror (errcode);
    977 	}
    978 
    979 	if (status & TIOCM_CAR)
    980 		lines |= DC_LINE_DCD;
    981 	if (status & TIOCM_CTS)
    982 		lines |= DC_LINE_CTS;
    983 	if (status & TIOCM_DSR)
    984 		lines |= DC_LINE_DSR;
    985 	if (status & TIOCM_RNG)
    986 		lines |= DC_LINE_RNG;
    987 
    988 	if (value)
    989 		*value = lines;
    990 
    991 	return DC_STATUS_SUCCESS;
    992 }
    993 
    994 static dc_status_t
    995 dc_serial_sleep (dc_iostream_t *abstract, unsigned int timeout)
    996 {
    997 	if (dc_platform_sleep (timeout) != 0) {
    998 		int errcode = errno;
    999 		SYSERROR (abstract->context, errcode);
   1000 		return syserror (errcode);
   1001 	}
   1002 
   1003 	return DC_STATUS_SUCCESS;
   1004 }