Compare commits

...

5 Commits

Author SHA1 Message Date
Emanuele Trabattoni
97bce90ba6 changed partition to littlefs, not working yet 2026-04-08 17:10:30 +02:00
Emanuele Trabattoni
12e1e8e7a4 Fixed Filters, split file in html, script and css 2026-04-08 16:55:03 +02:00
Emanuele Trabattoni
4dc45954e9 Webpage is OK, html in memory since SPIFFS is to slow.
Moving average to be fixed
2026-04-08 15:23:21 +02:00
Emanuele Trabattoni
07eb06f67b Save History Sync on flash, still some issues in deleting previous file 2026-04-08 10:27:18 +02:00
Emanuele Trabattoni
481f12f526 Enable/Disable pickup simulation 2026-04-08 10:26:44 +02:00
16 changed files with 726 additions and 115 deletions

View File

@@ -0,0 +1,88 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>ESP32 Dashboard</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h2>RotaxMonitor realtime data</h2>
<button onclick="start()">Start</button>
<button onclick="stop()">Stop</button>
<div style="max-width: 900px; margin: 0 auto; text-align: left;">
<p><strong>Timestamp:</strong> <span id="timestamp">-</span></p>
<p><strong>Data Valid:</strong> <span id="datavalid">-</span></p>
<p><strong>Generator voltage:</strong> <span id="volts_gen">-</span></p>
<p><strong>Engine RPM:</strong> <span id="eng_rpm">-</span></p>
<p><strong>ADC read time:</strong> <span id="adc_read_time">-</span></p>
<p><strong>Queue errors:</strong> <span id="n_queue_errors">-</span></p>
<table>
<thead>
<tr>
<th>Property</th>
<th>Coils 12</th>
<th>Coils 34</th>
</tr>
</thead>
<tbody>
<tr>
<td>Spark delay</td>
<td id="coils12_spark_delay">-</td>
<td id="coils34_spark_delay">-</td>
</tr>
<tr>
<td>Spark status</td>
<td id="coils12_spark_status">-</td>
<td id="coils34_spark_status">-</td>
</tr>
<tr>
<td>Soft start status</td>
<td id="coils12_sstart_status">-</td>
<td id="coils34_sstart_status">-</td>
</tr>
<tr>
<td>Peak P in</td>
<td id="coils12_peak_p_in">-</td>
<td id="coils34_peak_p_in">-</td>
</tr>
<tr>
<td>Peak N in</td>
<td id="coils12_peak_n_in">-</td>
<td id="coils34_peak_n_in">-</td>
</tr>
<tr>
<td>Peak P out</td>
<td id="coils12_peak_p_out">-</td>
<td id="coils34_peak_p_out">-</td>
</tr>
<tr>
<td>Peak N out</td>
<td id="coils12_peak_n_out">-</td>
<td id="coils34_peak_n_out">-</td>
</tr>
<tr>
<td>Level spark</td>
<td id="coils12_level_spark">-</td>
<td id="coils34_level_spark">-</td>
</tr>
<tr>
<td>Events</td>
<td id="coils12_n_events">-</td>
<td id="coils34_n_events">-</td>
</tr>
<tr>
<td>Missed firings</td>
<td id="coils12_n_missed_firing">-</td>
<td id="coils34_n_missed_firing">-</td>
</tr>
</tbody>
</table>
</div>
<script src="script.js"></script>
</body>
</html>

View File

@@ -0,0 +1,66 @@
let ws;
function connectWS() {
ws = new WebSocket("ws://" + location.host + "/ws");
ws.onopen = () => {
console.log("WebSocket connesso");
};
ws.onclose = () => {
console.log("WebSocket disconnesso, retry...");
setTimeout(connectWS, 5000);
};
ws.onmessage = (event) => {
let data;
try {
data = JSON.parse(event.data);
} catch (e) {
console.error("Invalid JSON received", e);
return;
}
document.getElementById("datavalid").textContent = data.datavalid ?? "-";
document.getElementById("timestamp").textContent = data.timestamp ?? "-";
document.getElementById("volts_gen").textContent = data.volts_gen ?? "-";
document.getElementById("eng_rpm").textContent = data.eng_rpm ?? "-";
document.getElementById("adc_read_time").textContent = data.adc_read_time ?? "-";
document.getElementById("n_queue_errors").textContent = data.n_queue_errors ?? "-";
const coils12 = data.coils12 || {};
const coils34 = data.coils34 || {};
document.getElementById("coils12_spark_delay").textContent = coils12.spark_delay ?? "-";
document.getElementById("coils34_spark_delay").textContent = coils34.spark_delay ?? "-";
document.getElementById("coils12_spark_status").textContent = coils12.spark_status ?? "-";
document.getElementById("coils34_spark_status").textContent = coils34.spark_status ?? "-";
document.getElementById("coils12_sstart_status").textContent = coils12.sstart_status ?? "-";
document.getElementById("coils34_sstart_status").textContent = coils34.sstart_status ?? "-";
document.getElementById("coils12_peak_p_in").textContent = coils12.peak_p_in ?? "-";
document.getElementById("coils34_peak_p_in").textContent = coils34.peak_p_in ?? "-";
document.getElementById("coils12_peak_n_in").textContent = coils12.peak_n_in ?? "-";
document.getElementById("coils34_peak_n_in").textContent = coils34.peak_n_in ?? "-";
document.getElementById("coils12_peak_p_out").textContent = coils12.peak_p_out ?? "-";
document.getElementById("coils34_peak_p_out").textContent = coils34.peak_p_out ?? "-";
document.getElementById("coils12_peak_n_out").textContent = coils12.peak_n_out ?? "-";
document.getElementById("coils34_peak_n_out").textContent = coils34.peak_n_out ?? "-";
document.getElementById("coils12_level_spark").textContent = coils12.level_spark ?? "-";
document.getElementById("coils34_level_spark").textContent = coils34.level_spark ?? "-";
document.getElementById("coils12_n_events").textContent = coils12.n_events ?? "-";
document.getElementById("coils34_n_events").textContent = coils34.n_events ?? "-";
document.getElementById("coils12_n_missed_firing").textContent = coils12.n_missed_firing ?? "-";
document.getElementById("coils34_n_missed_firing").textContent = coils34.n_missed_firing ?? "-";
};
}
function start() {
fetch("/start");
}
function stop() {
fetch("/stop");
}
connectWS();

View File

@@ -0,0 +1,29 @@
body {
font-family: Arial;
text-align: center;
margin-top: 40px;
}
table {
margin: auto;
border-collapse: collapse;
width: 100%;
max-width: 900px;
}
th, td {
border: 1px solid #ccc;
padding: 10px;
font-size: 16px;
text-align: left;
}
th {
background-color: #f4f4f4;
}
button {
margin: 10px;
padding: 10px 20px;
font-size: 16px;
}

View File

@@ -0,0 +1,6 @@
# ESP32 Partition Table
# Name, Type, SubType, Offset, Size
nvs, data, nvs, 0x9000, 0x4000
phy_init, data, phy, 0xd000, 0x1000
factory, app, factory, 0x10000, 0x300000
littlefs, data, littlefs, 0x310000, 0xCF0000
1 # ESP32 Partition Table
2 # Name, Type, SubType, Offset, Size
3 nvs, data, nvs, 0x9000, 0x4000
4 phy_init, data, phy, 0xd000, 0x1000
5 factory, app, factory, 0x10000, 0x300000
6 littlefs, data, littlefs, 0x310000, 0xCF0000

View File

@@ -2,5 +2,5 @@
# Name, Type, SubType, Offset, Size
nvs, data, nvs, 0x9000, 0x4000
phy_init, data, phy, 0xd000, 0x1000
factory, app, factory, 0x10000, 0x5F0000
spiffs, data, spiffs, 0x600000, 0xA00000
factory, app, factory, 0x10000, 0x300000
spiffs, data, spiffs, 0x310000, 0xCF0000
1 # ESP32 Partition Table
2 # Name, Type, SubType, Offset, Size
3 nvs, data, nvs, 0x9000, 0x4000
4 phy_init, data, phy, 0xd000, 0x1000
5 factory, app, factory, 0x10000, 0x5F0000 factory, app, factory, 0x10000, 0x300000
6 spiffs, data, spiffs, 0x600000, 0xA00000 spiffs, data, spiffs, 0x310000, 0xCF0000

View File

@@ -10,61 +10,63 @@
[env:esp32-s3-devkitc1-n16r8]
board = esp32-s3-devkitc1-n16r8
board_build.partitions = partitions/no_ota_10mb_spiffs.csv
board_build.partitions = partitions/no_ota_10mb_littlefs.csv
board_build.filesystem = littlefs
platform = https://github.com/pioarduino/platform-espressif32/releases/download/stable/platform-espressif32.zip
framework = arduino
lib_deps =
hideakitai/DebugLog@^0.8.4
bblanchon/ArduinoJson@^7.4.2
hideakitai/PCA95x5@^0.1.3
adafruit/Adafruit SSD1306@^2.5.16
garfius/Menu-UI@^1.2.0
;Upload protocol configuration
me-no-dev/AsyncTCP@^3.3.2
me-no-dev/ESPAsyncWebServer@^3.6.0
upload_protocol = esptool
upload_port = COM8
upload_port = COM4
upload_speed = 921600
;Monitor configuration
monitor_port = COM4
monitor_speed = 921600
; Build configuration
build_type = release
build_flags =
-DARDUINO_USB_CDC_ON_BOOT=0
-DARDUINO_USB_MODE=0
-fstack-protector-all
-DCONFIG_FREERTOS_GENERATE_RUN_TIME_STATS=1
-DCONFIG_FREERTOS_USE_TRACE_FACILITY=1
-DCORE_DEBUG_LEVEL=5
-DARDUINO_USB_CDC_ON_BOOT=0
-DARDUINO_USB_MODE=0
-DCONFIG_FREERTOS_GENERATE_RUN_TIME_STATS=1
-DCONFIG_FREERTOS_USE_TRACE_FACILITY=1
-DCONFIG_ASYNC_TCP_MAX_ACK_TIME=5000
-DCONFIG_ASYNC_TCP_PRIORITY=20
-DCONFIG_ASYNC_TCP_QUEUE_SIZE=128
-DCONFIG_ASYNC_TCP_RUNNING_CORE=1
-DCONFIG_ASYNC_TCP_STACK_SIZE=8192
-fstack-protector-all
[env:esp32-s3-devkitc1-n16r8-debug]
board = ${env:esp32-s3-devkitc1-n16r8.board}
board_build.partitions = ${env:esp32-s3-devkitc1-n16r8.board_build.partitions}
board_build.filesystem = ${env:esp32-s3-devkitc1-n16r8.board_build.filesystem}
platform = ${env:esp32-s3-devkitc1-n16r8.platform}
framework = ${env:esp32-s3-devkitc1-n16r8.framework}
lib_deps = ${env:esp32-s3-devkitc1-n16r8.lib_deps}
;Upload protocol configuration
lib_deps =
${env:esp32-s3-devkitc1-n16r8.lib_deps}
upload_protocol = esptool
upload_port = COM4
upload_port = COM8
upload_speed = 921600
;Monitor configuration
monitor_port = COM4
monitor_speed = 921600
; Debug configuration
debug_tool = esp-builtin
debug_speed = 15000
; Build configuration
build_type = debug
build_flags =
-O0
-g3
-ggdb3
-DCORE_DEBUG_LEVEL=5
-DARDUINO_USB_CDC_ON_BOOT=0
-DARDUINO_USB_MODE=0
-fstack-protector-all
-O0
-g3
-ggdb3
-DCORE_DEBUG_LEVEL=5
-DARDUINO_USB_CDC_ON_BOOT=0
-DARDUINO_USB_MODE=0
-DCONFIG_FREERTOS_GENERATE_RUN_TIME_STATS=1
-DCONFIG_FREERTOS_USE_TRACE_FACILITY=1
-DCONFIG_ASYNC_TCP_MAX_ACK_TIME=5000
-DCONFIG_ASYNC_TCP_PRIORITY=20
-DCONFIG_ASYNC_TCP_QUEUE_SIZE=128
-DCONFIG_ASYNC_TCP_RUNNING_CORE=1
-DCONFIG_ASYNC_TCP_STACK_SIZE=8192
-fstack-protector-all

