I still have a pretty long to-do list for my home-automation with Home Assistant, mostly related to “peak-shaving”.

One obstacle that I needed 15 mins of free mental cycles for was figuring out how to correctly control if the hot water tank should be running or not based on a time interval. A quick hack with HA’s built-in scripting turned out to be … meh: I want to have an interval with start- and end-time (which I’m setting based on electricity spot-price), and I hadn’t figured out how to handle the corner-case of a wrap around (e.g., start: 23:00, end 06:00) correctly, because the simple logic available (start < now < end) doesn’t work in that case, and would need severe, repeated, special-casing in the HA automation.

So I decided to end this once and for all with yet another template-sensor that tells me if we’re within the interval or not:

 (now() > today_at(states.input_datetime.water_on.state) and
      ((today_at(states.input_datetime.water_on.state) < today_at(states.input_datetime.water_off.state) and now() < today_at(states.input_datetime.water_off.state))
   or (today_at(states.input_datetime.water_on.state) > today_at(states.input_datetime.water_off.state))))
   or (today_at(states.input_datetime.water_on.state) > today_at(states.input_datetime.water_off.state) and now() < today_at(states.input_datetime.water_off.state))

It’s still mind-boggingly convoluted, but seems about right; could probably be simplified.

TODO: why does the code need a scroll-bar…