---
updatedAt: 2026-05-21T09:47:24.000Z
agentTools:
  projectIndex: https://docs.damoov.com/llms.txt
---

# 🌐 WebSocket - Live Tracking

wss://portal-apis.telematicssdk.com/realtime/api/v1/ws/realtime.

## WebSocket Real-Time Streaming

### Connection URL

```
wss://portal-apis.telematicssdk.com/realtime/api/v1/ws/realtime
```

### Authentication Flow

All WebSocket connections require JWT authentication. The server provides automatic subscription to your instance data after successful authentication:

```javascript
const ws = new WebSocket('wss://portal-apis.telematicssdk.com/realtime/api/v1/ws/realtime');

ws.onopen = () => {
    // Authenticate with JWT and preferences
    ws.send(JSON.stringify({
        type: 'authenticate',
        access_token: 'your_jwt_token',
        instance_id: 'your_instance_id',
        client_id: 'your_client_id',           // Optional client identifier
        device_token: 'optional_device_token', // For single-device mode
        units: 'metric',                       // 'metric' or 'imperial'
        timezone: 'America/New_York',          // Timezone for timestamps
        date_format: 'iso'                     // 'unix', 'iso', or 'localized'
    }));
};

ws.onmessage = (event) => {
    const data = JSON.parse(event.data);
    
    if (data.type === 'authenticated') {
        console.log('Authentication successful');
        // Wait for welcome message - subscription is automatic
    }
    
    if (data.type === 'welcome') {
        console.log('WebSocket Manager ready');
        console.log('Connection ID:', data.connection_id);
        console.log('Server time:', data.server_time);
        console.log('Instance ID:', data.instance_id);
        // Server will automatically subscribe you to your instance data
    }
    
    if (data.type === 'subscribed') {
        console.log('Automatically subscribed to:', data.topic);
        // Now you'll receive device updates for your instance
    }
    
    if (data.type === 'device_update') {
        // Handle real-time device data
        console.log('Device update:', data.device_token, data.position);
    }
    
    if (data.type === 'ping') {
        // Respond to server heartbeat (every 30 seconds)
        ws.send(JSON.stringify({
            type: 'pong',
            timestamp: Date.now()
        }));
    }
    
    if (data.type === 'error') {
        console.error('WebSocket error:', data.code, data.message);
        // Handle authentication errors, access denied, etc.
    }
};

ws.onerror = (error) => {
    console.error('WebSocket connection error:', error);
};

ws.onclose = (event) => {
    console.log('WebSocket closed:', event.code, event.reason);
    // Implement reconnection logic if needed
};
```
```python
import websocket
import json
import threading
from datetime import datetime

def create_websocket_connection(jwt_token, instance_id):
    """Create WebSocket connection with JWT authentication"""
    
    def on_open(ws):
        print("WebSocket connected")
        # Authenticate with JWT and preferences
        auth_message = {
            'type': 'authenticate',
            'access_token': jwt_token,
            'instance_id': instance_id,
            'client_id': f'python_client_{int(datetime.now().timestamp())}',  # Optional client identifier
            'device_token': None,           # Optional - for single-device mode
            'units': 'metric',              # 'metric' or 'imperial'
            'timezone': 'America/New_York', # Timezone for timestamps
            'date_format': 'iso'            # 'unix', 'iso', or 'localized'
        }
        ws.send(json.dumps(auth_message))
    
    def on_message(ws, message):
        try:
            data = json.loads(message)
            
            if data.get('type') == 'authenticated':
                print('Authentication successful')
                # Wait for welcome message - subscription is automatic
            
            elif data.get('type') == 'welcome':
                print('WebSocket Manager ready')
                print(f"Connection ID: {data.get('connection_id')}")
                print(f"Server time: {data.get('server_time')}")
                print(f"Instance ID: {data.get('instance_id')}")
                # Server will automatically subscribe you to your instance data
            
            elif data.get('type') == 'subscribed':
                print(f"Automatically subscribed to: {data.get('topic')}")
                # Now you'll receive device updates for your instance
            
            elif data.get('type') == 'device_update':
                # Handle real-time device data
                print(f"Device update: {data.get('device_token')}, {data.get('position')}")
            
            elif data.get('type') == 'ping':
                # Respond to server heartbeat (every 30 seconds)
                pong_message = {
                    'type': 'pong',
                    'timestamp': int(datetime.now().timestamp() * 1000)
                }
                ws.send(json.dumps(pong_message))
            
            elif data.get('type') == 'error':
                print(f"WebSocket error: {data.get('code')} {data.get('message')}")
                # Handle authentication errors, access denied, etc.
                
        except json.JSONDecodeError as e:
            print(f"Failed to parse JSON message: {e}")
        except Exception as e:
            print(f"Error processing message: {e}")
    
    def on_error(ws, error):
        print(f"WebSocket connection error: {error}")
    
    def on_close(ws, close_status_code, close_msg):
        print(f"WebSocket closed: {close_status_code} - {close_msg}")
        # Implement reconnection logic if needed
    
    # Create WebSocket connection
    ws = websocket.WebSocketApp(
        'wss://portal-apis.telematicssdk.com/realtime/api/v1/ws/realtime',
        on_open=on_open,
        on_message=on_message,
        on_error=on_error,
        on_close=on_close
    )
    
    return ws

# Usage example
jwt_token = 'your_jwt_token'
instance_id = 'your_instance_id'

# Create and start WebSocket connection
ws = create_websocket_connection(jwt_token, instance_id)

# Run WebSocket in a separate thread
ws_thread = threading.Thread(target=ws.run_forever)
ws_thread.daemon = True
ws_thread.start()

print("WebSocket connection started. Press Ctrl+C to stop...")

try:
    # Keep the main thread alive
    ws_thread.join()
except KeyboardInterrupt:
    print("Stopping WebSocket connection...")
    ws.close()
```

<br />

### Message Format

Real-time device updates are sent in the following format with raw sensor data for client-side conversion:

```json
{
  "type": "device_update",
  "device_token": "e4855fba-0d7e-4dbd-baad-aae9d0b90c15",
  "track_token": "9F6A4F03-300B-4C14-8847-DAC537E8D70C",
  "position": {
    "Latitude": 40.7128,
    "Longitude": -74.0060,
    "Speed": 7.85,                     // Raw m/s from sensor
    "Accuracy": 5.0,                   // Raw meters from sensor
    "Timestamp": 1640995200,           // Unix timestamp (or formatted based on date_format)
    "Heading": 180.0
  }
}
```

**Important Notes:**

* **Speed**: Always in m/s (raw sensor data) - convert client-side to km/h (×3.6) or mph (×2.236936)
* **Distance/Accuracy**: Always in meters (raw sensor data) - convert to feet (×3.28084) if needed
* **Timestamps**: Format depends on `date_format` parameter in authentication
* **Coordinates**: Always decimal degrees (no conversion needed)
* **Real-time Data**: All WebSocket data is live (not cached) unless specified otherwise

<br />

### Error Codes

| Code | Description            | Action Required                      |
| ---- | ---------------------- | ------------------------------------ |
| 400  | Invalid JSON message   | Fix message format                   |
| 401  | JWT Token Expired      | Refresh token and reconnect          |
| 403  | Access Denied          | Check token permissions for instance |
| 404  | Instance Not Found     | Verify instance ID                   |
| 408  | Authentication Timeout | Retry connection                     |
| 500  | Internal Server Error  | Contact support                      |
| 503  | Service Unavailable    | Retry with backoff                   |

***