Marketplace MQTT Event Bus

Update: Complete rewrite to use the rule templates published to the Marketplace. There is no need to code this or copy/paste code to make this work.

There is a Remote openHAB binding which replaces this capability in most cases. See openhab-addons/bundles/org.openhab.binding.remoteopenhab at main · openhab/openhab-addons · GitHub . However there may be use cases where MQTT is preferred, such as integration with a non-openHAB service.

Introduction

What’s an Event Bus?

There are times when one may have more than one OH instance that needs to have some or all of its Items synchronized across all the instances of OH. Another use is using MQTT to integrate openHAB with some other service such as a custom UI or external rule engine.

An Event Bus is a way to synchronize the Items command and updates across multiple instances of OH or other services.

When to use Event Bus

Let’s assume we have a Switch Item on a remote OH named Foo. We want to know the state of that Item on a local OH and we want to be able to send commands to that Item from local OH. This is the perfect use case for the Event Bus. To set this up all updates to Foo on remote OH need to be published to local OH and all commands on Foo’s proxy on local OH need to be published to remote OH.

Remote Foo updates → Event Bus → Local Foo updates
Remote Foo commands ← Event Bus ← Local Foo commands

When not to use the Event Bus

When you want to be able to process commands on both instances of an Item on both instances of OH. For example, if we have Item Foo exposed on the event bus and when a command is issued on Foo on remote OH, local OH needs to receive that command too and when a command is issued on Foo on local OH, Foo on remote OH needs to receive that command too. In that case, a straight forward configuration of the Event Bus will result in an infinite loop.

Remote Foo commands → Event bus → Local Foo commands → Event Bus → Remote Foo commands …

Parts of the Event Bus and General Flow

The event bus will have three parts, the subscription, the publishing, and online status reporting.

We will use the following conventions:

topic purpose
<openHAB name>/out/<Item>/command Topic where all commands that occur on <openHAB name> are published
<openHAB name>/out/<Item>/state Topic where all state updates that occur on <openHAB name> are published
<openHAB name>/in/<Item>/command Topic where commands that occur in another service are published that should be reflected in <openHAB name>.
<openHAB name>/in/<Item>/state Topic where state updates that occur in another service are published that should be reflected in <openHAB name>.

<openHAB name> is a name you chose to uniquely identify each openHAB instance. <Item> will be replaced with the Item name.

Note that you will want to use the same name for all Items that need to be synchronized across the OH instances. In other words, if you have an Item Foo linked to a device on a remote openHAB instance, you need an Item of the same type named Foo on your local openHAB instance.

When integrating multiuple openHAB instances each openHAB instance has four topics for each Item, but you do not use all four topics all of the time. Typically you will only use one or two of the topics at most for any given openHAB instance. In short, an openHAB instance will publish to it’s own out topics but subscribe to another openHAB instance’s out topics. The in topics are only used when integrating with a third party service.

Take the first scenario above where remote OH has an Item named Foo that we want to proxy on local OH. One approach that one might use is:

Instance Event Pub/Sub Topic
local command publish local/out/Foo/command
local update subscribe remote/out/Foo/state
remote command subscribe local/out/Foo/command
remote update publish remote/out/Foo/state

Let’s assume there is a command on Foo on local. The data flow will be:

  1. command received by Foo on local OH
  2. command is published to local/out/Foo/command
  3. command is received by remote OH and triggers the event bus subscription Rule (see below)
  4. remote OH Rule calls sendCommand("Foo", "CMD")
  5. eventually Foo may receive and update as a result of the command
  6. remote OH publish Rule triggers as a result of the update and publishes the update to remote/out/Foo/state
  7. local OH receives the update and triggers the event bus subscription Rule (see below)
  8. local OH calls postUpdate("Foo", "UPD")

This will be the typical configuration when one wants to proxy one or more Items from one OH instance to another. The topics published to and subscribed from for an Item will be those topics associated with the OH instance that has the “real” Item, e.g. the Item linked to the device. In this case, remote owns Foo so it is remote’s topics that are used to get updates.

