ESPHome  2024.3.1
uptime_sensor.cpp
Go to the documentation of this file.
1 #include "uptime_sensor.h"
2 #include "esphome/core/log.h"
3 #include "esphome/core/helpers.h"
4 #include "esphome/core/hal.h"
5 
6 namespace esphome {
7 namespace uptime {
8 
9 static const char *const TAG = "uptime.sensor";
10 
12  const uint32_t ms = millis();
13  const uint64_t ms_mask = (1ULL << 32) - 1ULL;
14  const uint32_t last_ms = this->uptime_ & ms_mask;
15  if (ms < last_ms) {
16  this->uptime_ += ms_mask + 1ULL;
17  ESP_LOGD(TAG, "Detected roll-over \xf0\x9f\xa6\x84");
18  }
19  this->uptime_ &= ~ms_mask;
20  this->uptime_ |= ms;
21 
22  // Do separate second and milliseconds conversion to avoid floating point division errors
23  // Probably some IEEE standard already guarantees this division can be done without loss
24  // of precision in a single division, but let's do it like this to be sure.
25  const uint64_t seconds_int = this->uptime_ / 1000ULL;
26  const float seconds = float(seconds_int) + (this->uptime_ % 1000ULL) / 1000.0f;
27  this->publish_state(seconds);
28 }
29 std::string UptimeSensor::unique_id() { return get_mac_address() + "-uptime"; }
31 void UptimeSensor::dump_config() { LOG_SENSOR("", "Uptime Sensor", this); }
32 
33 } // namespace uptime
34 } // namespace esphome
std::string unique_id() override
uint32_t IRAM_ATTR HOT millis()
Definition: core.cpp:25
float get_setup_priority() const override
std::string get_mac_address()
Get the device MAC address as a string, in lowercase hex notation.
Definition: helpers.cpp:587
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
This is a workaround until we can figure out a way to get the tflite-micro idf component code availab...
Definition: a01nyub.cpp:7