This add-on provides Ruby scripting language for automation rules.
It includes the [openhab-scripting](https://openhab.github.io/openhab-jruby/) helper library, a comprehensive Ruby gem designed to enhance automation in openHAB.
This library offers a streamlined syntax for writing file-based and UI-based rules, making it easier and more intuitive than Rules DSL, while delivering the full features of the Ruby language.
rule "Turn on light when sensor changed to open" do
changed Door_Sensor # a Contact item
run do |event|
if event.open?
Cupboard_Light.on for: 3.minutes # Automatically turn it off after 3 minutes
else
Cupboard_Light.off # This will automatically cancel the timer set above
end
end
end
```
```ruby
rule "Door open reminder" do
changed Doors.members, to: OPEN
run do |event|
# Create a timer using the triggering item as the timer id
# If a timer with the given id already exists, it will be rescheduled
after 5.minutes, id: event.item do |timer|
next if timer.cancelled? || event.item.closed?
Voice.say "The #{event.item} is open"
timer.reschedule # Use the original duration by default
end
end
end
```
Example UI-based rules:
```ruby
only_every(2.minutes) do # apply rate-limiting
Audio.play_sound("doorbell.mp3")
Notification.send("Someone pressed the doorbell")
end
```
Additional [example rules are available](https://openhab.github.io/openhab-jruby/main/file.examples.html), as well as examples of [conversions from Rules DSL, JavaScript, and Python rules](https://openhab.github.io/openhab-jruby/main/file.conversions.html).
- Go to `Settings -> Add-ons -> Automation` and install the jrubyscripting automation addon following the [openHAB instructions](https://www.openhab.org/docs/configuration/addons.html).
- Edit `<OPENHAB_CONF>/services/addons.cfg` and ensure that `jrubyscripting` is included in an uncommented `automation=` list of automations to install.
This allows the use of [items](https://openhab.github.io/openhab-jruby/main/OpenHAB/DSL.html#items-class_method), [rules](https://openhab.github.io/openhab-jruby/main/OpenHAB/DSL.html#rules-class_method), [shared_cache](https://openhab.github.io/openhab-jruby/main/OpenHAB/DSL.html#shared_cache-class_method) and other objects in your scripts.
Path to where Ruby Gems will be installed to and loaded from.
The directory will be created if necessary.
You can use `RUBY_ENGINE_VERSION`, `RUBY_ENGINE` and/or `RUBY_VERSION` replacements in this value to automatically point to a new directory when the addon is updated with a new version of JRuby.
| `openhab-scripting` | install the latest version of `openhab-scripting` gem |
| `openhab-scripting=~>5.0.0` | install the latest version 5.0.x but not 5.1.x |
| `openhab-scripting=~>5.0` | install the latest version 5.x but not 6.x |
| `openhab-scripting=~>5.0, faraday=~>2.7;>=2.7.4` | install `openhab-scripting` gem version 5.x and `faraday` gem version 2.7.4 or higher, but less than 3.0 |
| `gem1= >= 2.2.1; <= 2.2.5` | install `gem1` gem version 2.2.1 or above, but less than or equal to version 2.2.5 |
Otherwise it will try to fulfil the requirements with locally installed gems, and you can manage them yourself with an external Ruby by setting the same GEM_HOME.
You may want to disable dependency tracking if you plan on editing or updating a shared library, but don't want all your scripts to reload until you can test it.
Advanced users, or users migrating scripts from existing systems may want to use [File Based Scripts](#file-based-scripts) for managing rules using files in the user configuration directory.
Theoretically you could even use a system start trigger with a UI rule, and then use the [syntax](#file-based-rules) mostly developed for file based rules to create multiple rules.
### File Based Scripts
The JRuby Scripting addon will load scripts from `automation/ruby` in the user configuration directory.
The system will automatically reload scripts when changes are detected to files.
Local variable state is not persisted among reloads, see using the [cache](#cache) for a convenient way to persist objects.
See [File Based Rules](#file-based-rules) for examples of creating rules within your scripts.
### Event Object
When you use "Item event" as trigger (i.e. "[item] received a command", "[item] was updated", "[item] changed"), there is additional context available for the action in a variable called `event`.
| `state` | [State](https://openhab.github.io/openhab-jruby/main/OpenHAB/Core/Types/State.html) or `nil` | `[item] changed`, `[item] was updated` | State that triggered event | `triggeringItem.state` |
| `was` | [State](https://openhab.github.io/openhab-jruby/main/OpenHAB/Core/Types/State.html) or `nil` | `[item] changed` | Previous state of Item or Group that triggered event | `previousState` |
| `command` | [Command](https://openhab.github.io/openhab-jruby/main/OpenHAB/Core/Types/Command.html) | `[item] received a command` | Command that triggered event | `receivedCommand` |
| `item` | [Item](https://openhab.github.io/openhab-jruby/main/OpenHAB/Core/Items/Item.html) | All item related triggers | Item that triggered event | `triggeringItem` |
| `group` | [GroupItem](https://openhab.github.io/openhab-jruby/main/OpenHAB/Core/Items/Item.html) | `Member of [group] changed`, `Member of [group] was updated`, `Member of [group] received a command` | Group whose member triggered the event | `triggeringGroup` |
See [ensure_states](https://openhab.github.io/openhab-jruby/main/OpenHAB/DSL.html#ensure_states-class_method), [ensure_states!](https://openhab.github.io/openhab-jruby/main/OpenHAB/DSL.html#ensure_states!-class_method),
A [Timed Command](https://openhab.github.io/openhab-jruby/main/OpenHAB/DSL/Items/TimedCommand.html) is similar to the openHAB Item's [expire parameter](https://www.openhab.org/docs/configuration/items.html#parameter-expire) but it offers more flexibility.
The Item's state is accessible through [Item#state](https://openhab.github.io/openhab-jruby/main/OpenHAB/Core/Items/GenericItem.html#state-instance_method):
Check if an Item's state is [NULL](https://openhab.github.io/openhab-jruby/main/OpenHAB/Core/Types/UnDefType.html#NULL-constant) of [UNDEF](https://openhab.github.io/openhab-jruby/main/OpenHAB/Core/Types/UnDefType.html#UNDEF-constant):
Types that are comparable, such as [StringType](https://openhab.github.io/openhab-jruby/main/OpenHAB/Core/Types/StringType.html), [DateTimeType](https://openhab.github.io/openhab-jruby/main/OpenHAB/Core/Types/DateTimeType.html), [DecimalType](https://openhab.github.io/openhab-jruby/main/OpenHAB/Core/Types/DecimalType.html), [PercentType](https://openhab.github.io/openhab-jruby/main/OpenHAB/Core/Types/PercentType.html), include Ruby's [Comparable](https://docs.ruby-lang.org/en/master/Comparable.html) module which provides the handy [between?](https://docs.ruby-lang.org/en/master/Comparable.html#method-i-between-3F) method.
For example, a [DimmerItem](https://openhab.github.io/openhab-jruby/main/OpenHAB/Core/Items/DimmerItem.html) can accept a command with an [OnOffType](https://openhab.github.io/openhab-jruby/main/OpenHAB/Core/Types/OnOffType.html), [IncreaseDecreaseType](https://openhab.github.io/openhab-jruby/main/OpenHAB/Core/Types/IncreaseDecreaseType.html) or a [PercentType](https://openhab.github.io/openhab-jruby/main/OpenHAB/Core/Types/PercentType.html).
However, ultimately an item only stores its state in its native type, e.g. a [DimmerItems](https://openhab.github.io/openhab-jruby/main/OpenHAB/Core/Items/DimmerItem.html)'s native type is [PercentType](https://openhab.github.io/openhab-jruby/main/OpenHAB/Core/Types/PercentType.html).
In some contexts, you don't care about the precise value of a particular state, and just want to know if it fits the general definition of [ON](https://openhab.github.io/openhab-jruby/main/OpenHAB/Core/Types/OnOffType.html#ON-constant), etc.
You can either explicitly convert to the general type, _or_ all of the state predicate methods available on [Item](https://openhab.github.io/openhab-jruby/main/OpenHAB/Core/Items/Item.html), [ItemStateEvent](https://openhab.github.io/openhab-jruby/main/OpenHAB/Core/Events/ItemStateEvent.html), [ItemStateChangedEvent](https://openhab.github.io/openhab-jruby/main/OpenHAB/Core/Events/ItemStateChangedEvent.html), [ItemCommandEvent](https://openhab.github.io/openhab-jruby/main/OpenHAB/Core/Events/ItemCommandEvent.html), as well as specific types such as [PercentType](https://openhab.github.io/openhab-jruby/main/OpenHAB/Core/Types/PercentType.html) and [HSBType](https://openhab.github.io/openhab-jruby/main/OpenHAB/Core/Types/HSBType.html), will do the conversion internally.
[Persistence](https://openhab.github.io/openhab-jruby/main/OpenHAB/Core/Items/Persistence.html) methods are available directly on [Items](https://openhab.github.io/openhab-jruby/main/OpenHAB/Core/Items/Item.html).
Many [helper methods](https://openhab.github.io/openhab-jruby/main/OpenHAB/Core/Items/Semantics.html) are available to make it easy to navigate the semantic model to get related items.
If an [Item](https://openhab.github.io/openhab-jruby/main/OpenHAB/Core/Items/Item.html) is linked to a [Thing](https://openhab.github.io/openhab-jruby/main/OpenHAB/Core/Things/Thing.html), you can easily retrieve it.
[openHAB built-in actions](https://www.openhab.org/docs/configuration/actions.html) are available as children of the [Actions](https://openhab.github.io/openhab-jruby/main/OpenHAB/Core/Actions.html) module.
The [logger](https://openhab.github.io/openhab-jruby/main/OpenHAB/Logger.html) is similar to a standard [Ruby Logger](https://docs.ruby-lang.org/en/master/Logger.html).
`#to_s` (or `toString()` if it's a Java object) is called on `obj`, and the result is output to the openHAB log.
Additionally, all of these methods can take a [Ruby block](https://ruby-doc.com/docs/ProgrammingRuby/html/tut_containers.html#S2) instead, which will only be called if logging is enabled at the given level, and the result of the block will be treated as the log message.
### Timers
```ruby
sleep 1.5 # sleep for 1.5 seconds
```
See Ruby docs on [sleep](https://docs.ruby-lang.org/en/master/Kernel.html#method-i-sleep).
A [delay](https://openhab.github.io/openhab-jruby/main/OpenHAB/DSL/Rules/BuilderDSL.html#delay-instance_method) can be inserted in between two execution blocks to achieve the same result.
Alternatively a timer can be used in either a file-based rule or in a UI based rule using [after](https://openhab.github.io/openhab-jruby/main/OpenHAB/DSL.html#after-class_method).
After takes a [Duration](#durations) relative to `now`, e.g. `10.minutes`, or an absolute time with [ZonedDateTime](https://openhab.github.io/openhab-jruby/main/OpenHAB/CoreExt/Java/ZonedDateTime.html) or [Time](https://openhab.github.io/openhab-jruby/main/Time.html).
Be aware that this can lead to unintentional side effects, e.g. when you change the variable after timer creation, which can make debugging quite difficult!
Furthermore, you can manipulate the managed timers using the built-in [timers](https://openhab.github.io/openhab-jruby/main/OpenHAB/DSL/TimerManager.html) object.
The [shared_cache](https://openhab.github.io/openhab-jruby/main/OpenHAB/DSL.html#shared_cache-class_method) object provides a cache that can be used to set and retrieve objects that will be persisted between reloads of scripts, and available between different rules.
Get a previously set object with a default value, without assigning it (this version has an even longer amount of time between fetching the value and assigning it):
- Java [MonthDay](https://openhab.github.io/openhab-jruby/main/OpenHAB/CoreExt/Java/MonthDay.html) - represents a date with no time or year
- Java [ZonedDateTime](https://openhab.github.io/openhab-jruby/main/OpenHAB/CoreExt/Java/ZonedDateTime.html) - represents a specific instance with a date and time
Ruby [integers](https://docs.ruby-lang.org/en/master/Integer.html) and [floats](https://docs.ruby-lang.org/en/master/Float.html) are extended with several methods to support durations.
These methods create a new [Duration](https://openhab.github.io/openhab-jruby/main/OpenHAB/CoreExt/Java/Duration.html) or [Period](https://openhab.github.io/openhab-jruby/main/OpenHAB/CoreExt/Java/Period.html) object that is used by the [every](https://openhab.github.io/openhab-jruby/main/OpenHAB/DSL/Rules/BuilderDSL.html#every-instance_method) trigger, [delay](https://openhab.github.io/openhab-jruby/main/OpenHAB/DSL/Rules/BuilderDSL.html#delay-instance_method) block, the for option of [changed](https://openhab.github.io/openhab-jruby/main/OpenHAB/DSL/Rules/BuilderDSL.html#changed-instance_method) triggers, and [timers](https://openhab.github.io/openhab-jruby/main/OpenHAB/Core/Timer.html).
Comparisons, conversions and arithmetic are automatic between Java and Ruby types.
Note that anytime you do a comparison between a type with more specific data, and a type missing specific data, the comparison is done as if the more specific data is at the beginning of its period.
I.e. comparing a time to a month, the month will be treated as 00:00:00 on the first day of the month.
When comparing with a type that's missing more generic data, it will be filled in from the other object.
I.e. comparing a time to a month, the month will be assumed to be in the same year as the time.
Ranges of non-absolute, "circular" types ([LocalTime](https://openhab.github.io/openhab-jruby/main/OpenHAB/CoreExt/Java/LocalTime.html), [Month](https://openhab.github.io/openhab-jruby/main/OpenHAB/CoreExt/Java/Month.html), [MonthDay](https://openhab.github.io/openhab-jruby/main/OpenHAB/CoreExt/Java/MonthDay.html)) are smart enough to automatically handle boundary issues.
Coarse types (like [LocalDate](https://openhab.github.io/openhab-jruby/main/OpenHAB/CoreExt/Java/LocalDate.html), [Month](https://openhab.github.io/openhab-jruby/main/OpenHAB/CoreExt/Java/Month.html), [MonthDay](https://openhab.github.io/openhab-jruby/main/OpenHAB/CoreExt/Java/MonthDay.html)) will also work correctly when checking against a more specific type.
To easily parse strings into date-time ranges, use the [OpenHAB::DSL.between](https://openhab.github.io/openhab-jruby/main/OpenHAB/DSL.html#between-class_method) helper.
[Duration](https://openhab.github.io/openhab-jruby/main/OpenHAB/CoreExt/Java/Duration.html), [ZonedDateTime](https://openhab.github.io/openhab-jruby/main/OpenHAB/CoreExt/Java/ZonedDateTime.html), [LocalTime](https://openhab.github.io/openhab-jruby/main/OpenHAB/CoreExt/Java/LocalTime.html), [LocalDate](https://openhab.github.io/openhab-jruby/main/OpenHAB/CoreExt/Java/LocalDate.html), [MonthDay](https://openhab.github.io/openhab-jruby/main/OpenHAB/CoreExt/Java/MonthDay.html), [Month](https://openhab.github.io/openhab-jruby/main/OpenHAB/CoreExt/Java/Month.html), [Time](https://openhab.github.io/openhab-jruby/main/Time.html), [Date](https://openhab.github.io/openhab-jruby/main/Date.html), and [DateTime](https://openhab.github.io/openhab-jruby/main/DateTime.html) classes include [between?](https://openhab.github.io/openhab-jruby/main/OpenHAB/CoreExt/Between.html#between%3F-instance_method) method that accepts a range of string or any of the date/time objects.
[Helper methods](https://openhab.github.io/openhab-jruby/main/OpenHAB/CoreExt/Ephemeris.html) to easily access [openHAB's Ephemeris action](https://www.openhab.org/docs/configuration/actions.html#ephemeris) are provided on all date-like objects:
[Rules](https://openhab.github.io/openhab-jruby/main/OpenHAB/Core/Rules/Rule.html), Scenes and Scripts can be accessed using the [rules](https://openhab.github.io/openhab-jruby/main/OpenHAB/Core/Rules/Registry.html) object.
Scenes are rules with a `Scene` tag, and Scripts are rules with a `Script` tag.
They can be found using their uid just like normal rules, i.e. `rules[uid]`.
For convenience, a list of all Scenes are available through the enumerable [rules.scenes](https://openhab.github.io/openhab-jruby/main/OpenHAB/Core/Rules/Registry.html#scenes-instance_method), and a list of all Scripts through [rules.scripts](https://openhab.github.io/openhab-jruby/main/OpenHAB/Core/Rules/Registry.html#scripts-instance_method).
Or it can be written as one rule with the help of [trigger attachments](https://openhab.github.io/openhab-jruby/main/OpenHAB/DSL/Rules/BuilderDSL.html#Triggers-group).
Existing openHAB transformations can also be used by calling the [transform](https://openhab.github.io/openhab-jruby/main/OpenHAB/DSL.html#transform-class_method) method.
This enables the use of any transformations from the `/transform` folder or managed through the UI, such as MAP, JSONPATH, Jinja Transformation, etc.
```ruby
# Convert OPEN/CLOSED to Online/Offline using availability.map
This add-on also provides the necessary infrastructure to use Ruby for writing [transformations](https://www.openhab.org/docs/configuration/transformations.html).
The main value to be transformed is given to the script in a variable called `input`.
Note that the values are passed to the transformation as Strings even for numeric items and data types.
**Note**: In openHAB 3.4, due to an [issue](https://github.com/jruby/jruby/issues/5876) in the current version of JRuby, you will need to begin your script with `input ||= nil` (and `a ||= nil` etc. for additional query variables) so that JRuby will recognize the variables as variables--rather than method calls--when it's parsing the script.
You can also specify additional variables to be set in the script using a URI-like query syntax: `RB(mytransform.rb?a=1&b=c):%s` in order to share a single script with slightly different parameters for different items.
To trigger based on the date and time stored in a DateTime item, use [at ItemName](https://openhab.github.io/openhab-jruby/main/OpenHAB/DSL/Rules/BuilderDSL.html#at-instance_method):
```ruby
rule "DateTime Trigger" do
at My_DateTimeItem
run do |event|
logger.info "Triggered by #{event.item} at #{event.item.state}"
end
end
```
To trigger based on only the _time_ part of a DateTime item, use [every :day, at: ItemName](https://openhab.github.io/openhab-jruby/main/OpenHAB/DSL/Rules/BuilderDSL.html#every-instance_method):
```ruby
rule "TimeOnly Trigger" do
every :day, at: My_DateTimeItem
run do |event|
logger.info "Triggered by #{event.item} at #{event.item.state}"
A delay exection block is useful for adding a delay inbetween rule executions or even at the beginning of the trigger event without having to manually create a timer.
Unlike `sleep`, a delay block does not block the current executing thread.
It actually sets a timer for you behind the scenes.
The rule definition itself is just Ruby code, which means you can use code to generate your rules.
Take care when doing this as the the items/groups are processed when the rules file is processed, meaning that new items/groups will not automatically generate new rules.
File based scripts can also register [hooks](https://openhab.github.io/openhab-jruby/main/OpenHAB/Core/ScriptHandling.html) that will be called when the script has completed loading (`script_loaded`) and when it gets unloaded (`script_unloaded`).