Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Synced android and ios navigation state, refactored NavigationViewModel #167

Merged
merged 15 commits into from
Jul 31, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,8 @@ Before pushing, run the following in the `common` folder:
1. Run `cargo fmt` to automatically format any new rust code.
2. Run `cargo insta review` to update snapshot testing changes.
3. Run `cargo test` to validate testing and ensure snapshot changes were correctly applied by step 2.
4. Manually bump the version on the ferrostar Cargo.toml at `common/ferrostar/Cargo.toml`. If you forget to do this and make breaking changes, CI will fail.
if you don't.

### Web

Expand Down
2 changes: 1 addition & 1 deletion android/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -25,5 +25,5 @@ publishing {

allprojects {
group = "com.stadiamaps.ferrostar"
version = "0.5.0"
version = "0.6.0"
}
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,9 @@ class FerrostarCoreTest {
requestGenerator = MockRouteRequestGenerator(),
responseParser = MockRouteResponseParser(routes = listOf())),
httpClient = OkHttpClient.Builder().addInterceptor(interceptor).build(),
locationProvider = SimulatedLocationProvider())
locationProvider = SimulatedLocationProvider(),
navigationControllerConfig =
NavigationControllerConfig(StepAdvanceMode.Manual, RouteDeviationTracking.None))

try {
// Tests that the core generates a request and attempts to process it, but throws due to the
Expand Down Expand Up @@ -152,7 +154,9 @@ class FerrostarCoreTest {
requestGenerator = MockRouteRequestGenerator(),
responseParser = MockRouteResponseParser(routes = listOf(mockRoute))),
httpClient = OkHttpClient.Builder().addInterceptor(interceptor).build(),
locationProvider = SimulatedLocationProvider())
locationProvider = SimulatedLocationProvider(),
navigationControllerConfig =
NavigationControllerConfig(StepAdvanceMode.Manual, RouteDeviationTracking.None))
val routes =
core.getRoutes(
initialLocation =
Expand Down Expand Up @@ -199,7 +203,9 @@ class FerrostarCoreTest {
FerrostarCore(
customRouteProvider = routeProvider,
httpClient = OkHttpClient.Builder().addInterceptor(interceptor).build(),
locationProvider = SimulatedLocationProvider())
locationProvider = SimulatedLocationProvider(),
navigationControllerConfig =
NavigationControllerConfig(StepAdvanceMode.Manual, RouteDeviationTracking.None))
val routes =
core.getRoutes(
initialLocation =
Expand Down Expand Up @@ -264,7 +270,9 @@ class FerrostarCoreTest {
requestGenerator = MockRouteRequestGenerator(),
responseParser = MockRouteResponseParser(routes = listOf(mockRoute))),
httpClient = OkHttpClient.Builder().addInterceptor(interceptor).build(),
locationProvider = locationProvider)
locationProvider = locationProvider,
navigationControllerConfig =
NavigationControllerConfig(StepAdvanceMode.Manual, RouteDeviationTracking.None))

val deviationHandler = DeviationHandler()
core.deviationHandler = deviationHandler
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@ import okhttp3.mock.url
import org.junit.Assert.assertEquals
import org.junit.Test
import uniffi.ferrostar.GeographicCoordinate
import uniffi.ferrostar.NavigationControllerConfig
import uniffi.ferrostar.RouteDeviationTracking
import uniffi.ferrostar.StepAdvanceMode
import uniffi.ferrostar.UserLocation
import uniffi.ferrostar.Waypoint
import uniffi.ferrostar.WaypointKind
Expand Down Expand Up @@ -246,7 +249,9 @@ class ValhallaCoreTest {
valhallaEndpointURL = URL(valhallaEndpointUrl),
profile = "auto",
httpClient = OkHttpClient.Builder().addInterceptor(interceptor).build(),
locationProvider = SimulatedLocationProvider())
locationProvider = SimulatedLocationProvider(),
navigationControllerConfig =
NavigationControllerConfig(StepAdvanceMode.Manual, RouteDeviationTracking.None))

