]> sigrok.org Git - libserialport.git/blobdiff - serialport.c
Add sp_drain() function.
[libserialport.git] / serialport.c
index 7127cb36e532f369539af7f57c5d8199dc68af45..6104f241a17cb34db7638ef00ac9cebaff4529ce 100644 (file)
@@ -422,9 +422,10 @@ enum sp_return sp_open(struct sp_port *port, enum sp_mode flags)
        sprintf(escaped_port_name, "\\\\.\\%s", port->name);
 
        /* Map 'flags' to the OS-specific settings. */
-       desired_access |= GENERIC_READ;
        flags_and_attributes = FILE_ATTRIBUTE_NORMAL;
-       if (flags & SP_MODE_RDWR)
+       if (flags & SP_MODE_READ)
+               desired_access |= GENERIC_READ;
+       if (flags & SP_MODE_WRITE)
                desired_access |= GENERIC_WRITE;
        if (flags & SP_MODE_NONBLOCK)
                flags_and_attributes |= FILE_FLAG_OVERLAPPED;
@@ -443,10 +444,12 @@ enum sp_return sp_open(struct sp_port *port, enum sp_mode flags)
        int ret;
 
        /* Map 'flags' to the OS-specific settings. */
-       if (flags & SP_MODE_RDWR)
+       if (flags & (SP_MODE_READ | SP_MODE_WRITE))
                flags_local |= O_RDWR;
-       if (flags & SP_MODE_RDONLY)
+       else if (flags & SP_MODE_READ)
                flags_local |= O_RDONLY;
+       else if (flags & SP_MODE_WRITE)
+               flags_local |= O_WRONLY;
        if (flags & SP_MODE_NONBLOCK)
                flags_local |= O_NONBLOCK;
 
@@ -502,19 +505,50 @@ enum sp_return sp_close(struct sp_port *port)
        return SP_OK;
 }
 
-enum sp_return sp_flush(struct sp_port *port)
+enum sp_return sp_flush(struct sp_port *port, enum sp_buffer buffers)
+{
+       CHECK_PORT();
+
+#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 SP_ERR_FAIL;
+#else
+       int flags = 0;
+       if (buffers & SP_BUF_BOTH)
+               flags = TCIOFLUSH;
+       else if (buffers & SP_BUF_INPUT)
+               flags = TCIFLUSH;
+       if (buffers & SP_BUF_OUTPUT)
+               flags = TCOFLUSH;
+
+       /* Returns 0 upon success, -1 upon failure. */
+       if (tcflush(port->fd, flags) < 0)
+               return SP_ERR_FAIL;
+#endif
+       return SP_OK;
+}
+
+enum sp_return sp_drain(struct sp_port *port)
 {
        CHECK_PORT();
 
 #ifdef _WIN32
        /* Returns non-zero upon success, 0 upon failure. */
-       if (PurgeComm(port->hdl, PURGE_RXCLEAR | PURGE_TXCLEAR) == 0)
+       if (FlushFileBuffers(port->hdl) == 0)
                return SP_ERR_FAIL;
 #else
        /* Returns 0 upon success, -1 upon failure. */
-       if (tcflush(port->fd, TCIOFLUSH) < 0)
+       if (tcdrain(port->fd) < 0)
                return SP_ERR_FAIL;
 #endif
+
        return SP_OK;
 }