-
Notifications
You must be signed in to change notification settings - Fork 506
/
RingBuf.h
400 lines (396 loc) · 11.6 KB
/
RingBuf.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
/**
* Copyright (c) 2011-2022 Bill Greiman
* This file is part of the SdFat library for SD memory cards.
*
* MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#ifndef RingBuf_h
#define RingBuf_h
/**
* \file
* \brief Ring buffer for data loggers.
*/
#include "common/FmtNumber.h"
#include "common/SysCall.h"
#ifndef DOXYGEN_SHOULD_SKIP_THIS
// Teensy 3.5/3.6 has hard fault at 0x20000000 for unaligned memcpy.
#if defined(__MK64FX512__) || defined(__MK66FX1M0__)
inline bool is_aligned(const void* ptr, uintptr_t alignment) {
auto iptr = reinterpret_cast<uintptr_t>(ptr);
return !(iptr % alignment);
}
inline void memcpyBuf(void* dst, const void* src, size_t len) {
const uint8_t* b = reinterpret_cast<const uint8_t*>(0X20000000UL);
uint8_t* d = reinterpret_cast<uint8_t*>(dst);
const uint8_t* s = reinterpret_cast<const uint8_t*>(src);
if ((is_aligned(d, 4) && is_aligned(s, 4) && (len & 3) == 0) ||
!((d < b && b <= (d + len)) || (s < b && b <= (s + len)))) {
memcpy(dst, src, len);
} else {
while (len--) {
*d++ = *s++;
}
}
}
#else // defined(__MK64FX512__) || defined(__MK66FX1M0__)
inline void memcpyBuf(void* dst, const void* src, size_t len) {
memcpy(dst, src, len);
}
#endif // defined(__MK64FX512__) || defined(__MK66FX1M0__)
#endif // DOXYGEN_SHOULD_SKIP_THIS
/**
* \class RingBuf
* \brief Ring buffer for data loggers and data transmitters.
*
* This ring buffer may be used in ISRs. Use beginISR(), endISR(), write()
* and print() in the ISR and use writeOut() in non-interrupt code
* to write data to a file.
*
* Use beginISR(), endISR() and read() in an ISR with readIn() in non-interrupt
* code to provide file data to an ISR.
*/
template <class F, size_t Size>
class RingBuf : public Print {
public:
/**
* RingBuf Constructor.
*/
RingBuf() { begin(nullptr); }
/**
* Initialize RingBuf.
* \param[in] file Underlying file.
*/
void begin(F* file) {
m_file = file;
m_count = 0;
m_head = 0;
m_tail = 0;
m_inISR = false;
clearWriteError();
}
/**
* Disable protection of m_count by noInterrupts()/interrupts.
*/
void beginISR() { m_inISR = true; }
/**
* \return the RingBuf free space in bytes.
*/
size_t bytesFree() const { return Size - bytesUsed(); }
/**
* \return the RingBuf used space in bytes.
*/
size_t bytesUsed() const {
if (m_inISR) {
return m_count;
} else {
noInterrupts();
size_t rtn = m_count;
interrupts();
return rtn;
}
}
/**
* Enable protection of m_count by noInterrupts()/interrupts.
*/
void endISR() { m_inISR = false; }
#ifndef DOXYGEN_SHOULD_SKIP_THIS
// See write(), read(), beginISR() and endISR().
size_t __attribute__((error("use write(buf, count), beginISR(), endISR()")))
memcpyIn(const void* buf, size_t count);
size_t __attribute__((error("use read(buf, count), beginISR(), endISR()")))
memcpyOut(void* buf, size_t count);
#endif // DOXYGEN_SHOULD_SKIP_THIS
/** Print a number followed by a field terminator.
* \param[in] value The number to be printed.
* \param[in] term The field terminator. Use '\\n' for CR LF.
* \param[in] prec Number of digits after decimal point.
* \return The number of bytes written.
*/
size_t printField(double value, char term, uint8_t prec = 2) {
char buf[24];
char* str = buf + sizeof(buf);
if (term) {
*--str = term;
if (term == '\n') {
*--str = '\r';
}
}
str = fmtDouble(str, value, prec, false);
return write(str, buf + sizeof(buf) - str);
}
/** Print a number followed by a field terminator.
* \param[in] value The number to be printed.
* \param[in] term The field terminator. Use '\\n' for CR LF.
* \param[in] prec Number of digits after decimal point.
* \return The number of bytes written or -1 if an error occurs.
*/
size_t printField(float value, char term, uint8_t prec = 2) {
return printField(static_cast<double>(value), term, prec);
}
/** Print a number followed by a field terminator.
* \param[in] value The number to be printed.
* \param[in] term The field terminator. Use '\\n' for CR LF.
* \return The number of bytes written or -1 if an error occurs.
*/
template <typename Type>
size_t printField(Type value, char term) {
char sign = 0;
char buf[3 * sizeof(Type) + 3];
char* str = buf + sizeof(buf);
if (term) {
*--str = term;
if (term == '\n') {
*--str = '\r';
}
}
if (value < 0) {
value = -value;
sign = '-';
}
if (sizeof(Type) < 4) {
str = fmtBase10(str, (uint16_t)value);
} else {
str = fmtBase10(str, (uint32_t)value);
}
if (sign) {
*--str = sign;
}
return write((const uint8_t*)str, &buf[sizeof(buf)] - str);
}
/** Read data from RingBuf.
* \param[out] buf destination for data.
* \param[in] count number of bytes to read.
* \return Actual count of bytes read.
*/
size_t read(void* buf, size_t count) {
size_t n = bytesFree();
if (count > n) {
count = n;
}
uint8_t* dst = reinterpret_cast<uint8_t*>(buf);
n = minSize(Size - m_tail, count);
if (n == count) {
memcpyBuf(dst, m_buf + m_tail, n);
m_tail = advance(m_tail, n);
} else {
memcpyBuf(dst, m_buf + m_tail, n);
memcpyBuf(dst + n, m_buf, count - n);
m_tail = count - n;
}
adjustCount(-count);
return count;
}
/**
* Efficient read for small types.
*
* \param[in] data location for data item.
* \return true for success else false.
*/
template <typename Type>
bool read(Type* data) {
if (bytesUsed() < sizeof(Type)) {
return false;
}
uint8_t* ptr = reinterpret_cast<uint8_t*>(data);
for (size_t i = 0; i < sizeof(Type); i++) {
ptr[i] = m_buf[m_tail];
m_tail = advance(m_tail);
}
adjustCount(-sizeof(Type));
return true;
}
/**
* Read data into the RingBuf from the underlying file.
* the number of bytes read may be less than count if
* bytesFree is less than count.
*
* This function must not be used in an ISR.
*
* \param[in] count number of bytes to be read.
* \return Number of bytes actually read or negative for read error.
*/
int readIn(size_t count) {
size_t n = bytesFree();
if (count > n) {
count = n;
}
n = minSize(Size - m_head, count);
auto rtn = m_file->read(m_buf + m_head, n);
if (rtn <= 0) {
return rtn;
}
size_t nread = rtn;
if (n < count && nread == n) {
rtn = m_file->read(m_buf, count - n);
if (rtn > 0) {
nread += rtn;
}
}
m_head = advance(m_head, nread);
adjustCount(nread);
return nread;
}
/**
* Write all data in the RingBuf to the underlying file.
* \return true for success.
*/
bool sync() {
size_t n = bytesUsed();
return n ? writeOut(n) == n : true;
}
/**
* Copy data to the RingBuf from buf.
*
* No data will be copied if count is greater than bytesFree.
* Use getWriteError() to check for print errors and
* clearWriteError() to clear the error.
*
* \param[in] buf Location of data to be written.
* \param[in] count number of bytes to be written.
* \return Number of bytes actually written.
*/
size_t write(const void* buf, size_t count) {
if (bytesFree() < count) {
setWriteError();
return 0;
}
const uint8_t* src = (const uint8_t*)buf;
size_t n = minSize(Size - m_head, count);
if (n == count) {
memcpyBuf(m_buf + m_head, src, n);
m_head = advance(m_head, n);
} else {
memcpyBuf(m_buf + m_head, src, n);
memcpyBuf(m_buf, src + n, count - n);
m_head = count - n;
}
adjustCount(count);
return count;
}
/**
* Copy str to RingBuf.
*
* \param[in] str Location of data to be written.
* \return Number of bytes actually written.
*/
size_t write(const char* str) { return Print::write(str); }
/**
* Override virtual function in Print for efficiency.
*
* \param[in] buf Location of data to be written.
* \param[in] count number of bytes to be written.
* \return Number of bytes actually written.
*/
size_t write(const uint8_t* buf, size_t count) override {
return write((const void*)buf, count);
}
/**
* Efficient write for small types.
* \param[in] data Item to be written.
* \return Number of bytes actually written.
*/
template <typename Type>
size_t write(Type data) {
uint8_t* ptr = reinterpret_cast<uint8_t*>(&data);
if (bytesFree() < sizeof(Type)) {
setWriteError();
return 0;
}
for (size_t i = 0; i < sizeof(Type); i++) {
m_buf[m_head] = ptr[i];
m_head = advance(m_head);
}
adjustCount(sizeof(Type));
return sizeof(Type);
}
/**
* Required function for Print.
* \param[in] data Byte to be written.
* \return Number of bytes actually written.
*
* Try to force devirtualization by using final and always_inline.
*/
size_t write(uint8_t data) final __attribute__((always_inline)) {
// Use this if above does not compile size_t write(uint8_t data) final {
return write<uint8_t>(data);
}
/**
* Write data to file from RingBuf buffer.
* \param[in] count number of bytes to be written.
*
* The number of bytes written may be less than count if
* bytesUsed is less than count or if an error occurs.
*
* This function must only be used in non-interrupt code.
*
* \return Number of bytes actually written.
*/
size_t writeOut(size_t count) {
size_t n = bytesUsed(); // Protected from interrupts;
if (count > n) {
count = n;
}
n = minSize(Size - m_tail, count);
auto rtn = m_file->write(m_buf + m_tail, n);
if (rtn <= 0) {
return 0;
}
size_t nwrite = rtn;
if (n < count && nwrite == n) {
rtn = m_file->write(m_buf, count - n);
if (rtn > 0) {
nwrite += rtn;
}
}
m_tail = advance(m_tail, nwrite);
adjustCount(-nwrite);
return nwrite;
}
private:
uint8_t __attribute__((aligned(4))) m_buf[Size];
F* m_file;
volatile size_t m_count;
size_t m_head;
size_t m_tail;
volatile bool m_inISR;
void adjustCount(int amount) {
if (m_inISR) {
m_count += amount;
} else {
noInterrupts();
m_count += amount;
interrupts();
}
}
size_t advance(size_t index) {
if (!((Size - 1) & Size)) {
return (index + 1) & (Size - 1);
}
return index + 1 < Size ? index + 1 : 0;
}
size_t advance(size_t index, size_t n) {
index += n;
return index < Size ? index : index - Size;
}
// avoid macro MIN
size_t minSize(size_t a, size_t b) { return a < b ? a : b; }
};
#endif // RingBuf_h