Skip to content

Commit

Permalink
Merge pull request #176 from kieler/132-refactor-computation-of-vehic…
Browse files Browse the repository at this point in the history
…le-speed

132 refactor computation of vehicle speed
  • Loading branch information
Kebslock authored Sep 20, 2023
2 parents 7af0f7f + 9ed4bec commit 281434c
Showing 1 changed file with 30 additions and 7 deletions.
37 changes: 30 additions & 7 deletions Server/src/services/vehicle.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -333,7 +333,9 @@ export default class VehicleService {
percentagePosition: TrackService.getTrackKmAsPercentage(trackKm, track),
heading: latestLog.heading,
direction: this.computeVehicleTravelingDirection([[latestLog, trackKm]], track),
speed: latestLog.speed
// we cannot make any precise assertion about the speed and in most cases this
// is probably called, if the vehicle is not moving, so set speed to 0
speed: 0
}
}

Expand Down Expand Up @@ -527,15 +529,36 @@ export default class VehicleService {

/**
* Compute average speed of given logs
* @param logs logs to get the average speed from
* @param logs logs with their associated track kilometer to get the average speed from
* @returns average speed of `logs`
* @throws `HTTPError`, if no logs are given
*/
private static computeVehicleSpeed(logs: [Log, number][]): number {
// TODO: needs improvement (see #132)
let avgSpeed = 0
for (let i = 0; i < logs.length; i++) {
avgSpeed += logs[i][0].speed / logs.length
// just check, if we got any logs at all
if (logs.length === 0) {
throw new HTTPError(`Expected at least one log for computation of vehicle speed`, 500)
}

// get passed time
const passedTimeSec = (Date.now() - logs[0][0].timestamp.getTime()) / 1000

// special case of only one log, return raw data than
let currentSpeed
if (logs.length === 1) {
currentSpeed = logs[0][0].speed * (-Math.exp((passedTimeSec - 30) / 6) + 1)
} else {
// at least two logs, compute average speed of the last two positions
const trackKmDifference = logs[0][1] - logs[1][1] > 0 ? logs[0][1] - logs[1][1] : logs[1][1] - logs[0][1]
const timeDifference = logs[0][0].timestamp.getTime() / 3600000 - logs[1][0].timestamp.getTime() / 3600000
const averageSpeed = trackKmDifference / timeDifference

// return average of above calculation and two most recent log speeds with decelerating factor
currentSpeed =
((averageSpeed + logs[0][0].speed + logs[1][0].speed) / 3) * (-Math.exp((passedTimeSec - 30) / 6) + 1)
if (logs[0][0].vehicleId === 1) {
logger.silly(`Speeds: ${averageSpeed}, ${logs[0][0].speed}, ${logs[1][0].speed}, Result: ${currentSpeed}`)
}
}
return avgSpeed
return currentSpeed > 0 ? currentSpeed : 0
}
}

0 comments on commit 281434c

Please sign in to comment.