fmt and mqtt workarounds

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

File diff suppressed because it is too large Load Diff

View File

@ -37,9 +37,9 @@
"other_text_thickness": 0.15, "other_text_thickness": 0.15,
"other_text_upright": false, "other_text_upright": false,
"pads": { "pads": {
"drill": 0.0, "drill": 0.25,
"height": 3.0, "height": 0.35,
"width": 1.6 "width": 0.35
}, },
"silk_line_width": 0.12, "silk_line_width": 0.12,
"silk_text_italic": false, "silk_text_italic": false,
@ -58,13 +58,15 @@
"width": 0.0 "width": 0.0
} }
], ],
"drc_exclusions": [], "drc_exclusions": [
"courtyards_overlap|199080001|128865001|67ac55df-4a92-42f8-90ae-0f317d1fcee5|cfde0667-9234-45fc-8eda-14a18003cf8d"
],
"meta": { "meta": {
"filename": "board_design_settings.json", "filename": "board_design_settings.json",
"version": 2 "version": 2
}, },
"rule_severities": { "rule_severities": {
"annular_width": "error", "annular_width": "ignore",
"clearance": "error", "clearance": "error",
"connection_width": "warning", "connection_width": "warning",
"copper_edge_clearance": "error", "copper_edge_clearance": "error",

File diff suppressed because it is too large Load Diff

View File

@ -24,7 +24,7 @@ build-std = ["std", "panic_abort"]
[env] [env]
MCU="esp32c6" MCU="esp32c6"
# Note: this variable is not used by the pio builder (`cargo build --features pio`) # Note: this variable is not used by the pio builder (`cargo build --features pio`)
ESP_IDF_VERSION = "v5.1.1" ESP_IDF_VERSION = "v5.2.1"
CHRONO_TZ_TIMEZONE_FILTER="UTC|Europe/Berlin" CHRONO_TZ_TIMEZONE_FILTER="UTC|Europe/Berlin"
CARGO_WORKSPACE_DIR = { value = "", relative = true } CARGO_WORKSPACE_DIR = { value = "", relative = true }
RUST_BACKTRACE = "full" RUST_BACKTRACE = "full"

View File

@ -10,7 +10,7 @@ rust-version = "1.71"
# Explicitly disable LTO which the Xtensa codegen backend has issues # Explicitly disable LTO which the Xtensa codegen backend has issues
lto = true lto = true
strip = false strip = false
debug = false debug = true
overflow-checks = true overflow-checks = true
panic = "abort" panic = "abort"
incremental = true incremental = true

View File

@ -5,7 +5,11 @@ use chrono_tz::{Europe::Berlin, Tz};
use esp_idf_hal::delay::Delay; use esp_idf_hal::delay::Delay;
use esp_idf_sys::{ use esp_idf_sys::{
esp_deep_sleep, esp_ota_get_app_partition_count, esp_ota_get_running_partition, esp_ota_get_state_partition, esp_ota_img_states_t, esp_ota_img_states_t_ESP_OTA_IMG_ABORTED, esp_ota_img_states_t_ESP_OTA_IMG_INVALID, esp_ota_img_states_t_ESP_OTA_IMG_NEW, esp_ota_img_states_t_ESP_OTA_IMG_PENDING_VERIFY, esp_ota_img_states_t_ESP_OTA_IMG_UNDEFINED, esp_ota_img_states_t_ESP_OTA_IMG_VALID, esp_restart, vTaskDelay, CONFIG_FREERTOS_HZ esp_deep_sleep, esp_ota_get_app_partition_count, esp_ota_get_running_partition,
esp_ota_get_state_partition, esp_ota_img_states_t, esp_ota_img_states_t_ESP_OTA_IMG_ABORTED,
esp_ota_img_states_t_ESP_OTA_IMG_INVALID, esp_ota_img_states_t_ESP_OTA_IMG_NEW,
esp_ota_img_states_t_ESP_OTA_IMG_PENDING_VERIFY, esp_ota_img_states_t_ESP_OTA_IMG_UNDEFINED,
esp_ota_img_states_t_ESP_OTA_IMG_VALID, esp_restart, vTaskDelay, CONFIG_FREERTOS_HZ,
}; };
use log::error; use log::error;
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
@ -127,10 +131,7 @@ fn safe_main() -> anyhow::Result<()> {
println!("Partition count is {}", count); println!("Partition count is {}", count);
let mut ota_state: esp_ota_img_states_t = 0; let mut ota_state: esp_ota_img_states_t = 0;
let running_partition = unsafe { esp_ota_get_running_partition() }; let running_partition = unsafe { esp_ota_get_running_partition() };
let address = unsafe { let address = unsafe { (*running_partition).address };
(*running_partition).address
};
println!("Partition address is {}", address); println!("Partition address is {}", address);
let ota_state_string = unsafe { let ota_state_string = unsafe {
@ -298,16 +299,24 @@ fn safe_main() -> anyhow::Result<()> {
match ip_address { match ip_address {
Some(add_some) => { Some(add_some) => {
let _ = board.mqtt_publish(&config, "/firmware/address", add_some.as_bytes()); let _ = board.mqtt_publish(&config, "/firmware/address", add_some.as_bytes());
}, }
None => { None => {
let _ = board.mqtt_publish(&config, "/firmware/address", "N/A?".as_bytes()); let _ = board.mqtt_publish(&config, "/firmware/address", "N/A?".as_bytes());
}, }
} }
let _ = board.mqtt_publish(&config, "/firmware/githash", git_hash.as_bytes()); let _ = board.mqtt_publish(&config, "/firmware/githash", git_hash.as_bytes());
let _ = board.mqtt_publish(&config, "/firmware/buildtime", build_timestamp.as_bytes()); let _ = board.mqtt_publish(&config, "/firmware/buildtime", build_timestamp.as_bytes());
let _ = board.mqtt_publish(&config, "/firmware/last_online", europe_time.to_rfc3339().as_bytes()); let _ = board.mqtt_publish(
&config,
"/firmware/last_online",
europe_time.to_rfc3339().as_bytes(),
);
let _ = board.mqtt_publish(&config, "/firmware/ota_state", ota_state_string.as_bytes()); let _ = board.mqtt_publish(&config, "/firmware/ota_state", ota_state_string.as_bytes());
let _ = board.mqtt_publish(&config, "/firmware/partition_address", format!("{:#06x}",address).as_bytes()); let _ = board.mqtt_publish(
&config,
"/firmware/partition_address",
format!("{:#06x}", address).as_bytes(),
);
let _ = board.mqtt_publish(&config, "/state", "online".as_bytes()); let _ = board.mqtt_publish(&config, "/state", "online".as_bytes());
publish_battery_state(&mut board, &config); publish_battery_state(&mut board, &config);
@ -318,15 +327,23 @@ fn safe_main() -> anyhow::Result<()> {
if tank_state.sensor_error { if tank_state.sensor_error {
let _ = board.mqtt_publish(&config, "/water/ml", "error".to_string().as_bytes()); let _ = board.mqtt_publish(&config, "/water/ml", "error".to_string().as_bytes());
} else { } else {
let _ = board.mqtt_publish(&config, "/water/ml", tank_state.left_ml.to_string().as_bytes()); let _ = board.mqtt_publish(
let _ = board.mqtt_publish(&config, "/water/enough_water", tank_state.enough_water.to_string().as_bytes()); &config,
let _ = board.mqtt_publish(&config, "/water/raw", tank_state.raw.to_string().as_bytes()); "/water/ml",
tank_state.left_ml.to_string().as_bytes(),
);
let _ = board.mqtt_publish(
&config,
"/water/enough_water",
tank_state.enough_water.to_string().as_bytes(),
);
let _ =
board.mqtt_publish(&config, "/water/raw", tank_state.raw.to_string().as_bytes());
} }
} }
let mut water_frozen = false; let mut water_frozen = false;
let mut temp:Option<f32> = None; let mut temp: Option<f32> = None;
for _attempt in 0..5 { for _attempt in 0..5 {
let water_temperature = board.water_temperature_c(); let water_temperature = board.water_temperature_c();
match water_temperature { match water_temperature {
@ -346,24 +363,16 @@ fn safe_main() -> anyhow::Result<()> {
water_frozen = true; water_frozen = true;
} }
if online_mode == OnlineMode::Online { if online_mode == OnlineMode::Online {
let _ = board.mqtt_publish( let _ =
&config, board.mqtt_publish(&config, "/water/temperature", res.to_string().as_bytes());
"/water/temperature", }
res.to_string().as_bytes(),
);
} }
},
None => { None => {
if online_mode == OnlineMode::Online { if online_mode == OnlineMode::Online {
let _ = board.mqtt_publish(&config, "/water/temperature", "Error".as_bytes()); let _ = board.mqtt_publish(&config, "/water/temperature", "Error".as_bytes());
} }
},
} }
}
let mut plantstate = [PlantState { let mut plantstate = [PlantState {
..Default::default() ..Default::default()
@ -527,40 +536,24 @@ fn safe_main() -> anyhow::Result<()> {
let deep_sleep_duration_minutes: u32 = if state_of_charge < 10 { let deep_sleep_duration_minutes: u32 = if state_of_charge < 10 {
if online_mode == OnlineMode::Online { if online_mode == OnlineMode::Online {
let _ = board.mqtt_publish( let _ = board.mqtt_publish(&config, "/deepsleep", "low Volt 12h".as_bytes());
&config,
"/deepsleep",
"low Volt 12h".as_bytes(),
);
} }
12 * 60 12 * 60
} else if is_day { } else if is_day {
if did_pump { if did_pump {
if online_mode == OnlineMode::Online { if online_mode == OnlineMode::Online {
let _ = board.mqtt_publish( let _ = board.mqtt_publish(&config, "/deepsleep", "after pump".as_bytes());
&config,
"/deepsleep",
"after pump".as_bytes(),
);
} }
0 0
} else { } else {
if online_mode == OnlineMode::Online { if online_mode == OnlineMode::Online {
let _ = board.mqtt_publish( let _ = board.mqtt_publish(&config, "/deepsleep", "normal 20m".as_bytes());
&config,
"/deepsleep",
"normal 20m".as_bytes(),
);
} }
20 20
} }
} else { } else {
if online_mode == OnlineMode::Online { if online_mode == OnlineMode::Online {
let _ = board.mqtt_publish( let _ = board.mqtt_publish(&config, "/deepsleep", "night 1h".as_bytes());
&config,
"/deepsleep",
"night 1h".as_bytes(),
);
} }
60 60
}; };
@ -568,7 +561,6 @@ fn safe_main() -> anyhow::Result<()> {
let _ = board.mqtt_publish(&config, "/state", "sleep".as_bytes()); let _ = board.mqtt_publish(&config, "/state", "sleep".as_bytes());
} }
//determine next event //determine next event
//is light out of work trigger soon? //is light out of work trigger soon?
//is battery low ?? //is battery low ??
@ -853,18 +845,31 @@ fn determine_state_target_moisture_for_plant(
state.dry = true; state.dry = true;
if tank_state.sensor_error && !config.tank_allow_pumping_if_sensor_error { if tank_state.sensor_error && !config.tank_allow_pumping_if_sensor_error {
//ignore is ok //ignore is ok
} } else if !tank_state.enough_water {
else if !tank_state.enough_water {
state.no_water = true; state.no_water = true;
} }
} }
let duration = TimeDelta::try_minutes(plant_config.pump_cooldown_min as i64).unwrap(); let duration = TimeDelta::try_minutes(plant_config.pump_cooldown_min as i64).unwrap();
let next_pump = board.last_pump_time(plant) + duration; let last_pump = board.last_pump_time(plant);
match last_pump {
Some(last_pump) => {
let next_pump = last_pump + duration;
if next_pump > cur { if next_pump > cur {
let europe_time = next_pump.with_timezone(&Berlin); let europe_time = next_pump.with_timezone(&Berlin);
state.next_pump = Some(europe_time); state.next_pump = Some(europe_time);
state.cooldown = true; state.cooldown = true;
} }
}
None => {
println!(
"Could not restore last pump for plant {}, restoring",
plant + 1
);
board.store_last_pump_time(plant, DateTime::from_timestamp_millis(0).unwrap());
state.pump_error = true;
}
}
if !in_time_range( if !in_time_range(
cur, cur,
plant_config.pump_hour_start, plant_config.pump_hour_start,
@ -884,6 +889,100 @@ fn determine_state_target_moisture_for_plant(
} }
} }
fn determine_state_timer_only_for_plant(
board: &mut std::sync::MutexGuard<'_, PlantCtrlBoard<'_>>,
plant: usize,
state: &mut PlantState,
config: &Config,
tank_state: &TankState,
water_frozen: bool,
cur: DateTime<Tz>,
) {
let plant_config = &config.plants[plant];
let duration = TimeDelta::try_minutes(plant_config.pump_cooldown_min as i64).unwrap();
let last_pump = board.last_pump_time(plant);
match last_pump {
Some(last_pump) => {
let next_pump = last_pump + duration;
if next_pump > cur {
let europe_time = next_pump.with_timezone(&Berlin);
state.next_pump = Some(europe_time);
state.cooldown = true;
} else {
if water_frozen {
state.frozen = true;
} else {
if tank_state.sensor_error && !config.tank_allow_pumping_if_sensor_error {
state.do_water = true;
} else if !tank_state.enough_water {
state.no_water = true;
}
}
}
}
None => {
println!(
"Could not restore last pump for plant {}, restoring",
plant + 1
);
board.store_last_pump_time(plant, DateTime::from_timestamp_millis(0).unwrap());
state.pump_error = true;
}
}
}
fn determine_state_timer_and_deadzone_for_plant(
board: &mut std::sync::MutexGuard<'_, PlantCtrlBoard<'_>>,
plant: usize,
state: &mut PlantState,
config: &Config,
tank_state: &TankState,
water_frozen: bool,
cur: DateTime<Tz>,
) {
let plant_config = &config.plants[plant];
let duration = TimeDelta::try_minutes(plant_config.pump_cooldown_min as i64).unwrap();
let last_pump = board.last_pump_time(plant);
match last_pump {
Some(last_pump) => {
let next_pump = last_pump + duration;
if next_pump > cur {
let europe_time = next_pump.with_timezone(&Berlin);
state.next_pump = Some(europe_time);
state.cooldown = true;
}
if !in_time_range(
cur,
plant_config.pump_hour_start,
plant_config.pump_hour_end,
) {
state.out_of_work_hour = true;
}
if !state.cooldown && !state.out_of_work_hour {
if water_frozen {
state.frozen = true;
} else {
if tank_state.sensor_error && !config.tank_allow_pumping_if_sensor_error {
state.do_water = true;
} else if !tank_state.enough_water {
state.no_water = true;
}
}
}
}
None => {
println!(
"Could not restore last pump for plant {}, restoring",
plant + 1
);
board.store_last_pump_time(plant, DateTime::from_timestamp_millis(0).unwrap());
state.pump_error = true;
}
}
}
fn determine_next_plant( fn determine_next_plant(
plantstate: &mut [PlantState; PLANT_COUNT], plantstate: &mut [PlantState; PLANT_COUNT],
cur: DateTime<Tz>, cur: DateTime<Tz>,
@ -909,42 +1008,26 @@ fn determine_next_plant(
); );
} }
config::Mode::TimerOnly => { config::Mode::TimerOnly => {
let duration = TimeDelta::try_minutes(plant_config.pump_cooldown_min as i64).unwrap(); determine_state_timer_only_for_plant(
let next_pump = board.last_pump_time(plant) + duration; board,
if next_pump > cur { plant,
let europe_time = next_pump.with_timezone(&Berlin); state,
state.next_pump = Some(europe_time); config,
state.cooldown = true; tank_state,
} else { water_frozen,
if water_frozen { cur,
state.frozen = true; );
} else {
state.do_water = true;
}
}
} }
config::Mode::TimerAndDeadzone => { config::Mode::TimerAndDeadzone => {
let duration = TimeDelta::try_minutes(plant_config.pump_cooldown_min as i64).unwrap(); determine_state_timer_and_deadzone_for_plant(
let next_pump = board.last_pump_time(plant) + duration; board,
if next_pump > cur { plant,
let europe_time = next_pump.with_timezone(&Berlin); state,
state.next_pump = Some(europe_time); config,
state.cooldown = true; tank_state,
} water_frozen,
if !in_time_range(
cur, cur,
plant_config.pump_hour_start, );
plant_config.pump_hour_end,
) {
state.out_of_work_hour = true;
}
if !state.cooldown && !state.out_of_work_hour {
if water_frozen {
state.frozen = true;
} else {
state.do_water = true;
}
}
} }
} }
@ -995,6 +1078,8 @@ fn update_plant_state(
); );
let last_time = board.last_pump_time(plant); let last_time = board.last_pump_time(plant);
match last_time {
Some(last_time) => {
let europe_time = last_time.with_timezone(&Berlin); let europe_time = last_time.with_timezone(&Berlin);
if europe_time.year() > 2023 { if europe_time.year() > 2023 {
let time = europe_time.to_rfc3339(); let time = europe_time.to_rfc3339();
@ -1010,6 +1095,15 @@ fn update_plant_state(
"N/A".as_bytes(), "N/A".as_bytes(),
); );
} }
}
None => {
let _ = board.mqtt_publish(
&config,
format!("/plant{}/last pump", plant + 1).as_str(),
"N/A".as_bytes(),
);
}
}
match state.next_pump { match state.next_pump {
Some(next) => { Some(next) => {
@ -1121,8 +1215,6 @@ fn update_plant_state(
format!("/plant{}/consecutive pump count", plant + 1).as_str(), format!("/plant{}/consecutive pump count", plant + 1).as_str(),
state.consecutive_pump_count.to_string().as_bytes(), state.consecutive_pump_count.to_string().as_bytes(),
); );
} }
} }
@ -1171,13 +1263,13 @@ fn main() {
Ok(_) => { Ok(_) => {
println!("Main app finished, restarting"); println!("Main app finished, restarting");
unsafe { esp_restart() }; unsafe { esp_restart() };
}, }
Err(err) => { Err(err) => {
println!("Failed main {}", err); println!("Failed main {}", err);
let rollback_successful = rollback_and_reboot(); let rollback_successful = rollback_and_reboot();
println!("Failed to rollback :("); println!("Failed to rollback :(");
rollback_successful.unwrap(); rollback_successful.unwrap();
}, }
} }
} }
//error codes //error codes

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::nvs::EspDefaultNvsPartition;
use esp_idf_svc::wifi::config::{ScanConfig, ScanType}; use esp_idf_svc::wifi::config::{ScanConfig, ScanType};
use esp_idf_svc::wifi::EspWifi; use esp_idf_svc::wifi::EspWifi;
use measurements::Temperature; use measurements::{Frequency, Temperature};
use plant_ctrl2::sipo::ShiftRegister40; use plant_ctrl2::sipo::ShiftRegister40;
use anyhow::anyhow; use anyhow::anyhow;
@ -42,7 +42,7 @@ use esp_idf_hal::prelude::Peripherals;
use esp_idf_hal::reset::ResetReason; use esp_idf_hal::reset::ResetReason;
use esp_idf_svc::sntp::{self, SyncStatus}; use esp_idf_svc::sntp::{self, SyncStatus};
use esp_idf_svc::systime::EspSystemTime; 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 one_wire_bus::OneWire;
use crate::config::{self, Config, WifiConfig}; use crate::config::{self, Config, WifiConfig};
@ -82,8 +82,7 @@ pub enum ClearConfigType {
None, None,
} }
#[derive(Debug)] #[derive(Debug, PartialEq)]
#[derive(PartialEq)]
pub enum Sensor { pub enum Sensor {
A, A,
B, B,
@ -126,7 +125,7 @@ pub trait PlantCtrlBoardInteraction {
fn measure_moisture_hz(&self, plant: usize, sensor: Sensor) -> Result<i32>; fn measure_moisture_hz(&self, plant: usize, sensor: Sensor) -> Result<i32>;
fn pump(&self, plant: usize, enable: bool) -> Result<()>; 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_last_pump_time(&mut self, plant: usize, time: chrono::DateTime<Utc>);
fn store_consecutive_pump_count(&mut self, plant: usize, count: u32); fn store_consecutive_pump_count(&mut self, plant: usize, count: u32);
fn consecutive_pump_count(&mut self, plant: usize) -> 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_ap(&mut self) -> Result<()>;
fn wifi_scan(&mut self) -> Result<Vec<AccessPointInfo>>; fn wifi_scan(&mut self) -> Result<Vec<AccessPointInfo>>;
fn test(&mut self) -> Result<()>; 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 is_wifi_config_file_existant(&mut self) -> bool;
fn mqtt(&mut self, config: &Config) -> Result<()>; fn mqtt(&mut self, config: &Config) -> Result<()>;
fn mqtt_publish(&mut self, config: &Config, subtopic: &str, message: &[u8]) -> 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>, pub wifi_driver: EspWifi<'a>,
one_wire_bus: OneWire<PinDriver<'a, Gpio18, esp_idf_hal::gpio::InputOutput>>, one_wire_bus: OneWire<PinDriver<'a, Gpio18, esp_idf_hal::gpio::InputOutput>>,
mqtt_client: Option<EspMqttClient<'a>>, mqtt_client: Option<EspMqttClient<'a>>,
battery_driver: Bq34z100g1Driver<I2cDriver<'a>, Delay>, battery_driver: Option<Bq34z100g1Driver<I2cDriver<'a>, Delay>>,
} }
impl PlantCtrlBoardInteraction for PlantCtrlBoard<'_> { impl PlantCtrlBoardInteraction for PlantCtrlBoard<'_> {
@ -242,10 +241,7 @@ impl PlantCtrlBoardInteraction for PlantCtrlBoard<'_> {
let mut percent = r2 / 190_f32 * 100_f32; let mut percent = r2 / 190_f32 * 100_f32;
percent = percent.clamp(0.0, 100.0); percent = percent.clamp(0.0, 100.0);
println!( println!("Tank sensor raw {} percent {}", median, percent);
"Tank sensor raw {} percent {}",
median, percent
);
return Ok(percent as u16); return Ok(percent as u16);
} }
@ -271,15 +267,13 @@ impl PlantCtrlBoardInteraction for PlantCtrlBoard<'_> {
fn pump(&self, plant: usize, enable: bool) -> Result<()> { fn pump(&self, plant: usize, enable: bool) -> Result<()> {
let index = plant * PINS_PER_PLANT + PLANT_PUMP_OFFSET; let index = plant * PINS_PER_PLANT + PLANT_PUMP_OFFSET;
//currently infailable error, keep for future as result anyway //currently infailable error, keep for future as result anyway
self.shift_register.decompose()[index] self.shift_register.decompose()[index].set_state(enable.into())?;
.set_state(enable.into())
.unwrap();
Ok(()) 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]; 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>) { fn store_last_pump_time(&mut self, plant: usize, time: chrono::DateTime<Utc>) {
@ -407,13 +401,13 @@ impl PlantCtrlBoardInteraction for PlantCtrlBoard<'_> {
))?; ))?;
} }
None => { None => {
self.wifi_driver self.wifi_driver.set_configuration(&Configuration::Client(
.set_configuration(&Configuration::Client(ClientConfiguration { ClientConfiguration {
ssid: ssid, ssid: ssid,
auth_method: AuthMethod::None, auth_method: AuthMethod::None,
..Default::default() ..Default::default()
})) },
.unwrap(); ))?;
} }
} }
@ -435,7 +429,7 @@ impl PlantCtrlBoardInteraction for PlantCtrlBoard<'_> {
} }
println!("Should be connected now"); println!("Should be connected now");
while !self.wifi_driver.is_up().unwrap() { while !self.wifi_driver.is_up()? {
println!("Waiting for network being up"); println!("Waiting for network being up");
delay.delay_ms(250); delay.delay_ms(250);
counter += 250; counter += 250;
@ -447,7 +441,7 @@ impl PlantCtrlBoardInteraction for PlantCtrlBoard<'_> {
} }
} }
//update freertos registers ;) //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); println!("IP info: {:?}", address);
Ok(address) Ok(address)
} }
@ -568,7 +562,7 @@ impl PlantCtrlBoardInteraction for PlantCtrlBoard<'_> {
Ok(self.wifi_driver.get_scan_result()?) 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.any_pump(true)?;
self.pump(plant, true)?; self.pump(plant, true)?;
unsafe { vTaskDelay(30000) }; unsafe { vTaskDelay(30000) };
@ -622,7 +616,6 @@ impl PlantCtrlBoardInteraction for PlantCtrlBoard<'_> {
fn mqtt(&mut self, config: &Config) -> Result<()> { fn mqtt(&mut self, config: &Config) -> Result<()> {
let last_will_topic = format!("{}/state", config.base_topic); let last_will_topic = format!("{}/state", config.base_topic);
let mqtt_client_config = MqttClientConfiguration { let mqtt_client_config = MqttClientConfiguration {
lwt: Some(LwtConfiguration { lwt: Some(LwtConfiguration {
topic: &last_will_topic, topic: &last_will_topic,
@ -631,23 +624,34 @@ impl PlantCtrlBoardInteraction for PlantCtrlBoard<'_> {
retain: true, retain: true,
}), }),
client_id: Some("plantctrl"), 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 //room for improvement
..Default::default() ..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_ok = Arc::new(AtomicBool::new(false));
let round_trip_topic = format!("{}/internal/roundtrip", config.base_topic); let round_trip_topic = format!("{}/internal/roundtrip", config.base_topic);
let stay_alive_topic = format!("{}/stay_alive", config.base_topic); let stay_alive_topic = format!("{}/stay_alive", config.base_topic);
println!("Round trip topic is {}", round_trip_topic); println!("Round trip topic is {}", round_trip_topic);
println!("Stay alive topic is {}", stay_alive_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 stay_alive_topic_copy = stay_alive_topic.clone();
let round_trip_topic_copy = round_trip_topic.clone(); let round_trip_topic_copy = round_trip_topic.clone();
let round_trip_ok_copy = round_trip_ok.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 = let mut client =
EspMqttClient::new_cb(&config.mqtt_url, &mqtt_client_config, move |event| { EspMqttClient::new_cb(&config.mqtt_url, &mqtt_client_config, move |event| {
let payload = event.payload(); let payload = event.payload();
println!("received mqtt event {:?}", payload);
match payload { match payload {
embedded_svc::mqtt::client::EventPayload::Received { embedded_svc::mqtt::client::EventPayload::Received {
id: _, id: _,
@ -655,6 +659,7 @@ impl PlantCtrlBoardInteraction for PlantCtrlBoard<'_> {
data, data,
details: _, details: _,
} => { } => {
println!("Received something");
let data = String::from_utf8_lossy(data); let data = String::from_utf8_lossy(data);
if let Some(topic) = topic { if let Some(topic) = topic {
//todo use enums //todo use enums
@ -671,11 +676,42 @@ 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
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!("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(round_trip_topic.as_str(), ExactlyOnce)?;
client.subscribe(stay_alive_topic.as_str(), ExactlyOnce)?; client.subscribe(stay_alive_topic.as_str(), ExactlyOnce)?;
//publish to roundtrip //publish to roundtrip
@ -701,8 +737,21 @@ impl PlantCtrlBoardInteraction for PlantCtrlBoard<'_> {
} }
bail!("Mqtt did not complete roundtrip in time"); bail!("Mqtt did not complete roundtrip in time");
} }
false => {
bail!("Mqtt did respond but with failure")
}
}
}
false => {
unsafe { vTaskDelay(10) };
}
}
}
bail!("Mqtt did not fire connection callback in time");
}
fn mqtt_publish(&mut self, config: &Config, subtopic: &str, message: &[u8]) -> Result<()> { fn mqtt_publish(&mut self, config: &Config, subtopic: &str, message: &[u8]) -> Result<()> {
println!("Publishing mqtt {} content {:?}", subtopic, message);
if !subtopic.starts_with("/") { if !subtopic.starts_with("/") {
println!("Subtopic without / at start {}", subtopic); println!("Subtopic without / at start {}", subtopic);
bail!("Subtopic without / at start {}", subtopic); bail!("Subtopic without / at start {}", subtopic);
@ -715,8 +764,8 @@ impl PlantCtrlBoardInteraction for PlantCtrlBoard<'_> {
println!("Not connected to mqtt"); println!("Not connected to mqtt");
bail!("Not connected to mqtt"); bail!("Not connected to mqtt");
} }
let client = self.mqtt_client.as_mut().unwrap(); match &mut self.mqtt_client {
Some(client) => {
let mut full_topic: heapless::String<256> = heapless::String::new(); let mut full_topic: heapless::String<256> = heapless::String::new();
if full_topic.push_str(&config.base_topic).is_err() { if full_topic.push_str(&config.base_topic).is_err() {
println!("Some error assembling full_topic 1"); println!("Some error assembling full_topic 1");
@ -735,74 +784,110 @@ impl PlantCtrlBoardInteraction for PlantCtrlBoard<'_> {
Delay::new(10).delay_ms(50); Delay::new(10).delay_ms(50);
match publish { match publish {
OkStd(message_id) => { OkStd(message_id) => {
println!("Published mqtt topic {} with message {:#?} msgid is {:?}",full_topic, String::from_utf8_lossy(message), message_id); println!(
return Ok(()) "Published mqtt topic {} with message {:#?} msgid is {:?}",
}, full_topic,
Err(err) => { String::from_utf8_lossy(message),
println!("Error during mqtt send on topic {} with message {:#?} error is {:?}",full_topic, String::from_utf8_lossy(message), err); message_id
return Err(err)? );
}, 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> { fn state_charge_percent(&mut self) -> Result<u8> {
match self.battery_driver.state_of_charge() { match &mut self.battery_driver {
Some(driver) => match driver.state_of_charge() {
OkStd(r) => Ok(r), OkStd(r) => Ok(r),
Err(err) => bail!("Error reading SoC {:?}", err), Err(err) => bail!("Error reading SoC {:?}", err),
},
None => bail!("Error reading SoC bq34z100 not found"),
} }
} }
fn remaining_milli_ampere_hour(&mut self) -> Result<u16> { fn remaining_milli_ampere_hour(&mut self) -> Result<u16> {
match self.battery_driver.remaining_capacity() { match &mut self.battery_driver {
Some(driver) => match driver.remaining_capacity() {
OkStd(r) => Ok(r), OkStd(r) => Ok(r),
Err(err) => bail!("Error reading Remaining Capacity {:?}", err), 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> { fn max_milli_ampere_hour(&mut self) -> Result<u16> {
match self.battery_driver.full_charge_capacity() { match &mut self.battery_driver {
Some(driver) => match driver.full_charge_capacity() {
OkStd(r) => Ok(r), OkStd(r) => Ok(r),
Err(err) => bail!("Error reading Full Charge Capacity {:?}", err), 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> { fn design_milli_ampere_hour(&mut self) -> Result<u16> {
match self.battery_driver.design_capacity() { match &mut self.battery_driver {
Some(driver) => match driver.design_capacity() {
OkStd(r) => Ok(r), OkStd(r) => Ok(r),
Err(err) => bail!("Error reading Design Capacity {:?}", err), 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> { fn voltage_milli_volt(&mut self) -> Result<u16> {
return match self.battery_driver.voltage() { match &mut self.battery_driver {
Some(driver) => match driver.voltage() {
OkStd(r) => Ok(r), OkStd(r) => Ok(r),
Err(err) => bail!("Error reading voltage {:?}", err), Err(err) => bail!("Error reading voltage {:?}", err),
}; },
None => bail!("Error reading voltage bq34z100 not found"),
}
} }
fn average_current_milli_ampere(&mut self) -> Result<i16> { fn average_current_milli_ampere(&mut self) -> Result<i16> {
match self.battery_driver.average_current() { match &mut self.battery_driver {
Some(driver) => match driver.average_current() {
OkStd(r) => Ok(r), OkStd(r) => Ok(r),
Err(err) => bail!("Error reading Average Current {:?}", err), Err(err) => bail!("Error reading Average Current {:?}", err),
},
None => bail!("Error reading Average Current bq34z100 not found"),
} }
} }
fn cycle_count(&mut self) -> Result<u16> { fn cycle_count(&mut self) -> Result<u16> {
match self.battery_driver.cycle_count() { match &mut self.battery_driver {
Some(driver) => match driver.cycle_count() {
OkStd(r) => Ok(r), OkStd(r) => Ok(r),
Err(err) => bail!("Error reading Cycle Count {:?}", err), 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> { fn state_health_percent(&mut self) -> Result<u8> {
match self.battery_driver.state_of_health() { match &mut self.battery_driver {
Some(driver) => match driver.state_of_health() {
OkStd(r) => Ok(r as u8), OkStd(r) => Ok(r as u8),
Err(err) => bail!("Error reading State of Health {:?}", err), Err(err) => bail!("Error reading State of Health {:?}", err),
},
None => bail!("Error reading State of Health bq34z100 not found"),
} }
} }
} }
fn print_battery( fn print_battery(
@ -876,8 +961,8 @@ impl CreatePlantHal<'_> for PlantHal {
let driver = I2cDriver::new(i2c, sda, scl, &config).unwrap(); let driver = I2cDriver::new(i2c, sda, scl, &config).unwrap();
let i2c_port = driver.port(); //let i2c_port = driver.port();
esp!(unsafe { esp_idf_sys::i2c_set_timeout(i2c_port, 1048000) }).unwrap(); //esp!(unsafe { esp_idf_sys::i2c_set_timeout(i2c_port, 2)}).unwrap();
let mut battery_driver: Bq34z100g1Driver<I2cDriver, Delay> = Bq34z100g1Driver { let mut battery_driver: Bq34z100g1Driver<I2cDriver, Delay> = Bq34z100g1Driver {
i2c: driver, i2c: driver,
@ -1015,10 +1100,12 @@ impl CreatePlantHal<'_> for PlantHal {
println!("After stuff"); println!("After stuff");
let status = print_battery(&mut battery_driver); //let status = print_battery(&mut battery_driver);
if status.is_err() { //if status.is_err() {
println!("Error communicating with battery!! {:?}", status.err()); // println!("Error communicating with battery!! {:?}", status.err());
} //} else {
// println!("Managed to comunnicate with battery");
//}
let rv = Mutex::new(PlantCtrlBoard { let rv = Mutex::new(PlantCtrlBoard {
shift_register, shift_register,
tank_driver, tank_driver,
@ -1033,7 +1120,8 @@ impl CreatePlantHal<'_> for PlantHal {
signal_counter: counter_unit1, signal_counter: counter_unit1,
wifi_driver, wifi_driver,
mqtt_client: None, mqtt_client: None,
battery_driver, battery_driver: None,
//Some(battery_driver),
}); });
Ok(rv) Ok(rv)
} }

View File

@ -25,12 +25,12 @@ struct SSIDList<'a> {
#[derive(Serialize, Debug)] #[derive(Serialize, Debug)]
struct VersionInfo<'a> { struct VersionInfo<'a> {
git_hash: &'a str, git_hash: &'a str,
build_time: &'a str build_time: &'a str,
} }
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] #[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub struct TestPump{ pub struct TestPump {
pump: usize pump: usize,
} }
pub fn httpd_initial(reboot_now: Arc<AtomicBool>) -> Box<EspHttpServer<'static>> { pub fn httpd_initial(reboot_now: Arc<AtomicBool>) -> Box<EspHttpServer<'static>> {
@ -174,7 +174,7 @@ pub fn shared() -> Box<EspHttpServer<'static>> {
let mut response = request.into_ok_response()?; let mut response = request.into_ok_response()?;
let git_hash = env!("VERGEN_GIT_DESCRIBE"); let git_hash = env!("VERGEN_GIT_DESCRIBE");
let build_time = env!("VERGEN_BUILD_TIMESTAMP"); let build_time = env!("VERGEN_BUILD_TIMESTAMP");
let version_info = VersionInfo{ let version_info = VersionInfo {
git_hash, git_hash,
build_time, build_time,
}; };
@ -273,7 +273,8 @@ pub fn shared() -> Box<EspHttpServer<'static>> {
} }
let actual_data = &buf[0..read.unwrap()]; let actual_data = &buf[0..read.unwrap()];
println!("Raw data {}", from_utf8(actual_data).unwrap()); println!("Raw data {}", from_utf8(actual_data).unwrap());
let pump_test: Result<TestPump, serde_json::Error> = serde_json::from_slice(actual_data); let pump_test: Result<TestPump, serde_json::Error> =
serde_json::from_slice(actual_data);
if pump_test.is_err() { if pump_test.is_err() {
let error_text = pump_test.unwrap_err().to_string(); let error_text = pump_test.unwrap_err().to_string();
println!("Could not parse TestPump {}", error_text); println!("Could not parse TestPump {}", error_text);