Sensor states at HA restart?

I have two sensors for measuring outside light levels. One 100% reliable but not always accurate, the other not always reliable but very accurate.

I have automations switch to using the 100% reliable but less accurate sensor any time the other one isn’t available.

So, I decide if a room is dark based on the current sensor but every time HA restarts its state always goes to ‘on’. Why is that and can I stop it? Here is the sensor.

      dark_hall:
        friendly_name: Dark in the hall
        entity_id:
          - sensor.smartweather_average_illuminance
          - sensor.brightness
          - input_number.hall_smartweather_average_illuminance_sensor_threshold
          - input_number.hall_brightness_sensor_threshold
          - input_select.sensor_for_darkness
        value_template: >
          {% set sensor_threshold = states('input_number.hall_' + states('input_select.sensor_for_darkness') + '_sensor_threshold') | int %}
          {% set sensor_used = states('input_select.sensor_for_darkness') %}

          {{ states('sensor.' + sensor_used) | int <= sensor_threshold }}

I would have expected it to remember its state from before the restart but it doesn’t. Is that because it is a template sensor?

The only way I can think of doing this is by changing my state triggers to include a for:

  - alias: Hall Lights On When It Gets Dark
    trigger:
      #=== If it is dark
      - platform: state
        entity_id: binary_sensor.dark_hall
        from: 'off'
        to: 'on'
        for:
          seconds: 30

I’d wager that the value of your input_select is ‘unknown’ on startup. When you cast a string that’s not a number to an integer, it makes the number 0. 0 will be less than the threshold… so, it turns on.

Personally, i’d rewrite the whole thing to get rid of the input_select and just have a template sensor that dynamically changes between the 2.

Yeah, but the reason I wrote it that way was so I could also change it manually.
However I haven’t done that for so for so long now that I may change it to your way.

There’s missing pieces to the puzzle, but you can definitely change your template to choose one or the other. Then if the input select is set to a sensor, override it and choose that sensor. You’d just need to add an option for the input select that means ‘nothing is selected’. I tried to make this for you but there’s too many unknowns with your input_number and sensors. If you weren’t using the input numbers between the sensors, this would be a pretty easy template.

1 Like

Yes, great idea to have an ‘Auto’ option in the input_select.