---
# System prepended metadata

title: Pair device workflow

---

Pair device workflow

```sequence
App -> Device: Pair and provision Wifi credential
App -> API: Get list device's VID, PID support AWS control
App -> App: Check if device support AWS control
Note left of App: If device support AWS control
App -> Device: Read device id from Matter cluster
App -> API: Add device to room
Note left of App: If device don't support AWS control
App -> API: Create new device and add to room
```

Connect websocket

```sequence
Connect handle Lambda -> API: Get JWK if don't have JWK
Connect handle Lambda -> Connect handle Lambda: Validate token by JWK
Connect handle Lambda -> Redis: Push connection id to user's connection list
Connect handle Lambda -> Redis: Check if have user's device list data in Redis
Note left of Connect handle Lambda: If don't have user's device list data in Redis
Connect handle Lambda -> API: Get user's device list
Connect handle Lambda -> Redis: Save user's device list
```

Disconnect websocket

```sequence
Disconnect handle Lambda -> Redis: Pop connection id from user's connection list
```

Device state save history

```sequence
Device -> AWS IoT topic: Send device state
AWS IoT topic -> AWS IoT Rule: Listen message
AWS IoT Rule -> Kinesis Firehose: Trigger message
Kinesis Firehose -> S3: Save device state
```

Device state real-time handle

```sequence
Device -> AWS IoT topic: Send device state
AWS IoT topic -> AWS IoT Rule: Listen message
AWS IoT Rule -> Device state SQS: Trigger message
Device state SQS -> Device state handle Lambda: Trigger event
Device state handle Lambda -> Redis: Get list user's connection of device
Device state handle Lambda -> API Gateway WebSocket: Send message
```

Add device to room

```sequence
App -> API: Add device to room
API -> DB: Add device to room
API --> App: Response
API -> New device SQS: Trigger message
New device SQS -> New device handle Lambda: Trigger event
New device handle Lambda -> Redis: Add device to user device list
```

Remove device from room

```sequence
App -> API: Remove device from room
API -> DB: Remove device from room
API --> App: Response
API -> Remove device SQS: Trigger message
Remove device SQS -> Remove device handle Lambda: Trigger event
Remove device handle Lambda -> Redis: Remove device from user device list
```

Control device handle

```sequence
App -> API Gateway: Send control message
API Gateway -> Control device handle Lambda: Trigger event
Control device handle Lambda -> Redis: Check if user have permission to control device
Control device handle Lambda -> AWS thing shadow: Send control message
```