OPENHAB MQTT Binding

posted 1 May 2015, 03:01 by Lê Duy Nhân   [ updated 1 May 2015, 03:19 ]

Documentation of the MQTT binding Bundle

Introduction

The MQTT binding bundle is available as a separate (optional) download. This binding allows openHAB to act as an MQTT client, so that openHAB items can send and receiveMQTT messages to/from an MQTT broker. It does not provide MQTT broker functionality, for this you may want to have a look at Mosquitto. There are test servers available at m2m.eclipse.org and test.mosquitto.org. To install, place this bundle in the folder ${openhab_home}/addons and add binding information to your configuration. See the following sections on how to do this.

OpenHAB provides MQTT support on different levels. The table below gives a quick overview:

LevelDescriptionUsageBundle
TransportShared transport functions for setting up MQTT broker connections.Ideal if you want to roll your own binding using MQTT as the transport.o.o.io.transport.mqtt
Item bindingAllows MQTT publish/subscribe configuration on item levelIdeal for highly customized in and outbound message scenarios.o.o.binding.mqtt
Event bus bindingPublish/receive all states/commmands directly on the openHAB eventbus.Perfect for integrating multiple openHAB instances or broadcasting all events.o.o.binding.mqtt
PersistenceUses persistent strategies to push messages on change or a regular interval.Perfect for persisting time series to a public service like Xively. (See MQTT persistence.)o.o.persistence.mqtt

The Mqttitude binding is also available which is an extension of this binding.

Configuration

Transport Configuration

In order to consume or publish messages to an MQTT broker, you need to define all the brokers which you want to connect to, in your openhab.cfg file. The following properties can be configured to define a broker connection:

mqtt:<broker>.url=<url>
mqtt:<broker>.clientId=<clientId>
mqtt:<broker>.user=<user>
mqtt:<broker>.pwd=<password>
mqtt:<broker>.qos=<qos>
mqtt:<broker>.retain=<retain>
mqtt:<broker>.async=<async>

The properties indicated by <...> need to be replaced with an actual value. The table below lists the meaning of the different properties.

PropertyDescription
brokerAlias name for the MQTT broker. This is the name you can use in the item binding configurations afterwards.
urlURL to the MQTT broker, e.g. tcp://localhost:1883 or ssl://localhost:8883
clientIdOptional. Client id (max 23 chars) to use when connecting to the broker. If not provided a default one is generated.
userOptional. User id to authenticate with the broker.
pwdOptional. Password to authenticate with the broker.
qosOptional. Set the quality of service level for sending messages to this broker. Possible values are 0 (Deliver at most once),1 (Deliver at least once) or 2 (Deliver exactly once). Defaults to 0.
retainOptional. True or false. Defines if the broker should retain the messages sent to it. Defaults to false.
asyncOptional. True or false. Defines if messages are published asynchronously or synchronously. Defaults to true.

Example Configurations

Example configuration of a simple broker connection:

mqtt:m2m-eclipse.url=tcp://m2m.eclipse.org:1883

Example configuration of a encrypted broker connection with authentication:

mqtt:mosquitto.url=ssl://test.mosquitto.org:8883
mqtt:mosquitto.user=administrator
mqtt:mosquitto.pwd=mysecret
mqtt:mosquitto.qos=1
mqtt:mosquitto.retain=true
mqtt:mosquitto.async=false

Item Binding Configuration for Inbound Messages

Below you can see the structure of the inbound mqtt configuration string. Inbound configurations allow you to receive MQTT messages into an openHAB item. Every item is allowed to have multiple inbound (or outbound) configurations.

Item myItem {mqtt="<direction>[<broker>:<topic>:<type>:<transformer>], <direction>[<broker>:<topic>:<type>:<transformation>], ..."} 

Since 1.6 it is possible to add an optional 5th configuration like:

Item myItem {mqtt="<direction>[<broker>:<topic>:<type>:<transformer>:<regex_filter>], <direction>[<broker>:<topic>:<type>:<transformation>], ..."} 
PropertyDescription
directionThis is always "<" for inbound messages.
brokerThe broker alias as it is defined in the openHab configuration.
topicThe MQTT Topic to subscribe to.
typeDescribes what the message content contains: a status update or command. Allowed values are 'state' or 'command'.
transformationRule defining how to transform the received message content into something openHab recognizes. Transformations are defined in the format of TRANSFORMATION_NAME(transformation_function). Allowed values are 'default' or any of the transformers provided in the org.openhab.core.transform bundle. Custom transformations can be contributed directly to the transform bundle by making the Transformation available through Declarative Services. Any other value than the above types will be interpreted as static text, in which case the actual content of the message is ignored.
regex_filter(optional, since 1.6)A string representing a regular expression. Only messages that match this expression will be further processed. All other messages will be dropped. Use Case: If multiple different data is sent over one topic (for example multiple sensors of one device), it is possible to distinguish the messages for different items. Example ".*" will match every message, ".*\"type\"=2\n.*" will match every message including type=2.

