adjust rust code to new config file, fix bq34z100 flasher

This commit is contained in:
2024-12-16 02:15:03 +01:00
parent c89a617d9d
commit 74f9c17461
4 changed files with 267 additions and 220 deletions

View File

@@ -2,7 +2,6 @@ use bq34z100::{Bq34Z100Error, Bq34z100g1, Bq34z100g1Driver};
use ds323x::{DateTimeAccess, Ds323x};
use eeprom24x::page_size::No;
use eeprom24x::{Eeprom24x, SlaveAddr};
use embedded_hal_bus::i2c::MutexDevice;
use embedded_svc::wifi::{
@@ -14,7 +13,6 @@ use esp_idf_hal::adc::{attenuation, Resolution};
use esp_idf_hal::i2c::{APBTickType, I2cConfig, I2cDriver, I2cError};
use esp_idf_hal::units::FromValueType;
use esp_idf_svc::eventloop::EspSystemEventLoop;
use esp_idf_svc::io::vfs;
use esp_idf_svc::ipv4::IpInfo;
use esp_idf_svc::mqtt::client::QoS::AtLeastOnce;
use esp_idf_svc::mqtt::client::QoS::ExactlyOnce;
@@ -30,8 +28,7 @@ use anyhow::{anyhow, Context};
use anyhow::{bail, Ok, Result};
use serde::Serialize;
use std::ffi::CString;
use std::fs::{self, DirEntry, File};
use std::io::{Read, Write};
use std::fs::{self, File};
use std::path::Path;
use chrono::{DateTime, Utc};
@@ -52,10 +49,10 @@ use esp_idf_hal::prelude::Peripherals;
use esp_idf_hal::reset::ResetReason;
use esp_idf_svc::sntp::{self, SyncStatus};
use esp_idf_svc::systime::EspSystemTime;
use esp_idf_sys::{esp, esp_spiffs_check, f_opendir, gpio_hold_dis, gpio_hold_en, vTaskDelay, EspError};
use esp_idf_sys::{esp, esp_spiffs_check, gpio_hold_dis, gpio_hold_en, vTaskDelay, EspError};
use one_wire_bus::OneWire;
use crate::config::{self, Config};
use crate::config::{self, PlantControllerConfig};
use crate::{plant_hal, STAY_ALIVE};
//Only support for 8 right now!
@@ -171,37 +168,35 @@ pub struct PlantCtrlBoard<'a> {
}
#[derive(Serialize, Debug)]
pub struct FileInfo{
filename:String,
size:usize
pub struct FileInfo {
filename: String,
size: usize,
}
#[derive(Serialize, Debug)]
pub struct FileList{
pub struct FileList {
files: Vec<FileInfo>,
file_system_corrupt: Option<String>,
iter_error: Option<String>,
}
impl PlantCtrlBoard<'_> {
pub fn list_files(&self, filename:&str) -> FileList {
pub fn list_files(&self, filename: &str) -> FileList {
let storage = CString::new(SPIFFS_PARTITION_NAME).unwrap();
let error = unsafe {
esp!{
esp! {
esp_spiffs_check(storage.as_ptr())
}
};
let mut file_system_corrupt = match error {
OkStd(_) => {
None
},
OkStd(_) => None,
Err(err) => {
println!("Corrupt spiffs {err:?}");
Some(format!("{err:?}"))
},
}
};
let mut iter_error = None;
let mut result = Vec::new();
@@ -214,49 +209,53 @@ impl PlantCtrlBoard<'_> {
println!("start loop");
match item {
OkStd(file) => {
let f = FileInfo{
let f = FileInfo {
filename: file.file_name().into_string().unwrap(),
size: file.metadata().and_then(|it| core::result::Result::Ok(it.len())).unwrap_or_default() as usize
size: file
.metadata()
.and_then(|it| core::result::Result::Ok(it.len()))
.unwrap_or_default()
as usize,
};
println!("fileinfo {f:?}");
result.push(f);
},
}
Err(err) => {
iter_error = Some (format!("{err:?}"));
iter_error = Some(format!("{err:?}"));
break;
},
}
}
}
}
},
}
Err(err) => {
file_system_corrupt = Some(format!("{err:?}"));
},
}
}
return FileList{
return FileList {
file_system_corrupt,
files: result,
iter_error
iter_error,
};
}
pub fn delete_file(&self, filename:&str) -> Result<()>{
pub fn delete_file(&self, filename: &str) -> Result<()> {
let filepath = Path::new(BASE_PATH).join(Path::new(filename));
match (fs::remove_file(filepath)){
match fs::remove_file(filepath) {
OkStd(_) => Ok(()),
Err(err) => {
bail!(format!("{err:?}"))
},
}
}
}
pub fn get_file_handle(&self, filename:&str, write:bool) -> Result<File> {
pub fn get_file_handle(&self, filename: &str, write: bool) -> Result<File> {
let filepath = Path::new(BASE_PATH).join(Path::new(filename));
return Ok(if write {
File::create(filepath)?
} else {
File::open(filepath)?
})
});
}
pub fn is_day(&self) -> bool {
@@ -495,7 +494,10 @@ impl PlantCtrlBoard<'_> {
delay.delay_ms(10);
let unscaled = self.signal_counter.get_counter_value()? as i32;
let hz = (unscaled as f32 * factor) as i32;
println!("raw measure unscaled {} hz {}, plant {} sensor {:?}",unscaled, hz, plant, sensor);
println!(
"raw measure unscaled {} hz {}, plant {} sensor {:?}",
unscaled, hz, plant, sensor
);
results[repeat] = hz;
//println!("Measuring {:?} @ {} with {}", sensor, plant, hz);
}
@@ -598,7 +600,7 @@ impl PlantCtrlBoard<'_> {
max_files: 5,
format_if_mount_failed: true,
};
//TODO check fielsystem esp_spiffs_check
unsafe {
@@ -661,13 +663,13 @@ impl PlantCtrlBoard<'_> {
}
}
pub fn get_config(&mut self) -> Result<config::Config> {
pub fn get_config(&mut self) -> Result<config::PlantControllerConfig> {
let cfg = File::open(CONFIG_FILE)?;
let config: Config = serde_json::from_reader(cfg)?;
let config: PlantControllerConfig = serde_json::from_reader(cfg)?;
Ok(config)
}
pub fn set_config(&mut self, config: &Config) -> Result<()> {
pub fn set_config(&mut self, config: &PlantControllerConfig) -> Result<()> {
let mut cfg = File::create(CONFIG_FILE)?;
serde_json::to_writer(&mut cfg, &config)?;
println!("Wrote config config {:?}", config);
@@ -735,9 +737,17 @@ impl PlantCtrlBoard<'_> {
config.exists()
}
pub fn mqtt(&mut self, config: &Config) -> Result<()> {
let base_topic = config.base_topic.as_ref().context("missing base topic")?;
let mqtt_url = config.mqtt_url.as_ref().context("missing mqtt url")?;
pub fn mqtt(&mut self, config: &PlantControllerConfig) -> Result<()> {
let base_topic = config
.network
.base_topic
.as_ref()
.context("missing base topic")?;
let mqtt_url = config
.network
.mqtt_url
.as_ref()
.context("missing mqtt url")?;
let last_will_topic = format!("{}/state", base_topic);
let mqtt_client_config = MqttClientConfiguration {
@@ -865,7 +875,12 @@ impl PlantCtrlBoard<'_> {
bail!("Mqtt did not fire connection callback in time");
}
pub fn mqtt_publish(&mut self, config: &Config, subtopic: &str, message: &[u8]) -> Result<()> {
pub fn mqtt_publish(
&mut self,
config: &PlantControllerConfig,
subtopic: &str,
message: &[u8],
) -> Result<()> {
if self.mqtt_client.is_none() {
return Ok(());
}
@@ -880,7 +895,7 @@ impl PlantCtrlBoard<'_> {
let client = self.mqtt_client.as_mut().unwrap();
let mut full_topic: heapless::String<256> = heapless::String::new();
if full_topic
.push_str(&config.base_topic.as_ref().unwrap())
.push_str(&config.network.base_topic.as_ref().unwrap())
.is_err()
{
println!("Some error assembling full_topic 1");