# 消息类型详解

本文档详细介绍 JRSoft Subway WebSocket 协议中的所有消息类型。

## 消息类型总览

协议包含以下消息类型：

| 消息类型 | 方向 | 说明 |
|---------|------|------|
| **连接管理** |
| REGISTER | Client → Server | 客户端注册 |
| REGISTER_ACK | Server → Client | 注册确认 |
| UNREGISTER | Client → Server | 客户端注销 |
| UNREGISTER_ACK | Server → Client | 注销确认 |
| **心跳保活** |
| HEARTBEAT | Client → Server | 心跳请求 |
| HEARTBEAT_ACK | Server → Client | 心跳确认 |
| **命令执行** |
| COMMAND | Client → Client | 命令请求 |
| COMMAND_RESPONSE | Client → Client | 命令响应 |
| **程序管理** |
| PROGRAM | Client → Client | 程序上传请求 |
| PROGRAM_RESPONSE | Client → Client | 程序上传响应 |
| **进度报告** |
| PROGRESS_UPDATE | Client → Client | 进度更新 |
| **错误处理** |
| ERROR | Server → Client | 错误消息 |

## 消息类型枚举

```typescript
export enum MessageType {
  // 连接管理
  REGISTER = 'REGISTER',                   // 客户端注册
  REGISTER_ACK = 'REGISTER_ACK',          // 注册确认
  UNREGISTER = 'UNREGISTER',              // 客户端注销
  UNREGISTER_ACK = 'UNREGISTER_ACK',      // 注销确认
  
  // 心跳
  HEARTBEAT = 'HEARTBEAT',                // 心跳请求
  HEARTBEAT_ACK = 'HEARTBEAT_ACK',        // 心跳确认
  
  // 命令执行
  COMMAND = 'COMMAND',                    // 命令请求
  COMMAND_RESPONSE = 'COMMAND_RESPONSE',  // 命令响应
  
  // 程序管理
  PROGRAM = 'PROGRAM',                    // 程序上传请求
  PROGRAM_RESPONSE = 'PROGRAM_RESPONSE',  // 程序上传响应
  
  // 进度更新
  PROGRESS_UPDATE = 'PROGRESS_UPDATE',    // 进度更新
  
  // 错误
  ERROR = 'ERROR'                         // 错误消息
}
```

## 基础消息结构

所有消息都继承自 BaseMessage：

```typescript
interface BaseMessage {
  type: MessageType;
  timestamp: string;    // ISO 8601 格式
  version: string;      // 协议版本，如 "1.0"
}
```

## 1. 注册消息 (register)

客户端连接后必须立即发送注册消息。

### 消息结构

```typescript
interface RegisterMessage extends BaseMessage {
  type: MessageType.REGISTER;
  clientId: string;
  clientType: ClientType;
  clientInfo?: {
    name?: string;
    version?: string;
    description?: string;
    capabilities?: string[];
    metadata?: Record<string, any>;
  };
}
```

### 示例

```json
{
  "type": "REGISTER",
  "clientId": "edge-001",
  "clientType": "EDGE",
  "clientInfo": {
    "name": "隧道出口 Edge 节点",
    "version": "1.0.0",
    "capabilities": ["device-proxy", "batch-command"],
    "metadata": {
      "location": "tunnel-exit-1",
      "deviceCount": 50
    }
  },
  "timestamp": "2024-01-20T10:00:00Z",
  "version": "1.0"
}
```

### Edge 设备注册

当设备通过 Edge 节点注册时，会包含额外的 Edge 信息：

```json
{
  "type": "REGISTER",
  "clientId": "td-01",
  "clientType": "DEVICE",
  "edgeInfo": {
    "edgeId": "edge-001",
    "edgeVersion": "1.0.0",
    "connectionTime": "2024-01-20T09:59:00Z"
  },
  "clientInfo": {
    "version": "1.0.0",
    "deviceType": "media_player",
    "capabilities": ["play", "stop", "status_report"]
  },
  "timestamp": "2024-01-20T10:00:01Z",
  "version": "1.0"
}
```

## 2. 注册确认消息 (register_ack)

服务器响应客户端注册请求。

### 消息结构

```typescript
interface RegisterAckMessage extends BaseMessage {
  type: MessageType.REGISTER_ACK;
  clientId: string;
  success: boolean;
  sessionId?: string;
  error?: {
    code: string;
    message: string;
  };
  serverInfo?: {
    version: string;
    capabilities: string[];
    currentLoad?: number;
    maxClients?: number;
  };
}
```

### 示例 - 成功注册

```json
{
  "type": "REGISTER_ACK",
  "clientId": "edge-001",
  "success": true,
  "sessionId": "sess-123456",
  "serverInfo": {
    "version": "1.0.0",
    "capabilities": ["device_proxy", "batch_command", "status_report"],
    "currentLoad": 45,
    "maxClients": 1000
  },
  "timestamp": "2024-01-20T10:00:01Z",
  "version": "1.0"
}
```

### 示例 - 注册失败

```json
{
  "type": "REGISTER_ACK",
  "clientId": "edge-001",
  "success": false,
  "error": {
    "code": "DUPLICATE_CLIENT_ID",
    "message": "客户端ID已存在"
  },
  "timestamp": "2024-01-20T10:00:01Z",
  "version": "1.0"
}
```

## 3. 注销消息 (unregister)

客户端主动断开连接前发送。

### 消息结构

```typescript
interface UnregisterMessage extends BaseMessage {
  type: MessageType.UNREGISTER;
  clientId: string;
  reason?: string;
}
```

### 示例

```json
{
  "type": "UNREGISTER",
  "clientId": "edge-001",
  "reason": "shutdown",
  "timestamp": "2024-01-20T11:00:00Z",
  "version": "1.0"
}
```

## 4. 注销确认消息 (unregister_ack)

服务器确认客户端注销。

### 消息结构

```typescript
interface UnregisterAckMessage extends BaseMessage {
  type: MessageType.UNREGISTER_ACK;
  clientId: string;
  success: boolean;
  cleanupInfo?: {
    messagesProcessed: number;
    pendingMessages: number;
    connectionDuration: number;
  };
}
```

### 示例

```json
{
  "type": "UNREGISTER_ACK",
  "clientId": "edge-001",
  "success": true,
  "cleanupInfo": {
    "messagesProcessed": 1520,
    "pendingMessages": 0,
    "connectionDuration": 3600
  },
  "timestamp": "2024-01-20T11:00:00Z",
  "version": "1.0"
}
```

## 5. 心跳消息 (heartbeat)

用于保持连接活跃，检测连接状态。

### 消息结构

```typescript
interface HeartbeatMessage extends BaseMessage {
  type: MessageType.HEARTBEAT;
  clientId: string;
  sequence: number;
  clientTime: string;
}
```

### 示例

```json
{
  "type": "HEARTBEAT",
  "clientId": "backend-001",
  "sequence": 123,
  "clientTime": "2024-01-20T10:00:30Z",
  "timestamp": "2024-01-20T10:00:30Z",
  "version": "1.0"
}
```

## 6. 心跳确认消息 (heartbeat_ack)

服务器响应心跳请求。

### 消息结构

```typescript
interface HeartbeatAckMessage extends BaseMessage {
  type: MessageType.HEARTBEAT_ACK;
  clientId: string;
  sequence: number;
  clientTime: string;
  serverTime: string;
  latency?: number;
  serverStatus?: {
    healthy: boolean;
    activeConnections: number;
    messageQueueSize: number;
    cpuUsage?: number;
    memoryUsage?: number;
  };
}
```

### 示例

```json
{
  "type": "HEARTBEAT_ACK",
  "clientId": "backend-001",
  "sequence": 123,
  "clientTime": "2024-01-20T10:00:30Z",
  "serverTime": "2024-01-20T10:00:30.150Z",
  "latency": 15,
  "serverStatus": {
    "healthy": true,
    "activeConnections": 120,
    "messageQueueSize": 45,
    "cpuUsage": 23.5,
    "memoryUsage": 45.2
  },
  "timestamp": "2024-01-20T10:00:30Z",
  "version": "1.0"
}
```

## 7. 错误消息 (error)

用于报告各种错误情况。

### 消息结构