Example Inbound Configurations

Number temperature {mqtt="<[publicweatherservice:/london-city/temperature:state:default]"}
Number waterConsumption {mqtt="<[mybroker:/myHome/watermeter:state:XSLT(parse_water_message.xslt)]"} 
Switch doorbell {mqtt="<[mybroker:/myHome/doorbell:command:ON]"}
Number mfase1 {mqtt="<[flukso:/sensor/9cf3d75543fa82a4662fe70df5bf4fde/gauge:state:REGEX(.*,(.*),.*)]"}

Item Binding Configuration for Outbound Messages

Below you can see the structure of the outbound mqtt configuration string. Outbound configurations allow you to send an MQTT message when the an openHAB item receives a command or state update.

Item itemName {mqtt="<direction>[<broker>:<topic>:<type>:<trigger>:<transformation>]" }
PropertyDescription
directionThis is always ">" for outbound messages.
brokerThe broker alias as it was defined in the openHAB configuration.
topicThe MQTT Topic to publish messages to.
type'state' or 'command'. Indicates whether the receiving of a status update or command triggers the sending of an outbound message.
triggerSpecifies a specific OpenHAB command or state (e.g. ON, OFF, a DecimalType, ..) which triggers the sending of an outbound message. Use `*` to indicate that any command or state should trigger the sending.
transformationRule defining how to create the message content. Transformations are defined in the format of TRANSFORMATION_NAME(transformation_function). Allowed values are 'default' or any of the transformers provided in the org.openhab.core.transform bundle. Custom transformations can be contributed directly to the transform bundle by making the Transformation available through Declarative Services. Any other value than the above types will be interpreted as static text, in which case this text is used as the message content.

When the message content for an outbound message is created, the following variables are always replaced with their respective value:

  • ${itemName} : name of the item which triggered the sending
  • ${state} : current state of the item
  • ${command} : command which triggered the sending of the message

Example Outbound Configurations

Switch mySwitch {mqtt=">[mybroker:/myhouse/office/light:command:ON:1],>[mybroker:/myhouse/office/light:command:OFF:0]"}
Switch mySwitch {mqtt=">[mybroker:/myhouse/office/light:command:ON:1],>[mybroker:/myhouse/office/light:command:*:Switch ${itemName} was turned ${command}]"}

Event Bus Binding Configuration

In addition to configuring MQTT publish/subscribe options for specific openHAB items, you can also define a generic configuration in the openhab.cfg file which will act on ALL status updates or commands on the openHAB event bus.

The following properties can be used to configure MQTT for the openHAB event bus:

mqtt-eventbus:broker=<broker>
mqtt-eventbus:statePublishTopic=<statePublishTopic>
mqtt-eventbus:commandPublishTopic=<commandPublishTopic>
mqtt-eventbus:stateSubscribeTopic=<stateSubscribeTopic>
mqtt-eventbus:commandSubscribeTopic=<commandSubscribeTopic>

The properties indicated by <...> need to be replaced with an actual value. The table below lists the meaning of the different properties.

PropertyDescription
brokerName of the broker as it is defined in the openhab.cfg. If this property is not available, no event bus MQTT binding will be created.
statePublishTopicWhen available, all status updates which occur on the openHAB event bus are published to the provided topic. The message content will be the status. The variable ${item} will be replaced during publishing with the item name for which the state was received.
commandPublishTopicWhen available, all commands which occur on the openHAB event bus are published to the provided topic. The message content will be the command. The variable ${item} will be replaced during publishing with the item name for which the command was received.
stateSubscribeTopicWhen available, all status updates received on this topic will be posted to the openHAB event bus. The message content is assumed to be a string representation of the status. The topic should include the variable ${item} to indicate which part of the topic contains the item name which can be used for posting the received value to the event bus.
commandSubscribeTopicWhen available, all commands received on this topic will be posted to the openHAB event bus. The message content is assumed to be a string representation of the command. The topic should include the variable ${item} to indicate which part of the topic contains the item name which can be used for posting the received value to the event bus.

Example Configurations

Example configuration for a event bus binding, which sends all commands to an MQTT broker and receives status updates from that broker. This scenario could be used for example to link 2 openHAB instances together where the master instance sends all commands to the slave instance and the slave instance sends all status updates back to the master. The example below shows an example configuration for the master node.

mqtt-eventbus:broker=m2m-eclipse
mqtt-eventbus:commandPublishTopic=/openHAB/out/${item}/command
mqtt-eventbus:stateSubscribeTopic=/openHAB/in/${item}/state

Using the org.openhab.io.transport.mqtt bundle

