Skip to content

Rust ​

Use the rumqttc crate to connect Rust services and edge devices to ConnectMQ over TLS.

How it connects ​

Rust service connecting to ConnectMQ A Rust service uses rumqttc crate to connect to broker.connectmq.com over MQTT · TLS 8883 with a username, password and a client ID based on the issued client ID. The broker checks the client with the Broker API (credentials, client ID, ACL and plan limits) and delivers messages to the web console and other devices and services. Your codeEveryone else on the brokerConnectMQ CloudMQTT · TLS 8883username · password · client ID <ISSUED_ID>_<suffix>authRust servicerumqttc cratepublisher.publish(TOPIC, QoS::AtLeastOnce, false, payload)The event loop drives the connection · resubscribe after a reconnectMQTT brokerbroker.connectmq.comTLS 8883 · WSS 8084 /mqtt · MQTT 3.1.1 and 5Broker APICredentials · client IDACL · plan limitsWeb consoleapp.connectmq.com · live topics · alertsDevices & servicesESP32 · ConnectMQ Edge · back ends · appsMQTT messagesConnection check (credentials, client ID, ACL)

Install ​

bash
cargo add rumqttc

The 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 run

Use 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, use rumqttc::AsyncClient and call eventloop.poll().await in a loop instead.
  • rumqttc speaks MQTT 3.1.1 by default; MQTT 5 is available in the rumqttc::v5 module.
  • 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.com on port 1883 without TLS and credentials. The public test broker is readable by anyone, so use it for experiments only.

Fully managed MQTT broker for connected devices.