mqtt 学习

from paho.mqtt import client as mqtt_client
import random
import time
import sys
import logging

broker = 'broker.emqx.io'
port = 1883
topic = "/python/mqtt/llt/test"
client_id = f'python-mqtt-03'

def connect_mqtt():
    def on_connect(client, userdata, flags, rc):
        if rc == 0:
            print("====成功 Connected to MQTT Broker!====")
        else:
            print("***Failed to connect, return code %d ***\n", rc)
    # Set Connecting Client ID
    client = mqtt_client.Client(client_id)
    client.on_connect = on_connect
    client.connect(broker, port)
    client.on_subscribe = on_subscribe
    client.subscribe(topic)
    client.on_disconnect = my_on_disconnect
    return client

def on_subscribe(client, userdata, mid, granted_qos):
    print("=== 订阅主题 %s 成功 ===" % topic)

def my_on_disconnect(client, userdata, rc):
    print("===disconnect rc= %s  ===" % rc)
    if rc != 0:
        print("===异常断开 disconnection.rc = %s ===" % rc)
        client.connect_mqtt()
        client.subscribe(topic)
         #client.reconnect()
    else:
        print("===手动断开mqtt rc = %s ===" % rc)
        print("*** 五秒后将尝试重新连接 ***")
        client.reconnect()
        client.subscribe(topic)

def on_message(client, userdata, message):
    print("Received message '" + str(message.payload) + "' on topic '"+ message.topic + "' with QoS " + str(message.qos))
    flag = message.payload
    flag = flag.decode("utf-8")
    flag = (flag.split(': '))[1]
    print("flag = %s" % flag)
    if flag == "10":
        client.disconnect()

def publish(client):
    msg_count = 0
    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 == 20:
            msg_count = 0
            client.disconnect()



def run():
    client = connect_mqtt()
    # client.on_message = on_message
    client.loop_start()
    publish(client)


run()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值