下面显示的是英文原文。
MqttPublish
MqttPublish is the publish policy of a mount: the quality of service and the retain flag of every message it publishes.
A policy is a plain declaration that holds no connection, and the runtime pairs it with the connected broker into an MqttPublisher.
qos defaults to Qos::AtLeastOnce and retain to false.
The policy is also the default of the broker, so a reply and a retry copy leave through it unless the mount names another.
On a device the publisher encodes the message straight into a send buffer of the broker's memory, which the runner writes, and a message that does not fit the packet is refused with the message handed back.
On the heap variant the publisher copies the bytes of a message into a staging slot of the broker, whose buffers keep their capacity, so a publish allocates nothing once the slots have held the largest message the service sends.
Ok means the PUBLISH packet went out into the session; at QoS 1 and 2 the session keeps the message until the server acknowledges it.
A publish to a topic no server takes, such as one with a wildcard, is refused with MqttError::Publish, and a publish after the shutdown answers MqttError::NotConnected.
A refused publish hands its message back.
Example
A device reports every reading in degrees, and the reports are sent exactly once.
- Macros
- Manual
/// Reports every reading in degrees: the return value is the reply.
#[subscriber(MqttTopic::new("sensors/temp"), reply)]
async fn report(reading: &Reading) -> Report {
Report {
celsius: i16::try_from((i32::from(reading.millivolts) - 500) / 10).unwrap_or(i16::MAX),
}
}
#[ruststream::app(runtime = embassy)]
fn app(broker: MqttBroker) -> EmbeddedApp<impl Mounts> {
EmbeddedApp::new().with_broker(broker, |b| {
// Reports are sent exactly once.
b.include(report)
.out_reply(MqttPublish::default().qos(Qos::ExactlyOnce))
})
}
/// Reports every reading in degrees: the return value is the reply.
struct Reporter;
impl Handle<Reading, Report> for Reporter {
fn handle(
&self,
reading: &Reading,
_outs: &(),
_ctx: &mut Context<'_>,
) -> impl Future<Output = Result<Report, HandlerOutcome>> {
ready(Ok(Report {
celsius: i16::try_from((i32::from(reading.millivolts) - 500) / 10).unwrap_or(i16::MAX),
}))
}
}
fn app(broker: MqttBroker) -> EmbeddedApp<impl Mounts> {
EmbeddedApp::new().with_broker(broker, |b| {
// Reports are sent exactly once.
b.include(
subscriber("sensors/temp", Reporter)
.map_source(|_| MqttTopic::new("sensors/temp"))
.reply()
.to("reports/temp")
.build(),
)
.out_reply(MqttPublish::default().qos(Qos::ExactlyOnce))
})
}