Skip to content

Commit

Permalink
Add round sensor filter (esphome#5532)
Browse files Browse the repository at this point in the history
  • Loading branch information
jesserockz authored Oct 14, 2023
1 parent da3e390 commit 7ddcdab
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 0 deletions.
18 changes: 18 additions & 0 deletions esphome/components/sensor/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,7 @@ def sensor_entity_category(value):
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_
Expand Down Expand Up @@ -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)

Expand Down
9 changes: 9 additions & 0 deletions esphome/components/sensor/filter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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
9 changes: 9 additions & 0 deletions esphome/components/sensor/filter.h
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit 7ddcdab

Please sign in to comment.