diff --git a/esphome/components/text/text_sensor/__init__.py b/esphome/components/text/text_sensor/__init__.py new file mode 100644 index 00000000000..5e45f101939 --- /dev/null +++ b/esphome/components/text/text_sensor/__init__.py @@ -0,0 +1,25 @@ +import esphome.codegen as cg +from esphome.components import text_sensor +import esphome.config_validation as cv +from esphome.const import CONF_SOURCE_ID + +from .. import Text, text_ns + +TextTextSensor = text_ns.class_("TextTextSensor", text_sensor.TextSensor, cg.Component) + + +CONFIG_SCHEMA = ( + text_sensor.text_sensor_schema(TextTextSensor) + .extend( + { + cv.Required(CONF_SOURCE_ID): cv.use_id(Text), + } + ) + .extend(cv.COMPONENT_SCHEMA) +) + + +async def to_code(config): + source = await cg.get_variable(config[CONF_SOURCE_ID]) + var = await text_sensor.new_text_sensor(config, source) + await cg.register_component(var, config) diff --git a/esphome/components/text/text_sensor/text_text_sensor.cpp b/esphome/components/text/text_sensor/text_text_sensor.cpp new file mode 100644 index 00000000000..50504c605ea --- /dev/null +++ b/esphome/components/text/text_sensor/text_text_sensor.cpp @@ -0,0 +1,16 @@ +#include "text_text_sensor.h" +#include "esphome/core/log.h" + +namespace esphome::text { + +static const char *const TAG = "text.text_sensor"; + +void TextTextSensor::setup() { + this->source_->add_on_state_callback([this](const std::string &value) { this->publish_state(value); }); + if (this->source_->has_state()) + this->publish_state(this->source_->state); +} + +void TextTextSensor::dump_config() { LOG_TEXT_SENSOR("", "Text Text Sensor", this); } + +} // namespace esphome::text diff --git a/esphome/components/text/text_sensor/text_text_sensor.h b/esphome/components/text/text_sensor/text_text_sensor.h new file mode 100644 index 00000000000..fd70ea3451a --- /dev/null +++ b/esphome/components/text/text_sensor/text_text_sensor.h @@ -0,0 +1,19 @@ +#pragma once + +#include "../text.h" +#include "esphome/core/component.h" +#include "esphome/components/text_sensor/text_sensor.h" + +namespace esphome::text { + +class TextTextSensor : public text_sensor::TextSensor, public Component { + public: + explicit TextTextSensor(Text *source) : source_(source) {} + void setup() override; + void dump_config() override; + + protected: + Text *source_; +}; + +} // namespace esphome::text diff --git a/tests/components/text/common.yaml b/tests/components/text/common.yaml index 26618be03a7..561d17143f4 100644 --- a/tests/components/text/common.yaml +++ b/tests/components/text/common.yaml @@ -23,3 +23,8 @@ text: min_length: 8 max_length: 32 mode: password + +text_sensor: + - platform: text + name: "Test Text State" + source_id: test_text