Mosquitto: Getting Started

How to Begin 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.
  • Customisable 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), 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 demonstrating how to use Mosquitto at https://github.com/stackhero-io/mosquittoGettingStarted.

MQTT organises 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.

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
  • 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

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.

MQTT supports wildcards for efficient topic management:

  • The + wildcard matches a single level in the topic hierarchy. For example, subscribing to devices/+/temperature captures topics like devices/1/temperature but not devices/1/2/temperature.

  • The # wildcard matches multiple levels. For instance, devices/# matches topics such as devices/1/temperature, devices/2/humidity, and devices/1/2/somethingElse.

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:

  1. Subscribe to all topics using the # wildcard:

    mosquitto_sub -L -d "mqtts://admin:<PASSWORD>@<XXXXXX>.stackhero-network.com:<PORT_TLS>/#"
    
  2. 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.

You can directly connect to your Mosquitto server from a web browser using WebSockets. Refer to the "WebSockets" documentation for more details.

Examples demonstrating how to use Mosquitto with Node.js are available at https://github.com/stackhero-io/mosquittoGettingStarted.

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!