# Lovense Device Protocol

> Integration documentation for Lovense interactive devices.

**API Base URL:** `https://api.lovense.com/api/lan/v2` **Authentication:** API
Key + 24-hour Token

---

## Table of Contents

1. [Overview](#overview)
2. [Authentication](#authentication)
3. [Device Connection](#device-connection)
4. [Commands](#commands)
5. [Patterns](#patterns)
6. [Events](#events)
7. [Error Handling](#error-handling)

---

## Overview

Lovense devices are industry-leading interactive toys that can be controlled via
their cloud API or local network connection. The Aphrodite platform integrates
with Lovense to enable tip-triggered vibrations and creator-controlled patterns.

### Supported Devices

| Device | Type       | Features              |
| ------ | ---------- | --------------------- |
| Lush 3 | Vibrator   | Vibrate, patterns     |
| Nora   | Vibrator   | Vibrate, rotate       |
| Max 2  | Stroker    | Vibrate, air pump     |
| Domi 2 | Wand       | Vibrate, patterns     |
| Hush 2 | Plug       | Vibrate               |
| Edge 2 | Prostate   | Vibrate (dual motors) |
| Ferri  | Panty      | Vibrate, magnetic     |
| Osci 2 | Oscillator | Oscillate             |
| Dolce  | Couples    | Dual vibrators        |

---

## Authentication

### Get API Token

Request a temporary authentication token (valid for 24 hours).

```http
POST https://api.lovense.com/api/lan/v2/auth
Content-Type: application/json

{
  "apiKey": "<lovense_api_key>",
  "uid": "user_abc123"
}
```

**Response:**

```json
{
  "code": 0,
  "message": "Success",
  "data": {
    "authToken": "abc123xyz...",
    "expiresAt": "2026-01-19T12:00:00.000Z"
  }
}
```

### Refresh Token

```typescript
// Aphrodite implementation
class LovenseService {
  private async refreshToken(): Promise<string> {
    const response = await fetch('https://api.lovense.com/api/lan/v2/auth', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        apiKey: this.apiKey,
        uid: this.userId,
      }),
    });

    const data = await response.json();
    this.authToken = data.data.authToken;
    this.tokenExpiresAt = new Date(data.data.expiresAt);

    return this.authToken;
  }
}
```

---

## Device Connection

### Pair Device

Initiate device pairing via QR code or pairing code.

```http
POST https://api.lovense.com/api/lan/v2/pair
Authorization: Bearer <auth_token>
Content-Type: application/json

{
  "pairingCode": "ABC123"
}
```

**Response:**

```json
{
  "code": 0,
  "message": "Success",
  "data": {
    "deviceId": "dev_lush3_abc123",
    "deviceName": "Lush 3",
    "deviceType": "lush3",
    "firmware": "4.0.1",
    "battery": 85,
    "connected": true
  }
}
```

### Get Connected Devices

```http
GET https://api.lovense.com/api/lan/v2/devices
Authorization: Bearer <auth_token>
```

**Response:**

```json
{
  "code": 0,
  "data": {
    "devices": [
      {
        "deviceId": "dev_lush3_abc123",
        "deviceName": "Lush 3",
        "deviceType": "lush3",
        "status": "connected",
        "battery": 85,
        "firmware": "4.0.1"
      }
    ]
  }
}
```

### Disconnect Device

```http
POST https://api.lovense.com/api/lan/v2/disconnect
Authorization: Bearer <auth_token>
Content-Type: application/json

{
  "deviceId": "dev_lush3_abc123"
}
```

---

## Commands

### Basic Vibration

Set vibration intensity (0-20 scale).

```http
POST https://api.lovense.com/api/lan/v2/command
Authorization: Bearer <auth_token>
Content-Type: application/json

{
  "deviceId": "dev_lush3_abc123",
  "command": "Function",
  "action": "Vibrate",
  "intensity": 10,
  "duration": 0
}
```

**Parameters:**

| Parameter   | Type   | Range | Description                           |
| ----------- | ------ | ----- | ------------------------------------- |
| `intensity` | number | 0-20  | Vibration strength                    |
| `duration`  | number | 0-∞   | Duration in seconds (0=until stopped) |

**Response:**

```json
{
  "code": 0,
  "message": "Success"
}
```

### Stop Vibration

```http
POST https://api.lovense.com/api/lan/v2/command
Authorization: Bearer <auth_token>
Content-Type: application/json

{
  "deviceId": "dev_lush3_abc123",
  "command": "Function",
  "action": "Vibrate",
  "intensity": 0
}
```

### Rotation (Nora)

```json
{
  "deviceId": "dev_nora_abc123",
  "command": "Function",
  "action": "Rotate",
  "intensity": 10,
  "duration": 10
}
```

### Air Pump (Max 2)

```json
{
  "deviceId": "dev_max2_abc123",
  "command": "Function",
  "action": "Pump",
  "intensity": 3,
  "duration": 10
}
```

### Multiple Actions

Send multiple commands simultaneously.

```json
{
  "deviceId": "dev_nora_abc123",
  "command": "Function",
  "actions": [
    { "action": "Vibrate", "intensity": 15 },
    { "action": "Rotate", "intensity": 10 }
  ],
  "duration": 10
}
```

---

## Patterns

### Built-in Patterns

Execute pre-defined patterns.

```http
POST https://api.lovense.com/api/lan/v2/command
Authorization: Bearer <auth_token>
Content-Type: application/json

{
  "deviceId": "dev_lush3_abc123",
  "command": "Pattern",
  "pattern": "pulse",
  "duration": 30
}
```

**Available Patterns:**

| Pattern      | Description                |
| ------------ | -------------------------- |
| `pulse`      | Pulsating vibration        |
| `wave`       | Wave pattern               |
| `firework`   | Explosive burst pattern    |
| `earthquake` | Intense random pattern     |
| `heartbeat`  | Rhythmic heartbeat pattern |

### Custom Patterns

Define custom vibration sequences.

```json
{
  "deviceId": "dev_lush3_abc123",
  "command": "Pattern",
  "customPattern": {
    "duration": 30,
    "steps": [
      { "intensity": 5, "duration": 1 },
      { "intensity": 15, "duration": 2 },
      { "intensity": 5, "duration": 1 },
      { "intensity": 20, "duration": 3 },
      { "intensity": 0, "duration": 1 }
    ],
    "loop": true
  }
}
```

### Tip-to-Vibration Mapping

Aphrodite's built-in tip mapping:

```typescript
// libs/aphrodite/devices/src/lovense/tip-mapping.ts
const tipToVibration = (tipAmount: number): VibrationConfig => {
  if (tipAmount >= 100) {
    return { intensity: 20, duration: 30, pattern: 'earthquake' };
  } else if (tipAmount >= 50) {
    return { intensity: 15, duration: 20, pattern: 'wave' };
  } else if (tipAmount >= 25) {
    return { intensity: 10, duration: 10, pattern: 'pulse' };
  } else if (tipAmount >= 10) {
    return { intensity: 7, duration: 5 };
  } else {
    return { intensity: 5, duration: 3 };
  }
};
```

---

## Events

### Event Webhook

Register a webhook to receive device events.

```http
POST https://api.lovense.com/api/lan/v2/webhook
Authorization: Bearer <auth_token>
Content-Type: application/json

{
  "webhookUrl": "https://api.aphrodite.example.com/webhooks/lovense",
  "events": ["device.connected", "device.disconnected", "battery.low"]
}
```

### Event Types

| Event                 | Description                   |
| --------------------- | ----------------------------- |
| `device.connected`    | Device connected              |
| `device.disconnected` | Device disconnected           |
| `battery.low`         | Battery below 20%             |
| `battery.critical`    | Battery below 10%             |
| `command.executed`    | Command successfully executed |
| `command.failed`      | Command execution failed      |

### Event Payload

```json
{
  "event": "battery.low",
  "timestamp": "2026-01-18T12:00:00.000Z",
  "data": {
    "deviceId": "dev_lush3_abc123",
    "deviceType": "lush3",
    "battery": 18
  }
}
```

---

## Aphrodite Integration

### LovenseService

```typescript
// libs/aphrodite/devices/src/lovense/service.ts
import { EventEmitter } from 'events';

export interface LovenseDevice {
  id: string;
  name: string;
  type: string;
  battery: number;
  connected: boolean;
}

export interface VibrationCommand {
  intensity: number;
  duration?: number;
  pattern?: string;
}

export class LovenseService extends EventEmitter {
  private apiKey: string;
  private authToken: string | null = null;
  private devices: Map<string, LovenseDevice> = new Map();

  constructor(apiKey: string) {
    super();
    this.apiKey = apiKey;
  }

  async authenticate(userId: string): Promise<void> {
    // Authenticate and get token
    this.emit('lovense.authenticated', { userId });
  }

  async pairDevice(pairingCode: string): Promise<LovenseDevice> {
    // Pair device
    const device = await this.callApi('/pair', { pairingCode });
    this.devices.set(device.deviceId, device);
    this.emit('lovense.device.paired', device);
    return device;
  }

  async vibrate(deviceId: string, command: VibrationCommand): Promise<void> {
    await this.callApi('/command', {
      deviceId,
      command: 'Function',
      action: 'Vibrate',
      intensity: command.intensity,
      duration: command.duration || 0,
    });
    this.emit('lovense.device.vibration.sent', { deviceId, ...command });
  }

  async executePattern(
    deviceId: string,
    pattern: string,
    duration: number
  ): Promise<void> {
    await this.callApi('/command', {
      deviceId,
      command: 'Pattern',
      pattern,
      duration,
    });
  }

  async getBattery(deviceId: string): Promise<number> {
    const devices = await this.callApi('/devices', {});
    const device = devices.find((d: LovenseDevice) => d.id === deviceId);
    return device?.battery || 0;
  }

  private async callApi(
    endpoint: string,
    data: Record<string, unknown>
  ): Promise<unknown> {
    // API call implementation
  }
}
```

### Tip Integration

```typescript
// libs/aphrodite/devices/src/lovense/tip-handler.ts
export class LovenseTipHandler {
  constructor(
    private lovenseService: LovenseService,
    private tipMapping: TipMappingConfig
  ) {}

  async handleTip(tip: Tip, creatorDevices: LovenseDevice[]): Promise<void> {
    const vibrationConfig = this.mapTipToVibration(tip.amount);

    for (const device of creatorDevices) {
      if (device.connected) {
        await this.lovenseService.vibrate(device.id, vibrationConfig);
      }
    }
  }

  private mapTipToVibration(amount: number): VibrationCommand {
    // Find matching tier
    for (const tier of this.tipMapping.tiers) {
      if (amount >= tier.minAmount) {
        return {
          intensity: tier.intensity,
          duration: tier.duration,
          pattern: tier.pattern,
        };
      }
    }
    return { intensity: 5, duration: 3 };
  }
}
```

---

## Error Handling

### Error Codes

| Code | Description             |
| ---- | ----------------------- |
| 0    | Success                 |
| 1001 | Invalid API key         |
| 1002 | Token expired           |
| 1003 | Invalid token           |
| 2001 | Device not found        |
| 2002 | Device not connected    |
| 2003 | Device busy             |
| 3001 | Invalid command         |
| 3002 | Invalid intensity value |
| 3003 | Pattern not found       |

### Error Response

```json
{
  "code": 2002,
  "message": "Device not connected",
  "data": {
    "deviceId": "dev_lush3_abc123"
  }
}
```

### Retry Logic

```typescript
async function withRetry<T>(
  fn: () => Promise<T>,
  maxRetries: number = 3
): Promise<T> {
  let lastError: Error | null = null;

  for (let i = 0; i < maxRetries; i++) {
    try {
      return await fn();
    } catch (error) {
      lastError = error as Error;

      // Don't retry on auth errors
      if (error.code === 1001 || error.code === 1002) {
        throw error;
      }

      await new Promise((resolve) => setTimeout(resolve, 1000 * (i + 1)));
    }
  }

  throw lastError;
}
```

---

## Security Considerations

1. **API Key Storage**: Store Lovense API keys in secure vault, never in code
2. **Token Refresh**: Implement automatic token refresh before expiration
3. **Rate Limiting**: Respect Lovense API rate limits (100 requests/minute)
4. **User Consent**: Always obtain user consent before device pairing
5. **Data Privacy**: Don't log sensitive device data or patterns

---

## Document History

| Date       | Version | Changes                       |
| ---------- | ------- | ----------------------------- |
| 2026-01-18 | 1.0.0   | Initial Lovense Protocol docs |
