ESPHome  2024.9.2
uptime_timestamp_sensor.cpp
Go to the documentation of this file.
2 
3 #ifdef USE_TIME
4 
5 #include "esphome/core/hal.h"
6 #include "esphome/core/helpers.h"
7 #include "esphome/core/log.h"
8 
9 namespace esphome {
10 namespace uptime {
11 
12 static const char *const TAG = "uptime.sensor";
13 
15  this->time_->add_on_time_sync_callback([this]() {
16  if (this->has_state_)
17  return; // No need to update the timestamp if it's already set
18 
19  auto now = this->time_->now();
20  const uint32_t ms = millis();
21  if (!now.is_valid())
22  return; // No need to update the timestamp if the time is not valid
23 
24  time_t timestamp = now.timestamp;
25  uint32_t seconds = ms / 1000;
26  timestamp -= seconds;
27  this->publish_state(timestamp);
28  });
29 }
32  LOG_SENSOR("", "Uptime Sensor", this);
33  ESP_LOGCONFIG(TAG, " Type: Timestamp");
34 }
35 
36 } // namespace uptime
37 } // namespace esphome
38 
39 #endif // USE_TIME
ESPTime now()
Get the time in the currently defined timezone.
void add_on_time_sync_callback(std::function< void()> callback)
uint32_t IRAM_ATTR HOT millis()
Definition: core.cpp:25
const char *const TAG
Definition: spi.cpp:8
void publish_state(float state)
Publish a new state to the front-end.
Definition: sensor.cpp:39
uint16_t timestamp
Definition: tt21100.cpp:14
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