I used the config above for a device on my mailbox that runs on a single 18650 battery which is on my front yard and sometimes it takes more than a minute to connect with Home Assistant.
I think I have improved it a little bit to still enter sleep mode if it’s not able to connect with HA after a few attempts. (for example if the server is down or forgot to enable ICU)
My config sets variable sleep duration based on time which is retrieved from HA. The sleep duration is 1h if it wakes up before 7:00AM, 15min before 4:00PM and 30min after 4:00PM.
Feel free to edit/improve it for your needs.
globals:
- id: connectAttempts
type: int
restore_value: no
initial_value: '0'
deep_sleep:
sleep_duration: 15min
id: deep_sleep_control
binary_sensor:
- platform: homeassistant
id: prevent_deep_sleep
entity_id: input_boolean.prevent_deep_sleep
- platform: homeassistant
id: ICU
entity_id: input_boolean.icu
time:
- platform: homeassistant
id: ha_time
script:
- id: consider_deep_sleep
mode: queued
then:
- delay: 10s
- if:
condition:
binary_sensor.is_off: ICU
then:
- logger.log: 'Not connected to HomeAssisstant. Setup ICU and enable in HA to enable deepsleep'
- if:
# if ICU is off or not connected to HA, try 10 times (10x10sec) to connect or else enter sleep mode
condition:
- lambda: |-
if (id(connectAttempts) < 9) {
id(connectAttempts) += 1;
ESP_LOGD("customSleep", "Connection Attempts: %d", id(connectAttempts));
return false;
}
else {
id(connectAttempts) = 0;
id(deep_sleep_control).set_sleep_duration(900000);
ESP_LOGD("customSleep", "Connection Attempts: %d", id(connectAttempts));
ESP_LOGD("customSleep", "Set Sleep Duration: %d min", 900000/60000);
return true;
}
then:
- logger.log: 'Entering Deep Sleep after failed attempts to connect with HA and read ICU'
- delay: 500ms
- deep_sleep.enter: deep_sleep_control
else:
- logger.log: 'Try again to connect with HA'
else:
- if:
# if prevent is off enter sleep: 15min if time is invalid, 1h before 7:00, 15min before 16:00, 30min after 16:00
condition:
binary_sensor.is_on: prevent_deep_sleep
then:
- logger.log: 'Skipping sleep. Disable "Prevent Deep Sleep" in HA to enable sleep'
else:
- lambda: |-
auto time = id(ha_time).now();
if (time.is_valid()){
if (time.hour < 7 ){
id(deep_sleep_control).set_sleep_duration(3600000);
ESP_LOGD("customSleep", "Set Sleep Duration: %d min", 3600000/60000);
}
else if (time.hour < 16 ){
id(deep_sleep_control).set_sleep_duration(900000);
ESP_LOGD("customSleep", "Set Sleep Duration: %d min", 900000/60000);
}
else{
id(deep_sleep_control).set_sleep_duration(1800000);
ESP_LOGD("customSleep", "Set Sleep Duration: %d min", 1800000/60000);
}
}
else{
id(deep_sleep_control).set_sleep_duration(900000);
ESP_LOGD("customSleep", "Wrong Time - Set Sleep Duration: %d min", 900000/60000);
}
- logger.log: 'Entering Deep Sleep'
- delay: 500ms
- deep_sleep.enter: deep_sleep_control
- script.execute: consider_deep_sleep