fmt and mqtt workarounds

This commit is contained in:
2024-04-22 13:03:42 +02:00
parent 82bc9ed66d
commit 86c6bb5a73
8 changed files with 7252 additions and 9559 deletions

View File

@@ -14,7 +14,7 @@ use esp_idf_svc::mqtt::client::{EspMqttClient, LwtConfiguration, MqttClientConfi
use esp_idf_svc::nvs::EspDefaultNvsPartition;
use esp_idf_svc::wifi::config::{ScanConfig, ScanType};
use esp_idf_svc::wifi::EspWifi;
use measurements::Temperature;
use measurements::{Frequency, Temperature};
use plant_ctrl2::sipo::ShiftRegister40;
use anyhow::anyhow;
@@ -42,7 +42,7 @@ 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};
@@ -82,8 +82,7 @@ pub enum ClearConfigType {
None,
}
#[derive(Debug)]
#[derive(PartialEq)]
#[derive(Debug, PartialEq)]
pub enum Sensor {
A,
B,
@@ -126,7 +125,7 @@ pub trait PlantCtrlBoardInteraction {
fn measure_moisture_hz(&self, plant: usize, sensor: Sensor) -> Result<i32>;
fn pump(&self, plant: usize, enable: bool) -> Result<()>;
fn last_pump_time(&self, plant: usize) -> chrono::DateTime<Utc>;
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;
@@ -144,7 +143,7 @@ pub trait PlantCtrlBoardInteraction {
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 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<()>;
@@ -174,7 +173,7 @@ 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: Bq34z100g1Driver<I2cDriver<'a>, Delay>,
battery_driver: Option<Bq34z100g1Driver<I2cDriver<'a>, Delay>>,
}
impl PlantCtrlBoardInteraction for PlantCtrlBoard<'_> {
@@ -242,10 +241,7 @@ impl PlantCtrlBoardInteraction for PlantCtrlBoard<'_> {
let mut percent = r2 / 190_f32 * 100_f32;
percent = percent.clamp(0.0, 100.0);
println!(
"Tank sensor raw {} percent {}",
median, percent
);
println!("Tank sensor raw {} percent {}", median, percent);
return Ok(percent as u16);
}
@@ -271,15 +267,13 @@ impl PlantCtrlBoardInteraction for PlantCtrlBoard<'_> {
fn pump(&self, plant: usize, enable: bool) -> Result<()> {
let index = plant * PINS_PER_PLANT + PLANT_PUMP_OFFSET;
//currently infailable error, keep for future as result anyway
self.shift_register.decompose()[index]
.set_state(enable.into())
.unwrap();
self.shift_register.decompose()[index].set_state(enable.into())?;
Ok(())
}
fn last_pump_time(&self, plant: usize) -> chrono::DateTime<Utc> {
fn last_pump_time(&self, plant: usize) -> Option<chrono::DateTime<Utc>> {
let ts = unsafe { LAST_WATERING_TIMESTAMP }[plant];
return DateTime::from_timestamp_millis(ts).unwrap();
return Some(DateTime::from_timestamp_millis(ts)?);
}
fn store_last_pump_time(&mut self, plant: usize, time: chrono::DateTime<Utc>) {
@@ -407,13 +401,13 @@ impl PlantCtrlBoardInteraction for PlantCtrlBoard<'_> {
))?;
}
None => {
self.wifi_driver
.set_configuration(&Configuration::Client(ClientConfiguration {
self.wifi_driver.set_configuration(&Configuration::Client(
ClientConfiguration {
ssid: ssid,
auth_method: AuthMethod::None,
..Default::default()
}))
.unwrap();
},
))?;
}
}
@@ -435,7 +429,7 @@ impl PlantCtrlBoardInteraction for PlantCtrlBoard<'_> {
}
println!("Should be connected now");
while !self.wifi_driver.is_up().unwrap() {
while !self.wifi_driver.is_up()? {
println!("Waiting for network being up");
delay.delay_ms(250);
counter += 250;
@@ -447,7 +441,7 @@ impl PlantCtrlBoardInteraction for PlantCtrlBoard<'_> {
}
}
//update freertos registers ;)
let address = self.wifi_driver.sta_netif().get_ip_info().unwrap();
let address = self.wifi_driver.sta_netif().get_ip_info()?;
println!("IP info: {:?}", address);
Ok(address)
}
@@ -568,7 +562,7 @@ impl PlantCtrlBoardInteraction for PlantCtrlBoard<'_> {
Ok(self.wifi_driver.get_scan_result()?)
}
fn test_pump(&mut self, plant:usize) -> Result<()> {
fn test_pump(&mut self, plant: usize) -> Result<()> {
self.any_pump(true)?;
self.pump(plant, true)?;
unsafe { vTaskDelay(30000) };
@@ -622,7 +616,6 @@ impl PlantCtrlBoardInteraction for PlantCtrlBoard<'_> {
fn mqtt(&mut self, config: &Config) -> Result<()> {
let last_will_topic = format!("{}/state", config.base_topic);
let mqtt_client_config = MqttClientConfiguration {
lwt: Some(LwtConfiguration {
topic: &last_will_topic,
@@ -631,23 +624,34 @@ impl PlantCtrlBoardInteraction for PlantCtrlBoard<'_> {
retain: true,
}),
client_id: Some("plantctrl"),
keep_alive_interval : Some(Duration::from_secs(60*60*2)),
keep_alive_interval: Some(Duration::from_secs(60 * 60 * 2)),
//room for improvement
..Default::default()
};
let mqtt_connected_event_received = Arc::new(AtomicBool::new(false));
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);
println!("Stay alive topic is {}", stay_alive_topic);
let mqtt_connected_event_received_copy = mqtt_connected_event_received.clone();
let mqtt_connected_event_ok_copy = mqtt_connected_event_ok.clone();
let stay_alive_topic_copy = stay_alive_topic.clone();
let round_trip_topic_copy = round_trip_topic.clone();
let round_trip_ok_copy = round_trip_ok.clone();
println!(
"Connecting mqtt {} with id {}",
config.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();
println!("received mqtt event {:?}", payload);
match payload {
embedded_svc::mqtt::client::EventPayload::Received {
id: _,
@@ -655,6 +659,7 @@ impl PlantCtrlBoardInteraction for PlantCtrlBoard<'_> {
data,
details: _,
} => {
println!("Received something");
let data = String::from_utf8_lossy(data);
if let Some(topic) = topic {
//todo use enums
@@ -671,38 +676,82 @@ impl PlantCtrlBoardInteraction for PlantCtrlBoard<'_> {
}
}
}
_ => {}
embedded_svc::mqtt::client::EventPayload::Connected(session_present) => {
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(espError) => {
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");
}
_ => {
}
}
})?;
//subscribe to roundtrip
client.subscribe(round_trip_topic.as_str(), ExactlyOnce)?;
client.subscribe(stay_alive_topic.as_str(), ExactlyOnce)?;
//publish to roundtrip
client.publish(
round_trip_topic.as_str(),
ExactlyOnce,
false,
"online_test".as_bytes(),
)?;
let wait_for_roundtrip = 0;
while wait_for_roundtrip < 100 {
match round_trip_ok.load(std::sync::atomic::Ordering::Relaxed) {
let wait_for_connections_event = 0;
while wait_for_connections_event < 100 {
match true { //mqtt_connected_event_received.load(std::sync::atomic::Ordering::Relaxed) {
true => {
println!("Round trip registered, proceeding");
self.mqtt_client = Some(client);
return Ok(());
println!("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");
//subscribe to roundtrip
client.subscribe(round_trip_topic.as_str(), ExactlyOnce)?;
client.subscribe(stay_alive_topic.as_str(), ExactlyOnce)?;
//publish to roundtrip
client.publish(
round_trip_topic.as_str(),
ExactlyOnce,
false,
"online_test".as_bytes(),
)?;
let wait_for_roundtrip = 0;
while wait_for_roundtrip < 100 {
match round_trip_ok.load(std::sync::atomic::Ordering::Relaxed) {
true => {
println!("Round trip registered, proceeding");
self.mqtt_client = Some(client);
return Ok(());
}
false => {
unsafe { vTaskDelay(10) };
}
}
}
bail!("Mqtt did not complete roundtrip in time");
}
false => {
bail!("Mqtt did respond but with failure")
}
}
}
false => {
unsafe { vTaskDelay(10) };
}
}
}
bail!("Mqtt did not complete roundtrip in time");
bail!("Mqtt did not fire connection callback in time");
}
fn mqtt_publish(&mut self, config: &Config, subtopic: &str, message: &[u8]) -> Result<()> {
println!("Publishing mqtt {} content {:?}", subtopic, message);
if !subtopic.starts_with("/") {
println!("Subtopic without / at start {}", subtopic);
bail!("Subtopic without / at start {}", subtopic);
@@ -715,94 +764,130 @@ impl PlantCtrlBoardInteraction for PlantCtrlBoard<'_> {
println!("Not connected to mqtt");
bail!("Not connected to mqtt");
}
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).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);
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)?
},
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,
);
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)?;
}
};
}
None => {
bail!("No mqtt client, aborting publish");
}
}
;
}
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),
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"),
}
}
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),
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"),
}
}
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),
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"),
}
}
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),
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"),
}
}
fn voltage_milli_volt(&mut self) -> Result<u16> {
return match self.battery_driver.voltage() {
OkStd(r) => Ok(r),
Err(err) => bail!("Error reading voltage {:?}", err),
};
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"),
}
}
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),
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"),
}
}
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),
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"),
}
}
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),
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"),
}
}
}
fn print_battery(
@@ -876,8 +961,8 @@ impl CreatePlantHal<'_> for PlantHal {
let driver = I2cDriver::new(i2c, sda, scl, &config).unwrap();
let i2c_port = driver.port();
esp!(unsafe { esp_idf_sys::i2c_set_timeout(i2c_port, 1048000) }).unwrap();
//let i2c_port = driver.port();
//esp!(unsafe { esp_idf_sys::i2c_set_timeout(i2c_port, 2)}).unwrap();
let mut battery_driver: Bq34z100g1Driver<I2cDriver, Delay> = Bq34z100g1Driver {
i2c: driver,
@@ -1015,10 +1100,12 @@ impl CreatePlantHal<'_> for PlantHal {
println!("After stuff");
let status = print_battery(&mut battery_driver);
if status.is_err() {
println!("Error communicating with battery!! {:?}", status.err());
}
//let status = print_battery(&mut battery_driver);
//if status.is_err() {
// println!("Error communicating with battery!! {:?}", status.err());
//} else {
// println!("Managed to comunnicate with battery");
//}
let rv = Mutex::new(PlantCtrlBoard {
shift_register,
tank_driver,
@@ -1033,7 +1120,8 @@ impl CreatePlantHal<'_> for PlantHal {
signal_counter: counter_unit1,
wifi_driver,
mqtt_client: None,
battery_driver,
battery_driver: None,
//Some(battery_driver),
});
Ok(rv)
}