Jasmine Mae
Posted on November 25, 2024
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 MQTT trigger is a feature of the Spin 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 official SpinKube documentation which provides detailed information on how to configure and use the MQTT Trigger Plugin for Spin.
If you are interested in publishing outgoing MQTT messages from within a Spin application, then please visit the outbound MQTT messaging section of Fermyon Developer Home.
Why Should Developers Consider Using the MQTT Trigger?
MQTT is a dominant communication protocol in IoT and edge scenarios. In addition to offering efficient communication for constrained IoT and edge devices and networks, MQTT offers scalability. For example, MQTT is designed to handle large-scale deployments, allowing developers to build scalable and responsive applications that handle many concurrent connections.
MQTT is built for real-time communication, enabling instant data transfer between devices and servers. By using the MQTT trigger, developers can easily incorporate real-time capabilities into their Spin applications, facilitating timely updates and notifications.
What Problem Does the MQTT Trigger Solve?
The MQTT trigger solves the problem of integrating Spin applications with MQTT-based systems. It provides a seamless way to subscribe to MQTT topics and trigger actions based on incoming messages. This eliminates the need for developers to write complex code for MQTT integration, allowing developers to focus on building the core functionality of their applications (instead of focusing on the intricacies of the MQTT protocol)
If you’re looking to enhance your Spin applications with real-time communication, consider using the MQTT trigger and unlock the full potential of your applications. Let’s dive in and give it a try.
Installing Spin
If you haven’t already, please go ahead and install the latest version of Spin.
Upgrading Spin: If you have an older version of Spin, please see the Spin upgrade page.
Install Plugin
Install MQTT Plugin:
$ spin plugin install --url https://github.com/spinkube/spin-trigger-mqtt/releases/download/canary/trigger-mqtt.json --yes
[Note: release management for multiple versions of this plugin/trigger will be added soon]
Install Template
Spin templates 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:
$ 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 user
and password
, topic
and so on:
$ 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-app
dir, we can take a look at the layout and application configuration:
$ 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:
spin_manifest_version = 2
[application]
name = "mqtt-app"
version = "0.1.0"
authors = ["Fermyon Engineering <engineering@fermyon.com>"]
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 adding variables to your application section of the developer documentation for more information.
Running MQTT Broker
I am on Ubuntu, so installing and running an MQTT broker is fairly simple. We will use an open source MQTT broker called Mosquitto from hereon out. If you are connecting to a different remote MQTT broker, you might want to skip this step:
$ 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
:
mosquitto_sub -h localhost -t "mytopic"
Then, in a fresh terminal, we will use the following command to publish a message to the mytopic
topic:
mosquitto_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 the mytopic
topic …:
$ mosquitto_sub -h localhost -t "mytopic"
Hello, MQTT!
… and voilà!
Feel free to use ctrl
+ c
to 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:
#[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 build
command:
$ spin build
We can run our Spin application using the following command:
$ spin up
We now return to the terminal where we first published a message and, again, run a command to publish a message:
$ 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:
"2024-06-26 03:15:03.441455912" Message received by wasm component: 'Hello, MQTT via our Spin application!'
The MQTT component has received the message
and metadata
(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 Discord or via the GitHub repository for Spin MQTT Trigger.
Posted on November 25, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.