Loading files
This file is pinned to the selected release. Download the original to open it in your design tool.
3c36a1e66This file is pinned to the selected release. Download the original to open it in your design tool.
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) 2025 Jibril Sharafi
#include "customlog.h"
#include "taskprofiler.h"
namespace CustomLog
{
static TaskHeartbeat _heartbeat;
// Static variables - all internal to this module
static QueueHandle_t _udpLogQueue = nullptr;
static StaticQueue_t _udpLogQueueStruct;
static uint8_t* _udpLogQueueStorage = nullptr;
static WiFiUDP _udpClient;
static IPAddress _udpDestination;
static SemaphoreHandle_t _udpDestinationMutex = nullptr;
static char *_udpBuffer = nullptr; // UDP_LOG_BUFFER_SIZE - allocated in PSRAM
static bool _isUdpInitialized = false;
// Task state
static TaskHandle_t _udpTaskHandle = NULL;
static bool _udpTaskShouldRun = false;
static void _callbackMqtt(const LogEntry& entry);
static void _callbackUdp(const LogEntry& entry);
static int _espLogVprintf(const char* format, va_list args);
static bool _initializeQueue();
static void _startTask();
static void _stopTask();
static void _udpTask(void* parameter);
// Preferences management
static bool _loadUdpDestinationFromPreferences();
static bool _saveUdpDestinationToPreferences();
static bool _ensureUdpDestinationLoaded();
void begin()
{
if (_isUdpInitialized) {
LOG_DEBUG("UDP logging already initialized");
return;
}
// Mutex + destination are normally already loaded by now (the first LOG_*
// call after AdvancedLogger::setCallback lazily triggers this via
// _callbackUdp, well before WiFi/this begin() ever runs) - call it here
// too as a defensive no-op fallback in case no log line has fired yet.
if (!_ensureUdpDestinationLoaded()) {
LOG_ERROR("Failed to load UDP destination");
return;
}
// Allocate PSRAM buffer for UDP messages
if (_udpBuffer == nullptr) {
_udpBuffer = (char*)ps_malloc(UDP_LOG_BUFFER_SIZE);
if (_udpBuffer == nullptr) {
LOG_ERROR("Failed to allocate PSRAM for UDP log buffer");
return;
}
}
// Initialize queue if not already done
if (!_initializeQueue()) {
LOG_ERROR("Failed to initialize UDP log queue");
if (_udpBuffer != nullptr) {
free(_udpBuffer);
_udpBuffer = nullptr;
}
return;
}
// Make all ESP logs also go to our logger
esp_log_set_vprintf(_espLogVprintf);
_udpClient.begin(UDP_LOG_PORT);
_isUdpInitialized = true;
LOG_DEBUG("UDP logging configured to %d.%d.%d.%d:%d, PSRAM buffer: %zu bytes",
_udpDestination[0], _udpDestination[1],
_udpDestination[2], _udpDestination[3],
UDP_LOG_PORT, LOG_QUEUE_SIZE);
// Start async task
_startTask();
}
void stop()
{
_stopTask();
if (_isUdpInitialized) {
_udpClient.stop();
_isUdpInitialized = false;
LOG_DEBUG("UDP client stopped");
}
// Clean up the queue and PSRAM buffers
if (_udpLogQueueStorage != nullptr) {
_udpLogQueue = nullptr;
// Free PSRAM buffer
if (_udpLogQueueStorage != nullptr) {
free(_udpLogQueueStorage);
_udpLogQueueStorage = nullptr;
}
LOG_DEBUG("UDP logging queue stopped, PSRAM freed");
}
// Free UDP message buffer
if (_udpBuffer != nullptr) {
free(_udpBuffer);
_udpBuffer = nullptr;
}
// Delete mutex
deleteMutex(&_udpDestinationMutex);
}
void callbackMultiple(const LogEntry& entry)
{
_callbackUdp(entry);
_callbackMqtt(entry);
}
static int _espLogVprintf(const char* format, va_list args) {
// Create buffer for the formatted message
char buffer[LOG_ESPVPRINTF_CALLBACK_MESSAGE_SIZE];
int len = vsnprintf(buffer, sizeof(buffer), format, args);
if (len > 0) {
// Remove newlines and clean up the message
if (buffer[len - 1] == '\n') {
buffer[len - 1] = '\0';
}
// Map to ERROR for ESP error logs, WARNING for others
if (strstr(buffer, "E (") != nullptr) LOG_ERROR("[ESP-IDF] %s", buffer);
else if (strstr(buffer, "W (") != nullptr) LOG_WARNING("[ESP-IDF] %s", buffer);
else LOG_INFO("[ESP-IDF] %s", buffer);
}
// Also print to serial for debugging
return vprintf(format, args);
}
static bool _initializeQueue() // Cannot use logger here to avoid recursion
{
if (_udpLogQueueStorage != nullptr) return true;
// Allocate queue storage in PSRAM
uint32_t queueLength = LOG_QUEUE_SIZE / sizeof(LogEntry);
size_t realQueueSize = queueLength * sizeof(LogEntry);
_udpLogQueueStorage = (uint8_t*)ps_malloc(realQueueSize);
if (_udpLogQueueStorage == nullptr) {
Serial.printf("[ERROR] Failed to allocate PSRAM for UDP log queue (%d bytes) | Free PSRAM: %d bytes\n", realQueueSize, heap_caps_get_free_size(MALLOC_CAP_SPIRAM));
return false;
}
// Create FreeRTOS static queue using PSRAM buffer
_udpLogQueue = xQueueCreateStatic(queueLength, sizeof(LogEntry), _udpLogQueueStorage, &_udpLogQueueStruct);
if (_udpLogQueue == nullptr) {
Serial.printf("[ERROR] Failed to create UDP log queue\n");
free(_udpLogQueueStorage);
_udpLogQueueStorage = nullptr;
return false;
}
Serial.printf("[DEBUG] UDP log queue initialized with PSRAM buffer (%d bytes) | Free PSRAM: %d bytes\n", realQueueSize, heap_caps_get_free_size(MALLOC_CAP_SPIRAM));
return true;
}
static void _callbackMqtt(const LogEntry& entry)
{
if (!globalCommunityMode) Mqtt::pushLog(entry);
}
// Lazily creates the destination mutex and loads the persisted UDP destination
// on the first log callback, mirroring Mqtt::pushLog's lazy queue init - this
// is what lets _callbackUdp start queuing from the very first LOG_* call
// instead of dropping everything until CustomLog::begin() runs after WiFi
// connects (found while investigating a ~6s UDP-log blind spot at boot).
static bool _ensureUdpDestinationLoaded() // Cannot use logger here - runs inside the logger callback itself
{
static bool attempted = false;
if (attempted) return true;
attempted = true;
if (!createMutexIfNeeded(&_udpDestinationMutex)) {
Serial.printf("[ERROR] Failed to create UDP destination mutex\n");
return false;
}
// No persisted destination -> leave _udpDestination at 0.0.0.0 so _callbackUdp drops logs
// until one is configured via PUT /api/v1/logs-udp-destination.
if (!_loadUdpDestinationFromPreferences()) {
Serial.printf("[DEBUG] No saved UDP destination, UDP logging silent until one is set via API\n");
}
return true;
}
static void _callbackUdp(const LogEntry& entry)
{
if (entry.level == LogLevel::VERBOSE) return; // Never send verbose logs via UDP
if (!_ensureUdpDestinationLoaded()) return; // Failed to load, drop this log
if ((uint32_t)_udpDestination == 0) return; // No destination configured: drop silently
if (!_initializeQueue()) return; // Failed to initialize, drop this log
if (xQueueSend(_udpLogQueue, &entry, 0) != pdTRUE) { // Send to queue with no wait to avoid blocking
// Queue full -> drop
}
}
static void _startTask()
{
if (_udpTaskHandle != NULL) {
LOG_DEBUG("UDP log task already running");
return;
}
LOG_DEBUG("Starting UDP log task with %d bytes stack", UDP_LOG_TASK_STACK_SIZE);
BaseType_t result = xTaskCreate(
_udpTask,
UDP_LOG_TASK_NAME,
UDP_LOG_TASK_STACK_SIZE,
NULL,
UDP_LOG_TASK_PRIORITY,
&_udpTaskHandle);
if (result != pdPASS) {
LOG_ERROR("Failed to create UDP log task");
}
}
static void _stopTask()
{
stopTaskGracefully(&_udpTaskHandle, "UDP log task");
}
static void _udpTask(void* parameter) // No logging to avoid recursion
{
_udpTaskShouldRun = true;
while (_udpTaskShouldRun) {
TASK_HEARTBEAT(_heartbeat);
if (!_initializeQueue()) continue;
// Block waiting for a log entry, but wake up periodically to allow shutdown
LogEntry entry; // non-const for xQueueReceive
if (xQueueReceive(_udpLogQueue, &entry, pdMS_TO_TICKS(UDP_LOG_LOOP_INTERVAL)) != pdTRUE) {
// Timeout: check for stop notification
if (ulTaskNotifyTake(pdTRUE, 0) > 0) { _udpTaskShouldRun = false; break; }
continue;
}
// If not connected or UDP not initialized, requeue to front and wait
if (!_isUdpInitialized || !CustomNet::isFullyConnected()) {
xQueueSendToFront(_udpLogQueue, &entry, 0);
delay(DELAY_SEND_UDP);
continue;
}
// Prepare timestamp
char timestamp[TIMESTAMP_ISO_BUFFER_SIZE];
AdvancedLogger::getTimestampIsoUtcFromUnixTimeMilliseconds(
entry.unixTimeMilliseconds,
timestamp,
sizeof(timestamp)
);
// Format message
snprintf(_udpBuffer, UDP_LOG_BUFFER_SIZE,
"<%d>%s %s[%llu]: [%s][Core%d] %s[%s]: %s",
UDP_LOG_SERVERITY_FACILITY,
timestamp,
DEVICE_ID,
entry.millis,
AdvancedLogger::logLevelToString(entry.level),
entry.coreId,
entry.file,
entry.function,
entry.message);
// Send to configured destination
if (!acquireMutex(&_udpDestinationMutex, CONFIG_MUTEX_TIMEOUT_MS)) {
delay(DELAY_SEND_UDP);
continue;
}
if (!_udpClient.beginPacket(_udpDestination, UDP_LOG_PORT)) {
releaseMutex(&_udpDestinationMutex);
delay(DELAY_SEND_UDP);
continue;
}
size_t bytesWritten = _udpClient.write((const uint8_t*)_udpBuffer, strlen(_udpBuffer));
if (bytesWritten == 0) {
_udpClient.endPacket();
releaseMutex(&_udpDestinationMutex);
delay(DELAY_SEND_UDP);
continue;
}
if (!_udpClient.endPacket()) {
releaseMutex(&_udpDestinationMutex);
delay(DELAY_SEND_UDP);
continue;
}
releaseMutex(&_udpDestinationMutex);
}
// Removed LOG_DEBUG here to avoid recursive logging
_udpTaskHandle = NULL;
vTaskDelete(NULL);
}
TaskInfo getTaskInfo()
{
return getTaskInfoSafely(_udpTaskHandle, UDP_LOG_TASK_STACK_SIZE, &_heartbeat);
}
// UDP Destination Management
// ============================
static bool _loadUdpDestinationFromPreferences() // Cannot use logger here - reachable from _ensureUdpDestinationLoaded(), which runs inside the logger callback itself
{
Preferences prefs;
if (!prefs.begin(PREFERENCES_NAMESPACE_UDP_LOG, true)) {
return false;
}
char ipStr[IP_ADDRESS_BUFFER_SIZE];
size_t len = prefs.getString(PREFERENCES_KEY_UDP_DESTINATION, ipStr, sizeof(ipStr));
prefs.end();
if (len == 0) {
return false;
}
if (!acquireMutex(&_udpDestinationMutex, CONFIG_MUTEX_TIMEOUT_MS)) {
return false;
}
bool success = _udpDestination.fromString(ipStr);
releaseMutex(&_udpDestinationMutex);
if (success) {
Serial.printf("[DEBUG] Loaded UDP destination from preferences: %s\n", ipStr);
}
return success;
}
static bool _saveUdpDestinationToPreferences()
{
if (!acquireMutex(&_udpDestinationMutex, CONFIG_MUTEX_TIMEOUT_MS)) {
LOG_ERROR("Failed to acquire mutex for saving UDP destination");
return false;
}
String ipStr = _udpDestination.toString();
releaseMutex(&_udpDestinationMutex);
Preferences prefs;
if (!prefs.begin(PREFERENCES_NAMESPACE_UDP_LOG, false)) {
LOG_ERROR("Failed to open preferences for UDP destination");
return false;
}
bool success = prefs.putString(PREFERENCES_KEY_UDP_DESTINATION, ipStr.c_str()) > 0;
prefs.end();
if (success) {
LOG_DEBUG("Saved UDP destination to preferences: %s", ipStr.c_str());
}
return success;
}
bool getUdpDestination(char* ipAddress, size_t bufferSize)
{
if (!ipAddress || bufferSize < IP_ADDRESS_BUFFER_SIZE) {
LOG_ERROR("Invalid buffer for getting UDP destination");
return false;
}
if (!acquireMutex(&_udpDestinationMutex, CONFIG_MUTEX_TIMEOUT_MS)) {
LOG_ERROR("Failed to acquire mutex for getting UDP destination");
return false;
}
snprintf(ipAddress, bufferSize, "%s", _udpDestination.toString().c_str());
ipAddress[bufferSize - 1] = '\0';
releaseMutex(&_udpDestinationMutex);
return true;
}
bool setUdpDestination(const char* ipAddress)
{
if (!ipAddress) {
LOG_ERROR("Invalid IP address provided");
return false;
}
IPAddress newIp;
if (!newIp.fromString(ipAddress)) {
LOG_ERROR("Invalid IP address format: %s", ipAddress);
return false;
}
if (!acquireMutex(&_udpDestinationMutex, CONFIG_MUTEX_TIMEOUT_MS)) {
LOG_ERROR("Failed to acquire mutex for setting UDP destination");
return false;
}
_udpDestination = newIp;
releaseMutex(&_udpDestinationMutex);
bool saved = _saveUdpDestinationToPreferences();
if (saved) {
LOG_INFO("Updated UDP destination to: %s", ipAddress);
}
return saved;
}
}