ESPHome 2026.3.0-dev
Loading...
Searching...
No Matches
uptime_text_sensor.cpp
Go to the documentation of this file.
2
3#include "esphome/core/hal.h"
5#include "esphome/core/log.h"
6
7namespace esphome::uptime {
8
9static const char *const TAG = "uptime.sensor";
10
11static void append_unit(char *buf, size_t buf_size, size_t &pos, const char *separator, unsigned value,
12 const char *label) {
13 if (pos > 0) {
14 pos = buf_append_printf(buf, buf_size, pos, "%s", separator);
15 }
16 pos = buf_append_printf(buf, buf_size, pos, "%u%s", value, label);
17}
18
20
22 uint32_t uptime = static_cast<uint32_t>(millis_64() / 1000);
23 unsigned interval = this->get_update_interval() / 1000;
24
25 // Calculate all time units
26 unsigned seconds = uptime % 60;
27 uptime /= 60;
28 unsigned minutes = uptime % 60;
29 uptime /= 60;
30 unsigned hours = uptime % 24;
31 uptime /= 24;
32 unsigned days = uptime;
33
34 // Determine which units to display based on interval thresholds
35 bool seconds_enabled = interval < 30;
36 bool minutes_enabled = interval < 1800;
37 bool hours_enabled = interval < 12 * 3600;
38
39 // Show from highest non-zero unit (or all in expand mode) down to smallest enabled
40 bool show_days = this->expand_ || days > 0;
41 bool show_hours = hours_enabled && (show_days || hours > 0);
42 bool show_minutes = minutes_enabled && (show_hours || minutes > 0);
43 bool show_seconds = seconds_enabled && (show_minutes || seconds > 0);
44
45 // If nothing shown, show smallest enabled unit
46 if (!show_days && !show_hours && !show_minutes && !show_seconds) {
47 if (seconds_enabled) {
48 show_seconds = true;
49 } else if (minutes_enabled) {
50 show_minutes = true;
51 } else if (hours_enabled) {
52 show_hours = true;
53 } else {
54 show_days = true;
55 }
56 }
57
58 // Build output string on stack
59 // Home Assistant max state length is 255 chars + null terminator
60 char buf[256];
61 size_t pos = 0;
62 buf[0] = '\0'; // Initialize for empty case
63
64 if (show_days)
65 append_unit(buf, sizeof(buf), pos, this->separator_, days, this->days_text_);
66 if (show_hours)
67 append_unit(buf, sizeof(buf), pos, this->separator_, hours, this->hours_text_);
68 if (show_minutes)
69 append_unit(buf, sizeof(buf), pos, this->separator_, minutes, this->minutes_text_);
70 if (show_seconds)
71 append_unit(buf, sizeof(buf), pos, this->separator_, seconds, this->seconds_text_);
72
73 this->publish_state(buf);
74}
75
77void UptimeTextSensor::dump_config() { LOG_TEXT_SENSOR("", "Uptime Text Sensor", this); }
78
79} // namespace esphome::uptime
virtual uint32_t get_update_interval() const
Get the update interval in ms of this sensor.
void publish_state(const std::string &state)
float get_setup_priority() const override
constexpr float HARDWARE
For components that deal with hardware and are very important like GPIO switch.
Definition component.h:29
const char *const TAG
Definition spi.cpp:7
uint64_t HOT millis_64()
Definition core.cpp:26
size_t size_t pos
Definition helpers.h:854