Change state of items with a rule

This is my first self written Rule for openHAB 2 but unfortunately it does not work.
Item:

Switch presence "Anwesenheit" <parents_1_1> (gSensor)
Switch presence_anna "Anna" <woman_2> (gSensor)
Switch presence_jonathan "Jonathan" <man_2> (gSensor)

Rule:

rule "presence"
when
	Item presence_jonathan changed
	Item presence_anna changed
then
	 if((presence_jonathan.state==ON) || (presence_anna.state==ON)){
	 	 sendCommand(presence, ON)
	} else if ((presence_jonathan.state==OFF) && (presence_anna.state==OFF)){
	 	 createTimer(now.plusSeconds(60)) [| sendCommand(presence, OFF) ]
	}
end

Where is my mistake?

sendCommand would usually be used to send a command to a real device; a binding would take the command sent to the Item and pass it out to a device. If/when the device responds, the binding would then update the Item to reflect the physical state.

If you just want to change the state of an Item from a rule, use postUpdate (which directly changes the Item,no bindings or devices involved)

For various reasons, it is recommended to use the method form MyItem.postUpdate(xx) rather than the action form postUpdate(MyItem, xx)

1 Like

The most obvious problem I can see is a missing OR in the when-clause:

I completely agree with the previous poster on the use of the “method form” as opposed to the “action form”. I think, however, you should be just fine using presence.sendCommand(). If you prefer, you will probably be equally fine using presence.postUpdate().

Apart from this, I think your basic rule should work. To improve on your setup, you could cancel the timer (if running) before sending the ON command - in case one of you comes back in within the 60 second window.

1 Like

Thanks for the help! My solution:

var Timer timer
rule "presence"
when
	Item presence_jonathan changed or
	Item presence_anna changed
then
	if((presence_jonathan.state==ON) || (presence_anna.state==ON)){
		if(timer!=null) {
    		timer.cancel
    		timer = null
    	}
		presence.postUpdate(ON)
	} else if ((presence_jonathan.state==OFF) && (presence_anna.state==OFF)){
		timer = createTimer(now.plusSeconds(60)) [| presence.postUpdate(OFF) ]
	}
end