task refactoring work in progress

This commit is contained in:
Emanuele Trabattoni
2026-04-11 15:49:40 +02:00
parent 684c34e209
commit d1b96e932c
5 changed files with 367 additions and 185 deletions

View File

@@ -1,5 +1,8 @@
#include "tasks.h"
#include <esp_timer.h>
#include <datasave.h>
//// GLOBAL STATIC FUNCTIONS
// Timeout callback for microsecond precision
void spark_timeout_callback(void *arg)
@@ -8,7 +11,18 @@ void spark_timeout_callback(void *arg)
xTaskNotify(handle, SPARK_FLAG_TIMEOUT, eSetValueWithOverwrite);
}
void rtIgnitionTask::rtIgnitionTask_run(void *pvParameters)
// Manages queue receive, save data and callback to external tasks for communication
void rtIgnitionTask::rtIgnitionTask_manager(void *pvParameters)
{
rtIgnitionTask *cls = (rtIgnitionTask *)pvParameters;
while (cls->m_running)
{
cls->run();
}
}
// Static task function
void rtIgnitionTask::rtIgnitionTask_realtime(void *pvParameters)
{
// Invalid real time rt_task_ptr parameters, exit immediate
@@ -18,19 +32,18 @@ void rtIgnitionTask::rtIgnitionTask_run(void *pvParameters)
vTaskDelete(NULL);
}
// Task Parameters and Devices
rtTaskParams *params = (rtTaskParams *)pvParameters;
const rtTaskInterrupts rt_int = params->rt_int; // copy to avoid external override
const rtTaskResets rt_rst = params->rt_resets; // copy to avoid external override
const rtTaskInterruptParams rt_int = params->rt_int; // copy to avoid external override
const rtTaskIOParams rt_rst = params->rt_io; // copy to avoid external override
QueueHandle_t rt_queue = params->rt_queue;
Devices *dev = params->dev;
Devices *dev = params->dev.get();
ADS1256 *adc = dev->adc_a;
PCA9555 *io = dev->io;
TaskStatus_t rt_task_info;
vTaskGetInfo(NULL, &rt_task_info, pdFALSE, eInvalid);
const auto rt_task_name = pcTaskGetName(rt_task_info.xHandle);
LOG_INFO("rtTask Params OK [", rt_task_name, "]");
@@ -75,7 +88,6 @@ void rtIgnitionTask::rtIgnitionTask_run(void *pvParameters)
.name = "spark_timeout"};
esp_timer_create(&timer_args, &timeout_timer);
// Attach Pin Interrupts
attachInterruptArg(digitalPinToInterrupt(rt_int.trig_pin_12p), rt_int.isr_ptr, (void *)&isr_params_t12p, RISING);
attachInterruptArg(digitalPinToInterrupt(rt_int.trig_pin_12n), rt_int.isr_ptr, (void *)&isr_params_t12n, RISING);
@@ -235,17 +247,13 @@ void rtIgnitionTask::rtIgnitionTask_run(void *pvParameters)
ign_box_sts.adc_read_time = (int32_t)(esp_timer_get_time() - start_adc_read);
}
else // simulate adc read timig
vTaskDelay(pdMS_TO_TICKS(1));
vTaskDelay(pdMS_TO_TICKS(c_adc_time));
// reset peak detectors + sample and hold
// outputs on io expander
if (io)
{
const uint16_t iostat = io->read();
const uint16_t rst_bitmask = (0x0001 << rt_rst.rst_io_peak);
io->write(iostat | rst_bitmask);
vTaskDelay(pdMS_TO_TICKS(1));
io->write(iostat & ~rst_bitmask);
// [TODO] code to reset sample and hold and arm trigger level detectors
}
else
vTaskDelay(pdMS_TO_TICKS(1));
@@ -261,7 +269,7 @@ void rtIgnitionTask::rtIgnitionTask_run(void *pvParameters)
}
// Delete the timeout timer
esp_timer_delete(timeout_timer);
LOG_WARN("Ending realTime Task");
LOG_WARN("rtTask Ending [", rt_task_name, "]");
// Ignition A Interrupts DETACH
detachInterrupt(rt_int.trig_pin_12p);
detachInterrupt(rt_int.trig_pin_12n);
@@ -272,3 +280,229 @@ void rtIgnitionTask::rtIgnitionTask_run(void *pvParameters)
// delete present task
vTaskDelete(NULL);
}
///////////// CLASS MEMBER DEFINITIONS /////////////
rtIgnitionTask::rtIgnitionTask(const rtTaskParams params, const uint32_t history_size, const uint32_t queue_size, const uint8_t core, std::mutex &fs_mutex, fs::FS &filesystem = LittleFS) : m_params(params), m_filesystem(filesystem), m_fs_mutex(fs_mutex), m_core(core)
{
// create queue buffers
m_queue = xQueueCreate(queue_size, sizeof(ignitionBoxStatus));
if (!m_queue)
{
LOG_ERROR("Unable To Create Task [", params.name.c_str(), "] queues");
m_manager_status = rtTaskStatus::ERROR;
return;
}
else
m_params.rt_queue = m_queue;
// create PSram history vectors
m_history_0.resize(history_size);
m_history_1.resize(history_size);
// assing active and writable history
m_active_history = std::make_unique<PSHistory>(m_history_0.data());
m_save_history = std::make_unique<PSHistory>(m_history_1.data());
LOG_WARN("Starting Manager for [", m_params.name.c_str(), "]");
auto task_success = xTaskCreate(
rtIgnitionTask_manager,
(std::string("man_") + m_params.name).c_str(),
m_params.rt_stack_size,
(void *)this,
1,
&m_manager_handle);
if (task_success != pdPASS)
{
LOG_ERROR("Unable To Create Manager for [", params.name.c_str(), "]");
m_manager_status = rtTaskStatus::ERROR;
return;
}
// average every 10 samples
m_info_filtered = ignitionBoxStatusFiltered(10);
m_last_data = millis();
m_manager_status = rtTaskStatus::OK;
}
rtIgnitionTask::~rtIgnitionTask()
{
if (m_rt_handle)
vTaskDelete(m_rt_handle);
if (m_manager_handle)
vTaskDelete(m_manager_handle);
if (m_queue)
vQueueDelete(m_queue);
}
void rtIgnitionTask::run()
{
// receive new data from the queue
auto new_data = xQueueReceive(m_queue, &m_last_status, 0); // non blocking receive
if (new_data == pdPASS)
{
m_manager_status = rtTaskStatus::RUNNING;
// if history buffer is full swap buffers and if enabled save history buffer
if (m_counter_status >= m_active_history->size())
{
m_counter_status = 0;
m_partial_save = false; // reset partial save flag on new data cycle
std::swap(m_active_history, m_save_history);
if (m_enable_save)
save_history(*m_save_history, m_history_path); // directly call the save task function to save without delay
}
// update filtered data
m_info_filtered.update(m_last_status);
(*m_active_history)[m_counter_status] = m_last_status;
// update data counter
m_counter_status++;
}
else
{
if (millis() - m_last_data > c_idle_time)
m_manager_status = rtTaskStatus::IDLE;
delay(5); // yeld to another task
}
}
const bool rtIgnitionTask::start()
{
LOG_WARN("Starting rtTask [", m_params.name.c_str(), "]");
auto task_success = xTaskCreatePinnedToCore(
rtIgnitionTask_realtime,
m_params.name.c_str(),
m_params.rt_stack_size,
(void *)&m_params,
m_params.rt_priority,
&m_rt_handle,
m_core);
const bool success = task_success == pdPASS && m_rt_handle != nullptr;
if (success)
m_manager_status = rtTaskStatus::IDLE;
return success;
}
const bool rtIgnitionTask::stop()
{
LOG_WARN("Ending Task [", m_params.name.c_str(), "]");
if (m_rt_handle)
{
m_params.rt_running = false;
m_rt_handle = nullptr;
m_manager_status = rtTaskStatus::STOPPED;
return true;
}
return false;
}
const ignitionBoxStatus rtIgnitionTask::getLast() const
{
return m_last_status;
}
const ignitionBoxStatusFiltered rtIgnitionTask::getFiltered() const
{
return m_info_filtered;
}
const rtIgnitionTask::rtTaskStatus rtIgnitionTask::getStatus() const
{
return m_manager_status;
}
void rtIgnitionTask::enableSave(const bool enable, const std::filesystem::path filename)
{
m_enable_save = enable;
if (enable && !filename.empty())
{
LOG_WARN("Save History Enabled Task [", m_params.name.c_str(), "]");
m_history_path = m_filesystem.mountpoint() / filename;
}
else
{
LOG_WARN("Save History Disabled Task [", m_params.name.c_str(), "]");
}
}
void rtIgnitionTask::saveHistory(const rtIgnitionTask::PSHistory &history, const std::filesystem::path &file_name)
{
// Lock filesystem mutex to avoid concurrent access
std::lock_guard<std::mutex> fs_lock(m_fs_mutex);
// Check for free space
if (LittleFS.totalBytes() - LittleFS.usedBytes() < history.size() * sizeof(ignitionBoxStatus) * 200) // check if at least 1MB is free for saving history
{
LOG_ERROR("Not enough space in SPIFFS to save history");
return;
}
// create complete file path
const std::filesystem::path mount_point = std::filesystem::path(m_filesystem.mountpoint());
std::filesystem::path file_path = file_name;
if (file_name.root_path() != mount_point)
file_path = mount_point / file_name;
// if firt save remove old file and create new
auto save_flags = std::ios::out;
if (m_first_save && m_filesystem.exists(file_path.c_str()))
{
m_first_save = false;
save_flags |= std::ios::trunc; // overwrite existing file
m_filesystem.remove(file_path.c_str()); // ensure file is removed before saving to avoid issues with appending to existing file in SPIFFS
LOG_INFO("Saving history to Flash, new file:", file_path.c_str());
}
else // else append to existing file
{
save_flags |= std::ios::app; // append to new file
LOG_INFO("Saving history to Flash, appending to existing file:", file_path.c_str());
}
std::ofstream ofs(file_path, save_flags);
if (ofs.fail())
{
LOG_ERROR("Failed to open file for writing");
return;
}
// write csv header
if (m_first_save)
{
ofs << "TS,\
EVENTS_12,DLY_12,STAT_12,V_12_1,V_12_2,V_12_3,V_12_4,IGNITION_MODE_12,\
EVENTS_34,DLY_34,STAT_34,V_34_1,V_34_2,V_34_3,V_34_4,IGNITION_MODE_34,\
ENGINE_RPM,ADC_READTIME,N_QUEUE_ERRORS"
<< std::endl;
ofs.flush();
}
for (const auto &entry : history)
{
ofs << std::to_string(entry.timestamp) << ","
<< std::to_string(entry.coils12.n_events) << ","
<< std::to_string(entry.coils12.spark_delay) << ","
<< std::string(sparkStatusNames.at(entry.coils12.spark_status)) << ","
<< std::to_string(entry.coils12.peak_p_in) << ","
<< std::to_string(entry.coils12.peak_n_in) << ","
<< std::to_string(entry.coils12.peak_p_out) << ","
<< std::to_string(entry.coils12.peak_n_out) << ","
<< std::string(softStartStatusNames.at(entry.coils12.sstart_status)) << ","
<< std::to_string(entry.coils34.n_events) << ","
<< std::to_string(entry.coils34.spark_delay) << ","
<< std::string(sparkStatusNames.at(entry.coils34.spark_status)) << ","
<< std::to_string(entry.coils34.peak_p_in) << ","
<< std::to_string(entry.coils34.peak_n_in) << ","
<< std::to_string(entry.coils34.peak_p_out) << ","
<< std::to_string(entry.coils34.peak_n_out) << ","
<< std::string(softStartStatusNames.at(entry.coils34.sstart_status)) << ","
<< std::to_string(entry.eng_rpm) << ","
<< std::to_string(entry.adc_read_time) << ","
<< std::to_string(entry.n_queue_errors);
ofs << std::endl;
ofs.flush();
}
ofs.close();
LOG_INFO("Ignition Box history saved to Flash, records written: ", history.size());
}