Variables in Rules what is wrong with this?

At the top of the rule define the variable and initialize it to something:

var boolean isdark = false

In your rules is where you really set it. In your rules you do not need to redefine it so do not use “var” or “val”:

isdark = now.isBefore(daystart) || now.isAfter(dayend)

Two important things:
You must use “var” instead of “val”. A “val” is final meaning once you set it to somthing you can never change it.
You can define a variable globally and set it locally.

Assuming you want “isdark” to actually represent night (i.e. the time between sunset and sunrise with or without some buffer), you might be happier with a solution similar to the example I posted here. Otherwise you will be forced to keep every rule that needs to know isdark to reside in the same file, plus you lose all the other benefits I site above.

Whenever you see polling like this in a rule (i.e. your cron to run every minute) you should stop and consider whether there is a better way. I’ve yet to find a case where there wasn’t.

In this particular case the Items and Rules would look like the following:

Items:

Switch Sunset_Event   { astro="planet=sun, type=set, property=start" }
DateTime Sunset_Time  { astro="planet=sun, type=set, property=start" }
Switch Sunrise_Event  { astro="planet=sun, type=rise, property=start" }
DateTime Sunrise_Time { astro="planet=sun, type=rise, property=start" }
Switch Is_Dark

Rules:

// Rules to set and unset Is_Dark
rule "Start Dark"
when
    Item Sunrise_Event received update
then
    Is_Dark.sendCommand(OFF)
end

rule "End Dark"
when
    Item Sunset_Event received update
then
    Is_Dark.sendCommand(ON)
end

rule "turn on lights if dark and movement detected"
when
    Item ZONE12_GENERAL_STATUS received update OPEN
then
    if(office_ceiling.state == OFF && Is_Dark.state == ON) {
        sendCommand(office_ceiling, ON)
        office_group_counter= office_group_counter + 1
        logInfo("Alarm", "movement in office and is it dark = " + Is_Dark.state)
    }
end

NOTE: I just typed this in, there might be a typo. Also, this assumes that you have persistence set up and have restoreOnStartup strategy enabled and applied to your items, in particular Is_Dark.

NOTE 2: If you want to make sure Is_Dark is always accurate, there is one case where openHAB went down before the Sunrise_Event or Sunset_Event and came up after. In that case you can create a System Started triggered rule and check the Sunrise_Time and Sunset_Time to see if you are inside that time period and manually set Is_Dark as appropriate.

1 Like