I see two approaches:
- Event-based driven by when the sensor is updated.
If the sensor is read regularly, this may waste CPU performing time comparisons.
- Time-based driven by a cron statement.
Uses less CPU, but at the cost of being less flexible on start/stop and comparison times meaning you can’t check 17:30 - 20:45, but need to round to 17:30 - 20:30.
A combination is also possible, where a cron statement triggers a rule, say every 15 minutes, and then nested if statements check the time and temp.
My own rules use a combination of both - some use cases make sense to trigger by time (e.g. regularly check if a door has been left open, and how long), others by events (e.g. a motion sensor or an Astro binding item changing state on a variable sunset event).
I certainly feel your pain with date / time calculations.
Many OH1 examples use the joda.time libraries (http://www.joda.org/joda-time/) with explicit import statements, but in Java 8 and OH2, the functionality was incorporated (JSR-310) under slightly different java.time names.
After deciding to use the Java native versions in OH2, I have spent many happy hours reading Java class library documentation and wondering what the latest interpreter error message means!
So, at the very real risk of showing my ignorance of eXtend and the Java API, here’s two attempts at some pseudo code.
Event based
rule "Event Rule"
when
Item TempSensor changed
then
// borrow comparison code from Rich
// didn't realise it was possible to stack .plus - neat
if (now.isAfter(now.withTimeAtStartOfDay.plusHours(17).plusMinutes(30)) && now.isBefore(now.withTimeAtStartOfDay.plusHours(20).plusMinutes(45)) {
if ((TempSensor.state as DecimalType) < 22) {
logInfo("Time Rule", "Cold!")
}
}
end
Cron time based
rule "Time Rule"
when
// sec min hr dom mon dow yr
Time cron "0 30 17-20 ? * *"
then
// Rules fires at 17:30, 18:30, 19:30, 20:30 so efficient, but not to specification!
if ((TempSensor.state as DecimalType) < 22) {
logInfo("Time Rule", "Cold!")
{
end
Note that although temperature control looks as simple as a comparison statement, ‘real’ thermostats accommodate the characteristics of the controlled device with extras such as hysteresis (prevents lots of switching in response to small temperature changes), modulation / proportional control (some loads are not just ON or OFF - they can be 30% on), and optimum start (model how long it takes to achieve a set temperature, and turn on the device early to achieve the target set point at the start of the time period).
I’d also recommend including a hardware fall back (such as a physical frost thermostat) just in case your software controller decides to lock up in the midst of winter!