【发布时间】:2017-05-13 16:47:22
【问题描述】:
当我通过 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 重复,但我已经尝试从答案中导出我的代码,除非我做错了什么,否则它似乎无法解决我的问题。
【问题讨论】:
-
请编辑代码以包含
on_connect函数,以便我们检查您如何/何时进行订阅。 -
我已经添加了!
-
我看不出 MQTT 方面有什么问题。目前我没有任何东西可以连接到 pi 上的 GPIO 引脚,所以我在
while True循环中交换了一个sys.stdin.readline(),它可以很好地发送/接收消息。 -
你提到交换代理 ips,他们应该都指向同一个代理吗?
-
哦,我不知道我认为他们必须指向他们自己的 IP。我猜那是我的问题?我将尝试同时指向 192.168.1.10 @hardillb