```typescript
interface ErrorMessage extends BaseMessage {
  type: MessageType.ERROR;
  code: string;
  message: string;
  severity?: string;      // low, medium, high, critical
  category?: string;      // device, command, protocol, system
  context?: any;
  retryable?: boolean;
  requestRef?: string;    // 关联的请求引用
}
```

### 常见错误码

- `INVALID_MESSAGE` - 消息格式错误
- `UNAUTHORIZED` - 未授权
- `TARGET_NOT_FOUND` - 目标客户端不存在
- `TIMEOUT` - 操作超时
- `INTERNAL_ERROR` - 内部错误

### 示例

```json
{
  "type": "ERROR",
  "code": "TARGET_NOT_FOUND",
  "message": "目标客户端 device-01 不存在",
  "requestRef": "cmd-123",
  "timestamp": "2024-01-20T10:00:00Z",
  "version": "1.0"
}
```

## 8. 命令消息 (command)

用于发送各种控制命令。

### 消息结构

```typescript
interface CommandMessage extends BaseMessage {
  type: MessageType.COMMAND;
  requestRef: string;
  targetClientId?: string;  // Simple/Complex 命令必需
  command: Command;
  callback?: string;
  priority: Priority;
  timeout: number;
}

interface Command {
  commandType: CommandType;  // simple, batch, complex
  commandCode: string;
  deviceType?: string;
  deviceId?: string | number;
  operationType?: OperationType;
  parameters?: Record<string, any>;
}
```

### 示例 - Simple 命令

```json
{
  "type": "COMMAND",
  "requestRef": "cmd-123",
  "targetClientId": "td-01",
  "command": {
    "commandType": "SIMPLE",
    "commandCode": "SET_BRIGHTNESS",
    "deviceType": "screen",
    "deviceId": 1,
    "operationType": "WRITE",
    "parameters": {
      "brightness": 80
    }
  },
  "priority": "NORMAL",
  "timeout": 5000,
  "timestamp": "2024-01-20T10:00:00Z",
  "version": "1.0"
}
```

## 9. 命令响应消息 (command_response)

命令执行后的响应。

### 消息结构

```typescript
interface CommandResponseMessage extends BaseMessage {
  type: MessageType.COMMAND_RESPONSE;
  requestRef: string;
  status: CommandStatus;
  result?: CommandResult;
  report?: ReportMessage;
  executionTime?: number;
}

interface CommandResult {
  deviceType: string;
  deviceId: string | number;
  commandCode: string;
  operationType: OperationType;
  data: Record<string, any>;
}
```

### 示例 - 成功响应

```json
{
  "type": "COMMAND_RESPONSE",
  "requestRef": "cmd-123",
  "status": "COMPLETED",
  "result": {
    "deviceType": "screen",
    "deviceId": 1,
    "commandCode": "SET_BRIGHTNESS",
    "operationType": "WRITE",
    "data": {
      "previousValue": 60,
      "currentValue": 80
    }
  },
  "executionTime": 150,
  "timestamp": "2024-01-20T10:00:01Z",
  "version": "1.0"
}
```

## 10. 进度更新消息 (progress_update)

用于长时间运行操作的进度报告。

### 消息结构

```typescript
interface ProgressUpdateMessage extends BaseMessage {
  type: MessageType.PROGRESS_UPDATE;
  requestRef: string;
  status: ProgressStatus;
  phase: ProgressPhase | string;  // 支持预定义阶段或自定义阶段
  progress: number;  // 0-100
  sourceType: 'COMMAND' | 'SYSTEM';
  command?: DeviceOperationRecord;
  context?: ProgramContext;
  report?: ReportMessage;
}
```

### 进度阶段

预定义的进度阶段（ProgressPhase）：
- `DOWNLOAD` - 下载文件
- `DECOMPRESS` - 解压文件
- `PREPROCESS` - 预处理
- `FRAMES` - 创建帧
- `UPLOAD` - 上传到设备
- `STATS` - 统计信息

也支持自定义阶段名称，如：
- `"VALIDATE"` - 验证阶段
- `"BACKUP"` - 备份阶段
- `"ROLLBACK"` - 回滚阶段

### 示例 - 批量命令进度

