繁体   English   中英

在python paho mqtt中返回on_message数据

[英]return data on_message in python paho mqtt

我正在实施一个 paho mqtt 客户端。 这是我的代码:

import paho.mqtt.client as mqtt


def mess(client, userdata, message):
   print("{'" + str(message.payload) + "', " + str(message.topic) + "}")


def subscribe(c_id, topic, server, port):
   cl = mqtt.Client(c_id)
   cl.connect(server, port)
   cl.subscribe(topic)
   cl.on_message = mess
   cl.loop_forever()

这工作正常,但我不想在“混乱”中打印数据。 我需要将print()的字符串返回给调用函数。 我正在从另一个程序调用subscribe() 任何帮助,直接或推荐阅读将不胜感激。

根据您所展示的内容,您需要使用global标志来更新函数外部的data变量。

data = ''

def mess(client, userdata, message):
  global data
  data = "{'" + str(message.payload) + "', " + str(message.topic) + "}"

此外subscribe函数永远不会返回原样,因为它调用cl.loop_forever() 如果你想让它返回,你应该调用cl.loop_start()

subscribe打印data也不起作用,因为在您启动网络循环(打印后的行)之前,客户端实际上无法处理传入的消息。

此外,在您订阅主题后,也无法保证何时会发送消息。

由于不知道更多关于您想要实现的目标,我无法提供更多帮助,但我认为您需要回过头来看看您的整个方法,以了解发布/订阅消息的异步性质

我有完全相同的问题,hardillb 的回答确实有帮助。 我只想给出使用loop_start()loop_stop()的完整示例。

import paho.mqtt.client as mqtt
import time

current_pose = -1
def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))
    print("The position will will be printed in [mm]")
    client.subscribe("send position",qos=1)

def on_message(client, userdata, msg):
    global current_pose
    current_pose = msg.payload.decode('utf8')
    print("Position = ",current_pose)

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect("localhost", 1883, 60)
client.loop_start()

for i in range(0,10):
    time.sleep(1) # wait 1s
    print('current_pose = ', current_pose)
    
client.loop_stop() 
print('the position will not be updated anymore') 

在这个例子中,位置在十秒内每秒打印一次,此外,数据将由回调 on_message 打印。

除了使用提到的全局变量方法,还可以使用Queue包。

import Queue
import paho.mqtt.client as mqtt

q = Queue.Queue() #initialises a first in first out queue

def mess(client, userdata, message):
    q.put(("{'" + str(message.payload) + "', " + str(message.topic) + "}"))

if not q.empty(): #check if the queue is empty
    msg = q.get()  #get the first message which was received and delete

这避免了丢失任何传入数据或在使用时被覆盖的访问数据的任何损坏。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM