Getting Started

This guide will help you integrate the Vitals SDK into your web application and start measuring wellness indicators from camera video streams.

Installation

Install the Vitals SDK package using npm or yarn:

bash
# Using npm
npm install @vitals/sdk

# Using yarn
yarn add @vitals/sdk

Basic Setup

Import and initialize the SDK in your application:

javascript
import { VitalsSDK } from '@vitals/sdk';

// Initialize the SDK with configuration
const vitals = new VitalsSDK({
  apiEndpoint: 'wss://api.vitals.io/stream',
  apiKey: 'your-api-key-here',
  config: {
    windowDuration: 45, // seconds
    enableVideoPreview: true,
    qualityThreshold: 0.7
  }
});

Camera Integration

Set up the camera stream and start capturing video:

javascript
// Get camera permission and start video stream
async function startCamera() {
  try {
    const stream = await navigator.mediaDevices.getUserMedia({
      video: {
        width: { ideal: 1280 },
        height: { ideal: 720 },
        facingMode: 'user'
      }
    });

    const videoElement = document.getElementById('video-preview');
    videoElement.srcObject = stream;
    await videoElement.play();

    // Connect stream to Vitals SDK
    await vitals.connect(stream);
    
    console.log('Camera connected successfully');
  } catch (error) {
    console.error('Camera access denied:', error);
  }
}
Tip: Ensure your application is served over HTTPS to access the camera. Camera access is restricted to secure contexts for security reasons.

Session Lifecycle

The Vitals SDK follows a simple session lifecycle:

javascript
// 1. Start a new measurement session
const session = await vitals.startSession({
  userId: 'user-123',
  sessionId: 'session-' + Date.now()
});

// 2. Listen for real-time measurements
session.on('measurement', (data) => {
  console.log('Real-time vitals:', data);
  // data includes: heartRate, hrv, respiratoryRate, etc.
});

// 3. Listen for window results (aggregated)
session.on('windowResult', (windowData) => {
  console.log('Window result:', windowData);
  // windowData includes averaged vitals over the window period
});

// 4. Stop the session when done
await session.stop();

WebSocket Connection

The SDK uses WebSocket for real-time communication. Here's a direct WebSocket example:

javascript
// Direct WebSocket connection
const ws = new WebSocket('wss://api.vitals.io/stream?apiKey=your-key');

ws.onopen = () => {
  console.log('WebSocket connected');
  
  // Send configuration
  ws.send(JSON.stringify({
    type: 'config',
    data: {
      windowDuration: 45,
      qualityThreshold: 0.7
    }
  }));
};

ws.onmessage = (event) => {
  const message = JSON.parse(event.data);
  
  switch (message.type) {
    case 'measurement':
      handleMeasurement(message.data);
      break;
    case 'windowResult':
      handleWindowResult(message.data);
      break;
    case 'error':
      handleError(message.data);
      break;
  }
};

function handleMeasurement(data) {
  // Process real-time measurements
  document.getElementById('heartRate').textContent = 
    data.heartRate.toFixed(1) + ' BPM';
}

function handleWindowResult(data) {
  // Process window-averaged results
  console.log('Window quality:', data.quality);
  console.log('Averaged HR:', data.averagedHeartRate);
}

Handling Events

The SDK emits various events throughout the measurement process:

javascript
// Event handlers for different states
session.on('connected', () => {
  console.log('Session connected');
  updateStatus('Connected');
});

session.on('measuring', () => {
  console.log('Measurement in progress');
  updateStatus('Measuring...');
});

session.on('qualityUpdate', (quality) => {
  console.log('Signal quality:', quality);
  updateQualityIndicator(quality);
});

session.on('error', (error) => {
  console.error('Session error:', error);
  showError(error.message);
});

session.on('completed', (result) => {
  console.log('Session completed:', result);
  displayFinalResults(result);
});

Complete Example

Here's a complete working example:

javascript
import { VitalsSDK } from '@vitals/sdk';

class VitalsApp {
  constructor() {
    this.vitals = null;
    this.session = null;
  }

  async initialize() {
    this.vitals = new VitalsSDK({
      apiEndpoint: 'wss://api.vitals.io/stream',
      apiKey: process.env.VITALS_API_KEY
    });

    // Setup event listeners
    this.vitals.on('connected', this.handleConnected.bind(this));
    this.vitals.on('measurement', this.handleMeasurement.bind(this));
    this.vitals.on('windowResult', this.handleWindowResult.bind(this));
    this.vitals.on('error', this.handleError.bind(this));
  }

  async start() {
    try {
      // Get camera stream
      const stream = await navigator.mediaDevices.getUserMedia({
        video: { width: 1280, height: 720 }
      });

      // Connect to SDK
      await this.vitals.connect(stream);

      // Start session
      this.session = await this.vitals.startSession({
        userId: 'demo-user'
      });

      console.log('Vitals measurement started');
    } catch (error) {
      console.error('Failed to start:', error);
    }
  }

  handleConnected() {
    console.log('Connected to Vitals SDK');
  }

  handleMeasurement(data) {
    // Update UI with real-time data
    this.updateUI(data);
  }

  handleWindowResult(data) {
    // Process window-averaged results
    console.log('Window result:', data);
  }

  handleError(error) {
    console.error('Error:', error);
  }

  stop() {
    if (this.session) {
      this.session.stop();
    }
  }
}

// Usage
const app = new VitalsApp();
await app.initialize();
await app.start();

Configuration Options

Customize the SDK behavior with configuration options:

javascript
const config = {
  // Window duration in seconds (default: 45)
  windowDuration: 45,
  
  // Quality threshold (0.0 - 1.0)
  qualityThreshold: 0.7,
  
  // Enable video preview
  enableVideoPreview: true,
  
  // ROI detection settings
  roi: {
    region: 'forehead',
    padding: 20
  },
  
  // Output format
  outputFormat: {
    includeRawSignal: false,
    includeTimestamp: true,
    includeConfidence: true
  },
  
  // Debug mode
  debug: false
};

const vitals = new VitalsSDK({ config });
Important: Results are AI-estimated wellness indicators and are not a medical diagnosis. Always display appropriate disclaimers in your application and consult healthcare professionals for medical advice.

Next Steps