mqtt connection with native certs in rust

main.rs
use rumqtt::{MqttOptions, TlsConfiguration, Client, Notification};
use std::error::Error;
use std::time::Duration;

fn main() -> Result<(), Box<dyn Error>> {
    let ca = include_bytes!("mqtt-ca.pem");
    let cert = include_bytes!("mqtt-cert.pem");
    let key = include_bytes!("mqtt-key.pem");

    let mut mqtt_options = MqttOptions::new("test-1", "127.0.0.1", 1883);
    mqtt_options.set_keep_alive(5);

    let tls_config = TlsConfiguration::from_ca_and_auth(ca, cert, key);
    let (mut client, notifications) = Client::new(mqtt_options, Some(tls_config))?;

    client.subscribe("my/topic", rumqtt::QoS::AtMostOnce)?;

    for notification in notifications {
        match notification {
            Notification::Publish(publish) => {
                println!("Received: {:?}", publish);
            }
            Notification::Disconnected(disconnected) => {
                println!("Client disconnected: {:?}", disconnected);
            }
            Notification::Connected(_) => {
                println!("Client connected!");
            }
            _ => {}
        }
    }

    std::thread::sleep(Duration::from_secs(60));

    Ok(())
}
1156 chars
37 lines

related categories

gistlibby LogSnag