Mosquitto: Getting started
How to get started with Mosquitto
👋 Welcome to the Stackhero documentation!
Stackhero offers a ready-to-use Mosquitto MQTT cloud solution that provides a host of benefits, including:
- Unlimited message exchanges and transfers.
- Unlimited devices authentication via an external API.
- Advanced ACLs on topics, users and actions.
- Customizable domain name secured with HTTPS (for example, https://mqtt.your-company.com).
- Effortless updates with just a click.
- Optimal performance and robust security powered by a private and dedicated VM.
Save time and simplify your life: it only takes 5 minutes to try Stackhero's Mosquitto MQTT cloud hosting solution!
Mosquitto is an MQTT broker, implementing the MQTT protocol (Message Queuing Telemetry Transport), which is specifically designed for lightweight communication between IoT devices and servers.
On Stackhero, Mosquitto is configured with TLS encryption and user authentication to provide a secure communication environment.
You can find practical code examples showcasing how to utilize Mosquitto at https://github.com/stackhero-io/mosquittoGettingStarted.
Understanding MQTT topics
MQTT organizes communication into "topics", which act as channels for publishing and subscribing to data. Devices publish messages to specific topics or subscribe to them to receive relevant updates.
Structure of MQTT topics
Topics in MQTT are case-sensitive, must contain UTF-8 characters, and require at least one character. The hierarchy within topics is defined using the slash (/) character.
Here is an example setup for IoT devices collecting temperature and humidity data, identified by their MAC addresses:
-
For a device with MAC address
00:00:00:00:00:00:- Temperature:
devices/00:00:00:00:00:00/temperature - Humidity:
devices/00:00:00:00:00:00/humidity
- Temperature:
-
For a device with MAC address
11:11:11:11:11:11:- Temperature:
devices/11:11:11:11:11:11/temperature - Humidity:
devices/11:11:11:11:11:11/humidity
- Temperature:
Applications can subscribe to a specific topic, such as devices/00:00:00:00:00:00/temperature, to receive data from the respective IoT device.
Using wildcards in MQTT topics
MQTT supports wildcards for efficient topic management:
-
The
+wildcard matches a single level in the topic hierarchy. For example, subscribing todevices/+/temperaturecaptures topics likedevices/1/temperaturebut notdevices/1/2/temperature. -
The
#wildcard matches multiple levels. For instance,devices/#matches topics such asdevices/1/temperature,devices/2/humidity, anddevices/1/2/somethingElse.
Testing with mosquitto_pub and mosquitto_sub
The mosquitto_pub and mosquitto_sub CLI tools are excellent for testing MQTT setups. Before using them, ensure that the "Allow clear connections" option is disabled in your Mosquitto configuration on the Stackhero dashboard.
Here is how you can test:
-
Subscribe to all topics using the
#wildcard:mosquitto_sub -L -d "mqtts://admin:<PASSWORD>@<XXXXXX>.stackhero-network.com:<PORT_TLS>/#" -
Open another terminal to publish a message to a topic:
mosquitto_pub -L -d "mqtts://admin:<PASSWORD>@<XXXXXX>.stackhero-network.com:<PORT_TLS>/sensor/a" -m "It works"
In the first console, you should see the published message along with debug logs enabled by the -d flag.
Connecting to MQTT via WebSockets
You can directly connect to your Mosquitto server from a web browser using WebSockets. Refer to the "WebSockets" documentation for more details.
Node.js and MQTT
Examples demonstrating how to use Mosquitto with Node.js are available at https://github.com/stackhero-io/mosquittoGettingStarted.
Python and MQTT
To use Mosquitto with Python, the Paho MQTT Python client library is recommended. Install it using:
pip install paho-mqtt
Below is an example Python script for connecting to a Mosquitto server using TLS encryption and authentication:
import paho.mqtt.client as mqtt
import random
import string
from paho.mqtt.client import CallbackAPIVersion
def on_connect(client, userdata, flags, reason_code, properties=None):
if reason_code == 0:
print("Connected successfully")
else:
print(f"Connection failed with reason {reason_code}")
def on_message(client, userdata, msg, properties=None):
print(f"Received message: {msg.payload.decode()} on topic {msg.topic}")
def generate_client_id(length=8):
characters = string.ascii_letters + string.digits
return "client_" + ''.join(random.choice(characters) for _ in range(length))
client_id = generate_client_id()
client = mqtt.Client(
client_id=client_id,
callback_api_version=CallbackAPIVersion.VERSION2
)
client.on_connect = on_connect
client.on_message = on_message
host = "<XXXXXX>.stackhero-network.com"
port = <PORT_TLS>
client.username_pw_set("<USER>", "<PASSWORD>")
client.tls_set()
try:
print(f"Connecting to {host} with client ID: {client_id}")
client.connect(host, port)
client.loop_start()
client.subscribe("$SYS/#")
try:
while True:
pass
except KeyboardInterrupt:
print("\nDisconnecting...")
client.loop_stop()
client.disconnect()
except Exception as e:
print(f"Error: {e}")
With these instructions, you should be well-equipped to start working with Mosquitto on Stackhero. Have an enjoyable experience exploring MQTT!