mirror of
https://github.com/esphome/esphome.git
synced 2026-08-24 07:06:20 +00:00
[time] Remove C++ POSIX TZ string parser (#18383)
This commit is contained in:
@@ -1002,8 +1002,12 @@ message GetTimeResponse {
|
||||
option (no_delay) = true;
|
||||
|
||||
fixed32 epoch_seconds = 1;
|
||||
string timezone = 2;
|
||||
ParsedTimezone parsed_timezone = 3;
|
||||
// Deprecated in 2026.9.0: clients still send this string for older firmware,
|
||||
// but new firmware only reads parsed_timezone. Clients older than Home
|
||||
// Assistant 2026.3.0 that send only the string leave the device on its
|
||||
// codegen-configured timezone (or UTC).
|
||||
string timezone = 2 [deprecated = true];
|
||||
ParsedTimezone parsed_timezone = 3 [(track_presence) = true];
|
||||
}
|
||||
|
||||
// ==================== USER-DEFINES SERVICES ====================
|
||||
|
||||
@@ -1204,31 +1204,28 @@ void APIConnection::on_get_time_response(const GetTimeResponse &value) {
|
||||
if (homeassistant::global_homeassistant_time != nullptr) {
|
||||
homeassistant::global_homeassistant_time->set_epoch_time(value.epoch_seconds);
|
||||
#if defined(USE_HOMEASSISTANT_TIMEZONE) && defined(USE_TIME_TIMEZONE)
|
||||
if (!value.timezone.empty()) {
|
||||
// Check if the sender provided pre-parsed timezone data.
|
||||
// If std_offset is non-zero or DST rules are present, the parsed data was populated.
|
||||
// For UTC (all zeros), string parsing produces the same result, so the fallback is equivalent.
|
||||
// Apply only if the sender provided pre-parsed timezone data (Home Assistant 2026.3.0
|
||||
// and newer); field presence distinguishes a genuine all-zero UTC timezone from an
|
||||
// absent field. Older clients send only the deprecated timezone string, which is no
|
||||
// longer decoded; for them the device keeps its codegen-configured timezone.
|
||||
if (value.has_parsed_timezone) {
|
||||
const auto &pt = value.parsed_timezone;
|
||||
if (pt.std_offset_seconds != 0 || pt.dst_start.type != enums::DST_RULE_TYPE_NONE) {
|
||||
time::ParsedTimezone tz{};
|
||||
tz.std_offset_seconds = pt.std_offset_seconds;
|
||||
tz.dst_offset_seconds = pt.dst_offset_seconds;
|
||||
tz.dst_start.time_seconds = pt.dst_start.time_seconds;
|
||||
tz.dst_start.day = static_cast<uint16_t>(pt.dst_start.day);
|
||||
tz.dst_start.type = static_cast<time::DSTRuleType>(pt.dst_start.type);
|
||||
tz.dst_start.month = static_cast<uint8_t>(pt.dst_start.month);
|
||||
tz.dst_start.week = static_cast<uint8_t>(pt.dst_start.week);
|
||||
tz.dst_start.day_of_week = static_cast<uint8_t>(pt.dst_start.day_of_week);
|
||||
tz.dst_end.time_seconds = pt.dst_end.time_seconds;
|
||||
tz.dst_end.day = static_cast<uint16_t>(pt.dst_end.day);
|
||||
tz.dst_end.type = static_cast<time::DSTRuleType>(pt.dst_end.type);
|
||||
tz.dst_end.month = static_cast<uint8_t>(pt.dst_end.month);
|
||||
tz.dst_end.week = static_cast<uint8_t>(pt.dst_end.week);
|
||||
tz.dst_end.day_of_week = static_cast<uint8_t>(pt.dst_end.day_of_week);
|
||||
time::set_global_tz(tz);
|
||||
} else {
|
||||
homeassistant::global_homeassistant_time->set_timezone(value.timezone.c_str(), value.timezone.size());
|
||||
}
|
||||
time::ParsedTimezone tz{};
|
||||
tz.std_offset_seconds = pt.std_offset_seconds;
|
||||
tz.dst_offset_seconds = pt.dst_offset_seconds;
|
||||
tz.dst_start.time_seconds = pt.dst_start.time_seconds;
|
||||
tz.dst_start.day = static_cast<uint16_t>(pt.dst_start.day);
|
||||
tz.dst_start.type = static_cast<time::DSTRuleType>(pt.dst_start.type);
|
||||
tz.dst_start.month = static_cast<uint8_t>(pt.dst_start.month);
|
||||
tz.dst_start.week = static_cast<uint8_t>(pt.dst_start.week);
|
||||
tz.dst_start.day_of_week = static_cast<uint8_t>(pt.dst_start.day_of_week);
|
||||
tz.dst_end.time_seconds = pt.dst_end.time_seconds;
|
||||
tz.dst_end.day = static_cast<uint16_t>(pt.dst_end.day);
|
||||
tz.dst_end.type = static_cast<time::DSTRuleType>(pt.dst_end.type);
|
||||
tz.dst_end.month = static_cast<uint8_t>(pt.dst_end.month);
|
||||
tz.dst_end.week = static_cast<uint8_t>(pt.dst_end.week);
|
||||
tz.dst_end.day_of_week = static_cast<uint8_t>(pt.dst_end.day_of_week);
|
||||
time::set_global_tz(tz);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
@@ -116,4 +116,10 @@ extend google.protobuf.FieldOptions {
|
||||
// the per-byte loop when the upper bits are non-zero (the common case
|
||||
// for real MAC addresses, since OUIs occupy the top 24 bits).
|
||||
optional bool mac_address = 50019 [default=false];
|
||||
|
||||
// track_presence: Track whether this message-typed field was present on the wire.
|
||||
// Generates a `bool has_<field>{false};` member on the decoding side that is set
|
||||
// to true when the field arrives, so an all-default submessage can be told apart
|
||||
// from an absent one (e.g. a UTC ParsedTimezone, which is all zeros).
|
||||
optional bool track_presence = 50020 [default=false];
|
||||
}
|
||||
|
||||
@@ -1249,12 +1249,9 @@ bool ParsedTimezone::decode_length(uint32_t field_id, ProtoLengthDelimited value
|
||||
}
|
||||
bool GetTimeResponse::decode_length(uint32_t field_id, ProtoLengthDelimited value) {
|
||||
switch (field_id) {
|
||||
case 2: {
|
||||
this->timezone = StringRef(reinterpret_cast<const char *>(value.data()), value.size());
|
||||
break;
|
||||
}
|
||||
case 3:
|
||||
value.decode_to_message(this->parsed_timezone);
|
||||
this->has_parsed_timezone = true;
|
||||
break;
|
||||
default:
|
||||
return false;
|
||||
|
||||
@@ -1283,13 +1283,13 @@ class ParsedTimezone final : public ProtoDecodableMessage {
|
||||
class GetTimeResponse final : public ProtoDecodableMessage {
|
||||
public:
|
||||
static constexpr uint8_t MESSAGE_TYPE = 37;
|
||||
static constexpr uint8_t ESTIMATED_SIZE = 31;
|
||||
static constexpr uint8_t ESTIMATED_SIZE = 22;
|
||||
#ifdef HAS_PROTO_MESSAGE_DUMP
|
||||
const LogString *message_name() const override { return LOG_STR("get_time_response"); }
|
||||
#endif
|
||||
uint32_t epoch_seconds{0};
|
||||
StringRef timezone{};
|
||||
ParsedTimezone parsed_timezone{};
|
||||
bool has_parsed_timezone{false};
|
||||
#ifdef HAS_PROTO_MESSAGE_DUMP
|
||||
const char *dump_to(DumpBuffer &out) const override;
|
||||
#endif
|
||||
|
||||
@@ -1468,7 +1468,7 @@ const char *ParsedTimezone::dump_to(DumpBuffer &out) const {
|
||||
const char *GetTimeResponse::dump_to(DumpBuffer &out) const {
|
||||
MessageDumpHelper helper(out, ESPHOME_PSTR("GetTimeResponse"));
|
||||
dump_field(out, ESPHOME_PSTR("epoch_seconds"), this->epoch_seconds);
|
||||
dump_field(out, ESPHOME_PSTR("timezone"), this->timezone);
|
||||
dump_field(out, ESPHOME_PSTR("has_parsed_timezone"), this->has_parsed_timezone);
|
||||
out.append(2, ' ').append_p(ESPHOME_PSTR("parsed_timezone")).append(": ");
|
||||
this->parsed_timezone.dump_to(out);
|
||||
out.append("\n");
|
||||
|
||||
@@ -36,6 +36,7 @@ from esphome.const import (
|
||||
PLATFORM_RTL87XX,
|
||||
)
|
||||
from esphome.core import CORE, CoroPriority, EsphomeError, coroutine_with_priority
|
||||
from esphome.helpers import cpp_string_escape
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
@@ -411,17 +412,18 @@ async def setup_time_core_(time_var, config):
|
||||
cg.add_define("USE_TIME_TIMEZONE")
|
||||
|
||||
if CORE.is_host:
|
||||
# Host platform needs setenv("TZ")/tzset() for libc compatibility
|
||||
cg.add(time_var.set_timezone(timezone))
|
||||
else:
|
||||
# Embedded: pre-parse at codegen time, emit struct directly
|
||||
from aioesphomeapi.posix_tz import parse_posix_tz as parse_posix_tz_python
|
||||
# Host platform also needs setenv("TZ")/tzset() for libc compatibility
|
||||
cg.add(cg.RawExpression(f'setenv("TZ", {cpp_string_escape(timezone)}, 1)'))
|
||||
cg.add(cg.RawExpression("tzset()"))
|
||||
|
||||
try:
|
||||
parsed = parse_posix_tz_python(timezone)
|
||||
_emit_parsed_timezone_fields(parsed)
|
||||
except ValueError as e:
|
||||
raise EsphomeError(f"Invalid timezone: {timezone}") from e
|
||||
# Pre-parse at codegen time, emit struct directly
|
||||
from aioesphomeapi.posix_tz import parse_posix_tz as parse_posix_tz_python
|
||||
|
||||
try:
|
||||
parsed = parse_posix_tz_python(timezone)
|
||||
except ValueError as e:
|
||||
raise EsphomeError(f"Invalid timezone: {timezone}") from e
|
||||
_emit_parsed_timezone_fields(parsed)
|
||||
|
||||
for conf in config.get(CONF_ON_TIME, []):
|
||||
trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID], time_var)
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
#ifdef USE_TIME_TIMEZONE
|
||||
|
||||
#include "posix_tz.h"
|
||||
#include <cctype>
|
||||
#include <cstdio>
|
||||
|
||||
namespace esphome::time {
|
||||
@@ -18,17 +17,6 @@ const ParsedTimezone &get_global_tz() { return global_tz_; }
|
||||
|
||||
namespace internal {
|
||||
|
||||
// Remove before 2026.9.0: parse_uint, skip_tz_name, parse_offset, parse_dst_rule,
|
||||
// and parse_transition_time are only used by parse_posix_tz() (bridge code).
|
||||
static uint32_t parse_uint(const char *&p) {
|
||||
uint32_t value = 0;
|
||||
while (std::isdigit(static_cast<unsigned char>(*p))) {
|
||||
value = value * 10 + (*p - '0');
|
||||
p++;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
bool is_leap_year(int year) { return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0); }
|
||||
|
||||
// Get days in year (avoids duplicate is_leap_year calls)
|
||||
@@ -140,62 +128,6 @@ void __attribute__((noinline)) epoch_to_tm_utc(time_t epoch, struct tm *out_tm)
|
||||
out_tm->tm_isdst = 0;
|
||||
}
|
||||
|
||||
bool skip_tz_name(const char *&p) {
|
||||
if (*p == '<') {
|
||||
// Angle-bracket quoted name: <+07>, <-03>, <AEST>
|
||||
p++; // skip '<'
|
||||
while (*p && *p != '>') {
|
||||
p++;
|
||||
}
|
||||
if (*p == '>') {
|
||||
p++; // skip '>'
|
||||
return true;
|
||||
}
|
||||
return false; // Unterminated
|
||||
}
|
||||
|
||||
// Standard name: 3+ letters
|
||||
const char *start = p;
|
||||
while (*p && std::isalpha(static_cast<unsigned char>(*p))) {
|
||||
p++;
|
||||
}
|
||||
return (p - start) >= 3;
|
||||
}
|
||||
|
||||
int32_t __attribute__((noinline)) parse_offset(const char *&p) {
|
||||
int sign = 1;
|
||||
if (*p == '-') {
|
||||
sign = -1;
|
||||
p++;
|
||||
} else if (*p == '+') {
|
||||
p++;
|
||||
}
|
||||
|
||||
int hours = parse_uint(p);
|
||||
int minutes = 0;
|
||||
int seconds = 0;
|
||||
|
||||
if (*p == ':') {
|
||||
p++;
|
||||
minutes = parse_uint(p);
|
||||
if (*p == ':') {
|
||||
p++;
|
||||
seconds = parse_uint(p);
|
||||
}
|
||||
}
|
||||
|
||||
return sign * (hours * 3600 + minutes * 60 + seconds);
|
||||
}
|
||||
|
||||
// Helper to parse the optional /time suffix (reuses parse_offset logic)
|
||||
static void parse_transition_time(const char *&p, DSTRule &rule) {
|
||||
rule.time_seconds = 2 * 3600; // Default 02:00
|
||||
if (*p == '/') {
|
||||
p++;
|
||||
rule.time_seconds = parse_offset(p);
|
||||
}
|
||||
}
|
||||
|
||||
void __attribute__((noinline)) julian_to_month_day(int julian_day, int &out_month, int &out_day) {
|
||||
// J format: day 1-365, Feb 29 is NOT counted even in leap years
|
||||
// So day 60 is always March 1
|
||||
@@ -236,59 +168,6 @@ void __attribute__((noinline)) day_of_year_to_month_day(int day_of_year, int yea
|
||||
out_day = 31;
|
||||
}
|
||||
|
||||
bool parse_dst_rule(const char *&p, DSTRule &rule) {
|
||||
rule = {}; // Zero initialize
|
||||
|
||||
if (*p == 'M' || *p == 'm') {
|
||||
// M format: Mm.w.d (month.week.day)
|
||||
rule.type = DSTRuleType::MONTH_WEEK_DAY;
|
||||
p++;
|
||||
|
||||
rule.month = parse_uint(p);
|
||||
if (rule.month < 1 || rule.month > 12)
|
||||
return false;
|
||||
|
||||
if (*p++ != '.')
|
||||
return false;
|
||||
|
||||
rule.week = parse_uint(p);
|
||||
if (rule.week < 1 || rule.week > 5)
|
||||
return false;
|
||||
|
||||
if (*p++ != '.')
|
||||
return false;
|
||||
|
||||
rule.day_of_week = parse_uint(p);
|
||||
if (rule.day_of_week > 6)
|
||||
return false;
|
||||
|
||||
} else if (*p == 'J' || *p == 'j') {
|
||||
// J format: Jn (Julian day 1-365, not counting Feb 29)
|
||||
rule.type = DSTRuleType::JULIAN_NO_LEAP;
|
||||
p++;
|
||||
|
||||
rule.day = parse_uint(p);
|
||||
if (rule.day < 1 || rule.day > 365)
|
||||
return false;
|
||||
|
||||
} else if (std::isdigit(static_cast<unsigned char>(*p))) {
|
||||
// Plain number format: n (day 0-365, counting Feb 29)
|
||||
rule.type = DSTRuleType::DAY_OF_YEAR;
|
||||
|
||||
rule.day = parse_uint(p);
|
||||
if (rule.day > 365)
|
||||
return false;
|
||||
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Parse optional /time suffix
|
||||
parse_transition_time(p, rule);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// Calculate days from Jan 1 of given year to given month/day
|
||||
static int __attribute__((noinline)) days_from_year_start(int year, int month, int day) {
|
||||
int days = day - 1;
|
||||
@@ -373,83 +252,6 @@ bool __attribute__((noinline)) is_in_dst(time_t utc_epoch, const ParsedTimezone
|
||||
}
|
||||
}
|
||||
|
||||
// Remove before 2026.9.0: This parser is bridge code for backward compatibility with
|
||||
// older Home Assistant clients that send the timezone as a POSIX TZ string instead of
|
||||
// the pre-parsed ParsedTimezone protobuf struct. Once all clients send the struct
|
||||
// directly, this function and the parsing helpers above (skip_tz_name, parse_offset,
|
||||
// parse_dst_rule, parse_transition_time) can be removed.
|
||||
// See https://github.com/esphome/backlog/issues/91
|
||||
bool parse_posix_tz(const char *tz_string, ParsedTimezone &result) {
|
||||
if (!tz_string || !*tz_string) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const char *p = tz_string;
|
||||
|
||||
// Initialize result (dst_start/dst_end default to type=NONE, so has_dst() returns false)
|
||||
result.std_offset_seconds = 0;
|
||||
result.dst_offset_seconds = 0;
|
||||
result.dst_start = {};
|
||||
result.dst_end = {};
|
||||
|
||||
// Skip standard timezone name
|
||||
if (!internal::skip_tz_name(p)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Parse standard offset (required)
|
||||
if (!*p || (!std::isdigit(static_cast<unsigned char>(*p)) && *p != '+' && *p != '-')) {
|
||||
return false;
|
||||
}
|
||||
result.std_offset_seconds = internal::parse_offset(p);
|
||||
|
||||
// Check for DST name
|
||||
if (!*p) {
|
||||
return true; // No DST
|
||||
}
|
||||
|
||||
// If next char is comma, there's no DST name but there are rules (invalid)
|
||||
if (*p == ',') {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if there's something that looks like a DST name start
|
||||
// (letter or angle bracket). If not, treat as trailing garbage and return success.
|
||||
if (!std::isalpha(static_cast<unsigned char>(*p)) && *p != '<') {
|
||||
return true; // No DST, trailing characters ignored
|
||||
}
|
||||
|
||||
if (!internal::skip_tz_name(p)) {
|
||||
return false; // Invalid DST name (started but malformed)
|
||||
}
|
||||
|
||||
// Optional DST offset (default is std - 1 hour)
|
||||
if (*p && *p != ',' && (std::isdigit(static_cast<unsigned char>(*p)) || *p == '+' || *p == '-')) {
|
||||
result.dst_offset_seconds = internal::parse_offset(p);
|
||||
} else {
|
||||
result.dst_offset_seconds = result.std_offset_seconds - 3600;
|
||||
}
|
||||
|
||||
// Parse DST rules (required when DST name is present)
|
||||
if (*p != ',') {
|
||||
// DST name without rules - treat as no DST since we can't determine transitions
|
||||
return true;
|
||||
}
|
||||
|
||||
p++;
|
||||
if (!internal::parse_dst_rule(p, result.dst_start)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Second rule is required per POSIX
|
||||
if (*p != ',') {
|
||||
return false;
|
||||
}
|
||||
p++;
|
||||
// has_dst() now returns true since dst_start.type was set by parse_dst_rule
|
||||
return internal::parse_dst_rule(p, result.dst_end);
|
||||
}
|
||||
|
||||
// Format a POSIX offset (positive = west) as "+HHMM" / "-HHMM" for display.
|
||||
// Convention: negate POSIX sign so east-of-UTC is positive (ISO 8601 / RFC 2822).
|
||||
void format_designation(int32_t posix_offset, char *buf, size_t buf_size) {
|
||||
|
||||
@@ -39,28 +39,6 @@ struct ParsedTimezone {
|
||||
/// Format a POSIX offset as "+HHMM"/"-HHMM" into buf (must be >= 6 bytes).
|
||||
void format_designation(int32_t posix_offset, char *buf, size_t buf_size);
|
||||
|
||||
/// Parse a POSIX TZ string into a ParsedTimezone struct.
|
||||
///
|
||||
/// @deprecated Remove before 2026.9.0 (bridge code for backward compatibility).
|
||||
/// This parser only exists so that older Home Assistant clients that send the timezone
|
||||
/// as a string (instead of the pre-parsed ParsedTimezone protobuf struct) can still
|
||||
/// set the timezone on the device. Once all clients are updated to send the struct
|
||||
/// directly, this function and all internal parsing helpers will be removed.
|
||||
/// See https://github.com/esphome/backlog/issues/91
|
||||
///
|
||||
/// Supports formats like:
|
||||
/// - "EST5" (simple offset, no DST)
|
||||
/// - "EST5EDT,M3.2.0,M11.1.0" (with DST, M-format rules)
|
||||
/// - "CST6CDT,M3.2.0/2,M11.1.0/2" (with transition times)
|
||||
/// - "<+07>-7" (angle-bracket notation for special names)
|
||||
/// - "IST-5:30" (half-hour offsets)
|
||||
/// - "EST5EDT,J60,J300" (J-format: Julian day without leap day)
|
||||
/// - "EST5EDT,60,300" (plain day number: day of year with leap day)
|
||||
/// @param tz_string The POSIX TZ string to parse
|
||||
/// @param result Output: the parsed timezone data
|
||||
/// @return true if parsing succeeded, false on error
|
||||
bool parse_posix_tz(const char *tz_string, ParsedTimezone &result);
|
||||
|
||||
/// Convert a UTC epoch to local time using the parsed timezone.
|
||||
/// This replaces libc's localtime() to avoid scanf dependency.
|
||||
/// @param utc_epoch Unix timestamp in UTC
|
||||
@@ -70,8 +48,7 @@ bool parse_posix_tz(const char *tz_string, ParsedTimezone &result);
|
||||
bool epoch_to_local_tm(time_t utc_epoch, const ParsedTimezone &tz, struct tm *out_tm);
|
||||
|
||||
/// Set the global timezone used by epoch_to_local_tm() when called without a timezone.
|
||||
/// This is called by RealTimeClock::apply_timezone_() to enable ESPTime::from_epoch_local()
|
||||
/// to work without libc's localtime().
|
||||
/// This enables ESPTime::from_epoch_local() to work without libc's localtime().
|
||||
void set_global_tz(const ParsedTimezone &tz);
|
||||
|
||||
/// Get the global timezone.
|
||||
@@ -84,29 +61,9 @@ const ParsedTimezone &get_global_tz();
|
||||
bool is_in_dst(time_t utc_epoch, const ParsedTimezone &tz);
|
||||
|
||||
// Internal helper functions exposed for testing.
|
||||
// Remove before 2026.9.0: skip_tz_name, parse_offset, parse_dst_rule are only
|
||||
// used by parse_posix_tz() which is bridge code for backward compatibility.
|
||||
// The remaining helpers (epoch_to_tm_utc, day_of_week, days_in_month, etc.)
|
||||
// are used by the conversion functions and will stay.
|
||||
|
||||
namespace internal {
|
||||
|
||||
/// Skip a timezone name (letters or <...> quoted format)
|
||||
/// @param p Pointer to current position, updated on return
|
||||
/// @return true if a valid name was found
|
||||
bool skip_tz_name(const char *&p);
|
||||
|
||||
/// Parse an offset in format [-]hh[:mm[:ss]]
|
||||
/// @param p Pointer to current position, updated on return
|
||||
/// @return Offset in seconds
|
||||
int32_t parse_offset(const char *&p);
|
||||
|
||||
/// Parse a DST rule in format Mm.w.d[/time], Jn[/time], or n[/time]
|
||||
/// @param p Pointer to current position, updated on return
|
||||
/// @param rule Output: the parsed rule
|
||||
/// @return true if parsing succeeded
|
||||
bool parse_dst_rule(const char *&p, DSTRule &rule);
|
||||
|
||||
/// Convert Julian day (J format, 1-365 not counting Feb 29) to month/day
|
||||
/// @param julian_day Day number 1-365
|
||||
/// @param[out] month Output: month 1-12
|
||||
|
||||
@@ -107,35 +107,4 @@ void RealTimeClock::synchronize_epoch_(uint32_t epoch) {
|
||||
this->time_sync_callback_.call();
|
||||
}
|
||||
|
||||
#ifdef USE_TIME_TIMEZONE
|
||||
void RealTimeClock::apply_timezone_(const char *tz) {
|
||||
ParsedTimezone parsed{};
|
||||
|
||||
// Handle null or empty input - use UTC
|
||||
if (tz == nullptr || *tz == '\0') {
|
||||
// Skip if already UTC
|
||||
if (!get_global_tz().has_dst() && get_global_tz().std_offset_seconds == 0) {
|
||||
return;
|
||||
}
|
||||
set_global_tz(parsed);
|
||||
return;
|
||||
}
|
||||
|
||||
#ifdef USE_HOST
|
||||
// On host platform, also set TZ environment variable for libc compatibility
|
||||
setenv("TZ", tz, 1);
|
||||
tzset();
|
||||
#endif
|
||||
|
||||
// Parse the POSIX TZ string using our custom parser
|
||||
if (!parse_posix_tz(tz, parsed)) {
|
||||
ESP_LOGW(TAG, "Failed to parse timezone: %s", tz);
|
||||
return;
|
||||
}
|
||||
|
||||
// Set global timezone for all time conversions
|
||||
set_global_tz(parsed);
|
||||
}
|
||||
#endif
|
||||
|
||||
} // namespace esphome::time
|
||||
|
||||
@@ -15,37 +15,13 @@ namespace esphome::time {
|
||||
/// 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
|
||||
/// The timezone is pre-parsed into a ParsedTimezone struct: at codegen time from the YAML
|
||||
/// configuration, or at runtime by API clients that send the parsed struct (Home Assistant
|
||||
/// 2026.3.0 and newer). See set_global_tz() in posix_tz.h.
|
||||
class RealTimeClock : public PollingComponent {
|
||||
public:
|
||||
explicit RealTimeClock();
|
||||
|
||||
#ifdef USE_TIME_TIMEZONE
|
||||
/// Set the time zone from a POSIX TZ string.
|
||||
void set_timezone(const char *tz) { this->apply_timezone_(tz); }
|
||||
|
||||
/// Set the time zone from a character buffer with known length.
|
||||
/// The buffer does not need to be null-terminated.
|
||||
void set_timezone(const char *tz, size_t len) {
|
||||
if (tz == nullptr) {
|
||||
this->apply_timezone_(nullptr);
|
||||
return;
|
||||
}
|
||||
// Stack buffer - TZ strings from tzdata are typically short (< 50 chars)
|
||||
char buf[128];
|
||||
if (len >= sizeof(buf))
|
||||
len = sizeof(buf) - 1;
|
||||
memcpy(buf, tz, len);
|
||||
buf[len] = '\0';
|
||||
this->apply_timezone_(buf);
|
||||
}
|
||||
|
||||
/// Set the time zone from a std::string.
|
||||
void set_timezone(const std::string &tz) { this->apply_timezone_(tz.c_str()); }
|
||||
#endif
|
||||
|
||||
/// Get the time in the currently defined timezone.
|
||||
ESPTime now();
|
||||
|
||||
@@ -65,10 +41,6 @@ class RealTimeClock : public PollingComponent {
|
||||
/// Report a unix epoch as current time.
|
||||
void synchronize_epoch_(uint32_t epoch);
|
||||
|
||||
#ifdef USE_TIME_TIMEZONE
|
||||
void apply_timezone_(const char *tz);
|
||||
#endif
|
||||
|
||||
LazyCallbackManager<void()> time_sync_callback_;
|
||||
};
|
||||
|
||||
|
||||
@@ -498,6 +498,15 @@ def create_field_type_info(
|
||||
needs_encode: bool = True,
|
||||
) -> TypeInfo:
|
||||
"""Create the appropriate TypeInfo instance for a field, handling repeated fields and custom options."""
|
||||
if get_field_opt(field, pb.track_presence, False) and (
|
||||
field.label == FieldDescriptorProto.LABEL_REPEATED
|
||||
or field.type != 11
|
||||
or not needs_decode
|
||||
):
|
||||
raise ValueError(
|
||||
f"track_presence on field '{field.name}' has no effect; it requires "
|
||||
"a non-repeated message field in a message that is decoded"
|
||||
)
|
||||
if field.label == FieldDescriptorProto.LABEL_REPEATED:
|
||||
# Check if this is a packed_buffer field (zero-copy packed repeated)
|
||||
if get_field_opt(field, pb.packed_buffer, False):
|
||||
@@ -541,6 +550,8 @@ def create_field_type_info(
|
||||
return PointerToStringBufferType(field, None)
|
||||
|
||||
validate_field_type(field.type, field.name)
|
||||
if field.type == 11:
|
||||
return MessageType(field, needs_decode, needs_encode)
|
||||
return TYPE_INFO[field.type](field)
|
||||
|
||||
|
||||
@@ -937,9 +948,33 @@ class MessageType(TypeInfo):
|
||||
# runtime polymorphism through virtual function calls.
|
||||
return None
|
||||
|
||||
@property
|
||||
def public_content(self) -> list[str]:
|
||||
content = [self.class_member]
|
||||
if self._track_presence:
|
||||
content.append(f"bool has_{self.name}{{false}};")
|
||||
return content
|
||||
|
||||
@property
|
||||
def _track_presence(self) -> bool:
|
||||
# Presence is only observable on the decode side
|
||||
return self._needs_decode and get_field_opt(
|
||||
self._field, pb.track_presence, False
|
||||
)
|
||||
|
||||
@property
|
||||
def decode_length_content(self) -> str:
|
||||
# Custom decode that doesn't use templates
|
||||
if self._track_presence:
|
||||
# decode_to_message() cannot report failure, so setting the flag
|
||||
# afterwards only documents intent; a status-returning decode could
|
||||
# gate it for real without touching callers.
|
||||
return (
|
||||
f"case {self.number}:\n"
|
||||
f" value.decode_to_message(this->{self.field_name});\n"
|
||||
f" this->has_{self.name} = true;\n"
|
||||
f" break;"
|
||||
)
|
||||
return f"case {self.number}: value.decode_to_message(this->{self.field_name}); break;"
|
||||
|
||||
def dump(self, name: str) -> str:
|
||||
@@ -947,7 +982,10 @@ class MessageType(TypeInfo):
|
||||
|
||||
@property
|
||||
def dump_content(self) -> str:
|
||||
o = f'out.append(2, \' \').append_p(ESPHOME_PSTR("{self.name}")).append(": ");\n'
|
||||
o = ""
|
||||
if self._track_presence:
|
||||
o += f'dump_field(out, ESPHOME_PSTR("has_{self.name}"), this->has_{self.name});\n'
|
||||
o += f'out.append(2, \' \').append_p(ESPHOME_PSTR("{self.name}")).append(": ");\n'
|
||||
o += f"this->{self.field_name}.dump_to(out);\n"
|
||||
o += 'out.append("\\n");'
|
||||
return o
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,10 @@
|
||||
network:
|
||||
|
||||
api:
|
||||
|
||||
time:
|
||||
- platform: homeassistant
|
||||
# Angle-bracket name pins the explicit-timezone host codegen path
|
||||
# (setenv/tzset plus pre-parsed struct emission) with characters that
|
||||
# would break unescaped string interpolation.
|
||||
timezone: "<+07>-7"
|
||||
@@ -0,0 +1,20 @@
|
||||
esphome:
|
||||
name: get-time-tz-test
|
||||
host:
|
||||
api:
|
||||
logger:
|
||||
|
||||
time:
|
||||
- platform: homeassistant
|
||||
id: ha_time
|
||||
|
||||
sensor:
|
||||
# Exposes the standard offset of the effective timezone so the test can
|
||||
# observe which GetTimeResponse messages changed it
|
||||
- platform: template
|
||||
name: "TZ Offset"
|
||||
id: tz_offset
|
||||
accuracy_decimals: 0
|
||||
update_interval: 100ms
|
||||
lambda: |-
|
||||
return time::get_global_tz().std_offset_seconds;
|
||||
@@ -0,0 +1,67 @@
|
||||
"""Integration test for GetTimeResponse parsed_timezone presence handling."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from aioesphomeapi import connection as api_connection
|
||||
from aioesphomeapi.api_pb2 import GetTimeResponse
|
||||
import pytest
|
||||
|
||||
from .state_utils import SensorTracker, build_key_to_entity_mapping
|
||||
from .types import APIClientConnectedFactory, RunCompiledFunction
|
||||
|
||||
# 2024-01-01 00:00:00 UTC
|
||||
EPOCH = 1704067200
|
||||
# POSIX offsets are positive west of UTC, so UTC+7 is -25200 and UTC-5 is 18000
|
||||
UTC_PLUS_7 = -25200
|
||||
UTC_MINUS_5 = 18000
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_api_get_time_response_timezone(
|
||||
yaml_config: str,
|
||||
run_compiled: RunCompiledFunction,
|
||||
api_client_connected: APIClientConnectedFactory,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""A present parsed_timezone is applied even when all zero; an absent one is ignored."""
|
||||
# The client answers the device's own GetTimeRequest with the host timezone;
|
||||
# strip the parsed field from that reply so only the messages sent below
|
||||
# can change the device timezone.
|
||||
monkeypatch.setattr(api_connection, "_build_parsed_tz_proto", lambda tz: None)
|
||||
|
||||
async with run_compiled(yaml_config), api_client_connected() as client:
|
||||
entities, _ = await client.list_entities_services()
|
||||
tracker = SensorTracker(["tz_offset"])
|
||||
tracker.key_to_sensor = build_key_to_entity_mapping(entities, ["tz_offset"])
|
||||
client.subscribe_states(tracker.on_state)
|
||||
|
||||
await tracker.await_change(tracker.expect_any("tz_offset"), "tz_offset")
|
||||
initial = tracker.sensor_states["tz_offset"][-1]
|
||||
# Pick a zone that differs from the codegen default so the change is visible
|
||||
target = UTC_PLUS_7 if initial != UTC_PLUS_7 else UTC_MINUS_5
|
||||
|
||||
# Present, non-zero: applied
|
||||
future = tracker.expect("tz_offset", target)
|
||||
resp = GetTimeResponse(epoch_seconds=EPOCH)
|
||||
resp.parsed_timezone.std_offset_seconds = target
|
||||
resp.parsed_timezone.dst_offset_seconds = target
|
||||
client._connection.send_messages((resp,))
|
||||
await tracker.await_change(future, "tz_offset")
|
||||
|
||||
# Absent (legacy client with only the deprecated string): ignored, and in
|
||||
# particular not mistaken for an all-zero UTC zone
|
||||
future = tracker.expect("tz_offset", 0)
|
||||
resp = GetTimeResponse(epoch_seconds=EPOCH, timezone="UTC0")
|
||||
client._connection.send_messages((resp,))
|
||||
await tracker.await_must_not_change(future, "tz_offset", timeout=1.0)
|
||||
assert tracker.sensor_states["tz_offset"][-1] == target
|
||||
# Retire the expectation so it cannot swallow the first matching state
|
||||
# meant for the next phase
|
||||
future.cancel()
|
||||
|
||||
# Present but all zero (genuine UTC): applied
|
||||
future = tracker.expect("tz_offset", 0)
|
||||
resp = GetTimeResponse(epoch_seconds=EPOCH)
|
||||
resp.parsed_timezone.SetInParent()
|
||||
client._connection.send_messages((resp,))
|
||||
await tracker.await_change(future, "tz_offset")
|
||||
Reference in New Issue
Block a user