5 Commits

Author SHA1 Message Date
36f5429f11 move all mqtt publishing functions to mqtt module 2026-05-10 14:40:35 +02:00
9846244343 refctor: TankInfo structure (consistent layout)
- fix: use tagged enum serialization for TankError
- fix: rename TankInfo fields for consistent naming (volume_ml, pct, water_temp_c)
- renamed some fields for better clarity on contained value
2026-05-10 14:40:33 +02:00
11084ecf27 refactor: PlantInfo structure (consistent layout)
- fix: use tagged enum serialization for MoistureSensorError and PumpError
- fix: flatten PlantInfo sensors to SensorTelemetry with top-level moisture_pct
2026-05-10 14:40:31 +02:00
be1a10f025 refactor: BatteryInfo structure (consistent layout)
- use tagged enum serialization for BatteryError
- flatten BatteryInfo telemetry with consistent field names and typed error
2026-05-10 14:40:29 +02:00
228fbe7f8d fix: serialize firmware/state as JSON instead of Debug format 2026-05-10 14:40:27 +02:00
6 changed files with 77 additions and 273 deletions

View File

@@ -30,80 +30,59 @@ use core::result::Result::Ok;
use core::sync::atomic::{AtomicBool, Ordering}; use core::sync::atomic::{AtomicBool, Ordering};
use edge_http::io::server::{Connection, Handler, Server}; use edge_http::io::server::{Connection, Handler, Server};
use edge_http::Method; use edge_http::Method;
use edge_nal::io::{Read, Write};
use edge_nal::TcpBind; use edge_nal::TcpBind;
use edge_nal::io::{Read, Write};
use edge_nal_embassy::{Tcp, TcpBuffers}; use edge_nal_embassy::{Tcp, TcpBuffers};
use embassy_net::Stack; use embassy_net::Stack;
use embassy_time::Instant; use embassy_time::Instant;
use log::{error, info}; use log::info;
pub(crate) async fn ota_operations<T, const N: usize>( // fn ota(
conn: &mut Connection<'_, T, { N }>, // request: &mut Request<&mut EspHttpConnection>,
method: Method, // ) -> Result<Option<std::string::String>, anyhow::Error> {
) -> Result<Option<u32>, FatError> // let mut board = BOARD_ACCESS.lock().unwrap();
where // let mut ota = OtaUpdate::begin()?;
T: Read + Write, // log::info!("start ota");
{ //
Ok(match method { // //having a larger buffer is not really faster, requires more stack and prevents the progress bar from working ;)
Method::Options => { // const BUFFER_SIZE: usize = 512;
conn.initiate_response( // let mut buffer: [u8; BUFFER_SIZE] = [0; BUFFER_SIZE];
200, // let mut total_read: usize = 0;
Some("OK"), // let mut lastiter = 0;
&[ // loop {
("Access-Control-Allow-Origin", "*"), // let read = request.read(&mut buffer)?;
("Access-Control-Allow-Headers", "*"), // total_read += read;
("Access-Control-Allow-Methods", "*"), // let to_write = &buffer[0..read];
], // //delay for watchdog and wifi stuff
) // board.board_hal.get_esp().delay.delay_ms(1);
.await?; //
Some(200) // let iter = (total_read / 1024) % 8;
} // if iter != lastiter {
Method::Post => { // board.board_hal.general_fault(iter % 5 == 0);
let mut offset = 0_usize; // for i in 0..PLANT_COUNT {
let mut chunk = 0; // let _ = board.board_hal.fault(i, iter == i);
loop { // }
let buf = read_up_to_bytes_from_request(conn, Some(4096)).await?; // lastiter = iter;
if buf.is_empty() { // }
info!("file request for ota finished"); //
let mut board = BOARD_ACCESS.get().await.lock().await; // ota.write(to_write)?;
board.board_hal.get_esp().finalize_ota().await?; // if read == 0 {
break; // break;
} else { // }
let mut board = BOARD_ACCESS.get().await.lock().await; // }
board.board_hal.progress(chunk as u32).await; // log::info!("wrote bytes ota {total_read}");
// Erase next block if we are at a 4K boundary (including the first block at offset 0) // log::info!("finish ota");
board // let partition = ota.raw_partition();
.board_hal // log::info!("finalizing and changing boot partition to {partition:?}");
.get_esp() //
.write_ota(offset as u32, &buf) // let mut finalizer = ota.finalize()?;
.await?; // log::info!("changing boot partition");
} // board.board_hal.get_esp().set_restart_to_conf(true);
offset += buf.len(); // drop(board);
chunk += 1; // finalizer.set_as_boot_partition()?;
} // anyhow::Ok(None)
BOARD_ACCESS // }
.get() //
.await
.lock()
.await
.board_hal
.clear_progress()
.await;
conn.initiate_response(
200,
Some("OK"),
&[
("Access-Control-Allow-Origin", "*"),
("Access-Control-Allow-Headers", "*"),
("Access-Control-Allow-Methods", "*"),
],
)
.await?;
Some(200)
}
_ => None,
})
}
struct HTTPRequestRouter { struct HTTPRequestRouter {
reboot_now: Arc<AtomicBool>, reboot_now: Arc<AtomicBool>,
@@ -126,12 +105,7 @@ impl Handler for HTTPRequestRouter {
let path = headers.path; let path = headers.path;
let prefix = "/file?filename="; let prefix = "/file?filename=";
let status = if path == "/ota" { let status = if path.starts_with(prefix) {
ota_operations(conn, method).await.map_err(|e| {
error!("Error handling ota: {e}");
e
})?
} else if path.starts_with(prefix) {
file_operations(conn, method, &path, &prefix).await? file_operations(conn, method, &path, &prefix).await?
} else { } else {
match method { match method {

View File

@@ -157,13 +157,7 @@ export interface Moistures {
export interface VersionInfo { export interface VersionInfo {
git_hash: string, git_hash: string,
build_time: string, build_time: string,
current: string, partition: string
slot0_state: string,
slot1_state: string,
heap_total: number,
heap_used: number,
heap_free: number,
heap_max_used: number,
} }
export interface BatteryState { export interface BatteryState {

View File

@@ -31,7 +31,6 @@ import {
FileList, SolarState, PumpTestResult FileList, SolarState, PumpTestResult
} from "./api"; } from "./api";
import {SolarView} from "./solarview"; import {SolarView} from "./solarview";
import {toast} from "./toast";
export class Controller { export class Controller {
loadTankInfo(): Promise<void> { loadTankInfo(): Promise<void> {
@@ -201,22 +200,15 @@ export class Controller {
}, false); }, false);
ajax.addEventListener("load", () => { ajax.addEventListener("load", () => {
controller.progressview.removeProgress("ota_upload") controller.progressview.removeProgress("ota_upload")
const status = ajax.status; controller.reboot();
if (status >= 200 && status < 300) {
controller.reboot();
} else {
const statusText = ajax.statusText || "";
const body = ajax.responseText || "";
toast.error(`OTA update error (${status}${statusText ? ' ' + statusText : ''}): ${body}`);
}
}, false); }, false);
ajax.addEventListener("error", () => { ajax.addEventListener("error", () => {
alert("Error ota")
controller.progressview.removeProgress("ota_upload") controller.progressview.removeProgress("ota_upload")
toast.error("OTA upload failed due to a network error.");
}, false); }, false);
ajax.addEventListener("abort", () => { ajax.addEventListener("abort", () => {
alert("abort ota")
controller.progressview.removeProgress("ota_upload") controller.progressview.removeProgress("ota_upload")
toast.error("OTA upload was aborted.");
}, false); }, false);
ajax.open("POST", PUBLIC_URL + "/ota"); ajax.open("POST", PUBLIC_URL + "/ota");
ajax.send(file); ajax.send(file);

View File

@@ -1,27 +1,23 @@
<style> <style>
.otakey { .otakey{
min-width: 100px; min-width: 100px;
} }
.otavalue{
.otavalue { flex-grow: 1;
flex-grow: 1; }
} .otaform {
min-width: 100px;
.otaform { flex-grow: 1;
min-width: 100px; }
flex-grow: 1; .otachooser {
} min-width: 100px;
width: 100%;
.otachooser { }
min-width: 100px;
width: 100%;
}
</style> </style>
<div class="flexcontainer"> <div class="flexcontainer">
<div class="subtitle"> <div class="subtitle">
Current Firmware Current Firmware
</div> </div>
<button style="margin-left: auto;" type="button" id="refresh_firmware_info">Refresh</button>
</div> </div>
<div class="flexcontainer"> <div class="flexcontainer">
<span class="otakey">Buildtime:</span> <span class="otakey">Buildtime:</span>
@@ -32,46 +28,14 @@
<span class="otavalue" id="firmware_githash"></span> <span class="otavalue" id="firmware_githash"></span>
</div> </div>
<div class="flexcontainer"> <div class="flexcontainer">
<span class="otakey">Partition:</span> <span class="otakey">Partition:</span>
<span class="otavalue" id="firmware_partition"></span> <span class="otavalue" id="firmware_partition"></span>
</div>
<div class="flexcontainer">
<span class="otakey">State0:</span>
<span class="otavalue" id="firmware_state0"></span>
</div>
<div class="flexcontainer">
<span class="otakey">State1:</span>
<span class="otavalue" id="firmware_state1"></span>
</div> </div>
<div class="flexcontainer"> <div class="flexcontainer">
<form class="otaform" id="upload_form" method="post"> <form class="otaform" id="upload_form" method="post">
<input class="otachooser" type="file" name="file1" id="firmware_file"><br> <input class="otachooser" type="file" name="file1" id="firmware_file"><br>
</form> </form>
</div> </div>
<div class="flexcontainer">
<div class="subtitle">
Heap Memory
</div>
<div></div>
</div>
<div class="flexcontainer">
<span class="otakey">Free:</span>
<span class="otavalue" id="heap_free"></span>
</div>
<div class="flexcontainer">
<span class="otakey">Used:</span>
<span class="otavalue" id="heap_used"></span>
</div>
<div class="flexcontainer">
<span class="otakey">Total:</span>
<span class="otavalue" id="heap_total"></span>
</div>
<div class="flexcontainer">
<span class="otakey">Peak used:</span>
<span class="otavalue" id="heap_max_used"></span>
</div>
<div class="display:flex"> <div class="display:flex">
<button style="margin-left: 16px; margin-top: 8px;" class="col-6" type="button" id="test">Self-Test</button> <button style="margin-left: 16px; margin-top: 8px;" class="col-6" type="button" id="test">Self-Test</button>
</div> </div>

View File

@@ -1,37 +1,21 @@
import {Controller} from "./main"; import { Controller } from "./main";
import {VersionInfo} from "./api"; import {VersionInfo} from "./api";
function fmtBytes(n: number): string {
return `${n} B (${(n / 1024).toFixed(1)} KiB)`;
}
export class OTAView { export class OTAView {
readonly file1Upload: HTMLInputElement; readonly file1Upload: HTMLInputElement;
readonly firmware_buildtime: HTMLDivElement; readonly firmware_buildtime: HTMLDivElement;
readonly firmware_githash: HTMLDivElement; readonly firmware_githash: HTMLDivElement;
readonly firmware_partition: HTMLDivElement; readonly firmware_partition: HTMLDivElement;
readonly firmware_state0: HTMLDivElement;
readonly firmware_state1: HTMLDivElement;
readonly heap_free: HTMLDivElement;
readonly heap_used: HTMLDivElement;
readonly heap_total: HTMLDivElement;
readonly heap_max_used: HTMLDivElement;
constructor(controller: Controller) { constructor(controller: Controller) {
(document.getElementById("firmwareview") as HTMLElement).innerHTML = require("./ota.html") (document.getElementById("firmwareview") as HTMLElement).innerHTML = require("./ota.html")
let test = document.getElementById("test") as HTMLButtonElement; let test = document.getElementById("test") as HTMLButtonElement;
let refresh = document.getElementById("refresh_firmware_info") as HTMLButtonElement;
this.firmware_buildtime = document.getElementById("firmware_buildtime") as HTMLDivElement; this.firmware_buildtime = document.getElementById("firmware_buildtime") as HTMLDivElement;
this.firmware_githash = document.getElementById("firmware_githash") as HTMLDivElement; this.firmware_githash = document.getElementById("firmware_githash") as HTMLDivElement;
this.firmware_partition = document.getElementById("firmware_partition") as HTMLDivElement; this.firmware_partition = document.getElementById("firmware_partition") as HTMLDivElement;
this.firmware_state0 = document.getElementById("firmware_state0") as HTMLDivElement;
this.firmware_state1 = document.getElementById("firmware_state1") as HTMLDivElement;
this.heap_free = document.getElementById("heap_free") as HTMLDivElement;
this.heap_used = document.getElementById("heap_used") as HTMLDivElement;
this.heap_total = document.getElementById("heap_total") as HTMLDivElement;
this.heap_max_used = document.getElementById("heap_max_used") as HTMLDivElement;
const file = document.getElementById("firmware_file") as HTMLInputElement; const file = document.getElementById("firmware_file") as HTMLInputElement;
this.file1Upload = file this.file1Upload = file
@@ -47,21 +31,11 @@ export class OTAView {
test.onclick = () => { test.onclick = () => {
controller.selfTest(); controller.selfTest();
} }
refresh.onclick = () => {
controller.version();
}
} }
setVersion(versionInfo: VersionInfo) { setVersion(versionInfo: VersionInfo) {
this.firmware_buildtime.innerText = versionInfo.build_time; this.firmware_buildtime.innerText = versionInfo.build_time;
this.firmware_githash.innerText = versionInfo.git_hash; this.firmware_githash.innerText = versionInfo.git_hash;
this.firmware_partition.innerText = versionInfo.current; this.firmware_partition.innerText = versionInfo.partition;
this.firmware_state0.innerText = versionInfo.slot0_state;
this.firmware_state1.innerText = versionInfo.slot1_state;
this.heap_free.innerText = fmtBytes(versionInfo.heap_free);
this.heap_used.innerText = fmtBytes(versionInfo.heap_used);
this.heap_total.innerText = fmtBytes(versionInfo.heap_total);
this.heap_max_used.innerText = fmtBytes(versionInfo.heap_max_used);
} }
} }

View File

@@ -1,94 +0,0 @@
class ToastService {
private container: HTMLElement;
private stylesInjected = false;
constructor() {
this.container = this.ensureContainer();
this.injectStyles();
}
info(message: string, timeoutMs: number = 5000) {
const el = this.createToast(message, 'info');
this.container.appendChild(el);
// Auto-dismiss after timeout
const timer = window.setTimeout(() => this.dismiss(el), timeoutMs);
// Dismiss on click immediately
el.addEventListener('click', () => {
window.clearTimeout(timer);
this.dismiss(el);
});
}
error(message: string) {
console.error(message);
const el = this.createToast(message, 'error');
this.container.appendChild(el);
// Only dismiss on click
el.addEventListener('click', () => this.dismiss(el));
}
private dismiss(el: HTMLElement) {
if (!el.parentElement) return;
el.parentElement.removeChild(el);
}
private createToast(message: string, type: 'info' | 'error'): HTMLElement {
const div = document.createElement('div');
div.className = `toast ${type}`;
div.textContent = message;
div.setAttribute('role', 'status');
div.setAttribute('aria-live', 'polite');
return div;
}
private ensureContainer(): HTMLElement {
let container = document.getElementById('toast-container');
if (!container) {
container = document.createElement('div');
container.id = 'toast-container';
document.body.appendChild(container);
}
return container;
}
private injectStyles() {
if (this.stylesInjected) return;
const style = document.createElement('style');
style.textContent = `
#toast-container {
position: fixed;
top: 12px;
right: 12px;
display: flex;
flex-direction: column;
gap: 8px;
z-index: 9999;
}
.toast {
max-width: 320px;
padding: 10px 12px;
border-radius: 6px;
box-shadow: 0 2px 6px rgba(0,0,0,0.2);
cursor: pointer;
user-select: none;
font-family: sans-serif;
font-size: 14px;
line-height: 1.3;
}
.toast.info {
background-color: #d4edda; /* green-ish */
color: #155724;
border-left: 4px solid #28a745;
}
.toast.error {
background-color: #f8d7da; /* red-ish */
color: #721c24;
border-left: 4px solid #dc3545;
}
`;
document.head.appendChild(style);
this.stylesInjected = true;
}
}
export const toast = new ToastService();