[SOLVED] Multiple 'when' statements, (AND/OR)

Yeah’ I’ve been making many rule tweaks tonight - trial and error troubleshooting other issues. That definitely explains the ‘frequent’ occurrences! Thanks for clearing that up!

Also, thanks for the second look in, I’ve made some changes, changing Twilight_Event to Twilight_Time

rule "Get time period for right now"
when
    System started
then
    val morning = now.withTimeAtStartOfDay.plusHours(5).millis // 5 AM
    val sunrise = new DateTime((Sunrise_Time.state as DateTimeType).calendar.timeInMillis)
    val twilight = new DateTime((Twilight_Time.state as DateTimeType).calendar.timeInMillis)
    val night = now.withTimeAtStartOfDay.plusHours(23).millis // 11 PM

    if(now.isAfter(morning) && now.isBefore(sunrise)) {
        Morning.sendCommand(ON)
        Day.sendCommand(OFF)
        Twilight.sendCommand(OFF)
        Night.sendCommand(OFF)
    }
    else if(now.isAfter(sunrise) && now.isBefore(twilight)) {
        Morning.sendCommand(OFF)
        Day.sendCommand(ON)
        Twilight.sendCommand(OFF)
        Night.sendCommand(OFF)
    }
    else if(now.isAfter(twilight) && now.isBefore(night)) {
        Morning.sendCommand(OFF)
        Day.sendCommand(OFF)
        Twilight.sendCommand(ON)
        Night.sendCommand(OFF)
    }
    else if(now.isAfter(night) && now.isBefore(morning)) {
        Morning.sendCommand(OFF)
        Day.sendCommand(OFF)
        Twilight.sendCommand(OFF)
        Night.sendCommand(ON)
    }
end

and I’ve also added the items to rrd4j (although I’m not familiar with persistence, so this could be totally wrong!!)

// persistence strategies have a name and a definition and are referred to in the "Items" section
Strategies {
	// for rrd charts, we need a cron strategy
	everyMinute : "0 * * * * ?"
}

Items {
	Sunrise_Time,Twilight_Time,Sunset_Time : strategy = everyMinute, restoreOnStartup
	
	// let's only store temperature values in rrd
	Temperature*,Weather_Chart* : strategy = everyMinute, restoreOnStartup
}

I suspect checking every minute is overkill, but??

Will revisit tomorrow…

For rrd4j every minute is a good choice. The default config for it behaves badly if you don’t.

Ok, no noticeable errors now, however, it still doesn’t trigger an event (morning, day, twilight, night) on startup, which means some of my rules do not work until I manually set the initial ‘state’ (on each reboot).

