feat: add distance-filtering for drives (#383)

This commit is contained in:
Lukáš Stankovič
2025-10-30 09:34:07 +01:00
committed by GitHub
parent 4121945326
commit 959dcd0e06
2 changed files with 53 additions and 0 deletions

View File

@@ -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`

View File

@@ -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/<CarID>/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)