[text_sensor] Use register_apply_action for text_sensor.template.publish (#19539)

This commit is contained in:
J. Nick Koston
2026-09-23 16:55:58 -05:00
committed by GitHub
parent 4e2d1cd7fc
commit 01f9416a79
4 changed files with 13 additions and 24 deletions
@@ -1,7 +1,6 @@
from esphome import automation
import esphome.codegen as cg
from esphome.components import text_sensor
from esphome.components.text_sensor import TextSensorPublishAction
import esphome.config_validation as cv
from esphome.const import CONF_DEVICE_CLASS, CONF_ID, CONF_LAMBDA, CONF_STATE
@@ -38,20 +37,13 @@ async def to_code(config):
cg.add(var.set_template(template_))
@automation.register_action(
automation.register_apply_action(
"text_sensor.template.publish",
TextSensorPublishAction,
cv.Schema(
{
cv.Required(CONF_ID): cv.use_id(text_sensor.TextSensor),
cv.Required(CONF_STATE): cv.templatable(cv.string_strict),
}
),
synchronous=True,
automation.ApplyField(CONF_STATE, "publish_state", cg.std_string),
)
async def text_sensor_template_publish_to_code(config, action_id, template_arg, args):
paren = await cg.get_variable(config[CONF_ID])
var = cg.new_Pvariable(action_id, template_arg, paren)
template_ = await cg.templatable(config[CONF_STATE], args, cg.std_string)
cg.add(var.set_state(template_))
return var
@@ -43,9 +43,6 @@ text_sensor_ns = cg.esphome_ns.namespace("text_sensor")
TextSensor = text_sensor_ns.class_("TextSensor", cg.EntityBase)
TextSensorPtr = TextSensor.operator("ptr")
TextSensorPublishAction = text_sensor_ns.class_(
"TextSensorPublishAction", automation.Action
)
TextSensorStateCondition = text_sensor_ns.class_(
"TextSensorStateCondition", automation.Condition
)
@@ -34,15 +34,4 @@ template<typename... Ts> class TextSensorStateCondition final : public Condition
TextSensor *parent_;
};
template<typename... Ts> class TextSensorPublishAction final : public Action<Ts...> {
public:
TextSensorPublishAction(TextSensor *sensor) : sensor_(sensor) {}
TEMPLATABLE_VALUE(std::string, state)
void play(const Ts &...x) override { this->sensor_->publish_state(this->state_.value(x...)); }
protected:
TextSensor *sensor_;
};
} // namespace esphome::text_sensor
+11
View File
@@ -77,3 +77,14 @@ text_sensor:
return {x.substr(0, 10) + "..."};
}
return {x};
- platform: template
name: "Test Publish Action"
id: test_publish_action
on_value:
- text_sensor.template.publish:
id: test_map_single
state: "ON"
- text_sensor.template.publish:
id: test_map_single
state: !lambda 'return x + " again";'