21:50:28.264 [INFO ] [penhab.io.rest.RESTApplication:144  ] - Started REST API at /rest
21:50:35.602 [DEBUG] [.r.internal.RuleModelActivator:42   ] - Registered 'rules' configuration parser
21:50:35.720 [DEBUG] [i.internal.GenericItemProvider:154  ] - Processing binding configs for items from model 'home.items'
21:50:36.034 [DEBUG] [m.r.internal.engine.RuleEngine:77   ] - Started rule engine
21:50:36.164 [DEBUG] [i.internal.GenericItemProvider:133  ] - Read items from model 'home.items'
21:50:41.052 [DEBUG] [.prowl.internal.ProwlActivator:34   ] - Prowl action has been started.
21:50:41.276 [DEBUG] [.astro.internal.AstroActivator:32   ] - Astro action has been started.
21:50:41.306 [DEBUG] [.o.internal.OpenWebIfActivator:33   ] - OpenWebIf action has been started.
21:50:41.358 [DEBUG] [.a.mail.internal.MailActivator:34   ] - Mail action has been started.
21:50:41.396 [DEBUG] [nhab.io.habmin.HABminActivator:33   ] - HABmin Interface has been started.
21:50:41.700 [WARN ] [cpr.DefaultAnnotationProcessor:178  ] - Unable to detect annotations. Application may fail to deploy.
21:50:42.266 [WARN ] [sphere.cpr.AtmosphereFramework:941  ] - No BroadcasterCache configured. Broadcasted message between client reconnection will be LOST. It is recommended to configure the org.atmosphere.cache.UUIDBroadcasterCache
21:50:42.268 [INFO ] [.o.io.habmin.HABminApplication:181  ] - Started HABmin REST API at /services/habmin
21:50:42.268 [DEBUG] [o.o.i.s.i.DiscoveryServiceImpl:66   ] - Registering new service _openhab-server._tcp.local. at port 8080
21:50:45.004 [DEBUG] [o.o.i.s.i.DiscoveryServiceImpl:66   ] - Registering new service _openhab-server-ssl._tcp.local. at port 8443
21:50:46.236 [INFO ] [c.internal.ModelRepositoryImpl:80   ] - Loading model 'home.rules'
21:50:47.028 [DEBUG] [.r.i.engine.RuleTriggerManager:438  ] - Scheduled rule Turn Bathroom Speakers on at 6pm with cron expression 0 0 18 * * ?
21:50:47.048 [DEBUG] [.r.i.engine.RuleTriggerManager:438  ] - Scheduled rule Turn Kitchen Speakers on at 6pm with cron expression 0 0 13 * * ?
21:50:47.056 [DEBUG] [.r.i.engine.RuleTriggerManager:438  ] - Scheduled rule Turn Bedroom TV Off at Half past Midnight on a School night with cron expression 0 30 0 ? * MON,TUE,WED,THU,SUN *
21:50:47.100 [DEBUG] [.r.i.engine.RuleTriggerManager:438  ] - Scheduled rule Turn Bedroom TV Off at Half past Midnight at the weekend with cron expression 0 0 1 ? * FRI,SAT
21:50:47.102 [DEBUG] [.r.i.engine.RuleTriggerManager:438  ] - Scheduled rule Turn Bedroom TV down at 11pm with cron expression 0 0 23 * * ?
21:50:47.104 [DEBUG] [.r.i.engine.RuleTriggerManager:438  ] - Scheduled rule Turn Bedroom TV down at Midnight with cron expression 0 0 0 * * ?
21:50:47.104 [DEBUG] [.r.i.engine.RuleTriggerManager:438  ] - Scheduled rule Update max and min temperatures with cron expression 0 0 0 * * ?
21:50:47.106 [DEBUG] [.r.i.engine.RuleTriggerManager:438  ] - Scheduled rule Turn things off at 10:30pm daily with cron expression 0 30 22 * * ?
21:50:47.108 [DEBUG] [.r.i.engine.RuleTriggerManager:438  ] - Scheduled rule Turn everything off at Midnight with cron expression 0 0 0 * * ?
21:50:47.108 [DEBUG] [.r.i.engine.RuleTriggerManager:438  ] - Scheduled rule Morning Started with cron expression 0 0 5 * * ? *
21:50:47.110 [DEBUG] [.r.i.engine.RuleTriggerManager:438  ] - Scheduled rule Night Started with cron expression 0 0 23 * * ? *
21:50:47.124 [DEBUG] [m.r.internal.engine.RuleEngine:264  ] - Executing startup rule 'Update max and min temperatures'
21:50:47.346 [DEBUG] [riptExtensionClassNameProvider:63   ] - Script actions have changed: AstroActionService, PingActionService, HTTPActionService, MailActionService, TransformationActionService, AudioActionService, ExecActionService, OpenWebIfActionService, ProwlActionService, 
21:50:47.636 [WARN ] [.o.c.p.e.PersistenceExtensions:711  ] - There is no queryable persistence service registered with the name 'rrd4j'
21:50:47.642 [DEBUG] [.a.xbmc.internal.XBMCActivator:34   ] - XBMC action has been started.
21:50:47.786 [ERROR] [m.r.internal.engine.RuleEngine:278  ] - Error during the execution of startup rule 'Update max and min temperatures': cannot invoke method public abstract org.openhab.core.types.State org.openhab.core.persistence.HistoricItem.getState() on null
21:50:47.808 [DEBUG] [m.r.internal.engine.RuleEngine:264  ] - Executing startup rule 'Get time period for right now'
21:50:47.822 [DEBUG] [.o.b.ntp.internal.NtpActivator:31   ] - NTP binding has been started.
21:50:47.860 [DEBUG] [riptExtensionClassNameProvider:63   ] - Script actions have changed: AstroActionService, PingActionService, XBMCActionService, HTTPActionService, MailActionService, TransformationActionService, AudioActionService, ExecActionService, OpenWebIfActionService, ProwlActionService, 
21:50:48.532 [ERROR] [m.r.internal.engine.RuleEngine:278  ] - Error during the execution of startup rule 'Get time period for right now': Cannot cast org.openhab.core.types.UnDefType to org.openhab.core.library.types.DateTimeType
21:50:48.544 [DEBUG] [i.internal.GenericItemProvider:341  ] - Start processing binding configuration of Item 'Date (Type=DateTimeItem, State=Uninitialized)' with 'NtpGenericBindingProvider' reader.
21:50:48.556 [DEBUG] [o.b.n.i.NetworkHealthActivator:31   ] - NetworkHealth binding has been started.
21:50:48.736 [DEBUG] [i.internal.GenericItemProvider:341  ] - Start processing binding configuration of Item 'SamsungTV (Type=SwitchItem, State=Uninitialized)' with 'NetworkHealthGenericBindingProvider' reader.
21:50:48.740 [INFO ] [.service.AbstractActiveService:169  ] - NTP Refresh Service has been started
21:50:48.818 [INFO ] [.service.AbstractActiveService:169  ] - NetworkHealth Refresh Service has been started
21:50:48.830 [DEBUG] [.a.internal.bus.AstroActivator:32   ] - Astro binding has been started.
21:50:48.860 [DEBUG] [i.internal.GenericItemProvider:341  ] - Start processing binding configuration of Item 'Sunrise_Event (Type=SwitchItem, State=Uninitialized)' with 'AstroGenericBindingProvider' reader.
21:50:48.948 [DEBUG] [.b.AstroGenericBindingProvider:60   ] - Adding item Sunrise_Event with AstroBindingConfig[planet=sun,type=rise,property=start]
21:50:48.982 [DEBUG] [i.internal.GenericItemProvider:341  ] - Start processing binding configuration of Item 'Sunrise_Time (Type=DateTimeItem, State=Uninitialized)' with 'AstroGenericBindingProvider' reader.
21:50:49.000 [DEBUG] [.b.AstroGenericBindingProvider:60   ] - Adding item Sunrise_Time with AstroBindingConfig[planet=sun,type=rise,property=start]
21:50:49.000 [DEBUG] [i.internal.GenericItemProvider:341  ] - Start processing binding configuration of Item 'Twilight_Event (Type=SwitchItem, State=Uninitialized)' with 'AstroGenericBindingProvider' reader.
21:50:49.002 [DEBUG] [.b.AstroGenericBindingProvider:60   ] - Adding item Twilight_Event with AstroBindingConfig[planet=sun,type=set,property=start,offset=-60]
21:50:49.022 [DEBUG] [i.internal.GenericItemProvider:341  ] - Start processing binding configuration of Item 'Twilight_Time (Type=DateTimeItem, State=Uninitialized)' with 'AstroGenericBindingProvider' reader.
21:50:49.022 [DEBUG] [.b.AstroGenericBindingProvider:60   ] - Adding item Twilight_Time with AstroBindingConfig[planet=sun,type=set,property=start]
21:50:49.192 [DEBUG] [i.internal.GenericItemProvider:341  ] - Start processing binding configuration of Item 'Sunset_Event (Type=SwitchItem, State=Uninitialized)' with 'AstroGenericBindingProvider' reader.
21:50:49.193 [DEBUG] [.b.AstroGenericBindingProvider:60   ] - Adding item Sunset_Event with AstroBindingConfig[planet=sun,type=set,property=start]
21:50:49.193 [DEBUG] [i.internal.GenericItemProvider:341  ] - Start processing binding configuration of Item 'Sunset_Time (Type=DateTimeItem, State=Uninitialized)' with 'AstroGenericBindingProvider' reader.
21:50:49.194 [DEBUG] [.b.AstroGenericBindingProvider:60   ] - Adding item Sunset_Time with AstroBindingConfig[planet=sun,type=set,property=start]
21:50:49.194 [DEBUG] [i.internal.GenericItemProvider:341  ] - Start processing binding configuration of Item 'Sunset_Event_Offset (Type=SwitchItem, State=Uninitialized)' with 'AstroGenericBindingProvider' reader.
21:50:49.195 [DEBUG] [.b.AstroGenericBindingProvider:60   ] - Adding item Sunset_Event_Offset with AstroBindingConfig[planet=sun,type=set,property=start,offset=-30]
21:50:49.202 [INFO ] [.b.a.internal.bus.AstroBinding:70   ] - AstroConfig[latitude=53.3205,longitude=-1.3116,interval=43200,systemTimezone=Europe/London (GMT +0000),daylightSavings=false]
21:50:49.284 [DEBUG] [.onkyo.internal.OnkyoActivator:34   ] - Onkyo binding has been started.
21:50:49.322 [DEBUG] [i.internal.GenericItemProvider:341  ] - Start processing binding configuration of Item 'onkyoPower (Type=SwitchItem, State=Uninitialized)' with 'OnkyoGenericBindingProvider' reader.
21:50:49.838 [DEBUG] [o.o.b.n.i.NetworkHealthBinding:85   ] - established connection [host '192.168.1.240' port '0' timeout '5000']
21:50:49.974 [DEBUG] [.b.onkyo.internal.OnkyoBinding:71   ] - Activate
21:50:49.978 [DEBUG] [.b.onkyo.internal.OnkyoBinding:227  ] - Configuration updated, config true
21:50:49.992 [DEBUG] [.b.onkyo.internal.OnkyoBinding:429  ] - Initialize item onkyoVideoWide
21:50:50.036 [DEBUG] [.b.xbmc.internal.XbmcActivator:33   ] - XBMC binding has been started
21:50:50.318 [DEBUG] [.b.onkyo.internal.OnkyoBinding:429  ] - Initialize item onkyoNETArtist
21:50:50.446 [DEBUG] [.b.onkyo.internal.OnkyoBinding:334  ] - Received status update 'VWM00' from device 192.168.1.230
21:50:50.474 [DEBUG] [b.x.internal.XbmcActiveBinding:54   ] - XBMC Refresh Service activate()
21:50:50.650 [INFO ] [.service.AbstractActiveService:169  ] - XBMC Refresh Service has been started
21:50:50.658 [DEBUG] [.b.onkyo.internal.OnkyoBinding:429  ] - Initialize item onkyoNETTime
21:50:50.658 [DEBUG] [.b.onkyo.internal.OnkyoBinding:429  ] - Initialize item onkyoAudio
21:50:50.660 [DEBUG] [.b.onkyo.internal.OnkyoBinding:429  ] - Initialize item onkyoNETAlbum
21:50:50.700 [DEBUG] [i.internal.GenericItemProvider:341  ] - Start processing binding configuration of Item 'LgTvPower (Type=SwitchItem, State=Uninitialized)' with 'LgtvGenericBindingProvider' reader.
21:50:50.700 [DEBUG] [.b.onkyo.internal.OnkyoBinding:429  ] - Initialize item onkyoListenMode
21:50:50.704 [DEBUG] [i.internal.GenericItemProvider:341  ] - Start processing binding configuration of Item 'LgTvMute (Type=SwitchItem, State=Uninitialized)' with 'LgtvGenericBindingProvider' reader.
21:50:50.712 [DEBUG] [i.internal.GenericItemProvider:341  ] - Start processing binding configuration of Item 'LgTvVolume (Type=NumberItem, State=Uninitialized)' with 'LgtvGenericBindingProvider' reader.
21:50:50.712 [DEBUG] [.b.onkyo.internal.OnkyoBinding:429  ] - Initialize item onkyoPower
21:50:50.714 [DEBUG] [i.internal.GenericItemProvider:341  ] - Start processing binding configuration of Item 'LgTvConnStatus (Type=SwitchItem, State=Uninitialized)' with 'LgtvGenericBindingProvider' reader.
21:50:50.754 [DEBUG] [.m.internal.MqttitudeActivator:33   ] - Mqttitude binding has been started.
21:50:50.756 [DEBUG] [.b.onkyo.internal.OnkyoBinding:429  ] - Initialize item onkyoMute
21:50:50.804 [DEBUG] [.b.onkyo.internal.OnkyoBinding:429  ] - Initialize item onkyoVolume
21:50:50.812 [DEBUG] [.b.m.internal.MqttitudeBinding:84   ] - Activating Mqttitude binding
21:50:50.832 [DEBUG] [.b.onkyo.internal.OnkyoBinding:429  ] - Initialize item onkyoVideo
21:50:50.848 [DEBUG] [.b.onkyo.internal.OnkyoBinding:334  ] - Received status update 'NTM--:--:--/' from device 192.168.1.230
21:50:50.848 [DEBUG] [.b.onkyo.internal.OnkyoBinding:429  ] - Initialize item onkyoVideoPicture
21:50:50.852 [DEBUG] [.s.internal.SamsungTvActivator:34   ] - Samsung TV binding has been started.
21:50:50.882 [DEBUG] [.b.onkyo.internal.OnkyoBinding:429  ] - Initialize item onkyoNETTrack
21:50:50.952 [DEBUG] [i.internal.GenericItemProvider:341  ] - Start processing binding configuration of Item 'SamsungDirectChannel (Type=NumberItem, State=Uninitialized)' with 'SamsungTvGenericBindingProvider' reader.
21:50:50.974 [DEBUG] [.b.onkyo.internal.OnkyoBinding:429  ] - Initialize item onkyoAudysseyDynVol
21:50:50.984 [DEBUG] [i.internal.GenericItemProvider:341  ] - Start processing binding configuration of Item 'SamsungChannel (Type=DimmerItem, State=Uninitialized)' with 'SamsungTvGenericBindingProvider' reader.
21:50:50.990 [DEBUG] [i.internal.GenericItemProvider:341  ] - Start processing binding configuration of Item 'SamsungMute (Type=SwitchItem, State=Uninitialized)' with 'SamsungTvGenericBindingProvider' reader.
21:50:50.992 [DEBUG] [i.internal.GenericItemProvider:341  ] - Start processing binding configuration of Item 'SamsungVolume (Type=RollershutterItem, State=Uninitialized)' with 'SamsungTvGenericBindingProvider' reader.
21:50:51.004 [DEBUG] [.b.onkyo.internal.OnkyoBinding:334  ] - Received status update 'IFAHDMI 5,PCM,48 kHz,2.0 ch  ,All Ch Stereo,5.1.0 ch ,' from device 192.168.1.230
21:50:51.024 [DEBUG] [i.internal.GenericItemProvider:341  ] - Start processing binding configuration of Item 'SamsungPwr (Type=SwitchItem, State=Uninitialized)' with 'SamsungTvGenericBindingProvider' reader.
21:50:51.060 [DEBUG] [i.internal.GenericItemProvider:341  ] - Start processing binding configuration of Item 'SamsungPwrOn (Type=SwitchItem, State=Uninitialized)' with 'SamsungTvGenericBindingProvider' reader.
21:50:51.078 [DEBUG] [i.internal.GenericItemProvider:341  ] - Start processing binding configuration of Item 'SamsungPwrOff (Type=SwitchItem, State=Uninitialized)' with 'SamsungTvGenericBindingProvider' reader.
21:50:51.078 [DEBUG] [.b.onkyo.internal.OnkyoBinding:429  ] - Initialize item onkyoAudysseyDynEQ
21:50:51.302 [DEBUG] [.b.onkyo.internal.OnkyoBinding:334  ] - Received status update 'AMT00' from device 192.168.1.230
21:50:51.302 [DEBUG] [.b.onkyo.internal.OnkyoBinding:334  ] - Received status update 'IFVHDMI 5,1920 x 1080p  50 Hz,RGB,24bit,MAIN,1920 x 1080p  50 Hz,RGB,24bit,Bypass,' from device 192.168.1.230
21:50:51.304 [DEBUG] [.b.onkyo.internal.OnkyoBinding:334  ] - Received status update 'ADV00' from device 192.168.1.230
21:50:51.346 [DEBUG] [.b.onkyo.internal.OnkyoBinding:334  ] - Received status update 'LMD0C' from device 192.168.1.230
21:50:51.354 [DEBUG] [i.internal.GenericItemProvider:341  ] - Start processing binding configuration of Item 'NestHome_name (Type=StringItem, State=Uninitialized)' with 'NestGenericBindingProvider' reader.
21:50:51.612 [DEBUG] [.b.onkyo.internal.OnkyoBinding:429  ] - Initialize item onkyoDisplayMode
21:50:51.688 [DEBUG] [.b.onkyo.internal.OnkyoBinding:429  ] - Initialize item onkyoSleep
21:50:51.788 [DEBUG] [.b.onkyo.internal.OnkyoBinding:334  ] - Received status update 'MVL18' from device 192.168.1.230
21:50:51.790 [DEBUG] [i.internal.GenericItemProvider:341  ] - Start processing binding configuration of Item 'NestHome_country_code (Type=StringItem, State=Uninitialized)' with 'NestGenericBindingProvider' reader.
21:50:52.028 [DEBUG] [i.internal.GenericItemProvider:341  ] - Start processing binding configuration of Item 'NestHome_postal_code (Type=StringItem, State=Uninitialized)' with 'NestGenericBindingProvider' reader.
21:50:52.030 [DEBUG] [.b.onkyo.internal.OnkyoBinding:334  ] - Received status update 'NTR----/----' from device 192.168.1.230
21:50:52.030 [DEBUG] [.b.onkyo.internal.OnkyoBinding:429  ] - Initialize item onkyoNETTitle
21:50:52.046 [DEBUG] [.b.onkyo.internal.OnkyoBinding:334  ] - Received status update 'PWR01' from device 192.168.1.230
21:50:52.192 [DEBUG] [.b.onkyo.internal.OnkyoBinding:334  ] - Received status update 'VPM08' from device 192.168.1.230
21:50:52.204 [DEBUG] [i.internal.GenericItemProvider:341  ] - Start processing binding configuration of Item 'NestHome_time_zone (Type=StringItem, State=Uninitialized)' with 'NestGenericBindingProvider' reader.
21:50:52.206 [DEBUG] [i.internal.GenericItemProvider:341  ] - Start processing binding configuration of Item 'NestHome_away (Type=StringItem, State=Uninitialized)' with 'NestGenericBindingProvider' reader.
21:50:52.210 [DEBUG] [.b.onkyo.internal.OnkyoBinding:334  ] - Received status update 'ADQ01' from device 192.168.1.230
21:50:52.220 [DEBUG] [.b.onkyo.internal.OnkyoBinding:429  ] - Initialize item onkyoSource
21:50:52.220 [DEBUG] [.b.onkyo.internal.OnkyoBinding:429  ] - Initialize item onkyoNETPlayStatus
21:50:52.224 [DEBUG] [.b.onkyo.internal.OnkyoBinding:334  ] - Received status update 'DIF00' from device 192.168.1.230
21:50:52.282 [DEBUG] [.b.mqtt.internal.MqttActivator:34   ] - MQTT binding has been started.
21:50:52.312 [DEBUG] [.b.onkyo.internal.OnkyoBinding:429  ] - Initialize item onkyoDimmerLevel
21:50:52.312 [DEBUG] [.b.onkyo.internal.OnkyoBinding:334  ] - Received status update 'SLP00' from device 192.168.1.230
21:50:52.314 [INFO ] [.b.a.internal.job.JobScheduler:150  ] - Scheduled a daily job at midnight for astro calculation
21:50:52.316 [DEBUG] [.b.onkyo.internal.OnkyoBinding:429  ] - Initialize item onkyoNETService
21:50:52.346 [DEBUG] [m.internal.MqttEventBusBinding:61   ] - MQTT: Activating event bus binding.
21:50:52.376 [DEBUG] [.b.onkyo.internal.OnkyoBinding:334  ] - Received status update 'SLI05' from device 192.168.1.230
21:50:52.384 [DEBUG] [xecPersistenceServiceActivator:33   ] - Exec persistence bundle has been started.
21:50:52.394 [DEBUG] [a.internal.job.AbstractBaseJob:40   ] - Starting Astro DailyJob
21:50:52.402 [DEBUG] [b.x.internal.XbmcActiveBinding:388  ] - XBMC Refresh Service updated()
21:50:52.450 [DEBUG] [.b.a.internal.job.JobScheduler:207  ] - Scheduled job with name Season at 2016-03-20 04:31:00
21:50:52.454 [DEBUG] [.b.astro.internal.job.DailyJob:50   ] - Sun[sunrise=Range[start=Wed Jan 06 08:20:00 GMT 2016,end=Wed Jan 06 08:25:00 GMT 2016],noon=Range[start=Wed Jan 06 12:12:00 GMT 2016,end=Wed Jan 06 12:13:00 GMT 2016],sunset=Range[start=Wed Jan 06 15:59:00 GMT 2016,end=Wed Jan 06 16:03:00 GMT 2016],night=Range[start=Wed Jan 06 18:12:00 GMT 2016,end=Thu Jan 07 06:11:00 GMT 2016],morningNight=Range[start=Wed Jan 06 00:00:00 GMT 2016,end=Wed Jan 06 06:11:00 GMT 2016],astroDawn=Range[start=Wed Jan 06 06:11:00 GMT 2016,end=Wed Jan 06 06:54:00 GMT 2016],nauticDawn=Range[start=Wed Jan 06 06:54:00 GMT 2016,end=Wed Jan 06 07:38:00 GMT 2016],civilDawn=Range[start=Wed Jan 06 07:38:00 GMT 2016,end=Wed Jan 06 08:20:00 GMT 2016],civilDusk=Range[start=Wed Jan 06 16:03:00 GMT 2016,end=Wed Jan 06 16:45:00 GMT 2016],nauticDusk=Range[start=Wed Jan 06 16:45:00 GMT 2016,end=Wed Jan 06 17:30:00 GMT 2016],astroDusk=Range[start=Wed Jan 06 17:30:00 GMT 2016,end=Wed Jan 06 18:12:00 GMT 2016],daylight=Range[start=Wed Jan 06 08:25:00 GMT 2016,end=Wed Jan 06 15:59:00 GMT 2016],eveningNight=Range[start=Wed Jan 06 18:12:00 GMT 2016,end=Thu Jan 07 00:00:00 GMT 2016],eclipse=SunEclipse[total=Wed Mar 09 01:58:00 GMT 2016,partial=Thu Feb 15 20:53:00 GMT 2018,ring=Thu Sep 01 10:09:00 BST 2016]]
21:50:52.466 [DEBUG] [.p.internal.PersistenceManager:147  ] - Initializing exec persistence service.
21:50:52.474 [DEBUG] [.p.internal.PersistenceManager:441  ] - Scheduled strategy exec.everyMinute with cron expression 0 * * * * ?
21:50:52.490 [DEBUG] [.b.http.internal.HttpActivator:34   ] - HTTP binding has been started.
21:50:52.528 [DEBUG] [i.internal.GenericItemProvider:341  ] - Start processing binding configuration of Item 'Weather_Temperature (Type=NumberItem, State=Uninitialized)' with 'HttpGenericBindingProvider' reader.
21:50:52.572 [DEBUG] [.b.onkyo.internal.OnkyoBinding:334  ] - Received status update 'NSTS--' from device 192.168.1.230
21:50:52.686 [DEBUG] [i.internal.GenericItemProvider:341  ] - Start processing binding configuration of Item 'Weather_OutdoorTemperature (Type=NumberItem, State=Uninitialized)' with 'HttpGenericBindingProvider' reader.
21:50:52.688 [DEBUG] [i.internal.GenericItemProvider:341  ] - Start processing binding configuration of Item 'Weather_Humidity (Type=NumberItem, State=Uninitialized)' with 'HttpGenericBindingProvider' reader.
21:50:52.692 [INFO ] [.service.AbstractActiveService:169  ] - HTTP Refresh Service has been started
21:50:52.694 [DEBUG] [.o.b.http.internal.HttpBinding:163  ] - item 'Weather_Humidity' is about to be refreshed now
21:50:52.698 [DEBUG] [b.n.i.NetworkUpsToolsActivator:35   ] - NetworkUpsTools binding has been started.
21:50:52.912 [DEBUG] [.b.a.internal.job.JobScheduler:212  ] - Skipping job with name Twilight_Event for today, starttime is in the past
21:50:52.966 [DEBUG] [.b.onkyo.internal.OnkyoBinding:334  ] - Received status update 'DIM02' from device 192.168.1.230
21:50:52.984 [DEBUG] [o.o.b.c.i.ConfigAdminActivator:31   ] - ConfigAdmin binding has been started.
21:50:53.036 [DEBUG] [.b.a.internal.job.JobScheduler:212  ] - Skipping job with name Sunrise_Event for today, starttime is in the past
21:50:53.038 [DEBUG] [.b.a.internal.job.JobScheduler:212  ] - Skipping job with name Sunset_Event for today, starttime is in the past
21:50:53.050 [DEBUG] [.b.a.internal.job.JobScheduler:212  ] - Skipping job with name Sunset_Event_Offset for today, starttime is in the past
21:50:53.062 [DEBUG] [.b.astro.internal.job.DailyJob:57   ] - Moon[rise=Wed Jan 06 04:22:00 GMT 2016,set=Wed Jan 06 13:40:00 GMT 2016,phase=MoonPhase[firstQuarter=Sat Jan 16 23:27:00 GMT 2016,full=Sun Jan 24 01:47:00 GMT 2016,thirdQuarter=Mon Feb 01 03:29:00 GMT 2016,new=Sun Jan 10 01:32:00 GMT 2016,age=26,illumination=10.736042153211544,name=WANING_CRESCENT],apogee=MoonDistance[date=Sat Jan 30 09:11:00 GMT 2016,kilometer=404553.0740065285,miles=251377.62582270082],perigee=MoonDistance[date=Fri Jan 15 02:09:00 GMT 2016,kilometer=369621.13739149057,miles=229671.92672934628],distance=MoonDistance[date=Wed Jan 06 21:50:53 GMT 2016,kilometer=393124.64922948217,miles=244276.33189630523],eclipse=Eclipse[total=Wed Jan 31 13:31:00 GMT 2018,partial=Mon Aug 07 19:22:00 BST 2017],position=Position[azimuth=9.042605553517133,elevation=-53.69822472032319],zodiac=org.openhab.binding.astro.internal.model.Zodiac@d51eda8]
21:50:53.532 [DEBUG] [.o.b.http.internal.HttpBinding:197  ] - transformed response is '93'
21:50:53.534 [DEBUG] [.i.LoggingPersistenceActivator:31   ] - Logging persistence bundle has been started.
21:50:53.534 [DEBUG] [.o.b.http.internal.HttpBinding:163  ] - item 'Weather_Temperature' is about to be refreshed now
21:50:54.010 [WARN ] [inding.ntp.internal.NtpBinding:122  ] - couldn't establish network connection [host 'uk.pool.ntp.org'] -> returning current sytem time instead
21:50:54.113 [DEBUG] [.p.internal.PersistenceManager:147  ] - Initializing logging persistence service.
21:50:54.283 [DEBUG] [inding.ntp.internal.NtpBinding:83   ] - Got time from uk.pool.ntp.org: Wednesday, 6 January 2016 21:50:54 o'clock GMT
21:50:54.417 [DEBUG] [.p.db4o.internal.Db4oActivator:24   ] - db4o persistence bundle has been started.
21:50:54.445 [DEBUG] [.i.s.XsltTransformationService:89   ] - transformation resulted in '7'
21:50:54.471 [DEBUG] [.o.b.http.internal.HttpBinding:197  ] - transformed response is '7'
21:50:54.473 [DEBUG] [.o.b.http.internal.HttpBinding:163  ] - item 'Weather_OutdoorTemperature' is about to be refreshed now
21:50:54.479 [DEBUG] [m.r.internal.engine.RuleEngine:305  ] - Executing rule 'Update max and min temperatures'
21:50:54.599 [DEBUG] [.o.b.hue.internal.HueActivator:30   ] - Hue binding has been started.
21:50:54.621 [WARN ] [.o.c.p.e.PersistenceExtensions:711  ] - There is no queryable persistence service registered with the name 'rrd4j'
21:50:54.809 [DEBUG] [i.internal.GenericItemProvider:341  ] - Start processing binding configuration of Item 'Hue_LivingRoom_LampColor (Type=ColorItem, State=Uninitialized)' with 'HueGenericBindingProvider' reader.
21:50:54.815 [WARN ] [.o.c.p.e.PersistenceExtensions:711  ] - There is no queryable persistence service registered with the name 'rrd4j'
21:50:54.949 [DEBUG] [.i.s.XsltTransformationService:89   ] - transformation resulted in '7'
21:50:55.039 [DEBUG] [i.internal.GenericItemProvider:341  ] - Start processing binding configuration of Item 'Hue_LivingRoom_LampDim (Type=DimmerItem, State=Uninitialized)' with 'HueGenericBindingProvider' reader.
21:50:55.039 [DEBUG] [i.internal.GenericItemProvider:341  ] - Start processing binding configuration of Item 'Hue_LivingRoom_LampCT_Dim (Type=DimmerItem, State=Uninitialized)' with 'HueGenericBindingProvider' reader.
21:50:55.085 [WARN ] [.o.c.p.e.PersistenceExtensions:131  ] - There is no queryable persistence service registered with the name 'rrd4j'
21:50:55.111 [DEBUG] [.o.b.http.internal.HttpBinding:197  ] - transformed response is '7'
21:50:55.145 [INFO ] [g.openhab.model.script.Weather:53   ] - Temperature evolved of null degrees.
21:50:55.309 [DEBUG] [.rrd4j.internal.RRD4jActivator:31   ] - RRD4j persistence bundle has been started.
21:50:55.321 [WARN ] [.p.rrd4j.internal.RRD4jService:389  ] - Unknown property name : org.openhab.persistence.rrd4j
21:50:55.321 [DEBUG] [.p.rrd4j.internal.RRD4jService:358  ] - config 'objectClass' should have the format 'name.configkey'
21:50:55.321 [INFO ] [.p.rrd4j.internal.RRD4jService:401  ] - Removing invalid defintion component = null heartbeat = 0 min/max = 0.0/0.0 step = 0 0 archives(s) = [] 0 items(s) = []
21:50:55.321 [DEBUG] [.p.rrd4j.internal.RRD4jService:399  ] - Created default_other = GAUGE heartbeat = 3600 min/max = NaN/NaN step = 1 6 archives(s) = [ MAX xff = 0.999 steps = 1 rows = 3600 MAX xff = 0.999 steps = 10 rows = 1440 MAX xff = 0.999 steps = 60 rows = 1440 MAX xff = 0.999 steps = 900 rows = 2880 MAX xff = 0.999 steps = 21600 rows = 1460 MAX xff = 0.999 steps = 86400 rows = 3650] 0 items(s) = []
21:50:55.321 [DEBUG] [.p.rrd4j.internal.RRD4jService:399  ] - Created default_numeric = GAUGE heartbeat = 60 min/max = NaN/NaN step = 60 6 archives(s) = [ AVERAGE xff = 0.5 steps = 1 rows = 480 AVERAGE xff = 0.5 steps = 4 rows = 360 AVERAGE xff = 0.5 steps = 14 rows = 644 AVERAGE xff = 0.5 steps = 60 rows = 720 AVERAGE xff = 0.5 steps = 720 rows = 730 AVERAGE xff = 0.5 steps = 10080 rows = 520] 0 items(s) = []
21:50:55.323 [DEBUG] [.p.internal.PersistenceManager:147  ] - Initializing rrd4j persistence service.
21:50:55.327 [DEBUG] [.p.internal.PersistenceManager:441  ] - Scheduled strategy rrd4j.everyMinute with cron expression 0 * * * * ?
21:50:55.527 [DEBUG] [p.r.i.charts.RRD4jChartServlet:118  ] - Starting up rrd chart servlet at /rrdchart.png
21:50:55.559 [DEBUG] [.b.exec.internal.ExecActivator:34   ] - Exec binding has been started.
21:50:55.981 [DEBUG] [.b.plex.internal.PlexActivator:33   ] - Plex binding has been started.
21:50:55.983 [INFO ] [.service.AbstractActiveService:169  ] - Exec Refresh Service has been started
21:51:13.469 [INFO ] [.service.AbstractActiveService:169  ] - Nest Refresh Service has been started
21:51:13.481 [INFO ] [.service.AbstractActiveService:169  ] - ZWave Refresh Service has been started
21:51:14.893 [INFO ] [.h.internal.hardware.HueBridge:68   ] - Hue bridge not paired.
21:51:15.033 [DEBUG] [.o.b.plex.internal.PlexBinding:159  ] - Plex binding updated
21:51:38.496 [DEBUG] [m.r.internal.engine.RuleEngine:305  ] - Executing rule 'Enable Living Room Main Light on Motion (cat feed)'
21:51:38.498 [DEBUG] [m.r.internal.engine.RuleEngine:305  ] - Executing rule 'Enable Downstairs Hallway Light on Motion'
21:51:50.091 [DEBUG] [.b.onkyo.internal.OnkyoBinding:334  ] - Received status update 'PWR01' from device 192.168.1.230

