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

Add attribute support to Home Assistant sensors (#1770)

Co-authored-by: Jesse Hills <3060199+jesserockz@users.noreply.github.com>
This commit is contained in:
Franck Nijhof
2021-05-17 01:16:22 +02:00
committed by GitHub
parent 9a7a205510
commit 5645be4e0f
19 changed files with 113 additions and 25 deletions

View File

@@ -2,6 +2,7 @@ import esphome.codegen as cg
import esphome.config_validation as cv
from esphome.components import sensor
from esphome.const import (
CONF_ATTRIBUTE,
CONF_ENTITY_ID,
CONF_ID,
ICON_EMPTY,
@@ -22,6 +23,7 @@ CONFIG_SCHEMA = sensor.sensor_schema(
{
cv.GenerateID(): cv.declare_id(HomeassistantSensor),
cv.Required(CONF_ENTITY_ID): cv.entity_id,
cv.Optional(CONF_ATTRIBUTE): cv.string,
}
)
@@ -32,3 +34,5 @@ def to_code(config):
yield sensor.register_sensor(var, config)
cg.add(var.set_entity_id(config[CONF_ENTITY_ID]))
if CONF_ATTRIBUTE in config:
cg.add(var.set_attribute(config[CONF_ATTRIBUTE]))

View File

@@ -8,7 +8,7 @@ namespace homeassistant {
static const char *TAG = "homeassistant.sensor";
void HomeassistantSensor::setup() {
api::global_api_server->subscribe_home_assistant_state(this->entity_id_, [this](std::string state) {
api::global_api_server->subscribe_home_assistant_state(this->entity_id_, this->attribute_, [this](std::string state) {
auto val = parse_float(state);
if (!val.has_value()) {
ESP_LOGW(TAG, "Can't convert '%s' to number!", state.c_str());
@@ -16,13 +16,21 @@ void HomeassistantSensor::setup() {
return;
}
ESP_LOGD(TAG, "'%s': Got state %.2f", this->entity_id_.c_str(), *val);
if (this->attribute_.has_value()) {
ESP_LOGD(TAG, "'%s::%s': Got attribute state %.2f", this->entity_id_.c_str(), this->attribute_.value().c_str(),
*val);
} else {
ESP_LOGD(TAG, "'%s': Got state %.2f", this->entity_id_.c_str(), *val);
}
this->publish_state(*val);
});
}
void HomeassistantSensor::dump_config() {
LOG_SENSOR("", "Homeassistant Sensor", this);
ESP_LOGCONFIG(TAG, " Entity ID: '%s'", this->entity_id_.c_str());
if (this->attribute_.has_value()) {
ESP_LOGCONFIG(TAG, " Attribute: '%s'", this->attribute_.value().c_str());
}
}
float HomeassistantSensor::get_setup_priority() const { return setup_priority::AFTER_CONNECTION; }

View File

@@ -9,12 +9,14 @@ namespace homeassistant {
class HomeassistantSensor : public sensor::Sensor, public Component {
public:
void set_entity_id(const std::string &entity_id) { entity_id_ = entity_id; }
void set_attribute(const std::string &attribute) { attribute_ = attribute; }
void setup() override;
void dump_config() override;
float get_setup_priority() const override;
protected:
std::string entity_id_;
optional<std::string> attribute_;
};
} // namespace homeassistant