ESPHome  2025.2.0
uptime_text_sensor.cpp
Go to the documentation of this file.
1 #include "uptime_text_sensor.h"
2 
3 #include "esphome/core/hal.h"
4 #include "esphome/core/helpers.h"
5 #include "esphome/core/log.h"
6 
7 namespace esphome {
8 namespace uptime {
9 
10 static 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 
20  auto now = millis();
21  // get whole seconds since last update. Note that even if the millis count has overflowed between updates,
22  // the difference will still be correct due to the way twos-complement arithmetic works.
23  uint32_t delta = now - this->last_ms_;
24  this->last_ms_ = now - delta % 1000; // save remainder for next update
25  delta /= 1000;
26  this->uptime_ += delta;
27  auto uptime = this->uptime_;
28  unsigned interval = this->get_update_interval() / 1000;
29  std::string buffer{};
30  // display from the largest unit that corresponds to the update interval, drop larger units that are zero.
31  while (true) { // enable use of break for early exit
32  unsigned remainder = uptime % 60;
33  uptime /= 60;
34  if (interval < 30) {
35  buffer.insert(0, str_sprintf("%us", remainder));
36  if (uptime == 0)
37  break;
38  }
39  remainder = uptime % 60;
40  uptime /= 60;
41  if (interval < 1800) {
42  buffer.insert(0, str_sprintf("%um", remainder));
43  if (uptime == 0)
44  break;
45  }
46  remainder = uptime % 24;
47  uptime /= 24;
48  if (interval < 12 * 3600) {
49  buffer.insert(0, str_sprintf("%uh", remainder));
50  if (uptime == 0)
51  break;
52  }
53  buffer.insert(0, str_sprintf("%ud", (unsigned) uptime));
54  break;
55  }
56  this->publish_state(buffer);
57 }
58 
60 void UptimeTextSensor::dump_config() { LOG_TEXT_SENSOR("", "Uptime Text Sensor", this); }
61 
62 } // namespace uptime
63 } // namespace esphome
void publish_state(const std::string &state)
Definition: text_sensor.cpp:9
uint32_t IRAM_ATTR HOT millis()
Definition: core.cpp:25
float get_setup_priority() const override
const char *const TAG
Definition: spi.cpp:8
std::string str_sprintf(const char *fmt,...)
Definition: helpers.cpp:324
virtual uint32_t get_update_interval() const
Get the update interval in ms of this sensor.
Definition: component.cpp:228
const float HARDWARE
For components that deal with hardware and are very important like GPIO switch.
Definition: component.cpp:18
Implementation of SPI Controller mode.
Definition: a01nyub.cpp:7