Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.bookovia.com/llms.txt

Use this file to discover all available pages before exploring further.

Real-time Streaming

Bookovia’s Real-time Streaming enables live data transmission and instant vehicle tracking through WebSocket connections, providing immediate access to location updates, safety events, and trip status changes as they happen.

Overview

Real-time streaming transforms traditional polling-based tracking into instant, event-driven monitoring:
  • WebSocket Connections - Bidirectional, low-latency communication
  • Event-Driven Architecture - Instant notifications for critical events
  • Live Location Tracking - Real-time GPS position updates
  • Safety Monitoring - Immediate alerts for driving events
  • Status Updates - Trip lifecycle and vehicle state changes
  • Scalable Infrastructure - Handles thousands of concurrent connections

WebSocket Connection

Establishing Connection

Connect to the Bookovia streaming endpoint for live data:
const ws = new WebSocket('wss://api.bookovia.com/v1/streaming');

ws.onopen = () => {
  // Authenticate with API key
  ws.send(JSON.stringify({
    type: 'auth',
    api_key: 'bkv_live_your_api_key'
  }));
  
  // Subscribe to specific data streams
  ws.send(JSON.stringify({
    type: 'subscribe',
    channels: ['locations', 'safety_events', 'trip_updates'],
    filters: {
      organization_id: 'org_123',
      vehicle_ids: ['vehicle_456', 'vehicle_789']
    }
  }));
};

ws.onmessage = (event) => {
  const data = JSON.parse(event.data);
  handleStreamingData(data);
};

Connection Management

Handle connection lifecycle and reconnection:
class StreamingConnection {
  constructor(apiKey, options = {}) {
    this.apiKey = apiKey;
    this.options = {
      maxReconnectAttempts: 10,
      reconnectInterval: 5000,
      heartbeatInterval: 30000,
      ...options
    };
    
    this.reconnectAttempts = 0;
    this.isConnected = false;
    this.subscriptions = new Set();
  }
  
  connect() {
    this.ws = new WebSocket('wss://api.bookovia.com/v1/streaming');
    
    this.ws.onopen = () => {
      this.isConnected = true;
      this.reconnectAttempts = 0;
      
      this.authenticate();
      this.resubscribe();
      this.startHeartbeat();
    };
    
    this.ws.onclose = () => {
      this.isConnected = false;
      this.stopHeartbeat();
      this.attemptReconnect();
    };
    
    this.ws.onerror = (error) => {
      console.error('WebSocket error:', error);
    };
  }
  
  attemptReconnect() {
    if (this.reconnectAttempts < this.options.maxReconnectAttempts) {
      this.reconnectAttempts++;
      
      setTimeout(() => {
        this.connect();
      }, this.options.reconnectInterval * this.reconnectAttempts);
    }
  }
  
  startHeartbeat() {
    this.heartbeatInterval = setInterval(() => {
      if (this.isConnected) {
        this.send({ type: 'ping' });
      }
    }, this.options.heartbeatInterval);
  }
}

Live Location Updates

Location Streaming

Receive real-time GPS position updates:
{
  "type": "location_update",
  "timestamp": "2024-04-13T10:30:15Z",
  "trip_id": "trip_123",
  "vehicle_id": "vehicle_456",
  "driver_id": "driver_789",
  "location": {
    "latitude": 40.7128,
    "longitude": -74.0060,
    "speed": 45.5,
    "heading": 180.0,
    "accuracy": 3.2,
    "altitude": 12.5
  },
  "motion": {
    "acceleration": {
      "x": 0.1,
      "y": -0.2,
      "z": 9.8
    },
    "gyroscope": {
      "x": 0.05,
      "y": -0.03,
      "z": 0.01
    }
  }
}

Location Filtering

Subscribe to specific location updates:
// Filter by geographic area
ws.send(JSON.stringify({
  type: 'subscribe',
  channel: 'locations',
  filters: {
    geographic_bounds: {
      southwest: { lat: 40.7000, lng: -74.0200 },
      northeast: { lat: 40.7300, lng: -73.9800 }
    },
    min_speed: 10, // Only moving vehicles
    accuracy_threshold: 20 // High accuracy only
  }
}));

