4 Commits

18 changed files with 389 additions and 619 deletions

9
.gitignore vendored
View File

@@ -8,15 +8,6 @@ target
Cargo.lock Cargo.lock
node_modules/ node_modules/
rust/src/webserver/bundle.js rust/src/webserver/bundle.js
rust/src/webserver/bundle.js.gz
rust/src/webserver/index.html rust/src/webserver/index.html
rust/src/webserver/index.html.gz
rust/src_webpack/bundle.js
rust/src_webpack/bundle.js.gz
rust/src_webpack/index.html
rust/src_webpack/index.html.gz
rust/build/ rust/build/
rust/image.bin rust/image.bin
rust/target/
rust/Cargo.lock
rust/src_webpack/node_modules/

View File

@@ -1,22 +0,0 @@
#!/usr/bin/env bash
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
"${SCRIPT_DIR}/build_website.sh"
cargo build --release
espflash save-image \
--bootloader "${SCRIPT_DIR}/bootloader.bin" \
--partition-table "${SCRIPT_DIR}/partitions.csv" \
--chip esp32c6 \
target/riscv32imac-unknown-none-elf/release/plant-ctrl2 \
"${SCRIPT_DIR}/image.bin"
espflash flash --monitor \
--bootloader "${SCRIPT_DIR}/bootloader.bin" \
--chip esp32c6 \
--baud 921600 \
--partition-table "${SCRIPT_DIR}/partitions.csv" \
target/riscv32imac-unknown-none-elf/release/plant-ctrl2

View File

