more async migration

This commit is contained in:
2025-09-12 16:30:35 +02:00
parent 0d495d0f56
commit 79087c9353
11 changed files with 347 additions and 308 deletions

View File

@@ -1,22 +1,20 @@
use anyhow::anyhow;
use bq34z100::{Bq34Z100Error, Bq34z100g1, Bq34z100g1Driver};
use embedded_hal_bus::i2c::MutexDevice;
use esp_idf_hal::delay::Delay;
use esp_idf_hal::i2c::{I2cDriver, I2cError};
use async_trait::async_trait;
use measurements::Temperature;
use serde::Serialize;
#[async_trait]
pub trait BatteryInteraction {
fn state_charge_percent(&mut self) -> Result<f32, BatteryError>;
fn remaining_milli_ampere_hour(&mut self) -> Result<u16, BatteryError>;
fn max_milli_ampere_hour(&mut self) -> Result<u16, BatteryError>;
fn design_milli_ampere_hour(&mut self) -> Result<u16, BatteryError>;
fn voltage_milli_volt(&mut self) -> Result<u16, BatteryError>;
fn average_current_milli_ampere(&mut self) -> Result<i16, BatteryError>;
fn cycle_count(&mut self) -> Result<u16, BatteryError>;
fn state_health_percent(&mut self) -> Result<u16, BatteryError>;
fn bat_temperature(&mut self) -> Result<u16, BatteryError>;
fn get_battery_state(&mut self) -> Result<BatteryState, BatteryError>;
async fn state_charge_percent(&mut self) -> Result<f32, BatteryError>;
async fn remaining_milli_ampere_hour(&mut self) -> Result<u16, BatteryError>;
async fn max_milli_ampere_hour(&mut self) -> Result<u16, BatteryError>;
async fn design_milli_ampere_hour(&mut self) -> Result<u16, BatteryError>;
async fn voltage_milli_volt(&mut self) -> Result<u16, BatteryError>;
async fn average_current_milli_ampere(&mut self) -> Result<i16, BatteryError>;
async fn cycle_count(&mut self) -> Result<u16, BatteryError>;
async fn state_health_percent(&mut self) -> Result<u16, BatteryError>;
async fn bat_temperature(&mut self) -> Result<u16, BatteryError>;
async fn get_battery_state(&mut self) -> Result<BatteryState, BatteryError>;
}
#[derive(Debug, Serialize)]

View File

