Compare commits
12 Commits
9c363e3760
...
a8893974a5
| Author | SHA1 | Date | |
|---|---|---|---|
|
a8893974a5
|
|||
|
1b2ace0612
|
|||
|
9015a6376d
|
|||
|
4893cbce55
|
|||
|
d3d8d829be
|
|||
|
6889ba4561
|
|||
|
18095349f3
|
|||
|
3d8fd893f5
|
|||
|
1bea7ef2f4
|
|||
|
f5b9674840
|
|||
|
6f22881007
|
|||
|
1d8af1b6c4
|
@@ -27,20 +27,22 @@ pub trait BatteryInteraction {
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct BatteryInfo {
|
||||
pub voltage_milli_volt: u16,
|
||||
pub average_current_milli_ampere: i16,
|
||||
pub cycle_count: u16,
|
||||
pub design_milli_ampere_hour: u16,
|
||||
pub remaining_milli_ampere_hour: u16,
|
||||
pub state_of_charge: f32,
|
||||
pub state_of_health: u16,
|
||||
pub temperature: u16,
|
||||
pub voltage_mv: Option<u16>,
|
||||
pub avg_current_ma: Option<i16>,
|
||||
pub soc_pct: Option<f32>,
|
||||
pub soh_pct: Option<u16>,
|
||||
pub temperature_c: Option<u16>,
|
||||
pub cycle_count: Option<u16>,
|
||||
pub remaining_mah: Option<u16>,
|
||||
pub design_mah: Option<u16>,
|
||||
pub error: Option<BatteryError>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(tag = "kind")]
|
||||
pub enum BatteryError {
|
||||
NoBatteryMonitor,
|
||||
CommunicationError(String),
|
||||
CommunicationError { message: String },
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
@@ -180,14 +182,15 @@ impl BatteryInteraction for BQ34Z100G1 {
|
||||
|
||||
async fn get_battery_state(&mut self) -> FatResult<BatteryState> {
|
||||
Ok(BatteryState::Info(BatteryInfo {
|
||||
voltage_milli_volt: self.voltage_milli_volt().await?,
|
||||
average_current_milli_ampere: self.average_current_milli_ampere().await?,
|
||||
cycle_count: self.cycle_count().await?,
|
||||
design_milli_ampere_hour: self.design_milli_ampere_hour().await?,
|
||||
remaining_milli_ampere_hour: self.remaining_milli_ampere_hour().await?,
|
||||
state_of_charge: self.state_charge_percent().await?,
|
||||
state_of_health: self.state_health_percent().await?,
|
||||
temperature: self.bat_temperature().await?,
|
||||
voltage_mv: Some(self.voltage_milli_volt().await?),
|
||||
avg_current_ma: Some(self.average_current_milli_ampere().await?),
|
||||
soc_pct: Some(self.state_charge_percent().await?),
|
||||
soh_pct: Some(self.state_health_percent().await?),
|
||||
temperature_c: Some(self.bat_temperature().await?),
|
||||
cycle_count: Some(self.cycle_count().await?),
|
||||
remaining_mah: Some(self.remaining_milli_ampere_hour().await?),
|
||||
design_mah: Some(self.design_milli_ampere_hour().await?),
|
||||
error: None,
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,8 +17,6 @@ use core::net::{IpAddr, Ipv4Addr, SocketAddr};
|
||||
use core::str::FromStr;
|
||||
use core::sync::atomic::Ordering;
|
||||
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_sync::blocking_mutex::raw::CriticalSectionRawMutex;
|
||||
use embassy_sync::mutex::{Mutex, MutexGuard};
|
||||
@@ -44,9 +42,9 @@ use littlefs2::fs::Filesystem;
|
||||
use littlefs2_core::{FileType, PathBuf, SeekFrom};
|
||||
use log::{info, warn, error};
|
||||
use portable_atomic::AtomicBool;
|
||||
use sntpc::{NtpContext, NtpTimestampGenerator, NtpUdpSocket, get_time};
|
||||
|
||||
use super::shared_flash::MutexFlashStorage;
|
||||
use crate::network::{net_task, run_dhcp};
|
||||
|
||||
#[esp_hal::ram(unstable(rtc_fast), unstable(persistent))]
|
||||
static mut LAST_WATERING_TIMESTAMP: [i64; PLANT_COUNT] = [0; PLANT_COUNT];
|
||||
@@ -61,7 +59,6 @@ static mut LAST_CORROSION_PROTECTION_CHECK_DAY: i8 = -1;
|
||||
|
||||
|
||||
const CONFIG_FILE: &str = "config.json";
|
||||
const NTP_SERVER: &str = "pool.ntp.org";
|
||||
|
||||
#[derive(Serialize, Debug)]
|
||||
pub struct FileInfo {
|
||||
@@ -76,11 +73,6 @@ pub struct FileList {
|
||||
files: Vec<FileInfo>,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Default)]
|
||||
struct Timestamp {
|
||||
stamp: DateTime<Utc>,
|
||||
}
|
||||
|
||||
// Minimal esp-idf equivalent for gpio_hold on esp32c6 via ROM functions
|
||||
extern "C" {
|
||||
fn gpio_pad_hold(gpio_num: u32);
|
||||
@@ -97,53 +89,6 @@ pub fn hold_disable(gpio_num: u8) {
|
||||
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 fs: Arc<Mutex<CriticalSectionRawMutex, Filesystem<'static, LittleFs2Filesystem>>>,
|
||||
pub rng: Rng,
|
||||
@@ -345,66 +290,6 @@ impl Esp<'_> {
|
||||
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>> {
|
||||
info!("start wifi scan");
|
||||
let mut lock = self.controller.try_lock()?;
|
||||
@@ -462,160 +347,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) -> ! {
|
||||
// Mark the current OTA image as valid if we reached here while in pending verify.
|
||||
if let Ok(cur) = self.ota.current_ota_state() {
|
||||
@@ -731,52 +462,3 @@ impl Esp<'_> {
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
#[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;
|
||||
}
|
||||
}
|
||||
|
||||
175
rust/src/main.rs
175
rust/src/main.rs
@@ -17,7 +17,7 @@ use esp_backtrace as _;
|
||||
use hal::PROGRESS_ACTIVE;
|
||||
|
||||
use crate::config::{NetworkConfig, PlantConfig};
|
||||
use crate::fat_error::FatResult;
|
||||
use crate::fat_error::{ContextExt, FatResult};
|
||||
|
||||
use crate::log::log;
|
||||
use crate::tank::{determine_tank_state, TankError, TankState, WATER_FROZEN_THRESH};
|
||||
@@ -43,7 +43,7 @@ use embassy_time::{Duration, Instant, Timer};
|
||||
use esp_hal::rom::ets_delay_us;
|
||||
use esp_hal::system::software_reset;
|
||||
use esp_println::{logger, println};
|
||||
use hal::battery::BatteryState;
|
||||
use hal::battery::{BatteryError, BatteryInfo, BatteryState};
|
||||
use log::LogMessage;
|
||||
use option_lock::OptionLock;
|
||||
use plant_state::PlantState;
|
||||
@@ -68,6 +68,7 @@ mod fat_error;
|
||||
mod hal;
|
||||
mod log;
|
||||
mod mqtt;
|
||||
mod network;
|
||||
mod plant_state;
|
||||
mod tank;
|
||||
mod webserver;
|
||||
@@ -120,21 +121,7 @@ pub struct PumpResult {
|
||||
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<()> {
|
||||
info!("Startup Rust");
|
||||
@@ -208,7 +195,12 @@ async fn safe_main(spawner: Spawner) -> FatResult<()> {
|
||||
{
|
||||
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));
|
||||
println!("starting webserver");
|
||||
@@ -219,20 +211,30 @@ async fn safe_main(spawner: Spawner) -> FatResult<()> {
|
||||
|
||||
let mut stack: OptionLock<Stack> = OptionLock::empty();
|
||||
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 {
|
||||
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;
|
||||
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!");
|
||||
|
||||
let res = {
|
||||
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 {
|
||||
Ok(ap_stack) => {
|
||||
@@ -261,7 +263,7 @@ async fn safe_main(spawner: Spawner) -> FatResult<()> {
|
||||
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;
|
||||
publish_battery_state(&mut board).await;
|
||||
let _ = publish_mppt_state(&mut board).await;
|
||||
@@ -269,15 +271,15 @@ async fn safe_main(spawner: Spawner) -> FatResult<()> {
|
||||
|
||||
log(
|
||||
LogMessage::StartupInfo,
|
||||
matches!(network_mode, NetworkMode::WIFI { .. }) as u32,
|
||||
matches!(network_mode, network::NetworkMode::WIFI { .. }) as u32,
|
||||
matches!(
|
||||
network_mode,
|
||||
NetworkMode::WIFI {
|
||||
sntp: SntpMode::SYNC { .. },
|
||||
network::NetworkMode::WIFI {
|
||||
sntp: network::SntpMode::SYNC { .. },
|
||||
..
|
||||
}
|
||||
) as u32,
|
||||
matches!(network_mode, NetworkMode::WIFI { mqtt: true, .. })
|
||||
matches!(network_mode, network::NetworkMode::WIFI { mqtt: true, .. })
|
||||
.to_string()
|
||||
.as_str(),
|
||||
"",
|
||||
@@ -307,7 +309,7 @@ async fn safe_main(spawner: Spawner) -> FatResult<()> {
|
||||
if let Some(err) = tank_state.got_error(&board.board_hal.get_config().tank) {
|
||||
match err {
|
||||
TankError::SensorDisabled => { /* unreachable */ }
|
||||
TankError::SensorMissing(raw_value_mv) => log(
|
||||
TankError::SensorMissing { raw_mv: raw_value_mv } => log(
|
||||
LogMessage::TankSensorMissing,
|
||||
raw_value_mv as u32,
|
||||
0,
|
||||
@@ -321,8 +323,8 @@ async fn safe_main(spawner: Spawner) -> FatResult<()> {
|
||||
&format!("{value}"),
|
||||
"",
|
||||
),
|
||||
TankError::BoardError(err) => {
|
||||
log(LogMessage::TankSensorBoardError, 0, 0, "", &err.to_string())
|
||||
TankError::BoardError { message: err } => {
|
||||
log(LogMessage::TankSensorBoardError, 0, 0, "", &err)
|
||||
}
|
||||
}
|
||||
// disabled cannot trigger this because of wrapping if is_enabled
|
||||
@@ -732,85 +734,12 @@ async fn publish_firmware_info(
|
||||
timezone_time: &str,
|
||||
) {
|
||||
mqtt::publish("/firmware/address", ip_address).await;
|
||||
mqtt::publish("/firmware/state", format!("{:?}", &version).as_str())
|
||||
mqtt::publish("/firmware/state", &serde_json::to_string(&version).unwrap())
|
||||
.await;
|
||||
mqtt::publish("/firmware/last_online", timezone_time)
|
||||
.await;
|
||||
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 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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn pump_info(
|
||||
plant_id: usize,
|
||||
pump_active: bool,
|
||||
@@ -857,20 +786,40 @@ async fn publish_mppt_state(
|
||||
async fn publish_battery_state(
|
||||
board: &mut MutexGuard<'_, CriticalSectionRawMutex, HAL<'static>>,
|
||||
) -> () {
|
||||
let state = board
|
||||
let telemetry = match 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(),
|
||||
};
|
||||
.await
|
||||
{
|
||||
let _ = mqtt::publish("/battery", &*value).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 _ = mqtt::publish("/battery", &json).await;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
427
rust/src/network.rs
Normal file
427
rust/src/network.rs
Normal file
@@ -0,0 +1,427 @@
|
||||
use crate::bail;
|
||||
use crate::config::NetworkConfig;
|
||||
use crate::fat_error::{ContextExt, FatError, FatResult};
|
||||
use crate::hal::{PlantHal, HAL};
|
||||
use crate::mqtt;
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
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 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_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 {
|
||||
ShortCircuit { hz: f32, max: f32 },
|
||||
OpenLoop { hz: f32, min: f32 },
|
||||
BoardError(String),
|
||||
BoardError { message: String },
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Serialize)]
|
||||
@@ -49,6 +50,14 @@ impl MoistureSensorState {
|
||||
impl MoistureSensorState {}
|
||||
|
||||
#[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 {
|
||||
PumpNotWorking {
|
||||
failed_attempts: usize,
|
||||
@@ -134,9 +143,9 @@ impl PlantState {
|
||||
},
|
||||
Err(err) => MoistureSensorState::SensorError(err),
|
||||
},
|
||||
Err(err) => MoistureSensorState::SensorError(MoistureSensorError::BoardError(
|
||||
err.to_string(),
|
||||
)),
|
||||
Err(err) => MoistureSensorState::SensorError(MoistureSensorError::BoardError {
|
||||
message: err.to_string(),
|
||||
})
|
||||
}
|
||||
} else {
|
||||
MoistureSensorState::Disabled
|
||||
@@ -159,9 +168,9 @@ impl PlantState {
|
||||
},
|
||||
Err(err) => MoistureSensorState::SensorError(err),
|
||||
},
|
||||
Err(err) => MoistureSensorState::SensorError(MoistureSensorError::BoardError(
|
||||
err.to_string(),
|
||||
)),
|
||||
Err(err) => MoistureSensorState::SensorError(MoistureSensorError::BoardError {
|
||||
message: err.to_string(),
|
||||
})
|
||||
}
|
||||
} else {
|
||||
MoistureSensorState::Disabled
|
||||
@@ -277,13 +286,15 @@ impl PlantState {
|
||||
&self,
|
||||
plant_conf: &PlantConfig,
|
||||
current_time: &DateTime<Tz>,
|
||||
) -> PlantInfo<'_> {
|
||||
) -> PlantInfo {
|
||||
let (moisture_pct, _) = self.plant_moisture();
|
||||
PlantInfo {
|
||||
sensor_a: &self.sensor_a,
|
||||
sensor_b: &self.sensor_b,
|
||||
moisture_pct,
|
||||
sensor_a: Self::sensor_to_telemetry(&self.sensor_a),
|
||||
sensor_b: Self::sensor_to_telemetry(&self.sensor_b),
|
||||
mode: plant_conf.mode,
|
||||
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
|
||||
} else {
|
||||
false
|
||||
@@ -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)]
|
||||
/// 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
|
||||
sensor_a: &'a MoistureSensorState,
|
||||
sensor_a: SensorTelemetry,
|
||||
/// state of humidity sensor on bank b
|
||||
sensor_b: &'a MoistureSensorState,
|
||||
sensor_b: SensorTelemetry,
|
||||
/// configured plant watering mode
|
||||
mode: PlantWateringMode,
|
||||
/// 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;
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(tag = "kind")]
|
||||
pub enum TankError {
|
||||
SensorDisabled,
|
||||
SensorMissing(f32),
|
||||
SensorMissing { raw_mv: f32 },
|
||||
SensorValueError { value: f32, min: f32, max: f32 },
|
||||
BoardError(String),
|
||||
BoardError { message: String },
|
||||
}
|
||||
|
||||
pub enum TankState {
|
||||
@@ -25,7 +26,7 @@ pub enum TankState {
|
||||
|
||||
fn raw_voltage_to_divider_percent(raw_value_mv: f32) -> Result<f32, TankError> {
|
||||
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);
|
||||
@@ -141,15 +142,15 @@ impl TankState {
|
||||
TankInfo {
|
||||
enough_water,
|
||||
warn_level,
|
||||
left_ml,
|
||||
volume_ml: left_ml,
|
||||
sensor_error: tank_err,
|
||||
raw,
|
||||
fill_raw_v: raw,
|
||||
water_frozen: water_temp
|
||||
.as_ref()
|
||||
.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()),
|
||||
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()))
|
||||
{
|
||||
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 {
|
||||
TankState::Disabled
|
||||
@@ -179,16 +180,16 @@ pub struct TankInfo {
|
||||
/// warning that water needs to be refilled soon
|
||||
pub(crate) warn_level: bool,
|
||||
/// 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
|
||||
pub(crate) sensor_error: Option<TankError>,
|
||||
/// raw water sensor value
|
||||
pub(crate) raw: Option<f32>,
|
||||
pub(crate) fill_raw_v: Option<f32>,
|
||||
/// percent value
|
||||
pub(crate) percent: Option<f32>,
|
||||
pub(crate) fill_pct: Option<f32>,
|
||||
/// water in the tank might be frozen
|
||||
pub(crate) water_frozen: bool,
|
||||
/// water temperature
|
||||
pub(crate) water_temp: Option<f32>,
|
||||
pub(crate) water_temp_c: Option<f32>,
|
||||
pub(crate) temp_sensor_error: Option<String>,
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user