-
Notifications
You must be signed in to change notification settings - Fork 0
Rules
How to work with automation rules
- [Introduction] (Rules#introduction)
- [Defining Rules] (Rules#defining-rules)
- [File Location] (Rules#file-location)
- [IDE Support] (Rules#ide-support)
- [The Syntax] (Rules#the-syntax)
- Triggers
- [Rule Triggers] (Rules#rule-triggers)
- [Item- / Event-based Triggers] (Rules#item---event-based-triggers)
- [Time-based Triggers] (Rules#time-based-triggers)
- [System-based Triggers] (Rules#system-based-triggers)
- [Implicit Variables inside the Execution Block] (Rules#implicit-variables-inside-the-execution-block)
- [Using the same Variable name across separate rule files] (Rules#using-the-same-variable-name-across-separate-rule-files)
- [Concurrency Guard] (Rules#concurrency-guard)
- [Logging] (Rules#logging)
- [Example] (Rules#example)
"Rules" are used for automating processes: Each rule can be triggered, which invokes a script that performs any kinds of tasks, e.g. turn on lights by modifying your items, do mathematical calculations, start timers etcetera (for more details on what a rule can do, see scripts documentation).
openHAB has a highly integrated, lightweight but yet powerful rule engine included. On this page you will learn how to leverage its functionality to do real home automation.
Rules are placed in the folder ${openhab.home}/configurations/rules
. The runtime already comes with a demo file called demo.rules
, which has a couple of examples, which can be a good starting point.
A rule file can contain multiple rules. All rules of a file share a common execution context, i.e. they can access and exchange variables with each other. It therefore makes sense to have different rule files for different use-cases or categories.
The openHAB Designer offers full IDE support for rules, which includes syntax checks and coloring, validation with error markers, content assist (Ctrl+Space) incl. templates etc. This makes the creation of rules very easy!
Note: The rule syntax is based on Xbase and as a result it is sharing many details with Xtend, which is built on top of Xbase as well. As a result, we will often point to the Xtend documentation for details.
A rule file is a text file with the following structure:
[Imports]
[Variable Declarations]
[Rules]
The Imports section contains import statement just like in Java. As in Java, they make the imported types available without having to use the fully qualified name for them. For further details, please see the Xtend documentation for imports.
Example:
import org.openhab.core.library.types.*
The Variable Declarations section can be used to declare variables that should be accessible to all rules in this file. You can declare variables with or without initial values and modifiable or read-only. For further details, please see the Xtend documentation for variable declarations.
Example:
// a variable with an initial value. Note that the variable type is automatically inferred
var counter = 0
// a read-only value, again the type is automatically inferred
val msg = "This is a message"
// an uninitialized variable where we have to provide the type (as it cannot be inferred from an initial value)
var Number x
The Rules section contains a list of rules. Each rule has the following syntax:
rule "rule name"
when
<TRIGGER CONDITION1> or
<TRIGGER_CONDITION2> or
<TRIGGER_CONDITION3>
...
then
<EXECUTION_BLOCK>
end
A rule can have any number of trigger conditions, but must at least have one. The EXECUTION_BLOCK contains the code that should be executed, when a trigger condition is met. The content of the EXECUTION_BLOCK is in fact a script, so please refer to the scripts documentation for details.
Before a rule starts working, it has to be triggered.
There are different categories of rule triggers:
- Item(-Event)-based triggers: They react on events on the openHAB event bus, i.e. commands and status updates for items
- Time-based triggers: They react at special times, e.g. at midnight, every hour, etc.
- System-based triggers: They react on certain system statuses.
Here are the details for each category:
You can listen to commands for a specific item, on status updates or on status changes (an update might leave the status unchanged). You can decide whether you want to catch only a specific command/status or any. Here is the syntax for all these cases (parts in square brackets are optional):
Item <item> received command [<command>]
Item <item> received update [<state>]
Item <item> changed [from <state>] [to <state>]
A simplistic explanation of the differences between
command
andupdate
(useful if you are new to openHAB) can be found on the Actions page
You can either use some pre-defined expressions for timers or use a cron expression instead:
Time is midnight
Time is noon
Time cron "<cron expression>"
A cron expression takes the form of six or optionally seven fields:
- Seconds
- Minutes
- Hours
- Day-of-Month
- Month
- Day-of-Week
- Year (optional field)
for more information see: http://www.quartz-scheduler.org/documentation/quartz-2.1.x/tutorials/tutorial-lesson-06
You may also use CronMaker to generate cron expressions.
Currently, you schedule rules to be executed either at system startup or shutdown. Note that newly added or modified startup rules are executed once, even if openHAB is already up and running. They are simply executed once as soon as the system is aware of them. Here's the syntax for system triggers:
System started
System shuts down
Besides the implicitly available variables for items and commands/states (see the script documentation), rules can have additional pre-defined variables, depending on their triggers:
- Every rule that has at least one command event trigger, will have the variable
receivedCommand
available, which can be used inside the execution block. - Every rule that has at least one status change event trigger, will have the variable
previousState
available, which can be used inside the execution block.
It is worth being aware that there "could" be issues (despite what the documentation says) when using the same variable name in separate rule files.
Taken from 1121 Developer Kai says:
The theory is: Variables are global to all rules within one rule file and they are NOT visible to rules in other files. So it should be fine to use the same name for variables in different files. In practice, openHAB has afaik a bug regarding this and there actually ARE side effects if you use the same variable name across different files. Note that this has been fixed in ESH (https://bugs.eclipse.org/bugs/show_bug.cgi?id=423532), so in openHAB 2.0, this problem should not exist anymore.
If a rule triggers on UI events it may be necessary to guard against concurrency.
import java.util.concurrent.locks.ReentrantLock
var java.util.concurrent.locks.ReentrantLock lock = new java.util.concurrent.locks.ReentrantLock()
rule ConcurrentCode
when
Item Dummy received update
then
lock.lock()
try {
// do stuff (e.g. create and start a timer ...)
} finally{
lock.unlock()
}
end
You can emit log messages from your rules to aid debugging. There are a number of logging methods available from your rules, the java signatures are:
logDebug(String loggerName, String format, Object... args)
logInfo(String loggerName, String format, Object... args)
logWarn(String loggerName, String format, Object... args)
logError(String loggerName, String format, Object... args)
In each case, the loggerName
parameter is combined with the string org.openhab.model.script.
to create the log4j logger name. For example, if your rules file contained the following log message:
logDebug("kitchen", "Kitchen light turned on")
then the logger you would have to enable in your logbook.xml file to allow that message to appear in your logs would be:
<logger name="org.openhab.model.script.kitchen" level="DEBUG"/>
Taking all the information together, an example rule file could look like this:
// import the decimal type as we refer to it in a rule
import org.openhab.core.library.types.DecimalType
var Number counter
// setting the counter to some initial value
// we could have done this in the variable declaration already
rule Startup
when
System started
then
counter = 0
end
// increase the counter at midnight
rule "Increase counter"
when
Time cron "0 0 0 * * ?"
then
counter = counter + 1
end
// tell the number of days either at noon or if a button is pressed
rule "Announce number of days up"
when
Time is noon or
Item AnnounceButton received command ON
then
say("The system is up since " + counter + " days")
end
// sets the counter to the value of a received command
rule "Set the counter"
when
Item SetCounterItem received command
then
counter = receivedCommand as DecimalType
end
You can find further examples in the openHAB-samples section.
###Windows
###FreeBSD
- Classic UI
- iOS Client
- Android Client
- Windows Phone Client
- GreenT UI
- CometVisu
- Kodi
- Slack
- Chrome Extension
- Cosm Persistence
- db4o Persistence
- Amazon DynamoDB Persistence
- Exec Persistence
- InfluxDB Persistence
- JDBC Persistence
- JPA Persistence
- Logging Persistence
- mapdb Persistence
- MongoDB Persistence
- MQTT Persistence
- my.openHAB Persistence
- MySQL Persistence
- rrd4j Persistence
- Sen.Se Persistence
- SiteWhere Persistence
- AKM868 Binding
- AlarmDecoder Binding
- Anel Binding
- Arduino SmartHome Souliss Binding
- Asterisk Binding
- Astro Binding
- Autelis Pool Control Binding
- BenQ Projector Binding
- Bluetooth Binding
- Bticino Binding
- CalDAV Binding
- Chamberlain MyQ Binding
- Comfo Air Binding
- Config Admin Binding
- CUL Transport
- CUL Intertechno Binding
- CUPS Binding
- DAIKIN Binding
- Davis Binding
- Denon Binding
- digitalSTROM Binding
- DMX512 Binding
- DSC Alarm Binding
- DSMR Binding
- eBUS Binding
- Ecobee Binding
- EDS OWSever Binding
- eKey Binding
- Energenie Binding
- EnOcean Binding
- Enphase Energy Binding
- Epson Projector Binding
- Exec Binding
- Freebox Binding
- Freeswitch Binding
- Frontier Silicon Radio Binding
- Fritz AHA Binding
- Fritz!Box Binding
- FritzBox-TR064-Binding
- FS20 Binding
- Garadget Binding
- Global Caché IR Binding
- GPIO Binding
- HAI/Leviton OmniLink Binding
- HDAnywhere Binding
- Heatmiser Binding
- Homematic / Homegear Binding
- HTTP Binding
- IEC 62056-21 Binding
- IHC / ELKO Binding
- ImperiHome Binding
- Insteon Hub Binding
- Insteon PLM Binding
- IPX800 Binding
- IRtrans Binding
- jointSPACE-Binding
- KNX Binding
- Koubachi Binding
- LCN Binding
- LightwaveRF Binding
- Leviton/HAI Omnilink Binding
- Lg TV Binding
- Logitech Harmony Hub
- MailControl Binding
- MAX!Cube-Binding
- MAX! CUL Binding
- MiLight Binding
- MiOS Binding
- Mochad X10 Binding
- Modbus Binding
- MPD Binding
- MQTT Binding
- MQTTitude binding
- MystromEcoPower Binding
- Neohub Binding
- Nest Binding
- Netatmo Binding
- Network Health Binding
- Network UPS Tools Binding
- Nibe Heatpump Binding
- Nikobus Binding
- Novelan/Luxtronic Heatpump Binding
- NTP Binding
- One-Wire Binding
- Onkyo AV Receiver Binding
- Open Energy Monitor Binding
- OpenPaths presence detection binding
- OpenSprinkler Binding
- OSGi Configuration Admin Binding
- Panasonic TV Binding
- panStamp Binding
- Philips Hue Binding
- Picnet Binding
- Piface Binding
- PiXtend Binding
- pilight Binding
- Pioneer-AVR-Binding
- Plex Binding
- Plugwise Binding
- PLCBus Binding
- Powermax alarm Binding
- Primare Binding
- Pulseaudio Binding
- Raspberry Pi RC Switch Binding
- RFXCOM Binding
- RWE Smarthome Binding
- Sager WeatherCaster Binding
- Samsung AC Binding
- Samsung TV Binding
- Serial Binding
- Sallegra Binding
- Satel Alarm Binding
- SimpleBinary Binding
- Sinthesi Sapp Binding
- Smarthomatic Binding
- Snmp Binding
- Somfy URTSI II Binding
- Sonance Binding
- Sonos Binding
- Souliss Binding
- Squeezebox Binding
- Stiebel Eltron Heatpump
- Swegon ventilation Binding
- System Info Binding
- TA CMI Binding
- TCP/UDP Binding
- Tellstick Binding
- TinkerForge Binding
- Tivo Binding
- UCProjects.eu Relay Board Binding
- VDR Binding
- Velleman-K8055-Binding
- Wago Binding
- Wake-on-LAN Binding
- Waterkotte EcoTouch Heatpump Binding
- Weather Binding
- Wemo Binding
- Withings Binding
- XBMC Binding
- xPL Binding
- Yamahareceiver Binding
- Zibase Binding
- Z-Wave Binding
- Asterisk
- DoorBird
- FIND
- Foscam IP Cameras
- LG Hombot
- Worx Landroid
- Heatmiser PRT Thermostat
- Google Calendar
- Linux Media Players
- Rainforest EAGLE Energy Access Gateway
- Roku Integration
- ROS Robot Operating System
- Telldus Tellstick
- Zoneminder
- Wink Hub (rooted)
- Wink Monitoring
- Transformations
- XSLT
- JSON
- REST-API
- Security
- Service Discovery
- Voice Control
- BritishGasHive-Using-Ruby
- Dropbox Bundle
A good source of inspiration and tips from users gathered over the years. Be aware that things may have changed since they were written and some examples might not work correctly.
Please update the wiki if you do come across any out of date information.
- Rollershutter Bindings
- Squeezebox
- WAC Binding
- WebSolarLog
- Alarm Clock
- Convert Fahrenheit to Celsius
- The mother of all lighting rules
- Reusable Rules via Functions
- Combining different Items
- Items, Rules and more Examples of a SmartHome
- Google Map
- Controlling openHAB with Android
- Usecase examples
- B-Control Manager
- Spell checking for foreign languages
- Flic via Tasker
- Chromecast via castnow
- Speedtest.net integration