When the default MQTT binding configuration options are not sufficient for your needs, you can also use the MQTT transport bundle directly from within your own binding.

MqttService

Using the MqttService, your binding can add custom message consumers and publishers to any of the defined MQTT brokers. You don't have to worry about (re)connection issues, all of this is done by the transport.mqtt bundle. The MqttService class is available to your binding through Declarative Services. A good example on how to use the MqttService can be found in the org.openhab.persistence.mqtt bundle.

Eclipse Paho

If the above service doesn't provide all the flexibility you need, you can also use the Eclipse Paho library directly in your binding. To make the library available, it's sufficient to add a dependency to the org.openhab.io.transport.mqtt bundle and to add org.eclipse.paho.client.mqtttv3 to your list of imported packages.


1)  Under /configurations/openhab.cfg


######################## Mail Action configuration ############################$

mail:hostname=smtp.gmail.com

mail:port=587

mail:username=????? without the @gmail
mail:password=?????

mail:from=??? yourname@gmail.com

mail:tls=true





################################### MQTT Transport #########################################
#

mqtt:mymosquitto.url=tcp://localhost:1883

mqtt:mymosquitto.qos=0

mqtt:mymosquitto.retain=true

mqtt:mymosquitto.async=true


-----------------------------------------------------------------------------------------

2)  Under /configurations/items/demo.items


Switch itm_mailbox "Switch" (ALL)
Number itm_mailboxmqtt "Mailbox RSSI [%.1f]" (ALL) {mqtt="<[mymosquitto:4124:state:default]"}
Number itm_mailboxcnt "Mail Count [%.1f]" (ALL) {mqtt="<[mymosquitto:4122:state:default]"}
DateTime itm_mailbox_time "Mailbox Last Updated [%1$tA, %1$tm/%1$td, %1$tI:%1$tM %1$tp]"
Number itm_mailboxbat "Mailbox Battery [%.1f Volt]" (ALL) {mqtt="<[mymosquitto:4123:state:default]"}




-----------------------------------------------------------------------------------
3)  Under /configurations/sitemap/demo.sitemap

        Frame label="Mailbox"
        {
                Switch item=itm_mailbox label="Mailbox" mappings=[OFF="Off"]
                Text item=itm_mailbox_time
                Text item=itm_mailboxmqtt
                Text item=itm_mailboxcnt
                Text item=itm_mailboxbat
        }


--------------------------------------------------------------------------------
4)  Under /configurations/rules/demo.rules

rule "send email and talk"
        when
                Item itm_mailbox changed from OFF to ON
        then
                playSound("aolmail.mp3")
                sendMail("myemailaddress@gmail.com", "subject line here" , "email body text")


end


rule "update mailbox"
        when
                Item itm_mailboxmqtt received update
        then
                sendCommand(itm_mailbox, ON)
                postUpdate(itm_mailbox_time, new DateTimeType())
end




--------------------------------------------------------------------------------------
END OF CONFIGURATIONS



//OpenHAB Configuration for UberSensor.ino


/* Item Definition Uber sensor Alarms and Notifications Control*/
Switch itm_NAA_auto "Auto Schedule Alarms/Notifications"

Switch itm_uber1_gas_alm_enb "Gas / Smoke Notifer"
Switch itm_uber1_flame_alm_enb "Flame Notifier"
Switch itm_uber1_bark_alm_enb "Bark Notifier"
Switch itm_uber1_pir_alm_enb "Presence Notifier"

Switch itm_uber1_gas_alm_sta "Gas / Smoke Alarm Status"
Switch itm_uber1_flame_alm_sta "Flame Alarm Status"
Switch itm_uber1_bark_alm_sta "Bark Alarm Status"
Switch itm_uber1_pir_alm_sta "PIR Presence Status"

Switch itm_uber1_light_sta "Living Room Light"

DateTime itm_uber1_gas_time "Gas Alarm Time [%1$tA, %1$tm/%1$td, %1$tI:%1$tM %1$tp]"
DateTime itm_uber1_flame_time "Flame Alarm Time [%1$tA, %1$tm/%1$td, %1$tI:%1$tM %1$tp]"
DateTime itm_uber1_bark_time "Bark Alarm Time [%1$tA, %1$tm/%1$td, %1$tI:%1$tM %1$tp]"
DateTime itm_uber1_pir_time "PIR Presence Alarm Time [%1$tA, %1$tm/%1$td, %1$tI:%1$tM %1$tp]"

