1
0
mirror of https://github.com/esphome/esphome.git synced 2025-10-30 14:43:51 +00:00

Add support for time entities (#6399)

* Add time entities

* Add tests

* Add myself to datetime codeowners

* Fix publishing times with 0 values

* Log performing TimeCall

* Implement `on_time` trigger

* Rename var

* Fix initial value for time

* Add arg name for clarity

* Remove useless checks
This commit is contained in:
Jesse Hills
2024-04-09 13:46:35 +12:00
committed by GitHub
parent 3b6e8fa666
commit 76c5337987
37 changed files with 1251 additions and 23 deletions

View File

@@ -3,38 +3,50 @@ import esphome.codegen as cg
# import cpp_generator as cpp
import esphome.config_validation as cv
from esphome import automation
from esphome.components import mqtt
from esphome.components import mqtt, time
from esphome.const import (
CONF_ID,
CONF_ON_TIME,
CONF_ON_VALUE,
CONF_TIME_ID,
CONF_TRIGGER_ID,
CONF_TYPE,
CONF_MQTT_ID,
CONF_DATE,
CONF_TIME,
CONF_YEAR,
CONF_MONTH,
CONF_DAY,
CONF_SECOND,
CONF_HOUR,
CONF_MINUTE,
)
from esphome.core import CORE, coroutine_with_priority
from esphome.cpp_generator import MockObjClass
from esphome.cpp_helpers import setup_entity
CODEOWNERS = ["@rfdarter"]
CODEOWNERS = ["@rfdarter", "@jesserockz"]
IS_PLATFORM_COMPONENT = True
datetime_ns = cg.esphome_ns.namespace("datetime")
DateTimeBase = datetime_ns.class_("DateTimeBase", cg.EntityBase)
DateEntity = datetime_ns.class_("DateEntity", DateTimeBase)
TimeEntity = datetime_ns.class_("TimeEntity", DateTimeBase)
# Actions
DateSetAction = datetime_ns.class_("DateSetAction", automation.Action)
TimeSetAction = datetime_ns.class_("TimeSetAction", automation.Action)
DateTimeStateTrigger = datetime_ns.class_(
"DateTimeStateTrigger", automation.Trigger.template(cg.ESPTime)
)
OnTimeTrigger = datetime_ns.class_(
"OnTimeTrigger", automation.Trigger, cg.Component, cg.Parented.template(TimeEntity)
)
DATETIME_MODES = [
"DATE",
"TIME",
@@ -44,7 +56,6 @@ DATETIME_MODES = [
_DATETIME_SCHEMA = cv.Schema(
{
cv.OnlyWith(CONF_MQTT_ID, "mqtt"): cv.declare_id(mqtt.MQTTDatetimeComponent),
cv.Optional(CONF_ON_VALUE): automation.validate_automation(
{
cv.GenerateID(CONF_TRIGGER_ID): cv.declare_id(DateTimeStateTrigger),
@@ -57,6 +68,7 @@ _DATETIME_SCHEMA = cv.Schema(
def date_schema(class_: MockObjClass) -> cv.Schema:
schema = {
cv.GenerateID(): cv.declare_id(class_),
cv.OnlyWith(CONF_MQTT_ID, "mqtt"): cv.declare_id(mqtt.MQTTDateComponent),
cv.Optional(CONF_TYPE, default="DATE"): cv.one_of("DATE", upper=True),
}
return _DATETIME_SCHEMA.extend(schema)
@@ -65,7 +77,20 @@ def date_schema(class_: MockObjClass) -> cv.Schema:
def time_schema(class_: MockObjClass) -> cv.Schema:
schema = {
cv.GenerateID(): cv.declare_id(class_),
cv.OnlyWith(CONF_MQTT_ID, "mqtt"): cv.declare_id(mqtt.MQTTTimeComponent),
cv.Optional(CONF_TYPE, default="TIME"): cv.one_of("TIME", upper=True),
cv.Inclusive(
CONF_ON_TIME,
group_of_inclusion=CONF_ON_TIME,
msg="`on_time` and `time_id` must both be specified",
): automation.validate_automation(
{
cv.GenerateID(CONF_TRIGGER_ID): cv.declare_id(OnTimeTrigger),
}
),
cv.Inclusive(CONF_TIME_ID, group_of_inclusion=CONF_ON_TIME): cv.use_id(
time.RealTimeClock
),
}
return _DATETIME_SCHEMA.extend(schema)
@@ -88,6 +113,17 @@ async def setup_datetime_core_(var, config):
trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID], var)
await automation.build_automation(trigger, [(cg.ESPTime, "x")], conf)
rtc_id = config.get(CONF_TIME_ID)
rtc = None
if rtc_id is not None:
rtc = await cg.get_variable(rtc_id)
for conf in config.get(CONF_ON_TIME, []):
assert rtc is not None
trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID], rtc)
await automation.build_automation(trigger, [], conf)
await cg.register_component(trigger, conf)
await cg.register_parented(trigger, var)
async def register_datetime(var, config):
if not CORE.has_id(config[CONF_ID]):
@@ -109,18 +145,12 @@ async def to_code(config):
cg.add_global(datetime_ns.using)
OPERATION_BASE_SCHEMA = cv.Schema(
{
cv.Required(CONF_ID): cv.use_id(DateEntity),
}
)
@automation.register_action(
"datetime.date.set",
DateSetAction,
OPERATION_BASE_SCHEMA.extend(
cv.Schema(
{
cv.Required(CONF_ID): cv.use_id(DateEntity),
cv.Required(CONF_DATE): cv.Any(
cv.returning_lambda, cv.date_time(allowed_time=False)
),
@@ -144,3 +174,34 @@ async def datetime_date_set_to_code(config, action_id, template_arg, args):
)
cg.add(action_var.set_date(date_struct))
return action_var
@automation.register_action(
"datetime.time.set",
TimeSetAction,
cv.Schema(
{
cv.Required(CONF_ID): cv.use_id(TimeEntity),
cv.Required(CONF_TIME): cv.Any(
cv.returning_lambda, cv.date_time(allowed_date=False)
),
}
),
)
async def datetime_time_set_to_code(config, action_id, template_arg, args):
action_var = cg.new_Pvariable(action_id, template_arg)
await cg.register_parented(action_var, config[CONF_ID])
time_config = config[CONF_TIME]
if cg.is_template(time_config):
template_ = await cg.templatable(config[CONF_TIME], [], cg.ESPTime)
cg.add(action_var.set_time(template_))
else:
time_struct = cg.StructInitializer(
cg.ESPTime,
("second", time_config[CONF_SECOND]),
("minute", time_config[CONF_MINUTE]),
("hour", time_config[CONF_HOUR]),
)
cg.add(action_var.set_time(time_struct))
return action_var

View File

@@ -0,0 +1,156 @@
#include "time_entity.h"
#ifdef USE_DATETIME_TIME
#include "esphome/core/log.h"
namespace esphome {
namespace datetime {
static const char *const TAG = "datetime.time_entity";
void TimeEntity::publish_state() {
if (this->hour_ > 23) {
this->has_state_ = false;
ESP_LOGE(TAG, "Hour must be between 0 and 23");
return;
}
if (this->minute_ > 59) {
this->has_state_ = false;
ESP_LOGE(TAG, "Minute must be between 0 and 59");
return;
}
if (this->second_ > 59) {
this->has_state_ = false;
ESP_LOGE(TAG, "Second must be between 0 and 59");
return;
}
this->has_state_ = true;
ESP_LOGD(TAG, "'%s': Sending time %02d:%02d:%02d", this->get_name().c_str(), this->hour_, this->minute_,
this->second_);
this->state_callback_.call();
}
TimeCall TimeEntity::make_call() { return TimeCall(this); }
void TimeCall::validate_() {
if (this->hour_.has_value() && this->hour_ > 23) {
ESP_LOGE(TAG, "Hour must be between 0 and 23");
this->hour_.reset();
}
if (this->minute_.has_value() && this->minute_ > 59) {
ESP_LOGE(TAG, "Minute must be between 0 and 59");
this->minute_.reset();
}
if (this->second_.has_value() && this->second_ > 59) {
ESP_LOGE(TAG, "Second must be between 0 and 59");
this->second_.reset();
}
}
void TimeCall::perform() {
this->validate_();
ESP_LOGD(TAG, "'%s' - Setting", this->parent_->get_name().c_str());
if (this->hour_.has_value()) {
ESP_LOGD(TAG, " Hour: %d", *this->hour_);
}
if (this->minute_.has_value()) {
ESP_LOGD(TAG, " Minute: %d", *this->minute_);
}
if (this->second_.has_value()) {
ESP_LOGD(TAG, " Second: %d", *this->second_);
}
this->parent_->control(*this);
}
TimeCall &TimeCall::set_time(uint8_t hour, uint8_t minute, uint8_t second) {
this->hour_ = hour;
this->minute_ = minute;
this->second_ = second;
return *this;
};
TimeCall &TimeCall::set_time(ESPTime time) { return this->set_time(time.hour, time.minute, time.second); };
TimeCall &TimeCall::set_time(const std::string &time) {
ESPTime val{};
if (!ESPTime::strptime(time, val)) {
ESP_LOGE(TAG, "Could not convert the time string to an ESPTime object");
return *this;
}
return this->set_time(val);
}
TimeCall TimeEntityRestoreState::to_call(TimeEntity *time) {
TimeCall call = time->make_call();
call.set_time(this->hour, this->minute, this->second);
return call;
}
void TimeEntityRestoreState::apply(TimeEntity *time) {
time->hour_ = this->hour;
time->minute_ = this->minute;
time->second_ = this->second;
time->publish_state();
}
#ifdef USE_TIME
static const int MAX_TIMESTAMP_DRIFT = 900; // how far can the clock drift before we consider
// there has been a drastic time synchronization
void OnTimeTrigger::loop() {
if (!this->parent_->has_state()) {
return;
}
ESPTime time = this->rtc_->now();
if (!time.is_valid()) {
return;
}
if (this->last_check_.has_value()) {
if (*this->last_check_ > time && this->last_check_->timestamp - time.timestamp > MAX_TIMESTAMP_DRIFT) {
// We went back in time (a lot), probably caused by time synchronization
ESP_LOGW(TAG, "Time has jumped back!");
} else if (*this->last_check_ >= time) {
// already handled this one
return;
} else if (time > *this->last_check_ && time.timestamp - this->last_check_->timestamp > MAX_TIMESTAMP_DRIFT) {
// We went ahead in time (a lot), probably caused by time synchronization
ESP_LOGW(TAG, "Time has jumped ahead!");
this->last_check_ = time;
return;
}
while (true) {
this->last_check_->increment_second();
if (*this->last_check_ >= time)
break;
if (this->matches_(*this->last_check_)) {
this->trigger();
break;
}
}
}
this->last_check_ = time;
if (!time.fields_in_range()) {
ESP_LOGW(TAG, "Time is out of range!");
ESP_LOGD(TAG, "Second=%02u Minute=%02u Hour=%02u", time.second, time.minute, time.hour);
}
if (this->matches_(time))
this->trigger();
}
bool OnTimeTrigger::matches_(const ESPTime &time) const {
return time.is_valid() && time.hour == this->parent_->hour && time.minute == this->parent_->minute &&
time.second == this->parent_->second;
}
#endif
} // namespace datetime
} // namespace esphome
#endif // USE_DATETIME_TIME

View File

@@ -0,0 +1,137 @@
#pragma once
#include "esphome/core/defines.h"
#ifdef USE_DATETIME_TIME
#include "esphome/core/automation.h"
#include "esphome/core/helpers.h"
#include "esphome/core/time.h"
#include "datetime_base.h"
#ifdef USE_TIME
#include "esphome/components/time/real_time_clock.h"
#endif
namespace esphome {
namespace datetime {
#define LOG_DATETIME_TIME(prefix, type, obj) \
if ((obj) != nullptr) { \
ESP_LOGCONFIG(TAG, "%s%s '%s'", prefix, LOG_STR_LITERAL(type), (obj)->get_name().c_str()); \
if (!(obj)->get_icon().empty()) { \
ESP_LOGCONFIG(TAG, "%s Icon: '%s'", prefix, (obj)->get_icon().c_str()); \
} \
}
class TimeCall;
class TimeEntity;
struct TimeEntityRestoreState {
uint8_t hour;
uint8_t minute;
uint8_t second;
TimeCall to_call(TimeEntity *time);
void apply(TimeEntity *time);
} __attribute__((packed));
class TimeEntity : public DateTimeBase {
protected:
uint8_t hour_;
uint8_t minute_;
uint8_t second_;
public:
void publish_state();
TimeCall make_call();
ESPTime state_as_esptime() const override {
ESPTime obj;
obj.hour = this->hour_;
obj.minute = this->minute_;
obj.second = this->second_;
return obj;
}
const uint8_t &hour = hour_;
const uint8_t &minute = minute_;
const uint8_t &second = second_;
protected:
friend class TimeCall;
friend struct TimeEntityRestoreState;
virtual void control(const TimeCall &call) = 0;
};
class TimeCall {
public:
explicit TimeCall(TimeEntity *parent) : parent_(parent) {}
void perform();
TimeCall &set_time(uint8_t hour, uint8_t minute, uint8_t second);
TimeCall &set_time(ESPTime time);
TimeCall &set_time(const std::string &time);
TimeCall &set_hour(uint8_t hour) {
this->hour_ = hour;
return *this;
}
TimeCall &set_minute(uint8_t minute) {
this->minute_ = minute;
return *this;
}
TimeCall &set_second(uint8_t second) {
this->second_ = second;
return *this;
}
optional<uint8_t> get_hour() const { return this->hour_; }
optional<uint8_t> get_minute() const { return this->minute_; }
optional<uint8_t> get_second() const { return this->second_; }
protected:
void validate_();
TimeEntity *parent_;
optional<uint8_t> hour_;
optional<uint8_t> minute_;
optional<uint8_t> second_;
};
template<typename... Ts> class TimeSetAction : public Action<Ts...>, public Parented<TimeEntity> {
public:
TEMPLATABLE_VALUE(ESPTime, time)
void play(Ts... x) override {
auto call = this->parent_->make_call();
if (this->time_.has_value()) {
call.set_time(this->time_.value(x...));
}
call.perform();
}
};
#ifdef USE_TIME
class OnTimeTrigger : public Trigger<>, public Component, public Parented<TimeEntity> {
public:
explicit OnTimeTrigger(time::RealTimeClock *rtc) : rtc_(rtc) {}
void loop() override;
protected:
bool matches_(const ESPTime &time) const;
time::RealTimeClock *rtc_;
optional<ESPTime> last_check_;
};
#endif
} // namespace datetime
} // namespace esphome
#endif // USE_DATETIME_TIME