Skip to content

JSR223 Scripting ​

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 (spec) is a standard scripting API for Java Virtual Machine (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 (JVM scripting language), JavaScript/ECMAScript 2024+, JRuby, and Python (Python 3 on GraalVM). Legacy languages JavaScript/ECMA - 262 Edition 5.1 and Jython (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+, also known as JavaScript Scripting, 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) 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 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 ​

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);

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. 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.

Script Lifecycle ​

Script files from the above location are loaded on openHAB startup. openHAB watches the above location for changes, and loads new scripts on creation as well as reloads existing scripts on change. Upon reload of a script file, the old script is unloaded first and then the new script is loaded.

Other places in openHAB where scripting is used, e.g. transformations, might have a different script lifecycle.

ScriptExtension Presets ​

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, lifecycle and media presets are preloaded, so they do not require importing. With scriptExtension.get("automationManager") the automationManager can be made available without loading a preset.

default Preset ​

Imported by default (importPreset not required).

VariableDescription
Stateorg.openhab.core.types.State
Commandorg.openhab.core.types.Command
URLEncoderjava.net.URLEncoder
Filejava.io.File
Filesjava.nio.file.Files
Pathjava.nio.file.Path
Pathsjava.nio.file.Paths
ChronoUnitjava.time.temporal.ChronoUnit
DayOfWeekjava.time.DayOfWeek
Durationjava.time.Duration
Monthjava.time.Month
ZoneIdjava.time.ZoneId
ZonedDateTimejava.time.ZonedDateTime
IncreaseDecreaseTypeorg.openhab.core.library.types.IncreaseDecreaseType
DECREASEIncreaseDecreaseType enum item
INCREASEIncreaseDecreaseType enum item
OnOffTypeorg.openhab.core.library.types.OnOffType
ONOnOffType enum item
OFFOnOffType enum item
OpenClosedTypeorg.openhab.core.library.types.OpenClosedType
OPENOpenClosedType enum item
CLOSEDOpenClosedType enum item
StopMoveTypeorg.openhab.core.library.types.StopMoveType
STOPStopMoveType enum item
MOVEStopMoveType enum item
UpDownTypeorg.openhab.core.library.types.UpDownType
UPUpDownType enum item
DOWNUpDownType enum item
UnDefTypeorg.openhab.core.types.UnDefType
NULLUnDefType enum item
UNDEFUnDefType enum item
RefreshTypeorg.openhab.core.types.RefreshType
REFRESHRefreshType enum item
NextPreviousTypeorg.openhab.core.library.types.NextPreviusType
NEXTNextPreviousType enum item
PREVIOUSNextPreviousType enum item
PlayPauseTypeorg.openhab.core.library.types.PlayPauseType
PLAYPlayPauseType enum item
PAUSEPlayPauseType enum item
RewindFastforwardTypeorg.openhab.core.library.types.RewindFastforwardType
REWINDRewindFastforwardType enum item
FASTFORWARDRewindFastforwardType enum item
QuantityTypeorg.openhab.core.library.types.QuantityType
StringListTypeorg.openhab.core.library.types.StringListType
RawTypeorg.openhab.core.library.types.RawType
DateTimeTypeorg.openhab.core.library.types.DateTimeType
DecimalTypeorg.openhab.core.library.types.DecimalType
HSBTypeorg.openhab.core.library.types.HSBType
PercentTypeorg.openhab.core.library.types.PercentType
PointTypeorg.openhab.core.library.types.PointType
StringTypeorg.openhab.core.library.types.StringType
SIUnitsorg.openhab.core.library.unit.SIUnits
ImperialUnitsorg.openhab.core.library.unit.ImperialUnits
MetricPrefixorg.openhab.core.library.unit.MetricPrefix
Unitsorg.openhab.core.library.unit.Units
BinaryPrefixorg.openhab.core.library.unit.BinaryPrefix
itemsInstance of java.util.Map<String, State>
irAlias for itemRegistry
itemRegistryInstance of org.openhab.core.items.ItemRegistry
thingsInstance of org.openhab.core.thing.ThingRegistry
rulesInstance of org.openhab.core.automation.RuleRegistry
events(Internal) Used to send events, post commands, etc. Details below
actionsInstance of org.openhab.core.automation.module.script.defaultscope.ScriptThingActions
scriptExtension(internal) For loading script presets.
seAlias for scriptExtension

events operations ​

Instance of org.openhab.core.automation.module.script.action.BusEvent.

For all post update, send command, and send time series operations, methods with an additional String parameter are available to specify the source of the event. Refer to Developer: Event Bus for more information about event source.

Post Update ​
  • events.postUpdate(String, String)
  • events.postUpdate(Item, Number)
  • events.postUpdate(Item, String)
  • events.postUpdate(Item, State)
Send Command ​
  • events.sendCommand(String, String)
  • events.sendCommand(Item, Number)
  • events.sendCommand(Item, String)
  • events.sendCommand(Item, Command)
