By: Tim McCallum
Real-time communication is crucial for many applications. One powerful tool that developers can leverage is the Message Queuing Telemetry Transport (MQTT) Trigger for Spin. In this article, we will delve into what the MQTT trigger is, where to find documentation, why developers should consider using it, and the specific problem it solves. We will write and test a Spin application that responds to MQTT messages published by a message broker.
What Is MQTT?
MQTT is lightweight messaging protocol designed for efficient communication between devices and servers. It is a protocol designed for resource-constrained IoT devices, and offers different quality of service (QoS) levels to ensure reliable message delivery over constrained networks.
What Is the MQTT Trigger for Spin?
The framework that allows a Spin application to subscribe to a specific MQTT address. Individual components within that application can then be configured to monitor particular topics at the address. When messages are detected on these topics, the corresponding component functions are triggered.
How Do I Get Started With Spin and MQTT?
Developers can refer to the section of .
Upgrading Spin: If you have an older version of Spin, please see the Spin allow a Spin developer to quickly create the skeleton of an application or component, ready for the application logic to be filled in. As part of this repo, a new template is created to help build applications that make use of MQTT as a communication protocol/trigger.
Install MQTT Template:
CODE$ spin templates install --git https://github.com/spinkube/spin-trigger-mqtt --upgrade
Create Spin App
Below is a simple example where we create a new app and pass in some credentials like
userandpassword,topicand so on:
CODE$ spin new -t mqtt-rust mqtt-app
Description: Demo app to receive MQTT messages.
Mqtt Address: mqtt://localhost:1883
Mqtt Username: user
Mqtt Password: password
Mqtt Keep Alive Interval (Secs between 0-65535): 30
Mqtt Topic: mytopic
Mqtt QoS for Topic (between 0-2): 1
If we change directories into the
mqtt-appdir, we can take a look at the layout and application configuration:
CODE$ cd mqtt-app/
$ tree .
.
├── Cargo.toml
├── spin.toml
└── src
└── lib.rs
1 directory, 3 files
$ vi spin.toml
The application manifest will look similar to the following:
CODEspin_manifest_version = 2
[application]
name = "mqtt-app"
version = "0.1.0"
authors = ["Fermyon Engineering <[email protected]>"]
description = "Demo app to receive MQTT messages."
[application.trigger.mqtt]
address = "mqtt://localhost:1883"
username = "user"
password = "password"
keep_alive_interval = "30"
[[trigger.mqtt]]
component = "mqtt-app"
topic = "mytopic"
qos = "1"
[component.mqtt-app]
source = "target/wasm32-wasi/release/mqtt_app.wasm"
allowed_outbound_hosts = ["mqtt://localhost:1883"]
[component.mqtt-app.build]
command = "cargo build --target wasm32-wasi --release"
The
Address:,Username:,Password:andTopic:support the ability to be configured using Spin variables, which would be a better solution but is out of scope for this article. Please see the from hereon out. If you are connecting to a different remote MQTT broker, you might want to skip this step:
CODE$ sudo apt install mosquitto
$ sudo apt install mosquitto-clients
$ sudo systemctl start mosquitto
MQTT Broker Testing
We will digress here for just a minute to make sure that our MQTT broker is operational; we will return to the Spin application soon. We are going to type the following command, which will subscribe to a topic called
mytopic:
CODEmosquitto_sub -h localhost -t "mytopic"
Then, in a fresh terminal, we will use the following command to publish a message to the
mytopictopic:
CODEmosquitto_pub -h localhost -t "mytopic" -m "Hello, MQTT!"
If our default Mosquitto installation is working, we will see the message
"Hello, MQTT!"in the terminal from which we first subscribed to themytopictopic …:
CODE$ mosquitto_sub -h localhost -t "mytopic"
Hello, MQTT!
… and voilà!
Feel free to use
ctrl+cto stop this terminal now.
Spin Application Testing
With the knowledge that our MQTT broker is able to publish and consume on localhost, let’s go back and test the Spin application that we created earlier on. The Rust code used to create the Wasm component is pretty straightforward:
CODE#[mqtt_component]
async fn handle_message(message: Payload, metadata: Metadata) -> anyhow::Result<()> {
let datetime: DateTime<Utc> = std::time::SystemTime::now().into();
let formatted_time = datetime.format("%Y-%m-%d %H:%M:%S.%f").to_string();
println!(
"{:?} Message received by wasm component: '{}'",
formatted_time,
String::from_utf8_lossy(&message)
);
Ok(())
}
To build the application, we use the
spin buildcommand:
CODE$ spin build
We can run our Spin application using the following command:
CODE$ spin up
We now return to the terminal where we first published a message and, again, run a command to publish a message:
CODE$ mosquitto_pub -h localhost -t "mytopic" -m "Hello, MQTT via our Spin application!"
As a result, in the terminal where we started Spin, we see the following result:
CODE"2024-06-26 03:15:03.441455912" Message received by wasm component: 'Hello, MQTT via our Spin application!'
The MQTT component has received the
messageandmetadata(at the time of publishing) and we can see this clearly printed out, as per the source code above.
If you looking to streamline real-time communications in your applications, The MQTT Trigger for Spin is your gateway to efficiency and scalability. If you have any questions please reach out to us on .
↗ Original-Artikel auf dev.to lesenVollständiger Original-BerichtAusführliche Details, Code-Beispiele & Hersteller-Stellungnahme auf dev.to.
SOCIAL SHARE CARD GENERATOR