Using OpenHAB 3.1, but new to the ECMA scripting in it.
I thought this would be easy, but it’s driving me nuts. I have a motion sensor, and a light, and all I want to do, is:
- If there is motion, the light comes ON for 5 minutes, then reverts to the manual state.
- If the switch is thrown, that becomes the manual state and any timer running from the motion is cancelled.
So, I started with something like:
var logger = Java.type("org.slf4j.LoggerFactory").getLogger("org.openhab.model.script.Rules.MotionLightNew");
var ScriptExecution = Java.type("org.openhab.core.model.script.actions.ScriptExecution");
var ZonedDateTime = Java.type("java.time.ZonedDateTime");
var previousState = itemRegistry.getItem("BackHallLightPower_Switch").getState()
function lambdaSchmamda()
{
logger.info("Motion Timer: Back to Previous: " + previousState);
events.sendCommand('BackHallLightPower_Switch', previousState);
}
// Turn the light on
events.sendCommand('BackHallLightPower_Switch', 'ON');
// And start a timer
ScriptExecution.createTimer(ZonedDateTime.now().plusMinutes(5), lambdaSchmamda);
logger.info("Motion: Back Hall Light ON: Previous: " + previousState);
This works reasonably for the motion part. But now I need a manual “override” and am having a heck of a time figuring out how to do it. I’ve tried all sorts of things, and nothing “works”. My latest attempt was to try to add a rule that only triggers when the switch is manually toggled, which sets an Item state to the “manual state” of the switch:
var logger = Java.type("org.slf4j.LoggerFactory").getLogger("org.openhab.model.script.Rules.MotionLightNew");
// Record manual state
var previousState = itemRegistry.getItem("BackHallLightPower_Switch").getState();
itemRegistry.getItem("BackHallManualState").setState( previousState );
logger.info("Manual: toggle from " + previousState);
And when the motion timer runs out, I changed it to revert to the state of the “BackHallManualState” item.
But I have the problem that I can’t “manual toggle” because rule gets kicked when the motion script turns the light on or off. I don’t think I would need to cancel the timer if it always set the state back to the “manual” setting but I can’t find a way to set the BackHallManualState ONLY when the switch is physically toggled. I’ve tried adding another item that indicates the incoming “manual” state change should be ignored because it’s coming from the other script. That didn’t work out at all.
It just seems to me that this MUST have been solved by someone, it’s got to be one of the most common things! but my Google foo has failed me.
Is there a place somewhere that would contain a library of common rules like this? Can someone share THEIR solution? Any help would be great!