2 unstable releases
0.2.0 | Nov 30, 2021 |
---|---|
0.1.0 | Nov 8, 2021 |
#1137 in Asynchronous
600 downloads per month
43KB
978 lines
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
Dependencies
~6–15MB
~207K SLoC