+#ifdef WIN32
+/** To be called after port receive buffer is emptied. */
+static enum sp_return restart_wait(struct sp_port *port)
+{
+ DWORD wait_result;
+
+ if (port->wait_running) {
+ /* Check status of running wait operation. */
+ if (GetOverlappedResult(port->hdl, &port->wait_ovl,
+ &wait_result, FALSE)) {
+ DEBUG("Previous wait completed");
+ port->wait_running = FALSE;
+ } else if (GetLastError() == ERROR_IO_INCOMPLETE) {
+ DEBUG("Previous wait still running");
+ RETURN_OK();
+ } else {
+ RETURN_FAIL("GetOverlappedResult() failed");
+ }
+ }
+
+ if (!port->wait_running) {
+ /* Start new wait operation. */
+ if (WaitCommEvent(port->hdl, &port->events,
+ &port->wait_ovl)) {
+ DEBUG("New wait returned, events already pending");
+ } else if (GetLastError() == ERROR_IO_PENDING) {
+ DEBUG("New wait running in background");
+ port->wait_running = TRUE;
+ } else {
+ RETURN_FAIL("WaitCommEvent() failed");
+ }
+ }
+
+ RETURN_OK();
+}
+#endif
+
+SP_API enum sp_return sp_open(struct sp_port *port, enum sp_mode flags)
+{
+ struct port_data data;
+ struct sp_port_config config;
+ enum sp_return ret;
+
+ TRACE("%p, 0x%x", port, flags);
+
+ CHECK_PORT();
+
+ if (flags > SP_MODE_READ_WRITE)
+ RETURN_ERROR(SP_ERR_ARG, "Invalid flags");
+
+ DEBUG_FMT("Opening port %s", port->name);
+
+#ifdef _WIN32
+ DWORD desired_access = 0, flags_and_attributes = 0, errors;
+ char *escaped_port_name;
+ COMSTAT status;
+
+ /* Prefix port name with '\\.\' to work with ports above COM9. */
+ if (!(escaped_port_name = malloc(strlen(port->name) + 5)))
+ RETURN_ERROR(SP_ERR_MEM, "Escaped port name malloc failed");
+ sprintf(escaped_port_name, "\\\\.\\%s", port->name);
+
+ /* Map 'flags' to the OS-specific settings. */
+ flags_and_attributes = FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED;
+ if (flags & SP_MODE_READ)
+ desired_access |= GENERIC_READ;
+ if (flags & SP_MODE_WRITE)
+ desired_access |= GENERIC_WRITE;
+
+ port->hdl = CreateFileA(escaped_port_name, desired_access, 0, 0,
+ OPEN_EXISTING, flags_and_attributes, 0);
+
+ free(escaped_port_name);
+
+ if (port->hdl == INVALID_HANDLE_VALUE)
+ RETURN_FAIL("Port CreateFile() failed");
+
+ /* All timeouts initially disabled. */
+ port->timeouts.ReadIntervalTimeout = 0;
+ port->timeouts.ReadTotalTimeoutMultiplier = 0;
+ port->timeouts.ReadTotalTimeoutConstant = 0;
+ port->timeouts.WriteTotalTimeoutMultiplier = 0;
+ port->timeouts.WriteTotalTimeoutConstant = 0;
+
+ if (SetCommTimeouts(port->hdl, &port->timeouts) == 0) {
+ sp_close(port);
+ RETURN_FAIL("SetCommTimeouts() failed");
+ }
+
+ /* Prepare OVERLAPPED structures. */
+#define INIT_OVERLAPPED(ovl) do { \
+ memset(&port->ovl, 0, sizeof(port->ovl)); \
+ port->ovl.hEvent = INVALID_HANDLE_VALUE; \
+ if ((port->ovl.hEvent = CreateEvent(NULL, TRUE, TRUE, NULL)) \
+ == INVALID_HANDLE_VALUE) { \
+ sp_close(port); \
+ RETURN_FAIL(#ovl "CreateEvent() failed"); \
+ } \
+} while (0)
+
+ INIT_OVERLAPPED(read_ovl);
+ INIT_OVERLAPPED(write_ovl);
+ INIT_OVERLAPPED(wait_ovl);
+
+ /* Set event mask for RX and error events. */
+ if (SetCommMask(port->hdl, EV_RXCHAR | EV_ERR) == 0) {
+ sp_close(port);
+ RETURN_FAIL("SetCommMask() failed");
+ }
+
+ port->writing = FALSE;
+ port->wait_running = FALSE;
+
+ ret = restart_wait(port);
+
+ if (ret < 0) {
+ sp_close(port);
+ RETURN_CODEVAL(ret);
+ }
+#else
+ int flags_local = O_NONBLOCK | O_NOCTTY | O_CLOEXEC;
+
+ /* Map 'flags' to the OS-specific settings. */
+ if ((flags & SP_MODE_READ_WRITE) == SP_MODE_READ_WRITE)
+ flags_local |= O_RDWR;
+ else if (flags & SP_MODE_READ)
+ flags_local |= O_RDONLY;
+ else if (flags & SP_MODE_WRITE)
+ flags_local |= O_WRONLY;
+
+ if ((port->fd = open(port->name, flags_local)) < 0)
+ RETURN_FAIL("open() failed");
+
+ /*
+ * On POSIX in the default case the file descriptor of a serial port
+ * is not opened exclusively. Therefore the settings of a port are
+ * overwritten if the serial port is opened a second time. Windows
+ * opens all serial ports exclusively.
+ * So the idea is to open the serial ports alike in the exclusive mode.
+ *
+ * ioctl(*, TIOCEXCL) defines the file descriptor as exclusive. So all
+ * further open calls on the serial port will fail.
+ *
+ * There is a race condition if two processes open the same serial
+ * port. None of the processes will notice the exclusive ownership of
+ * the other process because ioctl() doesn't return an error code if
+ * the file descriptor is already marked as exclusive.
+ * This can be solved with flock(). It returns an error if the file
+ * descriptor is already locked by another process.
+ */
+#ifdef HAVE_FLOCK
+ if (flock(port->fd, LOCK_EX | LOCK_NB) < 0)
+ RETURN_FAIL("flock() failed");
+#endif
+
+#ifdef TIOCEXCL
+ /*
+ * Before Linux 3.8 ioctl(*, TIOCEXCL) was not implemented and could
+ * lead to EINVAL or ENOTTY.
+ * These errors aren't fatal and can be ignored.
+ */
+ if (ioctl(port->fd, TIOCEXCL) < 0 && errno != EINVAL && errno != ENOTTY)
+ RETURN_FAIL("ioctl() failed");
+#endif
+
+#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 remaining_ms, write_size, bytes_written;
+ size_t remaining_bytes, total_bytes_written = 0;
+ const uint8_t *write_ptr = (uint8_t *) buf;
+ bool result;
+ struct timeout timeout;
+
+ timeout_start(&timeout, timeout_ms);
+
+ TRY(await_write_completion(port));
+
+ while (total_bytes_written < count) {
+
+ if (timeout_check(&timeout))
+ break;
+
+ remaining_ms = timeout_remaining_ms(&timeout);
+
+ if (port->timeouts.WriteTotalTimeoutConstant != remaining_ms) {
+ port->timeouts.WriteTotalTimeoutConstant = remaining_ms;
+ if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
+ RETURN_FAIL("SetCommTimeouts() failed");
+ }
+
+ /* Reduce write size if it exceeds the WriteFile limit. */
+ remaining_bytes = count - total_bytes_written;
+ if (remaining_bytes > WRITEFILE_MAX_SIZE)
+ write_size = WRITEFILE_MAX_SIZE;
+ else
+ write_size = (DWORD) remaining_bytes;
+
+ /* Start write. */
+
+ result = WriteFile(port->hdl, write_ptr, write_size, NULL, &port->write_ovl);
+
+ timeout_update(&timeout);
+
+ if (result) {
+ DEBUG("Write completed immediately");
+ bytes_written = write_size;
+ } 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");
+ break;
+ } else {
+ RETURN_FAIL("GetOverlappedResult() failed");
+ }
+ }
+ DEBUG_FMT("Write completed, %d/%d bytes written", bytes_written, write_size);
+ } else {
+ RETURN_FAIL("WriteFile() failed");
+ }
+
+ write_ptr += bytes_written;
+ total_bytes_written += bytes_written;
+ }
+
+ RETURN_INT((int) total_bytes_written);
+#else
+ size_t bytes_written = 0;
+ unsigned char *ptr = (unsigned char *) buf;
+ struct timeout timeout;
+ fd_set fds;
+ int result;
+
+ timeout_start(&timeout, timeout_ms);
+
+ FD_ZERO(&fds);
+ FD_SET(port->fd, &fds);
+
+ /* Loop until we have written the requested number of bytes. */
+ while (bytes_written < count) {
+
+ if (timeout_check(&timeout))
+ break;
+
+ result = select(port->fd + 1, NULL, &fds, NULL, timeout_timeval(&timeout));
+
+ timeout_update(&timeout);
+
+ 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
+ size_t 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, (DWORD) 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((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;
+
+ /* 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, (DWORD) count, NULL, &port->read_ovl)) {
+ DEBUG("Read completed immediately");
+ bytes_read = (DWORD) 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((int) bytes_read);
+
+#else
+ size_t bytes_read = 0;
+ unsigned char *ptr = (unsigned char *) buf;
+ struct timeout timeout;
+ fd_set fds;
+ int result;
+
+ timeout_start(&timeout, timeout_ms);
+
+ FD_ZERO(&fds);
+ FD_SET(port->fd, &fds);
+
+ /* Loop until we have the requested number of bytes. */
+ while (bytes_read < count) {
+
+ if (timeout_check(&timeout))
+ /* Timeout has expired. */
+ break;
+
+ result = select(port->fd + 1, &fds, NULL, NULL, timeout_timeval(&timeout));
+
+ timeout_update(&timeout);
+
+ 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, (DWORD) 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));