ESPHome configuration help - enter deep sleep after all sensors read or after time out

Wanted to share my solution in case it may help anyone else who is trying to accomplish a similar thing :smile:

This solution avoids using any explicit delays/sleeps.

mqtt:
  id: mqtt_client
  on_connect:
    then:
      - script.execute: check_all_published

script:
  - id: check_all_published
    mode: restart
    then:
      - if:
          condition:
            lambda: 'return !id(ota_mode);'
          then:
            - lambda: |-
                static bool temp_published = false;
                static bool pressure_published = false;
                static bool humidity_published = false;

                if (!temp_published && id(${node_id}_temperature).has_state()) {
                  temp_published = true;
                }
                if (!pressure_published && id(${node_id}_pressure).has_state()) {
                  pressure_published = true;
                }
                if (!humidity_published && id(${node_id}_humidity).has_state()) {
                  humidity_published = true;
                }

                if (temp_published && pressure_published && humidity_published && id(mqtt_client)->is_connected()) {
                  id(deep_sleep_1).set_run_duration(0);
                  id(deep_sleep_1).set_sleep_duration(1000 * 60 * 5); // 5 minutes
                  id(deep_sleep_1).begin_sleep();
                }

sensor:
  - platform: bme280_i2c
    temperature:
      name: Temperature
      id: ${node_id}_temperature
      oversampling: 2x
      on_value:
        then:
          - script.execute: check_all_published
    pressure:
      name: Pressure
      id: ${node_id}_pressure
      oversampling: 2x
      on_value:
        then:
          - script.execute: check_all_published
    humidity:
      name: Humidity
      id: ${node_id}_humidity
      oversampling: 2x
      on_value:
        then:
          - script.execute: check_all_published
    address: 0x76

1 Like