# Trip management

## Trip autostart

The automatic mode detects vehicle movements and triggers the trip analysis without driver intervention while the application is in background. The analysis is stopped automatically at the end of the trip.&#x20;

This feature is recommended to avoid driver distraction and phone handling while driving. The automatic mode has been optimized to limit the battery drain.

By default, automatic trip detection is disabled, but you can enable it by calling the following method:

```swift
DriveKitTripAnalysis.shared.activateAutoStart(enable: true)
```

To disable automatic trip detection call the same method with parameter `enable` set to `false`

```swift
DriveKitTripAnalysis.shared.activateAutoStart(enable: false)
```

{% hint style="warning" %}
If a trip is running when automatic trip detection is disable, the trip will **not** be canceled. If you want to cancel the trip, you should also call [`cancelTrip`](#cancel-a-trip) method.
{% endhint %}

### Manually start a trip

You can start a trip by calling the following method:

```swift
DriveKitTripAnalysis.shared.startTrip()
```

{% hint style="info" %}
If a trip's already started, calling this method will have no effect.
{% endhint %}

### Stop a trip

You can stop a trip by calling the following method. The trip will be stopped instantly:

```swift
DriveKitTripAnalysis.shared.stopTrip()
```

{% hint style="info" %}
If a vehicle stops longer than the [timeout configured](#custom-stop-timeout), the trip will be stopped automatically.
{% endhint %}

{% hint style="info" %}
If there is no running trip, calling this method will have no effect.
{% endhint %}

### Cancel a trip

If you want to cancel a trip, you can call this method:

```swift
DriveKitTripAnalysis.shared.cancelTrip()
```

{% hint style="info" %}
If no trip is running or if the trip has been sent to the server and is currently analyzed, calling this method will have no effect.
{% endhint %}

## Vehicle

To obtain a more precise analysis on driving behavior, it's recommended to configure the vehicle used by the driver. You can do this by calling the following method:

```swift
DriveKitTripAnalysis.shared.setVehicle(vehicle: TripVehicle?)
```

A detailed description of vehicle parameter is available [here](https://docs.drivequant.com/trip-analysis/references#tripvehicle).

{% hint style="info" %}
If no vehicle is configured a default vehicle will be configured with following parameters:

* `carTypeIndex = 1`
* `carEngineIndex = 1`
* `carPower = 150`
* `carMass = 1400`
* `carGearboxIndex = 2`
* `carConsumption = 4.5`
* `engineDisplacement = 1200`
* `frontTireSize = "205/55/16"`
* `rearTireSize = "205/55/16"`
* `length = 4.5`
* `width = 1.8`
* `height = 1.45`
* `engineCylinderNb = 4`
* `driveWheels = 0`
  {% endhint %}

## SDK recorder state

Two methods are available to determine SDK state.

```swift
DriveKitTripAnalysis.shared.isTripRunning()
```

This method returns `false` if the SDK is in `inactive` state, and no trip is currently running.

If you want a more detailed state of the SDK, you can call the following method:

```swift
DriveKitTripAnalysis.shared.getRecorderState()
```

This method returns the state of the SDK:

* `inactive`: No trip is running.
* `starting`: The auto start mode detects a movement of the user and checks if it's a trip in vehicle.
* `running`: The trip has been confirmed by the speed of the movement.
* `stopping`: The SDK is in this state when a potential trip end is detected. If the trip continues, the SDK goes back in `running` state. The [duration of the stopping state](https://docs.drivequant.com/trip-analysis/ios/broken-reference) can be configured.
* `sending`: The trip is finished and is being sent to DriveQuant's server. When the SDK has the response from the server, the state becomes `inactive` waiting for the next trip.

## Get information about the current trip

When a trip analysis is starting, you may need some information about it, like the `StartMode` which triggers the trip recording, a local unique identifier of the trip that has not yet been analyzed by the DriveQuant’s servers, etc.

{% hint style="info" %}

* The local unique identifier generated by the SDK (`localTripId`) is different from the unique trip identifier generated after data analysis (`itinId`).
* A local trip identifier generated by the SDK (`localTripId`) is linked to a single unique trip identifier (`itinId`).
* If the trip is cancelled locally, there will be no trip analysis and therefore no unique trip identifier (`itinId`) linked to the unique local identifier (`localTripId`).
  {% endhint %}

To retrieve information about the current trip, use the following method:

{% tabs %}
{% tab title="DriveKitTripAnalysis" %}

```swift
func getCurrentTripInfo() -> DKTripInfo?
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
The method can return `nil` if there is no trip currently recording.
{% endhint %}

### DKTripInfo

| Property    | Type        | Description                                                                                                                                                                                                                                                     |
| ----------- | ----------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| localTripId | `String`    | <p>Local and unique trip identifier generated by DriveKit SDK.</p><p>⚠️ It is different from the <code>itinId</code> property returned in the Trip object. <code>itinId</code> corresponds to the unique trip identifier generated after the data analysis.</p> |
| date        | `Date`      | <p>Start date of the trip analysis. </p><p>⚠️ It is different from the startDate property returned in the <a href="../references#trip">Trip</a> object.</p>                                                                                                     |
| startMode   | `StartMode` | The [StartMode](https://docs.drivequant.com/trip-analysis/references#startmode) which triggered the trip analysis.                                                                                                                                              |

## Manual trip repost

Trip Analysis SDK have a repost mechanism, in most cases, when a trip is finished it is sent to DriveQuant's server to be analyzed and once it's done, the result of the analysis is sent back to the SDK.&#x20;

In some case, the trip can't be sent to the server (no network for example). In this case, the SDK will save the trip data locally, to send it later. A retry will be attempted when the next trip will start.

If you want to check if there is locally saved trips and if they can be sent to the server, you can call the following method:

```swift
DriveKitTripAnalysis.shared.checkTripToRepost()
```

## Custom stop timeout

A trip being analyzed is automatically stopped after a period of inactivity (which begins when the vehicle has stopped). The DriveQuant SDK allows to set the end-of-trip duration.&#x20;

By default, the trip analysis is stopped after 240 seconds. This value can be tuned according to your need and you can choose any integer values between 120 and 480 seconds by calling the following method:

```swift
DriveKitTripAnalysis.shared.setStopTimeOut(timeOut: 180)
```

{% hint style="warning" %}
If a value greater than 480 is set, the value will be forced to 480.

If a value lower than 120 is set, the value will be forced to 120.
{% endhint %}

## Custom max speed before cancellation

A trip being recorded is automatically cancelled if the speed is above a given value. The DriveKit SDK allows you to modify the threshold.

By default, the trip recording is canceled with the [highSpeed](https://docs.drivequant.com/trip-analysis/references#dktripcancelationreason) trip cancellation reason when speed is above 200 km/h. This value can be tuned according to your need and you can choose any double values between 50 and 1500 km/h by calling the following code:

{% tabs %}
{% tab title="Swift" %}

```kotlin
let desiredMaxSpeed = 300.0 // in km/h
DriveKitTripAnalysis.shared.autoCancelTripMaxSpeed = desiredMaxSpeed
```

{% endtab %}
{% endtabs %}

{% hint style="warning" %}
If a value greater than 1500 is set, the value will be forced to 1500.

If a value lower than 50 is set, the value will be forced to 50.
{% endhint %}

## Manage the location sharing while driving

Thanks to the driving location sharing feature, a user can generate a link that directs to a map displaying its location while driving. Location sharing provides peace of mind to family members during a trip. This section describes the methods to manage the location-sharing link.

### Check if the feature is available

If the trip sharing feature is enabled for your company, your API key carries out the feature access and a trip sharing link can be generated.

To check if the trip sharing feature is available for your API key, you can call the following code:

```swift
DriveKitTripAnalysis.shared.tripSharing.isAvailable()
```

### Create a link

To generate a link to share trips, use the following code:

```swift
let oneHourInSeconds = 3600
DriveKitTripAnalysis.shared.tripSharing.createLink(durationInSeconds: oneHourInSeconds) { status, data in
    // Check the status and manage the data
}
```

The method takes a `durationInSeconds` parameter which indicates how long in seconds from now the sharing link will be valid.

#### CreateTripSharingLinkStatus

<table><thead><tr><th width="303">Value</th><th>Description</th></tr></thead><tbody><tr><td>success</td><td>The link has been successfully created. Information is returned in <code>data</code>.</td></tr><tr><td>activeLinkAlreadyExists</td><td><p>A link already exists for this user.</p><p>Information returned in <code>data</code> is nil.</p><p></p><p>💡 You have to call the method to <a href="#retrieve-a-valid-sharing-link">retrieve an existing link</a> in your workflow.</p></td></tr><tr><td>error</td><td><p>An error occurred, for instance when the user has no network.</p><p>Information returned in <code>data</code> is nil.</p></td></tr><tr><td>userNotConnected</td><td>The user is not yet connected to DriveKit. Information returned in <code>data</code> is nil.</td></tr><tr><td>invalidDuration</td><td>An error occurred when trying to create a link. The duration parameter must be strictly greater than 0. Information returned in <code>data</code> is nil.</td></tr><tr><td>unauthenticated</td><td><p>The user has been disconnected.</p><p>Information returned in <code>data</code> is nil.</p></td></tr><tr><td>forbidden</td><td><p>Your API key is <strong>not</strong> allowed to use the feature.</p><p>Information returned in <code>data</code> is nil.</p></td></tr></tbody></table>

#### DKTripSharingLink

| Property  | Type   | Description                                                    |
| --------- | ------ | -------------------------------------------------------------- |
| code      | String | Unique trip sharing code.                                      |
| url       | String | URL of the map that will display the current trip of the user. |
| startDate | Date   | Link validity start date                                       |
| endDate   | Date   | Link expiration date.                                          |

### Retrieve a valid sharing link

To retrieve a link to share trips, use the following code:

```swift
DriveKitTripAnalysis.shared.tripSharing.getLink(synchronizationType: .defaultSync) { status, data in
    // Check the status and manage the data
}
```

The method takes a `synchronizationType` parameter. It will retrieve locally stored data if the value is `.cache`, otherwise with the `.defaultSync` value it will call the DriveQuant’s servers.

#### GetTripSharingLinkStatus

<table><thead><tr><th width="303">Value</th><th>Description</th></tr></thead><tbody><tr><td>success</td><td>The link has been successfully retrieved. Information is returned in <code>data</code>.</td></tr><tr><td>failedToGetCacheOnly</td><td>An error occurred when trying to retrieve a link. Locally trip sharing link, if exists, is returned in data.</td></tr><tr><td>noActiveLink</td><td><p>There is no active link for the user.</p><p>Information returned in <code>data</code> is nil.</p></td></tr><tr><td>userNotConnected</td><td>The user is not yet connected to DriveKit. Information returned in <code>data</code> is nil.</td></tr><tr><td>unauthenticated</td><td><p>The user has been disconnected.</p><p>Information returned in <code>data</code> is nil.</p></td></tr><tr><td>forbidden</td><td><p>Your API key is <strong>not</strong> allowed to use the feature.</p><p>Information returned in <code>data</code> is nil.</p></td></tr></tbody></table>

### Revoke a trip sharing link

To revoke a trip sharing link, use the following code:

```swift
DriveKitTripAnalysis.shared.tripSharing.revokeLink { status in
    // Check the status
}
```

#### RevokeTripSharingLinkStatus

<table><thead><tr><th width="303">Value</th><th>Description</th></tr></thead><tbody><tr><td>success</td><td>The link has been successfully revoked.</td></tr><tr><td>noActiveLink</td><td>There is no active link for the user.</td></tr><tr><td>error</td><td>An error occurred when trying to revoke the link.</td></tr><tr><td>userNotConnected</td><td>The user is not yet connected to DriveKit.</td></tr><tr><td>unauthenticated</td><td>The user has been disconnected.</td></tr><tr><td>forbidden</td><td>Your API key is <strong>not</strong> allowed to use the feature.</td></tr></tbody></table>

## Sharing data during the trip

{% hint style="warning" %}
This feature allows you to share to the server the location of a driver during all his trips. It is different from the [trip sharing with a link](#share-trips-with-a-link) feature where the user chooses to share his trips for a certain duration, thanks to a link showing his current trip on a map.
{% endhint %}

The Trip Analysis SDK records the trip locally while it is in progress. The data are recorded with a period of one point per second. At the end of the trip, the SDK requests the driving analysis service and then retrieves the driving indicators.

In addition to this feature, the SDK is also able to share data with the server before the journey is completed. The data is transmitted at a lower frequency with a time interval of one point per minute.

Sharing information with the server allows you to store the trip data even if it's been interrupted and the data post could not be performed at the end of the trip. This can happen in very rare cases such as the destruction of the mobile phone for instance.

By default, this setting is disabled but you can enable it by calling the following method:

```swift
DriveKitTripAnalysis.shared.enableSharePosition(enable: true)
```

To disable this setting, call the same method with the parameter set to `false`

```swift
DriveKitTripAnalysis.shared.enableSharePosition(enable: false)
```

Here is the list of data shared every minute by the SDK:

* Date of trip start.
* Duration of the trip in seconds.&#x20;
* Distance traveled in km.
* Longitude of the current location.
* Latitude of the current location.
* Smartphone battery level.
* Start-Mode for trip recording: manual, GPS-based or beacon-based.
* Beacon parameters: uuid, major, minor.

## Access the trip trigger events

### Why use trip triggers?

DriveKit's automatic start mode detects a trip and launches its recording immediately. This operating mode may not be appropriate for all use cases.

Your application may require other information or business logic before enabling the trip recording. For example, it may be appropriate to check that:

* A connected device is near to the smartphone.
* The trip recording is acceptable in a given time slot.

In this case, you may want to subscribe to the events that are indicative of the trip start but not necessarily launch the GPS sensor and the trip analysis.

This is why DriveKit allows you to subscribe to trigger events that indicate that a trip has probably started.

### How does it work?

By default, this feature is disabled.

To enable this feature, DriveKit Trip Analysis should not be configured in automatic mode but in manual mode.

If DriveKit Trip Analysis is set to automatic mode, the trip will be recorded.

If DriveKit Trip Analysis is set to manual mode and you follow the instructions below, you will be able to listen for trip start trigger events but the trip analysis will not be started automatically.

To listen to trigger events that indicate a start of trip, even if the autostart is disabled, you can call the following method:

```swift
DriveKitTripAnalysis.shared.monitorPotentialTripStart = true
```

Once the feature is enabled, events will be available in the [TripListener](https://docs.drivequant.com/trip-analysis/ios/triplistener) `potentialTripStart()`  callback.

The `potentialTripStart()` method can return all StartMode values ; except `MANUAL`. Indeed, a trip manually started is considered as confirmed.

## Get the arrival location of the last trip

This function returns the location of the end of the last trip recorded by the user.&#x20;

The returned location type is [DKTripLocation](https://docs.drivequant.com/trip-analysis/references#dktriplocation).

You can use the end-of-trip coordinate for a variety of purposes, for example:

* help the user find his vehicle
* alert the customer that the user has reached a specific destination
* create a region monitoring (also known as geofencing) to locate the vehicle

{% hint style="info" %}
The last trip corresponds to the last trip recorded by the DriveKit SDK, regardless of the mode of transport used.
{% endhint %}

To retrieve the location at which the last recorded trip ended, use the following method:

{% tabs %}
{% tab title="DriveKitTripAnalysis" %}

```swift
func getLastTripLocation() -> DKTripLocation?
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
The method can return `nil` if the user:

* is not authenticated,
* or didn’t make a trip since the authentication,
* or hasn’t made any valid trips.
  {% endhint %}

### Get Last Vehicle Trip Location

This function returns the location of the end of the last vehicle trip.&#x20;

The returned location type is [DKTripLocation](https://docs.drivequant.com/trip-analysis/references#dktriplocation).

To retrieve the location at which the last recorded vehicle trip ended, use the following method:

{% tabs %}
{% tab title="DriveKitTripAnalysis" %}

```swift
func getLastVehicleTripLocation() -> DKTripLocation?
```

{% endtab %}
{% endtabs %}
