After spending a considerable amount of time reading and studying Rust, I've decided to embark on rewriting some code. I have a Python program that I want to translate. Essentially, it communicates with a device using ModbusTCP and translates the data to MQTT.
Given that both Modbus and MQTT communication need to happen concurrently, I need the connections to be asynchronous. At this juncture, I'm attempting to make MQTT asynchronous without much success. Could I get some assistance?
I need to create a task to handle connection and auto-reconnect. If I understand how to do this, I can then subscribe to a topic.
const BROKER_ADDRESS: &str = "192.168.200.254";
const USER_NAME: &str = "user";
const PASSWORD: &str = "password";
const CLIENT_NAME: &str = "client-name";
use futures::{executor::block_on, stream::StreamExt};
use mqtt::{Client, ConnectOptions};
use paho_mqtt as mqtt;
use std::process;
use std::time::Duration;
fn create_mqtt() -> Client{
let host: String = "tcp://".to_owned() + BROKER_ADDRESS + ":1883";
let create_options = mqtt::CreateOptionsBuilder::new()
.server_uri(&host)
.client_id(CLIENT_NAME.to_string())
.finalize();
// Create a client.
let cli: Client = mqtt::Client::new(create_options).unwrap_or_else(|err| {
println!("Error creating the client: {:?}", err);
process::exit(1);
});
// println!("{}", &host);
cli
}
fn client_opts() -> ConnectOptions{
mqtt::ConnectOptionsBuilder::new()
.keep_alive_interval(Duration::from_secs(20))
.clean_session(false)
.user_name(USER_NAME.to_string())
.password(PASSWORD.to_string())
.finalize()
}
#[tokio::main]
async fn main() {
let cli: Client = create_mqtt();
let cli_opts: ConnectOptions = client_opts();
// Make the connection to the broker
if cli.is_connected() {
println!("Connected");
}else{
println!("Not connected");
}
if let Err(err) = cli.connect(cli_opts) {
eprintln!("{}", err);
}
println!("Hello, world!");
}
It would be beneficial to have a function with connection and reconnection capabilities, allowing us to create a non-blocking task in the main loop.
The paho_mqtt only present some examples which are not clear for a beginner. I really appreciate any kind of help.