Skip to content

Instantly share code, notes, and snippets.

Created February 17, 2023 16:23
Show Gist options
  • Save kquinsland/72ff8b59bd58ab2c12d8c186bf80f543 to your computer and use it in GitHub Desktop.
Save kquinsland/72ff8b59bd58ab2c12d8c186bf80f543 to your computer and use it in GitHub Desktop.
Quick "time-remaining" sensor for ESPHome

This is a quick and dirty cut/paste from an old ESPHome project that I never got around to writing up. It monitored several sensors and controlled a hydroponics system.

The specific snip above creates a text string that is published back to Home Assistant.

Hopefully it should be pretty easy to figure out what's going on.

The time remaining depended on several factors and could change arbitrarily. For this reason, I found it much simpler to update the time remaining sensor from other entities/components which is why the update_inteerval is never.

In several other places, I have lambda functions that make calls:


Depending on your needs, this may or may not be a good pattern.

# Useful for debugging and showing the true time left in a light cycle
- name: "${friendly_name_short} Lights Cycle Time Remaining"
id: txt_light_cycle_remaining
platform: template
icon: "mdi:theme-light-dark"
entity_category: "diagnostic"
# Given that we have timers that run for tens of min to tens of hours, it's silly to
# update this every 60s or whatever. Furthermore, we can't really adjust the interval
# so it's best to just handle it 100% ourselves in the _tick scripts.
update_interval: never
lambda: |
auto TAG="textSensor.light-cycle-remaining";
//Assuming 3 digits for hours, min, seconds _and_ three colons + 2 char extra
char buff[15];
int hr, min, sec;
hr = min = sec = 0;
if(! id(glbl_light_timer_armed)) {
return {"Disarmed"};
// I cut some logic that calculated _remaining_sec from other sensor input, you'd calculate or retrieve your own value here
int _remaining_sec = 0;
hr = _remaining_sec/3600;
min = (_remaining_sec % 3600) / 60;
sec = _remaining_sec % 60;
ESP_LOGD(TAG, "sec: %d, min: %d, hr: %d", sec, min, hr);
snprintf(buff, 15, "%02d:%02d:%02d", hr, min, sec);
ESP_LOGD(TAG, "buff: %s", buff);
return to_string(buff);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment