working send/receive to the broker
This commit is contained in:
@@ -1,3 +1,5 @@
|
|||||||
|
// src/bin/main.rs
|
||||||
|
|
||||||
#![no_std]
|
#![no_std]
|
||||||
#![no_main]
|
#![no_main]
|
||||||
#![deny(
|
#![deny(
|
||||||
@@ -6,19 +8,22 @@
|
|||||||
)]
|
)]
|
||||||
|
|
||||||
use embassy_executor::Spawner;
|
use embassy_executor::Spawner;
|
||||||
|
use embassy_futures::select::{select, Either};
|
||||||
use embassy_net::{Runner, StackResources};
|
use embassy_net::{Runner, StackResources};
|
||||||
use embassy_time::{Duration, Timer};
|
use embassy_time::{Duration, Timer};
|
||||||
use esp_alloc as _;
|
use esp_alloc as _;
|
||||||
use esp_backtrace as _;
|
use esp_backtrace as _;
|
||||||
use esp_hal::{clock::CpuClock, rng::Rng, timer::timg::TimerGroup};
|
use esp_hal::{clock::CpuClock, rng::Rng, timer::timg::TimerGroup};
|
||||||
use esp_wifi::{
|
use esp_wifi::{
|
||||||
EspWifiController,
|
|
||||||
init,
|
init,
|
||||||
wifi::{ClientConfiguration, Configuration, WifiController, WifiDevice, WifiEvent, WifiState},
|
wifi::{ClientConfiguration, Configuration, WifiController, WifiDevice, WifiEvent, WifiState},
|
||||||
|
EspWifiController,
|
||||||
};
|
};
|
||||||
use log::info;
|
use log::info;
|
||||||
use rust_mqtt::packet::v5::publish_packet::QualityOfService;
|
use rust_mqtt::packet::v5::publish_packet::QualityOfService;
|
||||||
use projekt_final::mqtt::client::{mqtt_task, mqtt_publish};
|
use projekt_final::mqtt::client::{
|
||||||
|
mqtt_events, mqtt_publish, mqtt_subscribe, mqtt_task, IncomingMsg,
|
||||||
|
};
|
||||||
use defmt_rtt as _;
|
use defmt_rtt as _;
|
||||||
|
|
||||||
extern crate alloc;
|
extern crate alloc;
|
||||||
@@ -53,7 +58,8 @@ async fn main(spawner: Spawner) -> ! {
|
|||||||
init(timg0.timer0, rng.clone()).unwrap()
|
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;
|
let wifi_interface = interfaces.sta;
|
||||||
|
|
||||||
@@ -95,18 +101,43 @@ async fn main(spawner: Spawner) -> ! {
|
|||||||
spawner.spawn(mqtt_task(stack)).expect("failed to spawn MQTT task");
|
spawner.spawn(mqtt_task(stack)).expect("failed to spawn MQTT task");
|
||||||
info!("MQTT task started");
|
info!("MQTT task started");
|
||||||
|
|
||||||
loop {
|
mqtt_publish("esp32/topic", b"hello from ESP32 (init)", QualityOfService::QoS1, false).await;
|
||||||
// TODO example
|
info!("Sent initial MQTT message");
|
||||||
mqtt_publish(
|
|
||||||
"esp32/topic",
|
|
||||||
b"hello from main",
|
|
||||||
QualityOfService::QoS1,
|
|
||||||
false,
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
|
|
||||||
// Avoid spamming, just an example cadence
|
// Subscribe to your topics (can be done anytime; command is queued)
|
||||||
Timer::after(Duration::from_secs(5)).await;
|
mqtt_subscribe("esp32/topic").await;
|
||||||
|
|
||||||
|
// Get a receiver for incoming MQTT messages
|
||||||
|
let mqtt_rx = mqtt_events();
|
||||||
|
|
||||||
|
loop {
|
||||||
|
// 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);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -9,8 +9,10 @@ use rust_mqtt::packet::v5::publish_packet::QualityOfService;
|
|||||||
use rust_mqtt::packet::v5::reason_codes::ReasonCode;
|
use rust_mqtt::packet::v5::reason_codes::ReasonCode;
|
||||||
use rust_mqtt::utils::rng_generator::CountingRng;
|
use rust_mqtt::utils::rng_generator::CountingRng;
|
||||||
use static_cell::ConstStaticCell;
|
use static_cell::ConstStaticCell;
|
||||||
|
|
||||||
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
|
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
|
||||||
use embassy_sync::channel::Channel;
|
use embassy_sync::channel::{Channel, Receiver};
|
||||||
|
|
||||||
use heapless::{String as HString, Vec as HVec};
|
use heapless::{String as HString, Vec as HVec};
|
||||||
|
|
||||||
use crate::mqtt::config::mqtt_broker_endpoint;
|
use crate::mqtt::config::mqtt_broker_endpoint;
|
||||||
@@ -19,10 +21,11 @@ const RECONNECT_DELAY_SECS: u64 = 5;
|
|||||||
const KEEPALIVE_SECS: u64 = 60;
|
const KEEPALIVE_SECS: u64 = 60;
|
||||||
const PING_PERIOD: Duration = Duration::from_secs(KEEPALIVE_SECS / 2);
|
const PING_PERIOD: Duration = Duration::from_secs(KEEPALIVE_SECS / 2);
|
||||||
|
|
||||||
// Small owned buffers for data from main (no heap, no lifetimes)
|
// Limits for small, static buffers (no heap)
|
||||||
pub const TOPIC_MAX: usize = 128;
|
pub const TOPIC_MAX: usize = 128;
|
||||||
pub const PAYLOAD_MAX: usize = 512;
|
pub const PAYLOAD_MAX: usize = 512;
|
||||||
const PUBLISH_QUEUE: usize = 4;
|
const COMMAND_QUEUE: usize = 8;
|
||||||
|
const EVENT_QUEUE: usize = 8;
|
||||||
|
|
||||||
// TCP socket buffers (for embassy-net TcpSocket)
|
// TCP socket buffers (for embassy-net TcpSocket)
|
||||||
static TCP_RX_BUFFER: ConstStaticCell<[u8; 2048]> = ConstStaticCell::new([0; 2048]);
|
static TCP_RX_BUFFER: ConstStaticCell<[u8; 2048]> = ConstStaticCell::new([0; 2048]);
|
||||||
@@ -32,10 +35,10 @@ static TCP_TX_BUFFER: ConstStaticCell<[u8; 2048]> = ConstStaticCell::new([0; 204
|
|||||||
static MQTT_TX_BUF: ConstStaticCell<[u8; 1024]> = ConstStaticCell::new([0; 1024]);
|
static MQTT_TX_BUF: ConstStaticCell<[u8; 1024]> = ConstStaticCell::new([0; 1024]);
|
||||||
static MQTT_RX_BUF: ConstStaticCell<[u8; 1024]> = ConstStaticCell::new([0; 1024]);
|
static MQTT_RX_BUF: ConstStaticCell<[u8; 1024]> = ConstStaticCell::new([0; 1024]);
|
||||||
|
|
||||||
// NOTE: Tie the TcpSocket lifetime to the session (not 'static), and
|
// Tie TcpSocket lifetime to session, MQTT buffers to 'a (fixes E0521).
|
||||||
// the MQTT buffers lifetime to 'a.
|
|
||||||
type Client<'a, 'net> = MqttClient<'a, TcpSocket<'net>, 8, CountingRng>;
|
type Client<'a, 'net> = MqttClient<'a, TcpSocket<'net>, 8, CountingRng>;
|
||||||
|
|
||||||
|
// ===== Commands from main to MQTT task =====
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
struct PublishMsg {
|
struct PublishMsg {
|
||||||
topic: HString<TOPIC_MAX>,
|
topic: HString<TOPIC_MAX>,
|
||||||
@@ -44,10 +47,28 @@ struct PublishMsg {
|
|||||||
retain: bool,
|
retain: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
static PUB_CHAN: Channel<CriticalSectionRawMutex, PublishMsg, PUBLISH_QUEUE> =
|
#[derive(Clone)]
|
||||||
|
enum MqttCommand {
|
||||||
|
Publish(PublishMsg),
|
||||||
|
Subscribe(HString<TOPIC_MAX>),
|
||||||
|
}
|
||||||
|
|
||||||
|
static CMD_CHAN: Channel<CriticalSectionRawMutex, MqttCommand, COMMAND_QUEUE> =
|
||||||
Channel::new();
|
Channel::new();
|
||||||
|
|
||||||
// Public API for main: enqueue a publish
|
// ===== Events (messages) from MQTT task to main =====
|
||||||
|
#[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 ===
|
||||||
|
|
||||||
|
// Enqueue a publish (non-alloc, copies into small heapless buffers)
|
||||||
pub async fn mqtt_publish(
|
pub async fn mqtt_publish(
|
||||||
topic: &str,
|
topic: &str,
|
||||||
payload: &[u8],
|
payload: &[u8],
|
||||||
@@ -59,16 +80,30 @@ pub async fn mqtt_publish(
|
|||||||
let mut p: HVec<u8, PAYLOAD_MAX> = HVec::new();
|
let mut p: HVec<u8, PAYLOAD_MAX> = HVec::new();
|
||||||
let take = core::cmp::min(payload.len(), PAYLOAD_MAX);
|
let take = core::cmp::min(payload.len(), PAYLOAD_MAX);
|
||||||
let _ = p.extend_from_slice(&payload[..take]);
|
let _ = p.extend_from_slice(&payload[..take]);
|
||||||
PUB_CHAN
|
|
||||||
.send(PublishMsg {
|
CMD_CHAN
|
||||||
|
.send(MqttCommand::Publish(PublishMsg {
|
||||||
topic: t,
|
topic: t,
|
||||||
payload: p,
|
payload: p,
|
||||||
qos,
|
qos,
|
||||||
retain,
|
retain,
|
||||||
})
|
}))
|
||||||
.await;
|
.await;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Enqueue a subscribe request
|
||||||
|
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 (use in main)
|
||||||
|
pub fn mqtt_events(
|
||||||
|
) -> Receiver<'static, CriticalSectionRawMutex, IncomingMsg, EVENT_QUEUE> {
|
||||||
|
EVT_CHAN.receiver()
|
||||||
|
}
|
||||||
|
|
||||||
fn build_client_config() -> ClientConfig<'static, 8, CountingRng> {
|
fn build_client_config() -> ClientConfig<'static, 8, CountingRng> {
|
||||||
let rng = CountingRng(0);
|
let rng = CountingRng(0);
|
||||||
let mut cfg: ClientConfig<'static, 8, _> = ClientConfig::new(MqttVersion::MQTTv5, rng);
|
let mut cfg: ClientConfig<'static, 8, _> = ClientConfig::new(MqttVersion::MQTTv5, rng);
|
||||||
@@ -105,34 +140,86 @@ async fn connect_mqtt(client: &mut Client<'_, '_>) -> Result<(), ReasonCode> {
|
|||||||
client.connect_to_broker().await
|
client.connect_to_broker().await
|
||||||
}
|
}
|
||||||
|
|
||||||
// While connected, either send queued publishes or ping periodically
|
// While connected, handle publishes, subscribes, ping, and incoming messages
|
||||||
async fn connected_loop(client: &mut Client<'_, '_>) -> Result<(), ReasonCode> {
|
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 {
|
loop {
|
||||||
match select(PUB_CHAN.receive(), Timer::after(PING_PERIOD)).await {
|
// Nested select so we react to incoming publishes ASAP, while still
|
||||||
// Got a publish request from main
|
// sending keepalive pings on schedule and servicing commands.
|
||||||
Either::First(cmd) => {
|
let in_or_ping = async {
|
||||||
// QoS1 may read PUBACK, keep all socket I/O here
|
select(client.receive_message(), Timer::after(PING_PERIOD)).await
|
||||||
let res = client
|
};
|
||||||
|
|
||||||
|
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(
|
.send_message(
|
||||||
cmd.topic.as_str(),
|
m.topic.as_str(),
|
||||||
&cmd.payload,
|
&m.payload,
|
||||||
cmd.qos,
|
m.qos,
|
||||||
cmd.retain,
|
m.retain,
|
||||||
)
|
)
|
||||||
.await;
|
.await
|
||||||
if let Err(e) = res {
|
{
|
||||||
return Err(e);
|
return Err(e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Time to ping
|
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;
|
||||||
|
}
|
||||||
|
// Error receiving => reconnect
|
||||||
|
Either::First(Err(e)) => {
|
||||||
|
info!("MQTT receive error (reconnect): {:?}", e);
|
||||||
|
return Err(e);
|
||||||
|
}
|
||||||
|
// Ping timer fired
|
||||||
Either::Second(_) => {
|
Either::Second(_) => {
|
||||||
client.send_ping().await?;
|
client.send_ping().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(
|
async fn run_one_session(
|
||||||
stack: Stack<'static>,
|
stack: Stack<'static>,
|
||||||
tcp_rx: &mut [u8],
|
tcp_rx: &mut [u8],
|
||||||
@@ -140,13 +227,11 @@ async fn run_one_session(
|
|||||||
mqtt_tx: &mut [u8],
|
mqtt_tx: &mut [u8],
|
||||||
mqtt_rx: &mut [u8],
|
mqtt_rx: &mut [u8],
|
||||||
) -> Result<(), ()> {
|
) -> Result<(), ()> {
|
||||||
// Build socket and connect TCP
|
|
||||||
let mut socket = TcpSocket::new(stack, tcp_rx, tcp_tx);
|
let mut socket = TcpSocket::new(stack, tcp_rx, tcp_tx);
|
||||||
if connect_tcp(&mut socket).await.is_err() {
|
if connect_tcp(&mut socket).await.is_err() {
|
||||||
return Err(());
|
return Err(());
|
||||||
}
|
}
|
||||||
|
|
||||||
// Build client and connect MQTT
|
|
||||||
let mut client = build_client(socket, mqtt_tx, mqtt_rx);
|
let mut client = build_client(socket, mqtt_tx, mqtt_rx);
|
||||||
match connect_mqtt(&mut client).await {
|
match connect_mqtt(&mut client).await {
|
||||||
Ok(_) => info!("MQTT CONNACK received"),
|
Ok(_) => info!("MQTT CONNACK received"),
|
||||||
@@ -156,10 +241,7 @@ async fn run_one_session(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// While connected, process publishes and ping. Any error triggers reconnect.
|
connected_loop(&mut client).await.map_err(|_| ())
|
||||||
connected_loop(&mut client)
|
|
||||||
.await
|
|
||||||
.map_err(|_| ())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[embassy_executor::task]
|
#[embassy_executor::task]
|
||||||
@@ -167,10 +249,10 @@ pub async fn mqtt_task(stack: Stack<'static>) {
|
|||||||
info!("MQTT task starting...");
|
info!("MQTT task starting...");
|
||||||
|
|
||||||
// Take static buffers once and reuse across reconnects
|
// Take static buffers once and reuse across reconnects
|
||||||
let mut tcp_rx = TCP_RX_BUFFER.take();
|
let tcp_rx = TCP_RX_BUFFER.take();
|
||||||
let mut tcp_tx = TCP_TX_BUFFER.take();
|
let tcp_tx = TCP_TX_BUFFER.take();
|
||||||
let mut mqtt_tx = MQTT_TX_BUF.take();
|
let mqtt_tx = MQTT_TX_BUF.take();
|
||||||
let mut mqtt_rx = MQTT_RX_BUF.take();
|
let mqtt_rx = MQTT_RX_BUF.take();
|
||||||
|
|
||||||
loop {
|
loop {
|
||||||
let _ = run_one_session(
|
let _ = run_one_session(
|
||||||
|
|||||||
@@ -23,6 +23,7 @@
|
|||||||
rustup
|
rustup
|
||||||
cargo-espflash
|
cargo-espflash
|
||||||
espup
|
espup
|
||||||
|
mosquitto
|
||||||
];
|
];
|
||||||
|
|
||||||
shellHook = ''
|
shellHook = ''
|
||||||
|
|||||||
@@ -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
|
|
||||||
Reference in New Issue
Block a user