started cleanup and moving from std to no_std

This commit is contained in:
2025-09-11 22:47:11 +02:00
parent f853b6f2b2
commit 242e748ca0
15 changed files with 199 additions and 197 deletions

View File

@@ -158,56 +158,56 @@ impl BatteryInteraction for BQ34Z100G1<'_> {
pub fn print_battery_bq34z100(
battery_driver: &mut Bq34z100g1Driver<MutexDevice<I2cDriver<'_>>, Delay>,
) -> anyhow::Result<(), Bq34Z100Error<I2cError>> {
println!("Try communicating with battery");
log::info!("Try communicating with battery");
let fwversion = battery_driver.fw_version().unwrap_or_else(|e| {
println!("Firmware {:?}", e);
log::info!("Firmware {:?}", e);
0
});
println!("fw version is {}", fwversion);
log::info!("fw version is {}", fwversion);
let design_capacity = battery_driver.design_capacity().unwrap_or_else(|e| {
println!("Design capacity {:?}", e);
log::info!("Design capacity {:?}", e);
0
});
println!("Design Capacity {}", design_capacity);
log::info!("Design Capacity {}", design_capacity);
if design_capacity == 1000 {
println!("Still stock configuring battery, readouts are likely to be wrong!");
log::info!("Still stock configuring battery, readouts are likely to be wrong!");
}
let flags = battery_driver.get_flags_decoded()?;
println!("Flags {:?}", flags);
log::info!("Flags {:?}", flags);
let chem_id = battery_driver.chem_id().unwrap_or_else(|e| {
println!("Chemid {:?}", e);
log::info!("Chemid {:?}", e);
0
});
let bat_temp = battery_driver.internal_temperature().unwrap_or_else(|e| {
println!("Bat Temp {:?}", e);
log::info!("Bat Temp {:?}", e);
0
});
let temp_c = Temperature::from_kelvin(bat_temp as f64 / 10_f64).as_celsius();
let voltage = battery_driver.voltage().unwrap_or_else(|e| {
println!("Bat volt {:?}", e);
log::info!("Bat volt {:?}", e);
0
});
let current = battery_driver.current().unwrap_or_else(|e| {
println!("Bat current {:?}", e);
log::info!("Bat current {:?}", e);
0
});
let state = battery_driver.state_of_charge().unwrap_or_else(|e| {
println!("Bat Soc {:?}", e);
log::info!("Bat Soc {:?}", e);
0
});
let charge_voltage = battery_driver.charge_voltage().unwrap_or_else(|e| {
println!("Bat Charge Volt {:?}", e);
log::info!("Bat Charge Volt {:?}", e);
0
});
let charge_current = battery_driver.charge_current().unwrap_or_else(|e| {
println!("Bat Charge Current {:?}", e);
log::info!("Bat Charge Current {:?}", e);
0
});
println!("ChemId: {} Current voltage {} and current {} with charge {}% and temp {} CVolt: {} CCur {}", chem_id, voltage, current, state, temp_c, charge_voltage, charge_current);
log::info!("ChemId: {} Current voltage {} and current {} with charge {}% and temp {} CVolt: {} CCur {}", chem_id, voltage, current, state, temp_c, charge_voltage, charge_current);
let _ = battery_driver.unsealed();
let _ = battery_driver.it_enable();
anyhow::Result::Ok(())

View File

@@ -4,30 +4,9 @@ use crate::log::{log, LogMessage};
use crate::STAY_ALIVE;
use anyhow::{anyhow, bail, Context};
use chrono::{DateTime, Utc};
use embedded_svc::ipv4::IpInfo;
use embedded_svc::mqtt::client::QoS::{AtLeastOnce, ExactlyOnce};
use embedded_svc::wifi::{
AccessPointConfiguration, AccessPointInfo, AuthMethod, ClientConfiguration, Configuration,
};
use esp_idf_hal::delay::Delay;
use esp_idf_hal::gpio::{Level, PinDriver};
use esp_idf_svc::mqtt::client::{EspMqttClient, LwtConfiguration, MqttClientConfiguration};
use esp_idf_svc::sntp;
use esp_idf_svc::sntp::SyncStatus;
use esp_idf_svc::systime::EspSystemTime;
use esp_idf_svc::wifi::config::{ScanConfig, ScanType};
use esp_idf_svc::wifi::EspWifi;
use esp_idf_sys::{esp_spiffs_info, vTaskDelay};
use serde::Serialize;
use std::ffi::CString;
use std::fs;
use std::fs::File;
use std::path::Path;
use std::result::Result::Ok as OkStd;
use std::str::FromStr;
use std::sync::atomic::AtomicBool;
use std::sync::Arc;
use std::time::Duration;
use alloc::{vec::Vec, string::String};
#[link_section = ".rtc.data"]
static mut LAST_WATERING_TIMESTAMP: [i64; PLANT_COUNT] = [0; PLANT_COUNT];
@@ -212,7 +191,7 @@ impl Esp<'_> {
bail!("Did not manage wifi connection within timeout");
}
}
println!("Should be connected now, waiting for link to be up");
log::info!("Should be connected now, waiting for link to be up");
while !self.wifi_driver.is_up()? {
delay.delay_ms(250);
@@ -237,23 +216,26 @@ impl Esp<'_> {
pub(crate) fn save_config(&mut self, config: &PlantControllerConfig) -> anyhow::Result<()> {
let mut cfg = File::create(Self::CONFIG_FILE)?;
serde_json::to_writer(&mut cfg, &config)?;
println!("Wrote config config {:?}", config);
log::info!("Wrote config config {:?}", config);
anyhow::Ok(())
}
pub(crate) fn mount_file_system(&mut self) -> anyhow::Result<()> {
log(LogMessage::MountingFilesystem, 0, 0, "", "");
let base_path = CString::new("/spiffs")?;
let storage = CString::new(Self::SPIFFS_PARTITION_NAME)?;
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,
};
let base_path = String::try_from("/spiffs")?;
let storage = String::try_from(Self::SPIFFS_PARTITION_NAME)?;
let conf = todo!();
unsafe {
esp_idf_sys::esp!(esp_idf_sys::esp_vfs_spiffs_register(&conf))?;
}
//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,
//};
//TODO
//unsafe {
//esp_idf_sys::esp!(esp_idf_sys::esp_vfs_spiffs_register(&conf))?;
//}
let free_space = self.file_system_size()?;
log(
@@ -377,13 +359,13 @@ impl Esp<'_> {
"",
);
for i in 0..PLANT_COUNT {
println!(
log::info!(
"LAST_WATERING_TIMESTAMP[{}] = UTC {}",
i, LAST_WATERING_TIMESTAMP[i]
);
}
for i in 0..PLANT_COUNT {
println!(
log::info!(
"CONSECUTIVE_WATERING_PLANT[{}] = {}",
i, CONSECUTIVE_WATERING_PLANT[i]
);
@@ -468,35 +450,35 @@ impl Esp<'_> {
mqtt_connected_event_received_copy
.store(true, std::sync::atomic::Ordering::Relaxed);
mqtt_connected_event_ok_copy.store(true, std::sync::atomic::Ordering::Relaxed);
println!("Mqtt connected");
log::info!("Mqtt connected");
}
esp_idf_svc::mqtt::client::EventPayload::Disconnected => {
mqtt_connected_event_received_copy
.store(true, std::sync::atomic::Ordering::Relaxed);
mqtt_connected_event_ok_copy.store(false, std::sync::atomic::Ordering::Relaxed);
println!("Mqtt disconnected");
log::info!("Mqtt disconnected");
}
esp_idf_svc::mqtt::client::EventPayload::Error(esp_error) => {
println!("EspMqttError reported {:?}", esp_error);
log::info!("EspMqttError reported {:?}", esp_error);
mqtt_connected_event_received_copy
.store(true, std::sync::atomic::Ordering::Relaxed);
mqtt_connected_event_ok_copy.store(false, std::sync::atomic::Ordering::Relaxed);
println!("Mqtt error");
log::info!("Mqtt error");
}
esp_idf_svc::mqtt::client::EventPayload::BeforeConnect => {
println!("Mqtt before connect")
log::info!("Mqtt before connect")
}
esp_idf_svc::mqtt::client::EventPayload::Subscribed(_) => {
println!("Mqtt subscribed")
log::info!("Mqtt subscribed")
}
esp_idf_svc::mqtt::client::EventPayload::Unsubscribed(_) => {
println!("Mqtt unsubscribed")
log::info!("Mqtt unsubscribed")
}
esp_idf_svc::mqtt::client::EventPayload::Published(_) => {
println!("Mqtt published")
log::info!("Mqtt published")
}
esp_idf_svc::mqtt::client::EventPayload::Deleted(_) => {
println!("Mqtt deleted")
log::info!("Mqtt deleted")
}
}
})?;
@@ -506,10 +488,10 @@ impl Esp<'_> {
wait_for_connections_event += 1;
match mqtt_connected_event_received.load(std::sync::atomic::Ordering::Relaxed) {
true => {
println!("Mqtt connection callback received, progressing");
log::info!("Mqtt connection callback received, progressing");
match mqtt_connected_event_ok.load(std::sync::atomic::Ordering::Relaxed) {
true => {
println!("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)?;
@@ -526,7 +508,7 @@ impl Esp<'_> {
wait_for_roundtrip += 1;
match round_trip_ok.load(std::sync::atomic::Ordering::Relaxed) {
true => {
println!("Round trip registered, proceeding");
log::info!("Round trip registered, proceeding");
self.mqtt_client = Some(MqttClient {
mqtt_client: client,
base_topic: base_topic_copy,
@@ -557,21 +539,21 @@ impl Esp<'_> {
return anyhow::Ok(());
}
if !subtopic.starts_with("/") {
println!("Subtopic without / at start {}", subtopic);
log::info!("Subtopic without / at start {}", subtopic);
bail!("Subtopic without / at start {}", subtopic);
}
if subtopic.len() > 192 {
println!("Subtopic exceeds 192 chars {}", subtopic);
log::info!("Subtopic exceeds 192 chars {}", subtopic);
bail!("Subtopic exceeds 192 chars {}", subtopic);
}
let client = self.mqtt_client.as_mut().unwrap();
let mut full_topic: heapless::String<256> = heapless::String::new();
if full_topic.push_str(client.base_topic.as_str()).is_err() {
println!("Some error assembling full_topic 1");
log::info!("Some error assembling full_topic 1");
bail!("Some error assembling full_topic 1")
};
if full_topic.push_str(subtopic).is_err() {
println!("Some error assembling full_topic 2");
log::info!("Some error assembling full_topic 2");
bail!("Some error assembling full_topic 2")
};
let publish = client
@@ -580,7 +562,7 @@ impl Esp<'_> {
Delay::new(10).delay_ms(50);
match publish {
OkStd(message_id) => {
println!(
log::info!(
"Published mqtt topic {} with message {:#?} msgid is {:?}",
full_topic,
String::from_utf8_lossy(message),
@@ -589,7 +571,7 @@ impl Esp<'_> {
anyhow::Ok(())
}
Err(err) => {
println!(
log::info!(
"Error during mqtt send on topic {} with message {:#?} error is {:?}",
full_topic,
String::from_utf8_lossy(message),

View File

@@ -9,9 +9,8 @@ use crate::{
use anyhow::{bail, Result};
use chrono::{DateTime, Utc};
use embedded_hal::digital::OutputPin;
use esp_idf_hal::gpio::{IOPin, Pull};
use esp_idf_hal::gpio::{InputOutput, PinDriver};
use measurements::{Current, Voltage};
use crate::alloc::boxed::Box;
pub struct Initial<'a> {
pub(crate) general_fault: PinDriver<'a, esp_idf_hal::gpio::AnyIOPin, InputOutput>,
@@ -51,7 +50,7 @@ pub(crate) fn create_initial_board(
config: PlantControllerConfig,
esp: Esp<'static>,
) -> Result<Box<dyn BoardInteraction<'static> + Send>> {
println!("Start initial");
log::info!("Start initial");
let mut general_fault = PinDriver::input_output(free_pins.gpio6.downgrade())?;
general_fault.set_pull(Pull::Floating)?;
general_fault.set_low()?;

View File

@@ -266,10 +266,10 @@ impl PlantHal {
let config = esp.load_config();
println!("Init rtc driver");
log::info!("Init rtc driver");
let mut rtc = Ds323x::new_ds3231(MutexDevice::new(&I2C_DRIVER));
println!("Init rtc eeprom driver");
log::info!("Init rtc eeprom driver");
let eeprom = {
Eeprom24x::new_24x32(
MutexDevice::new(&I2C_DRIVER),
@@ -279,10 +279,10 @@ impl PlantHal {
let rtc_time = rtc.datetime();
match rtc_time {
OkStd(tt) => {
println!("Rtc Module reports time at UTC {}", tt);
log::info!("Rtc Module reports time at UTC {}", tt);
}
Err(err) => {
println!("Rtc Module could not be read {:?}", err);
log::info!("Rtc Module could not be read {:?}", err);
}
}

View File

@@ -52,7 +52,7 @@ impl RTCModuleInteraction for DS3231Module<'_> {
let (header, len): (BackupHeader, usize) =
bincode::decode_from_slice(&header_page_buffer[..], CONFIG)?;
println!("Raw header is {:?} with size {}", header_page_buffer, len);
log::info!("Raw header is {:?} with size {}", header_page_buffer, len);
anyhow::Ok(header)
}
@@ -95,7 +95,7 @@ impl RTCModuleInteraction for DS3231Module<'_> {
};
let config = config::standard();
let encoded = bincode::encode_into_slice(&header, &mut header_page_buffer, config)?;
println!(
log::info!(
"Raw header is {:?} with size {}",
header_page_buffer, encoded
);

View File

@@ -94,7 +94,7 @@ pub(crate) fn create_v3(
battery_monitor: Box<dyn BatteryInteraction + Send>,
rtc_module: Box<dyn RTCModuleInteraction + Send>,
) -> Result<Box<dyn BoardInteraction<'static> + Send>> {
println!("Start v3");
log::info!("Start v3");
let mut clock = PinDriver::input_output(peripherals.gpio15.downgrade())?;
clock.set_pull(Pull::Floating)?;
let mut latch = PinDriver::input_output(peripherals.gpio3.downgrade())?;

View File

@@ -52,7 +52,7 @@ impl Charger<'_> {
operating_mode: OperatingMode::PowerDown,
})
.map_err(|e| {
println!(
log::info!(
"Error setting ina mppt configuration during deep sleep preparation{:?}",
e
);
@@ -133,7 +133,7 @@ pub(crate) fn create_v4(
battery_monitor: Box<dyn BatteryInteraction + Send>,
rtc_module: Box<dyn RTCModuleInteraction + Send>,
) -> anyhow::Result<Box<dyn BoardInteraction<'static> + Send + 'static>> {
println!("Start v4");
log::info!("Start v4");
let mut awake = PinDriver::output(peripherals.gpio21.downgrade())?;
awake.set_high()?;
@@ -163,7 +163,7 @@ pub(crate) fn create_v4(
let mut sensor_expander = Pca9535Immediate::new(MutexDevice::new(&I2C_DRIVER), 34);
let sensor = match sensor_expander.pin_into_output(GPIOBank::Bank0, 0) {
Ok(_) => {
println!("SensorExpander answered");
log::info!("SensorExpander answered");
//pulse counter version
let mut signal_counter = PcntDriver::new(
peripherals.pcnt0,
@@ -200,7 +200,7 @@ pub(crate) fn create_v4(
}
}
Err(_) => {
println!("Can bus mode ");
log::info!("Can bus mode ");
let timing = can::config::Timing::B25K;
let config = can::config::Config::new().timing(timing);
let can = can::CanDriver::new(peripherals.can, peripherals.gpio0, peripherals.gpio2, &config).unwrap();
@@ -211,7 +211,7 @@ pub(crate) fn create_v4(
can.transmit(&tx_frame, 1000).unwrap();
if let Ok(rx_frame) = can.receive(1000) {
println!("rx {:}:", rx_frame);
log::info!("rx {:}:", rx_frame);
}
//can bus version
SensorImpl::CanBus {
@@ -274,7 +274,7 @@ pub(crate) fn create_v4(
) {
Ok(pump_ina) => Some(pump_ina),
Err(err) => {
println!("Error creating pump ina: {:?}", err);
log::info!("Error creating pump ina: {:?}", err);
None
}
};

View File

@@ -109,11 +109,11 @@ impl<'a> TankSensor<'a> {
let temp = self.single_temperature_c();
match &temp {
Ok(res) => {
println!("Water temp is {}", res);
log::info!("Water temp is {}", res);
break temp;
}
Err(err) => {
println!("Could not get water temp {} attempt {}", err, attempt)
log::info!("Could not get water temp {} attempt {}", err, attempt)
}
}
if attempt == 5 {