Skip to main content

spin_sdk/
mqtt.rs

1//! MQTT message publishing.
2//!
3//! To receive MQTT messages, use the MQTT trigger.
4//!
5//! # Examples
6//!
7//! Send an MQTT message.
8//!
9//! ```no_run
10//! use spin_sdk::mqtt::{Connection, Qos};
11//!
12//! # async fn run() -> anyhow::Result<()> {
13//! let conn = Connection::open(
14//!     "mqtt://localhost:1883?client_id=123",
15//!     "user",
16//!     "password",
17//!     30 /* seconds */
18//! ).await?;
19//!
20//! let payload = b"hello mqtt".to_vec();
21//!
22//! conn.publish("pet-pictures", payload, Qos::AtLeastOnce).await?;
23//! # Ok(())
24//! # }
25//! ```
26
27#[doc(hidden)]
28/// Module containing wit bindgen generated code.
29///
30/// This is only meant for internal consumption.
31pub mod wit {
32    #![allow(missing_docs)]
33    use crate::wit_bindgen;
34
35    wit_bindgen::generate!({
36        runtime_path: "crate::wit_bindgen::rt",
37        world: "spin-sdk-mqtt",
38        path: "wit",
39        generate_all,
40    });
41
42    pub use spin::mqtt::mqtt;
43}
44
45/// An open connection to an MQTT queue.
46///
47/// The address must be in URL form, and must include a `client_id`:
48/// `mqtt://hostname?client_id=...`
49///
50/// # Examples
51///
52/// Send an MQTT message.
53///
54/// ```no_run
55/// use spin_sdk::mqtt::{Connection, Qos};
56///
57/// # async fn run() -> anyhow::Result<()> {
58/// let conn = Connection::open(
59///     "mqtt://localhost:1883?client_id=123",
60///     "user",
61///     "password",
62///     30 /* seconds */
63/// ).await?;
64///
65/// let payload = b"hello mqtt".to_vec();
66///
67/// conn.publish("pet-pictures", payload, Qos::AtLeastOnce).await?;
68/// # Ok(())
69/// # }
70/// ```
71pub struct Connection(wit::mqtt::Connection);
72
73pub use wit::mqtt::{Error, Payload, Qos};
74
75impl Connection {
76    /// Open a connection to the Mqtt instance at `address`.
77    pub async fn open(
78        address: impl AsRef<str>,
79        username: impl AsRef<str>,
80        password: impl AsRef<str>,
81        keep_alive_interval_in_secs: u64,
82    ) -> Result<Self, Error> {
83        wit::mqtt::Connection::open(
84            address.as_ref().to_string(),
85            username.as_ref().to_string(),
86            password.as_ref().to_string(),
87            keep_alive_interval_in_secs,
88        )
89        .await
90        .map(Connection)
91    }
92
93    /// Publish an Mqtt message to the specified `topic`.
94    pub async fn publish(
95        &self,
96        topic: impl AsRef<str>,
97        payload: Vec<u8>,
98        qos: Qos,
99    ) -> Result<(), Error> {
100        self.0
101            .publish(topic.as_ref().to_string(), payload, qos)
102            .await
103    }
104}