Add some logging to your system started rule and add an else statement with a log so you can figure out which if any of your if else clauses are executing. If you are not seeing anything I’m willing to bet there is something wrong there.

Hi Rich,

How would I do that? sorry

rule "Get time period for right now"
when
    System started
then
    logInfo("Started", "System started rule starting")
    val morning = now.withTimeAtStartOfDay.plusHours(5).millis // 5 AM
    val sunrise = new DateTime((Sunrise_Time.state as DateTimeType).calendar.timeInMillis)
    val twilight = new DateTime((Twilight_Time.state as DateTimeType).calendar.timeInMillis)
    val night = now.withTimeAtStartOfDay.plusHours(23).millis // 11 PM

    if(now.isAfter(morning) && now.isBefore(sunrise)) {
        logInfo("Started", "It is Morning!")
        Morning.sendCommand(ON)
        Day.sendCommand(OFF)
        Twilight.sendCommand(OFF)
        Night.sendCommand(OFF)
    }
    else if(now.isAfter(sunrise) && now.isBefore(twilight)) {
        logInfo("Started", "It is Day")
        Morning.sendCommand(OFF)
        Day.sendCommand(ON)
        Twilight.sendCommand(OFF)
        Night.sendCommand(OFF)
    }
    else if(now.isAfter(twilight) && now.isBefore(night)) {
        logInfo("Started", "It is Twilight!")
        Morning.sendCommand(OFF)
        Day.sendCommand(OFF)
        Twilight.sendCommand(ON)
        Night.sendCommand(OFF)
    }
    else if(now.isAfter(night) && now.isBefore(morning)) {
        logInfo("Started", "It is Night!")
        Morning.sendCommand(OFF)
        Day.sendCommand(OFF)
        Twilight.sendCommand(OFF)
        Night.sendCommand(ON)
    }
    else {
        logError("Started", "Failed to determine what time period we are in and set the time of day flags!")
    }
