Messaging
vld_data::rumqttc validates MQTT payloads as JSON: publish / try_publish check a value before it is queued on an AsyncClient, decode_publish checks an incoming Publish.
Install
Cargo.toml
[dependencies]
vld = "0.8"
vld-data = { version = "0.8", features = ["rumqttc"] }
rumqttc = "0.25"
| Feature | Module | Notes |
|---|---|---|
rumqttc | vld_data::rumqttc | rumqttc 0.25 (MQTT 3.1.1 client), default features off: pick TLS in your own rumqttc dependency |
Example
use rumqttc::{AsyncClient, Event, MqttOptions, Packet, QoS};
use vld_data::rumqttc::prelude::*;
vld::schema! {
#[derive(Debug, serde::Serialize)]
pub struct Reading {
pub sensor: String => vld::string().min(1),
pub celsius: f64 => vld::number().min(-50.0).max(150.0),
}
}
async fn run() -> Result<(), Box<dyn std::error::Error>> {
let (client, mut eventloop) = AsyncClient::new(MqttOptions::new("vld", "127.0.0.1", 1883), 10);
client.subscribe("sensors/#", QoS::AtLeastOnce).await?;
publish(&client, "sensors/1", QoS::AtLeastOnce, false,
&Reading { sensor: "s1".into(), celsius: 21.5 }).await?;
loop {
if let Event::Incoming(Packet::Publish(p)) = eventloop.poll().await? {
match decode_publish::<Reading>(&p) {
Ok(r) => println!("{} {}", r.sensor, r.celsius),
Err(e) => eprintln!("bad payload on {}: {e}", p.topic),
}
}
}
}
API
publish(&client, topic, qos, retain, &value)— validate, encode as JSON,AsyncClient::publish.try_publish(&client, topic, qos, retain, &value)— the same withAsyncClient::try_publish.decode_publish::<T>(&publish)— parse and validate an incoming payload.encode(&value),decode::<T>(&bytes)— the same on raw bytes.VldMqttError—Validation,Serialization,Deserialization,Client(rumqttc::ClientError).
Gotchas
- The value type is the schema: published values must be
Serialize + VldParse(aschema!struct with#[derive(serde::Serialize)]). - An invalid value is never queued.
publishreturningOkmeans the request reached the event loop, not the broker: keep polling theEventLoop. - MQTT 5 (
rumqttc::v5) is not covered; useencode/decodewith its client.