Mosquitto: Getting Started

How to Get Started with Mosquitto

👋 Welcome to the Stackhero documentation!

Stackhero provides you with a fully managed Mosquitto MQTT cloud environment, designed for reliability and flexibility:

  • Unlimited message throughput and data transfers, so your workflows never encounter artificial limits.
  • Unlimited device authentication through your own external API, making onboarding and access management simple.
  • Advanced ACLs for precise control over topics, users, and actions.
  • A custom domain name with built-in HTTPS for secure, branded endpoints (for example: https://mqtt.your-company.com).
  • Effortless updates: apply improvements or security patches with a single click.
  • Consistent performance and enhanced security, with every instance running on a private, dedicated infrastructure.

Accelerate your IoT projects and reduce operational overhead. You can have a secure, production-ready Mosquitto MQTT cloud hosting instance up and running in just a few minutes.

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 showcasing how to utilize Mosquitto at https://github.com/stackhero-io/mosquittoGettingStarted.

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.

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!