Created
January 17, 2020 16:24
-
-
Save thomasantony/e46b3bf0b7f8dd3f0e337d51b22b07ab to your computer and use it in GitHub Desktop.
Rust rumqtt client example
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 rumqtt::{MqttClient, MqttOptions, QoS, Notification}; | |
use std::{thread, time::Duration}; | |
use std::collections::HashMap; | |
use std::sync::Arc; | |
fn foo(payload: Arc<Vec<u8>>) | |
{ | |
println!("Got foo message: {:?}", payload); | |
} | |
fn bar(payload: Arc<Vec<u8>>) | |
{ | |
println!("Got bar message: {:?}", payload); | |
} | |
fn main() { | |
let mqtt_options = MqttOptions::new("test-pubsub1", "localhost", 1883); | |
let (mut mqtt_client, notifications) = MqttClient::start(mqtt_options).unwrap(); | |
mqtt_client.subscribe("hello/foo", QoS::AtLeastOnce).unwrap(); | |
mqtt_client.subscribe("hello/bar", QoS::AtLeastOnce).unwrap(); | |
let sleep_time = Duration::from_secs(1); | |
// thread::spawn(move || { | |
// for i in 0..100 { | |
// let payload = format!("publish {}", i); | |
// thread::sleep(sleep_time); | |
// mqtt_client.publish("hello/world", QoS::AtLeastOnce, false, payload).unwrap(); | |
// } | |
// }); | |
let mut callbacks: HashMap<String, fn(Arc<Vec<u8>>) -> ()> = HashMap::new(); | |
callbacks.insert("hello/foo".to_string(), foo); | |
callbacks.insert("hello/bar".to_string(), bar); | |
for notification in notifications { | |
match notification { | |
Notification::Publish(msg) => { | |
let topic = msg.topic_name; | |
// callbacks.get(topic).map(|cb| cb(msg.payload)); | |
match callbacks.get(&topic) | |
{ | |
Some(cb) => cb(msg.payload), | |
None => { | |
println!("Topic not in list of callbacks"); | |
continue; | |
} | |
} | |
} | |
_ => println!("Ignoring notification") | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment