# 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](https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901112) 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](https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901104) 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

```rust,no_run
use std::time::Duration;
use tokio::runtime;
use gmqtt_client::{MqttClientBuilder, QoS};
use serde::Serialize;

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

fn main() -> anyhow::Result<()> {
    let (mqtt_client, mqtt_worker) = MqttClientBuilder::new("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

```sh
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
```
