Ниже показан английский оригинал.
Qos
Qos picks at most once, at least once or exactly once; a delivery arrives at the lower of the publisher's and the subscription's level.
A subscription names its level with qos(..) on MqttTopic or MqttFilter, and the default is Qos::AtLeastOnce.
| Level | QoS | What the protocol does |
|---|---|---|
AtMostOnce | 0 | sends the message once, with no acknowledgement; a message lost on the way is gone |
AtLeastOnce | 1 | resends until the receiver answers PUBACK; a message may arrive twice |
ExactlyOnce | 2 | a four-packet handshake, so the message arrives once |
The server sends each message at the lower of two levels: the one its publisher sent it at and the one the subscription asked for.
So a QoS 2 subscription receives a QoS 0 publish at QoS 0, and MqttMessage::qos tells the level a delivery arrived at.
A delivery at QoS 1 or 2 is acknowledged when the handler settles it.
The level a publish is sent at is a setting of the publish policy.
Example
Telemetry read at most once, because the next reading replaces a lost one, and a valve command read exactly once.
- Macros
- Manual
/// Telemetry is read at most once: the next reading replaces a lost one.
#[subscriber(MqttTopic::new("sensors/temp").qos(Qos::AtMostOnce))]
async fn store(reading: &Reading) -> HandlerOutcome {
let _ = reading.celsius;
HandlerOutcome::ack()
}
/// A valve command is applied exactly once.
#[subscriber(MqttTopic::new("valves/v1/set").qos(Qos::ExactlyOnce))]
async fn set(command: &Command) -> HandlerOutcome {
let _ = command.open;
HandlerOutcome::ack()
}
#[ruststream::app(runtime = embassy)]
fn app(broker: MqttBroker) -> EmbeddedApp<impl Mounts> {
EmbeddedApp::new().with_broker(broker, |b| b.include(store).include(set))
}
/// Telemetry is read at most once: the next reading replaces a lost one.
struct Store;
impl Handle<Reading> for Store {
fn handle(
&self,
_reading: &Reading,
_outs: &(),
_ctx: &mut Context<'_>,
) -> impl Future<Output = Result<(), HandlerOutcome>> {
ready(Ok(()))
}
}
/// A valve command is applied exactly once.
struct Set;
impl Handle<Command> for Set {
fn handle(
&self,
_command: &Command,
_outs: &(),
_ctx: &mut Context<'_>,
) -> impl Future<Output = Result<(), HandlerOutcome>> {
ready(Ok(()))
}
}
fn app(broker: MqttBroker) -> EmbeddedApp<impl Mounts> {
EmbeddedApp::new().with_broker(broker, |b| {
let temp = MqttTopic::new("sensors/temp").qos(Qos::AtMostOnce);
let valve = MqttTopic::new("valves/v1/set").qos(Qos::ExactlyOnce);
b.include(
subscriber("sensors/temp", Store)
.map_source(|_| temp)
.build(),
)
.include(
subscriber("valves/v1/set", Set)
.map_source(|_| valve)
.build(),
)
})
}