Triggering a rule in Paper UI causes an exception if the rule has not already been triggered elsewhere

Before spending too much more time on this I’m learning a bunch of stuff through my experiments. I’m about to post a big long posting with all my results and turn it into a wiki to gather more data from others. That’s why I created a new post instead of replying here.

But my most recent discovery (copied from the posting in progress):

Get a list of all available Properties

'use strict';

function getProps(obj) {
  var result = [];
  for(var propName in obj) {
    result.push(propName);
  }
  return result;
}

var myLog = Java.type("org.slf4j.LoggerFactory").getLogger("org.eclipse.smarthome.model.script.Rules");

myLog.info("---------------------------")
myLog.info(getProps(this).join("\n"));
2018-10-24 14:07:28.275 [INFO ] [eclipse.smarthome.model.script.Rules] - ---------------------------
2018-10-24 14:07:28.279 [INFO ] [eclipse.smarthome.model.script.Rules] - se
scriptExtension
voice
audio
DOWN
FileUtils
StringType
rules
NextPreviousType
PLAY
ImperialUnits
INCREASE
OpenClosedType
things
UP
RawType
StringListType
events
SIUnits
itemRegistry
NULL
STOP
UnDefType
ir
RewindFastforwardType
DateTimeType
QuantityType
State
DecimalType
IncreaseDecreaseType
File
items
CLOSED
MetricPrefix
DECREASE
OFF
StopMoveType
PREVIOUS
PAUSE
StringUtils
NEXT
REWIND
URLEncoder
HSBType
ON
SmartHomeUnits
UpDownType
PercentType
FilenameUtils
OPEN
Command
OnOffType
MOVE
PlayPauseType
FASTFORWARD
PointType
UNDEF
ctx
ruleUID
getProps
getMethods
myLog

So what do we see here. The majority of the Objects are Item commands and State Types. What else do we have?

Object Purpose
se ???
scriptExtension ???
voice ???
audio ??
FileUtils ???
rules ???
ImperialUnits/SIUnits/MetricPrefix/SmartHomeUnits For unit conversion?
things Access to the Things registry?
events ???
itemRegistry Access to the Items registry
ir ???
File ???
items List of all the Items (how different from itemRegistry?)
StringUtils ???
URLEncoder ???
FilenameUtils ???
ctx ???
ruleUID ???
myLog The logger variable I created in my Rule
getProps Function defined in the Rule to get the properties on an Object
getMethods function defined in the Rule to get the accessible methods on an Object

I think I’m about to successfully create a Timer. I just need to figure out the right way to get access to now.

I DON’t need to import everything, I just needed a way to figure out what was already imported. Thank goodness for StackOverflow. :wink: I’ve tagged you in that post and you will see it shortly. We might be in better shape than I thought.

Though it definitely does appear you have uncovered a bug with triggering from within PaperUI. But so far, if I use what is imported for me instead of trying to import it myself I’ve not encountered any problems.

This shows what is included in the default scope (includes JS rule Actions)…

I’ll change the title of this post to just be more specific about this issue.

Never mind, I’m still stuck.

I can confirm part of what you observed. If I trigger the Rule with an Item I just get

Failed to execute rule '8d37ea74-08b7-4c24-b0ab-a5c5ebf91877': Fail to execute action: 2

and when I trigger it from PaperUI I get the class not found exception. But I was not able to successfully trigger the Rule from PaperUI, even after successfully triggering it using an Item.

Check my first post. There were some semicolons missing (wasn’t an issue, but cleaner with them) and the logging at DEBUG. Unless you have org.eclipse.smarthome.model.script.Rules set for DEBUG logging, you wouldn’t see that the rule actually triggered. I’ve set it to info now.

I fixed both issues i mine already:

'use strict';

var myLog = Java.type("org.slf4j.LoggerFactory").getLogger("org.eclipse.smarthome.model.script.Rules");

