6 Commits

Author SHA1 Message Date
bd257b89f0 implement async mqtt config update trigger and fix mqtt.rs corruption 2026-05-10 17:55:53 +02:00
4debbfb39e feat: implement config update via MQTT trigger 2026-05-10 17:35:30 +02:00
d83189417a feat: store MQTT config update payload 2026-05-10 17:30:02 +02:00
3c92cf0c26 feat: publish current config to MQTT 2026-05-10 17:25:32 +02:00
96023c8dc3 Merge branch 'refactor/mkstatic-util' into legacy/v3-support 2026-05-10 14:04:25 +02:00
7497a8c05d refactor: create util module with shared mk_static
- use crate::util::mk_static in network module
- use crate::util::mk_static in mqtt module
- use crate::util::mk_static in hal module
- remove dead mk_static macro from esp module
2026-05-10 14:01:57 +02:00
6 changed files with 81 additions and 37 deletions

View File

@@ -120,15 +120,6 @@ pub struct Esp<'a> {
// CPU cores/threads, reconsider this.
unsafe impl Send for Esp<'_> {}
macro_rules! mk_static {
($t:ty,$val:expr) => {{
static STATIC_CELL: static_cell::StaticCell<$t> = static_cell::StaticCell::new();
#[deny(unused_attributes)]
let x = STATIC_CELL.uninit().write(($val));
x
}};
}
impl Esp<'_> {
pub fn get_time(&self) -> DateTime<Utc> {
DateTime::from_timestamp_micros(self.rtc.current_time_us() as i64)

View File

@@ -282,14 +282,7 @@ pub struct FreePeripherals<'a> {
pub adc1: ADC1<'a>,
}
macro_rules! mk_static {
($t:ty,$val:expr) => {{
static STATIC_CELL: static_cell::StaticCell<$t> = static_cell::StaticCell::new();
#[deny(unused_attributes)]
let x = STATIC_CELL.uninit().write(($val));
x
}};
}
use crate::util::mk_static;
impl PlantHal {
pub async fn create() -> Result<Mutex<CriticalSectionRawMutex, HAL<'static>>, FatError> {

View File

@@ -71,6 +71,7 @@ mod mqtt;
mod network;
mod plant_state;
mod tank;
mod util;
mod webserver;
extern crate alloc;
@@ -267,6 +268,7 @@ async fn safe_main(spawner: Spawner) -> FatResult<()> {
publish_firmware_info(&mut board, version, ip_address, &timezone_time.to_rfc3339()).await;
publish_battery_state(&mut board).await;
let _ = publish_mppt_state(&mut board).await;
publish_config(&mut board).await;
}
log(
@@ -803,6 +805,21 @@ async fn publish_battery_state(
}
}
async fn publish_config(
board: &mut MutexGuard<'_, CriticalSectionRawMutex, HAL<'_>>,
) {
let config = board.board_hal.get_config();
match serde_json::to_string(&config) {
Ok(serialized) => {
let _ = mqtt::publish("/config", &serialized).await;
}
Err(err) => {
info!("Error serializing config: {}", err);
}
}
}
async fn wait_infinity(
board: MutexGuard<'_, CriticalSectionRawMutex, HAL<'static>>,
wait_type: WaitType,

View File

@@ -4,10 +4,12 @@ use crate::fat_error::{ContextExt, FatError, FatResult};
use crate::hal::PlantHal;
use crate::log::{log, LogMessage};
use alloc::string::String;
use alloc::{format, string::ToString};
use alloc::{format, string::ToString, vec::Vec};
use core::sync::atomic::Ordering;
use embassy_executor::Spawner;
use embassy_net::Stack;
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
use embassy_sync::mutex::Mutex;
use embassy_sync::once_lock::OnceLock;
use embassy_time::{Duration, Timer, WithTimeout};
use log::info;
@@ -37,6 +39,7 @@ static MQTT_CONNECTED_EVENT_RECEIVED: AtomicBool = AtomicBool::new(false);
static MQTT_ROUND_TRIP_RECEIVED: AtomicBool = AtomicBool::new(false);
pub static MQTT_STAY_ALIVE: AtomicBool = AtomicBool::new(false);
static MQTT_BASE_TOPIC: OnceLock<String> = OnceLock::new();
static MQTT_CONFIG_UPDATE_PAYLOAD: Mutex<CriticalSectionRawMutex, Option<String>> = Mutex::new(None);
pub fn is_stay_alive() -> bool {
MQTT_STAY_ALIVE.load(Ordering::Relaxed)
@@ -110,14 +113,7 @@ async fn publish_inner(subtopic: &str, message: &str) -> FatResult<()> {
}
}
macro_rules! mk_static {
($t:ty,$val:expr) => {{
static STATIC_CELL: static_cell::StaticCell<$t> = static_cell::StaticCell::new();
#[deny(unused_attributes)]
let x = STATIC_CELL.uninit().write(($val));
x
}};
}
use crate::util::mk_static;
pub async fn mqtt_init(
network_config: &'static NetworkConfig,
@@ -148,6 +144,8 @@ pub async fn mqtt_init(
let last_will_topic = format!("{base_topic}/state");
let round_trip_topic = format!("{base_topic}/internal/roundtrip");
let stay_alive_topic = format!("{base_topic}/stay_alive");
let config_update_payload_topic = format!("{base_topic}/config/update_payload");
let config_update_topic = format!("{base_topic}/config/update");
let mut builder: McutieBuilder<'_, String, PublishDisplay<String, &str>, 0> =
McutieBuilder::new(stack, "plant ctrl", mqtt_url);
@@ -166,10 +164,12 @@ pub async fn mqtt_init(
//TODO make configurable
builder = builder.with_device_id("plantctrl");
let builder: McutieBuilder<'_, String, PublishDisplay<String, &str>, 2> = builder
let builder: McutieBuilder<'_, String, PublishDisplay<String, &str>, 4> = builder
.with_subscriptions([
Topic::General(round_trip_topic.clone()),
Topic::General(stay_alive_topic.clone()),
Topic::General(config_update_payload_topic.clone()),
Topic::General(config_update_topic.clone()),
]);
let keep_alive = Duration::from_secs(60 * 60 * 2).as_secs() as u16;
@@ -179,6 +179,8 @@ pub async fn mqtt_init(
receiver,
round_trip_topic.clone(),
stay_alive_topic.clone(),
config_update_payload_topic.clone(),
config_update_topic.clone(),
)?);
spawner.spawn(mqtt_runner(task)?);
@@ -225,7 +227,7 @@ pub async fn mqtt_init(
#[embassy_executor::task]
async fn mqtt_runner(
task: McutieTask<'static, String, PublishDisplay<'static, String, &'static str>, 2>,
task: McutieTask<'static, String, PublishDisplay<'static, String, &'static str>, 4>,
) {
task.run().await;
}
@@ -235,6 +237,8 @@ async fn mqtt_incoming_task(
receiver: McutieReceiver,
round_trip_topic: String,
stay_alive_topic: String,
config_update_payload_topic: String,
config_update_topic: String,
) {
loop {
let message = receiver.receive().await;
@@ -260,6 +264,43 @@ async fn mqtt_incoming_task(
};
log(LogMessage::MqttStayAliveRec, a, 0, "", "");
MQTT_STAY_ALIVE.store(value, Ordering::Relaxed);
} else if subtopic.eq(config_update_payload_topic.as_str()) {
let payload_str = String::from_utf8_lossy(&payload[..]).to_string();
let mut buffer = MQTT_CONFIG_UPDATE_PAYLOAD.lock().await;
*buffer = Some(payload_str);
info!("MQTT config update payload received");
} else if subtopic.eq(config_update_topic.as_str()) {
let update_requested = payload.eq_ignore_ascii_case("true".as_ref())
|| payload.eq_ignore_ascii_case("1".as_ref());
if update_requested {
info!("MQTT config update requested");
let payload_lock = MQTT_CONFIG_UPDATE_PAYLOAD.lock().await;
if let Some(payload_str) = payload_lock.as_ref() {
match serde_json::from_str::<crate::config::PlantControllerConfig>(payload_str) {
Ok(config) => {
info!("Deserialized config, applying...");
let board_mutex = crate::BOARD_ACCESS.get().await;
let mut board = board_mutex.lock().await;
if let Err(e) = board.board_hal.get_esp().save_config(payload_str.as_bytes().to_vec()).await {
info!("Error saving config to flash: {}", e);
let _ = publish("/config/update", "false").await;
} else {
board.board_hal.set_config(config);
info!("Config applied, rebooting");
let _ = publish("/config/update", "false").await;
board.board_hal.get_esp().deep_sleep_ms(0);
}
}
Err(e) => {
info!("Error deserializing config: {}", e);
let _ = publish("/config/update", "false").await;
}
}
} else {
info!("No config update payload available");
let _ = publish("/config/update", "false").await;
}
}
} else {
log(LogMessage::UnknownTopic, 0, 0, "", &topic);
}

View File

@@ -3,6 +3,7 @@ use crate::config::NetworkConfig;
use crate::fat_error::{ContextExt, FatError, FatResult};
use crate::hal::{PlantHal, HAL};
use crate::mqtt;
use crate::util::mk_static;
use alloc::string::{String, ToString};
use alloc::sync::Arc;
use chrono::{DateTime, Utc};
@@ -196,15 +197,6 @@ pub(crate) async fn run_dhcp(stack: Stack<'static>, ip: Ipv4Addr) {
}
}
macro_rules! mk_static {
($t:ty,$val:expr) => {{
static STATIC_CELL: static_cell::StaticCell<$t> = static_cell::StaticCell::new();
#[deny(unused_attributes)]
let x = STATIC_CELL.uninit().write(($val));
x
}};
}
pub async fn wifi_ap(
ssid: String,
interface_ap: Interface<'static>,

10
rust/src/util.rs Normal file
View File

@@ -0,0 +1,10 @@
macro_rules! mk_static {
($t:ty,$val:expr) => {{
static STATIC_CELL: static_cell::StaticCell<$t> = static_cell::StaticCell::new();
#[deny(unused_attributes)]
let x = STATIC_CELL.uninit().write(($val));
x
}};
}
pub(crate) use mk_static;