voyage 0.0.3 copy "voyage: ^0.0.3" to clipboard
voyage: ^0.0.3 copied to clipboard

PlatformAndroid

Plugin to test the working of plugin already developed.

Voyage πŸš— #

A comprehensive Flutter plugin for the Kruzr 360 SDK, providing advanced driving analytics, trip monitoring, and user behavior analysis capabilities.

Version Flutter Dart

πŸ“‹ Table of Contents #

🌟 Overview #

Voyage is a Flutter plugin that integrates with the Kruzr 360 SDK to provide comprehensive driving analytics and trip monitoring capabilities. It enables developers to build applications with advanced telematics features including real-time trip tracking, driving behavior analysis, user ranking systems, and detailed performance metrics.

✨ Features #

  • πŸš€ SDK Integration - Easy initialization and platform version detection
  • πŸ“± Trip Monitoring - Automatic trip detection and real-time monitoring
  • πŸ‘€ User Management - Registration, authentication, and profile management
  • πŸ“Š Analytics & Metrics - Comprehensive driving behavior analysis
  • πŸ† Leaderboards - User rankings and performance comparison
  • πŸŽ–οΈ Achievements - Track progress across driving behavior categories
  • πŸ” OTP Authentication - [DEPRECATED] Secure phone number verification
  • 🌐 Data Synchronization - Automatic and manual data sync capabilities
  • 🎯 Trip Control - Manual trip start/stop functionality
  • πŸ—ΊοΈ Trip Route Visualization – Retrieve full route GeoJSON for rendering
  • πŸ“€ Trip Sharing - Generate shareable trip URLs
  • πŸ“Ά Bluetooth Support - Device scanning and management

πŸ“¦ Installation #

Add this to your pubspec.yaml file:

dependencies:
  voyage: ^0.0.3

Then run:

flutter pub get

πŸš€ Getting Started #

1. Initializes the Kruzr 360 SDK with the provided configuration. #

This method must be called before using any other functionality of the Kruzr 360 SDK. It establishes the connection with the underlying native SDK and configures various SDK behaviors and settings.

Parameters:

  • [kruzr360InitConfig]: Configuration object containing all required initialization settings:
    • licenseKey: Valid license key provided by Kruzr for authentication
    • appName: Name of your application for identification
    • notificationChannelId: Id for the notification channel (Android)
    • shouldTripAutoEnd: Whether trips should automatically end (default: true)
    • shouldTripAutoStart: Whether trips should automatically start (default: true)
    • allowEventSyncRealTime: Whether to sync events in real-time (default: true)

Usage:

try {
  final config = Kruzr360InitConfig(
    licenseKey: 'your-license-key-here',
    appName: 'My Driving App',
    notificationChannelId: 'co.mycompany.myapp.notification.CHANNEL_ID_TELEMATICS',
    shouldTripAutoEnd: true,
    shouldTripAutoStart: true,
    allowEventSyncRealTime: false,
  );
  await Kruzr360Communicator.initializeSDK(config);
  print('SDK initialized successfully');
} catch (e) {
  print('Failed to initialize SDK: $e');
}

Throws:

  • Future.error("Unable to initialize SDK"): When the SDK fails to initialize due to platform-specific issues, invalid license key, or other initialization errors.

Platform Exceptions Handled:

  • [PlatformException]: Catches platform-specific errors from native Android/iOS code
  • [Exception]: Catches any other general exceptions during initialization

Important Notes:

  • This is a static method and should be called before creating any instance of [Kruzr360Communicator]
  • The method will log detailed error information in debug mode for troubleshooting purposes
  • Initialization should typically be done in your main.dart file or during app startup
  • Configuration settings affect SDK behavior throughout the app lifecycle

Example Implementation:

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  try {
    final config = Kruzr360InitConfig(
      licenseKey: 'your-license-key',
      appName: 'My App',
      notificationChannelId: 'co.mycompany.myapp.notification.CHANNEL_ID_TELEMATICS',
    );
    await Kruzr360Communicator.initializeSDK(config);
    runApp(MyApp());
  } catch (e) {
    // Handle initialization failure
    print('SDK initialization failed: $e');
    // Show error dialog or fallback UI
   }
}

2. Create a Communicator Instance #

final communicator = Kruzr360Communicator(
  companyName: 'your-company-name',
  accountName: 'your-account-name',
);

3. Set Up Location Services #

communicator.setupLocationStuffs();

βš™οΈ Configuration #

