即時串流 API (SSE)
使用 Server-Sent Events 即時接收分析結果。
端點概覽
| 方法 | 路徑 | 說明 |
|---|---|---|
| GET | /api/v1/devices/:id/analysis/stream | 串流單一設備的分析結果 |
| GET | /api/v1/devices/analysis/stream/all | 串流所有設備的分析結果 |
使用場景
- 即時監控儀表板:在網頁上即時顯示排隊人數、等待時間等指標
- 低延遲通知:比輪詢更即時的數據更新
- 多設備監控:一次連線接收所有設備的分析結果
💡 SSE 比 WebSocket 更輕量,且瀏覽器原生支援自動重連。
串流單一設備
GET /api/v1/devices/:id/analysis/stream
JavaScript 範例
const eventSource = new EventSource(
'https://api.example.com/api/v1/devices/device-uuid/analysis/stream',
{
headers: {
'Authorization': 'Bearer YOUR_API_KEY'
}
}
);
eventSource.onmessage = (event) => {
const data = JSON.parse(event.data);
console.log('收到分析結果:', data);
};
eventSource.onerror = (error) => {
console.error('SSE 連線錯誤:', error);
};
SSE 事件格式
event: analysis_result
id: task-uuid-1738000000000
data: {"deviceId":"device-uuid","analysisId":"analysis-uuid","sceneId":"scene-uuid","timestamp":"2026-01-29T10:00:00Z","detections":[...]}
事件資料結構
| 欄位 | 型別 | 說明 |
|---|---|---|
deviceId | String (UUID) | 設備 ID |
analysisId | String (UUID) | 分析 ID |
sceneId | String (UUID) | 場景 ID |
timestamp | String (ISO 8601) | 分析時間戳 |
detections | Array | 偵測結果陣列 |
detections[].type | String | 偵測類型(person, object) |
detections[].confidence | Number | 信心度 (0-1) |
detections[].boundingBox | Object | 邊界框座標(可選) |
detections[].attributes | Object | 物件屬性(可選,level_02 限定) |
串流所有設備
GET /api/v1/devices/analysis/stream/all
接收當前用戶所有設備的分析結果。
const eventSource = new EventSource(
'https://api.example.com/api/v1/devices/analysis/stream/all',
{
headers: {
'Authorization': 'Bearer YOUR_API_KEY'
}
}
);
eventSource.addEventListener('analysis_result', (event) => {
const data = JSON.parse(event.data);
console.log(`設備 ${data.deviceId} 結果:`, data.detections);
});
連線管理
| 規則 | 說明 |
|---|---|
| 連線逾時 | 300 秒無活動自動斷開 |
| 自動重連 | 瀏覽器原生支援,間隔約 3 秒 |
| 同時連線數 | 每用戶最多 10 個 SSE 連線 |
使用 curl 測試
curl -N -H "Authorization: Bearer YOUR_API_KEY" \
"https://api.example.com/api/v1/devices/device-uuid/analysis/stream"
⚠️ SSE 僅支援
device:read或analytics:readscope 的 API Key。