> ## Documentation Index
> Fetch the complete documentation index at: https://docs.getmelody.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Subscription Flow

> Connect a device (or an intermediate app) to the Haptics server over WebSocket and receive haptic signals.

This is a step-by-step guide to connecting a **subscriber** — a device, or an application acting on its behalf — to the Haptics server and receiving signals. It assumes the device is already linked to a Melody account.

***

## 1. Obtain an authentication token

Request a short-lived authentication token and server endpoint from the **Subscriber Auth API** (see the [API Reference](/api-reference)). Use the **Device Subscriber** endpoint for a device connecting directly, or the **App Subscriber** endpoint when an intermediate application connects on the device's behalf.

```bash theme={null}
curl -X POST -H 'Content-Type: application/json' \
  https://api.getmelody.io/api/haptics/auth/subscriber/device \
  --data '{"subscription_id":"123-4567-890","pairing_token":"eyJ0eX..."}'
```

The response contains the WebSocket endpoint and a token to connect with:

```json theme={null}
{
  "ws_endpoint": "wss://ws.endpoint/haptics",
  "ws_proxy_endpoint": "wss://ws.endpoint/haptics",
  "token": "eyJ0eX..."
}
```

<Note>`ws_proxy_endpoint` is deprecated — use `ws_endpoint`.</Note>

***

## 2. Connect and authenticate

Connect to the Haptics server over WebSocket and send a [HapticFrame](/melody/streaming/haptic_frames) carrying a Protobuf `Auth` message.

**Open the connection:**

```go theme={null}
dialer := websocket.Dialer{
	TLSClientConfig: &tls.Config{},
}

conn, _, err := dialer.Dial("wss://ws.endpoint/haptics", nil)
```

**Send the authentication frame:**

```go theme={null}
authProto := &entities.Auth{
	JwtToken: token, // token from step 1
}

bytes, err := proto.Marshal(authProto)

authFrame := &protocol.HapticFrame{
	Type: entities.FrameType_SUBSCRIPTION,
	Data: bytes,
}

err = authFrame.WriteFrame(c.stream)
```

***

## 3. Receive signals

Read frames from the stream and dispatch on the frame type. Always echo `TIME_SYNC` frames back so the server can measure and manage stream quality.

```go theme={null}
for {
	dataFrame, err := protocol.ReadNextFrame(c.stream)

	switch dataFrame.Type {
	// Echo the system TIME_SYNC event back
	case entities.FrameType_TIME_SYNC:
		dataFrame.WriteFrame(c.stream)

	// Adjust internal algorithms using connection info
	case entities.FrameType_CONNECTION_INFO:
		// TODO: your logic

	// Process actual signal events
	case entities.FrameType_SIGNAL:
		// TODO: your logic

	default:
	}
}
```

This connects a subscriber to the Haptics server, authenticates it, and receives signals for further processing. To transmit signals instead, see the [Publication Flow](/melody/streaming/publication).
