Initial commit: MQTT publisher with rumqttc
This commit is contained in:
35
src/main.rs
Normal file
35
src/main.rs
Normal file
@@ -0,0 +1,35 @@
|
||||
use rumqttc::{AsyncClient, Event, MqttOptions, Packet, QoS};
|
||||
use std::time::Duration;
|
||||
use tokio::time::sleep;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let mut mqttoptions = MqttOptions::new(
|
||||
"mqtt-publisher",
|
||||
"localhost",
|
||||
1883,
|
||||
);
|
||||
mqttoptions.set_keep_alive(Duration::from_secs(30));
|
||||
|
||||
let (client, mut eventloop) = AsyncClient::new(mqttoptions, 100);
|
||||
|
||||
client
|
||||
.publish("test/topic", QoS::AtLeastOnce, false, b"Hello from Rust MQTT!")
|
||||
.await?;
|
||||
|
||||
println!("Published message to test/topic");
|
||||
|
||||
loop {
|
||||
match eventloop.poll().await {
|
||||
Ok(Event::Incoming(Packet::Publish(_))) => {}
|
||||
Ok(Event::Incoming(Packet::ConnAck(_))) => {
|
||||
println!("Connected to MQTT broker");
|
||||
}
|
||||
Ok(_) => {}
|
||||
Err(e) => {
|
||||
println!("Error: {:?}", e);
|
||||
sleep(Duration::from_secs(1)).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user