# WebSocket接口协议文档 ## 概述 本文档描述了设备运维平台中使用的WebSocket接口协议,用于实时设备监控、控制和数据通信。 ## 服务器信息 - **WebSocket服务器地址**: `ws://119.45.169.13:8848/messaging/{token}` - **Token获取地址**: `http://119.45.169.13:9900/api-device/token/query` - **Token有效期**: 默认3600秒(1小时),可配置 ## 连接流程 ### 1. 获取Token **请求方式**: GET **URL**: `/api-device/token/query` **参数**: - `expires`: Token有效期(秒),可选,默认3600 **响应格式**: ```json { "resp_code": 0, "resp_msg": "success", "data": { "result": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", "message": "success", "status": 200, "timestamp": 1640995200000, "expires": 3600 } } ``` ### 2. 建立WebSocket连接 **连接URL**: `ws://119.45.169.13:8848/messaging/{token}` **连接状态**: - `WebSocket.OPEN`: 连接已建立 - `WebSocket.CLOSED`: 连接已关闭 - `WebSocket.CONNECTING`: 正在连接 - `WebSocket.CLOSING`: 正在关闭 ## 消息格式 ### 通用消息结构 所有WebSocket消息都遵循以下JSON格式: ```json { "type": "消息类型", "topic": "主题路径", "parameter": { "messageType": "消息类型", "properties": { "method": "方法名", "data": {} }, "headers": { "async": false } }, "id": "唯一标识符" } ``` ## 消息类型 ### 1. 订阅消息 (sub) 用于订阅设备状态、属性上报、事件等消息。 #### 设备属性上报订阅 ```json { "type": "sub", "topic": "/device/*/*/message/property/report", "parameter": {}, "id": "sub_property_all_{timestamp}" } ``` #### 设备事件订阅 ```json { "type": "sub", "topic": "/device/*/*/message/event/fire_alarm", "parameter": {}, "id": "sub_event_all_{timestamp}" } ``` #### 设备上线状态订阅 ```json { "type": "sub", "topic": "/device/*/*/online", "parameter": {}, "id": "sub_online_all_{timestamp}" } ``` #### 设备离线状态订阅 ```json { "type": "sub", "topic": "/device/*/*/offline", "parameter": {}, "id": "sub_offline_all_{timestamp}" } ``` #### 指定设备订阅 ```json { "type": "sub", "topic": "/device/*/{deviceSn}/message/property/report", "parameter": {}, "id": "property-sub-{timestamp}-{deviceSn}" } ``` ### 2. 取消订阅消息 (unsub) 用于取消已订阅的消息。 ```json { "type": "unsub", "id": "订阅ID" } ``` ### 3. 设备控制消息 用于向设备发送控制指令。 #### 通用控制指令 ```json { "type": "sub", "topic": "/device-message-sender/D-Dock2/{deviceSn}", "parameter": { "messageType": "WRITE_PROPERTY", "properties": { "method": "方法名", "data": {} }, "headers": { "async": false } }, "id": "control_{method}_{deviceSn}_{timestamp}" } ``` #### 摇杆控制指令 ```json { "type": "sub", "topic": "/device-message-sender/D-Dock2/{deviceSn}", "parameter": { "messageType": "WRITE_PROPERTY", "properties": { "method": "stick_control", "data": { "roll": 1024, // 右手左右控制(范围:0-2048,1024为中立位) "pitch": 1024, // 右手上下控制(范围:0-2048,1024为中立位) "throttle": 1024, // 左手上下控制(范围:0-2048,1024为中立位) "yaw": 1024, // 左手左右控制(范围:1024±100) "gimbal_pitch": 1024 // 云台画面上下划(范围:0-2048,1024为中立位) } }, "headers": { "async": false } }, "id": "control_stick_control_{deviceSn}_{timestamp}" } ``` ### 4. 心跳消息 (ping/pong) 用于保持连接活跃。 **发送心跳**: ```json { "type": "ping", "timestamp": 1640995200000 } ``` **心跳响应**: ```json { "type": "pong" } ``` ## 响应消息 ### 1. 订阅结果响应 ```json { "type": "result", "topic": "/device/{productId}/{deviceSn}/message/property/report", "payload": { "headers": { "deviceName": "设备名称", "productName": "产品名称", "productId": "产品ID" }, "messageId": "消息ID", "deviceId": "设备ID", "timestamp": 1640995200000, "data": { "data": { // 环境数据 "temperature": 25.5, "humidity": 60.2, "wind_speed": 3.2, "rainfall": 0.0, "environment_temperature": 26.1, "latitude": 39.9042, "longitude": 116.4074, "height": 100.5, "heading": 180.0, // 设备状态 "drone_charge_state": { "capacity_percent": 85, "state": 1 }, "position_state": { "is_calibration": 0, "rtk_number": 8, "gps_number": 12, "is_fixed": 1, "quality": 95 }, "network_state": { "rate": 1000, "type": 1, "quality": 90 }, "drone_in_dock": 1, // 飞行任务数据 "flighttask_step_code": 0, "sdr": { "frequency_band": 2, "up_quality": 95, "down_quality": 92 }, "tilt_angle": { "valid": 1, "value": 0.5 }, "wireless_link": { "sdr_link_state": 1, "4g_freq_band": 1, "4g_quality": 85, "link_workmode": 1, "sdr_quality": 90, "4g_uav_quality": 88, "sdr_freq_band": 2, "4g_link_state": 1, "4g_gnd_quality": 87, "dongle_number": 1 } }, "deviceId": "设备ID", "timestamp": 1640995200000 }, "messageType": "REPORT_PROPERTY" } } ``` ### 2. 设备事件响应 ```json { "type": "result", "topic": "/device/{productId}/{deviceSn}/message/event/fire_alarm", "payload": { "headers": { "deviceName": "设备名称", "productName": "产品名称", "productId": "产品ID" }, "messageId": "消息ID", "deviceId": "设备ID", "timestamp": 1640995200000, "event": "fire_alarm", "data": { "alarm_level": 1, "alarm_type": "smoke", "location": "building_1", "description": "烟雾报警" } } } ``` ### 3. 设备状态响应 #### 设备上线 ```json { "type": "result", "topic": "/device/{productId}/{deviceSn}/online", "payload": { "deviceId": "设备ID", "timestamp": 1640995200000, "status": "online" } } ``` #### 设备离线 ```json { "type": "result", "topic": "/device/{productId}/{deviceSn}/offline", "payload": { "deviceId": "设备ID", "timestamp": 1640995200000, "status": "offline" } } ``` ## 主题路径说明 ### 主题格式 ``` /device/{productId}/{deviceSn}/{messageType}/{eventType} ``` ### 主题示例 - `/device/D-Dock2/DEVICE001/message/property/report` - 设备属性上报 - `/device/D-Dock2/DEVICE001/message/event/fire_alarm` - 火警事件 - `/device/D-Dock2/DEVICE001/online` - 设备上线 - `/device/D-Dock2/DEVICE001/offline` - 设备离线 ### 通配符使用 - `*` - 匹配任意字符串 - `/device/*/*/message/property/report` - 订阅所有设备的属性上报 - `/device/*/*/online` - 订阅所有设备的上线状态 ## 错误处理 ### 连接错误 当WebSocket连接出现错误时,系统会自动尝试重连: 1. 连接断开后等待5秒 2. 自动重新获取Token 3. 重新建立WebSocket连接 4. 重新订阅之前的消息 ### 消息错误 如果消息格式错误或处理失败,服务器会返回错误响应: ```json { "type": "error", "id": "消息ID", "error": { "code": "ERROR_CODE", "message": "错误描述" } } ``` ## 最佳实践 ### 1. 连接管理 - 实现自动重连机制 - 定期发送心跳保持连接 - 在页面卸载时正确关闭连接 ### 2. 消息处理 - 为每个消息生成唯一的ID - 实现消息超时处理 - 正确处理异步消息 ### 3. 错误处理 - 实现完善的错误处理机制 - 记录错误日志便于调试 - 提供用户友好的错误提示 ### 4. 性能优化 - 合理使用通配符订阅 - 及时取消不需要的订阅 - 避免频繁发送控制指令 ## 示例代码 ### JavaScript/TypeScript 示例 ```typescript class WebSocketClient { private ws: WebSocket | null = null; private token: string = ''; private reconnectTimer: NodeJS.Timeout | null = null; private heartbeatTimer: NodeJS.Timeout | null = null; // 获取Token async getToken(): Promise { const response = await fetch('/api-device/token/query?expires=3600'); const data = await response.json(); if (data.resp_code === 0) { return data.data.result; } throw new Error('获取Token失败'); } // 连接WebSocket async connect(): Promise { try { this.token = await this.getToken(); const wsUrl = `ws://119.45.169.13:8848/messaging/${this.token}`; this.ws = new WebSocket(wsUrl); this.ws.onopen = () => { console.log('WebSocket连接已建立'); this.startHeartbeat(); this.subscribeToMessages(); }; this.ws.onmessage = (event) => { const data = JSON.parse(event.data); this.handleMessage(data); }; this.ws.onclose = () => { console.log('WebSocket连接已关闭'); this.scheduleReconnect(); }; this.ws.onerror = (error) => { console.error('WebSocket错误:', error); }; } catch (error) { console.error('连接失败:', error); this.scheduleReconnect(); } } // 发送消息 sendMessage(message: any): void { if (this.ws && this.ws.readyState === WebSocket.OPEN) { this.ws.send(JSON.stringify(message)); } } // 订阅消息 subscribeToMessages(): void { const subscriptions = [ { type: 'sub', topic: '/device/*/*/message/property/report', id: `sub_property_${Date.now()}` }, { type: 'sub', topic: '/device/*/*/online', id: `sub_online_${Date.now()}` } ]; subscriptions.forEach(sub => this.sendMessage(sub)); } // 发送控制指令 sendControlCommand(deviceSn: string, method: string, data: any = {}): void { const message = { type: 'sub', topic: `/device-message-sender/D-Dock2/${deviceSn}`, parameter: { messageType: 'WRITE_PROPERTY', properties: { method, data }, headers: { async: false } }, id: `control_${method}_${deviceSn}_${Date.now()}` }; this.sendMessage(message); } // 心跳检测 startHeartbeat(): void { this.heartbeatTimer = setInterval(() => { this.sendMessage({ type: 'ping', timestamp: Date.now() }); }, 30000); } // 重连机制 scheduleReconnect(): void { if (this.reconnectTimer) { clearTimeout(this.reconnectTimer); } this.reconnectTimer = setTimeout(() => { console.log('尝试重新连接...'); this.connect(); }, 5000); } // 处理消息 handleMessage(data: any): void { switch (data.type) { case 'result': this.handleResultMessage(data); break; case 'pong': console.log('收到心跳响应'); break; case 'error': console.error('收到错误消息:', data.error); break; default: console.log('收到未知消息:', data); } } // 处理结果消息 handleResultMessage(data: any): void { const { topic, payload } = data; if (topic.includes('/message/property/report')) { console.log('设备属性上报:', payload); } else if (topic.includes('/online')) { console.log('设备上线:', payload); } else if (topic.includes('/offline')) { console.log('设备离线:', payload); } } // 关闭连接 disconnect(): void { if (this.heartbeatTimer) { clearInterval(this.heartbeatTimer); } if (this.reconnectTimer) { clearTimeout(this.reconnectTimer); } if (this.ws) { this.ws.close(); } } } // 使用示例 const wsClient = new WebSocketClient(); wsClient.connect(); // 发送控制指令 wsClient.sendControlCommand('DEVICE001', 'stick_control', { roll: 1024, pitch: 1024, throttle: 1024, yaw: 1024 }); // 页面卸载时关闭连接 window.addEventListener('beforeunload', () => { wsClient.disconnect(); }); ``` ## 注意事项 1. **Token管理**: Token有过期时间,需要定期刷新 2. **连接稳定性**: 实现自动重连和心跳机制 3. **消息处理**: 正确处理各种类型的消息 4. **错误处理**: 完善的错误处理机制 5. **资源清理**: 及时清理定时器和连接 6. **安全性**: 确保Token的安全性,不要在客户端存储敏感信息 ## 更新日志 - **v1.0.0**: 初始版本,包含基本的连接、订阅、控制功能 - **v1.1.0**: 添加心跳机制和自动重连 - **v1.2.0**: 完善错误处理和消息格式 - **v1.3.0**: 添加设备状态监控和事件处理