Android Setup #

Add the following permissions to your android/app/src/main/AndroidManifest.xml:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />

πŸ“± Usage #

User Registration and Authentication #

// Register User
final userId = await communicator.registerUserToKruzr(
  driverId: 'unique_driver_123',
  name: 'John Doe',
  countryCode: '+1',
  phoneNumber: '1234567890',
  email: '[email protected]',
);

Trip Monitoring #

// Initiate trip monitoring
await communicator.initiateTripMonitoring();

// Start a trip manually
final started = await communicator.startTrip();

// Get current trip data
final currentTrip = await communicator.getCurrentTripData();

// Stop a trip
final stopped = await communicator.stopTrip();

Enables or disables automatic trip start detection #

Controls whether the SDK should automatically detect and start recording trips based on vehicle movement patterns. When enabled, the SDK will automatically begin trip recording when driving behavior is detected.

Parameters:

  • [shouldAutoStart]: true to enable automatic trip start, false to disable

Usage:

try {
  // Enable automatic trip start
  await communicator.setTripAutoStartEnabled(true);
  print('Automatic trip start enabled');

  // Disable automatic trip start (manual start only)
  await communicator.setTripAutoStartEnabled(false);
  print('Automatic trip start disabled - manual start required');
} catch (e) {
  print('Failed to change auto start setting: $e');
}

Throws:

  • Future.error("Unable to change trip auto start pref"): When setting update fails

Important Notes:

  • Setting persists across app sessions
  • When disabled, trips must be started manually using [startTrip]
  • Overrides the initial configuration from [Kruzr360InitConfig]
  • Changes take effect immediately for new trip detection

Use Cases:

  • User preference settings
  • Fleet management policies
  • Testing and debugging scenarios
  • Power management optimization

Retrieves the current automatic trip start setting. #

Returns whether the SDK is currently configured to automatically detect and start recording trips based on vehicle movement patterns. Returns:

  • bool: true if automatic trip start is enabled, false otherwise Usage:
try {
  final autoStartEnabled = await communicator.getTripAutoStartEnabled();
  if (autoStartEnabled) {
    print('Automatic trip start is enabled');
    // Show UI indicating automatic mode
  } else {
    print('Manual trip start required');
    // Show manual start button
  }
} catch (e) {
  print('Failed to get auto start setting: $e');
}

Throws:

  • Future.error("Unable to get trip auto start pref"): When retrieval fails Use Cases:
  • Updating UI based on current settings
  • Validating configuration state
  • Settings screen initialization
  • Debugging trip detection issues

Retrieves the current automatic trip end setting. #

Returns whether the SDK is currently configured to automatically detect and stop recording trips when the vehicle stops moving. Returns:

  • bool: true if automatic trip end is enabled, false otherwise Usage:
try {
  final autoEndEnabled = await communicator.getTripAutoEndEnabled();
  if (autoEndEnabled) {
    print('Automatic trip end is enabled');
    // Trips will end automatically when stopped
  } else {
    print('Manual trip end required');
    // Show manual stop button
  }
} catch (e) {
  print('Failed to get auto end setting: $e');
}

Throws:

  • Future.error("Unable to get trip auto end pref"): When retrieval fails Use Cases:
  • Updating UI based on current settings
  • Validating configuration state
  • Settings screen initialization
  • Debugging trip termination issues

Enables or disables automatic trip end detection. #

Controls whether the SDK should automatically detect and stop recording trips when the vehicle stops moving for a sufficient duration. When enabled, the SDK will automatically end trip recording based on movement patterns. Parameters:

  • [shouldAutoEnd]: true to enable automatic trip end, false to disable Usage:
try {
  // Enable automatic trip end
  await communicator.setTripAutoEndEnabled(true);
  print('Automatic trip end enabled');
  // Disable automatic trip end (manual end only)
  await communicator.setTripAutoEndEnabled(false);
  print('Automatic trip end disabled - manual end required');
} catch (e) {
  print('Failed to change auto end setting: $e');
}

Throws:

  • Future.error("Unable to change trip auto end pref"): When setting update fails Important Notes:
  • Setting persists across app sessions
  • When disabled, trips must be stopped manually using [stopTrip]
  • Overrides the initial configuration from [Kruzr360InitConfig]
  • Changes take effect immediately for active trips Use Cases:
  • User preference settings
  • Fleet management policies
  • Long stop scenarios (gas stations, shopping)
  • Testing and debugging scenarios

Enables or disables real-time event synchronization. #

Controls whether driving events and trip data should be synchronized with Kruzr servers immediately as they occur, or batched for later synchronization. Real-time sync provides immediate data availability but may impact battery life and data usage.

Parameters:

  • [allowEventSyncRealTime]: true to enable real-time sync, false for batch sync

Usage:

try {
  // Enable real-time synchronization
  await communicator.shouldEventSyncRealTime(true);
  print('Real-time sync enabled - events sync immediately');
  // Disable real-time sync (batch mode)
  await communicator.shouldEventSyncRealTime(false);
  print('Batch sync enabled - events sync periodically');
} catch (e) {
  print('Failed to change sync setting: $e');
}

Throws:

  • Future.error("Unable to change event sync real time pref"): When setting update fails Important Notes:
  • Setting persists across app sessions
  • Real-time sync requires active internet connection
  • Overrides the initial configuration from [Kruzr360InitConfig]
  • Affects battery life and data usage patterns
  • May be subject to network conditions and server availability

Performance Considerations:

  • Real-time enabled: Immediate data availability, higher battery/data usage
  • Real-time disabled: Better battery life, periodic data updates

Use Cases:

  • Fleet monitoring requiring immediate updates
  • Battery optimization for extended trips
  • Network-constrained environments
  • User preference settings

Retrieves the current real-time event synchronization setting. #

Returns whether the SDK is currently configured to synchronize driving events and trip data immediately as they occur, or to batch them for later synchronization.

Returns:

  • bool: true if real-time sync is enabled, false for batch sync

Usage:

try {
  final realTimeSyncEnabled = await communicator.isEventSyncRealTimeEnabled();
  if (realTimeSyncEnabled) {
    print('Real-time sync active - immediate data updates');
    // Show real-time indicator in UI
  } else {
    print('Batch sync active - periodic data updates');
    // Show batch sync indicator
  }
} catch (e) {
  print('Failed to get sync setting: $e');
}

Throws:

  • Future.error("Unable to get event sync real time pref"): When retrieval fails

Use Cases:

  • Updating UI sync status indicators
  • Validating configuration state
  • Settings screen initialization
  • Performance monitoring and optimization
  • Debugging data synchronization issues

Analytics and Metrics #

// Get driving summary
final summary = await communicator.getDrivingSummary(
  DateTime.now().subtract(Duration(days: 30)),
  DateTime.now(),
  KruzrPerioicType.weekly,
);

// Get user ranking
final userRank = await communicator.getCurrentUserRank();

// Get leaderboard
final topDrivers = await communicator.getLeaderboardTop10();

// Get user achievements
final achievements = await communicator.fetchMyAchievements();
if (achievements != null) {
  // Check overall achievement progress
  print('Current tier: ${achievements.overall?.currentTier?.value}');
  print('Progress: ${achievements.overall?.count}');
  
  // Check specific category achievements
  if (achievements.speeding != null) {
    print('Speeding tier: ${achievements.speeding!.currentTier?.value}');
    print('Trips to next tier: ${achievements.speeding!.remainingTrips}');
  }
}

Retrieves possible intervention events that occurred during a specific trip. #

Analyzes trip data to identify segments where driving interventions could have been beneficial, such as areas with poor driving behavior, potential safety issues, or coaching opportunities. Each intervention includes location data, timing, and associated scoring statistics.

Parameters:

  • [appTripId]: Unique identifier for the trip to analyze

Returns:

  • List<PossibleIntervention>: List of intervention events with detailed information

Usage:

try {
  final interventions = await communicator.getPossibleInterventionsForAppTripId('trip-123');
  for (final intervention in interventions) {
    print('Intervention type: ${intervention.scoringType}');
    print('Start time: ${intervention.startTime}');
    print('Location: ${intervention.startAddress}');

    // Check scoring statistics
    if (intervention.scoreStats != null) {
      intervention.scoreStats!.forEach((scoreType, stats) {
        if (stats != null) {
          print('$scoreType - Average: ${stats.average}, Max: ${stats.max}');
        }
      });
    }
  }
} catch (e) {
  print('Failed to get interventions: $e');
}

Throws:

  • Future.error("Unable to get possible interventions"): When retrieval fails

Intervention Data Includes:

  • Timing: Start and end timestamps in ISO 8601 format
  • Location: GPS coordinates and resolved addresses for start/end points
  • Scoring: Statistical data for various driving behavior categories
  • Type: Classification of the intervention (e.g., "SPEEDING", "HARD_BRAKING", etc.)

Common Intervention Triggers:

  • Hard braking events
  • Rapid acceleration
  • Sharp cornering
  • Speeding incidents
  • Distracted driving patterns
  • Drowsy driving detection

Use Cases:

  • Driver coaching and feedback
  • Safety analysis and reporting
  • Insurance risk assessment
  • Fleet management insights
  • Training program development

Prerequisites:

  • Trip must be completed and processed
  • Trip data must be synchronized with servers
  • Valid app trip ID is required

πŸ—ΊοΈ Fetching Trip Route (GeoJSON) #

Fetch the complete trip route including start/end points, path, and event highlights.

try {
  final route = await communicator.fetchRoute("2985_1764285633333");

  if (route != null) {
    for (final feature in route.collection!) {
      print("Type: ${feature.type}");
      print("Properties: ${feature.properties}");
      print("Geometry: ${feature.geometry?.type}");
    }
  }
} catch (e) {
  print("Failed to fetch route: $e");
}

Route Contains:

  1. Route LineString (full trip path)

  2. Start and end points

  3. Speeding / braking / acceleration event markers

  4. Highlight segments with styling metadata

  5. Event metadata (startTime, scoreStats, etc.)

Works with any map render engine: MapLibre, Mapbox, flutter_map, Leaflet, or custom painter.

πŸ“– API Reference #

Core SDK Methods #

Method Description
initializeSDK(String licenseKey) Initialize the SDK with license key
getPlatformVersion() Get platform version information
setupLocationStuffs() Set up location services

Trip Monitoring #

Method Description
initiateTripMonitoring() Enable automatic trip detection
startTrip() Manually start a trip
stopTrip() Manually stop a trip
getCurrentTripData() Get real-time trip information

User Management #

Method Description
registerUserToKruzr() Register a new user
logout() Log out current user
isLoggedIn() Check login status
userDetails() Get user information

Analytics & Metrics #

Method Description
getUserStreak() Get driving streak information
getCurrentUserRank() Get user ranking
leaderboard() Get paginated leaderboard
getAggregatedDistanceTravelled() Get distance metrics
getDrivingSummary() Get comprehensive driving overview
getAggregatedDrivingScore() Get driving performance scores
fetchMyAchievements() Get user achievements across all categories
fetchTripDetailsByAppTripId() Get historical trip details
fetchTripStatsByAppTripId() Get trip statistical analysis
getPossibleInterventionsForAppTripId() Get possible intervention events for a trip
fetchRoute() Fetch Trip Route (GeoJSON)

Authentication (OTP) [DEPRECATED] #

Method Description
generateOtp() Generate OTP for phone verification
generateOtpAlternate() Alternative OTP generation method
verifyOtp() Verify OTP code

Data Management #

Method Description
syncTripData() Manually sync trip data
getPendingFilesCount() Get count of pending uploads

Sharing & Bluetooth #

Method Description
generateShareableURL() Create shareable trip URLs
bluetoothScanEventStream() Get Bluetooth event stream
scanForNearbyDevices() Scan for nearby Bluetooth devices

πŸ” Permissions #

This plugin requires the following permissions:

Android #

  • ACCESS_FINE_LOCATION - For accurate location tracking
  • ACCESS_COARSE_LOCATION - For general location services
  • ACCESS_BACKGROUND_LOCATION - For background trip monitoring
  • BLUETOOTH & BLUETOOTH_ADMIN - For Bluetooth device management

iOS #

  • Location permissions will be requested automatically
  • Bluetooth permissions for device scanning

πŸ’‘ Examples #

See the example/ directory for a complete Flutter application demonstrating the usage of the Voyage plugin.

πŸ› Issues and Support #

If you encounter any issues or have questions:

  1. Check the documentation
  2. Search existing issues
  3. Create a new issue with detailed information

πŸ“„ License #

This project is licensed under the terms specified in the LICENSE file.

🀝 Contributing #

Contributions are welcome! Please read the contributing guidelines before submitting pull requests.


Made with ❀️ by the Kruzr Team

0
likes
140
points
1.63k
downloads

Publisher

unverified uploader

Weekly Downloads

Plugin to test the working of plugin already developed.

Homepage
Repository (GitHub)

Documentation

API reference

License

unknown (license)

Dependencies

flutter, geojson_vi, permission_handler, plugin_platform_interface

More

Packages that depend on voyage

Packages that implement voyage