#Store MQTT client and connection in Tauri context

11 messages · Page 1 of 1 (latest)

river sparrow
#

I am trying to make an mqtt dashboard with Tauri. to be able to do that, I want to connect to the broker in the setup hook and then save the client and connection in the tauri::app so I can use it in my custom tauri commands. Any sugestions to make this to work?

.setup(|app| {
    //connect to mqtt broker
    let device_key = "device-key";
    let broker_url = "localhost";
    let broker_port = 1883;
    let mqtt_key = "mqtt-key";
    let mqtt_secret = "mqtt-secret";

    let mut mqttoptions = MqttOptions::new(device_key, broker_url, broker_port);

    let will = LastWill::new(
        format!("lastwill/{}", device_key),
        "disconnected",
        QoS::AtLeastOnce,
        false,
    );

    mqttoptions.set_last_will(will);
    mqttoptions.set_credentials(mqtt_key, mqtt_secret);
    mqttoptions.set_keep_alive(Duration::from_secs(5));
    let (mut client, mut connection) = Client::new(mqttoptions, 10);
    let mut ctx = app.context();
    ctx.data.insert(client);
    Ok(ctx) 
  })
#

Or store it in the context like this but I do not know how to do it ```fn main() {

//connect to mqtt broker
let device_key = "device-key";
let broker_url = "localhost";
let broker_port = 1883;
let mqtt_key = "mqtt-key";
let mqtt_secret = "mqtt-secret";

let mut mqttoptions = MqttOptions::new(device_key, broker_url, broker_port);

let will = LastWill::new(
format!("lastwill/{}", device_key),
"disconnected",
QoS::AtLeastOnce,
false,
);

mqttoptions.set_last_will(will);
mqttoptions.set_credentials(mqtt_key, mqtt_secret);
mqttoptions.set_keep_alive(Duration::from_secs(5));
let (mut client, mut connection) = Client::new(mqttoptions, 10);
let context = tauri::generate_context!();

// store client and connection in context

tauri::Builder::default()
.plugin(Builder::default().build())
.invoke_handler(tauri::generate_handler![publish_function])
.run(context)
.expect("error while running tauri application");
}```

#

Store MQTT client and connection in Tauri context

#

Or can I store it in Tauri State?

granite lantern
#

yeah, state is what you're looking for.

#

Context is not what you think it is. It's the additional data needed for the tauri app. like the content of tauri.conf.json, the stored assets (distDir) etc...
It's not used for storing just any data, that's what State is for

river sparrow
#

Oh okay thanks! You have a small example in how to store it in State?

granite lantern
#

if the Client needs to be mutable then you need to store it in a Mutex (or similar), if not then you can just store it as-is

river sparrow
#

Thanks, I'll have a look at that!

river sparrow
#

@granite lantern quick question, I only see examples with mutex that get initialized like Default::default() How can I initialize it with my client? struct MqttClient(Mutex<Client>); ... .manage(MqttClient(client))