Important changes to repositories hosted on mbed.com
Mbed hosted mercurial repositories are deprecated and are due to be permanently deleted in July 2026.
To keep a copy of this software download the repository Zip archive or clone locally using Mercurial.
It is also possible to export all your personal repositories from the account settings page.
LineSerial.cpp
- Committer:
- matsujirushi
- Date:
- 2014-10-13
- Revision:
- 1:2338acfb180d
- Parent:
- 0:d3ca6a57e60b
File content as of revision 1:2338acfb180d:
#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->puts("\b \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;
}