Skip to content

Commit 017ffd0

Browse files
committed
Add LineBufferProxy to the library
This adds a LineBufferProxy. It is a simple base class to add line buffered logging for log targets that handle lines or messages instead of stream (e.g. syslog). Signed-off-by: Jan Losinski <[email protected]>
1 parent 99d2227 commit 017ffd0

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed

src/LineBufferProxy.h

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
/**
2+
* ArduinoSimpleLogging
3+
*
4+
* https://github.com/janLo/ArduinoSimpleLogging
5+
*
6+
* Copyright (c) 2017 Jan Losinski.
7+
* MIT License
8+
*/
9+
10+
#ifndef LINEBUFFERPROXY_H
11+
#define LINEBUFFERPROXY_H
12+
13+
#include <Print.h>
14+
15+
template <int Buffsize>
16+
class LineBufferProxy : public Print {
17+
public:
18+
LineBufferProxy() : position(0) {}
19+
20+
size_t write(uint8_t byte) override {
21+
buffer[position] = byte;
22+
position++;
23+
24+
if (position >= Buffsize || byte == '\n') {
25+
doFlush();
26+
}
27+
28+
return 1;
29+
}
30+
size_t write(const uint8_t* incomming, size_t size) override {
31+
size_t start = 0;
32+
33+
while (size > 0) {
34+
size_t fit = std::min(size, Buffsize - position);
35+
36+
bool newline = false;
37+
for (size_t i = 0; i < fit; ++i) {
38+
buffer[position + i] = incomming[start + i];
39+
if (incomming[i + start] == '\n') {
40+
newline = true;
41+
fit = i + 1;
42+
break;
43+
}
44+
}
45+
46+
position += fit;
47+
48+
if (position >= Buffsize || newline) {
49+
doFlush();
50+
}
51+
52+
start += fit;
53+
size -= fit;
54+
}
55+
}
56+
57+
protected:
58+
virtual void flush(const char* buff) = 0;
59+
60+
private:
61+
void doFlush() {
62+
buffer[position] = '\0';
63+
flush(reinterpret_cast<char*>(buffer));
64+
position = 0;
65+
}
66+
67+
uint8_t buffer[Buffsize + 1];
68+
size_t position;
69+
};
70+
71+
#endif // LINEBUFFERPROXY_H

0 commit comments

Comments
 (0)