Using MQTT command for Switch Item

OK, given that there is only one message sent I would do the following.

  • Create a String Item that receives the message
String Sonoff_Basic_01_String {mqtt="<[mosquitto:cmd/sonoff-basic-01-switch/POWER1:state:default]"}
  • Create a Switch Proxy Item to represent the state of the physical device (see below)

  • Create a rule that triggers when the String Item receives an update. This rule will update the Switch to the proper state (presumably toggle it’s state?)

rule "Update Switch Proxy Item"
when
    Item Sonoff_Basic_01_String received update
then
    if(Sonoff_Basic_01_Switch.state == ON) Sonoff_Basic_01_Switch.postUpdate(OFF)
    else Sonoff_Basic_01_Switch.postUpdate(ON)
end
  • Add the outbound MQTT configuration to the Switch Item
Switch	Sonoff_Basic_01_Switch	["Lighting"] {mqtt=">[mosquitto:cmnd/sonoff-basic-01-switch/POWER1:command:*:TOGGLE]"}

Notice the modifications to the MQTT binding config in both cases.

I prefer this approach as it is a little easier to avoid infinite loops (i.e. the Switch publishes TOGGLE which causes the Switch Item to change which causes the MQTT binding to publish TOGGLE which causes …). Though you are not completely out of the woods here. Because the same topic is being used for communication both directions you may still be getting into an infinite loop because the client has no way to distinguish between messages it sent itself verses those sent by the device.

Anyway, the key in avoiding the loop is the use of postUpdate which only modifies the state of the Item in OH and does not trigger the binding to send the message to the device.

2 Likes