Another common configuration would be where the remote OH instance only has sensors that it publishes to other OH instances. In this case the recommended approach is to follow the same overall approach as above and just exclude the command topic, i.e. steps 5-8 above. In other words, remote OH publishes updates to remote/out/Foo/state.

Note that these two use cases are not mutually exclusive. It’s to be expected that there will be some Items that will follow the first scenario and other Items which follow the second in one deployment.

Also note that the concept of “leader/follower” is not being used here. There is no leader (a.k.a. master) or follower (a.k.a. slave) instance of OH. There is the Item owner, in this case remote, and the proxy, in this case local. And the role is determined on an Item by Item basis. So some Items might be owned by local and others might be owned by remote.

Finally, these are not the only configurations one can create with the Event Bus.

  • One can set up a start configuration where there is one main OH instance that is subscribing to events from remote OH and publishing commands to all the remote OH instances. In that case the recommended approach is to use the main openHAB instance’s Event Bus topics. All the remotes will publish to mainopenhab/in/<item>/state and all will subscribe to mainopenhab/out/<item>/command.

  • When integrating with an external service, that service will subscribe to the out topics and publish to the in topics.

MQTT Installation and Configuration

MQTT Broker

To work with MQTT one must install an MQTT Broker (the middle bubble in the data flow diagram above). Publishers send messages to topics on the broker and subscribers receive messages published to topics on the broker.

There are a number of options for brokers. For this tutorial the recommendation is to use Mosquitto.

There only needs to be one MQTT broker installed on your LAN. All openHAB instances must be able to see the machine and MQTT broker port over the network.

Mosquitto is very light weight and runs very well on an RPi along side openHAB.

Installation: openHABian

Mosquitto can be installed from openhabian-config → 20 Optional Components → 23 Mosquitto. openhabian-config will ask if you want to secure connectivity to the broker with a password.

Installation: Direct

