消息格式
所有 WebSocket 文本消息都使用 JSON。顶层 type 表示消息方向,topic 只用于请求和事件。
type | 方向 | 说明 |
|---|---|---|
request | 客户端到服务 | 发起请求 |
reply | 服务到客户端 | 回复某个 request |
event | 服务到客户端 | 主动推送事件 |
Request
json
{
"type": "request",
"requestId": "req_state_001",
"topic": "device.state.get",
"data": {
"deviceId": "abc123456789"
}
}| 字段 | 类型 | 必填 | 说明 |
|---|---|---|---|
type | string | 是 | 固定为 request |
requestId | string | 是 | 客户端生成的请求 ID,同一连接内应唯一 |
topic | string | 是 | 请求主题 |
data | object | 是 | 请求参数 |
设备写操作统一使用 device.operation.execute,具体操作由 data.operation.name 指定:
json
{
"type": "request",
"requestId": "req_relay_001",
"topic": "device.operation.execute",
"data": {
"deviceId": "abc123456789",
"idempotencyKey": "idem_relay_001",
"operation": {
"name": "device.relay.set",
"params": {
"relays": [
{ "index": 1, "action": "ON" }
]
}
}
}
}Reply
reply 通过 requestId 与请求关联,因此不重复返回 topic,也不使用 success 或嵌套的 error。
成功回复:
json
{
"type": "reply",
"requestId": "req_state_001",
"code": "SUCCESS",
"message": "OK.",
"data": {
"deviceId": "abc123456789",
"status": "ONLINE",
"peripherals": {
"relays": [
{ "index": 1, "on": true }
]
},
"stateUpdatedAt": "2026-07-15T08:30:00Z"
}
}命令已受理:
json
{
"type": "reply",
"requestId": "req_relay_001",
"code": "COMMAND_ACCEPTED",
"message": "Command accepted.",
"data": {
"command": {
"id": "cmd_01HX...",
"deviceId": "abc123456789",
"operation": "device.relay.set",
"status": "SUCCESS",
"params": {
"relays": [
{ "index": 1, "action": "ON" }
]
},
"createdAt": "2026-07-15T08:30:00Z"
}
}
}错误回复:
json
{
"type": "reply",
"requestId": "req_relay_001",
"code": "AUTH_SCOPE_DENIED",
"message": "This operation requires the device:control permission. Update the API Client permissions in the Developer Console and obtain a new access token.",
"data": {
"requiredScope": "device:control"
}
}| 字段 | 类型 | 必填 | 说明 |
|---|---|---|---|
type | string | 是 | 固定为 reply |
requestId | string | 是 | 对应请求的 requestId |
code | string | 是 | SUCCESS、COMMAND_ACCEPTED 或错误码 |
message | string | 是 | 便于阅读和排障的说明,不用于程序分支 |
data | object | 否 | 成功数据或结构化错误信息 |
客户端应根据 code 处理结果,不应依赖 message 文本。
Event
json
{
"type": "event",
"topic": "device.state.changed",
"data": {
"deviceId": "abc123456789",
"occurredAt": "2026-07-15T08:30:00Z",
"changes": [
{ "type": "relay", "indexes": [1] }
],
"peripherals": {
"relays": [
{ "index": 1, "on": true }
]
},
"stateUpdatedAt": "2026-07-15T08:30:00Z"
}
}| 字段 | 类型 | 必填 | 说明 |
|---|---|---|---|
type | string | 是 | 固定为 event |
topic | string | 是 | 事件主题 |
data | object | 是 | 事件数据 |
事件不对应某个请求,因此不包含 requestId。WebSocket 事件不提供历史回放;断线重连后,应主动查询关键设备状态。
外设字段详见 外设状态说明。
命名规则
type只使用request、reply、eventtopic使用小写英文和点号分段- 写操作统一通过
device.operation.execute,操作名放在operation.name - 事件 topic 表示已发生的事实,例如
device.state.changed、device.connection.online - 时间字段使用 RFC3339 UTC 字符串
- JSON 字段使用 camelCase
- 客户端应忽略暂时无法识别的新增字段
