Compare commits

...

2 Commits

Author SHA1 Message Date
Priec
e249c39c7b reconnect loop on dropped connection 2025-10-05 15:17:20 +02:00
Priec
3e0801674f split function to multiple functions in mqtt client 2025-10-05 12:24:38 +02:00

View File

@@ -5,62 +5,66 @@ use log::info;
use rust_mqtt::client::client::MqttClient;
use rust_mqtt::client::client_config::{ClientConfig, MqttVersion};
use rust_mqtt::packet::v5::publish_packet::QualityOfService;
use rust_mqtt::packet::v5::reason_codes::ReasonCode;
use rust_mqtt::utils::rng_generator::CountingRng;
use static_cell::ConstStaticCell;
use crate::mqtt::config::mqtt_broker_endpoint;
const RECONNECT_DELAY_SECS: u64 = 5;
// TCP socket buffers (for embassy-net TcpSocket)
static TCP_RX_BUFFER: ConstStaticCell<[u8; 2048]> = ConstStaticCell::new([0; 2048]);
static TCP_TX_BUFFER: ConstStaticCell<[u8; 2048]> = ConstStaticCell::new([0; 2048]);
// MQTT client buffers (separate from the TcpSockets buffers)
// MQTT client buffers (separate from the TcpSocket's buffers)
static MQTT_TX_BUF: ConstStaticCell<[u8; 1024]> = ConstStaticCell::new([0; 1024]);
static MQTT_RX_BUF: ConstStaticCell<[u8; 1024]> = ConstStaticCell::new([0; 1024]);
#[embassy_executor::task]
pub async fn mqtt_task(stack: Stack<'static>) {
info!("MQTT task starting...");
// Type alias for clarity in helper functions
// NOTE: Tie the TcpSocket lifetime to the session (not 'static), and
// the MQTT buffers lifetime to 'a. This resolves the E0521 error.
// The const 8 is the MAX_PROPERTIES generic used by rust-mqtt config.
type Client<'a, 'net> = MqttClient<'a, TcpSocket<'net>, 8, CountingRng>;
let tcp_rx = TCP_RX_BUFFER.take();
let tcp_tx = TCP_TX_BUFFER.take();
let mut socket = TcpSocket::new(stack, tcp_rx, tcp_tx);
match socket.connect(mqtt_broker_endpoint()).await {
Ok(_) => info!("Connected TCP to MQTT broker"),
Err(e) => {
info!("TCP connect failed: {:?}", e);
return;
}
}
let mqtt_tx = MQTT_TX_BUF.take();
let mqtt_rx = MQTT_RX_BUF.take();
// Config
fn build_client_config() -> ClientConfig<'static, 8, CountingRng> {
let rng = CountingRng(0);
let mut cfg: ClientConfig<'static, 8, _> = ClientConfig::new(MqttVersion::MQTTv5, rng);
cfg.keep_alive = 60;
cfg.add_client_id("esp32-client");
// cfg.add_username("user");
// cfg.add_password("pass");
cfg
}
fn build_client<'a, 'net>(
socket: TcpSocket<'net>,
mqtt_tx: &'a mut [u8],
mqtt_rx: &'a mut [u8],
) -> Client<'a, 'net> {
let cfg = build_client_config();
let mqtt_tx_len = mqtt_tx.len();
let mqtt_rx_len = mqtt_rx.len();
MqttClient::new(socket, mqtt_tx, mqtt_tx_len, mqtt_rx, mqtt_rx_len, cfg)
}
let mut client = MqttClient::new(socket, mqtt_tx, mqtt_tx_len, mqtt_rx, mqtt_rx_len, cfg);
// Connect
match client.connect_to_broker().await {
Ok(_) => info!("MQTT CONNACK received"),
Err(reason) => {
info!("MQTT connect failed: {:?}", reason);
return;
async fn connect_tcp<'net>(socket: &mut TcpSocket<'net>) -> Result<(), ()> {
match socket.connect(mqtt_broker_endpoint()).await {
Ok(_) => {
info!("Connected TCP to MQTT broker");
Ok(())
}
Err(e) => {
info!("TCP connect failed: {:?}", e);
Err(())
}
}
}
// Publish simple message
match client
async fn connect_mqtt(client: &mut Client<'_, '_>) -> Result<(), ReasonCode> {
client.connect_to_broker().await
}
async fn publish_once(client: &mut Client<'_, '_>) -> Result<(), ReasonCode> {
client
.send_message(
"esp32/topic",
b"hello from esp32",
@@ -68,16 +72,76 @@ pub async fn mqtt_task(stack: Stack<'static>) {
false,
)
.await
{
Ok(_) => info!("MQTT PUBLISH sent"),
Err(reason) => info!("MQTT publish failed: {:?}", reason),
}
}
async fn ping_loop(client: &mut Client<'_, '_>) -> Result<(), ReasonCode> {
loop {
if let Err(reason) = client.send_ping().await {
info!("MQTT ping failed: {:?}", reason);
break;
return Err(reason);
}
Timer::after(Duration::from_secs(30)).await;
}
}
// One full MQTT session: TCP connect -> MQTT connect -> (optional) publish -> ping loop
async fn run_one_session(
stack: Stack<'static>,
tcp_rx: &mut [u8],
tcp_tx: &mut [u8],
mqtt_tx: &mut [u8],
mqtt_rx: &mut [u8],
) -> Result<(), ()> {
// Build socket and connect TCP
let mut socket = TcpSocket::new(stack, tcp_rx, tcp_tx);
if connect_tcp(&mut socket).await.is_err() {
return Err(());
}
// Build client and connect MQTT
let mut client = build_client(socket, mqtt_tx, mqtt_rx);
match connect_mqtt(&mut client).await {
Ok(_) => info!("MQTT CONNACK received"),
Err(reason) => {
info!("MQTT connect failed: {:?}", reason);
return Err(());
}
}
// Optional demo publish (same behavior as before)
match publish_once(&mut client).await {
Ok(_) => info!("MQTT PUBLISH sent"),
Err(reason) => info!("MQTT publish failed: {:?}", reason),
}
// Keepalive. Any error ends the session; outer loop will reconnect.
ping_loop(&mut client).await.map_err(|_| ())
}
#[embassy_executor::task]
pub async fn mqtt_task(stack: Stack<'static>) {
info!("MQTT task starting...");
// Take static buffers once and reuse across reconnects
let mut tcp_rx = TCP_RX_BUFFER.take();
let mut tcp_tx = TCP_TX_BUFFER.take();
let mut mqtt_tx = MQTT_TX_BUF.take();
let mut mqtt_rx = MQTT_RX_BUF.take();
loop {
let _ = run_one_session(
stack,
&mut tcp_rx[..],
&mut tcp_tx[..],
&mut mqtt_tx[..],
&mut mqtt_rx[..],
)
.await;
info!(
"Reconnecting in {}s after session end/failure",
RECONNECT_DELAY_SECS
);
Timer::after(Duration::from_secs(RECONNECT_DELAY_SECS)).await;
}
}