gpt4 book ai didi

Python paho mqtt客户端不会同时发布和订阅

转载 作者:太空宇宙 更新时间:2023-11-03 15:14:44 26 4
gpt4 key购买 nike

当我通过 MQTTLens 测试发布时,它有效。然而,当我按下按钮时,它确实会触发“on_publish”,但另一端的 on_message 没有收到任何内容;它没有被触发。有两个 Raspberry Pi 运行相同的脚本,唯一的区别是它们的代理 IP 并且主题相反。

import RPi.GPIO as io
import os
import json
from time import sleep
import paho.mqtt.client as mqtt
import paho.mqtt.publish as publish

############### MQTT section ##################

Broker = "192.168.1.10"

rcv_topic = "home/groundfloor/livingroom/lights/lightx" # receive messages on this topic
snd_topic = "home/groundfloor/kitchen/lights/lightx" # send messages to this topic

def on_connect(mqttc, obj, flags, rc):
print("rc: "+str(rc))
mqttc.subscribe(rcv_topic) #receving/subscriber

#when receving a message:
def on_message(mqttc, obj, msg):
print("sub") #this is not being executed on button push, but it is when I publish through the MQTTLens
print(msg.topic+" "+str(msg.qos)+" "+str(msg.payload))
try:
p = msg.payload.decode("utf-8")
print("decoded payload: " + p)
x = json.loads(p)
set_leds(leds, tuple(x['leds'])) #set leds to received value

return
except Exception as e:
print(e)

# callback functie voor publish event
def on_publish(mqttc, obj, mid):
print("pub")
return

mqttc = mqtt.Client()
mqttc.on_message = on_message
mqttc.on_connect = on_connect
mqttc.on_publish = on_publish
mqttc.on_subscribe = on_subscribe
mqttc.connect(Broker, 1883, 60) #last could be a port too
mqttc.loop_start() #client.loop_forever()

############### led&button section ##################
def init_leds(leds):
io.setup(leds, io.OUT)

def set_leds(leds, states):
print("leds and states: " + str(leds) + " " + str(states))
io.output(leds, states)

def snd_msg(led):
dataToSend=json.dumps({"leds":[led1State,led2State]})
print("data: " + dataToSend)
mqttc.publish(snd_topic, dataToSend)

io.add_event_detect(btn1,io.FALLING,callback=lambda *a: snd_msg(1),bouncetime=500)

############### main ##################

def main():
try:
while True:
init_leds(leds)
except KeyboardInterrupt:
pass
finally:
io.cleanup()

#toplevel script
#below will only execute if ran directly - above is always accessible
if __name__ == '__main__':
main()

我只包含了与我的问题直接相关的代码部分,并将其中一些修改得更短。但是,如果需要更多代码,我随时可以提供。

我意识到这可能与此 question 重复。 ,但我已经尝试从答案中派生出我的代码,除非我做错了什么,否则它似乎无法解决我的问题。

最佳答案

您似乎正在两个不同的 IP 上发布和订阅。为了接收消息,您必须在 IP 192.168.1.10(我假设这是您的代理 IP)上发布主题 TOPIC_TEST(假设),并在 IP 192.168.1.10 上订阅同一主题 TOPIC_TEST。

关于Python paho mqtt客户端不会同时发布和订阅,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43955608/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com