mirror of
https://github.com/esphome/esphome.git
synced 2025-09-28 08:02:23 +01:00
add-black (#1593)
* Add black Update pre commit Update pre commit add empty line * Format with black
This commit is contained in:
committed by
GitHub
parent
2b60b0f1fa
commit
69879920eb
@@ -10,23 +10,38 @@ import tzlocal
|
||||
import esphome.codegen as cg
|
||||
import esphome.config_validation as cv
|
||||
from esphome import automation
|
||||
from esphome.const import CONF_ID, CONF_CRON, CONF_DAYS_OF_MONTH, CONF_DAYS_OF_WEEK, CONF_HOURS, \
|
||||
CONF_MINUTES, CONF_MONTHS, CONF_ON_TIME, CONF_ON_TIME_SYNC, CONF_SECONDS, CONF_TIMEZONE, \
|
||||
CONF_TRIGGER_ID, CONF_AT, CONF_SECOND, CONF_HOUR, CONF_MINUTE
|
||||
from esphome.const import (
|
||||
CONF_ID,
|
||||
CONF_CRON,
|
||||
CONF_DAYS_OF_MONTH,
|
||||
CONF_DAYS_OF_WEEK,
|
||||
CONF_HOURS,
|
||||
CONF_MINUTES,
|
||||
CONF_MONTHS,
|
||||
CONF_ON_TIME,
|
||||
CONF_ON_TIME_SYNC,
|
||||
CONF_SECONDS,
|
||||
CONF_TIMEZONE,
|
||||
CONF_TRIGGER_ID,
|
||||
CONF_AT,
|
||||
CONF_SECOND,
|
||||
CONF_HOUR,
|
||||
CONF_MINUTE,
|
||||
)
|
||||
from esphome.core import coroutine, coroutine_with_priority
|
||||
from esphome.automation import Condition
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
CODEOWNERS = ['@OttoWinter']
|
||||
CODEOWNERS = ["@OttoWinter"]
|
||||
IS_PLATFORM_COMPONENT = True
|
||||
|
||||
time_ns = cg.esphome_ns.namespace('time')
|
||||
RealTimeClock = time_ns.class_('RealTimeClock', cg.PollingComponent)
|
||||
CronTrigger = time_ns.class_('CronTrigger', automation.Trigger.template(), cg.Component)
|
||||
SyncTrigger = time_ns.class_('SyncTrigger', automation.Trigger.template(), cg.Component)
|
||||
ESPTime = time_ns.struct('ESPTime')
|
||||
TimeHasTimeCondition = time_ns.class_('TimeHasTimeCondition', Condition)
|
||||
time_ns = cg.esphome_ns.namespace("time")
|
||||
RealTimeClock = time_ns.class_("RealTimeClock", cg.PollingComponent)
|
||||
CronTrigger = time_ns.class_("CronTrigger", automation.Trigger.template(), cg.Component)
|
||||
SyncTrigger = time_ns.class_("SyncTrigger", automation.Trigger.template(), cg.Component)
|
||||
ESPTime = time_ns.struct("ESPTime")
|
||||
TimeHasTimeCondition = time_ns.class_("TimeHasTimeCondition", Condition)
|
||||
|
||||
|
||||
def _tz_timedelta(td):
|
||||
@@ -34,12 +49,12 @@ def _tz_timedelta(td):
|
||||
offset_minute = int(abs(td.total_seconds() / 60)) % 60
|
||||
offset_second = int(abs(td.total_seconds())) % 60
|
||||
if offset_hour == 0 and offset_minute == 0 and offset_second == 0:
|
||||
return '0'
|
||||
return "0"
|
||||
if offset_minute == 0 and offset_second == 0:
|
||||
return f'{offset_hour}'
|
||||
return f"{offset_hour}"
|
||||
if offset_second == 0:
|
||||
return f'{offset_hour}:{offset_minute}'
|
||||
return f'{offset_hour}:{offset_minute}:{offset_second}'
|
||||
return f"{offset_hour}:{offset_minute}"
|
||||
return f"{offset_hour}:{offset_minute}:{offset_second}"
|
||||
|
||||
|
||||
# https://stackoverflow.com/a/16804556/8924614
|
||||
@@ -52,8 +67,9 @@ def _week_of_month(dt):
|
||||
|
||||
def _tz_dst_str(dt):
|
||||
td = datetime.timedelta(hours=dt.hour, minutes=dt.minute, seconds=dt.second)
|
||||
return 'M{}.{}.{}/{}'.format(dt.month, _week_of_month(dt), dt.isoweekday() % 7,
|
||||
_tz_timedelta(td))
|
||||
return "M{}.{}.{}/{}".format(
|
||||
dt.month, _week_of_month(dt), dt.isoweekday() % 7, _tz_timedelta(td)
|
||||
)
|
||||
|
||||
|
||||
def _safe_tzname(tz, dt):
|
||||
@@ -62,16 +78,17 @@ def _safe_tzname(tz, dt):
|
||||
# For example: 'Europe/Saratov' returns '+04'
|
||||
# Work around it by using a generic name for the timezone
|
||||
if not all(c in string.ascii_letters for c in tzname):
|
||||
return 'TZ'
|
||||
return "TZ"
|
||||
return tzname
|
||||
|
||||
|
||||
def _non_dst_tz(tz, dt):
|
||||
tzname = _safe_tzname(tz, dt)
|
||||
utcoffset = tz.utcoffset(dt)
|
||||
_LOGGER.info("Detected timezone '%s' with UTC offset %s",
|
||||
tzname, _tz_timedelta(utcoffset))
|
||||
tzbase = '{}{}'.format(tzname, _tz_timedelta(-1 * utcoffset))
|
||||
_LOGGER.info(
|
||||
"Detected timezone '%s' with UTC offset %s", tzname, _tz_timedelta(utcoffset)
|
||||
)
|
||||
tzbase = "{}{}".format(tzname, _tz_timedelta(-1 * utcoffset))
|
||||
return tzbase
|
||||
|
||||
|
||||
@@ -112,15 +129,22 @@ def convert_tz(pytz_obj):
|
||||
dst_ends_utc = transition_times[idx2]
|
||||
dst_ends_local = dst_ends_utc + utcoffset_on
|
||||
|
||||
tzbase = '{}{}'.format(tzname_off, _tz_timedelta(-1 * utcoffset_off))
|
||||
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",
|
||||
tzname_off, _tz_timedelta(utcoffset_off),
|
||||
dst_begins_local.strftime("%d %B %X"),
|
||||
dst_ends_local.strftime("%d %B %X"))
|
||||
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",
|
||||
tzname_off,
|
||||
_tz_timedelta(utcoffset_off),
|
||||
dst_begins_local.strftime("%d %B %X"),
|
||||
dst_ends_local.strftime("%d %B %X"),
|
||||
)
|
||||
return tzbase + tzext
|
||||
|
||||
|
||||
@@ -129,7 +153,7 @@ def detect_tz():
|
||||
tz = tzlocal.get_localzone()
|
||||
except pytz.exceptions.UnknownTimeZoneError:
|
||||
_LOGGER.warning("Could not auto-detect timezone. Using UTC...")
|
||||
return 'UTC'
|
||||
return "UTC"
|
||||
|
||||
return convert_tz(tz)
|
||||
|
||||
@@ -146,42 +170,61 @@ def _parse_cron_int(value, special_mapping, message):
|
||||
|
||||
|
||||
def _parse_cron_part(part, min_value, max_value, special_mapping):
|
||||
if part in ('*', '?'):
|
||||
if part in ("*", "?"):
|
||||
return set(range(min_value, max_value + 1))
|
||||
if '/' in part:
|
||||
data = part.split('/')
|
||||
if "/" in part:
|
||||
data = part.split("/")
|
||||
if len(data) > 2:
|
||||
raise cv.Invalid("Can't have more than two '/' in one time expression, got {}"
|
||||
.format(part))
|
||||
raise cv.Invalid(
|
||||
"Can't have more than two '/' in one time expression, got {}".format(
|
||||
part
|
||||
)
|
||||
)
|
||||
offset, repeat = data
|
||||
offset_n = 0
|
||||
if offset:
|
||||
offset_n = _parse_cron_int(offset, special_mapping,
|
||||
"Offset for '/' time expression must be an integer, got {}")
|
||||
offset_n = _parse_cron_int(
|
||||
offset,
|
||||
special_mapping,
|
||||
"Offset for '/' time expression must be an integer, got {}",
|
||||
)
|
||||
|
||||
try:
|
||||
repeat_n = int(repeat)
|
||||
except ValueError:
|
||||
# pylint: disable=raise-missing-from
|
||||
raise cv.Invalid("Repeat for '/' time expression must be an integer, got {}"
|
||||
.format(repeat))
|
||||
raise cv.Invalid(
|
||||
"Repeat for '/' time expression must be an integer, got {}".format(
|
||||
repeat
|
||||
)
|
||||
)
|
||||
return set(range(offset_n, max_value + 1, repeat_n))
|
||||
if '-' in part:
|
||||
data = part.split('-')
|
||||
if "-" in part:
|
||||
data = part.split("-")
|
||||
if len(data) > 2:
|
||||
raise cv.Invalid("Can't have more than two '-' in range time expression '{}'"
|
||||
.format(part))
|
||||
raise cv.Invalid(
|
||||
"Can't have more than two '-' in range time expression '{}'".format(
|
||||
part
|
||||
)
|
||||
)
|
||||
begin, end = data
|
||||
begin_n = _parse_cron_int(begin, special_mapping, "Number for time range must be integer, "
|
||||
"got {}")
|
||||
end_n = _parse_cron_int(end, special_mapping, "Number for time range must be integer, "
|
||||
"got {}")
|
||||
begin_n = _parse_cron_int(
|
||||
begin, special_mapping, "Number for time range must be integer, " "got {}"
|
||||
)
|
||||
end_n = _parse_cron_int(
|
||||
end, special_mapping, "Number for time range must be integer, " "got {}"
|
||||
)
|
||||
if end_n < begin_n:
|
||||
return set(range(end_n, max_value + 1)) | set(range(min_value, begin_n + 1))
|
||||
return set(range(begin_n, end_n + 1))
|
||||
|
||||
return {_parse_cron_int(part, special_mapping, "Number for time expression must be an "
|
||||
"integer, got {}")}
|
||||
return {
|
||||
_parse_cron_int(
|
||||
part,
|
||||
special_mapping,
|
||||
"Number for time expression must be an " "integer, got {}",
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
def cron_expression_validator(name, min_value, max_value, special_mapping=None):
|
||||
@@ -190,42 +233,71 @@ def cron_expression_validator(name, min_value, max_value, special_mapping=None):
|
||||
for v in value:
|
||||
if not isinstance(v, int):
|
||||
raise cv.Invalid(
|
||||
"Expected integer for {} '{}', got {}".format(v, name, type(v)))
|
||||
"Expected integer for {} '{}', got {}".format(v, name, type(v))
|
||||
)
|
||||
if v < min_value or v > max_value:
|
||||
raise cv.Invalid(
|
||||
"{} {} is out of range (min={} max={}).".format(name, v, min_value,
|
||||
max_value))
|
||||
"{} {} is out of range (min={} max={}).".format(
|
||||
name, v, min_value, max_value
|
||||
)
|
||||
)
|
||||
return list(sorted(value))
|
||||
value = cv.string(value)
|
||||
values = set()
|
||||
for part in value.split(','):
|
||||
for part in value.split(","):
|
||||
values |= _parse_cron_part(part, min_value, max_value, special_mapping)
|
||||
return validator(list(values))
|
||||
|
||||
return validator
|
||||
|
||||
|
||||
validate_cron_seconds = cron_expression_validator('seconds', 0, 60)
|
||||
validate_cron_minutes = cron_expression_validator('minutes', 0, 59)
|
||||
validate_cron_hours = cron_expression_validator('hours', 0, 23)
|
||||
validate_cron_days_of_month = cron_expression_validator('days of month', 1, 31)
|
||||
validate_cron_months = cron_expression_validator('months', 1, 12, {
|
||||
'JAN': 1, 'FEB': 2, 'MAR': 3, 'APR': 4, 'MAY': 5, 'JUN': 6, 'JUL': 7, 'AUG': 8,
|
||||
'SEP': 9, 'OCT': 10, 'NOV': 11, 'DEC': 12
|
||||
})
|
||||
validate_cron_days_of_week = cron_expression_validator('days of week', 1, 7, {
|
||||
'SUN': 1, 'MON': 2, 'TUE': 3, 'WED': 4, 'THU': 5, 'FRI': 6, 'SAT': 7
|
||||
})
|
||||
CRON_KEYS = [CONF_SECONDS, CONF_MINUTES, CONF_HOURS, CONF_DAYS_OF_MONTH, CONF_MONTHS,
|
||||
CONF_DAYS_OF_WEEK]
|
||||
validate_cron_seconds = cron_expression_validator("seconds", 0, 60)
|
||||
validate_cron_minutes = cron_expression_validator("minutes", 0, 59)
|
||||
validate_cron_hours = cron_expression_validator("hours", 0, 23)
|
||||
validate_cron_days_of_month = cron_expression_validator("days of month", 1, 31)
|
||||
validate_cron_months = cron_expression_validator(
|
||||
"months",
|
||||
1,
|
||||
12,
|
||||
{
|
||||
"JAN": 1,
|
||||
"FEB": 2,
|
||||
"MAR": 3,
|
||||
"APR": 4,
|
||||
"MAY": 5,
|
||||
"JUN": 6,
|
||||
"JUL": 7,
|
||||
"AUG": 8,
|
||||
"SEP": 9,
|
||||
"OCT": 10,
|
||||
"NOV": 11,
|
||||
"DEC": 12,
|
||||
},
|
||||
)
|
||||
validate_cron_days_of_week = cron_expression_validator(
|
||||
"days of week",
|
||||
1,
|
||||
7,
|
||||
{"SUN": 1, "MON": 2, "TUE": 3, "WED": 4, "THU": 5, "FRI": 6, "SAT": 7},
|
||||
)
|
||||
CRON_KEYS = [
|
||||
CONF_SECONDS,
|
||||
CONF_MINUTES,
|
||||
CONF_HOURS,
|
||||
CONF_DAYS_OF_MONTH,
|
||||
CONF_MONTHS,
|
||||
CONF_DAYS_OF_WEEK,
|
||||
]
|
||||
|
||||
|
||||
def validate_cron_raw(value):
|
||||
value = cv.string(value)
|
||||
value = value.split(' ')
|
||||
value = value.split(" ")
|
||||
if len(value) != 6:
|
||||
raise cv.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),
|
||||
@@ -243,9 +315,9 @@ def validate_time_at(value):
|
||||
CONF_HOURS: [value[CONF_HOUR]],
|
||||
CONF_MINUTES: [value[CONF_MINUTE]],
|
||||
CONF_SECONDS: [value[CONF_SECOND]],
|
||||
CONF_DAYS_OF_MONTH: validate_cron_days_of_month('*'),
|
||||
CONF_MONTHS: validate_cron_months('*'),
|
||||
CONF_DAYS_OF_WEEK: validate_cron_days_of_week('*'),
|
||||
CONF_DAYS_OF_MONTH: validate_cron_days_of_month("*"),
|
||||
CONF_MONTHS: validate_cron_months("*"),
|
||||
CONF_DAYS_OF_WEEK: validate_cron_days_of_week("*"),
|
||||
}
|
||||
|
||||
|
||||
@@ -282,23 +354,30 @@ def validate_tz(value):
|
||||
return convert_tz(pytz_obj)
|
||||
|
||||
|
||||
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_id(CronTrigger),
|
||||
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),
|
||||
cv.Optional(CONF_ON_TIME_SYNC): automation.validate_automation({
|
||||
cv.GenerateID(CONF_TRIGGER_ID): cv.declare_id(SyncTrigger),
|
||||
}),
|
||||
}).extend(cv.polling_component_schema('15min'))
|
||||
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_id(CronTrigger),
|
||||
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,
|
||||
),
|
||||
cv.Optional(CONF_ON_TIME_SYNC): automation.validate_automation(
|
||||
{
|
||||
cv.GenerateID(CONF_TRIGGER_ID): cv.declare_id(SyncTrigger),
|
||||
}
|
||||
),
|
||||
}
|
||||
).extend(cv.polling_component_schema("15min"))
|
||||
|
||||
|
||||
@coroutine
|
||||
@@ -338,13 +417,19 @@ def register_time(time_var, config):
|
||||
|
||||
@coroutine_with_priority(100.0)
|
||||
def to_code(config):
|
||||
cg.add_define('USE_TIME')
|
||||
cg.add_define("USE_TIME")
|
||||
cg.add_global(time_ns.using)
|
||||
|
||||
|
||||
@automation.register_condition('time.has_time', TimeHasTimeCondition, cv.Schema({
|
||||
cv.GenerateID(): cv.use_id(RealTimeClock),
|
||||
}))
|
||||
@automation.register_condition(
|
||||
"time.has_time",
|
||||
TimeHasTimeCondition,
|
||||
cv.Schema(
|
||||
{
|
||||
cv.GenerateID(): cv.use_id(RealTimeClock),
|
||||
}
|
||||
),
|
||||
)
|
||||
def time_has_time_to_code(config, condition_id, template_arg, args):
|
||||
paren = yield cg.get_variable(config[CONF_ID])
|
||||
yield cg.new_Pvariable(condition_id, template_arg, paren)
|
||||
|
Reference in New Issue
Block a user