Compare commits

...

3 Commits

Author SHA1 Message Date
Priec
83b6465dc6 polishing only 2025-10-05 23:11:28 +02:00
Priec
b4e86bded6 working send/receive to the broker 2025-10-05 21:19:37 +02:00
Priec
73cbf7f912 decoupled publishing via mqtt 2025-10-05 16:04:52 +02:00
6 changed files with 224 additions and 61 deletions

27
final/Cargo.lock generated
View File

@@ -336,7 +336,7 @@ dependencies = [
"embassy-time 0.5.0",
"embedded-io-async",
"embedded-nal-async",
"heapless",
"heapless 0.8.0",
"log",
"managed",
"smoltcp",
@@ -359,7 +359,7 @@ dependencies = [
"embedded-io-async",
"futures-sink",
"futures-util",
"heapless",
"heapless 0.8.0",
]
[[package]]
@@ -373,7 +373,7 @@ dependencies = [
"embedded-io-async",
"futures-core",
"futures-sink",
"heapless",
"heapless 0.8.0",
]
[[package]]
@@ -425,7 +425,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc55c748d16908a65b166d09ce976575fb8852cf60ccd06174092b41064d8f83"
dependencies = [
"embassy-executor",
"heapless",
"heapless 0.8.0",
]
[[package]]
@@ -561,7 +561,7 @@ dependencies = [
"cfg-if",
"esp-config",
"esp-println",
"heapless",
"heapless 0.8.0",
"semihosting",
]
@@ -942,6 +942,16 @@ dependencies = [
"stable_deref_trait",
]
[[package]]
name = "heapless"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b1edcd5a338e64688fbdcb7531a846cfd3476a54784dcb918a0844682bc7ada5"
dependencies = [
"hash32",
"stable_deref_trait",
]
[[package]]
name = "heck"
version = "0.5.0"
@@ -1185,7 +1195,9 @@ dependencies = [
"defmt-rtt",
"dotenvy",
"embassy-executor",
"embassy-futures",
"embassy-net",
"embassy-sync 0.7.2",
"embassy-time 0.5.0",
"embedded-io",
"embedded-io-async",
@@ -1196,6 +1208,7 @@ dependencies = [
"esp-hal-embassy",
"esp-println",
"esp-wifi",
"heapless 0.9.1",
"log",
"rust-mqtt",
"smoltcp",
@@ -1279,7 +1292,7 @@ dependencies = [
"defmt 0.3.100",
"embedded-io",
"embedded-io-async",
"heapless",
"heapless 0.8.0",
"rand_core 0.6.4",
]
@@ -1347,7 +1360,7 @@ dependencies = [
"bitflags 1.3.2",
"byteorder",
"cfg-if",
"heapless",
"heapless 0.8.0",
"log",
"managed",
]

View File

@@ -68,6 +68,9 @@ smoltcp = { version = "0.12.0", default-features = false, features = [
static_cell = "2.1.1"
rust-mqtt = { version = "0.3.0", default-features = false, features = ["no_std"] }
defmt-rtt = "1.0.0"
embassy-futures = "0.1.2"
embassy-sync = "0.7.2"
heapless = "0.9.1"
[build-dependencies]
dotenvy = "0.15.7"

View File

@@ -1,3 +1,5 @@
// src/bin/main.rs
#![no_std]
#![no_main]
#![deny(
@@ -6,18 +8,22 @@
)]
use embassy_executor::Spawner;
use embassy_futures::select::{select, Either};
use embassy_net::{Runner, StackResources};
use embassy_time::{Duration, Timer};
use esp_alloc as _;
use esp_backtrace as _;
use esp_hal::{clock::CpuClock, rng::Rng, timer::timg::TimerGroup};
use esp_wifi::{
EspWifiController,
init,
wifi::{ClientConfiguration, Configuration, WifiController, WifiDevice, WifiEvent, WifiState},
EspWifiController,
};
use log::info;
use projekt_final::mqtt::client::mqtt_task;
use rust_mqtt::packet::v5::publish_packet::QualityOfService;
use projekt_final::mqtt::client::{
mqtt_events, mqtt_publish, mqtt_subscribe, mqtt_task, IncomingMsg,
};
use defmt_rtt as _;
extern crate alloc;
@@ -52,7 +58,8 @@ async fn main(spawner: Spawner) -> ! {
init(timg0.timer0, rng.clone()).unwrap()
);
let (controller, interfaces) = esp_wifi::wifi::new(&esp_wifi_ctrl, peripherals.WIFI).unwrap();
let (controller, interfaces) =
esp_wifi::wifi::new(&esp_wifi_ctrl, peripherals.WIFI).unwrap();
let wifi_interface = interfaces.sta;
@@ -94,8 +101,43 @@ async fn main(spawner: Spawner) -> ! {
spawner.spawn(mqtt_task(stack)).expect("failed to spawn MQTT task");
info!("MQTT task started");
mqtt_publish("esp32/topic", b"hello from ESP32 (init)", QualityOfService::QoS1, false).await;
info!("Sent initial MQTT message");
// Subscribe to your topics (can be done anytime; command is queued)
mqtt_subscribe("esp32/topic").await;
// Get a receiver for incoming MQTT messages
let mqtt_rx = mqtt_events();
loop {
Timer::after(Duration::from_secs(60)).await;
// Drive both: either process an MQTT message or publish periodically
match select(mqtt_rx.receive(), Timer::after(Duration::from_secs(5))).await
{
// Received inbound MQTT message (from broker)
Either::First(msg) => {
handle_incoming(msg);
}
// Time-based example publish
Either::Second(_) => {
// mqtt_publish(
// "esp32/topic",
// b"hello from main",
// QualityOfService::QoS1,
// false,
// )
// .await;
}
}
}
}
fn handle_incoming(msg: IncomingMsg) {
if let Ok(txt) = core::str::from_utf8(&msg.payload) {
info!("MAIN RX [{}]: {}", msg.topic.as_str(), txt);
info!("Received MQTT message -> topic: '{}', payload: '{}'", msg.topic.as_str(), txt);
} else {
info!("MAIN RX [{}]: {:?}", msg.topic.as_str(), msg.payload);
}
}

View File

@@ -1,4 +1,5 @@
// src/mqtt/client.rs
use embassy_futures::select::{select, Either};
use embassy_net::{tcp::TcpSocket, Stack};
use embassy_time::{Duration, Timer};
use log::info;
@@ -9,9 +10,22 @@ use rust_mqtt::packet::v5::reason_codes::ReasonCode;
use rust_mqtt::utils::rng_generator::CountingRng;
use static_cell::ConstStaticCell;
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
use embassy_sync::channel::{Channel, Receiver};
use heapless::{String as HString, Vec as HVec};
use crate::mqtt::config::mqtt_broker_endpoint;
const RECONNECT_DELAY_SECS: u64 = 5;
const KEEPALIVE_SECS: u64 = 60;
const PING_PERIOD: Duration = Duration::from_secs(KEEPALIVE_SECS / 2);
// Limits for small, static buffers (no heap)
pub const TOPIC_MAX: usize = 128;
pub const PAYLOAD_MAX: usize = 512;
const COMMAND_QUEUE: usize = 8;
const EVENT_QUEUE: usize = 8;
// TCP socket buffers (for embassy-net TcpSocket)
static TCP_RX_BUFFER: ConstStaticCell<[u8; 2048]> = ConstStaticCell::new([0; 2048]);
@@ -21,16 +35,72 @@ static TCP_TX_BUFFER: ConstStaticCell<[u8; 2048]> = ConstStaticCell::new([0; 204
static MQTT_TX_BUF: ConstStaticCell<[u8; 1024]> = ConstStaticCell::new([0; 1024]);
static MQTT_RX_BUF: ConstStaticCell<[u8; 1024]> = ConstStaticCell::new([0; 1024]);
// 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.
// Tie TcpSocket lifetime to session, MQTT buffers to 'a (fixes E0521).
type Client<'a, 'net> = MqttClient<'a, TcpSocket<'net>, 8, CountingRng>;
#[derive(Clone)]
struct PublishMsg {
topic: HString<TOPIC_MAX>,
payload: HVec<u8, PAYLOAD_MAX>,
qos: QualityOfService,
retain: bool,
}
#[derive(Clone)]
enum MqttCommand {
Publish(PublishMsg),
Subscribe(HString<TOPIC_MAX>),
}
static CMD_CHAN: Channel<CriticalSectionRawMutex, MqttCommand, COMMAND_QUEUE> = Channel::new();
#[derive(Clone)]
pub struct IncomingMsg {
pub topic: HString<TOPIC_MAX>,
pub payload: HVec<u8, PAYLOAD_MAX>,
}
static EVT_CHAN: Channel<CriticalSectionRawMutex, IncomingMsg, EVENT_QUEUE> = Channel::new();
// Public API for main
pub async fn mqtt_publish(
topic: &str,
payload: &[u8],
qos: QualityOfService,
retain: bool,
) {
let mut t: HString<TOPIC_MAX> = HString::new();
let _ = t.push_str(&topic[..core::cmp::min(topic.len(), TOPIC_MAX)]);
let mut p: HVec<u8, PAYLOAD_MAX> = HVec::new();
let take = core::cmp::min(payload.len(), PAYLOAD_MAX);
let _ = p.extend_from_slice(&payload[..take]);
CMD_CHAN
.send(MqttCommand::Publish(PublishMsg {
topic: t,
payload: p,
qos,
retain,
}))
.await;
}
pub async fn mqtt_subscribe(topic: &str) {
let mut t: HString<TOPIC_MAX> = HString::new();
let _ = t.push_str(&topic[..core::cmp::min(topic.len(), TOPIC_MAX)]);
CMD_CHAN.send(MqttCommand::Subscribe(t)).await;
}
// Receiver for incoming MQTT messages
pub fn mqtt_events(
) -> Receiver<'static, CriticalSectionRawMutex, IncomingMsg, EVENT_QUEUE> {
EVT_CHAN.receiver()
}
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.keep_alive = KEEPALIVE_SECS as u16;
cfg.add_client_id("esp32-client");
cfg
}
@@ -63,28 +133,84 @@ 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",
QualityOfService::QoS1,
false,
)
.await
}
async fn ping_loop(client: &mut Client<'_, '_>) -> Result<(), ReasonCode> {
loop {
if let Err(reason) = client.send_ping().await {
info!("MQTT ping failed: {:?}", reason);
return Err(reason);
// While connected, handle publishes, subscribes, ping, and incoming messages
async fn connected_loop(client: &mut Client<'_, '_>) -> Result<(), ReasonCode> {
// Subscribe to a default topic on connect (optional). You can remove this
// if you always subscribe from main via mqtt_subscribe().
let default_topic = "esp32/topic";
match client.subscribe_to_topic(default_topic).await {
Ok(_) => info!("Subscribed to '{}'", default_topic),
Err(e) => {
info!("Default subscribe failed: {:?}", e);
// Not fatal: continue
}
}
loop {
// Nested select so we react to incoming publishes ASAP, while still
// sending keepalive pings on schedule and servicing commands.
let in_or_ping = async {
select(client.receive_message(), Timer::after(PING_PERIOD)).await
};
match select(CMD_CHAN.receive(), in_or_ping).await {
// Command from main (publish/subscribe)
Either::First(cmd) => match cmd {
MqttCommand::Publish(m) => {
if let Err(e) = client
.send_message(
m.topic.as_str(),
&m.payload,
m.qos,
m.retain,
)
.await
{
return Err(e);
}
}
MqttCommand::Subscribe(topic) => {
match client.subscribe_to_topic(topic.as_str()).await {
Ok(_) => info!("Subscribed to '{}'", topic.as_str()),
Err(e) => {
info!(
"Subscribe failed for '{}': {:?}",
topic.as_str(),
e
);
return Err(e);
}
}
}
},
// Either an incoming publish or the ping timer fired
Either::Second(e) => match e {
// Got a PUBLISH from broker
Either::First(Ok((topic, msg))) => {
let mut t: HString<TOPIC_MAX> = HString::new();
let _ = t.push_str(
&topic[..core::cmp::min(topic.len(), TOPIC_MAX)],
);
let mut p: HVec<u8, PAYLOAD_MAX> = HVec::new();
let take = core::cmp::min(msg.len(), PAYLOAD_MAX);
let _ = p.extend_from_slice(&msg[..take]);
EVT_CHAN
.send(IncomingMsg { topic: t, payload: p })
.await;
}
Either::First(Err(e)) => {
info!("MQTT receive error (reconnect): {:?}", e);
return Err(e);
}
Either::Second(_) => {
client.send_ping().await?;
}
},
}
Timer::after(Duration::from_secs(30)).await;
}
}
// One full MQTT session: TCP connect -> MQTT connect -> (optional) publish -> ping loop
// Full session: TCP connect -> MQTT connect -> connected loop
async fn run_one_session(
stack: Stack<'static>,
tcp_rx: &mut [u8],
@@ -92,13 +218,11 @@ async fn run_one_session(
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"),
@@ -108,14 +232,7 @@ async fn run_one_session(
}
}
// 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(|_| ())
connected_loop(&mut client).await.map_err(|_| ())
}
#[embassy_executor::task]
@@ -123,10 +240,10 @@ 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();
let tcp_rx = TCP_RX_BUFFER.take();
let tcp_tx = TCP_TX_BUFFER.take();
let mqtt_tx = MQTT_TX_BUF.take();
let mqtt_rx = MQTT_RX_BUF.take();
loop {
let _ = run_one_session(

View File

@@ -23,6 +23,7 @@
rustup
cargo-espflash
espup
mosquitto
];
shellHook = ''

View File

@@ -1,13 +0,0 @@
# MQTT Implementation Notes
* WiFi connection runs in a separate task with auto-reconnect functionality
* Network stack operates in a dedicated packet processing task
* MQTT uses TCP socket connection (MqttClient wraps this socket)
* ClientConfig specifies: MQTT version, QoS levels, client ID
* Standard flow: connect_to_broker() → send_message() or subscribe()
## Implementation:
1. Perform DNS lookup for broker hostname
2. Establish TCP socket connection
3. Create MqttClient with configuration
4. Implement connect, publish, and subscribe logic