Compare commits
35 Commits
a84a325852
...
legacy/v3-
| Author | SHA1 | Date | |
|---|---|---|---|
|
961f5748c6
|
|||
|
a66843a455
|
|||
|
379808e659
|
|||
|
e2b2734301
|
|||
|
43a0c3c274
|
|||
|
2b83d99820
|
|||
|
4cc70f96de
|
|||
|
c90174be27
|
|||
|
b569fa4b04
|
|||
|
f71ca7ec6d
|
|||
|
28f7ae20ef
|
|||
|
52049c456e
|
|||
|
e3b7648a3f
|
|||
|
08ee9018cf
|
|||
|
c2929a65ae
|
|||
|
0b386b0ca3
|
|||
|
0ab1ea3635
|
|||
|
ae73f12d1c
|
|||
|
cfe1c2c6d8
|
|||
|
578379c0d9
|
|||
|
2ff219a1cb
|
|||
|
96023c8dc3
|
|||
|
7497a8c05d
|
|||
|
d3d8d829be
|
|||
|
6889ba4561
|
|||
|
18095349f3
|
|||
|
3d8fd893f5
|
|||
|
1bea7ef2f4
|
|||
|
f5b9674840
|
|||
|
6f22881007
|
|||
|
1d8af1b6c4
|
|||
|
2c532359fc
|
|||
|
53819484fb
|
|||
|
1151d099cf
|
|||
|
3feaacd460
|
9
.gitignore
vendored
9
.gitignore
vendored
@@ -8,6 +8,15 @@ 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/
|
||||||
|
|||||||
22
rust/all.sh
Executable file
22
rust/all.sh
Executable file
@@ -0,0 +1,22 @@
|
|||||||
|
#!/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
|
||||||
@@ -1,5 +1,3 @@
|
|||||||
use std::process::Command;
|
|
||||||
|
|
||||||
use vergen::EmitBuilder;
|
use vergen::EmitBuilder;
|
||||||
|
|
||||||
fn linker_be_nice() {
|
fn linker_be_nice() {
|
||||||
@@ -50,72 +48,9 @@ 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();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
21
rust/build_website.sh
Executable file
21
rust/build_website.sh
Executable file
@@ -0,0 +1,21 @@
|
|||||||
|
#!/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
|
||||||
7
rust/erase_ota.sh
Executable file
7
rust/erase_ota.sh
Executable file
@@ -0,0 +1,7 @@
|
|||||||
|
#!/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"
|
||||||
15
rust/flash.sh
Executable file
15
rust/flash.sh
Executable file
@@ -0,0 +1,15 @@
|
|||||||
|
#!/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
|
||||||
17
rust/image_build.sh
Executable file
17
rust/image_build.sh
Executable file
@@ -0,0 +1,17 @@
|
|||||||
|
#!/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"
|
||||||
@@ -27,20 +27,22 @@ pub trait BatteryInteraction {
|
|||||||
|
|
||||||
#[derive(Debug, Serialize)]
|
#[derive(Debug, Serialize)]
|
||||||
pub struct BatteryInfo {
|
pub struct BatteryInfo {
|
||||||
pub voltage_milli_volt: u16,
|
pub voltage_mv: Option<u16>,
|
||||||
pub average_current_milli_ampere: i16,
|
pub avg_current_ma: Option<i16>,
|
||||||
pub cycle_count: u16,
|
pub soc_pct: Option<f32>,
|
||||||
pub design_milli_ampere_hour: u16,
|
pub soh_pct: Option<u16>,
|
||||||
pub remaining_milli_ampere_hour: u16,
|
pub temperature_c: Option<u16>,
|
||||||
pub state_of_charge: f32,
|
pub cycle_count: Option<u16>,
|
||||||
pub state_of_health: u16,
|
pub remaining_mah: Option<u16>,
|
||||||
pub temperature: u16,
|
pub design_mah: Option<u16>,
|
||||||
|
pub error: Option<BatteryError>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Serialize)]
|
#[derive(Debug, Serialize)]
|
||||||
|
#[serde(tag = "kind")]
|
||||||
pub enum BatteryError {
|
pub enum BatteryError {
|
||||||
NoBatteryMonitor,
|
NoBatteryMonitor,
|
||||||
CommunicationError(String),
|
CommunicationError { message: String },
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Serialize)]
|
#[derive(Debug, Serialize)]
|
||||||
@@ -180,14 +182,15 @@ 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_milli_volt: self.voltage_milli_volt().await?,
|
voltage_mv: Some(self.voltage_milli_volt().await?),
|
||||||
average_current_milli_ampere: self.average_current_milli_ampere().await?,
|
avg_current_ma: Some(self.average_current_milli_ampere().await?),
|
||||||
cycle_count: self.cycle_count().await?,
|
soc_pct: Some(self.state_charge_percent().await?),
|
||||||
design_milli_ampere_hour: self.design_milli_ampere_hour().await?,
|
soh_pct: Some(self.state_health_percent().await?),
|
||||||
remaining_milli_ampere_hour: self.remaining_milli_ampere_hour().await?,
|
temperature_c: Some(self.bat_temperature().await?),
|
||||||
state_of_charge: self.state_charge_percent().await?,
|
cycle_count: Some(self.cycle_count().await?),
|
||||||
state_of_health: self.state_health_percent().await?,
|
remaining_mah: Some(self.remaining_milli_ampere_hour().await?),
|
||||||
temperature: self.bat_temperature().await?,
|
design_mah: Some(self.design_milli_ampere_hour().await?),
|
||||||
|
error: None,
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -17,12 +17,9 @@ use core::net::{IpAddr, Ipv4Addr, SocketAddr};
|
|||||||
use core::str::FromStr;
|
use core::str::FromStr;
|
||||||
use core::sync::atomic::Ordering;
|
use core::sync::atomic::Ordering;
|
||||||
use embassy_executor::Spawner;
|
use embassy_executor::Spawner;
|
||||||
use embassy_net::dns::DnsQueryType;
|
|
||||||
use embassy_net::udp::{PacketMetadata, UdpSocket};
|
|
||||||
use embassy_net::{DhcpConfig, IpAddress, Ipv4Cidr, Runner, Stack, StackResources, StaticConfigV4};
|
use embassy_net::{DhcpConfig, IpAddress, Ipv4Cidr, Runner, Stack, StackResources, StaticConfigV4};
|
||||||
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
|
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
|
||||||
use embassy_sync::mutex::{Mutex, MutexGuard};
|
use embassy_sync::mutex::{Mutex, MutexGuard};
|
||||||
use embassy_sync::once_lock::OnceLock;
|
|
||||||
use embassy_time::{Duration, Timer, WithTimeout};
|
use embassy_time::{Duration, Timer, WithTimeout};
|
||||||
use embedded_storage::nor_flash::{check_erase, NorFlash, ReadNorFlash, RmwNorFlashStorage};
|
use embedded_storage::nor_flash::{check_erase, NorFlash, ReadNorFlash, RmwNorFlashStorage};
|
||||||
use esp_bootloader_esp_idf::ota::OtaImageState::Valid;
|
use esp_bootloader_esp_idf::ota::OtaImageState::Valid;
|
||||||
@@ -44,14 +41,10 @@ use esp_storage::FlashStorage;
|
|||||||
use littlefs2::fs::Filesystem;
|
use littlefs2::fs::Filesystem;
|
||||||
use littlefs2_core::{FileType, PathBuf, SeekFrom};
|
use littlefs2_core::{FileType, PathBuf, SeekFrom};
|
||||||
use log::{info, warn, error};
|
use log::{info, warn, error};
|
||||||
use mcutie::{
|
|
||||||
Error, McutieBuilder, McutieReceiver, McutieTask, MqttMessage, PublishDisplay, Publishable,
|
|
||||||
QoS, Topic,
|
|
||||||
};
|
|
||||||
use portable_atomic::AtomicBool;
|
use portable_atomic::AtomicBool;
|
||||||
use sntpc::{NtpContext, NtpTimestampGenerator, NtpUdpSocket, get_time};
|
|
||||||
|
|
||||||
use super::shared_flash::MutexFlashStorage;
|
use super::shared_flash::MutexFlashStorage;
|
||||||
|
use crate::network::{net_task, run_dhcp};
|
||||||
|
|
||||||
#[esp_hal::ram(unstable(rtc_fast), unstable(persistent))]
|
#[esp_hal::ram(unstable(rtc_fast), unstable(persistent))]
|
||||||
static mut LAST_WATERING_TIMESTAMP: [i64; PLANT_COUNT] = [0; PLANT_COUNT];
|
static mut LAST_WATERING_TIMESTAMP: [i64; PLANT_COUNT] = [0; PLANT_COUNT];
|
||||||
@@ -66,12 +59,6 @@ static mut LAST_CORROSION_PROTECTION_CHECK_DAY: i8 = -1;
|
|||||||
|
|
||||||
|
|
||||||
const CONFIG_FILE: &str = "config.json";
|
const CONFIG_FILE: &str = "config.json";
|
||||||
const NTP_SERVER: &str = "pool.ntp.org";
|
|
||||||
|
|
||||||
static MQTT_CONNECTED_EVENT_RECEIVED: AtomicBool = AtomicBool::new(false);
|
|
||||||
static MQTT_ROUND_TRIP_RECEIVED: AtomicBool = AtomicBool::new(false);
|
|
||||||
pub static MQTT_STAY_ALIVE: AtomicBool = AtomicBool::new(false);
|
|
||||||
static MQTT_BASE_TOPIC: OnceLock<String> = OnceLock::new();
|
|
||||||
|
|
||||||
#[derive(Serialize, Debug)]
|
#[derive(Serialize, Debug)]
|
||||||
pub struct FileInfo {
|
pub struct FileInfo {
|
||||||
@@ -86,11 +73,6 @@ pub struct FileList {
|
|||||||
files: Vec<FileInfo>,
|
files: Vec<FileInfo>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Copy, Clone, Default)]
|
|
||||||
struct Timestamp {
|
|
||||||
stamp: DateTime<Utc>,
|
|
||||||
}
|
|
||||||
|
|
||||||
// Minimal esp-idf equivalent for gpio_hold on esp32c6 via ROM functions
|
// Minimal esp-idf equivalent for gpio_hold on esp32c6 via ROM functions
|
||||||
extern "C" {
|
extern "C" {
|
||||||
fn gpio_pad_hold(gpio_num: u32);
|
fn gpio_pad_hold(gpio_num: u32);
|
||||||
@@ -107,53 +89,6 @@ pub fn hold_disable(gpio_num: u8) {
|
|||||||
unsafe { gpio_pad_unhold(gpio_num as u32) }
|
unsafe { gpio_pad_unhold(gpio_num as u32) }
|
||||||
}
|
}
|
||||||
|
|
||||||
impl NtpTimestampGenerator for Timestamp {
|
|
||||||
fn init(&mut self) {
|
|
||||||
self.stamp = DateTime::default();
|
|
||||||
}
|
|
||||||
|
|
||||||
fn timestamp_sec(&self) -> u64 {
|
|
||||||
self.stamp.timestamp() as u64
|
|
||||||
}
|
|
||||||
|
|
||||||
fn timestamp_subsec_micros(&self) -> u32 {
|
|
||||||
self.stamp.timestamp_subsec_micros()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
struct EmbassyNtpSocket<'a, 'b> {
|
|
||||||
socket: &'a UdpSocket<'b>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a, 'b> EmbassyNtpSocket<'a, 'b> {
|
|
||||||
fn new(socket: &'a UdpSocket<'b>) -> Self {
|
|
||||||
Self { socket }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl NtpUdpSocket for EmbassyNtpSocket<'_, '_> {
|
|
||||||
async fn send_to(&self, buf: &[u8], addr: SocketAddr) -> sntpc::Result<usize> {
|
|
||||||
self.socket
|
|
||||||
.send_to(buf, addr)
|
|
||||||
.await
|
|
||||||
.map_err(|_| sntpc::Error::Network)?;
|
|
||||||
Ok(buf.len())
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn recv_from(&self, buf: &mut [u8]) -> sntpc::Result<(usize, SocketAddr)> {
|
|
||||||
let (len, metadata) = self
|
|
||||||
.socket
|
|
||||||
.recv_from(buf)
|
|
||||||
.await
|
|
||||||
.map_err(|_| sntpc::Error::Network)?;
|
|
||||||
let addr = match metadata.endpoint.addr {
|
|
||||||
IpAddress::Ipv4(ip) => IpAddr::V4(ip),
|
|
||||||
IpAddress::Ipv6(ip) => IpAddr::V6(ip),
|
|
||||||
};
|
|
||||||
Ok((len, SocketAddr::new(addr, metadata.endpoint.port)))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
pub struct Esp<'a> {
|
pub struct Esp<'a> {
|
||||||
pub fs: Arc<Mutex<CriticalSectionRawMutex, Filesystem<'static, LittleFs2Filesystem>>>,
|
pub fs: Arc<Mutex<CriticalSectionRawMutex, Filesystem<'static, LittleFs2Filesystem>>>,
|
||||||
pub rng: Rng,
|
pub rng: Rng,
|
||||||
@@ -185,15 +120,6 @@ pub struct Esp<'a> {
|
|||||||
// CPU cores/threads, reconsider this.
|
// CPU cores/threads, reconsider this.
|
||||||
unsafe impl Send for Esp<'_> {}
|
unsafe impl Send for Esp<'_> {}
|
||||||
|
|
||||||
macro_rules! mk_static {
|
|
||||||
($t:ty,$val:expr) => {{
|
|
||||||
static STATIC_CELL: static_cell::StaticCell<$t> = static_cell::StaticCell::new();
|
|
||||||
#[deny(unused_attributes)]
|
|
||||||
let x = STATIC_CELL.uninit().write(($val));
|
|
||||||
x
|
|
||||||
}};
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Esp<'_> {
|
impl Esp<'_> {
|
||||||
pub fn get_time(&self) -> DateTime<Utc> {
|
pub fn get_time(&self) -> DateTime<Utc> {
|
||||||
DateTime::from_timestamp_micros(self.rtc.current_time_us() as i64)
|
DateTime::from_timestamp_micros(self.rtc.current_time_us() as i64)
|
||||||
@@ -355,66 +281,6 @@ impl Esp<'_> {
|
|||||||
self.boot_button.is_low()
|
self.boot_button.is_low()
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) async fn sntp(
|
|
||||||
&mut self,
|
|
||||||
_max_wait_ms: u32,
|
|
||||||
stack: Stack<'_>,
|
|
||||||
) -> FatResult<DateTime<Utc>> {
|
|
||||||
println!("start sntp");
|
|
||||||
let mut rx_meta = [PacketMetadata::EMPTY; 16];
|
|
||||||
let mut rx_buffer = [0; 4096];
|
|
||||||
let mut tx_meta = [PacketMetadata::EMPTY; 16];
|
|
||||||
let mut tx_buffer = [0; 4096];
|
|
||||||
|
|
||||||
let mut socket = UdpSocket::new(
|
|
||||||
stack,
|
|
||||||
&mut rx_meta,
|
|
||||||
&mut rx_buffer,
|
|
||||||
&mut tx_meta,
|
|
||||||
&mut tx_buffer,
|
|
||||||
);
|
|
||||||
socket.bind(123).context("Could not bind UDP socket")?;
|
|
||||||
|
|
||||||
let context = NtpContext::new(Timestamp::default());
|
|
||||||
let ntp_socket = EmbassyNtpSocket::new(&socket);
|
|
||||||
|
|
||||||
let ntp_addrs = stack
|
|
||||||
.dns_query(NTP_SERVER, DnsQueryType::A)
|
|
||||||
.await
|
|
||||||
.context("Failed to resolve DNS")?;
|
|
||||||
|
|
||||||
if ntp_addrs.is_empty() {
|
|
||||||
bail!("No IP addresses found for NTP server");
|
|
||||||
}
|
|
||||||
let ntp = ntp_addrs[0];
|
|
||||||
info!("NTP server: {ntp:?}");
|
|
||||||
|
|
||||||
let mut counter = 0;
|
|
||||||
loop {
|
|
||||||
let addr: IpAddr = ntp.into();
|
|
||||||
let timeout = get_time(SocketAddr::from((addr, 123)), &ntp_socket, context)
|
|
||||||
.with_timeout(Duration::from_millis((_max_wait_ms / 10) as u64))
|
|
||||||
.await;
|
|
||||||
|
|
||||||
match timeout {
|
|
||||||
Ok(result) => {
|
|
||||||
let time = result?;
|
|
||||||
info!("Time: {time:?}");
|
|
||||||
return DateTime::from_timestamp(time.seconds as i64, 0)
|
|
||||||
.context("Could not convert Sntp result");
|
|
||||||
}
|
|
||||||
Err(err) => {
|
|
||||||
warn!("sntp timeout, retry: {err:?}");
|
|
||||||
counter += 1;
|
|
||||||
if counter > 10 {
|
|
||||||
bail!("Failed to get time from NTP server");
|
|
||||||
}
|
|
||||||
Timer::after(Duration::from_millis(100)).await;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) async fn wifi_scan(&mut self) -> FatResult<Vec<AccessPointInfo>> {
|
pub(crate) async fn wifi_scan(&mut self) -> FatResult<Vec<AccessPointInfo>> {
|
||||||
info!("start wifi scan");
|
info!("start wifi scan");
|
||||||
let mut lock = self.controller.try_lock()?;
|
let mut lock = self.controller.try_lock()?;
|
||||||
@@ -472,160 +338,6 @@ impl Esp<'_> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) async fn wifi_ap(&mut self, spawner: Spawner) -> FatResult<Stack<'static>> {
|
|
||||||
let ssid = match self.load_config().await {
|
|
||||||
Ok(config) => config.network.ap_ssid.as_str().to_string(),
|
|
||||||
Err(_) => "PlantCtrl Emergency Mode".to_string(),
|
|
||||||
};
|
|
||||||
|
|
||||||
let device = self
|
|
||||||
.interface_ap
|
|
||||||
.take()
|
|
||||||
.context("AP interface already taken")?;
|
|
||||||
let gw_ip_addr = Ipv4Addr::new(192, 168, 71, 1);
|
|
||||||
|
|
||||||
let config = embassy_net::Config::ipv4_static(StaticConfigV4 {
|
|
||||||
address: Ipv4Cidr::new(gw_ip_addr, 24),
|
|
||||||
gateway: Some(gw_ip_addr),
|
|
||||||
dns_servers: Default::default(),
|
|
||||||
});
|
|
||||||
|
|
||||||
let seed = (self.rng.random() as u64) << 32 | self.rng.random() as u64;
|
|
||||||
|
|
||||||
println!("init secondary stack");
|
|
||||||
// Init network stack
|
|
||||||
let (stack, runner) = embassy_net::new(
|
|
||||||
device,
|
|
||||||
config,
|
|
||||||
mk_static!(StackResources<4>, StackResources::<4>::new()),
|
|
||||||
seed,
|
|
||||||
);
|
|
||||||
let stack = mk_static!(Stack, stack);
|
|
||||||
|
|
||||||
let client_config =
|
|
||||||
Config::AccessPoint(AccessPointConfig::default().with_ssid(ssid.clone()));
|
|
||||||
self.controller.lock().await.set_config(&client_config)?;
|
|
||||||
|
|
||||||
println!("start net task");
|
|
||||||
spawner.spawn(net_task(runner)?);
|
|
||||||
println!("run dhcp");
|
|
||||||
spawner.spawn(run_dhcp(*stack, gw_ip_addr)?);
|
|
||||||
|
|
||||||
loop {
|
|
||||||
if stack.is_link_up() {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
Timer::after(Duration::from_millis(500)).await;
|
|
||||||
}
|
|
||||||
while !stack.is_config_up() {
|
|
||||||
Timer::after(Duration::from_millis(100)).await
|
|
||||||
}
|
|
||||||
println!("Connect to the AP `${ssid}` and point your browser to http://{gw_ip_addr}/");
|
|
||||||
stack
|
|
||||||
.config_v4()
|
|
||||||
.inspect(|c| println!("ipv4 config: {c:?}"));
|
|
||||||
|
|
||||||
Ok(*stack)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) async fn wifi(
|
|
||||||
&mut self,
|
|
||||||
network_config: &NetworkConfig,
|
|
||||||
spawner: Spawner,
|
|
||||||
) -> FatResult<Stack<'static>> {
|
|
||||||
esp_radio::wifi_set_log_verbose();
|
|
||||||
let ssid = match &network_config.ssid {
|
|
||||||
Some(ssid) => {
|
|
||||||
if ssid.is_empty() {
|
|
||||||
bail!("Wifi ssid was empty")
|
|
||||||
}
|
|
||||||
ssid.to_string()
|
|
||||||
}
|
|
||||||
None => {
|
|
||||||
bail!("Wifi ssid was empty")
|
|
||||||
}
|
|
||||||
};
|
|
||||||
info!("attempting to connect wifi {ssid}");
|
|
||||||
let password = match network_config.password {
|
|
||||||
Some(ref password) => password.to_string(),
|
|
||||||
None => "".to_string(),
|
|
||||||
};
|
|
||||||
let max_wait = network_config.max_wait;
|
|
||||||
|
|
||||||
let device = self
|
|
||||||
.interface_sta
|
|
||||||
.take()
|
|
||||||
.context("STA interface already taken")?;
|
|
||||||
let config = embassy_net::Config::dhcpv4(DhcpConfig::default());
|
|
||||||
|
|
||||||
let seed = (self.rng.random() as u64) << 32 | self.rng.random() as u64;
|
|
||||||
|
|
||||||
// Init network stack
|
|
||||||
let (stack, runner) = embassy_net::new(
|
|
||||||
device,
|
|
||||||
config,
|
|
||||||
mk_static!(StackResources<8>, StackResources::<8>::new()),
|
|
||||||
seed,
|
|
||||||
);
|
|
||||||
let stack = mk_static!(Stack, stack);
|
|
||||||
|
|
||||||
let auth_method = if password.is_empty() {
|
|
||||||
AuthenticationMethod::None
|
|
||||||
} 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);
|
|
||||||
|
|
||||||
self.controller
|
|
||||||
.lock()
|
|
||||||
.await
|
|
||||||
.set_config(&Config::Station(client_config))?;
|
|
||||||
spawner.spawn(net_task(runner)?);
|
|
||||||
self.controller
|
|
||||||
.lock()
|
|
||||||
.await
|
|
||||||
.connect_async()
|
|
||||||
.with_timeout(Duration::from_millis(max_wait as u64 * 1000))
|
|
||||||
.await
|
|
||||||
.context("Timeout waiting for wifi sta connected")??;
|
|
||||||
|
|
||||||
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;
|
|
||||||
|
|
||||||
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
|
|
||||||
}
|
|
||||||
Ok::<(), FatError>(())
|
|
||||||
}
|
|
||||||
.with_timeout(Duration::from_millis(max_wait as u64 * 1000))
|
|
||||||
.await;
|
|
||||||
|
|
||||||
if res.is_err() {
|
|
||||||
bail!("Timeout waiting for wifi config up")
|
|
||||||
}
|
|
||||||
|
|
||||||
info!("Connected WIFI, dhcp: {:?}", stack.config_v4());
|
|
||||||
Ok(*stack)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn deep_sleep_ms(&mut self, duration_in_ms: u64) -> ! {
|
pub fn deep_sleep_ms(&mut self, duration_in_ms: u64) -> ! {
|
||||||
// Mark the current OTA image as valid if we reached here while in pending verify.
|
// Mark the current OTA image as valid if we reached here while in pending verify.
|
||||||
if let Ok(cur) = self.ota.current_ota_state() {
|
if let Ok(cur) = self.ota.current_ota_state() {
|
||||||
@@ -740,275 +452,4 @@ impl Esp<'_> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) async fn mqtt(
|
|
||||||
&mut self,
|
|
||||||
network_config: &'static NetworkConfig,
|
|
||||||
stack: Stack<'static>,
|
|
||||||
spawner: Spawner,
|
|
||||||
) -> FatResult<()> {
|
|
||||||
let base_topic = network_config
|
|
||||||
.base_topic
|
|
||||||
.as_ref()
|
|
||||||
.context("missing base topic")?;
|
|
||||||
if base_topic.is_empty() {
|
|
||||||
bail!("Mqtt base_topic was empty")
|
|
||||||
}
|
|
||||||
MQTT_BASE_TOPIC
|
|
||||||
.init(base_topic.to_string())
|
|
||||||
.map_err(|_| FatError::String {
|
|
||||||
error: "Error setting basetopic".to_string(),
|
|
||||||
})?;
|
|
||||||
|
|
||||||
let mqtt_url = network_config
|
|
||||||
.mqtt_url
|
|
||||||
.as_ref()
|
|
||||||
.context("missing mqtt url")?;
|
|
||||||
if mqtt_url.is_empty() {
|
|
||||||
bail!("Mqtt url was empty")
|
|
||||||
}
|
|
||||||
|
|
||||||
let last_will_topic = format!("{base_topic}/state");
|
|
||||||
let round_trip_topic = format!("{base_topic}/internal/roundtrip");
|
|
||||||
let stay_alive_topic = format!("{base_topic}/stay_alive");
|
|
||||||
|
|
||||||
let mut builder: McutieBuilder<'_, String, PublishDisplay<String, &str>, 0> =
|
|
||||||
McutieBuilder::new(stack, "plant ctrl", mqtt_url);
|
|
||||||
if let (Some(mqtt_user), Some(mqtt_password)) = (
|
|
||||||
network_config.mqtt_user.as_ref(),
|
|
||||||
network_config.mqtt_password.as_ref(),
|
|
||||||
) {
|
|
||||||
builder = builder.with_authentication(mqtt_user, mqtt_password);
|
|
||||||
info!("With authentification");
|
|
||||||
}
|
|
||||||
|
|
||||||
let lwt = Topic::General(last_will_topic);
|
|
||||||
let lwt = mk_static!(Topic<String>, lwt);
|
|
||||||
let lwt = lwt.with_display("lost").retain(true).qos(QoS::AtLeastOnce);
|
|
||||||
builder = builder.with_last_will(lwt);
|
|
||||||
//TODO make configurable
|
|
||||||
builder = builder.with_device_id("plantctrl");
|
|
||||||
|
|
||||||
let builder: McutieBuilder<'_, String, PublishDisplay<String, &str>, 2> = builder
|
|
||||||
.with_subscriptions([
|
|
||||||
Topic::General(round_trip_topic.clone()),
|
|
||||||
Topic::General(stay_alive_topic.clone()),
|
|
||||||
]);
|
|
||||||
|
|
||||||
let keep_alive = Duration::from_secs(60 * 60 * 2).as_secs() as u16;
|
|
||||||
let (receiver, task) = builder.build(keep_alive);
|
|
||||||
|
|
||||||
spawner.spawn(mqtt_incoming_task(
|
|
||||||
receiver,
|
|
||||||
round_trip_topic.clone(),
|
|
||||||
stay_alive_topic.clone(),
|
|
||||||
)?);
|
|
||||||
spawner.spawn(mqtt_runner(task)?);
|
|
||||||
|
|
||||||
log(LogMessage::StayAlive, 0, 0, "", &stay_alive_topic);
|
|
||||||
|
|
||||||
log(LogMessage::MqttInfo, 0, 0, "", mqtt_url);
|
|
||||||
|
|
||||||
let mqtt_timeout = 15000;
|
|
||||||
let res = async {
|
|
||||||
while !MQTT_CONNECTED_EVENT_RECEIVED.load(Ordering::Relaxed) {
|
|
||||||
crate::hal::PlantHal::feed_watchdog();
|
|
||||||
Timer::after(Duration::from_millis(100)).await;
|
|
||||||
}
|
|
||||||
Ok::<(), FatError>(())
|
|
||||||
}
|
|
||||||
.with_timeout(Duration::from_millis(mqtt_timeout as u64))
|
|
||||||
.await;
|
|
||||||
|
|
||||||
if res.is_err() {
|
|
||||||
bail!("Timeout waiting MQTT connect event")
|
|
||||||
}
|
|
||||||
|
|
||||||
let _ = Topic::General(round_trip_topic.clone())
|
|
||||||
.with_display("online_text")
|
|
||||||
.publish()
|
|
||||||
.await;
|
|
||||||
|
|
||||||
let res = async {
|
|
||||||
while !MQTT_ROUND_TRIP_RECEIVED.load(Ordering::Relaxed) {
|
|
||||||
crate::hal::PlantHal::feed_watchdog();
|
|
||||||
Timer::after(Duration::from_millis(100)).await;
|
|
||||||
}
|
|
||||||
Ok::<(), FatError>(())
|
|
||||||
}
|
|
||||||
.with_timeout(Duration::from_millis(mqtt_timeout as u64))
|
|
||||||
.await;
|
|
||||||
|
|
||||||
if res.is_err() {
|
|
||||||
//ensure we do not further try to publish
|
|
||||||
MQTT_CONNECTED_EVENT_RECEIVED.store(false, Ordering::Relaxed);
|
|
||||||
bail!("Timeout waiting MQTT roundtrip")
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) async fn mqtt_inner(&mut self, subtopic: &str, message: &str) -> FatResult<()> {
|
|
||||||
if !subtopic.starts_with("/") {
|
|
||||||
bail!("Subtopic without / at start {}", subtopic);
|
|
||||||
}
|
|
||||||
if subtopic.len() > 192 {
|
|
||||||
bail!("Subtopic exceeds 192 chars {}", subtopic);
|
|
||||||
}
|
|
||||||
let base_topic = MQTT_BASE_TOPIC
|
|
||||||
.try_get()
|
|
||||||
.context("missing base topic in static!")?;
|
|
||||||
|
|
||||||
let full_topic = format!("{base_topic}{subtopic}");
|
|
||||||
|
|
||||||
loop {
|
|
||||||
let result = Topic::General(full_topic.as_str())
|
|
||||||
.with_display(message)
|
|
||||||
.retain(true)
|
|
||||||
.publish()
|
|
||||||
.await;
|
|
||||||
match result {
|
|
||||||
Ok(()) => return Ok(()),
|
|
||||||
Err(err) => {
|
|
||||||
let retry = match err {
|
|
||||||
Error::IOError => false,
|
|
||||||
Error::TimedOut => true,
|
|
||||||
Error::TooLarge => false,
|
|
||||||
Error::PacketError => false,
|
|
||||||
Error::Invalid => false,
|
|
||||||
Error::Rejected => false,
|
|
||||||
};
|
|
||||||
if !retry {
|
|
||||||
bail!(
|
|
||||||
"Error during mqtt send on topic {} with message {:#?} error is {:?}",
|
|
||||||
&full_topic,
|
|
||||||
message,
|
|
||||||
err
|
|
||||||
);
|
|
||||||
}
|
|
||||||
info!(
|
|
||||||
"Retransmit for {} with message {:#?} error is {:?} retrying {}",
|
|
||||||
&full_topic, message, err, retry
|
|
||||||
);
|
|
||||||
Timer::after(Duration::from_millis(100)).await;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
pub(crate) async fn mqtt_publish(&mut self, subtopic: &str, message: &str) {
|
|
||||||
let online = MQTT_CONNECTED_EVENT_RECEIVED.load(Ordering::Relaxed);
|
|
||||||
if !online {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
let roundtrip_ok = MQTT_ROUND_TRIP_RECEIVED.load(Ordering::Relaxed);
|
|
||||||
if !roundtrip_ok {
|
|
||||||
info!("MQTT roundtrip not received yet, dropping message");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
match self.mqtt_inner(subtopic, message).await {
|
|
||||||
Ok(()) => {}
|
|
||||||
Err(err) => {
|
|
||||||
info!(
|
|
||||||
"Error during mqtt send on topic {subtopic} with message {message:#?} error is {err:?}"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[embassy_executor::task]
|
|
||||||
async fn mqtt_runner(
|
|
||||||
task: McutieTask<'static, String, PublishDisplay<'static, String, &'static str>, 2>,
|
|
||||||
) {
|
|
||||||
task.run().await;
|
|
||||||
}
|
|
||||||
|
|
||||||
#[embassy_executor::task]
|
|
||||||
async fn mqtt_incoming_task(
|
|
||||||
receiver: McutieReceiver,
|
|
||||||
round_trip_topic: String,
|
|
||||||
stay_alive_topic: String,
|
|
||||||
) {
|
|
||||||
loop {
|
|
||||||
let message = receiver.receive().await;
|
|
||||||
match message {
|
|
||||||
MqttMessage::Connected => {
|
|
||||||
info!("Mqtt connected");
|
|
||||||
MQTT_CONNECTED_EVENT_RECEIVED.store(true, Ordering::Relaxed);
|
|
||||||
}
|
|
||||||
MqttMessage::Publish(topic, payload) => match topic {
|
|
||||||
Topic::DeviceType(_type_topic) => {}
|
|
||||||
Topic::Device(_device_topic) => {}
|
|
||||||
Topic::General(topic) => {
|
|
||||||
let subtopic = topic.as_str();
|
|
||||||
|
|
||||||
if subtopic.eq(round_trip_topic.as_str()) {
|
|
||||||
MQTT_ROUND_TRIP_RECEIVED.store(true, Ordering::Relaxed);
|
|
||||||
} else if subtopic.eq(stay_alive_topic.as_str()) {
|
|
||||||
let value = payload.eq_ignore_ascii_case("true".as_ref())
|
|
||||||
|| payload.eq_ignore_ascii_case("1".as_ref());
|
|
||||||
let a = match value {
|
|
||||||
true => 1,
|
|
||||||
false => 0,
|
|
||||||
};
|
|
||||||
log(LogMessage::MqttStayAliveRec, a, 0, "", "");
|
|
||||||
MQTT_STAY_ALIVE.store(value, Ordering::Relaxed);
|
|
||||||
} else {
|
|
||||||
log(LogMessage::UnknownTopic, 0, 0, "", &topic);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
MqttMessage::Disconnected => {
|
|
||||||
MQTT_CONNECTED_EVENT_RECEIVED.store(false, Ordering::Relaxed);
|
|
||||||
info!("Mqtt disconnected");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[embassy_executor::task(pool_size = 2)]
|
|
||||||
async fn net_task(mut runner: Runner<'static, Interface<'static>>) {
|
|
||||||
runner.run().await;
|
|
||||||
}
|
|
||||||
|
|
||||||
#[embassy_executor::task]
|
|
||||||
async fn run_dhcp(stack: Stack<'static>, ip: Ipv4Addr) {
|
|
||||||
use core::net::SocketAddrV4;
|
|
||||||
|
|
||||||
use edge_dhcp::{
|
|
||||||
io::{self, DEFAULT_SERVER_PORT},
|
|
||||||
server::{Server, ServerOptions},
|
|
||||||
};
|
|
||||||
use edge_nal::UdpBind;
|
|
||||||
use edge_nal_embassy::{Udp, UdpBuffers};
|
|
||||||
|
|
||||||
let mut buf = [0u8; 1500];
|
|
||||||
|
|
||||||
let mut gw_buf = [Ipv4Addr::UNSPECIFIED];
|
|
||||||
|
|
||||||
let buffers = UdpBuffers::<3, 1024, 1024, 10>::new();
|
|
||||||
let unbound_socket = Udp::new(stack, &buffers);
|
|
||||||
let mut bound_socket = match unbound_socket
|
|
||||||
.bind(SocketAddr::V4(SocketAddrV4::new(
|
|
||||||
Ipv4Addr::UNSPECIFIED,
|
|
||||||
DEFAULT_SERVER_PORT,
|
|
||||||
)))
|
|
||||||
.await
|
|
||||||
{
|
|
||||||
Ok(s) => s,
|
|
||||||
Err(e) => {
|
|
||||||
error!("dhcp task failed to bind socket: {:?}", e);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
loop {
|
|
||||||
_ = io::server::run(
|
|
||||||
&mut Server::<_, 64>::new_with_et(ip),
|
|
||||||
&ServerOptions::new(ip, Some(&mut gw_buf)),
|
|
||||||
&mut bound_socket,
|
|
||||||
&mut buf,
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
.inspect_err(|e| warn!("DHCP server error: {e:?}"));
|
|
||||||
Timer::after(Duration::from_millis(500)).await;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -282,14 +282,7 @@ pub struct FreePeripherals<'a> {
|
|||||||
pub adc1: ADC1<'a>,
|
pub adc1: ADC1<'a>,
|
||||||
}
|
}
|
||||||
|
|
||||||
macro_rules! mk_static {
|
use crate::util::mk_static;
|
||||||
($t:ty,$val:expr) => {{
|
|
||||||
static STATIC_CELL: static_cell::StaticCell<$t> = static_cell::StaticCell::new();
|
|
||||||
#[deny(unused_attributes)]
|
|
||||||
let x = STATIC_CELL.uninit().write(($val));
|
|
||||||
x
|
|
||||||
}};
|
|
||||||
}
|
|
||||||
|
|
||||||
impl PlantHal {
|
impl PlantHal {
|
||||||
pub async fn create() -> Result<Mutex<CriticalSectionRawMutex, HAL<'static>>, FatError> {
|
pub async fn create() -> Result<Mutex<CriticalSectionRawMutex, HAL<'static>>, FatError> {
|
||||||
|
|||||||
483
rust/src/main.rs
483
rust/src/main.rs
@@ -17,8 +17,8 @@ use esp_backtrace as _;
|
|||||||
use hal::PROGRESS_ACTIVE;
|
use hal::PROGRESS_ACTIVE;
|
||||||
|
|
||||||
use crate::config::{NetworkConfig, PlantConfig};
|
use crate::config::{NetworkConfig, PlantConfig};
|
||||||
use crate::fat_error::FatResult;
|
use crate::fat_error::{ContextExt, FatResult};
|
||||||
use crate::hal::esp::MQTT_STAY_ALIVE;
|
|
||||||
use crate::log::log;
|
use crate::log::log;
|
||||||
use crate::tank::{determine_tank_state, TankError, TankState, WATER_FROZEN_THRESH};
|
use crate::tank::{determine_tank_state, TankError, TankState, WATER_FROZEN_THRESH};
|
||||||
use crate::webserver::http_server;
|
use crate::webserver::http_server;
|
||||||
@@ -26,7 +26,7 @@ use crate::{
|
|||||||
config::BoardVersion::INITIAL,
|
config::BoardVersion::INITIAL,
|
||||||
hal::{PlantHal, HAL, PLANT_COUNT},
|
hal::{PlantHal, HAL, PLANT_COUNT},
|
||||||
};
|
};
|
||||||
use ::log::{info, warn, error};
|
use ::log::{error, info, warn};
|
||||||
use alloc::borrow::ToOwned;
|
use alloc::borrow::ToOwned;
|
||||||
use alloc::string::{String, ToString};
|
use alloc::string::{String, ToString};
|
||||||
use alloc::sync::Arc;
|
use alloc::sync::Arc;
|
||||||
@@ -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::BatteryState;
|
use hal::battery::{BatteryError, BatteryInfo, BatteryState};
|
||||||
use log::LogMessage;
|
use log::LogMessage;
|
||||||
use option_lock::OptionLock;
|
use option_lock::OptionLock;
|
||||||
use plant_state::PlantState;
|
use plant_state::PlantState;
|
||||||
@@ -67,8 +67,11 @@ mod config;
|
|||||||
mod fat_error;
|
mod fat_error;
|
||||||
mod hal;
|
mod hal;
|
||||||
mod log;
|
mod log;
|
||||||
|
mod mqtt;
|
||||||
|
mod network;
|
||||||
mod plant_state;
|
mod plant_state;
|
||||||
mod tank;
|
mod tank;
|
||||||
|
mod util;
|
||||||
mod webserver;
|
mod webserver;
|
||||||
|
|
||||||
extern crate alloc;
|
extern crate alloc;
|
||||||
@@ -83,12 +86,6 @@ enum WaitType {
|
|||||||
MqttConfig,
|
MqttConfig,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Debug, PartialEq)]
|
|
||||||
struct Solar {
|
|
||||||
current_ma: u32,
|
|
||||||
voltage_ma: u32,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl WaitType {
|
impl WaitType {
|
||||||
fn blink_pattern(&self) -> u64 {
|
fn blink_pattern(&self) -> u64 {
|
||||||
match self {
|
match self {
|
||||||
@@ -114,16 +111,6 @@ struct LightState {
|
|||||||
is_day: bool,
|
is_day: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Debug, PartialEq, Default)]
|
|
||||||
///mqtt struct to track pump activities
|
|
||||||
struct PumpInfo {
|
|
||||||
enabled: bool,
|
|
||||||
pump_ineffective: bool,
|
|
||||||
median_current_ma: u16,
|
|
||||||
max_current_ma: u16,
|
|
||||||
min_current_ma: u16,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Serialize)]
|
#[derive(Serialize)]
|
||||||
pub struct PumpResult {
|
pub struct PumpResult {
|
||||||
median_current_ma: u16,
|
median_current_ma: u16,
|
||||||
@@ -135,22 +122,6 @@ pub struct PumpResult {
|
|||||||
pump_time_s: u16,
|
pump_time_s: u16,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Serialize, Debug, PartialEq)]
|
|
||||||
enum SntpMode {
|
|
||||||
OFFLINE,
|
|
||||||
SYNC { current: DateTime<Utc> },
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Serialize, Debug, PartialEq)]
|
|
||||||
enum NetworkMode {
|
|
||||||
WIFI {
|
|
||||||
sntp: SntpMode,
|
|
||||||
mqtt: bool,
|
|
||||||
ip_address: String,
|
|
||||||
},
|
|
||||||
OFFLINE,
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn safe_main(spawner: Spawner) -> FatResult<()> {
|
async fn safe_main(spawner: Spawner) -> FatResult<()> {
|
||||||
info!("Startup Rust");
|
info!("Startup Rust");
|
||||||
|
|
||||||
@@ -223,7 +194,17 @@ async fn safe_main(spawner: Spawner) -> FatResult<()> {
|
|||||||
{
|
{
|
||||||
info!("No wifi configured, starting initial config mode");
|
info!("No wifi configured, starting initial config mode");
|
||||||
|
|
||||||
let stack = board.board_hal.get_esp().wifi_ap(spawner).await?;
|
let esp = board.board_hal.get_esp();
|
||||||
|
let ssid = esp
|
||||||
|
.load_config()
|
||||||
|
.await
|
||||||
|
.map(|config| config.network.ap_ssid.to_string())
|
||||||
|
.unwrap_or_else(|_| String::from("PlantCtrl Emergency Mode"));
|
||||||
|
let device = esp
|
||||||
|
.interface_ap
|
||||||
|
.take()
|
||||||
|
.context("AP interface already taken")?;
|
||||||
|
let stack = network::wifi_ap(ssid, device, &esp.controller, &mut esp.rng, spawner).await?;
|
||||||
|
|
||||||
let reboot_now = Arc::new(AtomicBool::new(false));
|
let reboot_now = Arc::new(AtomicBool::new(false));
|
||||||
println!("starting webserver");
|
println!("starting webserver");
|
||||||
@@ -234,20 +215,34 @@ async fn safe_main(spawner: Spawner) -> FatResult<()> {
|
|||||||
|
|
||||||
let mut stack: OptionLock<Stack> = OptionLock::empty();
|
let mut stack: OptionLock<Stack> = OptionLock::empty();
|
||||||
let network_mode = if board.board_hal.get_config().network.ssid.is_some() {
|
let network_mode = if board.board_hal.get_config().network.ssid.is_some() {
|
||||||
try_connect_wifi_sntp_mqtt(&mut board, &mut stack, spawner).await
|
network::try_connect_wifi_sntp_mqtt(&mut board, &mut stack, spawner).await
|
||||||
} else {
|
} else {
|
||||||
info!("No wifi configured");
|
info!("No wifi configured");
|
||||||
//the current sensors require this amount to stabilize, in the case of Wi-Fi this is already handled due to connect timings;
|
//the current sensors require this amount to stabilize, in the case of Wi-Fi this is already handled due to connect timings;
|
||||||
Timer::after_millis(100).await;
|
Timer::after_millis(100).await;
|
||||||
NetworkMode::OFFLINE
|
network::NetworkMode::OFFLINE
|
||||||
};
|
};
|
||||||
|
|
||||||
if matches!(network_mode, NetworkMode::OFFLINE) && to_config {
|
if matches!(network_mode, network::NetworkMode::OFFLINE) && to_config {
|
||||||
info!("Could not connect to station and config mode forced, switching to ap mode!");
|
info!("Could not connect to station and config mode forced, switching to ap mode!");
|
||||||
|
|
||||||
let res = {
|
let res = {
|
||||||
let esp = board.board_hal.get_esp();
|
let esp = board.board_hal.get_esp();
|
||||||
esp.wifi_ap(spawner).await
|
let ssid = esp
|
||||||
|
.load_config()
|
||||||
|
.await
|
||||||
|
.map(|config| config.network.ap_ssid.to_string())
|
||||||
|
.unwrap_or_else(|_| String::from("PlantCtrl Emergency Mode"));
|
||||||
|
let device = match esp.interface_ap.take() {
|
||||||
|
Some(d) => d,
|
||||||
|
None => {
|
||||||
|
use crate::fat_error::FatError;
|
||||||
|
return Err(FatError::String {
|
||||||
|
error: "AP interface already taken".to_string(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
network::wifi_ap(ssid, device, &esp.controller, &mut esp.rng, spawner).await
|
||||||
};
|
};
|
||||||
match res {
|
match res {
|
||||||
Ok(ap_stack) => {
|
Ok(ap_stack) => {
|
||||||
@@ -276,23 +271,23 @@ async fn safe_main(spawner: Spawner) -> FatResult<()> {
|
|||||||
timezone_time
|
timezone_time
|
||||||
);
|
);
|
||||||
|
|
||||||
if let NetworkMode::WIFI { ref ip_address, .. } = network_mode {
|
if let network::NetworkMode::WIFI { ref ip_address, .. } = network_mode {
|
||||||
publish_firmware_info(&mut board, version, ip_address, &timezone_time.to_rfc3339()).await;
|
mqtt::publish_firmware_info(&mut board, version, ip_address, &timezone_time.to_rfc3339()).await;
|
||||||
publish_battery_state(&mut board).await;
|
mqtt::publish_battery_state(&mut board).await;
|
||||||
let _ = publish_mppt_state(&mut board).await;
|
let _ = mqtt::publish_mppt_state(&mut board).await;
|
||||||
}
|
}
|
||||||
|
|
||||||
log(
|
log(
|
||||||
LogMessage::StartupInfo,
|
LogMessage::StartupInfo,
|
||||||
matches!(network_mode, NetworkMode::WIFI { .. }) as u32,
|
matches!(network_mode, network::NetworkMode::WIFI { .. }) as u32,
|
||||||
matches!(
|
matches!(
|
||||||
network_mode,
|
network_mode,
|
||||||
NetworkMode::WIFI {
|
network::NetworkMode::WIFI {
|
||||||
sntp: SntpMode::SYNC { .. },
|
sntp: network::SntpMode::SYNC { .. },
|
||||||
..
|
..
|
||||||
}
|
}
|
||||||
) as u32,
|
) as u32,
|
||||||
matches!(network_mode, NetworkMode::WIFI { mqtt: true, .. })
|
matches!(network_mode, network::NetworkMode::WIFI { mqtt: true, .. })
|
||||||
.to_string()
|
.to_string()
|
||||||
.as_str(),
|
.as_str(),
|
||||||
"",
|
"",
|
||||||
@@ -314,7 +309,7 @@ async fn safe_main(spawner: Spawner) -> FatResult<()> {
|
|||||||
log(LogMessage::NormalRun, 0, 0, "", "");
|
log(LogMessage::NormalRun, 0, 0, "", "");
|
||||||
}
|
}
|
||||||
|
|
||||||
let _dry_run = false;
|
let dry_run = false;
|
||||||
|
|
||||||
let tank_state = determine_tank_state(&mut board).await;
|
let tank_state = determine_tank_state(&mut board).await;
|
||||||
|
|
||||||
@@ -322,7 +317,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_value_mv) => log(
|
TankError::SensorMissing { raw_mv: raw_value_mv } => log(
|
||||||
LogMessage::TankSensorMissing,
|
LogMessage::TankSensorMissing,
|
||||||
raw_value_mv as u32,
|
raw_value_mv as u32,
|
||||||
0,
|
0,
|
||||||
@@ -336,8 +331,8 @@ async fn safe_main(spawner: Spawner) -> FatResult<()> {
|
|||||||
&format!("{value}"),
|
&format!("{value}"),
|
||||||
"",
|
"",
|
||||||
),
|
),
|
||||||
TankError::BoardError(err) => {
|
TankError::BoardError { message: err } => {
|
||||||
log(LogMessage::TankSensorBoardError, 0, 0, "", &err.to_string())
|
log(LogMessage::TankSensorBoardError, 0, 0, "", &err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// disabled cannot trigger this because of wrapping if is_enabled
|
// disabled cannot trigger this because of wrapping if is_enabled
|
||||||
@@ -351,7 +346,7 @@ async fn safe_main(spawner: Spawner) -> FatResult<()> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut _water_frozen = false;
|
let mut water_frozen = false;
|
||||||
let water_temp: FatResult<f32> = match board.board_hal.get_tank_sensor() {
|
let water_temp: FatResult<f32> = match board.board_hal.get_tank_sensor() {
|
||||||
Ok(sensor) => sensor.water_temperature_c().await,
|
Ok(sensor) => sensor.water_temperature_c().await,
|
||||||
Err(e) => Err(e),
|
Err(e) => Err(e),
|
||||||
@@ -359,12 +354,12 @@ async fn safe_main(spawner: Spawner) -> FatResult<()> {
|
|||||||
|
|
||||||
if let Ok(res) = water_temp {
|
if let Ok(res) = water_temp {
|
||||||
if res < WATER_FROZEN_THRESH {
|
if res < WATER_FROZEN_THRESH {
|
||||||
_water_frozen = true;
|
water_frozen = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
info!("Water temp is {}", water_temp.as_ref().unwrap_or(&0.));
|
info!("Water temp is {}", water_temp.as_ref().unwrap_or(&0.));
|
||||||
|
|
||||||
publish_tank_state(&mut board, &tank_state, water_temp).await;
|
mqtt::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,
|
||||||
@@ -377,76 +372,72 @@ async fn safe_main(spawner: Spawner) -> FatResult<()> {
|
|||||||
PlantState::read_hardware_state(7, &mut board).await,
|
PlantState::read_hardware_state(7, &mut board).await,
|
||||||
];
|
];
|
||||||
|
|
||||||
publish_plant_states(&mut board, &timezone_time.clone(), &plantstate).await;
|
mqtt::publish_plant_states(&mut board, &timezone_time.clone(), &plantstate).await;
|
||||||
|
|
||||||
// let pump_required = plantstate
|
let pump_required = plantstate
|
||||||
// .iter()
|
.iter()
|
||||||
// .zip(&board.board_hal.get_config().plants)
|
.zip(&board.board_hal.get_config().plants)
|
||||||
// .any(|(it, conf)| it.needs_to_be_watered(conf, &timezone_time))
|
.any(|(it, conf)| it.needs_to_be_watered(conf, &timezone_time))
|
||||||
// && !water_frozen;
|
&& !water_frozen;
|
||||||
// if pump_required {
|
if pump_required {
|
||||||
// log(LogMessage::EnableMain, dry_run as u32, 0, "", "");
|
log(LogMessage::EnableMain, dry_run as u32, 0, "", "");
|
||||||
// for (plant_id, (state, plant_config)) in plantstate
|
for (plant_id, (state, plant_config)) in plantstate
|
||||||
// .iter()
|
.iter()
|
||||||
// .zip(&board.board_hal.get_config().plants.clone())
|
.zip(&board.board_hal.get_config().plants.clone())
|
||||||
// .enumerate()
|
.enumerate()
|
||||||
// {
|
{
|
||||||
// if state.needs_to_be_watered(plant_config, &timezone_time) {
|
if state.needs_to_be_watered(plant_config, &timezone_time) {
|
||||||
// let pump_count = board.board_hal.get_esp().consecutive_pump_count(plant_id) + 1;
|
let pump_count = board.board_hal.get_esp().consecutive_pump_count(plant_id) + 1;
|
||||||
// board
|
board
|
||||||
// .board_hal
|
.board_hal
|
||||||
// .get_esp()
|
.get_esp()
|
||||||
// .store_consecutive_pump_count(plant_id, pump_count);
|
.store_consecutive_pump_count(plant_id, pump_count);
|
||||||
//
|
let pump_ineffective = pump_count > plant_config.max_consecutive_pump_count as u32;
|
||||||
// let pump_ineffective = pump_count > plant_config.max_consecutive_pump_count as u32;
|
if pump_ineffective {
|
||||||
// if pump_ineffective {
|
log(
|
||||||
// log(
|
LogMessage::ConsecutivePumpCountLimit,
|
||||||
// LogMessage::ConsecutivePumpCountLimit,
|
pump_count,
|
||||||
// pump_count,
|
plant_config.max_consecutive_pump_count as u32,
|
||||||
// plant_config.max_consecutive_pump_count as u32,
|
&(plant_id + 1).to_string(),
|
||||||
// &(plant_id + 1).to_string(),
|
"",
|
||||||
// "",
|
);
|
||||||
// );
|
board.board_hal.fault(plant_id, true).await?;
|
||||||
// board.board_hal.fault(plant_id, true).await?;
|
}
|
||||||
// }
|
log(
|
||||||
// log(
|
LogMessage::PumpPlant,
|
||||||
// LogMessage::PumpPlant,
|
(plant_id + 1) as u32,
|
||||||
// (plant_id + 1) as u32,
|
plant_config.pump_time_s as u32,
|
||||||
// plant_config.pump_time_s as u32,
|
&dry_run.to_string(),
|
||||||
// &dry_run.to_string(),
|
"",
|
||||||
// "",
|
);
|
||||||
// );
|
board
|
||||||
// board
|
.board_hal
|
||||||
// .board_hal
|
.get_esp()
|
||||||
// .get_esp()
|
.store_last_pump_time(plant_id, cur);
|
||||||
// .store_last_pump_time(plant_id, cur);
|
board.board_hal.get_esp().last_pump_time(plant_id);
|
||||||
// board.board_hal.get_esp().last_pump_time(plant_id);
|
mqtt::pump_info(plant_id, true, pump_ineffective, 0, 0, 0, false).await;
|
||||||
// //state.active = true;
|
let result = do_secure_pump(&mut board, plant_id, plant_config, dry_run).await?;
|
||||||
//
|
board.board_hal.pump(plant_id, false).await?;
|
||||||
// pump_info(plant_id, true, pump_ineffective, 0, 0, 0, false).await;
|
mqtt::pump_info(
|
||||||
//
|
plant_id,
|
||||||
// let result = do_secure_pump(plant_id, plant_config, dry_run).await?;
|
false,
|
||||||
// board.board_hal.pump(plant_id, false).await?;
|
pump_ineffective,
|
||||||
// pump_info(
|
result.median_current_ma,
|
||||||
// plant_id,
|
result.max_current_ma,
|
||||||
// false,
|
result.min_current_ma,
|
||||||
// pump_ineffective,
|
result.error,
|
||||||
// result.median_current_ma,
|
)
|
||||||
// result.max_current_ma,
|
.await;
|
||||||
// result.min_current_ma,
|
} else if !state.pump_in_timeout(plant_config, &timezone_time) {
|
||||||
// result.error,
|
// plant does not need to be watered and is not in timeout
|
||||||
// )
|
// -> reset consecutive pump count
|
||||||
// .await;
|
board
|
||||||
// } else if !state.pump_in_timeout(plant_config, &timezone_time) {
|
.board_hal
|
||||||
// // plant does not need to be watered and is not in timeout
|
.get_esp()
|
||||||
// // -> reset consecutive pump count
|
.store_consecutive_pump_count(plant_id, 0);
|
||||||
// board
|
}
|
||||||
// .board_hal
|
}
|
||||||
// .get_esp()
|
}
|
||||||
// .store_consecutive_pump_count(plant_id, 0);
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
|
|
||||||
info!("state of charg");
|
info!("state of charg");
|
||||||
let is_day = board.board_hal.is_day();
|
let is_day = board.board_hal.is_day();
|
||||||
@@ -536,11 +527,7 @@ async fn safe_main(spawner: Spawner) -> FatResult<()> {
|
|||||||
|
|
||||||
match &serde_json::to_string(&light_state) {
|
match &serde_json::to_string(&light_state) {
|
||||||
Ok(state) => {
|
Ok(state) => {
|
||||||
let _ = board
|
let _ = mqtt::publish("/light", state).await;
|
||||||
.board_hal
|
|
||||||
.get_esp()
|
|
||||||
.mqtt_publish("/light", state)
|
|
||||||
.await;
|
|
||||||
}
|
}
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
info!("Error publishing lightstate {}", err);
|
info!("Error publishing lightstate {}", err);
|
||||||
@@ -550,29 +537,16 @@ async fn safe_main(spawner: Spawner) -> FatResult<()> {
|
|||||||
let deep_sleep_duration_minutes: u32 =
|
let deep_sleep_duration_minutes: u32 =
|
||||||
// if battery soc is unknown assume battery has enough change
|
// if battery soc is unknown assume battery has enough change
|
||||||
if state_of_charge < 10.0 && !matches!(battery_state, BatteryState::Unknown) {
|
if state_of_charge < 10.0 && !matches!(battery_state, BatteryState::Unknown) {
|
||||||
let _ = board
|
let _ = mqtt::publish("/deepsleep", "low Volt 12h").await;
|
||||||
.board_hal
|
|
||||||
.get_esp()
|
|
||||||
.mqtt_publish("/deepsleep", "low Volt 12h").await;
|
|
||||||
12 * 60
|
12 * 60
|
||||||
} else if is_day {
|
} else if is_day {
|
||||||
let _ = board
|
let _ = mqtt::publish("/deepsleep", "normal 20m").await;
|
||||||
.board_hal
|
|
||||||
.get_esp()
|
|
||||||
.mqtt_publish("/deepsleep", "normal 20m").await;
|
|
||||||
20
|
20
|
||||||
} else {
|
} else {
|
||||||
let _ = board
|
let _ = mqtt::publish("/deepsleep", "night 1h").await;
|
||||||
.board_hal
|
|
||||||
.get_esp()
|
|
||||||
.mqtt_publish("/deepsleep", "night 1h").await;
|
|
||||||
60
|
60
|
||||||
};
|
};
|
||||||
let _ = board
|
let _ = mqtt::publish("/state", "sleep").await;
|
||||||
.board_hal
|
|
||||||
.get_esp()
|
|
||||||
.mqtt_publish("/state", "sleep")
|
|
||||||
.await;
|
|
||||||
|
|
||||||
info!("Go to sleep for {} minutes", deep_sleep_duration_minutes);
|
info!("Go to sleep for {} minutes", deep_sleep_duration_minutes);
|
||||||
//determine next event
|
//determine next event
|
||||||
@@ -582,12 +556,13 @@ async fn safe_main(spawner: Spawner) -> FatResult<()> {
|
|||||||
//TODO
|
//TODO
|
||||||
//mark_app_valid();
|
//mark_app_valid();
|
||||||
|
|
||||||
let stay_alive = MQTT_STAY_ALIVE.load(Ordering::Relaxed);
|
let stay_alive = mqtt::is_stay_alive();
|
||||||
info!("Check stay alive, current state is {}", stay_alive);
|
info!("Check stay alive, current state is {}", stay_alive);
|
||||||
|
|
||||||
if stay_alive {
|
if stay_alive {
|
||||||
let reboot_now = Arc::new(AtomicBool::new(false));
|
let reboot_now = Arc::new(AtomicBool::new(false));
|
||||||
let _webserver = http_server(reboot_now.clone(), stack.take().unwrap());
|
|
||||||
|
spawner.spawn(http_server(reboot_now.clone(), stack.take().unwrap())?);
|
||||||
wait_infinity(board, WaitType::MqttConfig, reboot_now.clone(), UTC).await;
|
wait_infinity(board, WaitType::MqttConfig, reboot_now.clone(), UTC).await;
|
||||||
} else {
|
} else {
|
||||||
//TODO wait for all mqtt publishes?
|
//TODO wait for all mqtt publishes?
|
||||||
@@ -728,209 +703,6 @@ 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 _ = board.board_hal.get_esp().mqtt_publish("/water", &*state);
|
|
||||||
}
|
|
||||||
|
|
||||||
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 _ = board
|
|
||||||
.board_hal
|
|
||||||
.get_esp()
|
|
||||||
.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,
|
|
||||||
) {
|
|
||||||
let esp = board.board_hal.get_esp();
|
|
||||||
esp.mqtt_publish("/firmware/address", ip_address).await;
|
|
||||||
esp.mqtt_publish("/firmware/state", format!("{:?}", &version).as_str())
|
|
||||||
.await;
|
|
||||||
esp.mqtt_publish("/firmware/last_online", timezone_time)
|
|
||||||
.await;
|
|
||||||
esp.mqtt_publish("/state", "online").await;
|
|
||||||
}
|
|
||||||
macro_rules! mk_static {
|
|
||||||
($t:ty,$val:expr) => {{
|
|
||||||
static STATIC_CELL: static_cell::StaticCell<$t> = static_cell::StaticCell::new();
|
|
||||||
#[deny(unused_attributes)]
|
|
||||||
let x = STATIC_CELL.uninit().write(($val));
|
|
||||||
x
|
|
||||||
}};
|
|
||||||
}
|
|
||||||
async fn try_connect_wifi_sntp_mqtt(
|
|
||||||
board: &mut MutexGuard<'static, CriticalSectionRawMutex, HAL<'static>>,
|
|
||||||
stack_store: &mut OptionLock<Stack<'static>>,
|
|
||||||
spawner: Spawner,
|
|
||||||
) -> NetworkMode {
|
|
||||||
let nw_conf = &board.board_hal.get_config().network.clone();
|
|
||||||
match board.board_hal.get_esp().wifi(nw_conf, spawner).await {
|
|
||||||
Ok(stack) => {
|
|
||||||
stack_store.replace(stack);
|
|
||||||
|
|
||||||
let sntp_mode: SntpMode = match board.board_hal.get_esp().sntp(1000 * 10, stack).await {
|
|
||||||
Ok(new_time) => {
|
|
||||||
info!("Using time from sntp {}", new_time.to_rfc3339());
|
|
||||||
let _ = board
|
|
||||||
.board_hal
|
|
||||||
.get_rtc_module()
|
|
||||||
.set_rtc_time(&new_time)
|
|
||||||
.await;
|
|
||||||
SntpMode::SYNC { current: new_time }
|
|
||||||
}
|
|
||||||
Err(err) => {
|
|
||||||
warn!("sntp error: {err}");
|
|
||||||
board.board_hal.general_fault(true).await;
|
|
||||||
SntpMode::OFFLINE
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
let mqtt_connected = if board.board_hal.get_config().network.mqtt_url.is_some() {
|
|
||||||
let nw_config = board.board_hal.get_config().network.clone();
|
|
||||||
let nw_config = mk_static!(NetworkConfig, nw_config);
|
|
||||||
match board
|
|
||||||
.board_hal
|
|
||||||
.get_esp()
|
|
||||||
.mqtt(nw_config, stack, spawner)
|
|
||||||
.await
|
|
||||||
{
|
|
||||||
Ok(_) => {
|
|
||||||
info!("Mqtt connection ready");
|
|
||||||
true
|
|
||||||
}
|
|
||||||
Err(err) => {
|
|
||||||
warn!("Could not connect mqtt due to {err}");
|
|
||||||
false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
false
|
|
||||||
};
|
|
||||||
|
|
||||||
let ip = match stack.config_v4() {
|
|
||||||
Some(config) => config.address.address().to_string(),
|
|
||||||
None => match stack.config_v6() {
|
|
||||||
Some(config) => config.address.address().to_string(),
|
|
||||||
None => String::from("No IP"),
|
|
||||||
},
|
|
||||||
};
|
|
||||||
NetworkMode::WIFI {
|
|
||||||
sntp: sntp_mode,
|
|
||||||
mqtt: mqtt_connected,
|
|
||||||
ip_address: ip,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Err(err) => {
|
|
||||||
info!("Offline mode due to {err}");
|
|
||||||
board.board_hal.general_fault(true).await;
|
|
||||||
NetworkMode::OFFLINE
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
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) => {
|
|
||||||
BOARD_ACCESS
|
|
||||||
.get()
|
|
||||||
.await
|
|
||||||
.lock()
|
|
||||||
.await
|
|
||||||
.board_hal
|
|
||||||
.get_esp()
|
|
||||||
.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 = 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 _ = board
|
|
||||||
.board_hal
|
|
||||||
.get_esp()
|
|
||||||
.mqtt_publish("/mppt", &serialized_solar_state_bytes);
|
|
||||||
}
|
|
||||||
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 _ = board
|
|
||||||
.board_hal
|
|
||||||
.get_esp()
|
|
||||||
.mqtt_publish("/battery", &*value)
|
|
||||||
.await;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn wait_infinity(
|
async fn wait_infinity(
|
||||||
board: MutexGuard<'_, CriticalSectionRawMutex, HAL<'static>>,
|
board: MutexGuard<'_, CriticalSectionRawMutex, HAL<'static>>,
|
||||||
wait_type: WaitType,
|
wait_type: WaitType,
|
||||||
@@ -1031,9 +803,8 @@ async fn wait_infinity(
|
|||||||
let cur = board.board_hal.get_time().await;
|
let cur = board.board_hal.get_time().await;
|
||||||
let timezone_time = cur.with_timezone(&timezone);
|
let timezone_time = cur.with_timezone(&timezone);
|
||||||
|
|
||||||
let esp = board.board_hal.get_esp();
|
mqtt::publish("/state", "config").await;
|
||||||
esp.mqtt_publish("/state", "config").await;
|
mqtt::publish("/firmware/last_online", &timezone_time.to_rfc3339())
|
||||||
esp.mqtt_publish("/firmware/last_online", &timezone_time.to_rfc3339())
|
|
||||||
.await;
|
.await;
|
||||||
last_mqtt_update = Some(now);
|
last_mqtt_update = Some(now);
|
||||||
}
|
}
|
||||||
@@ -1087,7 +858,7 @@ async fn wait_infinity(
|
|||||||
|
|
||||||
hal::PlantHal::feed_watchdog();
|
hal::PlantHal::feed_watchdog();
|
||||||
|
|
||||||
if wait_type == WaitType::MqttConfig && !MQTT_STAY_ALIVE.load(Ordering::Relaxed) {
|
if wait_type == WaitType::MqttConfig && !mqtt::is_stay_alive() {
|
||||||
reboot_now.store(true, Ordering::Relaxed);
|
reboot_now.store(true, Ordering::Relaxed);
|
||||||
}
|
}
|
||||||
if reboot_now.load(Ordering::Relaxed) {
|
if reboot_now.load(Ordering::Relaxed) {
|
||||||
|
|||||||
398
rust/src/mqtt.rs
Normal file
398
rust/src/mqtt.rs
Normal file
@@ -0,0 +1,398 @@
|
|||||||
|
use crate::config::NetworkConfig;
|
||||||
|
use crate::fat_error::{ContextExt, FatError, FatResult};
|
||||||
|
use crate::hal::battery::{BatteryError, BatteryInfo, BatteryState};
|
||||||
|
use crate::hal::{PlantHal, HAL};
|
||||||
|
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 chrono::DateTime;
|
||||||
|
use chrono_tz::Tz;
|
||||||
|
use core::sync::atomic::Ordering;
|
||||||
|
use embassy_executor::Spawner;
|
||||||
|
use embassy_net::Stack;
|
||||||
|
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
|
||||||
|
use embassy_sync::mutex::MutexGuard;
|
||||||
|
use embassy_sync::once_lock::OnceLock;
|
||||||
|
use embassy_time::{Duration, Timer, WithTimeout};
|
||||||
|
use log::{info, warn};
|
||||||
|
use mcutie::{
|
||||||
|
Error, McutieBuilder, McutieReceiver, McutieTask, MqttMessage, PublishDisplay, Publishable,
|
||||||
|
QoS, Topic,
|
||||||
|
};
|
||||||
|
use portable_atomic::AtomicBool;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
static MQTT_CONNECTED_EVENT_RECEIVED: AtomicBool = AtomicBool::new(false);
|
||||||
|
static MQTT_ROUND_TRIP_RECEIVED: AtomicBool = AtomicBool::new(false);
|
||||||
|
pub static MQTT_STAY_ALIVE: AtomicBool = AtomicBool::new(false);
|
||||||
|
static MQTT_BASE_TOPIC: OnceLock<String> = OnceLock::new();
|
||||||
|
|
||||||
|
pub fn is_stay_alive() -> bool {
|
||||||
|
MQTT_STAY_ALIVE.load(Ordering::Relaxed)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn publish(subtopic: &str, message: &str) {
|
||||||
|
let online = MQTT_CONNECTED_EVENT_RECEIVED.load(Ordering::Relaxed);
|
||||||
|
if !online {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let roundtrip_ok = MQTT_ROUND_TRIP_RECEIVED.load(Ordering::Relaxed);
|
||||||
|
if !roundtrip_ok {
|
||||||
|
info!("MQTT roundtrip not received yet, dropping message");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
match publish_inner(subtopic, message).await {
|
||||||
|
Ok(()) => {}
|
||||||
|
Err(err) => {
|
||||||
|
info!(
|
||||||
|
"Error during mqtt send on topic {subtopic} with message {message:#?} error is {err:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn publish_inner(subtopic: &str, message: &str) -> FatResult<()> {
|
||||||
|
if !subtopic.starts_with("/") {
|
||||||
|
bail!("Subtopic without / at start {}", subtopic);
|
||||||
|
}
|
||||||
|
if subtopic.len() > 192 {
|
||||||
|
bail!("Subtopic exceeds 192 chars {}", subtopic);
|
||||||
|
}
|
||||||
|
let base_topic = MQTT_BASE_TOPIC
|
||||||
|
.try_get()
|
||||||
|
.context("missing base topic in static!")?;
|
||||||
|
|
||||||
|
let full_topic = format!("{base_topic}{subtopic}");
|
||||||
|
|
||||||
|
loop {
|
||||||
|
let result = Topic::General(full_topic.as_str())
|
||||||
|
.with_display(message)
|
||||||
|
.retain(true)
|
||||||
|
.publish()
|
||||||
|
.await;
|
||||||
|
match result {
|
||||||
|
Ok(()) => return Ok(()),
|
||||||
|
Err(err) => {
|
||||||
|
let retry = match err {
|
||||||
|
Error::IOError => false,
|
||||||
|
Error::TimedOut => true,
|
||||||
|
Error::TooLarge => false,
|
||||||
|
Error::PacketError => false,
|
||||||
|
Error::Invalid => false,
|
||||||
|
Error::Rejected => false,
|
||||||
|
};
|
||||||
|
if !retry {
|
||||||
|
bail!(
|
||||||
|
"Error during mqtt send on topic {} with message {:#?} error is {:?}",
|
||||||
|
&full_topic,
|
||||||
|
message,
|
||||||
|
err
|
||||||
|
);
|
||||||
|
}
|
||||||
|
info!(
|
||||||
|
"Retransmit for {} with message {:#?} error is {:?} retrying {}",
|
||||||
|
&full_topic, message, err, retry
|
||||||
|
);
|
||||||
|
Timer::after(Duration::from_millis(100)).await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
use crate::util::mk_static;
|
||||||
|
|
||||||
|
pub async fn mqtt_init(
|
||||||
|
network_config: &'static NetworkConfig,
|
||||||
|
stack: Stack<'static>,
|
||||||
|
spawner: Spawner,
|
||||||
|
) -> FatResult<()> {
|
||||||
|
let base_topic = network_config
|
||||||
|
.base_topic
|
||||||
|
.as_ref()
|
||||||
|
.context("missing base topic")?;
|
||||||
|
if base_topic.is_empty() {
|
||||||
|
bail!("Mqtt base_topic was empty")
|
||||||
|
}
|
||||||
|
MQTT_BASE_TOPIC
|
||||||
|
.init(base_topic.to_string())
|
||||||
|
.map_err(|_| FatError::String {
|
||||||
|
error: "Error setting basetopic".to_string(),
|
||||||
|
})?;
|
||||||
|
|
||||||
|
let mqtt_url = network_config
|
||||||
|
.mqtt_url
|
||||||
|
.as_ref()
|
||||||
|
.context("missing mqtt url")?;
|
||||||
|
if mqtt_url.is_empty() {
|
||||||
|
bail!("Mqtt url was empty")
|
||||||
|
}
|
||||||
|
|
||||||
|
let last_will_topic = format!("{base_topic}/state");
|
||||||
|
let round_trip_topic = format!("{base_topic}/internal/roundtrip");
|
||||||
|
let stay_alive_topic = format!("{base_topic}/stay_alive");
|
||||||
|
|
||||||
|
let mut builder: McutieBuilder<'_, String, PublishDisplay<String, &str>, 0> =
|
||||||
|
McutieBuilder::new(stack, "plant ctrl", mqtt_url);
|
||||||
|
if let (Some(mqtt_user), Some(mqtt_password)) = (
|
||||||
|
network_config.mqtt_user.as_ref(),
|
||||||
|
network_config.mqtt_password.as_ref(),
|
||||||
|
) {
|
||||||
|
builder = builder.with_authentication(mqtt_user, mqtt_password);
|
||||||
|
info!("With authentification");
|
||||||
|
}
|
||||||
|
|
||||||
|
let lwt = Topic::General(last_will_topic);
|
||||||
|
let lwt = mk_static!(Topic<String>, lwt);
|
||||||
|
let lwt = lwt.with_display("lost").retain(true).qos(QoS::AtLeastOnce);
|
||||||
|
builder = builder.with_last_will(lwt);
|
||||||
|
//TODO make configurable
|
||||||
|
builder = builder.with_device_id("plantctrl");
|
||||||
|
|
||||||
|
let builder: McutieBuilder<'_, String, PublishDisplay<String, &str>, 2> = builder
|
||||||
|
.with_subscriptions([
|
||||||
|
Topic::General(round_trip_topic.clone()),
|
||||||
|
Topic::General(stay_alive_topic.clone()),
|
||||||
|
]);
|
||||||
|
|
||||||
|
let keep_alive = Duration::from_secs(60 * 60 * 2).as_secs() as u16;
|
||||||
|
let (receiver, task) = builder.build(keep_alive);
|
||||||
|
|
||||||
|
spawner.spawn(mqtt_incoming_task(
|
||||||
|
receiver,
|
||||||
|
round_trip_topic.clone(),
|
||||||
|
stay_alive_topic.clone(),
|
||||||
|
)?);
|
||||||
|
spawner.spawn(mqtt_runner(task)?);
|
||||||
|
|
||||||
|
log(LogMessage::StayAlive, 0, 0, "", &stay_alive_topic);
|
||||||
|
|
||||||
|
log(LogMessage::MqttInfo, 0, 0, "", mqtt_url);
|
||||||
|
|
||||||
|
let mqtt_timeout = 15000;
|
||||||
|
let res = async {
|
||||||
|
while !MQTT_CONNECTED_EVENT_RECEIVED.load(Ordering::Relaxed) {
|
||||||
|
PlantHal::feed_watchdog();
|
||||||
|
Timer::after(Duration::from_millis(100)).await;
|
||||||
|
}
|
||||||
|
Ok::<(), FatError>(())
|
||||||
|
}
|
||||||
|
.with_timeout(Duration::from_millis(mqtt_timeout as u64))
|
||||||
|
.await;
|
||||||
|
|
||||||
|
if res.is_err() {
|
||||||
|
bail!("Timeout waiting MQTT connect event")
|
||||||
|
}
|
||||||
|
|
||||||
|
let _ = Topic::General(round_trip_topic.clone())
|
||||||
|
.with_display("online_text")
|
||||||
|
.publish()
|
||||||
|
.await;
|
||||||
|
|
||||||
|
let res = async {
|
||||||
|
while !MQTT_ROUND_TRIP_RECEIVED.load(Ordering::Relaxed) {
|
||||||
|
PlantHal::feed_watchdog();
|
||||||
|
Timer::after(Duration::from_millis(100)).await;
|
||||||
|
}
|
||||||
|
Ok::<(), FatError>(())
|
||||||
|
}
|
||||||
|
.with_timeout(Duration::from_millis(mqtt_timeout as u64))
|
||||||
|
.await;
|
||||||
|
|
||||||
|
if res.is_err() {
|
||||||
|
MQTT_CONNECTED_EVENT_RECEIVED.store(false, Ordering::Relaxed);
|
||||||
|
bail!("Timeout waiting MQTT roundtrip")
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[embassy_executor::task]
|
||||||
|
async fn mqtt_runner(
|
||||||
|
task: McutieTask<'static, String, PublishDisplay<'static, String, &'static str>, 2>,
|
||||||
|
) {
|
||||||
|
task.run().await;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[embassy_executor::task]
|
||||||
|
async fn mqtt_incoming_task(
|
||||||
|
receiver: McutieReceiver,
|
||||||
|
round_trip_topic: String,
|
||||||
|
stay_alive_topic: String,
|
||||||
|
) {
|
||||||
|
loop {
|
||||||
|
let message = receiver.receive().await;
|
||||||
|
match message {
|
||||||
|
MqttMessage::Connected => {
|
||||||
|
info!("Mqtt connected");
|
||||||
|
MQTT_CONNECTED_EVENT_RECEIVED.store(true, Ordering::Relaxed);
|
||||||
|
}
|
||||||
|
MqttMessage::Publish(topic, payload) => match topic {
|
||||||
|
Topic::DeviceType(_type_topic) => {}
|
||||||
|
Topic::Device(_device_topic) => {}
|
||||||
|
Topic::General(topic) => {
|
||||||
|
let subtopic = topic.as_str();
|
||||||
|
|
||||||
|
if subtopic.eq(round_trip_topic.as_str()) {
|
||||||
|
MQTT_ROUND_TRIP_RECEIVED.store(true, Ordering::Relaxed);
|
||||||
|
} else if subtopic.eq(stay_alive_topic.as_str()) {
|
||||||
|
let value = payload.eq_ignore_ascii_case("true".as_ref())
|
||||||
|
|| payload.eq_ignore_ascii_case("1".as_ref());
|
||||||
|
let a = match value {
|
||||||
|
true => 1,
|
||||||
|
false => 0,
|
||||||
|
};
|
||||||
|
log(LogMessage::MqttStayAliveRec, a, 0, "", "");
|
||||||
|
MQTT_STAY_ALIVE.store(value, Ordering::Relaxed);
|
||||||
|
} else {
|
||||||
|
log(LogMessage::UnknownTopic, 0, 0, "", &topic);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
MqttMessage::Disconnected => {
|
||||||
|
MQTT_CONNECTED_EVENT_RECEIVED.store(false, Ordering::Relaxed);
|
||||||
|
info!("Mqtt disconnected");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
419
rust/src/network.rs
Normal file
419
rust/src/network.rs
Normal file
@@ -0,0 +1,419 @@
|
|||||||
|
use crate::bail;
|
||||||
|
use crate::config::NetworkConfig;
|
||||||
|
use crate::fat_error::{ContextExt, FatError, FatResult};
|
||||||
|
use crate::hal::{PlantHal, HAL};
|
||||||
|
use crate::mqtt;
|
||||||
|
use crate::util::mk_static;
|
||||||
|
use alloc::string::{String, ToString};
|
||||||
|
use alloc::sync::Arc;
|
||||||
|
use chrono::{DateTime, Utc};
|
||||||
|
use core::net::{IpAddr, Ipv4Addr, SocketAddr, SocketAddrV4};
|
||||||
|
use embassy_executor::Spawner;
|
||||||
|
use embassy_net::dns::DnsQueryType;
|
||||||
|
use embassy_net::udp::{PacketMetadata, UdpSocket};
|
||||||
|
use embassy_net::{DhcpConfig, Runner, Stack, StackResources, StaticConfigV4};
|
||||||
|
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
|
||||||
|
use embassy_sync::mutex::{Mutex, MutexGuard};
|
||||||
|
use embassy_time::{Duration, Timer, WithTimeout};
|
||||||
|
use option_lock::OptionLock;
|
||||||
|
use edge_dhcp::{
|
||||||
|
io::{self, DEFAULT_SERVER_PORT},
|
||||||
|
server::{Server, ServerOptions},
|
||||||
|
};
|
||||||
|
use edge_nal::UdpBind;
|
||||||
|
use edge_nal_embassy::{Udp, UdpBuffers};
|
||||||
|
use esp_hal::rng::Rng;
|
||||||
|
use esp_println::println;
|
||||||
|
use esp_radio::wifi::ap::AccessPointConfig;
|
||||||
|
use esp_radio::wifi::sta::StationConfig;
|
||||||
|
use esp_radio::wifi::{AuthenticationMethod, Config, Interface};
|
||||||
|
use log::{info, warn, error};
|
||||||
|
use serde::Serialize;
|
||||||
|
use sntpc::{NtpContext, NtpTimestampGenerator, NtpUdpSocket, get_time};
|
||||||
|
|
||||||
|
const NTP_SERVER: &str = "pool.ntp.org";
|
||||||
|
|
||||||
|
#[derive(Copy, Clone, Default)]
|
||||||
|
struct Timestamp {
|
||||||
|
stamp: DateTime<Utc>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl NtpTimestampGenerator for Timestamp {
|
||||||
|
fn init(&mut self) {
|
||||||
|
self.stamp = DateTime::default();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn timestamp_sec(&self) -> u64 {
|
||||||
|
self.stamp.timestamp() as u64
|
||||||
|
}
|
||||||
|
|
||||||
|
fn timestamp_subsec_micros(&self) -> u32 {
|
||||||
|
self.stamp.timestamp_subsec_micros()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct EmbassyNtpSocket<'a, 'b> {
|
||||||
|
socket: &'a UdpSocket<'b>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a, 'b> EmbassyNtpSocket<'a, 'b> {
|
||||||
|
fn new(socket: &'a UdpSocket<'b>) -> Self {
|
||||||
|
Self { socket }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl NtpUdpSocket for EmbassyNtpSocket<'_, '_> {
|
||||||
|
async fn send_to(&self, buf: &[u8], addr: SocketAddr) -> sntpc::Result<usize> {
|
||||||
|
self.socket
|
||||||
|
.send_to(buf, addr)
|
||||||
|
.await
|
||||||
|
.map_err(|_| sntpc::Error::Network)?;
|
||||||
|
Ok(buf.len())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn recv_from(&self, buf: &mut [u8]) -> sntpc::Result<(usize, SocketAddr)> {
|
||||||
|
let (len, metadata) = self
|
||||||
|
.socket
|
||||||
|
.recv_from(buf)
|
||||||
|
.await
|
||||||
|
.map_err(|_| sntpc::Error::Network)?;
|
||||||
|
let addr = match metadata.endpoint.addr {
|
||||||
|
embassy_net::IpAddress::Ipv4(ip) => IpAddr::V4(ip),
|
||||||
|
embassy_net::IpAddress::Ipv6(ip) => IpAddr::V6(ip),
|
||||||
|
};
|
||||||
|
Ok((len, SocketAddr::new(addr, metadata.endpoint.port)))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn sntp(max_wait_ms: u32, stack: Stack<'_>) -> FatResult<DateTime<Utc>> {
|
||||||
|
println!("start sntp");
|
||||||
|
let mut rx_meta = [PacketMetadata::EMPTY; 16];
|
||||||
|
let mut rx_buffer = [0; 4096];
|
||||||
|
let mut tx_meta = [PacketMetadata::EMPTY; 16];
|
||||||
|
let mut tx_buffer = [0; 4096];
|
||||||
|
|
||||||
|
let mut socket = UdpSocket::new(
|
||||||
|
stack,
|
||||||
|
&mut rx_meta,
|
||||||
|
&mut rx_buffer,
|
||||||
|
&mut tx_meta,
|
||||||
|
&mut tx_buffer,
|
||||||
|
);
|
||||||
|
socket.bind(123).context("Could not bind UDP socket")?;
|
||||||
|
|
||||||
|
let context = NtpContext::new(Timestamp::default());
|
||||||
|
let ntp_socket = EmbassyNtpSocket::new(&socket);
|
||||||
|
|
||||||
|
let ntp_addrs = stack
|
||||||
|
.dns_query(NTP_SERVER, DnsQueryType::A)
|
||||||
|
.await
|
||||||
|
.context("Failed to resolve DNS")?;
|
||||||
|
|
||||||
|
if ntp_addrs.is_empty() {
|
||||||
|
bail!("No IP addresses found for NTP server");
|
||||||
|
}
|
||||||
|
let ntp = ntp_addrs[0];
|
||||||
|
info!("NTP server: {ntp:?}");
|
||||||
|
|
||||||
|
let mut counter = 0;
|
||||||
|
loop {
|
||||||
|
let addr: IpAddr = ntp.into();
|
||||||
|
let timeout = get_time(SocketAddr::from((addr, 123)), &ntp_socket, context)
|
||||||
|
.with_timeout(Duration::from_millis((max_wait_ms / 10) as u64))
|
||||||
|
.await;
|
||||||
|
|
||||||
|
match timeout {
|
||||||
|
Ok(result) => {
|
||||||
|
let time = result?;
|
||||||
|
info!("Time: {time:?}");
|
||||||
|
return DateTime::from_timestamp(time.seconds as i64, 0)
|
||||||
|
.context("Could not convert Sntp result");
|
||||||
|
}
|
||||||
|
Err(err) => {
|
||||||
|
warn!("sntp timeout, retry: {err:?}");
|
||||||
|
counter += 1;
|
||||||
|
if counter > 10 {
|
||||||
|
bail!("Failed to get time from NTP server");
|
||||||
|
}
|
||||||
|
Timer::after(Duration::from_millis(100)).await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Debug, PartialEq)]
|
||||||
|
pub enum SntpMode {
|
||||||
|
OFFLINE,
|
||||||
|
SYNC { current: DateTime<Utc> },
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Debug, PartialEq)]
|
||||||
|
pub enum NetworkMode {
|
||||||
|
WIFI {
|
||||||
|
sntp: SntpMode,
|
||||||
|
mqtt: bool,
|
||||||
|
ip_address: String,
|
||||||
|
},
|
||||||
|
OFFLINE,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[embassy_executor::task(pool_size = 2)]
|
||||||
|
pub(crate) async fn net_task(mut runner: Runner<'static, Interface<'static>>) {
|
||||||
|
runner.run().await;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[embassy_executor::task]
|
||||||
|
pub(crate) async fn run_dhcp(stack: Stack<'static>, ip: Ipv4Addr) {
|
||||||
|
let mut buf = [0u8; 1500];
|
||||||
|
|
||||||
|
let mut gw_buf = [Ipv4Addr::UNSPECIFIED];
|
||||||
|
|
||||||
|
let buffers = UdpBuffers::<3, 1024, 1024, 10>::new();
|
||||||
|
let unbound_socket = Udp::new(stack, &buffers);
|
||||||
|
let mut bound_socket = match unbound_socket
|
||||||
|
.bind(SocketAddr::V4(SocketAddrV4::new(
|
||||||
|
Ipv4Addr::UNSPECIFIED,
|
||||||
|
DEFAULT_SERVER_PORT,
|
||||||
|
)))
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(s) => s,
|
||||||
|
Err(e) => {
|
||||||
|
error!("dhcp task failed to bind socket: {:?}", e);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
loop {
|
||||||
|
_ = io::server::run(
|
||||||
|
&mut Server::<_, 64>::new_with_et(ip),
|
||||||
|
&ServerOptions::new(ip, Some(&mut gw_buf)),
|
||||||
|
&mut bound_socket,
|
||||||
|
&mut buf,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.inspect_err(|e| warn!("DHCP server error: {e:?}"));
|
||||||
|
Timer::after(Duration::from_millis(500)).await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn wifi_ap(
|
||||||
|
ssid: String,
|
||||||
|
interface_ap: Interface<'static>,
|
||||||
|
controller: &Arc<Mutex<CriticalSectionRawMutex, esp_radio::wifi::WifiController<'static>>>,
|
||||||
|
rng: &mut Rng,
|
||||||
|
spawner: Spawner,
|
||||||
|
) -> FatResult<Stack<'static>> {
|
||||||
|
let gw_ip_addr = Ipv4Addr::new(192, 168, 71, 1);
|
||||||
|
|
||||||
|
let config = embassy_net::Config::ipv4_static(StaticConfigV4 {
|
||||||
|
address: embassy_net::Ipv4Cidr::new(gw_ip_addr, 24),
|
||||||
|
gateway: Some(gw_ip_addr),
|
||||||
|
dns_servers: Default::default(),
|
||||||
|
});
|
||||||
|
|
||||||
|
let seed = (rng.random() as u64) << 32 | rng.random() as u64;
|
||||||
|
|
||||||
|
println!("init secondary stack");
|
||||||
|
let (stack, runner) = embassy_net::new(
|
||||||
|
interface_ap,
|
||||||
|
config,
|
||||||
|
mk_static!(StackResources<4>, StackResources::<4>::new()),
|
||||||
|
seed,
|
||||||
|
);
|
||||||
|
let stack = mk_static!(Stack, stack);
|
||||||
|
|
||||||
|
let client_config =
|
||||||
|
Config::AccessPoint(AccessPointConfig::default().with_ssid(ssid.clone()));
|
||||||
|
controller.lock().await.set_config(&client_config)?;
|
||||||
|
|
||||||
|
println!("start net task");
|
||||||
|
spawner.spawn(net_task(runner)?);
|
||||||
|
println!("run dhcp");
|
||||||
|
spawner.spawn(run_dhcp(*stack, gw_ip_addr)?);
|
||||||
|
|
||||||
|
loop {
|
||||||
|
if stack.is_link_up() {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
Timer::after(Duration::from_millis(500)).await;
|
||||||
|
}
|
||||||
|
while !stack.is_config_up() {
|
||||||
|
Timer::after(Duration::from_millis(100)).await
|
||||||
|
}
|
||||||
|
println!("Connect to the AP `${ssid}` and point your browser to http://{gw_ip_addr}/");
|
||||||
|
stack
|
||||||
|
.config_v4()
|
||||||
|
.inspect(|c| println!("ipv4 config: {c:?}"));
|
||||||
|
|
||||||
|
Ok(*stack)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn wifi(
|
||||||
|
network_config: &NetworkConfig,
|
||||||
|
interface_sta: Interface<'static>,
|
||||||
|
controller: &Arc<Mutex<CriticalSectionRawMutex, esp_radio::wifi::WifiController<'static>>>,
|
||||||
|
rng: &mut Rng,
|
||||||
|
spawner: Spawner,
|
||||||
|
) -> FatResult<Stack<'static>> {
|
||||||
|
esp_radio::wifi_set_log_verbose();
|
||||||
|
let ssid = match &network_config.ssid {
|
||||||
|
Some(ssid) => {
|
||||||
|
if ssid.is_empty() {
|
||||||
|
bail!("Wifi ssid was empty")
|
||||||
|
}
|
||||||
|
ssid.as_str().to_string()
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
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 config = embassy_net::Config::dhcpv4(DhcpConfig::default());
|
||||||
|
|
||||||
|
let seed = (rng.random() as u64) << 32 | rng.random() as u64;
|
||||||
|
|
||||||
|
let (stack, runner) = embassy_net::new(
|
||||||
|
interface_sta,
|
||||||
|
config,
|
||||||
|
mk_static!(StackResources<8>, StackResources::<8>::new()),
|
||||||
|
seed,
|
||||||
|
);
|
||||||
|
let stack = mk_static!(Stack, stack);
|
||||||
|
|
||||||
|
let auth_method = if password.is_empty() {
|
||||||
|
AuthenticationMethod::None
|
||||||
|
} 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))?;
|
||||||
|
spawner.spawn(net_task(runner)?);
|
||||||
|
controller
|
||||||
|
.lock()
|
||||||
|
.await
|
||||||
|
.connect_async()
|
||||||
|
.with_timeout(Duration::from_millis(max_wait as u64 * 1000))
|
||||||
|
.await
|
||||||
|
.context("Timeout waiting for wifi sta connected")??;
|
||||||
|
|
||||||
|
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;
|
||||||
|
|
||||||
|
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
|
||||||
|
}
|
||||||
|
Ok::<(), FatError>(())
|
||||||
|
}
|
||||||
|
.with_timeout(Duration::from_millis(max_wait as u64 * 1000))
|
||||||
|
.await;
|
||||||
|
|
||||||
|
if res.is_err() {
|
||||||
|
bail!("Timeout waiting for wifi config up")
|
||||||
|
}
|
||||||
|
|
||||||
|
info!("Connected WIFI, dhcp: {:?}", stack.config_v4());
|
||||||
|
Ok(*stack)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn try_connect_wifi_sntp_mqtt(
|
||||||
|
board: &mut MutexGuard<'static, CriticalSectionRawMutex, HAL<'static>>,
|
||||||
|
stack_store: &mut OptionLock<Stack<'static>>,
|
||||||
|
spawner: Spawner,
|
||||||
|
) -> NetworkMode {
|
||||||
|
let nw_conf = &board.board_hal.get_config().network.clone();
|
||||||
|
let esp = board.board_hal.get_esp();
|
||||||
|
let device = match esp.interface_sta.take() {
|
||||||
|
Some(d) => d,
|
||||||
|
None => {
|
||||||
|
info!("Offline mode due to STA interface already taken");
|
||||||
|
board.board_hal.general_fault(true).await;
|
||||||
|
return NetworkMode::OFFLINE;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
match wifi(nw_conf, device, &esp.controller, &mut esp.rng, spawner).await {
|
||||||
|
Ok(stack) => {
|
||||||
|
stack_store.replace(stack);
|
||||||
|
|
||||||
|
let sntp_mode: SntpMode = match sntp(1000 * 10, stack).await {
|
||||||
|
Ok(new_time) => {
|
||||||
|
info!("Using time from sntp {}", new_time.to_rfc3339());
|
||||||
|
let _ = board
|
||||||
|
.board_hal
|
||||||
|
.get_rtc_module()
|
||||||
|
.set_rtc_time(&new_time)
|
||||||
|
.await;
|
||||||
|
SntpMode::SYNC { current: new_time }
|
||||||
|
}
|
||||||
|
Err(err) => {
|
||||||
|
warn!("sntp error: {err}");
|
||||||
|
board.board_hal.general_fault(true).await;
|
||||||
|
SntpMode::OFFLINE
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let mqtt_connected = if board.board_hal.get_config().network.mqtt_url.is_some() {
|
||||||
|
let nw_config = board.board_hal.get_config().network.clone();
|
||||||
|
let nw_config = mk_static!(NetworkConfig, nw_config);
|
||||||
|
match mqtt::mqtt_init(nw_config, stack, spawner).await {
|
||||||
|
Ok(_) => {
|
||||||
|
info!("Mqtt connection ready");
|
||||||
|
true
|
||||||
|
}
|
||||||
|
Err(err) => {
|
||||||
|
warn!("Could not connect mqtt due to {err}");
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
false
|
||||||
|
};
|
||||||
|
|
||||||
|
let ip = match stack.config_v4() {
|
||||||
|
Some(config) => config.address.address().to_string(),
|
||||||
|
None => match stack.config_v6() {
|
||||||
|
Some(config) => config.address.address().to_string(),
|
||||||
|
None => String::from("No IP"),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
NetworkMode::WIFI {
|
||||||
|
sntp: sntp_mode,
|
||||||
|
mqtt: mqtt_connected,
|
||||||
|
ip_address: ip,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(err) => {
|
||||||
|
info!("Offline mode due to {err}");
|
||||||
|
board.board_hal.general_fault(true).await;
|
||||||
|
NetworkMode::OFFLINE
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -11,11 +11,12 @@ 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, Serialize)]
|
#[derive(Debug, PartialEq, Clone, 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(String),
|
BoardError { message: String },
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, PartialEq, Serialize)]
|
#[derive(Debug, PartialEq, Serialize)]
|
||||||
@@ -49,6 +50,14 @@ 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,
|
||||||
@@ -134,9 +143,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 {
|
||||||
err.to_string(),
|
message: err.to_string(),
|
||||||
)),
|
})
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
MoistureSensorState::Disabled
|
MoistureSensorState::Disabled
|
||||||
@@ -159,9 +168,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 {
|
||||||
err.to_string(),
|
message: err.to_string(),
|
||||||
)),
|
})
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
MoistureSensorState::Disabled
|
MoistureSensorState::Disabled
|
||||||
@@ -277,19 +286,21 @@ 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 {
|
||||||
sensor_a: &self.sensor_a,
|
moisture_pct,
|
||||||
sensor_b: &self.sensor_b,
|
sensor_a: Self::sensor_to_telemetry(&self.sensor_a),
|
||||||
|
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) = self.plant_moisture().0 {
|
dry: if let Some(moisture_percent) = moisture_pct {
|
||||||
moisture_percent < plant_conf.target_moisture
|
moisture_percent < plant_conf.target_moisture
|
||||||
} else {
|
} else {
|
||||||
false
|
false
|
||||||
},
|
},
|
||||||
cooldown: self.pump_in_timeout(plant_conf, current_time),
|
cooldown: self.pump_in_timeout(plant_conf, current_time),
|
||||||
out_of_work_hour: in_time_range(
|
out_of_work_hour: !in_time_range(
|
||||||
current_time,
|
current_time,
|
||||||
plant_conf.pump_hour_start,
|
plant_conf.pump_hour_start,
|
||||||
plant_conf.pump_hour_end,
|
plant_conf.pump_hour_end,
|
||||||
@@ -316,15 +327,40 @@ 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<'a> {
|
pub struct PlantInfo {
|
||||||
|
/// 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: &'a MoistureSensorState,
|
sensor_a: SensorTelemetry,
|
||||||
/// state of humidity sensor on bank b
|
/// state of humidity sensor on bank b
|
||||||
sensor_b: &'a MoistureSensorState,
|
sensor_b: SensorTelemetry,
|
||||||
/// configured plant watering mode
|
/// configured plant watering mode
|
||||||
mode: PlantWateringMode,
|
mode: PlantWateringMode,
|
||||||
/// the plant needs to be watered
|
/// the plant needs to be watered
|
||||||
|
|||||||
@@ -10,11 +10,12 @@ 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(f32),
|
SensorMissing { raw_mv: f32 },
|
||||||
SensorValueError { value: f32, min: f32, max: f32 },
|
SensorValueError { value: f32, min: f32, max: f32 },
|
||||||
BoardError(String),
|
BoardError { message: String },
|
||||||
}
|
}
|
||||||
|
|
||||||
pub enum TankState {
|
pub enum TankState {
|
||||||
@@ -25,7 +26,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_value_mv));
|
return Err(TankError::SensorMissing { raw_mv: 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);
|
||||||
@@ -141,15 +142,15 @@ impl TankState {
|
|||||||
TankInfo {
|
TankInfo {
|
||||||
enough_water,
|
enough_water,
|
||||||
warn_level,
|
warn_level,
|
||||||
left_ml,
|
volume_ml: left_ml,
|
||||||
sensor_error: tank_err,
|
sensor_error: tank_err,
|
||||||
raw,
|
fill_raw_v: 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: water_temp.as_ref().copied().ok(),
|
water_temp_c: 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()),
|
||||||
percent,
|
fill_pct: percent,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -164,7 +165,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(err.to_string())),
|
Err(err) => TankState::Error(TankError::BoardError { message: err.to_string() }),
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
TankState::Disabled
|
TankState::Disabled
|
||||||
@@ -179,16 +180,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) left_ml: Option<f32>,
|
pub(crate) volume_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) raw: Option<f32>,
|
pub(crate) fill_raw_v: Option<f32>,
|
||||||
/// percent value
|
/// percent value
|
||||||
pub(crate) percent: Option<f32>,
|
pub(crate) fill_pct: 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: Option<f32>,
|
pub(crate) water_temp_c: Option<f32>,
|
||||||
pub(crate) temp_sensor_error: Option<String>,
|
pub(crate) temp_sensor_error: Option<String>,
|
||||||
}
|
}
|
||||||
|
|||||||
10
rust/src/util.rs
Normal file
10
rust/src/util.rs
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
macro_rules! mk_static {
|
||||||
|
($t:ty,$val:expr) => {{
|
||||||
|
static STATIC_CELL: static_cell::StaticCell<$t> = static_cell::StaticCell::new();
|
||||||
|
#[deny(unused_attributes)]
|
||||||
|
let x = STATIC_CELL.uninit().write(($val));
|
||||||
|
x
|
||||||
|
}};
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) use mk_static;
|
||||||
@@ -30,59 +30,80 @@ 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::TcpBind;
|
|
||||||
use edge_nal::io::{Read, Write};
|
use edge_nal::io::{Read, Write};
|
||||||
|
use edge_nal::TcpBind;
|
||||||
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::info;
|
use log::{error, info};
|
||||||
|
|
||||||
// fn ota(
|
pub(crate) async fn ota_operations<T, const N: usize>(
|
||||||
// request: &mut Request<&mut EspHttpConnection>,
|
conn: &mut Connection<'_, T, { N }>,
|
||||||
// ) -> Result<Option<std::string::String>, anyhow::Error> {
|
method: Method,
|
||||||
// let mut board = BOARD_ACCESS.lock().unwrap();
|
) -> Result<Option<u32>, FatError>
|
||||||
// let mut ota = OtaUpdate::begin()?;
|
where
|
||||||
// log::info!("start ota");
|
T: Read + Write,
|
||||||
//
|
{
|
||||||
// //having a larger buffer is not really faster, requires more stack and prevents the progress bar from working ;)
|
Ok(match method {
|
||||||
// const BUFFER_SIZE: usize = 512;
|
Method::Options => {
|
||||||
// let mut buffer: [u8; BUFFER_SIZE] = [0; BUFFER_SIZE];
|
conn.initiate_response(
|
||||||
// let mut total_read: usize = 0;
|
200,
|
||||||
// let mut lastiter = 0;
|
Some("OK"),
|
||||||
// loop {
|
&[
|
||||||
// let read = request.read(&mut buffer)?;
|
("Access-Control-Allow-Origin", "*"),
|
||||||
// total_read += read;
|
("Access-Control-Allow-Headers", "*"),
|
||||||
// let to_write = &buffer[0..read];
|
("Access-Control-Allow-Methods", "*"),
|
||||||
// //delay for watchdog and wifi stuff
|
],
|
||||||
// board.board_hal.get_esp().delay.delay_ms(1);
|
)
|
||||||
//
|
.await?;
|
||||||
// let iter = (total_read / 1024) % 8;
|
Some(200)
|
||||||
// if iter != lastiter {
|
}
|
||||||
// board.board_hal.general_fault(iter % 5 == 0);
|
Method::Post => {
|
||||||
// for i in 0..PLANT_COUNT {
|
let mut offset = 0_usize;
|
||||||
// let _ = board.board_hal.fault(i, iter == i);
|
let mut chunk = 0;
|
||||||
// }
|
loop {
|
||||||
// lastiter = iter;
|
let buf = read_up_to_bytes_from_request(conn, Some(4096)).await?;
|
||||||
// }
|
if buf.is_empty() {
|
||||||
//
|
info!("file request for ota finished");
|
||||||
// ota.write(to_write)?;
|
let mut board = BOARD_ACCESS.get().await.lock().await;
|
||||||
// if read == 0 {
|
board.board_hal.get_esp().finalize_ota().await?;
|
||||||
// break;
|
break;
|
||||||
// }
|
} else {
|
||||||
// }
|
let mut board = BOARD_ACCESS.get().await.lock().await;
|
||||||
// log::info!("wrote bytes ota {total_read}");
|
board.board_hal.progress(chunk as u32).await;
|
||||||
// log::info!("finish ota");
|
// Erase next block if we are at a 4K boundary (including the first block at offset 0)
|
||||||
// let partition = ota.raw_partition();
|
board
|
||||||
// log::info!("finalizing and changing boot partition to {partition:?}");
|
.board_hal
|
||||||
//
|
.get_esp()
|
||||||
// let mut finalizer = ota.finalize()?;
|
.write_ota(offset as u32, &buf)
|
||||||
// log::info!("changing boot partition");
|
.await?;
|
||||||
// board.board_hal.get_esp().set_restart_to_conf(true);
|
}
|
||||||
// drop(board);
|
offset += buf.len();
|
||||||
// finalizer.set_as_boot_partition()?;
|
chunk += 1;
|
||||||
// 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>,
|
||||||
@@ -105,7 +126,12 @@ impl Handler for HTTPRequestRouter {
|
|||||||
let path = headers.path;
|
let path = headers.path;
|
||||||
|
|
||||||
let prefix = "/file?filename=";
|
let prefix = "/file?filename=";
|
||||||
let status = if path.starts_with(prefix) {
|
let status = if path == "/ota" {
|
||||||
|
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 {
|
||||||
@@ -195,12 +221,18 @@ 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 read = request.read(&mut buf).await?;
|
let s_buf = if buf.len() <= left {
|
||||||
|
&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 = &buf[0..read];
|
let actual_data = &s_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}");
|
||||||
|
|||||||
@@ -157,7 +157,13 @@ export interface Moistures {
|
|||||||
export interface VersionInfo {
|
export interface VersionInfo {
|
||||||
git_hash: string,
|
git_hash: string,
|
||||||
build_time: string,
|
build_time: string,
|
||||||
partition: string
|
current: 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 {
|
||||||
|
|||||||
@@ -31,6 +31,7 @@ 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> {
|
||||||
@@ -200,15 +201,22 @@ export class Controller {
|
|||||||
}, false);
|
}, false);
|
||||||
ajax.addEventListener("load", () => {
|
ajax.addEventListener("load", () => {
|
||||||
controller.progressview.removeProgress("ota_upload")
|
controller.progressview.removeProgress("ota_upload")
|
||||||
controller.reboot();
|
const status = ajax.status;
|
||||||
|
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);
|
||||||
|
|||||||
@@ -1,23 +1,27 @@
|
|||||||
<style>
|
<style>
|
||||||
.otakey{
|
.otakey {
|
||||||
min-width: 100px;
|
min-width: 100px;
|
||||||
}
|
}
|
||||||
.otavalue{
|
|
||||||
flex-grow: 1;
|
.otavalue {
|
||||||
}
|
flex-grow: 1;
|
||||||
.otaform {
|
}
|
||||||
min-width: 100px;
|
|
||||||
flex-grow: 1;
|
.otaform {
|
||||||
}
|
min-width: 100px;
|
||||||
.otachooser {
|
flex-grow: 1;
|
||||||
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>
|
||||||
@@ -28,14 +32,46 @@
|
|||||||
<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>
|
||||||
@@ -1,21 +1,37 @@
|
|||||||
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
|
||||||
@@ -31,11 +47,21 @@ 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.partition;
|
this.firmware_partition.innerText = versionInfo.current;
|
||||||
|
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);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
94
rust/src_webpack/src/toast.ts
Normal file
94
rust/src_webpack/src/toast.ts
Normal file
@@ -0,0 +1,94 @@
|
|||||||
|
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();
|
||||||
Reference in New Issue
Block a user