```json
{
  "type": "PROGRESS_UPDATE",
  "requestRef": "batch-123",
  "status": "IN_PROGRESS",
  "phase": "FRAMES",
  "progress": 20,
  "sourceType": "COMMAND",
  "command": {
    "commandType": "SIMPLE",
    "commandCode": "SET_COLOR",
    "deviceType": "pillar",
    "deviceId": 2,
    "operationType": "WRITE",
    "result": {
      "success": true,
      "color": "#FF0000"
    }
  },
  "report": {
    "level": "INFO",
    "message": "光柱 2 颜色设置成功"
  },
  "timestamp": "2024-01-20T10:00:02Z",
  "version": "1.0"
}
```

## 11. 程序上传消息 (program)

用于上传节目内容到设备。

### 消息结构

```typescript
interface ProgramMessage extends BaseMessage {
  type: MessageType.PROGRAM;
  requestRef: string;
  targetClientId: string;
  command: {
    commandCode: string;
    parameters: ProgramParameters;
  };
}

interface ProgramParameters {
  deviceId: string;
  taskId: string;         // Snowflake ID
  programId: string;      // Snowflake ID
  programName: string;
  programNo: number;  // 1-10
  programType: 'DYNAMIC' | 'STATIC';
  width: number;
  height: number;
  direction: 'LEFT_TO_RIGHT' | 'RIGHT_TO_LEFT';
  publishTime?: string;   // 可选，不填则立即生效
  unpublishTime?: string; // 可选，不填则无限期
  downloadUrl: string;
  checksum: string;
  hashAlgorithm: 'SHA256' | 'MD5';
  fileSize?: number;      // 可选，设备下载后可自行获取
}
```

### 示例

```json
{
  "type": "PROGRAM",
  "requestRef": "prog-456",
  "targetClientId": "screen-01",
  "command": {
    "commandCode": "UPLOAD_PROGRAM",
    "parameters": {
      "taskId": "7423847329847329847",
      "programId": "7423847329847329848",
      "programName": "春节促销广告",
      "programNo": 1,
      "programType": "DYNAMIC",
      "fileUrl": "https://storage.example.com/programs/spring-festival.zip",
      "fileHash": "d41d8cd98f00b204e9800998ecf8427e",
      "hashAlgorithm": "MD5",
      "width": 1920,
      "height": 1080,
      "direction": "LEFT_TO_RIGHT",
      "publishTime": "2024-01-20T00:00:00Z",
      "unpublishTime": "2024-02-20T23:59:59Z"
    }
  },
  "timestamp": "2024-01-20T10:00:00Z",
  "version": "1.0"
}
```

## 12. 程序响应消息 (program_response)

节目处理完成后的响应。

### 消息结构

```typescript
interface ProgramResponseMessage extends BaseMessage {
  type: MessageType.PROGRAM_RESPONSE;
  requestRef: string;
  status: 'COMPLETED' | 'FAILED';
  context: ProgramContext;
  report?: ReportMessage;
}
```

### 示例

```json
{
  "type": "PROGRAM_RESPONSE",
  "requestRef": "prog-456",
  "status": "COMPLETED",
  "context": {
    "taskId": "7423847329847329847",
    "programId": "7423847329847329848",
    "programName": "春节促销广告",
    "programNo": 1,
    "programType": "DYNAMIC"
  },
  "report": {
    "level": "INFO",
    "message": "节目上传并部署成功"
  },
  "timestamp": "2024-01-20T10:05:00Z",
  "version": "1.0"
}
```

## 消息验证

所有消息都应该通过验证后再处理：

```typescript
// 使用提供的验证函数
import { validateMessage } from 'jrsoft-subway-protocol';

try {
  const validMessage = validateMessage(rawMessage);
  // 处理验证后的消息
} catch (error) {
  // 处理验证错误
}
```

## 最佳实践

1. **始终验证消息** - 使用提供的验证函数确保消息格式正确
2. **使用类型守卫** - 使用 `isCommandMessage()` 等函数进行类型检查
3. **处理所有消息类型** - 确保您的实现能处理所有可能的消息类型
4. **保持向后兼容** - 使用 version 字段处理协议升级
5. **及时响应** - 特别是心跳消息，应该立即响应

## 相关文档

- [协议规范](./specification.md) - 完整的协议定义
- [命令系统](../02-commands/) - 详细的命令类型说明
- [API 参考](../06-reference/api.md) - 编程接口文档