663 lines
38 KiB
Markdown
663 lines
38 KiB
Markdown
---
|
|
layout: documentation
|
|
title: JSR223 Scripting
|
|
---
|
|
|
|
# JSR223 Scripting
|
|
|
|
::: tip Note
|
|
This feature is for users who have or are willing to learn some programming skills
|
|
and are comfortable working with the command line prompt of the operating system hosting openHAB.
|
|
:::
|
|
|
|
## Overview
|
|
|
|
[JSR223](https://docs.oracle.com/javase/8/docs/technotes/guides/scripting/) ([spec](https://jcp.org/aboutJava/communityprocess/pr/jsr223/index.html)) is a standard scripting API for Java Virtual Machine (JVM) [languages](https://en.wikipedia.org/wiki/List_of_JVM_languages).
|
|
The JVM languages provide varying levels of support for the JSR223 API and interoperability with the Java runtime.
|
|
Currently the following languages are known to work well for openHAB scripting: [**Apache Groovy**](/addons/automation/groovyscripting/) (JVM scripting language), [**JavaScript/ECMAScript 2024+**](/addons/automation/jsscripting/), [**JRuby**](/addons/automation/jrubyscripting/), and [**Python**](/addons/automation/pythonscripting/) (Python 3 on GraalVM). Legacy languages [**JavaScript/ECMA - 262 Edition 5.1**](/addons/automation/jsscriptingnashorn/) and [**Jython**](/addons/automation/jythonscripting/) (Python 2.7 on the JVM) are also still supported.
|
|
|
|
Please note that **JavaScript/ECMA - 262 Edition 5.1** which is referenced here is using an older engine called NashornJS.
|
|
This version of JavaScript/ECMAScript is end of life and lacks many important features that have been added to the language since 2009.
|
|
If you plan to use JavaScript/ECMAScript as your scripting language, it is recommended to use [**JavaScript/ECMAScript 2024+**](/addons/automation/jsscripting/),
|
|
also known as [JS Scripting](/addons/automation/jsscripting/), which includes the latest **ES6** language features, supports third party node libraries (please keep in mind that not all NodeJS APIs are available in GraalJS),
|
|
and comes with a well documented helper library ([openhab-js](https://github.com/openhab/openhab-js/)) that makes interaction with the APIs documented on this page (and more) much simpler and straight forward in plain JavaScript.
|
|
|
|
Although JSR223 scripts can be used as a general-purpose extension language for openHAB, it is most commonly used for the creation of rules, and within scripted Actions or Conditions.
|
|
Currently, openHAB allows JSR223 scripting to access all packages, which may not be included in the official APIs.
|
|
This provides great flexibility for the users of JSR223, but is also _use at your own risk_, since changes outside of the official APIs occur frequently, and are not considered to be _breaking changes_.
|
|
New APIs are planned to be implemented in the future, which will provide standardized interfaces for interacting with openHAB through scripted automation.
|
|
|
|
### Example rules for a first impression
|
|
|
|
:::: tabs
|
|
|
|
::: tab JavaScript/ECMAScript - 262 Edition 5.1
|
|
|
|
```js
|
|
'use strict';
|
|
|
|
scriptExtension.importPreset("RuleSupport");
|
|
scriptExtension.importPreset("RuleSimple");
|
|
|
|
var sRule = new SimpleRule() {
|
|
execute: function( module, input) {
|
|
print("This is a 'hello world!' from a JavaScript rule.");
|
|
}
|
|
};
|
|
|
|
sRule.setTriggers([
|
|
TriggerBuilder.create()
|
|
.withId("aTimerTrigger")
|
|
.withTypeUID("timer.GenericCronTrigger")
|
|
.withConfiguration(
|
|
new Configuration({
|
|
"cronExpression": "0 * * * * ?"
|
|
})).build()
|
|
]);
|
|
|
|
automationManager.addRule(sRule);
|
|
```
|
|
|
|
:::
|
|
|
|
::: tab JS Scripting
|
|
|
|
```js
|
|
// Import openHAB Java API
|
|
Object.assign(this, require('@runtime'));
|
|
Object.assign(this, require('@runtime/RuleSimple'));
|
|
Object.assign(this, require('@runtime/RuleSupport'));
|
|
|
|
// Override non-working TriggerBuilder import
|
|
const TriggerBuilder = Java.type('org.openhab.core.automation.util.TriggerBuilder');
|
|
|
|
const sRule = new SimpleRule({
|
|
execute: function(module, input) {
|
|
print('This is a \'hello world!\' from a JavaScript rule.');
|
|
}
|
|
});
|
|
sRule.setName('A JavaScript/ECMAScript 262 Edition 11')
|
|
sRule.setTriggers([
|
|
TriggerBuilder.create()
|
|
.withId('aTimerTrigger')
|
|
.withTypeUID('timer.GenericCronTrigger')
|
|
.withConfiguration(
|
|
new Configuration({
|
|
'cronExpression': '0 * * * * ?'
|
|
}))
|
|
.build()
|
|
]);
|
|
|
|
automationManager.addRule(sRule);
|
|
```
|
|
|
|
```js
|
|
// And the same rule using the helper library:
|
|
|
|
const { rules, triggers } = require('openhab');
|
|
|
|
rules.JSRule({
|
|
name: 'A JavaScript/ECMAScript 262 Edition 11',
|
|
description: 'This is a JavaScript rule.',
|
|
triggers: [
|
|
triggers.GenericCronTrigger('0 * * * * ?')
|
|
],
|
|
execute: (event) => {
|
|
console.log('This is a \'hello world!\' from a JavaScript rule.');
|
|
}
|
|
});
|
|
```
|
|
|
|
:::
|
|
|
|
::: tab Jython
|
|
|
|
```python
|
|
scriptExtension.importPreset("RuleSupport")
|
|
scriptExtension.importPreset("RuleSimple")
|
|
|
|
class myRule(SimpleRule):
|
|
def execute(self, module, inputs):
|
|
print "This is a 'hello world!' from Jython rule."
|
|
|
|
sRule = myRule()
|
|
sRule.setTriggers([
|
|
TriggerBuilder.create()
|
|
.withId("aTimerTrigger")
|
|
.withTypeUID("timer.GenericCronTrigger")
|
|
.withConfiguration(
|
|
Configuration({
|
|
"cronExpression": "0 * * * * ?"
|
|
})).build()
|
|
])
|
|
|
|
automationManager.addRule(sRule)
|
|
```
|
|
|
|
:::
|
|
|
|
::: tab Groovy
|
|
|
|
```groovy
|
|
import org.openhab.core.automation.*
|
|
import org.openhab.core.automation.module.script.rulesupport.shared.simple.*
|
|
import org.openhab.core.config.core.Configuration
|
|
|
|
scriptExtension.importPreset("RuleSupport")
|
|
scriptExtension.importPreset("RuleSimple")
|
|
|
|
def sRule = new SimpleRule() {
|
|
Object execute(Action module, Map<String, ?> inputs) {
|
|
println("Hello World from Groovy")
|
|
}
|
|
}
|
|
sRule.setTriggers([
|
|
TriggerBuilder.create()
|
|
.withId("aTimerTrigger")
|
|
.withTypeUID("timer.GenericCronTrigger")
|
|
.withConfiguration(new Configuration([cronExpression: "0 * * * * ?"]))
|
|
.build()
|
|
])
|
|
|
|
automationManager.addRule(sRule)
|
|
```
|
|
|
|
:::
|
|
|
|
::: tab JRuby
|
|
|
|
```ruby
|
|
$scriptExtension.importPreset('RuleSupport')
|
|
$scriptExtension.importPreset('RuleSimple')
|
|
|
|
class MyRule < SimpleRule
|
|
def execute(_mod, _inputs)
|
|
logger = org.slf4j.LoggerFactory.getLogger('org.openhab.automation.example')
|
|
logger.info('Hello World from JRuby')
|
|
end
|
|
end
|
|
|
|
s_rule = MyRule.new
|
|
s_rule.set_triggers([
|
|
TriggerBuilder.create
|
|
.with_id('aTimerTrigger')
|
|
.with_type_uid('timer.GenericCronTrigger')
|
|
.with_configuration(Configuration.new({ 'cronExpression' => '0 * * * * ?' }))
|
|
.build
|
|
])
|
|
|
|
$automationManager.add_rule(s_rule)
|
|
```
|
|
|
|
```ruby
|
|
# And the same rule using the bundled helper library:
|
|
|
|
rule "A Cron Rule in Ruby" do
|
|
every :minute
|
|
run do
|
|
logger.info "Hello World from JRuby"
|
|
end
|
|
end
|
|
```
|
|
|
|
:::
|
|
|
|
::::
|
|
|
|
### Script Locations
|
|
|
|
Scripts should be placed in the `${OPENHAB_CONF}/automation/jsr223/` directory.
|
|
This directory will vary, [based on the type of openHAB installation used](https://www.openhab.org/docs/installation/linux.html#installation).
|
|
For example, Linux installations created with a package installer will use `/etc/openhab/automation/jsr223/`, and manual installations will use `/opt/openhab/conf/automation/jsr223/`.
|
|
|
|
When openHAB starts, scripts are loaded at start level 40 by default (in no particular order).
|
|
The start level for each script can be overridden by specifying a start level either in the filename (`./my_script.sl50.py`) or containing directory (`./sl50/my_script.py`).
|
|
The runtime provides no explicit dependency mechanism or ordering, yet scripts are loaded one at a time so can be ordered via start level if desired.
|
|
For example, with the following scripts and directory structure...
|
|
|
|
```text
|
|
├── automation/jsr223
|
|
│ ├── dir1
|
|
│ │ ├── script_a.py
|
|
│ │ └── script_b.py
|
|
│ ├── script.sl38.py
|
|
│ ├── sl30
|
|
│ │ ├── script_x.py
|
|
│ │ └── script_y.py
|
|
│ └── script.py
|
|
```
|
|
|
|
... the load order will be: (`sl30/script_x.py` & `sl30/script_y.py`) at start level 30, `script.sl38.py` at start level 38, then (`/dir1/script_a.py`, `/dir1/script_b.py`, `script.py`) at start level 40.
|
|
The script file watching mechanism itself is activated at start level 20, so scripts cannot be executed earlier than this.
|
|
|
|
Note that prior to openHAB 3, script ordering was performed alphanumerically based on file path. This is no longer supported as of openHAB 3 and later versions.
|
|
|
|
### `ScriptExtension` Objects (all JSR223 languages)
|
|
|
|
To facilitate JSR223 scripting, several openHAB-related variables are automatically predefined within `ScriptExtension` presets.
|
|
They can be loaded into the script context using `scriptExtension.importPreset(String preset)`, e.g. `scriptExtension.importPreset("RuleSimple")`.
|
|
The `default` preset is preloaded, so it does not require importing.
|
|
With `scriptExtension.get("automationManager")` the `automationManager` can be made available without loading a preset.
|
|
|
|
- [Overview](#overview)
|
|
- [Example rules for a first impression](#example-rules-for-a-first-impression)
|
|
- [Script Locations](#script-locations)
|
|
- [`ScriptExtension` Objects (all JSR223 languages)](#scriptextension-objects-all-jsr223-languages)
|
|
- [Default Preset (`importPreset` not required)](#default-preset-importpreset-not-required)
|
|
- [`events` operations](#events-operations)
|
|
- [RuleSimple Preset](#rulesimple-preset)
|
|
- [`RuleSupport` Preset](#rulesupport-preset)
|
|
- [`RuleFactories` Preset](#rulefactories-preset)
|
|
- [`ScriptAction` Preset](#scriptaction-preset)
|
|
- [`cache` Preset](#cache-preset)
|
|
- [`TriggerType` Objects (all JSR223 languages)](#triggertype-objects-all-jsr223-languages)
|
|
|
|
#### Default Preset (`importPreset` not required)
|
|
|
|
| Variable | Description |
|
|
|-------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
|
| `State` | [`org.openhab.core.types.State`](https://www.openhab.org/javadoc/latest/org/openhab/core/types/state) |
|
|
| `Command` | [`org.openhab.core.types.Command`](https://www.openhab.org/javadoc/latest/org/openhab/core/types/command) |
|
|
| `URLEncoder` | [`java.net.URLEncoder`](https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/net/URLEncoder.html) |
|
|
| `File` | [`java.io.File`](https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/io/File.html) |
|
|
| `Files` | [`java.nio.file.Files`](https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/nio/file/Files.html) |
|
|
| `Path` | [`java.nio.file.Path`](https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/nio/file/Path.html) |
|
|
| `Paths` | [`java.nio.file.Paths`](https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/nio/file/Paths.html) |
|
|
| `IncreaseDecreaseType` | [`org.openhab.core.library.types.IncreaseDecreaseType`](https://www.openhab.org/javadoc/latest/org/openhab/core/library/types/increasedecreasetype) |
|
|
| `DECREASE` | `IncreaseDecreaseType` enum item |
|
|
| `INCREASE` | `IncreaseDecreaseType` enum item |
|
|
| `OnOffType` | [`org.openhab.core.library.types.OnOffType`](https://www.openhab.org/javadoc/latest/org/openhab/core/library/types/onofftype) |
|
|
| `ON` | `OnOffType` enum item |
|
|
| `OFF` | `OnOffType` enum item |
|
|
| `OpenClosedType` | [`org.openhab.core.library.types.OpenClosedType`](https://www.openhab.org/javadoc/latest/org/openhab/core/library/types/openclosedtype) |
|
|
| `OPEN` | `OpenClosedType` enum item |
|
|
| `CLOSED` | `OpenClosedType` enum item |
|
|
| `StopMoveType` | [`org.openhab.core.library.types.StopMoveType`](https://www.openhab.org/javadoc/latest/org/openhab/core/library/types/stopmovetype) |
|
|
| `STOP` | `StopMoveType` enum item |
|
|
| `MOVE` | `StopMoveType` enum item |
|
|
| `UpDownType` | [`org.openhab.core.library.types.UpDownType`](https://www.openhab.org/javadoc/latest/org/openhab/core/library/types/updowntype) |
|
|
| `UP` | `UpDownType` enum item |
|
|
| `DOWN` | `UpDownType` enum item |
|
|
| `UnDefType` | [`org.openhab.core.library.types.UnDefType`](https://www.openhab.org/javadoc/latest/org/openhab/core/types/undeftype) |
|
|
| `NULL` | `UnDefType` enum item |
|
|
| `UNDEF` | `UnDefType` enum item |
|
|
| `RefreshType` | [`org.openhab.core.library.types.RefreshType`](https://www.openhab.org/javadoc/latest/org/openhab/core/types/refreshtype) |
|
|
| `REFRESH` | `RefreshType` enum item |
|
|
| `NextPreviousType` | [`org.openhab.core.library.types.NextPreviusType`](https://www.openhab.org/javadoc/latest/org/openhab/core/library/types/nextprevioustype) |
|
|
| `NEXT` | `NextPreviousType` enum item |
|
|
| `PREVIOUS` | `NextPreviousType` enum item |
|
|
| `PlayPauseType` | [`org.openhab.core.library.types.PlayPauseType`](https://www.openhab.org/javadoc/latest/org/openhab/core/library/types/playpausetype) |
|
|
| `PLAY` | `PlayPauseType` enum item |
|
|
| `PAUSE` | `PlayPauseType` enum item |
|
|
| `RewindFastforwardType` | [`org.openhab.core.library.types.RewindFastforwardType`](https://www.openhab.org/javadoc/latest/org/openhab/core/library/types/rewindfastforwardtype) |
|
|
| `REWIND` | `RewindFastforwardType` enum item |
|
|
| `FASTFORWARD` | `RewindFastforwardType` enum item |
|
|
| `QuantityType` | [`org.openhab.core.library.types.QuantityType`](https://www.openhab.org/javadoc/latest/org/openhab/core/library/types/quantitytype) |
|
|
| `StringListType` | [`org.openhab.core.library.types.StringListType`](https://www.openhab.org/javadoc/latest/org/openhab/core/library/types/stringlisttype) |
|
|
| `RawType` | [`org.openhab.core.library.types.RawType`](https://www.openhab.org/javadoc/latest/org/openhab/core/library/types/rawtype) |
|
|
| `DateTimeType` | [`org.openhab.core.library.types.DateTimeType`](https://www.openhab.org/javadoc/latest/org/openhab/core/library/types/datetimetype) |
|
|
| `DecimalType` | [`org.openhab.core.library.types.DecimalType`](https://www.openhab.org/javadoc/latest/org/openhab/core/library/types/decimaltype) |
|
|
| `HSBType` | [`org.openhab.core.library.types.HSBType`](https://www.openhab.org/javadoc/latest/org/openhab/core/library/types/hsbtype) |
|
|
| `PercentType` | [`org.openhab.core.library.types.PercentType`](https://www.openhab.org/javadoc/latest/org/openhab/core/library/types/percenttype) |
|
|
| `PointType` | [`org.openhab.core.library.types.PointType`](https://www.openhab.org/javadoc/latest/org/openhab/core/library/types/pointtype) |
|
|
| `StringType` | [`org.openhab.core.library.types.StringType`](https://www.openhab.org/javadoc/latest/org/openhab/core/library/types/stringtype) |
|
|
| `SIUnits` | [`org.openhab.core.library.unit.SIUnits`](https://www.openhab.org/javadoc/latest/org/openhab/core/library/unit/siunits) |
|
|
| `ImperialUnits` | [`org.openhab.core.library.unit.ImperialUnits`](https://www.openhab.org/javadoc/latest/org/openhab/core/library/unit/imperialunits) |
|
|
| `MetricPrefix` | [`org.openhab.core.library.unit.MetricPrefix`](https://www.openhab.org/javadoc/latest/org/openhab/core/library/unit/metricprefix) |
|
|
| `Units` | [`org.openhab.core.library.unit.Units`](https://www.openhab.org/javadoc/latest/org/openhab/core/library/unit/units) |
|
|
| `BinaryPrefix` | [`org.openhab.core.library.unit.BinaryPrefix`](https://www.openhab.org/javadoc/latest/org/openhab/core/library/unit/binaryprefix) |
|
|
| `items` | Instance of `java.util.Map<String, State>` |
|
|
| `ir` | Alias for `itemRegistry` |
|
|
| `itemRegistry` | Instance of `org.openhab.core.items.ItemRegistry` |
|
|
| `things` | Instance of `org.openhab.core.thing.ThingRegistry` |
|
|
| `rules` | Instance of `org.openhab.core.automation.RuleRegistry` |
|
|
| `events` | (internal) Used to send events, post commands, etc. [Details](#events-operations) below] |
|
|
| `actions` | Instance of [`org.openhab.core.automation.module.script.defaultscope.ScriptThingActions`](https://www.openhab.org/javadoc/latest/org/openhab/core/automation/module/script/defaultscope/scriptthingactions) |
|
|
| `scriptExtension` | (internal) For loading script presets. |
|
|
| `se` | Alias for `scriptExtension` |
|
|
|
|
##### `events` operations
|
|
|
|
- `events.postUpdate(String, String)`
|
|
- `events.postUpdate(Item, Number)`
|
|
- `events.postUpdate(Item, String)`
|
|
- `events.postUpdate(Item, State)`
|
|
- `events.sendCommand(String, String)`
|
|
- `events.sendCommand(Item, Number)`
|
|
- `events.sendCommand(Item, String)`
|
|
- `events.sendCommand(Item, Command)`
|
|
- `events.storeStates(Item...)`
|
|
- `events.restoreStates(Map<Item, State>)`
|
|
|
|
#### RuleSimple Preset
|
|
|
|
These variables and classes are loaded using:
|
|
|
|
```python
|
|
scriptExtension.importPreset("RuleSimple")
|
|
```
|
|
|
|
The primary usage of this preset is for defining rule (`SimpleRule`) subclasses.
|
|
See language-specific documentation for examples.
|
|
|
|
| Variable | Description |
|
|
| -------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
| ActionType | [`org.openhab.core.automation.type.ActionType`](https://www.openhab.org/javadoc/latest/org/openhab/core/automation/type/actiontype) |
|
|
| ConfigDescriptionParameter | [`org.openhab.core.config.core.ConfigDescriptionParameter`](https://www.openhab.org/javadoc/latest/org/openhab/core/config/core/configdescriptionparameter) |
|
|
| ModuleType | [`org.openhab.core.automation.type.ModuleType`](https://www.openhab.org/javadoc/latest/org/openhab/core/automation/type/moduletype) |
|
|
| SimpleActionHandler | [`org.openhab.core.automation.module.script.rulesupport.shared.simple.SimpleActionHandler`](https://www.openhab.org/javadoc/latest/org/openhab/core/automation/module/script/rulesupport/shared/simple/simpleactionhandler) |
|
|
| SimpleConditionHandler | [`org.openhab.core.automation.module.script.rulesupport.shared.simple.SimpleConditionHandler`](https://www.openhab.org/javadoc/latest/org/openhab/core/automation/module/script/rulesupport/shared/simple/simpleconditionhandler) |
|
|
| SimpleRule | Base class for Rules [`org.openhab.core.automation.module.script.rulesupport.shared.simple.SimpleRule`](https://www.openhab.org/javadoc/latest/org/openhab/core/automation/module/script/rulesupport/shared/simple/simplerule) |
|
|
| SimpleTriggerHandler | [`org.openhab.core.automation.module.script.rulesupport.shared.simple.SimpleTriggerHandler`](https://www.openhab.org/javadoc/latest/org/openhab/core/automation/module/script/rulesupport/shared/simple/simpletriggerhandler) |
|
|
| TriggerType | [`org.openhab.core.automation.type.TriggerType`](https://www.openhab.org/javadoc/latest/org/openhab/core/automation/type/triggertype) |
|
|
| Visibility | [`org.openhab.core.automation.Visibility`](https://www.openhab.org/javadoc/latest/org/openhab/core/automation/visibility) enum |
|
|
|
|
#### `RuleSupport` Preset
|
|
|
|
These variables and classes are loaded using:
|
|
|
|
```python
|
|
scriptExtension.importPreset("RuleSupport")
|
|
```
|
|
|
|
| Variable | Description |
|
|
| ----------------- | --------------------------------------------------------------------------------- |
|
|
| Action | `org.openhab.core.automation.Action` |
|
|
| ActionBuilder | `org.openhab.core.automation.ActionBuilder` |
|
|
| Condition | `org.openhab.core.automation.Condition` |
|
|
| ConditionBuilder | `org.openhab.core.automation.ConditionBuilder` |
|
|
| Configuration | `org.openhab.core.config.core.Configuration` |
|
|
| ModuleBuilder | `org.openhab.core.automation.ModuleBuilder` |
|
|
| Rule | `org.openhab.core.automation.Rule` (use `SimpleRule` for defining rules) |
|
|
| Trigger | `org.openhab.core.automation.Trigger` |
|
|
| TriggerBuilder | `org.openhab.core.automation.util.TriggerBuilder` |
|
|
| automationManager | Instance for managing rules and other openHAB module instances. (e.g., `addRule`) |
|
|
| ruleRegistry | `org.openhab.core.automation.Rule` |
|
|
|
|
#### `RuleFactories` Preset
|
|
|
|
>Note: Advanced usage
|
|
|
|
```python
|
|
scriptExtension.importPreset("RuleFactories")
|
|
```
|
|
|
|
| Variable | Description |
|
|
| ------------------------- | -------------------------------------------------------------------------------------------------------- |
|
|
| `ActionHandlerFactory` | `org.openhab.core.automation.module.script.rulesupport.shared.factories.ScriptedActionHandlerFactory` |
|
|
| `ConditionHandlerFactory` | `org.openhab.core.automation.module.script.rulesupport.shared.factories.ScriptedConditionHandlerFactory` |
|
|
| `TriggerHandlerFactory` | `org.openhab.core.automation.module.script.rulesupport.shared.factories.ScriptedTriggerHandlerFactory` |
|
|
|
|
#### `ScriptAction` Preset
|
|
|
|
This preset can be useful for scheduling asynchronous code execution with `org.openhab.core.automation.module.script.action.Timer`.
|
|
|
|
| Variable | Description |
|
|
|-------------------|--------------------------------------------------------------------|
|
|
| `scriptExecution` | `org.openhab.core.automation.module.script.action.ScriptExecution` |
|
|
|
|
:::: tabs
|
|
|
|
::: tab Groovy
|
|
|
|
```groovy
|
|
scriptExtension.importPreset("ScriptAction")
|
|
scriptExtension.importPreset("RuleSupport")
|
|
scriptExtension.importPreset("RuleSimple")
|
|
|
|
scriptExecution.createTimer(ZonedDateTime.now(), {
|
|
org.slf4j.LoggerFactory.getLogger('Test logger').warn('Timer ran')
|
|
})
|
|
```
|
|
|
|
:::
|
|
|
|
::: tab JSScripting
|
|
|
|
```javascript
|
|
actions.scriptExecution.createTimer(time.toZDT(1000), () => {
|
|
console.info('Timer ran');
|
|
})
|
|
```
|
|
|
|
:::
|
|
|
|
::: tab DSL
|
|
|
|
```java
|
|
createTimer(now.plusSeconds(1), [ |
|
|
logInfo('Test logger', 'Timer ran')
|
|
])
|
|
```
|
|
|
|
:::
|
|
|
|
::: tab JRuby
|
|
|
|
```ruby
|
|
after(1.second) do
|
|
logger.info("Timer ran")
|
|
end
|
|
```
|
|
|
|
:::
|
|
|
|
::::
|
|
|
|
#### `cache` Preset
|
|
|
|
The `cache` preset does not provide a default import and needs to be imported explicitly.
|
|
|
|
:::: tabs
|
|
|
|
::: tab Groovy
|
|
|
|
```groovy
|
|
scriptExtension.importPreset("cache")
|
|
|
|
sharedCache.put("x", "y")
|
|
```
|
|
|
|
:::
|
|
|
|
::: tab Nashorn JS
|
|
|
|
```js
|
|
scriptExtension.importPreset("cache")
|
|
|
|
var valueX = sharedCache.get("x")
|
|
```
|
|
|
|
:::
|
|
|
|
::: tab JS Scripting
|
|
|
|
```js
|
|
var { sharedCache, privateCache } = require('@runtime/cache')
|
|
|
|
sharedCache.remove("x")
|
|
```
|
|
|
|
:::
|
|
|
|
::: tab DSL
|
|
|
|
```java
|
|
sharedCache.put('foo', 'bar')
|
|
sharedCache.get('foo') // returns null if doesn't exist
|
|
sharedCache.remove('foo') // deletes the entry
|
|
```
|
|
|
|
:::
|
|
|
|
::: tab Jython
|
|
|
|
```python
|
|
scriptExtension.importPreset("cache")
|
|
```
|
|
|
|
:::
|
|
|
|
::: tab JRuby
|
|
|
|
```ruby
|
|
# the preset is imported automatically by the helper library.
|
|
value_x = shared_cache[:x]
|
|
shared_cache.delete(:x)
|
|
shared_cache[:x] = "y"
|
|
```
|
|
|
|
:::
|
|
|
|
::::
|
|
|
|
It provides two different caches:
|
|
|
|
- `sharedCache`: This cache is shared over all languages and all scripts (file-based and UI). Usage of entries is tracked and entries will be removed if the last script that ever accessed an entry is removed.
|
|
- `privateCache`: This cache is private to a script engine, usually that means it is private to a script or rule, depending on the implementation of the scripting language.
|
|
It is cleared when the script engine is unloaded (i.e. usually when the script is unloaded).
|
|
|
|
In both cases values that are either a `ScheduledFuture<?>` or a `Timer` are cancelled by calling `.cancel()` on the object if the object is removed automatically.
|
|
|
|
Both caches implement the `org.openhab.core.automation.module.script.rulesupport.shared.ValueCache` interface and therefore can be accessed by
|
|
|
|
- `Object put(String key, Object value)`: Put a key/value pair to the cache. Returns old value if already set, otherwise `null`.
|
|
- `Object remove(String key)`: Remove the key/value pair from the cache. Returns old value if already set, otherwise `null`.
|
|
- `Object get(String key)`: Get the value for the given key from the cache. Non-existent keys return `null`.
|
|
- `Object get(String key, Supplier<Object> supplier`: Get the value for the given key. If no value is present, add the value that is return from the `supplier`.
|
|
|
|
### `TriggerType` Objects (all JSR223 languages)
|
|
|
|
The following trigger types are defined by openHAB (custom triggers can also be defined) and take the specified configuration parameters.
|
|
All parameters are Strings.
|
|
Read the JSR223 language specific documentation for examples of using these `TriggerType` objects.
|
|
|
|
::: details timer.DateTimeTrigger
|
|
|
|
| Parameter | Description |
|
|
|------------|---------------------------------------------------------------------------|
|
|
| `itemName` | The name of the `Item` |
|
|
| `timeOnly` | Whether only the time of the item should be compared or the date and time |
|
|
| `offset` | The offset in seconds to add to the time of the item |
|
|
|
|
:::
|
|
|
|
::: details timer.GenericCronTrigger
|
|
|
|
| Parameter | Description |
|
|
|------------------|---------------------|
|
|
| `cronExpression` | The cron expression |
|
|
|
|
:::
|
|
|
|
::: details timer.TimeOfDayTrigger
|
|
|
|
| Parameter | Description |
|
|
|-----------|----------------------------|
|
|
| `time` | The time in "hh:mm" format |
|
|
|
|
:::
|
|
|
|
::: details core.ItemCommandTrigger
|
|
|
|
| Parameter | Description |
|
|
|------------|--------------------------|
|
|
| `itemName` | The name of the `Item` |
|
|
| `command` | The `Command` (optional) |
|
|
|
|
:::
|
|
|
|
::: details core.ItemStateUpdateTrigger
|
|
|
|
| Parameter | Description |
|
|
|------------|------------------------|
|
|
| `itemName` | The name of the `Item` |
|
|
| `state` | The `State` (optional) |
|
|
|
|
:::
|
|
|
|
::: details core.ItemStateChangeTrigger
|
|
|
|
| Parameter | Description |
|
|
|-----------------|---------------------------------|
|
|
| `itemName` | The name of the `Item` |
|
|
| `previousState` | The previous `State` (optional) |
|
|
| `state` | The `State` (optional) |
|
|
|
|
:::
|
|
|
|
::: details core.GroupCommandTrigger
|
|
|
|
| Parameter | Description |
|
|
|-------------|-----------------------------|
|
|
| `groupName` | The name of the `GroupItem` |
|
|
| `command` | The `Command` (optional) |
|
|
|
|
:::
|
|
|
|
::: details core.GroupStateUpdateTrigger
|
|
|
|
| Parameter | Description |
|
|
|-------------|-----------------------------|
|
|
| `groupName` | The name of the `GroupItem` |
|
|
| `state` | The `State` (optional) |
|
|
|
|
:::
|
|
|
|
::: details core.GroupStateChangeTrigger
|
|
|
|
| Parameter | Description |
|
|
|-----------------|---------------------------------|
|
|
| `groupName` | The name of the `GroupItem` |
|
|
| `previousState` | The previous `State` (optional) |
|
|
| `state` | The `State` (optional) |
|
|
|
|
:::
|
|
|
|
::: details core.ThingStatusUpdateTrigger
|
|
|
|
| Parameter | Description |
|
|
|------------|------------------------------|
|
|
| `thingUID` | The `thingUID` |
|
|
| `status` | The `ThingStatus` (optional) |
|
|
|
|
:::
|
|
|
|
::: details core.ThingStatusChangeTrigger
|
|
|
|
| Parameter | Description |
|
|
|------------------|---------------------------------------|
|
|
| `thingUID` | The `thingUID` |
|
|
| `previousStatus` | The previous `ThingStatus` (optional) |
|
|
| `status` | The `ThingStatus` (optional) |
|
|
|
|
:::
|
|
|
|
::: details core.ChannelEventTrigger
|
|
|
|
| Parameter | Description |
|
|
|--------------|------------------------------------------|
|
|
| `channelUID` | The `ChannelUID` of the `Channel` |
|
|
| `event` | The `Channel` trigger `Event` (optional) |
|
|
|
|
:::
|
|
|
|
::: details core.GenericEventTrigger
|
|
|
|
| Parameter | Description |
|
|
|-----------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
|
| `topic` | The topic to match, as a file-system style glob (*, **, ?, and {} operators).<br><br>Example filters:<br>Item events: "openhab/items/\*/"<br>Channel events: "openhab/channels/\*/triggered"<br>Thing events: "openhab/things/\*\*" |
|
|
| `source` | The object that triggered the event, such as `org.openhab.core.expire` |
|
|
| `types` | `ItemCommandEvent`, `ItemStateEvent`, `ItemStateChangedEvent`, `GroupItemStateChangedEvent`, `ItemAddedEvent`, `ItemRemovedEvent`, `ThingAddedEvent`, `ThingRemovedEvent`, `ThingStatusInfoChangedEvent`, `ThingStatusInfoEvent`, `ThingUpdatedEvent`, etc. A non-exhaustive list can be found [in the Javadocs](https://www.openhab.org/javadoc/latest/org/openhab/core/events/event). |
|
|
| `payload` | Regex to match against the actual event data. |
|
|
|
|
:::
|
|
|
|
::: details core.SystemStartlevelTrigger
|
|
|
|
| Parameter | Description |
|
|
|--------------|-------------------------|
|
|
| `startlevel` | The system `StartLevel` |
|
|
|
|
:::
|