Skip to content
New issue

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

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

Already on GitHub? # 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 8 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
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,
httpClient: OkHttpClient = 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,42 @@ 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 Override the configuration for the navigation session. This was provided on init.
* @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 +266,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 +280,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 +294,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 @@ -23,21 +26,48 @@ data class NavigationUiState(
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>
}

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

private var lastLocation: UserLocation

class NavigationViewModel(
stateFlow: StateFlow<NavigationState>,
initialUserLocation: UserLocation,
) : ViewModel() {
private var lastLocation: UserLocation = initialUserLocation
init {
lastLocation =
requireNotNull(locationProvider.lastLocation) {
"LocationProvider must have a last location."
}
}

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 -> lastLocation
}

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

fun stopNavigation() {
ferrostarCore.stopNavigation()
}

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))
NavigationUiState.fromFerrostar(coreState, location)
}

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

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
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package com.stadiamaps.ferrostar.core.extensions

import uniffi.ferrostar.TripState

/**
* Get the progress of the trip while navigating.
*
* @return The progress of the trip, or null if the trip is not navigating.
*/
fun TripState.progress() =
when (this) {
is TripState.Navigating -> this.progress
is TripState.Complete,
TripState.Idle -> null
}

/**
* Get the visual instruction for the current step.
*
* @return The visual instruction for the current step or null.
*/
fun TripState.visualInstruction() =
try {
when (this) {
is TripState.Navigating -> this.visualInstruction
is TripState.Complete,
TripState.Idle -> null
}
} catch (_: NoSuchElementException) {
null
}

/**
* Get the deviation handler from the trip.
*
* @return The deviation handler if navigating or null.
*/
fun TripState.deviation() =
when (this) {
is TripState.Navigating -> this.deviation
is TripState.Complete,
TripState.Idle -> null
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
package com.stadiamaps.ferrostar.core.mock

import androidx.lifecycle.ViewModel
import com.stadiamaps.ferrostar.core.NavigationState
import com.stadiamaps.ferrostar.core.NavigationUiState
import com.stadiamaps.ferrostar.core.NavigationViewModel
import java.time.Instant
import kotlinx.coroutines.flow.StateFlow
import uniffi.ferrostar.CourseOverGround
import uniffi.ferrostar.GeographicCoordinate
import uniffi.ferrostar.ManeuverModifier
Expand Down Expand Up @@ -53,3 +57,9 @@ fun NavigationState.Companion.pedestrianExample(): NavigationState {
routeGeometry = listOf(),
isCalculatingNewRoute = false)
}

fun NavigationUiState.Companion.pedestrianExample(): NavigationUiState =
fromFerrostar(NavigationState.pedestrianExample(), UserLocation.pedestrianExample())

class MockNavigationViewModel(override val uiState: StateFlow<NavigationUiState>) :
ViewModel(), NavigationViewModel
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,11 @@ object AppModule {
profile = "bicycle",
httpClient = httpClient,
locationProvider = locationProvider,
navigationControllerConfig =
NavigationControllerConfig(
StepAdvanceMode.RelativeLineStringDistance(
minimumHorizontalAccuracy = 25U, automaticAdvanceDistance = 10U),
RouteDeviationTracking.StaticThreshold(25U, 10.0)),
costingOptions = mapOf("bicycle" to mapOf("use_roads" to 0.2)))

// Not all navigation apps will require this sort of extra configuration.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,6 @@ import com.stadiamaps.ferrostar.support.initialSimulatedLocation
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import uniffi.ferrostar.GeographicCoordinate
import uniffi.ferrostar.NavigationControllerConfig
import uniffi.ferrostar.RouteDeviationTracking
import uniffi.ferrostar.StepAdvanceMode
import uniffi.ferrostar.Waypoint
import uniffi.ferrostar.WaypointKind

Expand Down Expand Up @@ -81,15 +78,7 @@ fun DemoNavigationScene(
))

val route = routes.first()
viewModel =
core.startNavigation(
route = route,
config =
NavigationControllerConfig(
StepAdvanceMode.RelativeLineStringDistance(
minimumHorizontalAccuracy = 25U, automaticAdvanceDistance = 10U),
RouteDeviationTracking.StaticThreshold(25U, 10.0)),
)
viewModel = core.startNavigation(route = route)

locationProvider.setSimulatedRoute(route)
}
Expand Down
Loading
Loading