myLog.info("createTimer---------------------------");
myLog.info("creating timer...");
var ScriptExecution = Java.type("org.eclipse.smarthome.model.script.actions.ScriptExecution");
var LocalDateTime = Java.type("java.time.LocalDateTime");
var fnc = function(){
    myLog.info("In timer");
}
scriptExtension.createTimer(LocalDateTime.now().plusSeconds(2), fnc);

I’m sure it is something I’m doing wrong.

My next thing to try will be seeing if I can import the JS library from the automation folder. If I can then perhaps a lot of this stuff becomes moot.

Check scriptExecution call… missing capital S.

Same result.

There are two errors there. Lower case s and it should be ScriptExecution, not ScriptExtension. I fixed both, same errors.

Gotta run, but will do some more testing tonight.

Thanks for the help!

Looks like createTimer expects a org.joda.time.base.AbstractInstant. I didn’t run into this with Jython, because I was already using Joda Time. Strange though, because I thought ESH had already removed Joda Time from everything. This should work. Easy to test by just running it in a script in /automation/jsr223/

'use strict';
var myLog = Java.type("org.slf4j.LoggerFactory").getLogger("org.eclipse.smarthome.model.script.Rules");
myLog.info("createTimer---------------------------");
var ScriptExecution = Java.type("org.eclipse.smarthome.model.script.actions.ScriptExecution");
//var LocalDateTime = Java.type("java.time.LocalDateTime");
var DateTime = Java.type("org.joda.time.DateTime");
var fnc = function(){
    myLog.info("Timer completed");
}
myLog.info("Creating timer...");
//ScriptExecution.createTimer(LocalDateTime.now().plusSeconds(5), fnc);
//2018-10-24 20:20:25.622 [ERROR] [org.eclipse.smarthome.automation.module.script.internal.ScriptEngineManagerImpl] - Error during evaluation of script 'file:/opt/openhab2/conf/automation/jsr223/test/testScript2.js': Cannot cast java.time.LocalDateTime to org.joda.time.base.AbstractInstant
ScriptExecution.createTimer(DateTime.now().plusSeconds(5), fnc);

OK, so here is what I’ve done since the last posting.

  1. Upgraded to build 1400
  2. Downloaded the JS library and put it into the automation folder and verified that the scripts get picked up
  3. Tried importing the library and using the logInfo function defined in the library
'use strict';

load('./../conf/automation/jsr223/jslib/JSRule.js');

logInfo("Using the library!");
  1. Just now I tried the code you just posted.
'use strict';

//load('./../conf/automation/jsr223/jslib/JSRule.js');

//logInfo("Using the library!");

var myLog = Java.type("org.slf4j.LoggerFactory").getLogger("org.eclipse.smarthome.model.script.Rules");
myLog.info("createTimer---------------------------");
var ScriptExecution = Java.type("org.eclipse.smarthome.model.script.actions.ScriptExecution");
//var LocalDateTime = Java.type("java.time.LocalDateTime");
var DateTime = Java.type("org.joda.time.DateTime");
var fnc = function(){
    myLog.info("Timer completed");
}
myLog.info("Creating timer...");
ScriptExecution.createTimer(DateTime.now().plusSeconds(5), fnc);

In all cases I get the ClassNotFoundException when I attempt to trigger the Rule from PaperUI and I get Failed to execute rule '8d37ea74-08b7-4c24-b0ab-a5c5ebf9 1877': Fail to execute action: 2 when I trigger the Rule by Item.

I’ll also note that one of the test scripts that the library comes with also fails with a complaint that DateTime doesn’t exit:

Error during evaluation of script 'file:/openhab/conf/au
tomation/jsr223/AccessibleFromAutomation.js': ReferenceError: "DateTime" is not defined in <eval> at line number 65

which makes some sense as the line that defines DateTime in helper.js is commented out

helper.js:	//var DateTime 				= Java.type("org.joda.time.DateTime");
helper.js:	var LocalDateTime 			= Java.type("java.time.LocalDateTime");
helper.js:	var OffsetDateTime 			= Java.type("java.time.OffsetDateTime");

