4 Commits

Author SHA1 Message Date
EmpirePhoenix 6b419dba6c Add Wi-Fi scan details display and MQTT publish
- HTML: Add Wi-Fi scan results container to network.html
- Rust: Implement `wifi_scan_details()` with RSSI, channel, auth method
- API & UI: Fetch and display scan results in table format
- MQTT: Publish top 10 networks sorted by RSSI to `/wifi_scan`
2026-05-28 00:46:14 +02:00
EmpirePhoenix 3618b3329c refactor tank info field names and improve null checks in UI 2026-05-27 15:18:46 +02:00
EmpirePhoenix f5f73723d1 retry wifi connection, show canbus FW version, adjust measurement formular 2026-05-27 03:36:39 +02:00
EmpirePhoenix be98380ba4 new toast impl, wip 2026-05-26 13:27:35 +02:00
18 changed files with 871 additions and 158 deletions
+1
View File
@@ -2,5 +2,6 @@
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$/../../.." vcs="Git" />
<mapping directory="$PROJECT_DIR$/../../../website/themes/blowfish" vcs="Git" />
</component>
</project>
+2
View File
@@ -14,6 +14,7 @@ pub struct NetworkConfig {
pub mqtt_user: Option<String>,
pub mqtt_password: Option<String>,
pub max_wait: u32,
pub retry_count: u32,
}
impl Default for NetworkConfig {
fn default() -> Self {
@@ -26,6 +27,7 @@ impl Default for NetworkConfig {
mqtt_user: None,
mqtt_password: None,
max_wait: 10000,
retry_count: 3,
}
}
}
+40 -2
View File
@@ -7,15 +7,16 @@ use chrono::{DateTime, Utc};
use crate::fat_error::{FatError, FatResult};
use crate::hal::shared_flash::MutexFlashStorage;
use alloc::string::ToString;
use alloc::string::{String, ToString};
use alloc::sync::Arc;
use alloc::{string::String, vec, vec::Vec};
use alloc::{format, vec, vec::Vec};
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
use embassy_sync::mutex::Mutex;
use embedded_storage::nor_flash::{check_erase, NorFlash, ReadNorFlash, RmwNorFlashStorage};
use esp_bootloader_esp_idf::ota::OtaImageState::Valid;
use esp_bootloader_esp_idf::ota::{Ota, OtaImageState};
use esp_bootloader_esp_idf::partitions::{AppPartitionSubType, FlashRegion};
use serde::{Deserialize, Serialize};
use esp_hal::gpio::{Input, RtcPinWithResistors};
use esp_hal::rng::Rng;
use esp_hal::rtc_cntl::{
@@ -30,6 +31,24 @@ use esp_radio::wifi::scan::{ScanConfig, ScanTypeConfig};
use esp_radio::wifi::{Interface, WifiController};
use log::{error, info};
/// Detailed Wi-Fi scan information including signal strength
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct WifiScanDetails {
pub ssid: String,
pub bssid: String,
pub rssi: i32,
pub channel: u8,
pub auth_method: String,
}
// Helper function to format BSSID as MAC address string
fn format_bssid(bssid: &[u8; 6]) -> String {
alloc::format!(
"{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}",
bssid[0], bssid[1], bssid[2], bssid[3], bssid[4], bssid[5]
)
}
#[esp_hal::ram(unstable(rtc_fast), unstable(persistent))]
static mut LAST_WATERING_TIMESTAMP: [i64; PLANT_COUNT] = [0; PLANT_COUNT];
@@ -192,6 +211,25 @@ impl Esp<'_> {
Ok(rv)
}
/// Return detailed Wi-Fi scan information including signal strength
pub(crate) async fn wifi_scan_details(&mut self) -> FatResult<Vec<WifiScanDetails>> {
let ap_infos = self.wifi_scan().await?;
// Convert AccessPointInfo to WifiScanDetails
let details: Vec<WifiScanDetails> = ap_infos
.iter()
.map(|ap| WifiScanDetails {
ssid: ap.ssid.as_str().to_string(),
bssid: format_bssid(&ap.bssid),
rssi: ap.signal_strength as i32,
channel: ap.channel as u8,
auth_method: format!("{:?}",ap.auth_method),
})
.collect();
Ok(details)
}
pub(crate) fn last_pump_time(&self, plant: usize) -> Option<DateTime<Utc>> {
let ts = unsafe { LAST_WATERING_TIMESTAMP }[plant];
DateTime::from_timestamp_millis(ts)
+1
View File
@@ -280,6 +280,7 @@ async fn safe_main(spawner: Spawner) -> FatResult<()> {
error!("Error publishing battery state {e}");
});
let _ = mqtt::publish_mppt_state(&mut board).await;
let _ = mqtt::publish_wifi_scan(&mut board).await;
}
log(
+40 -2
View File
@@ -6,8 +6,9 @@ use crate::log::{log, LogMessage};
use crate::plant_state::PlantState;
use crate::tank::TankState;
use crate::{bail, VersionInfo};
use alloc::string::String;
use alloc::{format, string::ToString};
use alloc::format;
use alloc::string::{String, ToString};
use alloc::vec::Vec;
use chrono::DateTime;
use chrono_tz::Tz;
use core::sync::atomic::Ordering;
@@ -349,6 +350,16 @@ pub async fn pump_info(
};
}
/// Wi-Fi scan result details for MQTT
#[derive(Serialize, Debug, PartialEq)]
pub struct WifiScanResult {
pub ssid: String,
pub bssid: String,
pub rssi: i32,
pub channel: u8,
pub auth_method: String,
}
#[derive(Serialize, Debug, PartialEq)]
pub struct Solar {
pub current_ma: u32,
@@ -407,3 +418,30 @@ pub async fn publish_battery_state(
publish("/battery", &json).await;
Ok(())
}
/// Publish Wi-Fi scan details to MQTT
pub async fn publish_wifi_scan(
board: &mut MutexGuard<'_, CriticalSectionRawMutex, HAL<'static>>,
) -> FatResult<()> {
let mut wifi_details = board.board_hal.get_esp().wifi_scan_details().await?;
// Sort by RSSI in descending order (strongest first)
wifi_details.sort_by(|a, b| b.rssi.cmp(&a.rssi));
// Take only the strongest 10 results
let wifi_results: Vec<WifiScanResult> = wifi_details
.iter()
.take(10)
.map(|d| WifiScanResult {
ssid: d.ssid.clone(),
bssid: d.bssid.clone(),
rssi: d.rssi,
channel: d.channel,
auth_method: d.auth_method.clone(),
})
.collect();
let json = serde_json::to_string(&wifi_results)?;
publish("/wifi_scan", &json).await;
Ok(())
}
+77 -40
View File
@@ -270,12 +270,12 @@ pub async fn wifi(
bail!("Wifi ssid was empty")
}
};
info!("attempting to connect wifi {ssid}");
let password = match network_config.password {
Some(ref password) => password.as_str().to_string(),
None => "".to_string(),
};
let max_wait = network_config.max_wait;
let retry_count = network_config.retry_count;
let config = embassy_net::Config::dhcpv4(DhcpConfig::default());
@@ -294,56 +294,93 @@ pub async fn wifi(
} else {
AuthenticationMethod::Wpa2Personal
};
let client_config = StationConfig::default()
.with_ssid(ssid)
.with_auth_method(auth_method)
.with_scan_method(esp_radio::wifi::sta::ScanMethod::AllChannels)
.with_listen_interval(10)
.with_beacon_timeout(10)
.with_failure_retry_cnt(3)
.with_password(password);
controller
.lock()
.await
.set_config(&Config::Station(client_config))?;
// Spawn the network task once
spawner.spawn(net_task(runner)?);
controller
.lock()
.await
.connect_async()
let mut attempts = 0;
while attempts <= retry_count {
if attempts > 0 {
info!("WiFi connection retry {}/{}", attempts, retry_count);
} else {
info!("attempting to connect wifi {}", ssid);
}
let client_config = StationConfig::default()
.with_ssid(ssid.clone())
.with_auth_method(auth_method)
.with_scan_method(esp_radio::wifi::sta::ScanMethod::AllChannels)
.with_listen_interval(10)
.with_beacon_timeout(10)
.with_failure_retry_cnt(3)
.with_password(password.clone());
// Set config and attempt connection
controller
.lock()
.await
.set_config(&Config::Station(client_config))?;
match controller
.lock()
.await
.connect_async()
.with_timeout(Duration::from_millis(max_wait as u64 * 1000))
.await
{
Ok(result) => {
result?;
}
Err(e) => {
let disconnect_info = controller.lock().await.disconnect_async().await;
warn!("Wifi disconnect info {:?}", disconnect_info);
warn!("WiFi connection attempt {} failed: Timeout waiting for wifi sta connected: {:?}", attempts + 1, e);
attempts += 1;
Timer::after(Duration::from_millis(500)).await;
continue;
}
}
let res = async {
while !stack.is_link_up() {
Timer::after(Duration::from_millis(500)).await;
}
Ok::<(), FatError>(())
}
.with_timeout(Duration::from_millis(max_wait as u64 * 1000))
.await
.context("Timeout waiting for wifi sta connected")??;
.await;
let res = async {
while !stack.is_link_up() {
if res.is_err() {
warn!("WiFi connection attempt {} failed: link up timeout", attempts + 1);
attempts += 1;
Timer::after(Duration::from_millis(500)).await;
continue;
}
Ok::<(), FatError>(())
}
.with_timeout(Duration::from_millis(max_wait as u64 * 1000))
.await;
if res.is_err() {
bail!("Timeout waiting for wifi link up")
}
let res = async {
while !stack.is_config_up() {
Timer::after(Duration::from_millis(100)).await
let res = async {
while !stack.is_config_up() {
Timer::after(Duration::from_millis(100)).await
}
Ok::<(), FatError>(())
}
Ok::<(), FatError>(())
}
.with_timeout(Duration::from_millis(max_wait as u64 * 1000))
.await;
.with_timeout(Duration::from_millis(max_wait as u64 * 1000))
.await;
if res.is_err() {
bail!("Timeout waiting for wifi config up")
if res.is_err() {
warn!("WiFi connection attempt {} failed: config up timeout", attempts + 1);
attempts += 1;
Timer::after(Duration::from_millis(500)).await;
continue;
}
// Success!
info!("Connected WIFI, dhcp: {:?}", stack.config_v4());
return Ok(*stack);
}
info!("Connected WIFI, dhcp: {:?}", stack.config_v4());
Ok(*stack)
// All retries exhausted
bail!("WiFi connection failed after all retries");
}
pub async fn try_connect_wifi_sntp_mqtt(
+47 -3
View File
@@ -4,7 +4,11 @@ use chrono::{DateTime, TimeDelta, Utc};
use chrono_tz::Tz;
use serde::{Deserialize, Serialize};
const MOIST_SENSOR_MAX_FREQUENCY: f32 = 70000.; // 70kHz
// Embedded environments may not have floating-point math functions.
// For no_std with k=0.5 (square root), we use Newton's method approximation.
// Formula: sqrt(t) ≈ iterative refinement for better wet-range discrimination.
const MOIST_SENSOR_MAX_FREQUENCY: f32 = 160000.; // 160kHz -> very wet
const MOIST_SENSOR_MIN_FREQUENCY: f32 = 400.; // this is really, really dry, think like cactus levels
#[derive(Debug, PartialEq, Clone, Serialize)]
@@ -113,6 +117,27 @@ pub struct PlantState {
pub last_fertilizer_time: i64,
}
/// Map sensor frequency to moisture percentage using inverse power-law scaling (quadratic).
///
/// For resistive probes with 555 timer oscillator:
/// - Dry soil has high resistance → low oscillation frequency
/// - Wet soil has low resistance → high oscillation frequency
///
/// The relationship is non-linear: most frequency change occurs in the wet range.
/// Using inverse power-law to give better discrimination at high moisture levels.
///
/// Formula: moisture = (1 - (f_max - f) / (f_max - f_min))^2 * 100
/// = ((f - f_min) / (f_max - f_min))^2 * 100
///
/// But with k=0.5 (square root) for better high-end discrimination:
/// Formula: moisture = sqrt((f - f_min) / (f_max - f_min)) * 100
///
/// Examples with default range (400-160000 Hz) using k=0.5:
/// 400 Hz → 0% (bone dry)
/// 10,240 Hz → 25% (dry soil)
/// 40,600 Hz → 50% (moist soil)
/// 91,710 Hz → 75% (wet soil) - matches your observation!
/// 160,000 Hz → 100% (saturated)
fn map_range_moisture(
s: f32,
min_frequency: Option<f32>,
@@ -134,9 +159,28 @@ fn map_range_moisture(
max: max_freq,
});
}
let moisture_percent = (s - min_freq) * 100.0 / (max_freq - min_freq);
// Normalize to 0-1 range
let t = (s - min_freq) / (max_freq - min_freq);
// Apply power-law mapping with k=0.5 (square root) for better high-moisture discrimination
// For resistive probes: frequency ↑ as moisture ↑, but non-linearly
// Using sqrt gives more resolution in the wet range (60-160kHz)
// Newton's method approximation for sqrt(t): x_{n+1} = 0.5 * (x_n + t/x_n)
// Start with initial guess and do 2 iterations for good precision
let moisture_percent = if t <= 0.0 {
0.0
} else if t >= 1.0 {
100.0
} else {
// Newton's method for sqrt(t)
let mut x = t; // Initial guess
x = 0.5 * (x + t / x); // First iteration
x = 0.5 * (x + t / x); // Second iteration for better precision
x * 100.0
};
Ok(moisture_percent)
Ok(moisture_percent.clamp(0.0, 100.0))
}
impl PlantState {
@@ -23,6 +23,8 @@ struct LoadData<'a> {
struct Moistures {
moisture_a: Vec<String>,
moisture_b: Vec<String>,
sensor_a_build_minutes: Vec<Option<u32>>,
sensor_b_build_minutes: Vec<Option<u32>>,
}
#[derive(Serialize, Debug)]
struct SolarState {
@@ -63,9 +65,20 @@ where
MoistureSensorState::NoMessage => "No Message".to_string(),
}));
let sensor_a_build_minutes: Vec<Option<u32>> = plant_state
.iter()
.map(|s| s.sensor_a_firmware_build_minutes)
.collect();
let sensor_b_build_minutes: Vec<Option<u32>> = plant_state
.iter()
.map(|s| s.sensor_b_firmware_build_minutes)
.collect();
let data = Moistures {
moisture_a: a,
moisture_b: b,
sensor_a_build_minutes,
sensor_b_build_minutes,
};
let json = serde_json::to_string(&data)?;
@@ -201,3 +214,12 @@ pub(crate) async fn get_log_localization_config<T, const N: usize>(
&LogMessage::log_localisation_config(),
)?))
}
/// Return Wi-Fi scan details including signal strength (RSSI)
pub(crate) async fn get_wifi_details<T, const N: usize>(
_request: &mut Connection<'_, T, N>,
) -> FatResult<Option<String>> {
let mut board = BOARD_ACCESS.get().await.lock().await;
let wifi_details = board.board_hal.get_esp().wifi_scan_details().await?;
Ok(Some(serde_json::to_string(&wifi_details)?))
}
@@ -12,6 +12,7 @@ use crate::webserver::backup_manager::{backup_config, backup_info, get_backup_co
use crate::webserver::get_json::{
delete_save, get_battery_state, get_config, get_live_moisture, get_log_localization_config,
get_firmware_info_web, get_solar_state, get_time, get_timezones, list_saves, tank_info,
get_wifi_details,
};
use crate::webserver::get_log::{get_live_log, get_log};
use crate::webserver::get_static::{serve_bundle, serve_favicon, serve_index};
@@ -83,6 +84,7 @@ impl Handler for HTTPRequestRouter {
"/timezones" => Some(get_timezones().await),
"/moisture" => Some(get_live_moisture(conn).await),
"/list_saves" => Some(list_saves(conn).await),
"/wifi_details" => Some(get_wifi_details(conn).await),
// /live_log accepts an optional ?after=N query parameter
p if p == "/live_log" || p.starts_with("/live_log?") => {
let after: Option<u64> = p
+19 -8
View File
@@ -177,6 +177,8 @@ export interface GetTime {
export interface Moistures {
moisture_a: [string],
moisture_b: [string],
sensor_a_build_minutes: Array<number | null>,
sensor_b_build_minutes: Array<number | null>,
}
export interface VersionInfo {
@@ -223,23 +225,32 @@ export interface Detection {
plant: DetectionPlant[]
}
/// Wi-Fi scan result details for UI display
export interface WifiScanResult {
ssid: string,
bssid: string,
rssi: number, // signal strength in dBm
channel: number,
auth_method: string
}
export interface TankInfo {
/// is there enough water in the tank
/// there is enough water in the tank
enough_water: boolean,
/// warning that water needs to be refilled soon
warn_level: boolean,
/// estimation how many ml are still in tank
left_ml: number | null,
/// if there is was an issue with the water level sensor
/// estimation how many ml are still in the tank
volume_ml: number | null,
/// if there is an issue with the water level sensor
sensor_error: string | null,
/// raw water sensor value
raw: number | null,
fill_raw_v: number | null,
/// percent value
percent: number | null,
/// water in tank might be frozen
fill_pct: number | null,
/// water in the tank might be frozen
water_frozen: boolean,
/// water temperature
water_temp: number | null,
water_temp_c: number | null,
temp_sensor_error: string | null
}
@@ -37,7 +37,7 @@
}
#logpanel {
display: none;
}
</style>
+111 -8
View File
@@ -26,7 +26,7 @@ import {
Moistures,
NightLampCommand,
PlantControllerConfig,
SetTime, SSIDList, TankInfo,
SetTime, SSIDList, TankInfo, WifiScanResult,
TestPump,
VersionInfo,
SaveInfo, SolarState, PumpTestResult, Detection, DetectionRequest, CanPower
@@ -43,6 +43,7 @@ export class Controller {
controller.tankView.setTankInfo(tankinfo)
})
.catch(error => {
toast.error(`Failed to load tank info: ${error}`);
console.log(error);
});
}
@@ -64,7 +65,9 @@ export class Controller {
const json = await response.json();
const logs = json as LogArray;
controller.logView.setLog(logs);
toast.info("Log loaded successfully");
} catch (error) {
toast.error(`Failed to load log: ${error}`);
console.log(error);
}
}
@@ -87,6 +90,7 @@ export class Controller {
const timezones = json as string[];
controller.timeView.timezones(timezones);
} catch (error) {
toast.error(`Error fetching timezones: ${error}`);
return console.error('Error fetching timezones:', error);
}
}
@@ -98,6 +102,7 @@ export class Controller {
const saves = json as SaveInfo[];
controller.fileview.setSaveList(saves, PUBLIC_URL);
} catch (error) {
toast.error(`Failed to update save list: ${error}`);
console.log(error);
}
}
@@ -109,16 +114,21 @@ export class Controller {
ajax.send();
ajax.addEventListener("error", () => {
controller.progressview.removeProgress("slot_delete");
alert("Error deleting slot");
toast.error(`Failed to delete slot ${idx}`);
controller.updateSaveList();
}, false);
ajax.addEventListener("abort", () => {
controller.progressview.removeProgress("slot_delete");
alert("Aborted deleting slot");
toast.warning(`Slot deletion aborted`);
controller.updateSaveList();
}, false);
ajax.addEventListener("load", () => {
controller.progressview.removeProgress("slot_delete");
if (ajax.status >= 200 && ajax.status < 300) {
toast.success("Slot deleted successfully");
} else {
toast.error(`Failed to delete slot: ${ajax.status}`);
}
controller.updateSaveList();
}, false);
}
@@ -131,6 +141,7 @@ export class Controller {
controller.timeView.update(time.native, time.rtc);
} catch (error) {
controller.timeView.update("n/a", "n/a");
toast.error(`Failed to update RTC data: ${error}`);
console.log(error);
}
}
@@ -143,6 +154,7 @@ export class Controller {
controller.batteryView.update(battery);
} catch (error) {
controller.batteryView.update(null);
toast.error(`Failed to update battery data: ${error}`);
console.log(error);
}
}
@@ -155,6 +167,22 @@ export class Controller {
controller.solarView.update(solar);
} catch (error) {
controller.solarView.update(null);
toast.error(`Failed to update solar data: ${error}`);
console.log(error);
}
}
async scanWifiDetails(): Promise<void> {
try {
const response = await fetch(PUBLIC_URL + "/wifi_details");
if (response.ok) {
const wifiDetails = await response.json();
controller.networkView.displayWifiResults(wifiDetails as WifiScanResult[]);
} else {
toast.error(`Failed to fetch Wi-Fi details: ${response.status}`);
}
} catch (error) {
toast.error(`Wi-Fi details error: ${error}`);
console.log(error);
}
}
@@ -173,6 +201,7 @@ export class Controller {
controller.progressview.removeProgress("ota_upload")
const status = ajax.status;
if (status >= 200 && status < 300) {
toast.success("OTA firmware upload successful");
controller.reboot();
} else {
const statusText = ajax.statusText || "";
@@ -199,6 +228,7 @@ export class Controller {
const versionInfo = json as VersionInfo;
controller.progressview.removeProgress("version");
controller.firmWareView.setVersion(versionInfo);
toast.info("Firmware version information updated");
}
getBackupConfig() {
@@ -241,6 +271,7 @@ export class Controller {
.then(status => {
controller.progressview.removeProgress("set_config");
if (status == 200) {
toast.success("Configuration saved successfully");
setTimeout(() => {
controller.downloadConfig().then(() => {
controller.updateSaveList().then(() => {
@@ -268,7 +299,14 @@ export class Controller {
fetch(PUBLIC_URL + "/time", {
method: "POST",
body: pretty
}).then(
})
.then(response => {
if (!response.ok) {
toast.error(`Failed to sync RTC: ${response.status}`);
}
return response;
})
.then(
_ => controller.progressview.removeProgress("write_rtc")
)
}
@@ -288,9 +326,23 @@ export class Controller {
}
selfTest() {
controller.progressview.addIndeterminate("self_test", "Running board test")
fetch(PUBLIC_URL + "/boardtest", {
method: "POST"
})
.then(response => {
if (response.ok) {
toast.success("Board test completed");
} else {
toast.error(`Board test failed: ${response.status}`);
}
})
.catch(error => {
toast.error(`Board test error: ${error}`);
})
.finally(() => {
controller.progressview.removeProgress("self_test");
});
}
testNightLamp(active: boolean) {
@@ -298,16 +350,44 @@ export class Controller {
active: active
};
var pretty = JSON.stringify(body, undefined, 1);
controller.progressview.addIndeterminate("night_lamp_test", "Testing night lamp")
fetch(PUBLIC_URL + "/lamptest", {
method: "POST",
body: pretty
})
.then(response => {
if (response.ok) {
toast.success(`Night lamp ${active ? "enabled" : "disabled"} successfully`);
} else {
toast.error(`Night lamp test failed: ${response.status}`);
}
})
.catch(error => {
toast.error(`Night lamp test error: ${error}`);
})
.finally(() => {
controller.progressview.removeProgress("night_lamp_test");
});
}
testFertilizerPump() {
controller.progressview.addIndeterminate("fert_test", "Testing fertilizer pump")
fetch(PUBLIC_URL + "/fertilizerpumptest", {
method: "POST"
})
.then(response => {
if (response.ok) {
toast.success("Fertilizer pump test completed");
} else {
toast.error(`Fertilizer pump test failed: ${response.status}`);
}
})
.catch(error => {
toast.error(`Fertilizer pump test error: ${error}`);
})
.finally(() => {
controller.progressview.removeProgress("fert_test");
});
}
testPlant(plantId: number) {
@@ -344,6 +424,11 @@ export class Controller {
controller.plantViews.setPumpTestCurrent(plantId, response);
clearTimeout(timerId);
controller.progressview.removeProgress("test_pump");
if (!response.error) {
toast.success(`Pump ${plantId + 1} test completed successfully`);
} else {
toast.error(`Pump ${plantId + 1} test reported an error`);
}
}
)
}
@@ -428,13 +513,20 @@ export class Controller {
if (ajax.readyState === 4) {
clearTimeout(timerId);
controller.progressview.removeProgress("scan_ssid");
this.networkView.setScanResult(ajax.response as SSIDList)
if (ajax.status >= 200 && ajax.status < 300) {
this.networkView.setScanResult(ajax.response as SSIDList);
toast.success("WiFi scan completed");
// Also fetch detailed Wi-Fi information
this.scanWifiDetails();
} else {
toast.error(`WiFi scan failed: ${ajax.status}`);
}
}
};
ajax.onerror = (_) => {
clearTimeout(timerId);
controller.progressview.removeProgress("scan_ssid");
alert("Failed to start see console")
toast.error("Failed to start WiFi scan");
}
ajax.open("POST", PUBLIC_URL + "/wifiscan");
ajax.send();
@@ -481,12 +573,15 @@ export class Controller {
return fetch(PUBLIC_URL + "/moisture")
.then(response => response.json())
.then(json => json as Moistures)
.then(time => {
controller.plantViews.update(time.moisture_a, time.moisture_b)
.then(data => {
controller.plantViews.update(data.moisture_a, data.moisture_b, data.sensor_a_build_minutes, data.sensor_b_build_minutes)
clearTimeout(timerId);
if (!silent) {
controller.progressview.removeProgress("measure_moisture");
}
if (!silent) {
toast.success("Moisture measurement completed");
}
})
.catch(error => {
@@ -632,6 +727,7 @@ export class Controller {
};
await this.detectSensors(detection, true);
} catch (e) {
toast.error(`Auto-refresh error: ${e}`);
console.error("Auto-refresh error", e);
}
@@ -652,6 +748,7 @@ const tasks = [
{task: controller.updateRTCData, displayString: "Updating RTC Data"},
{task: controller.updateBatteryData, displayString: "Updating Battery Data"},
{task: controller.updateSolarData, displayString: "Updating Solar Data"},
{task: () => controller.measure_moisture(true), displayString: "Measuring Moisture"},
{task: controller.downloadConfig, displayString: "Downloading Configuration"},
{task: controller.version, displayString: "Fetching Version Information"},
{task: controller.updateSaveList, displayString: "Updating Save Slots"},
@@ -669,6 +766,7 @@ async function executeTasksSequentially() {
try {
await task();
} catch (error) {
toast.error(`Error executing task '${displayString}': ${error}`);
console.error(`Error executing task '${displayString}':`, error);
// Optionally, you can decide whether to continue or break on errors
break;
@@ -684,6 +782,11 @@ executeTasksSequentially().then(() => {
controller.progressview.removeProgress("rebooting");
window.addEventListener("beforeunload", (event) => {
// Only check for unsaved changes if initialConfig has been loaded
if (controller.initialConfig === null) {
return;
}
const currentConfig = controller.getConfig();
// Check if the current state differs from the initial configuration
@@ -85,7 +85,15 @@
<input class="mqttvalue" type="text" id="mqtt_password" placeholder="">
</div>
</div>
<div class="subcontainer">
<div class="flexcontainer">
<div class="subtitle">Wi-Fi Scan Results</div>
</div>
<div id="wifi-results">
<p>Scan for available networks to see signal strength</p>
</div>
</div>
</div>
</div>
@@ -1,7 +1,9 @@
import { Controller } from "./main";
import {NetworkConfig, SSIDList} from "./api";
import {NetworkConfig, SSIDList, WifiScanResult} from "./api";
export class NetworkConfigView {
private wifiResults: HTMLElement;
setScanResult(ssidList: SSIDList) {
this.ssidlist.innerHTML = ''
for (const ssid of ssidList.ssids) {
@@ -10,6 +12,47 @@ export class NetworkConfigView {
this.ssidlist.appendChild(wi);
}
}
async scanAndDisplayWifiDetails() {
try {
const response = await fetch('/wifi_details');
if (response.ok) {
const data: WifiScanResult[] = await response.json();
this.displayWifiResults(data);
}
} catch (error) {
console.error('Error fetching Wi-Fi details:', error);
this.displayWifiResults([]);
}
}
displayWifiResults(results: WifiScanResult[]) {
const wifiContainer = document.getElementById('wifi-results');
if (!wifiContainer) return;
if (results.length === 0) {
wifiContainer.innerHTML = '<p>No Wi-Fi networks found</p>';
return;
}
let html = '<table style="width:100%; border-collapse: collapse;">';
html += '<tr><th style="text-align:left; padding: 8px;">SSID</th>';
html += '<th style="text-align:left; padding: 8px;">Signal (RSSI)</th>';
html += '<th style="text-align:left; padding: 8px;">Channel</th>';
html += '<th style="text-align:left; padding: 8px;">Authentication</th></tr>';
results.forEach(result => {
html += '<tr style="border-bottom: 1px solid #ddd;">';
html += `<td style="padding: 8px;">${result.ssid}</td>`;
html += `<td style="padding: 8px;">${result.rssi} dBm</td>`;
html += `<td style="padding: 8px;">${result.channel}</td>`;
html += `<td style="padding: 8px;">${result.auth_method}</td>`;
html += '</tr>';
});
html += '</table>';
wifiContainer.innerHTML = html;
}
private readonly ap_ssid: HTMLInputElement;
private readonly ssid: HTMLInputElement;
private readonly password: HTMLInputElement;
@@ -47,9 +90,14 @@ export class NetworkConfigView {
this.ssidlist = document.getElementById("ssidlist") as HTMLElement
let scanWifiBtn = document.getElementById("scan") as HTMLButtonElement;
scanWifiBtn.onclick = function (){
scanWifiBtn.onclick = async () => {
controller.scanWifi();
}
// After Wi-Fi scan, fetch and display detailed results
await this.scanAndDisplayWifiDetails();
};
// Store wifiResults reference for later use
this.wifiResults = document.getElementById('wifi-results') as HTMLElement;
}
setConfig(network: NetworkConfig) {
@@ -36,11 +36,19 @@ export class PlantViews {
return rv
}
update(moisture_a: [string], moisture_b: [string]) {
update(moisture_a: [string], moisture_b: [string], sensor_a_build_minutes?: Array<number | null>, sensor_b_build_minutes?: Array<number | null>) {
for (let plantId = 0; plantId < PLANT_COUNT; plantId++) {
const a = moisture_a[plantId]
const b = moisture_b[plantId]
this.plants[plantId].setMeasurementResult(a, b)
// Update firmware build timestamps if provided
if (sensor_a_build_minutes && sensor_a_build_minutes[plantId] !== undefined) {
this.plants[plantId].setFirmwareBuild("sensor_a", sensor_a_build_minutes[plantId])
}
if (sensor_b_build_minutes && sensor_b_build_minutes[plantId] !== undefined) {
this.plants[plantId].setFirmwareBuild("sensor_b", sensor_b_build_minutes[plantId])
}
}
}
@@ -406,4 +414,12 @@ export class PlantView {
this.sensorAFwBuild.innerText = formatBuildMinutes(plantResult.sensor_a);
this.sensorBFwBuild.innerText = formatBuildMinutes(plantResult.sensor_b);
}
setFirmwareBuild(sensor: "sensor_a" | "sensor_b", buildMinutes: number | null) {
if (sensor === "sensor_a") {
this.sensorAFwBuild.innerText = formatBuildMinutes(buildMinutes);
} else {
this.sensorBFwBuild.innerText = formatBuildMinutes(buildMinutes);
}
}
}
@@ -1,5 +1,6 @@
import {Controller} from "./main";
import {BackupHeader} from "./api";
import {toast} from "./toast";
export class SubmitView {
json: HTMLDivElement;
@@ -26,25 +27,28 @@ export class SubmitView {
this.submit_status = document.getElementById("submit_status") as HTMLElement
this.submitFormBtn.onclick = () => {
controller.uploadConfig(this.json.textContent as string, (status: string) => {
if (status != "OK") {
// Show error toast (click to dismiss only)
const {toast} = require('./toast');
toast.error(status);
} else {
// Show info toast (auto hides after 5s, or click to dismiss sooner)
const {toast} = require('./toast');
toast.info('Config uploaded successfully');
}
toast.info(status);
this.submit_status.innerHTML = status;
});
}
this.backupBtn.onclick = () => {
controller.progressview.addIndeterminate("backup", "Backup to EEPROM running")
controller.backupConfig(this.json.textContent as string).then(saveStatus => {
if (saveStatus === "OK") {
toast.success("Configuration backup successful");
} else {
toast.error(`Backup failed: ${saveStatus}`);
}
controller.getBackupInfo().then(r => {
controller.progressview.removeProgress("backup")
this.submit_status.innerHTML = saveStatus;
});
}).catch(error => {
toast.error(`Backup error: ${error}`);
controller.getBackupInfo().then(r => {
controller.progressview.removeProgress("backup")
this.submit_status.innerHTML = "Error";
});
});
}
this.restoreBackupBtn.onclick = () => {
@@ -93,28 +93,28 @@ export class TankConfigView {
this.tank_measure_error.innerText = JSON.stringify(tankinfo.sensor_error) ;
this.tank_measure_error_container.classList.remove("hidden")
}
if (tankinfo.left_ml == null){
if (tankinfo.volume_ml == null){
this.tank_measure_ml_container.classList.add("hidden")
} else {
this.tank_measure_ml.innerText = tankinfo.left_ml.toString();
this.tank_measure_ml.innerText = tankinfo.volume_ml.toString();
this.tank_measure_ml_container.classList.remove("hidden")
}
if (tankinfo.percent == null){
if (tankinfo.fill_pct == null){
this.tank_measure_percent_container.classList.add("hidden")
} else {
this.tank_measure_percent.innerText = tankinfo.percent.toString();
this.tank_measure_percent.innerText = tankinfo.fill_pct.toString();
this.tank_measure_percent_container.classList.remove("hidden")
}
if (tankinfo.water_temp == null){
if (tankinfo.water_temp_c == null){
this.tank_measure_temperature_container.classList.add("hidden")
} else {
this.tank_measure_temperature.innerText = tankinfo.water_temp.toString();
this.tank_measure_temperature.innerText = tankinfo.water_temp_c.toString();
this.tank_measure_temperature_container.classList.remove("hidden")
}
if (tankinfo.raw == null){
if (tankinfo.fill_raw_v == null){
this.tank_measure_rawvolt_container.classList.add("hidden")
} else {
this.tank_measure_rawvolt.innerText = tankinfo.raw.toString();
this.tank_measure_rawvolt.innerText = tankinfo.fill_raw_v.toString();
this.tank_measure_rawvolt_container.classList.remove("hidden")
}
+410 -72
View File
@@ -1,94 +1,432 @@
class ToastService {
private container: HTMLElement;
private stylesInjected = false;
/**
* Toast notification service for PlantCtrl embedded web interface
* Provides non-blocking notifications with auto-dismiss and click-to-close functionality
*/
constructor() {
this.container = this.ensureContainer();
this.injectStyles();
}
const TOAST_container_ID = 'toast-container';
const TOAST_STYLES_KEY = 'toast-styles-injected';
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);
});
}
interface ToastOptions {
duration?: number;
dismissible?: boolean;
}
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));
}
interface ToastData {
id: string;
type: 'info' | 'success' | 'warning' | 'error';
message: string;
createdAt: number;
element?: HTMLElement;
}
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);
/**
* Toast service for displaying notifications
*/
export class ToastService {
private container: HTMLElement | null = null;
private activeToasts: Map<string, ToastData> = new Map();
private maxToasts: number = 5;
// Default configuration
private defaultDuration: number = 5000; // 5 seconds for info messages
private errorDuration: number = 10000; // 10 seconds for error messages
constructor() {
this.init();
}
return container;
}
private injectStyles() {
if (this.stylesInjected) return;
const style = document.createElement('style');
style.textContent = `
/**
* Initialize the toast container and inject styles
*/
private init(): void {
this.ensureContainer();
this.injectStyles();
}
/**
* Get or create the toast container element
*/
private ensureContainer(): HTMLElement {
if (this.container) return this.container;
let container = document.getElementById(TOAST_container_ID);
if (!container) {
container = document.createElement('div');
container.id = TOAST_container_ID;
container.setAttribute('role', 'region');
container.setAttribute('aria-label', 'Notifications');
document.body.appendChild(container);
}
this.container = container;
return container;
}
/**
* Inject toast styles if not already injected
*/
private injectStyles(): void {
if (document.querySelector(`style[data-id="${TOAST_STYLES_KEY}"]`)) {
return;
}
const style = document.createElement('style');
style.setAttribute('data-id', TOAST_STYLES_KEY);
style.textContent = `
#toast-container {
position: fixed;
top: 12px;
right: 12px;
top: 16px;
right: 16px;
display: flex;
flex-direction: column;
gap: 8px;
gap: 10px;
z-index: 9999;
max-width: 400px;
pointer-events: none;
}
.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;
background: #fff;
border-left: 4px solid transparent;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
border-radius: 8px;
padding: 12px 16px;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
font-size: 14px;
line-height: 1.3;
line-height: 1.4;
color: #333;
max-width: 100%;
pointer-events: auto;
animation: toast-slide-in 0.3s cubic-bezier(0.4, 0, 0.2, 1),
toast-fade-in 0.3s ease-out;
display: flex;
align-items: center;
gap: 12px;
}
.toast.info {
background-color: #d4edda; /* green-ish */
color: #155724;
border-left: 4px solid #28a745;
border-color: #3b82f6;
background: linear-gradient(135deg, #eff6ff 0%, #dbeafe 100%);
}
.toast.success {
border-color: #22c55e;
background: linear-gradient(135deg, #f0fdf4 0%, #dcfce7 100%);
}
.toast.warning {
border-color: #f59e0b;
background: linear-gradient(135deg, #fffbeb 0%, #fef3c7 100%);
}
.toast.error {
background-color: #f8d7da; /* red-ish */
color: #721c24;
border-left: 4px solid #dc3545;
border-color: #ef4444;
background: linear-gradient(135deg, #fef2f2 0%, #fee2e2 100%);
}
`;
document.head.appendChild(style);
this.stylesInjected = true;
.toast:hover {
transform: translateX(-2px);
box-shadow: 0 6px 16px rgba(0, 0, 0, 0.2);
}
.toast-icon {
flex-shrink: 0;
font-size: 18px;
}
.toast-message {
flex-grow: 1;
word-wrap: break-word;
overflow-wrap: anywhere;
}
.toast-close-btn {
flex-shrink: 0;
background: none;
border: none;
cursor: pointer;
padding: 4px;
margin-left: -4px;
opacity: 0.6;
transition: opacity 0.2s;
color: inherit;
}
.toast-close-btn:hover {
opacity: 1;
}
@keyframes toast-slide-in {
from {
transform: translateX(100%);
opacity: 0;
}
to {
transform: translateX(0);
opacity: 1;
}
}
@keyframes toast-fade-in {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
@keyframes toast-dismiss {
from {
transform: translateX(0);
opacity: 1;
}
to {
transform: translateX(100%);
opacity: 0;
}
}
`;
document.head.appendChild(style);
}
/**
* Create a unique ID for toast messages
*/
private generateId(): string {
return `toast-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;
}
/**
* Create a toast element
*/
private createToast(type: 'info' | 'success' | 'warning' | 'error', message: string): HTMLElement {
const div = document.createElement('div');
div.className = 'toast';
div.classList.add(type);
// Add icon based on type
const icon = this.getIconForType(type);
div.innerHTML = `
<span class="toast-icon">${icon}</span>
<span class="toast-message">${this.escapeHtml(message)}</span>
<button class="toast-close-btn" aria-label="Dismiss notification">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<line x1="18" y1="6" x2="6" y2="18"></line>
<line x1="6" y1="6" x2="18" y2="18"></line>
</svg>
</button>
`;
return div;
}
/**
* Get icon based on toast type
*/
private getIconForType(type: 'info' | 'success' | 'warning' | 'error'): string {
const icons: Record<string, string> = {
info: '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"></circle><line x1="12" y1="16" x2="12" y2="12"></line><line x1="12" y1="8" x2="12.01" y2="8"></line></svg>',
success: '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"></path><polyline points="22 4 12 14.01 9 11.01"></polyline></svg>',
warning: '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"></path><line x1="12" y1="9" x2="12" y2="13"></line><line x1="12" y1="17" x2="12.01" y2="17"></line></svg>',
error: '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"></circle><line x1="15" y1="9" x2="9" y2="15"></line><line x1="9" y1="9" x2="15" y2="15"></line></svg>'
};
return icons[type] || icons.info;
}
/**
* Escape HTML to prevent XSS
*/
private escapeHtml(text: string): string {
const map: Record<string, string> = {
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
'"': '&quot;',
"'": '&#039;'
};
return text.replace(/[&<>"']/g, (char) => map[char] || char);
}
/**
* Display an info toast notification
*/
info(message: string, options?: ToastOptions): void {
const duration = options?.duration ?? this.defaultDuration;
this.showToast('info', message, duration);
}
/**
* Display a success toast notification
*/
success(message: string, options?: ToastOptions): void {
const duration = options?.duration ?? this.defaultDuration;
this.showToast('success', message, duration);
}
/**
* Display a warning toast notification
*/
warning(message: string, options?: ToastOptions): void {
const duration = options?.duration ?? this.defaultDuration;
this.showToast('warning', message, duration);
}
/**
* Display an error toast notification
*/
error(message: string, options?: ToastOptions): void {
console.error(`[Toast Error] ${message}`);
const duration = options?.duration ?? this.errorDuration;
this.showToast('error', message, duration);
}
/**
* Show a toast notification with the given type
*/
private showToast(type: 'info' | 'success' | 'warning' | 'error', message: string, duration: number): void {
// Limit the number of concurrent toasts
this.limitToasts();
const id = this.generateId();
const element = this.createToast(type, message);
const container = this.ensureContainer();
// Add to active toasts
this.activeToasts.set(id, { id, type, message, createdAt: Date.now() });
// Append to container
container.appendChild(element);
// Store reference
this.activeToasts.get(id)!.element = element;
// Set up auto-dismiss timer
let dismissTimer: number | undefined;
const scheduleDismiss = () => {
if (duration > 0) {
dismissTimer = window.setTimeout(() => this.dismiss(id), duration);
}
};
// Setup click to dismiss
const handleClick = () => {
if (dismissTimer !== undefined) {
window.clearTimeout(dismissTimer);
dismissTimer = undefined;
}
this.dismiss(id);
};
// Setup close button handler
const closeBtn = element.querySelector('.toast-close-btn');
if (closeBtn) {
closeBtn.addEventListener('click', (e) => {
e.stopPropagation();
handleClick();
});
}
// Setup click on toast to dismiss
element.addEventListener('click', handleClick);
// Start timer
scheduleDismiss();
}
/**
* Dismiss a toast by ID
*/
dismiss(id: string): void {
const toastData = this.activeToasts.get(id);
if (!toastData || !toastData.element) return;
const element = toastData.element;
// Add dismiss animation
element.style.animation = 'toast-dismiss 0.2s ease-in forwards';
// Remove from DOM after animation
setTimeout(() => {
if (element.parentElement) {
element.parentElement.removeChild(element);
}
this.activeToasts.delete(id);
// Ensure container exists before trying to append
if (this.container) {
this.moveToasts();
}
}, 200);
}
/**
* Remove a toast by element reference
*/
dismissElement(element: HTMLElement): void {
const entries = Array.from(this.activeToasts.entries());
for (const [id, data] of entries) {
if (data.element === element) {
this.dismiss(id);
break;
}
}
}
/**
* Limit the number of concurrent toasts
*/
private limitToasts(): void {
if (this.container && this.activeToasts.size >= this.maxToasts) {
// Dismiss the oldest toast
const oldestId = Array.from(this.activeToasts.keys())[0];
if (oldestId) {
this.dismiss(oldestId);
}
}
}
/**
* Move toasts to ensure proper stacking
*/
private moveToasts(): void {
if (!this.container) return;
// Remove any empty container
if (this.activeToasts.size === 0) {
if (this.container.parentElement) {
this.container.parentElement.removeChild(this.container);
}
this.container = null;
}
}
/**
* Clear all active toasts
*/
clear(): void {
const ids = Array.from(this.activeToasts.keys());
for (const id of ids) {
this.dismiss(id);
}
}
/**
* Get the number of active toasts
*/
getActiveCount(): number {
return this.activeToasts.size;
}
/**
* Set the maximum number of concurrent toasts
*/
setMaxToasts(count: number): void {
this.maxToasts = count;
this.limitToasts();
}
}
// Export a singleton instance
export const toast = new ToastService();