Refactor Mqtt Sync client (#5)

Co-authored-by: Felipe Diniello <felipediniello@pm.me>
Reviewed-on: #5
This commit was merged in pull request #5.
This commit is contained in:
2023-08-01 20:07:43 +02:00
parent c529335eac
commit 340df9a5d4
2 changed files with 44 additions and 30 deletions

View File

@@ -62,39 +62,51 @@ pub mod for_sync {
use paho_mqtt as mqtt;
use std::{process, time::Duration};
pub fn get_mqtt_cli() -> mqtt::Client {
let host = dotenv::var("MQTT_BROKER").unwrap_or_else(|_| {
pub struct MqttClient {
cli: mqtt::Client,
}
impl MqttClient {
pub fn new(client_id: Option<&str>) -> MqttClient {
let host = dotenv::var("MQTT_BROKER").unwrap_or_else(|_| {
println! {"MQTT_BROKER not found in .evn file, using default: tcp://localhost:1883"};
"tcp://localhost:1883".to_string()
});
let mut cli = mqtt::Client::new(host).unwrap_or_else(|e| {
println!("Error creating the client: {:?}", e);
process::exit(1);
});
let mut cli = if let Some(client_id) = client_id {
mqtt::Client::new((host, String::from(client_id))).unwrap_or_else(|e| {
println!("Error creating the client: {:?}", e);
process::exit(1);
})
} else {
mqtt::Client::new(host).unwrap_or_else(|e| {
println!("Error creating the client: {:?}", e);
process::exit(1);
})
};
// Use 5sec timeouts for sync calls.
cli.set_timeout(Duration::from_secs(5));
// Use 5sec timeouts for sync calls.
cli.set_timeout(Duration::from_secs(5));
// Connect and wait for it to complete or fail
if let Err(e) = cli.connect(None) {
println!("Unable to connect: {:?}", e);
process::exit(1);
// Connect and wait for it to complete or fail
if let Err(e) = cli.connect(None) {
println!("Unable to connect: {:?}", e);
process::exit(1);
}
MqttClient { cli }
}
pub fn publish(&self, topic: &str, payload: Option<&str>) -> Result<(), paho_mqtt::Error> {
let msg = if let Some(payload) = payload {
mqtt::MessageBuilder::new()
.topic(topic)
.qos(0)
.payload(payload)
.finalize()
} else {
mqtt::MessageBuilder::new().topic(topic).qos(0).finalize()
};
self.cli.publish(msg)
}
cli
}
pub fn mqtt_pub(
client: &mqtt::Client,
topic: &str,
payload: &str,
) -> Result<(), paho_mqtt::Error> {
let msg = mqtt::MessageBuilder::new()
.topic(topic)
.payload(payload)
.qos(0)
.finalize();
client.publish(msg)
}
}