Two MQTT events triggered for one switch action


You’ll have to excuse me as I’m just getting into this stuff but I’ve got a problem with duplicate items appearing in my MQTT queue.

So… What I’m trying to achieve is this:

  1. I move a switch on OpenHab and an entry is placed in the MQTT queue for that action.
  2. Something else can enter the action into the MQTT queue and OpenHab will reflect that change.

I currently have the following openHab config:
Items file:
Switch mqttSwitch {mqtt=">[remotepi:/myhouse/office/light:command:ON:1],>[remotepi:/myhouse/office/light:command:OFF:0]"} String mqttMessage { mqtt="<[remotepi:/myhouse/office/light:state:default]" }

Frame label="MQTT" { Switch item=mqttSwitch }

rule "MqttMessageChanged" when Item mqttMessage changed then switch mqttMessage.state { case '1': mqttSwitch.sendCommand("ON") case '0': mqttSwitch.sendCommand("OFF") } end

It all works lovely apart from the duplicated messages:
$ mosquitto_sub -t '/myhouse/#' 1 1 0 0
is one on/off of the switch and exactly the same happens when I issue these:
$ mosquitto_pub -t /myhouse/office/light -m '1' $ mosquitto_pub -t /myhouse/office/light -m '0'
$ mosquitto_sub -t '/myhouse/#' 1 1 0 0

Thanks for your help!

OK, so here is what happens, step by step.

  1. You move the switch on your sitemap which generates a sendCommand to mqttSwitch. Lets say the new state is ON.

  2. The sendCommand causes the MQTT binding to publish the message “1” to the topic

  3. The mqttMessage Item reads the message “1” off of the topic.

  4. The MqttMessageChanged rule triggers and sendscommand(“ON”) to the mqttSwitch.

  5. The MQTT binding on mqttSwitch publishes a second message “1” to the topic.

  6. The mqttMessage Item reads the message “1” off of the topic.

  7. The MqttMessageChanges rule does not trigger because this time the mqttMessage state doesn’t change.

This is why you are seeing the duplicate messages.

I believe the fix for this will be to use postUpdate in your rule instead of sendCommand. postUpdate will change the state of mqttSwitch without triggering the MQTT binding to send a message to the topic.

1 Like

Ah great thank you. I wondered if that sort of situation was happening but hoped that the MQTT stuff was intelligent enough to stop that sort of thing going on.

That works perfectly :smile: