# The Handy Device Protocol

> Integration documentation for The Handy male stroker device.

**API Base URL:** `https://www.handyfeeling.com/api/handy/v2`
**Authentication:** Connection Key (per-device)

---

## Table of Contents

1. [Overview](#overview)
2. [Authentication](#authentication)
3. [Device Information](#device-information)
4. [Control Modes](#control-modes)
5. [Synchronization](#synchronization)
6. [Aphrodite Integration](#aphrodite-integration)

---

## Overview

The Handy is an advanced male stroker device with precise stroke control and
video synchronization capabilities. It supports multiple control modes and can
sync with interactive content.

### Key Features

- Precise stroke position control (0-100%)
- Variable speed control (0-400 mm/s)
- Multiple control modes (HAMP, HDSP, HSSP, HBSP)
- Video/script synchronization
- Low latency control (~50ms)

---

## Authentication

### Connection Key

Each Handy device has a unique connection key obtained during initial setup. The
key is passed in the `X-Connection-Key` header for all API requests.

```http
GET https://www.handyfeeling.com/api/handy/v2/connected
X-Connection-Key: <device_connection_key>
```

### Check Connection

Verify device is connected and responsive.

```http
GET /connected
X-Connection-Key: <connection_key>
```

**Response:**

```json
{
  "connected": true,
  "state": {
    "mode": 0,
    "state": 0
  }
}
```

---

## Device Information

### Get Device Info

```http
GET /info
X-Connection-Key: <connection_key>
```

**Response:**

```json
{
  "fwVersion": "3.2.1",
  "fwStatus": 0,
  "hwVersion": "1.0",
  "model": "H",
  "branch": "release",
  "sessionId": "abc123"
}
```

### Get Device Status

```http
GET /status
X-Connection-Key: <connection_key>
```

**Response:**

```json
{
  "mode": 0,
  "state": 0,
  "slideMin": 0,
  "slideMax": 100,
  "position": 50,
  "speed": 0
}
```

### Get Device Settings

```http
GET /settings
X-Connection-Key: <connection_key>
```

**Response:**

```json
{
  "slideMin": 0,
  "slideMax": 100,
  "speedMin": 0,
  "speedMax": 400,
  "strokeZone": {
    "min": 0,
    "max": 100
  },
  "offset": 0
}
```

### Set Stroke Zone

Limit the stroke range.

```http
PUT /settings/strokezone
X-Connection-Key: <connection_key>
Content-Type: application/json

{
  "min": 10,
  "max": 90
}
```

---

## Control Modes

### Mode Overview

| Mode | Name | Description                      |
| ---- | ---- | -------------------------------- |
| 0    | HAMP | Handy Alternating Motion Pattern |
| 1    | HSSP | Handy Sync Server Protocol       |
| 2    | HDSP | Handy Direct Server Protocol     |
| 3    | HBSP | Handy Binary Script Protocol     |

### Set Mode

```http
PUT /mode
X-Connection-Key: <connection_key>
Content-Type: application/json

{
  "mode": 0
}
```

---

### HAMP Mode (Alternating Motion)

Simple up-down stroking motion at configurable speed.

#### Start HAMP

```http
PUT /hamp/start
X-Connection-Key: <connection_key>
```

#### Stop HAMP

```http
PUT /hamp/stop
X-Connection-Key: <connection_key>
```

#### Set HAMP Velocity

Control stroke speed (0-100%).

```http
PUT /hamp/velocity
X-Connection-Key: <connection_key>
Content-Type: application/json

{
  "velocity": 50
}
```

**Response:**

```json
{
  "result": 0,
  "velocity": 50
}
```

#### Get HAMP State

```http
GET /hamp/state
X-Connection-Key: <connection_key>
```

**Response:**

```json
{
  "result": 0,
  "state": 1,
  "velocity": 50
}
```

---

### HDSP Mode (Direct Position)

Direct position control with timing.

#### Move to Position

```http
PUT /hdsp/xpt
X-Connection-Key: <connection_key>
Content-Type: application/json

{
  "stopOnTarget": true,
  "immediateResponse": true,
  "position": 75,
  "duration": 500
}
```

**Parameters:**

| Parameter           | Type    | Description                          |
| ------------------- | ------- | ------------------------------------ |
| `position`          | number  | Target position (0-100)              |
| `duration`          | number  | Movement duration in ms              |
| `stopOnTarget`      | boolean | Stop at target position              |
| `immediateResponse` | boolean | Respond immediately vs on completion |

---

### HSSP Mode (Sync Server)

Synchronize with server-provided scripts.

#### Setup Sync

```http
PUT /hssp/setup
X-Connection-Key: <connection_key>
Content-Type: application/json

{
  "url": "https://api.aphrodite.example.com/scripts/script123.csv",
  "sha256": "abc123..."
}
```

#### Start Sync

```http
PUT /hssp/play
X-Connection-Key: <connection_key>
Content-Type: application/json

{
  "estimatedServerTime": 1737216000000,
  "startTime": 0
}
```

#### Stop Sync

```http
PUT /hssp/stop
X-Connection-Key: <connection_key>
```

#### Get Server Time

For synchronization timing.

```http
GET /servertime
X-Connection-Key: <connection_key>
```

**Response:**

```json
{
  "serverTime": 1737216000000
}
```

---

## Synchronization

### Time Synchronization

The Handy requires time synchronization for accurate script playback.

```typescript
async function syncTime(connectionKey: string): Promise<number> {
  const samples = [];

  for (let i = 0; i < 30; i++) {
    const t0 = Date.now();
    const response = await fetch(
      'https://www.handyfeeling.com/api/handy/v2/servertime',
      { headers: { 'X-Connection-Key': connectionKey } }
    );
    const data = await response.json();
    const t1 = Date.now();

    const rtd = t1 - t0;
    const offset = data.serverTime - (t0 + rtd / 2);
    samples.push({ rtd, offset });
  }

  // Filter outliers and calculate average
  samples.sort((a, b) => a.rtd - b.rtd);
  const filtered = samples.slice(0, Math.ceil(samples.length * 0.5));
  const avgOffset =
    filtered.reduce((sum, s) => sum + s.offset, 0) / filtered.length;

  return Math.round(avgOffset);
}
```

### Script Format (CSV)

The Handy uses CSV format for scripts with position-time pairs.

```csv
#File format
#https://www.handyfeeling.com/api/csv/
0,0
100,50
200,100
300,50
400,0
```

**Format:**

- First column: Time in milliseconds
- Second column: Position (0-100)

---

## Aphrodite Integration

### HandyService

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

export interface HandyDevice {
  connectionKey: string;
  connected: boolean;
  firmware: string;
  mode: HandyMode;
  strokeZone: { min: number; max: number };
  offset: number;
}

export enum HandyMode {
  HAMP = 0,
  HSSP = 1,
  HDSP = 2,
  HBSP = 3,
}

export class HandyService extends EventEmitter {
  private baseUrl = 'https://www.handyfeeling.com/api/handy/v2';
  private devices: Map<string, HandyDevice> = new Map();
  private timeOffsets: Map<string, number> = new Map();

  async connect(connectionKey: string): Promise<HandyDevice> {
    const connected = await this.checkConnection(connectionKey);
    if (!connected) {
      throw new Error('Device not connected');
    }

    const info = await this.getInfo(connectionKey);
    const status = await this.getStatus(connectionKey);

    const device: HandyDevice = {
      connectionKey,
      connected: true,
      firmware: info.fwVersion,
      mode: status.mode,
      strokeZone: { min: status.slideMin, max: status.slideMax },
      offset: 0,
    };

    this.devices.set(connectionKey, device);

    // Sync time
    const offset = await this.syncTime(connectionKey);
    this.timeOffsets.set(connectionKey, offset);
    device.offset = offset;

    this.emit('handy.authenticated', { connectionKey });
    this.emit('handy.device.paired', device);

    return device;
  }

  async startStroke(connectionKey: string, velocity: number): Promise<void> {
    await this.setMode(connectionKey, HandyMode.HAMP);
    await this.setVelocity(connectionKey, velocity);
    await this.callApi(connectionKey, 'PUT', '/hamp/start');
    this.emit('handy.stroking.started', { connectionKey, velocity });
  }

  async stopStroke(connectionKey: string): Promise<void> {
    await this.callApi(connectionKey, 'PUT', '/hamp/stop');
    this.emit('handy.stroking.stopped', { connectionKey });
  }

  async setVelocity(connectionKey: string, velocity: number): Promise<void> {
    const clampedVelocity = Math.min(100, Math.max(0, velocity));
    await this.callApi(connectionKey, 'PUT', '/hamp/velocity', {
      velocity: clampedVelocity,
    });
  }

  async moveToPosition(
    connectionKey: string,
    position: number,
    duration: number
  ): Promise<void> {
    await this.setMode(connectionKey, HandyMode.HDSP);
    await this.callApi(connectionKey, 'PUT', '/hdsp/xpt', {
      position: Math.min(100, Math.max(0, position)),
      duration,
      stopOnTarget: true,
      immediateResponse: true,
    });
  }

  async setStrokeZone(
    connectionKey: string,
    min: number,
    max: number
  ): Promise<void> {
    await this.callApi(connectionKey, 'PUT', '/settings/strokezone', {
      min: Math.max(0, min),
      max: Math.min(100, max),
    });

    const device = this.devices.get(connectionKey);
    if (device) {
      device.strokeZone = { min, max };
    }
  }

  async playScript(
    connectionKey: string,
    scriptUrl: string,
    sha256: string,
    startTime: number = 0
  ): Promise<void> {
    await this.setMode(connectionKey, HandyMode.HSSP);

    await this.callApi(connectionKey, 'PUT', '/hssp/setup', {
      url: scriptUrl,
      sha256,
    });

    const offset = this.timeOffsets.get(connectionKey) || 0;
    await this.callApi(connectionKey, 'PUT', '/hssp/play', {
      estimatedServerTime: Date.now() + offset,
      startTime,
    });
  }

  async stopScript(connectionKey: string): Promise<void> {
    await this.callApi(connectionKey, 'PUT', '/hssp/stop');
  }

  private async setMode(connectionKey: string, mode: HandyMode): Promise<void> {
    const device = this.devices.get(connectionKey);
    if (device?.mode !== mode) {
      await this.callApi(connectionKey, 'PUT', '/mode', { mode });
      if (device) device.mode = mode;
    }
  }

  private async checkConnection(connectionKey: string): Promise<boolean> {
    const response = await this.callApi(connectionKey, 'GET', '/connected');
    return response.connected === true;
  }

  private async getInfo(connectionKey: string): Promise<any> {
    return this.callApi(connectionKey, 'GET', '/info');
  }

  private async getStatus(connectionKey: string): Promise<any> {
    return this.callApi(connectionKey, 'GET', '/status');
  }

  private async syncTime(connectionKey: string): Promise<number> {
    // Time synchronization implementation
    // ... (as shown above)
    return 0;
  }

  private async callApi(
    connectionKey: string,
    method: string,
    endpoint: string,
    body?: Record<string, unknown>
  ): Promise<any> {
    const response = await fetch(`${this.baseUrl}${endpoint}`, {
      method,
      headers: {
        'X-Connection-Key': connectionKey,
        'Content-Type': 'application/json',
      },
      body: body ? JSON.stringify(body) : undefined,
    });

    if (!response.ok) {
      throw new Error(`Handy API error: ${response.status}`);
    }

    return response.json();
  }
}
```

### Tip Handler

```typescript
// libs/aphrodite/devices/src/handy/tip-handler.ts
export class HandyTipHandler {
  constructor(private handyService: HandyService) {}

  async handleTip(
    tip: Tip,
    connectionKey: string,
    patterns: TipPattern[]
  ): Promise<void> {
    const pattern = this.selectPattern(tip.amount, patterns);

    if (pattern.type === 'velocity') {
      await this.handyService.startStroke(connectionKey, pattern.velocity);

      setTimeout(async () => {
        await this.handyService.stopStroke(connectionKey);
      }, pattern.duration * 1000);
    } else if (pattern.type === 'script') {
      await this.handyService.playScript(
        connectionKey,
        pattern.scriptUrl,
        pattern.sha256
      );

      setTimeout(async () => {
        await this.handyService.stopScript(connectionKey);
      }, pattern.duration * 1000);
    }
  }

  private selectPattern(amount: number, patterns: TipPattern[]): TipPattern {
    // Find best matching pattern for tip amount
    for (const pattern of patterns.sort((a, b) => b.minAmount - a.minAmount)) {
      if (amount >= pattern.minAmount) {
        return pattern;
      }
    }
    return patterns[patterns.length - 1];
  }
}
```

---

## Built-in Patterns

### CSV Pattern Generator

```typescript
// libs/aphrodite/devices/src/handy/patterns.ts
export function generateStrokePattern(
  duration: number,
  velocity: number,
  type: 'slow' | 'fast' | 'random' | 'pulse'
): string {
  const lines = ['#Aphrodite generated pattern'];
  let time = 0;
  let position = 0;
  const interval = Math.max(50, Math.floor(1000 / velocity));

  while (time < duration * 1000) {
    lines.push(`${time},${position}`);

    switch (type) {
      case 'slow':
        position = position === 0 ? 100 : 0;
        time += interval * 2;
        break;
      case 'fast':
        position = position === 0 ? 100 : 0;
        time += interval / 2;
        break;
      case 'random':
        position = Math.floor(Math.random() * 100);
        time += interval;
        break;
      case 'pulse':
        position = position < 50 ? 80 : 20;
        time += interval;
        break;
    }
  }

  return lines.join('\n');
}
```

---

## Error Handling

### Error Codes

| Code | Description          |
| ---- | -------------------- |
| 0    | Success              |
| -1   | Generic error        |
| -2   | Device not connected |
| -3   | Invalid request      |
| -4   | Device busy          |

### Error Response

```json
{
  "error": {
    "code": -2,
    "name": "NotConnected",
    "message": "Device is not connected",
    "connected": false
  }
}
```

---

## Document History

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