OH4.0.0: How do I call an UI script from ECMAScript 2022+ rule

  • Platform information:
    • openHAB version: 4.0.0

Hello,
I am migrating from OH3 to OH4. One of my ECMAScript 2022+ rules is calling a script in the UI script folder (not in configurations/scripts !). I used to call this script this way:

var FrameworkUtil = Java.type("org.osgi.framework.FrameworkUtil");
var _bundle = FrameworkUtil.getBundle(scriptExtension.class);
var bundle_context = _bundle.getBundleContext();
var classname = "org.openhab.core.automation.RuleManager";
var RuleManager_Ref = bundle_context.getServiceReference(classname);
var RuleManager = bundle_context.getService(RuleManager_Ref);
RuleManager.runNow("OtherScript");

but in OH4.0.0 this leads to the error

Script execution of rule with UID ‘RunScript’ failed: org.graalvm.polyglot.PolyglotException: ReferenceError: “scriptExtension” is not defined

I have also tried

actions.ScriptExecution.callScript("OtherScript");

but this leads to the following error:

Script execution of rule with UID ‘OtherScript’ failed: org.openhab.core.model.script.engine.ScriptExecutionException: Script ‘OtherScript’ cannot be found.

This fits to the documentations that states:
Calls a script which must be located in the configurations/scripts folder.

So my question is: How would I call a script in the UI scripts folder from my ECMAScript 2022+ rule?

Thanks for helping!

In the new JSScripting, this is covered in the helper library. All you need is:

rules.runRule('uid-of-rule')
3 Likes

Works fine, thank you very much.

I find it a bit misleading that rules.runRule() starts rules and scripts though.

This is a common comment. The term ‘scripts’ is used in several independent cases in OH. In this case it’s easiest to just remember that the UI managed scripts (and the new UI managed scenes) are just special rules. They show up on different pages in the UI to make it slightly easier to track and create these special versions of rules, but in the end, they are still just rules. For example, the UI “scripts” are just rules that don’t have a defined trigger. With no trigger, there is no event in OH that will cause the body of the script(rule) to run, but they can be called to run in any other way that a rule can be run.

It would be better if there was non-overlapping terminology for these various “script” instances, but no matter how often users get tripped up a little by it, no one has yet managed to propose an alternative that is better (several have tried).

Thank you for the explanation, I didn’t know that. I appreciate it when I can gain deeper insights :slight_smile: