【问题标题】:MQTT in Python, subscriber not respondingPython中的MQTT,订阅者没有响应
【发布时间】:2021-07-13 11:30:13
【问题描述】:

跟随这个伟大的tutorial 在 Python 中实现 MQTT。当我运行发布者脚本但挂在订阅者脚本上时工作正常。我在不同的命令行中同时运行这两个脚本。这是我的两个代码:

#pub.py

import paho.mqtt.client as mqtt
import logging
import json
import time
import random
logging.basicConfig(level=logging.INFO)
# use DEBUG, INFO, WARNING

username="xxxxx"
password="xxxxx"
broker_url ='xxxxx'
broker_port=0000
client_id=f"client-{random.randint(0, 100)}"
to_wait=5
topic='hey-hey'
publish_count = 3
msg= 'Hey'

def on_log(client, userdata, level, buf):
    logging.info(buf)
    client.on_log = on_log

def connect_mqtt():
    def on_connect(client, userdata, flags, rc):
        if rc == 0:
            logging.info("Connected to Broker!: {}".format(rc))
        else:
            logging.info("Failed to Connect with code: "+str(rc))
    
    client = mqtt.Client(client_id)
    client.username_pw_set(username, password)
    client.on_connect = on_connect
    client.connect(broker_url, broker_port)
    return client

def on_publish(client):
    count = 1
    while count <= publish_count:
        time.sleep(to_wait)
        message = str(msg)
        result = client.publish(topic, message, 1, 1)
        status = result[0]
        if status == 0:
            published= client_id+ ' sent the message: ' +message)
            print(published)
        else:
            print(f"Failed to send the message")
        count +=1
        
def run():
    device1 = connect_mqtt()
    device1.loop_start
    on_publish(device1)
    device1.loop_stop()
    
if __name__ == '__main__':
    run()

我得到:

client-27 sent the message: Hey
client-27 sent the message: Hey
client-27 sent the message: Hey

但是,对于 sub.py

import paho.mqtt.client as mqtt
import logging
import json
import time
import random
logging.basicConfig(level=logging.INFO)
from datetime import datetime 
# use DEBUG, INFO, WARNING

username="xxxx"
password="xxxxxx"
broker_url ='xxxxx'
broker_port=0000
client_id=f"client-{random.randint(0, 100)}"
to_wait=5
topic='hey-hey'
publish_count = 3

def on_log(client, userdata, level, buf):
    logging.info(buf)
    client.on_log = on_log

def connect_mqtt():
    def on_connect(client, userdata, flags, rc):
        if rc == 0:
            logging.info("Connected to Broker!: {}".format(rc))
        else:
            print("Failed to Connect with code: "+str(rc))
            client.loop_stop()
    
    client = mqtt.Client(client_id)
    client.username_pw_set(username, password)
    client.on_connect = on_connect
    client.connect(broker_url, broker_port, 60)
    return client

def subscribe(client):
    def on_subscribe(client,userdata, mid, granted_qos):
        logging.info('subscribed')
        
    client.subscribe(topic)
    client.subscribe = on_subscribe


def process_message(client, userdata, message):
    msgr=str(message.payload.decode('utf-8'))
    msgr='Message Received' + msgr
    logging.info(msgr)
        
def run():
    device2 = connect_mqtt()
    device2.on_message = process_message
    device2.loop_forever()
    
    
if __name__ == '__main__':
    run()

它只是挂起并超时。我错过了什么吗?

【问题讨论】:

  • “它只是挂起并超时” - 什么超时(似乎不太可能是连接,因为建立连接的代码看起来相同),你有没有得到任何输出(例如“连接到代理!” )。
  • @Brits 什么都没有发生,甚至没有“连接到经纪人!”。只是挂在终端上。
  • 好的addlogging.getLogger().setLevel(logging.INFO)。请确认您正在运行sub.py,然后在单独的终端窗口中运行pub.py
  • 是的,首先运行 sub.py,然后运行 ​​pub.py,并且还添加了建议并面临同样的问题。
  • on_publish 是发布代码中函数名称的错误选择。该名称通常用于来自客户端的回调,以表示消息已发送到代理。使用它只会造成混乱。

标签: python mqtt


【解决方案1】:

您永远不会在订阅者代码中调用subscribe(),因此它永远不会告诉代理它想要接收哪些主题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多