Initial value from a templated binary sensor not available in ESPHome

In my ESPHome I want to have an information whether there is a day or night. For this I have created a binary sensor in the Home Assistant

binary_sensor:
  - platform: tod
    name: is_night
    after: sunset
    before: sunrise

and imported it to the ESPHome project with

binary_sensor:
  - platform: homeassistant
    id: is_night
    name: "Night Condition"
    entity_id: binary_sensor.is_night
    on_state:
      then:
        - lambda: '...'

The problem is that the on_state does not get fired on startup so in case I restart the device at night it thinks that it is a day. The log shows

[23:09:38][D][homeassistant.binary_sensor:021]: 'binary_sensor.is_night': Got state ON
[23:09:38][D][binary_sensor:034]: 'Night Condition': Sending initial state ON

It seems that the initial state does not trigger the on_state for the binary sensor. It does for text ones and on_value. Is this intended or is there something that I can do to be notified of when the initial value arrives?

ESPHome is 1.17.0 plus some of my changes unrelated to binary sensors, HA is 2021.2.3.

Thanks.

1 Like

Instead of on_state, you can use on_boot and check the condition in it. I think if condition would be supported with on_boot. On boot you can use the if condition to check the state of the sensor and accordingly set the actions.

If the if condition is not available with on boot you should first create a template switch with on_turn_on condition to check the state of sensor and proceed with the corresponding actions and then switch on this switch with on_boot.

There could be other ideas also but this is the one that comes to top of my mind.

yep, I have some workaround implemented so I am able to achieve the intended result, it is just ugly and an unnecessary code pollution. The value arrives with all the others, it is just not forwarded - maybe there is a reason, maybe there is a setting, maybe this is a bug I should log, so I am asking first as I am an ESPHome newbie :slight_smile:

As i have read, on_value on works with a change in value, the value we see just after boot is the initial value. that could be the thing. Maybe there could be a feature to check the initial value.

It is an old question but I came here looking for a solution to my problem. And I think I know how to solve this issue so I’ll leave a solution for others.

The binary sensor in ESP has a publish_initial_state property, setting it up to true should solve the issue.

1 Like