36 lines
998 B
Rust
36 lines
998 B
Rust
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;
|
|
}
|
|
}
|
|
}
|
|
}
|