MQTT用 python 收消息的例子

在MQTT官网给的 sub_wss.py 例子中修改

第一步要安装 paho-mqtt

pip install paho-mqtt

第二步开始写代码

改写自己的用户名和密码

BROKER = '*******.ala.cn-hangzhou.emqxsl.cn'    //改成自己的连接地址

USERNAME = '**************' //用户名
PASSWORD = '*************'  //密码

注意这句是 改使用 v1 回调 API(与旧版本的库一起使用)。

原因:Release 2.0.0 包含重大更改;这意味着,如果没有一些(最小的)修改,为 v1.x 编写的代码将无法工作。由于 v2.0.0几天前才发布,大多数示例(包括您引用的示例)将无法工作。

原代码

client = mqtt_client.Client(CLIENT_ID, transport='websockets')

运行报错

 要改为

client = mqtt.Client(client_id=CLIENT_ID, transport='websockets',callback_api_version=mqtt.CallbackAPIVersion.VERSION1)

这个密钥在官网下载,放在与python文件同一目录下

client.tls_set(ca_certs='./emqxsl-ca.crt')

完整代码

# python 3.6

import logging
import random
import time

#from paho.mqtt import client as mqtt_client
import paho.mqtt.client as mqtt

BROKER = '*******.ala.cn-hangzhou.emqxsl.cn'
PORT = 8084
TOPIC = "python-mqtt/wss"
# generate client ID with pub prefix randomly
CLIENT_ID = f'python-mqtt-wss-sub-{random.randint(0, 1000)}'
USERNAME = '********'
PASSWORD = '********'

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

FLAG_EXIT = False


def on_connect(client, userdata, flags, rc):
    if rc == 0 and client.is_connected():
        print("Connected to MQTT Broker!")
        client.subscribe(TOPIC)
    else:
        print(f'Failed to connect, return code {rc}')


def on_disconnect(client, userdata, rc):
    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)
    global FLAG_EXIT
    FLAG_EXIT = True


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


def connect_mqtt():
    client = mqtt.Client(client_id=CLIENT_ID, transport='websockets',callback_api_version=mqtt.CallbackAPIVersion.VERSION1)
    #client = mqtt_client.Client(CLIENT_ID, transport='websockets')
    client.tls_set(ca_certs='./emqxsl-ca.crt')
    client.username_pw_set(USERNAME, PASSWORD)
    client.on_connect = on_connect
    client.on_message = on_message
    client.connect(BROKER, PORT, keepalive=120)
    client.on_disconnect = on_disconnect
    return client


def run():
    logging.basicConfig(format='%(asctime)s - %(levelname)s: %(message)s',
                        level=logging.DEBUG)
    client = connect_mqtt()
    client.loop_forever()


if __name__ == '__main__':
    run()

测试

启动这个python程序

官网的 demo

 主题 

python-mqtt/wss

点订阅

 改主题为  python-mqtt/wss  。填写消息内容。点  发布  ,在python中就会收到这个消息

 

posted @ 2024-04-09 14:21  海乐学习  阅读(208)  评论(0编辑  收藏  举报