Send Time Series ​
  • events.sendTimeSeries(String, Map<ZonedDateTime, State>, String)
  • events.sendTimeSeries(Item, TimeSeries)
Store and Restore States ​
  • events.storeStates(Item...)
  • events.restoreStates(Map<Item, State>)

lifecycle Preset ​

Imported by default (importPreset not required).

Provides a mechanism to execute a callback on disposal. A script is disposed both on modification and removal, see Script Lifecycle.

VariableDescription
lifecycleTrackerorg.openhab.core.automation.module.script.LifecycleScriptExtensionProvider.LifecycleTracker

This is demonstrated in the scriptLoaded and scriptUnloaded functions section.

media Preset ​

Imported by default (importPreset not required).

VariableDescription
audioorg.openhab.core.audio.AudioManager
voiceorg.openhab.core.voice.VoiceManager

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.

VariableDescription
ActionTypeorg.openhab.core.automation.type.ActionType
ConfigDescriptionParameterorg.openhab.core.config.core.ConfigDescriptionParameter
ModuleTypeorg.openhab.core.automation.type.ModuleType
SimpleActionHandlerorg.openhab.core.automation.module.script.rulesupport.shared.simple.SimpleActionHandler
SimpleConditionHandlerorg.openhab.core.automation.module.script.rulesupport.shared.simple.SimpleConditionHandler
SimpleRuleBase class for Rules org.openhab.core.automation.module.script.rulesupport.shared.simple.SimpleRule
SimpleTriggerHandlerorg.openhab.core.automation.module.script.rulesupport.shared.simple.SimpleTriggerHandler
TriggerTypeorg.openhab.core.automation.type.TriggerType
Visibilityorg.openhab.core.automation.Visibility enum

RuleSupport Preset ​

These variables and classes are loaded using:

python
scriptExtension.importPreset("RuleSupport")
VariableDescription
Actionorg.openhab.core.automation.Action
ActionBuilderorg.openhab.core.automation.util.ActionBuilder
Conditionorg.openhab.core.automation.Condition
ConditionBuilderorg.openhab.core.automation.util.ConditionBuilder
Configurationorg.openhab.core.config.core.Configuration
ModuleBuilderorg.openhab.core.automation.util.ModuleBuilder
Ruleorg.openhab.core.automation.Rule (use SimpleRule for defining rules)
Triggerorg.openhab.core.automation.Trigger
TriggerBuilderorg.openhab.core.automation.util.TriggerBuilder
automationManagerorg.openhab.core.automation.module.script.rulesupport.shared.ScriptedAutomationManager instance for managing rules and other openHAB module instances. (e.g., addRule)
ruleRegistryorg.openhab.core.automation.Rule

RuleFactories Preset ​

Note: Advanced usage

python
scriptExtension.importPreset("RuleFactories")
VariableDescription
ActionHandlerFactoryorg.openhab.core.automation.module.script.rulesupport.shared.factories.ScriptedActionHandlerFactory
ActionTypeorg.openhab.core.automation.type.ActionType
ConditionHandlerFactoryorg.openhab.core.automation.module.script.rulesupport.shared.factories.ScriptedConditionHandlerFactory
ConfigDescriptionParameterorg.openhab.core.config.core.ConfigDescriptionParameter
ModuleTypeorg.openhab.core.automation.type.ModuleType
TriggerHandlerFactoryorg.openhab.core.automation.module.script.rulesupport.shared.factories.ScriptedTriggerHandlerFactory
TriggerTypeorg.openhab.core.automation.type.TriggerType
Visibilityorg.openhab.core.automation.Visibility

ScriptAction Preset ​

This preset can be useful for scheduling asynchronous code execution with org.openhab.core.automation.module.script.action.Timer.

VariableDescription
busEventorg.openhab.core.automation.module.script.action.BusEvent
scriptExecutionorg.openhab.core.automation.module.script.action.ScriptExecution

The busEvent variable is identical to the events variable in the default preset.

groovy
scriptExtension.importPreset("ScriptAction")

scriptExecution.createTimer(ZonedDateTime.now().plusSeconds(1), {
  org.slf4j.LoggerFactory.getLogger('Test logger').warn('Timer ran')
})

cache Preset ​

The cache preset does not provide a default import and needs to be imported explicitly.

groovy
scriptExtension.importPreset("cache")

