move to central config, make TZ compile time const, confgureable later!

This commit is contained in:
2024-11-13 22:04:47 +01:00
parent 7957cf4003
commit bfcf5e150c
10 changed files with 591 additions and 838 deletions

View File

@@ -1,14 +1,15 @@
use bq34z100::{Bq34Z100Error, Bq34z100g1, Bq34z100g1Driver};
use chrono_tz::Europe::Berlin;
use ds323x::Ds323x;
use ds323x::{DateTimeAccess, Ds323x};
use eeprom24x::{Eeprom24x, SlaveAddr};
use embedded_hal_bus::i2c::MutexDevice;
use embedded_svc::wifi::{
AccessPointConfiguration, AccessPointInfo, AuthMethod, ClientConfiguration, Configuration,
};
use esp_idf_hal::adc::{attenuation, Resolution};
use esp_idf_hal::adc::oneshot::config::AdcChannelConfig;
use esp_idf_hal::adc::oneshot::{AdcChannelDriver, AdcDriver};
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;
@@ -20,13 +21,13 @@ use esp_idf_svc::nvs::EspDefaultNvsPartition;
use esp_idf_svc::wifi::config::{ScanConfig, ScanType};
use esp_idf_svc::wifi::EspWifi;
use measurements::Temperature;
use once_cell::sync::Lazy;
use plant_ctrl2::sipo::ShiftRegister40;
use anyhow::anyhow;
use anyhow::{anyhow, Context};
use anyhow::{bail, Ok, Result};
use std::ffi::CString;
use std::fs::File;
use std::ops::Deref;
use std::path::Path;
use chrono::{DateTime, Utc};
@@ -47,10 +48,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, gpio_hold_dis, gpio_hold_en, vTaskDelay, EspError};
use esp_idf_sys::{gpio_hold_dis, gpio_hold_en, vTaskDelay, EspError};
use one_wire_bus::OneWire;
use crate::config::{self, Config, WifiConfig};
use crate::config::{self, Config};
use crate::{plant_hal, STAY_ALIVE};
//Only support for 8 right now!
@@ -58,7 +59,6 @@ pub const PLANT_COUNT: usize = 8;
const REPEAT_MOIST_MEASURE: usize = 3;
const SPIFFS_PARTITION_NAME: &str = "storage";
const WIFI_CONFIG_FILE: &str = "/spiffs/wifi.cfg";
const CONFIG_FILE: &str = "/spiffs/config.cfg";
const TANK_MULTI_SAMPLE: usize = 11;
@@ -122,10 +122,9 @@ pub struct FileSystemSizeInfo {
}
#[derive(strum::Display)]
pub enum ClearConfigType {
WifiConfig,
Config,
None,
pub enum StartMode {
AP,
Normal,
}
#[derive(Debug, PartialEq)]
@@ -133,73 +132,6 @@ pub enum Sensor {
A,
B,
}
pub trait PlantCtrlBoardInteraction {
fn time(&mut self) -> Result<chrono::DateTime<Utc>>;
fn wifi(
&mut self,
ssid: heapless::String<32>,
password: Option<heapless::String<64>>,
max_wait: u32,
) -> Result<IpInfo>;
fn sntp(&mut self, max_wait: u32) -> Result<chrono::DateTime<Utc>>;
fn mount_file_system(&mut self) -> Result<()>;
fn file_system_size(&mut self) -> Result<FileSystemSizeInfo>;
fn state_charge_percent(&mut self) -> Result<u8>;
fn remaining_milli_ampere_hour(&mut self) -> Result<u16>;
fn max_milli_ampere_hour(&mut self) -> Result<u16>;
fn design_milli_ampere_hour(&mut self) -> Result<u16>;
fn voltage_milli_volt(&mut self) -> Result<u16>;
fn average_current_milli_ampere(&mut self) -> Result<i16>;
fn cycle_count(&mut self) -> Result<u16>;
fn state_health_percent(&mut self) -> Result<u8>;
fn general_fault(&mut self, enable: bool);
fn is_day(&self) -> bool;
fn water_temperature_c(&mut self) -> Result<f32>;
fn tank_sensor_percent(&mut self) -> Result<u16>;
fn set_low_voltage_in_cycle(&mut self);
fn clear_low_voltage_in_cycle(&mut self);
fn low_voltage_in_cycle(&mut self) -> bool;
fn any_pump(&mut self, enabled: bool) -> Result<()>;
//keep state during deepsleep
fn light(&mut self, enable: bool) -> Result<()>;
fn measure_moisture_hz(&mut self, plant: usize, sensor: Sensor) -> Result<i32>;
fn pump(&self, plant: usize, enable: bool) -> Result<()>;
fn last_pump_time(&self, plant: usize) -> Option<chrono::DateTime<Utc>>;
fn store_last_pump_time(&mut self, plant: usize, time: chrono::DateTime<Utc>);
fn store_consecutive_pump_count(&mut self, plant: usize, count: u32);
fn consecutive_pump_count(&mut self, plant: usize) -> u32;
//keep state during deepsleep
fn fault(&self, plant: usize, enable: bool);
//config
fn is_config_reset(&mut self) -> bool;
fn remove_configs(&mut self) -> Result<ClearConfigType>;
fn get_config(&mut self) -> Result<config::Config>;
fn set_config(&mut self, wifi: &Config) -> Result<()>;
fn get_wifi(&mut self) -> Result<config::WifiConfig>;
fn set_wifi(&mut self, wifi: &WifiConfig) -> Result<()>;
fn wifi_ap(&mut self) -> Result<()>;
fn wifi_scan(&mut self) -> Result<Vec<AccessPointInfo>>;
fn test(&mut self) -> Result<()>;
fn test_pump(&mut self, plant: usize) -> Result<()>;
fn is_wifi_config_file_existant(&mut self) -> bool;
fn mqtt(&mut self, config: &Config) -> Result<()>;
fn mqtt_publish(&mut self, config: &Config, subtopic: &str, message: &[u8]) -> Result<()>;
fn sensor_multiplexer(&mut self, n: u8) -> Result<()>;
fn flash_bq34_z100(&mut self, line: &str, dryrun: bool) -> Result<()>;
}
pub trait CreatePlantHal<'a> {
fn create() -> Result<Mutex<PlantCtrlBoard<'static>>>;
}
pub struct PlantHal {}
@@ -222,16 +154,23 @@ pub struct PlantCtrlBoard<'a> {
pub wifi_driver: EspWifi<'a>,
one_wire_bus: OneWire<PinDriver<'a, Gpio18, esp_idf_hal::gpio::InputOutput>>,
mqtt_client: Option<EspMqttClient<'a>>,
battery_driver: Option<Bq34z100g1Driver<MutexDevice<'a, I2cDriver<'a>>, Delay>>,
rtc: Option<Ds323x<ds323x::interface::I2cInterface<MutexDevice<'a, I2cDriver<'a>>>, ds323x::ic::DS3231>>
battery_driver: Bq34z100g1Driver<MutexDevice<'a, I2cDriver<'a>>, Delay>,
rtc:
Ds323x<ds323x::interface::I2cInterface<MutexDevice<'a, I2cDriver<'a>>>, ds323x::ic::DS3231>,
eeprom: Eeprom24x<
MutexDevice<'a, I2cDriver<'a>>,
eeprom24x::page_size::B32,
eeprom24x::addr_size::TwoBytes,
eeprom24x::unique_serial::No,
>,
}
impl PlantCtrlBoardInteraction for PlantCtrlBoard<'_> {
fn is_day(&self) -> bool {
impl PlantCtrlBoard<'_> {
pub fn is_day(&self) -> bool {
self.solar_is_day.get_level().into()
}
fn water_temperature_c(&mut self) -> Result<f32> {
pub fn water_temperature_c(&mut self) -> Result<f32> {
let mut delay = Delay::new_default();
self.one_wire_bus
@@ -261,7 +200,7 @@ impl PlantCtrlBoardInteraction for PlantCtrlBoard<'_> {
Ok(sensor_data.temperature / 10_f32)
}
fn tank_sensor_percent(&mut self) -> Result<u16> {
pub fn tank_sensor_percent(&mut self) -> Result<u16> {
let delay = Delay::new_default();
self.tank_power.set_high()?;
//let stabilize
@@ -295,26 +234,26 @@ impl PlantCtrlBoardInteraction for PlantCtrlBoard<'_> {
return Ok(percent as u16);
}
fn set_low_voltage_in_cycle(&mut self) {
pub fn set_low_voltage_in_cycle(&mut self) {
unsafe {
LOW_VOLTAGE_DETECTED = true;
}
}
fn clear_low_voltage_in_cycle(&mut self) {
pub fn clear_low_voltage_in_cycle(&mut self) {
unsafe {
LOW_VOLTAGE_DETECTED = false;
}
}
fn light(&mut self, enable: bool) -> Result<()> {
pub fn light(&mut self, enable: bool) -> Result<()> {
unsafe { gpio_hold_dis(self.light.pin()) };
self.light.set_state(enable.into())?;
unsafe { gpio_hold_en(self.light.pin()) };
Ok(())
}
fn pump(&self, plant: usize, enable: bool) -> Result<()> {
pub fn pump(&self, plant: usize, enable: bool) -> Result<()> {
let index = match plant {
0 => PUMP1_BIT,
1 => PUMP2_BIT,
@@ -331,30 +270,30 @@ impl PlantCtrlBoardInteraction for PlantCtrlBoard<'_> {
Ok(())
}
fn last_pump_time(&self, plant: usize) -> Option<chrono::DateTime<Utc>> {
pub fn last_pump_time(&self, plant: usize) -> Option<chrono::DateTime<Utc>> {
let ts = unsafe { LAST_WATERING_TIMESTAMP }[plant];
return Some(DateTime::from_timestamp_millis(ts)?);
}
fn store_last_pump_time(&mut self, plant: usize, time: chrono::DateTime<Utc>) {
pub fn store_last_pump_time(&mut self, plant: usize, time: chrono::DateTime<Utc>) {
unsafe {
LAST_WATERING_TIMESTAMP[plant] = time.timestamp_millis();
}
}
fn store_consecutive_pump_count(&mut self, plant: usize, count: u32) {
pub fn store_consecutive_pump_count(&mut self, plant: usize, count: u32) {
unsafe {
CONSECUTIVE_WATERING_PLANT[plant] = count;
}
}
fn consecutive_pump_count(&mut self, plant: usize) -> u32 {
pub fn consecutive_pump_count(&mut self, plant: usize) -> u32 {
unsafe {
return CONSECUTIVE_WATERING_PLANT[plant];
}
}
fn fault(&self, plant: usize, enable: bool) {
pub fn fault(&self, plant: usize, enable: bool) {
let index = match plant {
0 => FAULT_1,
1 => FAULT_2,
@@ -371,20 +310,20 @@ impl PlantCtrlBoardInteraction for PlantCtrlBoard<'_> {
.unwrap()
}
fn low_voltage_in_cycle(&mut self) -> bool {
pub fn low_voltage_in_cycle(&mut self) -> bool {
unsafe {
return LOW_VOLTAGE_DETECTED;
}
}
fn any_pump(&mut self, enable: bool) -> Result<()> {
pub fn any_pump(&mut self, enable: bool) -> Result<()> {
{
self.main_pump.set_state(enable.into()).unwrap();
Ok(())
}
}
fn time(&mut self) -> Result<chrono::DateTime<Utc>> {
pub fn time(&mut self) -> Result<chrono::DateTime<Utc>> {
let time = EspSystemTime {}.now().as_millis();
let smaller_time = time as i64;
let local_time = DateTime::from_timestamp_millis(smaller_time)
@@ -392,7 +331,7 @@ impl PlantCtrlBoardInteraction for PlantCtrlBoard<'_> {
Ok(local_time)
}
fn sntp(&mut self, max_wait_ms: u32) -> Result<chrono::DateTime<Utc>> {
pub fn sntp(&mut self, max_wait_ms: u32) -> Result<chrono::DateTime<Utc>> {
let sntp = sntp::EspSntp::new_default()?;
let mut counter = 0;
while sntp.get_sync_status() != SyncStatus::Completed {
@@ -407,7 +346,7 @@ impl PlantCtrlBoardInteraction for PlantCtrlBoard<'_> {
self.time()
}
fn measure_moisture_hz(&mut self, plant: usize, sensor: Sensor) -> Result<i32> {
pub fn measure_moisture_hz(&mut self, plant: usize, sensor: Sensor) -> Result<i32> {
let sensor_channel = match sensor {
Sensor::A => match plant {
0 => SENSOR_A_1,
@@ -473,13 +412,13 @@ impl PlantCtrlBoardInteraction for PlantCtrlBoard<'_> {
Ok(results[mid])
}
fn general_fault(&mut self, enable: bool) {
pub fn general_fault(&mut self, enable: bool) {
unsafe { gpio_hold_dis(self.general_fault.pin()) };
self.general_fault.set_state(enable.into()).unwrap();
unsafe { gpio_hold_en(self.general_fault.pin()) };
}
fn wifi_ap(&mut self) -> Result<()> {
pub fn wifi_ap(&mut self) -> Result<()> {
let apconfig = AccessPointConfiguration {
ssid: heapless::String::from_str("PlantCtrl").unwrap(),
auth_method: AuthMethod::None,
@@ -493,7 +432,7 @@ impl PlantCtrlBoardInteraction for PlantCtrlBoard<'_> {
Ok(())
}
fn wifi(
pub fn wifi(
&mut self,
ssid: heapless::String<32>,
password: Option<heapless::String<64>>,
@@ -556,7 +495,7 @@ impl PlantCtrlBoardInteraction for PlantCtrlBoard<'_> {
Ok(address)
}
fn mount_file_system(&mut self) -> Result<()> {
pub fn mount_file_system(&mut self) -> Result<()> {
let base_path = CString::new("/spiffs")?;
let storage = CString::new(SPIFFS_PARTITION_NAME)?;
let conf = esp_idf_sys::esp_vfs_spiffs_conf_t {
@@ -572,7 +511,7 @@ impl PlantCtrlBoardInteraction for PlantCtrlBoard<'_> {
}
}
fn file_system_size(&mut self) -> Result<FileSystemSizeInfo> {
pub fn file_system_size(&mut self) -> Result<FileSystemSizeInfo> {
let storage = CString::new(SPIFFS_PARTITION_NAME)?;
let mut total_size = 0;
let mut used_size = 0;
@@ -590,59 +529,56 @@ impl PlantCtrlBoardInteraction for PlantCtrlBoard<'_> {
})
}
fn is_config_reset(&mut self) -> bool {
pub fn is_mode_override(&mut self) -> bool {
self.boot_button.get_level() == Level::Low
}
fn remove_configs(&mut self) -> Result<ClearConfigType> {
pub fn factory_reset(&mut self) -> Result<()> {
println!("factory resetting");
let config = Path::new(CONFIG_FILE);
if config.exists() {
println!("Removing config");
std::fs::remove_file(config)?;
return Ok(ClearConfigType::Config);
}
let wifi_config = Path::new(WIFI_CONFIG_FILE);
if wifi_config.exists() {
println!("Removing wifi config");
std::fs::remove_file(wifi_config)?;
return Ok(ClearConfigType::WifiConfig);
}
Ok(ClearConfigType::None)
}
fn get_wifi(&mut self) -> Result<config::WifiConfig> {
let cfg = File::open(WIFI_CONFIG_FILE)?;
let config: WifiConfig = serde_json::from_reader(cfg)?;
Ok(config)
}
fn set_wifi(&mut self, wifi: &WifiConfig) -> Result<()> {
let mut cfg = File::create(WIFI_CONFIG_FILE)?;
serde_json::to_writer(&mut cfg, &wifi)?;
println!("Wrote wifi config {}", wifi);
//TODO clear eeprom
Ok(())
}
fn get_config(&mut self) -> Result<config::Config> {
let cfg = File::open(CONFIG_FILE)?;
let mut config: Config = serde_json::from_reader(cfg)?;
//remove duplicate end of topic
if config.base_topic.ends_with("/") {
config.base_topic.pop();
pub fn get_rtc_time(&mut self) -> Result<DateTime<Utc>> {
match self.rtc.datetime() {
OkStd(rtc_time) => {
return Ok(rtc_time.and_utc());
}
Err(err) => {
bail!("Error getting rtc time {:?}", err)
}
}
}
pub fn set_rtc_time(&mut self, time: &DateTime<Utc>) -> Result<()> {
let naive_time = time.naive_utc();
match self.rtc.set_datetime(&naive_time) {
OkStd(_) => Ok(()),
Err(err) => {
bail!("Error getting rtc time {:?}", err)
}
}
}
pub fn get_config(&mut self) -> Result<config::Config> {
let cfg = File::open(CONFIG_FILE)?;
let config: Config = serde_json::from_reader(cfg)?;
Ok(config)
}
fn set_config(&mut self, config: &Config) -> Result<()> {
pub fn set_config(&mut self, config: &Config) -> Result<()> {
let mut cfg = File::create(CONFIG_FILE)?;
serde_json::to_writer(&mut cfg, &config)?;
println!("Wrote config config {:?}", config);
Ok(())
}
fn wifi_scan(&mut self) -> Result<Vec<AccessPointInfo>> {
pub fn wifi_scan(&mut self) -> Result<Vec<AccessPointInfo>> {
self.wifi_driver.start_scan(
&ScanConfig {
scan_type: ScanType::Passive(Duration::from_secs(5)),
@@ -654,7 +590,7 @@ impl PlantCtrlBoardInteraction for PlantCtrlBoard<'_> {
Ok(self.wifi_driver.get_scan_result()?)
}
fn test_pump(&mut self, plant: usize) -> Result<()> {
pub fn test_pump(&mut self, plant: usize) -> Result<()> {
self.any_pump(true)?;
self.pump(plant, true)?;
unsafe { vTaskDelay(30000) };
@@ -663,7 +599,7 @@ impl PlantCtrlBoardInteraction for PlantCtrlBoard<'_> {
Ok(())
}
fn test(&mut self) -> Result<()> {
pub fn test(&mut self) -> Result<()> {
self.general_fault(true);
unsafe { vTaskDelay(100) };
self.general_fault(false);
@@ -698,13 +634,16 @@ impl PlantCtrlBoardInteraction for PlantCtrlBoard<'_> {
Ok(())
}
fn is_wifi_config_file_existant(&mut self) -> bool {
pub fn is_wifi_config_file_existant(&mut self) -> bool {
let config = Path::new(CONFIG_FILE);
config.exists()
}
fn mqtt(&mut self, config: &Config) -> Result<()> {
let last_will_topic = format!("{}/state", config.base_topic);
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")?;
let last_will_topic = format!("{}/state", base_topic);
let mqtt_client_config = MqttClientConfiguration {
lwt: Some(LwtConfiguration {
topic: &last_will_topic,
@@ -722,9 +661,8 @@ impl PlantCtrlBoardInteraction for PlantCtrlBoard<'_> {
let mqtt_connected_event_ok = Arc::new(AtomicBool::new(false));
let round_trip_ok = Arc::new(AtomicBool::new(false));
let round_trip_topic = format!("{}/internal/roundtrip", config.base_topic);
let stay_alive_topic = format!("{}/stay_alive", config.base_topic);
println!("Round trip topic is {}", round_trip_topic);
let round_trip_topic = format!("{}/internal/roundtrip", base_topic);
let stay_alive_topic = format!("{}/stay_alive", base_topic);
println!("Stay alive topic is {}", stay_alive_topic);
let mqtt_connected_event_received_copy = mqtt_connected_event_received.clone();
@@ -734,60 +672,55 @@ impl PlantCtrlBoardInteraction for PlantCtrlBoard<'_> {
let round_trip_ok_copy = round_trip_ok.clone();
println!(
"Connecting mqtt {} with id {}",
config.mqtt_url,
mqtt_url,
mqtt_client_config.client_id.unwrap_or("not set")
);
let mut client =
EspMqttClient::new_cb(&config.mqtt_url, &mqtt_client_config, move |event| {
let payload = event.payload();
match payload {
embedded_svc::mqtt::client::EventPayload::Received {
id: _,
topic,
data,
details: _,
} => {
let data = String::from_utf8_lossy(data);
if let Some(topic) = topic {
//todo use enums
if topic.eq(round_trip_topic_copy.as_str()) {
round_trip_ok_copy
.store(true, std::sync::atomic::Ordering::Relaxed);
} else if topic.eq(stay_alive_topic_copy.as_str()) {
let value = data.eq_ignore_ascii_case("true")
|| data.eq_ignore_ascii_case("1");
println!("Received stay alive with value {}", value);
STAY_ALIVE.store(value, std::sync::atomic::Ordering::Relaxed);
} else {
println!("Unknown topic recieved {}", topic);
}
let mut client = EspMqttClient::new_cb(&mqtt_url, &mqtt_client_config, move |event| {
let payload = event.payload();
match payload {
embedded_svc::mqtt::client::EventPayload::Received {
id: _,
topic,
data,
details: _,
} => {
let data = String::from_utf8_lossy(data);
if let Some(topic) = topic {
//todo use enums
if topic.eq(round_trip_topic_copy.as_str()) {
round_trip_ok_copy.store(true, std::sync::atomic::Ordering::Relaxed);
} else if topic.eq(stay_alive_topic_copy.as_str()) {
let value =
data.eq_ignore_ascii_case("true") || data.eq_ignore_ascii_case("1");
println!("Received stay alive with value {}", value);
STAY_ALIVE.store(value, std::sync::atomic::Ordering::Relaxed);
} else {
println!("Unknown topic recieved {}", topic);
}
}
embedded_svc::mqtt::client::EventPayload::Connected(_) => {
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");
}
embedded_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");
}
embedded_svc::mqtt::client::EventPayload::Error(esp_error) => {
println!("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");
}
_ => {}
}
})?;
embedded_svc::mqtt::client::EventPayload::Connected(_) => {
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");
}
embedded_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");
}
embedded_svc::mqtt::client::EventPayload::Error(esp_error) => {
println!("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");
}
_ => {}
}
})?;
let wait_for_connections_event = 0;
while wait_for_connections_event < 100 {
@@ -836,7 +769,10 @@ impl PlantCtrlBoardInteraction for PlantCtrlBoard<'_> {
bail!("Mqtt did not fire connection callback in time");
}
fn mqtt_publish(&mut self, config: &Config, subtopic: &str, message: &[u8]) -> Result<()> {
pub fn mqtt_publish(&mut self, config: &Config, subtopic: &str, message: &[u8]) -> Result<()> {
if self.mqtt_client.is_none() {
return Ok(());
}
if !subtopic.starts_with("/") {
println!("Subtopic without / at start {}", subtopic);
bail!("Subtopic without / at start {}", subtopic);
@@ -845,136 +781,112 @@ impl PlantCtrlBoardInteraction for PlantCtrlBoard<'_> {
println!("Subtopic exceeds 192 chars {}", subtopic);
bail!("Subtopic exceeds 192 chars {}", subtopic);
}
if self.mqtt_client.is_none() {
println!("Not connected to mqtt");
bail!("Not connected to mqtt");
}
match &mut self.mqtt_client {
Some(client) => {
let mut full_topic: heapless::String<256> = heapless::String::new();
if full_topic.push_str(&config.base_topic).is_err() {
println!("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");
bail!("Some error assembling full_topic 2")
};
let publish = client.publish(
&full_topic,
embedded_svc::mqtt::client::QoS::ExactlyOnce,
true,
message,
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())
.is_err()
{
println!("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");
bail!("Some error assembling full_topic 2")
};
let publish = client.publish(
&full_topic,
embedded_svc::mqtt::client::QoS::ExactlyOnce,
true,
message,
);
Delay::new(10).delay_ms(50);
match publish {
OkStd(message_id) => {
println!(
"Published mqtt topic {} with message {:#?} msgid is {:?}",
full_topic,
String::from_utf8_lossy(message),
message_id
);
Delay::new(10).delay_ms(50);
match publish {
OkStd(message_id) => {
println!(
"Published mqtt topic {} with message {:#?} msgid is {:?}",
full_topic,
String::from_utf8_lossy(message),
message_id
);
return Ok(());
}
Err(err) => {
println!(
"Error during mqtt send on topic {} with message {:#?} error is {:?}",
full_topic,
String::from_utf8_lossy(message),
err
);
return Err(err)?;
}
};
return Ok(());
}
None => {
bail!("No mqtt client");
Err(err) => {
println!(
"Error during mqtt send on topic {} with message {:#?} error is {:?}",
full_topic,
String::from_utf8_lossy(message),
err
);
return Err(err)?;
}
};
}
pub fn state_charge_percent(&mut self) -> Result<u8> {
match self.battery_driver.state_of_charge() {
OkStd(r) => Ok(r),
Err(err) => bail!("Error reading SoC {:?}", err),
}
}
fn state_charge_percent(&mut self) -> Result<u8> {
match &mut self.battery_driver {
Some(driver) => match driver.state_of_charge() {
OkStd(r) => Ok(r),
Err(err) => bail!("Error reading SoC {:?}", err),
},
None => bail!("Error reading SoC bq34z100 not found"),
pub fn remaining_milli_ampere_hour(&mut self) -> Result<u16> {
match self.battery_driver.remaining_capacity() {
OkStd(r) => Ok(r),
Err(err) => bail!("Error reading Remaining Capacity {:?}", err),
}
}
fn remaining_milli_ampere_hour(&mut self) -> Result<u16> {
match &mut self.battery_driver {
Some(driver) => match driver.remaining_capacity() {
OkStd(r) => Ok(r),
Err(err) => bail!("Error reading Remaining Capacity {:?}", err),
},
None => bail!("Error reading Remaining Capacity bq34z100 not found"),
pub fn max_milli_ampere_hour(&mut self) -> Result<u16> {
match self.battery_driver.full_charge_capacity() {
OkStd(r) => Ok(r),
Err(err) => bail!("Error reading Full Charge Capacity {:?}", err),
}
}
fn max_milli_ampere_hour(&mut self) -> Result<u16> {
match &mut self.battery_driver {
Some(driver) => match driver.full_charge_capacity() {
OkStd(r) => Ok(r),
Err(err) => bail!("Error reading Full Charge Capacity {:?}", err),
},
None => bail!("Error reading Full Charge Capacity bq34z100 not found"),
pub fn design_milli_ampere_hour(&mut self) -> Result<u16> {
match self.battery_driver.design_capacity() {
OkStd(r) => Ok(r),
Err(err) => bail!("Error reading Design Capacity {:?}", err),
}
}
fn design_milli_ampere_hour(&mut self) -> Result<u16> {
match &mut self.battery_driver {
Some(driver) => match driver.design_capacity() {
OkStd(r) => Ok(r),
Err(err) => bail!("Error reading Design Capacity {:?}", err),
},
None => bail!("Error reading Design Capacity bq34z100 not found"),
pub fn voltage_milli_volt(&mut self) -> Result<u16> {
match self.battery_driver.voltage() {
OkStd(r) => Ok(r),
Err(err) => bail!("Error reading voltage {:?}", err),
}
}
fn voltage_milli_volt(&mut self) -> Result<u16> {
match &mut self.battery_driver {
Some(driver) => match driver.voltage() {
OkStd(r) => Ok(r),
Err(err) => bail!("Error reading voltage {:?}", err),
},
None => bail!("Error reading voltage bq34z100 not found"),
pub fn average_current_milli_ampere(&mut self) -> Result<i16> {
match self.battery_driver.average_current() {
OkStd(r) => Ok(r),
Err(err) => bail!("Error reading Average Current {:?}", err),
}
}
fn average_current_milli_ampere(&mut self) -> Result<i16> {
match &mut self.battery_driver {
Some(driver) => match driver.average_current() {
OkStd(r) => Ok(r),
Err(err) => bail!("Error reading Average Current {:?}", err),
},
None => bail!("Error reading Average Current bq34z100 not found"),
pub fn cycle_count(&mut self) -> Result<u16> {
match self.battery_driver.cycle_count() {
OkStd(r) => Ok(r),
Err(err) => bail!("Error reading Cycle Count {:?}", err),
}
}
fn cycle_count(&mut self) -> Result<u16> {
match &mut self.battery_driver {
Some(driver) => match driver.cycle_count() {
OkStd(r) => Ok(r),
Err(err) => bail!("Error reading Cycle Count {:?}", err),
},
None => bail!("Error reading Cycle Count bq34z100 not found"),
pub fn state_health_percent(&mut self) -> Result<u8> {
match self.battery_driver.state_of_health() {
OkStd(r) => Ok(r as u8),
Err(err) => bail!("Error reading State of Health {:?}", err),
}
}
fn state_health_percent(&mut self) -> Result<u8> {
match &mut self.battery_driver {
Some(driver) => match driver.state_of_health() {
OkStd(r) => Ok(r as u8),
Err(err) => bail!("Error reading State of Health {:?}", err),
},
None => bail!("Error reading State of Health bq34z100 not found"),
pub fn flash_bq34_z100(&mut self, line: &str, dryrun: bool) -> Result<()> {
match self.battery_driver.write_flash_stream_i2c(line, dryrun) {
OkStd(r) => Ok(r),
Err(err) => bail!("Error reading SoC {:?}", err),
}
}
fn sensor_multiplexer(&mut self, n: u8) -> Result<()> {
pub fn sensor_multiplexer(&mut self, n: u8) -> Result<()> {
assert!(n < 16);
let is_bit_set = |b: u8| -> bool { n & (1 << b) != 0 };
@@ -1004,20 +916,10 @@ impl PlantCtrlBoardInteraction for PlantCtrlBoard<'_> {
}
Ok(())
}
fn flash_bq34_z100(&mut self, line: &str, dryrun: bool) -> Result<()> {
match &mut self.battery_driver {
Some(driver) => match driver.write_flash_stream_i2c(line, dryrun) {
OkStd(r) => Ok(r),
Err(err) => bail!("Error reading SoC {:?}", err),
},
None => bail!("Error reading SoC bq34z100 not found"),
}
}
}
fn print_battery(
battery_driver: &mut Bq34z100g1Driver<MutexDevice<'_, I2cDriver<'_>>, Delay>,
battery_driver: &mut Bq34z100g1Driver<MutexDevice<I2cDriver<'_>>, Delay>,
) -> Result<(), Bq34Z100Error<I2cError>> {
println!("Try communicating with battery");
let fwversion = battery_driver.fw_version().unwrap_or_else(|e| {
@@ -1074,37 +976,61 @@ fn print_battery(
return Result::Ok(());
}
impl CreatePlantHal<'_> for PlantHal {
fn create() -> Result<Mutex<PlantCtrlBoard<'static>>> {
let peripherals = Peripherals::take()?;
pub static I2C_DRIVER: Lazy<Mutex<I2cDriver<'static>>> = Lazy::new(|| PlantHal::create_i2c());
impl PlantHal {
fn create_i2c() -> Mutex<I2cDriver<'static>> {
let peripherals = unsafe { Peripherals::new() };
let i2c = peripherals.i2c0;
let config = I2cConfig::new()
.scl_enable_pullup(true)
.sda_enable_pullup(true)
.baudrate(400_u32.kHz().into())
.baudrate(100_u32.kHz().into())
.timeout(APBTickType::from(Duration::from_millis(100)));
let i2c = peripherals.i2c0;
let scl = peripherals.pins.gpio19.downgrade();
let sda = peripherals.pins.gpio20.downgrade();
let driver = I2cDriver::new(i2c, sda, scl, &config).unwrap();
let i2c_port = driver.port();
let mut timeout: i32 = 0;
esp!(unsafe { esp_idf_sys::i2c_get_timeout(i2c_port, &mut timeout) }).unwrap();
println!("init i2c timeout is {}", timeout);
Mutex::new(I2cDriver::new(i2c, sda, scl, &config).unwrap())
}
pub fn create() -> Result<Mutex<PlantCtrlBoard<'static>>> {
let peripherals = Peripherals::take()?;
let i2c_mutex = Arc::new(Mutex::new(driver));
let i2c_battery_device = MutexDevice::new(&i2c_mutex);
let mut battery_driver: Bq34z100g1Driver<MutexDevice<I2cDriver>, Delay> = Bq34z100g1Driver {
i2c: i2c_battery_device,
println!("Init battery driver");
let mut battery_driver = Bq34z100g1Driver {
i2c: MutexDevice::new(&I2C_DRIVER),
delay: Delay::new(0),
flash_block_data: [0; 32],
};
let i2c_rtc_device = MutexDevice::new(&i2c_mutex);
let rtc = Ds323x::new_ds3231(i2c_rtc_device);
println!("Init rtc driver");
let mut rtc = Ds323x::new_ds3231(MutexDevice::new(&I2C_DRIVER));
println!("Init rtc eeprom driver");
let mut eeprom = {
Eeprom24x::new_24x32(
MutexDevice::new(&I2C_DRIVER),
SlaveAddr::Alternative(true, true, true),
)
};
let rtc_time = rtc.datetime();
match rtc_time {
OkStd(tt) => {
println!("Rtc Module reports time at UTC {}", tt);
}
Err(err) => {
println!("Rtc Module could not be read {:?}", err);
}
}
match eeprom.read_byte(0) {
OkStd(byte) => {
println!("Read first byte with status {}", byte);
}
Err(err) => {
println!("Eeprom could not read first byte {:?}", err);
}
}
let mut clock = PinDriver::input_output(peripherals.pins.gpio15.downgrade())?;
clock.set_pull(Pull::Floating).unwrap();
@@ -1165,14 +1091,9 @@ impl CreatePlantHal<'_> for PlantHal {
LOW_VOLTAGE_DETECTED
);
for i in 0..PLANT_COUNT {
let smaller_time = LAST_WATERING_TIMESTAMP[i];
let utc_time = DateTime::from_timestamp_millis(smaller_time)
.ok_or(anyhow!("could not convert timestamp"))?;
let europe_time = utc_time.with_timezone(&Berlin);
println!(
"LAST_WATERING_TIMESTAMP[{}] = {} as europe {}",
i, LAST_WATERING_TIMESTAMP[i], europe_time
"LAST_WATERING_TIMESTAMP[{}] = UTC {}",
i, LAST_WATERING_TIMESTAMP[i]
);
}
for i in 0..PLANT_COUNT {
@@ -1275,8 +1196,9 @@ impl CreatePlantHal<'_> for PlantHal {
signal_counter: counter_unit1,
wifi_driver,
mqtt_client: None,
battery_driver: Some(battery_driver),
rtc: Some(rtc)
battery_driver: battery_driver,
rtc: rtc,
eeprom: eeprom,
});
let _ = rv.lock().is_ok_and(|mut board| {