polytech umpc project

Fork of SerialGPS by Shinichiro Nakamura

Revision:
0:3d0c5d7e5d0a
Child:
1:a5b887e09aa4
diff -r 000000000000 -r 3d0c5d7e5d0a SerialBuffered.cpp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/SerialBuffered.cpp	Mon Sep 20 06:03:38 2010 +0000
@@ -0,0 +1,69 @@
+#include "mbed.h"
+#include "SerialBuffered.h"
+
+SerialBuffered::SerialBuffered(PinName tx, PinName rx) : Serial(tx, rx) {
+    indexContentStart = 0;
+    indexContentEnd = 0;
+    timeout = 1;
+    attach(this, &SerialBuffered::handleInterrupt);
+}
+
+SerialBuffered::~SerialBuffered() {
+}
+
+void SerialBuffered::setTimeout(int ms) {
+    timeout = ms;
+}
+
+size_t SerialBuffered::readBytes(uint8_t *bytes, size_t requested) {
+    int i = 0;
+    while (i < requested) {
+        int c = getc();
+        if (c < 0) {
+            break;
+        }
+        bytes[i] = c;
+        i++;
+    }
+    return i;
+}
+
+int SerialBuffered::getc() {
+    timer.reset();
+    timer.start();
+    while (indexContentStart == indexContentEnd) {
+        wait_ms(1);
+        if ((timeout > 0) && (timer.read_ms() > timeout)) {
+            /*
+             * Timeout occured.
+             */
+            // printf("Timeout occured.\n");
+            return EOF;
+        }
+    }
+    timer.stop();
+
+    uint8_t result = buffer[indexContentStart++];
+    indexContentStart =  indexContentStart % BUFFERSIZE;
+
+    return result;
+}
+
+int SerialBuffered::readable() {
+    return indexContentStart != indexContentEnd;
+}
+
+void SerialBuffered::handleInterrupt() {
+    while (Serial::readable()) {
+        if (indexContentStart == ((indexContentEnd + 1) % BUFFERSIZE)) {
+            /*
+             * Buffer overrun occured.
+             */
+            // printf("Buffer overrun occured.\n");
+            Serial::getc();
+        } else {
+            buffer[indexContentEnd++] = Serial::getc();
+            indexContentEnd = indexContentEnd % BUFFERSIZE;
+        }
+    }
+}