Takashi Matsuoka / MJ_LineSerial
Revision:
0:d3ca6a57e60b
Child:
1:2338acfb180d
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/LineSerial.cpp	Mon Oct 13 12:50:10 2014 +0000
@@ -0,0 +1,116 @@
+#include "LineSerial.h"
+
+LineSerial::LineSerial(PinName tx, PinName rx, const char *name) : Serial(tx, rx, name), 
+    readBuffer(NULL),
+    readBufferSize(0),
+    readBufferCount(0),
+    readLineFunc(NULL)
+{
+}
+
+LineSerial::~LineSerial()
+{
+    if (this->readBuffer != NULL)
+    {
+        delete this->readBuffer;
+        this->readBuffer = NULL;
+    }
+}
+
+void LineSerial::allocateReadBuffer(size_t size)
+{
+    // free memory.
+    if (this->readBuffer != NULL)
+    {
+        delete this->readBuffer;
+    }
+    
+    // allocate memory.
+    if (size <= 0)
+    {
+        this->readBuffer = NULL;
+    }
+    else
+    {
+        this->readBuffer = new char[size];
+    }
+    
+    // initialize related values.
+    this->readBufferSize = size <= 0 ? 0 : size;
+    this->readBufferCount = 0;
+}
+
+void LineSerial::attachReadLine(void (*func)(const char* str))
+{
+    this->readLineFunc = func;
+}
+
+void LineSerial::task()
+{
+    if (this->readable())
+    {
+        char c = this->getc();
+        switch (c)
+        {
+        case '\r':
+            if (this->readLineFunc != NULL)
+            {
+                this->readBuffer[this->readBufferCount] = '\0';
+                this->readLineFunc(this->readBuffer);
+                this->readBufferCount = 0;
+            }
+            break;
+        case '\b':
+            if (!this->removeReadBuffer())
+            {
+                this->putc('\a');
+            }
+            else
+            {
+                this->putc('\b');
+            }
+            break;
+        default:
+            if (!this->appendReadBuffer(c))
+            {
+                this->putc('\a');
+            }
+            else
+            {
+                this->putc(c);
+            }
+            break;
+        }
+    }
+}
+
+bool LineSerial::appendReadBuffer(char data)
+{
+    if (this->readBuffer == NULL)
+    {
+        return false;
+    }
+    if (this->readBufferCount >= this->readBufferSize - 1)
+    {
+        return false;
+    }
+    
+    this->readBuffer[this->readBufferCount++] = data;
+    return true;
+}
+
+bool LineSerial::removeReadBuffer()
+{
+    if (this->readBuffer == NULL)
+    {
+        return false;
+    }
+    if (this->readBufferCount <= 0)
+    {
+        return false;
+    }
+    
+    this->readBufferCount--;
+    return true;
+}
+