Mosquitto: Python and MQTT

This documentation is part of the Getting Started guide. You can view the complete guide here: How to Begin 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 via your own external API, making onboarding and access management straightforward.
  • Advanced ACLs for precise control over topics, users, and actions.
  • A custom domain name with integrated 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.

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!