uart: add capability to check if data can be read from device
authorJon Trulson <jtrulson@ics.com>
Wed, 29 Apr 2015 22:13:07 +0000 (16:13 -0600)
committerThomas Ingleby <thomas.c.ingleby@intel.com>
Thu, 28 May 2015 22:31:11 +0000 (23:31 +0100)
Signed-off-by: Jon Trulson <jtrulson@ics.com>
Signed-off-by: Brendan Le Foll <brendan.le.foll@intel.com>
api/mraa/uart.h
api/mraa/uart.hpp
src/uart/uart.c

index e321d6a..468778a 100644 (file)
@@ -113,6 +113,15 @@ int mraa_uart_read(mraa_uart_context dev, char *buf, size_t len);
  */
 int mraa_uart_write(mraa_uart_context dev, char *buf, size_t len);
 
+/**
+ * Check to see if data is available on the device for reading
+ *
+ * @param dev uart context
+ * @param millis number of milliseconds to wait, or 0 to return immediately
+ * @return 1 if there is data available to read, 0 otherwise
+ */
+mraa_boolean_t
+mraa_uart_data_available(mraa_uart_context dev, unsigned int millis);
 
 #ifdef __cplusplus
 }
index d158d52..82296b8 100644 (file)
@@ -128,6 +128,21 @@ class Uart
         return mraa_uart_write(m_uart, buf, len);
     }
 
+    /**
+     * Check to see if data is available on the device for reading
+     *
+     * @param millis number of milliseconds to wait, or 0 to return immediately
+     * @return true if there is data available to read, false otherwise
+     */
+     bool
+     dataAvailable(unsigned int millis=0)
+     {
+       if (mraa_uart_data_available(m_uart, millis))
+           return true;
+       else
+           return false;
+     }
+
   private:
     mraa_uart_context m_uart;
 };
index 416cf71..b8d8ec5 100644 (file)
@@ -204,3 +204,39 @@ mraa_uart_write(mraa_uart_context dev, char *buf, size_t len)
 
     return write(dev->fd, buf, len);
 }
+
+mraa_boolean_t
+mraa_uart_data_available(mraa_uart_context dev, unsigned int millis)
+{
+    if (!dev) {
+        syslog(LOG_ERR, "uart: data_available: write context is NULL");
+        return 0;
+    }
+
+    if (dev->fd < 0) {
+        syslog(LOG_ERR, "uart: port is not open");
+        return 0;
+    }
+
+    struct timeval timeout;
+
+    if (millis == 0) {
+        // no waiting
+        timeout.tv_sec = 0;
+        timeout.tv_usec = 0;
+    }
+    else {
+        timeout.tv_sec = millis / 1000;
+        timeout.tv_usec = (millis % 1000) * 1000;
+    }
+
+    fd_set readfds;
+
+    FD_ZERO(&readfds);
+    FD_SET(dev->fd, &readfds);
+
+    if (select(dev->fd + 1, &readfds, NULL, NULL, &timeout) > 0)
+        return 1;                // data is ready
+    else
+        return 0;
+}