Rust
Use the rumqttc crate to connect Rust services and edge devices to ConnectMQ over TLS.
How it connects
Install
bash
cargo add rumqttcThe default features include TLS with rustls.
Publish and subscribe
rust
use rumqttc::{Client, Event, MqttOptions, Packet, QoS, Transport};
use std::{env, thread, time::Duration};
const FILTER: &str = "acme/istanbul/#";
const TOPIC: &str = "acme/istanbul/assembly/line1/rust-01/telemetry";
fn main() {
// Issued client ID + "_" + suffix
let client_id = format!("{}_rust-service", env::var("CMQ_CLIENT_ID").unwrap());
let mut options = MqttOptions::new(client_id, "broker.connectmq.com", 8883);
options.set_keep_alive(Duration::from_secs(60));
options.set_credentials(env::var("CMQ_USERNAME").unwrap(), env::var("CMQ_PASSWORD").unwrap());
// TLS: the system CA store verifies the broker certificate
options.set_transport(Transport::tls_with_default_config());
let (client, mut connection) = Client::new(options, 10);
// Publish a JSON reading every 5 seconds from a second thread
let publisher = client.clone();
thread::spawn(move || loop {
let payload = format!(r#"{{"temperature":{}}}"#, 21.5);
if let Err(e) = publisher.publish(TOPIC, QoS::AtLeastOnce, false, payload) {
eprintln!("publish: {e}");
}
thread::sleep(Duration::from_secs(5));
});
// Drive the connection: rumqttc reconnects on the next iteration after an error
for event in connection.iter() {
match event {
// Subscribe after every (re)connect: a clean session has no subscriptions
Ok(Event::Incoming(Packet::ConnAck(_))) => {
client.subscribe(FILTER, QoS::AtLeastOnce).unwrap();
}
Ok(Event::Incoming(Packet::Publish(p))) => {
println!("{}: {}", p.topic, String::from_utf8_lossy(&p.payload));
}
Ok(_) => {}
Err(e) => {
eprintln!("connection error: {e}, retrying");
thread::sleep(Duration::from_secs(2));
}
}
}
}bash
CMQ_CLIENT_ID=connectmq_client_123456 CMQ_USERNAME=cmq_xxxx CMQ_PASSWORD='...' cargo runUse your issued client ID
The client ID must be your issued client ID plus a suffix, unique per process. Any other ID is refused with Client identifier not valid (0x85) (why).
Notes
- Nothing is sent or received unless you keep iterating
connection. In async code, userumqttc::AsyncClientand calleventloop.poll().awaitin a loop instead. rumqttcspeaks MQTT 3.1.1 by default; MQTT 5 is available in therumqttc::v5module.- Build JSON payloads with
serde_json::to_vec(&value)when they get bigger than a format string. - Try without an account: connect to
broker.connectmq.comon port 1883 without TLS and credentials. The public test broker is readable by anyone, so use it for experiments only.