@@ -6,7 +6,10 @@ use anyhow::{anyhow, bail, Context};
use chrono::{DateTime, Utc};
use serde::Serialize;
use alloc::{vec::Vec, string::{String, ToString}};
use alloc::{
string::{String, ToString},
vec::Vec,
};
#[link_section = ".rtc.data"]
static mut LAST_WATERING_TIMESTAMP: [i64; PLANT_COUNT] = [0; PLANT_COUNT];
@@ -39,35 +42,38 @@ pub struct FileSystemSizeInfo {
}
pub struct MqttClient<'a> {
mqtt_client: EspMqttClient<'a>,
//mqtt_client: EspMqttClient<'a>,
base_topic: heapless::String<64>,
}
pub struct Esp<'a> {
pub(crate) mqtt_client: Option<MqttClient<'a>>,
pub(crate) wifi_driver: EspWifi<'a>,
pub(crate) boot_button: PinDriver<'a, esp_idf_hal::gpio::AnyIOPin, esp_idf_hal::gpio::Input>,
pub(crate) delay: Delay,
//pub(crate) wifi_driver: EspWifi<'a>,
//pub(crate) boot_button: PinDriver<'a, esp_idf_hal::gpio::AnyIOPin, esp_idf_hal::gpio::Input>,
}
struct AccessPointInfo {}
impl Esp<'_> {
const SPIFFS_PARTITION_NAME: &'static str = "storage";
const CONFIG_FILE: &'static str = "/spiffs/config.cfg";
const BASE_PATH: &'static str = "/spiffs";
pub(crate) fn mode_override_pressed(&mut self) -> bool {
self.boot_button.get_level() == Level::Low
todo!();
//self.boot_button.get_level() == Level::Low
}
pub(crate) fn sntp(&mut self, max_wait_ms: u32) -> anyhow::Result<DateTime<Utc>> {
let sntp = sntp::EspSntp::new_default()?;
let mut counter = 0;
while sntp.get_sync_status() != SyncStatus::Completed {
self.delay.delay_ms(100);
counter += 100;
if counter > max_wait_ms {
bail!("Reached sntp timeout, aborting")
}
}
self.time()
pub(crate) async fn sntp(&mut self, max_wait_ms: u32) -> anyhow::Result<DateTime<Utc>> {
//let sntp = sntp::EspSntp::new_default()?;
//let mut counter = 0;
//while sntp.get_sync_status() != SyncStatus::Completed {
// self.delay.delay_ms(100);
// counter += 100;
// if counter > max_wait_ms {
// bail!("Reached sntp timeout, aborting")
// }
//}
//self.time()
todo!();
}
pub(crate) fn time(&mut self) -> anyhow::Result<DateTime<Utc>> {
let time = EspSystemTime {}.now().as_millis();
@@ -76,7 +82,8 @@ impl Esp<'_> {
.ok_or(anyhow!("could not convert timestamp"))?;
anyhow::Ok(local_time)
}
pub(crate) fn wifi_scan(&mut self) -> anyhow::Result<Vec<AccessPointInfo>> {
pub(crate) async fn wifi_scan(&mut self) -> anyhow::Result<Vec<AccessPointInfo>> {
self.wifi_driver.start_scan(
&ScanConfig {
scan_type: ScanType::Passive(Duration::from_secs(5)),
@@ -128,7 +135,7 @@ impl Esp<'_> {
}
}
pub(crate) fn wifi_ap(&mut self) -> anyhow::Result<()> {
pub(crate) async fn wifi_ap(&mut self) -> anyhow::Result<()> {
let ssid = match self.load_config() {
Ok(config) => config.network.ap_ssid.clone(),
Err(_) => heapless::String::from_str("PlantCtrl Emergency Mode").unwrap(),
@@ -146,7 +153,7 @@ impl Esp<'_> {
anyhow::Ok(())
}
pub(crate) fn wifi(&mut self, network_config: &NetworkConfig) -> anyhow::Result<IpInfo> {
pub(crate) async fn wifi(&mut self, network_config: &NetworkConfig) -> anyhow::Result<IpInfo> {
let ssid = network_config
.ssid
.clone()
@@ -208,33 +215,36 @@ impl Esp<'_> {
log(LogMessage::WifiInfo, 0, 0, "", &format!("{address:?}"));
anyhow::Ok(address)
}
pub(crate) fn load_config(&mut self) -> anyhow::Result<PlantControllerConfig> {
pub(crate) async fn load_config(&mut self) -> anyhow::Result<PlantControllerConfig> {
let cfg = File::open(Self::CONFIG_FILE)?;
let config: PlantControllerConfig = serde_json::from_reader(cfg)?;
anyhow::Ok(config)
}
pub(crate) fn save_config(&mut self, config: &PlantControllerConfig) -> anyhow::Result<()> {
pub(crate) async fn save_config(
&mut self,
config: &PlantControllerConfig,
) -> anyhow::Result<()> {
let mut cfg = File::create(Self::CONFIG_FILE)?;
serde_json::to_writer(&mut cfg, &config)?;
log::info!("Wrote config config {:?}", config);
anyhow::Ok(())
}
pub(crate) fn mount_file_system(&mut self) -> anyhow::Result<()> {
pub(crate) async fn mount_file_system(&mut self) -> anyhow::Result<()> {
log(LogMessage::MountingFilesystem, 0, 0, "", "");
let base_path = String::try_from("/spiffs")?;
let storage = String::try_from(Self::SPIFFS_PARTITION_NAME)?;
let conf = todo!();
//let conf = esp_idf_sys::esp_vfs_spiffs_conf_t {
//base_path: base_path.as_ptr(),
//partition_label: storage.as_ptr(),
//max_files: 5,
//format_if_mount_failed: true,
//base_path: base_path.as_ptr(),
//partition_label: storage.as_ptr(),
//max_files: 5,
//format_if_mount_failed: true,
//};
//TODO
//unsafe {
//esp_idf_sys::esp!(esp_idf_sys::esp_vfs_spiffs_register(&conf))?;
//esp_idf_sys::esp!(esp_idf_sys::esp_vfs_spiffs_register(&conf))?;
//}
let free_space = self.file_system_size()?;
@@ -247,7 +257,7 @@ impl Esp<'_> {
);
anyhow::Ok(())
}
fn file_system_size(&mut self) -> anyhow::Result<FileSystemSizeInfo> {
async fn file_system_size(&mut self) -> anyhow::Result<FileSystemSizeInfo> {
let storage = CString::new(Self::SPIFFS_PARTITION_NAME)?;
let mut total_size = 0;
let mut used_size = 0;
@@ -265,7 +275,7 @@ impl Esp<'_> {
})
}
pub(crate) fn list_files(&self) -> FileList {
pub(crate) async fn list_files(&self) -> FileList {
let storage = CString::new(Self::SPIFFS_PARTITION_NAME).unwrap();
let mut file_system_corrupt = None;
@@ -312,7 +322,7 @@ impl Esp<'_> {
iter_error,
}
}
pub(crate) fn delete_file(&self, filename: &str) -> anyhow::Result<()> {
pub(crate) async fn delete_file(&self, filename: &str) -> anyhow::Result<()> {
let filepath = Path::new(Self::BASE_PATH).join(Path::new(filename));
match fs::remove_file(filepath) {
OkStd(_) => anyhow::Ok(()),
@@ -321,7 +331,11 @@ impl Esp<'_> {
}
}
}
pub(crate) fn get_file_handle(&self, filename: &str, write: bool) -> anyhow::Result<File> {
pub(crate) async fn get_file_handle(
&self,
filename: &str,
write: bool,
) -> anyhow::Result<File> {
let filepath = Path::new(Self::BASE_PATH).join(Path::new(filename));
anyhow::Ok(if write {
File::create(filepath)?
@@ -361,20 +375,22 @@ impl Esp<'_> {
for i in 0..PLANT_COUNT {
log::info!(
"LAST_WATERING_TIMESTAMP[{}] = UTC {}",
i, LAST_WATERING_TIMESTAMP[i]
i,
LAST_WATERING_TIMESTAMP[i]
);
}
for i in 0..PLANT_COUNT {
log::info!(
"CONSECUTIVE_WATERING_PLANT[{}] = {}",
i, CONSECUTIVE_WATERING_PLANT[i]
i,
CONSECUTIVE_WATERING_PLANT[i]
);
}
}
}
}
pub(crate) fn mqtt(&mut self, network_config: &NetworkConfig) -> anyhow::Result<()> {
pub(crate) async fn mqtt(&mut self, network_config: &NetworkConfig) -> anyhow::Result<()> {
let base_topic = network_config
.base_topic
.as_ref()
@@ -491,7 +507,9 @@ impl Esp<'_> {
log::info!("Mqtt connection callback received, progressing");
match mqtt_connected_event_ok.load(std::sync::atomic::Ordering::Relaxed) {
true => {
log::info!("Mqtt did callback as connected, testing with roundtrip now");
log::info!(
"Mqtt did callback as connected, testing with roundtrip now"
);
//subscribe to roundtrip
client.subscribe(round_trip_topic.as_str(), ExactlyOnce)?;
client.subscribe(stay_alive_topic.as_str(), ExactlyOnce)?;
@@ -534,7 +552,11 @@ impl Esp<'_> {
}
bail!("Mqtt did not fire connection callback in time");
}
pub(crate) fn mqtt_publish(&mut self, subtopic: &str, message: &[u8]) -> anyhow::Result<()> {
pub(crate) async fn mqtt_publish(
&mut self,
subtopic: &str,
message: &[u8],
) -> anyhow::Result<()> {
if self.mqtt_client.is_none() {
return anyhow::Ok(());
}

View File

@@ -4,9 +4,10 @@ mod initial_hal;
mod rtc;
mod v3_hal;
mod v4_hal;
mod water;
mod v4_sensor;
mod water;
use crate::alloc::string::ToString;
use crate::hal::rtc::{DS3231Module, RTCModuleInteraction};
use crate::hal::water::TankSensor;
use crate::{
@@ -19,11 +20,16 @@ use crate::{
};
use alloc::boxed::Box;
use anyhow::{Ok, Result};
use async_trait::async_trait;
use battery::BQ34Z100G1;
use bq34z100::Bq34z100g1Driver;
use ds323x::{DateTimeAccess, Ds323x};
use eeprom24x::{Eeprom24x, SlaveAddr, Storage};
use embassy_sync::blocking_mutex::raw::{CriticalSectionRawMutex, NoopRawMutex};
use embassy_sync::mutex::Mutex;
use embassy_sync::{LazyLock, Mutex};
use embedded_hal_bus::i2c::MutexDevice;
use esp_idf_hal::can::CAN;
use esp_idf_hal::pcnt::PCNT1;
use esp_idf_hal::{
adc::ADC1,
@@ -46,9 +52,6 @@ use esp_idf_sys::{
};
use esp_ota::mark_app_valid;
use measurements::{Current, Voltage};
use embassy_sync::{Mutex, LazyLock};
use esp_idf_hal::can::CAN;
use crate::alloc::string::ToString;
//Only support for 8 right now!
pub const PLANT_COUNT: usize = 8;
@@ -87,8 +90,9 @@ pub struct HAL<'a> {
pub board_hal: Box<dyn BoardInteraction<'a> + Send>,
}
#[async_trait]
pub trait BoardInteraction<'a> {
fn get_tank_sensor(&mut self) -> Option<&mut TankSensor<'a>>;
fn get_tank_sensor(&mut self) -> Option<&mut TankSensor>;
fn get_esp(&mut self) -> &mut Esp<'a>;
fn get_config(&mut self) -> &PlantControllerConfig;
fn get_battery_monitor(&mut self) -> &mut Box<dyn BatteryInteraction + Send>;
@@ -99,20 +103,20 @@ pub trait BoardInteraction<'a> {
fn is_day(&self) -> bool;
//should be multsampled
fn light(&mut self, enable: bool) -> Result<()>;
fn pump(&mut self, plant: usize, enable: bool) -> Result<()>;
fn pump_current(&mut self, plant: usize) -> Result<Current>;
fn fault(&mut self, plant: usize, enable: bool) -> Result<()>;
fn measure_moisture_hz(&mut self, plant: usize, sensor: Sensor) -> Result<f32>;
fn general_fault(&mut self, enable: bool);
fn test(&mut self) -> Result<()>;
fn set_config(&mut self, config: PlantControllerConfig) -> Result<()>;
fn get_mptt_voltage(&mut self) -> anyhow::Result<Voltage>;
fn get_mptt_current(&mut self) -> anyhow::Result<Current>;
async fn pump(&mut self, plant: usize, enable: bool) -> Result<()>;
async fn pump_current(&mut self, plant: usize) -> Result<Current>;
async fn fault(&mut self, plant: usize, enable: bool) -> Result<()>;
async fn measure_moisture_hz(&mut self, plant: usize, sensor: Sensor) -> Result<f32>;
async fn general_fault(&mut self, enable: bool);
async fn test(&mut self) -> Result<()>;
async fn set_config(&mut self, config: PlantControllerConfig) -> Result<()>;
async fn get_mptt_voltage(&mut self) -> anyhow::Result<Voltage>;
async fn get_mptt_current(&mut self) -> anyhow::Result<Current>;
}
impl dyn BoardInteraction<'_> {
//the counter is just some arbitrary number that increases whenever some progress was made, try to keep the updates < 10 per second for ux reasons
fn _progress(&mut self, counter: u32) {
async fn _progress(&mut self, counter: u32) {
let even = counter % 2 == 0;
let current = counter / (PLANT_COUNT as u32);
for led in 0..PLANT_COUNT {
@@ -177,7 +181,7 @@ impl PlantHal {
Mutex::new(I2cDriver::new(i2c, sda, scl, &config).unwrap())
}
pub fn create() -> Result<Mutex<HAL<'static>>> {
pub fn create() -> Result<Mutex<CriticalSectionRawMutex, HAL<'static>>> {
let peripherals = Peripherals::take()?;
let sys_loop = EspSystemEventLoop::take()?;
let nvs = EspDefaultNvsPartition::take()?;

View File

@@ -1,4 +1,7 @@
use crate::hal::Box;
use alloc::vec::Vec;
use anyhow::{anyhow, bail};
use async_trait::async_trait;
use bincode::config::Configuration;
use bincode::{config, Decode, Encode};
use chrono::{DateTime, Utc};
@@ -7,23 +10,20 @@ use eeprom24x::addr_size::TwoBytes;
use eeprom24x::page_size::B32;
use eeprom24x::unique_serial::No;
use eeprom24x::Storage;
use embedded_hal_bus::i2c::MutexDevice;
use embedded_storage::ReadStorage as embedded_storage_ReadStorage;
use embedded_storage::Storage as embedded_storage_Storage;
use esp_idf_hal::delay::Delay;
use esp_idf_hal::i2c::I2cDriver;
use serde::{Deserialize, Serialize};
use std::result::Result::Ok as OkStd;
const X25: crc::Crc<u16> = crc::Crc::<u16>::new(&crc::CRC_16_IBM_SDLC);
const CONFIG: Configuration = config::standard();
#[async_trait]
pub trait RTCModuleInteraction {
fn get_backup_info(&mut self) -> anyhow::Result<BackupHeader>;
fn get_backup_config(&mut self) -> anyhow::Result<Vec<u8>>;
fn backup_config(&mut self, bytes: &[u8]) -> anyhow::Result<()>;
fn get_rtc_time(&mut self) -> anyhow::Result<DateTime<Utc>>;
fn set_rtc_time(&mut self, time: &DateTime<Utc>) -> anyhow::Result<()>;
async fn get_backup_info(&mut self) -> anyhow::Result<BackupHeader>;
async fn get_backup_config(&mut self) -> anyhow::Result<Vec<u8>>;
async fn backup_config(&mut self, bytes: &[u8]) -> anyhow::Result<()>;
async fn get_rtc_time(&mut self) -> anyhow::Result<DateTime<Utc>>;
async fn set_rtc_time(&mut self, time: &DateTime<Utc>) -> anyhow::Result<()>;
}
const BACKUP_HEADER_MAX_SIZE: usize = 64;
@@ -97,7 +97,8 @@ impl RTCModuleInteraction for DS3231Module<'_> {
let encoded = bincode::encode_into_slice(&header, &mut header_page_buffer, config)?;
log::info!(
"Raw header is {:?} with size {}",
header_page_buffer, encoded
header_page_buffer,
encoded
);
self.storage
.write(0, &header_page_buffer)

View File

@@ -1,3 +1,5 @@
use crate::hal::Sensor;
use crate::log::{log, LogMessage};
use alloc::string::ToString;
use embedded_hal_bus::i2c::MutexDevice;
use esp_idf_hal::can::CanDriver;
@@ -5,13 +7,11 @@ use esp_idf_hal::delay::Delay;
use esp_idf_hal::i2c::I2cDriver;
use esp_idf_hal::pcnt::PcntDriver;
use pca9535::{GPIOBank, Pca9535Immediate, StandardExpanderInterface};
use crate::hal::Sensor;
use crate::log::{log, LogMessage};
const REPEAT_MOIST_MEASURE: usize = 10;
pub trait SensorInteraction {
fn measure_moisture_hz(&mut self, plant: usize, sensor: Sensor) -> anyhow::Result<f32>;
async fn measure_moisture_hz(&mut self, plant: usize, sensor: Sensor) -> anyhow::Result<f32>;
}
const MS0: u8 = 1_u8;
@@ -22,19 +22,23 @@ const MS4: u8 = 2_u8;
const SENSOR_ON: u8 = 5_u8;
pub enum SensorImpl<'a> {
PulseCounter{
PulseCounter {
signal_counter: PcntDriver<'a>,
sensor_expander: Pca9535Immediate<MutexDevice<'a, I2cDriver<'a>>>,
},
CanBus{
can: CanDriver<'a>
}
CanBus {
can: CanDriver<'a>,
},
}
impl SensorInteraction for SensorImpl<'_> {
fn measure_moisture_hz(&mut self, plant: usize, sensor: Sensor) -> anyhow::Result<f32> {
match self {
SensorImpl::PulseCounter { signal_counter, sensor_expander, .. } => {
SensorImpl::PulseCounter {
signal_counter,
sensor_expander,
..
} => {
let mut results = [0_f32; REPEAT_MOIST_MEASURE];
for repeat in 0..REPEAT_MOIST_MEASURE {
signal_counter.counter_pause()?;
@@ -71,8 +75,7 @@ impl SensorInteraction for SensorImpl<'_> {
}
sensor_expander.pin_set_low(GPIOBank::Bank0, MS4)?;
sensor_expander
.pin_set_high(GPIOBank::Bank0, SENSOR_ON)?;
sensor_expander.pin_set_high(GPIOBank::Bank0, SENSOR_ON)?;
let delay = Delay::new_default();
let measurement = 100; // TODO what is this scaling factor? what is its purpose?
@@ -84,8 +87,7 @@ impl SensorInteraction for SensorImpl<'_> {
delay.delay_ms(measurement);
signal_counter.counter_pause()?;
sensor_expander.pin_set_high(GPIOBank::Bank0, MS4)?;
sensor_expander
.pin_set_low(GPIOBank::Bank0, SENSOR_ON)?;
sensor_expander.pin_set_low(GPIOBank::Bank0, SENSOR_ON)?;
sensor_expander.pin_set_low(GPIOBank::Bank0, MS0)?;
sensor_expander.pin_set_low(GPIOBank::Bank0, MS1)?;
sensor_expander.pin_set_low(GPIOBank::Bank0, MS2)?;

View File

@@ -102,7 +102,7 @@ impl<'a> TankSensor<'a> {
self.get_flow_meter_value()
}
pub fn water_temperature_c(&mut self) -> anyhow::Result<f32> {
pub async fn water_temperature_c(&mut self) -> anyhow::Result<f32> {
//multisample should be moved to water_temperature_c
let mut attempt = 1;
let water_temp: Result<f32, anyhow::Error> = loop {
@@ -124,7 +124,7 @@ impl<'a> TankSensor<'a> {
water_temp
}
fn single_temperature_c(&mut self) -> anyhow::Result<f32> {
async fn single_temperature_c(&mut self) -> anyhow::Result<f32> {
self.one_wire_bus
.reset(&mut self.delay)
.map_err(|err| -> anyhow::Error { anyhow!("Missing attribute: {:?}", err) })?;
@@ -152,7 +152,7 @@ impl<'a> TankSensor<'a> {
anyhow::Ok(sensor_data.temperature / 10_f32)
}
pub fn tank_sensor_voltage(&mut self) -> anyhow::Result<f32> {
pub async fn tank_sensor_voltage(&mut self) -> anyhow::Result<f32> {
self.tank_power.set_high()?;
//let stabilize
self.delay.delay_ms(100);