Homeassistant Binary Sensor

I am trying to configure an ESPHome device to read the status of a fan on Homeassistant when the ESP boots and then set an LED light on the ESP on or off, to match.

I have configured a binary sensor in HomeAssistant to provide the binary state:

binary_sensor:
  - platform: template
    sensors:
      room_fan_status:
        friendly_name: "Room Fan On / Off"
        device_class: power
        value_template: "{{ is_state('switch.room_fan', 'on')}}"

And have then got a binary sensor in the ESPHome code to read this:

binary_sensor:
  - platform: homeassistant
    id: fan
    name: "Fan Sensor"
    entity_id: sensor.room_fan_status

and then have a on_boot section

  on_boot:
    priority: -10
    then:
      - if:
          condition:
            - binary_sensor.is_on: fan
          then:
            - logger.log: "The fan is on"
            - light.turn_on: room_fan_led
          else:
            - logger.log: "The fan is off"
            - light.turn_off: room_fan_led

This is not working and I can’t see why. Can anyone help, please?

I believe you’ll also need some logic on the binary_sensor on the ESP side, as on_boot will only update when the ESP device starts up.
Try to get it working that side first, then if you need startup value you can debug that later, the issue might be related to the time the wifi is available, api is connected etc.

Thanks, @glmnet - at the moment I have it working where HA updates the LED when status of the fan changes (it ‘pushes’ the status to the ESP) and it works well. The problem is if the ESP goes off line for any reason and then when it restarts it gets out of sync until the HA next updates the status.

What I am trying to do here is have the ESP ‘pull’ the status from HA once when it starts up so that it starts in sync.

I did wonder about that timing issue, maybe I should set a lower priority and see if that helps.

on_boot is too early, ESP does not connect to HA, it happens the other way round, ESP accepts clients connection, in fact, ESP can accept more than one HA instance connected to it.
Unfortunately the api: component does not provide a on_client_connected: trigger.
A few things to try:

  • Add a delay: to your current script, so hopefully HA connects before timing out, easy to test.
  • Add the Home assistant status sensor and I have not tested this but I believe you can add automatons to it like on_state:, on_press: etc.
  • If previous does not work you can for sure add the status sensor and then configure an automation in HA to call a ESPHome service

I don’t know other good alternatives, may be filling an github issue to get more support.

Thanks again, @glmnet - I will try those options and report back.