gmqtt-client

Crates.iogmqtt-client
lib.rsgmqtt-client
version0.2.0
sourcesrc
created_at2021-11-08 08:54:50.119501
updated_at2021-11-30 07:31:28.457509
descriptionSimple MQTTv5 client
homepage
repositoryhttps://gitlab.com/genesismobo/gmqtt-client
max_upload_size
id478424
size63,469
Marcin Pajkowski (mpajkowski)

documentation

README

Simple MQTTv5 client

gmqtt-client is pure-rust implementation of an mqtt 5.0 protocol.

Main features:

  • Auto reconnect
  • Resubscribe topics after reconnect
  • Message queue supports Message Expiry Interval and Retain flag

Messages queue

When disconnected from mqtt broker, messages are kept in queue on RAM. If client disconnects from MQTT broker, messages will be kept in queue in RAM.

Messages with Message Expiry Interval are counted down and dropped when expired. For example, if message is sent with message_expiry_interval = 60 (seconds) and client reconnects after 15 seconds, the message will be send with message_expiry_interval = 45 to broker.

Messages with Retain flag and the same topic are replaced in queue. Only last retained message is kept and send to broker.

Those two features help to reduce memory usage when client is offline for long time.

Basic Example

use std::time::Duration;
use tokio::runtime;
use gmqtt_client::{MqttClientBuilder, QoS};
use url::Url;
use serde::Serialize;

#[derive(Serialize)]
struct Event {
    id: u32,
}

fn main() -> anyhow::Result<()> {
    let (mqtt_client, mqtt_worker) = MqttClientBuilder::new(Url::parse("tcp://localhost:1883")?)
        .on_message_owned_callback(|message, instant| {
            println!("Message: {:?} received {} us ago", message, instant.elapsed().as_micros());
        })
        .subscribe("client/example/receive", QoS::AtLeastOnce)
        .build();

    let worker_runtime = runtime::Builder::new_multi_thread()
        .enable_all()
        .worker_threads(1)
        .build()?;

    worker_runtime.spawn(async { mqtt_worker.run().await });

    let payload = Event {
        id: 10
    };

    mqtt_client.publish_json(
        "client/example/publish",
        &payload,
        false,
        QoS::AtLeastOnce,
        Some(Duration::from_secs(10)),
    )?;

    std::thread::park();
    Ok(())
}

Run Example

sudo apt-get install mosquitto mosquitto-clients

# Run example client
cargo run --example client

# Listen to what is being published
mosquitto_sub -t 'client/example/publish' --pretty -F '%J'

# Send a message over to the client
mosquitto_pub -t 'client/example/receive' -m "hello" -q 1 -V 5 -r -D publish message-expiry-interval 5

# Send 1000 messages
for i in {0..1000}; do mosquitto_pub -t 'client/example/receive' -m "$i" -q 1 -V 5 -r -D publish message-expiry-interval 5; echo "sending $i"; done
Commit count: 8

cargo fmt