Skip to content

WebSocket API Specification

Marc Sanchis edited this page Jun 8, 2025 · 1 revision

WebSocket API Specification

This document defines the complete WebSocket API used for communication between the backend and frontend applications (control-station, ethernet-view).

Connection Details

Endpoint: ws://localhost:8080/ws (configurable in backend)
Protocol: WebSocket over HTTP
Content-Type: application/json

Message Format

All WebSocket messages follow a consistent structure:

{
    "topic": "string",
    "payload": {}
}
  • topic: String identifying the message type and routing
  • payload: Object containing topic-specific data

Message Topics

Data Topics

data/update

Direction: Backend → Frontend
Purpose: Real-time measurement data updates

{
    "topic": "data/update",
    "payload": {
        "board_id": 0,
        "packet_id": 211,
        "packet_name": "vcu_regulator_packet",
        "timestamp": "2024-01-15T10:30:45.123Z",
        "measurements": {
            "valve_state": {
                "value": "open",
                "type": "enum",
                "enabled": true
            },
            "reference_pressure": {
                "value": 8.5,
                "type": "float32", 
                "enabled": true,
                "units": "bar"
            },
            "actual_pressure": {
                "value": 8.3,
                "type": "float32",
                "enabled": true, 
                "units": "bar"
            }
        }
    }
}

data/push

Direction: Backend → Frontend
Purpose: Batch data updates for chart displays

{
    "topic": "data/push", 
    "payload": {
        "board_id": 0,
        "measurements": [
            {
                "name": "brake_pressure",
                "value": 85.2,
                "timestamp": "2024-01-15T10:30:45.123Z"
            }
        ]
    }
}

Connection Topics

connection/update

Direction: Backend → Frontend
Purpose: Board connection status updates

{
    "topic": "connection/update",
    "payload": {
        "board_id": 0,
        "board_name": "VCU",
        "ip_address": "127.0.0.6",
        "connected": true,
        "last_seen": "2024-01-15T10:30:45.123Z",
        "packets_received": 1250,
        "bytes_received": 125000,
        "connection_quality": "excellent"
    }
}

Connection Quality Values:

  • excellent: < 1% packet loss, < 10ms latency
  • good: < 5% packet loss, < 50ms latency
  • poor: > 5% packet loss or > 50ms latency
  • unknown: Insufficient data for assessment

connection/push

Direction: Backend → Frontend
Purpose: Initial connection state when client connects

{
    "topic": "connection/push",
    "payload": {
        "connections": [
            {
                "board_id": 0,
                "board_name": "VCU", 
                "connected": true,
                "last_seen": "2024-01-15T10:30:45.123Z"
            }
        ]
    }
}

Order Topics

order/send

Direction: Frontend → Backend
Purpose: Send command to vehicle board

{
    "topic": "order/send",
    "payload": {
        "board_id": 0,
        "order_name": "brake_engage",
        "parameters": {
            "target_pressure": 85.0,
            "engage_time": 2000
        }
    }
}

order/state

Direction: Backend → Frontend
Purpose: Order execution status updates

{
    "topic": "order/state",
    "payload": {
        "board_id": 0,
        "order_name": "brake_engage",
        "status": "completed",
        "timestamp": "2024-01-15T10:30:45.123Z",
        "parameters": {
            "target_pressure": 85.0
        },
        "execution_time_ms": 1250
    }
}

Status Values:

  • pending: Order queued for transmission
  • executing: Order sent to vehicle, awaiting completion
  • completed: Order successfully executed
  • failed: Order execution failed
  • timeout: Order execution timed out

Protection Topics

protection/alert

Direction: Backend → Frontend
Purpose: Safety alerts and fault notifications

{
    "topic": "protection/alert",
    "payload": {
        "board_id": 0,
        "packet_id": 2,
        "severity": "fault",
        "protection_type": "above",
        "measurement_name": "brake_pressure",
        "current_value": 105.0,
        "threshold_value": 100.0,
        "message": "Brake pressure above safe limit",
        "timestamp": "2024-01-15T10:30:45.123Z",
        "acknowledged": false,
        "protection_id": "brake_pressure_high"
    }
}

Severity Levels:

  • fault: Critical condition requiring immediate attention
  • warning: Concerning condition requiring monitoring
  • ok: Recovery from previous fault/warning

Protection Types:

  • above: Value above threshold
  • below: Value below threshold
  • outofbounds: Value outside acceptable range
  • equals: Value equals specific condition
  • notequals: Value doesn't equal expected condition
  • errorhandler: System error condition
  • timeaccumulation: Time-based accumulation fault

Logger Topics

logger/enable

Direction: Frontend → Backend
Purpose: Start data logging

{
    "topic": "logger/enable",
    "payload": {
        "log_type": "data",
        "measurements": ["brake_pressure", "valve_state"],
        "log_rate": 100,
        "format": "csv",
        "filename": "run_001_data.csv"
    }
}

Log Types:

  • data: Measurement data logging
  • protection: Protection event logging
  • state: State space logging
  • order: Command execution logging

Formats:

  • csv: Comma-separated values
  • json: JSON format with timestamps

logger/disable

Direction: Frontend → Backend
Purpose: Stop data logging

{
    "topic": "logger/disable", 
    "payload": {
        "log_type": "data"
    }
}

Message Topics

message/update

