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_upright": false,
"pads": {
"drill": 0.0,
"height": 3.0,
"width": 1.6
"drill": 0.25,
"height": 0.35,
"width": 0.35
},
"silk_line_width": 0.12,
"silk_text_italic": false,
@ -58,13 +58,15 @@
"width": 0.0
}
],
"drc_exclusions": [],
"drc_exclusions": [
"courtyards_overlap|199080001|128865001|67ac55df-4a92-42f8-90ae-0f317d1fcee5|cfde0667-9234-45fc-8eda-14a18003cf8d"
],
"meta": {
"filename": "board_design_settings.json",
"version": 2
},
"rule_severities": {
"annular_width": "error",
"annular_width": "ignore",
"clearance": "error",
"connection_width": "warning",
"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]
MCU="esp32c6"
# 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"
CARGO_WORKSPACE_DIR = { value = "", relative = true }
RUST_BACKTRACE = "full"

View File

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

View File

@ -5,7 +5,11 @@ use chrono_tz::{Europe::Berlin, Tz};
use esp_idf_hal::delay::Delay;
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 once_cell::sync::Lazy;
@ -127,10 +131,7 @@ fn safe_main() -> anyhow::Result<()> {
println!("Partition count is {}", count);
let mut ota_state: esp_ota_img_states_t = 0;
let running_partition = unsafe { esp_ota_get_running_partition() };
let address = unsafe {
(*running_partition).address
};
let address = unsafe { (*running_partition).address };
println!("Partition address is {}", address);
let ota_state_string = unsafe {
@ -237,10 +238,10 @@ fn safe_main() -> anyhow::Result<()> {
};
println!("attempting to connect wifi");
let mut ip_address: Option<String> = None;
let mut ip_address: Option<String> = None;
match board.wifi(wifi.ssid, wifi.password, 10000) {
Ok(ip_info) => {
ip_address = Some(ip_info.ip.to_string());
ip_address = Some(ip_info.ip.to_string());
online_mode = OnlineMode::Wifi;
}
Err(_) => {
@ -298,16 +299,24 @@ fn safe_main() -> anyhow::Result<()> {
match ip_address {
Some(add_some) => {
let _ = board.mqtt_publish(&config, "/firmware/address", add_some.as_bytes());
},
}
None => {
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/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/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());
publish_battery_state(&mut board, &config);
@ -318,15 +327,23 @@ fn safe_main() -> anyhow::Result<()> {
if tank_state.sensor_error {
let _ = board.mqtt_publish(&config, "/water/ml", "error".to_string().as_bytes());
} else {
let _ = board.mqtt_publish(&config, "/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 _ = board.mqtt_publish(
&config,
"/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 temp:Option<f32> = None;
let mut temp: Option<f32> = None;
for _attempt in 0..5 {
let water_temperature = board.water_temperature_c();
match water_temperature {
@ -346,25 +363,17 @@ fn safe_main() -> anyhow::Result<()> {
water_frozen = true;
}
if online_mode == OnlineMode::Online {
let _ = board.mqtt_publish(
&config,
"/water/temperature",
res.to_string().as_bytes(),
);
let _ =
board.mqtt_publish(&config, "/water/temperature", res.to_string().as_bytes());
}
},
}
None => {
if online_mode == OnlineMode::Online {
let _ = board.mqtt_publish(&config, "/water/temperature", "Error".as_bytes());
}
},
}
}
let mut plantstate = [PlantState {
..Default::default()
}; PLANT_COUNT];
@ -527,40 +536,24 @@ fn safe_main() -> anyhow::Result<()> {
let deep_sleep_duration_minutes: u32 = if state_of_charge < 10 {
if online_mode == OnlineMode::Online {
let _ = board.mqtt_publish(
&config,
"/deepsleep",
"low Volt 12h".as_bytes(),
);
let _ = board.mqtt_publish(&config, "/deepsleep", "low Volt 12h".as_bytes());
}
12 * 60
} else if is_day {
if did_pump {
if online_mode == OnlineMode::Online {
let _ = board.mqtt_publish(
&config,
"/deepsleep",
"after pump".as_bytes(),
);
let _ = board.mqtt_publish(&config, "/deepsleep", "after pump".as_bytes());
}
0
} else {
if online_mode == OnlineMode::Online {
let _ = board.mqtt_publish(
&config,
"/deepsleep",
"normal 20m".as_bytes(),
);
let _ = board.mqtt_publish(&config, "/deepsleep", "normal 20m".as_bytes());
}
20
}
} else {
if online_mode == OnlineMode::Online {
let _ = board.mqtt_publish(
&config,
"/deepsleep",
"night 1h".as_bytes(),
);
let _ = board.mqtt_publish(&config, "/deepsleep", "night 1h".as_bytes());
}
60
};
@ -568,7 +561,6 @@ fn safe_main() -> anyhow::Result<()> {
let _ = board.mqtt_publish(&config, "/state", "sleep".as_bytes());
}
//determine next event
//is light out of work trigger soon?
//is battery low ??
@ -853,18 +845,31 @@ fn determine_state_target_moisture_for_plant(
state.dry = true;
if tank_state.sensor_error && !config.tank_allow_pumping_if_sensor_error {
//ignore is ok
}
else if !tank_state.enough_water {
} else if !tank_state.enough_water {
state.no_water = true;
}
}
let duration = TimeDelta::try_minutes(plant_config.pump_cooldown_min as i64).unwrap();
let next_pump = board.last_pump_time(plant) + duration;
if next_pump > cur {
let europe_time = next_pump.with_timezone(&Berlin);
state.next_pump = Some(europe_time);
state.cooldown = true;
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;
}
}
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(
cur,
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(
plantstate: &mut [PlantState; PLANT_COUNT],
cur: DateTime<Tz>,
@ -909,42 +1008,26 @@ fn determine_next_plant(
);
}
config::Mode::TimerOnly => {
let duration = TimeDelta::try_minutes(plant_config.pump_cooldown_min as i64).unwrap();
let next_pump = board.last_pump_time(plant) + 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 {
state.do_water = true;
}
}
determine_state_timer_only_for_plant(
board,
plant,
state,
config,
tank_state,
water_frozen,
cur,
);
}
config::Mode::TimerAndDeadzone => {
let duration = TimeDelta::try_minutes(plant_config.pump_cooldown_min as i64).unwrap();
let next_pump = board.last_pump_time(plant) + 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(
determine_state_timer_and_deadzone_for_plant(
board,
plant,
state,
config,
tank_state,
water_frozen,
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,20 +1078,31 @@ fn update_plant_state(
);
let last_time = board.last_pump_time(plant);
let europe_time = last_time.with_timezone(&Berlin);
if europe_time.year() > 2023 {
let time = europe_time.to_rfc3339();
let _ = board.mqtt_publish(
&config,
format!("/plant{}/last pump", plant + 1).as_str(),
time.as_bytes(),
);
} else {
let _ = board.mqtt_publish(
&config,
format!("/plant{}/last pump", plant + 1).as_str(),
"N/A".as_bytes(),
);
match last_time {
Some(last_time) => {
let europe_time = last_time.with_timezone(&Berlin);
if europe_time.year() > 2023 {
let time = europe_time.to_rfc3339();
let _ = board.mqtt_publish(
&config,
format!("/plant{}/last pump", plant + 1).as_str(),
time.as_bytes(),
);
} else {
let _ = board.mqtt_publish(
&config,
format!("/plant{}/last pump", plant + 1).as_str(),
"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 {
@ -1121,8 +1215,6 @@ fn update_plant_state(
format!("/plant{}/consecutive pump count", plant + 1).as_str(),
state.consecutive_pump_count.to_string().as_bytes(),
);
}
}
@ -1171,13 +1263,13 @@ fn main() {
Ok(_) => {
println!("Main app finished, restarting");
unsafe { esp_restart() };
},
}
Err(err) => {
println!("Failed main {}", err);
let rollback_successful = rollback_and_reboot();
println!("Failed to rollback :(");
rollback_successful.unwrap();
},
}
}
}
//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::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)
}

View File

@ -25,12 +25,12 @@ struct SSIDList<'a> {
#[derive(Serialize, Debug)]
struct VersionInfo<'a> {
git_hash: &'a str,
build_time: &'a str
build_time: &'a str,
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub struct TestPump{
pump: usize
pub struct TestPump {
pump: usize,
}
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 git_hash = env!("VERGEN_GIT_DESCRIBE");
let build_time = env!("VERGEN_BUILD_TIMESTAMP");
let version_info = VersionInfo{
let version_info = VersionInfo {
git_hash,
build_time,
};
@ -253,39 +253,40 @@ pub fn shared() -> Box<EspHttpServer<'static>> {
})
.unwrap();
server
.fn_handler("/boardtest", Method::Post, move |_| {
let mut board = BOARD_ACCESS.lock().unwrap();
board.test()?;
anyhow::Ok(())
})
.unwrap();
.fn_handler("/boardtest", Method::Post, move |_| {
let mut board = BOARD_ACCESS.lock().unwrap();
board.test()?;
anyhow::Ok(())
})
.unwrap();
server
.fn_handler("/pumptest", Method::Post, |mut request| {
let mut buf = [0_u8; 3072];
let read = request.read(&mut buf);
if read.is_err() {
let error_text = read.unwrap_err().to_string();
println!("Could not parse testrequest {}", error_text);
request
.into_status_response(500)?
.write(error_text.as_bytes())?;
return anyhow::Ok(());
}
let actual_data = &buf[0..read.unwrap()];
println!("Raw data {}", from_utf8(actual_data).unwrap());
let pump_test: Result<TestPump, serde_json::Error> = serde_json::from_slice(actual_data);
if pump_test.is_err() {
let error_text = pump_test.unwrap_err().to_string();
println!("Could not parse TestPump {}", error_text);
request
.into_status_response(500)?
.write(error_text.as_bytes())?;
return Ok(());
}
let mut board = BOARD_ACCESS.lock().unwrap();
board.test_pump(pump_test.unwrap().pump)?;
anyhow::Ok(())
})
.unwrap();
.fn_handler("/pumptest", Method::Post, |mut request| {
let mut buf = [0_u8; 3072];
let read = request.read(&mut buf);
if read.is_err() {
let error_text = read.unwrap_err().to_string();
println!("Could not parse testrequest {}", error_text);
request
.into_status_response(500)?
.write(error_text.as_bytes())?;
return anyhow::Ok(());
}
let actual_data = &buf[0..read.unwrap()];
println!("Raw data {}", from_utf8(actual_data).unwrap());
let pump_test: Result<TestPump, serde_json::Error> =
serde_json::from_slice(actual_data);
if pump_test.is_err() {
let error_text = pump_test.unwrap_err().to_string();
println!("Could not parse TestPump {}", error_text);
request
.into_status_response(500)?
.write(error_text.as_bytes())?;
return Ok(());
}
let mut board = BOARD_ACCESS.lock().unwrap();
board.test_pump(pump_test.unwrap().pump)?;
anyhow::Ok(())
})
.unwrap();
server
}