forked from stadiamaps/ferrostar
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFerrostarCore.swift
More file actions
551 lines (492 loc) · 24 KB
/
Copy pathFerrostarCore.swift
File metadata and controls
551 lines (492 loc) · 24 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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
import CoreLocation
import FerrostarCoreFFI
import Foundation
enum FerrostarCoreError: Error, Equatable {
/// The user has disabled location services for this app.
case locationServicesDisabled
case userLocationUnknown
/// The route request from the route adapter has an invalid URL.
///
/// This should never be encountered by end users of the library, and indicates a programming error
/// in the route adapter.
case invalidRequestUrl
/// Invalid (non-2xx) HTTP status
case httpStatusCode(Int)
/// A resumable cached session was not found. Enable navigation session caching.
case noCachedSession
}
/// Corrective action to take when the user deviates from the route.
public enum CorrectiveAction {
/// Don't do anything.
///
/// Note that this is most commonly paired with no route deviation tracking as a formality.
/// Think twice before using this as a mechanism for implementing your own logic outside of the provided framework,
/// as doing so will mean you miss out on state updates around alternate route calculation.
case doNothing
/// Tells the core to fetch new routes from the route adapter.
///
/// Once they are available, the delegate will be notified of the new routes.
case getNewRoutes(waypoints: [Waypoint])
}
/// Receives events from ``FerrostarCore``.
///
/// This is the central point responsible for relaying updates back to the application.
public protocol FerrostarCoreDelegate: AnyObject {
/// Called when navigation is started on a specific route.
func core(_ core: FerrostarCore, didStartWith route: Route)
/// Called when the core detects that the user has deviated from the route.
///
/// This hook enables app developers to take the most appropriate corrective action.
func core(
_ core: FerrostarCore,
correctiveActionForDeviation deviation: DeviationKind,
remainingWaypoints waypoints: [Waypoint]
) -> CorrectiveAction
/// Called when the core has loaded alternate routes.
///
/// The developer may decide whether or not to act on this information given the current trip state.
/// This is currently used for recalculation when the user diverges from the route, but can be extended for other
/// uses in the future.
/// Note that the `isCalculatingNewRoute` property of ``NavigationState`` will be true until this method returns.
/// Delegates may thus rely on this state introspection to decide what action to take given alternate routes.
func core(_ core: FerrostarCore, loadedAlternateRoutes routes: [Route])
}
/// This is the entrypoint for end users of Ferrostar on iOS, 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, set a ``delegate``,
/// and reuse the instance for as long as it makes sense (necessarily somewhat app-specific).
/// You can first call ``getRoutes(initialLocation:waypoints:)``
/// to fetch a list of possible routes asynchronously. After selecting a suitable route (either interactively by the
/// user, or programmatically), call ``startNavigation(route:config:)`` to start a session.
///
/// NOTE: it is the responsibility of the caller to ensure that the location provider is authorized to get
/// live user location with high precision.
// TODO: See about making FerrostarCore its own actor; then we can verify that we've published things back on the main actor. Need to see if this is possible with obj-c interop. See https://github.com/apple/swift-evolution/blob/main/proposals/0306-actors.md#actor-interoperability-with-objective-c
@objc public class FerrostarCore: NSObject {
/// The delegate which will receive Ferrostar core events.
public weak var delegate: FerrostarCoreDelegate?
/// The spoken instruction observer; responsible for text-to-speech announcements.
public let spokenInstructionObserver: SpokenInstructionObserver
/// 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).
public var minimumTimeBeforeRecalculation: TimeInterval = 5
/// The minimum distance (in meters) the user must move before performing another route recalculation.
///
/// This ensures that, while the user remains off the route, we don't keep triggering useless recalculations.
public var minimumMovementBeforeRecalculation = CLLocationDistance(50)
/// The observable state of the model (for easy binding in SwiftUI views).
@Published private var coreNavState: NavState?
@Published public private(set) var state: NavigationState?
@Published public private(set) var route: Route?
public let annotation: (any AnnotationPublishing)?
public let widgetProvider: WidgetProviding?
private let networkSession: URLRequestLoading
private let routeProvider: RouteProvider
private let locationProvider: LocationProviding
private let sessionBuilder: FerrostarSessionBuilder
private var navigationSession: NavigationSession?
private var routeRequestInFlight = false
private var lastAutomaticRecalculation: Date?
private var lastLocation: UserLocation?
// The last location from which we triggered a recalculation
private var lastRecalculationLocation: UserLocation?
private var recalculationTask: Task<Void, Never>?
private var queuedUtteranceIDs: Set<UUID> = Set()
public init(
routeProvider: RouteProvider,
locationProvider: LocationProviding,
sessionBuilder: FerrostarSessionBuilder,
networkSession: URLRequestLoading,
annotation: (any AnnotationPublishing)? = nil,
spokenInstructionObserver: SpokenInstructionObserver =
.initAVSpeechSynthesizer(), // Set up the a standard Apple AV Speech Synth.
widgetProvider: WidgetProviding? = nil
) {
self.routeProvider = routeProvider
self.locationProvider = locationProvider
self.networkSession = networkSession
self.annotation = annotation
self.spokenInstructionObserver = spokenInstructionObserver
self.widgetProvider = widgetProvider
self.sessionBuilder = sessionBuilder
super.init()
// Location provider setup
locationProvider.delegate = self
// Annotation publisher setup
self.annotation?.configure($state)
}
/// Initializes a core instance with the given parameters.
///
/// This designated initializer is the most flexible, but the convenience ones may be easier to use.
/// for common configurations.
///
/// - Parameters:
/// - routeProvider: The route provider is responsible for fetching routes from a server or locally.
/// - locationProvider: The location provider is responsible for tracking the user's location for navigation trip
/// updates.
/// - navigationControllerConfig: Configure the behavior of the navigation controller.
/// - networkSession: The network session to run route fetches on. A custom ``RouteProvider`` may not use this.
/// - annotation: An implementation of the annotation publisher that transforms custom annotation JSON into
/// published values of defined swift types.
public convenience init(
routeProvider: RouteProvider,
locationProvider: LocationProviding,
navigationControllerConfig: SwiftNavigationControllerConfig,
networkSession: URLRequestLoading,
annotation: (any AnnotationPublishing)? = nil,
spokenInstructionObserver: SpokenInstructionObserver =
.initAVSpeechSynthesizer(), // Set up the a standard Apple AV Speech Synth.
widgetProvider: WidgetProviding? = nil
) {
let sessionBuilder = FerrostarSessionBuilder(
config: navigationControllerConfig
)
self.init(
routeProvider: routeProvider,
locationProvider: locationProvider,
sessionBuilder: sessionBuilder,
networkSession: networkSession,
annotation: annotation,
spokenInstructionObserver: spokenInstructionObserver,
widgetProvider: widgetProvider
)
}
/// Initializes a core instance for a well-known API accessed over HTTP.
/// This convenience initializer provides easy access for any built-in route provider.
///
/// - Parameters
/// - routingEngine: The configuration for a well-known routing engine.
/// - navigationControllerConfig: Configuration of the navigation session.
/// - options: A dictionary of options to include in the request. The Valhalla request generator sets several
/// automatically (like `format`), but this lets you add arbitrary options so you can access the full API.
/// - networkSession: The network session to use. Don't set this unless you need to replace the networking stack
/// (ex: for testing).
/// - annotation: An implementation of the annotation publisher that transforms custom annotation JSON into
/// published values of defined swift types.
public convenience init(
wellKnownRouteProvider: WellKnownRouteProvider,
locationProvider: LocationProviding,
navigationControllerConfig: SwiftNavigationControllerConfig,
networkSession: URLRequestLoading = URLSession.shared,
annotation: (any AnnotationPublishing)? = nil,
spokenInstructionObserver: SpokenInstructionObserver =
.initAVSpeechSynthesizer(),
widgetProvider: WidgetProviding? = nil
) throws {
let adapter = try RouteAdapter.fromWellKnownRouteProvider(wellKnownRouteProvider: wellKnownRouteProvider)
self.init(
routeProvider: .routeAdapter(adapter),
locationProvider: locationProvider,
navigationControllerConfig: navigationControllerConfig,
networkSession: networkSession,
annotation: annotation,
spokenInstructionObserver: spokenInstructionObserver,
widgetProvider: widgetProvider
)
}
public convenience init(
routeAdapter: RouteAdapterProtocol,
locationProvider: LocationProviding,
navigationControllerConfig: SwiftNavigationControllerConfig,
networkSession: URLRequestLoading = URLSession.shared,
annotation: (any AnnotationPublishing)? = nil,
spokenInstructionObserver: SpokenInstructionObserver =
.initAVSpeechSynthesizer(),
widgetProvider: WidgetProviding? = nil
) {
self.init(
routeProvider: .routeAdapter(routeAdapter),
locationProvider: locationProvider,
navigationControllerConfig: navigationControllerConfig,
networkSession: networkSession,
annotation: annotation,
spokenInstructionObserver: spokenInstructionObserver,
widgetProvider: widgetProvider
)
}
public convenience init(
customRouteProvider: CustomRouteProvider,
locationProvider: LocationProviding,
sessionBuilder: FerrostarSessionBuilder,
networkSession: URLRequestLoading = URLSession.shared,
annotation: (any AnnotationPublishing)? = nil,
spokenInstructionObserver: SpokenInstructionObserver =
.initAVSpeechSynthesizer(),
widgetProvider: WidgetProviding? = nil
) {
self.init(
routeProvider: .customProvider(customRouteProvider),
locationProvider: locationProvider,
sessionBuilder: sessionBuilder,
networkSession: networkSession,
annotation: annotation,
spokenInstructionObserver: spokenInstructionObserver,
widgetProvider: widgetProvider
)
}
public convenience init(
customRouteProvider: CustomRouteProvider,
locationProvider: LocationProviding,
navigationControllerConfig: SwiftNavigationControllerConfig,
networkSession: URLRequestLoading = URLSession.shared,
annotation: (any AnnotationPublishing)? = nil,
spokenInstructionObserver: SpokenInstructionObserver =
.initAVSpeechSynthesizer(),
widgetProvider: WidgetProviding? = nil
) {
self.init(
routeProvider: .customProvider(customRouteProvider),
locationProvider: locationProvider,
navigationControllerConfig: navigationControllerConfig,
networkSession: networkSession,
annotation: annotation,
spokenInstructionObserver: spokenInstructionObserver,
widgetProvider: widgetProvider
)
}
/// Tries to get routes visiting one or more waypoints starting from the initial location.
///
/// Success and failure are communicated via ``delegate`` methods.
public func getRoutes(initialLocation: UserLocation, waypoints: [Waypoint]) async throws
-> [Route]
{
routeRequestInFlight = true
defer {
routeRequestInFlight = false
}
switch routeProvider {
case let .customProvider(provider):
return try await provider.getRoutes(userLocation: initialLocation, waypoints: waypoints)
case let .routeAdapter(routeAdapter):
let routeRequest = try routeAdapter.generateRequest(
userLocation: initialLocation,
waypoints: waypoints
)
let urlRequest = try routeRequest.urlRequest
let (data, response) = try await networkSession.loadData(with: urlRequest)
if let res = response as? HTTPURLResponse, res.statusCode < 200 || res.statusCode >= 300 {
throw FerrostarCoreError.httpStatusCode(res.statusCode)
} else {
return try routeAdapter.parseResponse(response: data)
}
}
}
/// Starts navigation with the given route. Any previous navigation session is dropped.
///
/// - Parameters:
/// - route: The route to navigate.
/// - userLocation: The user's location. This should be as close to the users location and the start of the route
/// as possible. If the location is too stale, the user may be almost immediately flagged as off the route,
/// triggering a recalculation.
/// If this parameter is `nil`, the last location will be obtained from the configured location provider
/// automatically.
/// If no location is available, this method will throw an exception.
/// - config: Override the configuration for the navigation session. This was provided on init.
public func startNavigation(
route: Route,
userLocation: UserLocation? = nil,
config: SwiftNavigationControllerConfig? = nil
) throws {
// This is technically possible, so we need to check and throw, but
// it should be rather difficult to get a location fix, get a route,
// and then somehow this property go nil again.
guard let location = userLocation ?? locationProvider.lastLocation else {
throw FerrostarCoreError.userLocationUnknown
}
// TODO: We should be able to circumvent this and simply start updating, wait and start nav.
// Create the navigation session.
let navigationSession = sessionBuilder.build(for: route, with: config?.ffiValue)
self.navigationSession = navigationSession
locationProvider.startUpdating()
self.route = route
let navState = navigationSession.getInitialState(location: location)
coreNavState = navState
state = NavigationState(
navState: navState,
routeGeometry: route.geometry
)
DispatchQueue.main.async {
self.update(navState, location: location)
}
}
/// Resumes a previously started navigation session from the last known state.
///
/// **Important! This feature is experimental and may exhibit unexpected behavior. Please
/// report any issues you encounter to help us improve it.**
///
/// - Parameter userLocation: The user's current location.
public func resumeNavigation(
userLocation: UserLocation? = nil
) throws {
// This is technically possible, so we need to check and throw, but
// it should be rather difficult to get a location fix, get a route,
// and then somehow this property go nil again.
guard let location = userLocation ?? locationProvider.lastLocation else {
throw FerrostarCoreError.userLocationUnknown
}
// TODO: We should be able to circumvent this and simply start updating, wait and start nav.
let (navigationSession, route, navState) = try sessionBuilder.buildResumedSession()
self.navigationSession = navigationSession
locationProvider.startUpdating()
self.route = route
coreNavState = navState
state = NavigationState(
navState: navState,
routeGeometry: route.geometry
)
DispatchQueue.main.async {
self.update(navState, location: location)
}
}
public func advanceToNextStep() {
guard let session = navigationSession, let state = coreNavState, let lastLocation
else {
return
}
let newState = session.advanceToNextStep(state: state)
update(newState, location: lastLocation)
}
// TODO: Ability to pause without totally stopping and clearing state
/// Stops navigation and stops requesting location updates (to save battery).
public func stopNavigation() {
navigationSession = nil
route = nil
state = nil
queuedUtteranceIDs.removeAll()
locationProvider.stopUpdating()
spokenInstructionObserver.stopAndClearQueue()
widgetProvider?.terminate()
lastRecalculationLocation = nil
}
/// Internal state update.
///
/// You should call this rather than setting properties directly
private func update(_ state: NavState, location: UserLocation) {
DispatchQueue.main.async {
self.coreNavState = state
self.state?.tripState = state.tripState
switch state.tripState {
case .idle(userLocation: _):
break
case let .navigating(
currentStepGeometryIndex: _,
userLocation: _,
snappedUserLocation: _,
remainingSteps: _,
remainingWaypoints: remainingWaypoints,
progress: tripProgress,
summary: _,
deviation: deviation,
visualInstruction: visualInstruction,
spokenInstruction: spokenInstruction,
annotationJson: _
):
switch deviation {
case .noDeviation:
// No action
break
case let .deviation(kind: kind):
guard !self.routeRequestInFlight, // We can't have a request in flight already
// Ensure a minimum cool down before a new route fetch
self.lastAutomaticRecalculation?.timeIntervalSinceNow ?? -TimeInterval
.greatestFiniteMagnitude < -self
.minimumTimeBeforeRecalculation,
// Don't recalculate again if the user hasn't moved much
self.lastRecalculationLocation?.clLocation
.distance(from: location.clLocation) ?? .greatestFiniteMagnitude
> self
.minimumMovementBeforeRecalculation
else {
break
}
switch self.delegate?.core(
self,
correctiveActionForDeviation: kind,
remainingWaypoints: remainingWaypoints
) ?? .getNewRoutes(waypoints: remainingWaypoints) {
case .doNothing:
break
case let .getNewRoutes(waypoints):
self.state?.isCalculatingNewRoute = true
self.lastRecalculationLocation = location
self.recalculationTask = Task {
do {
let routes = try await self.getRoutes(
initialLocation: location,
waypoints: waypoints
)
if let delegate = self.delegate {
delegate.core(self, loadedAlternateRoutes: routes)
} else if let route = routes.first {
// Default behavior when no delegate is assigned:
// accept the first route, as this is what most users want when they go off route.
try self.startNavigation(route: route)
}
} catch {
// Do nothing; this exists to enable us to run what amounts to an "async defer"
}
await MainActor.run {
self.lastAutomaticRecalculation = Date()
self.state?.isCalculatingNewRoute = false
}
}
}
}
var spokenInstructionToAlert: SpokenInstruction?
if let spokenInstruction,
!self.queuedUtteranceIDs.contains(spokenInstruction.utteranceId)
{
self.queuedUtteranceIDs.insert(spokenInstruction.utteranceId)
// Only set the spoken instruction to alert when it's queued here.
// Otherwise we'll ignore it.
spokenInstructionToAlert = spokenInstruction
// This should not happen on the main queue as it can block;
// we'll probably remove the need for this eventually
// by making FerrostarCore its own actor
DispatchQueue.global(qos: .default).async {
self.spokenInstructionObserver.spokenInstructionTriggered(spokenInstruction)
}
}
// Update the dynamic island if it's being used.
if let visualInstruction {
self.widgetProvider?.update(
visualInstruction: visualInstruction,
spokenInstruction: spokenInstructionToAlert,
tripProgress: tripProgress
)
}
case .complete(userLocation: _, summary: _):
// End the widget session if the route is completed, regardless of whether stop is called.
// This avoids a dangling LiveActivity the user must close.
self.widgetProvider?.terminate()
}
}
}
}
extension FerrostarCore: LocationManagingDelegate {
public func locationManager(_: LocationProviding, didUpdateLocations locations: [UserLocation]) {
guard let location = locations.last,
let navState = coreNavState,
let newState = navigationSession?.updateUserLocation(
location: location, state: navState
)
else {
return
}
lastLocation = location
update(newState, location: location)
}
public func locationManager(_: LocationProviding, didUpdateHeading _: Heading) {
// TODO: Make use of heading in TripState?
// state?.heading = newHeading
}
public func locationManager(_: LocationProviding, didFailWithError _: Error) {
// TODO: Decide if/how to propagate this upstream later.
// For initial releases, we simply assume that the developer has requested the correct permissions
// and ensure this before attempting to start location updates.
}
}