WIP - RoutingController now no longer returns mock data, working alternative calculation for bike and walking
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good

Yet to implement: transit routes from carta, consider weather
This commit is contained in:
2026-01-02 17:13:19 +01:00
parent 12aed5ef26
commit 5f5365d5bc
8 changed files with 162 additions and 40 deletions
@@ -0,0 +1,7 @@
Weather client based on the public API from https://open-meteo.com:
[Forecast](https://open-meteo.com/en/docs)
- to be used for future and
[Historical Weather](https://open-meteo.com/en/docs/historical-weather-api)
@@ -26,19 +26,13 @@ public class RoutingController {
// TODO operation description + how to handle preferences (optional, if not provided use saved users prefs or default
@PostMapping("/request")
public ResponseEntity<List<RouteDTO>> requestAlternativeRoutes(@Valid @RequestBody RoutingAlternativeRequestDTO routingAlternativeRequestDTO) {
RoutingPreferencesDTO preferences = routingAlternativeRequestDTO.getRoutingPreferencesDTO();
if (preferences == null) { // Use default preferences if none are provided
if (routingAlternativeRequestDTO.getRoutingPreferencesDTO() == null) { // Use default preferences if none are provided
// TODO we might want to also save users preferences in the future
preferences = new RoutingPreferencesDTO(); // use default preferences
var preferences = new RoutingPreferencesDTO(); // use default preferences
routingAlternativeRequestDTO.setRoutingPreferencesDTO(preferences);
}
// var routeDTOs = routingService.getAlternativeRoute(routingAlternativeRequestDTO);
// Mocking response for app development
var routeDTOs = List.of(RouteDTO.getMockRouteDTO());
var routeDTOs = routingService.getAlternativeRoute(routingAlternativeRequestDTO);
return ResponseEntity.ok(routeDTOs);
}
}
@@ -1,12 +1,18 @@
package SuMoC.backend.routing;
import SuMoC.backend.carta.CartaClient;
import SuMoC.backend.geocoding.AddressDTO;
import SuMoC.backend.geocoding.GeoCodingService;
import SuMoC.backend.routing.config.RoutingProperties;
import SuMoC.backend.routing.dtos.RouteDTO;
import SuMoC.backend.routing.dtos.RoutingAlternativeRequestDTO;
import SuMoC.backend.routing.dtos.StepDTO;
import SuMoC.backend.routing.exceptions.NoCarRouteFoundException;
import SuMoC.backend.routing.exceptions.NoCarbonEmissionFoundException;
import SuMoC.backend.trip.Modality;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;
import sumoc.backend.carta.client.model.Direction;
import sumoc.backend.carta.client.model.Route;
@@ -19,14 +25,17 @@ import java.util.concurrent.CompletableFuture;
@Service
public class RoutingService {
private final GeoCodingService geoCodingService;
private final CartaClient cartaClient;
private final RoutingProperties routingProperties;
@Autowired
public RoutingService(CartaClient cartaClient, RoutingProperties routingProperties) {
public RoutingService(CartaClient cartaClient, RoutingProperties routingProperties, GeoCodingService geoCodingService) {
this.cartaClient = cartaClient;
this.routingProperties = routingProperties;
this.geoCodingService = geoCodingService;
}
/**
@@ -93,7 +102,7 @@ public class RoutingService {
typeList.add("6"); // gondola
typeList.add("7"); // funicular
String types = String.join(",", typeList);
futuresByMode.put("transit", getCartaFuture(requestDTO, "transit", types, 1));
futuresByMode.put("transit", getCartaFuture(requestDTO, "transit", types, 3));
}
// return all future results as list when resvoled
@@ -104,28 +113,73 @@ public class RoutingService {
return directions;
}
// TODO think about error handling, what if no car route found?
public List<RouteDTO> getAlternativeRoute(RoutingAlternativeRequestDTO requestDTO) {
assert requestDTO.getRoutingPreferencesDTO() != null;
HashMap<String, Direction> directionMap = getPossibleDirectionsFromCarta(requestDTO);
// if consider weather
// get weather for origin
// if bad, remove walking and biking options
// filter applicable routes (car is only baseline, never suggested)
ArrayList<RouteDTO> suggestedAlternatives = new ArrayList<>();
// Fetch origin and destination addresses concurrently
var addressesMono = Mono.zip(
geoCodingService.getAddress(requestDTO.getOriginLat(), requestDTO.getOriginLon()),
geoCodingService.getAddress(requestDTO.getDestinationLat(), requestDTO.getDestinationLon())
);
var addressesTuple = addressesMono.block();
AddressDTO originAddress = addressesTuple.getT1();
AddressDTO destinationAddress = addressesTuple.getT2();
// Define max additional time for sustainable alternatives
int maxAdditionalTimeNonPhysical = routingProperties.getToleratedAdditionalTravelSeconds();
int maxAdditionalTimePhysical = requestDTO.getRoutingPreferencesDTO().isPreferPhysicalActivity() ?
routingProperties.getToleratedAdditionalPhysicalActivitiesSeconds() :
routingProperties.getToleratedAdditionalTravelSeconds();
// Setting up car data for baseline
Route carRoute;
try {
carRoute = directionMap.get("car").getRoutes().getFirst();
} catch (NullPointerException e) {
throw new NoCarRouteFoundException("No car route to compare to was found.");
}
double carCarbondDioxide;
try {
carCarbondDioxide = carRoute.getEmission().getCarbonDioxide();
} catch (NullPointerException e) {
throw new NoCarbonEmissionFoundException("No carbon emission was provided for the car route.");
}
if (directionMap.containsKey("bike")) {
Direction bikeDirection = directionMap.get("bike");
if (bikeDirection.getRoutes() != null && !bikeDirection.getRoutes().isEmpty()) {
Route bikeRoute = bikeDirection.getRoutes().getFirst();
int durationDifferenceCar = bikeRoute.getDuration() - carRoute.getDuration();
if (durationDifferenceCar < maxAdditionalTimePhysical) {
ArrayList<StepDTO> steps = new ArrayList<>();
steps.add(new StepDTO(
Modality.BICYCLE,
null,
bikeRoute.getDistance()
)
);
RouteDTO routeDTO = new RouteDTO(
originAddress,
null,
bikeRoute.getSourceCoordinate().getLatitude(),
bikeRoute.getSourceCoordinate().getLongitude(),
destinationAddress,
null,
bikeRoute.getTargetCoordinate().getLatitude(),
bikeRoute.getTargetCoordinate().getLongitude(),
requestDTO.getArrivalTime().minusSeconds(bikeRoute.getDuration()),
requestDTO.getArrivalTime(),
steps,
carCarbondDioxide,
bikeRoute.getDuration() - carRoute.getDuration()
);
suggestedAlternatives.add(routeDTO);
}
}
}
if (directionMap.containsKey("walk")) {
Direction walkDirection = directionMap.get("walk");
@@ -133,17 +187,38 @@ public class RoutingService {
Route walkRoute = walkDirection.getRoutes().getFirst();
int durationDifferenceCar = walkRoute.getDuration() - carRoute.getDuration();
if (durationDifferenceCar < maxAdditionalTimePhysical) {
ArrayList<StepDTO> steps = new ArrayList<>();
steps.add(new StepDTO(
Modality.WALKING,
null,
walkRoute.getDistance()
));
RouteDTO routeDTO = new RouteDTO(
originAddress,
null,
walkRoute.getSourceCoordinate().getLatitude(),
walkRoute.getSourceCoordinate().getLongitude(),
destinationAddress,
null,
walkRoute.getTargetCoordinate().getLatitude(),
walkRoute.getTargetCoordinate().getLongitude(),
requestDTO.getArrivalTime().minusSeconds(walkRoute.getDuration()),
requestDTO.getArrivalTime(),
steps,
carCarbondDioxide,
walkRoute.getDuration() - carRoute.getDuration()
);
suggestedAlternatives.add(routeDTO);
}
}
}
// certain threshold how much more delay is okay
// apply physical preference if set
// TODO public transit
// TODO if consider weather
// get weather for origin
// if bad, remove walking and biking options
// convert remaining routes to routedto
return new ArrayList<RouteDTO>();
return suggestedAlternatives;
}
}
@@ -1,4 +1,4 @@
package SuMoC.backend.routing;
package SuMoC.backend.routing.config;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@@ -1,4 +1,4 @@
package SuMoC.backend.routing;
package SuMoC.backend.routing.config;
import lombok.Getter;
import lombok.Setter;
@@ -9,5 +9,5 @@ import org.springframework.boot.context.properties.ConfigurationProperties;
@Setter
public class RoutingProperties {
private int toleratedAdditionalTravelSeconds = 15 * 60;
private int toleratedAdditionalPhysicalActivitiesSeconds = 30 * 60;
private int toleratedAdditionalPhysicalActivitiesSeconds = 45 * 60;
}
@@ -1,9 +1,9 @@
package SuMoC.backend.routing.dtos;
import SuMoC.backend.geocoding.AddressDTO;
import SuMoC.backend.trip.Modality;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.annotation.Nullable;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@@ -15,11 +15,10 @@ import java.util.List;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Schema(description = "This DTO represents a suggested route as a response to a requested alternative route.")
public class RouteDTO {
@Schema(description = "The actual address of the start location.")
private String startAddress;
private AddressDTO startAddress;
@Schema(description = "The name of the first stop if the route uses public transport. E.g. \"Essen West\" if the route starts with a footpath to the first train leaving there.")
@Nullable
private String firstStopName;
@@ -28,14 +27,14 @@ public class RouteDTO {
@Schema(description = "The longitude of the start address.")
private double startLon;
@Schema(description = "The actual address of the end location.")
private String endAddress;
private AddressDTO endAddress;
@Schema(description = "The name of the last stop if the route uses public transport. E.g. \"Essen Hbf\" if the route ends with a train arriving there (might still contain a footpath afterwards).")
@Nullable
private String lastStopName;
@Schema(description = "The latitude of the end address.")
private String endLat;
private double endLat;
@Schema(description = "The longitude of the end address.")
private String endLon;
private double endLon;
@Schema(description = "The start date and time of the route.")
private LocalDateTime startDateTime;
@Schema(description = "The end date and time of the route.")
@@ -43,9 +42,25 @@ public class RouteDTO {
@Schema(description = "The steps the route consists of.")
private List<StepDTO> steps;
@Schema(description = "Amount of CO2e savings in gramm compared to a car trip for the same route.")
private float co2Savings;
private double co2Savings;
@Schema(description = "The temporal difference in minutes compared to the original route the user requested alternatives for.")
private float timeDifferenceMinutes;
private double timeDifferenceSeconds;
public RouteDTO(AddressDTO startAddress, @Nullable String firstStopName, double startLat, double startLon, AddressDTO endAddress, @Nullable String lastStopName, double endLat, double endLon, LocalDateTime startDateTime, LocalDateTime endDateTime, List<StepDTO> steps, double co2Savings, double timeDifferenceSeconds) {
this.startAddress = startAddress;
this.firstStopName = firstStopName;
this.startLat = startLat;
this.startLon = startLon;
this.endAddress = endAddress;
this.lastStopName = lastStopName;
this.endLat = endLat;
this.endLon = endLon;
this.startDateTime = startDateTime;
this.endDateTime = endDateTime;
this.steps = steps;
this.co2Savings = co2Savings;
this.timeDifferenceSeconds = timeDifferenceSeconds;
}
/**
* Mock method for testing purposes
@@ -53,15 +68,39 @@ public class RouteDTO {
* @return RouteDto with mock data
*/
public static RouteDTO getMockRouteDTO() {
var startAddress = new AddressDTO(
"28a",
"Janssenstraße",
"Holsterhausen",
"Stadtbezirk III",
"Essen",
"Nordrhein-Westfalen",
"DE-NW",
"45147",
"Deutschland",
"de"
);
var endAddress = new AddressDTO(
"70",
"Schützenbahn",
null,
null,
"Essen",
"Nordrhein-Westfalen",
"DE-NW",
"45127",
"Deutschland",
"de"
);
var dto = new RouteDTO(
"Janssenstraße 28a, 45147 Essen, Germany",
startAddress,
"Rubensstraße",
51.440395,
6.984785,
"Schützenbahn 70, 45127 Essen, Germany",
endAddress,
"Viehhofer Platz",
"51.459167",
"7.014928",
51.459167,
7.014928,
LocalDateTime.now().minusMinutes(30),
LocalDateTime.now(),
new ArrayList<StepDTO>(),
@@ -15,5 +15,5 @@ import lombok.Setter;
public class StepDTO {
private Modality modality;
private String lineNumber;
private float distanceMeters;
private double distanceMeters;
}
@@ -0,0 +1,7 @@
package SuMoC.backend.routing.exceptions;
public class NoCarbonEmissionFoundException extends RuntimeException {
public NoCarbonEmissionFoundException(String message) {
super(message);
}
}