+#endif
+
+ ret = get_config(port, &data, &config);
+
+ if (ret < 0) {
+ sp_close(port);
+ RETURN_CODEVAL(ret);
+ }
+
+ /* Set sane port settings. */
+#ifdef _WIN32
+ data.dcb.fBinary = TRUE;
+ data.dcb.fDsrSensitivity = FALSE;
+ data.dcb.fErrorChar = FALSE;
+ data.dcb.fNull = FALSE;
+ data.dcb.fAbortOnError = FALSE;
+#else
+ /* Turn off all fancy termios tricks, give us a raw channel. */
+ data.term.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IMAXBEL);
+#ifdef IUCLC
+ data.term.c_iflag &= ~IUCLC;
+#endif
+ data.term.c_oflag &= ~(OPOST | ONLCR | OCRNL | ONOCR | ONLRET);
+#ifdef OLCUC
+ data.term.c_oflag &= ~OLCUC;
+#endif
+#ifdef NLDLY
+ data.term.c_oflag &= ~NLDLY;
+#endif
+#ifdef CRDLY
+ data.term.c_oflag &= ~CRDLY;
+#endif
+#ifdef TABDLY
+ data.term.c_oflag &= ~TABDLY;
+#endif
+#ifdef BSDLY
+ data.term.c_oflag &= ~BSDLY;
+#endif
+#ifdef VTDLY
+ data.term.c_oflag &= ~VTDLY;
+#endif
+#ifdef FFDLY
+ data.term.c_oflag &= ~FFDLY;
+#endif
+#ifdef OFILL
+ data.term.c_oflag &= ~OFILL;
+#endif
+ data.term.c_lflag &= ~(ISIG | ICANON | ECHO | IEXTEN);
+ data.term.c_cc[VMIN] = 0;
+ data.term.c_cc[VTIME] = 0;
+
+ /* Ignore modem status lines; enable receiver; leave control lines alone on close. */
+ data.term.c_cflag |= (CLOCAL | CREAD | HUPCL);
+#endif
+
+#ifdef _WIN32
+ if (ClearCommError(port->hdl, &errors, &status) == 0)
+ RETURN_FAIL("ClearCommError() failed");
+#endif
+
+ ret = set_config(port, &data, &config);
+
+ if (ret < 0) {
+ sp_close(port);
+ RETURN_CODEVAL(ret);
+ }
+
+ RETURN_OK();
+}
+
+SP_API enum sp_return sp_close(struct sp_port *port)
+{
+ TRACE("%p", port);
+
+ CHECK_OPEN_PORT();
+
+ DEBUG_FMT("Closing port %s", port->name);
+
+#ifdef _WIN32
+ /* Returns non-zero upon success, 0 upon failure. */
+ if (CloseHandle(port->hdl) == 0)
+ RETURN_FAIL("Port CloseHandle() failed");
+ port->hdl = INVALID_HANDLE_VALUE;
+
+ /* Close event handles for overlapped structures. */
+#define CLOSE_OVERLAPPED(ovl) do { \
+ if (port->ovl.hEvent != INVALID_HANDLE_VALUE && \
+ CloseHandle(port->ovl.hEvent) == 0) \
+ RETURN_FAIL(# ovl "event CloseHandle() failed"); \
+} while (0)
+ CLOSE_OVERLAPPED(read_ovl);
+ CLOSE_OVERLAPPED(write_ovl);
+ CLOSE_OVERLAPPED(wait_ovl);
+
+ if (port->write_buf) {
+ free(port->write_buf);
+ port->write_buf = NULL;
+ }
+#else
+ /* Returns 0 upon success, -1 upon failure. */
+ if (close(port->fd) == -1)
+ RETURN_FAIL("close() failed");
+ port->fd = -1;
+#endif
+
+ RETURN_OK();
+}
+
+SP_API enum sp_return sp_flush(struct sp_port *port, enum sp_buffer buffers)
+{
+ TRACE("%p, 0x%x", port, buffers);
+
+ CHECK_OPEN_PORT();
+
+ if (buffers > SP_BUF_BOTH)
+ RETURN_ERROR(SP_ERR_ARG, "Invalid buffer selection");
+
+ const char *buffer_names[] = {"no", "input", "output", "both"};
+
+ DEBUG_FMT("Flushing %s buffers on port %s",
+ buffer_names[buffers], port->name);
+
+#ifdef _WIN32
+ DWORD flags = 0;
+ if (buffers & SP_BUF_INPUT)
+ flags |= PURGE_RXCLEAR;
+ if (buffers & SP_BUF_OUTPUT)
+ flags |= PURGE_TXCLEAR;
+
+ /* Returns non-zero upon success, 0 upon failure. */
+ if (PurgeComm(port->hdl, flags) == 0)
+ RETURN_FAIL("PurgeComm() failed");
+
+ if (buffers & SP_BUF_INPUT)
+ TRY(restart_wait(port));
+#else
+ int flags = 0;
+ if (buffers == SP_BUF_BOTH)
+ flags = TCIOFLUSH;
+ else if (buffers == SP_BUF_INPUT)
+ flags = TCIFLUSH;
+ else if (buffers == SP_BUF_OUTPUT)
+ flags = TCOFLUSH;
+
+ /* Returns 0 upon success, -1 upon failure. */
+ if (tcflush(port->fd, flags) < 0)
+ RETURN_FAIL("tcflush() failed");
+#endif
+ RETURN_OK();
+}
+
+SP_API enum sp_return sp_drain(struct sp_port *port)
+{
+ TRACE("%p", port);
+
+ CHECK_OPEN_PORT();
+
+ DEBUG_FMT("Draining port %s", port->name);
+
+#ifdef _WIN32
+ /* Returns non-zero upon success, 0 upon failure. */
+ if (FlushFileBuffers(port->hdl) == 0)
+ RETURN_FAIL("FlushFileBuffers() failed");
+ RETURN_OK();
+#else
+ int result;
+ while (1) {
+#if defined(__ANDROID__) && (__ANDROID_API__ < 21)
+ /* Android only has tcdrain from platform 21 onwards.
+ * On previous API versions, use the ioctl directly. */
+ int arg = 1;
+ result = ioctl(port->fd, TCSBRK, &arg);
+#else
+ result = tcdrain(port->fd);
+#endif
+ if (result < 0) {
+ if (errno == EINTR) {
+ DEBUG("tcdrain() was interrupted");
+ continue;
+ } else {
+ RETURN_FAIL("tcdrain() failed");
+ }
+ } else {
+ RETURN_OK();
+ }
+ }
+#endif
+}
+
+#ifdef _WIN32
+static enum sp_return await_write_completion(struct sp_port *port)
+{
+ TRACE("%p", port);
+ DWORD bytes_written;
+ BOOL result;
+
+ /* Wait for previous non-blocking write to complete, if any. */
+ if (port->writing) {
+ DEBUG("Waiting for previous write to complete");
+ result = GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE);
+ port->writing = 0;
+ if (!result)
+ RETURN_FAIL("Previous write failed to complete");
+ DEBUG("Previous write completed");
+ }
+
+ RETURN_OK();
+}
+#endif
+
+SP_API enum sp_return sp_blocking_write(struct sp_port *port, const void *buf,
+ size_t count, unsigned int timeout_ms)
+{
+ TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
+
+ CHECK_OPEN_PORT();
+
+ if (!buf)
+ RETURN_ERROR(SP_ERR_ARG, "Null buffer");
+
+ if (timeout_ms)
+ DEBUG_FMT("Writing %d bytes to port %s, timeout %d ms",
+ count, port->name, timeout_ms);
+ else
+ DEBUG_FMT("Writing %d bytes to port %s, no timeout",
+ count, port->name);
+
+ if (count == 0)
+ RETURN_INT(0);
+
+#ifdef _WIN32
+ DWORD bytes_written = 0;
+
+ TRY(await_write_completion(port));
+
+ /* Set timeout. */
+ if (port->timeouts.WriteTotalTimeoutConstant != timeout_ms) {
+ port->timeouts.WriteTotalTimeoutConstant = timeout_ms;
+ if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
+ RETURN_FAIL("SetCommTimeouts() failed");
+ }
+
+ /* Reduce count if it exceeds the WriteFile limit. */
+ if (count > WRITEFILE_MAX_SIZE)
+ count = WRITEFILE_MAX_SIZE;
+
+ /* Start write. */
+ if (WriteFile(port->hdl, buf, count, NULL, &port->write_ovl)) {
+ DEBUG("Write completed immediately");
+ RETURN_INT(count);
+ } else if (GetLastError() == ERROR_IO_PENDING) {
+ DEBUG("Waiting for write to complete");
+ if (GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE) == 0) {
+ if (GetLastError() == ERROR_SEM_TIMEOUT) {
+ DEBUG("Write timed out");
+ RETURN_INT(0);
+ } else {
+ RETURN_FAIL("GetOverlappedResult() failed");
+ }
+ }
+ DEBUG_FMT("Write completed, %d/%d bytes written", bytes_written, count);
+ RETURN_INT(bytes_written);
+ } else {
+ RETURN_FAIL("WriteFile() failed");
+ }
+#else
+ size_t bytes_written = 0;
+ unsigned char *ptr = (unsigned char *) buf;
+ struct timeval start, delta, now, end = {0, 0};
+ int started = 0;
+ fd_set fds;
+ int result;
+
+ if (timeout_ms) {
+ /* Get time at start of operation. */
+ get_time(&start);
+ /* Define duration of timeout. */
+ delta.tv_sec = timeout_ms / 1000;
+ delta.tv_usec = (timeout_ms % 1000) * 1000;
+ /* Calculate time at which we should give up. */
+ timeradd(&start, &delta, &end);
+ }
+
+ FD_ZERO(&fds);
+ FD_SET(port->fd, &fds);
+
+ /* Loop until we have written the requested number of bytes. */
+ while (bytes_written < count) {
+ /*
+ * Check timeout only if we have run select() at least once,
+ * to avoid any issues if a short timeout is reached before
+ * select() is even run.
+ */
+ if (timeout_ms && started) {
+ get_time(&now);
+ if (timercmp(&now, &end, >))
+ /* Timeout has expired. */
+ break;
+ timersub(&end, &now, &delta);
+ }
+ result = select(port->fd + 1, NULL, &fds, NULL, timeout_ms ? &delta : NULL);
+ started = 1;
+ if (result < 0) {
+ if (errno == EINTR) {
+ DEBUG("select() call was interrupted, repeating");
+ continue;
+ } else {
+ RETURN_FAIL("select() failed");
+ }
+ } else if (result == 0) {
+ /* Timeout has expired. */
+ break;
+ }
+
+ /* Do write. */
+ result = write(port->fd, ptr, count - bytes_written);
+
+ if (result < 0) {
+ if (errno == EAGAIN)
+ /* This shouldn't happen because we did a select() first, but handle anyway. */
+ continue;
+ else
+ /* This is an actual failure. */
+ RETURN_FAIL("write() failed");
+ }
+
+ bytes_written += result;
+ ptr += result;
+ }
+
+ if (bytes_written < count)
+ DEBUG("Write timed out");
+
+ RETURN_INT(bytes_written);
+#endif
+}
+
+SP_API enum sp_return sp_nonblocking_write(struct sp_port *port,
+ const void *buf, size_t count)
+{
+ TRACE("%p, %p, %d", port, buf, count);
+
+ CHECK_OPEN_PORT();
+
+ if (!buf)
+ RETURN_ERROR(SP_ERR_ARG, "Null buffer");
+
+ DEBUG_FMT("Writing up to %d bytes to port %s", count, port->name);
+
+ if (count == 0)
+ RETURN_INT(0);
+
+#ifdef _WIN32
+ DWORD buf_bytes;
+
+ /* Check whether previous write is complete. */
+ if (port->writing) {
+ if (HasOverlappedIoCompleted(&port->write_ovl)) {
+ DEBUG("Previous write completed");
+ port->writing = 0;
+ } else {
+ DEBUG("Previous write not complete");
+ /* Can't take a new write until the previous one finishes. */
+ RETURN_INT(0);
+ }
+ }
+
+ /* Set timeout. */
+ if (port->timeouts.WriteTotalTimeoutConstant != 0) {
+ port->timeouts.WriteTotalTimeoutConstant = 0;
+ if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
+ RETURN_FAIL("SetCommTimeouts() failed");
+ }
+
+ /* Reduce count if it exceeds the WriteFile limit. */
+ if (count > WRITEFILE_MAX_SIZE)
+ count = WRITEFILE_MAX_SIZE;
+
+ /* Copy data to our write buffer. */
+ buf_bytes = min(port->write_buf_size, count);
+ memcpy(port->write_buf, buf, buf_bytes);
+
+ /* Start asynchronous write. */
+ if (WriteFile(port->hdl, port->write_buf, buf_bytes, NULL, &port->write_ovl) == 0) {
+ if (GetLastError() == ERROR_IO_PENDING) {
+ if ((port->writing = !HasOverlappedIoCompleted(&port->write_ovl)))
+ DEBUG("Asynchronous write completed immediately");
+ else
+ DEBUG("Asynchronous write running");
+ } else {
+ /* Actual failure of some kind. */
+ RETURN_FAIL("WriteFile() failed");
+ }
+ }
+
+ DEBUG("All bytes written immediately");
+
+ RETURN_INT(buf_bytes);
+#else
+ /* Returns the number of bytes written, or -1 upon failure. */
+ ssize_t written = write(port->fd, buf, count);
+
+ if (written < 0) {
+ if (errno == EAGAIN)
+ // Buffer is full, no bytes written.
+ RETURN_INT(0);
+ else
+ RETURN_FAIL("write() failed");
+ } else {
+ RETURN_INT(written);
+ }
+#endif
+}
+
+#ifdef _WIN32
+/* Restart wait operation if buffer was emptied. */
+static enum sp_return restart_wait_if_needed(struct sp_port *port, unsigned int bytes_read)
+{
+ DWORD errors;
+ COMSTAT comstat;
+
+ if (bytes_read == 0)
+ RETURN_OK();
+
+ if (ClearCommError(port->hdl, &errors, &comstat) == 0)
+ RETURN_FAIL("ClearCommError() failed");
+
+ if (comstat.cbInQue == 0)
+ TRY(restart_wait(port));
+
+ RETURN_OK();
+}
+#endif
+
+SP_API enum sp_return sp_blocking_read(struct sp_port *port, void *buf,
+ size_t count, unsigned int timeout_ms)
+{
+ TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
+
+ CHECK_OPEN_PORT();
+
+ if (!buf)
+ RETURN_ERROR(SP_ERR_ARG, "Null buffer");
+
+ if (timeout_ms)
+ DEBUG_FMT("Reading %d bytes from port %s, timeout %d ms",
+ count, port->name, timeout_ms);
+ else
+ DEBUG_FMT("Reading %d bytes from port %s, no timeout",
+ count, port->name);
+
+ if (count == 0)
+ RETURN_INT(0);
+
+#ifdef _WIN32
+ DWORD bytes_read = 0;
+
+ /* Set timeout. */
+ if (port->timeouts.ReadIntervalTimeout != 0 ||
+ port->timeouts.ReadTotalTimeoutMultiplier != 0 ||
+ port->timeouts.ReadTotalTimeoutConstant != timeout_ms) {
+ port->timeouts.ReadIntervalTimeout = 0;
+ port->timeouts.ReadTotalTimeoutMultiplier = 0;
+ port->timeouts.ReadTotalTimeoutConstant = timeout_ms;
+ if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
+ RETURN_FAIL("SetCommTimeouts() failed");
+ }
+
+ /* Start read. */
+ if (ReadFile(port->hdl, buf, count, NULL, &port->read_ovl)) {
+ DEBUG("Read completed immediately");
+ bytes_read = count;
+ } else if (GetLastError() == ERROR_IO_PENDING) {
+ DEBUG("Waiting for read to complete");
+ if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE) == 0)
+ RETURN_FAIL("GetOverlappedResult() failed");
+ DEBUG_FMT("Read completed, %d/%d bytes read", bytes_read, count);
+ } else {
+ RETURN_FAIL("ReadFile() failed");
+ }
+
+ TRY(restart_wait_if_needed(port, bytes_read));
+
+ RETURN_INT(bytes_read);
+
+#else
+ size_t bytes_read = 0;
+ unsigned char *ptr = (unsigned char *)buf;
+ struct timeval start, delta, now, end = {0, 0};
+ int started = 0;
+ fd_set fds;
+ int result;
+
+ if (timeout_ms) {
+ /* Get time at start of operation. */
+ get_time(&start);
+ /* Define duration of timeout. */
+ delta.tv_sec = timeout_ms / 1000;
+ delta.tv_usec = (timeout_ms % 1000) * 1000;
+ /* Calculate time at which we should give up. */
+ timeradd(&start, &delta, &end);
+ }
+
+ FD_ZERO(&fds);
+ FD_SET(port->fd, &fds);
+
+ /* Loop until we have the requested number of bytes. */
+ while (bytes_read < count) {
+ /*
+ * Check timeout only if we have run select() at least once,
+ * to avoid any issues if a short timeout is reached before
+ * select() is even run.
+ */
+ if (timeout_ms && started) {
+ get_time(&now);
+ if (timercmp(&now, &end, >))
+ /* Timeout has expired. */
+ break;
+ timersub(&end, &now, &delta);
+ }
+ result = select(port->fd + 1, &fds, NULL, NULL, timeout_ms ? &delta : NULL);
+ started = 1;
+ if (result < 0) {
+ if (errno == EINTR) {
+ DEBUG("select() call was interrupted, repeating");
+ continue;
+ } else {
+ RETURN_FAIL("select() failed");
+ }
+ } else if (result == 0) {
+ /* Timeout has expired. */
+ break;
+ }
+
+ /* Do read. */
+ result = read(port->fd, ptr, count - bytes_read);
+
+ if (result < 0) {
+ if (errno == EAGAIN)
+ /*
+ * This shouldn't happen because we did a
+ * select() first, but handle anyway.
+ */
+ continue;
+ else
+ /* This is an actual failure. */
+ RETURN_FAIL("read() failed");
+ }
+
+ bytes_read += result;
+ ptr += result;
+ }
+
+ if (bytes_read < count)
+ DEBUG("Read timed out");
+
+ RETURN_INT(bytes_read);
+#endif
+}
+
+SP_API enum sp_return sp_blocking_read_next(struct sp_port *port, void *buf,
+ size_t count, unsigned int timeout_ms)
+{
+ TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
+
+ CHECK_OPEN_PORT();
+
+ if (!buf)
+ RETURN_ERROR(SP_ERR_ARG, "Null buffer");
+
+ if (count == 0)
+ RETURN_ERROR(SP_ERR_ARG, "Zero count");
+
+ if (timeout_ms)
+ DEBUG_FMT("Reading next max %d bytes from port %s, timeout %d ms",
+ count, port->name, timeout_ms);
+ else
+ DEBUG_FMT("Reading next max %d bytes from port %s, no timeout",
+ count, port->name);
+
+#ifdef _WIN32
+ DWORD bytes_read = 0;
+
+ /* If timeout_ms == 0, set maximum timeout. */
+ DWORD timeout_val = (timeout_ms == 0 ? MAXDWORD - 1 : timeout_ms);
+
+ /* Set timeout. */
+ if (port->timeouts.ReadIntervalTimeout != MAXDWORD ||
+ port->timeouts.ReadTotalTimeoutMultiplier != MAXDWORD ||
+ port->timeouts.ReadTotalTimeoutConstant != timeout_val) {
+ port->timeouts.ReadIntervalTimeout = MAXDWORD;
+ port->timeouts.ReadTotalTimeoutMultiplier = MAXDWORD;
+ port->timeouts.ReadTotalTimeoutConstant = timeout_val;
+ if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
+ RETURN_FAIL("SetCommTimeouts() failed");
+ }
+
+ /* Loop until we have at least one byte, or timeout is reached. */
+ while (bytes_read == 0) {
+ /* Start read. */
+ if (ReadFile(port->hdl, buf, count, &bytes_read, &port->read_ovl)) {
+ DEBUG("Read completed immediately");
+ } else if (GetLastError() == ERROR_IO_PENDING) {
+ DEBUG("Waiting for read to complete");
+ if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE) == 0)
+ RETURN_FAIL("GetOverlappedResult() failed");
+ if (bytes_read > 0) {
+ DEBUG("Read completed");
+ } else if (timeout_ms > 0) {
+ DEBUG("Read timed out");
+ break;
+ } else {
+ DEBUG("Restarting read");
+ }
+ } else {
+ RETURN_FAIL("ReadFile() failed");
+ }
+ }
+
+ TRY(restart_wait_if_needed(port, bytes_read));
+
+ RETURN_INT(bytes_read);
+
+#else
+ size_t bytes_read = 0;
+ struct timeval start, delta, now, end = {0, 0};
+ int started = 0;
+ fd_set fds;
+ int result;
+
+ if (timeout_ms) {
+ /* Get time at start of operation. */
+ get_time(&start);
+ /* Define duration of timeout. */
+ delta.tv_sec = timeout_ms / 1000;
+ delta.tv_usec = (timeout_ms % 1000) * 1000;
+ /* Calculate time at which we should give up. */
+ timeradd(&start, &delta, &end);
+ }
+
+ FD_ZERO(&fds);
+ FD_SET(port->fd, &fds);
+
+ /* Loop until we have at least one byte, or timeout is reached. */
+ while (bytes_read == 0) {
+ /*
+ * Check timeout only if we have run select() at least once,
+ * to avoid any issues if a short timeout is reached before
+ * select() is even run.
+ */
+ if (timeout_ms && started) {
+ get_time(&now);
+ if (timercmp(&now, &end, >))
+ /* Timeout has expired. */
+ break;
+ timersub(&end, &now, &delta);
+ }
+ result = select(port->fd + 1, &fds, NULL, NULL, timeout_ms ? &delta : NULL);
+ started = 1;
+ if (result < 0) {
+ if (errno == EINTR) {
+ DEBUG("select() call was interrupted, repeating");
+ continue;
+ } else {
+ RETURN_FAIL("select() failed");
+ }
+ } else if (result == 0) {
+ /* Timeout has expired. */
+ break;
+ }
+
+ /* Do read. */
+ result = read(port->fd, buf, count);
+
+ if (result < 0) {
+ if (errno == EAGAIN)
+ /* This shouldn't happen because we did a select() first, but handle anyway. */
+ continue;
+ else
+ /* This is an actual failure. */
+ RETURN_FAIL("read() failed");
+ }
+
+ bytes_read = result;
+ }
+
+ if (bytes_read == 0)
+ DEBUG("Read timed out");
+
+ RETURN_INT(bytes_read);
+#endif
+}
+
+SP_API enum sp_return sp_nonblocking_read(struct sp_port *port, void *buf,
+ size_t count)
+{
+ TRACE("%p, %p, %d", port, buf, count);
+
+ CHECK_OPEN_PORT();