Compare two number items and turn on a switch

Hi all,

First, this is my first post on the forums! I am having a lot of fun with openHAB, but I’m finding the rules system slightly confusing.

Basically I have two temperature sensors that are Number Items in openHAB and I have some switches set up to turn outlets on and off. I want to create a rule that compares the temperatures and turns on the switch if the condition is met.

For example I’m thinking something like this:

rule "Turn Fans on"
when
Item Bedroom_Temp > 65
then
Item Outlet_1 == ON

Any suggestions would be awesome.

Rules are triggered based on events, not states. So what you need to do is identify and event (temperature changing) which when it occurs the Rule should run. Then in the rule you write your logic to see what state everything is in and do the appropriate thing.

rule "Turn Fans on"
when
    Item Bedroom_Temp changed
then
    if((Bedroom_temp.state as DecimalType) > 65) {
        Outlet_1.sendCommand(ON)
    }
    else {
         Outlet_1.sendCommand(OFF)
    }
end

Note two important things. The “value” of an Item is stored in it’s state. There is a bunch of other aspects of Items available as well including past values if you have persistence set up. Secondly, to change the state of an Item you must call either sendCommand or postUpdate. The difference is sendCommand will treat the new state as a directive and cause the physical outlet to turn ON or OFF. postUpdate is a way to update the state of an Item internal to openHAB, usually so it corresponds with the state of the actual device which was learned is some other way. For example, if the outlets tells OH it is OFF, we don’t want OH turning around and telling the outlet to turn OFF.

3 Likes

This works great. I think I’m starting to understand more about how rules work. Thanks so much!!

Hi, is it possible to write sth like this:

rule "Turn Fans on"
when
    Item Bedroom_Temp changed
then
    if(50 < (Bedroom_temp.state as DecimalType) < 65) {
        Outlet_1.sendCommand(ON)
    }
    else {
         Outlet_1.sendCommand(OFF)
    }
end

I wnat to turn on a switch when an item is between two number like above temperature.
I read your post in other topic that you said:

Only “or” is allowed in the if part of a rule. Rules are event triggered and no two events will ever occur at the exact same time so it makes no sense to have an “and” in the when clause of a rule.

but I need an “and”
can I use above approach or this one:

rule "Turn Fans on"
when
    Item Bedroom_Temp changed
then
    if((Bedroom_temp.state as DecimalType) > 50 && (Bedroom_temp.state as DecimalType) < 65) {
        Outlet_1.sendCommand(ON)
    }
    else {
         Outlet_1.sendCommand(OFF)
    }
end

tnx

Your first example wouldn’t work because the language doesn’t support that syntax. The second example should work.

1 Like