tencent cloud

TDMQ for MQTT

Release Notes and Announcements
Release Notes
Product Introduction
TDMQ Product Series Introduction and Selection
What Is TDMQ for MQTT
Scenarios
Technical Architecture
Product series
MQTT Protocol Compatibility Notes
Comparison with Apache
High Availability
Product Constraints and Usage Quota
Basic Concepts
Supported Regions
Billing
Billing Overview
Renewal Instructions
Viewing Consumption Details
Overdue Payment Instructions
Refund
Getting Started
Guide for Getting Started
Preparations
Public Network Access
VPC Network Access
User Guide
Usage Process Guide
Configuring Account Permission
Creating a Cluster
Managing Topic
Connecting to the Cluster
Querying Messages
Managing Client
Managing a Cluster
Viewing Monitoring Metrics and Configuring Alarm Policies
Data Integration
Integrating Data Into SCF
Integrating Data Into CKafka
Integrating Data into RocketMQ
Development Guide
MQTT 5 Advanced Features
Data Plane HTTP API Description
Quota and Flow Control Mechanism Description
Configuring a Custom Domain Name
Configuring SQL Filtering
Configuring Point-to-Point Subscription
MQTT over QUIC
Managing Client Subscription
Message Enhancement Rule
Use Cases
Must-Knows for MQTT Client Development
Observability
Topic and Wildcard Subscriptions
​​API Reference
History
Introduction
API Category
Making API Requests
Cluster APIs
Topic APIs
Authorization Policy APIs
User APIs
Client APIs
Message Enhancement Rule APIs
Message APIs
Data Types
Error Codes
SDK Reference
Access Point Format
Java SDK
C SDK
Javascript/Node.JS/Mini Program
Go SDK
iOS SDK
JavaScript SDK
Dart SDK
Python SDK
.NET
Security and Compliance
Permission Management
FAQs
Related Agreement
Privacy Policy
Data Privacy And Security Agreement
TDMQ for MQTT Service Level Agreement
Contact Us

Python SDK

Focus Mode
Font Size
Last updated: 2026-04-01 16:37:52

Feature Overview

Eclipse Paho Python is the Python client library under the Eclipse Paho project. It can connect to an MQTT broker to publish messages, subscribe to topics, and receive published messages.
The client depends on Google's proxy and websockets packages, which can be installed through the following command.

Cloud Resource Preparation

Please refer to the operation step of creating a resource to complete cloud resource preparation.

Environment Preparation

mkdir -p /root/quick-start && python3 -m venv /root/quick-start
cd /root/quick-start
./bin/pip3 install paho-mqtt
Notes:
Paho-MQTT only supports Python 3.7+.

Sample Code

Save the following code to /root/quick-start/example.py
# python 3.11

import time
import logging

from paho.mqtt import client as mqtt_client


host = 'mqtt-sample-sh-public.mqtt.tencenttdmq.com'
port = 1883
topic = "home/room/1"
client_id = 'QuickStart'
username = 'your-username'
password = 'your-password'

FIRST_RECONNECT_DELAY = 1
RECONNECT_RATE = 2
MAX_RECONNECT_COUNT = 12
MAX_RECONNECT_DELAY = 60

def on_disconnect(client, userdata, rc, properties):
logging.info("Disconnected with result code: %s", rc)
reconnect_count, reconnect_delay = 0, FIRST_RECONNECT_DELAY
while reconnect_count < MAX_RECONNECT_COUNT:
logging.info("Reconnecting in %d seconds...", reconnect_delay)
time.sleep(reconnect_delay)

try:
client.reconnect()
logging.info("Reconnected successfully!")
return
except Exception as err:
logging.error("%s. Reconnect failed. Retrying...", err)

reconnect_delay *= RECONNECT_RATE
reconnect_delay = min(reconnect_delay, MAX_RECONNECT_DELAY)
reconnect_count += 1
logging.info("Reconnect failed after %s attempts. Exiting...", reconnect_count)

def on_message(client, userdata, msg):
print(f"Received `{msg.payload.decode()}` from `{msg.topic}` topic")

def connect_mqtt():
def on_connect(client, userdata, flags, rc, properties):
if rc == 0:
print("Connected to MQTT Broker!")
else:
print("Failed to connect, return code %d\\n", rc)
logging.basicConfig(level=logging.DEBUG)
client = mqtt_client.Client(mqtt_client.CallbackAPIVersion.VERSION2, client_id, clean_session=True, userdata=None, protocol=mqtt_client.MQTTv311)
client.username_pw_set(username, password)
client.on_connect = on_connect
client.on_disconnect = on_disconnect
client.on_message = on_message
client.enable_logger()
client.connect(host, port)
return client

def on_subscribe(client, userdata, mid, reason_code_list, properties):
# Since we subscribed only for a single channel, reason_code_list contains
# a single entry
if reason_code_list[0].is_failure:
print(f"Broker rejected you subscription: {reason_code_list[0]}")
else:
print(f"Broker granted the following QoS: {reason_code_list[0].value}")

def on_unsubscribe(client, userdata, mid, reason_code_list, properties):
# Be careful, the reason_code_list is only present in MQTTv5.
# In MQTTv3 it will always be empty
if len(reason_code_list) == 0 or not reason_code_list[0].is_failure:
print("unsubscribe succeeded (if SUBACK is received in MQTTv3 it success)")
else:
print(f"Broker replied with failure: {reason_code_list[0]}")

def subscribe(client):
client.on_subscribe = on_subscribe
client.on_unsubscribe = on_unsubscribe
# Subscribe topic with QoS 1
client.subscribe(topic, 1)
print(f"Subscribed `{topic}`")


def publish(client):
msg_count = 1
while True:
time.sleep(1)
msg = f"messages: {msg_count}"
result = client.publish(topic, msg)
# result: [0, 1]
status = result[0]
if status == 0:
print(f"Send `{msg}` to topic `{topic}`")
else:
print(f"Failed to send message to topic {topic}")
msg_count += 1
if msg_count > 5:
break


def run():
client = connect_mqtt()
client.loop_start()
subscribe(client)
publish(client)
client.loop_stop()
time.sleep(30)


if __name__ == '__main__':
run()


Running Example

cd /root/quick-start
./bin/python3 example.py

Sample Output

DEBUG:paho.mqtt.client:Sending CONNECT (u1, p1, wr0, wq0, wf0, c1, k60) client_id=b'quick-start'
DEBUG:paho.mqtt.client:Sending SUBSCRIBE (d0, m1) [(b'home/room/1', 1)]
Subscribed `home/room/1`
DEBUG:paho.mqtt.client:Received CONNACK (0, 0)
Connected to MQTT Broker!
DEBUG:paho.mqtt.client:Received SUBACK
Broker granted the following QoS: 1
DEBUG:paho.mqtt.client:Sending PUBLISH (d0, q0, r0, m2), 'b'home/room/1'', ... (11 bytes)
Send `messages: 1` to topic `home/room/1`
DEBUG:paho.mqtt.client:Received PUBLISH (d0, q0, r0, m0), 'home/room/1', ... (11 bytes)
Received `messages: 1` from `home/room/1` topic
DEBUG:paho.mqtt.client:Sending PUBLISH (d0, q0, r0, m3), 'b'home/room/1'', ... (11 bytes)
Send `messages: 2` to topic `home/room/1`
DEBUG:paho.mqtt.client:Received PUBLISH (d0, q0, r0, m0), 'home/room/1', ... (11 bytes)
Received `messages: 2` from `home/room/1` topic
DEBUG:paho.mqtt.client:Sending PUBLISH (d0, q0, r0, m4), 'b'home/room/1'', ... (11 bytes)
Send `messages: 3` to topic `home/room/1`
DEBUG:paho.mqtt.client:Received PUBLISH (d0, q0, r0, m0), 'home/room/1', ... (11 bytes)
Received `messages: 3` from `home/room/1` topic
DEBUG:paho.mqtt.client:Sending PUBLISH (d0, q0, r0, m5), 'b'home/room/1'', ... (11 bytes)
Send `messages: 4` to topic `home/room/1`
DEBUG:paho.mqtt.client:Received PUBLISH (d0, q0, r0, m0), 'home/room/1', ... (11 bytes)
Received `messages: 4` from `home/room/1` topic
DEBUG:paho.mqtt.client:Sending PUBLISH (d0, q0, r0, m6), 'b'home/room/1'', ... (11 bytes)
Send `messages: 5` to topic `home/room/1`
Received `messages: 5` from `home/room/1` topic


Help and Support

Was this page helpful?

Help us improve! Rate your documentation experience in 5 mins.

Feedback