Skip to content

Python ​

Use the Eclipse Paho client (paho-mqtt 2.x) to publish and subscribe from Python 3.

Install ​

bash
pip install "paho-mqtt>=2.0"

Publish and subscribe ​

python
import json
import os
import time

import paho.mqtt.client as mqtt

HOST = "broker.connectmq.com"
PORT = 8883
CLIENT_ID = os.environ["CMQ_CLIENT_ID"] + "_python-demo"  # issued client ID + "_" + suffix
USERNAME = os.environ["CMQ_USERNAME"]
PASSWORD = os.environ["CMQ_PASSWORD"]
TOPIC = "acme/istanbul/assembly/line1/cnc-01/telemetry"


def on_connect(client, userdata, flags, reason_code, properties):
    print("Connected:", reason_code)
    client.subscribe(TOPIC, qos=1)


def on_message(client, userdata, msg):
    print(msg.topic, msg.payload.decode())


client = mqtt.Client(
    mqtt.CallbackAPIVersion.VERSION2,
    client_id=CLIENT_ID,
    protocol=mqtt.MQTTv5,
)
client.on_connect = on_connect
client.on_message = on_message
client.username_pw_set(USERNAME, PASSWORD)
client.tls_set()  # the system CA store verifies the broker certificate

client.connect(HOST, PORT, keepalive=60)
client.loop_start()

while True:
    reading = {"temperature": 62.4, "spindleRpm": 11950}
    client.publish(TOPIC, json.dumps(reading), qos=1)
    time.sleep(5)

Set the three environment variables first:

bash
export CMQ_CLIENT_ID=connectmq_client_123456
export CMQ_USERNAME=cmq_xxxxxxxxxxxx
export CMQ_PASSWORD='your-password'
python main.py
powershell
$env:CMQ_CLIENT_ID = "connectmq_client_123456"
$env:CMQ_USERNAME = "cmq_xxxxxxxxxxxx"
$env:CMQ_PASSWORD = "your-password"
python main.py

Notes ​

  • client.tls_set() with no arguments uses the operating system's trusted CAs. Do not disable certificate verification.
  • Send JSON objects such as {"temperature": 62.4}: the console turns every numeric field into a live value with a sparkline, and alert rules can test each field.
  • Use loop_forever() for subscriber-only scripts and loop_start() when your own loop publishes.
  • More samples (public broker, MQTT 3.1.1, TLS options) are in connectmq/mqtt-code-samples.

Fully managed MQTT broker for connected devices.