View File

@@ -1,45 +1,158 @@
#include "datasave.h"
#include <math.h>
static const size_t min_free = 1024 * 1024; // minimum free space in SPIFFS to allow saving history (1MB)
static bool first_save = true; // flag to indicate if this is the first save (to write header)
void save_history(const PSRAMVector<ignitionBoxStatus> &history, const std::filesystem::path &file_path)
void ignitionBoxStatusAverage::filter(int32_t &old, const int32_t value, const uint32_t k)
{
float alpha = 1.0f / (float)k;
old = old + (int32_t)(alpha * (float)(value - old));
}
void ignitionBoxStatusAverage::filter(float &old, const float value, const uint32_t k)
{
float alpha = 1.0f / (float)k;
old = old + (float)(alpha * (float)(value - old));
}
void ignitionBoxStatusAverage::reset()
{
m_last = ignitionBoxStatus();
m_count = 0;
m_data_valid = false;
}
void ignitionBoxStatusAverage::update(const ignitionBoxStatus &new_status)
{
if (m_count == 0 && !m_data_valid)
{
m_last = new_status;
}
m_count++;
// simple moving average calculation
m_last.timestamp = new_status.timestamp; // keep timestamp of latest status
m_last.coils12.n_events = new_status.coils12.n_events; // sum events instead of averaging
m_last.coils12.n_missed_firing = new_status.coils12.n_missed_firing; // sum missed firings instead of averaging
m_last.coils12.spark_status = new_status.coils12.spark_status; // take latest spark status
m_last.coils12.sstart_status = new_status.coils12.sstart_status; // take latest soft start status
filter(m_last.coils12.spark_delay, new_status.coils12.spark_delay, m_max_count); // incremental average calculation
filter(m_last.coils12.peak_p_in, new_status.coils12.peak_p_in, m_max_count); // incremental average calculation
filter(m_last.coils12.peak_n_in, new_status.coils12.peak_n_in, m_max_count); // incremental average calculation
filter(m_last.coils12.peak_p_out, new_status.coils12.peak_p_out, m_max_count); // incremental average calculation
filter(m_last.coils12.peak_n_out, new_status.coils12.peak_n_out, m_max_count); // incremental average calculation
m_last.coils34.n_events = new_status.coils34.n_events; // sum events instead of averaging
m_last.coils34.n_missed_firing = new_status.coils34.n_missed_firing; // sum missed firings instead of averaging
m_last.coils34.spark_status = new_status.coils34.spark_status; // take latest spark status
m_last.coils34.sstart_status = new_status.coils34.sstart_status; // take latest soft start status
filter(m_last.coils34.spark_delay, new_status.coils34.spark_delay, m_max_count); // incremental average calculation
filter(m_last.coils34.peak_p_in, new_status.coils34.peak_p_in, m_max_count); // incremental average calculation
filter(m_last.coils34.peak_n_in, new_status.coils34.peak_n_in, m_max_count); // incremental average calculation
filter(m_last.coils34.peak_p_out, new_status.coils34.peak_p_out, m_max_count); // incremental average calculation
filter(m_last.coils34.peak_n_out, new_status.coils34.peak_n_out, m_max_count); // incremental average calculation
filter(m_last.eng_rpm, new_status.eng_rpm, m_max_count); // incremental average calculation // incremental average calculation
filter(m_last.adc_read_time, m_last.adc_read_time, m_max_count); // incremental average calculation
m_last.n_queue_errors = new_status.n_queue_errors; // take last of queue errors since it's a cumulative count of errors in the queue, not an average value
if (m_count >= m_max_count)
{
m_count = 0; // reset count after reaching max samples to average
m_data_valid = true; // set data valid flag after first average is calculated
}
}
const bool ignitionBoxStatusAverage::get(ignitionBoxStatus &status) const
{
if (m_data_valid)
{
status = m_last;
}
return m_data_valid;
}
const ArduinoJson::JsonDocument ignitionBoxStatusAverage::toJson() const
{
ArduinoJson::JsonDocument doc;
if (m_data_valid)
{
doc["timestamp"] = m_last.timestamp;
doc["datavalid"] = m_data_valid ? "TRUE" : "FALSE";
doc["coils12"]["n_events"] = m_last.coils12.n_events;
doc["coils12"]["n_missed_firing"] = m_last.coils12.n_missed_firing;
doc["coils12"]["spark_delay"] = m_last.coils12.spark_delay;
doc["coils12"]["spark_status"] = sparkStatusNames.at(m_last.coils12.spark_status);
doc["coils12"]["peak_p_in"] = m_last.coils12.peak_p_in;
doc["coils12"]["peak_n_in"] = m_last.coils12.peak_n_in;
doc["coils12"]["peak_p_out"] = m_last.coils12.peak_p_out;
doc["coils12"]["peak_n_out"] = m_last.coils12.peak_n_out;
doc["coils12"]["sstart_status"] = softStartStatusNames.at(m_last.coils12.sstart_status);
doc["coils34"]["n_events"] = m_last.coils34.n_events;
doc["coils34"]["n_missed_firing"] = m_last.coils34.n_missed_firing;
doc["coils34"]["spark_delay"] = m_last.coils34.spark_delay;
doc["coils34"]["spark_status"] = sparkStatusNames.at(m_last.coils34.spark_status);
doc["coils34"]["peak_p_in"] = m_last.coils34.peak_p_in;
doc["coils34"]["peak_n_in"] = m_last.coils34.peak_n_in;
doc["coils34"]["peak_p_out"] = m_last.coils34.peak_p_out;
doc["coils34"]["peak_n_out"] = m_last.coils34.peak_n_out;
doc["coils34"]["sstart_status"] = softStartStatusNames.at(m_last.coils34.sstart_status);
doc["eng_rpm"] = m_last.eng_rpm;
doc["adc_read_time"] = m_last.adc_read_time;
doc["n_queue_errors"] = m_last.n_queue_errors;
}
return doc;
}
void saveHistoryTask(void *pvParameters)
{
const auto *params = static_cast<dataSaveParams *>(pvParameters);
const auto &history = *params->history;
const auto &file_path = params->file_path;
if (!params)
{
LOG_ERROR("Invalid parameters for saveHistoryTask");
return;
}
LOG_DEBUG("Starting saving: ", file_path.c_str());
save_history(history, file_path);
vTaskDelete(NULL);
}
void save_history(const PSRAMVector<ignitionBoxStatus> &history, const std::filesystem::path &file_name)
{
// Initialize SPIFFS
if (!SPIFFS.begin(true))
{
LOG_ERROR("Failed to mount SPIFFS");
LOG_ERROR("5 seconds to restart...");
vTaskDelay(pdMS_TO_TICKS(5000));
esp_restart();
}
if (!SAVE_HISTORY_TO_SPIFFS)
return;
// auto spiffs_guard = LITTLEFSGuard(); // use RAII guard to ensure SPIFFS is properly mounted and unmounted
LOG_INFO("SPIFFS mounted successfully");
if (SPIFFS.totalBytes() - SPIFFS.usedBytes() < min_free ) // check if at least 1MB is free for saving history
if (LittleFS.totalBytes() - LittleFS.usedBytes() < min_free) // check if at least 1MB is free for saving history
{
LOG_ERROR("Not enough space in SPIFFS to save history");
return;
}
std::filesystem::path to_save = file_path;
if (file_path.root_path() != "/spiffs")
to_save = std::filesystem::path("/spiffs") / file_path;
std::filesystem::path file_path = file_name;
if (file_name.root_path() != "/littlefs")
file_path = std::filesystem::path("/littlefs") / file_name;
auto save_flags = std::ios::out;
if (first_save && SPIFFS.exists(to_save.c_str()))
if (first_save && LittleFS.exists(file_path.c_str()))
{
first_save = false;
save_flags |= std::ios::trunc; // overwrite existing file
SPIFFS.remove(to_save.c_str()); // ensure file is removed before saving to avoid issues with appending to existing file in SPIFFS
LOG_INFO("Saving history to SPIFFS, new file: ", to_save.c_str());
save_flags |= std::ios::trunc; // overwrite existing file
LittleFS.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 LittleFS, new file:", file_path.c_str());
}
else
{
save_flags |= std::ios::app; // append to new file
LOG_INFO("Saving history to SPIFFS, appending to existing file: ", to_save.c_str());
LOG_INFO("Saving history to LittleFS, appending to existing file:", file_path.c_str());
}
std::ofstream ofs(to_save, save_flags);
std::ofstream ofs(file_path, save_flags);
if (ofs.fail())
{
LOG_ERROR("Failed to open file for writing");
@@ -50,9 +163,10 @@ void save_history(const PSRAMVector<ignitionBoxStatus> &history, const std::file
if (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;
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();
}
@@ -83,6 +197,5 @@ void save_history(const PSRAMVector<ignitionBoxStatus> &history, const std::file
}
ofs.close();
LOG_INFO("Ignition A history saved to SPIFFS, records written: ", history.size());
SPIFFS.end(); // unmount SPIFFS to ensure data is written and avoid corruption on next mount
LOG_INFO("Ignition A history saved to LittleFS, records written: ", history.size());
}

View File

@@ -1,19 +1,22 @@
#pragma once
#define DEBUGLOG_DEFAULT_LOG_LEVEL_INFO
// System Includes
#include <Arduino.h>
#include <DebugLog.h>
#include <SPIFFS.h>
#include <LittleFS.h>
#include <string>
#include <fstream>
#include <filesystem>
#include <ArduinoJson.h>
// Project Includes
#include "isr.h"
#include "psvector.h"
const uint32_t max_history = 256;
const bool SAVE_HISTORY_TO_SPIFFS = true; // Set to true to enable saving history to SPIFFS, false to disable
const bool SAVE_HISTORY_TO_SPIFFS = false; // Set to true to enable saving history to SPIFFS, false to disable
static bool first_save = true; // flag to indicate if this is the first save (to write header)
struct dataSaveParams
{
@@ -21,18 +24,50 @@ struct dataSaveParams
const std::filesystem::path file_path;
};
void save_history(const PSRAMVector<ignitionBoxStatus> &history, const std::filesystem::path& file_path);
static void saveHistoryTask(void *pvParameters)
class LITTLEFSGuard
{
const auto *params = static_cast<dataSaveParams *>(pvParameters);
const auto &history = *params->history;
const auto &file_path = params->file_path;
if (!params) {
LOG_ERROR("Invalid parameters for saveHistoryTask");
return;
public:
LITTLEFSGuard()
{
if (!LittleFS.begin(true))
{
LOG_ERROR("Failed to mount LittleFS");
}
LOG_INFO("SPIFFS mounted successfully");
}
LOG_INFO("Starting saving: ", file_path.c_str());
save_history(history, file_path);
//vTaskDelete(NULL);
}
~LITTLEFSGuard()
{
LittleFS.end();
LOG_INFO("LittleFS unmounted successfully");
}
};
class ignitionBoxStatusAverage
{
private:
ignitionBoxStatus m_last;
uint32_t m_count = 0;
uint32_t m_max_count = 100; // number of samples to average before resetting
bool m_data_valid = false; // flag to indicate if the average data is valid (i.e. at least one sample has been added)
public:
ignitionBoxStatusAverage() = default;
ignitionBoxStatusAverage(const uint32_t max_count) : m_max_count(max_count) {
m_data_valid = false;
m_count = 0;
}
void reset();
void update(const ignitionBoxStatus &new_status);
const bool get(ignitionBoxStatus &status) const;
const ArduinoJson::JsonDocument toJson() const;
private:
void filter(int32_t &old, const int32_t value, const uint32_t k);
void filter(float &old, const float value, const uint32_t k);
};
// Task and function declarations
void saveHistoryTask(void *pvParameters);
void save_history(const PSRAMVector<ignitionBoxStatus> &history, const std::filesystem::path &file_path);

View File

@@ -61,7 +61,7 @@ struct coilsStatus
{
int64_t trig_time = 0;
int64_t spark_time = 0;
uint32_t spark_delay = 0; // in microseconds
int32_t spark_delay = 0; // in microseconds
sparkStatus spark_status = sparkStatus::SPARK_POS_OK;
softStartStatus sstart_status = softStartStatus::NORMAL;
float peak_p_in = 0.0;
@@ -83,8 +83,8 @@ struct ignitionBoxStatus
// voltage from generator
float volts_gen = 0.0;
// enine rpm
uint32_t eng_rpm = 0;
int32_t eng_rpm = 0;
// debug values
uint32_t n_queue_errors = 0;
uint32_t adc_read_time = 0;
int32_t adc_read_time = 0;
};

View File

@@ -6,7 +6,6 @@
// Device Libraries
#include <ADS1256.h>
#include <AD5292.h>
#include <Adafruit_SSD1306.h>
#include <PCA95x5.h>
// ADC Channel mapping
@@ -23,7 +22,6 @@
struct Devices {
AD5292 *pot_a = NULL, *pot_b = NULL;
ADS1256 *adc_a = NULL, *adc_b = NULL;
Adafruit_SSD1306* lcd = NULL;
PCA9555* io = NULL;
};

View File

@@ -5,6 +5,10 @@
#include <DebugLog.h>
#include <DebugLogEnable.h>
#include <SPI.h>
#include <WiFi.h>
#include <ArduinoJson.h>
#include <ESPAsyncWebServer.h>
#include <AsyncTCP.h>
// Definitions
#include <tasks.h>
@@ -19,6 +23,23 @@
// #define CH_B_ENABLE
#define TEST
#define WIFI_SSID "AstroRotaxMonitor"
#define WIFI_PASSWORD "maledettirotax"
void onWsEvent(AsyncWebSocket *server, AsyncWebSocketClient *client,
AwsEventType type, void *arg, uint8_t *data, size_t len)
{
switch (type)
{
case WS_EVT_CONNECT:
Serial.printf("WS client IP[%s]-ID[%u] CONNECTED\r\n", client->remoteIP().toString().c_str(), client->id());
break;
case WS_EVT_DISCONNECT:
Serial.printf("WS client ID[%u] DISCONNECTED\r\n", client->remoteIP().toString().c_str(), client->id());
break;
}
}
void setup()
{
Serial.begin(921600);
@@ -29,21 +50,43 @@ void setup()
LOG_SET_LEVEL(DebugLogLevel::LVL_INFO);
// Print Processor Info
LOG_INFO("ESP32 Chip:", ESP.getChipModel());
LOG_DEBUG("ESP32 Chip:", ESP.getChipModel());
if (psramFound())
{
LOG_INFO("ESP32 PSram Found");
LOG_INFO("ESP32 PSram:", ESP.getPsramSize());
LOG_DEBUG("ESP32 PSram Found");
LOG_DEBUG("ESP32 PSram:", ESP.getPsramSize());
psramInit();
}
LOG_INFO("ESP32 Flash:", ESP.getFlashChipSize());
LOG_INFO("ESP32 Heap:", ESP.getHeapSize());
LOG_INFO("ESP32 Sketch:", ESP.getFreeSketchSpace());
LOG_DEBUG("ESP32 Flash:", ESP.getFlashChipSize());
LOG_DEBUG("ESP32 Heap:", ESP.getHeapSize());
LOG_DEBUG("ESP32 Sketch:", ESP.getFreeSketchSpace());
// Initialize Interrupt pins on PICKUP detectors
initTriggerPinsInputs();
// Initialize Interrupt pins on SPARK detectors
initSparkPinInputs();
// Init Wifi station
LOG_INFO("Initializing WiFi...");
WiFi.mode(WIFI_AP);
IPAddress local_IP(10, 11, 12, 1);
IPAddress gateway(10, 11, 12, 1);
IPAddress subnet(255, 255, 255, 0);
WiFi.softAPConfig(local_IP, gateway, subnet);
if (WiFi.softAP(WIFI_SSID, WIFI_PASSWORD))
{
LOG_INFO("WiFi AP Mode Started");
LOG_INFO("Wifi SSID:", WIFI_SSID);
LOG_INFO("Wifi Password:", WIFI_PASSWORD);
LOG_INFO("WiFi IP:" + WiFi.softAPIP().toString());
}
else
{
LOG_ERROR("Failed to start WiFi AP Mode");
LOG_ERROR("5 seconds to restart...");
vTaskDelay(pdMS_TO_TICKS(5000));
esp_restart();
}
}
void loop()
@@ -51,6 +94,7 @@ void loop()
// global variables
bool running = true;
const uint32_t max_queue = 128;
const uint32_t filter_k = 10;
PSRAMVector<ignitionBoxStatus> ignA_history_0(max_history);
PSRAMVector<ignitionBoxStatus> ignA_history_1(max_history);
auto *active_history = &ignA_history_0;
@@ -79,7 +123,7 @@ void loop()
.spark_pin_34 = SPARK_PIN_A34},
.rt_resets = rtTaskResets{.rst_io_12p = RST_EXT_A12P, .rst_io_12n = RST_EXT_A12N, .rst_io_34p = RST_EXT_A34P, .rst_io_34n = RST_EXT_A34N}};
LOG_INFO("Task Variables OK");
LOG_DEBUG("Task Variables OK");
#ifdef CH_B_ENABLE
QueueHandle_t rt_taskB_queue = xQueueCreate(max_queue, sizeof(ignitionBoxStatus));
@@ -118,7 +162,7 @@ void loop()
vTaskDelay(pdMS_TO_TICKS(5000));
esp_restart();
}
LOG_INFO("Init SPI OK");
LOG_DEBUG("Init SPI OK");
// Init ADC_A
dev.adc_a = new ADS1256(ADC_A_DRDY, ADS1256::PIN_UNUSED, ADC_A_SYNC, ADC_A_CS, 2.5, &SPI_A);
@@ -134,7 +178,7 @@ void loop()
dev.adc_a->setDRATE(DRATE_1000SPS);
#endif
LOG_INFO("Init ADC OK");
LOG_DEBUG("Init ADC OK");
// Ignition A on Core 0
auto ignA_task_success = pdPASS;
@@ -168,17 +212,29 @@ void loop()
esp_restart();
}
LOG_INFO("Real Time Tasks A & B initialized");
LOG_DEBUG("Real Time Tasks A & B initialized");
////////////////////// MAIN LOOP //////////////////////
clearScreen();
setCursor(0, 0);
bool partial_save = false; // flag to indicate if a partial save has been done after a timeout
uint32_t counter = 0;
uint32_t wait_count = 0;
ignitionBoxStatus ign_info;
int64_t last = esp_timer_get_time();
uint32_t missed_firings12 = 0;
uint32_t missed_firings34 = 0;
ignitionBoxStatusAverage ignA_avg(filter_k); // moving average calculator for ignition box A with a window of 100 samples
AsyncWebServer server(80);
AsyncWebSocket ws("/ws");
ws.onEvent(onWsEvent);
server.addHandler(&ws);
auto spiffs_guard = LITTLEFSGuard(); // use RAII guard to ensure SPIFFS is properly mounted and unmounted
server.serveStatic("/", LittleFS, "/").setDefaultFile("index.html");
server.begin();
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request)
{ request->send(200, "text/html", htmlTest.c_str()); });
while (running)
{
@@ -192,20 +248,7 @@ void loop()
dataSaveParams save_params{
.history = writable_history,
.file_path = "ignition_history.csv"};
saveHistoryTask(&save_params); // directly call the save task function to save without delay, since we already switched buffers and writable_history is now empty and ready for new data
// if (SAVE_HISTORY_TO_SPIFFS)
// if (pdFAIL ==
// xTaskCreatePinnedToCore(
// saveHistoryTask,
// "saveHistoryTask",
// RT_TASK_STACK,
// &save_params,
// RT_TASK_PRIORITY - 1, // higher priority to ensure it runs asap after buffer switch
// NULL,
// CORE_1))
// {
// LOG_ERROR("Unable to create saveHistoryTask");
// }
save_history(*writable_history, "ignition_history.csv"); // directly call the save task function to save without delay
}
if (xQueueReceive(rt_taskA_queue, &ign_info, pdMS_TO_TICKS(1000)) == pdTRUE)
@@ -213,17 +256,28 @@ void loop()
// printInfo(ign_info);
auto &hist = *active_history;
hist[counter++ % active_history->size()] = ign_info;
ignA_avg.update(ign_info); // update moving average with latest ignition status
Serial.print("Data Received: " + String(counter) + "/" + String(hist.size()) + '\r');
if (ws.count() > 0 && counter % 10 == 0) // send data every 10 samples
{
Serial.println();
LOG_INFO("Sending average ignition status to websocket clients...");
auto msg = ignA_avg.toJson().as<String>();
ws.textAll(msg);
}
}
else
{
Serial.println("Waiting for data... ");
Serial.printf("[%d] Waiting for data...\r", wait_count++);
if (!partial_save && counter > 0) // if timeout occurs but we have unsaved data, save it before next timeout
{
counter = 0; // reset counter after saving
partial_save = true;
Serial.println("Saving history to SPIFFS...");
active_history->resize(counter); // resize active history to actual number of records received to avoid saving empty records
save_history(*active_history, "ignition_history.csv");
active_history->resize(max_history); // resize back to max history size for next data cycle
counter = 0; // reset counter after saving
partial_save = true;
first_save = true;
}
delay(500);
}

View File

@@ -157,7 +157,7 @@ void rtIgnitionTask(void *pvParameters)
auto current_time = esp_timer_get_time();
auto cycle_time = current_time - last_cycle_time;
last_cycle_time = current_time;
ign_box_sts.eng_rpm = (uint32_t)(60.0f / (cycle_time / 1000000.0f));
ign_box_sts.eng_rpm = (int32_t)(60.0f / (cycle_time / 1000000.0f));
}
case TRIG_FLAG_12N:
coils = &ign_box_sts.coils12;
@@ -177,7 +177,7 @@ void rtIgnitionTask(void *pvParameters)
// Timeout not occourred, expected POSITIVE edge spark OCCOURRED
if (spark_flag != SPARK_FLAG_TIMEOUT)
{
coils->spark_delay = (uint32_t)(coils->spark_time - coils->trig_time);
coils->spark_delay = (int32_t)(coils->spark_time - coils->trig_time);
coils->sstart_status = softStartStatus::NORMAL; // because spark on positive edge
coils->spark_status = sparkStatus::SPARK_POS_OK; // do not wait for spark on negative edge
}
@@ -197,7 +197,7 @@ void rtIgnitionTask(void *pvParameters)
// Timeout not occourred, expected NEGATIVE edge spark OCCOURRED
if (spark_flag != SPARK_FLAG_TIMEOUT && expected_negative)
{
coils->spark_delay = (uint32_t)(coils->spark_time - coils->trig_time);
coils->spark_delay = (int32_t)(coils->spark_time - coils->trig_time);
coils->sstart_status = softStartStatus::SOFT_START;
coils->spark_status = sparkStatus::SPARK_NEG_OK;
}
@@ -248,7 +248,7 @@ void rtIgnitionTask(void *pvParameters)
ign_box_sts.coils12.peak_n_out = adcReadChannel(adc, ADC_CH_PEAK_12N_OUT);
ign_box_sts.coils34.peak_p_out = adcReadChannel(adc, ADC_CH_PEAK_34P_OUT);
ign_box_sts.coils34.peak_n_out = adcReadChannel(adc, ADC_CH_PEAK_34N_OUT);
ign_box_sts.adc_read_time = (uint32_t)(esp_timer_get_time() - start_adc_read);
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));