end
1 Like

added the rule, and restarted the service - now get;

16:16:20.169 [DEBUG] [m.r.internal.engine.RuleEngine:264  ] - Executing startup rule 'Get time period for right now'
16:16:20.194 [INFO ] [g.openhab.model.script.Started:53   ] - System started rule starting
16:16:20.384 [ERROR] [m.r.internal.engine.RuleEngine:278  ] - Error during the execution of startup rule 'Get time period for right now': Cannot cast org.openhab.core.types.UnDefType to org.openhab.core.library.types.DateTimeType

Make sure all of your *_Time" items you refer to in that rule are defined in your Items file. In particular, did you add a line to your Items for Twilight_Time?

I believe I have covered all those bases;

items.items
Switch Morning

Switch   Sunrise_Event                         { astro="planet=sun, type=rise, property=start" }
DateTime Sunrise_Time  "Sunrise [%1$tr]" <sun> { astro="planet=sun, type=rise, property=start" }
Switch   Day

Switch   Twilight_Event                        { astro="planet=sun, type=set, property=start, offset=-60" }
DateTime Twilight_Time  "Twilight [%1$tr]" <moon>  { astro="planet=sun, type=set, property=start" }
Switch   Twilight

Switch   Twilight_Increase1                         { astro="planet=sun, type=set, property=start, offset=-45" }
Switch   Twilight_Increase2                         { astro="planet=sun, type=set, property=start, offset=-30" }
Switch   Twilight_Increase3                         { astro="planet=sun, type=set, property=start, offset=-15" }

