ESPhome: binary sensor based on sensor does follow state changes

Hello, I have following definition

sensor:
   some sensor providing value "light"

and then binary sensor that is true if sensor is above some threshold and false if it is below:

binary sensor
   lambda: |-
      if (id(light).state >= id(threshold)) return true;
      if (id(light).state < id(threshold)) return false;

it seems to me that the binary sensor does not follows state updates of sensor if it is based on value of master sensor in lambda. How to update the binary sensor currently? You cannot use on_value and then component.update: binary_sensor because it does not work on binary sensors.

Post your actual code: it’s likely you’ve made an error somewhere.

OK, but the code is a bit complicated. The is_sun binary sensor does not update as often as bh1750. It actually does not update until bh1750 goes over threshold, but bh1750 does update every 3 minutes because light changes even if it is still over or under threshold…

It seems to me that if lambda in binary sensor evaluates true and it was true before, then it does not proceed further to on_state, because state actually has not changed. But I need the on_state to run as often as bh1750 updates, even if it is true again. I think I would better move it to interval…

globals:
# CONSTANTS
  - id: light_threshold
    type: float
    initial_value: "20000.0"
sensor:
  - platform: bh1750
    name: "BH1750 Illuminance"
    id: bh1750_illuminance
    measurement_duration: 31
    update_interval: 3min
binary_sensor:
  - platform: template
    name: "Is sun"
    id: is_sun
    device_class: light
    lambda: |-
      if (id(bh1750_illuminance).state > id(light_threshold)) {   
        return true;
        }
      else {
        return false;
        }
    on_state:
      then:
        - component.update: bh1750_illuminance
        - if:  
               ...ando some complex automations here...

what if I manually publish state of this binary sensor in lambda by id(is_sun).publish_state(true) twice in a row, will it trigger on_state twice as well, or only on first publish?

Only the first.

true to true isn’t a state change.

Why not run the on_state code in the bh1750_illuminance sensor instead with the first step to test against the threshold? The binary_sensor is only ever going to change state when the illuminance sensor sends a new value, so it’ll be run just as often.

Your code does appear to ask it for a new value immediately, though: perhaps that should be the last step in your on_state code, once it’s finished dealing with the current value?

EDIT: on_value for sensors, thanks Tom!

I think it would be on_value rather than on_state for a sensor.

And I was going to suggest it until I saw that one of the commands was:

component.update: bh1750_illuminance

Which would put it in an infinite loop.

I don’t understand why this is needed though.

1 Like