mirror of
https://github.com/esphome/esphome.git
synced 2025-11-19 08:15:49 +00:00
Add map filter for text sensors (#2761)
This commit is contained in:
@@ -49,6 +49,7 @@ ToLowerFilter = text_sensor_ns.class_("ToLowerFilter", Filter)
|
||||
AppendFilter = text_sensor_ns.class_("AppendFilter", Filter)
|
||||
PrependFilter = text_sensor_ns.class_("PrependFilter", Filter)
|
||||
SubstituteFilter = text_sensor_ns.class_("SubstituteFilter", Filter)
|
||||
MapFilter = text_sensor_ns.class_("MapFilter", Filter)
|
||||
|
||||
|
||||
@FILTER_REGISTRY.register("lambda", LambdaFilter, cv.returning_lambda)
|
||||
@@ -79,26 +80,21 @@ async def prepend_filter_to_code(config, filter_id):
|
||||
return cg.new_Pvariable(filter_id, config)
|
||||
|
||||
|
||||
def validate_substitute(value):
|
||||
if isinstance(value, dict):
|
||||
return cv.Schema(
|
||||
{
|
||||
cv.Required(CONF_FROM): cv.string,
|
||||
cv.Required(CONF_TO): cv.string,
|
||||
}
|
||||
)(value)
|
||||
value = cv.string(value)
|
||||
if "->" not in value:
|
||||
raise cv.Invalid("Substitute mapping must contain '->'")
|
||||
a, b = value.split("->", 1)
|
||||
a, b = a.strip(), b.strip()
|
||||
return validate_substitute({CONF_FROM: cv.string(a), CONF_TO: cv.string(b)})
|
||||
def validate_mapping(value):
|
||||
if not isinstance(value, dict):
|
||||
value = cv.string(value)
|
||||
if "->" not in value:
|
||||
raise cv.Invalid("Mapping must contain '->'")
|
||||
a, b = value.split("->", 1)
|
||||
value = {CONF_FROM: a.strip(), CONF_TO: b.strip()}
|
||||
|
||||
return cv.Schema(
|
||||
{cv.Required(CONF_FROM): cv.string, cv.Required(CONF_TO): cv.string}
|
||||
)(value)
|
||||
|
||||
|
||||
@FILTER_REGISTRY.register(
|
||||
"substitute",
|
||||
SubstituteFilter,
|
||||
cv.All(cv.ensure_list(validate_substitute), cv.Length(min=2)),
|
||||
"substitute", SubstituteFilter, cv.ensure_list(validate_mapping)
|
||||
)
|
||||
async def substitute_filter_to_code(config, filter_id):
|
||||
from_strings = [conf[CONF_FROM] for conf in config]
|
||||
@@ -106,6 +102,14 @@ async def substitute_filter_to_code(config, filter_id):
|
||||
return cg.new_Pvariable(filter_id, from_strings, to_strings)
|
||||
|
||||
|
||||
@FILTER_REGISTRY.register("map", MapFilter, cv.ensure_list(validate_mapping))
|
||||
async def map_filter_to_code(config, filter_id):
|
||||
map_ = cg.std_ns.class_("map").template(cg.std_string, cg.std_string)
|
||||
return cg.new_Pvariable(
|
||||
filter_id, map_([(item[CONF_FROM], item[CONF_TO]) for item in config])
|
||||
)
|
||||
|
||||
|
||||
icon = cv.icon
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user