tencent cloud

ドキュメントTDMQ for MQTT

Python SDK

フォーカスモード
フォントサイズ
最終更新日: 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


ヘルプとサポート

この記事はお役に立ちましたか?

フィードバック