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