// Filter by vehicle or driver
ws.send(JSON.stringify({
  type: 'subscribe',
  channel: 'locations',
  filters: {
    vehicle_ids: ['vehicle_456', 'vehicle_789'],
    driver_ids: ['driver_123'],
    trip_status: ['active', 'in_progress']
  }
}));

Batch Location Updates

Receive multiple location points in a single message:
{
  "type": "location_batch",
  "timestamp": "2024-04-13T10:30:15Z",
  "locations": [
    {
      "trip_id": "trip_123",
      "vehicle_id": "vehicle_456",
      "location": {
        "latitude": 40.7128,
        "longitude": -74.0060,
        "timestamp": "2024-04-13T10:30:00Z"
      }
    },
    {
      "trip_id": "trip_456",
      "vehicle_id": "vehicle_789",
      "location": {
        "latitude": 40.7150,
        "longitude": -74.0040,
        "timestamp": "2024-04-13T10:30:10Z"
      }
    }
  ]
}

Safety Event Streaming

Real-time Safety Alerts

Immediate notifications for safety events:
{
  "type": "safety_event",
  "timestamp": "2024-04-13T10:30:45Z",
  "trip_id": "trip_123",
  "vehicle_id": "vehicle_456",
  "driver_id": "driver_789",
  "event": {
    "type": "harsh_braking",
    "severity": "high",
    "details": {
      "deceleration": -5.2,
      "duration_seconds": 2.1,
      "speed_before": 55,
      "speed_after": 25
    },
    "location": {
      "latitude": 40.7128,
      "longitude": -74.0060,
      "address": "123 Main St, New York, NY"
    }
  },
  "risk_assessment": {
    "crash_probability": 0.15,
    "severity_score": 8.2,
    "contributing_factors": ["wet_roads", "heavy_traffic"]
  }
}

Event Filtering and Thresholds

Configure which safety events to receive:
// Subscribe to high-severity events only
ws.send(JSON.stringify({
  type: 'subscribe',
  channel: 'safety_events',
  filters: {
    severity: ['high', 'critical'],
    event_types: ['harsh_braking', 'harsh_acceleration', 'phone_usage'],
    risk_threshold: 0.7,
    notification_priority: 'immediate'
  }
}));

// Custom threshold configuration
ws.send(JSON.stringify({
  type: 'configure_thresholds',
  thresholds: {
    harsh_acceleration: { threshold: 3.5, duration: 2.0 },
    harsh_braking: { threshold: -4.0, duration: 1.5 },
    harsh_cornering: { threshold: 0.6, duration: 3.0 },
    speeding: { over_limit: 15, duration: 30 }
  }
}));

Trip Status Updates

Real-time Trip Events

Monitor trip lifecycle changes:
{
  "type": "trip_update",
  "timestamp": "2024-04-13T10:30:00Z",
  "trip_id": "trip_123",
  "vehicle_id": "vehicle_456",
  "driver_id": "driver_789",
  "event": "trip_started",
  "details": {
    "start_location": {
      "latitude": 40.7128,
      "longitude": -74.0060,
      "address": "123 Warehouse Dr, New York, NY"
    },
    "planned_route": {
      "distance_km": 45.2,
      "estimated_duration_minutes": 67,
      "waypoints": 8
    },
    "driver_info": {
      "name": "John Smith",
      "license_number": "D123456789",
      "safety_score": 87.5
    }
  }
}

Trip Event Types

Available trip status events:
EventDescriptionTiming
trip_startedTrip begins with first location pointReal-time
trip_pausedVehicle stopped for extended periodAfter 5 minutes
trip_resumedMovement detected after pauseImmediate
waypoint_reachedArrival at planned destinationReal-time
geofence_entryVehicle enters defined boundaryImmediate
geofence_exitVehicle leaves defined boundaryImmediate
trip_completedTrip ends with final locationReal-time
trip_cancelledTrip terminated before completionImmediate

Fleet Management Streaming

Multi-Vehicle Monitoring

Track entire fleet in real-time:
// Fleet overview stream
ws.send(JSON.stringify({
  type: 'subscribe',
  channel: 'fleet_overview',
  filters: {
    organization_id: 'org_123',
    include_inactive: false,
    update_frequency: 'high' // Every 10 seconds
  }
}));

// Receive fleet status
{
  "type": "fleet_status",
  "timestamp": "2024-04-13T10:30:00Z",
  "organization_id": "org_123",
  "summary": {
    "total_vehicles": 25,
    "active_trips": 18,
    "idle_vehicles": 7,
    "maintenance_due": 3,
    "safety_alerts": 2
  },
  "vehicles": [
    {
      "vehicle_id": "vehicle_456",
      "status": "active",
      "trip_id": "trip_123",
      "driver_id": "driver_789",
      "last_location": {
        "latitude": 40.7128,
        "longitude": -74.0060,
        "timestamp": "2024-04-13T10:29:45Z"
      },
      "safety_score": 87.5,
      "current_speed": 45,
      "fuel_level": 0.75
    }
  ]
}

Driver Performance Streaming

Real-time driver behavior monitoring:
{
  "type": "driver_performance",
  "timestamp": "2024-04-13T10:30:00Z",
  "driver_id": "driver_789",
  "trip_id": "trip_123",
  "performance": {
    "current_safety_score": 85.2,
    "session_events": {
      "harsh_braking": 2,
      "harsh_acceleration": 1,
      "speeding_incidents": 0,
      "phone_usage": 0
    },
    "efficiency_metrics": {
      "fuel_economy": 8.5,
      "idle_time_percent": 12.3,
      "route_adherence": 0.94
    },
    "trends": {
      "score_change": -2.1,
      "improvement_areas": ["smooth_braking", "acceleration_control"]
    }
  }
}

Custom Event Streams

Defining Custom Events

Create application-specific event streams:
// Register custom event type
ws.send(JSON.stringify({
  type: 'register_custom_event',
  event_name: 'delivery_completed',
  triggers: {
    geofence_entry: 'customer_location',
    stop_duration: 120, // 2 minutes minimum
    confirmation_required: true
  }
}));

// Subscribe to custom events
ws.send(JSON.stringify({
  type: 'subscribe',
  channel: 'custom_events',
  filters: {
    event_names: ['delivery_completed', 'maintenance_alert'],
    priority: ['high', 'critical']
  }
}));

Webhook Integration

Combine streaming with webhooks for redundancy:
{
  "webhook_config": {
    "url": "https://your-app.com/webhooks/bookovia",
    "events": ["safety_events", "trip_updates"],
    "backup_for_streaming": true,
    "retry_policy": {
      "max_attempts": 3,
      "backoff_multiplier": 2,
      "initial_delay_seconds": 1
    },
    "authentication": {
      "type": "bearer_token",
      "token": "your_webhook_secret"
    }
  }
}

Performance Optimization

Connection Scaling

Optimize for high-volume streaming:
class StreamingManager {
  constructor() {
    this.connections = new Map();
    this.connectionPool = [];
    this.maxConnections = 10;
  }
  
  // Distribute subscriptions across connections
  subscribe(channel, filters = {}) {
    const connection = this.getLeastLoadedConnection();
    connection.subscribe(channel, filters);
  }
  
  getLeastLoadedConnection() {
    return this.connections
      .values()
      .reduce((min, conn) => 
        conn.subscriptionCount < min.subscriptionCount ? conn : min
      );
  }
  
  // Implement connection pooling
  createConnection() {
    if (this.connectionPool.length > 0) {
      return this.connectionPool.pop();
    }
    
    return new StreamingConnection(this.apiKey, {
      bufferSize: 1000,
      compressionEnabled: true,
      heartbeatInterval: 30000
    });
  }
}

Data Compression

Enable compression for high-frequency updates:
// Enable compression at connection level
ws.send(JSON.stringify({
  type: 'configure',
  options: {
    compression: 'gzip',
    buffer_size: 1000,
    batch_interval: 100, // milliseconds
    deduplicate: true
  }
}));

Message Batching

Batch updates for efficiency:
{
  "type": "batch_update",
  "timestamp": "2024-04-13T10:30:00Z",
  "batch_id": "batch_456",
  "messages": [
    {
      "type": "location_update",
      "trip_id": "trip_123",
      "location": { "latitude": 40.7128, "longitude": -74.0060 }
    },
    {
      "type": "location_update", 
      "trip_id": "trip_456",
      "location": { "latitude": 40.7150, "longitude": -74.0040 }
    }
  ]
}

Security and Authentication

Secure Connections

All streaming connections use secure protocols:
  • TLS 1.3 Encryption - End-to-end encryption
  • API Key Authentication - Secure key-based access
  • Connection Limits - Rate limiting and abuse prevention
  • Origin Validation - Allowed domain restrictions

Authentication Flow

// Authenticate streaming connection
const authenticate = () => {
  ws.send(JSON.stringify({
    type: 'auth',
    api_key: 'bkv_live_your_api_key',
    timestamp: Date.now(),
    signature: generateSignature(apiKey, timestamp)
  }));
};

// Generate HMAC signature for added security
const generateSignature = (apiKey, timestamp) => {
  const payload = `${apiKey}:${timestamp}`;
  return crypto.createHmac('sha256', apiKey).update(payload).digest('hex');
};

Access Control

Fine-grained permissions for streaming data:
{
  "permissions": {
    "channels": {
      "locations": "read",
      "safety_events": "read", 
      "trip_updates": "read",
      "fleet_overview": "admin_only"
    },
    "filters": {
      "organization_scope": true,
      "vehicle_restrictions": ["vehicle_456", "vehicle_789"],
      "geographic_bounds": {
        "enabled": true,
        "southwest": { "lat": 40.7000, "lng": -74.0200 },
        "northeast": { "lat": 40.7300, "lng": -73.9800 }
      }
    }
  }
}

Error Handling

Connection Errors

Handle various connection failure scenarios:
class RobustStreamingClient {
  handleError(error) {
    switch (error.type) {
      case 'connection_timeout':
        this.reconnect({ immediate: true });
        break;
        
      case 'authentication_failed':
        this.refreshApiKey().then(() => this.reconnect());
        break;
        
      case 'rate_limit_exceeded':
        this.backoffAndReconnect(error.retryAfter);
        break;
        
      case 'invalid_subscription':
        this.revalidateSubscriptions();
        break;
        
      default:
        this.log('Unhandled error:', error);
        this.reconnect({ delay: 5000 });
    }
  }
  
  backoffAndReconnect(retryAfter) {
    const delay = retryAfter || (Math.pow(2, this.reconnectAttempts) * 1000);
    
    setTimeout(() => {
      this.reconnect();
    }, Math.min(delay, 30000)); // Max 30 second delay
  }
}

Message Validation

Validate incoming streaming data:
const validateMessage = (message) => {
  try {
    const data = JSON.parse(message);
    
    // Validate message structure
    if (!data.type || !data.timestamp) {
      throw new Error('Invalid message format');
    }
    
    // Validate timestamp freshness
    const messageAge = Date.now() - new Date(data.timestamp).getTime();
    if (messageAge > 60000) { // 1 minute threshold
      console.warn('Stale message received:', messageAge);
    }
    
    // Type-specific validation
    switch (data.type) {
      case 'location_update':
        validateLocationData(data.location);
        break;
      case 'safety_event':
        validateSafetyEvent(data.event);
        break;
    }
    
    return data;
  } catch (error) {
    console.error('Message validation failed:', error);
    return null;
  }
};

Integration Examples

Real-time Dashboard

Live fleet monitoring dashboard:
import { useStreamingData } from '@bookovia/react-sdk';

const FleetDashboard = () => {
  const { 
    vehicles, 
    safetyEvents, 
    connectionStatus 
  } = useStreamingData({
    channels: ['locations', 'safety_events', 'fleet_overview'],
    filters: {
      organization_id: 'org_123'
    }
  });
  
  return (
    <div className="dashboard">
      <ConnectionIndicator status={connectionStatus} />
      
      <FleetMap vehicles={vehicles} />
      
      <SafetyAlerts events={safetyEvents} />
      
      <VehicleList 
        vehicles={vehicles}
        onVehicleSelect={(id) => focusVehicle(id)}
      />
    </div>
  );
};

Mobile App Integration

React Native real-time tracking:
import { useEffect } from 'react';
import { useStreamingConnection } from '@bookovia/react-native-sdk';

const LiveTracking = ({ tripId }) => {
  const { connect, subscribe, data, isConnected } = useStreamingConnection();
  
  useEffect(() => {
    connect('bkv_live_your_api_key');
    
    subscribe('locations', {
      trip_ids: [tripId],
      update_frequency: 'high'
    });
    
    subscribe('safety_events', {
      trip_ids: [tripId],
      severity: ['medium', 'high', 'critical']
    });
  }, [tripId]);
  
  return (
    <View>
      <StatusIndicator connected={isConnected} />
      <LiveMap locationData={data.locations} />
      <SafetyAlerts events={data.safetyEvents} />
    </View>
  );
};

WebSocket Proxy Server

Node.js server for WebSocket management:
const WebSocket = require('ws');
const express = require('express');

class StreamingProxy {
  constructor() {
    this.clients = new Map();
    this.bookovia = new WebSocket('wss://api.bookovia.com/v1/streaming');
  }
  
  start(port = 8080) {
    const server = express().listen(port);
    this.wss = new WebSocket.Server({ server });
    
    this.wss.on('connection', (ws, req) => {
      const clientId = this.generateClientId();
      this.clients.set(clientId, ws);
      
      ws.on('message', (message) => {
        this.handleClientMessage(clientId, message);
      });
      
      ws.on('close', () => {
        this.clients.delete(clientId);
      });
    });
    
    // Forward Bookovia messages to clients
    this.bookovia.on('message', (data) => {
      this.broadcast(data);
    });
  }
  
  broadcast(data) {
    this.clients.forEach((ws) => {
      if (ws.readyState === WebSocket.OPEN) {
        ws.send(data);
      }
    });
  }
}

Best Practices

Connection Management

  • Implement exponential backoff for reconnection attempts
  • Maximum reconnection delay of 30 seconds
  • Track connection health with heartbeat messages
  • Gracefully handle network transitions
  • Subscribe only to necessary data streams
  • Use specific filters to reduce bandwidth
  • Unsubscribe from unused channels
  • Batch subscription changes when possible
  • Validate all incoming messages
  • Handle duplicate messages gracefully
  • Implement message queuing for high-volume streams
  • Process messages asynchronously to avoid blocking

Performance Optimization

  • Enable compression for high-frequency updates
  • Use message batching for efficiency
  • Filter data at the source, not client-side
  • Monitor connection bandwidth usage
  • Implement circular buffers for location history
  • Clean up old event data regularly
  • Use weak references for temporary subscriptions
  • Monitor memory usage in long-running connections
  • Reduce update frequency when app is backgrounded
  • Use push notifications for critical events
  • Implement intelligent wake-up strategies
  • Balance real-time needs with battery life

Use Cases

Emergency Response

Real-time safety monitoring for emergency situations:
// Critical safety event monitoring
ws.send(JSON.stringify({
  type: 'subscribe',
  channel: 'safety_events',
  filters: {
    severity: ['critical'],
    event_types: ['crash_detection', 'panic_button'],
    immediate_notification: true
  }
}));

// Handle emergency events
ws.onmessage = (event) => {
  const data = JSON.parse(event.data);
  
  if (data.type === 'safety_event' && data.event.severity === 'critical') {
    // Immediate emergency response
    dispatchEmergencyServices({
      location: data.location,
      vehicle: data.vehicle_id,
      driver: data.driver_id,
      incident_type: data.event.type
    });
  }
};

Fleet Optimization

Real-time route optimization and dispatch:
// Monitor fleet capacity and location
const optimizeDispatch = (newOrder) => {
  const availableVehicles = vehicles.filter(v => 
    v.status === 'available' && 
    v.capacity >= newOrder.size
  );
  
  const optimalVehicle = availableVehicles
    .sort((a, b) => 
      calculateDistance(a.location, newOrder.pickup) - 
      calculateDistance(b.location, newOrder.pickup)
    )[0];
    
  if (optimalVehicle) {
    assignOrder(optimalVehicle.id, newOrder);
  }
};

Compliance Monitoring

Real-time regulatory compliance tracking:
// Monitor hours of service compliance
ws.send(JSON.stringify({
  type: 'subscribe',
  channel: 'driver_compliance',
  filters: {
    regulation: 'DOT_FMCSA',
    warnings: ['hours_approaching', 'rest_required'],
    jurisdiction: 'US'
  }
}));

Next Steps

Safety Analytics

Learn how real-time data powers safety scoring and risk assessment

Trip Management

Understand trip lifecycle and real-time status updates

Streaming API Reference

Explore detailed API documentation for streaming endpoints

Mobile Integration

See how to implement streaming in mobile applications

Ready to implement real-time streaming? Check out our streaming API reference for detailed connection examples.