I need to implement a DateTime variable that records the previous time when a motion detector was activated. When OH is started this variable must be initialized to some value. I tried the following code at the top of the .rules file…
var DateTime Front_Bedroom_Motion_Detector_Last_Triggered = now
… but this fails with the following error message; => so how can I initialize such a DateTime var without a failure? (note: using OH 2.5 latest release)
2019-12-27 14:51:29.223 [WARN ] [me.internal.engine.RuleContextHelper] - Variable 'Front_Bedroom_Motion_Detector_Last_Triggered' on rule file '24g.rules' cannot be initialized with value 'now': The name 'now' cannot be resolved to an item or type; line 44, column 61, length 3
You can set it to null and have your rules deal with that, as meaning “not yet known”
I do not think you can perform evaluations in the “global” context of a rules file, only assign constants.
So I was surprised that var DateTime Front_Bedroom_Motion_Detector_Last_Triggered = DateTime.now
doesn’t throw an error.
Here’s the weird part though (which may not matter to you)
That doesn’t get evaluated at xxx.rules file load time. If you log it out some time after load, it gives that instant i.e. it gets evaluated at first use.
It’s a bit of a magic trick, but I can’t think of use for that.
What most people do is use an Item. Added bonus, use persistence and have the genuine last value survive system reboots.
Hmm @rossko57 thank you for the interesting insights. I was wondering also how to make some rules execute conditionally depending a Boolean var that has been initialized as false as follows…
var Boolean isReadyToRun = new Boolean(false)
// rule A
when
..
then
if (isReadyToRun) {}
end
// rule B
when
..
then
...
isReadyToRun = true
end
Hi @rossko57 many thanks for your inputs. I am running OH v2.5 openHabian on a Raspberry Pi machine, and I discovered, via your posts, that this build/version has a console configuration option “44” which allows to delay the loading of the .rules file by approximately 2 minutes. This prevents any var initialization errors, and gives time for the Things and Items to be loaded properly, before any rules are started. It works perfectly for me!