Mosquitto is included with most Linux Distros. Use the package manager for your distro (e.g. apt, yum, etc.) to install mosquitto and mosquitto-clients`.

sudo apt install mosquitto mosquitto-clients

On Windows you can download an installer from Download | Eclipse Mosquitto

On Mac mosquitto is available through Homebrew. See https://brew.sh/.

For those distros that support snap, Mosquitto is available as a a snap.

There are other ways to install Mosquitto that are beyond the scope of this tutorial, such as Docker. Please see the Mosquitto docs for details.

MQTT Broker Configuration

These instructions assume the default configuration of Mosquitto so no additional configuration is required. If desired, a username/password can be set.

  1. run mosquitto_passwd -b /etc/mosquitto/passwd <user> <password>

  2. Add the following lines to /etc/mosquitto/mosquitto.conf:

    password_file /etc/mosquitto/passwd
    allow_anonymous false

On openHABian this is done for you when you supply a password when asked. Where relevant, these instructions will assume openhabian as the user and password as the password.

openHAB Binding Installation and Base Configuration

See Adding Things - Advanced | openHAB for instructions on installing the MQTT binding and creating the MQTT Broker Thing.

Before saving the MQTT Broker Thing, fill in the following fields. Any field not in the list should be left blank or set to the default value shown. You may need to check the “Show Advanced” checkbox to see all the fields.

Field Value Notes
Name <Something Meaningful> This is the name that the Thing will appear as in the List of Things, e.g. Mosquitto Broker
Thing ID <Something Meaningful> E.g. mosquitto
Broker Hostname/IP <Hostname or IP address> The machine running the MQTT broker; can be localhost or 127.0.0.1 if installed on the same machine as this instance of openHAB
Client ID <client id> Uniquely identifies the OH instance to the MQTT broker, each client must have a unique client ID. If left blank, a random string is generated. This is not the same as the username. Should be set to the name for this OH instance. In the above discussion remote and local are used.
Last Will Message OFFLINE Message sent to the Last Will Topic when this instance of OH loses it’s connection to the MQTT broker
Last Will Topic <client id>/status Where the ONLINE/OFFLINE status gets’ published to. <client id> will be the name of this instance of openHAB and be the root of the MQTT topic hierarchy.
Last Will Retain ON This causes the (LWT) message to be retained so any client that subscribes to the topic will always know the ONLINE/OFFLINE status of this OH instance
Username openhabian Username configured on the broker, blank if one was not set
Password password Password configured on the broker, blank if one was not set

Repeat these steps on all openHAB instances that will participate with the Event Bus. Use a unique <client id> for each.

Rules

The rules for the MQTT Event Bus are published to the Marketplace (available on OH 3.2 M2 or later).

There are text based Python versions of these rules published at GitHub - rkoshak/openhab-rules-tools: Library functions, classes, and examples to reuse in the development of new Rules.. This code has not been tested with OH 3 but is known to work with OH 2.5.

Installation

In MainUI navigate to Settings → Automation.
Find and install “MQTT Online Status”, “MQTT Event Bus Subscription”, and “MQTT Event Bus Publication”. You may need to click “Show All” to see them all.

Configuration

What you have installed are rule templates. Templates can be instantiated one or more times to become rules. You will want to instantiate at least two of these rules, depending on the scenario.

Online Status

In MainUI from Settings → Rules click the + icon to create a new rule.

Fill in reasonable values for Unique ID, Name, and Description.

Select “Publishes ONLINE to LWT Topic” as the template to use for this rule.

Select your Broker Thing (created above) from the list for “MQTT Broker Thing”

Type in the LWT topic configured on the MQTT Broker Thing (see above).

Click “Save” and run the rule manually by clicking the triangle play button to get that first “ONLINE” message posted and test out the new rule.

Subscribe

In MainUI from Settings → Things open your MQTT Broker Thing and click on the “Channels” tab.

Click on “Add Channel” and configure it with a wild card subscription for the root topics on the event bus where updates and commands will come from. The specific topic will depend on the scenario this event bus is being used for.

In the example in the screen shot below I’m subscribing to sensor Items on an openHAB instance running at my dad’s house. So dadsoh “owns” the sensors meaning my “main” openHAB subscribes for updates.

Put a # into the “Separator Character” field.

Now navigate to Settings → Rules and click the + icon to create a new rule.

Enter reasonable information for the Unique ID, Name, and Description.

Select “MQTT Event Bus Subscribe” from the list of templates.

Select the MQTT Broker Thing (created above) from the list for the “MQTT Broker Thing” and the Event Channel created above for the “MQTT Event Channel”.

Click “Save”.

If one is creating a complicated deployment where there are multiple event bus topics to subscribe to, create multiple Event Channels on the MQTT Broker Thing and add that as a new trigger for the subscription rule.

Publish

Create a Group with a reasonable name which will have as members all those Items that should have their commands published to the event bus. I used EB_Command. Add all the proxy Items that are “owned” by another instance of OH to this Group.

Create another Group with a reasonable name which will have as members all those Items that should have their updates published to the event bus. I used EB_Update`. Add all the Items owned by this instance of openHAB that should have their updates published to the event bus to this Group.

No Items should be members of both Groups.

Now navigate to Settings → Rules and click the + icon to create a new rule.

Enter reasonable information for Unique ID, Name, and Description.

Select “MQTT Event Bus Publisher” from the list of templates.

Select the MQTT Broker thing for “MQTT Broker Thing” (created above).

Enter the name for this openHAB instance which is used as the root of the MQTT topic.

Select the command Item Group created above for “Command Group” and the updates Item Group created above for the “Update Group”.

Click “Save”.

Do I need all three?

In very simple cases you may only need two of the three rules instantiated. For example, I’ve only got some sensors deployed to my dad’s house so that instance of openHAB has the online status rule and the publisher rule instantiated. My main openHAB only has the subscription rule instantiated and the broker is configured to subscribe to my dad’s event bus out topics.

Example Topologies

This section presents some example topologies that are possible with the MQTT Event Bus. The topologies described here is not exhaustive and are presented for illustration purposes.

Leader/Follower

In this topology there are two openHAB instances, one of which is a leader and the other is the follower. The leader has all the rules and is the primary openHAB instance. The follower “owns” the Items and implements the links to the actual devices. All the Items from the follower exist as proxies in the leader.

In this topology, all commands to the proxied Items in the leader need to be published to the follower. All updates to the “real” Items in the follower need to be published to the leader.

