MQTT switch how to get two states?

I’m new to MQTT and I am trying to understand how this works :slight_smile:

I am trying to create a Switch item that can be either ON/OFF and that retrieves its state from a mosquitto topic.

So far I have the item as follows:

Switch Motion "Motion [%s]" { mqtt="<[mosquitto:System/Motion:command:ON]" }

From a SSH I tried publishing messages to that topic as follows:

mosquitto_pub -r -t System/Motion -m “ON”

and

mosquitto_pub -r -t System/Motion -m “OFF”

In another SSH I subscribed to that topic with:

mosquitto_sub -v -t ‘System/Motion’

and whenever I change the state from the other SSH I can see the change happening:

System/Motion OFF
System/Motion ON
System/Motion OFF

But in OH2 I never see the OFF state, it always shows ON!

I also tried and create an outbound switch to try and publish from OH as follows:

Switch mySwitch { mqtt=">[mosquitto:System/Motion:command:ON:1],>[mosquitto:System/Motion:command:OFF:0]" }

I tried using it in a HABPanel and I see the item being changed in OH but it never gets to the topic itself.

What I am I doing wrong? :tired_face:

I made some progress and now I can write to the topic from mySwitch but not read it :disappointed:

Modified item:

Switch mySwitch { mqtt=">[mosquitto:System/Motion:command:ON:ON],>[mosquitto:System/Motion:command:OFF:OFF]" }

I figured it out, the item that is reading has to contain both states like:

Switch Motion "Motion [%s]" { mqtt="<[mosquitto:System/Motion:command:ON:ON],<[mosquitto:System/Motion:command:OFF:OFF]" }

Yay!

Good to hear that you got it to work, although I am a bit surprised as your item-string seems a bit weird.

In my MQTT setup I use a more generic item configuration, and this works well:

Switch Motion "Motion [%s]" { mqtt=">[mosquitto:System/Motion:command:*:default], <[mosquitto:System/Motion:state:default" }

The outbound binding sends a command (ON or OFF) when the switch is toggled, and the inbound binding will post an update with whatever is received on the MQTT topic (meaning that your device should send ON or OFF).