Skip to main content

Usage Examples for React Native and Expo apps

1. Relationship with the Native SDKs​

The React Native and Expo TelematicsSDK modules act as a thin integration layer over the native TelematicsSDKs (iOS and Android).

All methods exposed by these modules map directly to the corresponding native SDK methods and preserve the same responsibilities, behavior, and functional scope. The modules communicate with the native layers through a platform bridge.

As a result:

  • The functional behavior of each method is identical to its native SDK counterpart.
  • The JavaScript API is a direct representation of the native SDK capabilities.
  • No additional abstraction or alternative logic is introduced at the JavaScript level.

For detailed explanations of each feature, including business rules, edge cases, and platform-specific behavior, refer to the native SDK documentation:

The examples below focus on how to consume those capabilities from a React Native or Expo application.

2. React Native and Expo​

The React Native module (@driviantelematics/telematics-sdk-rn) and the Expo module (@driviantelematics/telematics-sdk-expo) expose exactly the same API. The examples below import from the React Native package; in an Expo project, import from @driviantelematics/telematics-sdk-expo instead:

// React Native
import { initSDKWithOptions } from '@driviantelematics/telematics-sdk-rn';

// Expo
import { initSDKWithOptions } from '@driviantelematics/telematics-sdk-expo';

All methods return a Promise. When a call fails, the Promise is rejected with an error that has a code property (see 3.13 Errors).

Both packages include TypeScript definitions for all options, models and event payloads (for example TelematicsInitOptions, TelematicsSessionState, TripResume, TripDetails, MetricsSummary and TelematicsPeriodsPage).


3. Usage​

Here you have some usage examples of the TelematicsSDK.

A typical integration follows this flow:

  1. Initialize the SDK with the user's tokens (3.1).
  2. Register the vehicle (3.3).
  3. Make sure all permissions are granted (3.5).
  4. Start the telematics service (3.6).

3.1 Initialization​

Initialize the SDK at the start of your application, typically inside your app's main initialization flow.

The SDK is initialized with the access token and refresh token of the authenticated user, together with the base URL of the telematics platform provided by Sentilant. These values are obtained by your application from your authentication backend.

