Rust + Solace

tkunnumpurath
tkunnumpurath Member, Employee Posts: 11 Solace Employee
edited February 2022 in Blogs & Tutorials #1

Rust is an exciting new language created by the Mozilla foundation. I recently wanted to see if I can create a Rust App that publishes/subscribes to Solace. Sure enough Rust has an MQTT plugin (yay for open protocols) and was able to succesfully send/receive messages using Rust.

Here are the high-level overview of the steps you need to take to get a Rust App connected to Solace.
1. Install Rust
2. Run cargo new hello-world which will create a template project for you
3. Add the following dependency in cargo.toml rumqtt = "0.31.0"
4. In your src/main.rs file add the following import statement to the top use rumqtt::{MqttClient, MqttOptions, QoS, SecurityOptions};
5. The following code will instantiate an mqtt client:

let mqtt_options =
        MqttOptions::new(mqtt_client_id, mqtt_host, mqtt_port).set_security_opts(
            SecurityOptions::UsernamePassword(mqtt_username, mqtt_password),
        );

    let (mut mqtt_client, _) = MqttClient::start(mqtt_options).unwrap();

(Note the mqtt credentials can be retrieved from your Solace Cloud Connect Me Tab) or use the default localhost:1883 for a local broker
6. From there publishing/subscribing is a breeze... example:

//Publish
 mqtt_client
                .publish(topic_string, QoS::AtLeastOnce, false, payload)
                .unwrap()
//Subscribe
mqtt_client.subscribe(topic,0)?;

let mut mc = m.callbacks(());
mc.on_message(|data,msg| {
//callback logic
});

To see an implemented Rust Mqtt Solace client - you can visit this repo - https://github.com/solacese/rust-options-data-simulator

Tagged: