From 959dcd0e061e7740e28709f5316cb3b85cc24e44 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Stankovi=C4=8D?= Date: Thu, 30 Oct 2025 09:34:07 +0100 Subject: [PATCH] feat: add distance-filtering for drives (#383) --- README.md | 2 ++ src/v1_TeslaMateAPICarsDrives.go | 51 ++++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+) diff --git a/README.md b/README.md index 63f895c..7cc3fef 100644 --- a/README.md +++ b/README.md @@ -173,6 +173,8 @@ More detailed documentation of every endpoint will come.. - Supported parameters: - `startDate` (optional, use canonical UTC format in RFC3339) - `endDate` (optional, use canonical UTC format in RFC3339) + - `minDistance` (optional, filter by minimum trip distance, units based on TeslaMate settings) + - `maxDistance` (optional, filter by maximum trip distance, units based on TeslaMate settings) - GET `/api/v1/cars/:CarID/drives/:DriveID` - PUT `/api/v1/cars/:CarID/logging/:Command` - GET `/api/v1/cars/:CarID/logging` diff --git a/src/v1_TeslaMateAPICarsDrives.go b/src/v1_TeslaMateAPICarsDrives.go index 1fdc1c9..ef31c04 100644 --- a/src/v1_TeslaMateAPICarsDrives.go +++ b/src/v1_TeslaMateAPICarsDrives.go @@ -31,6 +31,23 @@ func TeslaMateAPICarsDrivesV1(c *gin.Context) { TeslaMateAPIHandleErrorResponse(c, "TeslaMateAPICarsDrivesV1", CarsDrivesError2, err.Error()) return } + // get optional minDistance and maxDistance filters from query parameters + minDistanceParam := c.Query("minDistance") + minDistance := 0.0 + if minDistanceParam != "" { + minDistance = convertStringToFloat(minDistanceParam) + if minDistance < 0 { + minDistance = 0 + } + } + maxDistanceParam := c.Query("maxDistance") + maxDistance := 0.0 + if maxDistanceParam != "" { + maxDistance = convertStringToFloat(maxDistanceParam) + if maxDistance < 0 { + maxDistance = 0 + } + } // creating structs for /cars//drives // Car struct - child of Data @@ -183,6 +200,40 @@ func TeslaMateAPICarsDrivesV1(c *gin.Context) { paramIndex++ } + // Add minimum/maximum distance filtering if provided + if minDistance > 0 || maxDistance > 0 { + var unitsLength string + err = db.QueryRow("SELECT unit_of_length FROM settings LIMIT 1").Scan(&unitsLength) + if err != nil { + TeslaMateAPIHandleErrorResponse( + c, + "TeslaMateAPICarsDrivesV1", + CarsDrivesError1, + fmt.Sprintf("unable to retrieve unit_of_length from settings table: %v", err), + ) + return + } + if unitsLength == "mi" { + if minDistance > 0 { + minDistance = milesToKilometers(minDistance) + } + if maxDistance > 0 { + maxDistance = milesToKilometers(maxDistance) + } + } + + if minDistance > 0 { + query += fmt.Sprintf(" AND distance >= $%d", paramIndex) + queryParams = append(queryParams, minDistance) + paramIndex++ + } + if maxDistance > 0 { + query += fmt.Sprintf(" AND distance <= $%d", paramIndex) + queryParams = append(queryParams, maxDistance) + paramIndex++ + } + } + query += fmt.Sprintf(` ORDER BY start_date DESC LIMIT $%d OFFSET $%d;`, paramIndex, paramIndex+1)