Skip to content

Instantly share code, notes, and snippets.

@mfiumara
Last active October 8, 2022 15:36
Show Gist options
  • Save mfiumara/10805ba7c5d09b24185f71cea195ca49 to your computer and use it in GitHub Desktop.
Save mfiumara/10805ba7c5d09b24185f71cea195ca49 to your computer and use it in GitHub Desktop.
MQTT publish and subscribe
// Spawn thread to listen to incoming events on the mqtt connection
thread::spawn(move || {
println!("MQTT Listening for messages");
while let Some(msg) = connection.next() {
match msg {
Err(e) => println!("MQTT Message ERROR: {}", e),
Ok(event) => {
println!("MQTT Event: {:?}", event);
// Wait for a received event
match event {
Event::Received(rcv) => {
let s = match str::from_utf8(rcv.data()) {
Ok(v) => v,
Err(e) => panic!("Invalid UTF-8 sequence: {}", e),
};
println!("rcv: {:?}", s);
}
// Ignore all other events for now
_ => {}
}
}
}
}
println!("MQTT connection loop exit");
});
mqtt_client.subscribe("my/test/sub", QoS::AtMostOnce).unwrap();
println!("Subscribed to my/test/sub");
loop {
thread::sleep(Duration::from_secs(1));
mqtt_client.publish("my/test/pub", QoS::AtMostOnce, false, "Hello world".as_bytes()).unwrap();
println!("Publishing done!");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment