From c6305f86c6b0cdcf55f333c3d4d002aeb18b7f6a Mon Sep 17 00:00:00 2001 From: Rohan Dhiman Date: Sat, 25 Nov 2023 20:26:06 -0500 Subject: [PATCH] Apply advanced filtering issue 243 --- .../sensors/driver/BarometerInternal.java | 23 ++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/src/main/java/de/dennisguse/opentracks/sensors/driver/BarometerInternal.java b/src/main/java/de/dennisguse/opentracks/sensors/driver/BarometerInternal.java index 8a405f720..0ef78c3ab 100644 --- a/src/main/java/de/dennisguse/opentracks/sensors/driver/BarometerInternal.java +++ b/src/main/java/de/dennisguse/opentracks/sensors/driver/BarometerInternal.java @@ -13,6 +13,11 @@ import de.dennisguse.opentracks.data.models.AtmosphericPressure; import de.dennisguse.opentracks.sensors.AltitudeSumManager; +import java.util.LinkedList; +import java.util.Queue; + + + public class BarometerInternal { private static final String TAG = BarometerInternal.class.getSimpleName(); @@ -21,6 +26,8 @@ public class BarometerInternal { private AltitudeSumManager observer; + private static final int FILTER_WINDOW_SIZE = 5; // Window size for the moving average filter + private Queue pressureReadings = new LinkedList<>(); private final SensorEventListener listener = new SensorEventListener() { @Override public void onSensorChanged(SensorEvent event) { @@ -29,7 +36,21 @@ public void onSensorChanged(SensorEvent event) { return; } - observer.onSensorValueChanged(AtmosphericPressure.ofHPA(event.values[0])); + // Add new reading to the queue + if (pressureReadings.size() >= FILTER_WINDOW_SIZE) { + pressureReadings.poll(); // Remove the oldest reading + } + pressureReadings.offer(event.values[0]); + + // Calculate the average of the readings in the queue + float sum = 0; + for (Float reading : pressureReadings) { + sum += reading; + } + float average = sum / pressureReadings.size(); + + // Use the averaged value instead of the raw reading + observer.onSensorValueChanged(AtmosphericPressure.ofHPA(average)); } @Override