Sound Byte Libs 0.5.1-340-gab5b79a
C++ firmware library for audio applications on 32-bit ARM Cortex-M processors
Loading...
Searching...
No Matches
tagged.hpp
Go to the documentation of this file.
1/**
2 * @file tagged.hpp
3 * @brief Tagged output lines: a builder and a throttled value report
4 *
5 * Lines have the tagged-output form `#TAG key=value ...`,
6 * terminated with `\r\n`. They are written to the sink as built, without the
7 * logger's level, time and location prefix, so a host tool reads them by
8 * their first character.
9 *
10 * TaggedLine builds one line in a fixed buffer. A field that does not fit is
11 * left out and the line marks itself overflowed; what it writes is always
12 * whole fields.
13 *
14 * TaggedValues keeps a set of named values and writes them under one tag when
15 * one has moved more than a threshold since the last write and a minimum
16 * interval has passed. A change inside the interval is written when the
17 * interval ends, so the last value always arrives. Every write carries every
18 * value, split over as many lines as the buffer needs.
19 *
20 * Both write to the log sink, so both belong to the main loop: the audio and
21 * control interrupts never log.
22 *
23 * Usage:
24 * @code
25 * sbl::log::TaggedLine<64> line{"WATCH"};
26 * line.field("f_hz", 220.0f, 2).field("gate", 1u);
27 * line.write<SBL_LOG_OUTPUT>(); // #WATCH f_hz=220.00 gate=1
28 *
29 * sbl::log::TaggedValues<2> watch{"WATCH", {"f_hz", "env"}};
30 * watch.set(0, f_hz); // main loop, every pass
31 * watch.set(1, env_level);
32 * watch.poll<SBL_LOG_OUTPUT>(timer::millis());
33 * @endcode
34 */
35
36#ifndef SBL_COMMON_LOG_TAGGED_HPP_
37#define SBL_COMMON_LOG_TAGGED_HPP_
38
39#include <cstddef>
40#include <cstdint>
41#include <type_traits>
42
44
45namespace sbl::log {
46
47/** Decimal places TaggedLine writes a float with at most. */
48inline constexpr uint8_t TAGGED_MAX_DECIMALS = 6;
49
50/** Largest magnitude format() writes a float at (its integer part is a uint32_t). */
51inline constexpr float TAGGED_MAX_MAGNITUDE = 4.0e9f;
52
53/**
54 * @brief One `#TAG key=value ...` line in a fixed buffer
55 *
56 * @tparam SIZE Buffer size in bytes, terminator and line ending included
57 */
58template<size_t SIZE = 128>
60 static_assert(SIZE >= 8, "a tagged line needs room for a tag and its line ending");
61
62public:
63 explicit TaggedLine(const char* tag) { reset(tag); }
64
65 /** Start over with a new tag and no fields. */
66 void reset(const char* tag) {
67 length_ = 0;
68 fields_ = 0;
69 overflowed_ = false;
70 if (!append("#%s", tag)) {
71 length_ = 0;
72 buffer_[0] = '\0';
73 overflowed_ = true;
74 }
75 }
76
77 /**
78 * @brief A float field, rounded to `decimals` places
79 *
80 * A value that is not finite, or beyond TAGGED_MAX_MAGNITUDE, is written as `nan`.
81 */
82 TaggedLine& field(const char* key, float value, uint8_t decimals = 3) {
84 return field(key, "nan");
85 }
88 }
89 double half = 0.5;
90 for (uint8_t i = 0; i < decimals; ++i) {
91 half /= 10.0;
92 }
93 // format() truncates; half a unit in the last place makes that a rounding.
94 const double rounded = static_cast<double>(value) + (value < 0.0f ? -half : half);
95 if (decimals == 0) {
96 add(" %s=%d", key, static_cast<int>(rounded)); // format() always writes a point after %f
97 return *this;
98 }
99 char spec[] = " %s=%.0f";
100 spec[6] = static_cast<char>('0' + decimals);
101 add(spec, key, rounded);
102 return *this;
103 }
104
105 /** An integer field. */
106 template<typename T, typename = std::enable_if_t<std::is_integral_v<T>>>
107 TaggedLine& field(const char* key, T value) {
108 if constexpr (std::is_signed_v<T>) {
109 add(" %s=%d", key, static_cast<int>(value));
110 } else {
111 add(" %s=%u", key, static_cast<unsigned>(value));
112 }
113 return *this;
114 }
115
116 /** A string field. The convention allows no spaces in a value. */
117 TaggedLine& field(const char* key, const char* value) {
118 add(" %s=%s", key, value);
119 return *this;
120 }
121
122 /** Number of fields on the line. */
123 uint8_t fields() const { return fields_; }
124
125 /** True when a field was left out for lack of room. */
126 bool overflowed() const { return overflowed_; }
127
128 /** The line so far, without its line ending. */
129 const char* c_str() const { return buffer_; }
130
131 /** Write the line and its line ending to Output (a sink with `static void write(const char*)`). */
132 template<typename Output>
133 void write() {
134 buffer_[length_] = '\r';
135 buffer_[length_ + 1] = '\n';
136 buffer_[length_ + 2] = '\0';
137 Output::write(buffer_);
138 buffer_[length_] = '\0';
139 }
140
141private:
142 static constexpr size_t ENDING = 3; // \r \n \0
143 static constexpr size_t CAPACITY = SIZE - ENDING;
144
145 template<typename... Args>
146 void add(const char* spec, Args... args) {
147 const size_t before = length_;
148 if (append(spec, args...)) {
149 ++fields_;
150 } else {
151 length_ = before;
152 buffer_[length_] = '\0';
153 overflowed_ = true;
154 }
155 }
156
157 /** Append formatted text; false, with the buffer left dirty, when it does not fit. */
158 template<typename... Args>
159 bool append(const char* spec, Args... args) {
160 const size_t room = CAPACITY - length_ + 1; // format() reserves one byte for its terminator
161 const int wanted = format(buffer_ + length_, room, spec, args...);
162 if (wanted < 0 || static_cast<size_t>(wanted) >= room) {
163 return false;
164 }
165 length_ += static_cast<size_t>(wanted);
166 return true;
167 }
168
169 char buffer_[SIZE] = {};
170 size_t length_ = 0;
171 uint8_t fields_ = 0;
172 bool overflowed_ = false;
173};
174
175/**
176 * @brief Named values written under one tag, on change, at a capped rate
177 *
178 * @tparam COUNT Number of values
179 * @tparam LINE Line buffer size; a write that needs more is split into several lines
180 */
181template<size_t COUNT, size_t LINE = 128>
183 static_assert(COUNT > 0, "TaggedValues needs at least one value");
184
185public:
186 /** Minimum time between writes, 33 ms (about 30 lines a second). */
187 static constexpr uint32_t DEFAULT_INTERVAL_MS = 33;
188
189 /** A change smaller than this, in the values' own unit, is not written. */
190 static constexpr float DEFAULT_THRESHOLD = 1.0f / 1024.0f;
191
192 /**
193 * @param tag The line's tag, e.g. "WATCH"
194 * @param names Key for each value: `[a-z][a-z0-9_]*`
195 */
196 TaggedValues(const char* tag, const char* const (&names)[COUNT]) : tag_(tag) {
197 for (size_t i = 0; i < COUNT; ++i) {
198 names_[i] = names[i];
199 }
200 }
201
202 /** Values named one at a time with name(). */
203 explicit TaggedValues(const char* tag) : tag_(tag) {}
204
205 /** Set the key of one value: `[a-z][a-z0-9_]*`. */
206 void name(size_t index, const char* key) {
207 if (index < COUNT) {
208 names_[index] = key;
209 }
210 }
211
212 void set_interval_ms(uint32_t ms) { interval_ms_ = ms; }
213 void set_threshold(float threshold) { threshold_ = threshold; }
214 void set_decimals(uint8_t decimals) { decimals_ = decimals; }
215
216 /** Take a value's current reading. */
217 void set(size_t index, float value) {
218 if (index >= COUNT) {
219 return;
220 }
221 values_[index] = value;
222 const float moved = value - sent_[index];
223 if (moved > threshold_ || moved < -threshold_ || value != value) {
224 dirty_ = true;
225 }
226 }
227
228 float value(size_t index) const { return index < COUNT ? values_[index] : 0.0f; }
229
230 /** Write every value at the next poll, whether it moved or not. */
231 void force() {
232 dirty_ = true;
233 forced_ = true;
234 }
235
236 /**
237 * @brief Write the values if one moved and the interval has passed
238 *
239 * @param now_ms A millisecond clock; wraparound is handled
240 * @return true if lines were written
241 */
242 template<typename Output>
244 if (!dirty_) {
245 return false;
246 }
247 if (!forced_ && written_ && now_ms - last_ms_ < interval_ms_) {
248 return false;
249 }
251 for (size_t i = 0; i < COUNT; ++i) {
252 if (names_[i] == nullptr) {
253 continue;
254 }
255 line.field(names_[i], values_[i], decimals_);
256 if (line.overflowed()) {
257 if (line.fields() > 0) {
258 line.template write<Output>();
259 }
260 line.reset(tag_);
261 line.field(names_[i], values_[i], decimals_); // a field too long for an empty line is dropped
262 }
263 sent_[i] = values_[i];
264 }
265 if (line.fields() > 0) {
266 line.template write<Output>();
267 }
268 dirty_ = false;
269 forced_ = false;
270 written_ = true;
271 last_ms_ = now_ms;
272 return true;
273 }
274
275private:
276 const char* tag_;
277 const char* names_[COUNT] = {};
278 float values_[COUNT] = {};
279 float sent_[COUNT] = {};
280 uint32_t interval_ms_ = DEFAULT_INTERVAL_MS;
281 float threshold_ = DEFAULT_THRESHOLD;
282 uint8_t decimals_ = 3;
283 uint32_t last_ms_ = 0;
284 bool dirty_ = true; // the first poll writes the starting values
285 bool forced_ = false;
286 bool written_ = false;
287};
288
289} // namespace sbl::log
290
291#endif // SBL_COMMON_LOG_TAGGED_HPP_
One #TAG key=value ... line in a fixed buffer.
Definition tagged.hpp:59
void reset(const char *tag)
Definition tagged.hpp:66
TaggedLine & field(const char *key, float value, uint8_t decimals=3)
A float field, rounded to decimals places.
Definition tagged.hpp:82
TaggedLine & field(const char *key, T value)
Definition tagged.hpp:107
TaggedLine & field(const char *key, const char *value)
Definition tagged.hpp:117
const char * c_str() const
Definition tagged.hpp:129
bool overflowed() const
Definition tagged.hpp:126
uint8_t fields() const
Definition tagged.hpp:123
Named values written under one tag, on change, at a capped rate.
Definition tagged.hpp:182
void set(size_t index, float value)
Definition tagged.hpp:217
TaggedValues(const char *tag, const char *const (&names)[COUNT])
Definition tagged.hpp:196
TaggedValues(const char *tag)
Definition tagged.hpp:203
bool poll(uint32_t now_ms)
Write the values if one moved and the interval has passed.
Definition tagged.hpp:243
void name(size_t index, const char *key)
Definition tagged.hpp:206
static constexpr uint32_t DEFAULT_INTERVAL_MS
Definition tagged.hpp:187
static constexpr float DEFAULT_THRESHOLD
Definition tagged.hpp:190
Minimal safe string formatting for embedded systems.
Logging.
Definition banner.hpp:53
constexpr float TAGGED_MAX_MAGNITUDE
Definition tagged.hpp:51
constexpr bool is_sink_v
Definition sink.hpp:55
constexpr uint8_t TAGGED_MAX_DECIMALS
Definition tagged.hpp:48
int format(char *buf, size_t size, const char *fmt,...)
Format a string into a buffer (snprintf-style)
Definition format.hpp:265