Compare commits

...

44 Commits

Author SHA1 Message Date
f0e237cd71 Switch to PIO image
Some checks failed
Test compiling project / test (push) Failing after 0s
2025-05-24 16:02:15 +00:00
7b0f3d20b0 Switch to devcontainer
Some checks are pending
Test compiling project / test (push) Waiting to run
2025-05-24 15:59:22 +00:00
ef04f1077c Merge branch 'main' of ssh://gitea.maiertobi.de:222/tobimai/waterlevel-software
All checks were successful
Test compiling project / test (push) Successful in 2m42s
2025-04-18 21:05:09 +02:00
47445d6cd5 version bump 2025-04-18 21:05:07 +02:00
78867ae8a3 Merge pull request 'Fix Sensor' (#2) from fix-sensor into main
All checks were successful
Test compiling project / test (push) Successful in 2m43s
Reviewed-on: https://gitea.maiertobi.de/tobimai/waterlevel-software/pulls/2
2025-04-18 21:00:15 +02:00
0f581a54c5 Fix Sensor
All checks were successful
Test compiling project / test (push) Successful in 2m46s
2025-04-18 20:57:09 +02:00
82455c830f revert change + version bump
All checks were successful
Test compiling project / test (push) Successful in 2m41s
2025-03-23 18:27:16 +01:00
d73b2c66cd Version bump
All checks were successful
Test compiling project / test (push) Successful in 2m44s
2025-03-23 18:14:52 +01:00
0cc2638db2 Merge pull request 'logger-rework' (#1) from logger-rework into main
Some checks failed
Test compiling project / test (push) Has been cancelled
Reviewed-on: https://gitea.maiertobi.de/tobimai/waterlevel-software/pulls/1
2025-03-23 18:14:19 +01:00
abbb8d918b fix
All checks were successful
Test compiling project / test (push) Successful in 2m44s
2025-03-23 18:04:14 +01:00
67e9ae1bca Fixed wrong shunt voltage reading
Some checks failed
Test compiling project / test (push) Failing after 2m24s
2025-03-23 17:59:43 +01:00
2fa4b0761b FAR nicer logging
Some checks failed
Test compiling project / test (push) Failing after 2m14s
2025-03-20 22:33:22 +01:00
9064d3cd01 Merge branch 'logger-rework' of ssh://gitea.maiertobi.de:222/tobimai/waterlevel-software into logger-rework
Some checks failed
Test compiling project / test (push) Failing after 1m39s
2025-03-20 21:09:03 +01:00
f16659c25c Changes 2025-03-20 21:08:37 +01:00
6364becbe2 Fixed library
Some checks failed
Test compiling project / test (push) Has been cancelled
2025-03-20 21:08:30 +01:00
76e182935b Added syslog
Some checks failed
Test compiling project / test (push) Failing after 1m37s
2025-03-18 22:51:41 +01:00
eeaac9548e Rework logging
Some checks failed
Test compiling project / test (push) Failing after 1m34s
2025-03-10 23:33:41 +01:00
374b23d99a Merge branch 'main' of ssh://gitea.maiertobi.de:222/tobimai/waterlevel-software
All checks were successful
Test compiling project / test (push) Successful in 2m27s
2025-03-10 22:06:42 +01:00
bd18952fe2 fixed ip 2025-03-10 22:06:12 +01:00
0071a09935 Fix water levelTest
All checks were successful
Test compiling project / test (push) Successful in 2m30s
2025-02-23 17:54:19 +01:00
99705355aa Cleanup + bump to 1.0.0
All checks were successful
Test compiling project / test (push) Successful in 2m31s
2025-02-23 11:34:41 +01:00
dabcafa5db Fixed data export docs
All checks were successful
Test compiling project / test (push) Successful in 2m36s
2025-02-23 10:56:38 +01:00
e348ef21c9 Switched to 2 decimal rounded percentage
All checks were successful
Test compiling project / test (push) Successful in 2m40s
2025-02-23 10:50:53 +01:00
d0daa024dc Added raw water and level endpoints
All checks were successful
Test compiling project / test (push) Successful in 2m39s
2025-02-23 10:40:11 +01:00
354661c9ee FIxed SSID display in settings
All checks were successful
Test compiling project / test (push) Successful in 2m43s
2025-02-23 10:36:28 +01:00
146a4412e0 Fixed OTA Ethernet bug
All checks were successful
Test compiling project / test (push) Successful in 2m28s
2025-02-23 02:38:59 +01:00
2c4344e40d Added printout of shunt voltage
All checks were successful
Test compiling project / test (push) Successful in 2m27s
2025-02-22 22:59:08 +01:00
6e171fbde7 Version bumps, OTA working
All checks were successful
Test compiling project / test (push) Successful in 2m23s
2025-02-22 22:15:43 +01:00
32d35d7029 Version bump
All checks were successful
Test compiling project / test (push) Successful in 2m46s
2025-02-22 21:45:50 +01:00
102a842079 Added updating shit
All checks were successful
Test compiling project / test (push) Successful in 2m32s
2025-02-19 21:22:52 +01:00
ab16379e73 Added SPIFFS updating
All checks were successful
Test compiling project / test (push) Successful in 2m38s
2025-02-19 20:48:26 +01:00
0cd42484f9 Updated SPIFFS version
All checks were successful
Test compiling project / test (push) Successful in 2m35s
2025-02-19 20:40:50 +01:00
f213ecd345 well lets see lol
All checks were successful
Test compiling project / test (push) Successful in 2m22s
2025-02-18 21:59:51 +01:00
3b03c8619b Version bump
All checks were successful
Test compiling project / test (push) Successful in 2m19s
2025-02-17 21:52:27 +01:00
8b8a848701 Fixed bug always showing available update
Some checks failed
Test compiling project / test (push) Has been cancelled
2025-02-17 21:52:15 +01:00
6cec8f0a11 First Version to be updateable over API
All checks were successful
Test compiling project / test (push) Successful in 2m34s
2025-02-17 21:46:20 +01:00
6c4dc144d8 Added Update API endpoint
All checks were successful
Test compiling project / test (push) Successful in 2m30s
2025-02-17 20:59:32 +01:00
3b1ab2e9e9 Updated shit
All checks were successful
Test compiling project / test (push) Successful in 2m21s
2025-02-17 00:12:50 +01:00
7c4dd280c2 Fixed stuff
All checks were successful
Test compiling project / test (push) Successful in 2m17s
2025-02-15 18:05:25 +01:00
97cd402aa4 Version bump
All checks were successful
Test compiling project / test (push) Successful in 2m20s
2025-02-15 17:44:50 +01:00
16462eb844 Test if update actually updates
All checks were successful
Test compiling project / test (push) Successful in 2m15s
2025-02-15 17:11:07 +01:00
6186959d8f First version able to OTA update
All checks were successful
Test compiling project / test (push) Successful in 2m17s
2025-02-15 17:06:20 +01:00
f1f42f3014 Fixed CICD
All checks were successful
Test compiling project / test (push) Successful in 2m22s
2025-02-15 16:57:44 +01:00
e8b8e95c13 Inital version to support OTA 2025-02-15 16:57:21 +01:00
33 changed files with 793 additions and 202 deletions

View File

@@ -0,0 +1,17 @@
{
"name": "Waterlevel Software Development",
"dockerComposeFile": "docker-compose.yaml",
"service": "app",
"workspaceFolder": "/workspace",
"customizations": {
"vscode": {
"extensions": [
"platformio.platformio-ide",
"mutantdino.resourcemonitor",
"ms-azuretools.vscode-docker",
"meezilla.json"
]
}
}
}

View File

@@ -0,0 +1,9 @@
version: '3.8'
services:
app:
image: gitea.maiertobi.de/tobimai/devcontainer-pio:latest
user: tobi:tobi
volumes:
- ..:/workspace:cached
- /home/tobi/.ssh:/home/tobi/.ssh:ro
command: sleep infinity

View File

@@ -6,13 +6,9 @@ jobs:
test:
runs-on: ubuntu-latest
container:
image: debian:latest
image: gitea.maiertobi.de/tobimai/devcontainer-pio:latest
steps:
- name: Install necessary dependencies
run: apt update && apt install nodejs python3 python3-pip git curl -y
- name: Install Platformio
run: pip install --break-system-packages --upgrade platformio
- name: Checkout Code
uses: actions/checkout@v2
- name: Run PlatformIO Tests
@@ -21,11 +17,11 @@ jobs:
run: pio run -e ESP32_INA233
- name: Run PlatformIO build for INA226
run: pio run -e ESP32_INA226
- name: look at the output
run: ls -lah .pio/build/ESP32_INA233/ .pio/build/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_version Version{[[:space:]]*\([0-9]\+\),[[:space:]]*\([0-9]\+\),[[:space:]]*\([0-9]\+\)}/\1.\2.\3/p' src/global_data/defines.h)
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)
echo "Extracted version: $VERSION"
curl -X PUT \
@@ -35,10 +31,20 @@ jobs:
- name: Upload firmware binary for INA226
run: |
VERSION=$(sed -n 's/#define current_version Version{[[:space:]]*\([0-9]\+\),[[:space:]]*\([0-9]\+\),[[:space:]]*\([0-9]\+\)}/\1.\2.\3/p' src/global_data/defines.h)
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)
echo "Extracted version: $VERSION"
curl -X PUT \
-H "Content-Type: application/octet-stream" \
--data-binary @.pio/build/ESP32_INA226/firmware.bin \
https://iot.tobiasmaier.me/firmware/waterlevel/INA226/${VERSION}
- name: Upload SPIFFS binary
run: |
VERSION=$(cat data/version)
echo "Extracted version: $VERSION"
curl -X PUT \
-H "Content-Type: application/octet-stream" \
--data-binary @.pio/build/ESP32_INA233/spiffs.bin \
https://iot.tobiasmaier.me/filesystem/waterlevel/generic/${VERSION}

