-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
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
II had to do something like this to get the message: