### Setup and Event Handling for Smart Geofences Source: https://github.com/sentiance/react-native-sentiance/blob/main/_autodocs/api-reference/smart-geofences.md This example demonstrates how to initialize smart geofences, register for geofence entry/exit events, and periodically refresh geofence data. It includes error handling for refresh failures. ```typescript import SentianceSmartGeofences, { DetectionMode } from "@sentiance-react-native/smart-geofences"; async function setupSmartGeofences() { try { // Check current detection mode const detectionMode = await SentianceSmartGeofences.getDetectionMode(); console.log(`Geofence detection mode: ${detectionMode}`); if (detectionMode === "DISABLED") { console.log("Note: Geofence detection is disabled"); } // Register geofence event listener const subscription = await SentianceSmartGeofences.addSmartGeofenceEventListener( (event) => { const eventName = event.eventType === "ENTRY" ? "Entered" : "Exited"; console.log(`${eventName} ${event.geofences.length} geofence(s)`); event.geofences.forEach((geofence) => { console.log(` ID: ${geofence.externalId}`); console.log(` Location: ${geofence.latitude}, ${geofence.longitude}`); console.log(` Radius: ${geofence.radius}m`); }); // Send event to your backend reportGeofenceEvent(event); } ); // Periodically refresh geofences (e.g., every hour) const refreshInterval = setInterval(async () => { try { await SentianceSmartGeofences.refreshGeofences(); console.log("Geofences refreshed"); } catch (error) { const refreshError = error as SmartGeofencesRefreshError; console.error(`Failed to refresh: ${refreshError.reason}`); // Handle specific errors if (refreshError.reason === "TOO_MANY_FREQUENT_CALLS") { console.log("Refresh called too frequently"); } else if (refreshError.reason === "NO_USER") { console.log("User not created yet"); } } }, 60 * 60 * 1000); // Every hour // Return cleanup function return () => { subscription.remove(); clearInterval(refreshInterval); }; } catch (error) { console.error("Error setting up geofences:", error); } } ``` -------------------------------- ### Initialize Sentiance SDK without Auto-Start Source: https://github.com/sentiance/react-native-sentiance/blob/main/_autodocs/configuration.md Initializes the Sentiance SDK but requires manual start of detections. Use this when you need to perform other setup steps before starting detection. ```typescript const status2 = await RNSentiance.init( "app_id", "app_secret", null, false // Manual start required ); ``` -------------------------------- ### Create User and Start SDK (Without Linking) Source: https://github.com/sentiance/react-native-sentiance/blob/main/docs/react-native.md Initialize the Sentiance SDK by creating a user with provided credentials and then starting the SDK. This is used when user linking is not required. ```javascript await RNSentiance.createUserExperimental({ credentials: { appId, appSecret, baseUrl }, }); await RNSentiance.start(); ``` -------------------------------- ### Setup User Context Tracking Source: https://github.com/sentiance/react-native-sentiance/blob/main/_autodocs/api-reference/user-context.md Requests the current user context and sets up a listener for future context updates. Handles potential errors during setup. ```typescript import SentianceUserContext from "@sentiance-react-native/user-context"; async function setupUserContextTracking() { try { // Get current context const context = await SentianceUserContext.requestUserContext(); console.log("User segments:", context.activeSegments); console.log("Home location:", context.home); console.log("Work location:", context.work); // Listen for future updates const subscription = await SentianceUserContext.addUserContextUpdateListener( (update) => { const criteria = update.criteria; console.log("Context updated due to:", criteria); if (criteria.includes("CURRENT_EVENT")) { console.log("Current event changed"); const currentEvent = update.userContext.events[0]; if (currentEvent?.transportMode) { console.log(`Transport: ${currentEvent.transportMode}`); } } if (criteria.includes("ACTIVE_SEGMENTS")) { console.log("Active segments:", update.userContext.activeSegments); } } ); // Return cleanup function return () => subscription.remove(); } catch (error) { console.error("Error setting up user context:", error); } } ``` -------------------------------- ### Full Sentiance Initialization Order Source: https://github.com/sentiance/react-native-sentiance/blob/main/_autodocs/configuration.md Demonstrates the correct sequence for initializing the Sentiance SDK, including user creation, data configuration, and listener setup. Ensure this order is followed for a complete setup. ```typescript // Correct order for full initialization async function initializeSentiance() { // 1. Create user if needed if (!await SentianceCore.userExists()) { await SentianceCore.createUser({ appId: "app_id", appSecret: "app_secret" }); } // 2. Configure data transmission await SentianceCore.setTransmittableDataTypes(["ALL"]); // 3. Enable detections await SentianceCore.enableDetections(); // 4. Set up listeners await SentianceCore.addSdkStatusUpdateListener(handleStatusUpdate); // 5. Configure optional features await SentianceSmartGeofences.addSmartGeofenceEventListener(handleGeofence); } ``` -------------------------------- ### Install Verdaccio Source: https://github.com/sentiance/react-native-sentiance/blob/main/publishing.md Installs Verdaccio globally using npm. This is the first step to setting up a local private NPM registry. ```bash npm i -g verdaccio ``` -------------------------------- ### Create User and Start SDK (Without User Linking) Source: https://github.com/sentiance/react-native-sentiance/blob/main/docs/react-native.md Initializes the Sentiance SDK by creating a user with provided credentials and starts the data collection process. This method is used when user linking to the Sentiance platform is not required. ```APIDOC ## CreateUserExperimental and Start ### Description Initializes the Sentiance SDK by creating a user with provided credentials and starts the data collection process. This method is used when user linking to the Sentiance platform is not required. ### Method `createUserExperimental` (POST-like operation for initialization) `start` (POST-like operation for starting service) ### Parameters #### `createUserExperimental` Parameters - **credentials** (object) - Required - Object containing `appId`, `appSecret`, and `baseUrl`. - **appId** (string) - Required - Your Sentiance application ID. - **appSecret** (string) - Required - Your Sentiance application secret. - **baseUrl** (string) - Required - The base URL for Sentiance API services. #### `start` Parameters None ### Request Example ```javascript await RNSentiance.createUserExperimental({ credentials: { appId, appSecret, baseUrl }, }); await RNSentiance.start(); ``` ### Response #### Success Response (200) Indicates successful initialization and start of the SDK. #### Response Example (No specific response body is detailed for these operations, success is implied by lack of error.) ``` -------------------------------- ### Start Detection Source: https://github.com/sentiance/react-native-sentiance/blob/main/_autodocs/api-reference/legacy.md Starts trip and activity detection. This method is part of the legacy module. ```APIDOC ## start() ### Description Starts trip and activity detection. ### Method start ### Response #### Success Response - **Promise** - The current status of the SDK. ``` -------------------------------- ### Driving Insights Integration Example Source: https://github.com/sentiance/react-native-sentiance/blob/main/_autodocs/api-reference/driving-insights.md Demonstrates how to integrate with the Sentiance Driving Insights module to listen for driving events, retrieve safety scores, and get detailed event data like harsh driving and speeding incidents. ```typescript import SentianceDrivingInsights from "@sentiance-react-native/driving-insights"; async function analyzeDrivingBehavior() { try { // Listen for insights when available const subscription = await SentianceDrivingInsights.addDrivingInsightsReadyListener( async (insights) => { const scores = insights.safetyScores; console.log(`Transport ${insights.transportEvent.id} insights:`); console.log(` Overall: ${scores.overallScore}`); console.log(` Smooth: ${scores.smoothScore}`); console.log(` Legal: ${scores.legalScore}`); // Get detailed events const harshEvents = await SentianceDrivingInsights.getHarshDrivingEvents( insights.transportEvent.id ); console.log(` Harsh events: ${harshEvents.length}`); const speedingEvents = await SentianceDrivingInsights.getSpeedingEvents( insights.transportEvent.id ); console.log(` Speeding incidents: ${speedingEvents.length}`); } ); // Get average score for the last 7 days const avgScore = await SentianceDrivingInsights.getAverageOverallSafetyScore({ period: 7, transportModes: ["CAR"], occupantRoles: "ALL_ROLES" }); console.log(`7-day average score: ${avgScore}`); // Cleanup return () => subscription.remove(); } catch (error) { console.error("Error analyzing driving:", error); } } ``` -------------------------------- ### Start Detection Source: https://github.com/sentiance/react-native-sentiance/blob/main/_autodocs/api-reference/legacy.md Starts trip and activity detection. Returns a promise that resolves to the SdkStatus. ```typescript start(): Promise ``` -------------------------------- ### startTrip Source: https://github.com/sentiance/react-native-sentiance/blob/main/_autodocs/api-reference/legacy.md Starts a manual trip, allowing for custom trip initiation with optional metadata and transport mode hints. ```APIDOC ## startTrip(metadata: MetadataObject | null, hint: TransportMode) ### Description Starts a manual trip. ### Method Not specified (assumed to be a method call) ### Parameters #### Path Parameters - **metadata** (MetadataObject | null) - Required - Metadata or null - **hint** (TransportMode) - Required - Transport mode hint ### Return Type `Promise` ``` -------------------------------- ### Listen for User Activity Updates Source: https://github.com/sentiance/react-native-sentiance/blob/main/_autodocs/api-reference/legacy.md Starts a listener to receive real-time updates on the user's activity. Returns a promise that resolves to a boolean indicating if the listener was successfully started. ```typescript listenUserActivityUpdates(): Promise ``` -------------------------------- ### Create User and Start SDK (With Linking) Source: https://github.com/sentiance/react-native-sentiance/blob/main/docs/react-native.md Initialize the Sentiance SDK by creating a user with credentials and a linker function for user linking. The linker function should call 'done()' upon completion or 'done(false)' on failure. ```javascript await RNSentiance.createUserExperimental({ credentials: { appId, appSecret, baseUrl }, linker: async (data, done) => { // request your backend to perform user linking await linkUser(data.installId); // Ensure you call the "done" after done(); }, }); await RNSentiance.start(); ``` -------------------------------- ### UserContext Data Type Example Source: https://github.com/sentiance/react-native-sentiance/blob/main/_autodocs/api-reference/user-context.md An example illustrating the structure of the UserContext object, which contains events, active segments, last known location, home and work venues, and semantic time. ```typescript const userContext: UserContext = { events: [/* ... */], activeSegments: [/* ... */], lastKnownLocation: { latitude: 40.7128, longitude: -74.0060, accuracy: 10 }, home: { /* ... */ }, work: { /* ... */ }, semanticTime: "AFTERNOON" }; ``` -------------------------------- ### Create User and Start SDK (With User Linking) Source: https://github.com/sentiance/react-native-sentiance/blob/main/docs/react-native.md Initializes the Sentiance SDK, creates a user, and initiates the user linking process with the Sentiance platform. This involves a callback function to handle the linking logic on your backend. ```APIDOC ## CreateUserExperimental with Linker and Start ### Description Initializes the Sentiance SDK, creates a user, and initiates the user linking process with the Sentiance platform. This involves a callback function to handle the linking logic on your backend. ### Method `createUserExperimental` (POST-like operation for initialization with linking) `start` (POST-like operation for starting service) ### Parameters #### `createUserExperimental` Parameters - **credentials** (object) - Required - Object containing `appId`, `appSecret`, and `baseUrl`. - **appId** (string) - Required - Your Sentiance application ID. - **appSecret** (string) - Required - Your Sentiance application secret. - **baseUrl** (string) - Required - The base URL for Sentiance API services. - **linker** (function) - Required - A callback function that takes `data` and `done` as arguments. It should perform user linking on your backend and then call `done()` upon completion or `done(false)` if linking fails. - **data** (object) - Contains `installId` for linking. - **done** (function) - Callback to signal completion or failure of the linking process. #### `start` Parameters None ### Request Example ```javascript await RNSentiance.createUserExperimental({ credentials: { appId, appSecret, baseUrl }, linker: async (data, done) => { // request your backend to perform user linking await linkUser(data.installId); // Ensure you call the "done" after done(); }, }); await RNSentiance.start(); ``` ### Response #### Success Response (200) Indicates successful initialization, user linking, and start of the SDK. #### Response Example (No specific response body is detailed for these operations, success is implied by lack of error.) #### Error Handling - If your backend fails to link the user, call `done(false)` within the linker function to notify the SDK of the failure. ``` -------------------------------- ### Start Detection with Stop Date Source: https://github.com/sentiance/react-native-sentiance/blob/main/_autodocs/api-reference/legacy.md Starts detections with an optional stop date. This method is part of the legacy module. ```APIDOC ## startWithStopDate(stopEpochTimeMs: number | null) ### Description Starts detections with an optional stop date. ### Method startWithStopDate ### Parameters #### Path Parameters - **stopEpochTimeMs** (number | null) - Required - Epoch time when to stop, or null for no expiry ### Response #### Success Response - **Promise** - The current status of the SDK. ``` -------------------------------- ### Get Initialization State Source: https://github.com/sentiance/react-native-sentiance/blob/main/_autodocs/api-reference/legacy.md Retrieves the current SDK initialization state. This method is part of the legacy module. ```APIDOC ## getInitState() ### Description Retrieves the current SDK initialization state. ### Method getInitState ### Response #### Success Response - **Promise** - The initialization state. Possible values: NOT_INITIALIZED, INIT_IN_PROGRESS, INITIALIZED, RESETTING, UNRECOGNIZED_STATE. ``` -------------------------------- ### Run Verdaccio Local Registry Source: https://github.com/sentiance/react-native-sentiance/blob/main/publishing.md Starts the Verdaccio local private NPM registry. Ensure this is running before publishing packages. ```bash verdaccio ``` -------------------------------- ### Start Detections with Stop Date Source: https://github.com/sentiance/react-native-sentiance/blob/main/_autodocs/api-reference/legacy.md Starts detections and specifies an optional epoch time in milliseconds when detection should automatically stop. Returns a promise that resolves to SdkStatus. ```typescript startWithStopDate(stopEpochTimeMs: number | null): Promise ``` -------------------------------- ### Initialize Sentiance SDK with Auto-Start Source: https://github.com/sentiance/react-native-sentiance/blob/main/_autodocs/configuration.md Initializes the Sentiance SDK and automatically starts detections. Use this when immediate detection is required upon app launch. ```typescript const status1 = await RNSentiance.init( "app_id", "app_secret", null, // Use default URL true // Auto-start detections ); ``` -------------------------------- ### reset() Source: https://github.com/sentiance/react-native-sentiance/blob/main/_autodocs/api-reference/core.md Resets the SDK to its pre-initialization state, clearing all data. This is useful for re-initializing the SDK or starting fresh. ```APIDOC ## reset() ### Description Resets the SDK to its pre-initialization state, clearing all data. This is useful for re-initializing the SDK or starting fresh. ### Method `Promise` ### Return Type `Promise` - Contains `initState` after reset ### Example ```typescript const result = await SentianceCore.reset(); console.log("SDK reset, init state:", result.initState); ``` ``` -------------------------------- ### isNativeInitializationEnabled Source: https://github.com/sentiance/react-native-sentiance/blob/main/_autodocs/api-reference/legacy.md Checks if the native initialization process for the SDK is enabled. This is useful for verifying SDK setup. ```APIDOC ## isNativeInitializationEnabled() ### Description Checks if native initialization is enabled. ### Method Not specified (assumed to be a method call) ### Return Type `Promise` ``` -------------------------------- ### enableNativeInitialization Source: https://github.com/sentiance/react-native-sentiance/blob/main/_autodocs/api-reference/legacy.md Enables the native SDK initialization process. This method should be called to start the SDK's background operations. ```APIDOC ## enableNativeInitialization() ### Description Enables native SDK initialization. This method initiates the SDK's background processes. ### Method ``` enableNativeInitialization(): Promise ``` ### Return Value - `Promise`: A promise that resolves to a boolean indicating success or failure of the initialization enablement. ``` -------------------------------- ### Custom Linker Callback Implementation Source: https://github.com/sentiance/react-native-sentiance/blob/main/_autodocs/configuration.md Example of a custom linker function that sends the installId to a backend API and returns a boolean indicating success. ```typescript const customLinker: Linker = async (installId) => { try { const response = await fetch('https://your-api.com/link-user', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ installId: installId, timestamp: Date.now() }) }); const data = await response.json(); return data.success === true; } catch (error) { console.error('Linking failed:', error); return false; } }; const user = await SentianceCore.createUser({ linker: customLinker }); ``` -------------------------------- ### Start a manual trip with metadata and transport hint Source: https://github.com/sentiance/react-native-sentiance/blob/main/_autodocs/api-reference/core.md Use this function to manually initiate a trip. You can provide key-value metadata and a hint for the transport mode to improve accuracy. ```typescript await SentianceCore.startTrip( { "trip_type": "business" }, SentianceCore.TransportMode.CAR ); ``` -------------------------------- ### Setup and Usage of Event Timeline Source: https://github.com/sentiance/react-native-sentiance/blob/main/_autodocs/api-reference/event-timeline.md This snippet demonstrates setting transport tags, listening for timeline updates, submitting occupant role feedback, and querying historical events. It includes error handling and a cleanup function for the listener subscription. ```typescript import eventTimeline, { submitOccupantRoleFeedback } from "@sentiance-react-native/event-timeline"; async function setupEventTimeline() { try { // Set transport tags for all future transports await eventTimeline.setTransportTags({ app_session: "session_123", user_tier: "premium" }); // Listen for timeline updates const subscription = await eventTimeline.addTimelineUpdateListener( async (event) => { console.log(`Event ${event.id}: ${event.type}`); // When a transport completes, allow user to provide feedback if (event.type === "IN_TRANSPORT" && event.endTime) { const feedbackResult = await submitOccupantRoleFeedback( event.id, "DRIVER" ); console.log(`Feedback result: ${feedbackResult}`); } } ); // Query historical events const today = new Date(); today.setHours(0, 0, 0, 0); const tomorrow = new Date(today); tomorrow.setDate(tomorrow.getDate() + 1); const todaysEvents = await eventTimeline.getTimelineEvents( today.getTime(), tomorrow.getTime() ); console.log(`Events today: ${todaysEvents.length}`); // Return cleanup function return () => subscription.remove(); } catch (error) { console.error("Error setting up event timeline:", error); } } ``` -------------------------------- ### Venue Example Source: https://github.com/sentiance/react-native-sentiance/blob/main/_autodocs/api-reference/user-context.md Represents a significant location visited by the user. Use this to identify places like home or work. ```typescript const venue: Venue = { location: { latitude: 40.7128, longitude: -74.0060, accuracy: 10 }, significance: "WORK", type: "OFFICE" }; ``` -------------------------------- ### Get SDK Version Source: https://github.com/sentiance/react-native-sentiance/blob/main/_autodocs/api-reference/legacy.md Retrieves the current version string of the SDK. Returns a promise that resolves to a string. ```typescript getVersion(): Promise ``` -------------------------------- ### Get SDK Version Source: https://github.com/sentiance/react-native-sentiance/blob/main/_autodocs/api-reference/legacy.md Retrieves the SDK version string. This method is part of the legacy module. ```APIDOC ## getVersion() ### Description Retrieves the SDK version string. ### Method getVersion ### Response #### Success Response - **Promise** - The version string of the SDK. ``` -------------------------------- ### startTrip Source: https://github.com/sentiance/react-native-sentiance/blob/main/docs/react-native.md Starts tracking a trip, overriding default moving state detection. The SDK will track the trip until stopTrip is called or a 2-hour timeout is reached. Accepts a metadata object and an optional transport mode hint. ```APIDOC ## startTrip ### Description Initiates trip tracking, allowing manual control over moving state detection. The SDK monitors the trip until explicitly stopped or a timeout occurs. ### Method `RNSentiance.startTrip(metadata: object, transportModeHint?: number) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **metadata** (object) - Required - An object containing metadata for the trip. - **transportModeHint** (number) - Optional - A hint for the transport mode (e.g., SENTTransportModeCar, SENTTransportModeOnFoot). ### Request Example ```javascript const metadata = { corrolation_id: "3a5276ec-b2b2-4636-b893-eb9a9f014938" }; const transportModeHint = 2; // SENTTransportModeCar try { await RNSentiance.startTrip(metadata, transportModeHint); // Trip is started } catch (err) { // Unable to start trip } ``` ### Response #### Success Response None (operation is asynchronous) #### Response Example None ``` -------------------------------- ### Setup and Listen for Crash Detection Events Source: https://github.com/sentiance/react-native-sentiance/blob/main/_autodocs/api-reference/crash-detection.md Initializes crash detection, checks for device support, and registers listeners for vehicle crash events and diagnostic updates. Ensure the crash detection module is imported before use. ```typescript import SentianceCrashDetection from "@sentiance-react-native/crash-detection"; async function setupCrashDetection() { // Check if crash detection is supported const supported = await SentianceCrashDetection.isVehicleCrashDetectionSupported(); if (!supported) { console.log("Crash detection not supported on this device"); return; } // Register crash event listener const crashSubscription = await SentianceCrashDetection.addVehicleCrashEventListener( (crashEvent) => { console.log("Crash detected!"); console.log(`Severity: ${crashEvent.severity}`); console.log(`Location: ${crashEvent.location.latitude}, ${crashEvent.location.longitude}`); console.log(`Speed at impact: ${crashEvent.speedAtImpact} m/s`); // Send crash data to your backend reportCrashToBackend(crashEvent); } ); // Register diagnostic listener const diagnosticSubscription = await SentianceCrashDetection.addVehicleCrashDiagnosticListener( (diagnostic) => { console.log(`Diagnostic: ${diagnostic.crashDetectionStateDescription}`); } ); // Cleanup function return () => { crashSubscription.remove(); diagnosticSubscription.remove(); }; } ``` -------------------------------- ### Get SDK Status Source: https://github.com/sentiance/react-native-sentiance/blob/main/_autodocs/api-reference/legacy.md Retrieves comprehensive SDK status. This method is part of the legacy module. ```APIDOC ## getSdkStatus() ### Description Retrieves comprehensive SDK status. ### Method getSdkStatus ### Response #### Success Response - **Promise** - The comprehensive status of the SDK. ``` -------------------------------- ### Start a Trip with Metadata and Transport Mode Source: https://github.com/sentiance/react-native-sentiance/blob/main/docs/react-native.md Initiates trip tracking, overriding automatic detection. Accepts metadata and a transport mode hint. The trip continues until stopped or a 2-hour timeout is reached. ```javascript const metadata = { corrolation_id: "3a5276ec-b2b2-4636-b893-eb9a9f014938" }; const transportModeHint = 1; try { await RNSentiance.startTrip(metadata, transportModeHint); // Trip is started } catch (err) { // Unable to start trip } ``` -------------------------------- ### Reset SDK Source: https://github.com/sentiance/react-native-sentiance/blob/main/_autodocs/api-reference/core.md Resets the SDK to its pre-initialization state, clearing all stored data. This is useful for a clean start or troubleshooting. ```typescript const result = await SentianceCore.reset(); console.log("SDK reset, init state:", result.initState); ``` -------------------------------- ### Enable Detections Source: https://github.com/sentiance/react-native-sentiance/blob/main/_autodocs/api-reference/core.md Enables trip and activity detection on the SDK. This is a prerequisite for the SDK to start monitoring user activities. ```typescript const result = await SentianceCore.enableDetections(); console.log("Detection status:", result.detectionStatus); ``` -------------------------------- ### listenUserActivityUpdates Source: https://github.com/sentiance/react-native-sentiance/blob/main/_autodocs/api-reference/legacy.md Starts listening for real-time updates on user activity. This enables applications to react to changes in user behavior. ```APIDOC ## listenUserActivityUpdates() ### Description Starts listening for activity updates. ### Method Not specified (assumed to be a method call) ### Return Type `Promise` ``` -------------------------------- ### Start Listening for Vehicle Crash Events Source: https://github.com/sentiance/react-native-sentiance/blob/main/_autodocs/api-reference/legacy.md Initiates listening for vehicle crash events. Returns a promise that resolves to a boolean. ```typescript listenVehicleCrashEvents(): Promise ``` -------------------------------- ### Start Manual Trip Source: https://github.com/sentiance/react-native-sentiance/blob/main/_autodocs/api-reference/legacy.md Initiates a manual trip recording. Requires metadata and a transport mode hint. Returns a promise that resolves to a boolean indicating success. ```typescript startTrip(metadata: MetadataObject | null, hint: TransportMode): Promise ``` -------------------------------- ### Set Basic Transport Tags Source: https://github.com/sentiance/react-native-sentiance/blob/main/_autodocs/configuration.md Configure custom tags for future data transports. This example sets a user ID and app version. ```typescript // Set basic transport tags await SentianceCore.setTransportTags({ 'user_id': 'user_123', 'app_version': '1.0.0' }); ``` -------------------------------- ### Get Initialization Status Source: https://github.com/sentiance/react-native-sentiance/blob/main/docs/react-native.md Checks the current initialization status of the Sentiance SDK. Returns a string indicating whether the SDK is initialized. ```APIDOC ## Get Init Status ### Description Checks the current initialization status of the Sentiance SDK. Returns a string indicating whether the SDK is initialized. ### Method `getInitState` (GET-like operation for status retrieval) ### Parameters None ### Request Example ```javascript const initState = await RNSentiance.getInitState(); const isInitialized = initState == "INITIALIZED"; ``` ### Response #### Success Response (200) - **initState** (string) - The current initialization state of the SDK. Expected value for initialized state is "INITIALIZED". #### Response Example ```json { "initState": "INITIALIZED" } ``` ``` -------------------------------- ### Get All Timeline Updates Source: https://github.com/sentiance/react-native-sentiance/blob/main/_autodocs/configuration.md Fetches all available timeline updates starting from the epoch time (0). ```typescript const allUpdates = await eventTimeline.getTimelineUpdates(0); ``` -------------------------------- ### Configure Mobile Data Usage Based on User Preference Source: https://github.com/sentiance/react-native-sentiance/blob/main/_autodocs/configuration.md Dynamically control mobile data usage based on a user's preference. This example retrieves user data and applies the preference to the SDK setting. ```typescript const userPreference = await getUserDataPlan(); await SentianceCore.setIsAllowedToUseMobileData(userPreference.canUseMobileData); ``` -------------------------------- ### listenUserActivityUpdates() Source: https://github.com/sentiance/react-native-sentiance/blob/main/_autodocs/api-reference/core.md Starts listening for user activity updates via events. This enables real-time notifications of changes in user activity. ```APIDOC ## listenUserActivityUpdates() ### Description Starts listening for user activity updates via events. This enables real-time notifications of changes in user activity. ### Method `Promise` ### Example ```typescript await SentianceCore.listenUserActivityUpdates(); ``` ``` -------------------------------- ### listenTripTimeout Source: https://github.com/sentiance/react-native-sentiance/blob/main/_autodocs/api-reference/legacy.md Starts listening for trip timeout events. This is crucial for managing and handling trips that exceed their expected duration. ```APIDOC ## listenTripTimeout() ### Description Starts listening for trip timeout events. ### Method Not specified (assumed to be a method call) ### Return Type `Promise` ``` -------------------------------- ### Get SDK Initialization State Source: https://github.com/sentiance/react-native-sentiance/blob/main/_autodocs/api-reference/core.md Retrieves the current SDK initialization state. This helps in understanding the SDK's readiness before performing other operations. ```typescript const state = await SentianceCore.getInitState(); console.log("Init state:", state); ``` -------------------------------- ### Get Last Week's Timeline Events Source: https://github.com/sentiance/react-native-sentiance/blob/main/_autodocs/configuration.md Retrieves all timeline events from the past week. Uses the current date to calculate the start timestamp. ```typescript const oneWeekAgo = new Date(); oneWeekAgo.setDate(oneWeekAgo.getDate() - 7); const weekEvents = await eventTimeline.getTimelineEvents( oneWeekAgo.getTime(), Date.now() ); ``` -------------------------------- ### Segment Example Source: https://github.com/sentiance/react-native-sentiance/blob/main/_autodocs/api-reference/user-context.md Represents a user behavioral segment or persona. Use this to understand user habits like commuting. ```typescript const segment: Segment = { category: "MOBILITY", subcategory: "COMMUTE", type: "HEAVY_COMMUTER", id: 42, startTime: "2023-06-13T09:00:00Z", startTimeEpoch: 1686667200000, endTime: null, endTimeEpoch: null, attributes: [ { name: "commute_distance_km", value: 25.5 } ] }; ``` -------------------------------- ### Add Event Listener Example Source: https://github.com/sentiance/react-native-sentiance/blob/main/_autodocs/api-reference/legacy.md Demonstrates how to add a listener for the 'SENTIANCE_STATUS_UPDATE_EVENT' using the legacy module's addListener method. The callback function logs the received SDK status. ```typescript RNSentiance.addListener( "SENTIANCE_STATUS_UPDATE_EVENT", (status) => { console.log("SDK status updated:", status); } ); ``` -------------------------------- ### Get Today's Timeline Events Source: https://github.com/sentiance/react-native-sentiance/blob/main/_autodocs/configuration.md Fetches all timeline events that occurred today. Requires setting start and end timestamps for the current day. ```typescript const today = new Date(); today.setHours(0, 0, 0, 0); const tomorrow = new Date(today); tomorrow.setDate(tomorrow.getDate() + 1); const todayEvents = await eventTimeline.getTimelineEvents( today.getTime(), tomorrow.getTime() ); ``` -------------------------------- ### Initialization Source: https://github.com/sentiance/react-native-sentiance/blob/main/_autodocs/api-reference/legacy.md Initializes the SDK with credentials and auto-start option. This method is part of the legacy module for backward compatibility. ```APIDOC ## init(appId: string, secret: string, baseURL: string | null, shouldStart: boolean) ### Description Initializes the SDK with credentials and auto-start option. ### Method init ### Parameters #### Path Parameters - **appId** (string) - Required - Application ID - **secret** (string) - Required - Application secret - **baseURL** (string | null) - Required - Server URL or null for default - **shouldStart** (boolean) - Required - Auto-start detections after init ### Response #### Success Response - **Promise** - Indicates the success of the initialization and the SDK status. ``` -------------------------------- ### Get Harsh Driving Events for a Transport Source: https://github.com/sentiance/react-native-sentiance/blob/main/_autodocs/api-reference/driving-insights.md Fetch an array of harsh driving events recorded during a completed transport. Each event includes its type, start time, and magnitude. ```typescript const harshEvents = await SentianceDrivingInsights.getHarshDrivingEvents("transport_123"); harshEvents.forEach((event) => { console.log(`${event.type} at ${event.startTime}`); console.log(`Magnitude: ${event.magnitude}`); }); ``` -------------------------------- ### Get Timeline Updates Source: https://github.com/sentiance/react-native-sentiance/blob/main/_autodocs/api-reference/event-timeline.md Retrieve updated events from the timeline after a specified timestamp. Useful for staying up-to-date with the latest changes, including events that started before the timestamp but were updated afterward. ```typescript getTimelineUpdates( afterEpochTimeMs: number, includeProvisionalEvents?: boolean ): Promise ``` ```typescript // Get timeline updates from one hour ago const oneHourAgo = Date.now() - (60 * 60 * 1000); const events = await eventTimeline.getTimelineUpdates(oneHourAgo, true); console.log(`Got ${events.length} updates`); ``` -------------------------------- ### Get SDK Version Source: https://github.com/sentiance/react-native-sentiance/blob/main/_autodocs/api-reference/core.md Retrieves the current version string of the Sentiance SDK. Useful for debugging and compatibility checks. ```typescript const version = await SentianceCore.getVersion(); console.log("SDK Version:", version); ``` -------------------------------- ### Get Call While Moving Events for a Transport Source: https://github.com/sentiance/react-native-sentiance/blob/main/_autodocs/api-reference/driving-insights.md Fetch an array of events where calls were made while the vehicle was in motion during a completed transport. Logs the call start time and maximum speed during the call. ```typescript const callEvents = await SentianceDrivingInsights.getCallWhileMovingEvents("transport_123"); callEvents.forEach((event) => { console.log(`Call at ${event.startTime}`); console.log(`Max speed: ${event.maxTravelledSpeedInMps} m/s`); }); ``` -------------------------------- ### Initialize SDK Source: https://github.com/sentiance/react-native-sentiance/blob/main/_autodocs/api-reference/legacy.md Initializes the SDK with application credentials, an optional base URL, and an auto-start flag. This method returns a promise that resolves to a boolean or SdkStatus. ```typescript init( appId: string, secret: string, baseURL: string | null, shouldStart: boolean ): Promise ``` -------------------------------- ### Configuration Reference Source: https://github.com/sentiance/react-native-sentiance/blob/main/_autodocs/README.md Details constructor options, method parameters, and configuration patterns for the SDK. ```APIDOC ## Configuration Reference ### Description This reference details all available constructor options, method parameters, and general configuration patterns for the Sentiance React Native SDK. ### Documentation Link [configuration.md](configuration.md) ``` -------------------------------- ### Initialize SDK with User Linking Source: https://github.com/sentiance/react-native-sentiance/blob/main/_autodocs/api-reference/legacy.md Initializes the SDK with user linking enabled, using provided credentials, an optional base URL, and an auto-start flag. The promise resolves to a boolean or SdkStatus. ```typescript initWithUserLinkingEnabled( appId: string, secret: string, baseURL: string | null, shouldStart: boolean ): Promise ``` -------------------------------- ### Enable App Session Data Collection Source: https://github.com/sentiance/react-native-sentiance/blob/main/_autodocs/configuration.md Enable the Sentiance SDK to collect app session data. Call this function with `true` to start data collection. ```typescript await SentianceCore.setAppSessionDataCollectionEnabled(true); ``` -------------------------------- ### Listen for User Activity Updates Source: https://github.com/sentiance/react-native-sentiance/blob/main/_autodocs/api-reference/core.md Starts listening for user activity updates via events. This allows your application to react to changes in user activity in real-time. ```typescript await SentianceCore.listenUserActivityUpdates(); ``` -------------------------------- ### Initialization with User Linking Source: https://github.com/sentiance/react-native-sentiance/blob/main/_autodocs/api-reference/legacy.md Initializes the SDK with user linking enabled. This method is part of the legacy module for backward compatibility. ```APIDOC ## initWithUserLinkingEnabled(appId: string, secret: string, baseURL: string | null, shouldStart: boolean) ### Description Initializes SDK with user linking enabled. ### Method initWithUserLinkingEnabled ### Parameters #### Path Parameters - **appId** (string) - Required - Application ID - **secret** (string) - Required - Application secret - **baseURL** (string | null) - Required - Server URL or null for default - **shouldStart** (boolean) - Required - Auto-start detections after init ### Response #### Success Response - **Promise** - Indicates the success of the initialization and the SDK status. ``` -------------------------------- ### SafetyScores Data Type Example Source: https://github.com/sentiance/react-native-sentiance/blob/main/_autodocs/api-reference/driving-insights.md An example demonstrating the structure of the SafetyScores object, which includes various driving metrics on a scale of 0 to 1. ```typescript const scores: SafetyScores = { smoothScore: 0.95, focusScore: 0.88, legalScore: 0.92, overallScore: 0.92 }; ``` -------------------------------- ### Linker Type Source: https://github.com/sentiance/react-native-sentiance/blob/main/_autodocs/types.md A callback function type used for user linking. It takes an install ID and returns a promise resolving to a boolean indicating success. ```typescript type Linker = (installId: string) => Promise; ``` -------------------------------- ### Core Module Source: https://github.com/sentiance/react-native-sentiance/blob/main/_autodocs/README.md Provides user management, SDK initialization, trip and activity detection, metadata management, listener registration, and data transmission. ```APIDOC ## Core Module (`@sentiance-react-native/core`) ### Description This module handles core functionalities including user management and linking, SDK initialization and state management, trip and activity detection, metadata management, listener registration for events, and data transmission and quotas. ### Documentation Link [api-reference/core.md](api-reference/core.md) ``` -------------------------------- ### Enable Native SDK Initialization Source: https://github.com/sentiance/react-native-sentiance/blob/main/_autodocs/api-reference/legacy.md Call this function to enable the native SDK initialization. It returns a promise that resolves to a boolean indicating success. ```typescript enableNativeInitialization(): Promise ``` -------------------------------- ### Initialize Sentiance SDK with Custom Server URL Source: https://github.com/sentiance/react-native-sentiance/blob/main/_autodocs/configuration.md Initializes the Sentiance SDK using a specified custom server URL. Use this if you are using a private or regional Sentiance endpoint. ```typescript const status3 = await RNSentiance.init( "app_id", "app_secret", "https://custom-sentiance.example.com", true ); ``` -------------------------------- ### getTimelineUpdates Source: https://github.com/sentiance/react-native-sentiance/blob/main/_autodocs/api-reference/event-timeline.md Returns all updated events in the event timeline after the specified date, sorted by last update time. This method returns events that started after `afterEpochTimeMs`, but may also return events that started before if they were updated afterward. ```APIDOC ## getTimelineUpdates(afterEpochTimeMs: number, includeProvisionalEvents?: boolean) ### Description Returns all updated events in the event timeline after the specified date, sorted by last update time. This method returns events that started after `afterEpochTimeMs`, but may also return events that started before if they were updated afterward. ### Parameters #### Query Parameters - **afterEpochTimeMs** (number) - Required - Timestamp (milliseconds) to retrieve updates from (exclusive) - **includeProvisionalEvents** (boolean) - Optional - Include provisional events (defaults to false) ### Return Type `Promise` - Array of Event objects sorted by last update time, or empty array if none found ### Example ```typescript // Get timeline updates from one hour ago const oneHourAgo = Date.now() - (60 * 60 * 1000); const events = await eventTimeline.getTimelineUpdates(oneHourAgo, true); console.log(`Got ${events.length} updates`); ``` ``` -------------------------------- ### getInitState() Source: https://github.com/sentiance/react-native-sentiance/blob/main/_autodocs/api-reference/core.md Retrieves the current SDK initialization state. This helps in understanding the SDK's readiness before performing other operations. ```APIDOC ## getInitState() ### Description Retrieves the current SDK initialization state. This helps in understanding the SDK's readiness before performing other operations. ### Method `Promise` ### Return Type `Promise` - One of: `"NOT_INITIALIZED"`, `"INIT_IN_PROGRESS"`, `"INITIALIZED"`, `"RESETTING"`, `"UNRECOGNIZED_STATE"` ### Example ```typescript const state = await SentianceCore.getInitState(); console.log("Init state:", state); ``` ``` -------------------------------- ### SpeedingEvent Source: https://github.com/sentiance/react-native-sentiance/blob/main/_autodocs/api-reference/driving-insights.md Represents an instance of speeding. Includes start and end times, and GPS waypoints. ```APIDOC ## SpeedingEvent ### Description Represents an instance of speeding. ### Fields - **startTime** (string) - ISO 8601 start time - **startTimeEpoch** (number) - Start time in milliseconds - **endTime** (string) - ISO 8601 end time - **endTimeEpoch** (number) - End time in milliseconds - **waypoints** (Waypoint[]) - GPS points during speeding ``` -------------------------------- ### Get User ID Source: https://github.com/sentiance/react-native-sentiance/blob/main/_autodocs/api-reference/legacy.md Retrieves the user ID. This method is part of the legacy module. ```APIDOC ## getUserId() ### Description Retrieves the user ID. ### Method getUserId ### Response #### Success Response - **Promise** - The unique user ID. ``` -------------------------------- ### Get SDK Version Source: https://github.com/sentiance/react-native-sentiance/blob/main/docs/react-native.md Retrieves the current version of the Sentiance SDK that is integrated into your application. ```APIDOC ## Get SDK Version ### Description Retrieves the current version of the Sentiance SDK that is integrated into your application. ### Method `getVersion` (GET-like operation for version retrieval) ### Parameters None ### Request Example ```javascript const version = await RNSentiance.getVersion(); ``` ### Response #### Success Response (200) - **version** (string) - The current version string of the Sentiance SDK. #### Response Example ```json { "version": "1.2.3" } ``` ``` -------------------------------- ### PhoneUsageEvent Source: https://github.com/sentiance/react-native-sentiance/blob/main/_autodocs/api-reference/driving-insights.md Represents phone usage during driving. Includes start and end times, and GPS waypoints. ```APIDOC ## PhoneUsageEvent ### Description Represents phone usage during driving. ### Fields - **startTime** (string) - ISO 8601 start time - **startTimeEpoch** (number) - Start time in milliseconds - **endTime** (string) - ISO 8601 end time - **endTimeEpoch** (number) - End time in milliseconds - **waypoints** (Waypoint[]) - GPS points during event ``` -------------------------------- ### linkUser(linker: (installId: string) => boolean) Source: https://github.com/sentiance/react-native-sentiance/blob/main/_autodocs/api-reference/core.md Links an existing user to the device using a custom linker callback. This allows for custom user linking logic. ```APIDIDOC ## linkUser(linker: (installId: string) => boolean) ### Description Links an existing user to the device using a custom linker callback. ### Method `linkUser` ### Parameters #### Request Body - **linker** (Function) - Required - Callback that receives `installId` and returns boolean ### Return Type `Promise` - Contains `userInfo` with user details ### Example ```typescript const result = await SentianceCore.linkUser((installId) => { // Send installId to your backend to validate and link user return true; // Return true on success }); ``` ``` -------------------------------- ### Publish Library Packages Locally Source: https://github.com/sentiance/react-native-sentiance/blob/main/publishing.md Executes the npm script to publish all library packages to the configured local Verdaccio repository. ```bash npm run publishLocal ``` -------------------------------- ### Get User Current Activity Source: https://github.com/sentiance/react-native-sentiance/blob/main/docs/react-native.md Asynchronously fetches the user's current detected activity. ```javascript const userActivity = await RNSentiance.getUserActivity(); ``` -------------------------------- ### Get Wi-Fi Quota Limit Source: https://github.com/sentiance/react-native-sentiance/blob/main/docs/react-native.md Retrieves the current limit for Wi-Fi data usage in bytes. ```javascript const limit = await RNSentiance.getWiFiQuotaLimit(); ``` -------------------------------- ### Link User with Custom Callback Source: https://github.com/sentiance/react-native-sentiance/blob/main/_autodocs/api-reference/core.md Links an existing user to the device using a custom linker callback. The callback receives an installId and should return a boolean indicating success. This is useful for custom user linking flows. ```typescript const result = await SentianceCore.linkUser((installId) => { // Send installId to your backend to validate and link user return true; // Return true on success }); ``` -------------------------------- ### Import SentianceCore Module Source: https://github.com/sentiance/react-native-sentiance/blob/main/_autodocs/api-reference/core.md Import the main singleton interface for core SDK operations. ```typescript import SentianceCore from "@sentiance-react-native/core"; ``` -------------------------------- ### Legacy Module Source: https://github.com/sentiance/react-native-sentiance/blob/main/_autodocs/README.md Provides a backward-compatible API for migration purposes, including the original initialization interface and event-based listener system. ```APIDOC ## Legacy Module (`@sentiance-react-native/legacy`) ### Description This module offers a backward-compatible API, including the original initialization interface and an event-based listener system. It is maintained for migration purposes. ### Documentation Link [api-reference/legacy.md](api-reference/legacy.md) ``` -------------------------------- ### enableDetections() Source: https://github.com/sentiance/react-native-sentiance/blob/main/_autodocs/api-reference/core.md Enables trip and activity detection on the SDK. This is a prerequisite for the SDK to start monitoring user movements. ```APIDOC ## enableDetections() ### Description Enables trip and activity detection on the SDK. This is a prerequisite for the SDK to start monitoring user movements. ### Method `Promise` ### Return Type `Promise` - Contains `sdkStatus` and `detectionStatus` ### Example ```typescript const result = await SentianceCore.enableDetections(); console.log("Detection status:", result.detectionStatus); ``` ``` -------------------------------- ### Initialize Sentiance SDK with User Linking Source: https://github.com/sentiance/react-native-sentiance/blob/main/_autodocs/configuration.md Initializes the Sentiance SDK and enables user linking features. This is typically used when integrating with an existing user management system. ```typescript const status4 = await RNSentiance.initWithUserLinkingEnabled( "app_id", "app_secret", null, true ); ``` -------------------------------- ### Get User Access Token Source: https://github.com/sentiance/react-native-sentiance/blob/main/_autodocs/api-reference/legacy.md Requests a user access token. This method is part of the legacy module. ```APIDOC ## getUserAccessToken() ### Description Requests a user access token. ### Method getUserAccessToken ### Response #### Success Response - **Promise** - The user access token object. ``` -------------------------------- ### Get User ID Source: https://github.com/sentiance/react-native-sentiance/blob/main/_autodocs/api-reference/legacy.md Retrieves the unique identifier for the current user. Returns a promise that resolves to a string. ```typescript getUserId(): Promise ``` -------------------------------- ### Create User with Linker Callback Source: https://github.com/sentiance/react-native-sentiance/blob/main/_autodocs/configuration.md Use this option to provide a custom asynchronous function for user linking. The linker should return true on success and false on failure. ```typescript const user3 = await SentianceCore.createUser({ linker: async (installId) => { // Send installId to your backend const response = await fetch('/api/link-user', { method: 'POST', body: JSON.stringify({ installId }) }); return response.ok; } }); ``` -------------------------------- ### Get SDK Status Source: https://github.com/sentiance/react-native-sentiance/blob/main/_autodocs/api-reference/legacy.md Retrieves comprehensive status information about the SDK. Returns a promise that resolves to SdkStatus. ```typescript getSdkStatus(): Promise ``` -------------------------------- ### getVersion() Source: https://github.com/sentiance/react-native-sentiance/blob/main/_autodocs/api-reference/core.md Retrieves the SDK version string. Useful for debugging and compatibility checks. ```APIDOC ## getVersion() ### Description Retrieves the SDK version string. ### Method `getVersion` ### Parameters None ### Return Type `Promise` - Version string (e.g., "6.16.0") ### Example ```typescript const version = await SentianceCore.getVersion(); console.log("SDK Version:", version); ``` ``` -------------------------------- ### listenVehicleCrashEvents Source: https://github.com/sentiance/react-native-sentiance/blob/main/_autodocs/api-reference/legacy.md Starts listening for vehicle crash events. This function should be called to receive notifications when a vehicle crash is detected. ```APIDOC ## listenVehicleCrashEvents() ### Description Starts listening for vehicle crash events. This function enables the reception of notifications when a vehicle crash is detected. ### Method ``` listenVehicleCrashEvents(): Promise ``` ### Return Value - `Promise`: A promise that resolves to a boolean indicating if the listener was successfully started. ``` -------------------------------- ### Import Event Timeline Module Source: https://github.com/sentiance/react-native-sentiance/blob/main/_autodocs/api-reference/event-timeline.md Import the main event timeline module or specific functions like submitOccupantRoleFeedback. ```typescript import eventTimeline from "@sentiance-react-native/event-timeline"; // or access feedback through: import { submitOccupantRoleFeedback } from "@sentiance-react-native/event-timeline"; ``` -------------------------------- ### Define SDK Initialization States Source: https://github.com/sentiance/react-native-sentiance/blob/main/_autodocs/api-reference/legacy.md Defines the enumeration for the different states of SDK initialization. ```typescript type SdkInitState = | "NOT_INITIALIZED" | "INIT_IN_PROGRESS" | "INITIALIZED" | "RESETTING" | "UNRECOGNIZED_STATE" ``` -------------------------------- ### Import SentianceSmartGeofences Module Source: https://github.com/sentiance/react-native-sentiance/blob/main/_autodocs/api-reference/smart-geofences.md Import the necessary module to use Sentiance Smart Geofences functionality. ```typescript import SentianceSmartGeofences from "@sentiance-react-native/smart-geofences"; ``` -------------------------------- ### DrivingEvent Interface Source: https://github.com/sentiance/react-native-sentiance/blob/main/_autodocs/types.md Base interface for driving-related events, defining common properties like start and end times and waypoints. ```typescript interface DrivingEvent { startTime: string; startTimeEpoch: number; endTime: string; endTimeEpoch: number; waypoints: Waypoint[]; } ``` -------------------------------- ### Types Reference Source: https://github.com/sentiance/react-native-sentiance/blob/main/_autodocs/README.md Complete documentation of all public types, interfaces, and enumerations used within the SDK. ```APIDOC ## Types Reference ### Description This section provides complete documentation for all public types, interfaces, and enumerations used within the Sentiance React Native SDK. ### Documentation Link [types.md](types.md) ```