Back to Docs
📡
MQTT Integration
Combine ALEC compression with MQTT for efficient pub/sub IoT messaging. Reduce bandwidth by 90% while leveraging MQTT's reliability features.
Dependencies
[dependencies]
alec = "1.0"
rumqttc = "0.24" # Or paho-mqtt, mosquitto-rs Publisher (Sensor Side)
use alec::{Encoder, Context, Priority};
use rumqttc::{MqttOptions, Client, QoS};
fn main() {
// ALEC setup
let mut ctx = Context::new();
let encoder = Encoder::new(&mut ctx);
// MQTT setup
let mut mqttoptions = MqttOptions::new("sensor-001", "broker.example.com", 1883);
mqttoptions.set_keep_alive(Duration::from_secs(30));
let (mut client, mut connection) = Client::new(mqttoptions, 10);
// Sensor loop
loop {
let temperature = read_sensor();
let msg = encoder.encode(temperature, Priority::Auto);
// Map ALEC priority to MQTT QoS
let qos = match msg.priority() {
Priority::P1 | Priority::P2 => QoS::ExactlyOnce,
Priority::P3 | Priority::P4 => QoS::AtLeastOnce,
Priority::P5 => QoS::AtMostOnce,
};
client.publish("sensors/temp/001", qos, false, msg.as_bytes()).unwrap();
thread::sleep(Duration::from_secs(10));
}
} Priority to QoS Mapping
- P1/P2 → QoS 2 (Exactly Once) - Critical alerts must arrive
- P3/P4 → QoS 1 (At Least Once) - Important data
- P5 → QoS 0 (At Most Once) - Routine, loss acceptable
Subscriber (Server Side)
use alec::{Decoder, Context};
use rumqttc::{MqttOptions, Client, QoS, Event, Packet};
fn main() {
let mut ctx = Context::new();
let decoder = Decoder::new(&mut ctx);
let (mut client, mut connection) = Client::new(mqttoptions, 10);
client.subscribe("sensors/temp/#", QoS::AtLeastOnce).unwrap();
for notification in connection.iter() {
if let Event::Incoming(Packet::Publish(publish)) = notification {
let value = decoder.decode(&publish.payload).unwrap();
println!("Received: {}", value);
}
}
} Recommended Topic Structure
sensors/
├── {device_id}/
│ ├── raw # Full readings (P4)
│ ├── delta # Delta-encoded (P5)
│ ├── alert # Anomalies (P2)
│ └── critical # Safety alerts (P1)
└── fleet/
└── sync # Context synchronization Retained Messages
Use retained messages for context sync. New subscribers get the latest context state immediately.
Last Will
Configure LWT to notify when a sensor goes offline. Helps with fleet management.