Switch   Sunset_Event                          { astro="planet=sun, type=set, property=start" }
DateTime Sunset_Time  "Sunset [%1$tr]" <moon>  { astro="planet=sun, type=set, property=start" }
Switch	 Sunset_Event_Offset		       { astro="planet=sun, type=set, property=start, offset=-30" }

Switch   Night

Do you have multiple .item files? If yes then you may need to change the rules file loading period in openhab.cfg to something longer to give openHAB time to loading all your items files before running your rules.

Presumably, thats done like so;

# Configuration folders (must exist as a subdirectory of "configurations"; the value
# tells the number of seconds for the next scan of the directory for changes. A
# value of -1 deactivates the scan).
# A comma separated list can follow after the refresh value. This list defines a filter
# for valid file extensions for the models.
folder:items=10,items
folder:sitemaps=10,sitemap
folder:scripts=10,script
folder:persistence=10,persist
folder:rules=60,rules

Hmmm, progress?

22:25:21.897 [DEBUG] [m.r.internal.engine.RuleEngine:264  ] - Executing startup rule 'Get time period for right now'
22:25:21.933 [INFO ] [g.openhab.model.script.Started:53   ] - System started rule starting
22:25:22.397 [INFO ] [g.openhab.model.script.Started:53   ] - It is Twilight!

