Translate MQTT payload to commands

  • openHABian v3 on rPi4

I have a Sonoff button that sends three actions: single, double, and long, which I’d like to translate to commands.

These actions should behave like toggles. E.g., single = ON|OFF.

My rule looks as follows:

val String LOG_PREFIX = "ShedLights."
var int sonoff_button_02_switch = 0

rule "ShedLights: translate button actions to commands"
	    Channel "mqtt:topic:mosquitto:sonoff_button_02:buttonaction" triggered
        //if (debug == 1)
            logInfo(LOG_PREFIX + "03.01",
                "SO Button 02 buttonaction is {}", receivedEvent)

            case "single":
                if (sonoff_button_02_switch == 0)
                    sonoff_button_02_switch = 1
                    sonoff_button_02_switch = 0

        //if (debug == 1)
            logInfo(LOG_PREFIX + "03.02",
                "SO Button 02 state is {}", sonoff_button_02_switch)

… but it does not get triggered.

I have a thing, with a channel called buttonaction as string, receiving this topic:

  - id: buttonaction
    channelTypeUID: mqtt:string
    label: Button Action
    description: ""
      stateTopic: zigbee2mqtt/KDL/Max_Troffer_Light/action


  1. Is this even the right approach?
  2. If so, why is the rule not triggered?
  3. If not, any pointers for a better approach are appreciated.

One of the main points of having logging levels is to be able to control what gets logged through config (i.e. log4j2.xml) and not changes to the code. If you use logDebug then you can configure the logger through the Karaf console, REST API, or log4j2.xml file to log at the INFO level and that statement will not appear in the log file.

By not triggering you mean that there are no logs to indicate the rule is being triggered? Or the switch statement isn’t running?

It seems reasonable. You can’t use the rawRocker or rawButton profiles because those only support two commands, not three. So a rule is what needs to be used here.

That’s not a trigger Channel. That’s a state Channel. So you either need to change it to be a trigger Channel:

Or you need to link your existing Channel to a String Item and change your rule trigger to an Item received update or, even better, modify your Channel config to treat messages as commands and use an Item received command trigger.

Given these are momentary events and not states, the more canonical approach would be the make the Channel be a trigger Channel.

1 Like

So much to learn! :slight_smile:

Changing that channel to a trigger made the rule work. Thank you.

While I say ‘changing’, I had to delete and recreate the channel.

As for the log levels; I understand what you mean, but I use these only while developing rules.