ESPHome 2025.5.0
Loading...
Searching...
No Matches
uptime_seconds_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 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}
30std::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
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
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7
uint32_t IRAM_ATTR HOT millis()
Definition core.cpp:27
std::string get_mac_address()
Get the device MAC address as a string, in lowercase hex notation.
Definition helpers.cpp:726