sharedCache.put("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.

provider Preset ​

VariableDescription
itemRegistryorg.openhab.core.automation.module.script.providersupport.shared.ProviderItemRegistryDelegate
metadataRegistryorg.openhab.core.automation.module.script.providersupport.shared.ProviderMetadataRegistryDelegate
thingRegistryorg.openhab.core.automation.module.script.providersupport.shared.ProviderThingRegistryDelegate
itemChannelLinkRegistryorg.openhab.core.automation.module.script.providersupport.shared.ProviderItemChannelLinkRegistry

The above instances provide implementations of the interfaces org.openhab.core.items.ItemRegistry, org.openhab.core.items.MetadataRegistry and org.openhab.core.thing.ThingRegistry respectively. The itemChannelLinkRegistry does not provide the same methods as the org.openhab.core.thing.link.ItemChannelLinkRegistry interface.

All instances from this preset have an addPermanent(...) method, in addition to add(...). With the add(...) method, elements added over the above instances are removed when the script that inserted the elements is unloaded. When addPermanent(...) is used, the inserted elements are not removed. itemRegistry.addPermanent(...)/thingRegistry.addPermanent(...) from this preset offer the same functionality as itemRegistry.add(...)/things.add(...) from the default preset.

TriggerType Objects ​

The following trigger types are defined by openHAB (custom triggers can also be defined) and take the specified parameters in the constructor of org.openhab.core.config.core.Configuration. The configuration can be passed to TriggerBuilder.withConfiguration(). All parameters are Strings. Read the JSR223 language specific documentation for examples of using these TriggerType objects.

timer.DateTimeTrigger
ParameterDescription
itemNameThe name of the Item
timeOnlyWhether only the time of the item should be compared or the date and time
offsetThe offset in seconds to add to the time of the item
timer.GenericCronTrigger
ParameterDescription
cronExpressionThe cron expression
timer.TimeOfDayTrigger
ParameterDescription
timeThe time in "hh:mm" format
core.ItemCommandTrigger
ParameterDescription
itemNameThe name of the Item
commandThe Command (optional)
core.ItemStateUpdateTrigger
ParameterDescription
itemNameThe name of the Item
stateThe State (optional)
core.ItemStateChangeTrigger
ParameterDescription
itemNameThe name of the Item
previousStateThe previous State (optional)
stateThe State (optional)
core.GroupCommandTrigger
ParameterDescription
groupNameThe name of the GroupItem
commandThe Command (optional)
core.GroupStateUpdateTrigger
ParameterDescription
groupNameThe name of the GroupItem
stateThe State (optional)
core.GroupStateChangeTrigger
ParameterDescription
groupNameThe name of the GroupItem
previousStateThe previous State (optional)
stateThe State (optional)
core.ThingStatusUpdateTrigger
ParameterDescription
thingUIDThe thingUID
statusThe ThingStatus (optional)
core.ThingStatusChangeTrigger
ParameterDescription
thingUIDThe thingUID
previousStatusThe previous ThingStatus (optional)
statusThe ThingStatus (optional)
core.ChannelEventTrigger
ParameterDescription
channelUIDThe ChannelUID of the Channel
eventThe Channel trigger Event (optional)
core.GenericEventTrigger
ParameterDescription
topicThe topic to match, as a file-system style glob (*, **, ?, and {} operators).

Example filters:
Item events: "openhab/items/*/"
Channel events: "openhab/channels/*/triggered"
Thing events: "openhab/things/**"
sourceThe object that triggered the event, such as org.openhab.core.expire
typesItemCommandEvent, ItemStateEvent, ItemStateChangedEvent, GroupItemStateChangedEvent, ItemAddedEvent, ItemRemovedEvent, ThingAddedEvent, ThingRemovedEvent, ThingStatusInfoChangedEvent, ThingStatusInfoEvent, ThingUpdatedEvent, etc. A non-exhaustive list can be found in the Javadocs.
payloadRegex to match against the actual event data.
core.SystemStartlevelTrigger
ParameterDescription
startlevelThe system StartLevel

scriptLoaded and scriptUnloaded functions ​

When a script file is loaded, the scriptLoaded(String) function is invoked if it is defined. The path of the script file will be passed as parameter. Similarly, when a script file is unloaded, the scriptUnloaded() function is invoked if it is defined. Note that scriptLoaded(String) and scriptUnloaded() are only executed for script files – not transformations, Script Actions or Script conditions of rules. Refer to the Script Lifecycle section for more information on load and unload behavior.

lifecycleTracker's addDisposeHook(Disposable) and the scriptUnloaded() function serve similar purposes, but it is recommended to use addDisposeHook(Disposable) as its functionality is not limited to script files only. The lifecyleTracker also supports adding multiple dispose hooks, contrary to scriptUnloaded() that can only be defined once.

groovy
static @groovy.transform.Field logger = org.slf4j.LoggerFactory.getLogger("org.openhab.automation.example")

lifecycleTracker.addDisposeHook(new org.openhab.core.automation.module.script.LifecycleScriptExtensionProvider.Disposable() {
  public void dispose() {
    logger.error("I am logged fourth.")
  }
})

lifecycleTracker.addDisposeHook{ logger.error("I am logged fifth. Bye!") }

void scriptLoaded(String filename) { // can be static
  logger.error("I am logged second and I am from ${filename}.")
}

static void scriptUnloaded() { // can be non-static
  logger.error("I am logged third.")
}
logger.error("I am logged first.")