View File

@@ -1,6 +1,7 @@
{
"files.associations": {
"iostream": "cpp",
"random": "cpp"
"random": "cpp",
"vector": "cpp"
}
}

File diff suppressed because one or more lines are too long

View File

@@ -1,14 +1,7 @@
<!DOCTYPE html>
<!DOCTYPE html>
<head>
<link rel="stylesheet" href="/chota.css">
<script>
if (window.matchMedia &&
window.matchMedia('(prefers-color-scheme: dark)').matches) {
document.body.classList.add('dark');
}
</script>
</head>
<body>
@@ -31,25 +24,21 @@
<header>
<h4>JSON</h4>
</header>
Hello json
<ul>
<li><code>/sensor_data</code> Sensor values like voltage or current</li>
<li><code>/water_data</code> Water data like percent of level</li>
</ul>
</div>
<div class="card">
<header>
<h4>MQTT</h4>
<h4>Raw</h4>
</header>
Hello mqtt
<ul>
<li><code>/raw_percent</code> Water level in percent as raw text</li>
<li><code>/raw_level</code> Water level in cm as raw text</li>
</ul>
</div>
<div class="card">
<header>
<h4>Email alert</h4>
</header>
Hello json
</div>
</div>
</body>

View File

@@ -10,6 +10,7 @@ function fetchElectricData() {
.then(data => {
document.getElementById('voltage').textContent = data.bus_voltage ? (roundToTwo(data.bus_voltage) + ' V') : 'XXX';
document.getElementById('current').textContent = data.current ? (roundToTwo(data.current) + ' mA') : 'XXX';
document.getElementById('shunt_voltage').textContent = data.current ? (roundToTwo(data.shunt_voltage) + ' mV') : 'XXX';
})
.catch(error => {
console.error("There was an error fetching data from the API", error);
@@ -32,7 +33,6 @@ function fetchTelemetryData() {
function fetchWaterData(gauge) {
const apiUrl = '/water_data';
console.log("FD");
// Fetching data from the API
fetch(apiUrl)
.then(response => response.json())
@@ -44,6 +44,25 @@ function fetchWaterData(gauge) {
})
.catch(error => {
console.error("There was an error fetching data from the API", error);
});
}
function fetchUpdateData(gauge) {
const apiUrl = '/ota_udpate_status';
// Fetching data from the API
fetch(apiUrl)
.then(response => response.json())
.then(data => {
document.getElementById('current_fw').textContent = data.current_version || 'N/A';
document.getElementById('server_fw').textContent = data.new_version || 'N/A';
if (data.update_available == true) {
document.getElementById("update_button").style.visibility = 'visible';
} else {
document.getElementById("update_button").style.visibility = 'hidden';
};
})
.catch(error => {
console.error("There was an error fetching data from the API for OTA Data", error);
});
}
@@ -112,10 +131,12 @@ window.addEventListener('DOMContentLoaded', (event) => {
fetchTelemetryData();
fetchElectricData();
fetchConnectionData();
fetchUpdateData();
setInterval(function(){fetchWaterData(gauge);}, 5000);
setInterval(fetchTelemetryData, 5000);
setInterval(fetchElectricData, 5000);
setInterval(fetchConnectionData, 5000);
setInterval(fetchUpdateData, 5000);
});

View File

@@ -29,11 +29,11 @@
</p>
<p>
<label for="level_max">Water max height in cm</label>
<input id="level_max" name="water_level_max" type="number" value="%water_level_min%">
<input id="level_max" name="water_level_max" type="number" value="%water_level_max%">
</p>
<p>
<label for="level_min">Water min height in cm</label>
<input id="level_min" name="water_level_min" type="number" value="%water_level_max%">
<input id="level_min" name="water_level_min" type="number" value="%water_level_min%">
</p>
<p>
<label for="liters">Volume in liters</label>
@@ -55,11 +55,11 @@
<p>
<label for="ssid">SSID</label>
<input id="ssid" name="ssid" type="text" value="%sensor_range%">
<input id="ssid" name="ssid" type="text" value="%ssid%">
</p>
<p>
<label for="wifi_password">Password</label>
<input id="wifi_password" name="wifi_password" type="password" value="%sensor_range%">
<input id="wifi_password" name="wifi_password" type="password">
</p>
<p>

View File

@@ -42,6 +42,10 @@
<td>Current: </td>
<td id="current">WAITING</td>
</tr>
<tr>
<td>Shunt Voltage: </td>
<td id="shunt_voltage">WAITING</td>
</tr>
</tbody>
</table>
</div>
@@ -68,6 +72,28 @@
</tbody>
</table>
</div>
<!--Update card-->
<div class="card">
<header>
<h4>Update Status</h4>
</header>
<table class="tg">
<thead></thead>
<tbody>
<tr>
<td>Current Version: </td>
<td id="current_fw">WAITING</td>
</tr>
<tr>
<td>Newest Version: </td>
<td id="server_fw">WAITING</td>
</tr>
<tr>
<td><a class="button outline" href="/run_ota_update" id="update_button">UPDATE NOW</a></td>
</tr>
</tbody>
</table>
</div>
</div>

58
data/update_progress.html Normal file
View File

@@ -0,0 +1,58 @@
<!DOCTYPE html>
<head>
<link rel="stylesheet" href="/chota.css">
</head>
<body>
<div class="container">
<div class="card bd-success">
<header class="is-center">
<h4>Update running</h4>
</header>
<div class="is-center" id="progress">
Running update...
</div>
</div>
</div>
</body>
<script>
const webSocket = new WebSocket('webSocket://' + window.location.host + '/webSocket');
webSocket.onopen = function() {
console.log('WebSocket connection opened.');
};
webSocket.onmessage = function(event) {
console.log('Progress:', event.data);
// Update the progress bar
let progress = parseInt(event.data);
if (progress == -1) {
document.getElementById('progress').textContent = "Upgrade Done, wait for reboot...";
const checkStatus = setInterval(() => {
fetch('/ota_udpate_status')
.then(response => {
if (response.ok) {
clearInterval(checkStatus);
window.location.href = '/';
}
})
.catch(error => console.error('Error checking OTA update status:', error));
}, 1000);
} else {
document.getElementById('progress').textContent = progress + '%';
}
};
webSocket.onerror = function(error) {
console.error('WebSocket error:', error);
};
webSocket.onclose = function() {
console.log('WebSocket connection closed.');
};
</script>

1
data/version Normal file
View File

@@ -0,0 +1 @@
8

38
documentation/old.md Normal file
View File

@@ -0,0 +1,38 @@
extern "C" {
#include "lwip/netif.h"
}
void listNetworkInterfaces() {
esp_netif_t *netif = NULL;
Serial.println("\n=== Listing Network Interfaces ===");
for (netif = esp_netif_next(NULL); netif != NULL; netif = esp_netif_next(netif)) {
const char* if_key = esp_netif_get_ifkey(netif);
const char* if_desc = esp_netif_get_desc(netif);
Serial.printf("Interface Key: %s\n", if_key);
Serial.printf("Description : %s\n", if_desc);
Serial.println("-----------------------------");
}
}
void setEthernetAsDefault() {
logger.log(0, DEBUG, "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
listNetworkInterfaces();
// Attempt to locate the Ethernet network interface.
// (The name may vary—on some systems it might be "eth0")
esp_netif_t* netif = esp_netif_get_handle_from_ifkey("ETH_DEF");
if (netif) {
Serial.println("Netif handle obtained successfully.");
} else {
Serial.println("Failed to obtain netif handle.");
}
struct netif *eth_netif2 = netif_find("ETH_DEF");
if (netif) {
netif_set_default(eth_netif2);
logger.log(0, DEBUG, "Ethernet set as default network interface.");
} else {
logger.log(0, DEBUG, "Could not find Ethernet netif.");
}
}

View File

@@ -23,6 +23,31 @@ uint16_t get_word(uint8_t address, uint8_t reg) {
return (data[1] << 8) | data[0];
}
String INA233::get_device_model() {
char data[7]; // Array size includes space for the null terminator
// Request data from the PMBus device
Wire.beginTransmission(INA233::_address);
Wire.write(0x9A); // Command to read the manufacturer ID
Wire.endTransmission();
Wire.requestFrom(INA233::_address, 7);
if (Wire.available() == 7) {
uint8_t i = Wire.read();
data[0] = Wire.read();
data[1] = Wire.read();
data[2] = Wire.read();
data[3] = Wire.read();
data[4] = Wire.read();
data[5] = Wire.read();
data[6] = '\0'; // Null-terminate the string
} else {
return String("");
}
return String(data);
}
void sendWord(uint8_t deviceAddress, uint8_t registerAddress, uint16_t value) {
Wire.beginTransmission(deviceAddress);
@@ -32,6 +57,13 @@ void sendWord(uint8_t deviceAddress, uint8_t registerAddress, uint16_t value) {
Wire.endTransmission();
}
void sendByte(uint8_t deviceAddress, uint8_t registerAddress, uint8_t value) {
Wire.beginTransmission(deviceAddress);
Wire.write(registerAddress); // Send the register address
Wire.write((uint8_t)value); // Send the low byte first
Wire.endTransmission();
}
INA233::INA233(const uint8_t address, TwoWire *wire)
{
_address = address;
@@ -85,7 +117,8 @@ float INA233::getBusVoltage() {
float INA233::getShuntVoltage() {
uint16_t rawVoltage = get_word(INA233::_address, REGISTER_READ_VSHUNT);
float voltage = rawVoltage * pow(10,-4);
float voltage = rawVoltage * 2.5e-6;
return voltage;
}
@@ -149,4 +182,12 @@ void INA233::setShuntVoltageConversionTime(ConversionTime conversion_time) {
uint16_t INA233::getConfigRegister() {
return get_word(INA233::_address, REGISTER_CONFIGURATION);
}
void INA233::reset() {
sendByte(INA233::_address, 0x12, 0x00);
}
void INA233::setCalibrationRegister(int value) {
sendWord(INA233::_address, 0xD4, value);
}

View File

@@ -7,6 +7,7 @@
#define REGISTER_READ_VIN 0x88
#define REGISTER_READ_VSHUNT 0xD1
#define REGISTER_CONFIGURATION 0xD0
#define REGISTER_READ_IIN 0x89
enum AveragingMode {
averages_1 = B000,
@@ -32,20 +33,25 @@ enum ConversionTime {
class INA233{
public:
INA233(uint8_t addr, TwoWire *wire = &Wire);
bool begin(const uint8_t sda, const uint8_t scl);
String get_device_model();
INA233(uint8_t addr, TwoWire* wire = &Wire);
bool begin(const uint8_t sda, const uint8_t scl);
float getBusVoltage(void);
float getShuntVoltage_mV(void);
float getShuntVoltage(void);
float getBusVoltage(void);
float getShuntVoltage_mV(void);
float getShuntVoltage(void);
void setAveragingMode(AveragingMode);
void setBusVoltageConversionTime(ConversionTime);
void setShuntVoltageConversionTime(ConversionTime);
uint16_t getConfigRegister();
void setAveragingMode(AveragingMode);
void setBusVoltageConversionTime(ConversionTime);
void setShuntVoltageConversionTime(ConversionTime);
bool isConnected(void);
uint16_t getConfigRegister();
void reset();
void setCalibrationRegister(int value);
bool isConnected(void);
private:
float _current_LSB;

View File

@@ -5,16 +5,16 @@
#include "Arduino.h"
#include <ArduinoJson.h>
#include <HTTPClient.h>
#include <vector>
#include <ArduinoLog.h>
#include <Elog.h>
#include <HTTPUpdate.h>
OTA::OTA(String server_url, String currentVersion, String currentDeviceConfiguration) {
OTA::OTA(String server_url, Version currentVersion, String currentDeviceConfiguration) {
_serverUrl = server_url;
_currentVersion = parseVersion(currentVersion.c_str());
_currentVersion = currentVersion;
_current_device_configuration = currentDeviceConfiguration;
_current_device_configuration.toLowerCase();
}
@@ -22,12 +22,14 @@ Firmware OTA::getLatestVersionOnServer() {
HTTPClient http;
http.begin(_serverUrl);
int httpCode = http.GET();
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, DEBUG, "Payload: %s", payload.c_str());
DynamicJsonDocument doc(4096);
DeserializationError error = deserializeJson(doc, payload);
@@ -41,13 +43,19 @@ Firmware OTA::getLatestVersionOnServer() {
std::vector<Configuration> configs;
for (JsonObject config : doc["Configurations"].as<JsonArray>()) {
if (config.containsKey("Version") && config.containsKey("URL")) {
configs.push_back(Configuration{
parseVersion(config["Version"]),
config["URL"],
config["Board"],
config["Configuration"]
});
if (config.containsKey("Version") && config.containsKey("URL") && config.containsKey("Config")) {
String deviceConfig = config["Config"].as<String>();
deviceConfig.toLowerCase();
if (deviceConfig == _current_device_configuration) {
configs.push_back(Configuration{
parseVersion(config["Version"]),
config["URL"],
config["Board"],
deviceConfig
});
} else {
logger.log(0, DEBUG, "Configuration %s does not match current device configuration %s", deviceConfig.c_str(), _current_device_configuration.c_str());
}
}
}
@@ -55,7 +63,13 @@ Firmware OTA::getLatestVersionOnServer() {
return createErrorResponse("No valid configuration found in the JSON response");
}
Configuration latest = getLatestConfiguration(configs.data(), configs.size());
if (!isVersionNewer(_currentVersion, latest.version)) {
logger.log(0, DEBUG, "No newer version found. Server version: %d.%d.%d", latest.version.major, latest.version.minor, latest.version.patch);
}
return Firmware{
latest.version,
latest.url,
@@ -73,32 +87,80 @@ Firmware OTA::createErrorResponse(const String& errorMsg) {
};
}
void OTA::run_ota_update(String url) {
Log.verbose("Starting OTA upgrade");
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, DEBUG, "Starting OTA upgrade");
HTTPUpdate httpUpdate;
httpUpdate.onStart(update_started);
httpUpdate.onEnd(update_finished);
httpUpdate.onProgress(update_progress);
httpUpdate.onError(update_error);
Serial.println("RUNNING OTA");
WiFiClientSecure client;
client.setInsecure();
t_httpUpdate_return ret = httpUpdate.update(client, "https://iot.tobiasmaier.me/firmware/waterlevel/INA233/1_1_1.bin");
// t_httpUpdate_return ret = httpUpdate.update(client, "https://iot.tobiasmaier.me", 443, "/firmware/waterlevel/INA233/1_0_1.bin");
httpUpdate.onStart(callback_started);
httpUpdate.onEnd(callback_finished);
httpUpdate.onProgress(callback_progress);
httpUpdate.onError(callback_error);
logger.log(0, DEBUG, "Defined callbacks, Starting update now");
t_httpUpdate_return ret;
if (url.startsWith("https")) {
logger.log(0, DEBUG, "HTTPS URL");
WiFiClientSecure client;
client.setInsecure();
ret = httpUpdate.update(client, url);
} else if (url.startsWith("http")) {
logger.log(0, DEBUG, "HTTP URL");
WiFiClient client;
ret = httpUpdate.update(client, url);
} else {
logger.log(0, ERROR, "URL is not valid: \n%s", url.c_str());
}
switch (ret) {
case HTTP_UPDATE_FAILED:
Serial.printf("HTTP_UPDATE_FAILED Error (%d): %s\n", httpUpdate.getLastError(), httpUpdate.getLastErrorString().c_str());
break;
logger.log(0, ERROR, "HTTP_UPDATE_FAILED Error (%d): %s\n", httpUpdate.getLastError(), httpUpdate.getLastErrorString().c_str());
break;
case HTTP_UPDATE_NO_UPDATES:
Serial.println("HTTP_UPDATE_NO_UPDATES");
break;
logger.log(0, ERROR, "HTTP_UPDATE_NO_UPDATES");
break;
case HTTP_UPDATE_OK:
Serial.println("HTTP_UPDATE_OK");
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, 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, DEBUG, "Defined callbacks, Starting update now");
t_httpUpdate_return ret;
if (url.startsWith("https")) {
logger.log(0, DEBUG, "HTTPS URL");
WiFiClientSecure client;
client.setInsecure();
ret = httpUpdate.updateSpiffs(client, url);
} else if (url.startsWith("http")) {
logger.log(0, DEBUG, "HTTP URL");
WiFiClient client;
ret = httpUpdate.updateSpiffs(client, url);
} else {
logger.log(0, ERROR, "URL is not valid: \n%s", url.c_str());
}
switch (ret) {
case HTTP_UPDATE_FAILED:
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, ERROR, "HTTP_UPDATE_NO_UPDATES");
break;
case HTTP_UPDATE_OK:
logger.log(0, DEBUG, "SPIFFS Update done");
break;
}
}

View File

@@ -7,15 +7,17 @@
#include <Arduino.h>
#endif
#pragma once
class OTA {
public:
OTA(String server_url, String currentVersion, String currentDeviceConfiguration);
OTA(String server_url, Version currentVersion, String currentDeviceConfiguration);
Firmware getLatestVersionOnServer();
bool checkForUpdate();
private:
bool _isHTTPS = false;
String _serverUrl;
@@ -24,4 +26,7 @@ class OTA {
Firmware 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);
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);
#endif

View File

@@ -30,4 +30,13 @@ Configuration getLatestConfiguration(Configuration *configs, int count) {
}
}
return latest;
}
bool isVersionNewer(Version oldVersion, Version newVersion) {
if (newVersion.major > oldVersion.major ||
(newVersion.major == oldVersion.major && newVersion.minor > oldVersion.minor) ||
(newVersion.major == oldVersion.major && newVersion.minor == oldVersion.minor && newVersion.patch > oldVersion.patch)) {
return true;
}
return false;
}

View File

@@ -5,6 +5,8 @@
#include <WString.h>
#endif
#pragma once
struct Version {
int major;
int minor;
@@ -26,4 +28,5 @@ struct Configuration {
};
Version parseVersion(const char *versionStr);
Configuration getLatestConfiguration(Configuration *configs, int count);
Configuration getLatestConfiguration(Configuration *configs, int count);
bool isVersionNewer(Version oldVersion, Version newVersion);

View File

@@ -19,13 +19,14 @@ monitor_speed = 115200
lib_deps =
ottowinter/ESPAsyncWebServer-esphome@^3.3.0
bblanchon/ArduinoJson@^6.21.3
jsc/ArduinoLog
fetchOTA
INA322
INA233
ESP32Ping
https://github.com/tobimai/elog.git#fix-syslog
board_build.partitions = default.csv
upload_protocol = espota
upload_port = 192.168.5.181
build_flags = -Wall -Wextra
upload_port = 192.168.5.205
build_flags = -Wall -Wextra -DLOGGING_SPIFFS_DISABLE -DLOGGING_SD_DISABLE
[env:ESP32_INA226]
platform = espressif32
@@ -37,13 +38,16 @@ lib_deps =
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.5.181
build_flags = -Wall -Wextra -DUSE_INA226
upload_port = 192.168.4.18
build_flags = -Wall -Wextra -DUSE_INA226 -DLOGGING_SPIFFS_DISABLE -DLOGGING_SD_DISABLE
[env:native]
platform = native
build_flags = -DUNIT_TEST -Ilib/fetchOTA/
lib_deps =
fetchOTA
fetchOTA
arduino-libraries/ArduinoHttpClient@^0.6.1

View File

@@ -1,7 +1,8 @@
#include "leds.h"
#include <Arduino.h>
#include <ArduinoLog.h>
#include <Elog.h>
#include "../tools/tools.h"
#include <tools/log.h>
extern ActiveErrors active_errors;
extern WaterData water_data;
@@ -72,20 +73,22 @@ void display_task(void* parameter)
// We have no error, refresh status display and wait half a second
display_percentage(water_data.percentage);
} else {
Log.verbose("Error detected");
// 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);

View File

@@ -1,10 +1,13 @@
// Define keys to prevent typos
#include <utils.h>
#define ssid_key "ssid"
#define wifi_password_key "wifi_password"
#define level_sensor_range_key "sensor_range"
#define water_level_min_key "water_level_min"
#define water_level_max_key "water_level_max"
#define water_volume_key "water_volume"
#define current_version Version{0, 0, 2}
#define current_software_version Version{1, 3, 0}
#define REQUIRED_SPIFFS_VERSION Version{8, 0, 0}
#define RESISTOR_VALUE 4

View File

@@ -7,4 +7,6 @@ DeviceTelemetry telemetry;
SensorData shunt_data;
WaterData water_data;
OTAStatus ota_status;
ActiveErrors active_errors = { false, false, false, false, false, false };

View File

@@ -45,4 +45,5 @@ struct OTAStatus {
Version current_version;
Version latest_version;
int update_progress;
String update_url;
};

View File

@@ -8,7 +8,7 @@
#include "AsyncJson.h"
#include <ArduinoJson.h>
#include <ArduinoLog.h>
#include <Elog.h>
#include <ArduinoOTA.h>
@@ -24,6 +24,11 @@
#include "networking/json_builder.h"
#include "networking/responses.h"
#include <fetchOTA.h>
#include <ESP32Ping.h>
#include "time.h"
#include "tools/log.h"
#define MYLOG 0
Preferences prefs;
@@ -35,44 +40,19 @@ extern SensorData shunt_data;
extern "C" int rom_phy_get_vdd33();
Version current_spiffs_version;
AsyncWebServer server(80);
AsyncWebSocket webSocket("/webSocket");
#define FORMAT_LITTLEFS_IF_FAILED true
void update_started() {
Serial.println("CALLBACK: HTTP update process started");
}
void update_finished() {
Serial.println("CALLBACK: HTTP update process finished");
}
void update_progress(int cur, int total) {
Serial.printf("CALLBACK: HTTP update process at %d of %d bytes...\n", cur, total);
}
void update_error(int err) {
Serial.printf("CALLBACK: HTTP update fatal error code %d\n", err);
}
void run_ota(void* parameter) {
OTA ota("https://iot.tobiasmaier.me/firmware/waterlevel", "1.1.1", "INA233");
Firmware fw = ota.getLatestVersionOnServer();
Log.verbose("we are done");
Serial.printf("Firmware Info: Valid: %d, Version: %d.%d.%d, URL: %s\n", fw.valid, fw.version.major, fw.version.minor, fw.version.patch, fw.url.c_str());
vTaskDelete(NULL);
}
void setup()
{
{
logger.registerSerial(MYLOG, DEBUG, "tst");
prefs.begin("waterlevel", false);
Serial.begin(115200);
Log.begin(LOG_LEVEL_VERBOSE, &Serial);
Log.setSuffix(printSuffix);
Log.setPrefix(print_prefix);
Log.verbose("Init LEDs");
LOG(DEBUG, "Init LEDs");
pinMode(LED_1, OUTPUT);
pinMode(LED_2, OUTPUT);
pinMode(LED_3, OUTPUT);
@@ -84,17 +64,30 @@ void setup()
display_error_code(17);
init_sensor();
Log.verbose("Beginning SPIFFS");
LOG(DEBUG, "Beginning SPIFFS");
SPIFFS.begin(true);
Log.verbose("SPIFFS initialized");
// Read the current SPIFFS version from the versions file on the spiffs
File file = SPIFFS.open("/version", FILE_READ);
if (!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(DEBUG, "Current SPIFFS Version: %d.%d.%d", current_spiffs_version.major, current_spiffs_version.minor, current_spiffs_version.patch);
}
LOG(DEBUG, "SPIFFS initialized");
display_error_code(19);
Log.verbose("Begin INA");
LOG(DEBUG, "Begin INA");
display_error_code(22);
/////////////////////////////// ROUTES ///////////////////////////////
Log.verbose("Route Setup");
LOG(DEBUG, "Route Setup");
// Normal HTML stuff
server.on("/", HTTP_GET, [](AsyncWebServerRequest* request) { request->send(SPIFFS, "/status.html", "text/html", false, processor); });
@@ -105,13 +98,15 @@ void setup()
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.verbose("Updating SSID config");
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());
@@ -120,14 +115,14 @@ void setup()
} else {
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
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.verbose("Updating Sensor config");
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);
@@ -149,52 +144,44 @@ void setup()
// Convert the C string to a float using strtod
float value = strtod(paramCStr, &endPtr);
Log.verbose("range_float:%D:", range_float);
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.verbose("range_float_after:%D:", prefs.getFloat(level_sensor_range_key, -1.0));
LOG(DEBUG, "range_float_after:%D:", prefs.getFloat(level_sensor_range_key, -1.0));
} else {
Log.verbose("!!!! FAIL lo");
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.verbose("POST[%s]: %s\n", p->name().c_str(), p->value().c_str());
LOG(DEBUG, "POST[%s]: %s\n", p->name().c_str(), p->value().c_str());
} else if (p->isPost()) {
Log.verbose("POST[%s]: %s\n", p->name().c_str(), p->value().c_str());
LOG(DEBUG, "POST[%s]: %s\n", p->name().c_str(), p->value().c_str());
} else {
Log.verbose("GET[%s]: %s\n", p->name().c_str(), p->value().c_str());
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
});
server.on("/ota", HTTP_GET, [](AsyncWebServerRequest* request) {
Serial.println("OTA Task start");
xTaskCreate(run_ota, "OTATask", 1024 * 8, NULL, 1, NULL);
request->send(200, "text/plain", "OTA done");
});
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(23);
display_error_code(24);
Log.verbose("OTA Setup");
LOG(DEBUG, "OTA Setup");
ArduinoOTA
.onStart([]() {
String type;
@@ -204,39 +191,103 @@ void setup()
type = "filesystem";
// NOTE: if updating SPIFFS this would be the place to unmount SPIFFS using SPIFFS.end()
Log.verbose("Start updating %s", type); })
.onEnd([]() { Log.verbose("\nEnd"); })
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.verbose("Auth Failed");
else if (error == OTA_BEGIN_ERROR) Log.verbose("Begin Failed");
else if (error == OTA_CONNECT_ERROR) Log.verbose("Connect Failed");
else if (error == OTA_RECEIVE_ERROR) Log.verbose("Receive Failed");
else if (error == OTA_END_ERROR) Log.verbose("End Failed"); });
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);
xTaskCreate(wifi_task, "WiFiTask", 10000, NULL, 1, NULL);
delay(250);
// Create Etnernet task and wait a second to see if there is connection
LOG(DEBUG, "Started Ethernet, waiting");
delay(2000);
Log.verbose("Starting webserver");
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", 2048, 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()
{
ArduinoOTA.handle();
delay(1000);
}
}

View File

@@ -1,5 +1,5 @@
#include "json_builder.h"
#include <ArduinoLog.h>
#include <Elog.h>
extern WaterData water_data;
extern DeviceTelemetry telemetry;
@@ -41,5 +41,15 @@ StaticJsonDocument<256> build_network_json(NetworkData wired, NetworkData wirele
doc["ethernet"]["rssi"] = wired.rssi;
doc["ethernet"]["link"] = wired.link;
return doc;
}
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;
return doc;
}

View File

@@ -4,4 +4,5 @@
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<256> build_network_json(NetworkData wired, NetworkData wireless);
StaticJsonDocument<128> build_ota_json(OTAStatus status);

View File

@@ -1,9 +1,10 @@
#include <ArduinoLog.h>
#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>
int64_t mac_address = ESP.getEfuseMac();
uint8_t failed_connection_attempts = 0;
@@ -34,21 +35,21 @@ const char * get_hostname(HostnameType host_type) {
void wifi_task(void* parameter)
{
Log.verbose("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.verbose("Failed to connecto to currently saved SSID, starting SoftAP");
LOG(DEBUG, "Failed to connecto to currently saved SSID, starting SoftAP");
} else {
Log.verbose("No SSID saved, starting SoftAP");
LOG(DEBUG, "No SSID saved, starting SoftAP");
}
String ap_ssid = get_hostname(Wireless);
WiFi.softAP(ap_ssid, "");
Log.verbose("[WIFI_TASK] 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) {
@@ -64,11 +65,11 @@ void wifi_task(void* parameter)
wifi_data.network_name = WiFi.SSID();
wifi_data.ip_address = WiFi.localIP().toString();
// Log.verbose("RSSI: %F, IP Address, %p, SSID: %s", float(WiFi.RSSI()), WiFi.localIP(), prefs.getString(ssid_key, "NOSSID"));
// Serial.println(WiFi.channel());
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 {
Log.verbose("Connecting to %s using password %s", prefs.getString(ssid_key, ""), prefs.getString(wifi_password_key, ""));
LOG(DEBUG, "Connecting to %s using password %s", prefs.getString(ssid_key, ""), prefs.getString(wifi_password_key, ""));
WiFi.mode(WIFI_STA);
WiFi.begin(prefs.getString(ssid_key, ""), prefs.getString(wifi_password_key, ""));
failed_connection_attempts++;
@@ -80,14 +81,15 @@ void wifi_task(void* parameter)
void ethernet_task(void* parameter)
{
Log.verbose("Connecting Ethernet");
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();
ethernet_data.ip_address = ETH.localIP().toString();
// Log.verbose("Ethernet RSSI: %F, IP Address, %s, LINK: %s", float(ethernet_data.rssi), ethernet_data.ip_address, String(ethernet_data.link));
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);
}
}

View File

@@ -4,14 +4,17 @@
#include <ESPAsyncWebServer.h>
#include "AsyncJson.h"
#include <ArduinoJson.h>
#include <ArduinoLog.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;
@@ -26,6 +29,17 @@ void setup_api_endpoints(){
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);
@@ -36,4 +50,27 @@ void setup_api_endpoints(){
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);
});
}

View File

@@ -1,6 +1,6 @@
#include "../global_data/defines.h"
#include <Preferences.h>
#include <ArduinoLog.h>
#include <Elog.h>
#include "Wire.h"
#include "../global_data/global_data.h"
@@ -12,6 +12,10 @@ INA226 ina_sensor(0x40);
#include <INA233.h>
INA233 ina_sensor(0x40);
#endif
#include <tools/log.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
extern Preferences prefs;
extern WaterData water_data;
@@ -29,9 +33,11 @@ void init_sensor(){
ina_sensor.setShuntVoltageConversionTime(7);
ina_sensor.setAverage(4);
#else
ina_sensor.reset();
ina_sensor.setShuntVoltageConversionTime(conversion_time_8244uS);
ina_sensor.setBusVoltageConversionTime(conversion_time_8244uS);
ina_sensor.setAveragingMode(averages_128);
ina_sensor.setCalibrationRegister(128);
#endif
}
@@ -39,10 +45,16 @@ void read_sensor_task(void* parameter)
{
while (true) {
// Get Values from sensor
#ifndef USE_INA226
String chip_id = ina_sensor.get_device_model();
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(DEBUG, "RAW Shunt voltage: %F mV", ina_sensor.getShuntVoltage_mV());
float shunt_current = shunt_voltage / RESISTOR_VALUE;
// Get values from storage
@@ -61,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.verbose("max_water_level_mA: %F", max_water_level_mA);
// Log.verbose("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;
@@ -72,7 +84,7 @@ void read_sensor_task(void* parameter)
// Raw unrounded percentage in decimal
float percentage_raw = (shunt_current_over_zero / (max_water_level_mA_over_zero - min_water_level_mA_over_zero));
float percentage_rounded = round(percentage_raw*100);
float percentage_rounded = round(percentage_raw * 10000) / 100;
// Tank volume in liters
float liters_raw = max_liters * percentage_raw;
@@ -82,10 +94,10 @@ void read_sensor_task(void* parameter)
active_errors.current_high = shunt_current > 20.2;
active_errors.voltage_low = bus_voltage < 23;
active_errors.voltage_high = bus_voltage > 25;
// Log.verbose("Shunt current: %F", shunt_current);
// Log.verbose("Shunt voltage: %F", shunt_voltage);
// Log.verbose("Bus voltage: %F", bus_voltage);
// Log.verbose("cm_over_zero: %F", cm_over_zero);
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;

11
src/tools/log.h Normal file
View File

@@ -0,0 +1,11 @@
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#define LOG(LEVEL, FMT, ...) \
do { \
logger.log(0, LEVEL, "[Core: %i][Task: %s][%s] " FMT, \
xPortGetCoreID(), \
pcTaskGetName(xTaskGetCurrentTaskHandle()), \
__FUNCTION__, \
##__VA_ARGS__); \
} while (0)

View File

@@ -1,24 +1,17 @@
#include <Arduino.h>
#include "tools.h"
#include <ArduinoLog.h>
#include <Elog.h>
#include "../global_data/defines.h"
#include <Preferences.h>
#include <fetchOTA.h>
#include <AsyncWebSocket.h>
#include "log.h"
extern Preferences prefs;
extern OTAStatus ota_status;
extern AsyncWebSocket webSocket;
void printSuffix(Print* _logOutput, int logLevel)
{
_logOutput->print(CR);
}
void print_prefix(Print* _logOutput, int logLevel)
{
_logOutput->print("WATERMETER - C");
_logOutput->print(xPortGetCoreID());
_logOutput->print(" - ");
_logOutput->print(pcTaskGetName(xTaskGetCurrentTaskHandle()));
_logOutput->print(" - ");
}
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;
@@ -34,7 +27,114 @@ String processor(const String& var)
return String(prefs.getFloat(water_level_max_key, -1));
} else if (var == water_volume_key) {
return String(prefs.getFloat(water_volume_key, -1));
} else if (var == ssid_key) {
return String(prefs.getString(ssid_key, ""));
}
return String("Test");
}
return String("");
}
// OTA Callbacks
void update_started() {
LOG(DEBUG, "OTA Update started");
ota_status.update_progress = 0;
}
void update_finished() {
LOG(DEBUG, "OTA Update finished");
ota_status.update_progress = -1;
webSocket.textAll(String(-1).c_str());
}
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(DEBUG, "OTA Update progress: %d/%d, %i", cur, total, ota_status.update_progress);
}
webSocket.textAll(String(ota_status.update_progress).c_str());
LOG(DEBUG, "OTA Update progress: %d/%d", cur, total);
}
void update_error(int err) {
LOG(ERROR, "OTA Update error: %d", err);
ota_status.update_progress = -2;
}
void check_update_task(void* parameter) {
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");
}
}
while (true) {
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 {
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 run_ota_update_task(void* parameter) {
TaskArgs_t *args = (TaskArgs_t *) parameter;
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);
}
void onWsEvent(AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventType type,
void *arg, uint8_t *data, size_t len) {
if (type == WS_EVT_CONNECT) {
Serial.println("WebSocket client connected");
} else if (type == WS_EVT_DISCONNECT) {
Serial.println("WebSocket client disconnected");
} else if (type == WS_EVT_DATA) {
// Optionally process data received from the client
}
}

View File

@@ -1,7 +1,18 @@
#include <Arduino.h>
#include "../global_data/global_data.h"
#include <fetchOTA.h>
#include <AsyncWebSocket.h>
void printSuffix(Print* _logOutput, int logLevel);
void print_prefix(Print* _logOutput, int logLevel);
bool is_error(ActiveErrors active_errors);
String processor(const String& var);
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);
typedef struct {
OTAStatus ota_status;
Version spiffs_version;
} TaskArgs_t;