Looks like its working. You probably don’t need to make the polling period 60 seconds, 15 would probably be plenty.

1 Like

Seems to be working now, I’ve bounced it again this morning just to ensure it wasn’t persistence or something that caused it to work last night.

Thanks for sticking with my @rlkoshak, really appreciate it!

I am trying to setup something similar. I’m only trying to do it with a night & day switch, not the twilight and morning. I have the night and day switches setup and I can use them in rules. I am trying to get them to run at start-up. I am getting the following error message:
Error during the execution of startup rule ‘Get time period for right now’: Cannot cast org.openhab.core.types.UnDefType to org.openhab.core.library.types.DateTimeType
Here are my items and rule:

Switch   Day
Switch   Night   
Switch Sunrise_Event   {astro="planet=sun, type=rise, property=start, offset=30"}
Switch Sunset_Event    {astro="planet=sun, type=set, property=end, offset=-30"}
String Sunrise_Sunset  "Sunrise / Sunset [%s]"    <sun>
DateTime Sunrise_Time  "Sunrise [%1$tH:%1$tM]"    <sun>    {astro="planet=sun, type=rise, property=start"}   
DateTime Sunset_Time   "Sunset [%1$tH:%1$tM]"     <sun>    {astro="planet=sun, type=set, property=end"}

