Where have you seen rules like this? never, ever anywhere…
A rule i this:
rule "name" // keyword rule is start of rule named "name", where "name" has to be unique
when // keyword for the triggers part
// Triggers
then // keyword for the execute part
// Execute part
end // keyword for end of the rule
You must use every keyword exactly as written above (so once per rule)
when
is not another if
, and then
is not part of if
either.
A rule needs at least one trigger, this could be a change of a status, a received command or a received update. There are more triggers, like Time cron, Thing status, Channel events or system start. all of them can trigger a rule, alone or in combination, but each trigger will trigger, there is no such thing as an boolean and
for rule triggers, as it’s extremely unlikely, that two triggers will ever happen to happen at the very same moment.
So, a correct rule to automatically switch off an item which was switched on would be
rule "Relay time"
when
Item Switch1 received command ON
then
createTimer(now.plusSeconds(5)) [|sendCommand(Switch1 ,OFF)sendCommand(Switch2 ,ON)]
end
rule "relay"
when
Item Switch2 received command ON
then
createTimer(now.plusSeconds(5)) [|sendCommand(Switch2 ,OFF)]
end
But this code is not as nice as it can be. Presumpting that every time, the 1st relay is switched on, the 2nd relay should follow and the 2nd relay sould never switch alone, this rule would do better:
var Timer tRelay = null
rule "Relay auto off and follow"
when
Item Switch1 received command ON // whenever relay 1 is switched ON
then
if(tRelay !== null) return; // cancel rule, if existing timer
tRelay = createTimer(now.plusSeconds(5), [| // create timer
if(Switch1.state == ON) { // relay 1 on, so 1st execution
Switch1.sendCommand(OFF) // switch off relay 1
Switch2.sendCommand(ON) // switch on relay 2
tRelay.reschedule(now.plusSeconds(5)) // reschedule timer
} else { // relay 1 off, so 2nd execution
Switch2.sendCommand(OFF) // switch off relay 2
tRelay = null
}
])
end
Please be aware that nothing prevents you from switching both relays to ON. The timer might reset the 1st relay if doing that while relay 2 is ON, but only after timer expired!
As you can see, I used a slightly different notation.
- a command is ON or OFF (for switches), not “ON” or “OFF” (these are strings, openHAB will change them silently to switch commands)
- whenever possible, please use the method instead of the action. Item.sendCommand(command) is the method, sendCommand(Item, command) is the action. The difference is that the action needs two strings, where the method is often capable to handle different types of input.
- the lambda (part in brackets [] ) is a parameter of the createTimer(), it’s more clear to write it a part of parameter list, although your code is also correct.