318 lines
13 KiB
Java
318 lines
13 KiB
Java
package SuMoC.backend.carta;
|
|
|
|
import SuMoC.backend.geocoding.AddressDTO;
|
|
import SuMoC.backend.geocoding.GeoCodingService;
|
|
import SuMoC.backend.routing.dtos.RouteDTO;
|
|
import SuMoC.backend.routing.dtos.StepDTO;
|
|
import SuMoC.backend.routing.exceptions.NoCarRouteFoundException;
|
|
import SuMoC.backend.routing.exceptions.NoCarbonEmissionFoundException;
|
|
import SuMoC.backend.routing.services.CartaTransitRouteProcessor;
|
|
import SuMoC.backend.trip.Modality;
|
|
import lombok.RequiredArgsConstructor;
|
|
import org.springframework.stereotype.Service;
|
|
import reactor.core.publisher.Mono;
|
|
import sumoc.backend.carta.client.model.Direction;
|
|
import sumoc.backend.carta.client.model.Route;
|
|
|
|
import java.time.Instant;
|
|
import java.time.LocalDate;
|
|
import java.time.LocalDateTime;
|
|
import java.time.ZoneId;
|
|
import java.util.ArrayList;
|
|
import java.util.HashMap;
|
|
import java.util.List;
|
|
import java.util.Map;
|
|
import java.util.concurrent.CompletableFuture;
|
|
|
|
import static SuMoC.backend.trip.Modality.BICYCLE;
|
|
import static SuMoC.backend.trip.Modality.CAR;
|
|
|
|
@Service
|
|
@RequiredArgsConstructor
|
|
public class DirectionsService {
|
|
|
|
private final CartaClient cartaClient;
|
|
|
|
private final GeoCodingService geoCodingService;
|
|
|
|
public List<RouteDTO> getPossibleAlternativeRoutes(DirectionsRequest requestDTO) {
|
|
return getPossibleRoutes(requestDTO, false);
|
|
}
|
|
|
|
/**
|
|
* Returns possible routes for the request - no sanity filtering regarding travel times etc. is applied.
|
|
* TODO this does not handle the case where origin/destination is provided as address only -> geocoding call to carta needed -> do in directions controller
|
|
*/
|
|
public List<RouteDTO> getPossibleRoutes(DirectionsRequest requestDTO, boolean includeCarRoute) {
|
|
assert requestDTO.getRoutingPreferencesDTO() != null;
|
|
HashMap<String, Direction> directionMap = getPossibleDirections(requestDTO);
|
|
ArrayList<RouteDTO> suggestedRoutes = 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();
|
|
|
|
// 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.");
|
|
}
|
|
double carDuration = carRoute.getDuration();
|
|
|
|
// Creating RouteDTOs for all available modes
|
|
if (includeCarRoute) {
|
|
Direction carDirection = directionMap.get("car");
|
|
if (carDirection.getRoutes() != null && !carDirection.getRoutes().isEmpty()) {
|
|
suggestedRoutes.add(createRouteDTO(
|
|
requestDTO,
|
|
carRoute,
|
|
List.of(new StepDTO(CAR, carRoute.getDistance())),
|
|
originAddress,
|
|
destinationAddress,
|
|
null,
|
|
null,
|
|
carCarbondDioxide,
|
|
carDuration,
|
|
false
|
|
));
|
|
}
|
|
}
|
|
|
|
if (directionMap.containsKey("bike")) {
|
|
Direction bikeDirection = directionMap.get("bike");
|
|
if (bikeDirection.getRoutes() != null && !bikeDirection.getRoutes().isEmpty()) {
|
|
Route bikeRoute = bikeDirection.getRoutes().getFirst();
|
|
suggestedRoutes.add(createRouteDTO(
|
|
requestDTO,
|
|
bikeRoute,
|
|
List.of(new StepDTO(BICYCLE, bikeRoute.getDistance())),
|
|
originAddress,
|
|
destinationAddress,
|
|
null,
|
|
null,
|
|
carCarbondDioxide,
|
|
carDuration,
|
|
false
|
|
));
|
|
}
|
|
}
|
|
|
|
if (directionMap.containsKey("walk")) {
|
|
Direction walkDirection = directionMap.get("walk");
|
|
if (walkDirection.getRoutes() != null && !walkDirection.getRoutes().isEmpty()) {
|
|
Route walkRoute = walkDirection.getRoutes().getFirst();
|
|
suggestedRoutes.add(createRouteDTO(
|
|
requestDTO,
|
|
walkRoute,
|
|
List.of(new StepDTO(Modality.WALKING, walkRoute.getDistance())),
|
|
originAddress,
|
|
destinationAddress,
|
|
null,
|
|
null,
|
|
carCarbondDioxide,
|
|
carDuration,
|
|
false
|
|
));
|
|
}
|
|
}
|
|
|
|
if (directionMap.containsKey("transit")) {
|
|
Direction transitDirection = directionMap.get("transit");
|
|
if (transitDirection.getRoutes() != null && !transitDirection.getRoutes().isEmpty()) {
|
|
for (Route route : transitDirection.getRoutes()) {
|
|
CartaTransitRouteProcessor routeProcessor = new CartaTransitRouteProcessor(route);
|
|
suggestedRoutes.add(createRouteDTO(
|
|
requestDTO,
|
|
route,
|
|
routeProcessor.getSteps(),
|
|
originAddress,
|
|
destinationAddress,
|
|
routeProcessor.getFirstStopName(),
|
|
routeProcessor.getLastStopName(),
|
|
carCarbondDioxide,
|
|
carDuration,
|
|
true
|
|
));
|
|
}
|
|
}
|
|
}
|
|
|
|
return suggestedRoutes;
|
|
}
|
|
|
|
private RouteDTO createRouteDTO(
|
|
DirectionsRequest requestDTO,
|
|
Route route,
|
|
List<StepDTO> steps,
|
|
AddressDTO originAddress,
|
|
AddressDTO destinationAddress,
|
|
String firstStopName,
|
|
String lastStopName,
|
|
double carVariantco2Emission,
|
|
double carVariantTimeSeconds,
|
|
boolean isTransit
|
|
) {
|
|
|
|
Instant arrivalTime;
|
|
Instant departureTime;
|
|
// Baseline is comparing with car version, except for alternative route requests
|
|
double timeDifferenceSeconds = route.getDuration() - carVariantTimeSeconds;
|
|
if (requestDTO.getArrivalTime() != null && requestDTO.getDepartureTime() != null) {
|
|
// Case 1: both arrival and departure time provided -> must be alternative route request
|
|
if (isTransit) { // for transit routes, we need to look up the exact arrival time at the last stop
|
|
arrivalTime = cartaTimeToInstant(route.getSteps().getLast().getStopTime(), requestDTO.getArrivalTime());
|
|
} else {
|
|
arrivalTime = requestDTO.getArrivalTime();
|
|
}
|
|
departureTime = arrivalTime.minusSeconds(route.getDuration());
|
|
timeDifferenceSeconds = route.getDuration() - (requestDTO.getArrivalTime().getEpochSecond() - requestDTO.getDepartureTime().getEpochSecond());
|
|
} else if (requestDTO.getArrivalTime() != null) {
|
|
// Case 2: only arrival time provided
|
|
if (isTransit) {
|
|
arrivalTime = cartaTimeToInstant(route.getSteps().getLast().getStopTime(), requestDTO.getArrivalTime());
|
|
} else {
|
|
arrivalTime = requestDTO.getArrivalTime();
|
|
}
|
|
departureTime = arrivalTime.minusSeconds(route.getDuration());
|
|
} else {
|
|
// Case 3: only departure time provided
|
|
if (isTransit) {
|
|
departureTime = cartaTimeToInstant(route.getSteps().getFirst().getStartTime(), requestDTO.getDepartureTime());
|
|
} else {
|
|
departureTime = requestDTO.getDepartureTime();
|
|
}
|
|
arrivalTime = departureTime.plusSeconds(route.getDuration());
|
|
}
|
|
|
|
double co2savings = carVariantco2Emission - route.getEmission().getCarbonDioxide();
|
|
|
|
RouteDTO routeDTO = new RouteDTO(
|
|
originAddress,
|
|
firstStopName,
|
|
route.getSourceCoordinate().getLatitude(),
|
|
route.getSourceCoordinate().getLongitude(),
|
|
destinationAddress,
|
|
lastStopName,
|
|
route.getTargetCoordinate().getLatitude(),
|
|
route.getTargetCoordinate().getLongitude(),
|
|
departureTime,
|
|
arrivalTime,
|
|
steps,
|
|
co2savings,
|
|
timeDifferenceSeconds,
|
|
route.getEmission().getCarbonDioxide()
|
|
);
|
|
return routeDTO;
|
|
}
|
|
|
|
/**
|
|
* Makes concurrent direction calls to CARTA for all modes requested + car as baseline.
|
|
* Possible keys of the returned Map:
|
|
* - car (always)
|
|
* - walk (optional)
|
|
* - bike (optional)
|
|
* - transit (optional)
|
|
*/
|
|
private HashMap<String, Direction> getPossibleDirections(DirectionsRequest requestDTO) {
|
|
Map<String, CompletableFuture<Direction>> futuresByMode = new HashMap<>();
|
|
assert requestDTO.getRoutingPreferencesDTO() != null;
|
|
|
|
// serves as baseline
|
|
futuresByMode.put("car", getCartaFuture(requestDTO, "driving", "", 1));
|
|
// type string for carta api
|
|
List<String> typeList = new ArrayList<>();
|
|
// add request futures for all modes request by user + assemble type string for a possible transit directions request
|
|
for (Modality modality : requestDTO.getRoutingPreferencesDTO().getModalitiesToConsider()) {
|
|
switch (modality) {
|
|
case WALKING -> futuresByMode.put("walk", getCartaFuture(requestDTO, "walking", "", 1));
|
|
case BICYCLE -> futuresByMode.put("bike", getCartaFuture(requestDTO, "cycling", "", 1));
|
|
case BUS -> {
|
|
typeList.add("3"); // bus
|
|
typeList.add("8"); // trolleybus
|
|
}
|
|
// case ESCOOTER -> typeList.add("X"); TODO - check if this and bike should be included in transit or separate
|
|
case TRAM -> typeList.add("0");
|
|
case TRAIN -> {
|
|
typeList.add("1"); // subway
|
|
typeList.add("2"); // rail
|
|
typeList.add("9"); // monorail
|
|
}
|
|
}
|
|
}
|
|
if (!typeList.isEmpty()) { // if any public transit the app allows toggling is selcted we add the funny transit types and make the transit request
|
|
typeList.add("4"); // Ferry
|
|
typeList.add("5"); // cablecar
|
|
typeList.add("6"); // gondola
|
|
typeList.add("7"); // funicular
|
|
String types = String.join(",", typeList);
|
|
futuresByMode.put("transit", getCartaFuture(requestDTO, "transit", types, 3));
|
|
}
|
|
|
|
// return all future results as list when resvoled
|
|
HashMap<String, Direction> directions = new HashMap<>();
|
|
for (Map.Entry<String, CompletableFuture<Direction>> entry : futuresByMode.entrySet()) {
|
|
directions.put(entry.getKey(), entry.getValue().join());
|
|
}
|
|
return directions;
|
|
}
|
|
|
|
/**
|
|
* Converts a Carta time (seconds since midnight of current day) to an Instant.
|
|
*
|
|
* @return
|
|
*/
|
|
private Instant cartaTimeToInstant(Integer secondsSinceMidnight, Instant instantOfReferenceDay) {
|
|
LocalDate date = instantOfReferenceDay.atZone(ZoneId.systemDefault()).toLocalDate();
|
|
LocalDateTime startOfDay = date.atStartOfDay();
|
|
LocalDateTime resultDateTime = startOfDay.plusSeconds(secondsSinceMidnight);
|
|
return resultDateTime.atZone(ZoneId.systemDefault()).toInstant();
|
|
}
|
|
|
|
/**
|
|
* Makes an individual call to the CARTA API and returns a direction future.
|
|
*/
|
|
private CompletableFuture<Direction> getCartaFuture(
|
|
DirectionsRequest requestDTO,
|
|
String mode,
|
|
String types,
|
|
int alternatives
|
|
) {
|
|
Instant departureTime = null;
|
|
Instant arrivalTime = null;
|
|
if (requestDTO.getArrivalTime() != null) {
|
|
arrivalTime = requestDTO.getArrivalTime();
|
|
} else if (requestDTO.getDepartureTime() != null) {
|
|
departureTime = requestDTO.getDepartureTime();
|
|
} else {
|
|
throw new IllegalArgumentException("Either arrivalTime or departureTime must be provided.");
|
|
}
|
|
|
|
return cartaClient.asyncGetRoute(
|
|
requestDTO.getOriginLat() + "," + requestDTO.getOriginLon(),
|
|
requestDTO.getDestinationLat() + "," + requestDTO.getDestinationLon(),
|
|
mode,
|
|
arrivalTime,
|
|
departureTime,
|
|
alternatives, // alternatives
|
|
null, // walkingSpeed
|
|
null, // transferTime TODO what is default? adapt?
|
|
types,
|
|
null, // range
|
|
requestDTO.getOriginLat() + "," + requestDTO.getOriginLon()
|
|
);
|
|
}
|
|
}
|