return runTest {
val routes =
Expand Down Expand Up @@ -291,6 +296,8 @@ class ValhallaCoreTest {
profile = "auto",
httpClient = OkHttpClient.Builder().addInterceptor(interceptor).build(),
locationProvider = SimulatedLocationProvider(),
navigationControllerConfig =
NavigationControllerConfig(StepAdvanceMode.Manual, RouteDeviationTracking.None),
costingOptions = mapOf("auto" to mapOf("useTolls" to 0)))

return runTest {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import java.util.concurrent.Executors
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import okhttp3.OkHttpClient
Expand All @@ -29,10 +31,10 @@ import uniffi.ferrostar.Waypoint
/** Represents the complete state of the navigation session provided by FerrostarCore-RS. */
data class NavigationState(
/** The raw trip state from the core. */
val tripState: TripState,
val routeGeometry: List<GeographicCoordinate>,
val tripState: TripState = TripState.Idle,
val routeGeometry: List<GeographicCoordinate> = emptyList(),
/** Indicates when the core is calculating a new route (ex: due to the user being off route). */
val isCalculatingNewRoute: Boolean
val isCalculatingNewRoute: Boolean = false
) {
companion object
}
Expand All @@ -57,6 +59,7 @@ class FerrostarCore(
val routeProvider: RouteProvider,
val httpClient: OkHttpClient,
val locationProvider: LocationProvider,
navigationControllerConfig: NavigationControllerConfig,
) : LocationUpdateListener {
companion object {
private const val TAG = "FerrostarCore"
Expand Down Expand Up @@ -112,46 +115,56 @@ class FerrostarCore(
private val _executor = Executors.newSingleThreadScheduledExecutor()
private val _scope = CoroutineScope(Dispatchers.IO)
private var _navigationController: NavigationController? = null
private var _state: MutableStateFlow<NavigationState>? = null
private var _state: MutableStateFlow<NavigationState> = MutableStateFlow(NavigationState())
private var _routeRequestInFlight = false
private var _lastAutomaticRecalculation: Long? = null
private var _lastLocation: UserLocation? = null

private var _config: NavigationControllerConfig? = null
private var _config: NavigationControllerConfig = navigationControllerConfig

/**
* The current state of the navigation session. This can be used in a custom ViewModel or
* elsewhere. If using the default behavior, use the DefaultNavigationViewModel by injection or as
* provided by startNavigation().
*/
var state: StateFlow<NavigationState> = _state.asStateFlow()

constructor(
valhallaEndpointURL: URL,
profile: String,
httpClient: OkHttpClient,
locationProvider: LocationProvider,
navigationControllerConfig: NavigationControllerConfig,
costingOptions: Map<String, Any> = emptyMap(),
) : this(
RouteProvider.RouteAdapter(
RouteAdapter.newValhallaHttp(
valhallaEndpointURL.toString(), profile, jsonAdapter.toJson(costingOptions))),
httpClient,
locationProvider,
)
navigationControllerConfig)

constructor(
routeAdapter: RouteAdapter,
httpClient: OkHttpClient,
locationProvider: LocationProvider,
navigationControllerConfig: NavigationControllerConfig,
) : this(
RouteProvider.RouteAdapter(routeAdapter),
httpClient,
locationProvider,
)
navigationControllerConfig)

constructor(
customRouteProvider: CustomRouteProvider,
httpClient: OkHttpClient,
locationProvider: LocationProvider,
navigationControllerConfig: NavigationControllerConfig,
) : this(
RouteProvider.CustomProvider(customRouteProvider),
httpClient,
locationProvider,
)
navigationControllerConfig)

suspend fun getRoutes(initialLocation: UserLocation, waypoints: List<Waypoint>): List<Route> =
try {
Expand Down Expand Up @@ -198,31 +211,43 @@ class FerrostarCore(
* WARNING: If you want to reuse the existing view model, ex: when getting a new route after going
* off course, use [replaceRoute] instead! Otherwise, you will miss out on updates as the old view
* model is "orphaned"!
*
* @param route the route to navigate.
* @param config change the configuration in the core before staring navigation. This was
* originally provided on init, but you can set a new value for future sessions.
* @return a view model tied to the navigation session. This can be ignored if you're injecting
* the [NavigationViewModel]/[DefaultNavigationViewModel].
* @throws UserLocationUnknown if the location provider has no last known location.
*/
@Throws(UserLocationUnknown::class)
fun startNavigation(route: Route, config: NavigationControllerConfig): NavigationViewModel {
fun startNavigation(
route: Route,
config: NavigationControllerConfig? = null
): DefaultNavigationViewModel {
stopNavigation()

// Apply the new config if provided, otherwise use the original.
_config = config ?: _config

val controller =
NavigationController(
route,
config,
_config,
)
val startingLocation =
locationProvider.lastLocation
?: UserLocation(route.geometry.first(), 0.0, null, Instant.now(), null)

val initialTripState = controller.getInitialState(startingLocation)
val stateFlow =
MutableStateFlow(NavigationState(tripState = initialTripState, route.geometry, false))
val newState = NavigationState(tripState = initialTripState, route.geometry, false)
handleStateUpdate(initialTripState, startingLocation)

_navigationController = controller
_state = stateFlow
_state.value = newState

locationProvider.addListener(this, _executor)

return NavigationViewModel(stateFlow, startingLocation)
return DefaultNavigationViewModel(this, locationProvider)
}

/**
Expand All @@ -242,10 +267,7 @@ class FerrostarCore(
?: UserLocation(route.geometry.first(), 0.0, null, Instant.now(), null)

_navigationController = controller
if (_state == null) {
android.util.Log.e(TAG, "Unexpected null state")
}
_state?.update {
_state.update {
val newState = controller.getInitialState(startingLocation)

handleStateUpdate(newState, startingLocation)
Expand All @@ -259,7 +281,7 @@ class FerrostarCore(
val location = _lastLocation

if (controller != null && location != null) {
_state?.update { currentValue ->
_state.update { currentValue ->
val newState = controller.advanceToNextStep(state = currentValue.tripState)

handleStateUpdate(newState, location)
Expand All @@ -273,7 +295,7 @@ class FerrostarCore(
locationProvider.removeListener(this)
_navigationController?.destroy()
_navigationController = null
_state = null
_state.value = NavigationState()
_queuedUtteranceIds.clear()
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ package com.stadiamaps.ferrostar.core

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.stadiamaps.ferrostar.core.extensions.deviation
import com.stadiamaps.ferrostar.core.extensions.progress
import com.stadiamaps.ferrostar.core.extensions.visualInstruction
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.map
Expand All @@ -15,29 +18,51 @@ import uniffi.ferrostar.UserLocation
import uniffi.ferrostar.VisualInstruction

data class NavigationUiState(
val snappedLocation: UserLocation,
val snappedLocation: UserLocation?,
val heading: Float?,
val routeGeometry: List<GeographicCoordinate>,
val visualInstruction: VisualInstruction?,
val spokenInstruction: SpokenInstruction?,
val progress: TripProgress?,
val isCalculatingNewRoute: Boolean?,
val routeDeviation: RouteDeviation?
)
) {
companion object {
fun fromFerrostar(coreState: NavigationState, userLocation: UserLocation?): NavigationUiState =
NavigationUiState(
snappedLocation = userLocation,
// TODO: Heading/course over ground
heading = null,
routeGeometry = coreState.routeGeometry,
visualInstruction = coreState.tripState.visualInstruction(),
spokenInstruction = null,
progress = coreState.tripState.progress(),
isCalculatingNewRoute = coreState.isCalculatingNewRoute,
routeDeviation = coreState.tripState.deviation())
}
}

interface NavigationViewModel {
val uiState: StateFlow<NavigationUiState>

fun stopNavigation()
}

class DefaultNavigationViewModel(
private val ferrostarCore: FerrostarCore,
locationProvider: LocationProvider
) : ViewModel(), NavigationViewModel {

class NavigationViewModel(
stateFlow: StateFlow<NavigationState>,
initialUserLocation: UserLocation,
) : ViewModel() {
private var lastLocation: UserLocation = initialUserLocation
private var lastLocation: UserLocation? = locationProvider.lastLocation

val uiState =
stateFlow
override val uiState =
ferrostarCore.state
.map { coreState ->
lastLocation =
when (coreState.tripState) {
is TripState.Navigating -> coreState.tripState.snappedUserLocation
is TripState.Complete -> lastLocation
is TripState.Complete,
TripState.Idle -> locationProvider.lastLocation
}

uiState(coreState, lastLocation)
Expand All @@ -48,39 +73,12 @@ class NavigationViewModel(
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(),
initialValue = uiState(stateFlow.value, initialUserLocation))
initialValue = uiState(ferrostarCore.state.value, lastLocation))

private fun uiState(coreState: NavigationState, location: UserLocation) =
NavigationUiState(
snappedLocation = location,
// TODO: Heading/course over ground
heading = null,
routeGeometry = coreState.routeGeometry,
visualInstruction = visualInstructionForState(coreState.tripState),
spokenInstruction = null,
progress = progressForState(coreState.tripState),
isCalculatingNewRoute = coreState.isCalculatingNewRoute,
routeDeviation = deviationForState(coreState.tripState))
}

private fun progressForState(newState: TripState) =
when (newState) {
is TripState.Navigating -> newState.progress
is TripState.Complete -> null
}
override fun stopNavigation() {
ferrostarCore.stopNavigation()
}

private fun visualInstructionForState(newState: TripState) =
try {
when (newState) {
is TripState.Navigating -> newState.visualInstruction
is TripState.Complete -> null
}
} catch (_: NoSuchElementException) {
null
}

private fun deviationForState(newState: TripState) =
when (newState) {
is TripState.Navigating -> newState.deviation
is TripState.Complete -> null
}
private fun uiState(coreState: NavigationState, location: UserLocation?) =
NavigationUiState.fromFerrostar(coreState, location)
}
Loading
Loading