A client for the SmartREST protocol from Cumulocity.
Fork of MbedSmartRest by
Diff: MbedDataSink.cpp
- Revision:
- 13:e76920d5e1ec
- Parent:
- 2:1038411466a6
- Child:
- 14:dc3f8dd5c02b
--- a/MbedDataSink.cpp Wed Apr 02 12:23:46 2014 +0000 +++ b/MbedDataSink.cpp Fri Apr 11 09:33:45 2014 +0000 @@ -1,65 +1,104 @@ #include "MbedDataSink.h" +#include "MbedClient.h" #include <stdlib.h> #include <stdio.h> +#include <string.h> -MbedDataSink::MbedDataSink(size_t length) +#include "mbed.h" + +MbedDataSink::MbedDataSink(TCPSocketConnection& sock) : _len(0), _sock(sock) { - _len = length; - _ptr = _buf = (char*)malloc(length); } MbedDataSink::~MbedDataSink() { - free(_buf); } size_t MbedDataSink::write(char c) { - if (_ptr - _buf == _len) - return 0; - *_ptr++ = c; + while (MBED_SINK_BUFFER_SIZE - _len < 1) { + if (!send()) + return 0; + } + + putchar(c); + _buf[_len++] = c; return 1; } size_t MbedDataSink::write(void *buf, size_t length) { - size_t written = 0; - char *b = (char*)buf; + size_t sent = 0, len; - while ((length-- > 0) && (write(*b++))) - written++; - - return written; + while (sent < length) { + while (MBED_SINK_BUFFER_SIZE - _len < 1) { + if (!send()) + return 0; + } + + if (MBED_SINK_BUFFER_SIZE - _len >= length-sent) + len = length-sent; + else + len = MBED_SINK_BUFFER_SIZE - _len; + + memcpy(_buf+_len, (char*)buf+sent, len); + _len += len; + sent += len; + } + + return length; } size_t MbedDataSink::write(const char *str) { - size_t written = 0; - - for (char c, *p = (char*)str; (c = *p) > 0; ++p) { - if (!write(c)) - break; - written++; - } - return written; + return write((void*)str, strlen(str)); } size_t MbedDataSink::write(unsigned long number) { - size_t left, len; + char str[24]; - left = _len - (_ptr - _buf); - len = snprintf(_ptr, left, "%ld", number); - _ptr += len; - return len; + snprintf(str, 24, "%uld", number); + return write(str); +} + +bool MbedDataSink::flush() +{ + while (_len > 0) { + if (!send()) + return false; + } + + return true; } -const char * MbedDataSink::buffer() +bool MbedDataSink::send() { - return _buf; + int ret; + + if (!_sock.is_connected()) + return false; + + _sock.set_blocking(true); + ret = _sock.send(_buf, _len); + + //TODO: fix bug in u-blox so no longer wait is needed + wait(0.5); + + if (ret < 0){ + puts("Send failed."); + return false; + } + + // move rest of buffer + if ((ret > 0) && (ret < _len)) + memmove(_buf, _buf+ret, _len-ret); + + _len -= ret; + return true; } -size_t MbedDataSink::length() +void MbedDataSink::reset() { - return _ptr - _buf; -} + _len = 0; +} \ No newline at end of file