View File

@@ -84,6 +84,48 @@ void test_parse_version_extra_content() {
TEST_ASSERT_EQUAL(0, v.patch);
}
void test_is_version_newer_major() {
Version oldVersion = {1, 3, 4};
Version newVersion = {2, 1, 1};
TEST_ASSERT_TRUE(isVersionNewer(oldVersion, newVersion));
}
void test_is_version_newer_minor() {
Version oldVersion = {1, 0, 8};
Version newVersion = {1, 1, 0};
TEST_ASSERT_TRUE(isVersionNewer(oldVersion, newVersion));
}
void test_is_version_newer_patch() {
Version oldVersion = {1, 1, 1};
Version newVersion = {1, 1, 2};
TEST_ASSERT_TRUE(isVersionNewer(oldVersion, newVersion));
}
void test_is_version_not_newer_same() {
Version oldVersion = {1, 1, 1};
Version newVersion = {1, 1, 1};
TEST_ASSERT_FALSE(isVersionNewer(oldVersion, newVersion));
}
void test_is_version_not_newer_major() {
Version oldVersion = {2, 0, 0};
Version newVersion = {1, 99, 99};
TEST_ASSERT_FALSE(isVersionNewer(oldVersion, newVersion));
}
void test_is_version_not_newer_minor() {
Version oldVersion = {1, 2, 0};
Version newVersion = {1, 1, 99};
TEST_ASSERT_FALSE(isVersionNewer(oldVersion, newVersion));
}
void test_is_version_not_newer_patch() {
Version oldVersion = {1, 1, 2};
Version newVersion = {1, 1, 1};
TEST_ASSERT_FALSE(isVersionNewer(oldVersion, newVersion));
}
int main() {
UNITY_BEGIN();
@@ -96,5 +138,12 @@ int main() {
RUN_TEST(test_parse_version_extra_content);
RUN_TEST(test_parse_version_valid_input_2);
RUN_TEST(test_parse_version_more_missing_parts);
RUN_TEST(test_is_version_newer_major);
RUN_TEST(test_is_version_newer_minor);
RUN_TEST(test_is_version_newer_patch);
RUN_TEST(test_is_version_not_newer_same);
RUN_TEST(test_is_version_not_newer_major);
RUN_TEST(test_is_version_not_newer_minor);
RUN_TEST(test_is_version_not_newer_patch);
UNITY_END();
}