JS Scripting ECMAScript 2021, right? I ask because this code looks a whole lot like Nashorn ECMAScript 5.1 and the two are not the same. For one thing, JS Scripting doesn’t have an items
dict like that.
While you can make Nashorn rules work in JS Scripting, especially for something this short and simple you would do well to rewrite it to use the Js Scripting add-on’s helper library.
Also, you shouldn’t use the this.timer = blah blah blah
trick anymore in either language. Use the privateCache
.
The rule should look something like this (I’m just typing this in, debugging is an exercise to the student).
console.loggerName = 'org.openhab.rule.'+ ruleUID;
var TimerMinutes = items.getItem('MotionTimer').state; // note the state is always a String in this usage
console.info('TimerMinutes: ' + TimerMinutes);
var timer = cache.privateCache.get('timer');
if(timer !== null) {
timer.cancel();
}
var turnOff = () => {
var i = items.getItem('CoridorRoomLightCeiling1_Power1');
i.sendCommand('OFF');
console.info('MotionSensor turned ' + i.state); // this almost certainly never worked,
// it takes time for an Item's state to reflect the result of command,
// it likely has always shown the old state.
// I left it as is to have a one-to-one translation of the original, errors and all
cache.privateCache.put('timer', null);
};
cache.privateCache.put('timer', actions.ScriptExecution.createTimer(time.toZDT('PT'+timerMinutes+'M') , turnOff);
That is staying as close to the original as possible. However, JS Scripting has a native JavaScript Timer capability which could be used here too with setTimeout.
All the syntax and types involved when using Js Scripting with the helper library are documented here.
There is one thing to note though. In OH 4 the mime types for Nashorn and GraalVM JavaScript have swapped. Previously application/javascript
was for the older Nashorn and application/javascript;ecmascript=2021
(or something like that) was for JS Scripting (i.e. GraalVM JavaScript ECMAScript 2021). Now JS Scripting gets the standard type and Nashorn gets the one with ;ecmascript=5.1
or something like that.
If your problem is you have some Nashorn rules and you want to continue to use Nashorn, you’ll need to:
- Install the Nashorn JS addon
- Open the “code” tab for your rules and change any place you see
application/javascript
to what ever is required for Nashorn (right now I can’t create a Script with Nashorn even though I’ve it installed for some reason so I can’t tell you exactly what it should be).
Or you can just install the Nashorn add-on and uninstall the JS Scripting addon. That might work.
I think there is a plan to make this switch happen automatically in the future but that’s not done yet.