rule "Get time period for right now"
when
    System started
then
    val sunrise = new DateTime((Sunrise_Time.state as DateTimeType).calendar.timeInMillis)
    val sunset = new DateTime((Sunset_Time.state as DateTimeType).calendar.timeInMillis)
    if(now.isAfter(sunrise) && now.isBefore(sunset)) {
        Day.sendCommand(ON)
        Night.sendCommand(OFF)
    }
    else if(now.isAfter(sunset) && now.isBefore(sunrise)) {
        Day.sendCommand(OFF)
        Night.sendCommand(ON) 
    }
end

Do you have persistence installed and confgured to restoreOnStartup your Sunrise_Time and Sunset_Time Items? If not your startup rule is probably running before the Astro binding is recalculating the times for the current day.

Do I need persistence to run this rule? I ended up getting rid of the rrd4j persistence. I do have the myopenhab persist, but I’m thinking of uninstalling that too.

Yes. Otherwise your sunrise and sunset time items will be undefined at startup.

OK, I tried to setup db4o on my system. I copied the jar file to the right directory, edited db40 settings in my openhab.cfg and made it the default persistence and created the persist file. I am gettings this error message:

2016-01-19 06:13:00.035 [ERROR] [org.quartz.core.JobRunShell   ] - Job db4o.everyMinute threw an unhandled Exception:
java.lang.NullPointerException: null
        at org.openhab.core.persistence.internal.PersistItemsJob.hasStrategy(PersistItemsJob.java:73) ~[na:na]
        at org.openhab.core.persistence.internal.PersistItemsJob.execute(PersistItemsJob.java:52) ~[na:na]
        at org.quartz.core.JobRunShell.run(JobRunShell.java:213) ~[quartz-all-2.1.7.jar:na]
        at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:557) [quartz-all-2.1.7.jar:na] 
