ESPHome 2025.5.0
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 {
8namespace uptime {
9
10static const char *const TAG = "uptime.sensor";
11
13 this->last_ms_ = millis();
14 if (this->last_ms_ < 60 * 1000)
15 this->last_ms_ = 0;
16 this->update();
17}
18
19void UptimeTextSensor::insert_buffer_(std::string &buffer, const char *key, unsigned value) const {
20 buffer.insert(0, this->separator_);
21 buffer.insert(0, str_sprintf("%u%s", value, key));
22}
23
25 auto now = millis();
26 // get whole seconds since last update. Note that even if the millis count has overflowed between updates,
27 // the difference will still be correct due to the way twos-complement arithmetic works.
28 uint32_t delta = now - this->last_ms_;
29 this->last_ms_ = now - delta % 1000; // save remainder for next update
30 delta /= 1000;
31 this->uptime_ += delta;
32 auto uptime = this->uptime_;
33 unsigned interval = this->get_update_interval() / 1000;
34 std::string buffer{};
35 // display from the largest unit that corresponds to the update interval, drop larger units that are zero.
36 while (true) { // enable use of break for early exit
37 unsigned remainder = uptime % 60;
38 uptime /= 60;
39 if (interval < 30) {
40 this->insert_buffer_(buffer, this->seconds_text_, remainder);
41 if (!this->expand_ && uptime == 0)
42 break;
43 }
44 remainder = uptime % 60;
45 uptime /= 60;
46 if (interval < 1800) {
47 this->insert_buffer_(buffer, this->minutes_text_, remainder);
48 if (!this->expand_ && uptime == 0)
49 break;
50 }
51 remainder = uptime % 24;
52 uptime /= 24;
53 if (interval < 12 * 3600) {
54 this->insert_buffer_(buffer, this->hours_text_, remainder);
55 if (!this->expand_ && uptime == 0)
56 break;
57 }
58 this->insert_buffer_(buffer, this->days_text_, (unsigned) uptime);
59 break;
60 }
61 this->publish_state(buffer);
62}
63
65void UptimeTextSensor::dump_config() { LOG_TEXT_SENSOR("", "Uptime Text Sensor", this); }
66
67} // namespace uptime
68} // namespace esphome
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
void insert_buffer_(std::string &buffer, const char *key, unsigned value) const
const float HARDWARE
For components that deal with hardware and are very important like GPIO switch.
Definition component.cpp:18
const char *const TAG
Definition spi.cpp:8
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7
std::string str_sprintf(const char *fmt,...)
Definition helpers.cpp:323
uint32_t IRAM_ATTR HOT millis()
Definition core.cpp:27