View File

@@ -14,6 +14,11 @@ void setCursor(const uint8_t x, const uint8_t y)
}
void printField(const char name[], const uint32_t val)
{
Serial.printf("%15s: %06u\n", name, val);
}
void printField(const char name[], const int32_t val)
{
Serial.printf("%15s: %06d\n", name, val);
}

View File

@@ -2,12 +2,203 @@
#include <Arduino.h>
#include <datastruct.h>
#include <string>
void clearScreen();
void setCursor(const uint8_t x, const uint8_t y);
void printField(const char name[], const uint32_t val);
void printField(const char name[], const int32_t val);
void printField(const char name[], const int64_t val);
void printField(const char name[], const float val);
void printField(const char name[], const char *val);
void printInfo(const ignitionBoxStatus &info);
void printInfo(const ignitionBoxStatus &info);
static const std::string htmlTest = R"rawliteral(
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>ESP32 Dashboard</title>
<style>
body {
font-family: Arial;
text-align: center;
margin-top: 40px;
}
table {
margin: auto;
border-collapse: collapse;
width: 100%;
max-width: 900px;
}
th, td {
border: 1px solid #ccc;
padding: 10px;
font-size: 16px;
text-align: left;
}
th {
background-color: #f4f4f4;
}
button {
margin: 10px;
padding: 10px 20px;
font-size: 16px;
}
</style>
</head>
<body>
<h2>RotaxMonitor realtime data</h2>
<button onclick="start()">Start</button>
<button onclick="stop()">Stop</button>
<div style="max-width: 900px; margin: 0 auto; text-align: left;">
<p><strong>Timestamp:</strong> <span id="timestamp">-</span></p>
<p><strong>Data Valid:</strong> <span id="datavalid">-</span></p>
<p><strong>Generator voltage:</strong> <span id="volts_gen">-</span></p>
<p><strong>Engine RPM:</strong> <span id="eng_rpm">-</span></p>
<p><strong>ADC read time:</strong> <span id="adc_read_time">-</span></p>
<p><strong>Queue errors:</strong> <span id="n_queue_errors">-</span></p>
<table>
<thead>
<tr>
<th>Property</th>
<th>Coils 12</th>
<th>Coils 34</th>
</tr>
</thead>
<tbody>
<tr>
<td>Spark delay</td>
<td id="coils12_spark_delay">-</td>
<td id="coils34_spark_delay">-</td>
</tr>
<tr>
<td>Spark status</td>
<td id="coils12_spark_status">-</td>
<td id="coils34_spark_status">-</td>
</tr>
<tr>
<td>Soft start status</td>
<td id="coils12_sstart_status">-</td>
<td id="coils34_sstart_status">-</td>
</tr>
<tr>
<td>Peak P in</td>
<td id="coils12_peak_p_in">-</td>
<td id="coils34_peak_p_in">-</td>
</tr>
<tr>
<td>Peak N in</td>
<td id="coils12_peak_n_in">-</td>
<td id="coils34_peak_n_in">-</td>
</tr>
<tr>
<td>Peak P out</td>
<td id="coils12_peak_p_out">-</td>
<td id="coils34_peak_p_out">-</td>
</tr>
<tr>
<td>Peak N out</td>
<td id="coils12_peak_n_out">-</td>
<td id="coils34_peak_n_out">-</td>
</tr>
<tr>
<td>Level spark</td>
<td id="coils12_level_spark">-</td>
<td id="coils34_level_spark">-</td>
</tr>
<tr>
<td>Events</td>
<td id="coils12_n_events">-</td>
<td id="coils34_n_events">-</td>
</tr>
<tr>
<td>Missed firings</td>
<td id="coils12_n_missed_firing">-</td>
<td id="coils34_n_missed_firing">-</td>
</tr>
</tbody>
</table>
</div>
<script>
let ws;
function connectWS() {
ws = new WebSocket("ws://" + location.host + "/ws");
ws.onopen = () => {
console.log("WebSocket connesso");
};
ws.onclose = () => {
console.log("WebSocket disconnesso, retry...");
setTimeout(connectWS, 5000);
};
ws.onmessage = (event) => {
let data;
try {
data = JSON.parse(event.data);
} catch (e) {
console.error("Invalid JSON received", e);
return;
}
document.getElementById("datavalid").textContent = data.datavalid ?? "-";
document.getElementById("timestamp").textContent = data.timestamp ?? "-";
document.getElementById("volts_gen").textContent = data.volts_gen ?? "-";
document.getElementById("eng_rpm").textContent = data.eng_rpm ?? "-";
document.getElementById("adc_read_time").textContent = data.adc_read_time ?? "-";
document.getElementById("n_queue_errors").textContent = data.n_queue_errors ?? "-";
const coils12 = data.coils12 || {};
const coils34 = data.coils34 || {};
document.getElementById("coils12_spark_delay").textContent = coils12.spark_delay ?? "-";
document.getElementById("coils34_spark_delay").textContent = coils34.spark_delay ?? "-";
document.getElementById("coils12_spark_status").textContent = coils12.spark_status ?? "-";
document.getElementById("coils34_spark_status").textContent = coils34.spark_status ?? "-";
document.getElementById("coils12_sstart_status").textContent = coils12.sstart_status ?? "-";
document.getElementById("coils34_sstart_status").textContent = coils34.sstart_status ?? "-";
document.getElementById("coils12_peak_p_in").textContent = coils12.peak_p_in ?? "-";
document.getElementById("coils34_peak_p_in").textContent = coils34.peak_p_in ?? "-";
document.getElementById("coils12_peak_n_in").textContent = coils12.peak_n_in ?? "-";
document.getElementById("coils34_peak_n_in").textContent = coils34.peak_n_in ?? "-";
document.getElementById("coils12_peak_p_out").textContent = coils12.peak_p_out ?? "-";
document.getElementById("coils34_peak_p_out").textContent = coils34.peak_p_out ?? "-";
document.getElementById("coils12_peak_n_out").textContent = coils12.peak_n_out ?? "-";
document.getElementById("coils34_peak_n_out").textContent = coils34.peak_n_out ?? "-";
document.getElementById("coils12_level_spark").textContent = coils12.level_spark ?? "-";
document.getElementById("coils34_level_spark").textContent = coils34.level_spark ?? "-";
document.getElementById("coils12_n_events").textContent = coils12.n_events ?? "-";
document.getElementById("coils34_n_events").textContent = coils34.n_events ?? "-";
document.getElementById("coils12_n_missed_firing").textContent = coils12.n_missed_firing ?? "-";
document.getElementById("coils34_n_missed_firing").textContent = coils34.n_missed_firing ?? "-";
};
}
function start() {
fetch("/start");
}
function stop() {
fetch("/stop");
}
connectWS();
</script>
</body>
</html>
)rawliteral";

