OH2 - Checking state after rule received command

I’ve noticed a difference in how some of my rules execute in OH2 opposed to OH1. I don’t know if it is just because the timing is different, or something has changed in the processing of OH2. Basically, I want to check the state of an item after a “received command” trigger on the same item. However, the state does not always match the command with OH2. Seems to be a timing issue since the behavior is inconsistent.

rule "test rule"
when
Item test_num received command
then
// First I change the value in karaf: smarthome:update test_num 50
// Next I send a command in karaf: smarthome:send test_num 100
// Sometimes I see value 50 instead of 100 for the following debug line.
logDebug(“test”, “{}”, test_num)
end

I have a rule that I don’t want to execute when postUpdate is called so I do not want the trigger “changed” or “recieved update”. I only want it to execute when a command has been sent. Hence my trigger being “received command”. Is this a bug in OH2 or am I using the rules wrong?

A command does NOT instantly change the state of an Item.
The basic design philisophy is that a binding acts on a command, sends to a device. The device would respond with its new status, and the binding now updates the Item.

Of course, not all devices actually provide feedback, those that do may not give it promptly, and not all Items are bound to devices anyway.
So for our convenience an autoupdate mechanism is provided in OH, which can be thought of as a dummy binding. It sees a command and processes it into an update on the Item.

The kicker is that that may happen before or after any ‘real’ bindings act on the command, and before or after any rules trigger on the command.

Sometimes it is actually simpler to turn off the autoupdate for an Item altogether, especially if you are looking to “check the state” of a real device.

I was aware of the autoupdate concept for an item and the fact that it could be turned off. I just figured when the command was received that the state would have been updated in the same thread. I guess this is not the case. So how would I have a trigger on receiving a command for a number item and know what that command was? Right now I have an ugly timer delay in my rule to work around the issue so that I can check the state.

rule "test rule"
 when
   Item test_num received command
 then
   logDebug("test", "Command was " + receivedCommand.toString)
end

receivedCommand is a documented magic word in Rules
http://docs.openhab.org/configuration/rules-dsl.html#implicit-variables-inside-the-execution-block

4 Likes

Outstanding! Exactly what I need. Thanks @rossko57!!!