Compare commits

..

1 Commits

Author SHA1 Message Date
J. Nick Koston
0699ecbd19 [uptime] Use buf_append_printf for ESP8266 flash optimization 2026-01-16 11:26:43 -10:00
2 changed files with 13 additions and 16 deletions

View File

@@ -47,27 +47,29 @@ void Syslog::log_(const int level, const char *tag, const char *message, size_t
size_t remaining = sizeof(packet);
// Write PRI - abort if this fails as packet would be malformed
offset = buf_append_printf(packet, sizeof(packet), 0, "<%d>", pri);
if (offset == 0) {
return; // PRI always produces at least "<0>" (3 chars), so 0 means error
int ret = snprintf(packet, remaining, "<%d>", pri);
if (ret <= 0 || static_cast<size_t>(ret) >= remaining) {
return;
}
remaining -= offset;
offset = ret;
remaining -= ret;
// Write timestamp directly into packet (RFC 5424: use "-" if time not valid or strftime fails)
auto now = this->time_->now();
size_t ts_written = now.is_valid() ? now.strftime(packet + offset, remaining, "%b %e %H:%M:%S") : 0;
if (ts_written > 0) {
offset += ts_written;
remaining -= ts_written;
} else if (remaining > 0) {
packet[offset++] = '-';
remaining--;
}
// Write hostname, tag, and message
offset = buf_append_printf(packet, sizeof(packet), offset, " %s %s: %.*s", App.get_name().c_str(), tag, (int) len,
message);
// Clamp to exclude null terminator position if buffer was filled
if (offset >= sizeof(packet)) {
offset = sizeof(packet) - 1;
ret = snprintf(packet + offset, remaining, " %s %s: %.*s", App.get_name().c_str(), tag, (int) len, message);
if (ret > 0) {
// snprintf returns chars that would be written; clamp to actual buffer space
offset += std::min(static_cast<size_t>(ret), remaining > 0 ? remaining - 1 : 0);
}
if (offset > 0) {

View File

@@ -9,17 +9,12 @@ namespace uptime {
static const char *const TAG = "uptime.sensor";
// Clamp position to valid buffer range when snprintf indicates truncation
static size_t clamp_buffer_pos(size_t pos, size_t buf_size) { return pos < buf_size ? pos : buf_size - 1; }
static void append_unit(char *buf, size_t buf_size, size_t &pos, const char *separator, unsigned value,
const char *label) {
if (pos > 0) {
pos += snprintf(buf + pos, buf_size - pos, "%s", separator);
pos = clamp_buffer_pos(pos, buf_size);
pos = buf_append_printf(buf, buf_size, pos, "%s", separator);
}
pos += snprintf(buf + pos, buf_size - pos, "%u%s", value, label);
pos = clamp_buffer_pos(pos, buf_size);
pos = buf_append_printf(buf, buf_size, pos, "%u%s", value, label);
}
void UptimeTextSensor::setup() {