Using a stateless MQTT command with OpenHAB

Tags: #<Tag:0x00007f61796e0190> #<Tag:0x00007f61796e00a0>

Hi all,
Thanks for reading.

I have an Arduino setup as a light switch controller for my OpenHAB installation. With each press of a button the Arduino publishes an MQTT message with the topic “buttons” and the payload containing the button number, ie “10-01”, This broadcast is stateless, just a button number and not off or on.

Can I use this to toggle a switch in OpenHAB on and off? Furthermore, if the switch is toggled in OpenHAB will it keep track of the state.
This is controlling a customized Sonoff Basic that responds on the topic of “Sonoff_01/cmd” with a payload of 1 or 0. I will eventually be also deploying addtional Sonoff Basic’s and either Pi Zero or Arduino to control a relay board.

I have been researching this for weeks and getting nowhere.

I’m not sure if this is the best way to go, but I have resorted to writing a python script running on my RPi server that takes the Arduino Switch controller’s stateless broadcast and re-broadcasts using the Topic “buttons/10-01” with the payload 1 or 0 and keeping track of its state. Although I have this working, I have, however not been successful in getting this to update as the switch is changed in OpenHAB, or any of the OpenHAB clients (IOS and Windows 10 App).

Many thanks for your help.

Bill

You can have a Number Item:

Number SwitchNumber { mqtt="broker:buttons:command:default" }

Then a rule:

rule "Arduino switches"
when
    Item SwitchNumber received command
then
    var switchNo = received command
    if (switchNo == 1) {
        // Do want you want for switch 1
    } else if (switchNo == 2) {
        // Do what you want for switch 2
    } // else if and so on...
end

The state will be kept
You can set-up persistence to get a history or restoring at boot

In other words this device sends a “change” command only!

Using a rule as posted above would connect that recieved “change” command by switching the connected item from ON to OFF or vice versa.
The OH item does keep track those received commands, however there is no way to actively sync those since you do neither send an explicit command (like ON or OFF) nor does your switch report it’s state ( at least we have to assume that).

Thanks for the replies.
I’ll give it a go.
I must admit, I’m very new at this, and although I have some programming experience, finding the syntax and structure in this a little daunting, especially trying to get the syntax right with mqtt and rules.

I’m sure I’ll be back with another question very soon :wink:

Many thanks, Bill