View File

@@ -54,6 +54,8 @@ static timerStatus stsA = {
.spark_delay_us = 50,
.main_task = NULL};
static bool isEnabled = false;
void setup()
{
@@ -76,9 +78,14 @@ void setup()
pinMode(SPARK_B34, OUTPUT);
pinMode(SPARK_DELAY_POT, ANALOG);
pinMode(FREQ_POT, ANALOG);
pinMode(ENABLE_PIN, INPUT_PULLUP);
stsA.main_task = xTaskGetCurrentTaskHandleForCore(1);
timerA = timerBegin(FREQUENCY);
timerStop(timerA);
timerAttachInterruptArg(timerA, &onTimer, (void *)&stsA);
timerAlarm(timerA, 1, true, 0);
@@ -100,11 +107,25 @@ void loop()
double new_rpm = (double)(map(analogRead(FREQ_POT), 0, 4096, RPM_MIN, RPM_MAX));
filtered_rpm = filtered_rpm + 0.1 * (new_rpm - filtered_rpm);
stsA.pause_long_us = (uint32_t)(60000000.0f / filtered_rpm / 2.0f);
if (isEnabled) {
LOG_INFO("==== System is ENABLED ====");
} else {
LOG_INFO("==== System is DISABLED ====");
}
LOG_INFO("Spark Delay uS: ", stsA.spark_delay_us, "\tSoft Start: ", stsA.soft_start ? "TRUE" : "FALSE");
LOG_INFO("Engine Rpm: ", (uint32_t)(filtered_rpm));
LOG_INFO("Coil Pulse: ", stsA.coil_pulse_us, "us");
LOG_INFO("Spark Pulse: ", stsA.spark_pulse_us, "us");
if (digitalRead(ENABLE_PIN) == LOW && !isEnabled) {
timerStart(timerA);
isEnabled = true;
} else if (digitalRead(ENABLE_PIN) == HIGH && isEnabled) {
timerStop(timerA);
isEnabled = false;
}
delay(100);
clearScreen();

View File

@@ -1,5 +1,8 @@
#pragma once
// Enable Pin
#define ENABLE_PIN 16
///// Ignition Box A /////
#define PIN_TRIG_A12P 18
#define PIN_TRIG_A12N 19