openHAB Instance Subscribe topics Publish topics Command Group Update Group
leader follower/out/# leader/out/# All proxy Items that can be commanded. None
follower leader/out/# follower/out/# None All Items proxied to the leader.

One-to-One

This scenario is more complicated than Leader/Follower in that which instance of openHAB owns the real Item versus the proxy Item can be either openHAB instance. Therefore the Items need to be individually Grouped properly.

openHAB Instance Subscribe topics Publish topics Command Group Update Group
one two/out/# one/out/# All Items owned by “two” and proxied by “one” and can be commanded. All Items owned by “one” that are to be published to the event bus.
two one/out/# two/out/# All Items owned by “one” and proxied by “two” and can be commanded. All Items owned by “two” that are to be published to the event bus.

Star Topology

In this topology there is one central main openHAB instance with multiple satellite openHAB instances. The “real” Items are all owned by the satellite instances and are proxied in main. Note that all the Items in the satellites need to have a unique name across all the satellite instances.

openHAB Instance Subscribe topics Publish topics Command Group Update Group
main main/in/# main/out/# All Items proxied from the satellite instances that can be commanded from main. None
sat_one main/out/# main/in/# None All Items proxied to the event bus.
sat_two main/out/# main/in/# None All Items proxied to the event bus.
sat_three main/out/# main/in/# None All Items proxied to the event bus.

Notice how the satellite instances are all configured the same. No commands ever come from the satellite instances. No updates come from the main instance.


The code below is deprecated. Once the Marketplace hits the main release version I will be removing everything below this point. It will be preserved at my repo for some time after that but the Rule Templates will be the only code that is maintained by the author of this tutorial going forward.


These instructions assume the MQTT binding configuration discussed above has already been performed. With the MQTT Broker Thing configured with the proper event Channel, edit $OH_CONF/automation/lib/python/configuration.py and add the following new variables:

Variable Purpose
mqtt_eb_name Name for the instance of openHAB, will be used as the root of the MQTT topic hierarchy for the Publisher.
mqtt_eb_broker Thing ID for the MQTT Broker Thing.
mqtt_eb_puball Optional variable, when absent or set to True indicates that all command and updates to all Items are to be published to the event bus. When False, only those Items with the eb_update and eb_command tags are published.
mqtt_eb_in_chan The Channel ID for the Event Channel on the Broker Thing.

For example (also contained in configuration.py.mqtt_eb_example):

# The Channel ID of the MQTT Event Bus subscription channel
mqtt_eb_in_chan = "mqtt:broker:broker:eventbus"

# The name to use for this instance of openHAB, forms the root of the MQTT topic
# hierarchy.
mqtt_eb_name = "remote-openhab"

# Thing ID for the MQTT broker Thing.
mqtt_eb_broker = "mqtt:broker:mosquitto"

# Optional flag, when True all Item commands and updates are puiblished.
# Defaults to True.
mqtt_eb_puball = True

If the mqtt_eb_puball variable is left out or set to False, the next step is to add the following tags to only those Items that should publish to the event bus.

Tag Purpose
eb_update Items tagged with this will have all their updates published to the event bus.
eb_command Items tagged with this will have all ther command published to the event bus.

For example:

Switch Foo [eb_command] // publishes only commands to the event bus

String Bar [eb_update] // publishes only updates to the event bus

Number Baz [eb_command,eb_update] // publishes both command and updates to the event bus

Rules DSL

The Event Bus requires the installation of a few short Rules. These Rules do not need to be customized. They work as is so they only need to be copied to the right location in the openHAB installation.

Conventions

For the code below, we will be using the following variables:

Variable Value Purpose
eb_cmd_gr PubItems_CMD Group containing all the Items whose commands are published to the bus.
eb_upd_gr PubItems_UPD Group containing all the Items whose updates are published to the bus.
eb_name remote Name for the publishing OH instance, will be the root of the topics.
eb_br mqtt:broker:mosquitto Thing ID for the MQTT Broker Thing created above
eb_in_chan mqtt:broker:mosquitto:eventbus Channel ID for the Trigger Channel defined on the MQTT Broker Thing for the OH instance that subscribes to the event bus (see below)

Publishing to the Event Bus

