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
sd_output.hpp
Go to the documentation of this file.
1/**
2 * @file sd_output.hpp
3 * @brief SD card log sink for the logger
4 *
5 * Per-boot sequential log files with size and count limits.
6 * Buffers writes to a 512-byte sector-aligned buffer and flushes
7 * to SD card via FatFs. Call flush() periodically from the main
8 * loop (never from ISR).
9 *
10 * Usage:
11 * @code
12 * // Mount FatFs first, then:
13 * SdLogConfig cfg;
14 * cfg.millis = sbl::system::timer::millis; // required
15 * SdLogOutput::init(cfg);
16 *
17 * // In main loop:
18 * SdLogOutput::write("hello\r\n");
19 * SdLogOutput::flush(); // time-gated, safe to call every iteration
20 * @endcode
21 */
22
23#ifndef SBL_COMMON_LOG_SD_OUTPUT_HPP_
24#define SBL_COMMON_LOG_SD_OUTPUT_HPP_
25
26#include "ff.h"
27#include <cstring>
28
29namespace sbl::log {
30
32 const char* prefix = "LOG"; // Filename prefix -> LOG_000.TXT
33 size_t max_file_bytes = 4 * 1024 * 1024;// 4MB per file
34 uint16_t max_files = 256; // 256 files x 4MB = 1GB max card usage
35 uint16_t flush_interval_ms = 100; // Min ms between flushes (0 = every call)
36 uint32_t (*millis)() = nullptr; // Millisecond timestamp function (required)
37};
38
40public:
41 /**
42 * Initialize: scan existing files, create next sequential log.
43 * Returns true if log file was opened successfully.
44 */
45 static bool init(const SdLogConfig& cfg = {}) {
46 cfg_ = cfg;
47 pos_ = 0;
48 file_bytes_ = 0;
49 last_flush_ms_ = 0;
50 open_ = false;
51
52 // Find the next available file number
53 current_num_ = find_next_file_number();
54
55 // At max_files, delete the oldest to make room
56 if (current_num_ >= cfg_.max_files) {
57 delete_oldest();
58 current_num_ = find_next_file_number();
59 }
60
61 return open_file(current_num_);
62 }
63
64 /** Logger sink interface - buffers data, auto-flushes when buffer is full. */
65 static void write(const char* str) {
66 if (!open_) {
67 return;
68 }
69 size_t len = strlen(str);
70 const char* p = str;
71 while (len > 0) {
72 size_t space = BUF_SIZE - pos_;
73 size_t chunk = len < space ? len : space;
74 memcpy(buf_ + pos_, p, chunk);
75 pos_ += chunk;
76 p += chunk;
77 len -= chunk;
78 if (pos_ >= BUF_SIZE) {
79 flush_buffer();
80 }
81 }
82 }
83
84 /**
85 * Time-gated flush. Safe to call every main loop iteration.
86 * Only writes to SD if flush_interval_ms has elapsed or buffer is >75% full.
87 */
88 static void flush() {
89 if (!open_ || pos_ == 0) {
90 return;
91 }
92
93 bool time_to_flush = true;
94 if (cfg_.millis && cfg_.flush_interval_ms > 0) {
95 uint32_t now = cfg_.millis();
96 uint32_t elapsed = now - last_flush_ms_;
97 time_to_flush = (elapsed >= cfg_.flush_interval_ms) || (pos_ >= BUF_SIZE * 3 / 4);
98 }
99
100 if (time_to_flush) {
101 flush_buffer();
102 }
103 }
104
105 /** Flush immediately, bypassing time gate. */
106 static void force_flush() {
107 if (!open_ || pos_ == 0) {
108 return;
109 }
110 flush_buffer();
111 }
112
113 /** Close file (flushes first). Call before removing card. */
114 static void close() {
115 if (!open_) {
116 return;
117 }
118 force_flush();
119 f_close(&fil_);
120 open_ = false;
121 }
122
123 static bool is_open() { return open_; }
124
125private:
126 static constexpr size_t BUF_SIZE = 512;
127 static constexpr size_t NAME_BUF = 16; // "LOG_000.TXT\0"
128
129 static void make_filename(char* buf, uint16_t num) {
130 // Build PREFIX_NNN.TXT (8.3 format)
131 size_t i = 0;
132 const char* p = cfg_.prefix;
133 while (*p && i < 4) {
134 buf[i++] = *p++;
135 }
136 buf[i++] = '_';
137 buf[i++] = '0' + (num / 100) % 10;
138 buf[i++] = '0' + (num / 10) % 10;
139 buf[i++] = '0' + num % 10;
140 buf[i++] = '.';
141 buf[i++] = 'T';
142 buf[i++] = 'X';
143 buf[i++] = 'T';
144 buf[i] = '\0';
145 }
146
147 static uint16_t find_next_file_number() {
148 // Find the lowest unused file number
149 char name[NAME_BUF];
150 FILINFO fno;
151 for (uint16_t n = 0; n < cfg_.max_files; n++) {
152 make_filename(name, n);
153 if (f_stat(name, &fno) != FR_OK) {
154 return n; // File doesn't exist - use this number
155 }
156 }
157 return cfg_.max_files; // All slots full
158 }
159
160 static void delete_oldest() {
161 // Delete the lowest-numbered existing file; no files are renamed
162 char name[NAME_BUF];
163 FILINFO fno;
164 for (uint16_t n = 0; n < cfg_.max_files; n++) {
165 make_filename(name, n);
166 if (f_stat(name, &fno) == FR_OK) {
167 f_unlink(name);
168 return; // Deleted oldest, now find_next will find the gap
169 }
170 }
171 }
172
173 static bool open_file(uint16_t num) {
174 char name[NAME_BUF];
175 make_filename(name, num);
176 FRESULT fr = f_open(&fil_, name, FA_WRITE | FA_CREATE_NEW);
177 if (fr != FR_OK) {
178 return false;
179 }
180 open_ = true;
181 file_bytes_ = 0;
182 return true;
183 }
184
185 static bool rotate_file() {
186 // Close current, open next
187 f_close(&fil_);
188 open_ = false;
189 current_num_++;
190
191 if (current_num_ >= cfg_.max_files) {
192 delete_oldest();
193 current_num_ = find_next_file_number();
194 }
195
196 return open_file(current_num_);
197 }
198
199 static void flush_buffer() {
200 if (pos_ == 0) {
201 return;
202 }
203
204 // Rotate before writing if the file is full
205 if (cfg_.max_file_bytes > 0 && file_bytes_ + pos_ > cfg_.max_file_bytes) {
206 if (!rotate_file()) {
207 pos_ = 0;
208 return; // Rotation failed, drop data
209 }
210 }
211
212 UINT bw;
213 f_write(&fil_, buf_, pos_, &bw);
214 f_sync(&fil_);
215 file_bytes_ += bw;
216 pos_ = 0;
217
218 if (cfg_.millis) {
219 last_flush_ms_ = cfg_.millis();
220 }
221 }
222
223 static inline SdLogConfig cfg_;
224 static inline FIL fil_;
225 static inline char buf_[BUF_SIZE];
226 static inline size_t pos_ = 0;
227 static inline size_t file_bytes_ = 0;
228 static inline uint16_t current_num_ = 0;
229 static inline uint32_t last_flush_ms_ = 0;
230 static inline bool open_ = false;
231};
232
233} // namespace sbl::log
234
235#endif // SBL_COMMON_LOG_SD_OUTPUT_HPP_
static void close()
static void flush()
Definition sd_output.hpp:88
static void force_flush()
static bool init(const SdLogConfig &cfg={})
Definition sd_output.hpp:45
static void write(const char *str)
Definition sd_output.hpp:65
Logging.
Definition banner.hpp:53
constexpr bool is_sink_v
Definition sink.hpp:55