Some additional insight on “What is Available in the Script” that I gathered from reading through a lot of the code in org.eclipse.smarthome.automation
a year ago I would edit the wiki but I’m not sure how, it’s a little low level… but here it is anyways, it might help understand better how it all works.
Here you’ll see 2 more variables added to the execution context:
-
ruleUID
which is the UID of the current rule -
ctx
which is an object containing the current “context”
You will find an example of using the “ctx” variable here: https://github.com/eclipse/smarthome/blob/master/bundles/automation/org.eclipse.smarthome.automation.module.script.test/ESH-INF/automation/rules/DemoScriptRule.json
As far as I understood, outputs of each trigger and action modules (which are different for each module type, you can have a look at http://openhab:8080/rest/module-types to determine the ouputs defined for a given module type) are added to the context with the ID of the module as a prefix in the format "<moduleID>.<variable>"
Therefore, if you have a module of type core.ItemStateChangeTrigger
with an ID of trigger1
, since that module type has 3 outputs, newState
, oldState
and event
, you can access those outputs in the scripts with ctx['trigger1.newState']
(attention, this is different than ctx.trigger1.newState
which won’t work!), ctx['trigger1.oldState']
, ctx['trigger1.event']
.
Now later in the setExecutionContext
method linked above, you have this code:
That’s basically what gives you the global variables like newState
, oldState
, event
which differ depending on type of the trigger. If there are collisions (multiple outputs with the same name for different modules) then which one ends up as a global variable is unclear.
Two things I found interesting but haven’t really explored:
- script actions has a “result” output too, which is the result of the script, so if you have multiple script actions in a sequence, their IDs being let’s say
script1
and laterscript2
, you can potentially access the result of the first script in the second script withctx['script1.result']
- this could be an simple type, or an array, or an object to reuse in subsequent scripts; - The
core.RunRuleAction
(“run rules”) action forwards the context of the current rule to the rules it runs! This means, if all modules have unique IDs, you may be able to chain rules and still access outputs of modules of the calling rules (for instance, determine what was the oldState in the trigger of the original rule in a rule that was run from it). This was very interesting for my “flows builder” because it relies heavily on the “run rules” action to build flows into rules chained together.
Hope this helps!