@@ -1,3 +1,5 @@
use std::process::Command;
use vergen::EmitBuilder; use vergen::EmitBuilder;
fn linker_be_nice() { fn linker_be_nice() {
@@ -48,9 +50,72 @@ fn linker_be_nice() {
} }
fn main() { fn main() {
webpack();
linker_be_nice(); linker_be_nice();
// Non-existent path causes Cargo to always re-run this script,
// keeping VERGEN_BUILD_TIMESTAMP fresh on every build.
println!("cargo:rerun-if-changed=ALWAYS_REBUILD_SENTINEL");
let _ = EmitBuilder::builder().all_git().all_build().emit(); let _ = EmitBuilder::builder().all_git().all_build().emit();
} }
fn webpack() {
//println!("cargo:rerun-if-changed=./src/src_webpack");
Command::new("rm")
.arg("./src/webserver/bundle.js.gz")
.output()
.unwrap();
match Command::new("cmd").spawn() {
Ok(_) => {
println!("Assuming build on windows");
let output = Command::new("cmd")
.arg("/K")
.arg("npx")
.arg("webpack")
.current_dir("./src_webpack")
.output()
.unwrap();
println!("status: {}", output.status);
println!("stdout: {}", String::from_utf8_lossy(&output.stdout));
println!("stderr: {}", String::from_utf8_lossy(&output.stderr));
assert!(output.status.success());
// move webpack results to rust webserver src
let _ = Command::new("cmd")
.arg("/K")
.arg("move")
.arg("./src_webpack/bundle.js.gz")
.arg("./src/webserver")
.output()
.unwrap();
let _ = Command::new("cmd")
.arg("/K")
.arg("move")
.arg("./src_webpack/index.html.gz")
.arg("./src/webserver")
.output()
.unwrap();
}
Err(_) => {
println!("Assuming build on linux");
let output = Command::new("npx")
.arg("webpack")
.current_dir("./src_webpack")
.output()
.unwrap();
println!("status: {}", output.status);
println!("stdout: {}", String::from_utf8_lossy(&output.stdout));
println!("stderr: {}", String::from_utf8_lossy(&output.stderr));
assert!(output.status.success());
// move webpack results to rust webserver src
let _ = Command::new("mv")
.arg("./src_webpack/bundle.js.gz")
.arg("./src/webserver")
.output()
.unwrap();
let _ = Command::new("mv")
.arg("./src_webpack/index.html.gz")
.arg("./src/webserver")
.output()
.unwrap();
}
}
}

View File

@@ -1,21 +0,0 @@
#!/usr/bin/env bash
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
WEBPACK_DIR="${SCRIPT_DIR}/src_webpack"
WEBSERVER_DIR="${SCRIPT_DIR}/src/webserver"
rm -f "${WEBSERVER_DIR}/index.html.gz"
rm -f "${WEBSERVER_DIR}/bundle.js.gz"
rm -f "${WEBPACK_DIR}/index.html.gz"
rm -f "${WEBPACK_DIR}/bundle.js.gz"
rm -f "${WEBPACK_DIR}/index.html"
rm -f "${WEBPACK_DIR}/bundle.js"
pushd "${WEBPACK_DIR}"
npm install
npx webpack build
cp index.html.gz "${WEBSERVER_DIR}/index.html.gz"
cp bundle.js.gz "${WEBSERVER_DIR}/bundle.js.gz"
popd

View File

@@ -1,7 +0,0 @@
#!/usr/bin/env bash
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cargo espflash erase-parts otadata --partition-table "${SCRIPT_DIR}/partitions.csv"

View File

@@ -1,15 +0,0 @@
#!/usr/bin/env bash
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
"${SCRIPT_DIR}/build_website.sh"
cargo build --release
espflash flash --monitor \
--bootloader "${SCRIPT_DIR}/bootloader.bin" \
--chip esp32c6 \
--baud 921600 \
--partition-table "${SCRIPT_DIR}/partitions.csv" \
target/riscv32imac-unknown-none-elf/release/plant-ctrl2

View File

@@ -1,17 +0,0 @@
#!/usr/bin/env bash
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
rm -f "${SCRIPT_DIR}/image.bin"
"${SCRIPT_DIR}/build_website.sh"
cargo build --release
espflash save-image \
--bootloader "${SCRIPT_DIR}/bootloader.bin" \
--partition-table "${SCRIPT_DIR}/partitions.csv" \
--chip esp32c6 \
target/riscv32imac-unknown-none-elf/release/plant-ctrl2 \
"${SCRIPT_DIR}/image.bin"

View File

@@ -27,22 +27,20 @@ pub trait BatteryInteraction {
#[derive(Debug, Serialize)] #[derive(Debug, Serialize)]
pub struct BatteryInfo { pub struct BatteryInfo {
pub voltage_mv: Option<u16>, pub voltage_milli_volt: u16,
pub avg_current_ma: Option<i16>, pub average_current_milli_ampere: i16,
pub soc_pct: Option<f32>, pub cycle_count: u16,
pub soh_pct: Option<u16>, pub design_milli_ampere_hour: u16,
pub temperature_c: Option<u16>, pub remaining_milli_ampere_hour: u16,
pub cycle_count: Option<u16>, pub state_of_charge: f32,
pub remaining_mah: Option<u16>, pub state_of_health: u16,
pub design_mah: Option<u16>, pub temperature: u16,
pub error: Option<BatteryError>,
} }
#[derive(Debug, Serialize)] #[derive(Debug, Serialize)]
#[serde(tag = "kind")]
pub enum BatteryError { pub enum BatteryError {
NoBatteryMonitor, NoBatteryMonitor,
CommunicationError { message: String }, CommunicationError(String),
} }
#[derive(Debug, Serialize)] #[derive(Debug, Serialize)]
@@ -182,15 +180,14 @@ impl BatteryInteraction for BQ34Z100G1 {
async fn get_battery_state(&mut self) -> FatResult<BatteryState> { async fn get_battery_state(&mut self) -> FatResult<BatteryState> {
Ok(BatteryState::Info(BatteryInfo { Ok(BatteryState::Info(BatteryInfo {
voltage_mv: Some(self.voltage_milli_volt().await?), voltage_milli_volt: self.voltage_milli_volt().await?,
avg_current_ma: Some(self.average_current_milli_ampere().await?), average_current_milli_ampere: self.average_current_milli_ampere().await?,
soc_pct: Some(self.state_charge_percent().await?), cycle_count: self.cycle_count().await?,
soh_pct: Some(self.state_health_percent().await?), design_milli_ampere_hour: self.design_milli_ampere_hour().await?,
temperature_c: Some(self.bat_temperature().await?), remaining_milli_ampere_hour: self.remaining_milli_ampere_hour().await?,
cycle_count: Some(self.cycle_count().await?), state_of_charge: self.state_charge_percent().await?,
remaining_mah: Some(self.remaining_milli_ampere_hour().await?), state_of_health: self.state_health_percent().await?,
design_mah: Some(self.design_milli_ampere_hour().await?), temperature: self.bat_temperature().await?,
error: None,
})) }))
} }
} }

View File

@@ -43,7 +43,7 @@ use embassy_time::{Duration, Instant, Timer};
use esp_hal::rom::ets_delay_us; use esp_hal::rom::ets_delay_us;
use esp_hal::system::software_reset; use esp_hal::system::software_reset;
use esp_println::{logger, println}; use esp_println::{logger, println};
use hal::battery::{BatteryError, BatteryInfo, BatteryState}; use hal::battery::BatteryState;
use log::LogMessage; use log::LogMessage;
use option_lock::OptionLock; use option_lock::OptionLock;
use plant_state::PlantState; use plant_state::PlantState;
@@ -265,9 +265,10 @@ async fn safe_main(spawner: Spawner) -> FatResult<()> {
); );
if let network::NetworkMode::WIFI { ref ip_address, .. } = network_mode { if let network::NetworkMode::WIFI { ref ip_address, .. } = network_mode {
mqtt::publish_firmware_info(&mut board, version, ip_address, &timezone_time.to_rfc3339()).await; publish_firmware_info(&mut board, version, ip_address, &timezone_time.to_rfc3339()).await;
mqtt::publish_battery_state(&mut board).await; publish_battery_state(&mut board).await;
let _ = mqtt::publish_mppt_state(&mut board).await; let _ = publish_mppt_state(&mut board).await;
publish_config(&mut board).await;
} }
log( log(
@@ -310,7 +311,7 @@ async fn safe_main(spawner: Spawner) -> FatResult<()> {
if let Some(err) = tank_state.got_error(&board.board_hal.get_config().tank) { if let Some(err) = tank_state.got_error(&board.board_hal.get_config().tank) {
match err { match err {
TankError::SensorDisabled => { /* unreachable */ } TankError::SensorDisabled => { /* unreachable */ }
TankError::SensorMissing { raw_mv: raw_value_mv } => log( TankError::SensorMissing(raw_value_mv) => log(
LogMessage::TankSensorMissing, LogMessage::TankSensorMissing,
raw_value_mv as u32, raw_value_mv as u32,
0, 0,
@@ -324,8 +325,8 @@ async fn safe_main(spawner: Spawner) -> FatResult<()> {
&format!("{value}"), &format!("{value}"),
"", "",
), ),
TankError::BoardError { message: err } => { TankError::BoardError(err) => {
log(LogMessage::TankSensorBoardError, 0, 0, "", &err) log(LogMessage::TankSensorBoardError, 0, 0, "", &err.to_string())
} }
} }
// disabled cannot trigger this because of wrapping if is_enabled // disabled cannot trigger this because of wrapping if is_enabled
@@ -352,7 +353,7 @@ async fn safe_main(spawner: Spawner) -> FatResult<()> {
} }
info!("Water temp is {}", water_temp.as_ref().unwrap_or(&0.)); info!("Water temp is {}", water_temp.as_ref().unwrap_or(&0.));
mqtt::publish_tank_state(&mut board, &tank_state, water_temp).await; publish_tank_state(&mut board, &tank_state, water_temp).await;
let plantstate: [PlantState; PLANT_COUNT] = [ let plantstate: [PlantState; PLANT_COUNT] = [
PlantState::read_hardware_state(0, &mut board).await, PlantState::read_hardware_state(0, &mut board).await,
@@ -365,7 +366,7 @@ async fn safe_main(spawner: Spawner) -> FatResult<()> {
PlantState::read_hardware_state(7, &mut board).await, PlantState::read_hardware_state(7, &mut board).await,
]; ];
mqtt::publish_plant_states(&mut board, &timezone_time.clone(), &plantstate).await; publish_plant_states(&mut board, &timezone_time.clone(), &plantstate).await;
// let pump_required = plantstate // let pump_required = plantstate
// .iter() // .iter()
@@ -699,6 +700,126 @@ async fn update_charge_indicator(
Ok(()) Ok(())
} }
async fn publish_tank_state(
board: &mut MutexGuard<'_, CriticalSectionRawMutex, HAL<'static>>,
tank_state: &TankState,
water_temp: FatResult<f32>,
) {
let state = serde_json::to_string(
&tank_state.as_mqtt_info(&board.board_hal.get_config().tank, &water_temp),
)
.unwrap();
let _ = mqtt::publish("/water", &*state).await;
}
async fn publish_plant_states(
board: &mut MutexGuard<'_, CriticalSectionRawMutex, HAL<'static>>,
timezone_time: &DateTime<Tz>,
plantstate: &[PlantState; 8],
) {
for (plant_id, (plant_state, plant_conf)) in plantstate
.iter()
.zip(&board.board_hal.get_config().plants.clone())
.enumerate()
{
let state =
serde_json::to_string(&plant_state.to_mqtt_info(plant_conf, timezone_time)).unwrap();
let plant_topic = format!("/plant{}", plant_id + 1);
let _ = mqtt::publish(&plant_topic, &state).await;
}
}
async fn publish_firmware_info(
board: &mut MutexGuard<'_, CriticalSectionRawMutex, HAL<'static>>,
version: VersionInfo,
ip_address: &str,
timezone_time: &str,
) {
mqtt::publish("/firmware/address", ip_address).await;
mqtt::publish("/firmware/state", format!("{:?}", &version).as_str())
.await;
mqtt::publish("/firmware/last_online", timezone_time)
.await;
mqtt::publish("/state", "online").await;
}
async fn pump_info(
plant_id: usize,
pump_active: bool,
pump_ineffective: bool,
median_current_ma: u16,
max_current_ma: u16,
min_current_ma: u16,
_error: bool,
) {
let pump_info = mqtt::PumpInfo {
enabled: pump_active,
pump_ineffective,
median_current_ma,
max_current_ma,
min_current_ma,
};
let pump_topic = format!("/pump{}", plant_id + 1);
match serde_json::to_string(&pump_info) {
Ok(state) => {
let _ = mqtt::publish(&pump_topic, &state).await;
}
Err(err) => {
warn!("Error publishing pump state {}", err);
}
};
}
async fn publish_mppt_state(
board: &mut MutexGuard<'_, CriticalSectionRawMutex, HAL<'static>>,
) -> FatResult<()> {
let current = board.board_hal.get_mptt_current().await?;
let voltage = board.board_hal.get_mptt_voltage().await?;
let solar_state = mqtt::Solar {
current_ma: current.as_milliamperes() as u32,
voltage_ma: voltage.as_millivolts() as u32,
};
if let Ok(serialized_solar_state_bytes) = serde_json::to_string(&solar_state) {
let _ = mqtt::publish("/mppt", &serialized_solar_state_bytes).await;
}
Ok(())
}
async fn publish_battery_state(
board: &mut MutexGuard<'_, CriticalSectionRawMutex, HAL<'static>>,
) -> () {
let state = board
.board_hal
.get_battery_monitor()
.get_battery_state()
.await;
let value = match state {
Ok(state) => {
let json = serde_json::to_string(&state).unwrap().to_owned();
json.to_owned()
}
Err(_) => "error".to_owned(),
};
{
let _ = mqtt::publish("/battery", &*value).await;
}
}
async fn publish_config(
board: &mut MutexGuard<'_, CriticalSectionRawMutex, HAL<'_>>,
) {
let config = board.board_hal.get_config();
match serde_json::to_string(&config) {
Ok(serialized) => {
let _ = mqtt::publish("/config", &serialized).await;
}
Err(err) => {
info!("Error serializing config: {}", err);
}
}
}
async fn wait_infinity( async fn wait_infinity(
board: MutexGuard<'_, CriticalSectionRawMutex, HAL<'static>>, board: MutexGuard<'_, CriticalSectionRawMutex, HAL<'static>>,
wait_type: WaitType, wait_type: WaitType,

View File

@@ -1,23 +1,18 @@
use crate::bail;
use crate::config::NetworkConfig; use crate::config::NetworkConfig;
use crate::fat_error::{ContextExt, FatError, FatResult}; use crate::fat_error::{ContextExt, FatError, FatResult};
use crate::hal::battery::{BatteryError, BatteryInfo, BatteryState}; use crate::hal::PlantHal;
use crate::hal::{PlantHal, HAL};
use crate::log::{log, LogMessage}; use crate::log::{log, LogMessage};
use crate::plant_state::PlantState;
use crate::tank::TankState;
use crate::{bail, VersionInfo};
use alloc::string::String; use alloc::string::String;
use alloc::{format, string::ToString}; use alloc::{format, string::ToString, vec::Vec};
use chrono::DateTime;
use chrono_tz::Tz;
use core::sync::atomic::Ordering; use core::sync::atomic::Ordering;
use embassy_executor::Spawner; use embassy_executor::Spawner;
use embassy_net::Stack; use embassy_net::Stack;
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex; use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
use embassy_sync::mutex::MutexGuard; use embassy_sync::mutex::Mutex;
use embassy_sync::once_lock::OnceLock; use embassy_sync::once_lock::OnceLock;
use embassy_time::{Duration, Timer, WithTimeout}; use embassy_time::{Duration, Timer, WithTimeout};
use log::{info, warn}; use log::info;
use mcutie::{ use mcutie::{
Error, McutieBuilder, McutieReceiver, McutieTask, MqttMessage, PublishDisplay, Publishable, Error, McutieBuilder, McutieReceiver, McutieTask, MqttMessage, PublishDisplay, Publishable,
QoS, Topic, QoS, Topic,
@@ -25,10 +20,26 @@ use mcutie::{
use portable_atomic::AtomicBool; use portable_atomic::AtomicBool;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug, PartialEq, Default)]
pub struct PumpInfo {
pub enabled: bool,
pub pump_ineffective: bool,
pub median_current_ma: u16,
pub max_current_ma: u16,
pub min_current_ma: u16,
}
#[derive(Serialize, Debug, PartialEq)]
pub struct Solar {
pub current_ma: u32,
pub voltage_ma: u32,
}
static MQTT_CONNECTED_EVENT_RECEIVED: AtomicBool = AtomicBool::new(false); static MQTT_CONNECTED_EVENT_RECEIVED: AtomicBool = AtomicBool::new(false);
static MQTT_ROUND_TRIP_RECEIVED: AtomicBool = AtomicBool::new(false); static MQTT_ROUND_TRIP_RECEIVED: AtomicBool = AtomicBool::new(false);
pub static MQTT_STAY_ALIVE: AtomicBool = AtomicBool::new(false); pub static MQTT_STAY_ALIVE: AtomicBool = AtomicBool::new(false);
static MQTT_BASE_TOPIC: OnceLock<String> = OnceLock::new(); static MQTT_BASE_TOPIC: OnceLock<String> = OnceLock::new();
static MQTT_CONFIG_UPDATE_PAYLOAD: Mutex<CriticalSectionRawMutex, Option<String>> = Mutex::new(None);
pub fn is_stay_alive() -> bool { pub fn is_stay_alive() -> bool {
MQTT_STAY_ALIVE.load(Ordering::Relaxed) MQTT_STAY_ALIVE.load(Ordering::Relaxed)
@@ -133,6 +144,8 @@ pub async fn mqtt_init(
let last_will_topic = format!("{base_topic}/state"); let last_will_topic = format!("{base_topic}/state");
let round_trip_topic = format!("{base_topic}/internal/roundtrip"); let round_trip_topic = format!("{base_topic}/internal/roundtrip");
let stay_alive_topic = format!("{base_topic}/stay_alive"); let stay_alive_topic = format!("{base_topic}/stay_alive");
let config_update_payload_topic = format!("{base_topic}/config/update_payload");
let config_update_topic = format!("{base_topic}/config/update");
let mut builder: McutieBuilder<'_, String, PublishDisplay<String, &str>, 0> = let mut builder: McutieBuilder<'_, String, PublishDisplay<String, &str>, 0> =
McutieBuilder::new(stack, "plant ctrl", mqtt_url); McutieBuilder::new(stack, "plant ctrl", mqtt_url);
@@ -151,10 +164,12 @@ pub async fn mqtt_init(
//TODO make configurable //TODO make configurable
builder = builder.with_device_id("plantctrl"); builder = builder.with_device_id("plantctrl");
let builder: McutieBuilder<'_, String, PublishDisplay<String, &str>, 2> = builder let builder: McutieBuilder<'_, String, PublishDisplay<String, &str>, 4> = builder
.with_subscriptions([ .with_subscriptions([
Topic::General(round_trip_topic.clone()), Topic::General(round_trip_topic.clone()),
Topic::General(stay_alive_topic.clone()), Topic::General(stay_alive_topic.clone()),
Topic::General(config_update_payload_topic.clone()),
Topic::General(config_update_topic.clone()),
]); ]);
let keep_alive = Duration::from_secs(60 * 60 * 2).as_secs() as u16; let keep_alive = Duration::from_secs(60 * 60 * 2).as_secs() as u16;
@@ -164,6 +179,8 @@ pub async fn mqtt_init(
receiver, receiver,
round_trip_topic.clone(), round_trip_topic.clone(),
stay_alive_topic.clone(), stay_alive_topic.clone(),
config_update_payload_topic.clone(),
config_update_topic.clone(),
)?); )?);
spawner.spawn(mqtt_runner(task)?); spawner.spawn(mqtt_runner(task)?);
@@ -210,7 +227,7 @@ pub async fn mqtt_init(
#[embassy_executor::task] #[embassy_executor::task]
async fn mqtt_runner( async fn mqtt_runner(
task: McutieTask<'static, String, PublishDisplay<'static, String, &'static str>, 2>, task: McutieTask<'static, String, PublishDisplay<'static, String, &'static str>, 4>,
) { ) {
task.run().await; task.run().await;
} }
@@ -220,6 +237,8 @@ async fn mqtt_incoming_task(
receiver: McutieReceiver, receiver: McutieReceiver,
round_trip_topic: String, round_trip_topic: String,
stay_alive_topic: String, stay_alive_topic: String,
config_update_payload_topic: String,
config_update_topic: String,
) { ) {
loop { loop {
let message = receiver.receive().await; let message = receiver.receive().await;
@@ -245,6 +264,43 @@ async fn mqtt_incoming_task(
}; };
log(LogMessage::MqttStayAliveRec, a, 0, "", ""); log(LogMessage::MqttStayAliveRec, a, 0, "", "");
MQTT_STAY_ALIVE.store(value, Ordering::Relaxed); MQTT_STAY_ALIVE.store(value, Ordering::Relaxed);
} else if subtopic.eq(config_update_payload_topic.as_str()) {
let payload_str = String::from_utf8_lossy(&payload[..]).to_string();
let mut buffer = MQTT_CONFIG_UPDATE_PAYLOAD.lock().await;
*buffer = Some(payload_str);
info!("MQTT config update payload received");
} else if subtopic.eq(config_update_topic.as_str()) {
let update_requested = payload.eq_ignore_ascii_case("true".as_ref())
|| payload.eq_ignore_ascii_case("1".as_ref());
if update_requested {
info!("MQTT config update requested");
let payload_lock = MQTT_CONFIG_UPDATE_PAYLOAD.lock().await;
if let Some(payload_str) = payload_lock.as_ref() {
match serde_json::from_str::<crate::config::PlantControllerConfig>(payload_str) {
Ok(config) => {
info!("Deserialized config, applying...");
let board_mutex = crate::BOARD_ACCESS.get().await;
let mut board = board_mutex.lock().await;
if let Err(e) = board.board_hal.get_esp().save_config(payload_str.as_bytes().to_vec()).await {
info!("Error saving config to flash: {}", e);
let _ = publish("/config/update", "false").await;
} else {
board.board_hal.set_config(config);
info!("Config applied, rebooting");
let _ = publish("/config/update", "false").await;
board.board_hal.get_esp().deep_sleep_ms(0);
}
}
Err(e) => {
info!("Error deserializing config: {}", e);
let _ = publish("/config/update", "false").await;
}
}
} else {
info!("No config update payload available");
let _ = publish("/config/update", "false").await;
}
}
} else { } else {
log(LogMessage::UnknownTopic, 0, 0, "", &topic); log(LogMessage::UnknownTopic, 0, 0, "", &topic);
} }
@@ -257,142 +313,3 @@ async fn mqtt_incoming_task(
} }
} }
} }
pub async fn publish_tank_state(
board: &mut MutexGuard<'_, CriticalSectionRawMutex, HAL<'static>>,
tank_state: &TankState,
water_temp: FatResult<f32>,
) {
let state = serde_json::to_string(
&tank_state.as_mqtt_info(&board.board_hal.get_config().tank, &water_temp),
)
.unwrap();
let _ = publish("/water", &*state).await;
}
pub async fn publish_plant_states(
board: &mut MutexGuard<'_, CriticalSectionRawMutex, HAL<'static>>,
timezone_time: &DateTime<Tz>,
plantstate: &[PlantState; 8],
) {
for (plant_id, (plant_state, plant_conf)) in plantstate
.iter()
.zip(&board.board_hal.get_config().plants.clone())
.enumerate()
{
let state =
serde_json::to_string(&plant_state.to_mqtt_info(plant_conf, timezone_time)).unwrap();
let plant_topic = format!("/plant{}", plant_id + 1);
let _ = publish(&plant_topic, &state).await;
}
}
pub async fn publish_firmware_info(
board: &mut MutexGuard<'_, CriticalSectionRawMutex, HAL<'static>>,
version: VersionInfo,
ip_address: &str,
timezone_time: &str,
) {
publish("/firmware/address", ip_address).await;
publish("/firmware/state", &serde_json::to_string(&version).unwrap()).await;
publish("/firmware/last_online", timezone_time).await;
publish("/state", "online").await;
}
#[derive(Serialize, Deserialize, Debug, PartialEq, Default)]
struct PumpInfo {
pub enabled: bool,
pub pump_ineffective: bool,
pub median_current_ma: u16,
pub max_current_ma: u16,
pub min_current_ma: u16,
}
pub async fn pump_info(
plant_id: usize,
pump_active: bool,
pump_ineffective: bool,
median_current_ma: u16,
max_current_ma: u16,
min_current_ma: u16,
_error: bool,
) {
let pump_info = PumpInfo {
enabled: pump_active,
pump_ineffective,
median_current_ma,
max_current_ma,
min_current_ma,
};
let pump_topic = format!("/pump{}", plant_id + 1);
match serde_json::to_string(&pump_info) {
Ok(state) => {
let _ = publish(&pump_topic, &state).await;
}
Err(err) => {
warn!("Error publishing pump state {}", err);
}
};
}
#[derive(Serialize, Debug, PartialEq)]
pub struct Solar {
pub current_ma: u32,
pub voltage_ma: u32,
}
pub async fn publish_mppt_state(
board: &mut MutexGuard<'_, CriticalSectionRawMutex, HAL<'static>>,
) -> FatResult<()> {
let current = board.board_hal.get_mptt_current().await?;
let voltage = board.board_hal.get_mptt_voltage().await?;
let solar_state = Solar {
current_ma: current.as_milliamperes() as u32,
voltage_ma: voltage.as_millivolts() as u32,
};
if let Ok(serialized_solar_state_bytes) = serde_json::to_string(&solar_state) {
let _ = publish("/mppt", &serialized_solar_state_bytes).await;
}
Ok(())
}
pub async fn publish_battery_state(
board: &mut MutexGuard<'_, CriticalSectionRawMutex, HAL<'static>>,
) -> () {
let telemetry = match board
.board_hal
.get_battery_monitor()
.get_battery_state()
.await
{
Ok(BatteryState::Info(info)) => info,
Ok(BatteryState::Unknown) => BatteryInfo {
voltage_mv: None,
avg_current_ma: None,
soc_pct: None,
soh_pct: None,
temperature_c: None,
cycle_count: None,
remaining_mah: None,
design_mah: None,
error: Some(BatteryError::NoBatteryMonitor),
},
Err(e) => BatteryInfo {
voltage_mv: None,
avg_current_ma: None,
soc_pct: None,
soh_pct: None,
temperature_c: None,
cycle_count: None,
remaining_mah: None,
design_mah: None,
error: Some(BatteryError::CommunicationError {
message: alloc::format!("{:?}", e),
}),
},
};
if let Ok(json) = serde_json::to_string(&telemetry) {
let _ = publish("/battery", &json).await;
}
}

View File

@@ -11,12 +11,11 @@ use serde::{Deserialize, Serialize};
const MOIST_SENSOR_MAX_FREQUENCY: f32 = 7500.; // 60kHz (500Hz margin) const MOIST_SENSOR_MAX_FREQUENCY: f32 = 7500.; // 60kHz (500Hz margin)
const MOIST_SENSOR_MIN_FREQUENCY: f32 = 150.; // this is really, really dry, think like cactus levels const MOIST_SENSOR_MIN_FREQUENCY: f32 = 150.; // this is really, really dry, think like cactus levels
#[derive(Debug, PartialEq, Clone, Serialize)] #[derive(Debug, PartialEq, Serialize)]
#[serde(tag = "kind")]
pub enum MoistureSensorError { pub enum MoistureSensorError {
ShortCircuit { hz: f32, max: f32 }, ShortCircuit { hz: f32, max: f32 },
OpenLoop { hz: f32, min: f32 }, OpenLoop { hz: f32, min: f32 },
BoardError { message: String }, BoardError(String),
} }
#[derive(Debug, PartialEq, Serialize)] #[derive(Debug, PartialEq, Serialize)]
@@ -50,14 +49,6 @@ impl MoistureSensorState {
impl MoistureSensorState {} impl MoistureSensorState {}
#[derive(Debug, PartialEq, Serialize)] #[derive(Debug, PartialEq, Serialize)]
pub struct SensorTelemetry {
pub moisture_pct: Option<f32>,
pub raw_hz: Option<f32>,
pub error: Option<MoistureSensorError>,
}
#[derive(Debug, PartialEq, Serialize)]
#[serde(tag = "kind")]
pub enum PumpError { pub enum PumpError {
PumpNotWorking { PumpNotWorking {
failed_attempts: usize, failed_attempts: usize,
@@ -143,9 +134,9 @@ impl PlantState {
}, },
Err(err) => MoistureSensorState::SensorError(err), Err(err) => MoistureSensorState::SensorError(err),
}, },
Err(err) => MoistureSensorState::SensorError(MoistureSensorError::BoardError { Err(err) => MoistureSensorState::SensorError(MoistureSensorError::BoardError(
message: err.to_string(), err.to_string(),
}) )),
} }
} else { } else {
MoistureSensorState::Disabled MoistureSensorState::Disabled
@@ -168,9 +159,9 @@ impl PlantState {
}, },
Err(err) => MoistureSensorState::SensorError(err), Err(err) => MoistureSensorState::SensorError(err),
}, },
Err(err) => MoistureSensorState::SensorError(MoistureSensorError::BoardError { Err(err) => MoistureSensorState::SensorError(MoistureSensorError::BoardError(
message: err.to_string(), err.to_string(),
}) )),
} }
} else { } else {
MoistureSensorState::Disabled MoistureSensorState::Disabled
@@ -286,15 +277,13 @@ impl PlantState {
&self, &self,
plant_conf: &PlantConfig, plant_conf: &PlantConfig,
current_time: &DateTime<Tz>, current_time: &DateTime<Tz>,
) -> PlantInfo { ) -> PlantInfo<'_> {
let (moisture_pct, _) = self.plant_moisture();
PlantInfo { PlantInfo {
moisture_pct, sensor_a: &self.sensor_a,
sensor_a: Self::sensor_to_telemetry(&self.sensor_a), sensor_b: &self.sensor_b,
sensor_b: Self::sensor_to_telemetry(&self.sensor_b),
mode: plant_conf.mode, mode: plant_conf.mode,
do_water: self.needs_to_be_watered(plant_conf, current_time), do_water: self.needs_to_be_watered(plant_conf, current_time),
dry: if let Some(moisture_percent) = moisture_pct { dry: if let Some(moisture_percent) = self.plant_moisture().0 {
moisture_percent < plant_conf.target_moisture moisture_percent < plant_conf.target_moisture
} else { } else {
false false
@@ -327,40 +316,15 @@ impl PlantState {
}, },
} }
} }
fn sensor_to_telemetry(sensor: &MoistureSensorState) -> SensorTelemetry {
match sensor {
MoistureSensorState::Disabled => SensorTelemetry {
moisture_pct: None,
raw_hz: None,
error: None,
},
MoistureSensorState::MoistureValue {
raw_hz,
moisture_percent,
} => SensorTelemetry {
moisture_pct: Some(*moisture_percent),
raw_hz: Some(*raw_hz),
error: None,
},
MoistureSensorState::SensorError(err) => SensorTelemetry {
moisture_pct: None,
raw_hz: None,
error: Some(err.clone()),
},
}
}
} }
#[derive(Debug, PartialEq, Serialize)] #[derive(Debug, PartialEq, Serialize)]
/// State of a single plant to be tracked /// State of a single plant to be tracked
pub struct PlantInfo { pub struct PlantInfo<'a> {
/// combined plant moisture from available sensors
moisture_pct: Option<f32>,
/// state of humidity sensor on bank a /// state of humidity sensor on bank a
sensor_a: SensorTelemetry, sensor_a: &'a MoistureSensorState,
/// state of humidity sensor on bank b /// state of humidity sensor on bank b
sensor_b: SensorTelemetry, sensor_b: &'a MoistureSensorState,
/// configured plant watering mode /// configured plant watering mode
mode: PlantWateringMode, mode: PlantWateringMode,
/// the plant needs to be watered /// the plant needs to be watered

View File

@@ -10,12 +10,11 @@ const OPEN_TANK_VOLTAGE: f32 = 3.0;
pub const WATER_FROZEN_THRESH: f32 = 4.0; pub const WATER_FROZEN_THRESH: f32 = 4.0;
#[derive(Debug, Clone, Serialize)] #[derive(Debug, Clone, Serialize)]
#[serde(tag = "kind")]
pub enum TankError { pub enum TankError {
SensorDisabled, SensorDisabled,
SensorMissing { raw_mv: f32 }, SensorMissing(f32),
SensorValueError { value: f32, min: f32, max: f32 }, SensorValueError { value: f32, min: f32, max: f32 },
BoardError { message: String }, BoardError(String),
} }
pub enum TankState { pub enum TankState {
@@ -26,7 +25,7 @@ pub enum TankState {
fn raw_voltage_to_divider_percent(raw_value_mv: f32) -> Result<f32, TankError> { fn raw_voltage_to_divider_percent(raw_value_mv: f32) -> Result<f32, TankError> {
if raw_value_mv > OPEN_TANK_VOLTAGE { if raw_value_mv > OPEN_TANK_VOLTAGE {
return Err(TankError::SensorMissing { raw_mv: raw_value_mv }); return Err(TankError::SensorMissing(raw_value_mv));
} }
let r2 = raw_value_mv * 50.0 / (3.3 - raw_value_mv); let r2 = raw_value_mv * 50.0 / (3.3 - raw_value_mv);
@@ -142,15 +141,15 @@ impl TankState {
TankInfo { TankInfo {
enough_water, enough_water,
warn_level, warn_level,
volume_ml: left_ml, left_ml,
sensor_error: tank_err, sensor_error: tank_err,
fill_raw_v: raw, raw,
water_frozen: water_temp water_frozen: water_temp
.as_ref() .as_ref()
.is_ok_and(|temp| *temp < WATER_FROZEN_THRESH), .is_ok_and(|temp| *temp < WATER_FROZEN_THRESH),
water_temp_c: water_temp.as_ref().copied().ok(), water_temp: water_temp.as_ref().copied().ok(),
temp_sensor_error: water_temp.as_ref().err().map(|err| err.to_string()), temp_sensor_error: water_temp.as_ref().err().map(|err| err.to_string()),
fill_pct: percent, percent,
} }
} }
} }
@@ -165,7 +164,7 @@ pub async fn determine_tank_state(
.and_then(|f| core::prelude::v1::Ok(f.tank_sensor_voltage())) .and_then(|f| core::prelude::v1::Ok(f.tank_sensor_voltage()))
{ {
Ok(raw_sensor_value_mv) => TankState::Present(raw_sensor_value_mv.await.unwrap()), Ok(raw_sensor_value_mv) => TankState::Present(raw_sensor_value_mv.await.unwrap()),
Err(err) => TankState::Error(TankError::BoardError { message: err.to_string() }), Err(err) => TankState::Error(TankError::BoardError(err.to_string())),
} }
} else { } else {
TankState::Disabled TankState::Disabled
@@ -180,16 +179,16 @@ pub struct TankInfo {
/// warning that water needs to be refilled soon /// warning that water needs to be refilled soon
pub(crate) warn_level: bool, pub(crate) warn_level: bool,
/// estimation how many ml are still in the tank /// estimation how many ml are still in the tank
pub(crate) volume_ml: Option<f32>, pub(crate) left_ml: Option<f32>,
/// if there is an issue with the water level sensor /// if there is an issue with the water level sensor
pub(crate) sensor_error: Option<TankError>, pub(crate) sensor_error: Option<TankError>,
/// raw water sensor value /// raw water sensor value
pub(crate) fill_raw_v: Option<f32>, pub(crate) raw: Option<f32>,
/// percent value /// percent value
pub(crate) fill_pct: Option<f32>, pub(crate) percent: Option<f32>,
/// water in the tank might be frozen /// water in the tank might be frozen
pub(crate) water_frozen: bool, pub(crate) water_frozen: bool,
/// water temperature /// water temperature
pub(crate) water_temp_c: Option<f32>, pub(crate) water_temp: Option<f32>,
pub(crate) temp_sensor_error: Option<String>, pub(crate) temp_sensor_error: Option<String>,
} }

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 {
@@ -221,18 +195,12 @@ where
let mut data_store = Vec::new(); let mut data_store = Vec::new();
let mut total_read = 0; let mut total_read = 0;
loop { loop {
let left = max_read - total_read;
let mut buf = [0_u8; 64]; let mut buf = [0_u8; 64];
let s_buf = if buf.len() <= left { let read = request.read(&mut buf).await?;
&mut buf
} else {
&mut buf[0..left]
};
let read = request.read(s_buf).await?;
if read == 0 { if read == 0 {
break; break;
} }
let actual_data = &s_buf[0..read]; let actual_data = &buf[0..read];
total_read += read; total_read += read;
if total_read > max_read { if total_read > max_read {
bail!("Request too large {total_read} > {max_read}"); bail!("Request too large {total_read} > {max_read}");

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 {
@@ -195,4 +189,4 @@ export interface TankInfo {
/// water temperature /// water temperature
water_temp: number | null, water_temp: number | null,
temp_sensor_error: string | null temp_sensor_error: string | null
} }

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);
@@ -577,4 +569,4 @@ window.addEventListener("beforeunload", (event) => {
event.returnValue = confirmationMessage; // This will trigger the browser's default dialog event.returnValue = confirmationMessage; // This will trigger the browser's default dialog
return confirmationMessage; return confirmationMessage;
} }
}); });

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,38 +1,22 @@
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
this.file1Upload.onchange = () => { this.file1Upload.onchange = () => {
@@ -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();