功能概述
云资源准备
环境准备
mkdir -p /root/quick-start && python3 -m venv /root/quick-startcd /root/quick-start./bin/pip3 install paho-mqtt
注意:
paho-mqtt 仅支持 Python 3.7+。
示例代码
将下面代码保存到 /root/quick-start/example.py
# python 3.11import timeimport loggingfrom paho.mqtt import client as mqtt_clienthost = 'mqtt-sample-sh-public.mqtt.tencenttdmq.com'port = 1883topic = "home/room/1"client_id = 'QuickStart'username = 'your-username'password = 'your-password'FIRST_RECONNECT_DELAY = 1RECONNECT_RATE = 2MAX_RECONNECT_COUNT = 12MAX_RECONNECT_DELAY = 60def on_disconnect(client, userdata, rc, properties):logging.info("Disconnected with result code: %s", rc)reconnect_count, reconnect_delay = 0, FIRST_RECONNECT_DELAYwhile reconnect_count < MAX_RECONNECT_COUNT:logging.info("Reconnecting in %d seconds...", reconnect_delay)time.sleep(reconnect_delay)try:client.reconnect()logging.info("Reconnected successfully!")returnexcept Exception as err:logging.error("%s. Reconnect failed. Retrying...", err)reconnect_delay *= RECONNECT_RATEreconnect_delay = min(reconnect_delay, MAX_RECONNECT_DELAY)reconnect_count += 1logging.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_connectclient.on_disconnect = on_disconnectclient.on_message = on_messageclient.enable_logger()client.connect(host, port)return clientdef on_subscribe(client, userdata, mid, reason_code_list, properties):# Since we subscribed only for a single channel, reason_code_list contains# a single entryif 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 emptyif 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_subscribeclient.on_unsubscribe = on_unsubscribe# Subscribe topic with QoS 1client.subscribe(topic, 1)print(f"Subscribed `{topic}`")def publish(client):msg_count = 1while 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 += 1if msg_count > 5:breakdef run():client = connect_mqtt()client.loop_start()subscribe(client)publish(client)client.loop_stop()time.sleep(30)if __name__ == '__main__':run()
运行示例
cd /root/quick-start./bin/python3 example.py
样例输出
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 SUBACKBroker granted the following QoS: 1DEBUG: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` topicDEBUG: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` topicDEBUG: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` topicDEBUG: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` topicDEBUG: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