ESPHome 2025.9.0-dev
Loading...
Searching...
No Matches
task_log_buffer.h
Go to the documentation of this file.
1#pragma once
2
5
6#ifdef USE_ESPHOME_TASK_LOG_BUFFER
7#include <cstddef>
8#include <cstring>
9#include <memory>
10#include <atomic>
11#include <freertos/FreeRTOS.h>
12#include <freertos/ringbuf.h>
13
14namespace esphome::logger {
15
17 public:
18 // Structure for a log message header (text data follows immediately after)
19 struct LogMessage {
20 const char *tag; // We store the pointer, assuming tags are static
21 char thread_name[16]; // Store thread name directly (only used for non-main threads)
22 uint16_t text_length; // Length of the message text (up to ~64KB)
23 uint16_t line; // Source code line number
24 uint8_t level; // Log level (0-7)
25
26 // Methods for accessing message contents
27 inline char *text_data() { return reinterpret_cast<char *>(this) + sizeof(LogMessage); }
28
29 inline const char *text_data() const { return reinterpret_cast<const char *>(this) + sizeof(LogMessage); }
30 };
31
32 // Constructor that takes a total buffer size
33 explicit TaskLogBuffer(size_t total_buffer_size);
35
36 // NOT thread-safe - borrow a message from the ring buffer, only call from main loop
37 bool borrow_message_main_loop(LogMessage **message, const char **text, void **received_token);
38
39 // NOT thread-safe - release a message buffer and update the counter, only call from main loop
40 void release_message_main_loop(void *token);
41
42 // Thread-safe - send a message to the ring buffer from any thread
43 bool send_message_thread_safe(uint8_t level, const char *tag, uint16_t line, TaskHandle_t task_handle,
44 const char *format, va_list args);
45
46 // Check if there are messages ready to be processed using an atomic counter for performance
47 inline bool HOT has_messages() const {
48 return message_counter_.load(std::memory_order_relaxed) != last_processed_counter_;
49 }
50
51 // Get the total buffer size in bytes
52 inline size_t size() const { return size_; }
53
54 private:
55 RingbufHandle_t ring_buffer_{nullptr}; // FreeRTOS ring buffer handle
56 StaticRingbuffer_t structure_; // Static structure for the ring buffer
57 uint8_t *storage_{nullptr}; // Pointer to allocated memory
58 size_t size_{0}; // Size of allocated memory
59
60 // Atomic counter for message tracking (only differences matter)
61 std::atomic<uint16_t> message_counter_{0}; // Incremented when messages are committed
62 mutable uint16_t last_processed_counter_{0}; // Tracks last processed message
63};
64
65} // namespace esphome::logger
66
67#endif // USE_ESPHOME_TASK_LOG_BUFFER
TaskLogBuffer(size_t total_buffer_size)
bool borrow_message_main_loop(LogMessage **message, const char **text, void **received_token)
bool send_message_thread_safe(uint8_t level, const char *tag, uint16_t line, TaskHandle_t task_handle, const char *format, va_list args)
void release_message_main_loop(void *token)