Number itm_uber1_gas_mqtt "Gas [%.1f]" (ALL) {mqtt="<[mymosquitto:1222:state:default]"}
Number itm_uber1_flame_mqtt "Flame [%.1f]" (ALL) {mqtt="<[mymosquitto:1232:state:default]"}
Number itm_uber1_pir_mqtt "PIR [%.1f]" (ALL) {mqtt="<[mymosquitto:1242:state:default]"}
Number itm_uber1_bark_mqtt "Bark [%.1f]" (ALL) {mqtt="<[mymosquitto:1252:state:default]"}
Number itm_uber1_temp_mqtt "Uber Temperature [%.1f]" (ALL) {mqtt="<[mymosquitto:1262:state:default]"}
Number itm_uber1_hum_mqtt "Uber Humidity [%.1f]" (ALL) {mqtt="<[mymosquitto:1263:state:default]"}
Number itm_uber1_light_mqtt "Light Sensor [%.1f]" (ALL) {mqtt="<[mymosquitto:1272:state:default]"}


---------------------------------------------------------------------------------


/* Uber sensor rules */
/* -------------  Uber Sensor -------------------- */
rule "Uber Lighs"
        when
                Item itm_uber1_light_mqtt received update
        then
                if(itm_uber1_light_mqtt.state < 350)
                {
                        sendCommand(itm_uber1_light_sta, OFF)
                }
                else
                {
                         sendCommand(itm_uber1_light_sta, ON)
                }
end


/*-----  uber - gas/smoke ---------- */
rule "Uber gas smoke threshold"
        when
                Item itm_uber1_gas_mqtt received update
        then
                if((itm_uber1_gas_mqtt.state > 220) && (itm_uber1_gas_alm_enb.state == ON))
                {
                        sendCommand(itm_uber1_gas_alm_sta, ON)
                }
end

rule "Uber gas smoke response"
        when
                Item itm_uber1_gas_alm_sta changed from OFF to ON
        then
		sendMail("ArduinoHomeAutomationOpenHAB@gmail.com", "gas / smoke" , "gas or smoke detected")
                //playSound("ding.mp3")
                postUpdate(itm_uber1_gas_time, new DateTimeType())
end

/* --------- uber flame ---------- */
rule "Uber flame threshold"
        when
                Item itm_uber1_flame_mqtt received update
        then
                if((itm_uber1_flame_mqtt.state < 900) && (itm_uber1_flame_alm_enb.state == ON))
                {
                        sendCommand(itm_uber1_flame_alm_sta, ON)
                }
end

rule "Uber flame response"
        when
                Item itm_uber1_flame_alm_sta changed from OFF to ON
        then
                sendMail("ArduinoHomeAutomationOpenHAB@gmail.com", "fire detected" , "fire detected")
                //playSound("ding.mp3")
                postUpdate(itm_uber1_flame_time, new DateTimeType())
end


/* --------- uber bark ---------- */
rule "Uber bark threshold"
        when
                Item itm_uber1_bark_mqtt received update
        then
                if(itm_uber1_bark_alm_enb.state == ON)
                {
                        sendCommand(itm_uber1_bark_alm_sta, ON)
                }
end

rule "Uber bark response"
        when
                Item itm_uber1_bark_alm_sta changed from OFF to ON
        then
                sendMail("ArduinoHomeAutomationOpenHAB@gmail.com", "bark detected" , "dog barked!!!")
                //playSound("ding.mp3")
                postUpdate(itm_uber1_bark_time, new DateTimeType())
end

/* --------- uber pir ---------- */
rule "Uber pir threshold"
        when
                Item itm_uber1_pir_mqtt received update
        then
                if(itm_uber1_pir_alm_enb.state == ON)
                {
                        sendCommand(itm_uber1_pir_alm_sta, ON)
                }
end

rule "Uber pir response"
        when
                Item itm_uber1_pir_alm_sta changed from OFF to ON
        then
                sendMail("ArduinoHomeAutomationOpenHAB@gmail.com", "pir detected" , "dog pired!!!")
                //playSound("ding.mp3")
                postUpdate(itm_uber1_pir_time, new DateTimeType())
end


-----------------------------------------------------------------
    Frame label="Uber Sensor" {
            Text item=itm_uber1_temp_mqtt
            Text item=itm_uber1_hum_mqtt
            Switch item=itm_uber1_light_sta
            Switch item=itm_NAA_auto
    }
    Frame label="Uber Sensor Alarm Status" {
            Switch item=itm_uber1_gas_alm_sta mappings=[OFF="Off"]
            Switch item=itm_uber1_flame_alm_sta mappings=[OFF="Off"]
            Switch item=itm_uber1_bark_alm_sta mappings=[OFF="Off"]
            Switch item=itm_uber1_pir_alm_sta mappings=[OFF="Off"]
    }
    Frame label="Uber Sensor Alarm Enable" {
            Switch item=itm_uber1_gas_alm_enb
            Switch item=itm_uber1_flame_alm_enb
            Switch item=itm_uber1_bark_alm_enb
            Switch item=itm_uber1_pir_alm_enb
    }
Comments