ESPHome help with dynamic update interval of a sensor

Hello guys! I’m trying to set a temperature sensor to change its update interval based on another switch state. I need it to be 5 seconds when the switch is on and 5 minutes when it is off. Here’s my code:

output:

  - platform: gpio
    pin: GPIO12
    id: relay_1

  - platform: gpio
    pin: GPIO5
    id: relay_2

switch:

  - platform: output
    name: "Desumidificador - Resistência"
    id: resistencia
    output: relay_1
    icon: "mdi:heating-coil"
    on_turn_on:
      - lambda: |-
          id(dht_sensor).set_update_interval(5000);
      - delay: 3600s
      - switch.turn_off: resistencia
    on_turn_off:
      - lambda: |-
          id(dht_sensor).set_update_interval(300000);

  - platform: output
    name: "Desumidificador - Cooler"
    id: cooler
    output: relay_2
    icon: "mdi:fan"

sensor:

  - platform: dht
    pin: RX
    id: dht_sensor
    temperature:
      name: "Desumidificador - Temperatura"
    humidity:
      name: "Desumidificador - Umidade"
    update_interval: never

This doesn’t work, results with “unavailable” sensor data. Any ideas?

Thanks!

Is sensor return any data without manipulations with set_update_interval() ?

Set the update interval of the sensor to 0 (disable) and cal the component update from a script which takes the state of the switch into account to determine the interval you want

Ok, so what happens when I get the unavailable data from the sensor is because when it boots up, it gets the off state from the switch and sets the update interval to five minutes, so until then, it shows unavailable. The lambda call is working. The problem is that the same lambda call from the turn on state does not update the update interval from the sensor, not sure why. I’ve also set the sensor update interval to never, just edited the original post. Thanks!

1 Like

You might just trigger a manual component update ‘on_boot’ to get the first value/reading populated

Thanks for the idea. Actually there’s no problem with the sensor booting with the 5 minutes update time, the main idea here is to have it updating every 5 seconds while the switch is on.