1
0
mirror of https://github.com/esphome/esphome.git synced 2025-09-26 15:12:21 +01:00

Text sensor schema generator similar to sensor (#3172)

This commit is contained in:
Jesse Hills
2022-02-08 17:23:45 +13:00
committed by GitHub
parent ad43d6a5bc
commit 69856286e8
25 changed files with 176 additions and 298 deletions

View File

@@ -3,7 +3,9 @@ import esphome.config_validation as cv
from esphome import automation
from esphome.components import mqtt
from esphome.const import (
CONF_ENTITY_CATEGORY,
CONF_FILTERS,
CONF_ICON,
CONF_ID,
CONF_ON_VALUE,
CONF_ON_RAW_VALUE,
@@ -14,6 +16,7 @@ from esphome.const import (
CONF_TO,
)
from esphome.core import CORE, coroutine_with_priority
from esphome.cpp_generator import MockObjClass
from esphome.cpp_helpers import setup_entity
from esphome.util import Registry
@@ -110,12 +113,10 @@ async def map_filter_to_code(config, filter_id):
)
icon = cv.icon
TEXT_SENSOR_SCHEMA = cv.ENTITY_BASE_SCHEMA.extend(cv.MQTT_COMPONENT_SCHEMA).extend(
{
cv.OnlyWith(CONF_MQTT_ID, "mqtt"): cv.declare_id(mqtt.MQTTTextSensor),
cv.GenerateID(): cv.declare_id(TextSensor),
cv.Optional(CONF_FILTERS): validate_filters,
cv.Optional(CONF_ON_VALUE): automation.validate_automation(
{
@@ -132,6 +133,29 @@ TEXT_SENSOR_SCHEMA = cv.ENTITY_BASE_SCHEMA.extend(cv.MQTT_COMPONENT_SCHEMA).exte
}
)
_UNDEF = object()
def text_sensor_schema(
klass: MockObjClass = _UNDEF,
icon: str = _UNDEF,
entity_category: str = _UNDEF,
) -> cv.Schema:
schema = TEXT_SENSOR_SCHEMA
if klass is not _UNDEF:
schema = schema.extend({cv.GenerateID(): cv.declare_id(klass)})
if icon is not _UNDEF:
schema = schema.extend({cv.Optional(CONF_ICON, default=icon): cv.icon})
if entity_category is not _UNDEF:
schema = schema.extend(
{
cv.Optional(
CONF_ENTITY_CATEGORY, default=entity_category
): cv.entity_category
}
)
return schema
async def build_filters(config):
return await cg.build_registry_list(FILTER_REGISTRY, config)
@@ -164,6 +188,12 @@ async def register_text_sensor(var, config):
await setup_text_sensor_core_(var, config)
async def new_text_sensor(config):
var = cg.new_Pvariable(config[CONF_ID])
await register_text_sensor(var, config)
return var
@coroutine_with_priority(100.0)
async def to_code(config):
cg.add_define("USE_TEXT_SENSOR")