# Buttplug.io Protocol

> Integration documentation for Buttplug.io compatible devices.

**Protocol:** Buttplug Protocol v3 **Connection:** WebSocket **Default URL:**
`ws://localhost:12345`

---

## Table of Contents

1. [Overview](#overview)
2. [Connection](#connection)
3. [Device Discovery](#device-discovery)
4. [Commands](#commands)
5. [Events](#events)
6. [Aphrodite Integration](#aphrodite-integration)

---

## Overview

Buttplug.io is an open-source protocol supporting 200+ devices from various
manufacturers. The protocol uses WebSocket for communication with a local
Buttplug server (like Intiface Central).

### Supported Device Types

| Type         | Capabilities         | Example Devices          |
| ------------ | -------------------- | ------------------------ |
| Vibrators    | Vibrate              | Lovense, We-Vibe, Kiiroo |
| Strokers     | Linear movement      | Handy, Kiiroo            |
| Oscillators  | Oscillating movement | Lovense Osci             |
| Rotators     | Rotation             | Lovense Nora             |
| Inflatable   | Air pump             | Various                  |
| Constriction | Constrict/release    | Various                  |
| Position     | Position feedback    | Various                  |

---

## Connection

### WebSocket Handshake

```typescript
const ws = new WebSocket('ws://localhost:12345');

ws.onopen = () => {
  // Send handshake
  ws.send(
    JSON.stringify([
      {
        RequestServerInfo: {
          Id: 1,
          ClientName: 'Aphrodite',
          MessageVersion: 3,
        },
      },
    ])
  );
};
```

### Server Info Response

```json
[
  {
    "ServerInfo": {
      "Id": 1,
      "ServerName": "Intiface Central",
      "MessageVersion": 3,
      "MaxPingTime": 0
    }
  }
]
```

### Connection Class

```typescript
// libs/aphrodite/devices/src/buttplug/service.ts
export class ButtplugService extends EventEmitter {
  private ws: WebSocket | null = null;
  private messageId = 1;
  private devices: Map<number, ButtplugDevice> = new Map();

  async connect(url: string = 'ws://localhost:12345'): Promise<void> {
    return new Promise((resolve, reject) => {
      this.ws = new WebSocket(url);

      this.ws.onopen = () => {
        this.sendMessage({
          RequestServerInfo: {
            Id: this.messageId++,
            ClientName: 'Aphrodite',
            MessageVersion: 3,
          },
        });
      };

      this.ws.onmessage = (event) => {
        const messages = JSON.parse(event.data);
        this.handleMessages(messages);

        // Check for ServerInfo response
        const serverInfo = messages.find((m: any) => m.ServerInfo);
        if (serverInfo) {
          this.emit('buttplug.connected', serverInfo.ServerInfo);
          resolve();
        }
      };

      this.ws.onerror = (error) => {
        this.emit('buttplug.error', error);
        reject(error);
      };

      this.ws.onclose = () => {
        this.emit('buttplug.disconnected');
      };
    });
  }

  disconnect(): void {
    if (this.ws) {
      this.ws.close();
      this.ws = null;
    }
  }

  private sendMessage(message: Record<string, unknown>): void {
    if (this.ws?.readyState === WebSocket.OPEN) {
      this.ws.send(JSON.stringify([message]));
    }
  }
}
```

---

## Device Discovery

### Start Scanning

```typescript
// Send StartScanning message
{
  "StartScanning": {
    "Id": 2
  }
}
```

### Stop Scanning

```typescript
{
  "StopScanning": {
    "Id": 3
  }
}
```

### Device Added Event

When a device is discovered:

```json
[
  {
    "DeviceAdded": {
      "Id": 0,
      "DeviceIndex": 0,
      "DeviceName": "Lovense Lush",
      "DeviceDisplayName": "Lush 3",
      "DeviceMessageTimingGap": 50,
      "DeviceMessages": {
        "ScalarCmd": [
          {
            "FeatureDescriptor": "Vibrator",
            "ActuatorType": "Vibrate",
            "StepCount": 20
          }
        ],
        "StopDeviceCmd": {}
      }
    }
  }
]
```

### Device Removed Event

```json
[
  {
    "DeviceRemoved": {
      "Id": 0,
      "DeviceIndex": 0
    }
  }
]
```

### Request Device List

Get all connected devices:

```typescript
{
  "RequestDeviceList": {
    "Id": 4
  }
}
```

**Response:**

```json
[
  {
    "DeviceList": {
      "Id": 4,
      "Devices": [
        {
          "DeviceIndex": 0,
          "DeviceName": "Lovense Lush",
          "DeviceDisplayName": "Lush 3",
          "DeviceMessages": { ... }
        }
      ]
    }
  }
]
```

---

## Commands

### ScalarCmd (Vibration, etc.)

Control scalar actuators (vibration intensity, etc.).

```typescript
{
  "ScalarCmd": {
    "Id": 5,
    "DeviceIndex": 0,
    "Scalars": [
      {
        "Index": 0,
        "Scalar": 0.5,
        "ActuatorType": "Vibrate"
      }
    ]
  }
}
```

**Parameters:**

| Parameter      | Type   | Range   | Description               |
| -------------- | ------ | ------- | ------------------------- |
| `DeviceIndex`  | number | 0+      | Device identifier         |
| `Index`        | number | 0+      | Actuator index            |
| `Scalar`       | number | 0.0-1.0 | Intensity (0=off, 1=max)  |
| `ActuatorType` | string | -       | "Vibrate", "Rotate", etc. |

### LinearCmd (Strokers)

Control linear movement devices.

```typescript
{
  "LinearCmd": {
    "Id": 6,
    "DeviceIndex": 0,
    "Vectors": [
      {
        "Index": 0,
        "Duration": 500,
        "Position": 0.8
      }
    ]
  }
}
```

**Parameters:**

| Parameter  | Type   | Range   | Description            |
| ---------- | ------ | ------- | ---------------------- |
| `Duration` | number | 0+      | Movement duration (ms) |
| `Position` | number | 0.0-1.0 | Target position        |

### RotateCmd

Control rotation devices.

```typescript
{
  "RotateCmd": {
    "Id": 7,
    "DeviceIndex": 0,
    "Rotations": [
      {
        "Index": 0,
        "Speed": 0.5,
        "Clockwise": true
      }
    ]
  }
}
```

### StopDeviceCmd

Stop a specific device.

```typescript
{
  "StopDeviceCmd": {
    "Id": 8,
    "DeviceIndex": 0
  }
}
```

### StopAllDevices

Stop all connected devices.

```typescript
{
  "StopAllDevices": {
    "Id": 9
  }
}
```

---

## Events

### Scanning Finished

```json
[
  {
    "ScanningFinished": {
      "Id": 0
    }
  }
]
```

### Error

```json
[
  {
    "Error": {
      "Id": 5,
      "ErrorCode": 3,
      "ErrorMessage": "Device not connected"
    }
  }
]
```

### Error Codes

| Code | Name          | Description          |
| ---- | ------------- | -------------------- |
| 0    | ERROR_UNKNOWN | Unknown error        |
| 1    | ERROR_INIT    | Initialization error |
| 2    | ERROR_PING    | Ping timeout         |
| 3    | ERROR_MSG     | Message error        |
| 4    | ERROR_DEVICE  | Device error         |

---

## Aphrodite Integration

### ButtplugService

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

export interface ButtplugDevice {
  index: number;
  name: string;
  displayName: string;
  capabilities: DeviceCapability[];
}

export interface DeviceCapability {
  type: 'vibrate' | 'rotate' | 'linear' | 'oscillate';
  stepCount: number;
  index: number;
}

export class ButtplugService extends EventEmitter {
  private ws: WebSocket | null = null;
  private messageId = 1;
  private devices: Map<number, ButtplugDevice> = new Map();
  private pendingRequests: Map<number, (response: any) => void> = new Map();

  async connect(url: string = 'ws://localhost:12345'): Promise<void> {
    // Connection implementation
  }

  async startScanning(): Promise<void> {
    this.sendMessage({
      StartScanning: { Id: this.messageId++ },
    });
    this.emit('buttplug.scanning.started');
  }

  async stopScanning(): Promise<void> {
    this.sendMessage({
      StopScanning: { Id: this.messageId++ },
    });
    this.emit('buttplug.scanning.stopped');
  }

  async vibrate(
    deviceIndex: number,
    intensity: number,
    duration?: number
  ): Promise<void> {
    const device = this.devices.get(deviceIndex);
    if (!device) throw new Error('Device not found');

    // Find vibrate capability
    const vibrateCap = device.capabilities.find((c) => c.type === 'vibrate');
    if (!vibrateCap) throw new Error('Device does not support vibration');

    // Scale intensity to 0-1 range
    const scalar = Math.min(1, Math.max(0, intensity / 100));

    this.sendMessage({
      ScalarCmd: {
        Id: this.messageId++,
        DeviceIndex: deviceIndex,
        Scalars: [
          {
            Index: vibrateCap.index,
            Scalar: scalar,
            ActuatorType: 'Vibrate',
          },
        ],
      },
    });

    // Auto-stop after duration
    if (duration && duration > 0) {
      setTimeout(() => this.stopDevice(deviceIndex), duration * 1000);
    }
  }

  async linear(
    deviceIndex: number,
    position: number,
    duration: number
  ): Promise<void> {
    const device = this.devices.get(deviceIndex);
    if (!device) throw new Error('Device not found');

    const linearCap = device.capabilities.find((c) => c.type === 'linear');
    if (!linearCap) throw new Error('Device does not support linear movement');

    this.sendMessage({
      LinearCmd: {
        Id: this.messageId++,
        DeviceIndex: deviceIndex,
        Vectors: [
          {
            Index: linearCap.index,
            Duration: duration,
            Position: Math.min(1, Math.max(0, position)),
          },
        ],
      },
    });
  }

  async stopDevice(deviceIndex: number): Promise<void> {
    this.sendMessage({
      StopDeviceCmd: {
        Id: this.messageId++,
        DeviceIndex: deviceIndex,
      },
    });
  }

  async stopAllDevices(): Promise<void> {
    this.sendMessage({
      StopAllDevices: { Id: this.messageId++ },
    });
  }

  getDevices(): ButtplugDevice[] {
    return Array.from(this.devices.values());
  }

  private handleMessages(messages: any[]): void {
    for (const message of messages) {
      if (message.DeviceAdded) {
        this.handleDeviceAdded(message.DeviceAdded);
      } else if (message.DeviceRemoved) {
        this.handleDeviceRemoved(message.DeviceRemoved);
      } else if (message.ScanningFinished) {
        this.emit('buttplug.scanning.stopped');
      } else if (message.Error) {
        this.emit('buttplug.error', message.Error);
      }
    }
  }

  private handleDeviceAdded(data: any): void {
    const device: ButtplugDevice = {
      index: data.DeviceIndex,
      name: data.DeviceName,
      displayName: data.DeviceDisplayName || data.DeviceName,
      capabilities: this.parseCapabilities(data.DeviceMessages),
    };

    this.devices.set(device.index, device);
    this.emit('buttplug.device.discovered', device);
  }

  private handleDeviceRemoved(data: any): void {
    const device = this.devices.get(data.DeviceIndex);
    if (device) {
      this.devices.delete(data.DeviceIndex);
      this.emit('buttplug.device.disconnected', device);
    }
  }

  private parseCapabilities(messages: any): DeviceCapability[] {
    const caps: DeviceCapability[] = [];

    if (messages.ScalarCmd) {
      for (const scalar of messages.ScalarCmd) {
        caps.push({
          type: scalar.ActuatorType.toLowerCase() as any,
          stepCount: scalar.StepCount,
          index: scalar.Index || 0,
        });
      }
    }

    if (messages.LinearCmd) {
      for (const linear of messages.LinearCmd) {
        caps.push({
          type: 'linear',
          stepCount: linear.StepCount,
          index: linear.Index || 0,
        });
      }
    }

    if (messages.RotateCmd) {
      for (const rotate of messages.RotateCmd) {
        caps.push({
          type: 'rotate',
          stepCount: rotate.StepCount,
          index: rotate.Index || 0,
        });
      }
    }

    return caps;
  }

  private sendMessage(message: Record<string, unknown>): void {
    if (this.ws?.readyState === WebSocket.OPEN) {
      this.ws.send(JSON.stringify([message]));
    }
  }
}
```

### Tip Handler

```typescript
// libs/aphrodite/devices/src/buttplug/tip-handler.ts
export class ButtplugTipHandler {
  constructor(private buttplugService: ButtplugService) {}

  async handleTip(tip: Tip, creatorDevices: number[]): Promise<void> {
    const intensity = this.mapTipToIntensity(tip.amount);
    const duration = this.mapTipToDuration(tip.amount);

    for (const deviceIndex of creatorDevices) {
      try {
        await this.buttplugService.vibrate(deviceIndex, intensity, duration);
      } catch (error) {
        console.error(`Failed to vibrate device ${deviceIndex}:`, error);
      }
    }
  }

  private mapTipToIntensity(amount: number): number {
    if (amount >= 100) return 100;
    if (amount >= 50) return 75;
    if (amount >= 25) return 50;
    if (amount >= 10) return 35;
    return 25;
  }

  private mapTipToDuration(amount: number): number {
    if (amount >= 100) return 30;
    if (amount >= 50) return 20;
    if (amount >= 25) return 10;
    return 5;
  }
}
```

---

## Security Considerations

1. **Local Only**: Buttplug server runs locally, no internet exposure
2. **User Control**: User must explicitly connect devices
3. **Consent**: Always obtain consent before device control
4. **Rate Limiting**: Implement command rate limiting to prevent abuse
5. **Disconnect Handling**: Gracefully handle device disconnections

---

## Document History

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