[Solved] Binary Operations in Rules

This rule works as expected and produces the output “Trap 3”:

    var Number nID
    var int intValue
    nID = 12
    intValue = 0
    if (nID == 25) {
        if (intValue == 0) {
            logInfo("sensor.rules", "Trap 1")
        }
        else logInfo("sensor.rules", "Trap 2")
    }
    else logInfo("sensor.rules", "Trap 3")

Then the 2nd if-statement is changed to perform a binary operation.
The rule looks like this and gives the unexpected result “Trap 1”:

    var Number nID
    var int intValue
    nID = 12
    intValue = 0
    if (nID == 25) {
        if ((intValue | 0x20) == 0) {
            logInfo("sensor.rules", "Trap 1")
        }
        else logInfo("sensor.rules", "Trap 2")
    }
    else logInfo("sensor.rules", "Trap 3")

Because nID does not match the value given in the 1st if-statement it should not even check the 2nd one.
Besides that the 2nd if-statement which is a binary OR would give a false result anyway.
From what I’ve read about binary operations in Java that code should be OK (e.g. https://www.tutorialspoint.com/java/java_bitwise_operators_examples.htm).

So there are 3 questions:

  1. Why is the 2nd if-statement checked at all after the 1st one results in a false condition.
  2. Why does the rule evaluate the 2nd if-statement to true?
  3. If there’s anything wrong in that code how is it done right?

I suspect the single pipe is breaking everything. Did you intend || for OR? That would always return true though.

Unfortunately this is not Java, rules are written in a OH specific version of Xtend. Mostly very like Java. But distinctly quirky so far as handling Numbers bitwise goes.
Googling for OpenHAB bitwise throws up tidbits worth reading, example
https://groups.google.com/forum/#!topic/openhab/z4cYibhnoHc

OK, it’s not Java.
With that information and the link I could change my rule to this:

    var Number nID
    var int intValue
    nID = 12
    intValue = 0
    if (nID == 25) {
        if (intValue.bitwiseOr(0x20) == 0) {
            logInfo("sensor.rules", "Trap 1")
        }
        else logInfo("sensor.rules", "Trap 2")
    }
    else logInfo("sensor.rules", "Trap 3")

When playing with the variable values the statements now are evaluated like expected.
Thanks a lot!

1 Like