我正在实现一个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()
。
任何帮助,直接或推荐阅读将不胜感激。
答案 0 :(得分:1)
根据您显示的内容,您需要使用global
标志更新函数外的data
变量。
data = ''
def mess(client, userdata, message):
global data
data = "{'" + str(message.payload) + "', " + str(message.topic) + "}"
subscribe
函数也不会按原样返回,因为它调用cl.loop_forever()
。如果您想要它返回,请致电cl.loop_start()
在data
中打印subscribe
将无效,因为客户端无法在您启动网络循环(打印后的行)之前实际处理传入的消息。
此外,无法保证在您订阅主题后会传递消息。
在完全了解你想要实现的目标的情况下,我无法提供更多帮助,但我认为你需要回过头来看看你的整个方法,以了解pub / sub messaging的异步性质
答案 1 :(得分:0)
我有完全相同的问题,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 打印。
答案 2 :(得分:-1)
不使用提到的全局变量方法,也可以使用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
这可以避免在使用时丢失任何传入数据或被访问数据的任何损坏。