Trigger an item's sendCommand from a remote MQTT client

Let’s imagine you use a binding for some things/items. You have linked binding things to some items and all is working great but only via Openhab UI. Now you want to control this item from outside, for example via MQTT. How to do this?

Initially you would need to create a channel for your broker. You can do that via Paper UI or via file:

Bridge mqtt:broker:main "MQTT Broker" [ host="192.168.1.2"] {
    Channels:
        Type publishTrigger: command_item "Command" [ stateTopic="openhab/command/item/+", separator="#" ]
}

Then you need to add a generic send command rule that would be triggered on a MQTT’s set_command channel:

import org.eclipse.smarthome.model.script.ScriptServiceUtil
rule "MQTT item command"
when
    Channel "mqtt:broker:main:command_item" triggered
then
    val arr = receivedEvent.getEvent().split("#", 2)
    val tarr = arr.get(0).split("/")
    val item_name = tarr.get(tarr.length - 1)
    val payload = arr.get(1)

    val item = ScriptServiceUtil.getItemRegistry.getItem(item_name)
    item.sendCommand(payload)
end

As simple as that.

Now when you send a payload to mqtt topic openhab/command/item/MyItem
MyItem will receive command with your MQTT payload.

IMHO the mqtt rule action as described Here is the build-in way to do such.

Is this not what the MQTT channel’s postCommand option is for, too?

1 Like

Yes it is. Well spotted, young man. It works very well too, I might add.

This is essentially how MQTT 2.5 Event Bus works, at least on the subscription side. If you are using Scripted Automation, you can get this capability from the Helper Libraries which will eventually just come with OH. See the link above for the publishing side of things too.

@opus The link to the doc that you provided shows exactly opposite direction from what I posted. In my example I show Direction from remote MQTT client -> Openhab2 MQTT.

In this case I completly misunderstood/misread the “control this item from outside” part of your post. Sorry for that🤔

Probably it requires a better wording. Any suggestions?