WTH don't template binary sensors survive a restart?

Example code:

binary_sensor:
  - platform: template
    sensors:
      room_occupied:
         value_template: >
           {{
             is_state('room_motion', 'on')
           }}
         delay_off:
           minutes: 120

Adding a delay_on or delay_off to a template binary_sensor should add a timestamp attribute to the binary_sensor. So, when Home Assistant is restarted, it can get the previous values for state and the timestamp and then evaluate these to determine if the sensor should start in the “on” or “off” state and how much time should be left on the “timer”.

Without this, if I’m working on another automation that requires restarting Home Assistant, all rooms with occupancy sensors like the above are suddenly unoccupied, resulting in lights that turn off while people are in the room and other undesired effects.

Something like this may help:

binary_sensor:
  - platform: template
    sensors:
      room_occupied:
         value_template: >
           {{
             is_state('room_motion', 'on')
             if not is_state('room_motion', 'unavailable')
             else states('binary_sensor.room_occupied')
           }}

That will filter out any cases where the room motion sensor ‘unavailable’.

How does that help? I tried it, just in case I was overlooking something. It doesn’t work at all, as expected.

The problem is not that “room_motion” goes ‘unavailable’ when Home Assistant starts (though, if that were the case your template would help).

The issue is that when Home Assistant starts, the previous state of the template binary sensor is not known to Home Assistant. It doesn’t know that the binary_sensor was previously “on” due to the “delay_on” and, since that time has not elapsed yet, it should still be on. It evaluates “room_motion”, sees that it is now off, and sets the state of the the template binary_sensor to “off”.