1
0
mirror of https://github.com/esphome/esphome.git synced 2025-10-26 20:53:50 +00:00

Device class attribute for sensor component (#1525)

* Add constants for sensor device_class

* Add device_class attribute to sensor component

* Add device_class attribute to sensor class

* Add device_class to mhz19 temperature sensor

* Add device_class to sensor in api component

* Add test for device_class of sensor

* Rename DEVICE_CLASS_NONE to DEVICE_CLASS_EMPTY for consistency

* Make optional attributes of sensor component truly optional
This commit is contained in:
marecabo
2021-02-15 16:49:02 +01:00
committed by GitHub
parent a342302114
commit f95be6a0df
11 changed files with 117 additions and 12 deletions

View File

@@ -10,6 +10,9 @@ namespace sensor {
#define LOG_SENSOR(prefix, type, obj) \
if (obj != nullptr) { \
ESP_LOGCONFIG(TAG, "%s%s '%s'", prefix, type, obj->get_name().c_str()); \
if (!obj->get_device_class().empty()) { \
ESP_LOGCONFIG(TAG, "%s Device Class: '%s'", prefix, obj->get_device_class().c_str()); \
} \
ESP_LOGCONFIG(TAG, "%s Unit of Measurement: '%s'", prefix, obj->get_unit_of_measurement().c_str()); \
ESP_LOGCONFIG(TAG, "%s Accuracy Decimals: %d", prefix, obj->get_accuracy_decimals()); \
if (!obj->get_icon().empty()) { \
@@ -122,6 +125,12 @@ class Sensor : public Nameable {
*/
float state;
/// Manually set the Home Assistant device class (see sensor::device_class)
void set_device_class(const std::string &device_class);
/// Get the device class for this sensor, using the manual override if specified.
std::string get_device_class();
/** This member variable stores the current raw state of the sensor. Unlike .state,
* this will be updated immediately when publish_state is called.
*/
@@ -130,6 +139,14 @@ class Sensor : public Nameable {
/// Return whether this sensor has gotten a full state (that passed through all filters) yet.
bool has_state() const;
/** Override this to set the Home Assistant device class for this sensor.
*
* Return "" to disable this feature.
*
* @return The device class of this sensor, for example "temperature".
*/
virtual std::string device_class();
/** A unique ID for this sensor, empty for no unique id. See unique ID requirements:
* https://developers.home-assistant.io/docs/en/entity_registry_index.html#unique-id-requirements
*
@@ -174,6 +191,8 @@ class Sensor : public Nameable {
/// Return the accuracy in decimals for this sensor.
virtual int8_t accuracy_decimals(); // NOLINT
optional<std::string> device_class_{}; ///< Stores the override of the device class
uint32_t hash_base() override;
CallbackManager<void(float)> raw_callback_; ///< Storage for raw state callbacks.