semestralka na tprais
This commit is contained in:
293
tprais_semestralka1/src/bin/main.rs
Normal file
293
tprais_semestralka1/src/bin/main.rs
Normal file
@@ -0,0 +1,293 @@
|
||||
// src/bin/main.rs
|
||||
|
||||
#![no_std]
|
||||
#![no_main]
|
||||
#![deny(
|
||||
clippy::mem_forget,
|
||||
reason = "mem::forget is generally not safe to do with esp_hal types"
|
||||
)]
|
||||
// TODO WARNING core 1 should be logic, core 0 wifi, its flipped now
|
||||
|
||||
use embassy_executor::Spawner;
|
||||
use embassy_futures::select::{select, Either, select3, Either3};
|
||||
use embassy_net::{Runner, StackResources};
|
||||
use embassy_sync::signal::Signal;
|
||||
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
|
||||
use embassy_time::{Duration, Timer, Instant};
|
||||
use projekt_final::bus::I2cInner;
|
||||
use projekt_final::mqtt::client;
|
||||
|
||||
use esp_alloc as _;
|
||||
use esp_backtrace as _;
|
||||
|
||||
use esp_hal::{
|
||||
gpio::InputConfig,
|
||||
clock::CpuClock,
|
||||
gpio::{Input, Pull},
|
||||
i2c::master::{Config as I2cConfig, I2c},
|
||||
rng::Rng,
|
||||
system::{CpuControl, Stack},
|
||||
timer::timg::TimerGroup,
|
||||
};
|
||||
use esp_wifi::{
|
||||
wifi::{ClientConfiguration, Configuration, WifiController, WifiDevice, WifiEvent, WifiState},
|
||||
EspWifiController,
|
||||
};
|
||||
|
||||
use pages_tui::input::Key;
|
||||
use log::info;
|
||||
use rust_mqtt::packet::v5::publish_packet::QualityOfService;
|
||||
use static_cell::StaticCell;
|
||||
use core::cell::RefCell;
|
||||
use heapless::String;
|
||||
use core::fmt::Write;
|
||||
|
||||
use projekt_final::{
|
||||
bus,
|
||||
display,
|
||||
mpu,
|
||||
mqtt::client::{mqtt_events, mqtt_try_publish, mqtt_publish, mqtt_subscribe, mqtt_task, IncomingMsg},
|
||||
};
|
||||
|
||||
extern crate alloc;
|
||||
use alloc::format;
|
||||
|
||||
static I2C_BUS: StaticCell<RefCell<I2cInner>> = StaticCell::new();
|
||||
static APP_CORE_STACK: StaticCell<Stack<8192>> = StaticCell::new();
|
||||
static EXECUTOR_CORE1: StaticCell<esp_hal_embassy::Executor> = StaticCell::new();
|
||||
static NETWORK_READY: Signal<CriticalSectionRawMutex, ()> = Signal::new();
|
||||
|
||||
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
|
||||
}};
|
||||
}
|
||||
|
||||
const SSID: &str = env!("SSID");
|
||||
const PASSWORD: &str = env!("PASSWORD");
|
||||
const MQTT_PUBLISH_DIVIDER: u32 = 10;
|
||||
|
||||
esp_bootloader_esp_idf::esp_app_desc!();
|
||||
|
||||
#[esp_hal_embassy::main]
|
||||
async fn main(spawner: Spawner) -> ! {
|
||||
esp_println::logger::init_logger_from_env();
|
||||
info!("===============================");
|
||||
info!(" ESP32 IoT Firmware Starting");
|
||||
info!("===============================");
|
||||
|
||||
let config = esp_hal::Config::default().with_cpu_clock(CpuClock::max());
|
||||
let peripherals = esp_hal::init(config);
|
||||
esp_alloc::heap_allocator!(size: 72 * 1024);
|
||||
|
||||
info!("Initializing I2C bus...");
|
||||
let i2c = I2c::new(peripherals.I2C0, I2cConfig::default())
|
||||
.expect("Failed to create I2C instance")
|
||||
.with_sda(peripherals.GPIO21)
|
||||
.with_scl(peripherals.GPIO22)
|
||||
.into_async();
|
||||
|
||||
let i2c_bus = I2C_BUS.init(RefCell::new(i2c));
|
||||
let display_i2c = bus::new_device(i2c_bus);
|
||||
let mpu_i2c = bus::new_device(i2c_bus);
|
||||
|
||||
info!("Initializing WiFi...");
|
||||
let timg0 = TimerGroup::new(peripherals.TIMG0);
|
||||
let mut rng = Rng::new(peripherals.RNG);
|
||||
|
||||
let esp_wifi_ctrl = mk_static!(
|
||||
EspWifiController<'static>,
|
||||
esp_wifi::init(timg0.timer0, rng.clone()).unwrap()
|
||||
);
|
||||
|
||||
let (controller, interfaces) =
|
||||
esp_wifi::wifi::new(esp_wifi_ctrl, peripherals.WIFI).unwrap();
|
||||
|
||||
let wifi_interface = interfaces.sta;
|
||||
let timg1 = TimerGroup::new(peripherals.TIMG1);
|
||||
esp_hal_embassy::init([timg1.timer0, timg1.timer1]);
|
||||
|
||||
let seed = (rng.random() as u64) << 32 | rng.random() as u64;
|
||||
|
||||
// Start core 1 for WiFi and MQTT (network stack created there)
|
||||
let mut cpu_control = CpuControl::new(peripherals.CPU_CTRL);
|
||||
let _guard = cpu_control.start_app_core(
|
||||
APP_CORE_STACK.init(Stack::new()),
|
||||
move || {
|
||||
let executor = EXECUTOR_CORE1.init(esp_hal_embassy::Executor::new());
|
||||
executor.run(|spawner| {
|
||||
spawner.spawn(core1_network_task(spawner, controller, wifi_interface, seed)).ok();
|
||||
});
|
||||
}
|
||||
).unwrap();
|
||||
|
||||
// Wait for network to be ready (signaled from core 1)
|
||||
NETWORK_READY.wait().await;
|
||||
info!("Network ready, starting core 0 tasks");
|
||||
|
||||
let config = InputConfig::default().with_pull(Pull::Down);
|
||||
let button_select = Input::new(peripherals.GPIO32, config);
|
||||
let button_next = Input::new(peripherals.GPIO35, config);
|
||||
spawner.spawn(button_detection_task(button_select, button_next)).unwrap();
|
||||
|
||||
// Core 0: display and MPU tasks
|
||||
spawner.spawn(display::task::display_task(display_i2c)).expect("spawn display_task");
|
||||
spawner.spawn(mpu::task::mpu_task(mpu_i2c)).expect("spawn mpu_task");
|
||||
|
||||
display::api::set_status("Booting...").await;
|
||||
mqtt_subscribe("esp32/read").await;
|
||||
mqtt_publish("esp32/imu", b"online", QualityOfService::QoS1, false).await;
|
||||
|
||||
display::api::set_status("Running").await;
|
||||
display::api::set_mqtt_status(true, 0).await;
|
||||
|
||||
let mqtt_rx = mqtt_events();
|
||||
let imu_rx = mpu::api::events();
|
||||
let mut imu_reading_count: u32 = 0;
|
||||
let mut mqtt_msg_count: u32 = 0;
|
||||
let mut mqtt_publish_drops: u32 = 0;
|
||||
let mut last_mqtt_publish = Instant::now();
|
||||
let mqtt_publish_interval = Duration::from_secs(3);
|
||||
|
||||
loop {
|
||||
match select3(
|
||||
mqtt_rx.receive(),
|
||||
imu_rx.receive(),
|
||||
Timer::after(Duration::from_secs(5)),
|
||||
).await {
|
||||
Either3::First(msg) => {
|
||||
mqtt_msg_count += 1;
|
||||
handle_mqtt_message(msg).await;
|
||||
display::api::set_mqtt_status(true, mqtt_msg_count).await;
|
||||
}
|
||||
Either3::Second(mut reading) => {
|
||||
// Drain zabezpečuje, že 'reading' je najčerstvejšia možná hodnota
|
||||
let mut drained = 0;
|
||||
while let Ok(next) = imu_rx.try_receive() {
|
||||
reading = next;
|
||||
drained += 1;
|
||||
}
|
||||
|
||||
imu_reading_count += 1;
|
||||
display::api::show_imu(reading);
|
||||
|
||||
// 3. Nahraďte pôvodnú podmienku týmto časovým zámkom
|
||||
if last_mqtt_publish.elapsed() >= mqtt_publish_interval {
|
||||
let payload = client::encode_imu_json(&reading);
|
||||
client::mqtt_set_imu_payload(payload);
|
||||
last_mqtt_publish = Instant::now();
|
||||
}
|
||||
}
|
||||
Either3::Third(_) => {
|
||||
crate::mpu::api::IMU_CHANNEL.clear();
|
||||
info!("IMU heartbeat: force-cleared queue, {} readings total, {} mqtt drops",
|
||||
imu_reading_count, mqtt_publish_drops);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Runs on core 1 - creates and owns the network stack
|
||||
#[embassy_executor::task]
|
||||
async fn core1_network_task(
|
||||
spawner: Spawner,
|
||||
controller: WifiController<'static>,
|
||||
wifi_interface: WifiDevice<'static>,
|
||||
seed: u64,
|
||||
) {
|
||||
spawner.spawn(connection_task(controller)).ok();
|
||||
|
||||
let net_config = embassy_net::Config::dhcpv4(Default::default());
|
||||
let (stack, runner) = embassy_net::new(
|
||||
wifi_interface,
|
||||
net_config,
|
||||
mk_static!(StackResources<3>, StackResources::<3>::new()),
|
||||
seed,
|
||||
);
|
||||
|
||||
spawner.spawn(net_task(runner)).ok();
|
||||
|
||||
// Wait for network
|
||||
loop {
|
||||
if stack.is_link_up() { break; }
|
||||
Timer::after(Duration::from_millis(500)).await;
|
||||
}
|
||||
loop {
|
||||
if let Some(config) = stack.config_v4() {
|
||||
info!("Got IP: {}", config.address);
|
||||
break;
|
||||
}
|
||||
Timer::after(Duration::from_millis(500)).await;
|
||||
}
|
||||
|
||||
// Signal core 0 that network is ready
|
||||
NETWORK_READY.signal(());
|
||||
|
||||
spawner.spawn(mqtt_task(stack)).ok();
|
||||
}
|
||||
|
||||
async fn handle_mqtt_message(msg: IncomingMsg) {
|
||||
if let Ok(txt) = core::str::from_utf8(&msg.payload) {
|
||||
match txt {
|
||||
"clear" => { display::api::clear().await; }
|
||||
"status" => { mqtt_publish("esp32/status", b"running", QualityOfService::QoS1, false).await; }
|
||||
_ => { display::api::add_chat_message(txt).await; }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[embassy_executor::task]
|
||||
async fn connection_task(mut controller: WifiController<'static>) {
|
||||
loop {
|
||||
if esp_wifi::wifi::wifi_state() == WifiState::StaConnected {
|
||||
controller.wait_for_event(WifiEvent::StaDisconnected).await;
|
||||
Timer::after(Duration::from_millis(5000)).await;
|
||||
}
|
||||
if !matches!(controller.is_started(), Ok(true)) {
|
||||
let client_config = Configuration::Client(ClientConfiguration {
|
||||
ssid: SSID.into(),
|
||||
password: PASSWORD.into(),
|
||||
..Default::default()
|
||||
});
|
||||
controller.set_configuration(&client_config).unwrap();
|
||||
info!("Wi-Fi starting...");
|
||||
controller.start_async().await.unwrap();
|
||||
}
|
||||
match controller.connect_async().await {
|
||||
Ok(_) => info!("Wifi connected!"),
|
||||
Err(e) => {
|
||||
info!("Failed to connect to wifi: {e:#?}");
|
||||
Timer::after(Duration::from_millis(5000)).await
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[embassy_executor::task]
|
||||
async fn net_task(mut runner: Runner<'static, WifiDevice<'static>>) {
|
||||
runner.run().await
|
||||
}
|
||||
|
||||
#[embassy_executor::task]
|
||||
async fn button_detection_task(mut select_btn: Input<'static>, mut next_btn: Input<'static>) {
|
||||
loop {
|
||||
match select(
|
||||
select_btn.wait_for_rising_edge(),
|
||||
next_btn.wait_for_rising_edge(),
|
||||
).await {
|
||||
Either::First(_) => {
|
||||
info!("Detection: GPIO 32 (Select) triggered!");
|
||||
display::api::push_key(Key::enter()).await;
|
||||
}
|
||||
Either::Second(_) => {
|
||||
info!("Detection: GPIO 35 (Next) triggered!");
|
||||
display::api::push_key(Key::tab()).await
|
||||
}
|
||||
}
|
||||
// Debounce: prevent mechanical bouncing from double-triggering
|
||||
embassy_time::Timer::after(embassy_time::Duration::from_millis(200)).await;
|
||||
}
|
||||
}
|
||||
4
tprais_semestralka1/src/lib.rs
Normal file
4
tprais_semestralka1/src/lib.rs
Normal file
@@ -0,0 +1,4 @@
|
||||
#![no_std]
|
||||
extern crate alloc;
|
||||
|
||||
pub mod mqtt;
|
||||
442
tprais_semestralka1/src/mqtt/client.rs
Normal file
442
tprais_semestralka1/src/mqtt/client.rs
Normal file
@@ -0,0 +1,442 @@
|
||||
// src/mqtt/client.rs
|
||||
|
||||
use embassy_net::{tcp::TcpSocket, Stack};
|
||||
use embassy_time::{Duration, Timer, Instant};
|
||||
use embassy_futures::select::{select, Either};
|
||||
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 embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
|
||||
use embassy_sync::mutex::Mutex;
|
||||
use embassy_sync::channel::{Channel, Receiver};
|
||||
use embassy_sync::signal::Signal;
|
||||
use heapless::{String, Vec};
|
||||
use static_cell::ConstStaticCell;
|
||||
use core::fmt::Write;
|
||||
use log::{info, warn};
|
||||
|
||||
use crate::mqtt::config::mqtt_broker_endpoint;
|
||||
use crate::contracts::ImuReading;
|
||||
|
||||
const RECONNECT_DELAY_SECS: u64 = 5;
|
||||
const KEEPALIVE_SECS: u64 = 60;
|
||||
const PING_PERIOD: Duration = Duration::from_secs(KEEPALIVE_SECS / 2);
|
||||
const SOCKET_POLL_TIMEOUT: Duration = Duration::from_secs(1);
|
||||
const PING_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
// Must be > PING_PERIOD, ideally > KEEPALIVE
|
||||
const NO_SUCCESS_TIMEOUT: Duration = Duration::from_secs(120);
|
||||
const NO_IMU_SIG_WARN: Duration = Duration::from_secs(10);
|
||||
const SUBS_MAX: usize = 8;
|
||||
|
||||
// Limits for static buffers
|
||||
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]);
|
||||
static TCP_TX_BUFFER: ConstStaticCell<[u8; 2048]> = ConstStaticCell::new([0; 2048]);
|
||||
|
||||
// MQTT client buffers (separate from the TcpSocket buffers)
|
||||
static MQTT_TX_BUF: ConstStaticCell<[u8; 1024]> = ConstStaticCell::new([0; 1024]);
|
||||
static MQTT_RX_BUF: ConstStaticCell<[u8; 1024]> = ConstStaticCell::new([0; 1024]);
|
||||
|
||||
// Tie TcpSocket lifetime to session
|
||||
type Client<'a, 'net> = MqttClient<'a, TcpSocket<'net>, 8, CountingRng>;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct IncomingMsg {
|
||||
pub topic: String<TOPIC_MAX>,
|
||||
pub payload: Vec<u8, PAYLOAD_MAX>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct PublishMsg {
|
||||
topic: String<TOPIC_MAX>,
|
||||
payload: Vec<u8, PAYLOAD_MAX>,
|
||||
qos: QualityOfService,
|
||||
retain: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
enum Command {
|
||||
Publish(PublishMsg),
|
||||
Subscribe(String<TOPIC_MAX>),
|
||||
}
|
||||
|
||||
// Command/info channels
|
||||
static CMD_CHAN: Channel<CriticalSectionRawMutex, Command, COMMAND_QUEUE> = Channel::new();
|
||||
static EVT_CHAN: Channel<CriticalSectionRawMutex, IncomingMsg, EVENT_QUEUE> = Channel::new();
|
||||
|
||||
/// Latest-value + wake-up semantics for IMU publish payload (single consumer: MQTT task)
|
||||
static IMU_SIG: Signal<CriticalSectionRawMutex, Vec<u8, PAYLOAD_MAX>> = Signal::new();
|
||||
|
||||
static SUBS: Mutex<CriticalSectionRawMutex, Vec<String<TOPIC_MAX>, SUBS_MAX>> =
|
||||
Mutex::new(Vec::new());
|
||||
|
||||
/// Public API
|
||||
|
||||
pub async fn mqtt_publish(topic: &str, payload: &[u8], qos: QualityOfService, retain: bool) {
|
||||
CMD_CHAN
|
||||
.send(Command::Publish(PublishMsg {
|
||||
topic: truncate_str::<TOPIC_MAX>(topic),
|
||||
payload: truncate_payload(payload),
|
||||
qos,
|
||||
retain,
|
||||
}))
|
||||
.await;
|
||||
}
|
||||
|
||||
pub fn mqtt_try_publish(topic: &str, payload: &[u8], qos: QualityOfService, retain: bool) -> bool {
|
||||
CMD_CHAN
|
||||
.try_send(Command::Publish(PublishMsg {
|
||||
topic: truncate_str::<TOPIC_MAX>(topic),
|
||||
payload: truncate_payload(payload),
|
||||
qos,
|
||||
retain,
|
||||
}))
|
||||
.is_ok()
|
||||
}
|
||||
|
||||
pub fn mqtt_set_imu(reading: ImuReading) {
|
||||
// Encode JSON into a bounded buffer (no alloc::format!)
|
||||
let payload = encode_imu_json(&reading);
|
||||
IMU_SIG.signal(payload);
|
||||
}
|
||||
|
||||
pub fn mqtt_set_imu_payload(payload: Vec<u8, PAYLOAD_MAX>) {
|
||||
IMU_SIG.signal(payload);
|
||||
}
|
||||
|
||||
pub fn encode_imu_json(reading: &ImuReading) -> Vec<u8, PAYLOAD_MAX> {
|
||||
let mut s: String<256> = String::new();
|
||||
let _ = write!(
|
||||
&mut s,
|
||||
"{{\"ax\":{:.2},\"ay\":{:.2},\"az\":{:.2},\"gx\":{:.1},\"gy\":{:.1},\"gz\":{:.1},\"t\":{:.1},\"ts\":{}}}",
|
||||
reading.accel_g[0], reading.accel_g[1], reading.accel_g[2],
|
||||
reading.gyro_dps[0], reading.gyro_dps[1], reading.gyro_dps[2],
|
||||
reading.temp_c,
|
||||
reading.timestamp_ms
|
||||
);
|
||||
let mut v: Vec<u8, PAYLOAD_MAX> = Vec::new();
|
||||
let _ = v.extend_from_slice(s.as_bytes());
|
||||
v
|
||||
}
|
||||
|
||||
pub async fn mqtt_subscribe(topic: &str) {
|
||||
let t = truncate_str::<TOPIC_MAX>(topic);
|
||||
{
|
||||
let mut subs = SUBS.lock().await;
|
||||
let exists = subs.iter().any(|s| s.as_str() == t.as_str());
|
||||
if !exists {
|
||||
let _ = subs.push(t.clone());
|
||||
}
|
||||
}
|
||||
CMD_CHAN.send(Command::Subscribe(t)).await;
|
||||
}
|
||||
|
||||
pub fn mqtt_events(
|
||||
) -> Receiver<'static, CriticalSectionRawMutex, IncomingMsg, EVENT_QUEUE> {
|
||||
EVT_CHAN.receiver()
|
||||
}
|
||||
|
||||
/// Internals
|
||||
|
||||
fn truncate_str<const N: usize>(s: &str) -> String<N> {
|
||||
let mut h = String::new();
|
||||
if N == 0 {
|
||||
return h;
|
||||
}
|
||||
if s.len() <= N {
|
||||
let _ = h.push_str(s);
|
||||
return h;
|
||||
}
|
||||
|
||||
let mut cut = N;
|
||||
while cut > 0 && !s.is_char_boundary(cut) {
|
||||
cut -= 1;
|
||||
}
|
||||
let _ = h.push_str(&s[..cut]);
|
||||
h
|
||||
}
|
||||
|
||||
fn truncate_payload(data: &[u8]) -> Vec<u8, PAYLOAD_MAX> {
|
||||
let mut v = Vec::new();
|
||||
let _ = v.extend_from_slice(&data[..data.len().min(PAYLOAD_MAX)]);
|
||||
v
|
||||
}
|
||||
|
||||
async fn handle_command(client: &mut Client<'_, '_>, cmd: Command) -> Result<(), ReasonCode> {
|
||||
match cmd {
|
||||
Command::Publish(msg) => {
|
||||
client
|
||||
.send_message(msg.topic.as_str(), &msg.payload, msg.qos, msg.retain)
|
||||
.await
|
||||
}
|
||||
Command::Subscribe(topic) => {
|
||||
let res = client.subscribe_to_topic(topic.as_str()).await;
|
||||
if res.is_ok() {
|
||||
info!("Subscribed to '{}'", topic);
|
||||
}
|
||||
res
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn handle_incoming(result: Result<(&str, &[u8]), ReasonCode>) -> Result<(), ReasonCode> {
|
||||
let (topic, payload) = result?;
|
||||
let msg = IncomingMsg {
|
||||
topic: truncate_str::<TOPIC_MAX>(topic),
|
||||
payload: truncate_payload(payload),
|
||||
};
|
||||
if EVT_CHAN.try_send(msg).is_err() {
|
||||
warn!("MQTT EVT queue full, dropping incoming message");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
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<(), ()> {
|
||||
let mut socket = TcpSocket::new(stack, tcp_rx, tcp_tx);
|
||||
socket.set_timeout(Some(SOCKET_POLL_TIMEOUT * 10));
|
||||
match socket.connect(mqtt_broker_endpoint()).await {
|
||||
Ok(_) => info!("Connected TCP to MQTT broker"),
|
||||
Err(e) => {
|
||||
info!("TCP connect failed: {:#?}", e);
|
||||
return Err(());
|
||||
}
|
||||
}
|
||||
|
||||
let mut cfg: ClientConfig<8, CountingRng> =
|
||||
ClientConfig::new(MqttVersion::MQTTv5, CountingRng(0));
|
||||
cfg.keep_alive = KEEPALIVE_SECS as u16;
|
||||
cfg.add_client_id("esp32-client");
|
||||
|
||||
let mut client =
|
||||
MqttClient::new(socket, mqtt_tx, mqtt_tx.len(), mqtt_rx, mqtt_rx.len(), cfg);
|
||||
|
||||
match client.connect_to_broker().await {
|
||||
Ok(_) => info!("MQTT CONNACK received"),
|
||||
Err(reason) => {
|
||||
info!("MQTT connect failed: {:?}", reason);
|
||||
return Err(());
|
||||
}
|
||||
}
|
||||
|
||||
// Re-subscribe after every (re)connect
|
||||
let mut subs_snapshot: Vec<String<TOPIC_MAX>, SUBS_MAX> = Vec::new();
|
||||
{
|
||||
let subs = SUBS.lock().await;
|
||||
for t in subs.iter() {
|
||||
let _ = subs_snapshot.push(t.clone());
|
||||
}
|
||||
}
|
||||
for t in subs_snapshot.iter() {
|
||||
match client.subscribe_to_topic(t.as_str()).await {
|
||||
Ok(_) => info!("Subscribed to '{}'", t),
|
||||
Err(e) => {
|
||||
warn!("MQTT resubscribe failed: {:?}", e);
|
||||
return Err(());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut next_ping_at = Instant::now() + PING_PERIOD;
|
||||
let cmd_rx = CMD_CHAN.receiver();
|
||||
|
||||
// Only restart the session after N consecutive IMU publish failures
|
||||
let mut imu_tx_fail_streak: u8 = 0;
|
||||
let mut hb_at = Instant::now() + Duration::from_secs(10);
|
||||
let mut tx_ok: u32 = 0;
|
||||
let mut tx_err: u32 = 0;
|
||||
let mut rx_ok: u32 = 0;
|
||||
let mut ping_ok: u32 = 0;
|
||||
let mut last_ok = Instant::now(); // last successful MQTT I/O (tx/rx/ping)
|
||||
let mut last_imu_sig = Instant::now(); // last time we received IMU_SIG in MQTT task
|
||||
|
||||
loop {
|
||||
let now = Instant::now();
|
||||
|
||||
if now - last_ok > NO_SUCCESS_TIMEOUT {
|
||||
warn!(
|
||||
"MQTT no successful I/O for {:?} -> restart session",
|
||||
now - last_ok
|
||||
);
|
||||
return Err(());
|
||||
}
|
||||
|
||||
if now - last_imu_sig > NO_IMU_SIG_WARN {
|
||||
// This is diagnostic: if core0 claims it's sending, but this prints, you have cross-core signaling loss.
|
||||
warn!(
|
||||
"MQTT hasn't received IMU_SIG for {:?} (core0->core1 sync likely broken)",
|
||||
now - last_imu_sig
|
||||
);
|
||||
// Rate-limit the warning
|
||||
last_imu_sig = now;
|
||||
}
|
||||
|
||||
let ping_in = if next_ping_at > now { next_ping_at - now } else { Duration::from_secs(0) };
|
||||
|
||||
// Timebox receive_message() even if lower layers misbehave.
|
||||
let recv_fut = async {
|
||||
match select(client.receive_message(), Timer::after(SOCKET_POLL_TIMEOUT)).await {
|
||||
Either::First(res) => Some(res),
|
||||
Either::Second(_) => None,
|
||||
}
|
||||
};
|
||||
|
||||
// 4-way select using nested selects to avoid relying on select4()
|
||||
match select(
|
||||
select(cmd_rx.receive(), IMU_SIG.wait()),
|
||||
select(recv_fut, Timer::after(ping_in)),
|
||||
)
|
||||
.await
|
||||
{
|
||||
// Command received
|
||||
Either::First(Either::First(cmd)) => {
|
||||
handle_command(&mut client, cmd).await.map_err(|_| ())?;
|
||||
next_ping_at = Instant::now() + PING_PERIOD;
|
||||
last_ok = Instant::now();
|
||||
|
||||
// Drain any additional queued commands quickly
|
||||
while let Ok(cmd) = CMD_CHAN.try_receive() {
|
||||
handle_command(&mut client, cmd).await.map_err(|_| ())?;
|
||||
last_ok = Instant::now();
|
||||
next_ping_at = Instant::now() + PING_PERIOD;
|
||||
}
|
||||
}
|
||||
|
||||
// IMU update signaled (latest value semantics)
|
||||
Either::First(Either::Second(payload)) => {
|
||||
last_imu_sig = Instant::now();
|
||||
// Enable temporarily for diagnostics:
|
||||
// info!("IMU_SIG received in MQTT task (len={})", payload.len());
|
||||
|
||||
// Timebox the publish so we don't hang forever inside send_message().await
|
||||
let send_res = match select(
|
||||
client.send_message("esp32/imu", &payload, QualityOfService::QoS0, false),
|
||||
Timer::after(Duration::from_secs(5)),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Either::First(res) => res,
|
||||
Either::Second(_) => Err(ReasonCode::NetworkError),
|
||||
};
|
||||
|
||||
match send_res {
|
||||
Ok(_) => {
|
||||
next_ping_at = Instant::now() + PING_PERIOD;
|
||||
imu_tx_fail_streak = 0;
|
||||
last_ok = Instant::now();
|
||||
|
||||
tx_ok = tx_ok.wrapping_add(1);
|
||||
if (tx_ok % 10) == 0 {
|
||||
info!(
|
||||
"MQTT alive: tx_ok={} tx_err={} rx_ok={} streak={}",
|
||||
tx_ok, tx_err, rx_ok, imu_tx_fail_streak
|
||||
);
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
tx_err = tx_err.wrapping_add(1);
|
||||
imu_tx_fail_streak = imu_tx_fail_streak.saturating_add(1);
|
||||
warn!("MQTT IMU TX fail {}/5: {:?}", imu_tx_fail_streak, e);
|
||||
|
||||
if imu_tx_fail_streak >= 5 {
|
||||
warn!("MQTT IMU TX fail 5x -> restart session");
|
||||
return Err(());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Incoming message (or None on timeout)
|
||||
Either::Second(Either::First(opt)) => {
|
||||
if let Some(res) = opt {
|
||||
match res {
|
||||
Ok((topic, payload)) => {
|
||||
rx_ok = rx_ok.wrapping_add(1);
|
||||
let _ = handle_incoming(Ok((topic, payload))).await;
|
||||
|
||||
last_ok = Instant::now();
|
||||
imu_tx_fail_streak = 0;
|
||||
next_ping_at = Instant::now() + PING_PERIOD;
|
||||
}
|
||||
Err(ReasonCode::NetworkError) => {
|
||||
// idle tick
|
||||
}
|
||||
Err(e) => {
|
||||
warn!("MQTT receive error (fatal): {:?}", e);
|
||||
return Err(());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Ping timer fired
|
||||
Either::Second(Either::Second(_)) => {
|
||||
if Instant::now() >= hb_at {
|
||||
info!(
|
||||
"MQTT hb tx_ok={} tx_err={} rx_ok={} ping_ok={} streak={}",
|
||||
tx_ok, tx_err, rx_ok, ping_ok, imu_tx_fail_streak
|
||||
);
|
||||
hb_at = Instant::now() + Duration::from_secs(10);
|
||||
}
|
||||
|
||||
let ping_res = match select(client.send_ping(), Timer::after(PING_TIMEOUT)).await {
|
||||
Either::First(res) => res,
|
||||
Either::Second(_) => Err(ReasonCode::NetworkError),
|
||||
};
|
||||
|
||||
match ping_res {
|
||||
Ok(_) => {
|
||||
ping_ok = ping_ok.wrapping_add(1);
|
||||
imu_tx_fail_streak = 0;
|
||||
last_ok = Instant::now();
|
||||
next_ping_at = Instant::now() + PING_PERIOD;
|
||||
}
|
||||
Err(e) => {
|
||||
warn!("MQTT ping failed/timeout: {:?}", e);
|
||||
return Err(());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[embassy_executor::task]
|
||||
pub async fn mqtt_task(stack: Stack<'static>) {
|
||||
info!("MQTT task starting...");
|
||||
|
||||
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(
|
||||
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;
|
||||
}
|
||||
}
|
||||
122
tprais_semestralka1/src/mqtt/config.rs
Normal file
122
tprais_semestralka1/src/mqtt/config.rs
Normal file
@@ -0,0 +1,122 @@
|
||||
// src/mqtt/config.rs
|
||||
#![allow(dead_code)]
|
||||
|
||||
use embassy_net::{IpAddress, Ipv4Address, Ipv6Address};
|
||||
|
||||
// Compile-time values injected by build.rs
|
||||
const BROKER_IP: &str = env!("BROKER_IP");
|
||||
const BROKER_PORT: &str = env!("BROKER_PORT");
|
||||
|
||||
pub fn mqtt_broker_endpoint() -> (IpAddress, u16) {
|
||||
(parse_ip(BROKER_IP), parse_port(BROKER_PORT))
|
||||
}
|
||||
|
||||
fn parse_port(s: &str) -> u16 {
|
||||
let p: u16 = s
|
||||
.parse()
|
||||
.unwrap_or_else(|_| panic!("BROKER_PORT must be a valid u16 (1..=65535)"));
|
||||
assert!(p != 0, "BROKER_PORT cannot be 0");
|
||||
p
|
||||
}
|
||||
|
||||
fn parse_ip(s: &str) -> IpAddress {
|
||||
if s.contains(':') {
|
||||
IpAddress::Ipv6(parse_ipv6(s))
|
||||
} else {
|
||||
IpAddress::Ipv4(parse_ipv4(s))
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_ipv4(s: &str) -> Ipv4Address {
|
||||
let mut it = s.split('.');
|
||||
let a = parse_octet(it.next(), 1);
|
||||
let b = parse_octet(it.next(), 2);
|
||||
let c = parse_octet(it.next(), 3);
|
||||
let d = parse_octet(it.next(), 4);
|
||||
assert!(it.next().is_none(), "Too many IPv4 octets");
|
||||
Ipv4Address::new(a, b, c, d)
|
||||
}
|
||||
|
||||
fn parse_octet(part: Option<&str>, idx: usize) -> u8 {
|
||||
let p = part.unwrap_or_else(|| panic!("IPv4 missing octet {}", idx));
|
||||
let v: u16 = p
|
||||
.parse()
|
||||
.unwrap_or_else(|_| panic!("Invalid IPv4 octet {}: {}", idx, p));
|
||||
assert!(v <= 255, "IPv4 octet {} out of range: {}", idx, v);
|
||||
v as u8
|
||||
}
|
||||
|
||||
// Minimal IPv6 parser with '::' compression. Does not handle IPv4-embedded IPv6.
|
||||
fn parse_ipv6(s: &str) -> Ipv6Address {
|
||||
assert!(
|
||||
!s.contains('.'),
|
||||
"IPv4-embedded IPv6 like ::ffff:192.0.2.1 not supported; \
|
||||
use pure hex IPv6"
|
||||
);
|
||||
|
||||
let has_double = s.contains("::");
|
||||
let (left_s, right_s) = if has_double {
|
||||
let mut sp = s.splitn(2, "::");
|
||||
(sp.next().unwrap_or(""), sp.next().unwrap_or(""))
|
||||
} else {
|
||||
(s, "")
|
||||
};
|
||||
|
||||
let mut left = [0u16; 8];
|
||||
let mut right = [0u16; 8];
|
||||
let mut ll = 0usize;
|
||||
let mut rl = 0usize;
|
||||
|
||||
if !left_s.is_empty() {
|
||||
for part in left_s.split(':') {
|
||||
left[ll] = parse_group(part);
|
||||
ll += 1;
|
||||
assert!(ll <= 8, "Too many IPv6 groups on the left");
|
||||
}
|
||||
}
|
||||
|
||||
if !right_s.is_empty() {
|
||||
for part in right_s.split(':') {
|
||||
right[rl] = parse_group(part);
|
||||
rl += 1;
|
||||
assert!(rl <= 8, "Too many IPv6 groups on the right");
|
||||
}
|
||||
}
|
||||
|
||||
let zeros = if has_double {
|
||||
assert!(ll + rl < 8, "Invalid IPv6 '::' usage");
|
||||
8 - (ll + rl)
|
||||
} else {
|
||||
assert!(ll == 8, "IPv6 must have 8 groups without '::'");
|
||||
0
|
||||
};
|
||||
|
||||
let mut g = [0u16; 8];
|
||||
let mut idx = 0usize;
|
||||
|
||||
for i in 0..ll {
|
||||
g[idx] = left[i];
|
||||
idx += 1;
|
||||
}
|
||||
for _ in 0..zeros {
|
||||
g[idx] = 0;
|
||||
idx += 1;
|
||||
}
|
||||
for i in 0..rl {
|
||||
g[idx] = right[i];
|
||||
idx += 1;
|
||||
}
|
||||
assert!(idx == 8, "IPv6 did not resolve to 8 groups");
|
||||
|
||||
Ipv6Address::new(g[0], g[1], g[2], g[3], g[4], g[5], g[6], g[7])
|
||||
}
|
||||
|
||||
fn parse_group(part: &str) -> u16 {
|
||||
assert!(
|
||||
!part.is_empty(),
|
||||
"Empty IPv6 group (use '::' instead for compression)"
|
||||
);
|
||||
assert!(part.len() <= 4, "IPv6 group too long: {}", part);
|
||||
u16::from_str_radix(part, 16)
|
||||
.unwrap_or_else(|_| panic!("Invalid IPv6 hex group: {}", part))
|
||||
}
|
||||
4
tprais_semestralka1/src/mqtt/mod.rs
Normal file
4
tprais_semestralka1/src/mqtt/mod.rs
Normal file
@@ -0,0 +1,4 @@
|
||||
// src/mqtt/mod.rs
|
||||
|
||||
pub mod client;
|
||||
pub mod config;
|
||||
Reference in New Issue
Block a user