1
0
mirror of https://github.com/esphome/esphome.git synced 2025-09-28 16:12:24 +01:00

🏗 Merge C++ into python codebase (#504)

## Description:

Move esphome-core codebase into esphome (and a bunch of other refactors). See https://github.com/esphome/feature-requests/issues/97

Yes this is a shit ton of work and no there's no way to automate it :( But it will be worth it 👍

Progress:
- Core support (file copy etc): 80%
- Base Abstractions (light, switch): ~50%
- Integrations: ~10%
- Working? Yes, (but only with ported components).

Other refactors:
- Moves all codegen related stuff into a single class: `esphome.codegen` (imported as `cg`)
- Rework coroutine syntax
- Move from `component/platform.py` to `domain/component.py` structure as with HA
- Move all defaults out of C++ and into config validation.
- Remove `make_...` helpers from Application class. Reason: Merge conflicts with every single new integration.
- Pointer Variables are stored globally instead of locally in setup(). Reason: stack size limit.

Future work:
- Rework const.py - Move all `CONF_...` into a conf class (usage `conf.UPDATE_INTERVAL` vs `CONF_UPDATE_INTERVAL`). Reason: Less convoluted import block
- Enable loading from `custom_components` folder.

**Related issue (if applicable):** https://github.com/esphome/feature-requests/issues/97

**Pull request in [esphome-docs](https://github.com/esphome/esphome-docs) with documentation (if applicable):** esphome/esphome-docs#<esphome-docs PR number goes here>

## Checklist:
  - [ ] The code change is tested and works locally.
  - [ ] Tests have been added to verify that the new code works (under `tests/` folder).

If user exposed functionality or configuration variables are added/changed:
  - [ ] Documentation added/updated in [esphomedocs](https://github.com/OttoWinter/esphomedocs).
This commit is contained in:
Otto Winter
2019-04-17 12:06:00 +02:00
committed by GitHub
parent 049807e3ab
commit 6682c43dfa
817 changed files with 54156 additions and 10830 deletions

View File

@@ -1,28 +1,27 @@
import bisect
import datetime
import logging
import math
import voluptuous as vol
import pytz
import tzlocal
from esphome import automation
import esphome.codegen as cg
import esphome.config_validation as cv
from esphome import automation
from esphome.const import CONF_CRON, CONF_DAYS_OF_MONTH, CONF_DAYS_OF_WEEK, CONF_HOURS, \
CONF_MINUTES, CONF_MONTHS, CONF_ON_TIME, CONF_SECONDS, CONF_TIMEZONE, CONF_TRIGGER_ID, \
CONF_AT, CONF_SECOND, CONF_HOUR, CONF_MINUTE
from esphome.core import CORE
from esphome.cpp_generator import Pvariable, add
from esphome.cpp_types import App, Component, Trigger, esphome_ns
from esphome.core import coroutine
from esphome.py_compat import string_types
_LOGGER = logging.getLogger(__name__)
PLATFORM_SCHEMA = cv.PLATFORM_SCHEMA.extend({
IS_PLATFORM_COMPONENT = True
})
time_ns = esphome_ns.namespace('time')
RealTimeClockComponent = time_ns.class_('RealTimeClockComponent', Component)
CronTrigger = time_ns.class_('CronTrigger', Trigger.template(), Component)
time_ns = cg.esphome_ns.namespace('time')
RealTimeClock = time_ns.class_('RealTimeClock', cg.Component)
CronTrigger = time_ns.class_('CronTrigger', cg.Trigger.template(), cg.Component)
ESPTime = time_ns.struct('ESPTime')
@@ -56,72 +55,46 @@ def _tz_dst_str(dt):
def convert_tz(pytz_obj):
tz = pytz_obj
def _dst(dt, is_dst):
try:
return tz.dst(dt, is_dst=is_dst)
except TypeError: # stupid pytz...
return tz.dst(dt)
now = datetime.datetime.now()
first_january = datetime.datetime(year=now.year, month=1, day=1)
def _tzname(dt, is_dst):
try:
return tz.tzname(dt, is_dst=is_dst)
except TypeError: # stupid pytz...
return tz.tzname(dt)
def _utcoffset(dt, is_dst):
try:
return tz.utcoffset(dt, is_dst=is_dst)
except TypeError: # stupid pytz...
return tz.utcoffset(dt)
dst_begins = None
dst_tzname = None
dst_utcoffset = None
dst_ends = None
norm_tzname = None
norm_utcoffset = None
hour = datetime.timedelta(hours=1)
this_year = datetime.datetime.now().year
dt = datetime.datetime(year=this_year, month=1, day=1)
last_dst = None
while dt.year == this_year:
current_dst = _dst(dt, not last_dst)
is_dst = bool(current_dst)
if is_dst != last_dst:
if is_dst:
dst_begins = dt
dst_tzname = _tzname(dt, True)
dst_utcoffset = _utcoffset(dt, True)
else:
dst_ends = dt + hour
norm_tzname = _tzname(dt, False)
norm_utcoffset = _utcoffset(dt, False)
last_dst = is_dst
dt += hour
tzbase = '{}{}'.format(norm_tzname, _tz_timedelta(-1 * norm_utcoffset))
if dst_begins is None:
# No DST in this timezone
if not isinstance(tz, pytz.tzinfo.DstTzInfo):
tzname = tz.tzname(first_january)
utcoffset = tz.utcoffset(first_january)
_LOGGER.info("Detected timezone '%s' with UTC offset %s",
norm_tzname, _tz_timedelta(norm_utcoffset))
tzname, _tz_timedelta(utcoffset))
tzbase = '{}{}'.format(tzname, _tz_timedelta(-1 * utcoffset))
return tzbase
tzext = '{}{},{},{}'.format(dst_tzname, _tz_timedelta(-1 * dst_utcoffset),
_tz_dst_str(dst_begins), _tz_dst_str(dst_ends))
# pylint: disable=protected-access
transition_times = tz._utc_transition_times
transition_info = tz._transition_info
idx = max(0, bisect.bisect_right(transition_times, now))
idx1, idx2 = idx, idx + 1
dstoffset1 = transition_info[idx1][1]
if dstoffset1 == datetime.timedelta(seconds=0):
# Normalize to 1 being DST on
idx1, idx2 = idx + 1, idx + 2
utcoffset_on, _, tzname_on = transition_info[idx1]
utcoffset_off, _, tzname_off = transition_info[idx2]
dst_begins_utc = transition_times[idx1]
dst_begins_local = dst_begins_utc + utcoffset_off
dst_ends_utc = transition_times[idx2]
dst_ends_local = dst_ends_utc + utcoffset_on
tzbase = '{}{}'.format(tzname_off, _tz_timedelta(-1 * utcoffset_off))
tzext = '{}{},{},{}'.format(tzname_on, _tz_timedelta(-1 * utcoffset_on),
_tz_dst_str(dst_begins_local), _tz_dst_str(dst_ends_local))
_LOGGER.info("Detected timezone '%s' with UTC offset %s and daylight savings time from "
"%s to %s",
norm_tzname, _tz_timedelta(norm_utcoffset), dst_begins.strftime("%x %X"),
dst_ends.strftime("%x %X"))
tzname_off, _tz_timedelta(utcoffset_off), dst_begins_local.strftime("%x %X"),
dst_ends_local.strftime("%x %X"))
return tzbase + tzext
def detect_tz():
try:
import tzlocal
import pytz
except ImportError:
raise vol.Invalid("No timezone specified and 'tzlocal' not installed. To automatically "
"detect the timezone please install tzlocal (pip install tzlocal)")
try:
tz = tzlocal.get_localzone()
except pytz.exceptions.UnknownTimeZoneError:
@@ -138,7 +111,7 @@ def _parse_cron_int(value, special_mapping, message):
try:
return int(value)
except ValueError:
raise vol.Invalid(message.format(value))
raise cv.Invalid(message.format(value))
def _parse_cron_part(part, min_value, max_value, special_mapping):
@@ -147,8 +120,8 @@ def _parse_cron_part(part, min_value, max_value, special_mapping):
if '/' in part:
data = part.split('/')
if len(data) > 2:
raise vol.Invalid(u"Can't have more than two '/' in one time expression, got {}"
.format(part))
raise cv.Invalid(u"Can't have more than two '/' in one time expression, got {}"
.format(part))
offset, repeat = data
offset_n = 0
if offset:
@@ -158,14 +131,14 @@ def _parse_cron_part(part, min_value, max_value, special_mapping):
try:
repeat_n = int(repeat)
except ValueError:
raise vol.Invalid(u"Repeat for '/' time expression must be an integer, got {}"
.format(repeat))
raise cv.Invalid(u"Repeat for '/' time expression must be an integer, got {}"
.format(repeat))
return set(x for x in range(offset_n, max_value + 1, repeat_n))
if '-' in part:
data = part.split('-')
if len(data) > 2:
raise vol.Invalid(u"Can't have more than two '-' in range time expression '{}'"
.format(part))
raise cv.Invalid(u"Can't have more than two '-' in range time expression '{}'"
.format(part))
begin, end = data
begin_n = _parse_cron_int(begin, special_mapping, u"Number for time range must be integer, "
u"got {}")
@@ -185,10 +158,10 @@ def cron_expression_validator(name, min_value, max_value, special_mapping=None):
if isinstance(value, list):
for v in value:
if not isinstance(v, int):
raise vol.Invalid(
raise cv.Invalid(
"Expected integer for {} '{}', got {}".format(v, name, type(v)))
if v < min_value or v > max_value:
raise vol.Invalid(
raise cv.Invalid(
"{} {} is out of range (min={} max={}).".format(name, v, min_value,
max_value))
return list(sorted(value))
@@ -220,8 +193,8 @@ def validate_cron_raw(value):
value = cv.string(value)
value = value.split(' ')
if len(value) != 6:
raise vol.Invalid("Cron expression must consist of exactly 6 space-separated parts, "
"not {}".format(len(value)))
raise cv.Invalid("Cron expression must consist of exactly 6 space-separated parts, "
"not {}".format(len(value)))
seconds, minutes, hours, days_of_month, months, days_of_week = value
return {
CONF_SECONDS: validate_cron_seconds(seconds),
@@ -249,9 +222,9 @@ def validate_cron_keys(value):
if CONF_CRON in value:
for key in value.keys():
if key in CRON_KEYS:
raise vol.Invalid("Cannot use option {} when cron: is specified.".format(key))
raise cv.Invalid("Cannot use option {} when cron: is specified.".format(key))
if CONF_AT in value:
raise vol.Invalid("Cannot use option at with cron!")
raise cv.Invalid("Cannot use option at with cron!")
cron_ = value[CONF_CRON]
value = {x: value[x] for x in value if x != CONF_CRON}
value.update(cron_)
@@ -259,7 +232,7 @@ def validate_cron_keys(value):
if CONF_AT in value:
for key in value.keys():
if key in CRON_KEYS:
raise vol.Invalid("Cannot use option {} when at: is specified.".format(key))
raise cv.Invalid("Cannot use option {} when at: is specified.".format(key))
at_ = value[CONF_AT]
value = {x: value[x] for x in value if x != CONF_AT}
value.update(at_)
@@ -271,59 +244,55 @@ def validate_tz(value):
value = cv.string_strict(value)
try:
import pytz
return convert_tz(pytz.timezone(value))
except Exception: # pylint: disable=broad-except
return value
TIME_PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Optional(CONF_TIMEZONE, default=detect_tz): validate_tz,
vol.Optional(CONF_ON_TIME): automation.validate_automation({
TIME_SCHEMA = cv.Schema({
cv.Optional(CONF_TIMEZONE, default=detect_tz): validate_tz,
cv.Optional(CONF_ON_TIME): automation.validate_automation({
cv.GenerateID(CONF_TRIGGER_ID): cv.declare_variable_id(CronTrigger),
vol.Optional(CONF_SECONDS): validate_cron_seconds,
vol.Optional(CONF_MINUTES): validate_cron_minutes,
vol.Optional(CONF_HOURS): validate_cron_hours,
vol.Optional(CONF_DAYS_OF_MONTH): validate_cron_days_of_month,
vol.Optional(CONF_MONTHS): validate_cron_months,
vol.Optional(CONF_DAYS_OF_WEEK): validate_cron_days_of_week,
vol.Optional(CONF_CRON): validate_cron_raw,
vol.Optional(CONF_AT): validate_time_at,
cv.Optional(CONF_SECONDS): validate_cron_seconds,
cv.Optional(CONF_MINUTES): validate_cron_minutes,
cv.Optional(CONF_HOURS): validate_cron_hours,
cv.Optional(CONF_DAYS_OF_MONTH): validate_cron_days_of_month,
cv.Optional(CONF_MONTHS): validate_cron_months,
cv.Optional(CONF_DAYS_OF_WEEK): validate_cron_days_of_week,
cv.Optional(CONF_CRON): validate_cron_raw,
cv.Optional(CONF_AT): validate_time_at,
}, validate_cron_keys),
})
@coroutine
def setup_time_core_(time_var, config):
add(time_var.set_timezone(config[CONF_TIMEZONE]))
cg.add(time_var.set_timezone(config[CONF_TIMEZONE]))
for conf in config.get(CONF_ON_TIME, []):
rhs = App.register_component(time_var.Pmake_cron_trigger())
trigger = Pvariable(conf[CONF_TRIGGER_ID], rhs)
trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID], time_var)
seconds = conf.get(CONF_SECONDS, [x for x in range(0, 61)])
add(trigger.add_seconds(seconds))
cg.add(trigger.add_seconds(seconds))
minutes = conf.get(CONF_MINUTES, [x for x in range(0, 60)])
add(trigger.add_minutes(minutes))
cg.add(trigger.add_minutes(minutes))
hours = conf.get(CONF_HOURS, [x for x in range(0, 24)])
add(trigger.add_hours(hours))
cg.add(trigger.add_hours(hours))
days_of_month = conf.get(CONF_DAYS_OF_MONTH, [x for x in range(1, 32)])
add(trigger.add_days_of_month(days_of_month))
cg.add(trigger.add_days_of_month(days_of_month))
months = conf.get(CONF_MONTHS, [x for x in range(1, 13)])
add(trigger.add_months(months))
cg.add(trigger.add_months(months))
days_of_week = conf.get(CONF_DAYS_OF_WEEK, [x for x in range(1, 8)])
add(trigger.add_days_of_week(days_of_week))
cg.add(trigger.add_days_of_week(days_of_week))
automation.build_automations(trigger, [], conf)
yield automation.build_automation(trigger, [], conf)
def setup_time(time_var, config):
CORE.add_job(setup_time_core_, time_var, config)
@coroutine
def register_time(time_var, config):
yield setup_time_core_(time_var, config)
BUILD_FLAGS = '-DUSE_TIME'
def to_code(config):
cg.add_define('USE_TIME')
cg.add_global(time_ns.using)

View File

@@ -0,0 +1,79 @@
#include "automation.h"
#include "esphome/core/log.h"
namespace esphome {
namespace time {
static const char *TAG = "something.something";
void CronTrigger::add_second(uint8_t second) { this->seconds_[second] = true; }
void CronTrigger::add_minute(uint8_t minute) { this->minutes_[minute] = true; }
void CronTrigger::add_hour(uint8_t hour) { this->hours_[hour] = true; }
void CronTrigger::add_day_of_month(uint8_t day_of_month) { this->days_of_month_[day_of_month] = true; }
void CronTrigger::add_month(uint8_t month) { this->months_[month] = true; }
void CronTrigger::add_day_of_week(uint8_t day_of_week) { this->days_of_week_[day_of_week] = true; }
bool CronTrigger::matches(const ESPTime &time) {
return time.is_valid() && this->seconds_[time.second] && this->minutes_[time.minute] && this->hours_[time.hour] &&
this->days_of_month_[time.day_of_month] && this->months_[time.month] && this->days_of_week_[time.day_of_week];
}
void CronTrigger::loop() {
ESPTime time = this->rtc_->now();
if (!time.is_valid())
return;
if (this->last_check_.has_value()) {
if (*this->last_check_ >= time) {
// already handled this one
return;
}
while (true) {
this->last_check_->increment_second();
if (*this->last_check_ >= time)
break;
if (this->matches(*this->last_check_))
this->trigger();
}
}
this->last_check_ = time;
if (!time.in_range()) {
ESP_LOGW(TAG, "Time is out of range!");
ESP_LOGD(TAG, "Second=%02u Minute=%02u Hour=%02u DayOfWeek=%u DayOfMonth=%u DayOfYear=%u Month=%u time=%ld",
time.second, time.minute, time.hour, time.day_of_week, time.day_of_month, time.day_of_year, time.month,
time.time);
}
if (this->matches(time))
this->trigger();
}
CronTrigger::CronTrigger(RealTimeClock *rtc) : rtc_(rtc) {}
void CronTrigger::add_seconds(const std::vector<uint8_t> &seconds) {
for (uint8_t it : seconds)
this->add_second(it);
}
void CronTrigger::add_minutes(const std::vector<uint8_t> &minutes) {
for (uint8_t it : minutes)
this->add_minute(it);
}
void CronTrigger::add_hours(const std::vector<uint8_t> &hours) {
for (uint8_t it : hours)
this->add_hour(it);
}
void CronTrigger::add_days_of_month(const std::vector<uint8_t> &days_of_month) {
for (uint8_t it : days_of_month)
this->add_day_of_month(it);
}
void CronTrigger::add_months(const std::vector<uint8_t> &months) {
for (uint8_t it : months)
this->add_month(it);
}
void CronTrigger::add_days_of_week(const std::vector<uint8_t> &days_of_week) {
for (uint8_t it : days_of_week)
this->add_day_of_week(it);
}
float CronTrigger::get_setup_priority() const { return setup_priority::HARDWARE; }
} // namespace time
} // namespace esphome

View File

@@ -0,0 +1,41 @@
#pragma once
#include "esphome/core/component.h"
#include "esphome/core/automation.h"
#include "real_time_clock.h"
namespace esphome {
namespace time {
class CronTrigger : public Trigger<>, public Component {
public:
explicit CronTrigger(RealTimeClock *rtc);
void add_second(uint8_t second);
void add_seconds(const std::vector<uint8_t> &seconds);
void add_minute(uint8_t minute);
void add_minutes(const std::vector<uint8_t> &minutes);
void add_hour(uint8_t hour);
void add_hours(const std::vector<uint8_t> &hours);
void add_day_of_month(uint8_t day_of_month);
void add_days_of_month(const std::vector<uint8_t> &days_of_month);
void add_month(uint8_t month);
void add_months(const std::vector<uint8_t> &months);
void add_day_of_week(uint8_t day_of_week);
void add_days_of_week(const std::vector<uint8_t> &days_of_week);
bool matches(const ESPTime &time);
void loop() override;
float get_setup_priority() const override;
protected:
std::bitset<61> seconds_;
std::bitset<60> minutes_;
std::bitset<24> hours_;
std::bitset<32> days_of_month_;
std::bitset<13> months_;
std::bitset<8> days_of_week_;
RealTimeClock *rtc_;
optional<ESPTime> last_check_;
};
} // namespace time
} // namespace esphome

View File

@@ -1,24 +0,0 @@
from esphome.components import time as time_
import esphome.config_validation as cv
from esphome.const import CONF_ID
from esphome.cpp_generator import Pvariable
from esphome.cpp_helpers import setup_component
from esphome.cpp_types import App
DEPENDENCIES = ['api']
HomeAssistantTime = time_.time_ns.class_('HomeAssistantTime', time_.RealTimeClockComponent)
PLATFORM_SCHEMA = time_.TIME_PLATFORM_SCHEMA.extend({
cv.GenerateID(): cv.declare_variable_id(HomeAssistantTime),
}).extend(cv.COMPONENT_SCHEMA.schema)
def to_code(config):
rhs = App.make_homeassistant_time_component()
ha_time = Pvariable(config[CONF_ID], rhs)
time_.setup_time(ha_time, config)
setup_component(ha_time, config)
BUILD_FLAGS = '-DUSE_HOMEASSISTANT_TIME'

View File

@@ -0,0 +1,138 @@
#include "real_time_clock.h"
#include "esphome/core/log.h"
#include "lwip/opt.h"
#ifdef ARDUINO_ARCH_ESP8266
#include "sys/time.h"
#endif
namespace esphome {
namespace time {
static const char *TAG = "time";
RealTimeClock::RealTimeClock() = default;
ESPTime RealTimeClock::now() {
time_t t = ::time(nullptr);
struct tm *c_tm = ::localtime(&t);
return ESPTime::from_tm(c_tm, t);
}
ESPTime RealTimeClock::utcnow() {
time_t t = ::time(nullptr);
struct tm *c_tm = ::gmtime(&t);
return ESPTime::from_tm(c_tm, t);
}
void RealTimeClock::call_setup() {
this->setup_internal_();
setenv("TZ", this->timezone_.c_str(), 1);
tzset();
this->setup();
}
void RealTimeClock::synchronize_epoch_(uint32_t epoch) {
struct timeval timev {
.tv_sec = static_cast<time_t>(epoch), .tv_usec = 0,
};
timezone tz = {0, 0};
settimeofday(&timev, &tz);
auto time = this->now();
char buf[128];
time.strftime(buf, sizeof(buf), "%c");
ESP_LOGD(TAG, "Synchronized time: %s", buf);
}
size_t ESPTime::strftime(char *buffer, size_t buffer_len, const char *format) {
struct tm c_tm = this->to_c_tm();
return ::strftime(buffer, buffer_len, format, &c_tm);
}
ESPTime ESPTime::from_tm(struct tm *c_tm, time_t c_time) {
return ESPTime{.second = uint8_t(c_tm->tm_sec),
.minute = uint8_t(c_tm->tm_min),
.hour = uint8_t(c_tm->tm_hour),
.day_of_week = uint8_t(c_tm->tm_wday + 1),
.day_of_month = uint8_t(c_tm->tm_mday),
.day_of_year = uint16_t(c_tm->tm_yday + 1),
.month = uint8_t(c_tm->tm_mon + 1),
.year = uint16_t(c_tm->tm_year + 1900),
.is_dst = bool(c_tm->tm_isdst),
.time = c_time};
}
struct tm ESPTime::to_c_tm() {
struct tm c_tm = tm{.tm_sec = this->second,
.tm_min = this->minute,
.tm_hour = this->hour,
.tm_mday = this->day_of_month,
.tm_mon = this->month - 1,
.tm_year = this->year - 1900,
.tm_wday = this->day_of_week - 1,
.tm_yday = this->day_of_year - 1,
.tm_isdst = this->is_dst};
return c_tm;
}
std::string ESPTime::strftime(const std::string &format) {
std::string timestr;
timestr.resize(format.size() * 4);
struct tm c_tm = this->to_c_tm();
size_t len = ::strftime(&timestr[0], timestr.size(), format.c_str(), &c_tm);
while (len == 0) {
timestr.resize(timestr.size() * 2);
len = ::strftime(&timestr[0], timestr.size(), format.c_str(), &c_tm);
}
timestr.resize(len);
return timestr;
}
bool ESPTime::is_valid() const { return this->year >= 2018; }
template<typename T> bool increment_time_value(T &current, uint16_t begin, uint16_t end) {
current++;
if (current >= end) {
current = begin;
return true;
}
return false;
}
void ESPTime::increment_second() {
this->time++;
if (!increment_time_value(this->second, 0, 60))
return;
// second roll-over, increment minute
if (!increment_time_value(this->minute, 0, 60))
return;
// minute roll-over, increment hour
if (!increment_time_value(this->hour, 0, 24))
return;
// hour roll-over, increment day
increment_time_value(this->day_of_week, 1, 8);
static const uint8_t DAYS_IN_MONTH[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
uint8_t days_in_month = DAYS_IN_MONTH[this->month];
if (this->month == 2 && this->year % 4 == 0)
days_in_month = 29;
if (increment_time_value(this->day_of_month, 1, days_in_month + 1)) {
// day of month roll-over, increment month
increment_time_value(this->month, 1, 13);
}
uint16_t days_in_year = (this->year % 4 == 0) ? 366 : 365;
if (increment_time_value(this->day_of_year, 1, days_in_year + 1)) {
// day of year roll-over, increment year
this->year++;
}
}
bool ESPTime::operator<(ESPTime other) { return this->time < other.time; }
bool ESPTime::operator<=(ESPTime other) { return this->time <= other.time; }
bool ESPTime::operator==(ESPTime other) { return this->time == other.time; }
bool ESPTime::operator>=(ESPTime other) { return this->time >= other.time; }
bool ESPTime::operator>(ESPTime other) { return this->time > other.time; }
bool ESPTime::in_range() const {
return this->second < 61 && this->minute < 60 && this->hour < 24 && this->day_of_week > 0 && this->day_of_week < 8 &&
this->day_of_month > 0 && this->day_of_month < 32 && this->day_of_year > 0 && this->day_of_year < 367 &&
this->month > 0 && this->month < 13;
}
} // namespace time
} // namespace esphome

View File

@@ -0,0 +1,99 @@
#pragma once
#include "esphome/core/component.h"
#include <stdlib.h>
#include <time.h>
#include <bitset>
namespace esphome {
namespace time {
/// A more user-friendly version of struct tm from time.h
struct ESPTime {
/** seconds after the minute [0-60]
* @note second is generally 0-59; the extra range is to accommodate leap seconds.
*/
uint8_t second;
/// minutes after the hour [0-59]
uint8_t minute;
/// hours since midnight [0-23]
uint8_t hour;
/// day of the week; sunday=1 [1-7]
uint8_t day_of_week;
/// day of the month [1-31]
uint8_t day_of_month;
/// day of the year [1-366]
uint16_t day_of_year;
/// month; january=1 [1-12]
uint8_t month;
/// year
uint16_t year;
/// daylight savings time flag
bool is_dst;
/// unix epoch time (seconds since UTC Midnight January 1, 1970)
time_t time;
/** Convert this ESPTime struct to a null-terminated c string buffer as specified by the format argument.
* Up to buffer_len bytes are written.
*
* @see https://www.gnu.org/software/libc/manual/html_node/Formatting-Calendar-Time.html#index-strftime
*/
size_t strftime(char *buffer, size_t buffer_len, const char *format);
/** Convert this ESPTime struct to a string as specified by the format argument.
* @see https://www.gnu.org/software/libc/manual/html_node/Formatting-Calendar-Time.html#index-strftime
*
* @warning This method uses dynamically allocated strings which can cause heap fragmentation with some
* microcontrollers.
*/
std::string strftime(const std::string &format);
bool is_valid() const;
bool in_range() const;
static ESPTime from_tm(struct tm *c_tm, time_t c_time);
struct tm to_c_tm();
void increment_second();
bool operator<(ESPTime other);
bool operator<=(ESPTime other);
bool operator==(ESPTime other);
bool operator>=(ESPTime other);
bool operator>(ESPTime other);
};
/// The RealTimeClock class exposes common timekeeping functions via the device's local real-time clock.
///
/// \note
/// The C library (newlib) available on ESPs only supports TZ strings that specify an offset and DST info;
/// you cannot specify zone names or paths to zoneinfo files.
/// \see https://www.gnu.org/software/libc/manual/html_node/TZ-Variable.html
class RealTimeClock : public Component {
public:
explicit RealTimeClock();
/// Set the time zone.
void set_timezone(const std::string &tz) { this->timezone_ = tz; }
/// Get the time zone currently in use.
std::string get_timezone() { return this->timezone_; }
/// Get the time in the currently defined timezone.
ESPTime now();
/// Get the time without any time zone or DST corrections.
ESPTime utcnow();
void call_setup() override;
protected:
/// Report a unix epoch as current time.
void synchronize_epoch_(uint32_t epoch);
std::string timezone_{};
};
} // namespace time
} // namespace esphome

View File

@@ -1,30 +0,0 @@
import voluptuous as vol
from esphome.components import time as time_
import esphome.config_validation as cv
from esphome.const import CONF_ID, CONF_SERVERS
from esphome.cpp_generator import Pvariable, add
from esphome.cpp_helpers import setup_component
from esphome.cpp_types import App
SNTPComponent = time_.time_ns.class_('SNTPComponent', time_.RealTimeClockComponent)
PLATFORM_SCHEMA = time_.TIME_PLATFORM_SCHEMA.extend({
cv.GenerateID(): cv.declare_variable_id(SNTPComponent),
vol.Optional(CONF_SERVERS): vol.All(cv.ensure_list(cv.domain), vol.Length(min=1, max=3)),
}).extend(cv.COMPONENT_SCHEMA.schema)
def to_code(config):
rhs = App.make_sntp_component()
sntp = Pvariable(config[CONF_ID], rhs)
if CONF_SERVERS in config:
servers = config[CONF_SERVERS]
servers += [''] * (3 - len(servers))
add(sntp.set_servers(*servers))
time_.setup_time(sntp, config)
setup_component(sntp, config)
BUILD_FLAGS = '-DUSE_SNTP_COMPONENT'