比较MQTT主题的先前和当前发布的值

时间:2018-10-23 09:42:51

标签: python mqtt mosquitto paho

我的问题是如何比较每个主题的当前发布值和先前发布值,并决定是否将命令发送到设备以进行开/关。 如果状态已从先前状态更改,我想发送命令以点亮,否则将不发送命令。 我有以下代码。

import paho.mqtt.client as mqtt #import the client1
import time
def on_message(client, userdata, message):
    print("message received " ,str(message.payload.decode("utf-8")))    
    print("message topic=", message.topic)
    print("message qos=",message.qos)
    print("message retain flag=",message.retain)

def on_connect(client, userdata, flags, rc):    
    print("Connected with result code "+str(rc))    

broker_address="127.0.0.1"
print("creating new instance")
client = mqtt.Client("P1") 
client.on_connect=on_connect
client.on_message=on_message 
print("connecting to broker")
client.connect(broker_address) #connect to broker
client.loop_start()
print("Subscribing to all topics")
client.subscribe("#")
print("Publishing message to topic","house/bulbs/bulb1")
client.publish("house/bulbs/bulb1","OFF",qos=0,retain=true)
client.publish("house/bulbs/bulb1","ON",qos=0,retain=true)

print("Publishing message to topic", "house/bulbs/bulb2")
client.publish("house/bulbs/bulb2", "ON")
client.publish("house/bulbs/bulb2", "ON")
time.sleep(4) # wait
client.loop_stop() #stop the loop

1 个答案:

答案 0 :(得分:0)

唯一的方法是将状态存储在代码中,并将传入的消息与该存储的值进行比较。

import paho.mqtt.client as mqtt #import the client1

bulb1 = OFF
bulb2 = OFF

def on_message(client, userdata, message):
    global bulb1
    global bulb2
    print("message received " ,str(message.payload.decode("utf-8")))    
    print("message topic=", message.topic)
    print("message qos=",message.qos)
    print("message retain flag=",message.retain)

    if message.topic == 'house/bulbs/bulb1':
      if bulb1 != str(message.payload.decode("utf-8")):
          #State changed
          bulb1 = str(message.payload.decode("utf-8"))

def on_connect(client, userdata, flags, rc):    
    print("Connected with result code "+str(rc))  
    client.subscribe("#")  

broker_address="127.0.0.1"
print("creating new instance")
client = mqtt.Client("P1") 
client.on_connect=on_connect
client.on_message=on_message 
print("connecting to broker")
client.connect(broker_address) #connect to broker
client.loop_start()


print("Publishing message to topic","house/bulbs/bulb1")
client.publish("house/bulbs/bulb1","OFF",qos=0,retain=true)
client.publish("house/bulbs/bulb1","ON",qos=0,retain=true)

print("Publishing message to topic", "house/bulbs/bulb2")
client.publish("house/bulbs/bulb2", "ON")
client.publish("house/bulbs/bulb2", "ON")
time.sleep(4) # wait
client.loop_stop() #stop the loop