mirror of
https://github.com/esphome/esphome.git
synced 2024-11-10 01:07:45 +01:00
Add round sensor filter (#5532)
This commit is contained in:
parent
da3e3903dd
commit
7ddcdab351
3 changed files with 36 additions and 0 deletions
|
@ -242,6 +242,7 @@ CalibrateLinearFilter = sensor_ns.class_("CalibrateLinearFilter", Filter)
|
|||
CalibratePolynomialFilter = sensor_ns.class_("CalibratePolynomialFilter", Filter)
|
||||
SensorInRangeCondition = sensor_ns.class_("SensorInRangeCondition", Filter)
|
||||
ClampFilter = sensor_ns.class_("ClampFilter", Filter)
|
||||
RoundFilter = sensor_ns.class_("RoundFilter", Filter)
|
||||
|
||||
validate_unit_of_measurement = cv.string_strict
|
||||
validate_accuracy_decimals = cv.int_
|
||||
|
@ -702,6 +703,23 @@ async def clamp_filter_to_code(config, filter_id):
|
|||
)
|
||||
|
||||
|
||||
@FILTER_REGISTRY.register(
|
||||
"round",
|
||||
RoundFilter,
|
||||
cv.maybe_simple_value(
|
||||
{
|
||||
cv.Required(CONF_ACCURACY_DECIMALS): cv.uint8_t,
|
||||
},
|
||||
key=CONF_ACCURACY_DECIMALS,
|
||||
),
|
||||
)
|
||||
async def round_filter_to_code(config, filter_id):
|
||||
return cg.new_Pvariable(
|
||||
filter_id,
|
||||
config[CONF_ACCURACY_DECIMALS],
|
||||
)
|
||||
|
||||
|
||||
async def build_filters(config):
|
||||
return await cg.build_registry_list(FILTER_REGISTRY, config)
|
||||
|
||||
|
|
|
@ -445,5 +445,14 @@ optional<float> ClampFilter::new_value(float value) {
|
|||
return value;
|
||||
}
|
||||
|
||||
RoundFilter::RoundFilter(uint8_t precision) : precision_(precision) {}
|
||||
optional<float> RoundFilter::new_value(float value) {
|
||||
if (std::isfinite(value)) {
|
||||
float accuracy_mult = powf(10.0f, this->precision_);
|
||||
return roundf(accuracy_mult * value) / accuracy_mult;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
} // namespace sensor
|
||||
} // namespace esphome
|
||||
|
|
|
@ -419,5 +419,14 @@ class ClampFilter : public Filter {
|
|||
float max_{NAN};
|
||||
};
|
||||
|
||||
class RoundFilter : public Filter {
|
||||
public:
|
||||
explicit RoundFilter(uint8_t precision);
|
||||
optional<float> new_value(float value) override;
|
||||
|
||||
protected:
|
||||
uint8_t precision_;
|
||||
};
|
||||
|
||||
} // namespace sensor
|
||||
} // namespace esphome
|
||||
|
|
Loading…
Reference in a new issue