Items and Groups

The first step to publish commands and updates to the out topics is to create a Group for each. Be sure to give the Group a Type. It doesn’t matter what type we choose because we will not be aggregating the states of it’s members, but without a Type the Group will not receive events that are necessary to drive Rules.

Group:String PubItems_CMD
Group:String PubItems_UPD

All Items that need to be published to the “event bus” need to be a member of these Groups. For example, on the remote openHAB instance, all of the “real” Items (those linked to devices) must be members of PubItems_UPD so all updates on the Items get shared with the local openHAB instance. On the local openHAB instance where the proxies reside, the Proxy Items must be members of PubItems_CMD so all commands issued on the proxy Item get published out and acted upon by the remote openHAB instance.

Take care when adding the Items to the Groups to follow this convention.

Rules

Next we will need Rules. Copy these to $OH_CONF/rules/eb_pub.rules and modify at a minimum eb_name. If a custom value was used for anything else modify the code as appropriate.

eventbus_pub.rules

val eb_br = "mqtt:broker:mosquitto" // Thing ID of the broker connection
val eb_name = "remote"              // <client ID>

rule "Publish commands to the event bus"
when
    Member of PubItems_CMD received command // eb_cmd_gr
then
    val mqttActions = getActions("mqtt",eb_br) 
    mqttActions.publishMQTT(eb_name+"/out/"+triggeringItem.name+"/command",receivedCommand.toString)
end

rule "Publish updates to the event bus"
when
    Member of PubItems_UPD received update // eb_upd_gr
then
    val mqttActions = getActions("mqtt",eb_br)
    mqttActions.publishMQTT(eb_name+"/out/"+triggeringItem.name+"/state",triggeringItem.state.toString)
end    

Repeat for all OH instances.

Summary

That’s all there is to it. All commands to all members of PubItems_CMD get published to the command topic and all updates get published to the state topic.

Subscribing from the Event Bus

Items and Groups

For every Item that needs to be proxied the subscriber must have an Item of the same name and type defined. For example, if there is a Switch Foo linked to a device on remote, there needs to be a Switch Foo defined. Linking an incoming message to an Item is done based on Item name.

Setting up the Subscriptions

For subscription we need to create a publish trigger Channel on the MQTT Broker Thing. This subscription will be subscribing to the desired out topics on the publishing instance of OH. MQTT and configure it to subscribe to the output topics from the other openHAB. You can use the wild card subscription to use this one Channel for all the Items. Be sure to define a separator character so we can get the MQTT topic from the event in our Rule.

In PaperUI navigate to the MQTT Broker Thing. Click on the + icon to add a Channel and enter:

