Compare commits
2 Commits
rev2
...
7542d44e21
| Author | SHA1 | Date | |
|---|---|---|---|
| 7542d44e21 | |||
| df06be23cb |
@@ -1,7 +1,7 @@
|
||||
version: '3.8'
|
||||
services:
|
||||
app:
|
||||
image: gitea.tobiasmaier.me/tobimai/devcontainer-pio:latest
|
||||
image: gitea.maiertobi.de/tobimai/devcontainer-pio:latest
|
||||
user: tobi:tobi
|
||||
volumes:
|
||||
- ..:/workspace:cached
|
||||
|
||||
@@ -1,26 +1,24 @@
|
||||
name: Compilie project and upload binaries
|
||||
name: Test compiling project
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: ["main"]
|
||||
on: [push]
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
container:
|
||||
image: gitea.tobiasmaier.me/tobimai/devcontainer-pio:2.1
|
||||
image: gitea.maiertobi.de/tobimai/devcontainer-pio:latest
|
||||
|
||||
steps:
|
||||
- name: Checkout Code
|
||||
uses: actions/checkout@v2
|
||||
- name: Run PlatformIO build for SPIFFS (same in both platforms, so only one build is necessary)
|
||||
run: which pio && id && pio run --target buildfs -e ESP32_INA233
|
||||
- name: Run PlatformIO Tests
|
||||
run: pio test -e native
|
||||
- name: Run PlatformIO build for INA233
|
||||
run: pio run -e ESP32_INA233
|
||||
- name: Run PlatformIO build for INA226
|
||||
run: pio run -e ESP32_INA226
|
||||
- name: Run PlatformIO build for SPIFFS (same in both platforms, so only one build is necessary)
|
||||
run: pio run --target buildfs -e ESP32_INA233
|
||||
- name: Upload firmware binary for INA233
|
||||
run: |
|
||||
VERSION=$(sed -n 's/#define current_software_version Version{[[:space:]]*\([0-9]\+\),[[:space:]]*\([0-9]\+\),[[:space:]]*\([0-9]\+\)}/\1.\2.\3/p' src/global_data/defines.h)
|
||||
@@ -29,7 +27,7 @@ jobs:
|
||||
curl -X PUT \
|
||||
-H "Content-Type: application/octet-stream" \
|
||||
--data-binary @.pio/build/ESP32_INA233/firmware.bin \
|
||||
https://iot.tobiasmaier.me/firmware/waterlevel/INA233REV2/${VERSION}
|
||||
https://iot.tobiasmaier.me/firmware/waterlevel/INA233/${VERSION}
|
||||
|
||||
- name: Upload firmware binary for INA226
|
||||
run: |
|
||||
@@ -39,7 +37,7 @@ jobs:
|
||||
curl -X PUT \
|
||||
-H "Content-Type: application/octet-stream" \
|
||||
--data-binary @.pio/build/ESP32_INA226/firmware.bin \
|
||||
https://iot.tobiasmaier.me/firmware/waterlevel/INA226REV2/${VERSION}
|
||||
https://iot.tobiasmaier.me/firmware/waterlevel/INA226/${VERSION}
|
||||
|
||||
- name: Upload SPIFFS binary
|
||||
run: |
|
||||
@@ -48,5 +46,5 @@ jobs:
|
||||
|
||||
curl -X PUT \
|
||||
-H "Content-Type: application/octet-stream" \
|
||||
--data-binary @.pio/build/ESP32_INA233/littlefs.bin \
|
||||
--data-binary @.pio/build/ESP32_INA233/spiffs.bin \
|
||||
https://iot.tobiasmaier.me/filesystem/waterlevel/generic/${VERSION}
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
name: Test project compilation
|
||||
|
||||
on:
|
||||
push:
|
||||
branches-ignore: ["main"]
|
||||
pull_request:
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
container:
|
||||
image: gitea.tobiasmaier.me/tobimai/devcontainer-pio:2.1
|
||||
|
||||
steps:
|
||||
- name: Checkout Code
|
||||
uses: actions/checkout@v2
|
||||
- name: Run PlatformIO build for SPIFFS (same in both platforms, so only one build is necessary)
|
||||
run: which pio && id && pio run --target buildfs -e ESP32_INA233
|
||||
- name: Run PlatformIO Tests
|
||||
run: pio test -e native
|
||||
- name: Run PlatformIO build for INA233
|
||||
run: pio run -e ESP32_INA233
|
||||
- name: Run PlatformIO build for INA226
|
||||
run: pio run -e ESP32_INA226
|
||||
1
.vscode/extensions.json
vendored
1
.vscode/extensions.json
vendored
@@ -2,7 +2,6 @@
|
||||
// See http://go.microsoft.com/fwlink/?LinkId=827846
|
||||
// for the documentation about the extensions.json format
|
||||
"recommendations": [
|
||||
"pioarduino.pioarduino-ide",
|
||||
"platformio.platformio-ide"
|
||||
],
|
||||
"unwantedRecommendations": [
|
||||
|
||||
22
.vscode/settings.json
vendored
22
.vscode/settings.json
vendored
@@ -2,26 +2,6 @@
|
||||
"files.associations": {
|
||||
"iostream": "cpp",
|
||||
"random": "cpp",
|
||||
"vector": "cpp",
|
||||
"array": "cpp",
|
||||
"deque": "cpp",
|
||||
"string": "cpp",
|
||||
"unordered_map": "cpp",
|
||||
"unordered_set": "cpp",
|
||||
"string_view": "cpp",
|
||||
"memory": "cpp",
|
||||
"initializer_list": "cpp",
|
||||
"regex": "cpp",
|
||||
"istream": "cpp",
|
||||
"ostream": "cpp",
|
||||
"chrono": "cpp",
|
||||
"list": "cpp",
|
||||
"format": "cpp",
|
||||
"mutex": "cpp",
|
||||
"span": "cpp",
|
||||
"text_encoding": "cpp",
|
||||
"thread": "cpp",
|
||||
"*.inc": "cpp",
|
||||
"cstddef": "cpp"
|
||||
"vector": "cpp"
|
||||
}
|
||||
}
|
||||
@@ -25,7 +25,6 @@ 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);
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
<!DOCTYPE html>
|
||||
<meta charset="UTF-8">
|
||||
|
||||
<head>
|
||||
<link rel="stylesheet" href="/chota.css">
|
||||
@@ -20,6 +19,9 @@
|
||||
<a href="/export">Data export</a>
|
||||
</div>
|
||||
</div>
|
||||
<div class="nav-right">
|
||||
<a class="button outline">Button</a>
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
<div class="row">
|
||||
@@ -119,10 +121,6 @@
|
||||
<td>Heap usage: </td>
|
||||
<td id="heap">XXX</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>CPU Temperature: </td>
|
||||
<td id="temperature">XXX</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
@@ -1 +1 @@
|
||||
10
|
||||
8
|
||||
@@ -17,7 +17,7 @@ void listNetworkInterfaces() {
|
||||
}
|
||||
|
||||
void setEthernetAsDefault() {
|
||||
Logger.log(0, ELOG_LEVEL_DEBUG, "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
|
||||
logger.log(0, DEBUG, "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
|
||||
listNetworkInterfaces();
|
||||
// Attempt to locate the Ethernet network interface.
|
||||
// (The name may vary—on some systems it might be "eth0")
|
||||
@@ -31,8 +31,8 @@ void setEthernetAsDefault() {
|
||||
struct netif *eth_netif2 = netif_find("ETH_DEF");
|
||||
if (netif) {
|
||||
netif_set_default(eth_netif2);
|
||||
Logger.log(0, ELOG_LEVEL_DEBUG, "Ethernet set as default network interface.");
|
||||
logger.log(0, DEBUG, "Ethernet set as default network interface.");
|
||||
} else {
|
||||
Logger.log(0, ELOG_LEVEL_DEBUG, "Could not find Ethernet netif.");
|
||||
logger.log(0, DEBUG, "Could not find Ethernet netif.");
|
||||
}
|
||||
}
|
||||
@@ -10,25 +10,25 @@
|
||||
#define REGISTER_READ_IIN 0x89
|
||||
|
||||
enum AveragingMode {
|
||||
averages_1 = 0b000,
|
||||
averages_4 = 0b001,
|
||||
averages_16 = 0b010,
|
||||
averages_64 = 0b011,
|
||||
averages_128 = 0b100,
|
||||
averages_256 = 0b101,
|
||||
averages_512 = 0b110,
|
||||
averages_1024 = 0b111
|
||||
averages_1 = B000,
|
||||
averages_4 = B001,
|
||||
averages_16 = B010,
|
||||
averages_64 = B011,
|
||||
averages_128 = B100,
|
||||
averages_256 = B101,
|
||||
averages_512 = B110,
|
||||
averages_1024 = B111
|
||||
};
|
||||
|
||||
enum ConversionTime {
|
||||
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
|
||||
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
|
||||
};
|
||||
|
||||
class INA233{
|
||||
|
||||
@@ -5,8 +5,6 @@
|
||||
#include "Arduino.h"
|
||||
#include <ArduinoJson.h>
|
||||
#include <HTTPClient.h>
|
||||
#include <WiFiClient.h>
|
||||
#include <WiFiClientSecure.h>
|
||||
#include <vector>
|
||||
#include <Elog.h>
|
||||
#include <HTTPUpdate.h>
|
||||
@@ -24,14 +22,14 @@ Firmware OTA::getLatestVersionOnServer() {
|
||||
HTTPClient http;
|
||||
http.begin(_serverUrl);
|
||||
int httpCode = http.GET();
|
||||
Logger.log(0, ELOG_LEVEL_DEBUG, "HTTP Code: %d", httpCode);
|
||||
logger.log(0, DEBUG, "HTTP Code: %d", httpCode);
|
||||
|
||||
if (httpCode != 200) {
|
||||
return createErrorResponse("HTTP GET request failed with code " + String(httpCode));
|
||||
}
|
||||
|
||||
String payload = http.getString();
|
||||
Logger.log(0, ELOG_LEVEL_DEBUG, "Payload: %s", payload.c_str());
|
||||
logger.log(0, DEBUG, "Payload: %s", payload.c_str());
|
||||
DynamicJsonDocument doc(4096);
|
||||
DeserializationError error = deserializeJson(doc, payload);
|
||||
|
||||
@@ -56,7 +54,7 @@ Firmware OTA::getLatestVersionOnServer() {
|
||||
deviceConfig
|
||||
});
|
||||
} else {
|
||||
Logger.log(0, ELOG_LEVEL_DEBUG, "Configuration %s does not match current device configuration %s", deviceConfig.c_str(), _current_device_configuration.c_str());
|
||||
logger.log(0, DEBUG, "Configuration %s does not match current device configuration %s", deviceConfig.c_str(), _current_device_configuration.c_str());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -69,7 +67,7 @@ Firmware OTA::getLatestVersionOnServer() {
|
||||
Configuration latest = getLatestConfiguration(configs.data(), configs.size());
|
||||
|
||||
if (!isVersionNewer(_currentVersion, latest.version)) {
|
||||
Logger.log(0, ELOG_LEVEL_DEBUG, "No newer version found. Server version: %d.%d.%d", latest.version.major, latest.version.minor, latest.version.patch);
|
||||
logger.log(0, DEBUG, "No newer version found. Server version: %d.%d.%d", latest.version.major, latest.version.minor, latest.version.patch);
|
||||
}
|
||||
|
||||
return Firmware{
|
||||
@@ -90,89 +88,79 @@ Firmware OTA::createErrorResponse(const String& errorMsg) {
|
||||
}
|
||||
|
||||
void run_ota_update(String url, std::function<void()> callback_started, std::function<void()> callback_finished, std::function<void(int, int)> callback_progress, std::function<void(int)> callback_error) {
|
||||
Logger.log(0, ELOG_LEVEL_DEBUG, "Starting OTA upgrade");
|
||||
logger.log(0, DEBUG, "Starting OTA upgrade");
|
||||
HTTPUpdate httpUpdate;
|
||||
httpUpdate.onStart(callback_started);
|
||||
httpUpdate.onEnd(callback_finished);
|
||||
httpUpdate.onProgress(callback_progress);
|
||||
httpUpdate.onError(callback_error);
|
||||
Logger.log(0, ELOG_LEVEL_DEBUG, "Defined callbacks, Starting update now");
|
||||
logger.log(0, DEBUG, "Defined callbacks, Starting update now");
|
||||
|
||||
t_httpUpdate_return ret = HTTP_UPDATE_FAILED;
|
||||
t_httpUpdate_return ret;
|
||||
|
||||
if (url.startsWith("https")) {
|
||||
Logger.log(0, ELOG_LEVEL_DEBUG, "HTTPS URL");
|
||||
logger.log(0, DEBUG, "HTTPS URL");
|
||||
WiFiClientSecure client;
|
||||
// client.setInsecure();
|
||||
client.setInsecure();
|
||||
ret = httpUpdate.update(client, url);
|
||||
} else if (url.startsWith("http")) {
|
||||
Logger.log(0, ELOG_LEVEL_DEBUG, "HTTP URL");
|
||||
logger.log(0, DEBUG, "HTTP URL");
|
||||
WiFiClient client;
|
||||
ret = httpUpdate.update(client, url);
|
||||
} else {
|
||||
Logger.log(0, ELOG_LEVEL_ERROR, "URL is not valid: \n%s", url.c_str());
|
||||
if (callback_error) callback_error(-1);
|
||||
return;
|
||||
logger.log(0, ERROR, "URL is not valid: \n%s", url.c_str());
|
||||
}
|
||||
|
||||
switch (ret) {
|
||||
case HTTP_UPDATE_FAILED:
|
||||
Logger.log(0, ELOG_LEVEL_ERROR, "HTTP_UPDATE_FAILED Error (%d): %s\n", httpUpdate.getLastError(), httpUpdate.getLastErrorString().c_str());
|
||||
// Don't restart ESP on HTTP errors, just return
|
||||
if (callback_error) callback_error(httpUpdate.getLastError());
|
||||
logger.log(0, ERROR, "HTTP_UPDATE_FAILED Error (%d): %s\n", httpUpdate.getLastError(), httpUpdate.getLastErrorString().c_str());
|
||||
break;
|
||||
|
||||
case HTTP_UPDATE_NO_UPDATES:
|
||||
Logger.log(0, ELOG_LEVEL_ERROR, "HTTP_UPDATE_NO_UPDATES");
|
||||
if (callback_error) callback_error(-2);
|
||||
logger.log(0, ERROR, "HTTP_UPDATE_NO_UPDATES");
|
||||
break;
|
||||
|
||||
case HTTP_UPDATE_OK:
|
||||
Logger.log(0, ELOG_LEVEL_DEBUG, "Update done");
|
||||
logger.log(0, DEBUG, "Update done");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void run_ota_spiffs_update(String url, std::function<void()> callback_started, std::function<void()> callback_finished, std::function<void(int, int)> callback_progress, std::function<void(int)> callback_error) {
|
||||
Logger.log(0, ELOG_LEVEL_DEBUG, "Starting OTA SPIFFS upgrade");
|
||||
logger.log(0, DEBUG, "Starting OTA SPIFFS upgrade");
|
||||
HTTPUpdate httpUpdate;
|
||||
httpUpdate.onStart(callback_started);
|
||||
httpUpdate.onEnd(callback_finished);
|
||||
httpUpdate.onProgress(callback_progress);
|
||||
httpUpdate.onError(callback_error);
|
||||
Logger.log(0, ELOG_LEVEL_DEBUG, "Defined callbacks, Starting update now");
|
||||
logger.log(0, DEBUG, "Defined callbacks, Starting update now");
|
||||
|
||||
t_httpUpdate_return ret = HTTP_UPDATE_FAILED;
|
||||
t_httpUpdate_return ret;
|
||||
|
||||
if (url.startsWith("https")) {
|
||||
Logger.log(0, ELOG_LEVEL_DEBUG, "HTTPS URL");
|
||||
logger.log(0, DEBUG, "HTTPS URL");
|
||||
WiFiClientSecure client;
|
||||
client.setInsecure();
|
||||
ret = httpUpdate.updateSpiffs(client, url);
|
||||
} else if (url.startsWith("http")) {
|
||||
Logger.log(0, ELOG_LEVEL_DEBUG, "HTTP URL");
|
||||
logger.log(0, DEBUG, "HTTP URL");
|
||||
WiFiClient client;
|
||||
ret = httpUpdate.updateSpiffs(client, url);
|
||||
} else {
|
||||
Logger.log(0, ELOG_LEVEL_ERROR, "URL is not valid: \n%s", url.c_str());
|
||||
if (callback_error) callback_error(-1);
|
||||
return;
|
||||
logger.log(0, ERROR, "URL is not valid: \n%s", url.c_str());
|
||||
}
|
||||
|
||||
switch (ret) {
|
||||
case HTTP_UPDATE_FAILED:
|
||||
Logger.log(0, ELOG_LEVEL_ERROR, "HTTP_UPDATE_FAILED Error (%d): %s\n", httpUpdate.getLastError(), httpUpdate.getLastErrorString().c_str());
|
||||
// Don't restart ESP on HTTP errors, just return
|
||||
if (callback_error) callback_error(httpUpdate.getLastError());
|
||||
logger.log(0, ERROR, "HTTP_UPDATE_FAILED Error (%d): %s\n", httpUpdate.getLastError(), httpUpdate.getLastErrorString().c_str());
|
||||
break;
|
||||
|
||||
case HTTP_UPDATE_NO_UPDATES:
|
||||
Logger.log(0, ELOG_LEVEL_ERROR, "HTTP_UPDATE_NO_UPDATES");
|
||||
if (callback_error) callback_error(-2);
|
||||
logger.log(0, ERROR, "HTTP_UPDATE_NO_UPDATES");
|
||||
break;
|
||||
|
||||
case HTTP_UPDATE_OK:
|
||||
Logger.log(0, ELOG_LEVEL_DEBUG, "SPIFFS Update done");
|
||||
logger.log(0, DEBUG, "SPIFFS Update done");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,40 +11,39 @@
|
||||
[platformio]
|
||||
default_envs = ESP32_INA233, ESP32_INA226
|
||||
|
||||
[env:esp32_base]
|
||||
platform = https://github.com/pioarduino/platform-espressif32/releases/download/55.03.32/platform-espressif32.zip
|
||||
[env:ESP32_INA233]
|
||||
platform = espressif32
|
||||
board = esp32dev
|
||||
framework = arduino
|
||||
monitor_speed = 115200
|
||||
monitor_filters = esp32_exception_decoder
|
||||
board_build.partitions = min_spiffs.csv
|
||||
lib_deps =
|
||||
esp32async/AsyncTCP @ ~3.4.9
|
||||
esp32async/ESPAsyncWebServer @ ~3.8.1
|
||||
robtillaart/INA226@ ~0.6.4
|
||||
bblanchon/ArduinoJson@^6.21.3
|
||||
x385832/Elog@~2.0.10
|
||||
fetchOTA
|
||||
build_flags = -fexceptions
|
||||
build_src_flags = -Wall -Wextra
|
||||
|
||||
|
||||
[env:ESP32_INA233]
|
||||
extends = env:esp32_base
|
||||
lib_deps =
|
||||
${env:esp32_base.lib_deps}
|
||||
ottowinter/ESPAsyncWebServer-esphome@^3.3.0
|
||||
bblanchon/ArduinoJson@^6.21.3
|
||||
fetchOTA
|
||||
INA233
|
||||
; upload_protocol = espota
|
||||
; upload_port = 192.168.18.18
|
||||
ESP32Ping
|
||||
https://github.com/tobimai/elog.git#fix-syslog
|
||||
board_build.partitions = default.csv
|
||||
upload_protocol = espota
|
||||
upload_port = 192.168.5.205
|
||||
build_flags = -Wall -Wextra -DLOGGING_SPIFFS_DISABLE -DLOGGING_SD_DISABLE
|
||||
|
||||
[env:ESP32_INA226]
|
||||
extends = env:esp32_base
|
||||
platform = espressif32
|
||||
board = esp32dev
|
||||
framework = arduino
|
||||
monitor_speed = 115200
|
||||
lib_deps =
|
||||
${env:esp32_base.lib_deps}
|
||||
robtillaart/INA226@ ~0.6.4
|
||||
ottowinter/ESPAsyncWebServer-esphome@^3.3.0
|
||||
robtillaart/INA226@^0.4.4
|
||||
bblanchon/ArduinoJson@^6.21.3
|
||||
jsc/ArduinoLog
|
||||
ESP32Ping
|
||||
https://github.com/tobimai/elog.git#fix-syslog
|
||||
board_build.partitions = default.csv
|
||||
upload_protocol = espota
|
||||
upload_port = 192.168.18.21
|
||||
build_flags = ${env:esp32_base.build_flags} -DUSE_INA226
|
||||
upload_port = 192.168.4.18
|
||||
build_flags = -Wall -Wextra -DUSE_INA226 -DLOGGING_SPIFFS_DISABLE -DLOGGING_SD_DISABLE
|
||||
|
||||
[env:native]
|
||||
platform = native
|
||||
@@ -52,4 +51,3 @@ build_flags = -DUNIT_TEST -Ilib/fetchOTA/
|
||||
lib_deps =
|
||||
fetchOTA
|
||||
arduino-libraries/ArduinoHttpClient@^0.6.1
|
||||
|
||||
|
||||
@@ -4,31 +4,96 @@
|
||||
#include "../tools/tools.h"
|
||||
#include <tools/log.h>
|
||||
|
||||
// TODO: Rewrite so that this task does not do anything smart, just receives data over queue and displays it
|
||||
// So it just receives: OK, Error, error code X, warning, warning X (blink)
|
||||
extern ActiveErrors active_errors;
|
||||
extern WaterData water_data;
|
||||
|
||||
void display_task(void* parameter)
|
||||
void display_percentage(float percentage)
|
||||
{
|
||||
LOG(ELOG_LEVEL_DEBUG, "Starting LED tasks");
|
||||
led_setup();
|
||||
while (true) {
|
||||
ledcWrite(LED_RED, 0);
|
||||
ledcWrite(LED_GREEN, 255);
|
||||
delay(500);
|
||||
ledcWrite(LED_RED, LED_RED_HIGH);
|
||||
ledcWrite(LED_GREEN, 0);
|
||||
delay(500);
|
||||
digitalWrite(LED_RED, 0);
|
||||
|
||||
if (percentage > 0) {
|
||||
digitalWrite(LED_1, 1);
|
||||
} else {
|
||||
digitalWrite(LED_1, 0);
|
||||
}
|
||||
if (percentage > 20) {
|
||||
digitalWrite(LED_2, 1);
|
||||
} else {
|
||||
digitalWrite(LED_2, 0);
|
||||
}
|
||||
if (percentage > 40) {
|
||||
digitalWrite(LED_3, 1);
|
||||
} else {
|
||||
digitalWrite(LED_3, 0);
|
||||
}
|
||||
if (percentage > 60) {
|
||||
digitalWrite(LED_4, 1);
|
||||
} else {
|
||||
digitalWrite(LED_4, 0);
|
||||
}
|
||||
if (percentage > 80) {
|
||||
digitalWrite(LED_5, 1);
|
||||
} else {
|
||||
digitalWrite(LED_5, 0);
|
||||
}
|
||||
|
||||
if (percentage > 10) {
|
||||
delay(3000);
|
||||
} else if (percentage > 0) {
|
||||
for (int i = 0; i < 3; i++) {
|
||||
digitalWrite(LED_1, 1);
|
||||
delay(500);
|
||||
digitalWrite(LED_1, 0);
|
||||
delay(500);
|
||||
}
|
||||
} else if (percentage <= 0) {
|
||||
for (int i = 0; i < 15; i++) {
|
||||
digitalWrite(LED_1, 1);
|
||||
delay(100);
|
||||
digitalWrite(LED_1, 0);
|
||||
delay(100);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void display_error_code(byte err_code)
|
||||
{
|
||||
digitalWrite(LED_RED, 1);
|
||||
digitalWrite(LED_1, bitRead(err_code, 0));
|
||||
digitalWrite(LED_2, bitRead(err_code, 1));
|
||||
digitalWrite(LED_3, bitRead(err_code, 2));
|
||||
digitalWrite(LED_4, bitRead(err_code, 3));
|
||||
digitalWrite(LED_5, bitRead(err_code, 4));
|
||||
}
|
||||
|
||||
// Setup pin modes etc.
|
||||
void led_setup() {
|
||||
pinMode(LED_RED, OUTPUT);
|
||||
pinMode(LED_GREEN, OUTPUT);
|
||||
|
||||
ledcAttach(LED_RED, LED_PWM_FREQUENCY, LED_PWM_RESOLUTION);
|
||||
ledcAttach(LED_GREEN, LED_PWM_FREQUENCY, LED_PWM_RESOLUTION);
|
||||
ledcWrite(LED_RED, LED_RED_HIGH);
|
||||
ledcWrite(LED_GREEN, 255);
|
||||
void display_task(void* parameter)
|
||||
{
|
||||
while (true) {
|
||||
if (!is_error(active_errors)) {
|
||||
// We have no error, refresh status display and wait half a second
|
||||
display_percentage(water_data.percentage);
|
||||
} else {
|
||||
// We have an error, display error code for 3 seconds and then water level for 3 seconds
|
||||
if (active_errors.voltage_low) {
|
||||
display_error_code(1);
|
||||
LOG(WARNING, "Sensor Error - Voltage low");
|
||||
delay(3000);
|
||||
} else if (active_errors.voltage_high) {
|
||||
display_error_code(2);
|
||||
LOG(WARNING, "Sensor Error - Voltage High");
|
||||
delay(3000);
|
||||
} else if (active_errors.current_low) {
|
||||
display_error_code(3);
|
||||
LOG(WARNING, "Sensor Error - Current low");
|
||||
delay(3000);
|
||||
} else if (active_errors.current_high) {
|
||||
display_error_code(4);
|
||||
LOG(WARNING, "Sensor Error - Current high");
|
||||
delay(3000);
|
||||
} else {
|
||||
delay(3000);
|
||||
}
|
||||
display_percentage(water_data.percentage);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,12 @@
|
||||
#include <Arduino.h>
|
||||
|
||||
#define LED_RED 15
|
||||
#define LED_GREEN 2
|
||||
#define LED_PWM_FREQUENCY 5000
|
||||
#define LED_PWM_RESOLUTION 8
|
||||
#define LED_CHANNEL_RED 0
|
||||
#define LED_CHANNEL_GREEN 1
|
||||
#define LED_1 4
|
||||
#define LED_2 2
|
||||
#define LED_3 15
|
||||
#define LED_4 13
|
||||
#define LED_5 12
|
||||
#define LED_RED 14
|
||||
|
||||
#define LED_RED_HIGH 150
|
||||
|
||||
// void display_error_code(byte err_code);
|
||||
void display_task(void* parameter);
|
||||
void led_setup();
|
||||
void display_percentage(float percentage);
|
||||
void display_error_code(byte err_code);
|
||||
void display_task(void* parameter);
|
||||
@@ -7,7 +7,7 @@
|
||||
#define water_level_min_key "water_level_min"
|
||||
#define water_level_max_key "water_level_max"
|
||||
#define water_volume_key "water_volume"
|
||||
#define current_software_version Version{2, 5, 0}
|
||||
#define REQUIRED_SPIFFS_VERSION Version{10, 0, 0}
|
||||
#define current_software_version Version{1, 3, 0}
|
||||
#define REQUIRED_SPIFFS_VERSION Version{8, 0, 0}
|
||||
|
||||
#define RESISTOR_VALUE 4
|
||||
@@ -1,3 +1,12 @@
|
||||
#include "global_data.h"
|
||||
|
||||
OTAStatus ota_status;
|
||||
NetworkData wifi_data;
|
||||
NetworkData ethernet_data;
|
||||
DeviceTelemetry telemetry;
|
||||
|
||||
SensorData shunt_data;
|
||||
WaterData water_data;
|
||||
|
||||
OTAStatus ota_status;
|
||||
|
||||
ActiveErrors active_errors = { false, false, false, false, false, false };
|
||||
@@ -3,112 +3,47 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
/**
|
||||
* @brief Structure to hold sensor data.
|
||||
*
|
||||
* Contains voltage and current measurements from the sensor.
|
||||
*/
|
||||
struct SensorData {
|
||||
float bus_voltage; /**< Bus voltage in volts */
|
||||
float shunt_voltage; /**< Shunt voltage in millivolts */
|
||||
float shunt_current; /**< Shunt current in milliamps */
|
||||
float bus_voltage;
|
||||
float shunt_voltage;
|
||||
float shunt_current;
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Structure to hold water data.
|
||||
*
|
||||
* Contains water level, volume, and percentage measurements.
|
||||
*/
|
||||
struct WaterData{
|
||||
float level; /**< Water level in cm */
|
||||
float liters; /**< Water volume in liters */
|
||||
float percentage; /**< Water level as a percentage */
|
||||
// Water level in cm
|
||||
float level;
|
||||
// Water volume in liters
|
||||
float liters;
|
||||
// Percentage
|
||||
float percentage;
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Structure to hold network data.
|
||||
*
|
||||
* Contains network-related information such as IP address and signal strength.
|
||||
*/
|
||||
|
||||
struct NetworkData {
|
||||
char ip_address[16]; /**< IP address of the device (max 15 chars + null terminator) */
|
||||
bool link; /**< Whether the network link is active */
|
||||
float rssi; /**< Received signal strength indicator */
|
||||
char network_name[33]; /**< Name of the network (max 32 chars + null terminator) */
|
||||
String ip_address;
|
||||
bool link;
|
||||
float rssi;
|
||||
String network_name;
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Structure to hold device telemetry data.
|
||||
*
|
||||
* Contains information about the device's internal state.
|
||||
*/
|
||||
struct DeviceTelemetry {
|
||||
float heap_used_percent; /**< Percentage of heap memory used */
|
||||
int uptime_seconds; /**< Uptime of the device in seconds */
|
||||
float temperature; /**< Temperature of the device in Celsius */
|
||||
float heap_used_percent;
|
||||
int uptime_seconds;
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Structure to hold active error flags.
|
||||
*
|
||||
* Contains boolean flags indicating various error conditions.
|
||||
*/
|
||||
struct ActiveErrors {
|
||||
bool voltage_low; /**< Indicates if the voltage is too low */
|
||||
bool voltage_high; /**< Indicates if the voltage is too high */
|
||||
bool current_low; /**< Indicates if the current is too low */
|
||||
bool current_high; /**< Indicates if the current is too high */
|
||||
bool level_low; /**< Indicates if the water level is too low */
|
||||
bool level_high; /**< Indicates if the water level is too high */
|
||||
bool voltage_low;
|
||||
bool voltage_high;
|
||||
bool current_low;
|
||||
bool current_high;
|
||||
bool level_low;
|
||||
bool level_high;
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Structure to hold OTA (Over-The-Air) update status.
|
||||
*
|
||||
* Contains information about the OTA update process.
|
||||
*/
|
||||
struct OTAStatus {
|
||||
bool update_available; /**< Indicates if an update is available */
|
||||
Version current_version; /**< Current version of the firmware */
|
||||
Version latest_version; /**< Latest available version of the firmware */
|
||||
int update_progress; /**< Progress of the update as a percentage */
|
||||
String update_url; /**< URL to download the update */
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Structure to hold the current state of the system.
|
||||
*
|
||||
* Contains all data structs to represent the current state of the system.
|
||||
*/
|
||||
typedef struct {
|
||||
WaterData waterData; /**< Latest water data */
|
||||
SensorData sensorData; /**< Latest sensor data */
|
||||
NetworkData wifiData; /**< Latest WiFi network data */
|
||||
NetworkData ethernetData; /**< Latest Ethernet network data */
|
||||
DeviceTelemetry telemetryData; /**< Latest telemetry data */
|
||||
OTAStatus otaStatus; /**< Latest OTA status */
|
||||
ActiveErrors activeErrors; /**< Latest active errors */
|
||||
} CurrentState;
|
||||
|
||||
// Enum to represent different types of data that can be sent between tasks
|
||||
typedef enum {
|
||||
DATA_TYPE_SENSOR,
|
||||
DATA_TYPE_WATER,
|
||||
DATA_TYPE_WIFI,
|
||||
DATA_TYPE_ETHERNET,
|
||||
DATA_TYPE_TELEMETRY
|
||||
} DataType;
|
||||
|
||||
// Union to hold different types of data
|
||||
typedef union {
|
||||
SensorData sensorData;
|
||||
WaterData waterData;
|
||||
NetworkData networkData;
|
||||
DeviceTelemetry telemetryData;
|
||||
} DataUnion;
|
||||
|
||||
// Structure to hold data type and the actual data
|
||||
typedef struct {
|
||||
DataType type;
|
||||
DataUnion data;
|
||||
} DataMessage;
|
||||
bool update_available;
|
||||
Version current_version;
|
||||
Version latest_version;
|
||||
int update_progress;
|
||||
String update_url;
|
||||
};
|
||||
336
src/main.cpp
336
src/main.cpp
@@ -1,6 +1,7 @@
|
||||
#include "SPIFFS.h"
|
||||
#include <Arduino.h>
|
||||
#include <AsyncTCP.h>
|
||||
#include <ESPAsyncWebServer.h>
|
||||
#include <ETH.h>
|
||||
#include <WiFi.h>
|
||||
#include <HTTPUpdate.h>
|
||||
@@ -12,10 +13,8 @@
|
||||
#include <ArduinoOTA.h>
|
||||
|
||||
#include "global_data/defines.h"
|
||||
#include "global_data/global_data.h"
|
||||
|
||||
#include "networking/networking.h"
|
||||
#include "networking/webserver.h"
|
||||
|
||||
#include "external_interfacing/leds.h"
|
||||
#include "sensor/sensor.h"
|
||||
@@ -23,135 +22,272 @@
|
||||
#include "tools/tools.h"
|
||||
#include <Preferences.h>
|
||||
#include "networking/json_builder.h"
|
||||
#include "networking/responses.h"
|
||||
#include <fetchOTA.h>
|
||||
#include <ESP32Ping.h>
|
||||
#include "time.h"
|
||||
#include "tools/log.h"
|
||||
#include "tools/ota_handler.h"
|
||||
#include <LittleFS.h>
|
||||
|
||||
#include "esp_heap_caps.h"
|
||||
|
||||
#define MYLOG 0
|
||||
|
||||
Preferences prefs;
|
||||
|
||||
extern AsyncWebSocket webSocket;
|
||||
extern WaterData water_data;
|
||||
extern DeviceTelemetry telemetry;
|
||||
extern NetworkData wifi_data;
|
||||
extern NetworkData ethernet_data;
|
||||
extern SensorData shunt_data;
|
||||
|
||||
extern "C" int rom_phy_get_vdd33();
|
||||
|
||||
Version current_spiffs_version;
|
||||
|
||||
// Variable to store the current state of the system
|
||||
CurrentState current_state = {
|
||||
{-999.0f, -999.0f, -999.0f},
|
||||
{-999.0f, -999.0f, -999.0f},
|
||||
{"0.0.0.0", false, -999.0f, "UNKNOWN"}, // wifiData
|
||||
{"0.0.0.0", false, -999.0f, "UNKNOWN"}, // ethernetData
|
||||
{-999.0f, -999, -999.0f},
|
||||
{false, {0, 0, 0}, {0, 0, 0}, -999, "UNKNOWN"},
|
||||
{false, false, false, false, false, false}
|
||||
};
|
||||
|
||||
AsyncWebServer server(80);
|
||||
AsyncWebSocket webSocket("/webSocket");
|
||||
#define FORMAT_LITTLEFS_IF_FAILED true
|
||||
|
||||
// Queue for sending data from producers to the processor in main
|
||||
QueueHandle_t dataQueue = xQueueCreate(5, sizeof(DataMessage));
|
||||
|
||||
// Queue for sending data from processor to different tasks
|
||||
QueueHandle_t stateForWebserverQueue = xQueueCreate(2, sizeof(CurrentState));
|
||||
|
||||
void setup()
|
||||
{
|
||||
Logger.registerSerial(MYLOG, ELOG_LEVEL_DEBUG, "Serial");
|
||||
LOG(ELOG_LEVEL_DEBUG, "Init Starting prefs and Serial output");
|
||||
{
|
||||
logger.registerSerial(MYLOG, DEBUG, "tst");
|
||||
prefs.begin("waterlevel", false);
|
||||
Serial.begin(115200);
|
||||
|
||||
LOG(DEBUG, "Init LEDs");
|
||||
pinMode(LED_1, OUTPUT);
|
||||
pinMode(LED_2, OUTPUT);
|
||||
pinMode(LED_3, OUTPUT);
|
||||
pinMode(LED_4, OUTPUT);
|
||||
pinMode(LED_5, OUTPUT);
|
||||
pinMode(LED_RED, OUTPUT);
|
||||
display_error_code(31);
|
||||
delay(500);
|
||||
LOG(ELOG_LEVEL_DEBUG, "Init Sensor");
|
||||
display_error_code(17);
|
||||
init_sensor();
|
||||
|
||||
LOG(ELOG_LEVEL_DEBUG, "Beginning LittleFS");
|
||||
LittleFS.begin(FORMAT_LITTLEFS_IF_FAILED);
|
||||
|
||||
LOG(DEBUG, "Beginning SPIFFS");
|
||||
SPIFFS.begin(true);
|
||||
|
||||
// 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);
|
||||
File file = SPIFFS.open("/version", FILE_READ);
|
||||
if (!file) {
|
||||
LOG( ELOG_LEVEL_ERROR, "Failed opening LittleFS version file");
|
||||
Serial.println("Failed to open version file for reading");
|
||||
} else {
|
||||
String version = file.readStringUntil('\n');
|
||||
LOG(DEBUG, "Version: %s", version);
|
||||
current_spiffs_version = parseVersion(version.c_str());
|
||||
LOG(ELOG_LEVEL_DEBUG, "Current LittleFS Version: %d.%d.%d", current_spiffs_version.major, current_spiffs_version.minor, current_spiffs_version.patch);
|
||||
LOG(DEBUG, "Current SPIFFS Version: %d.%d.%d", current_spiffs_version.major, current_spiffs_version.minor, current_spiffs_version.patch);
|
||||
}
|
||||
LOG(ELOG_LEVEL_DEBUG, "LittleFS initialized");
|
||||
LOG(ELOG_LEVEL_DEBUG, "Starting main tasks");
|
||||
|
||||
|
||||
if (dataQueue == NULL) {
|
||||
LOG(ELOG_LEVEL_ERROR, "Failed to create data queue");
|
||||
} else {
|
||||
xTaskCreate(ethernet_task, "EthernetTask", 1024 * 4, dataQueue, 1, NULL);
|
||||
xTaskCreate(wifi_task, "WiFiTask", 1024 * 4, dataQueue, 1, NULL);
|
||||
xTaskCreate(read_sensor_task, "ReadSensorTask", 1024 * 4, dataQueue, 1, NULL);
|
||||
xTaskCreate(collect_internal_telemetry_task, "InternalTelemetryTask", 1024 * 2, dataQueue, 1, NULL);
|
||||
xTaskCreate(display_task, "DisplayTask", 1024 * 2, NULL, 1, NULL);
|
||||
xTaskCreate(get_time_task, "GetTimeTask", 1024 * 2, NULL, 1, NULL);
|
||||
|
||||
delay(5000);
|
||||
xTaskCreate(check_update_task, "CheckUpdateTask", 1024 * 6, NULL, 1, NULL);
|
||||
xTaskCreate(webserver_task, "WebServerTask", 1024 * 4, stateForWebserverQueue, 1, NULL);
|
||||
xTaskCreate(ota_handler_task, "OTAHandlerTask", 1024 * 4, NULL, 3, NULL);
|
||||
|
||||
LOG(DEBUG, "SPIFFS initialized");
|
||||
display_error_code(19);
|
||||
|
||||
LOG(DEBUG, "Begin INA");
|
||||
|
||||
display_error_code(22);
|
||||
|
||||
/////////////////////////////// ROUTES ///////////////////////////////
|
||||
LOG(DEBUG, "Route Setup");
|
||||
|
||||
// Normal HTML stuff
|
||||
server.on("/", HTTP_GET, [](AsyncWebServerRequest* request) { request->send(SPIFFS, "/status.html", "text/html", false, processor); });
|
||||
|
||||
server.on("/settings", HTTP_GET, [](AsyncWebServerRequest* request) { request->send(SPIFFS, "/settings.html", "text/html", false, processor); });
|
||||
|
||||
server.on("/export", HTTP_GET, [](AsyncWebServerRequest* request) { request->send(SPIFFS, "/data_export.html", "text/html", false); });
|
||||
|
||||
server.on("/logic.js", HTTP_GET, [](AsyncWebServerRequest* request) { request->send(SPIFFS, "/logic.js", "application/javascript", false, processor); });
|
||||
|
||||
server.on("/update", HTTP_GET, [](AsyncWebServerRequest* request) { request->send(SPIFFS, "/update_progress.html", "text/html", false, processor); });
|
||||
|
||||
// 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(DEBUG, "Updating SSID config");
|
||||
AsyncWebParameter* ssid_param = request->getParam(ssid_key, true);
|
||||
AsyncWebParameter* password_param = request->getParam(wifi_password_key, true);
|
||||
prefs.putString(ssid_key, ssid_param->value().c_str());
|
||||
prefs.putString(wifi_password_key, password_param->value().c_str());
|
||||
|
||||
} else {
|
||||
request->send(400, "text/plain", "Missing parameters"); // TODO add proper error messages
|
||||
}
|
||||
request->send(SPIFFS, "/settings.html", "text/html", false, processor); // TODO add proper return templating
|
||||
});
|
||||
|
||||
server.on("/update_sensor_settings", HTTP_POST, [](AsyncWebServerRequest* request) {
|
||||
int params = request->params();
|
||||
|
||||
if (request->hasParam(level_sensor_range_key, true) && request->hasParam(water_level_min_key, true) && request->hasParam(water_level_max_key, true) && request->hasParam(water_volume_key, true)) {
|
||||
LOG(DEBUG, "Updating Sensor config");
|
||||
AsyncWebParameter* range_param = request->getParam(level_sensor_range_key, true);
|
||||
AsyncWebParameter* level_min_param = request->getParam(water_level_min_key, true);
|
||||
AsyncWebParameter* level_max_param = request->getParam(water_level_max_key, true);
|
||||
AsyncWebParameter* liters_param = request->getParam(water_volume_key, true);
|
||||
|
||||
String range_str = range_param->value();
|
||||
String level_min_str = level_min_param->value();
|
||||
String level_max_str = level_max_param->value();
|
||||
String liters_str = liters_param->value();
|
||||
|
||||
float range_float = range_str.toFloat();
|
||||
float level_min_float = level_min_str.toFloat();
|
||||
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(DEBUG, "range_float:%D:", range_float);
|
||||
|
||||
prefs.putFloat(level_sensor_range_key, range_float);
|
||||
prefs.putFloat(water_level_min_key, level_min_float);
|
||||
prefs.putFloat(water_level_max_key, level_max_float);
|
||||
prefs.putFloat(water_volume_key, liters_float);
|
||||
|
||||
LOG(DEBUG, "range_float_after:%D:", prefs.getFloat(level_sensor_range_key, -1.0));
|
||||
} else {
|
||||
LOG(DEBUG, "!!!! FAIL lo");
|
||||
for (int i = 0; i < params; i++) {
|
||||
AsyncWebParameter* p = request->getParam(i);
|
||||
if (p->isFile()) { // p->isPost() is also true
|
||||
LOG(DEBUG, "POST[%s]: %s\n", p->name().c_str(), p->value().c_str());
|
||||
} else if (p->isPost()) {
|
||||
LOG(DEBUG, "POST[%s]: %s\n", p->name().c_str(), p->value().c_str());
|
||||
} else {
|
||||
LOG(DEBUG, "GET[%s]: %s\n", p->name().c_str(), p->value().c_str());
|
||||
}
|
||||
}
|
||||
request->send(400, "text/plain", "Missing parameters"); // TODO add proper error messages
|
||||
}
|
||||
request->send(SPIFFS, "/settings.html", "text/html", false); // TODO add proper return templating
|
||||
});
|
||||
|
||||
setup_api_endpoints();
|
||||
display_error_code(23);
|
||||
webSocket.onEvent(onWsEvent);
|
||||
server.addHandler(&webSocket);
|
||||
|
||||
|
||||
|
||||
server.on("/chota.css", HTTP_GET, [](AsyncWebServerRequest* request) { request->send(SPIFFS, "/chota.css", "text/css", false); });
|
||||
server.on("/gauge.js", HTTP_GET, [](AsyncWebServerRequest* request) { request->send(SPIFFS, "/gauge.js", "application/javascript", false); });
|
||||
|
||||
display_error_code(24);
|
||||
|
||||
LOG(DEBUG, "OTA Setup");
|
||||
ArduinoOTA
|
||||
.onStart([]() {
|
||||
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(DEBUG, "Start updating %s", type); })
|
||||
.onEnd([]() { LOG(DEBUG, "\nEnd"); })
|
||||
.onProgress([](unsigned int progress, unsigned int total) { Serial.printf("Progress: %u%%\r", (progress / (total / 100))); })
|
||||
.onError([](ota_error_t error) {
|
||||
Serial.printf("Error[%u]: ", error);
|
||||
if (error == OTA_AUTH_ERROR) LOG(DEBUG, "Auth Failed");
|
||||
else if (error == OTA_BEGIN_ERROR) LOG(DEBUG, "Begin Failed");
|
||||
else if (error == OTA_CONNECT_ERROR) LOG(DEBUG, "Connect Failed");
|
||||
else if (error == OTA_RECEIVE_ERROR) LOG(DEBUG, "Receive Failed");
|
||||
else if (error == OTA_END_ERROR) LOG(DEBUG, "End Failed"); });
|
||||
|
||||
display_error_code(26);
|
||||
digitalWrite(LED_RED, 0);
|
||||
|
||||
// Starting bootup sequence
|
||||
|
||||
xTaskCreate(ethernet_task, "EthernetTask", 4096, NULL, 1, NULL);
|
||||
|
||||
// Create Etnernet task and wait a second to see if there is connection
|
||||
LOG(DEBUG, "Started Ethernet, waiting");
|
||||
delay(2000);
|
||||
|
||||
if (ETH.linkUp()){
|
||||
LOG(DEBUG, "Ethernet connected, starting update checker");
|
||||
xTaskCreate(check_update_task, "CheckUpdateTask", 1024 * 8, NULL, 1, NULL);
|
||||
} else {
|
||||
LOG(DEBUG, "Ethernet not connected, starting update checker and WiFi Task");
|
||||
xTaskCreate(wifi_task, "WiFiTask", 10000, NULL, 1, NULL);
|
||||
xTaskCreate(check_update_task, "CheckUpdateTask", 1024 * 8, NULL, 1, NULL);
|
||||
delay(2000);
|
||||
}
|
||||
|
||||
LOG(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(DEBUG, "Time not set properly: ");
|
||||
} else {
|
||||
LOG(DEBUG, "Time is valid: %s", asctime(&timeinfo));
|
||||
}
|
||||
|
||||
// Setup syslog
|
||||
logger.configureSyslog("192.168.6.11", 5514, "esp32");
|
||||
logger.registerSyslog(MYLOG, DEBUG, FAC_USER, "waterlevel");
|
||||
LOG(ERROR, "Here is an error message, error code: %d", 17);
|
||||
|
||||
|
||||
|
||||
|
||||
LOG(DEBUG, "Starting webserver");
|
||||
server.begin();
|
||||
ArduinoOTA.begin();
|
||||
display_error_code(25);
|
||||
|
||||
xTaskCreate(display_task, "DisplayTask", 10000, NULL, 1, NULL);
|
||||
xTaskCreate(read_sensor_task, "ReadSensorTask", 1024 * 4, NULL, 1, NULL);
|
||||
xTaskCreate(collect_internal_telemetry_task, "InternalTelemetryTask", 2048, NULL, 1, NULL);
|
||||
|
||||
// Wait until there is network connection
|
||||
while (true) {
|
||||
if (WiFi.status() == WL_CONNECTED || ETH.localIP()) {
|
||||
int pingResult = Ping.ping("8.8.8.8"); // Use Google's public DNS server as a test IP
|
||||
if (pingResult >= 0) {
|
||||
LOG(DEBUG, "Network connection established");
|
||||
break;
|
||||
} else {
|
||||
LOG(DEBUG, "Network not ready, retrying...");
|
||||
}
|
||||
} else {
|
||||
LOG(DEBUG, "No WiFi or Ethernet connection, retrying...");
|
||||
}
|
||||
delay(1000); // Delay to prevent rapid retry
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
void loop()
|
||||
{
|
||||
size_t free_heap = heap_caps_get_free_size(MALLOC_CAP_8BIT);
|
||||
Serial.println(free_heap);
|
||||
|
||||
// Check if there is new data in the queue
|
||||
DataMessage dataMessage;
|
||||
if (xQueueReceive(dataQueue, &dataMessage, portMAX_DELAY) == pdTRUE) {
|
||||
// Decode the data based on its type and update the current state
|
||||
switch (dataMessage.type) {
|
||||
case DATA_TYPE_WATER:
|
||||
current_state.waterData = dataMessage.data.waterData;
|
||||
LOG(ELOG_LEVEL_DEBUG, "Received water data: level=%F, liters=%F, percentage=%F",
|
||||
current_state.waterData.level, current_state.waterData.liters, current_state.waterData.percentage);
|
||||
break;
|
||||
case DATA_TYPE_SENSOR:
|
||||
current_state.sensorData = dataMessage.data.sensorData;
|
||||
LOG(ELOG_LEVEL_DEBUG, "Received sensor data: bus_voltage=%F, shunt_voltage=%F, shunt_current=%F",
|
||||
current_state.sensorData.bus_voltage, current_state.sensorData.shunt_voltage, current_state.sensorData.shunt_current);
|
||||
break;
|
||||
case DATA_TYPE_WIFI:
|
||||
current_state.wifiData = dataMessage.data.networkData;
|
||||
LOG(ELOG_LEVEL_DEBUG, "Received WiFi data: ip=%s, link=%d, rssi=%F, name=%s",
|
||||
current_state.wifiData.ip_address, current_state.wifiData.link,
|
||||
current_state.wifiData.rssi, current_state.wifiData.network_name);
|
||||
break;
|
||||
case DATA_TYPE_ETHERNET:
|
||||
current_state.ethernetData = dataMessage.data.networkData;
|
||||
LOG(ELOG_LEVEL_DEBUG, "Received Ethernet data: ip=%s, link=%d, rssi=%F, name=%s",
|
||||
current_state.ethernetData.ip_address, current_state.ethernetData.link,
|
||||
current_state.ethernetData.rssi, current_state.ethernetData.network_name);
|
||||
break;
|
||||
case DATA_TYPE_TELEMETRY:
|
||||
current_state.telemetryData = dataMessage.data.telemetryData;
|
||||
LOG(ELOG_LEVEL_DEBUG, "Received telemetry data: heap=%F, uptime=%d, temperature=%F",
|
||||
current_state.telemetryData.heap_used_percent, current_state.telemetryData.uptime_seconds,
|
||||
current_state.telemetryData.temperature);
|
||||
break;
|
||||
default:
|
||||
LOG(ELOG_LEVEL_ERROR, "Unknown data type received");
|
||||
break;
|
||||
}
|
||||
// Send the updated current_state to the webserver queue
|
||||
if (xQueueSendToBack(stateForWebserverQueue, ¤t_state, 250 / portTICK_PERIOD_MS) != pdTRUE) {
|
||||
LOG(ELOG_LEVEL_ERROR, "Failed to send current_state to webserver queue");
|
||||
}
|
||||
} else {
|
||||
LOG(ELOG_LEVEL_WARNING, "No message received within max wait");
|
||||
}
|
||||
|
||||
ArduinoOTA.handle();
|
||||
delay(1000);
|
||||
}
|
||||
@@ -1,34 +1,37 @@
|
||||
#include "json_builder.h"
|
||||
#include <Elog.h>
|
||||
|
||||
// Refactored: no return by value, serialize directly to output String
|
||||
// Reduced document sizes based on actual JSON output requirements
|
||||
void build_shunt_data_json(SensorData data, String& output) {
|
||||
StaticJsonDocument<96> doc; // Reduced from 128: 3 floats ~70-80 bytes
|
||||
extern WaterData water_data;
|
||||
extern DeviceTelemetry telemetry;
|
||||
extern NetworkData wifi_data;
|
||||
extern NetworkData ethernet_data;
|
||||
extern SensorData shunt_data;
|
||||
|
||||
StaticJsonDocument<128> build_shunt_data_json(SensorData data) {
|
||||
StaticJsonDocument<128> doc;
|
||||
doc["bus_voltage"] = data.bus_voltage;
|
||||
doc["shunt_voltage"] = data.shunt_voltage;
|
||||
doc["current"] = data.shunt_current;
|
||||
serializeJson(doc, output);
|
||||
return doc;
|
||||
}
|
||||
|
||||
void build_water_data_json(WaterData data, String& output) {
|
||||
StaticJsonDocument<96> doc; // Reduced from 128: 3 floats ~70-80 bytes
|
||||
StaticJsonDocument<128> build_water_data_json(WaterData data) {
|
||||
StaticJsonDocument<128> doc;
|
||||
doc["percentage"] = data.percentage;
|
||||
doc["water_height"] = data.level;
|
||||
doc["liters"] = data.liters;
|
||||
serializeJson(doc, output);
|
||||
return doc;
|
||||
}
|
||||
|
||||
void build_telemetry_json(DeviceTelemetry data, String& output) {
|
||||
StaticJsonDocument<96> doc; // Reduced from 128: 1 int + 2 floats ~70-80 bytes
|
||||
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;
|
||||
serializeJson(doc, output);
|
||||
return doc;
|
||||
}
|
||||
|
||||
void build_network_json(NetworkData wired, NetworkData wireless, String& output) {
|
||||
StaticJsonDocument<256> doc; // Keep 256: nested objects + strings ~200 bytes
|
||||
StaticJsonDocument<256> build_network_json(NetworkData wired, NetworkData wireless) {
|
||||
StaticJsonDocument<256> doc;
|
||||
doc["wifi"]["ip"] = wireless.ip_address;
|
||||
doc["wifi"]["rssi"] = wireless.rssi;
|
||||
doc["wifi"]["link"] = wireless.link;
|
||||
@@ -38,15 +41,15 @@ void build_network_json(NetworkData wired, NetworkData wireless, String& output)
|
||||
doc["ethernet"]["rssi"] = wired.rssi;
|
||||
doc["ethernet"]["link"] = wired.link;
|
||||
|
||||
serializeJson(doc, output);
|
||||
return doc;
|
||||
}
|
||||
|
||||
void build_ota_json(OTAStatus status, String& output) {
|
||||
StaticJsonDocument<192> doc; // Reduced from 256: bool + 2 version strings + int ~150-170 bytes
|
||||
StaticJsonDocument<128> build_ota_json(OTAStatus status) {
|
||||
StaticJsonDocument<256> doc;
|
||||
doc["update_available"] = status.update_available;
|
||||
doc["current_version"] = String(status.current_version.major) + "." + String(status.current_version.minor) + "." + String(status.current_version.patch);
|
||||
doc["new_version"] = String(status.latest_version.major) + "." + String(status.latest_version.minor) + "." + String(status.latest_version.patch);
|
||||
doc["progress"] = status.update_progress;
|
||||
|
||||
serializeJson(doc, output);
|
||||
}
|
||||
return doc;
|
||||
}
|
||||
@@ -1,9 +1,8 @@
|
||||
#include <ArduinoJson.h>
|
||||
#include "../global_data/global_data.h"
|
||||
|
||||
// Refactored to pass by reference - no expensive copies on stack
|
||||
void build_shunt_data_json(SensorData data, String& output);
|
||||
void build_water_data_json(WaterData data, String& output);
|
||||
void build_telemetry_json(DeviceTelemetry data, String& output);
|
||||
void build_network_json(NetworkData wired, NetworkData wireless, String& output);
|
||||
void build_ota_json(OTAStatus status, String& output);
|
||||
StaticJsonDocument<128> build_shunt_data_json(SensorData data);
|
||||
StaticJsonDocument<128> build_water_data_json(WaterData data);
|
||||
StaticJsonDocument<128> build_telemetry_json(DeviceTelemetry data);
|
||||
StaticJsonDocument<256> build_network_json(NetworkData wired, NetworkData wireless);
|
||||
StaticJsonDocument<128> build_ota_json(OTAStatus status);
|
||||
@@ -1,30 +1,18 @@
|
||||
#include <Elog.h>
|
||||
#include <ETH.h>
|
||||
#include <WiFi.h>
|
||||
#include "../global_data/defines.h"
|
||||
#include <Preferences.h>
|
||||
#include "../global_data/global_data.h"
|
||||
#include <tools/log.h>
|
||||
#include "freertos/queue.h"
|
||||
|
||||
#define ETH_PHY_TYPE ETH_PHY_LAN8720
|
||||
#define ETH_PHY_ADDR 0
|
||||
#define ETH_PHY_MDC 23
|
||||
#define ETH_PHY_MDIO 18
|
||||
#define ETH_PHY_POWER 14
|
||||
#define ETH_CLK_MODE ETH_CLOCK_GPIO0_IN
|
||||
|
||||
|
||||
#include <ETH.h>
|
||||
|
||||
int64_t mac_address = ESP.getEfuseMac();
|
||||
uint8_t failed_connection_attempts = 0;
|
||||
|
||||
NetworkData wifi_data;
|
||||
NetworkData ethernet_data;
|
||||
|
||||
extern NetworkData wifi_data;
|
||||
extern NetworkData ethernet_data;
|
||||
extern Preferences prefs;
|
||||
|
||||
// Defines the type of connection for which the hostname should be created
|
||||
enum HostnameType {
|
||||
Wireless,
|
||||
Ethernet,
|
||||
@@ -40,36 +28,28 @@ const char * get_hostname(HostnameType host_type) {
|
||||
return (hostname + "-wl").c_str();
|
||||
case Ethernet:
|
||||
return (hostname + "-eth").c_str();
|
||||
default:
|
||||
case Generic:
|
||||
return hostname.c_str();
|
||||
}
|
||||
}
|
||||
|
||||
void wifi_task(void* parameter)
|
||||
{
|
||||
// Extract the queue handle from the task parameters
|
||||
QueueHandle_t dataQueue = (QueueHandle_t)parameter;
|
||||
if (dataQueue == NULL) {
|
||||
LOG(ELOG_LEVEL_ERROR, "Data queue is NULL");
|
||||
vTaskDelete(NULL);
|
||||
return;
|
||||
}
|
||||
|
||||
LOG(ELOG_LEVEL_DEBUG, "Starting WiFi Task");
|
||||
LOG(DEBUG, "Starting WiFi Task");
|
||||
WiFi.setHostname(get_hostname(Wireless));
|
||||
while (true) {
|
||||
if (prefs.getString(ssid_key, "") == "" || failed_connection_attempts > 5) {
|
||||
wifi_data.link = false;
|
||||
if (failed_connection_attempts > 5) {
|
||||
LOG(ELOG_LEVEL_WARNING, "Failed to connect to currently saved SSID, starting SoftAP");
|
||||
LOG(DEBUG, "Failed to connecto to currently saved SSID, starting SoftAP");
|
||||
} else {
|
||||
LOG(ELOG_LEVEL_WARNING, "No SSID saved, starting SoftAP");
|
||||
LOG(DEBUG, "No SSID saved, starting SoftAP");
|
||||
}
|
||||
|
||||
String ap_ssid = get_hostname(Wireless);
|
||||
WiFi.softAP(ap_ssid.c_str(), "");
|
||||
WiFi.softAP(ap_ssid, "");
|
||||
|
||||
LOG(ELOG_LEVEL_DEBUG, "Waiting for SSID now...");
|
||||
LOG(DEBUG, "[WIFI_TASK] Waiting for SSID now...");
|
||||
|
||||
String old_ssid = prefs.getString(ssid_key, "xxx");
|
||||
while (prefs.getString(ssid_key, "") == "" || prefs.getString(ssid_key, "") == old_ssid) {
|
||||
@@ -82,31 +62,17 @@ void wifi_task(void* parameter)
|
||||
failed_connection_attempts = 0;
|
||||
wifi_data.rssi = WiFi.RSSI();
|
||||
wifi_data.link = true;
|
||||
strncpy(wifi_data.network_name, WiFi.SSID().c_str(), sizeof(wifi_data.network_name) - 1);
|
||||
wifi_data.network_name[sizeof(wifi_data.network_name) - 1] = '\0';
|
||||
strncpy(wifi_data.ip_address, WiFi.localIP().toString().c_str(), sizeof(wifi_data.ip_address) - 1);
|
||||
wifi_data.ip_address[sizeof(wifi_data.ip_address) - 1] = '\0';
|
||||
|
||||
// Create a DataMessage for WiFi data
|
||||
DataMessage dataMessage;
|
||||
dataMessage.type = DATA_TYPE_WIFI;
|
||||
dataMessage.data.networkData = wifi_data;
|
||||
|
||||
// Send the WiFi data to the queue
|
||||
if (xQueueSend(dataQueue, &dataMessage, 0) != pdTRUE) {
|
||||
LOG(ELOG_LEVEL_ERROR, "Failed to send WiFi data to queue");
|
||||
}
|
||||
|
||||
LOG(ELOG_LEVEL_DEBUG, "WIFI connected; RSSI: %F, IP Address, %s, SSID: %s", float(WiFi.RSSI()), WiFi.localIP().toString(), prefs.getString(ssid_key, "NOSSID"));
|
||||
delay(1000 * 60);
|
||||
wifi_data.network_name = WiFi.SSID();
|
||||
wifi_data.ip_address = WiFi.localIP().toString();
|
||||
|
||||
LOG(DEBUG, "RSSI: %F, IP Address, %p, SSID: %s", float(WiFi.RSSI()), WiFi.localIP(), prefs.getString(ssid_key, "NOSSID"));
|
||||
Serial.println(WiFi.channel());
|
||||
delay(5000);
|
||||
} else {
|
||||
String ssid = prefs.getString(ssid_key, "");
|
||||
String password = prefs.getString(wifi_password_key, "");
|
||||
LOG(ELOG_LEVEL_DEBUG, "Connecting to %s...", ssid);
|
||||
LOG(DEBUG, "Connecting to %s using password %s", prefs.getString(ssid_key, ""), prefs.getString(wifi_password_key, ""));
|
||||
WiFi.mode(WIFI_STA);
|
||||
WiFi.begin(ssid, password);
|
||||
WiFi.begin(prefs.getString(ssid_key, ""), prefs.getString(wifi_password_key, ""));
|
||||
failed_connection_attempts++;
|
||||
LOG(ELOG_LEVEL_WARNING, "Failed to connect, retrying...");
|
||||
delay(5000);
|
||||
}
|
||||
}
|
||||
@@ -115,40 +81,15 @@ void wifi_task(void* parameter)
|
||||
|
||||
void ethernet_task(void* parameter)
|
||||
{
|
||||
// Extract the queue handle from the task parameters
|
||||
QueueHandle_t dataQueue = (QueueHandle_t)parameter;
|
||||
if (dataQueue == NULL) {
|
||||
LOG(ELOG_LEVEL_ERROR, "Data queue is NULL");
|
||||
vTaskDelete(NULL);
|
||||
return;
|
||||
}
|
||||
|
||||
LOG(ELOG_LEVEL_DEBUG, "Starting Ethernet Task");
|
||||
ETH.begin();
|
||||
LOG(DEBUG, "Connecting Ethernet");
|
||||
ETH.begin(0, 17, 23, 18);
|
||||
ETH.setHostname(get_hostname(Ethernet));
|
||||
while (true) {
|
||||
ethernet_data.link = ETH.linkUp();
|
||||
ethernet_data.rssi = ETH.linkSpeed();
|
||||
strncpy(ethernet_data.ip_address, ETH.localIP().toString().c_str(), sizeof(ethernet_data.ip_address) - 1);
|
||||
ethernet_data.ip_address[sizeof(ethernet_data.ip_address) - 1] = '\0';
|
||||
|
||||
// Create a DataMessage for Ethernet data
|
||||
DataMessage dataMessage;
|
||||
dataMessage.type = DATA_TYPE_ETHERNET;
|
||||
dataMessage.data.networkData = ethernet_data;
|
||||
|
||||
// Send the Ethernet data to the queue
|
||||
if (xQueueSend(dataQueue, &dataMessage, 0) != pdTRUE) {
|
||||
LOG(ELOG_LEVEL_ERROR, "Failed to send Ethernet data to queue");
|
||||
}
|
||||
|
||||
LOG(ELOG_LEVEL_DEBUG, "Ethernet RSSI: %F, IP Address, %s, LINK: %s", float(ethernet_data.rssi), ETH.localIP().toString(), String(ethernet_data.link));
|
||||
|
||||
if (ETH.linkUp() && !ETH.isDefault() && ETH.localIP().toString() != "0.0.0.0") {
|
||||
LOG(ELOG_LEVEL_DEBUG, "Ethernet is up, setting to default");
|
||||
ETH.setDefault();
|
||||
}
|
||||
|
||||
ethernet_data.ip_address = ETH.localIP().toString();
|
||||
Serial.println( ETH.localIP().toString());
|
||||
LOG(DEBUG, "Ethernet RSSI: %F, IP Address, %s, LINK: %s", float(ethernet_data.rssi), ETH.localIP().toString().c_str(), String(ethernet_data.link));
|
||||
delay(60 * 1000);
|
||||
}
|
||||
}
|
||||
76
src/networking/responses.cpp
Normal file
76
src/networking/responses.cpp
Normal file
@@ -0,0 +1,76 @@
|
||||
#include "responses.h"
|
||||
|
||||
#include <Arduino.h>
|
||||
#include <ESPAsyncWebServer.h>
|
||||
#include "AsyncJson.h"
|
||||
#include <ArduinoJson.h>
|
||||
#include <Elog.h>
|
||||
#include "json_builder.h"
|
||||
#include "../tools/tools.h"
|
||||
#include <SPIFFS.h>
|
||||
|
||||
extern WaterData water_data;
|
||||
extern DeviceTelemetry telemetry;
|
||||
extern NetworkData wifi_data;
|
||||
extern NetworkData ethernet_data;
|
||||
extern SensorData shunt_data;
|
||||
extern OTAStatus ota_status;
|
||||
|
||||
extern AsyncWebServer server;
|
||||
|
||||
void setup_api_endpoints(){
|
||||
server.on("/sensor_data", HTTP_GET, [](AsyncWebServerRequest* request) {
|
||||
String output;
|
||||
serializeJson(build_shunt_data_json(shunt_data), output);
|
||||
request->send(200, "application/json", output); });
|
||||
|
||||
server.on("/water_data", HTTP_GET, [](AsyncWebServerRequest* request) {
|
||||
String output;
|
||||
serializeJson(build_water_data_json(water_data), output);
|
||||
request->send(200, "application/json", output); });
|
||||
|
||||
server.on("/raw_percent", HTTP_GET, [](AsyncWebServerRequest* request) {
|
||||
String output;
|
||||
output = water_data.percentage;
|
||||
request->send(200, "text/raw", output); });
|
||||
|
||||
server.on("/raw_level", HTTP_GET, [](AsyncWebServerRequest* request) {
|
||||
String output;
|
||||
output = water_data.level;
|
||||
request->send(200, "text/raw", output); });
|
||||
|
||||
|
||||
server.on("/telemetry", HTTP_GET, [](AsyncWebServerRequest* request) {
|
||||
String output;
|
||||
serializeJson(build_telemetry_json(telemetry), output);
|
||||
request->send(200, "application/json", output); });
|
||||
|
||||
server.on("/network_info", HTTP_GET, [](AsyncWebServerRequest* request) {
|
||||
String output;
|
||||
serializeJson(build_network_json(ethernet_data, wifi_data), output);
|
||||
request->send(200, "application/json", output);
|
||||
});
|
||||
|
||||
server.on("/ota_udpate_status", HTTP_GET, [](AsyncWebServerRequest* request) {
|
||||
String output;
|
||||
serializeJson(build_ota_json(ota_status), output);
|
||||
request->send(200, "application/json", output);
|
||||
});
|
||||
|
||||
server.on("/run_ota_update", HTTP_GET, [](AsyncWebServerRequest* request) {
|
||||
if (ota_status.update_progress > -1) {
|
||||
request->send(200, "text/plain", "OTA Update already in progress");
|
||||
return;
|
||||
} else if (!ota_status.update_available) {
|
||||
request->send(200, "text/plain", "No update available");
|
||||
return;
|
||||
}
|
||||
|
||||
static TaskArgs_t args = {
|
||||
.ota_status = ota_status
|
||||
};
|
||||
|
||||
xTaskCreate(run_ota_update_task, "RunOTAUpdate", 1024 * 8, (void *)&args, 1, NULL);
|
||||
request->send(SPIFFS, "/update_progress.html", "text/html", false, processor);
|
||||
});
|
||||
}
|
||||
3
src/networking/responses.h
Normal file
3
src/networking/responses.h
Normal file
@@ -0,0 +1,3 @@
|
||||
#include <ESPAsyncWebServer.h>
|
||||
|
||||
void setup_api_endpoints();
|
||||
@@ -1,371 +0,0 @@
|
||||
#include "webserver.h"
|
||||
|
||||
#include <Arduino.h>
|
||||
#include <ESPAsyncWebServer.h>
|
||||
#include <LittleFS.h>
|
||||
#include <Elog.h>
|
||||
#include <AsyncTCP.h>
|
||||
#include <Preferences.h>
|
||||
#include "tools/log.h"
|
||||
#include "AsyncJson.h"
|
||||
#include <ArduinoJson.h>
|
||||
#include <SPIFFS.h>
|
||||
#include <freertos/FreeRTOS.h>
|
||||
#include <freertos/semphr.h>
|
||||
#include <freertos/queue.h>
|
||||
|
||||
#include "../global_data/global_data.h"
|
||||
#include "../tools/tools.h"
|
||||
#include "../tools/readers_writer_lock.h"
|
||||
#include "../global_data/defines.h"
|
||||
#include "json_builder.h"
|
||||
|
||||
extern Preferences prefs;
|
||||
|
||||
AsyncWebSocket webSocket("/webSocket");
|
||||
AsyncWebServer server(80);
|
||||
|
||||
|
||||
WaterData local_water_data;
|
||||
SensorData local_sensor_data;
|
||||
NetworkData local_wifi_data;
|
||||
NetworkData local_ethernet_data;
|
||||
DeviceTelemetry local_telemetry;
|
||||
OTAStatus local_ota_status;
|
||||
|
||||
|
||||
ReadersWriterLock waterDataLock;
|
||||
ReadersWriterLock sensorDataLock;
|
||||
ReadersWriterLock networkDataLock;
|
||||
ReadersWriterLock telemetryDataLock;
|
||||
ReadersWriterLock otaStatusLock;
|
||||
|
||||
|
||||
// ======================
|
||||
// Webserver Setup
|
||||
// ======================
|
||||
|
||||
/**
|
||||
* @brief Sets up all routes for the webserver.
|
||||
*
|
||||
* Configures routes for serving HTML pages, handling form submissions,
|
||||
* REST API endpoints, WebSocket connections, and static assets.
|
||||
*
|
||||
* @note Calls setup_api_endpoints() to configure API-specific routes.
|
||||
*/
|
||||
void setup_routes() {
|
||||
server.on("/", HTTP_GET, [](AsyncWebServerRequest* request) { request->send(LittleFS, "/status.html", "text/html", false, processor); });
|
||||
|
||||
server.on("/settings", HTTP_GET, [](AsyncWebServerRequest* request) { request->send(LittleFS, "/settings.html", "text/html", false, processor); });
|
||||
|
||||
server.on("/export", HTTP_GET, [](AsyncWebServerRequest* request) { request->send(LittleFS, "/data_export.html", "text/html", false); });
|
||||
|
||||
server.on("/logic.js", HTTP_GET, [](AsyncWebServerRequest* request) { request->send(LittleFS, "/logic.js", "application/javascript", false, processor); });
|
||||
|
||||
server.on("/update", HTTP_GET, [](AsyncWebServerRequest* request) { request->send(LittleFS, "/update_progress.html", "text/html", false, processor); });
|
||||
|
||||
// API stuff - internal
|
||||
server.on("/update_wifi_credentials", HTTP_POST, [](AsyncWebServerRequest* request) {
|
||||
handle_update_wifi_credentials(request);
|
||||
});
|
||||
|
||||
server.on("/update_sensor_settings", HTTP_POST, [](AsyncWebServerRequest* request) {
|
||||
handle_update_sensor_settings(request);
|
||||
});
|
||||
|
||||
setup_api_endpoints();
|
||||
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); });
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Configures REST API endpoints for data retrieval.
|
||||
*
|
||||
* Sets up endpoints to fetch sensor data, water data, telemetry,
|
||||
* network information, and OTA update status in JSON format.
|
||||
*
|
||||
* @note These endpoints are used by the frontend to dynamically
|
||||
* display device status and configuration.
|
||||
*/
|
||||
void setup_api_endpoints(){
|
||||
server.on("/sensor_data", HTTP_GET, [](AsyncWebServerRequest* request) {
|
||||
rwLockAcquireRead(&sensorDataLock);
|
||||
String output;
|
||||
build_shunt_data_json(local_sensor_data, output);
|
||||
rwLockReleaseRead(&sensorDataLock);
|
||||
request->send(200, "application/json", output); });
|
||||
|
||||
server.on("/water_data", HTTP_GET, [](AsyncWebServerRequest* request) {
|
||||
rwLockAcquireRead(&waterDataLock);
|
||||
String output;
|
||||
build_water_data_json(local_water_data, output);
|
||||
rwLockReleaseRead(&waterDataLock);
|
||||
request->send(200, "application/json", output);
|
||||
});
|
||||
|
||||
server.on("/raw_percent", HTTP_GET, [](AsyncWebServerRequest* request) {
|
||||
rwLockAcquireRead(&waterDataLock);
|
||||
String output = String(local_water_data.percentage);
|
||||
rwLockReleaseRead(&waterDataLock);
|
||||
request->send(200, "text/raw", output);
|
||||
});
|
||||
|
||||
server.on("/raw_level", HTTP_GET, [](AsyncWebServerRequest* request) {
|
||||
rwLockAcquireRead(&waterDataLock);
|
||||
String output = String(local_water_data.level);
|
||||
rwLockReleaseRead(&waterDataLock);
|
||||
request->send(200, "text/raw", output);
|
||||
});
|
||||
|
||||
server.on("/telemetry", HTTP_GET, [](AsyncWebServerRequest* request) {
|
||||
rwLockAcquireRead(&telemetryDataLock);
|
||||
String output;
|
||||
build_telemetry_json(local_telemetry, output);
|
||||
rwLockReleaseRead(&telemetryDataLock);
|
||||
request->send(200, "application/json", output); });
|
||||
|
||||
server.on("/network_info", HTTP_GET, [](AsyncWebServerRequest* request) {
|
||||
rwLockAcquireRead(&networkDataLock);
|
||||
String output;
|
||||
build_network_json(local_ethernet_data, local_wifi_data, output);
|
||||
rwLockReleaseRead(&networkDataLock);
|
||||
request->send(200, "application/json", output);
|
||||
});
|
||||
|
||||
server.on("/ota_update_status", HTTP_GET, [](AsyncWebServerRequest* request) {
|
||||
rwLockAcquireRead(&otaStatusLock);
|
||||
String output;
|
||||
build_ota_json(local_ota_status, output);
|
||||
rwLockReleaseRead(&otaStatusLock);
|
||||
request->send(200, "application/json", output); });
|
||||
|
||||
server.on("/run_ota_update", HTTP_GET, [](AsyncWebServerRequest* request) {
|
||||
if (local_ota_status.update_progress > -1) {
|
||||
request->send(200, "text/plain", "OTA Update already in progress");
|
||||
return;
|
||||
} else if (!local_ota_status.update_available) {
|
||||
request->send(200, "text/plain", "No update available");
|
||||
return;
|
||||
}
|
||||
|
||||
static TaskArgs_t args = {
|
||||
.ota_status = local_ota_status
|
||||
};
|
||||
|
||||
xTaskCreate(run_ota_update_task, "RunOTAUpdate", 1024 * 8, (void *)&args, 1, NULL);
|
||||
request->send(LittleFS, "/update_progress.html", "text/html", false, processor);
|
||||
});
|
||||
}
|
||||
|
||||
// ======================
|
||||
// Helper Functions
|
||||
// ======================
|
||||
|
||||
/**
|
||||
* @brief Handles the update of WiFi credentials.
|
||||
*
|
||||
* Validates and updates the SSID and password in preferences.
|
||||
*
|
||||
* @param request The web server request object.
|
||||
*/
|
||||
void handle_update_wifi_credentials(AsyncWebServerRequest* request) {
|
||||
if (request->hasParam(ssid_key, true) && request->hasParam(wifi_password_key, true)) {
|
||||
LOG(ELOG_LEVEL_DEBUG, "Updating SSID config");
|
||||
const AsyncWebParameter* ssid_param = request->getParam(ssid_key, true);
|
||||
const AsyncWebParameter* password_param = request->getParam(wifi_password_key, true);
|
||||
prefs.putString(ssid_key, ssid_param->value().c_str());
|
||||
prefs.putString(wifi_password_key, password_param->value().c_str());
|
||||
} else {
|
||||
request->send(400, "text/plain", "Missing parameters");
|
||||
return;
|
||||
}
|
||||
request->send(LittleFS, "/settings.html", "text/html", false, processor);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Handles the update of sensor settings.
|
||||
*
|
||||
* Validates and updates sensor configuration parameters in preferences.
|
||||
*
|
||||
* @param request The web server request object.
|
||||
*/
|
||||
void handle_update_sensor_settings(AsyncWebServerRequest* request) {
|
||||
int params = request->params();
|
||||
|
||||
if (request->hasParam(level_sensor_range_key, true) && request->hasParam(water_level_min_key, true) &&
|
||||
request->hasParam(water_level_max_key, true) && request->hasParam(water_volume_key, true)) {
|
||||
LOG(ELOG_LEVEL_DEBUG, "Updating Sensor config");
|
||||
const AsyncWebParameter* range_param = request->getParam(level_sensor_range_key, true);
|
||||
const AsyncWebParameter* level_min_param = request->getParam(water_level_min_key, true);
|
||||
const AsyncWebParameter* level_max_param = request->getParam(water_level_max_key, true);
|
||||
const AsyncWebParameter* liters_param = request->getParam(water_volume_key, true);
|
||||
|
||||
String range_str = range_param->value();
|
||||
String level_min_str = level_min_param->value();
|
||||
String level_max_str = level_max_param->value();
|
||||
String liters_str = liters_param->value();
|
||||
|
||||
float range_float = range_str.toFloat();
|
||||
float level_min_float = level_min_str.toFloat();
|
||||
float level_max_float = level_max_str.toFloat();
|
||||
float liters_float = liters_str.toFloat();
|
||||
|
||||
LOG(ELOG_LEVEL_DEBUG, "range_float:%D:", range_float);
|
||||
|
||||
prefs.putFloat(level_sensor_range_key, range_float);
|
||||
prefs.putFloat(water_level_min_key, level_min_float);
|
||||
prefs.putFloat(water_level_max_key, level_max_float);
|
||||
prefs.putFloat(water_volume_key, liters_float);
|
||||
|
||||
LOG(ELOG_LEVEL_DEBUG, "range_float_after:%D:", prefs.getFloat(level_sensor_range_key, -1.0));
|
||||
} else {
|
||||
LOG(ELOG_LEVEL_DEBUG, "!!!! FAIL lo");
|
||||
for (int i = 0; i < params; i++) {
|
||||
const AsyncWebParameter* p = request->getParam(i);
|
||||
if (p->isFile()) {
|
||||
LOG(ELOG_LEVEL_DEBUG, "POST[%s]: %s\n", p->name().c_str(), p->value().c_str());
|
||||
} else if (p->isPost()) {
|
||||
LOG(ELOG_LEVEL_DEBUG, "POST[%s]: %s\n", p->name().c_str(), p->value().c_str());
|
||||
} else {
|
||||
LOG(ELOG_LEVEL_DEBUG, "GET[%s]: %s\n", p->name().c_str(), p->value().c_str());
|
||||
}
|
||||
}
|
||||
request->send(400, "text/plain", "Missing parameters");
|
||||
return;
|
||||
}
|
||||
request->send(LittleFS, "/settings.html", "text/html", false);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Main task for the webserver.
|
||||
*
|
||||
* Initializes all routes, starts the webserver, and sets up local water data.
|
||||
* Receives the current state from the main task via a queue and updates local_water_data.
|
||||
* Runs indefinitely to keep the server active.
|
||||
*
|
||||
* @param pvParameters Task parameters (expected to be a QueueHandle_t for the state queue).
|
||||
*/
|
||||
void webserver_task(void *pvParameters) {
|
||||
// Extract the queue handle from the task parameters
|
||||
QueueHandle_t stateQueue = (QueueHandle_t)pvParameters;
|
||||
if (stateQueue == NULL) {
|
||||
LOG(ELOG_LEVEL_ERROR, "State queue is NULL");
|
||||
vTaskDelete(NULL);
|
||||
return;
|
||||
}
|
||||
|
||||
LOG(ELOG_LEVEL_DEBUG, "Setting up routes");
|
||||
setup_routes();
|
||||
|
||||
// Initialize the readers-writer locks
|
||||
if (!rwLockInit(&waterDataLock)) {
|
||||
LOG(ELOG_LEVEL_ERROR, "Failed to initialize water data readers-writer lock");
|
||||
vTaskDelete(NULL);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!rwLockInit(&sensorDataLock)) {
|
||||
LOG(ELOG_LEVEL_ERROR, "Failed to initialize sensor data readers-writer lock");
|
||||
vTaskDelete(NULL);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!rwLockInit(&networkDataLock)) {
|
||||
LOG(ELOG_LEVEL_ERROR, "Failed to initialize network data readers-writer lock");
|
||||
vTaskDelete(NULL);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!rwLockInit(&telemetryDataLock)) {
|
||||
LOG(ELOG_LEVEL_ERROR, "Failed to initialize telemetry data readers-writer lock");
|
||||
vTaskDelete(NULL);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!rwLockInit(&otaStatusLock)) {
|
||||
LOG(ELOG_LEVEL_ERROR, "Failed to initialize OTA status readers-writer lock");
|
||||
vTaskDelete(NULL);
|
||||
return;
|
||||
}
|
||||
|
||||
// Initialize local water data with static values
|
||||
rwLockAcquireWrite(&waterDataLock);
|
||||
local_water_data.level = -1.0;
|
||||
local_water_data.liters = -1.0;
|
||||
local_water_data.percentage = -1.0;
|
||||
rwLockReleaseWrite(&waterDataLock);
|
||||
|
||||
// Initialize local sensor data with static values
|
||||
rwLockAcquireWrite(&sensorDataLock);
|
||||
local_sensor_data.bus_voltage = -1.0;
|
||||
local_sensor_data.shunt_voltage = -1.0;
|
||||
local_sensor_data.shunt_current = -1.0;
|
||||
rwLockReleaseWrite(&sensorDataLock);
|
||||
|
||||
// Initialize local network data with static values
|
||||
rwLockAcquireWrite(&networkDataLock);
|
||||
strcpy(local_wifi_data.ip_address, "0.0.0.0");
|
||||
local_wifi_data.link = false;
|
||||
local_wifi_data.rssi = -1.0;
|
||||
strcpy(local_wifi_data.network_name, "UNKNOWN");
|
||||
|
||||
strcpy(local_ethernet_data.ip_address, "0.0.0.0");
|
||||
local_ethernet_data.link = false;
|
||||
local_ethernet_data.rssi = -1.0;
|
||||
strcpy(local_ethernet_data.network_name, "UNKNOWN");
|
||||
rwLockReleaseWrite(&networkDataLock);
|
||||
|
||||
// Initialize local telemetry data with static values
|
||||
rwLockAcquireWrite(&telemetryDataLock);
|
||||
local_telemetry.heap_used_percent = -1.0;
|
||||
local_telemetry.uptime_seconds = -1;
|
||||
local_telemetry.temperature = -1.0;
|
||||
rwLockReleaseWrite(&telemetryDataLock);
|
||||
|
||||
// Initialize local OTA status with static values
|
||||
rwLockAcquireWrite(&otaStatusLock);
|
||||
local_ota_status.update_available = false;
|
||||
local_ota_status.current_version = {0, 0, 0};
|
||||
local_ota_status.latest_version = {0, 0, 0};
|
||||
local_ota_status.update_progress = -1;
|
||||
local_ota_status.update_url = "UNKNOWN";
|
||||
rwLockReleaseWrite(&otaStatusLock);
|
||||
|
||||
LOG(ELOG_LEVEL_DEBUG, "Starting webserver");
|
||||
server.begin();
|
||||
|
||||
while (1) {
|
||||
// Check if there is new state data in the queue
|
||||
CurrentState currentState;
|
||||
if (xQueueReceive(stateQueue, ¤tState, portMAX_DELAY) == pdTRUE) {
|
||||
// Update local_water_data with the new data from the queue
|
||||
rwLockAcquireWrite(&waterDataLock);
|
||||
local_water_data = currentState.waterData;
|
||||
rwLockReleaseWrite(&waterDataLock);
|
||||
|
||||
// Update local_sensor_data with the new data from the queue
|
||||
rwLockAcquireWrite(&sensorDataLock);
|
||||
local_sensor_data = currentState.sensorData;
|
||||
rwLockReleaseWrite(&sensorDataLock);
|
||||
|
||||
// Update local network data with the new data from the queue
|
||||
rwLockAcquireWrite(&networkDataLock);
|
||||
local_wifi_data = currentState.wifiData;
|
||||
local_ethernet_data = currentState.ethernetData;
|
||||
rwLockReleaseWrite(&networkDataLock);
|
||||
|
||||
// Update local telemetry data with the new data from the queue
|
||||
rwLockAcquireWrite(&telemetryDataLock);
|
||||
local_telemetry = currentState.telemetryData;
|
||||
rwLockReleaseWrite(&telemetryDataLock);
|
||||
|
||||
// Update local OTA status with the new data from the queue
|
||||
rwLockAcquireWrite(&otaStatusLock);
|
||||
local_ota_status = currentState.otaStatus;
|
||||
rwLockReleaseWrite(&otaStatusLock);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
#ifndef ASYNC_WEBSERVER_H
|
||||
#define ASYNC_WEBSERVER_H
|
||||
|
||||
#include <ESPAsyncWebServer.h>
|
||||
#include <LittleFS.h>
|
||||
|
||||
extern AsyncWebServer server;
|
||||
|
||||
void setup_api_endpoints();
|
||||
void setup_routes();
|
||||
void webserver_task(void *pvParameters);
|
||||
void handle_update_wifi_credentials(AsyncWebServerRequest* request);
|
||||
void handle_update_sensor_settings(AsyncWebServerRequest* request);
|
||||
|
||||
#endif // ASYNC_WEBSERVER_H
|
||||
|
||||
@@ -18,24 +18,21 @@ INA233 ina_sensor(0x40);
|
||||
#include "freertos/task.h"
|
||||
|
||||
extern Preferences prefs;
|
||||
|
||||
WaterData water_data;
|
||||
extern WaterData water_data;
|
||||
extern ActiveErrors active_errors;
|
||||
extern SensorData shunt_data;
|
||||
|
||||
// Calibration variables
|
||||
float zero_value = 0.03; // Measured shunt voltage with nothing connected, used to fix measuring offset
|
||||
|
||||
void init_sensor(){
|
||||
ina_sensor.begin(33, 32);
|
||||
#ifdef USE_INA226
|
||||
Wire.begin(33, 32);
|
||||
ina_sensor.begin();
|
||||
ina_sensor.setMaxCurrentShunt(0.02, 4, false);
|
||||
ina_sensor.setBusVoltageConversionTime(7);
|
||||
ina_sensor.setShuntVoltageConversionTime(7);
|
||||
ina_sensor.setAverage(4);
|
||||
// 111 - Shunt + Bus continous
|
||||
ina_sensor.setMode(7);
|
||||
#else
|
||||
ina_sensor.begin(33, 32);
|
||||
ina_sensor.reset();
|
||||
ina_sensor.setShuntVoltageConversionTime(conversion_time_8244uS);
|
||||
ina_sensor.setBusVoltageConversionTime(conversion_time_8244uS);
|
||||
@@ -46,43 +43,19 @@ void init_sensor(){
|
||||
|
||||
void read_sensor_task(void* parameter)
|
||||
{
|
||||
// Extract the queue handle from the task parameters
|
||||
QueueHandle_t dataQueue = (QueueHandle_t)parameter;
|
||||
if (dataQueue == NULL) {
|
||||
LOG(ELOG_LEVEL_ERROR, "Data queue is NULL");
|
||||
vTaskDelete(NULL);
|
||||
return;
|
||||
}
|
||||
|
||||
LOG(ELOG_LEVEL_DEBUG, "Starting read sensor tasks");
|
||||
while (true) {
|
||||
// Get Values from sensor
|
||||
#ifndef USE_INA226
|
||||
String chip_id = ina_sensor.get_device_model();
|
||||
LOG(ELOG_LEVEL_DEBUG, "Chip Model: %s", chip_id.c_str());
|
||||
LOG(DEBUG, "Chip Model: %s", chip_id.c_str());
|
||||
#endif
|
||||
|
||||
float bus_voltage = ina_sensor.getBusVoltage();
|
||||
float shunt_voltage = ina_sensor.getShuntVoltage_mV() - zero_value;
|
||||
|
||||
LOG(ELOG_LEVEL_DEBUG, "RAW Shunt voltage: %F mV", ina_sensor.getShuntVoltage_mV());
|
||||
LOG(DEBUG, "RAW Shunt voltage: %F mV", ina_sensor.getShuntVoltage_mV());
|
||||
|
||||
float shunt_current = shunt_voltage / RESISTOR_VALUE;
|
||||
|
||||
|
||||
// Build SensorData object
|
||||
SensorData sensor_data;
|
||||
sensor_data.bus_voltage = bus_voltage;
|
||||
sensor_data.shunt_current = shunt_current;
|
||||
sensor_data.shunt_voltage = shunt_voltage;
|
||||
|
||||
// Send the sensor data to the data queue
|
||||
DataMessage dataMessageSensor;
|
||||
dataMessageSensor.type = DATA_TYPE_SENSOR;
|
||||
dataMessageSensor.data.sensorData = sensor_data;
|
||||
if (xQueueSend(dataQueue, &dataMessageSensor, 0) != pdTRUE) {
|
||||
LOG(ELOG_LEVEL_ERROR, "Failed to send water data to queue");
|
||||
}
|
||||
|
||||
|
||||
// Get values from storage
|
||||
float sensor_range = prefs.getFloat(level_sensor_range_key, 200);
|
||||
@@ -100,8 +73,8 @@ void read_sensor_task(void* parameter)
|
||||
float min_water_level_mA = 4 + min_water_level_mA_over_zero;
|
||||
float max_water_level_mA = 4 + max_water_level_mA_over_zero;
|
||||
|
||||
LOG(ELOG_LEVEL_DEBUG, "max_water_level_mA: %F", max_water_level_mA);
|
||||
LOG(ELOG_LEVEL_DEBUG, "min_water_level_mA_over_zero: %F", min_water_level_mA_over_zero);
|
||||
LOG(DEBUG, "max_water_level_mA: %F", max_water_level_mA);
|
||||
LOG(DEBUG, "min_water_level_mA_over_zero: %F", min_water_level_mA_over_zero);
|
||||
|
||||
// Current over the 0 level of the water
|
||||
float shunt_current_over_zero = shunt_current - min_water_level_mA;
|
||||
@@ -117,31 +90,23 @@ void read_sensor_task(void* parameter)
|
||||
float liters_raw = max_liters * percentage_raw;
|
||||
int liters = round(liters_raw);
|
||||
|
||||
LOG(ELOG_LEVEL_DEBUG, "Shunt current: %F", shunt_current);
|
||||
LOG(ELOG_LEVEL_DEBUG, "Shunt voltage: %F", shunt_voltage);
|
||||
LOG(ELOG_LEVEL_DEBUG, "Bus voltage: %F", bus_voltage);
|
||||
LOG(ELOG_LEVEL_DEBUG, "cm_over_zero: %F", cm_over_zero);
|
||||
active_errors.current_low = shunt_current < 3.8;
|
||||
active_errors.current_high = shunt_current > 20.2;
|
||||
active_errors.voltage_low = bus_voltage < 23;
|
||||
active_errors.voltage_high = bus_voltage > 25;
|
||||
LOG(DEBUG, "Shunt current: %F", shunt_current);
|
||||
LOG(DEBUG, "Shunt voltage: %F", shunt_voltage);
|
||||
LOG(DEBUG, "Bus voltage: %F", bus_voltage);
|
||||
LOG(DEBUG, "cm_over_zero: %F", cm_over_zero);
|
||||
|
||||
shunt_data.bus_voltage = bus_voltage;
|
||||
shunt_data.shunt_voltage = shunt_voltage;
|
||||
shunt_data.shunt_current = shunt_current;
|
||||
|
||||
water_data.level = cm_over_zero;
|
||||
water_data.liters = liters;
|
||||
water_data.percentage = percentage_rounded;
|
||||
|
||||
// Send the water data to the data queue
|
||||
DataMessage dataMessageWater;
|
||||
dataMessageWater.type = DATA_TYPE_WATER;
|
||||
dataMessageWater.data.waterData = water_data;
|
||||
|
||||
// Log the data being sent
|
||||
LOG(ELOG_LEVEL_DEBUG, "Sending water data to queue: level=%F, liters=%F, percentage=%F",
|
||||
water_data.level, water_data.liters, water_data.percentage);
|
||||
|
||||
if (xQueueSend(dataQueue, &dataMessageWater, 0) != pdTRUE) {
|
||||
LOG(ELOG_LEVEL_ERROR, "Failed to send water data to queue");
|
||||
// Log the queue status
|
||||
UBaseType_t messagesWaiting = uxQueueMessagesWaiting(dataQueue);
|
||||
LOG(ELOG_LEVEL_ERROR, "Queue messages waiting: %d", messagesWaiting);
|
||||
}
|
||||
|
||||
delay(20000);
|
||||
}
|
||||
}
|
||||
@@ -1,39 +1,17 @@
|
||||
#include "telemetry.h"
|
||||
#include <Arduino.h>
|
||||
#include "../global_data/global_data.h"
|
||||
#include "tools/log.h"
|
||||
#include <freertos/queue.h>
|
||||
|
||||
extern "C" uint8_t temprature_sens_read();
|
||||
extern DeviceTelemetry telemetry;
|
||||
|
||||
void collect_internal_telemetry_task(void* parameter)
|
||||
{
|
||||
// Extract the queue handle from the task parameters
|
||||
QueueHandle_t dataQueue = (QueueHandle_t)parameter;
|
||||
if (dataQueue == NULL) {
|
||||
LOG(ELOG_LEVEL_ERROR, "Data queue is NULL");
|
||||
vTaskDelete(NULL);
|
||||
return;
|
||||
}
|
||||
|
||||
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;
|
||||
float temperature = (temprature_sens_read()-32) / 1.8;
|
||||
|
||||
// Create a DataMessage for telemetry data
|
||||
DataMessage dataMessage;
|
||||
dataMessage.type = DATA_TYPE_TELEMETRY;
|
||||
dataMessage.data.telemetryData.heap_used_percent = heap_usage;
|
||||
dataMessage.data.telemetryData.uptime_seconds = uptime_seconds;
|
||||
dataMessage.data.telemetryData.temperature = temperature;
|
||||
|
||||
// Send the telemetry data to the queue
|
||||
if (xQueueSend(dataQueue, &dataMessage, 0) != pdTRUE) {
|
||||
LOG(ELOG_LEVEL_ERROR, "Failed to send telemetry data to queue");
|
||||
}
|
||||
|
||||
delay(10 * 1000);
|
||||
telemetry.heap_used_percent = heap_usage;
|
||||
telemetry.uptime_seconds = uptime_seconds;
|
||||
delay(60000);
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,9 @@
|
||||
#include "freertos/FreeRTOS.h"
|
||||
#include "freertos/task.h"
|
||||
#include <Elog.h>
|
||||
|
||||
#define LOG(LEVEL, FMT, ...) \
|
||||
do { \
|
||||
Logger.log(0, LEVEL, "[Core: %i][Task: %s][Fn: %s] " FMT, \
|
||||
logger.log(0, LEVEL, "[Core: %i][Task: %s][%s] " FMT, \
|
||||
xPortGetCoreID(), \
|
||||
pcTaskGetName(xTaskGetCurrentTaskHandle()), \
|
||||
__FUNCTION__, \
|
||||
|
||||
@@ -1,59 +0,0 @@
|
||||
#include <ArduinoOTA.h>
|
||||
#include <Elog.h>
|
||||
#include "tools/log.h"
|
||||
|
||||
/**
|
||||
* @brief Task to handle ArduinoOTA updates.
|
||||
*
|
||||
* This task initializes the ArduinoOTA library and handles OTA updates.
|
||||
* It runs indefinitely to process OTA update requests.
|
||||
*
|
||||
* @param pvParameters Task parameters (unused).
|
||||
*/
|
||||
void ota_handler_task(void *pvParameters) {
|
||||
(void)pvParameters; // Suppress unused parameter warning
|
||||
|
||||
LOG(ELOG_LEVEL_DEBUG, "Setting up OTA handler");
|
||||
|
||||
// Configure OTA settings
|
||||
ArduinoOTA
|
||||
.onStart([]() {
|
||||
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.c_str());
|
||||
})
|
||||
.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) {
|
||||
Serial.printf("Error[%u]: ", error);
|
||||
if (error == OTA_AUTH_ERROR) {
|
||||
LOG(ELOG_LEVEL_DEBUG, "Auth Failed");
|
||||
} else if (error == OTA_BEGIN_ERROR) {
|
||||
LOG(ELOG_LEVEL_DEBUG, "Begin Failed");
|
||||
} else if (error == OTA_CONNECT_ERROR) {
|
||||
LOG(ELOG_LEVEL_DEBUG, "Connect Failed");
|
||||
} else if (error == OTA_RECEIVE_ERROR) {
|
||||
LOG(ELOG_LEVEL_DEBUG, "Receive Failed");
|
||||
} else if (error == OTA_END_ERROR) {
|
||||
LOG(ELOG_LEVEL_DEBUG, "End Failed");
|
||||
}
|
||||
});
|
||||
// Start the OTA handler
|
||||
ArduinoOTA.begin();
|
||||
|
||||
// Run indefinitely to handle OTA updates
|
||||
while (1) {
|
||||
ArduinoOTA.handle();
|
||||
vTaskDelay(250 / portTICK_PERIOD_MS); // Even more frequent handling
|
||||
}
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
#ifndef OTA_HANDLER_H
|
||||
#define OTA_HANDLER_H
|
||||
|
||||
/**
|
||||
* @brief Task to handle ArduinoOTA updates.
|
||||
*
|
||||
* This task initializes the ArduinoOTA library and handles OTA updates.
|
||||
* It runs indefinitely to process OTA update requests.
|
||||
*
|
||||
* @param pvParameters Task parameters (unused).
|
||||
*/
|
||||
void ota_handler_task(void *pvParameters);
|
||||
|
||||
#endif // OTA_HANDLER_H
|
||||
@@ -1,70 +0,0 @@
|
||||
#include "readers_writer_lock.h"
|
||||
#include <freertos/task.h>
|
||||
|
||||
bool rwLockInit(ReadersWriterLock* rwLock) {
|
||||
if (rwLock == NULL) {
|
||||
return false;
|
||||
}
|
||||
|
||||
rwLock->mutex = xSemaphoreCreateMutex();
|
||||
if (rwLock->mutex == NULL) {
|
||||
return false;
|
||||
}
|
||||
|
||||
rwLock->readersCount = 0;
|
||||
rwLock->writerActive = false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void rwLockAcquireRead(ReadersWriterLock* rwLock) {
|
||||
if (rwLock == NULL) {
|
||||
return;
|
||||
}
|
||||
|
||||
xSemaphoreTake(rwLock->mutex, portMAX_DELAY);
|
||||
// Wait until no writer is active
|
||||
while (rwLock->writerActive) {
|
||||
xSemaphoreGive(rwLock->mutex);
|
||||
vTaskDelay(10 / portTICK_PERIOD_MS); // Small delay to avoid busy-waiting
|
||||
xSemaphoreTake(rwLock->mutex, portMAX_DELAY);
|
||||
}
|
||||
rwLock->readersCount++;
|
||||
xSemaphoreGive(rwLock->mutex);
|
||||
}
|
||||
|
||||
void rwLockReleaseRead(ReadersWriterLock* rwLock) {
|
||||
if (rwLock == NULL) {
|
||||
return;
|
||||
}
|
||||
|
||||
xSemaphoreTake(rwLock->mutex, portMAX_DELAY);
|
||||
rwLock->readersCount--;
|
||||
xSemaphoreGive(rwLock->mutex);
|
||||
}
|
||||
|
||||
void rwLockAcquireWrite(ReadersWriterLock* rwLock) {
|
||||
if (rwLock == NULL) {
|
||||
return;
|
||||
}
|
||||
|
||||
xSemaphoreTake(rwLock->mutex, portMAX_DELAY);
|
||||
// Set the writer active flag to block new readers
|
||||
rwLock->writerActive = true;
|
||||
// Wait until no readers are active
|
||||
while (rwLock->readersCount > 0) {
|
||||
xSemaphoreGive(rwLock->mutex);
|
||||
vTaskDelay(10 / portTICK_PERIOD_MS); // Small delay to avoid busy-waiting
|
||||
xSemaphoreTake(rwLock->mutex, portMAX_DELAY);
|
||||
}
|
||||
// Writer now has exclusive access
|
||||
}
|
||||
|
||||
void rwLockReleaseWrite(ReadersWriterLock* rwLock) {
|
||||
if (rwLock == NULL) {
|
||||
return;
|
||||
}
|
||||
|
||||
rwLock->writerActive = false;
|
||||
xSemaphoreGive(rwLock->mutex);
|
||||
}
|
||||
@@ -1,65 +0,0 @@
|
||||
#ifndef READERS_WRITER_LOCK_H
|
||||
#define READERS_WRITER_LOCK_H
|
||||
|
||||
#include <freertos/FreeRTOS.h>
|
||||
#include <freertos/semphr.h>
|
||||
|
||||
/**
|
||||
* @brief Readers-Writer Lock structure.
|
||||
*
|
||||
* This structure holds the state for a readers-writer lock,
|
||||
* allowing multiple readers or a single writer to access a shared resource.
|
||||
*/
|
||||
typedef struct {
|
||||
SemaphoreHandle_t mutex; /**< Mutex to protect the lock state. */
|
||||
int readersCount; /**< Number of active readers. */
|
||||
bool writerActive; /**< Flag to indicate if a writer is active. */
|
||||
} ReadersWriterLock;
|
||||
|
||||
/**
|
||||
* @brief Initialize a readers-writer lock.
|
||||
*
|
||||
* Initializes the mutex and sets the initial state of the lock.
|
||||
*
|
||||
* @param rwLock Pointer to the ReadersWriterLock structure to initialize.
|
||||
* @return true if initialization succeeded, false otherwise.
|
||||
*/
|
||||
bool rwLockInit(ReadersWriterLock* rwLock);
|
||||
|
||||
/**
|
||||
* @brief Acquire a read lock.
|
||||
*
|
||||
* Blocks if a writer is active, otherwise allows multiple readers to access the data simultaneously.
|
||||
*
|
||||
* @param rwLock Pointer to the ReadersWriterLock structure.
|
||||
*/
|
||||
void rwLockAcquireRead(ReadersWriterLock* rwLock);
|
||||
|
||||
/**
|
||||
* @brief Release a read lock.
|
||||
*
|
||||
* Decrements the readers count.
|
||||
*
|
||||
* @param rwLock Pointer to the ReadersWriterLock structure.
|
||||
*/
|
||||
void rwLockReleaseRead(ReadersWriterLock* rwLock);
|
||||
|
||||
/**
|
||||
* @brief Acquire a write lock.
|
||||
*
|
||||
* Blocks until all readers have finished and sets the writer active flag.
|
||||
*
|
||||
* @param rwLock Pointer to the ReadersWriterLock structure.
|
||||
*/
|
||||
void rwLockAcquireWrite(ReadersWriterLock* rwLock);
|
||||
|
||||
/**
|
||||
* @brief Release a write lock.
|
||||
*
|
||||
* Clears the writer active flag and allows readers and writers.
|
||||
*
|
||||
* @param rwLock Pointer to the ReadersWriterLock structure.
|
||||
*/
|
||||
void rwLockReleaseWrite(ReadersWriterLock* rwLock);
|
||||
|
||||
#endif // READERS_WRITER_LOCK_H
|
||||
@@ -6,14 +6,6 @@
|
||||
#include <fetchOTA.h>
|
||||
#include <AsyncWebSocket.h>
|
||||
#include "log.h"
|
||||
#include "esp_sntp.h"
|
||||
#include <HTTPClient.h>
|
||||
|
||||
#ifdef USE_INA226
|
||||
#define BOARD_VARIANT "INA226REV2"
|
||||
#else
|
||||
#define BOARD_VARIANT "INA233REV2"
|
||||
#endif
|
||||
|
||||
extern Preferences prefs;
|
||||
extern OTAStatus ota_status;
|
||||
@@ -21,6 +13,10 @@ extern AsyncWebSocket webSocket;
|
||||
|
||||
extern Version current_spiffs_version;
|
||||
|
||||
bool is_error(ActiveErrors active_errors) {
|
||||
return active_errors.current_high || active_errors.current_low || active_errors.level_high || active_errors.level_low || active_errors.voltage_high || active_errors.voltage_low;
|
||||
}
|
||||
|
||||
String processor(const String& var)
|
||||
{
|
||||
if (var == level_sensor_range_key) {
|
||||
@@ -40,118 +36,93 @@ String processor(const String& var)
|
||||
|
||||
// OTA Callbacks
|
||||
void update_started() {
|
||||
LOG(ELOG_LEVEL_DEBUG, "OTA Update started");
|
||||
LOG(DEBUG, "OTA Update started");
|
||||
ota_status.update_progress = 0;
|
||||
}
|
||||
|
||||
void update_finished() {
|
||||
LOG(ELOG_LEVEL_DEBUG, "OTA Update finished, rebooting after 2 seconds");
|
||||
LOG(DEBUG, "OTA Update finished");
|
||||
ota_status.update_progress = -1;
|
||||
webSocket.textAll(String(-1).c_str());
|
||||
delay(2000);
|
||||
ESP.restart();
|
||||
}
|
||||
|
||||
void update_progress(int cur, int total) {
|
||||
ota_status.update_progress = 0;
|
||||
if (cur != 0 ) {
|
||||
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);
|
||||
LOG(DEBUG, "OTA Update progress: %d/%d, %i", cur, total, ota_status.update_progress);
|
||||
}
|
||||
webSocket.textAll(String(ota_status.update_progress).c_str());
|
||||
LOG(ELOG_LEVEL_DEBUG, "OTA Update progress: %d/%d", cur, total);
|
||||
LOG(DEBUG, "OTA Update progress: %d/%d", cur, total);
|
||||
}
|
||||
|
||||
void update_error(int err) {
|
||||
LOG(ELOG_LEVEL_ERROR, "OTA Update error: %d", err);
|
||||
LOG(ERROR, "OTA Update error: %d", err);
|
||||
ota_status.update_progress = -2;
|
||||
}
|
||||
|
||||
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
|
||||
OTA ota("https://iot.tobiasmaier.me/firmware/waterlevel", current_software_version, "INA226");
|
||||
#else
|
||||
OTA ota("https://iot.tobiasmaier.me/firmware/waterlevel", current_software_version, "INA233");
|
||||
#endif
|
||||
OTA spiffs_fs("https://iot.tobiasmaier.me/filesystem/waterlevel", REQUIRED_SPIFFS_VERSION, "generic");
|
||||
|
||||
|
||||
// Init SPIFFS update and check for update
|
||||
// If there is a SPIFSS update it will be ran automatically, as SPIFFS is necessary for the firmware to run
|
||||
Firmware latest_spiff_version = spiffs_fs.getLatestVersionOnServer();
|
||||
|
||||
LOG(DEBUG, "Required SPIFFS Version: %d.%d.%d; Current SPIFFS version: %d.%d.%d; Server SPIFFS Version: %d.%d.%d", REQUIRED_SPIFFS_VERSION.major, REQUIRED_SPIFFS_VERSION.minor, REQUIRED_SPIFFS_VERSION.patch, current_spiffs_version.major, current_spiffs_version.minor, current_spiffs_version.patch, latest_spiff_version.version.major, latest_spiff_version.version.minor, latest_spiff_version.version.patch);
|
||||
|
||||
if (latest_spiff_version.valid) {
|
||||
if (isVersionNewer(current_spiffs_version, REQUIRED_SPIFFS_VERSION)) {
|
||||
// If Required SPIFFS version is newer than current version, update
|
||||
LOG(DEBUG, "New SPIFFS version, running update now");
|
||||
run_ota_spiffs_update(latest_spiff_version.url, update_started, update_finished, update_progress, update_error);
|
||||
// Reboot just to be safe
|
||||
ESP.restart();
|
||||
} else if (isVersionNewer(REQUIRED_SPIFFS_VERSION, latest_spiff_version.version)) {
|
||||
// If Server has new SPIFFS version but it's not required
|
||||
LOG(DEBUG, "New SPIFFS version available: %d.%d.%d, current version: %d.%d.%d but not necessary to update", latest_spiff_version.version.major, latest_spiff_version.version.minor, latest_spiff_version.version.patch, REQUIRED_SPIFFS_VERSION.major, REQUIRED_SPIFFS_VERSION.minor, REQUIRED_SPIFFS_VERSION.patch);
|
||||
} else {
|
||||
LOG(DEBUG, "No new SPIFFS version available");
|
||||
}
|
||||
}
|
||||
|
||||
OTA ota("https://iot.tobiasmaier.me/firmware/waterlevel", current_software_version, BOARD_VARIANT);
|
||||
OTA littlefs_ota("https://iot.tobiasmaier.me/filesystem/waterlevel", REQUIRED_SPIFFS_VERSION, "generic");
|
||||
|
||||
while (true) {
|
||||
// Check if internet connection exists before running update, the web client seems to fail otherwise
|
||||
|
||||
if (check_for_internet_connection()) {
|
||||
LOG(ELOG_LEVEL_DEBUG, "Ping sucessful, starting update checks");
|
||||
check_and_update_littleFS(littlefs_ota);
|
||||
check_and_update_firmware(ota);
|
||||
Firmware fw = ota.getLatestVersionOnServer();
|
||||
if (fw.valid) {
|
||||
LOG(DEBUG, "New firmware available: %d.%d.%d, current version: %d.%d.%d", fw.version.major, fw.version.minor, fw.version.patch, current_software_version.major, current_software_version.minor, current_software_version.patch);
|
||||
ota_status.latest_version = fw.version;
|
||||
ota_status.update_url = fw.url;
|
||||
if (isVersionNewer(current_software_version, fw.version)) {
|
||||
LOG(DEBUG, "Remote version is newer than current version");
|
||||
ota_status.update_available = true;
|
||||
} else {
|
||||
ota_status.update_available = false;
|
||||
}
|
||||
} else {
|
||||
LOG(ELOG_LEVEL_WARNING, "Server did not respond to ping, waiting...");
|
||||
if (fw.version.major != 0 && fw.version.minor != 0 && fw.version.patch != 0) {
|
||||
ota_status.latest_version = fw.version;
|
||||
ota_status.update_available = false;
|
||||
}
|
||||
|
||||
LOG(DEBUG, "No new firmware available");
|
||||
}
|
||||
delay(1000 * 60 * 1);
|
||||
}
|
||||
}
|
||||
|
||||
void check_and_update_littleFS(OTA littlefs) {
|
||||
Firmware latest_fs_version = littlefs.getLatestVersionOnServer();
|
||||
|
||||
LOG(ELOG_LEVEL_DEBUG, "Required SPIFFS Version: %d.%d.%d; Current SPIFFS version: %d.%d.%d; Server SPIFFS Version: %d.%d.%d", REQUIRED_SPIFFS_VERSION.major, REQUIRED_SPIFFS_VERSION.minor, REQUIRED_SPIFFS_VERSION.patch, current_spiffs_version.major, current_spiffs_version.minor, current_spiffs_version.patch, latest_fs_version.version.major, latest_fs_version.version.minor, latest_fs_version.version.patch);
|
||||
|
||||
if (latest_fs_version.valid) {
|
||||
|
||||
// If we need new version and the server has a new version
|
||||
if (isVersionNewer(current_spiffs_version, REQUIRED_SPIFFS_VERSION) && isVersionNewer(current_spiffs_version, latest_fs_version.version)) {
|
||||
LOG(ELOG_LEVEL_DEBUG, "New SPIFFS version, running update now");
|
||||
run_ota_spiffs_update(latest_fs_version.url, update_started, update_finished, update_progress, update_error);
|
||||
|
||||
// If we do not need a new version but one is available on the server
|
||||
} else if (isVersionNewer(REQUIRED_SPIFFS_VERSION, latest_fs_version.version)) {
|
||||
LOG(ELOG_LEVEL_DEBUG, "New SPIFFS version available: %d.%d.%d, current version: %d.%d.%d but not necessary to update", latest_fs_version.version.major, latest_fs_version.version.minor, latest_fs_version.version.patch, REQUIRED_SPIFFS_VERSION.major, REQUIRED_SPIFFS_VERSION.minor, REQUIRED_SPIFFS_VERSION.patch);
|
||||
|
||||
// If we need a new version but server has no new version
|
||||
} else if (isVersionNewer(current_spiffs_version, REQUIRED_SPIFFS_VERSION)) {
|
||||
LOG(ELOG_LEVEL_ERROR, "New LittleFS Version is needed, but not found on server");
|
||||
|
||||
// Catch case for the rest
|
||||
} else {
|
||||
LOG(ELOG_LEVEL_DEBUG, "No new SPIFFS version available");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void check_and_update_firmware(OTA ota){
|
||||
Firmware fw = ota.getLatestVersionOnServer();
|
||||
if (fw.valid) {
|
||||
LOG(ELOG_LEVEL_DEBUG, "Firmware available on server: %d.%d.%d, current version: %d.%d.%d", fw.version.major, fw.version.minor, fw.version.patch, current_software_version.major, current_software_version.minor, current_software_version.patch);
|
||||
ota_status.latest_version = fw.version;
|
||||
ota_status.update_url = fw.url;
|
||||
if (isVersionNewer(current_software_version, fw.version)) {
|
||||
LOG(ELOG_LEVEL_DEBUG, "Remote version is newer than current version");
|
||||
ota_status.update_available = true;
|
||||
} else {
|
||||
ota_status.update_available = false;
|
||||
}
|
||||
} else {
|
||||
if (fw.version.major != 0 && fw.version.minor != 0 && fw.version.patch != 0) {
|
||||
ota_status.latest_version = fw.version;
|
||||
ota_status.update_available = false;
|
||||
}
|
||||
|
||||
LOG(ELOG_LEVEL_DEBUG, "No new firmware available");
|
||||
}
|
||||
}
|
||||
|
||||
bool check_for_internet_connection() {
|
||||
HTTPClient http;
|
||||
http.begin("https://iot.tobiasmaier.me");
|
||||
int code = http.sendRequest("HEAD");
|
||||
if (code > 0) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
void run_ota_update_task(void* parameter) {
|
||||
TaskArgs_t *args = (TaskArgs_t *) parameter;
|
||||
LOG(ELOG_LEVEL_DEBUG, "Running OTA upgrade now with URL: %s", args->ota_status.update_url.c_str());
|
||||
LOG(DEBUG, "Running OTA upgrade now with URL: %s", args->ota_status.update_url.c_str());
|
||||
run_ota_update(args->ota_status.update_url, update_started, update_finished, update_progress, update_error);
|
||||
vTaskDelete(NULL);
|
||||
}
|
||||
@@ -167,36 +138,3 @@ void onWsEvent(AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventTyp
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
@@ -6,17 +6,11 @@
|
||||
|
||||
void printSuffix(Print* _logOutput, int logLevel);
|
||||
void print_prefix(Print* _logOutput, int logLevel);
|
||||
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 get_time_task(void* parameter);
|
||||
|
||||
void onTimeSync(struct timeval* tv);
|
||||
bool waitForTime();
|
||||
void check_and_update_firmware(OTA fw);
|
||||
void check_and_update_littleFS(OTA littlefs);
|
||||
bool check_for_internet_connection();
|
||||
|
||||
typedef struct {
|
||||
OTAStatus ota_status;
|
||||
|
||||
Reference in New Issue
Block a user