Crate mqtt_typed_client_core

Source
Expand description

§MQTT Typed Client

A Rust library providing a typed MQTT client with pattern-based routing and automatic subscription management.

§Features

  • Typed Publishers and Subscribers: Type-safe message publishing and subscription
  • Pattern-based Routing: Support for MQTT wildcard patterns (+, #)
  • Automatic Subscription Management: Handles subscription lifecycle automatically
  • Graceful Shutdown: Proper resource cleanup and connection termination
  • Async/Await Support: Built on top of tokio for async operations
  • Error Handling: Comprehensive error types with retry logic
  • Message Serialization: Pluggable serialization (Bincode included)

§Quick Start

use mqtt_typed_client_core::{MqttClient, MqttClientConfig, BincodeSerializer};
use serde::{Deserialize, Serialize};
use bincode::{Encode, Decode};

#[derive(Serialize, Deserialize, Encode, Decode, Debug)]
struct SensorData {
    temperature: f64,
    humidity: f64,
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Simple connection using URL
    let (client, connection) = MqttClient::<BincodeSerializer>::connect(
        "mqtt://broker.hivemq.com:1883?client_id=my_client"
    ).await?;

    // Advanced configuration
    let mut config = MqttClientConfig::new("my_client", "broker.hivemq.com", 1883);
    config.connection.set_keep_alive(std::time::Duration::from_secs(30));
    config.connection.set_clean_session(true);
    config.settings.topic_cache_size = 500;
     
    let (client, connection) = MqttClient::<BincodeSerializer>::connect_with_config(config).await?;

    // Create a typed publisher
    let publisher = client.get_publisher::<SensorData>("sensors/temperature")?;

    // Create a typed subscriber
    let mut subscriber = client.subscribe::<SensorData>("sensors/+").await?;

    // Publish data
    let data = SensorData { temperature: 23.5, humidity: 45.0 };
    publisher.publish(&data).await?;

    // Receive data
    if let Some((topic, result)) = subscriber.receive().await {
        match result {
            Ok(sensor_data) => println!("Received from {}: {:?}", topic, sensor_data),
            Err(e) => eprintln!("Deserialization error: {:?}", e),
        }
    }

    // Graceful shutdown
    connection.shutdown().await?;
    Ok(())
}

§Pattern Matching

The library supports MQTT topic pattern matching:

  • + matches a single topic level (e.g., sensors/+/temperature)
  • # matches multiple topic levels (e.g., sensors/#)

§Publisher Limitations

Note: Multi-level wildcards (#) can only be used for subscriptions, not for publishing. This is because publishers need to generate specific topic strings, while # represents a variable number of topic segments.

For patterns containing #, use the mqtt_topic macro with explicit subscriber mode, or create separate structs for publishing and subscribing.

§Custom Serialization

Implement the MessageSerializer trait for custom serialization:

use mqtt_typed_client_core::MessageSerializer;

#[derive(Clone, Default)]
struct JsonSerializer;

impl<T> MessageSerializer<T> for JsonSerializer
where
    T: serde::Serialize + serde::de::DeserializeOwned + 'static,
{
    type SerializeError = serde_json::Error;
    type DeserializeError = serde_json::Error;

    fn serialize(&self, data: &T) -> Result<Vec<u8>, Self::SerializeError> {
        serde_json::to_vec(data)
    }

    fn deserialize(&self, bytes: &[u8]) -> Result<T, Self::DeserializeError> {
        serde_json::from_slice(bytes)
    }
}

Re-exports§

pub use client::ClientSettings;
pub use client::MqttClient;
pub use client::MqttClientConfig;
pub use client::MqttClientError;
pub use client::TypedLastWill;
pub use client::MqttPublisher;
pub use client::MqttSubscriber;
pub use client::SubscriptionBuilder;
pub use connection::MqttConnection;
pub use message_serializer::BincodeSerializer;
pub use message_serializer::JsonSerializer;
pub use message_serializer::MessageSerializer;
pub use routing::CacheStrategy;
pub use routing::SubscriptionConfig;
pub use structured::FromMqttMessage;
pub use structured::MessageConversionError;
pub use structured::MqttTopicSubscriber;
pub use structured::extract_topic_parameter;
pub use topic::TopicError;
pub use topic::TopicPatternError;
pub use topic::TopicPatternPath;

Modules§

advanced
Advanced types and utilities for complex use cases
client
MQTT client module
connection
MQTT connection management module
errors
Error types used throughout the library
message_serializer
Message serialization traits and implementations.
prelude
Prelude module for convenient imports
routing
Message routing and subscription management module
structured
Structured MQTT subscribers with automatic topic parameter extraction
topic
Topic handling module

Structs§

MqttOptions
Options to configure the behaviour of MQTT connection

Enums§

QoS
Quality of service

Type Aliases§

Result
Result type alias for operations that may fail with MqttClientError