OptionRequiredDescription
baseURLYesBase URL of the telematics platform (e.g. https://telematics.example.com).
tokenYesAccess token of the user.
tokenExpiresNoExpiry of the access token, as an ISO 8601 timestamp (e.g. 2026-11-03T12:43:29.562522Z).
refreshTokenNoRefresh token of the user. Supplying it enables automatic token renewal.
refreshTokenExpiresNoExpiry of the refresh token, as an ISO 8601 timestamp.

When a refresh token is supplied, the SDK renews the access token on its own, before it expires or when the server rejects it. Without a refresh token, the SDK uses the access token as-is until it stops working.

After a successful initialization, the SDK retrieves the authenticated user automatically. No additional login call is required.

import { initSDKWithOptions } from '@driviantelematics/telematics-sdk-rn';

try {
await initSDKWithOptions({
baseURL: 'TELEMATICS_BASE_URL',
token: 'ACCESS_TOKEN',
tokenExpires: 'ACCESS_TOKEN_EXPIRES',
refreshToken: 'REFRESH_TOKEN',
refreshTokenExpires: 'REFRESH_TOKEN_EXPIRES',
});

// Initialization succeeded
} catch (e) {
// Handle initialization error (e.code === 'INVALID_ARGUMENT' for invalid options)
}

3.2 Session lifecycle​

Authentication invalidated​

Register a listener to be notified when the SDK can no longer authenticate. The listener receives the reason and whether the session was destroyed (invalidatesSession).

ReasonSession destroyedDescription
REFRESH_TOKEN_EXPIREDYesThe refresh token expired.
REFRESH_TOKEN_REJECTEDYesThe server rejected the refresh token.
ACCESS_TOKEN_REJECTEDYesThe server rejected the access token of a session without a refresh token.
ACCOUNT_INACTIVENoThe user account is inactive. The credentials remain valid.
ACCESS_DENIEDNoThe server refused access. The credentials remain valid.

When the session was destroyed, the SDK has already stopped telemetry and removed the user and vehicle. To restore the session:

  1. obtain new tokens and call initSDKWithOptions again;
  2. set the vehicle again (setVehicle);
  3. call startTelematicsService again. Telemetry does not restart by itself.

Data collected before the invalidation is kept on the device and is uploaded automatically once the session is restored.

import { addAuthenticationInvalidatedListener } from '@driviantelematics/telematics-sdk-rn';

const subscription = addAuthenticationInvalidatedListener(({ reason, invalidatesSession }) => {
if (invalidatesSession) {
// Session destroyed: obtain new tokens, call initSDKWithOptions, setVehicle and startTelematicsService
} else {
// Access refused (e.g. inactive account): the session is kept
}
});

// When no longer needed
subscription.remove();

Session state​

getSessionState() returns what the SDK knows about its session, without making any request.

StatusDescription
NOT_AUTHENTICATEDNo credentials: the SDK was never initialized, or the user logged out.
VERIFIEDThe server accepted the current access token (at lastVerifiedAt).
UNVERIFIEDThere are credentials, but the server has not confirmed them yet.
DENIEDThe server refused access (e.g. inactive account). New credentials would not help.
INVALIDThe server rejected the session. New tokens must be provided through initSDKWithOptions.

The returned object also contains:

  • invalidationReason: the reason for the INVALID or DENIED status, or null.
  • isAutoRenewing: true if the SDK holds a refresh token and renews the access token on its own.
  • recoverableUntil: until when the session can be kept alive without new tokens (ISO 8601, UTC), or null if unknown.
  • lastVerifiedAt: when the server last accepted the access token (ISO 8601, UTC), or null.

The status reflects the last answer from the server, not a live check.

import { getSessionState } from '@driviantelematics/telematics-sdk-rn';

const state = await getSessionState();

if (state.status === 'INVALID') {
// Obtain new tokens and call initSDKWithOptions again
}

Current user​

Retrieve the identifier and the name of the authenticated user using getCurrentUserInfo:

import { getCurrentUserInfo } from '@driviantelematics/telematics-sdk-rn';

try {
const { id, username } = await getCurrentUserInfo();
} catch (e) {
// Handle error fetching current user
}

On Android, getCurrentUserDetails() returns the full user details (id, name, group and nickname).

Logout​

logout() ends the session of the current user. It:

  1. stops telemetry, if the telematics service is running;
  2. tries to send the telemetry data still stored on the device to the server;
  3. ends the session, removing the credentials, the user and the vehicle from the SDK.

Data that could not be sent before the session ended (for example, without network) is kept on the device and is sent after the next successful initSDKWithOptions.

After logout, the session status is NOT_AUTHENTICATED. To use the SDK again, call initSDKWithOptions with the tokens of the new session.

import { logout } from '@driviantelematics/telematics-sdk-rn';

await logout();

3.3 Vehicle Management​

Set the user vehicle using the setVehicle method. The vehicle type, add reason and fuel type are identifier codes returned by getVehicleTypes, getAddVehicleReasons and getFuelTypes. Each of these methods returns an object where the key is the name and the value is the identifier code.

import {
getFuelTypes,
getVehicleTypes,
getAddVehicleReasons,
setVehicle,
} from '@driviantelematics/telematics-sdk-rn';

try {
const fuelTypes = await getFuelTypes(); // e.g. { Diesel: 1, Gasoline: 2, ... }
const vehicleTypes = await getVehicleTypes();
const addReasons = await getAddVehicleReasons();

const fuelType = Object.values(fuelTypes)[0];
const vehicleType = Object.values(vehicleTypes)[0];
const addReason = Object.values(addReasons)[0];

// setVehicle(plate, internalPlate, type, addReason, fuelType)
await setVehicle('plate123', 'internalPlate', vehicleType, addReason, fuelType);

// Vehicle set successfully
} catch (e) {
// Handle error setting vehicle
}

If the vehicle already exists, it can be set by its license plate only. The vehicle details are returned, or the Promise is rejected if no vehicle with that plate exists:

import { setVehicleByPlate } from '@driviantelematics/telematics-sdk-rn';

try {
const vehicle = await setVehicleByPlate('plate123');
} catch (e) {
// Vehicle not found or error setting vehicle
}

Other vehicle methods:

  • getCurrentVehicleInfo(): returns the details of the current vehicle, or rejects if no vehicle is set.
  • clearVehicle(): removes the current vehicle from the SDK.

3.4 Report vehicle kms​

Report the vehicle's current kilometers using the reportKilometers method:

import { reportKilometers } from '@driviantelematics/telematics-sdk-rn';

try {
await reportKilometers(1200, 'Routine check');

// Kilometers reported successfully
} catch (e) {
// Handle error reporting kilometers
}

Other kilometer methods:

  • correctKilometers(kilometers, observations, correctionCount): corrects the odometer reading, applying the value to the given number of past records.
  • getEstimatedMileage(): returns the estimated current mileage in kilometers, or -1 if it cannot be estimated.

3.5 Permission Handling​

Check the required permissions using the getRequiredPermissions and checkPermissions methods:

  • getRequiredPermissions() returns the permissions required by the SDK, using platform-specific identifiers.
  • checkPermissions() returns the required permissions that are not granted. An empty array means all permissions are granted.
  • isBatteryOptimizationDeactivated() (Android only) returns true if battery optimization is disabled for the application.

The module does not request permissions by itself. See Permissions Setup.

import { Platform } from 'react-native';
import {
checkPermissions,
getRequiredPermissions,
isBatteryOptimizationDeactivated,
} from '@driviantelematics/telematics-sdk-rn';

const missingPermissions = await checkPermissions();

if (missingPermissions.length === 0) {
// All required permissions are granted
} else {
// Request missing permissions
}

const requiredPermissions = await getRequiredPermissions();

// iOS:
// ["Location Permission", "Background Location Permission", "Motion and Fitness Permission"]

// Android (depends on the Android version):
// ["android.permission.ACCESS_FINE_LOCATION", "android.permission.ACCESS_COARSE_LOCATION", ...]

if (Platform.OS === 'android' && !(await isBatteryOptimizationDeactivated())) {
// Ask the user to disable battery optimization for the app
}

3.6 Telematics Service​

Start and stop the telematics service as needed. Before starting, the native SDK validates that the session is valid, that a user and a vehicle are set and that all permissions are granted (and, on Android, that battery optimization is disabled). If any of these checks fails, the Promise is rejected.

import {
startTelematicsService,
isTelematicsServiceRunning,
stopTelematicsService,
} from '@driviantelematics/telematics-sdk-rn';

try {
// Start the service
await startTelematicsService();

// Check if the service is running
const running = await isTelematicsServiceRunning();

// Stop the service
await stopTelematicsService();
} catch (e) {
// Handle error starting or stopping telematics service
}

On Android, startTelematicsServiceWithOptions(options) and stopTelematicsServiceWithOptions(options) allow sending additional information with the start or stop (reason, observations, serviceCode, vehicleKms, realVolume and extraData). On iOS these methods are not available and are rejected with UNSUPPORTED_PLATFORM.

import { Platform } from 'react-native';
import { startTelematicsService, startTelematicsServiceWithOptions } from '@driviantelematics/telematics-sdk-rn';

if (Platform.OS === 'android') {
await startTelematicsServiceWithOptions({
reason: 'Start of shift',
vehicleKms: 1200,
extraData: { key: 'value' },
});
} else {
await startTelematicsService();
}

setServiceCode(serviceCode) changes the service code used by the telematics service.

3.7 Attention Detection​

While the telematics service is running, the native SDKs can detect on the device, using a machine learning model, when the user is handling the phone while driving. Each detection produces an attention event.

  • Attention detection is enabled by default and runs only while the telematics service is running.
  • Use setAttentionDetectionEnabled(false) to disable it. The choice is persisted and applies immediately if the service is running. While disabled, telemetry is collected exactly as without this feature.
  • isAttentionDetectionEnabled() returns whether the detection is currently enabled.
  • Attention events are stored on the device and uploaded to the platform automatically, in the same way as telemetry data.
  • Each event covers a 10 second window. A new window starts every 5 seconds, so a continuous distraction produces several events.

Register a listener with addAttentionEventListener to receive the events in your application. The function returns a subscription; call remove() when the listener is no longer needed. Events detected while no listener is registered are not delivered later, but are still uploaded to the platform.

import {
addAttentionEventListener,
setAttentionDetectionEnabled,
isAttentionDetectionEnabled,
} from '@driviantelematics/telematics-sdk-rn';

const subscription = addAttentionEventListener((event) => {
// event.type -> 'phone_distraction'
// event.startTimestampMs / event.endTimestampMs -> window, epoch milliseconds
// event.confidence -> 0..1
});

// When no longer needed
subscription.remove();

// Enable or disable attention detection
await setAttentionDetectionEnabled(true);
const enabled = await isAttentionDetectionEnabled();

The event (AttentionEvent) has the same fields on Android and iOS:

FieldTypeDescription
idstringUnique identifier of the event (UUID).
typestringEvent type. Currently 'phone_distraction'.
startTimestampMs / endTimestampMsnumberStart and end of the window, epoch milliseconds.
confidencenumberDetection confidence, from 0 to 1.
averageSpeedMpsnumber | nullMean GPS speed during the window in m/s.
latitude / longitudenumber | nullPosition of the first valid GPS fix in the window.
horizontalAccuracyMnumber | nullHorizontal accuracy of that fix in meters.
locationTimestampMsnumber | nullTime of that fix, epoch milliseconds.
detectorVersionstringIdentifier of the detector that produced the event.

The location fields are either all set or all null.

3.8 Trips​

Retrieve a list of trips within an optional date range.

startTs and endTs are Unix timestamps in seconds (UTC). Pass null to remove one of the filters.

import { getTripsList } from '@driviantelematics/telematics-sdk-rn';

// Example: trips from the last 7 days until now
const endTs = Math.floor(Date.now() / 1000);
const startTs = endTs - 7 * 24 * 60 * 60;

try {
const trips = await getTripsList(startTs, endTs);

// Trips list fetched successfully
} catch (e) {
// Handle error fetching trips list
}

To retrieve the details of a single trip, use getTripById(id, includeSamples). Set includeSamples to true to include the trip samples in the response.

3.9 Metrics Summary​

Retrieve a summary of user metrics within an optional date range. startTs and endTs are Unix timestamps in seconds (UTC), or null.

import { getMetricsSummary } from '@driviantelematics/telematics-sdk-rn';

// Example: metrics for the current month
const now = new Date();
const startTs = Math.floor(new Date(now.getFullYear(), now.getMonth(), 1).getTime() / 1000);
const endTs = Math.floor(now.getTime() / 1000);

try {
const summary = await getMetricsSummary(startTs, endTs);

// Metrics summary fetched successfully
} catch (e) {
// Handle error fetching metrics summary
}

Other metrics methods:

  • getActivityMetricsSummary(startTs, endTs): activity metrics summary for an optional date range.
  • getLastTelematicsPeriodMetricsSummary() (Android only): metrics summary of the last telematics period.
  • getLastTelematicsDayMetricsSummary() (Android only): metrics summary of the last telematics day.

3.10 Telematics Periods​

Retrieve the telematics periods within an optional date range (Unix timestamps in seconds, or null). isProcessed filters by processed state and can be null.

  • getTelematicsPeriods(startTs, endTs, isProcessed, page): one page of periods. page can be null to use the default page.
  • getAllTelematicsPeriods(startTs, endTs, isProcessed): the full list of periods, returned in the same page format.
  • getTelematicsPeriod(id): the details of a single period.
import { getAllTelematicsPeriods } from '@driviantelematics/telematics-sdk-rn';

try {
const page = await getAllTelematicsPeriods(null, null, null);

// Telematics periods fetched successfully
} catch (e) {
// Handle error fetching telematics periods
}

3.11 Manual Events​

Manual events allow the user to mark, during a trip, the moment a specific driving event happened (for example, a hard braking or a distraction).

The SDK records the event type with the current time and the latest location collected by the SDK, and sends it to the server. The event is therefore meant to be inserted while a trip is being recorded.

Later, when analysing the trip, the manual events can be compared with the events detected automatically by the SDK. For example, if a manual distraction event is marked at minute 10 of a trip, you can check whether a distraction event was also detected at that minute, and use this comparison to validate the trip and assess the reliability of the event detection.

Register a manual event using insertManualEvent, with a value from MANUAL_EVENT_TYPE: ABRUPT_ACCELERATION_HIGH_SPEED, ABRUPT_ACCELERATION_LOW_SPEED, HARD_BRAKING_HIGH_SPEED, HARD_BRAKING_LOW_SPEED, HARD_CORNERING, SPEEDING, DISTRACTION, WALKING, DRIVING, STOPPED, TRIP_START and TRIP_END.

import { insertManualEvent, MANUAL_EVENT_TYPE } from '@driviantelematics/telematics-sdk-rn';

await insertManualEvent(MANUAL_EVENT_TYPE.HARD_BRAKING_HIGH_SPEED);

3.12 Permission Events (iOS)​

On iOS, the module forwards the three permission-related callbacks of the iOS SDK as events. Each add…Listener function returns a subscription; call remove() when the listener is no longer needed. These events are not emitted on Android.

See Permissions Runtime Behavior for details and examples.

3.13 Errors​

When a call fails, the Promise is rejected with an error that has a code property. Use isTelematicsError(error) to check if an error comes from the SDK. The most common codes are:

CodeWhen
INVALID_ARGUMENTAn argument is missing or invalid (e.g. empty baseURL or token).
NOT_INITIALIZEDThe SDK was not initialized.
UNSUPPORTED_PLATFORMThe method is not available on the current platform.
INIT_ERROR, START_SERVICE_ERROR, SET_VEHICLE_ERROR, ...The corresponding operation failed. The error message contains the reason reported by the native SDK.
import { isTelematicsError, isUnsupportedPlatform } from '@driviantelematics/telematics-sdk-rn';

try {
// ...
} catch (e) {
if (isUnsupportedPlatform(e)) {
// Method not available on this platform
} else if (isTelematicsError(e)) {
console.log(e.code, e.message);
}
}

The full list of codes is available in ERROR_CODES.


4. Platform differences​

The JavaScript API is the same on both platforms, but some capabilities only exist in one of the native SDKs. On an unsupported platform, the method is rejected with UNSUPPORTED_PLATFORM and the events are never emitted.

CapabilityAndroidiOS
getCurrentUserDetails✅❌
isBatteryOptimizationDeactivated✅❌
startTelematicsServiceWithOptions / stopTelematicsServiceWithOptions✅❌
getLastTelematicsPeriodMetricsSummary / getLastTelematicsDayMetricsSummary✅❌
Permission events (addPermissionsMissingListener, addPermissionsLostWhileRunningListener, addTelemetryGapDetectedListener)❌✅

The same information is available at runtime in PLATFORM_RESTRICTED, and through isSupported(capability, platform) and unsupportedCapabilities(platform):

import { Platform } from 'react-native';
import { isSupported } from '@driviantelematics/telematics-sdk-rn';

if (isSupported('isBatteryOptimizationDeactivated', Platform.OS)) {
// ...
}