Эта страница ещё не переведена
Ниже показан английский оригинал.
Retained messages
A retained message is kept by the server, which hands the last one of each topic to every new subscription that is not shared.
retain(true) on the policy retains every message of the mount, and the step retains one.
A dashboard that starts later reads the state without waiting for the next change.
Publishing an empty retained payload clears the topic.
The subscription receives the retained message at the lower of the two levels, as any other delivery.
Example
The state of the valve is retained, so a subscriber that joins later reads the latest one.
- Macros
- Manual
/// The valve's state is retained, so a subscriber that joins later reads the latest one.
#[subscriber(MqttTopic::new("valves/v1/position"))]
async fn track(
position: &Position,
Out(states): Out<impl Publisher<Options = MqttPublishOptions>, States>,
) -> HandlerOutcome {
let state = State {
open: position.percent > 0,
};
if states.message(&state).retain(true).publish().await.is_err() {
return HandlerOutcome::retry();
}
HandlerOutcome::ack()
}
#[ruststream::app(runtime = embassy)]
fn app(broker: MqttBroker) -> EmbeddedApp<impl Mounts> {
EmbeddedApp::new().with_broker(broker, |b| {
b.include(track).out(States, MqttPublish::default())
})
}
/// The valve's state is retained, so a subscriber that joins later reads the latest one.
struct Track;
impl<Entry> Handle<Position, (), Outs<(Entry,)>> for Track
where
Entry: OutEntry<States, Wire: Publisher<Options = MqttPublishOptions>>,
{
async fn handle(
&self,
position: &Position,
outs: &Outs<(Entry,)>,
_ctx: &mut Context<'_>,
) -> Result<(), HandlerOutcome> {
let state = State {
open: position.percent > 0,
};
outs.get(States)
.message(&state)
.retain(true)
.publish()
.await
.map_err(|_| HandlerOutcome::retry())
}
}
fn app(broker: MqttBroker) -> EmbeddedApp<impl Mounts> {
EmbeddedApp::new().with_broker(broker, |b| {
b.include(
subscriber("valves/v1/position", Track)
.map_source(|_| MqttTopic::new("valves/v1/position"))
.build(),
)
.out(States, MqttPublish::default())
})
}