Second ADC debugging in process

This commit is contained in:
2026-04-21 16:11:07 +02:00
parent dce6b0fd4f
commit 7e7d0a1c59
7 changed files with 199 additions and 156 deletions

View File

@@ -14,10 +14,11 @@
#include "Arduino.h" #include "Arduino.h"
#include "ADS1256.h" #include "ADS1256.h"
#include "SPI.h" #include "SPI.h"
#include <DebugLog.h>
#define convertSigned24BitToLong(value) ((value) & (1l << 23) ? (value) - 0x1000000 : value) #define convertSigned24BitToLong(value) ((value) & (1l << 23) ? (value) - 0x1000000 : value)
void drdyCallback(void *arg) void IRAM_ATTR drdyCallback(void *arg)
{ {
auto cls = (ADS1256 *)arg; auto cls = (ADS1256 *)arg;
if (!arg) if (!arg)
@@ -61,11 +62,16 @@ ADS1256::ADS1256(const int8_t DRDY_pin, const int8_t RESET_pin, const int8_t SYN
updateConversionParameter(); updateConversionParameter();
m_drdyHigh = xSemaphoreCreateBinary(); // m_drdyHigh = xSemaphoreCreateBinary();
m_drdyLow = xSemaphoreCreateBinary(); // m_drdyLow = xSemaphoreCreateBinary();
xSemaphoreGive(m_drdyHigh); // if (!m_drdyHigh || !m_drdyLow) {
xSemaphoreGive(m_drdyLow); // LOG_ERROR("ADC Unable to create interrupt semaphores");
attachInterruptArg(DRDY_pin, drdyCallback, (void *)this, CHANGE); // return;
// }
// xSemaphoreGive(m_drdyHigh);
// xSemaphoreGive(m_drdyLow);
//attachInterruptArg(DRDY_pin, drdyCallback, (void *)this, CHANGE);
} }
// Initialization // Initialization
@@ -119,14 +125,16 @@ void ADS1256::InitializeADC()
void ADS1256::waitForLowDRDY() void ADS1256::waitForLowDRDY()
{ {
xSemaphoreTake(m_drdyLow, pdMS_TO_TICKS(10)); while(digitalRead(m_DRDY_pin) == HIGH) {vTaskDelay(1);};
xSemaphoreGive(m_drdyLow); // xSemaphoreTake(m_drdyLow, pdMS_TO_TICKS(10));
// xSemaphoreGive(m_drdyLow);
} }
void ADS1256::waitForHighDRDY() void ADS1256::waitForHighDRDY()
{ {
xSemaphoreTake(m_drdyHigh, pdMS_TO_TICKS(10)); while(digitalRead(m_DRDY_pin) == LOW) {vTaskDelay(1);};
xSemaphoreGive(m_drdyHigh); // xSemaphoreTake(m_drdyHigh, pdMS_TO_TICKS(10));
// xSemaphoreGive(m_drdyHigh);
} }
void ADS1256::stopConversion() // Sending SDATAC to stop the continuous conversion void ADS1256::stopConversion() // Sending SDATAC to stop the continuous conversion

View File

@@ -20,7 +20,6 @@ lib_deps =
hideakitai/PCA95x5@^0.1.3 hideakitai/PCA95x5@^0.1.3
me-no-dev/AsyncTCP@^3.3.2 me-no-dev/AsyncTCP@^3.3.2
me-no-dev/ESPAsyncWebServer@^3.6.0 me-no-dev/ESPAsyncWebServer@^3.6.0
adafruit/Adafruit NeoPixel@^1.15.4
upload_protocol = esptool upload_protocol = esptool
upload_port = /dev/ttyACM1 upload_port = /dev/ttyACM1
upload_speed = 921600 upload_speed = 921600
@@ -28,15 +27,14 @@ monitor_port = /dev/ttyACM0
monitor_speed = 921600 monitor_speed = 921600
build_type = release build_type = release
build_flags = build_flags =
-DCORE_DEBUG_LEVEL=5 -DCORE_DEBUG_LEVEL=3
-DARDUINO_USB_CDC_ON_BOOT=0 -DARDUINO_USB_CDC_ON_BOOT=0
-DARDUINO_USB_MODE=0 -DARDUINO_USB_MODE=0
-DCONFIG_ASYNC_TCP_MAX_ACK_TIME=5000 -DCONFIG_ASYNC_TCP_MAX_ACK_TIME=5000
-DCONFIG_ASYNC_TCP_PRIORITY=21 -DCONFIG_ASYNC_TCP_PRIORITY=21
-DCONFIG_ASYNC_TCP_QUEUE_SIZE=64 -DCONFIG_ASYNC_TCP_QUEUE_SIZE=128
-DCONFIG_ASYNC_TCP_RUNNING_CORE=1 -DCONFIG_ASYNC_TCP_RUNNING_CORE=1
-DCONFIG_ASYNC_TCP_STACK_SIZE=4096 -DCONFIG_ASYNC_TCP_STACK_SIZE=8192
-fstack-protector-all
[env:esp32-s3-devkitc1-n16r8-debug] [env:esp32-s3-devkitc1-n16r8-debug]
board = ${env:esp32-s3-devkitc1-n16r8.board} board = ${env:esp32-s3-devkitc1-n16r8.board}
@@ -46,7 +44,6 @@ platform = ${env:esp32-s3-devkitc1-n16r8.platform}
framework = ${env:esp32-s3-devkitc1-n16r8.framework} framework = ${env:esp32-s3-devkitc1-n16r8.framework}
lib_deps = lib_deps =
${env:esp32-s3-devkitc1-n16r8.lib_deps} ${env:esp32-s3-devkitc1-n16r8.lib_deps}
adafruit/Adafruit NeoPixel@^1.15.4
upload_protocol = esptool upload_protocol = esptool
upload_port = /dev/ttyACM1 upload_port = /dev/ttyACM1
upload_speed = 921600 upload_speed = 921600
@@ -59,7 +56,7 @@ build_flags =
-O0 -O0
-g3 -g3
-ggdb3 -ggdb3
-DCORE_DEBUG_LEVEL=5 -DCORE_DEBUG_LEVEL=3
-DARDUINO_USB_CDC_ON_BOOT=0 -DARDUINO_USB_CDC_ON_BOOT=0
-DARDUINO_USB_MODE=0 -DARDUINO_USB_MODE=0
-DCONFIG_ASYNC_TCP_MAX_ACK_TIME=5000 -DCONFIG_ASYNC_TCP_MAX_ACK_TIME=5000
@@ -67,4 +64,3 @@ build_flags =
-DCONFIG_ASYNC_TCP_QUEUE_SIZE=128 -DCONFIG_ASYNC_TCP_QUEUE_SIZE=128
-DCONFIG_ASYNC_TCP_RUNNING_CORE=1 -DCONFIG_ASYNC_TCP_RUNNING_CORE=1
-DCONFIG_ASYNC_TCP_STACK_SIZE=8192 -DCONFIG_ASYNC_TCP_STACK_SIZE=8192
-fstack-protector-all

View File

@@ -26,9 +26,9 @@
struct Devices struct Devices
{ {
// Busses // Busses
std::unique_ptr<TwoWire> m_i2c = nullptr; TwoWire *m_i2c = NULL;
std::unique_ptr<SPIClass> m_spi_a = nullptr; SPIClass *m_spi_a = NULL;
std::unique_ptr<SPIClass> m_spi_b = nullptr; SPIClass *m_spi_b = NULL;
// Bus Mutextes // Bus Mutextes
std::mutex m_spi_a_mutex; std::mutex m_spi_a_mutex;
@@ -36,13 +36,13 @@ struct Devices
std::mutex m_i2c_mutex; std::mutex m_i2c_mutex;
// Device Pointers // Device Pointers
std::unique_ptr<AD5292> m_pot_a = nullptr; AD5292 *m_pot_a = NULL;
std::unique_ptr<AD5292> m_pot_b = nullptr; AD5292 *m_pot_b = NULL;
std::unique_ptr<ADS1256> m_adc_a = nullptr; ADS1256 *m_adc_a = NULL;
std::unique_ptr<ADS1256> m_adc_b = nullptr; ADS1256 *m_adc_b = NULL;
std::unique_ptr<ExternalIO> m_ext_io = nullptr; ExternalIO *m_ext_io = NULL;
}; };
// Adc read channel wrapper to selet mux before reading // Adc read channel wrapper to selet mux before reading

View File

@@ -16,20 +16,24 @@
#include <ui.h> #include <ui.h>
#include <led.h> #include <led.h>
// Defines to enable channel B #define CH_A_ENABLE
#define CH_B_ENABLE #define CH_B_ENABLE
#define CH_A_RT_ENABLE
#define CH_B_RT_ENABLE
// #define I2C_ENABLE
// #define WEB_ENABLE
// Debug Defines // Debug Defines
#define WIFI_SSID "AstroRotaxMonitor" #define WIFI_SSID "AstroRotaxMonitor"
#define WIFI_PASSWORD "maledettirotax" #define WIFI_PASSWORD "maledettirotax"
#define PSRAM_MAX 4096 #define PSRAM_MAX 1024
#define QUEUE_MAX 256 #define QUEUE_MAX 32
void setup() void setup()
{ {
Serial.begin(115200); Serial.begin(115200);
delay(250); delay(250);
Serial.setTimeout(30000); Serial.setTimeout(5000);
// Setup Logger // Setup Logger
LOG_ATTACH_SERIAL(Serial); LOG_ATTACH_SERIAL(Serial);
@@ -48,27 +52,29 @@ void setup()
LOG_DEBUG("ESP32 Sketch:", ESP.getFreeSketchSpace()); LOG_DEBUG("ESP32 Sketch:", ESP.getFreeSketchSpace());
// Init Wifi station // Init Wifi station
// LOG_INFO("Initializing WiFi..."); #ifdef WEB_ENABLE
// WiFi.mode(WIFI_AP); LOG_INFO("Initializing WiFi...");
// IPAddress local_IP(10, 11, 12, 1); WiFi.mode(WIFI_AP);
// IPAddress gateway(10, 11, 12, 1); IPAddress local_IP(10, 11, 12, 1);
// IPAddress subnet(255, 255, 255, 0); IPAddress gateway(10, 11, 12, 1);
// WiFi.softAPConfig(local_IP, gateway, subnet); IPAddress subnet(255, 255, 255, 0);
// WiFi.setTxPower(WIFI_POWER_5dBm); // reduce wifi power WiFi.softAPConfig(local_IP, gateway, subnet);
// if (WiFi.softAP(WIFI_SSID, WIFI_PASSWORD)) WiFi.setTxPower(WIFI_POWER_5dBm); // reduce wifi power
// { if (WiFi.softAP(WIFI_SSID, WIFI_PASSWORD))
// LOG_INFO("WiFi AP Mode Started"); {
// LOG_INFO("Wifi SSID:", WIFI_SSID); LOG_INFO("WiFi AP Mode Started");
// LOG_INFO("Wifi Password:", WIFI_PASSWORD); LOG_INFO("Wifi SSID:", WIFI_SSID);
// LOG_INFO("WiFi IP:" + WiFi.softAPIP().toString()); LOG_INFO("Wifi Password:", WIFI_PASSWORD);
// } LOG_INFO("WiFi IP:" + WiFi.softAPIP().toString());
// else }
// { else
// LOG_ERROR("Failed to start WiFi AP Mode"); {
// LOG_ERROR("5 seconds to restart..."); LOG_ERROR("Failed to start WiFi AP Mode");
// vTaskDelay(pdMS_TO_TICKS(5000)); LOG_ERROR("5 seconds to restart...");
// esp_restart(); vTaskDelay(pdMS_TO_TICKS(5000));
// } esp_restart();
}
#endif
// Initialize Interrupt pins on PICKUP detectors // Initialize Interrupt pins on PICKUP detectors
initTriggerPinsInputs(); initTriggerPinsInputs();
@@ -84,7 +90,7 @@ void loop()
led.setBrightness(0.025f); led.setBrightness(0.025f);
led.setStatus(RGBled::LedStatus::INIT); led.setStatus(RGBled::LedStatus::INIT);
std::shared_ptr<Devices> dev = std::make_shared<Devices>(); Devices dev;
bool running = true; bool running = true;
std::mutex fs_mutex; std::mutex fs_mutex;
LITTLEFSGuard fsGuard; LITTLEFSGuard fsGuard;
@@ -94,34 +100,40 @@ void loop()
bool spiB_ok = true; bool spiB_ok = true;
//////// INIT SPI INTERFACES //////// //////// INIT SPI INTERFACES ////////
LOG_DEBUG("Init SPI Interfaces"); LOG_DEBUG("Init SPI Interfaces");
SPIClass SPI_A(FSPI); #ifdef CH_A_ENABLE
LOG_DEBUG("Begin Init SPI_A");
SPIClass SPI_A(HSPI);
spiA_ok = SPI_A.begin(SPI_A_SCK, SPI_A_MISO, SPI_A_MOSI); spiA_ok = SPI_A.begin(SPI_A_SCK, SPI_A_MISO, SPI_A_MOSI);
SPI_A.setDataMode(SPI_MODE1); // ADS1256 requires SPI mode 1 SPI_A.setDataMode(SPI_MODE1); // ADS1256 requires SPI mode 1
LOG_DEBUG("Init SPI A ok"); LOG_DEBUG("Init SPI_A -> OK");
Serial.readStringUntil('\n'); delay(500);
dev->m_spi_a.reset(&SPI_A); LOG_DEBUG("Begin Init ADC_A");
dev->m_adc_a = std::make_unique<ADS1256>(ADC_A_DRDY, ADS1256::PIN_UNUSED, ADS1256::PIN_UNUSED, ADC_A_CS, 2.5, &SPI_A); ADS1256 ADC_A(ADC_A_DRDY, ADS1256::PIN_UNUSED, ADS1256::PIN_UNUSED, ADC_A_CS, 2.5, &SPI_A);
dev->m_adc_a->InitializeADC(); ADC_A.InitializeADC();
dev->m_adc_a->setPGA(PGA_1); ADC_A.setPGA(PGA_1);
dev->m_adc_a->setDRATE(DRATE_7500SPS); ADC_A.setDRATE(DRATE_7500SPS);
LOG_DEBUG("Init ADC A ok"); dev.m_adc_a = &ADC_A;
Serial.readStringUntil('\n'); dev.m_spi_a = &SPI_A;
LOG_DEBUG("Init ADC_A -> OK");
delay(250); delay(1000);
#endif
#ifdef CH_B_ENABLE #ifdef CH_B_ENABLE
SPIClass SPI_B(HSPI); LOG_DEBUG("Begin Init SPI_B");
SPIClass SPI_B(FSPI);
spiB_ok = SPI_B.begin(SPI_B_SCK, SPI_B_MISO, SPI_B_MOSI); spiB_ok = SPI_B.begin(SPI_B_SCK, SPI_B_MISO, SPI_B_MOSI);
SPI_B.setDataMode(SPI_MODE1); // ADS1256 requires SPI mode 1 SPI_B.setDataMode(SPI_MODE1); // ADS1256 requires SPI mode 1
LOG_DEBUG("Init SPI B ok"); LOG_DEBUG("Init SPI_B -> OK");
Serial.readStringUntil('\n'); delay(500);
dev->m_spi_b.reset(&SPI_B); LOG_DEBUG("Begin Init ADC_B");
dev->m_adc_b = std::make_unique<ADS1256>(ADC_B_DRDY, ADS1256::PIN_UNUSED, ADS1256::PIN_UNUSED, ADC_B_CS, 2.5, &SPI_B); ADS1256 ADC_B(ADC_B_DRDY, ADS1256::PIN_UNUSED, ADS1256::PIN_UNUSED, ADC_B_CS, 2.5, &SPI_B);
dev->m_adc_b->InitializeADC(); ADC_B.InitializeADC();
dev->m_adc_b->setPGA(PGA_1); ADC_B.setPGA(PGA_1);
dev->m_adc_b->setDRATE(DRATE_7500SPS); ADC_B.setDRATE(DRATE_7500SPS);
LOG_DEBUG("Init ADC B ok"); dev.m_adc_b = &ADC_B;
Serial.readStringUntil('\n'); dev.m_spi_b = &SPI_B;
LOG_DEBUG("Init ADC_B -> OK");
delay(1000);
#endif #endif
if (!spiA_ok || !spiB_ok) if (!spiA_ok || !spiB_ok)
@@ -132,27 +144,29 @@ void loop()
esp_restart(); esp_restart();
} }
LOG_DEBUG("Init SPI OK"); LOG_DEBUG("Init SPI -> OK");
Serial.readStringUntil('\n');
//////// INIT I2C INTERFACES //////// //////// INIT I2C INTERFACES ////////
// LOG_DEBUG("Init I2C Interfaces"); #ifdef I2C_ENABLE
// bool i2c_ok = true; LOG_DEBUG("Init I2C Interfaces");
// i2c_ok = Wire.begin(SDA, SCL, 100000); bool i2c_ok = true;
// if (!i2c_ok) i2c_ok = Wire.begin(SDA, SCL, 100000);
// { if (!i2c_ok)
// LOG_ERROR("Unable to Initialize I2C Bus"); {
// LOG_ERROR("5 seconds to restart..."); LOG_ERROR("Unable to Initialize I2C Bus");
// vTaskDelay(pdMS_TO_TICKS(5000)); LOG_ERROR("5 seconds to restart...");
// esp_restart(); vTaskDelay(pdMS_TO_TICKS(5000));
// } esp_restart();
// LOG_DEBUG("Init I2c ok"); }
// Serial.readStringUntil('\n'); LOG_DEBUG("Init I2c ok");
Serial.readStringUntil('\n');
// Init IO Expanders // Init IO Expanders
// dev->m_ext_io = std::make_unique<ExternalIO>(Wire, dev->m_i2c_mutex, EXPANDER_ALL_INTERRUPT); dev->m_ext_io = std::make_unique<ExternalIO>(Wire, dev->m_i2c_mutex, EXPANDER_ALL_INTERRUPT);
#endif
//////// INIT REALTIME TASKS PARAMETERS //////// //////// INIT REALTIME TASKS PARAMETERS ////////
#ifdef CH_A_RT_ENABLE
const rtIgnitionTask::rtTaskParams taskA_params{ const rtIgnitionTask::rtTaskParams taskA_params{
.rt_running = true, .rt_running = true,
.name = "rtIgnTask_A", .name = "rtIgnTask_A",
@@ -182,8 +196,9 @@ void loop()
.relay_out_34 = RELAY_OUT_A34, .relay_out_34 = RELAY_OUT_A34,
}, },
.rt_queue = nullptr, .rt_queue = nullptr,
.dev = dev}; .dev = &dev};
#endif
#ifdef CH_B_RT_ENABLE
const rtIgnitionTask::rtTaskParams taskB_params{ const rtIgnitionTask::rtTaskParams taskB_params{
.rt_running = true, .rt_running = true,
.name = "rtIgnTask_B", .name = "rtIgnTask_B",
@@ -213,18 +228,30 @@ void loop()
.relay_out_34 = RELAY_OUT_B34, .relay_out_34 = RELAY_OUT_B34,
}, },
.rt_queue = nullptr, .rt_queue = nullptr,
.dev = dev}; .dev = &dev};
#endif
//////// SPAWN REALTIME TASKS //////// //////// SPAWN REALTIME TASKS ////////
auto task_A = rtIgnitionTask(taskA_params, PSRAM_MAX, QUEUE_MAX, CORE_0, fs_mutex); bool tasK_A_rt = true;
delay(50); bool task_B_rt = true;
Serial.readStringUntil('\n'); BaseType_t ignA_task_success = pdPASS;
BaseType_t ignB_task_success = pdPASS;
#ifdef CH_A_RT_ENABLE
auto task_A = rtIgnitionTask(taskA_params, PSRAM_MAX, QUEUE_MAX, CORE_1, fs_mutex);
ignA_task_success = task_A.getStatus() == rtIgnitionTask::OK ? pdPASS : pdFAIL;
//tasK_A_rt = task_A.start();
delay(1000);
#endif
#ifdef CH_B_RT_ENABLE
auto task_B = rtIgnitionTask(taskB_params, PSRAM_MAX, QUEUE_MAX, CORE_1, fs_mutex); auto task_B = rtIgnitionTask(taskB_params, PSRAM_MAX, QUEUE_MAX, CORE_1, fs_mutex);
Serial.readStringUntil('\n'); ignB_task_success = task_B.getStatus() == rtIgnitionTask::OK ? pdPASS : pdFAIL;
//task_B_rt = task_B.start();
delay(1000);
#endif
// Ignition A on Core 0 // Ignition A on Core 0
auto ignA_task_success = task_A.getStatus() == rtIgnitionTask::OK ? pdPASS : pdFAIL;
auto ignB_task_success = task_B.getStatus() == rtIgnitionTask::OK ? pdPASS : pdFAIL;
if (ignA_task_success != pdPASS || ignB_task_success != pdPASS) if (ignA_task_success != pdPASS || ignB_task_success != pdPASS)
{ {
LOG_ERROR("Unable to initialize ISR task"); LOG_ERROR("Unable to initialize ISR task");
@@ -232,10 +259,6 @@ void loop()
vTaskDelay(pdMS_TO_TICKS(5000)); vTaskDelay(pdMS_TO_TICKS(5000));
esp_restart(); esp_restart();
} }
const bool tasK_A_rt = task_A.start();
delay(50);
const bool task_B_rt = task_B.start();
if (tasK_A_rt != true || task_B_rt != true) if (tasK_A_rt != true || task_B_rt != true)
{ {
led.setStatus(RGBled::LedStatus::ERROR); led.setStatus(RGBled::LedStatus::ERROR);
@@ -248,18 +271,23 @@ void loop()
} }
//////// SPAWN WEBSERVER and WEBSOCKET //////// //////// SPAWN WEBSERVER and WEBSOCKET ////////
AstroWebServer webPage(80, LittleFS);
ArduinoJson::JsonDocument json_data; ArduinoJson::JsonDocument json_data;
bool data_a, data_b; bool data_a = false, data_b = false;
#ifdef WEB_ENABLE
AstroWebServer webPage(80, LittleFS);
delay(1000);
task_A.onMessage([&webPage, &json_data, &data_a](ignitionBoxStatusFiltered sts) task_A.onMessage([&webPage, &json_data, &data_a](ignitionBoxStatusFiltered sts)
{ {
json_data["box_a"] = sts.toJson(); json_data["box_a"] = sts.toJson();
data_a = true; }); data_a = true; });
#ifdef CH_B_RT_ENABLE
task_B.onMessage([&webPage, &json_data, &data_b](ignitionBoxStatusFiltered sts) task_B.onMessage([&webPage, &json_data, &data_b](ignitionBoxStatusFiltered sts)
{ {
json_data["box_b"] = sts.toJson(); json_data["box_b"] = sts.toJson();
data_b = true; }); data_b = true; });
#endif
#endif
// task_A.enableSave(true, "ignitionA_test.csv"); // task_A.enableSave(true, "ignitionA_test.csv");
// task_B.enableSave(true, "ignitionB_test.csv"); // task_B.enableSave(true, "ignitionB_test.csv");
@@ -270,12 +298,14 @@ void loop()
while (running) while (running)
{ {
uint32_t this_loop = millis(); uint32_t this_loop = millis();
if (this_loop - monitor_loop > 2000) if (this_loop - monitor_loop > 5000)
{ {
clearScreen(); clearScreen();
printRunningTasksMod(Serial); printRunningTasksMod(Serial);
monitor_loop = millis(); monitor_loop = millis();
} }
vTaskDelay(pdMS_TO_TICKS(10));
#ifdef WEB_ENABLE
if ((data_a && data_b) || (this_loop - data_loop > 500)) if ((data_a && data_b) || (this_loop - data_loop > 500))
{ {
webPage.sendWsData(json_data.as<String>()); webPage.sendWsData(json_data.as<String>());
@@ -283,6 +313,7 @@ void loop()
data_a = data_b = false; data_a = data_b = false;
data_loop = millis(); data_loop = millis();
} }
#endif
} //////////////// INNER LOOP ///////////////////// } //////////////// INNER LOOP /////////////////////
} ////////////////////// MAIN LOOP ////////////////////// } ////////////////////// MAIN LOOP //////////////////////

