-
Notifications
You must be signed in to change notification settings - Fork 76
Expand file tree
/
Copy pathFerrostarCore.ts
More file actions
412 lines (354 loc) · 13.2 KB
/
Copy pathFerrostarCore.ts
File metadata and controls
412 lines (354 loc) · 13.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
import {
GeographicCoordinate,
Heading,
NavigationController,
NavigationControllerConfig,
Route,
RouteDeviation,
TripState,
UserLocation,
Waypoint,
} from '@stadiamaps/ferrostar-uniffi-react-native';
import { getNanoTime } from './_utils';
import type { AlternativeRouteProcessor } from './AlternativeRouteProcessor';
import {
LocationProvider,
type LocationProviderInterface,
type LocationUpdateListener,
} from './LocationProvider';
import {
CorrectiveAction,
type RouteDeviationHandler,
} from './RouteDeviationHandler';
import type { RouteProviderInterface } from './RouteProvider';
import { RouteProvider } from './RouteProvider';
/**
* Represents the complete state of the navigation session provided by FerrostarCore-RS
*/
export class NavigationState {
static #instance: NavigationState;
public tripState: TripState = TripState.Idle.new();
public routeGeometry: Array<GeographicCoordinate> = [];
public isCalculatingNewRoute: boolean = false;
private constructor() {}
static instance(): NavigationState {
if (this.#instance) {
return this.#instance;
}
this.#instance = new NavigationState();
return this.#instance;
}
isNavigating(): boolean {
if (TripState.Navigating.instanceOf(this.tripState.tag)) {
return true;
}
return false;
}
set(
tripState: TripState,
routeGeometry: Array<GeographicCoordinate>,
isCalculatingNewRoute: boolean
) {
this.tripState = tripState;
this.routeGeometry = routeGeometry;
this.isCalculatingNewRoute = isCalculatingNewRoute;
}
reset() {
this.tripState = TripState.Idle.new();
this.routeGeometry = [];
this.isCalculatingNewRoute = false;
}
}
/**
* This is the entrypoint for end users of Ferrostar on React Native, and is responsible for "driving"
* the navigation with location updates and other events.
*
* The usual flow is for callers to configure an instance of the core reuse the instance for as long
* as it makes sense (necessarily somewhat app-specific). You can first call {@link getRoutes} to fetch a
* list of possible routes asynchronously. After selecting a suitable route (either interactively by
* the user or programmatically), call {@link startNavigation} to start a session.
*
* NOTE: It is the responsibility of the caller to ensure that the location manager is authorized to
* access the user's location.
*/
export class FerrostarCore implements LocationUpdateListener {
navigationControllerConfig: NavigationControllerConfig;
locationProvider: LocationProviderInterface;
routeProvider: RouteProviderInterface;
/**
* The minimum time to wait before initiating another route recalculation.
*
* This matters in the case that a user is off route, the framework calculates a new route, and
* the user is determined to still be off the new route. This adds a minimum delay (default 5
* seconds).
*/
minimumTimeBeforeRecalculation: number = 5;
/**
* Controls what happens when the user deviates from the route.
*
* The default behavior (when this property is `null`) is to fetch new routes automatically. These
* will be passed to the {@link AlternativeRouteProcessor} or, if none is specified, navigation will
* automatically proceed according to the first route.
*/
deviationHandler?: RouteDeviationHandler;
/**
* Handles alternative routes as they are loaded.
*
* The default behavior (when this property is `null`) is to automatically reroute the user when
* an alternative route arrives due to the user being off course. In all other cases, no action
* will be taken unless an {@link AlternativeRouteProcessor} is provided.
*/
alternativeRouteProcessor?: AlternativeRouteProcessor;
// Maintains a set of utterance IDs which been seen previously.
// This helps us maintain the guarantee that the observer won't see the same one twice.
_queuedUtteranceIds: Array<string> = [];
isCalculatingNewRoute: boolean = false;
_navigationController?: NavigationController;
_state: NavigationState = NavigationState.instance();
_routeRequestInFlight: boolean = false;
_lastAutomaticRecalculation?: number;
_lastLocation?: UserLocation;
_listeners: Map<number, (state: NavigationState) => void> = new Map();
constructor(
valhallaEndpointURL: string,
profile: string,
navigationControllerConfig: NavigationControllerConfig,
options: Record<string, unknown> = {},
locationProvider: LocationProviderInterface = new LocationProvider(),
routeProvider: RouteProviderInterface = new RouteProvider(
valhallaEndpointURL,
profile,
options
)
) {
this.navigationControllerConfig = navigationControllerConfig;
this.routeProvider = routeProvider;
this.locationProvider = locationProvider;
}
async getRoutes(
initialLocation: UserLocation,
waypoints: Array<Waypoint>
): Promise<Array<Route>> {
try {
this._routeRequestInFlight = true;
return await this.routeProvider.getRoute(initialLocation, waypoints);
} catch (e) {
console.log(`Failed to get routes: ${e}`);
return [];
} finally {
this._routeRequestInFlight = false;
}
}
/**
* Starts a navigation session with the given parameters (erasing any previous state).
*
* Once you have a location fix and a desired route, invoke this method. It will automatically
* subscribe to location provider updates. Returns a view model which is tied to the navigation
* session. You can observe this in either your own or one of the provided navigation compose
* views.
*
* WARNING: If you want to reuse the existing view model, ex: when getting a new route after going
* off course, use {@link 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.
* @throws UserLocationUnknown if the location provider has no last known location.
*/
startNavigation(route: Route, config?: NavigationControllerConfig) {
this.stopNavigation();
this.navigationControllerConfig = config ?? this.navigationControllerConfig;
const controller = new NavigationController(
route,
this.navigationControllerConfig
);
const firstRouteLocation = route.geometry[0];
if (firstRouteLocation === undefined) {
return;
}
const startingLocation =
this.locationProvider.lastLocation ??
UserLocation.new({
coordinates: firstRouteLocation,
horizontalAccuracy: 0.0,
courseOverGround: undefined,
timestamp: new Date(),
speed: undefined,
});
const initialTripState = controller.getInitialState(startingLocation);
this._navigationController = controller;
this._state.set(initialTripState, route.geometry, false);
this.handleStateUpdate(initialTripState, startingLocation);
// Add location provider listener here
this.locationProvider.addListener(this);
}
/**
* Replace the currently running route with a new one.
*
* This allows you to reuse the existing view model. Do not call this method unless you are
* already navigating.
*
* @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.
*/
replaceRoute(route: Route, config?: NavigationControllerConfig) {
this.navigationControllerConfig = config ?? this.navigationControllerConfig;
const controller = new NavigationController(
route,
this.navigationControllerConfig
);
const firstRouteLocation = route.geometry[0];
if (firstRouteLocation === undefined) {
return;
}
const startingLocation =
this.locationProvider.lastLocation ??
UserLocation.new({
coordinates: firstRouteLocation,
horizontalAccuracy: 0.0,
courseOverGround: undefined,
timestamp: new Date(),
speed: undefined,
});
this._navigationController = controller;
const newState = controller.getInitialState(startingLocation);
this._state.set(newState, route.geometry, false);
this.handleStateUpdate(newState, startingLocation);
}
advanceToNextStep() {
const controller = this._navigationController;
const location = this._lastLocation;
if (controller === undefined || location === undefined) {
return;
}
const newState = controller.advanceToNextStep(this._state.tripState);
this._state.set(
newState,
this._state.routeGeometry,
this.isCalculatingNewRoute
);
this.handleStateUpdate(newState, location);
}
stopNavigation(stopLocationUpdates: boolean = true) {
if (!this._state.isNavigating()) {
return;
}
if (stopLocationUpdates) {
this.locationProvider.removeListener(this);
}
this._navigationController?.uniffiDestroy();
this._navigationController = undefined;
this._state.reset();
// TODO: handle state change event here
// Send listeners the new state
this._listeners.forEach((listener) => {
listener(this._state);
});
this._queuedUtteranceIds = [];
// TODO: add TTS observer to clear queued utterances
}
private async handleStateUpdate(newState: TripState, location: UserLocation) {
// If we're not navigating, we don't care about state changes.
if (!TripState.Navigating.instanceOf(newState)) {
return;
}
// If we're not recalculating a new route, we don't care about state changes.
if (RouteDeviation.OffRoute.instanceOf(newState.inner.deviation)) {
// Check that the last automatic recalculation wasn't too recent.
// We have to do some weird thing here with hrTime since JavaScript doesn't have a nice nanoseoncds method.
const isGreaterThanMinimumTime = this._lastAutomaticRecalculation
? getNanoTime() - this._lastAutomaticRecalculation >
this.minimumTimeBeforeRecalculation
: true;
if (this._routeRequestInFlight || !isGreaterThanMinimumTime) {
return;
}
const action =
this.deviationHandler?.correctiveActionForDeviation(
this,
newState.inner.deviation.inner.deviationFromRouteLine,
newState.inner.remainingWaypoints
) ?? CorrectiveAction.GetNewRoutes;
switch (action) {
case CorrectiveAction.DoNothing:
break;
case CorrectiveAction.GetNewRoutes:
this.isCalculatingNewRoute = true;
try {
const routes = await this.getRoutes(
location,
newState.inner.remainingWaypoints
);
const config = this.navigationControllerConfig;
const processor = this.alternativeRouteProcessor;
const state = this._state;
// Make sure we are still navigating and the new route is still relevant.
if (
TripState.Navigating.instanceOf(state.tripState) &&
RouteDeviation.OffRoute.instanceOf(
state.tripState.inner.deviation
)
) {
if (processor !== undefined) {
processor.loadedAlternativeRoutes(this, routes);
} else if (routes.length > 0) {
// Default behavior when there is no user-defined behavior:
// accept the first route, as this is what most users want when they go off route.
const firstRoute = routes[0];
// Stupid TS can't figure out that firstRoute is not undefined here.
if (firstRoute === undefined) {
throw new Error('No route found');
}
this.replaceRoute(firstRoute, config);
}
}
} catch (e) {
console.log(`Failed to recalculate route: ${e}`);
} finally {
this._lastAutomaticRecalculation = getNanoTime();
this.isCalculatingNewRoute = false;
}
break;
}
}
// Send listeners the new state
this._listeners.forEach((listener) => {
listener(this._state);
});
}
addStateListener(listener: (state: NavigationState) => void): number {
// Create id for listener
const id = this._listeners.size + 1;
this._listeners.set(id, listener);
return id;
}
removeStateListener(id: number): void {
this._listeners.delete(id);
}
onLocationUpdate(location: UserLocation): void {
this._lastLocation = location;
const controller = this._navigationController;
if (controller === undefined) {
return;
}
const newState = controller.updateUserLocation(
location,
this._state.tripState
);
this.handleStateUpdate(newState, location);
this._state.set(
newState,
this._state.routeGeometry,
this.isCalculatingNewRoute
);
}
// TODO: remove once we have a way to update the heading
// eslint-disable-next-line @typescript-eslint/no-unused-vars
onHeadingUpdate(_heading: Heading): void {
// TODO: heading update
}
// TODO: handle the spoken instructions queue here
// TODO: foreground service update here
}