From 4f02a8f3d0f189d853df0251d9581dc84427d11c Mon Sep 17 00:00:00 2001 From: tobimai Date: Tue, 4 Nov 2025 21:09:40 +0100 Subject: [PATCH] fixed time --- data/logic.js | 1 + data/status.html | 8 ++- lib/INA233/INA233.h | 32 ++++----- platformio.ini | 15 ++-- src/external_interfacing/leds.cpp | 1 + src/global_data/global_data.h | 1 + src/main.cpp | 112 +++++++----------------------- src/networking/json_builder.cpp | 1 + src/networking/networking.cpp | 2 +- src/sensor/sensor.cpp | 1 + src/telemetry/telemetry.cpp | 5 ++ src/tools/log.h | 2 +- src/tools/tools.cpp | 62 +++++++++++++---- src/tools/tools.h | 6 +- 14 files changed, 120 insertions(+), 129 deletions(-) diff --git a/data/logic.js b/data/logic.js index 905077a..11f863a 100644 --- a/data/logic.js +++ b/data/logic.js @@ -25,6 +25,7 @@ function fetchTelemetryData() { .then(data => { document.getElementById('uptime').textContent = data.uptime_seconds ? (roundToTwo(data.uptime_seconds) + ' s') : 'XXX'; document.getElementById('heap').textContent = data.heap_percent ? (roundToTwo(data.heap_percent) + ' %%') : 'XXX'; + document.getElementById('temperature').textContent = data.heap_percent ? (roundToTwo(data.temperature) + ' °C') : 'XXX'; }) .catch(error => { console.error("There was an error fetching data from the API", error); diff --git a/data/status.html b/data/status.html index 2620fbe..1c06fc6 100644 --- a/data/status.html +++ b/data/status.html @@ -1,4 +1,5 @@ + @@ -19,9 +20,6 @@ Data export -
@@ -121,6 +119,10 @@ Heap usage: XXX + + CPU Temperature: + XXX +
diff --git a/lib/INA233/INA233.h b/lib/INA233/INA233.h index 8e17802..4f087c9 100644 --- a/lib/INA233/INA233.h +++ b/lib/INA233/INA233.h @@ -10,25 +10,25 @@ #define REGISTER_READ_IIN 0x89 enum AveragingMode { - averages_1 = B000, - averages_4 = B001, - averages_16 = B010, - averages_64 = B011, - averages_128 = B100, - averages_256 = B101, - averages_512 = B110, - averages_1024 = B111 + averages_1 = 0b000, + averages_4 = 0b001, + averages_16 = 0b010, + averages_64 = 0b011, + averages_128 = 0b100, + averages_256 = 0b101, + averages_512 = 0b110, + averages_1024 = 0b111 }; enum ConversionTime { - conversion_time_140uS = B000, - conversion_time_204uS = B001, - conversion_time_332us = B010, - conversion_time_588uS = B011, - conversion_time_1100uS = B100, - conversion_time_2116uS = B101, - conversion_time_4156uS = B110, - conversion_time_8244uS = B111 + conversion_time_140uS = 0b000, + conversion_time_204uS = 0b001, + conversion_time_332us = 0b010, + conversion_time_588uS = 0b011, + conversion_time_1100uS = 0b100, + conversion_time_2116uS = 0b101, + conversion_time_4156uS = 0b110, + conversion_time_8244uS = 0b111 }; class INA233{ diff --git a/platformio.ini b/platformio.ini index ef31b24..65dbd05 100644 --- a/platformio.ini +++ b/platformio.ini @@ -16,11 +16,8 @@ platform = https://github.com/pioarduino/platform-espressif32/releases/download/ board = esp32dev framework = arduino monitor_speed = 115200 -; monitor_filters = esp32_exception_decoder +monitor_filters = esp32_exception_decoder board_build.partitions = min_spiffs.csv -build_flags = -Wall -Wextra -DUSE_INA226 -fexceptions - -[common_esp32_libs] lib_deps = esp32async/AsyncTCP @ ~3.4.9 esp32async/ESPAsyncWebServer @ ~3.8.1 @@ -28,22 +25,24 @@ lib_deps = bblanchon/ArduinoJson@^6.21.3 x385832/Elog@~2.0.10 fetchOTA +build_flags = -fexceptions +build_src_flags = -Wall -Wextra + [env:ESP32_INA233] -extends = common_esp32_libs lib_deps = - ${common_esp32_libs.lib_deps} + ${env.lib_deps} INA233 upload_protocol = espota upload_port = 192.168.5.205 [env:ESP32_INA226] -extends = common_esp32_libs lib_deps = - ${common_esp32_libs.lib_deps} + ${env.lib_deps} robtillaart/INA226@ ~0.6.4 upload_protocol = espota upload_port = 192.168.6.45 +build_flags = ${env.build_flags} -DUSE_INA226 [env:native] platform = native diff --git a/src/external_interfacing/leds.cpp b/src/external_interfacing/leds.cpp index f6e1e0a..3d638b5 100644 --- a/src/external_interfacing/leds.cpp +++ b/src/external_interfacing/leds.cpp @@ -9,6 +9,7 @@ extern WaterData water_data; void display_task(void* parameter) { + LOG(ELOG_LEVEL_DEBUG, "Starting display tasks"); while (true) { if (!is_error(active_errors)) { // We have no error, refresh status display and wait half a second diff --git a/src/global_data/global_data.h b/src/global_data/global_data.h index f3288d0..ea6cc09 100644 --- a/src/global_data/global_data.h +++ b/src/global_data/global_data.h @@ -29,6 +29,7 @@ struct NetworkData { struct DeviceTelemetry { float heap_used_percent; int uptime_seconds; + float temperature; }; struct ActiveErrors { diff --git a/src/main.cpp b/src/main.cpp index ffa18e2..2e35014 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -39,48 +39,41 @@ extern NetworkData ethernet_data; extern SensorData shunt_data; extern ActiveErrors active_errors; -extern "C" int rom_phy_get_vdd33(); - Version current_spiffs_version; AsyncWebServer server(80); -// AsyncWebSocket webSocket("/webSocket"); +AsyncWebSocket webSocket("/webSocket"); #define FORMAT_LITTLEFS_IF_FAILED true void setup() { Logger.registerSerial(MYLOG, ELOG_LEVEL_DEBUG, "Serial"); + LOG(ELOG_LEVEL_DEBUG, "Init LEDs"); led_setup(); - + LOG(ELOG_LEVEL_DEBUG, "Init Starting prefs and Serial output"); prefs.begin("waterlevel", false); Serial.begin(115200); - delay(500); + LOG(ELOG_LEVEL_DEBUG, "Init Sensor"); init_sensor(); - LOG(ELOG_LEVEL_DEBUG, "Beginning SPIFFS"); - //SPIFFS.begin(FORMAT_LITTLEFS_IF_FAILED); + LOG(ELOG_LEVEL_DEBUG, "Beginning LittleFS"); LittleFS.begin(FORMAT_LITTLEFS_IF_FAILED); // Read the current SPIFFS version from the versions file on the spiffs + LOG(ELOG_LEVEL_DEBUG, "Reading LittleFS version"); File file = LittleFS.open("/version", FILE_READ); if (!file) { - Serial.println("Failed to open version file for reading"); + LOG( ELOG_LEVEL_ERROR, "Failed opening LittleFS version file"); } else { String version = file.readStringUntil('\n'); - LOG(ELOG_LEVEL_DEBUG, "Version: %s", version); current_spiffs_version = parseVersion(version.c_str()); - LOG(ELOG_LEVEL_DEBUG, "Current SPIFFS Version: %d.%d.%d", current_spiffs_version.major, current_spiffs_version.minor, current_spiffs_version.patch); + LOG(ELOG_LEVEL_DEBUG, "Current LittleFS Version: %d.%d.%d", current_spiffs_version.major, current_spiffs_version.minor, current_spiffs_version.patch); } - - - LOG(ELOG_LEVEL_DEBUG, "SPIFFS initialized"); - - LOG(ELOG_LEVEL_DEBUG, "Begin INA"); - + LOG(ELOG_LEVEL_DEBUG, "LittleFS initialized"); /////////////////////////////// ROUTES /////////////////////////////// LOG(ELOG_LEVEL_DEBUG, "Route Setup"); @@ -98,8 +91,6 @@ void setup() // API stuff - internal server.on("/update_wifi_credentials", HTTP_POST, [](AsyncWebServerRequest* request) { - int params = request->params(); - // For settings SSID if (request->hasParam(ssid_key, true) && request->hasParam(wifi_password_key, true)) { LOG(ELOG_LEVEL_DEBUG, "Updating SSID config"); @@ -134,12 +125,6 @@ void setup() float level_max_float = level_max_str.toFloat(); float liters_float = liters_str.toFloat(); - const char* paramCStr = range_str.c_str(); - char* endPtr; - - // Convert the C string to a float using strtod - float value = strtod(paramCStr, &endPtr); - LOG(ELOG_LEVEL_DEBUG, "range_float:%D:", range_float); prefs.putFloat(level_sensor_range_key, range_float); @@ -166,10 +151,8 @@ void setup() }); setup_api_endpoints(); - // webSocket.onEvent(onWsEvent); - // server.addHandler(&webSocket); - - + webSocket.onEvent(onWsEvent); + server.addHandler(&webSocket); server.on("/chota.css", HTTP_GET, [](AsyncWebServerRequest* request) { request->send(LittleFS, "/chota.css", "text/css", false); }); server.on("/gauge.js", HTTP_GET, [](AsyncWebServerRequest* request) { request->send(LittleFS, "/gauge.js", "application/javascript", false); }); @@ -178,14 +161,14 @@ void setup() LOG(ELOG_LEVEL_DEBUG, "OTA Setup"); ArduinoOTA .onStart([]() { - String type; - if (ArduinoOTA.getCommand() == U_FLASH) - type = "sketch"; - else // U_SPIFFS - type = "filesystem"; + String type; + if (ArduinoOTA.getCommand() == U_FLASH) + type = "sketch"; + else // U_SPIFFS + type = "filesystem"; - // NOTE: if updating SPIFFS this would be the place to unmount SPIFFS using SPIFFS.end() - LOG(ELOG_LEVEL_DEBUG, "Start updating %s", type); }) + // NOTE: if updating SPIFFS this would be the place to unmount SPIFFS using SPIFFS.end() + LOG(ELOG_LEVEL_DEBUG, "Start updating %s", type); }) .onEnd([]() { LOG(ELOG_LEVEL_DEBUG, "\nEnd"); }) .onProgress([](unsigned int progress, unsigned int total) { Serial.printf("Progress: %u%%\r", (progress / (total / 100))); }) .onError([](ota_error_t error) { @@ -196,63 +179,20 @@ void setup() else if (error == OTA_RECEIVE_ERROR) LOG(ELOG_LEVEL_DEBUG, "Receive Failed"); else if (error == OTA_END_ERROR) LOG(ELOG_LEVEL_DEBUG, "End Failed"); }); - digitalWrite(LED_RED, 0); - - // Starting bootup sequence + LOG(ELOG_LEVEL_DEBUG, "Starting main tasks"); xTaskCreate(ethernet_task, "EthernetTask", 4096, NULL, 1, NULL); xTaskCreate(wifi_task, "WiFiTask", 10000, NULL, 1, NULL); - - if (ETH.linkUp()){ - LOG(ELOG_LEVEL_DEBUG, "Ethernet connected, starting update checker"); - xTaskCreate(check_update_task, "CheckUpdateTask", 1024 * 8, NULL, 1, NULL); - } else { - LOG(ELOG_LEVEL_DEBUG, "Ethernet not connected, starting update checker and WiFi Task"); - // esp_netif_set_default_netif(esp_netif_get_handle_from_ifkey("ETH_DEF")); - xTaskCreate(check_update_task, "CheckUpdateTask", 1024 * 8, NULL, 1, NULL); - delay(2000); - } - - LOG(ELOG_LEVEL_DEBUG, "Getting time now"); - // Configure time to UTC - configTime(0, 0, "pool.ntp.org"); - - // Wait until a valid time is obtained (time > 8 hours in seconds) - time_t now = time(NULL); - struct tm timeinfo; - int retry = 0; - while (now < 8 * 3600 && retry < 10) { - if(!getLocalTime(&timeinfo)){ - Serial.println("Failed to obtain time"); - } - Serial.println(&timeinfo, "%A, %B %d %Y %H:%M:%S"); - retry++; - } - - - getLocalTime(&timeinfo); - - // Sanity check: Ensure the year is at least 2020. - int currentYear = timeinfo.tm_year + 1900; // tm_year is years since 1900 - if (currentYear < 2020) { - LOG(ELOG_LEVEL_DEBUG, "Time not set properly: "); - } else { - LOG(ELOG_LEVEL_DEBUG, "Time is valid: %s", asctime(&timeinfo)); - } - - // Setup syslog - LOG(ELOG_LEVEL_ERROR, "Here is an error message, error code: %d", 17); - - - - - LOG(ELOG_LEVEL_DEBUG, "Starting webserver"); - server.begin(); - ArduinoOTA.begin(); - + // xTaskCreate(check_update_task, "CheckUpdateTask", 1024 * 8, NULL, 1, NULL); xTaskCreate(read_sensor_task, "ReadSensorTask", 1024 * 4, NULL, 1, NULL); xTaskCreate(collect_internal_telemetry_task, "InternalTelemetryTask", 2048, NULL, 1, NULL); xTaskCreate(display_task, "DisplayTask", 10000, NULL, 1, NULL); + xTaskCreate(get_time_task, "GetTimeTask", 1024 * 4, NULL, 1, NULL); + + LOG(ELOG_LEVEL_DEBUG, "Starting webserver"); + server.begin(); + LOG(ELOG_LEVEL_DEBUG, "Starting OTA handler"); + ArduinoOTA.begin(); } diff --git a/src/networking/json_builder.cpp b/src/networking/json_builder.cpp index 309d1d0..55705ab 100644 --- a/src/networking/json_builder.cpp +++ b/src/networking/json_builder.cpp @@ -27,6 +27,7 @@ StaticJsonDocument<128> build_telemetry_json(DeviceTelemetry data) { StaticJsonDocument<128> doc; doc["uptime_seconds"] = data.uptime_seconds; doc["heap_percent"] = data.heap_used_percent; + doc["temperature"] = data.temperature; return doc; } diff --git a/src/networking/networking.cpp b/src/networking/networking.cpp index a461700..e2e8e63 100644 --- a/src/networking/networking.cpp +++ b/src/networking/networking.cpp @@ -92,7 +92,7 @@ void wifi_task(void* parameter) void ethernet_task(void* parameter) { - LOG(ELOG_LEVEL_DEBUG, "Connecting Ethernet"); + LOG(ELOG_LEVEL_DEBUG, "Starting Ethernet Task"); ETH.begin(); ETH.setHostname(get_hostname(Ethernet)); while (true) { diff --git a/src/sensor/sensor.cpp b/src/sensor/sensor.cpp index 1927b14..2f42687 100644 --- a/src/sensor/sensor.cpp +++ b/src/sensor/sensor.cpp @@ -45,6 +45,7 @@ void init_sensor(){ void read_sensor_task(void* parameter) { + LOG(ELOG_LEVEL_DEBUG, "Starting read sensor tasks"); while (true) { // Get Values from sensor #ifndef USE_INA226 diff --git a/src/telemetry/telemetry.cpp b/src/telemetry/telemetry.cpp index 1fa7922..e870a77 100644 --- a/src/telemetry/telemetry.cpp +++ b/src/telemetry/telemetry.cpp @@ -1,17 +1,22 @@ #include "telemetry.h" #include #include "../global_data/global_data.h" +#include "tools/log.h" + +extern "C" uint8_t temprature_sens_read(); extern DeviceTelemetry telemetry; void collect_internal_telemetry_task(void* parameter) { + LOG(ELOG_LEVEL_DEBUG, "Starting internal telemetry tasks"); while (true) { float heap_usage = (float(ESP.getFreeHeap()) / float(ESP.getHeapSize())) * 100; uint64_t uptime_seconds = millis() / 1000; telemetry.heap_used_percent = heap_usage; telemetry.uptime_seconds = uptime_seconds; + telemetry.temperature = (temprature_sens_read()-32) / 1.8; delay(60000); } } \ No newline at end of file diff --git a/src/tools/log.h b/src/tools/log.h index ea0a3f7..35ee4fe 100644 --- a/src/tools/log.h +++ b/src/tools/log.h @@ -4,7 +4,7 @@ #define LOG(LEVEL, FMT, ...) \ do { \ - Logger.log(0, LEVEL, "[Core: %i][Task: %s][Fn: %s]" FMT, \ + Logger.log(0, LEVEL, "[Core: %i][Task: %s][Fn: %s] " FMT, \ xPortGetCoreID(), \ pcTaskGetName(xTaskGetCurrentTaskHandle()), \ __FUNCTION__, \ diff --git a/src/tools/tools.cpp b/src/tools/tools.cpp index 8df1dc5..cb67833 100644 --- a/src/tools/tools.cpp +++ b/src/tools/tools.cpp @@ -6,10 +6,12 @@ #include #include #include "log.h" +#include "esp_sntp.h" + extern Preferences prefs; extern OTAStatus ota_status; -// extern AsyncWebSocket webSocket; +extern AsyncWebSocket webSocket; extern Version current_spiffs_version; @@ -43,7 +45,7 @@ void update_started() { void update_finished() { LOG(ELOG_LEVEL_DEBUG, "OTA Update finished"); ota_status.update_progress = -1; - // webSocket.textAll(String(-1).c_str()); + webSocket.textAll(String(-1).c_str()); } void update_progress(int cur, int total) { @@ -52,7 +54,7 @@ void update_progress(int cur, int total) { ota_status.update_progress = int(float(cur)/float(total)*100); LOG(ELOG_LEVEL_DEBUG, "OTA Update progress: %d/%d, %i", cur, total, ota_status.update_progress); } - // webSocket.textAll(String(ota_status.update_progress).c_str()); + webSocket.textAll(String(ota_status.update_progress).c_str()); LOG(ELOG_LEVEL_DEBUG, "OTA Update progress: %d/%d", cur, total); } @@ -62,6 +64,7 @@ void update_error(int err) { } void check_update_task(void* parameter) { + LOG(ELOG_LEVEL_DEBUG, "Starting check Update Task"); ota_status.current_version = current_software_version; ota_status.update_progress = -1; #ifdef USE_INA226 @@ -127,14 +130,47 @@ void run_ota_update_task(void* parameter) { vTaskDelete(NULL); } -// void onWsEvent(AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventType type, -// void *arg, uint8_t *data, size_t len) { -// if (type == WS_EVT_CONNECT) { -// Serial.println("WebSocket client connected"); -// } else if (type == WS_EVT_DISCONNECT) { -// Serial.println("WebSocket client disconnected"); -// } else if (type == WS_EVT_DATA) { -// // Optionally process data received from the client -// } -// } +void onWsEvent(AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventType type, + void *arg, uint8_t *data, size_t len) { + if (type == WS_EVT_CONNECT) { + Serial.println("WebSocket client connected"); + } else if (type == WS_EVT_DISCONNECT) { + Serial.println("WebSocket client disconnected"); + } else if (type == WS_EVT_DATA) { + // Optionally process data received from the client + } +} +void get_time_task(void* parameter) { + LOG(ELOG_LEVEL_DEBUG, "Starting GetTimeTask"); + LOG(ELOG_LEVEL_DEBUG, "Trying to get time from Internet"); + + sntp_set_time_sync_notification_cb(onTimeSync); + sntp_set_sync_mode(SNTP_SYNC_MODE_SMOOTH); + sntp_set_sync_interval(1000 * 60 * 60); //re-sync every hour + configTzTime("UTC0", "pool.ntp.org", "1.europe.pool.ntp.org", " time.Windows.com"); + waitForTime(); + vTaskDelete(NULL); +} + +// Time stuff + +// Handler to handle successful time sync +void onTimeSync(struct timeval* tv) { + struct tm timeinfo; + getLocalTime(&timeinfo); + LOG(ELOG_LEVEL_DEBUG, "Time synchronized. New Time: %s", asctime(&timeinfo)); +} + +// wait for succesful time sync +bool waitForTime() { + time_t now; + do { + time(&now); + if (now > 8 * 3600) break; + delay(500); + LOG(ELOG_LEVEL_WARNING, "No valid time."); + } while (true); + LOG(ELOG_LEVEL_DEBUG, "Found valid time."); + return true; +} \ No newline at end of file diff --git a/src/tools/tools.h b/src/tools/tools.h index 839a48f..62af982 100644 --- a/src/tools/tools.h +++ b/src/tools/tools.h @@ -10,7 +10,11 @@ bool is_error(ActiveErrors active_errors); String processor(const String& var); void check_update_task(void* parameter); void run_ota_update_task(void* parameter); -// void onWsEvent(AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventType type,void *arg, uint8_t *data, size_t len); +void onWsEvent(AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventType type,void *arg, uint8_t *data, size_t len); +void get_time_task(void* parameter); + +void onTimeSync(struct timeval* tv); +bool waitForTime(); typedef struct { OTAStatus ota_status;