Skip to content

Commit

Permalink
Redirect ESP log messages into virtual debug console
Browse files Browse the repository at this point in the history
  • Loading branch information
ranma committed Sep 28, 2024
1 parent b206cee commit 5cefc89
Show file tree
Hide file tree
Showing 3 changed files with 92 additions and 0 deletions.
27 changes: 27 additions & 0 deletions include/ESPLog.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
// SPDX-License-Identifier: GPL-2.0-or-later
#pragma once

#include <stdarg.h>
#include <TaskSchedulerDeclarations.h>
#include <mutex>

#define BUFFER_SIZE 500

class ESPLogClass {
public:
ESPLogClass();
void init(Scheduler& scheduler);
int vprintf(const char *format, va_list ap);

private:
void loop();

Task _loopTask;

uint8_t _buffer[BUFFER_SIZE];
uint16_t _buff_pos = 0;
std::mutex _lock;
};

extern ESPLogClass ESPLog;

63 changes: 63 additions & 0 deletions src/ESPLog.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* Copyright (C) 2022-2024 Thomas Basler and others
*/
#include "ESPLog.h"
#include "MessageOutput.h"

#include <Arduino.h>

ESPLogClass ESPLog;

namespace {

static int extern "C" wrap_vprintf(const char *format, va_list ap)
{
return ESPLog.vprintf(format, ap);
}

}; // namespace

ESPLogClass::ESPLogClass()
: _loopTask(TASK_IMMEDIATE, TASK_FOREVER, std::bind(&ESPLogClass::loop, this))
{
}

void ESPLogClass::init(Scheduler& scheduler)
{
scheduler.addTask(_loopTask);
_loopTask.enable();
esp_log_set_vprintf(wrap_vprintf);
}

void ESPLogClass::loop()
{
_lock.lock();
int front = 0;
int used = _buff_pos;
while (used > front) {
_lock.unlock();
MessageOutput.write(&_buffer[front], used);
_lock.lock();

front = used;
used = _buff_pos;
};
_buff_pos = 0;
_lock.unlock();
}

int ESPLogClass::vprintf(const char *format, va_list ap)
{
std::lock_guard<std::mutex> lock(_lock);
char *buf = reinterpret_cast<char*>(&_buffer[_buff_pos]);
size_t remain = sizeof(_buffer) - _buff_pos;

if (remain == 0) {
return 0;
}

int printed = vsnprintf(buf, remain, format, ap);
_buff_pos += printed;
return printed;
}
2 changes: 2 additions & 0 deletions src/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
#include "InverterSettings.h"
#include "Led_Single.h"
#include "MessageOutput.h"
#include "ESPLog.h"
#include "MqttHandleDtu.h"
#include "MqttHandleHass.h"
#include "MqttHandleInverter.h"
Expand Down Expand Up @@ -51,6 +52,7 @@ void setup()
yield();
#endif
MessageOutput.init(scheduler);
ESPLog.init(scheduler);
MessageOutput.println();
MessageOutput.println("Starting OpenDTU");

Expand Down

0 comments on commit 5cefc89

Please sign in to comment.