Colota - Android GPS Location tracker
fix(trips): stop stationary heartbeat runs becoming 0m trips (#569)
Max Dietrichf1f3afeb004c
diff --git a/apps/docs/docs/development/architecture.md b/apps/docs/docs/development/architecture.mdindex cc832a09..fc9515ac 100644--- a/apps/docs/docs/development/architecture.md+++ b/apps/docs/docs/development/architecture.md@@ -369,7 +369,7 @@ Supporting utilities in `mapUtils.ts`:| `logger` | Environment-aware logging - suppresses debug/info console output in production via `__DEV__`, always logs warn/error to console. All levels are always captured in a ring buffer (2000 entries) for the Logging screen || `geo` | Haversine distance, speed/distance/duration/time formatting with configurable unit system (metric/imperial) and time format (12h/24h), auto-detected from locale on first use || `exportConverters` | Export-format metadata (labels, icons, extensions, MIME types) for the export UI. Serialization itself is native - see `ExportConverters.kt` |-| `trips` | Trip segmentation via time-gap detection (15-min threshold) with distance computation, trip stats (avg speed, elevation gain/loss), and trip color assignment |+| `trips` | Trip segmentation via time-gap detection (15-min threshold), dropping segments whose bounding box spans under 100 m so stationary heartbeat runs do not become trips, plus distance computation, trip stats (avg speed, elevation gain/loss), and trip color assignment. `getDailyStats` in `DatabaseHelper.kt` mirrors both thresholds for the calendar and summary || `queueStatus` | Maps sync queue size to color indicators for the dashboard || `settingsValidation` | URL validation and security checks for endpoint configuration |diff --git a/apps/mobile/android/app/src/main/java/com/colota/data/DatabaseHelper.kt b/apps/mobile/android/app/src/main/java/com/colota/data/DatabaseHelper.ktindex c25f40ac..5d7c75ee 100644--- a/apps/mobile/android/app/src/main/java/com/colota/data/DatabaseHelper.kt+++ b/apps/mobile/android/app/src/main/java/com/colota/data/DatabaseHelper.kt@@ -47,6 +47,7 @@ class DatabaseHelper private constructor(context: Context) :private const val TAG = "LocationDB"private const val TRIP_GAP_SECONDS = 900L // 15 min, matches JS segmentTrips+ private const val MIN_TRIP_EXTENT_METERS = 100.0 // bbox diagonal, matches JS segmentTripsprivate const val CREATE_PROFILES_TABLE = """CREATE TABLE IF NOT EXISTS $TABLE_PROFILES (@@ -997,11 +998,27 @@ class DatabaseHelper private constructor(context: Context) :var endTime = 0Lvar distance = 0.0var tripCount = 0- var segmentSize = 0var prevLat = 0.0var prevLon = 0.0var prevTs = 0L+ // Distance is buffered until the segment qualifies as a trip+ var segMinLat = 0.0+ var segMaxLat = 0.0+ var segMinLon = 0.0+ var segMaxLon = 0.0+ var segDistance = 0.0+ var segCounted = false++ fun startSegment(lat: Double, lon: Double) {+ segMinLat = lat+ segMaxLat = lat+ segMinLon = lon+ segMaxLon = lon+ segDistance = 0.0+ segCounted = false+ }+fun emitDay() {if (currentDay != null) {stats.add(mapOf(@@ -1029,7 +1046,7 @@ class DatabaseHelper private constructor(context: Context) :endTime = tsdistance = 0.0tripCount = 0- segmentSize = 1+ startSegment(lat, lon)prevLat = latprevLon = lonprevTs = ts@@ -1037,11 +1054,23 @@ class DatabaseHelper private constructor(context: Context) :count++endTime = tsif (ts - prevTs >= TRIP_GAP_SECONDS) {- segmentSize = 1+ startSegment(lat, lon)} else {- segmentSize++- if (segmentSize == 2) tripCount++- distance += haversineDistance(prevLat, prevLon, lat, lon)+ segDistance += haversineDistance(prevLat, prevLon, lat, lon)+ if (lat < segMinLat) segMinLat = lat+ if (lat > segMaxLat) segMaxLat = lat+ if (lon < segMinLon) segMinLon = lon+ if (lon > segMaxLon) segMaxLon = lon+ if (!segCounted &&+ haversineDistance(segMinLat, segMinLon, segMaxLat, segMaxLon) >= MIN_TRIP_EXTENT_METERS+ ) {+ tripCount+++ segCounted = true+ }+ if (segCounted) {+ distance += segDistance+ segDistance = 0.0+ }}}prevLat = latdiff --git a/apps/mobile/android/app/src/test/java/com/Colota/data/DatabaseHelperSQLiteTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/data/DatabaseHelperSQLiteTest.ktindex 162693c9..81524f4c 100644--- a/apps/mobile/android/app/src/test/java/com/Colota/data/DatabaseHelperSQLiteTest.kt+++ b/apps/mobile/android/app/src/test/java/com/Colota/data/DatabaseHelperSQLiteTest.kt@@ -900,6 +900,53 @@ class DatabaseHelperSQLiteTest {assertEquals(2, stats[0]["tripCount"])}+ @Test+ fun `getDailyStats ignores a stationary run at a single coordinate`() {+ // Heartbeat points at the zone centre, 10 min apart so they chain into one segment+ repeat(10) { i ->+ db.saveLocation(latitude = 52.52, longitude = 13.405, timestamp = 1708344000L + i * 600L)+ }++ val stats = db.getDailyStats(1708300000L, 1708400000L)+ assertEquals(1, stats.size)+ assertEquals(10, stats[0]["count"])+ assertEquals(0, stats[0]["tripCount"])+ assertEquals(0.0, stats[0]["distanceMeters"] as Double, 0.001)+ }++ @Test+ fun `getDailyStats ignores a jittering stationary run despite its total distance`() {+ // Real fixes, so every point moves - total distance passes 200m while the bbox stays ~60m+ val offsets = listOf(0.0, 0.0002, -0.0001, 0.00025, -0.00022, 0.0001, -0.00025, 0.00018, -0.00015, 0.00022)+ offsets.forEachIndexed { i, d ->+ db.saveLocation(+ latitude = 52.52 + d,+ longitude = 13.405 + if (i % 2 == 0) d else -d,+ timestamp = 1708344000L + i * 600L+ )+ }++ val stats = db.getDailyStats(1708300000L, 1708400000L)+ assertEquals(1, stats.size)+ assertEquals(0, stats[0]["tripCount"])+ assertEquals(0.0, stats[0]["distanceMeters"] as Double, 0.001)+ }++ @Test+ fun `getDailyStats counts a real trip that follows a stationary run`() {+ // Stationary run followed by a real trip+ repeat(5) { i ->+ db.saveLocation(latitude = 52.52, longitude = 13.405, timestamp = 1708344000L + i * 600L)+ }+ db.saveLocation(latitude = 52.6, longitude = 13.405, timestamp = 1708348000L)+ db.saveLocation(latitude = 52.61, longitude = 13.405, timestamp = 1708348060L)++ val stats = db.getDailyStats(1708300000L, 1708400000L)+ assertEquals(1, stats.size)+ assertEquals(1, stats[0]["tripCount"])+ assertTrue((stats[0]["distanceMeters"] as Double) > 1000)+ }+@Testfun `getDailyStats returns empty for no data`() {val stats = db.getDailyStats(1708300000L, 1708400000L)diff --git a/apps/mobile/src/components/features/inspector/TrackMap.tsx b/apps/mobile/src/components/features/inspector/TrackMap.tsxindex a75ed742..2cfa6ae4 100644--- a/apps/mobile/src/components/features/inspector/TrackMap.tsx+++ b/apps/mobile/src/components/features/inspector/TrackMap.tsx@@ -68,14 +68,10 @@ export function TrackMap({ locations, colors, trips, trackColor, fitVersion, onPconst bounds = useMemo(() => computeTrackBounds(locations), [locations])const fittedVersionRef = useRef(-1)- useEffect(() => {- if (!bounds || !mapReady || !mapRef.current?.camera) return- if (fitVersion === fittedVersionRef.current) return- // Defer to next frame so the map's GL context is fully ready after onDidFinishLoadingMap- requestAnimationFrame(() => {- const camera = mapRef.current?.camera- if (!camera) return- fittedVersionRef.current = fitVersion ?? 0+ // Zero-extent bounds would make fitBounds zoom past the deepest tile level+ const fitCamera = useCallback(+ (camera: NonNullable<ColotaMapRef["camera"]>) => {+ if (!bounds) returnif (bounds.sw[0] === bounds.ne[0] && bounds.sw[1] === bounds.ne[1]) {camera.setStop({ center: bounds.sw, zoom: DEFAULT_MAP_ZOOM, duration: MAP_ANIMATION_DURATION_MS })} else {@@ -84,8 +80,21 @@ export function TrackMap({ locations, colors, trips, trackColor, fitVersion, onPduration: MAP_ANIMATION_DURATION_MS})}+ },+ [bounds]+ )++ useEffect(() => {+ if (!bounds || !mapReady || !mapRef.current?.camera) return+ if (fitVersion === fittedVersionRef.current) return+ // Defer to next frame so the map's GL context is fully ready after onDidFinishLoadingMap+ requestAnimationFrame(() => {+ const camera = mapRef.current?.camera+ if (!camera) return+ fittedVersionRef.current = fitVersion ?? 0+ fitCamera(camera)})- }, [bounds, mapReady, fitVersion])+ }, [bounds, mapReady, fitVersion, fitCamera])const handleMapReady = useCallback(() => setMapReady(true), [])@@ -98,13 +107,10 @@ export function TrackMap({ locations, colors, trips, trackColor, fitVersion, onPconst handleFitTrack = useCallback(() => {if (bounds && mapRef.current?.camera) {- mapRef.current.camera.fitBounds([bounds.sw[0], bounds.sw[1], bounds.ne[0], bounds.ne[1]], {- padding: { top: 60, right: 60, bottom: 60, left: 60 },- duration: MAP_ANIMATION_DURATION_MS- })+ fitCamera(mapRef.current.camera)setIsCentered(true)}- }, [bounds])+ }, [bounds, fitCamera])const handleRegionChange = useCallback((payload: { isUserInteraction: boolean }) => {if (payload.isUserInteraction) {@@ -112,35 +118,33 @@ export function TrackMap({ locations, colors, trips, trackColor, fitVersion, onP}}, [])- // Trip boundary indices to avoid drawing lines between trips+ // Owning trip per point, -1 when segmentTrips dropped the segment. Keyed on startIndex,+ // since a running locationCount sum skips over dropped segments+ const tripIdByPoint = useMemo(() => {+ if (!trips) return undefined+ const ids = new Int32Array(locations.length).fill(-1)+ trips.forEach((trip, tripId) => {+ const end = Math.min(trip.startIndex + trip.locationCount, locations.length)+ for (let i = trip.startIndex; i < end; i++) ids[i] = tripId+ })+ return ids+ }, [trips, locations])++ // Line breaks between trips, and on both sides of every dropped pointconst skipIndices = useMemo(() => {- if (!trips || trips.length <= 1) return undefined+ if (!tripIdByPoint) return undefinedconst indices = new Set<number>()- let offset = 0- for (const trip of trips) {- if (offset > 0) indices.add(offset)- offset += trip.locationCount+ for (let i = 1; i < tripIdByPoint.length; i++) {+ if (tripIdByPoint[i] < 0 || tripIdByPoint[i] !== tripIdByPoint[i - 1]) indices.add(i)}return indices- }, [trips])+ }, [tripIdByPoint])// Per-location colorsconst locationColors = useMemo(() => {- if (trips) {- const arr: string[] = []- for (const trip of trips) {- const tripColor = getTripColor(trip.index)- for (let j = 0; j < trip.locationCount; j++) {- arr.push(tripColor)- }- }- while (arr.length < locations.length) {- arr.push(trackColor)- }- return arr- }- return locations.map(() => trackColor)- }, [trips, locations, trackColor])+ if (!tripIdByPoint || !trips) return locations.map(() => trackColor)+ return Array.from(tripIdByPoint, (tripId) => (tripId < 0 ? trackColor : getTripColor(trips[tripId].index)))+ }, [tripIdByPoint, trips, locations, trackColor])// GeoJSON dataconst segmentsGeoJSON = useMemo(diff --git a/apps/mobile/src/components/features/inspector/__tests__/TrackMap.test.tsx b/apps/mobile/src/components/features/inspector/__tests__/TrackMap.test.tsxindex 01cf9421..0511b7b3 100644--- a/apps/mobile/src/components/features/inspector/__tests__/TrackMap.test.tsx+++ b/apps/mobile/src/components/features/inspector/__tests__/TrackMap.test.tsx@@ -2,9 +2,22 @@ import React from "react"import { render, act } from "@testing-library/react-native"import { TrackMap } from "../TrackMap"import { DEFAULT_MAP_ZOOM } from "../../../../constants"+import type { Trip } from "../../../../types/global"const mockFitBounds = jest.fn()const mockSetStop = jest.fn()+const mockBuildSegments = jest.fn()++jest.mock("../../map/mapUtils", () => {+ const actual = jest.requireActual("../../map/mapUtils")+ return {+ ...actual,+ buildTrackSegmentsGeoJSON: (...args: any[]) => {+ mockBuildSegments(...args)+ return actual.buildTrackSegmentsGeoJSON(...args)+ }+ }+})jest.mock("../../map/ColotaMapView", () => {const R = require("react")@@ -52,7 +65,7 @@ jest.mock("../../../../utils/geo", () => ({}))jest.mock("../../../../utils/trips", () => ({- getTripColor: () => "#000"+ getTripColor: (index: number) => `#trip${index}`}))const colors = {@@ -119,3 +132,22 @@ describe("TrackMap auto-fit", () => {expect(mockSetStop).toHaveBeenCalledWith(expect.objectContaining({ center: [13.4, 52.5], zoom: DEFAULT_MAP_ZOOM }))})})++describe("TrackMap trip coloring", () => {+ beforeEach(() => mockBuildSegments.mockClear())++ it("keeps points aligned with their trip when segmentTrips dropped a segment", () => {+ // Points 2-4 were dropped by segmentTrips+ const locations = [loc(52.5, 13.4), loc(52.51, 13.4), loc(52.6, 13.4), loc(52.6, 13.4), loc(52.6, 13.4), loc(52.7, 13.4), loc(52.71, 13.4)] // prettier-ignore+ const trips: Trip[] = [+ { index: 1, locations: [], startTime: 0, endTime: 0, distance: 1000, locationCount: 2, startIndex: 0 },+ { index: 2, locations: [], startTime: 0, endTime: 0, distance: 1000, locationCount: 2, startIndex: 5 }+ ]++ render(<TrackMap locations={locations} colors={colors} trips={trips} trackColor="#track" fitVersion={1} />)++ const options = mockBuildSegments.mock.calls[0][2]+ expect(options.locationColors).toEqual(["#trip1", "#trip1", "#track", "#track", "#track", "#trip2", "#trip2"])+ expect([...options.skipIndices].sort((a: number, b: number) => a - b)).toEqual([2, 3, 4, 5])+ })+})diff --git a/apps/mobile/src/components/features/inspector/__tests__/TripList.test.tsx b/apps/mobile/src/components/features/inspector/__tests__/TripList.test.tsxindex 50f157d5..f926e5fa 100644--- a/apps/mobile/src/components/features/inspector/__tests__/TripList.test.tsx+++ b/apps/mobile/src/components/features/inspector/__tests__/TripList.test.tsx@@ -83,7 +83,8 @@ function makeTrip(index: number, distance = 1000): Trip {startTime: index * 100,endTime: index * 100 + 60,distance,- locationCount: 5+ locationCount: 5,+ startIndex: (index - 1) * 5}}diff --git a/apps/mobile/src/types/global.ts b/apps/mobile/src/types/global.tsindex 988c3d82..866e1988 100644--- a/apps/mobile/src/types/global.ts+++ b/apps/mobile/src/types/global.ts@@ -441,6 +441,7 @@ export interface Trip {endTime: number // Unix secondsdistance: number // meterslocationCount: number+ startIndex: number // offset into the day's location array}// ============================================================================diff --git a/apps/mobile/src/utils/__tests__/trips.test.ts b/apps/mobile/src/utils/__tests__/trips.test.tsindex 0f4902b4..c922c73f 100644--- a/apps/mobile/src/utils/__tests__/trips.test.ts+++ b/apps/mobile/src/utils/__tests__/trips.test.ts@@ -1,5 +1,5 @@import { segmentTrips, getTripColor, TRIP_COLORS, computeTripStats } from "../trips"-import { formatDuration, formatTime, formatDate } from "../geo"+import { formatDuration, formatTime, formatDate, computeTotalDistance } from "../geo"describe("segmentTrips", () => {it("returns empty array for empty input", () => {@@ -88,6 +88,58 @@ describe("segmentTrips", () => {expect(trips[0].distance).toBeLessThan(1200)})+ it("drops a stationary run at a single coordinate", () => {+ // Heartbeat points at the zone centre+ const locations = Array.from({ length: 20 }, (_, i) => ({+ latitude: 52.52,+ longitude: 13.405,+ timestamp: 1000 + i * 600+ }))+ expect(segmentTrips(locations)).toHaveLength(0)+ })++ it("drops a jittering stationary run even though its total distance is long", () => {+ // Real fixes, so every point moves - total distance passes 200m while the bbox stays ~60m+ const offsets = [0, 0.0002, -0.0001, 0.00025, -0.00022, 0.0001, -0.00025, 0.00018, -0.00015, 0.00022]+ const locations = offsets.map((d, i) => ({+ latitude: 52.52 + d,+ longitude: 13.405 + (i % 2 === 0 ? d : -d),+ timestamp: 1000 + i * 600+ }))+ expect(computeTotalDistance(locations)).toBeGreaterThan(200)+ expect(segmentTrips(locations)).toHaveLength(0)+ })++ it("keeps a round trip that returns to its start", () => {+ // start == end, but the track reaches ~330m away+ const locations = [+ { latitude: 52.52, longitude: 13.405, timestamp: 1000 },+ { latitude: 52.521, longitude: 13.405, timestamp: 1100 },+ { latitude: 52.523, longitude: 13.405, timestamp: 1200 },+ { latitude: 52.521, longitude: 13.405, timestamp: 1300 },+ { latitude: 52.52, longitude: 13.405, timestamp: 1400 }+ ]+ expect(segmentTrips(locations)).toHaveLength(1)+ })++ it("reports each trip's offset into the full location array", () => {+ // TrackMap indexes point colors by this offset+ const locations = [+ { latitude: 52.52, longitude: 13.405, timestamp: 1000 },+ { latitude: 52.522, longitude: 13.405, timestamp: 1005 },+ // stationary run, dropped+ { latitude: 52.6, longitude: 13.405, timestamp: 2000 },+ { latitude: 52.6, longitude: 13.405, timestamp: 2600 },+ { latitude: 52.6, longitude: 13.405, timestamp: 3200 },+ { latitude: 52.7, longitude: 13.405, timestamp: 4200 },+ { latitude: 52.702, longitude: 13.405, timestamp: 4205 }+ ]+ const trips = segmentTrips(locations)+ expect(trips).toHaveLength(2)+ expect(trips[0].startIndex).toBe(0)+ expect(trips[1].startIndex).toBe(5)+ })+it("respects custom gap threshold", () => {const locations = [{ latitude: 52.52, longitude: 13.405, timestamp: 1000 },diff --git a/apps/mobile/src/utils/trips.ts b/apps/mobile/src/utils/trips.tsindex 2d736432..8927dc45 100644--- a/apps/mobile/src/utils/trips.ts+++ b/apps/mobile/src/utils/trips.ts@@ -3,7 +3,7 @@* Licensed under the GNU AGPLv3. See LICENSE in the project root for details.*/-import { computeTotalDistance } from "./geo"+import { computeTotalDistance, haversine } from "./geo"import type { Trip, LocationCoords } from "../types/global"export const TRIP_COLORS = ["#3B82F6", "#10B981", "#F59E0B", "#EF4444", "#8B5CF6", "#EC4899"]@@ -13,7 +13,8 @@ export function getTripColor(index: number): string {}const DEFAULT_GAP_SECONDS = 900 // 15 minutes-const MIN_TRIP_POINTS = 2+// Total distance is no use here - stationary fixes accumulate it without moving+const MIN_TRIP_EXTENT_METERS = 100 // bbox diagonal, matches DatabaseHelper.getDailyStats/*** Segments a chronologically-sorted array of locations into trips.@@ -24,6 +25,7 @@ export function segmentTrips(locations: LocationCoords[], gapThresholdSeconds: nif (locations.length === 0) return []const trips: Trip[] = []+ let startIndex = 0let currentTripLocations: LocationCoords[] = [locations[0]]for (let i = 1; i < locations.length; i++) {@@ -31,7 +33,8 @@ export function segmentTrips(locations: LocationCoords[], gapThresholdSeconds: nconst currTs = locations[i].timestamp ?? 0if (currTs - prevTs >= gapThresholdSeconds) {- trips.push(buildTrip(currentTripLocations))+ trips.push(buildTrip(currentTripLocations, startIndex))+ startIndex = icurrentTripLocations = [locations[i]]} else {currentTripLocations.push(locations[i])@@ -39,23 +42,40 @@ export function segmentTrips(locations: LocationCoords[], gapThresholdSeconds: n}if (currentTripLocations.length > 0) {- trips.push(buildTrip(currentTripLocations))+ trips.push(buildTrip(currentTripLocations, startIndex))}- // Filter out single-point "trips" (stray GPS fixes during long stops)- const filtered = trips.filter((t) => t.locationCount >= MIN_TRIP_POINTS)+ // Drops stray fixes during long stops as well as stationary runs+ const filtered = trips.filter((t) => trackExtent(t.locations) >= MIN_TRIP_EXTENT_METERS)// Re-index after filteringreturn filtered.map((t, i) => ({ ...t, index: i + 1 }))}-function buildTrip(locations: LocationCoords[]): Trip {+/** Bounding box diagonal, in meters. */+function trackExtent(locations: LocationCoords[]): number {+ if (locations.length === 0) return 0+ let minLat = locations[0].latitude+ let maxLat = locations[0].latitude+ let minLon = locations[0].longitude+ let maxLon = locations[0].longitude+ for (const loc of locations) {+ if (loc.latitude < minLat) minLat = loc.latitude+ if (loc.latitude > maxLat) maxLat = loc.latitude+ if (loc.longitude < minLon) minLon = loc.longitude+ if (loc.longitude > maxLon) maxLon = loc.longitude+ }+ return haversine(minLat, minLon, maxLat, maxLon)+}++function buildTrip(locations: LocationCoords[], startIndex: number): Trip {return {index: 0,locations,startTime: locations[0].timestamp ?? 0,endTime: locations[locations.length - 1].timestamp ?? 0,distance: computeTotalDistance(locations),- locationCount: locations.length+ locationCount: locations.length,+ startIndex}}diff --git a/fastlane/metadata/android/en-US/changelogs/44.txt b/fastlane/metadata/android/en-US/changelogs/44.txtindex 40b08d34..6735a4de 100644--- a/fastlane/metadata/android/en-US/changelogs/44.txt+++ b/fastlane/metadata/android/en-US/changelogs/44.txt@@ -1,3 +1,4 @@- The Stationary profile now records a point at each interval while the device is still- Auto-export file names are now customisable with {date}, {time} and {device} placeholders- Add {device} to the file name to keep retention per device model when several phones share an export folder+- Stationary heartbeat points no longer show up as 0 m trips in the history - a run of points now has to cover at least 100 m to count as a trip