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

时间:2017-05-13 16:47:23

标签: python mqtt paho

当我通过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重复,但我已经尝试从答案中获取代码,除非我做错了,否则它似乎不能解决我的问题。< / p>

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

正如hardillb所建议的那样(我不确定如何标记某人),我的错误是我使用不同的IP作为每个Rpi的经纪人..他们现在都是听1.10并且它有效。

  

你提到交换经纪人ips,肯定他们都应该   指着同一个经纪人? - hardillb