ESPHome  2024.11.1
uptime_seconds_sensor.cpp
Go to the documentation of this file.
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  const uint32_t ms = millis();
14  const uint64_t ms_mask = (1ULL << 32) - 1ULL;
15  const uint32_t last_ms = this->uptime_ & ms_mask;
16  if (ms < last_ms) {
17  this->uptime_ += ms_mask + 1ULL;
18  ESP_LOGD(TAG, "Detected roll-over \xf0\x9f\xa6\x84");
19  }
20  this->uptime_ &= ~ms_mask;
21  this->uptime_ |= ms;
22 
23  // Do separate second and milliseconds conversion to avoid floating point division errors
24  // Probably some IEEE standard already guarantees this division can be done without loss
25  // of precision in a single division, but let's do it like this to be sure.
26  const uint64_t seconds_int = this->uptime_ / 1000ULL;
27  const float seconds = float(seconds_int) + (this->uptime_ % 1000ULL) / 1000.0f;
28  this->publish_state(seconds);
29 }
30 std::string UptimeSecondsSensor::unique_id() { return get_mac_address() + "-uptime"; }
33  LOG_SENSOR("", "Uptime Sensor", this);
34  ESP_LOGCONFIG(TAG, " Type: Seconds");
35 }
36 
37 } // namespace uptime
38 } // namespace esphome
uint32_t IRAM_ATTR HOT millis()
Definition: core.cpp:25
std::string get_mac_address()
Get the device MAC address as a string, in lowercase hex notation.
Definition: helpers.cpp:706
void publish_state(float state)
Publish a new state to the front-end.
Definition: sensor.cpp:39
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