2016-01-19 06:13:00.041 [ERROR] [org.quartz.core.ErrorLogger   ] - Job (db4o.everyMinute threw an exception.
org.quartz.SchedulerException: Job threw an unhandled exception.
        at org.quartz.core.JobRunShell.run(JobRunShell.java:224) ~[quartz-all-2.1.7.jar:na]
        at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:557) [quartz-all-2.1.7.jar:na]
Caused by: java.lang.NullPointerException: null
        at org.openhab.core.persistence.internal.PersistItemsJob.hasStrategy(PersistItemsJob.java:73) ~[na:na]
        at org.openhab.core.persistence.internal.PersistItemsJob.execute(PersistItemsJob.java:52) ~[na:na]
        at org.quartz.core.JobRunShell.run(JobRunShell.java:213) ~[quartz-all-2.1.7.jar:na]
        ... 1 common frames omitted

Here is my persist file:

Strategies {
    everyMinute : "0 * * * * ?"
    everyHour 	: "0 0 * * * ?"
    everyDay	: "0 0 0 * * ?"
    default = everyChange
}
Items {
    // persist everything when the value is updated, just a default, and restore them from database on startup
    * : strategy = everyChange, restoreOnStartup

    // next we define specific strategies of everyHour for anything in the Temperature group, and and every minute       for Humidity
    Temperature* : strategy = everyHour
    Humidity* : strategy = everyMinute

    // alternatively you can add specific items here, such as
    //Bedroom_Humidity,JamesInOffice : strategy = everyMinute
        Sunrise_Time : strategy = everyminute, restoreOnStartup
        Sunset_Time : strategy = everyminute, restoreOnStartup
}

Here is my rules file for Sunrise/Sunset:

import org.openhab.core.library.types.*
import org.openhab.core.persistence.*
import org.openhab.model.script.actions.*
import org.joda.time.*
import org.java.math.*

////////////////////////////////////////////////////////////////////////////
// Rule:    Initialize system on startup / rule update
// Purpose: Initialize the system
rule "Initialize system on startup / rule update"
when
    System started
then
    var DateTimeType sunrise = new DateTimeType(getAstroSunriseStart(now.toDate, 42.5803, 83.0303))
    var DateTimeType sunset = new DateTimeType(getAstroSunsetStart(now.toDate, 42.5803, 83.0303))
    Sunrise_Time.postUpdate(sunrise)
    Sunset_Time.postUpdate(sunset)
end

////////////////////////////////////////////////////////////////////////////
// Rule:    Sunrise/Sunset changed
// Purpose: Update Sunrise_Sunset string with the updated sunrise and sunset
//          times. The Sunrise_Sunset string is used to display both the
//          sunrise time and sunset time on a single line in the GUI
rule "Sunrise/Sunset changed"
when
    Item Sunrise_Time changed
    or Item Sunset_Time changed
then
    var DateTime sunrise = new DateTime((Sunrise_Time.state as DateTimeType).calendar.timeInMillis)
    var DateTime sunset = new DateTime((Sunset_Time.state as DateTimeType).calendar.timeInMillis)
    Sunrise_Sunset.postUpdate(String::format("%02d:%02d / %02d:%02d", sunrise.getHourOfDay(), s
sunrise.getMinuteOfHour(), sunset.getHourOfDay(), sunset.getMinuteOfHour()))
         end

    rule "Day"
    when
        Item Sunrise_Event received update
    then
    Night.sendCommand(OFF)
    Day.sendCommand(ON)
end

rule "Night"
when
    Item Sunset_Event received update
then
    Day.sendCommand(OFF)
    Night.sendCommand(ON)
end

rule "Get time period for right now"
when
    System started
then
    val sunrise = new DateTime((Sunrise_Time.state as DateTimeType).calendar.timeInMillis)
    val sunset = new DateTime((Sunset_Time.state as DateTimeType).calendar.timeInMillis)
    if(now.isAfter(sunrise) && now.isBefore(sunset)) {
        Day.sendCommand(ON)
        Night.sendCommand(OFF)
    }
    else if(now.isAfter(sunset) && now.isBefore(sunrise)) {
        Day.sendCommand(OFF)
        Night.sendCommand(ON) 
    }
end 

Can you see anything I’m doing wrong?

Do you indeed have a Temperature and Humidity group? That is the only thing I can think of that could be wrong. Also, since you are using db4o it is not that important to use the everyMinute strategy like you do with rrd4j and since by default everything gets saved every change and restoreOnStartup I would remove the lines for Sunrise_Time and Sunset_Time.