Improve error handling, ensure robust defaults, and eliminate unsafe unwraps/expectations across modules.

This commit is contained in:
2026-04-06 15:26:52 +02:00
parent 4d4fcbe33b
commit 0ad7a58219
13 changed files with 186 additions and 87 deletions

View File

@@ -314,17 +314,19 @@ impl Esp<'_> {
&mut tx_meta,
&mut tx_buffer,
);
socket.bind(123).unwrap();
socket.bind(123).context("Could not bind UDP socket")?;
let context = NtpContext::new(Timestamp::default());
let ntp_addrs = stack
.dns_query(NTP_SERVER, DnsQueryType::A)
.await;
if ntp_addrs.is_err() {
bail!("Failed to resolve DNS");
.await
.context("Failed to resolve DNS")?;
if ntp_addrs.is_empty() {
bail!("No IP addresses found for NTP server");
}
let ntp = ntp_addrs.unwrap()[0];
let ntp = ntp_addrs[0];
info!("NTP server: {ntp:?}");
let mut counter = 0;
@@ -416,9 +418,14 @@ impl Esp<'_> {
Err(_) => "PlantCtrl Emergency Mode".to_string(),
};
let device = self.interface_ap.take().unwrap();
let device = self
.interface_ap
.take()
.context("AP interface already taken")?;
let gw_ip_addr_str = "192.168.71.1";
let gw_ip_addr = Ipv4Addr::from_str(gw_ip_addr_str).expect("failed to parse gateway ip");
let gw_ip_addr = Ipv4Addr::from_str(gw_ip_addr_str).map_err(|_| FatError::String {
error: "failed to parse gateway ip".to_string(),
})?;
let config = embassy_net::Config::ipv4_static(StaticConfigV4 {
address: Ipv4Cidr::new(gw_ip_addr, 24),
@@ -472,18 +479,17 @@ impl Esp<'_> {
spawner: Spawner,
) -> FatResult<Stack<'static>> {
esp_radio::wifi_set_log_verbose();
let ssid = network_config.ssid.clone();
match &ssid {
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")
}
}
let ssid = ssid.unwrap().to_string();
};
info!("attempting to connect wifi {ssid}");
let password = match network_config.password {
Some(ref password) => password.to_string(),
@@ -491,7 +497,10 @@ impl Esp<'_> {
};
let max_wait = network_config.max_wait;
let device = self.interface_sta.take().unwrap();
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;
@@ -596,9 +605,9 @@ impl Esp<'_> {
if let Ok(cur) = self.ota.current_ota_state() {
if cur == OtaImageState::PendingVerify {
info!("Marking OTA image as valid");
self.ota
.set_current_ota_state(Valid)
.expect("Could not set image to valid");
if let Err(err) = self.ota.set_current_ota_state(Valid) {
error!("Could not set image to valid: {:?}", err);
}
}
} else {
info!("No OTA image to mark as valid");
@@ -753,10 +762,7 @@ impl Esp<'_> {
network_config.mqtt_user.as_ref(),
network_config.mqtt_password.as_ref(),
) {
builder = builder.with_authentication(
mqtt_user,
mqtt_password,
);
builder = builder.with_authentication(mqtt_user, mqtt_password);
info!("With authentification");
}
@@ -808,11 +814,10 @@ impl Esp<'_> {
Timer::after(Duration::from_millis(100)).await;
}
Topic::General(round_trip_topic.clone())
let _ = Topic::General(round_trip_topic.clone())
.with_display("online_text")
.publish()
.await
.unwrap();
.await;
let timeout = {
let guard = TIME_ACCESS.get().await.lock().await;
@@ -974,7 +979,13 @@ async fn run_dhcp(stack: Stack<'static>, gw_ip_addr: &'static str) {
use edge_nal::UdpBind;
use edge_nal_embassy::{Udp, UdpBuffers};
let ip = Ipv4Addr::from_str(gw_ip_addr).expect("dhcp task failed to parse gw ip");
let ip = match Ipv4Addr::from_str(gw_ip_addr) {
Ok(ip) => ip,
Err(_) => {
error!("dhcp task failed to parse gw ip");
return;
}
};
let mut buf = [0u8; 1500];
@@ -982,13 +993,19 @@ async fn run_dhcp(stack: Stack<'static>, gw_ip_addr: &'static str) {
let buffers = UdpBuffers::<3, 1024, 1024, 10>::new();
let unbound_socket = Udp::new(stack, &buffers);
let mut bound_socket = unbound_socket
let mut bound_socket = match unbound_socket
.bind(SocketAddr::V4(SocketAddrV4::new(
Ipv4Addr::UNSPECIFIED,
DEFAULT_SERVER_PORT,
)))
.await
.unwrap();
{
Ok(s) => s,
Err(e) => {
error!("dhcp task failed to bind socket: {:?}", e);
return;
}
};
loop {
_ = io::server::run(

View File

@@ -150,7 +150,6 @@ pub trait BoardInteraction<'a> {
async fn set_charge_indicator(&mut self, charging: bool) -> Result<(), FatError>;
async fn deep_sleep(&mut self, duration_in_ms: u64) -> !;
fn is_day(&self) -> bool;
//should be multsampled
async fn light(&mut self, enable: bool) -> FatResult<()>;
@@ -165,7 +164,7 @@ pub trait BoardInteraction<'a> {
async fn get_mptt_current(&mut self) -> FatResult<Current>;
async fn can_power(&mut self, state: bool) -> FatResult<()>;
async fn backup_config(&mut self, config: &PlantControllerConfig) -> FatResult<()>;
async fn backup_config(&mut self, config: &PlantControllerConfig) -> FatResult<()>;
async fn read_backup(&mut self) -> FatResult<PlantControllerConfig>;
async fn backup_info(&mut self) -> FatResult<BackupHeader>;
@@ -271,12 +270,17 @@ impl PlantHal {
let rng = Rng::new();
let esp_wifi_ctrl = &*mk_static!(
Controller<'static>,
init().expect("Could not init wifi controller")
init().map_err(|e| FatError::String {
error: format!("Could not init wifi controller: {:?}", e)
})?
);
let (controller, interfaces) =
esp_radio::wifi::new(esp_wifi_ctrl, peripherals.WIFI, Default::default())
.expect("Could not init wifi");
esp_radio::wifi::new(esp_wifi_ctrl, peripherals.WIFI, Default::default()).map_err(
|e| FatError::String {
error: format!("Could not init wifi: {:?}", e),
},
)?;
let pcnt_module = Pcnt::new(peripherals.PCNT);
@@ -330,7 +334,7 @@ impl PlantHal {
pt.find_partition(esp_bootloader_esp_idf::partitions::PartitionType::Data(
DataPartitionSubType::Ota,
))?
.expect("No OTA data partition found")
.context("No OTA data partition found")?
);
let ota_data = mk_static!(
@@ -375,7 +379,7 @@ impl PlantHal {
.find_partition(esp_bootloader_esp_idf::partitions::PartitionType::Data(
DataPartitionSubType::LittleFs,
))?
.expect("Data partition with littlefs not found");
.context("Data partition with littlefs not found")?;
let data_partition = mk_static!(PartitionEntry, data_partition);
let data = mk_static!(
@@ -399,7 +403,8 @@ impl PlantHal {
#[allow(clippy::arc_with_non_send_sync)]
let fs = Arc::new(Mutex::new(
lfs2Filesystem::mount(alloc, lfs2filesystem).expect("Could not mount lfs2 filesystem"),
lfs2Filesystem::mount(alloc, lfs2filesystem)
.context("Could not mount lfs2 filesystem")?,
));
let uart0 =
@@ -493,7 +498,9 @@ impl PlantHal {
RefCell<I2c<Blocking>>,
> = CriticalSectionMutex::new(RefCell::new(i2c));
I2C_DRIVER.init(i2c_bus).expect("Could not init i2c driver");
I2C_DRIVER.init(i2c_bus).map_err(|_| FatError::String {
error: "Could not init i2c driver".to_string(),
})?;
let i2c_bus = I2C_DRIVER.get().await;
let rtc_device = I2cDevice::new(i2c_bus);
@@ -655,7 +662,7 @@ pub fn next_partition(current: AppPartitionSubType) -> FatResult<AppPartitionSub
pub async fn esp_time() -> DateTime<Utc> {
let guard = TIME_ACCESS.get().await.lock().await;
DateTime::from_timestamp_micros(guard.current_time_us() as i64).unwrap()
DateTime::from_timestamp_micros(guard.current_time_us() as i64).unwrap_or(DateTime::UNIX_EPOCH)
}
pub async fn esp_set_time(time: DateTime<FixedOffset>) -> FatResult<()> {

View File

@@ -31,6 +31,7 @@ use ina219::SyncIna219;
use log::{error, info, warn};
use measurements::Resistance;
use measurements::{Current, Voltage};
// use no_panic::no_panic;
use pca9535::{GPIOBank, Pca9535Immediate, StandardExpanderInterface};
pub const BACKUP_HEADER_MAX_SIZE: usize = 64;
@@ -368,7 +369,7 @@ impl<'a> BoardInteraction<'a> for V4<'a> {
async fn measure_moisture_hz(&mut self) -> FatResult<Moistures> {
self.can_power.set_high();
Timer::after_millis(500).await;
let config = self.twai_config.take().expect("twai config not set");
let config = self.twai_config.take().context("twai config not set")?;
let mut twai = config.into_async().start();
if twai.is_bus_off() {
@@ -398,7 +399,7 @@ impl<'a> BoardInteraction<'a> for V4<'a> {
async fn detect_sensors(&mut self, request: Detection) -> FatResult<Detection> {
self.can_power.set_high();
Timer::after_millis(500).await;
let config = self.twai_config.take().expect("twai config not set");
let config = self.twai_config.take().context("twai config not set")?;
let mut twai = config.into_async().start();
if twai.is_bus_off() {
@@ -542,8 +543,8 @@ impl<'a> BoardInteraction<'a> for V4<'a> {
}
Ok(())
}
async fn backup_config(&mut self, controller_config: &PlantControllerConfig) -> FatResult<()>{
let mut buffer: [u8; 4096-BACKUP_HEADER_MAX_SIZE] = [0; 4096-BACKUP_HEADER_MAX_SIZE];
async fn backup_config(&mut self, controller_config: &PlantControllerConfig) -> FatResult<()> {
let mut buffer: [u8; 4096 - BACKUP_HEADER_MAX_SIZE] = [0; 4096 - BACKUP_HEADER_MAX_SIZE];
let length = bincode::encode_into_slice(controller_config, &mut buffer, CONFIG)?;
let mut checksum = X25.digest();
checksum.update(&buffer[..length]);
@@ -562,7 +563,7 @@ impl<'a> BoardInteraction<'a> for V4<'a> {
while to_write > 0 {
self.progress(chunk as u32).await;
let start = BACKUP_HEADER_MAX_SIZE + chunk* EEPROM_PAGE;
let start = BACKUP_HEADER_MAX_SIZE + chunk * EEPROM_PAGE;
let end = start + crate::hal::rtc::EEPROM_PAGE;
let part = &buffer[start..end];
to_write -= part.len();
@@ -576,7 +577,8 @@ impl<'a> BoardInteraction<'a> for V4<'a> {
async fn read_backup(&mut self) -> FatResult<PlantControllerConfig> {
let info = self.backup_info().await?;
let mut store = alloc::vec![0_u8; info.size as usize];
self.rtc_module.read(BACKUP_HEADER_MAX_SIZE as u32, store.as_mut_slice())?;
self.rtc_module
.read(BACKUP_HEADER_MAX_SIZE as u32, store.as_mut_slice())?;
let mut checksum = X25.digest();
checksum.update(&store[..]);
let crc = checksum.finalize();
@@ -593,7 +595,10 @@ impl<'a> BoardInteraction<'a> for V4<'a> {
let info: Result<(BackupHeader, usize), bincode::error::DecodeError> =
bincode::decode_from_slice(&header_page_buffer[..], CONFIG);
info.map(|(header, _)| header).map_err(|e| FatError::String {error:"Could not read backup header: ".to_string() + &e.to_string()})
info.map(|(header, _)| header)
.map_err(|e| FatError::String {
error: "Could not read backup header: ".to_string() + &e.to_string(),
})
}
}
@@ -654,8 +659,6 @@ async fn wait_for_can_measurements(
}
}
}
}
impl From<Moistures> for Detection {

View File

@@ -33,7 +33,8 @@ impl<'a> TankSensor<'a> {
one_wire_pin.apply_output_config(&OutputConfig::default().with_pull(Pull::None));
let mut adc1_config = AdcConfig::new();
let tank_pin = adc1_config.enable_pin_with_cal::<_, AdcCalLine<_>>(gpio5, Attenuation::_11dB);
let tank_pin =
adc1_config.enable_pin_with_cal::<_, AdcCalLine<_>>(gpio5, Attenuation::_11dB);
let tank_channel = Adc::new(adc1, adc1_config);
let one_wire_bus = OneWire::new(one_wire_pin, false);
@@ -141,12 +142,17 @@ impl<'a> TankSensor<'a> {
let value = self.tank_channel.read_oneshot(&mut self.tank_pin);
//force yield
Timer::after_millis(10).await;
*sample = value.unwrap();
match value {
Ok(v) => *sample = v,
Err(e) => {
bail!("ADC Hardware error: {:?}", e);
}
};
}
self.tank_power.set_low();
store.sort();
let median_mv = store[TANK_MULTI_SAMPLE / 2] as f32;
Ok(median_mv/1000.0)
Ok(median_mv / 1000.0)
}
}