Field Value Notes
Channel Type Publish Trigger The only choice
Channel ID <client-ID>cmd, upd Choose a meaningful name indicating what OH instance the Channel subscribes from (e.g. in this case on remote we subscribe to commands from local so use local-cmd.
Label Human readable name for the Channel Spell out what this Channel does, e.g. “Local’s Commands”
MQTT Topic On the local openHAB subscribe to remote/out/+/state, On the remote openHAB subscribe to local/out/+/command If you want to subscribe to both commands and updates from remote subscribe to remote/out/#.
Separator Character # Triggers the Rule with and event consisting of topic#message.

If you have more than one “remote” OH instances, create a Channel for each instance. Alternatively, if this openHAB instance doesn’t publish anything to the Event Bus (e.g. the remote OH instances only publish sensor readings) you can subscribe to +/out/# which will subscribe to all events from all other instances of OH. If you do that and do publish for the local instance of OH, an infinite loop will result.

Rules

With the Channel in place we only need a single Rule.

If more than one trigger Channel was created above, add those additional triggers as rule triggers to the Rules.

eventbus_sub.rules

rule "Subscribe for commands and updates from the event bus"
when
    Channel "mqtt:broker:broker:remote-updates" triggered
then
    var topic = receivedEvent.toString.split("#").get(0)
    var state = receivedEvent.toString.split("#").get(1)
    val itemName = topic.split("/").get(2)
    val type = topic.split("/").get(3)

    if(type == "command") sendCommand(itemName, state)
    else postUpdate(itemName, state)
end

The Rules DSL version has one limitation that doesn’t exist for the Python version. If the Item doesn’t exist an error will be generated on the sendCommand or postUpdate. To avoid this error make sure to define a proxy for all the Items that are published to the event bus.

Online Status

It is also desirable to know when one of the OH instances goes offline. To handle this, we configured the LWT on the MQTT Broker Thing (see above).

When the OH instance loses it’s connection to the MQTT Broker, the Broker will publish “OFFLINE” to <client ID>/status. Since the message is retained, even if the subscribers are not online, they will get the OFFLINE message when they reconnect.

Next we need a Rule triggered at Systems started to publish “ONLINE” as a retained message when the OH instance comes back online.

eventbus_online.rules

rule "Eventbus Online"
when
    System started or
    Thing mqtt:broker:mosquitto changed to ONLINE
then
    logInfo("mqtt-eb", "Reporting eventbus as online")
    getActions("mqtt", "mqtt:broker:mosquitto").publishMQTT("openhab-remote/status", "ONLINE", true)
end
19 Likes
MQTT 2 Binding receives Messages but doesn't send updates
Multiple MQTT Brokers Question: Moquette and Mosquitto needed for network and localhost comms?
MQTT Event Bus Publication
Running OpenHAB on several Raspberry Pis
Qubino Smart Meters (ZMNHXD, ZMNHTD) endless problems
MQTT Event Bus Subscription
[SOLVED] Any item state change
Move from MQTT 1.14 to 2.5.12
Move from MQTT 1.14 to 2.5.12
OH 2: Systeminfo Binding over multiple openHAB instances via MQTT
Smart Way to send all Status to MQTT?
Control Openhab things from thingsboard
How to subscribe an mqtt state and show it on the sitemap
Migrate OpenHAB 2.5.12 to OpenHAB3 MQTT 1x Items Help
Problems migrating MQTT 1 to MQTT 2 Binding
Generic MQTT rule
MQTT persistance in openhab3
OH3 remote openHAB doesn't reconnect
Trouble configuring MQTT on openhab 2.5
2 instances of openhab - advice please
Remote openHAB Binding
Openhab stops sending to MQTT
Hue: channels for a single bulb, rather than the whole group?
Logging changes/events to remote MQTT server as JSON payloads
Replacing SmartThings API with OpenHAB + OpenHAB-cloud
Publish devices to MQTT using homie - automatically
MQTT Binding: I don´t understand
Eventbus_online.rule Problem
[Solved] Attempt to migrate from MQTT1 to v2
Legacy bindings for openHAB3, esp: ekey, FritzboxTR064 and mqqteventbus
openHAB 3.0 Milestone 1 discussion
openHAB 3.0 Milestone 1 discussion
IP/Ethernet to Z-WAVE gateways
VictronEnergy MQTT Item - direct Transformation MAP?
Ansible Revisited
Suggestions how to correlate or present data from several Openhab instances
Python Example of Subscribing to openHAB's SSE Feed
OH going to 100% (or greater) and not responding
Z-Wave - How to reach an out-building?
MQTT1 items with multiple PUB SUB -->> migrate to MQTT 2.x
Design Pattern: Rule Refresh
openHAB 2 version - PiFace Binding
Multiple Persistence add-ons configured, ignore errors?
OpenHab user notofication
Suggestions for OpenHAB
Multi-homed openHAB
MQTT-Binding: cannot read values with | (pipe) in topic
Control Zwave device with MQTT
Why use a MQTT message broker as the centralized message bus?
Karaf Cellar and OH
I need to get MQTT "stateTopic" and "commandTopic" values from a Rule
Remote Z-wave, serial over TCP/IP?
Trigger an item's sendCommand from a remote MQTT client
Bridge Openhab to HA
JSON transformation of 85x diagnostics on an MQTT topic
PaperUI Topic/channel name
Tie multiple instances of openhab together using MQTT?
MQTT Event bus - state of an AVG or SUM group
MQTT Client on OH2 to send MQTT messages to a OH2 Master
Questions about the Event Bus
Main Server with Zwave and RaspberryPi's
Stable repository broken, migrated or abandoned?
No more OH 1.x bindings!
Link between an openHAB1 and another openHAB2 instance?
Real world solution / Openhab at two locations
Using MQTT Persistence
Remote connection
Master OH2 linked to slave Openhabians
Rrd4j Graphs not working
Poll: Which OH1.x addons do you use?
Migration from 1.8 to newest(stable) OpenHAB release
See multiple openHab installations(like 3-4)
How can I get an MQTT thing/channel's "commandTopic" from a rule?
How I Use Rule Templates
Openhab 3.2 mqtt persistence
Distributed setup
Integration with esphome
Integration with esphome
Netatmo + Openhab 3 + MQTT it doesn't work correctly
Link OH3 with OH1
Where can I find a tutorial "basic demo-setup"
zWave - running OH 2.x and OH 3.x - best practice for migration
Topic consolidation
Setup OpenHAB3 with CLI and textfiles
[possible new binding] openHAB Eventbus to MQTT
[possible new binding] openHAB Eventbus to MQTT
How to: MQTTv2 Eventbus rules
[possible new binding] openHAB Eventbus to MQTT
OH3 as facilitator to make "Niko Home Crontrol" MQTT-aware
MQTT <--> REST Bridge
MQTT Binding and linked items
OH3 - MQTT-Eventbus implementation using file based config

I use them in Jython in a more basic Form than yours but this is it in principle:

@rule("Publish all")
@when("Member of OutItems changed")
def MQTTPublishOut(event):
    output1 = event.itemName
    output2 = str(event.itemState)
    actions.get("mqtt","mqtt:broker:f79d2a84").publishMQTT("allItemsout/"+output1,output2)

@rule("Receive all")
@when("Channel mqtt:broker:f79d2a84:TriggerIn triggered")
def MQTTPublishIn(event):
    input1 = event.event
    input2 = input1.split("/")
    input3 = input2[1].split("#")
    events.sendCommand(input3[0], input3[1])

Best regards Johannes

Hi Guys,

I hope that someone can give me the redeeming answer because it is starting to drive me crazy. I’ve been playing around for a few days but can’t get out.

I use the event bus rule of a Rich. This works fine, however, he sent to the Mqtt broker an On or and OFF instead of 1 or a 0.
I would like to transform this.

Can someone help me on my way? Do I have to do the transformation via the Item file or in the rule?

Thanks

The Event Bus is intended to work as a way to federate two OH instances. OH understands ON and OFF.

If you have something that isn’t OH and it expects something besides ON and OFF, you should not be using the Event Bus to integrate that device/system or you should adjust that device/system so it understands OH’s states.

To properly integrate a device/subsystem with OH, you would create a Generic MQTT Thing (assuming it doesn’t support Homie or HA standards) and define Channels. In the Channels you can define a transformation that will convert the ON to 1 and OFF to 0.

Thank you for your quick response Rich.

I have a Mqtt channel which also sends the status of the item. Only this one will send a 0 or a 1.

I was so happy with your rule that I can choose which item to put on the bus

Switch Output_2 “Output_2 [%s]” (PubItems) { channel=“knx:device:9d0e2d38:1”, channel=“mqtt:topic:mybroker:satelthing:output_2” [profile=“follow”]}

if I do a transformation in the channels does this work with the rule above?

No. That isn’t what the Rule is intended to do. It publishs the openHAB states to topics. On the subscriber side it expects openHAB states.

It is not designed to nor is it intended to be used with some other system beyond two or more OH instances talking to each other.

If you cannot make whatever it is that you are using that needs the 1 and 0 instead of ON and OFF, this is not the correct approach.

This is the right approach. This Rule does nothing for you.

Thnx Rich

Thank you for your clear explanation always. Where would the community be without you.
Can you perhaps explain why the Mqqt also sends the statuses of all other items when there is a change in status of 1 of the items?
I do not use the rule but only via the mqtt things.
This is quite a big load with multiple items.

You will have to describe the behavior more. Are you saying the Rules in the OP does this? Or are you saying that your Generic Things are doing this?

I don’t see how this behavior is possible given the Rules above. The Rule only triggers when a member of PubItems receives a command or receives an update. Then the Rule only publishes on that one Item that triggered the Rule. If it’s sending updates for ALL Items, that means that the Rule is triggering for all Items which means that all of your Items are receiving an update at the same time.

Sorry I wasn’t entirely clear.
I do not use the rule as above but only the Items and the channels.

When the staus of output 1 changes, the mqtt binding also immediately sends the status of output 2.

Items file

Switch Output_1 “Output_1 [%s]” (Test) { channel=“knx:device:9d0e2d38:2”, channel=“mqtt:topic:mybroker:satelthing:output_1” [profile=“follow”]}
Switch Output_2 “Output_2 [%s]” (Test) { channel=“knx:device:9d0e2d38:1”, channel=“mqtt:topic:mybroker:satelthing:output_2” [profile=“follow”]}

Mqtt things

    Type switch : output_1 "Output_1" [ stateTopic="output_1", commandTopic="output_1/state", postCommand="true" ] 
    Type switch : output_2 "Output_2" [ stateTopic="output_2", commandTopic="output_2/state", postCommand="true" ]

You will need to post a new thread and hope someone who knows more about the MQTT binding, especially when using .things files to configure them will see and can help.

ok thanks

Rich,

Is there not a possibility to use your rule anyway? Possibly create a proxy item and have it converted to 0 and 1

You could (you can do just about anything you want), but why would you? Just create a Thing, configure the transform on the Channel and avoid the extra Item and rule. That’s what the Generic Things are for. What you are proposing, given the information I have so far, send like an awful lot of extra work just to avoid the little bit of work of creating the Thing.

The problem with that is that I also want to link an alarm system (Satel) to another system. However, this alarm system only allows 1 connection. With a status change of 1 zone, the system immediately sends the status of all zones. This means that when 1 zone is changed, 200 statuses are immediately sent over the broker.
With the rule above I can override this by replacing meber or group changed instead of received command.

If I use the thing, all statuses are also sent.
So I am looking for a solution to overcome this.

Is that really a problem? MQTT brokers are designed to presses tens of thousands of messages with hundreds of connections on machines like an RPi. I found these 200 messages are overloading the broker. So what other system is actually experiencing a problem?

It’s best not to try to fix things that are not actually a problem.

But it you do want to user a rule liked the above, than you need to code it significantly differently. You will have to add logic to figure out what sort of message it is and convert it as appropriate

This is great!

I actually had this idea the other day, and wondered how I could connect more OH systems to eachother… The idea was to use two or three Rpi´s placed strategic in our house to cover every corner of Zigbee/Zwave or whatever else needed near these particular places… (I live in a rather big one level house, so wireless communication is impossible everywhere with just one single coordinator/gateway).

I understand MQTT is an option, but I also wondered if there are any plans to make this possibilty more “integrated” directly into OH. (mainly because I´m still struggling with understanding MQTT fully).

All plans I’m aware of involve MQTT. I have plans to improve the above and perhaps there will be tighter integration with openHAB, but I know of no current plans to implement this using anything but MQTT. It is, IMHO, the best tool for the job.

Some of the things I’m considering include:

  • automatically create the Itemson the subscriber side
  • automatically discover remote OH instances
  • turn this into a Rule Template to make installation and use easier
  • add it as a feature to the MQTT binding or create a separate binding

What direction this goes will depend on what direction OH 3 goes. And I don’t want to do too much to it until it gets merged into the Helper Libraries.

I understand you wont put too much effort into it. But it sure would be nice to see those things mentioned beeing included.
The best option would be, if this “event bus” could be added directly into OH. I have a little idea, that many would find it highly usefull.

I said I won’t put much effort into it until what I’ve already submitted gets merged. I didn’t say I’m not going to not work on it much at all for ever.

That’s exactly what rule templates are.

Sorry thats what I meant… I took that for granted I gues…Sorry!

What I meant was, the event bus got a part of the system itself, as an direct option in the setup where you specify wheter you need to activate this even bus, and if yes, then there would be an option where you place to where, and which funktions/items/things etc you want to share between the systems… The actualy communcation should then be established automaticly. Perhas like main system “download” a list of all resources/items/things ext from the other(s) system(s).