diff --git a/unit_tests/tests/test_sticky_pps.cpp b/unit_tests/tests/test_sticky_pps.cpp new file mode 100644 index 0000000000..d51a024934 --- /dev/null +++ b/unit_tests/tests/test_sticky_pps.cpp @@ -0,0 +1,46 @@ + +#include "pch.h" +// todo: should we unify code with deadband.h? + +template +class StickyValue { +public: + T get(T currentValue, T deadbandThreshold) { + // If we're within the deadband, be "sticky" with the previous value + T absError = absF(currentValue - m_lastValue); + + if (std::is_same::value) { + if (cisnan(currentValue)) + return currentValue; + if (cisnan(m_lastValue)) + m_lastValue = currentValue; + } + + // use current value if there's enough error + if (absError > deadbandThreshold) { + m_lastValue = currentValue; + } + + return m_lastValue; + } + +private: + T m_lastValue = 0; +}; + + +TEST(Sticky, PPS) { + StickyValue pps; + + float threshold = 0.5; + + EXPECT_EQ(1, pps.get(1, threshold)); + EXPECT_EQ(1, pps.get(1.2, threshold)); + EXPECT_EQ(1, pps.get(0.8, threshold)); + EXPECT_NEAR(2.2, pps.get(2.2, threshold), EPS4D); + + float expectedNaN = pps.get(NAN, threshold); + EXPECT_TRUE(cisnan(expectedNaN)); + + EXPECT_NEAR(33, pps.get(33, threshold), EPS4D); +} diff --git a/unit_tests/tests/tests.mk b/unit_tests/tests/tests.mk index b9f72f1d36..facd58460f 100644 --- a/unit_tests/tests/tests.mk +++ b/unit_tests/tests/tests.mk @@ -79,6 +79,7 @@ TESTS_SRC_CPP = \ tests/test_accel_enrichment.cpp \ tests/test_gpiochip.cpp \ tests/test_deadband.cpp \ + tests/test_sticky_pps.cpp \ tests/test_knock.cpp \ tests/test_lambda_monitor.cpp \ tests/sensor/basic_sensor.cpp \