I can’t say what this tells us, if anything.

When I uncomment that line the AccessibleFromAutomation.js works as expected.

Me either :smile:

But it seems like you may be complicating things. It might be worth going after correcting the error before adding more layers. And I’m not going to be much help with any of the JS extensions. Maybe @lewie could assist with them.

If you create a new rule using Paper UI with a JS Action, then trigger it with an Item, will it run without an exception? That is what I am seeing. You should hopefully then be able to trigger it through the Paper UI, as long as you don’t edit it. Well, you can edit it, but always trigger it through the Item first or you will get the exception.

BTW, I do not see a build 1400 in Cloudbees, but I’ve seen some people mention it in the forum. It should include the fix I put in for ItemStateTriggerHandler.

Looks like they are moving off of Cloudbees… Integration Builds [Jenkins].

I’m not adding layers. I’m trying different things out in isolation just trying to find something that works. For example I’m not trying to use the code above to create the Timer at the same time as loading the library. I’m testing them separately.

Success! So the bug you identified above totally kills the Rule from running ever. I was assuming that a restart would clear that bug out of the way.

I just had a Timer successfully run, first triggered by an Item and then triggered from PaperUI.

I went in and changed the Rule to use LocalDateTime and I received the ClassNotFoundException again, which I mostly expected to happen. I deleted the Rule and created another one this time using LocalDateTime. As you saw when you ran it I get the exception about wanting the Joda class.

I now edited the Rule again, just for grins to test out the JS library. This time I triggered it first from the Item and it too ran without error.

So it would seem the bug above has been the cause of ALL my problems. Grrr.

I run in Docker so all I know is the build number from whatever snapshot I pulled from Dockerhub today claims build 1400.

It would seem I’m over the hump and can start figuring things out in a more systemized manner.

Thanks!

Excellent! I’m excited that you are drilling in to the ERE. I’m thinking most of the openhab2-Jython repo documentation could be moved into the official docs. But I’m also thinking through how to best share scripts and modules. JSR223-JS and even JS Actions should also be considered. I’m leaning towards GH. IMO, the forum isn’t suitable, although you’ve been able to centralize a lot of the Rules DSL with the DPs. I’m curious what your thoughts are. Probably a good topic to bring to the forum too.

I’ve also been asking the forum admins about creating a category for the new rule engine, with subcategories for JSR223, etc., but haven’t gotten a response yet.

It seems that the builds are no longer there but now here:
https://ci.openhab.org/job/openHAB-Distribution/

I also missed that somehow at first…

I agree. There are places for them there.

One of Kai’s visions for the ERE was to enable the creation of a more reasonable distribution of libraries like this. I think the high level vision was to use the IoT Marketplace or something like that to give a place for devs to distribute and for users to be able to select and import them into their Rules environment. So imagine a DP library and all the user’s need to do is set up their Items and make the calls to library functions or predefined Rules.

Given that high level vision I think GH would be the most appropriate place to get started.

I only use the forum for Rules DSL stuff because people are going to need to do copy and paste and edit type operations to use them anyway so I may as well include the explanatory text and the code inline. I didn’t see much benefit at the time to point to an external GH repo for them. Also, the amount of code in these sorts of Rules DSL examples rarely extend beyond 40 lines of code.

As a moderator I don’t have the power to create a new topic. Have you just messaged the admins group or admins individually? Kai is usually pretty responsive to this sort of request. I wonder if the request just got lost in the shuffle.

1 Like

I spent hours running around this issue thinking that my setup has something wrong!
I am on the latest version and this issue still occurs! Do you have any update on it or why it is happening?

Just don’t execute rules through Paper UI, which is an incomplete implementation. If you need to trigger rules from a UI, add an Item to the triggers and then add the Item to a sitemap or HABpanel.

It worked with your workaround.
Any idea what is happening?

IIRC, the context is not being provided. This can only be fixed in OH 3.0. Paper UI has been removed, so this needs to be addressed in the new UI or OH core when this feature is reimplemented.

1 Like