View File

@@ -16,9 +16,16 @@ void spark_timeout_callback(void *arg)
void rtIgnitionTask::rtIgnitionTask_manager(void *pvParameters) void rtIgnitionTask::rtIgnitionTask_manager(void *pvParameters)
{ {
rtIgnitionTask *cls = (rtIgnitionTask *)pvParameters; rtIgnitionTask *cls = (rtIgnitionTask *)pvParameters;
auto last_loop = millis();
uint32_t count(0);
while (cls->m_running) while (cls->m_running)
{ {
cls->run(); cls->run();
// if (millis() - last_loop > 2000) {
// LOG_DEBUG("TASK [", cls->m_name.c_str(), "] Alive -", count++);
// last_loop = millis();
// }
vTaskDelay(pdMS_TO_TICKS(1));
} }
} }
@@ -38,10 +45,12 @@ void rtIgnitionTask::rtIgnitionTask_realtime(void *pvParameters)
const rtTaskInterruptParams rt_int = params->rt_int; // 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 const rtTaskIOParams rt_rst = params->rt_io; // copy to avoid external override
QueueHandle_t rt_queue = params->rt_queue; QueueHandle_t rt_queue = params->rt_queue;
Devices *dev = params->dev.get(); Devices *dev = params->dev;
ADS1256 *adc = params->name == "rtIgnTask_A" ? dev->m_adc_a.get() : dev->m_adc_b.get(); ExternalIO *io = dev->m_ext_io;
std::mutex &spi_mutex = params->name == "rtIgnTask_A" ? dev->m_spi_a_mutex : dev->m_spi_b_mutex; // ADS1256 *adc = params->name == "rtIgnTask_A" ? dev->m_adc_a : dev->m_adc_b;
ExternalIO *io = dev->m_ext_io.get(); ADS1256 *adc = NULL;
// std::mutex &spi_mutex = params->name == "rtIgnTask_A" ? dev->m_spi_a_mutex : dev->m_spi_b_mutex;
std::mutex spi_mutex;
TaskStatus_t rt_task_info; TaskStatus_t rt_task_info;
vTaskGetInfo(NULL, &rt_task_info, pdFALSE, eInvalid); vTaskGetInfo(NULL, &rt_task_info, pdFALSE, eInvalid);
@@ -76,10 +85,6 @@ void rtIgnitionTask::rtIgnitionTask_realtime(void *pvParameters)
.ign_stat = &ign_box_sts, .ign_stat = &ign_box_sts,
.rt_handle_ptr = rt_task_info.xHandle}; .rt_handle_ptr = rt_task_info.xHandle};
LOG_DEBUG("rtTask HDL Params OK, HDL* [", (uint32_t)rt_task_info.xHandle, "]");
LOG_DEBUG("rtTask ISR Params OK, ISR* [", (uint32_t)rt_int.isr_ptr, "]");
LOG_DEBUG("rtTask QUE Params OK, QUE* [", (uint32_t)rt_queue, "]");
// Create esp_timer for microsecond precision timeout // Create esp_timer for microsecond precision timeout
esp_timer_handle_t timeout_timer; esp_timer_handle_t timeout_timer;
esp_timer_create_args_t timer_args = { esp_timer_create_args_t timer_args = {
@@ -87,7 +92,11 @@ void rtIgnitionTask::rtIgnitionTask_realtime(void *pvParameters)
.arg = (void *)rt_task_info.xHandle, .arg = (void *)rt_task_info.xHandle,
.dispatch_method = ESP_TIMER_TASK, .dispatch_method = ESP_TIMER_TASK,
.name = "spark_timeout"}; .name = "spark_timeout"};
esp_timer_create(&timer_args, &timeout_timer); if (esp_timer_create(&timer_args, &timeout_timer) != ESP_OK)
{
LOG_INFO("rtTask [", params->name.c_str(), "] Fail to allocate timeoutTimer");
vTaskDelete(NULL);
}
// Attach Pin Interrupts // 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_12p), rt_int.isr_ptr, (void *)&isr_params_t12p, RISING);
@@ -300,6 +309,7 @@ void rtIgnitionTask::rtIgnitionTask_realtime(void *pvParameters)
///////////// CLASS MEMBER DEFINITIONS ///////////// ///////////// 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) : m_params(params), m_filesystem(filesystem), m_fs_mutex(fs_mutex), m_core(core), m_max_history(history_size) 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) : m_params(params), m_filesystem(filesystem), m_fs_mutex(fs_mutex), m_core(core), m_max_history(history_size)
{ {
LOG_WARN("Starting Manager for [", m_params.name.c_str(), "]");
// create queue buffers // create queue buffers
m_queue = xQueueCreate(queue_size, sizeof(ignitionBoxStatus)); m_queue = xQueueCreate(queue_size, sizeof(ignitionBoxStatus));
if (!m_queue) if (!m_queue)
@@ -318,12 +328,12 @@ rtIgnitionTask::rtIgnitionTask(const rtTaskParams params, const uint32_t history
m_active_history = std::unique_ptr<PSHistory>(&m_history_0); m_active_history = std::unique_ptr<PSHistory>(&m_history_0);
m_save_history = std::unique_ptr<PSHistory>(&m_history_1); m_save_history = std::unique_ptr<PSHistory>(&m_history_1);
LOG_WARN("Starting Manager for [", m_params.name.c_str(), "]"); m_name = (std::string("man_") + m_params.name).c_str();
// auto task_success = pdPASS; // auto task_success = pdPASS;
auto task_success = xTaskCreatePinnedToCore( auto task_success = xTaskCreatePinnedToCore(
rtIgnitionTask_manager, rtIgnitionTask_manager,
(std::string("man_") + m_params.name).c_str(), m_name.c_str(),
8192, RT_TASK_STACK,
(void *)this, (void *)this,
m_params.rt_priority >> 2, m_params.rt_priority >> 2,
&m_manager_handle, &m_manager_handle,
@@ -362,14 +372,15 @@ void rtIgnitionTask::run()
m_last_data = millis(); m_last_data = millis();
m_manager_status = rtTaskStatus::RUNNING; m_manager_status = rtTaskStatus::RUNNING;
// if history buffer is full swap buffers and if enabled save history buffer // if history buffer is full swap buffers and if enabled save history buffer
if (m_counter_status >= m_active_history->size()) if (m_counter_status >= m_max_history)
{ {
LOG_DEBUG("Save for Buffer Full: ", m_counter_status); LOG_DEBUG("Save for Buffer Full: ", m_counter_status);
m_counter_status = 0; m_counter_status = 0;
m_partial_save = false; // reset partial save flag on new data cycle m_partial_save = false; // reset partial save flag on new data cycle
std::swap(m_active_history, m_save_history); std::swap(m_active_history, m_save_history);
if (m_enable_save) if (m_enable_save)
saveHistory(*m_save_history, m_history_path); // directly call the save task function to save without delay // saveHistory(m_save_history, m_history_path); // directly call the save task function to save without delay
LOG_INFO("Save History");
} }
// update filtered data // update filtered data
@@ -391,15 +402,14 @@ void rtIgnitionTask::run()
if (m_counter_status > 0 && !m_partial_save) if (m_counter_status > 0 && !m_partial_save)
{ {
LOG_DEBUG("Save Partial: ", m_counter_status); LOG_DEBUG("Save Partial: ", m_counter_status);
m_active_history->resize(m_counter_status); // m_active_history->resize(m_counter_status);
saveHistory(*m_active_history, m_history_path); // saveHistory(m_active_history, m_history_path);
m_active_history->resize(m_max_history); // m_active_history->resize(m_max_history);
m_counter_status = 0; m_counter_status = 0;
m_partial_save = true; m_partial_save = true;
} }
m_manager_status = rtTaskStatus::IDLE; m_manager_status = rtTaskStatus::IDLE;
} }
delay(5); // yeld to another task
} }
} }

View File

@@ -41,6 +41,7 @@ static const std::map<const uint32_t, const char *> names = {
class rtIgnitionTask class rtIgnitionTask
{ {
using PSHistory = PSRAMVector<ignitionBoxStatus>; using PSHistory = PSRAMVector<ignitionBoxStatus>;
// using PSHistory = std::vector<ignitionBoxStatus>;
public: public:
// RT task Interrupt parameters // RT task Interrupt parameters
@@ -84,7 +85,7 @@ public:
const rtTaskInterruptParams rt_int; // interrupt pins to attach const rtTaskInterruptParams rt_int; // interrupt pins to attach
const rtTaskIOParams rt_io; // reset ping for peak detectors const rtTaskIOParams rt_io; // reset ping for peak detectors
QueueHandle_t rt_queue; // queue for task io QueueHandle_t rt_queue; // queue for task io
const std::shared_ptr<Devices> dev; Devices *dev;
}; };
enum rtTaskStatus enum rtTaskStatus
@@ -124,6 +125,7 @@ private: // static functions for FreeRTOS
private: private:
bool m_running = true; bool m_running = true;
rtTaskStatus m_manager_status = INIT; rtTaskStatus m_manager_status = INIT;
std::string m_name;
rtTaskParams m_params; rtTaskParams m_params;
const uint8_t m_core; const uint8_t m_core;

View File

@@ -7,7 +7,7 @@
#include "esp_heap_caps.h" #include "esp_heap_caps.h"
#include "esp_system.h" #include "esp_system.h"
#include "esp_spi_flash.h" #include "spi_flash_mmap.h"
#include "esp_partition.h" #include "esp_partition.h"
#include "LittleFS.h" #include "LittleFS.h"
@@ -49,23 +49,27 @@ void printBar(Print &printer, const char *label, size_t used, size_t total, cons
{ {
float perc = total > 0 ? ((float)used / total) : 0; float perc = total > 0 ? ((float)used / total) : 0;
int filled = perc * BAR_WIDTH; int filled = perc * BAR_WIDTH;
char str[256] = {0};
uint16_t k(0);
printer.printf("%s%-12s [" COLOR_RESET, color, label); k += sprintf(str, "%s%-12s [" COLOR_RESET, color, label);
for (int i = 0; i < BAR_WIDTH; i++) for (int i = 0; i < BAR_WIDTH; i++)
{ {
if (i < filled) if (i < filled)
printer.printf("%s#%s", color, COLOR_RESET); k += sprintf(&str[k], "%s#%s", color, COLOR_RESET);
else else
printer.printf("-"); k += sprintf(&str[k], "-");
} }
printer.printf("] %s%6.2f%%%s (%5.3f/%5.3f)MB\n", sprintf(&str[k], "] %s%6.2f%%%s (%5.3f/%5.3f)MB\n",
color, color,
perc * 100.0, perc * 100.0,
COLOR_RESET, COLOR_RESET,
(used / 1024.0f / 1024.0f), (used / 1024.0f / 1024.0f),
(total / 1024.0f / 1024.0f)); (total / 1024.0f / 1024.0f));
printer.println(str);
} }
void printRunningTasksMod(Print &printer, std::function<bool(const TaskStatus_t &a, const TaskStatus_t &b)> orderBy) void printRunningTasksMod(Print &printer, std::function<bool(const TaskStatus_t &a, const TaskStatus_t &b)> orderBy)
@@ -95,6 +99,7 @@ void printRunningTasksMod(Print &printer, std::function<bool(const TaskStatus_t
// Compute system total runtime // Compute system total runtime
ulCurrentRunTime = ulTotalRunTime - ulLastRunTime; ulCurrentRunTime = ulTotalRunTime - ulLastRunTime;
ulCurrentRunTime = ulCurrentRunTime > 0 ? ulCurrentRunTime : 1;
ulLastRunTime = ulTotalRunTime; ulLastRunTime = ulTotalRunTime;
// PRINT MEMORY INFO // PRINT MEMORY INFO
@@ -134,17 +139,6 @@ void printRunningTasksMod(Print &printer, std::function<bool(const TaskStatus_t
ESP_PARTITION_SUBTYPE_APP_FACTORY, ESP_PARTITION_SUBTYPE_APP_FACTORY,
NULL); NULL);
if (app_partition)
{
size_t totalAPP = app_partition->size; // dimensione reale partizione
size_t sketchSize = ESP.getSketchSize();
printBar(printer, "FLASH APP", sketchSize, totalAPP, COLOR_CYAN);
}
else
{
printer.printf(COLOR_YELLOW "%-12s [NOT FOUND]\n" COLOR_RESET, "FLASH APP");
}
// ===== LITTLEFS (corretto con partition table) ===== // ===== LITTLEFS (corretto con partition table) =====
const esp_partition_t *fs_partition = const esp_partition_t *fs_partition =
esp_partition_find_first(ESP_PARTITION_TYPE_DATA, esp_partition_find_first(ESP_PARTITION_TYPE_DATA,
@@ -164,7 +158,9 @@ void printRunningTasksMod(Print &printer, std::function<bool(const TaskStatus_t
// ===== MIN HEAP ===== // ===== MIN HEAP =====
size_t minHeap = esp_get_minimum_free_heap_size(); size_t minHeap = esp_get_minimum_free_heap_size();
printer.printf("%s\nMin Heap Ever:%s %u KB\n\n", COLOR_RED, COLOR_RESET, minHeap / 1024); printer.printf("%s\nMin Heap Ever:%s %u KB\n", COLOR_RED, COLOR_RESET, minHeap / 1024);
size_t max_block = heap_caps_get_largest_free_block(MALLOC_CAP_SPIRAM);
printer.printf("%s\nMax PSRAM Block:%s %u KB\n\n", COLOR_RED, COLOR_RESET, max_block / 1024);
// Print Runtime Information // Print Runtime Information
printer.printf("Tasks: %u, Runtime: %lus, Period: %luus\r\n", uxArraySize, ulTotalRunTime / 1000000, ulCurrentRunTime); printer.printf("Tasks: %u, Runtime: %lus, Period: %luus\r\n", uxArraySize, ulTotalRunTime / 1000000, ulCurrentRunTime);