Skip to content

Instantly share code, notes, and snippets.

@ngarske

ngarske/main.rs Secret

Last active October 19, 2023 06:29
Show Gist options
  • Save ngarske/cc5257fff416459f10fd88c422e173cb to your computer and use it in GitHub Desktop.
Save ngarske/cc5257fff416459f10fd88c422e173cb to your computer and use it in GitHub Desktop.
Let's take a look at MQTT and how you can use MQTT with Rust using the rumqttc crate in your next IoT project.
use std::{thread, time::Duration};
use rumqttc::{Client, MqttOptions, QoS};
fn main() {
let mut mqttoptions = MqttOptions::new("NAME", "YOUR BROKER", 1883);
mqttoptions.set_keep_alive(Duration::from_secs(5));
let (mut client, mut connection) = Client::new(mqttoptions, 10);
client.subscribe("demo/mqtt", QoS::AtMostOnce).unwrap();
thread::spawn(move || {
for i in 0..10 {
client
.publish("demo/mqtt", QoS::AtLeastOnce, false, vec![i; i as usize])
.unwrap();
thread::sleep(Duration::from_millis(100));
}
});
for (_i, message) in connection.iter().enumerate() {
println!("Message = {:?}", message);
}
}
@iot-resister
Copy link

iot-resister commented Nov 26, 2022

II had to do something like this to get the message:

    for (_, notification) in connection.iter().enumerate() {
        match notification.unwrap() {
            Event::Incoming(Packet::Publish(p)) => {
                println!("Received: {:?}", p.payload);
            }
            Event::Outgoing(_) => {
                println!("Outgoing");
            }
            _ => {
                println!("Other");
            }
        }
    }

@menjaraz
Copy link

menjaraz commented Oct 19, 2023

So the new GIST should be...

use std::{thread, time::Duration};
use rumqttc::{Client, Event, MqttOptions, Packet, QoS};

fn main() {
    let mut mqttoptions = MqttOptions::new("NAME", "YOUR BROKER", 1883);
    mqttoptions.set_keep_alive(Duration::from_secs(5));

    let (mut client, mut connection) = Client::new(mqttoptions, 10);
    client.subscribe("demo/mqtt", QoS::AtMostOnce).unwrap();

    thread::spawn(move || {
        for i in 0..10 {
            client
                .publish("demo/mqtt", QoS::AtLeastOnce, false, vec![i; i as usize])
                .unwrap();
            thread::sleep(Duration::from_millis(100));
        }
    });

    for (_, notification) in connection.iter().enumerate() {
        match notification.unwrap() {
            Event::Incoming(Packet::Publish(p)) => {
                println!("Received: {:?}", p.payload);
            }

            Event::Outgoing(_) => {
                println!("Outgoing");
            }

            _ => {
                println!("Other");
            }
        }
    }
}

It compiles under Rust 1.7.3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment