Use proper schema for delta filter (#4723)

This commit is contained in:
Jesse Hills 2023-04-24 08:42:46 +12:00 committed by GitHub
parent bb05ba3d00
commit 327cd662b4
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -25,10 +25,12 @@ from esphome.const import (
CONF_STATE_CLASS, CONF_STATE_CLASS,
CONF_TO, CONF_TO,
CONF_TRIGGER_ID, CONF_TRIGGER_ID,
CONF_TYPE,
CONF_UNIT_OF_MEASUREMENT, CONF_UNIT_OF_MEASUREMENT,
CONF_WINDOW_SIZE, CONF_WINDOW_SIZE,
CONF_MQTT_ID, CONF_MQTT_ID,
CONF_FORCE_UPDATE, CONF_FORCE_UPDATE,
CONF_VALUE,
DEVICE_CLASS_APPARENT_POWER, DEVICE_CLASS_APPARENT_POWER,
DEVICE_CLASS_AQI, DEVICE_CLASS_AQI,
DEVICE_CLASS_ATMOSPHERIC_PRESSURE, DEVICE_CLASS_ATMOSPHERIC_PRESSURE,
@ -476,21 +478,38 @@ async def lambda_filter_to_code(config, filter_id):
return cg.new_Pvariable(filter_id, lambda_) return cg.new_Pvariable(filter_id, lambda_)
DELTA_SCHEMA = cv.Schema(
{
cv.Required(CONF_VALUE): cv.positive_float,
cv.Optional(CONF_TYPE, default="absolute"): cv.one_of(
"absolute", "percentage", lower=True
),
}
)
def validate_delta(config): def validate_delta(config):
try: try:
return (cv.positive_float(config), False) value = cv.positive_float(config)
return DELTA_SCHEMA({CONF_VALUE: value, CONF_TYPE: "absolute"})
except cv.Invalid: except cv.Invalid:
pass pass
try: try:
return (cv.percentage(config), True) value = cv.percentage(config)
return DELTA_SCHEMA({CONF_VALUE: value, CONF_TYPE: "percentage"})
except cv.Invalid: except cv.Invalid:
pass pass
raise cv.Invalid("Delta filter requires a positive number or percentage value.") raise cv.Invalid("Delta filter requires a positive number or percentage value.")
@FILTER_REGISTRY.register("delta", DeltaFilter, validate_delta) @FILTER_REGISTRY.register("delta", DeltaFilter, cv.Any(DELTA_SCHEMA, validate_delta))
async def delta_filter_to_code(config, filter_id): async def delta_filter_to_code(config, filter_id):
return cg.new_Pvariable(filter_id, *config) percentage = config[CONF_TYPE] == "percentage"
return cg.new_Pvariable(
filter_id,
config[CONF_VALUE],
percentage,
)
@FILTER_REGISTRY.register("or", OrFilter, validate_filters) @FILTER_REGISTRY.register("or", OrFilter, validate_filters)