Direction: Backend → Frontend
Purpose: System messages and notifications

{
    "topic": "message/update",
    "payload": {
        "id": "unique_message_id",
        "level": "info",
        "source": "backend",
        "title": "Connection Established",
        "message": "Successfully connected to VCU board",
        "timestamp": "2024-01-15T10:30:45.123Z",
        "board_id": 0,
        "auto_dismiss": true,
        "dismiss_timeout": 5000
    }
}

Message Levels:

  • info: Informational messages
  • warning: Warning conditions
  • error: Error conditions requiring attention

Message Sources:

  • backend: Backend system messages
  • vehicle: Messages from vehicle systems
  • system: Operating system messages

BLCU Topics (Bootloader)

blcu/upload

Direction: Frontend → Backend
Purpose: Upload firmware to vehicle board

{
    "topic": "blcu/upload",
    "payload": {
        "board_id": 0,
        "filename": "firmware_v2.1.bin",
        "file_data": "base64_encoded_data",
        "checksum": "sha256_hash"
    }
}

blcu/download

Direction: Frontend → Backend
Purpose: Download file from vehicle board

{
    "topic": "blcu/download",
    "payload": {
        "board_id": 0,
        "filename": "config.json",
        "destination": "local_config.json"
    }
}

blcu/register

Direction: Backend → Frontend
Purpose: BLCU operation status updates

{
    "topic": "blcu/register",
    "payload": {
        "board_id": 0,
        "operation": "upload",
        "status": "in_progress",
        "progress": 0.65,
        "bytes_transferred": 340000,
        "total_bytes": 524288,
        "estimated_time_remaining": 45,
        "error_message": null
    }
}

Operation Types:

  • upload: Firmware/file upload to vehicle
  • download: File download from vehicle

Status Values:

  • pending: Operation queued
  • in_progress: Operation executing
  • completed: Operation successful
  • failed: Operation failed

Error Handling

Connection Errors

{
    "topic": "error",
    "payload": {
        "error": "connection_lost",
        "message": "WebSocket connection lost",
        "timestamp": "2024-01-15T10:30:45.123Z",
        "reconnect_in": 5000
    }
}

Protocol Errors

{
    "topic": "error",
    "payload": {
        "error": "invalid_message_format",
        "details": "Missing required field: topic",
        "original_message": {},
        "timestamp": "2024-01-15T10:30:45.123Z"
    }
}

Validation Errors

{
    "topic": "error",
    "payload": {
        "error": "validation_failed",
        "field": "board_id",
        "message": "Board ID must be a valid integer",
        "received_value": "invalid_id"
    }
}

Performance and Rate Limiting

Message Rate Limits

  • Data Updates: Max 100 Hz per measurement
  • Order Commands: Max 10 per second per client
  • Logger Operations: Max 1 per second
  • BLCU Operations: Max 1 concurrent operation per board

Connection Limits

  • Maximum Clients: 50 concurrent connections
  • Message Buffer: 1000 messages per client
  • Timeout: 30 seconds idle timeout

Performance Characteristics

  • Latency: < 10ms for local connections
  • Throughput: 1000+ messages/second per connection
  • Memory: ~1MB per active connection

Client Implementation

TypeScript Integration

interface WebSocketMessage {
    topic: string;
    payload: any;
}

interface DataUpdatePayload {
    board_id: number;
    packet_id: number;
    packet_name: string;
    timestamp: string;
    measurements: Record<string, MeasurementValue>;
}

interface MeasurementValue {
    value: number | string | boolean;
    type: DataType;
    enabled: boolean;
    units?: string;
}

type DataType = 'uint8' | 'uint16' | 'uint32' | 'uint64' | 
               'int8' | 'int16' | 'int32' | 'int64' | 
               'float32' | 'float64' | 'bool' | 'enum';

Connection Management

class WebSocketClient {
    private ws: WebSocket;
    private reconnectDelay = 1000;
    private maxReconnectDelay = 30000;
    
    connect() {
        this.ws = new WebSocket('ws://localhost:8080/ws');
        
        this.ws.onopen = () => {
            console.log('Connected to backend');
            this.reconnectDelay = 1000;
        };
        
        this.ws.onmessage = (event) => {
            const message: WebSocketMessage = JSON.parse(event.data);
            this.handleMessage(message);
        };
        
        this.ws.onclose = () => {
            console.log('Connection lost, reconnecting...');
            setTimeout(() => this.connect(), this.reconnectDelay);
            this.reconnectDelay = Math.min(this.reconnectDelay * 2, this.maxReconnectDelay);
        };
    }
    
    send(topic: string, payload: any) {
        if (this.ws.readyState === WebSocket.OPEN) {
            this.ws.send(JSON.stringify({ topic, payload }));
        }
    }
}

Security Considerations

Current Implementation

  • No Authentication: Assumes trusted network environment
  • Input Validation: All messages validated against schemas
  • Rate Limiting: Prevents abuse and resource exhaustion
  • Origin Checking: WebSocket origin validation recommended

Production Recommendations

  • TLS Encryption: Use WSS for secure connections
  • Authentication Tokens: JWT-based client authentication
  • Role-Based Access: Different permissions for operators vs viewers
  • Audit Logging: Track all command executions

For implementation examples and integration details, see the frontend source code in common-front/src/wsHandler/ and control-station/src/services/.

Clone this wiki locally