]> sigrok.org Git - libserialport.git/blobdiff - serialport.c
Implement non-blocking I/O on Windows.
[libserialport.git] / serialport.c
index 1b1be34fd555956f776d44896fbd40d8de7a97cf..a57f1773b856d6d569b337cce8722f604db2c437 100644 (file)
 
 #include "libserialport.h"
 
+struct sp_port {
+       char *name;
+       int nonblocking;
+#ifdef _WIN32
+       HANDLE hdl;
+       OVERLAPPED write_ovl;
+       BYTE *write_buf;
+       BOOL writing;
+#else
+       int fd;
+#endif
+};
+
+struct sp_port_config {
+       int baudrate;
+       int bits;
+       enum sp_parity parity;
+       int stopbits;
+       enum sp_rts rts;
+       enum sp_cts cts;
+       enum sp_dtr dtr;
+       enum sp_dsr dsr;
+       enum sp_xonxoff xon_xoff;
+};
+
 struct port_data {
 #ifdef _WIN32
        DCB dcb;
@@ -108,8 +133,6 @@ void (*sp_debug_handler)(const char *format, ...) = sp_default_debug_handler;
 #define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))
 #define NUM_STD_BAUDRATES ARRAY_SIZE(std_baudrates)
 
-#define TRY(x) do { int ret = x; if (ret != SP_OK) return ret; } while (0)
-
 /* Debug output macros. */
 #define DEBUG(fmt, ...) do { if (sp_debug_handler) sp_debug_handler(fmt ".\n", ##__VA_ARGS__); } while (0)
 #define DEBUG_ERROR(err, msg) DEBUG("%s returning " #err ": " msg, __func__)
@@ -134,9 +157,11 @@ void (*sp_debug_handler)(const char *format, ...) = sp_default_debug_handler;
 #define RETURN_FAIL(msg) do { DEBUG_FAIL(msg); return SP_ERR_FAIL; } while (0)
 #define RETURN_VALUE(fmt, x) do { DEBUG("%s returning " fmt, __func__, x); return x; } while (0)
 #define SET_ERROR(val, err, msg) do { DEBUG_ERROR(err, msg); val = err; } while (0)
-#define SET_FAIL(val, msg) do { DEBUG_FAIL(msg); val = err; } while (0)
+#define SET_FAIL(val, msg) do { DEBUG_FAIL(msg); val = SP_ERR_FAIL; } while (0)
 #define TRACE(fmt, ...) DEBUG("%s(" fmt ") called", __func__, ##__VA_ARGS__)
 
+#define TRY(x) do { int ret = x; if (ret != SP_OK) RETURN_CODEVAL(ret); } while (0)
+
 /* Helper functions. */
 static struct sp_port **list_append(struct sp_port **list, const char *portname);
 static enum sp_return get_config(struct sp_port *port, struct port_data *data,
@@ -159,6 +184,8 @@ enum sp_return sp_get_port_by_name(const char *portname, struct sp_port **port_p
        if (!portname)
                RETURN_ERROR(SP_ERR_ARG, "Null port name");
 
+       DEBUG("Building structure for port %s", portname);
+
        if (!(port = malloc(sizeof(struct sp_port))))
                RETURN_ERROR(SP_ERR_MEM, "Port structure malloc failed");
 
@@ -182,6 +209,34 @@ enum sp_return sp_get_port_by_name(const char *portname, struct sp_port **port_p
        RETURN_OK();
 }
 
+char *sp_get_port_name(const struct sp_port *port)
+{
+       TRACE("%p", port);
+
+       if (!port)
+               return NULL;
+
+       RETURN_VALUE("%s", port->name);
+}
+
+enum sp_return sp_get_port_handle(const struct sp_port *port, void *result_ptr)
+{
+       TRACE("%p", port);
+
+       if (!port)
+               RETURN_ERROR(SP_ERR_ARG, "Null port");
+
+#ifdef _WIN32
+       HANDLE *handle_ptr = result_ptr;
+       *handle_ptr = port->hdl;
+#else
+       int *fd_ptr = result_ptr;
+       *fd_ptr = port->fd;
+#endif
+
+       RETURN_OK();
+}
+
 enum sp_return sp_copy_port(const struct sp_port *port, struct sp_port **copy_ptr)
 {
        TRACE("%p, %p", port, copy_ptr);
@@ -197,6 +252,8 @@ enum sp_return sp_copy_port(const struct sp_port *port, struct sp_port **copy_pt
        if (!port->name)
                RETURN_ERROR(SP_ERR_ARG, "Null port name");
 
+       DEBUG("Copying port structure");
+
        RETURN_VALUE("%p", sp_get_port_by_name(port->name, copy_ptr));
 }
 
@@ -210,6 +267,8 @@ void sp_free_port(struct sp_port *port)
                RETURN();
        }
 
+       DEBUG("Freeing port structure");
+
        if (port->name)
                free(port->name);
 
@@ -240,10 +299,15 @@ fail:
 enum sp_return sp_list_ports(struct sp_port ***list_ptr)
 {
        struct sp_port **list;
-       int ret = SP_OK;
+       int ret = SP_ERR_SUPP;
 
        TRACE("%p", list_ptr);
 
+       if (!list_ptr)
+               RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
+
+       DEBUG("Enumerating ports");
+
        if (!(list = malloc(sizeof(struct sp_port **))))
                RETURN_ERROR(SP_ERR_MEM, "Port list malloc failed");
 
@@ -258,11 +322,15 @@ enum sp_return sp_list_ports(struct sp_port ***list_ptr)
        char *name;
        int name_len;
 
+       ret = SP_OK;
+
+       DEBUG("Opening registry key");
        if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("HARDWARE\\DEVICEMAP\\SERIALCOMM"),
                        0, KEY_QUERY_VALUE, &key) != ERROR_SUCCESS) {
                SET_FAIL(ret, "RegOpenKeyEx() failed");
                goto out_done;
        }
+       DEBUG("Querying registry key value and data sizes");
        if (RegQueryInfoKey(key, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
                                &max_value_len, &max_data_size, NULL, NULL) != ERROR_SUCCESS) {
                SET_FAIL(ret, "RegQueryInfoKey() failed");
@@ -277,6 +345,7 @@ enum sp_return sp_list_ports(struct sp_port ***list_ptr)
                SET_ERROR(ret, SP_ERR_MEM, "registry data malloc failed");
                goto out_free_value;
        }
+       DEBUG("Iterating over values");
        while (
                value_len = max_value_len + 1,
                data_size = max_data_size,
@@ -325,11 +394,15 @@ out_done:
        CFTypeRef cf_path;
        Boolean result;
 
+       ret = SP_OK;
+
+       DEBUG("Getting IOKit master port");
        if (IOMasterPort(MACH_PORT_NULL, &master) != KERN_SUCCESS) {
                SET_FAIL(ret, "IOMasterPort() failed");
                goto out_done;
        }
 
+       DEBUG("Creating matching dictionary");
        if (!(classes = IOServiceMatching(kIOSerialBSDServiceValue))) {
                SET_FAIL(ret, "IOServiceMatching() failed");
                goto out_done;
@@ -338,6 +411,7 @@ out_done:
        CFDictionarySetValue(classes,
                        CFSTR(kIOSerialBSDTypeKey), CFSTR(kIOSerialBSDAllTypes));
 
+       DEBUG("Getting matching services");
        if (IOServiceGetMatchingServices(master, classes, &iter) != KERN_SUCCESS) {
                SET_FAIL(ret, "IOServiceGetMatchingServices() failed");
                goto out_done;
@@ -348,6 +422,7 @@ out_done:
                goto out_release;
        }
 
+       DEBUG("Iterating over results");
        while ((port = IOIteratorNext(iter))) {
                cf_path = IORegistryEntryCreateCFProperty(port,
                                CFSTR(kIOCalloutDeviceKey), kCFAllocatorDefault, 0);
@@ -384,17 +459,23 @@ out_done:
        int fd, ioctl_result;
        struct serial_struct serial_info;
 
+       ret = SP_OK;
+
+       DEBUG("Enumerating tty devices");
        ud = udev_new();
        ud_enumerate = udev_enumerate_new(ud);
        udev_enumerate_add_match_subsystem(ud_enumerate, "tty");
        udev_enumerate_scan_devices(ud_enumerate);
        ud_list = udev_enumerate_get_list_entry(ud_enumerate);
+       DEBUG("Iterating over results");
        udev_list_entry_foreach(ud_entry, ud_list) {
                path = udev_list_entry_get_name(ud_entry);
+               DEBUG("Found device %s", path);
                ud_dev = udev_device_new_from_syspath(ud, path);
                /* If there is no parent device, this is a virtual tty. */
                ud_parent = udev_device_get_parent(ud_dev);
                if (ud_parent == NULL) {
+                       DEBUG("No parent device, assuming virtual tty");
                        udev_device_unref(ud_dev);
                        continue;
                }
@@ -404,14 +485,21 @@ out_done:
                 * is to try to open them and make an ioctl call. */
                driver = udev_device_get_driver(ud_parent);
                if (driver && !strcmp(driver, "serial8250")) {
-                       if ((fd = open(name, O_RDWR | O_NONBLOCK | O_NOCTTY)) < 0)
+                       DEBUG("serial8250 device, attempting to open");
+                       if ((fd = open(name, O_RDWR | O_NONBLOCK | O_NOCTTY)) < 0) {
+                               DEBUG("open failed, skipping");
                                goto skip;
+                       }
                        ioctl_result = ioctl(fd, TIOCGSERIAL, &serial_info);
                        close(fd);
-                       if (ioctl_result != 0)
+                       if (ioctl_result != 0) {
+                               DEBUG("ioctl failed, skipping");
                                goto skip;
-                       if (serial_info.type == PORT_UNKNOWN)
+                       }
+                       if (serial_info.type == PORT_UNKNOWN) {
+                               DEBUG("port type is unknown, skipping");
                                goto skip;
+                       }
                }
                DEBUG("Found port %s", name);
                list = list_append(list, name);
@@ -427,10 +515,13 @@ out:
        udev_unref(ud);
 #endif
 
-       if (ret == SP_OK) {
+       switch (ret) {
+       case SP_OK:
                *list_ptr = list;
                RETURN_OK();
-       } else {
+       case SP_ERR_SUPP:
+               DEBUG_ERROR(SP_ERR_SUPP, "Enumeration not supported on this platform.");
+       default:
                if (list)
                        sp_free_port_list(list);
                *list_ptr = NULL;
@@ -444,6 +535,13 @@ void sp_free_port_list(struct sp_port **list)
 
        TRACE("%p", list);
 
+       if (!list) {
+               DEBUG("Null list");
+               RETURN();
+       }
+
+       DEBUG("Freeing port list");
+
        for (i = 0; list[i]; i++)
                sp_free_port(list[i]);
        free(list);
@@ -451,31 +549,44 @@ void sp_free_port_list(struct sp_port **list)
        RETURN();
 }
 
-#ifdef _WIN32
 #define CHECK_PORT() do { \
        if (port == NULL) \
                RETURN_ERROR(SP_ERR_ARG, "Null port"); \
+       if (port->name == NULL) \
+               RETURN_ERROR(SP_ERR_ARG, "Null port name"); \
+} while (0)
+#ifdef _WIN32
+#define CHECK_PORT_HANDLE() do { \
        if (port->hdl == INVALID_HANDLE_VALUE) \
                RETURN_ERROR(SP_ERR_ARG, "Invalid port handle"); \
-} while(0);
+} while (0)
 #else
-#define CHECK_PORT() do { \
-       if (port == NULL) \
-               RETURN_ERROR(SP_ERR_ARG, "Null port"); \
+#define CHECK_PORT_HANDLE() do { \
        if (port->fd < 0) \
                RETURN_ERROR(SP_ERR_ARG, "Invalid port fd"); \
-} while(0);
+} while (0)
 #endif
+#define CHECK_OPEN_PORT() do { \
+       CHECK_PORT(); \
+       CHECK_PORT_HANDLE(); \
+} while (0)
 
 enum sp_return sp_open(struct sp_port *port, enum sp_mode flags)
 {
        TRACE("%p, %x", port, flags);
 
-       if (!port)
-               RETURN_ERROR(SP_ERR_ARG, "Null port");
+       CHECK_PORT();
+
+       if (flags > (SP_MODE_READ | SP_MODE_WRITE | SP_MODE_NONBLOCK))
+               RETURN_ERROR(SP_ERR_ARG, "Invalid flags");
+
+       DEBUG("Opening port %s", port->name);
+
+       port->nonblocking = (flags & SP_MODE_NONBLOCK) ? 1 : 0;
 
 #ifdef _WIN32
        DWORD desired_access = 0, flags_and_attributes = 0;
+       COMMTIMEOUTS timeouts;
        char *escaped_port_name;
 
        /* Prefix port name with '\\.\' to work with ports above COM9. */
@@ -499,6 +610,31 @@ enum sp_return sp_open(struct sp_port *port, enum sp_mode flags)
 
        if (port->hdl == INVALID_HANDLE_VALUE)
                RETURN_FAIL("CreateFile() failed");
+
+       /* All timeouts disabled. */
+       timeouts.ReadIntervalTimeout = 0;
+       timeouts.ReadTotalTimeoutMultiplier = 0;
+       timeouts.ReadTotalTimeoutConstant = 0;
+       timeouts.WriteTotalTimeoutMultiplier = 0;
+       timeouts.WriteTotalTimeoutConstant = 0;
+
+       if (port->nonblocking) {
+               /* Set read timeout such that all reads return immediately. */
+               timeouts.ReadIntervalTimeout = MAXDWORD;
+               /* Prepare OVERLAPPED structure for non-blocking writes. */
+               memset(&port->write_ovl, 0, sizeof(port->write_ovl));
+               if (!(port->write_ovl.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL))) {
+                       sp_close(port);
+                       RETURN_FAIL("CreateEvent() failed");
+               }
+               port->write_buf = NULL;
+               port->writing = FALSE;
+       }
+
+       if (SetCommTimeouts(port->hdl, &timeouts) == 0) {
+               sp_close(port);
+               RETURN_FAIL("SetCommTimeouts() failed");
+       }
 #else
        int flags_local = 0;
        struct port_data data;
@@ -552,13 +688,23 @@ enum sp_return sp_close(struct sp_port *port)
 {
        TRACE("%p", port);
 
-       CHECK_PORT();
+       CHECK_OPEN_PORT();
+
+       DEBUG("Closing port %s", port->name);
 
 #ifdef _WIN32
        /* Returns non-zero upon success, 0 upon failure. */
        if (CloseHandle(port->hdl) == 0)
                RETURN_FAIL("CloseHandle() failed");
        port->hdl = INVALID_HANDLE_VALUE;
+       if (port->nonblocking) {
+               if (port->writing)
+                       /* Write should have been stopped by closing the port, so safe to free buffer. */
+                       free(port->write_buf);
+               /* Close event handle created for overlapped writes. */
+               if (CloseHandle(port->write_ovl.hEvent) == 0)
+                       RETURN_FAIL("CloseHandle() failed");
+       }
 #else
        /* Returns 0 upon success, -1 upon failure. */
        if (close(port->fd) == -1)
@@ -573,7 +719,14 @@ enum sp_return sp_flush(struct sp_port *port, enum sp_buffer buffers)
 {
        TRACE("%p, %x", port, buffers);
 
-       CHECK_PORT();
+       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("Flushing %s buffers on port %s", buffer_names[buffers], port->name);
 
 #ifdef _WIN32
        DWORD flags = 0;
@@ -605,7 +758,9 @@ enum sp_return sp_drain(struct sp_port *port)
 {
        TRACE("%p", port);
 
-       CHECK_PORT();
+       CHECK_OPEN_PORT();
+
+       DEBUG("Draining port %s", port->name);
 
 #ifdef _WIN32
        /* Returns non-zero upon success, 0 upon failure. */
@@ -624,17 +779,66 @@ enum sp_return sp_write(struct sp_port *port, const void *buf, size_t count)
 {
        TRACE("%p, %p, %d", port, buf, count);
 
-       CHECK_PORT();
+       CHECK_OPEN_PORT();
 
        if (!buf)
                RETURN_ERROR(SP_ERR_ARG, "Null buffer");
 
+       DEBUG("Writing up to %d bytes to port %s", count, port->name);
+
+       if (count == 0)
+               RETURN_VALUE("0", 0);
+
 #ifdef _WIN32
        DWORD written = 0;
 
-       /* Returns non-zero upon success, 0 upon failure. */
-       if (WriteFile(port->hdl, buf, count, &written, NULL) == 0)
-               RETURN_FAIL("WriteFile() failed");
+       if (port->nonblocking) {
+               /* Non-blocking write. */
+
+               /* Check whether previous write is complete. */
+               if (port->writing) {
+                       if (HasOverlappedIoCompleted(&port->write_ovl)) {
+                               DEBUG("Previous write completed");
+                               port->writing = 0;
+                               free(port->write_buf);
+                               port->write_buf = NULL;
+                       } else {
+                               DEBUG("Previous write not complete");
+                               /* Can't take a new write until the previous one finishes. */
+                               RETURN_VALUE("0", 0);
+                       }
+               }
+
+               /* Copy user buffer. */
+               if (!(port->write_buf = malloc(count)))
+                       RETURN_ERROR(SP_ERR_MEM, "buffer copy malloc failed");
+               memcpy(port->write_buf, buf, count);
+
+               /* Start asynchronous write. */
+               if (WriteFile(port->hdl, buf, count, NULL, &port->write_ovl) == 0) {
+                       if (GetLastError() == ERROR_IO_PENDING) {
+                               DEBUG("Asynchronous write started");
+                               port->writing = 1;
+                               RETURN_VALUE("%d", count);
+                       } else {
+                               free(port->write_buf);
+                               port->write_buf = NULL;
+                               /* Actual failure of some kind. */
+                               RETURN_FAIL("WriteFile() failed");
+                       }
+               } else {
+                       DEBUG("Write completed immediately");
+                       free(port->write_buf);
+                       port->write_buf = NULL;
+                       RETURN_VALUE("%d", count);
+               }
+       } else {
+               /* Blocking write. */
+               if (WriteFile(port->hdl, buf, count, &written, NULL) == 0) {
+                       RETURN_FAIL("WriteFile() failed");
+               }
+       }
+
        RETURN_VALUE("%d", written);
 #else
        /* Returns the number of bytes written, or -1 upon failure. */
@@ -651,11 +855,13 @@ enum sp_return sp_read(struct sp_port *port, void *buf, size_t count)
 {
        TRACE("%p, %p, %d", port, buf, count);
 
-       CHECK_PORT();
+       CHECK_OPEN_PORT();
 
        if (!buf)
                RETURN_ERROR(SP_ERR_ARG, "Null buffer");
 
+       DEBUG("Reading up to %d bytes from port %s", count, port->name);
+
 #ifdef _WIN32
        DWORD bytes_read = 0;
 
@@ -667,8 +873,14 @@ enum sp_return sp_read(struct sp_port *port, void *buf, size_t count)
        ssize_t bytes_read;
 
        /* Returns the number of bytes read, or -1 upon failure. */
-       if ((bytes_read = read(port->fd, buf, count)) < 0)
-               RETURN_FAIL("read() failed");
+       if ((bytes_read = read(port->fd, buf, count)) < 0) {
+               if (port->nonblocking && errno == EAGAIN)
+                       /* Port is opened in nonblocking mode and there are no bytes available. */
+                       bytes_read = 0;
+               else
+                       /* This is an actual failure. */
+                       RETURN_FAIL("read() failed");
+       }
        RETURN_VALUE("%d", bytes_read);
 #endif
 }
@@ -680,6 +892,8 @@ static enum sp_return get_baudrate(int fd, int *baudrate)
 
        TRACE("%d, %p", fd, baudrate);
 
+       DEBUG("Getting baud rate");
+
        if (!(data = malloc(get_termios_size())))
                RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
 
@@ -701,6 +915,8 @@ static enum sp_return set_baudrate(int fd, int baudrate)
 
        TRACE("%d, %d", fd, baudrate);
 
+       DEBUG("Getting baud rate");
+
        if (!(data = malloc(get_termios_size())))
                RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
 
@@ -709,6 +925,8 @@ static enum sp_return set_baudrate(int fd, int baudrate)
                RETURN_FAIL("getting termios failed");
        }
 
+       DEBUG("Setting baud rate");
+
        set_termios_speed(data, baudrate);
 
        if (ioctl(fd, get_termios_set_ioctl(), data) < 0) {
@@ -728,6 +946,8 @@ static enum sp_return get_flow(int fd, int *flow)
 
        TRACE("%d, %p", fd, flow);
 
+       DEBUG("Getting advanced flow control");
+
        if (!(data = malloc(get_termiox_size())))
                RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
 
@@ -749,6 +969,8 @@ static enum sp_return set_flow(int fd, int flow)
 
        TRACE("%d, %d", fd, flow);
 
+       DEBUG("Getting advanced flow control");
+
        if (!(data = malloc(get_termiox_size())))
                RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
 
@@ -757,6 +979,8 @@ static enum sp_return set_flow(int fd, int flow)
                RETURN_FAIL("getting termiox failed");
        }
 
+       DEBUG("Setting advanced flow control");
+
        set_termiox_flow(data, flow);
 
        if (ioctl(fd, TCSETX, data) < 0) {
@@ -778,6 +1002,8 @@ static enum sp_return get_config(struct sp_port *port, struct port_data *data,
 
        TRACE("%p, %p, %p", port, data, config);
 
+       DEBUG("Getting configuration for port %s", port->name);
+
 #ifdef _WIN32
        if (!GetCommState(port->hdl, &data->dcb))
                RETURN_FAIL("GetCommState() failed");
@@ -983,6 +1209,8 @@ static enum sp_return set_config(struct sp_port *port, struct port_data *data,
 
        TRACE("%p, %p, %p", port, data, config);
 
+       DEBUG("Setting configuration for port %s", port->name);
+
 #ifdef _WIN32
        if (config->baudrate >= 0) {
                for (i = 0; i < NUM_STD_BAUDRATES; i++) {
@@ -1329,6 +1557,61 @@ static enum sp_return set_config(struct sp_port *port, struct port_data *data,
        RETURN_OK();
 }
 
+enum sp_return sp_new_config(struct sp_port_config **config_ptr)
+{
+       TRACE("%p", config_ptr);
+       struct sp_port_config *config;
+
+       if (!config_ptr)
+               RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
+
+       *config_ptr = NULL;
+
+       if (!(config = malloc(sizeof(struct sp_port_config))))
+               RETURN_ERROR(SP_ERR_MEM, "config malloc failed");
+
+       config->baudrate = -1;
+       config->bits = -1;
+       config->parity = -1;
+       config->stopbits = -1;
+       config->rts = -1;
+       config->cts = -1;
+       config->dtr = -1;
+       config->dsr = -1;
+
+       *config_ptr = config;
+
+       RETURN_OK();
+}
+
+void sp_free_config(struct sp_port_config *config)
+{
+       TRACE("%p", config);
+
+       if (!config)
+               DEBUG("Null config");
+       else
+               free(config);
+
+       RETURN();
+}
+
+enum sp_return sp_get_config(struct sp_port *port, struct sp_port_config *config)
+{
+       struct port_data data;
+
+       TRACE("%p, %p", port, config);
+
+       CHECK_OPEN_PORT();
+
+       if (!config)
+               RETURN_ERROR(SP_ERR_ARG, "Null config");
+
+       TRY(get_config(port, &data, config));
+
+       RETURN_OK();
+}
+
 enum sp_return sp_set_config(struct sp_port *port, const struct sp_port_config *config)
 {
        struct port_data data;
@@ -1336,7 +1619,7 @@ enum sp_return sp_set_config(struct sp_port *port, const struct sp_port_config *
 
        TRACE("%p, %p", port, config);
 
-       CHECK_PORT();
+       CHECK_OPEN_PORT();
 
        if (!config)
                RETURN_ERROR(SP_ERR_ARG, "Null config");
@@ -1347,61 +1630,89 @@ enum sp_return sp_set_config(struct sp_port *port, const struct sp_port_config *
        RETURN_OK();
 }
 
-#define CREATE_SETTER(x, type) int sp_set_##x(struct sp_port *port, type x) { \
+#define CREATE_ACCESSORS(x, type) \
+enum sp_return sp_set_##x(struct sp_port *port, type x) { \
        struct port_data data; \
        struct sp_port_config config; \
        TRACE("%p, %d", port, x); \
-       CHECK_PORT(); \
+       CHECK_OPEN_PORT(); \
        TRY(get_config(port, &data, &config)); \
        config.x = x; \
        TRY(set_config(port, &data, &config)); \
        RETURN_OK(); \
+} \
+enum sp_return sp_get_config_##x(const struct sp_port_config *config, type *x) { \
+       TRACE("%p", config); \
+       if (!config) \
+               RETURN_ERROR(SP_ERR_ARG, "Null config"); \
+       *x = config->x; \
+       RETURN_OK(); \
+} \
+enum sp_return sp_set_config_##x(struct sp_port_config *config, type x) { \
+       TRACE("%p, %d", config, x); \
+       if (!config) \
+               RETURN_ERROR(SP_ERR_ARG, "Null config"); \
+       config->x = x; \
+       RETURN_OK(); \
 }
 
-CREATE_SETTER(baudrate, int)
-CREATE_SETTER(bits, int)
-CREATE_SETTER(parity, enum sp_parity)
-CREATE_SETTER(stopbits, int)
-CREATE_SETTER(rts, enum sp_rts)
-CREATE_SETTER(cts, enum sp_cts)
-CREATE_SETTER(dtr, enum sp_dtr)
-CREATE_SETTER(dsr, enum sp_dsr)
-CREATE_SETTER(xon_xoff, enum sp_xonxoff)
-
-enum sp_return sp_set_flowcontrol(struct sp_port *port, enum sp_flowcontrol flowcontrol)
+CREATE_ACCESSORS(baudrate, int)
+CREATE_ACCESSORS(bits, int)
+CREATE_ACCESSORS(parity, enum sp_parity)
+CREATE_ACCESSORS(stopbits, int)
+CREATE_ACCESSORS(rts, enum sp_rts)
+CREATE_ACCESSORS(cts, enum sp_cts)
+CREATE_ACCESSORS(dtr, enum sp_dtr)
+CREATE_ACCESSORS(dsr, enum sp_dsr)
+CREATE_ACCESSORS(xon_xoff, enum sp_xonxoff)
+
+enum sp_return sp_set_config_flowcontrol(struct sp_port_config *config, enum sp_flowcontrol flowcontrol)
 {
-       struct port_data data;
-       struct sp_port_config config;
-
-       TRACE("%p, %d", port, flowcontrol);
-
-       CHECK_PORT();
+       if (!config)
+               RETURN_ERROR(SP_ERR_ARG, "Null configuration");
 
-       TRY(get_config(port, &data, &config));
+       if (flowcontrol > SP_FLOWCONTROL_DTRDSR)
+               RETURN_ERROR(SP_ERR_ARG, "Invalid flow control setting");
 
        if (flowcontrol == SP_FLOWCONTROL_XONXOFF)
-               config.xon_xoff = SP_XONXOFF_INOUT;
+               config->xon_xoff = SP_XONXOFF_INOUT;
        else
-               config.xon_xoff = SP_XONXOFF_DISABLED;
+               config->xon_xoff = SP_XONXOFF_DISABLED;
 
        if (flowcontrol == SP_FLOWCONTROL_RTSCTS) {
-               config.rts = SP_RTS_FLOW_CONTROL;
-               config.cts = SP_CTS_FLOW_CONTROL;
+               config->rts = SP_RTS_FLOW_CONTROL;
+               config->cts = SP_CTS_FLOW_CONTROL;
        } else {
-               if (config.rts == SP_RTS_FLOW_CONTROL)
-                       config.rts = SP_RTS_ON;
-               config.cts = SP_CTS_IGNORE;
+               if (config->rts == SP_RTS_FLOW_CONTROL)
+                       config->rts = SP_RTS_ON;
+               config->cts = SP_CTS_IGNORE;
        }
 
        if (flowcontrol == SP_FLOWCONTROL_DTRDSR) {
-               config.dtr = SP_DTR_FLOW_CONTROL;
-               config.dsr = SP_DSR_FLOW_CONTROL;
+               config->dtr = SP_DTR_FLOW_CONTROL;
+               config->dsr = SP_DSR_FLOW_CONTROL;
        } else {
-               if (config.dtr == SP_DTR_FLOW_CONTROL)
-                       config.dtr = SP_DTR_ON;
-               config.dsr = SP_DSR_IGNORE;
+               if (config->dtr == SP_DTR_FLOW_CONTROL)
+                       config->dtr = SP_DTR_ON;
+               config->dsr = SP_DSR_IGNORE;
        }
 
+       RETURN_OK();
+}
+
+enum sp_return sp_set_flowcontrol(struct sp_port *port, enum sp_flowcontrol flowcontrol)
+{
+       struct port_data data;
+       struct sp_port_config config;
+
+       TRACE("%p, %d", port, flowcontrol);
+
+       CHECK_OPEN_PORT();
+
+       TRY(get_config(port, &data, &config));
+
+       TRY(sp_set_config_flowcontrol(&config, flowcontrol));
+
        TRY(set_config(port, &data, &config));
 
        RETURN_OK();
@@ -1411,11 +1722,13 @@ enum sp_return sp_get_signals(struct sp_port *port, enum sp_signal *signals)
 {
        TRACE("%p, %p", port, signals);
 
-       CHECK_PORT();
+       CHECK_OPEN_PORT();
 
        if (!signals)
                RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
 
+       DEBUG("Getting control signals for port %s", port->name);
+
        *signals = 0;
 #ifdef _WIN32
        DWORD bits;
@@ -1425,9 +1738,9 @@ enum sp_return sp_get_signals(struct sp_port *port, enum sp_signal *signals)
                *signals |= SP_SIG_CTS;
        if (bits & MS_DSR_ON)
                *signals |= SP_SIG_DSR;
-       if (bits & MS_RING_ON)
-               *signals |= SP_SIG_DCD;
        if (bits & MS_RLSD_ON)
+               *signals |= SP_SIG_DCD;
+       if (bits & MS_RING_ON)
                *signals |= SP_SIG_RI;
 #else
        int bits;
@@ -1449,7 +1762,7 @@ enum sp_return sp_start_break(struct sp_port *port)
 {
        TRACE("%p", port);
 
-       CHECK_PORT();
+       CHECK_OPEN_PORT();
 #ifdef _WIN32
        if (SetCommBreak(port->hdl) == 0)
                RETURN_FAIL("SetCommBreak() failed");
@@ -1465,7 +1778,7 @@ enum sp_return sp_end_break(struct sp_port *port)
 {
        TRACE("%p", port);
 
-       CHECK_PORT();
+       CHECK_OPEN_PORT();
 #ifdef _WIN32
        if (ClearCommBreak(port->hdl) == 0)
                RETURN_FAIL("ClearCommBreak() failed");