# Complex 命令执行流程详解

## 概述

Complex 类型命令是 JRSoft Subway 协议中用于处理需要持续响应的场景，如健康检查、监播数据导出、系统日志收集等。

### 核心特性

1. **持续响应** - 设备可以在执行过程中发送多个 `progress_update` 消息
2. **阶段报告** - 每个进度更新可以报告不同阶段的结果
3. **结构化日志** - 使用 ReportMessage 提供不同级别的日志信息
4. **最终结束** - 必须发送 `command_response` 标志命令执行结束

### 适用场景

- **健康检查** - 逐步检查各个子系统状态
- **监播数据导出** - 分批导出大量数据
- **系统日志收集** - 持续收集和报告日志
- **配置同步** - 逐步同步多个设备配置
- **状态监控** - 实时监控设备状态变化

## 执行流程

### 完整执行流程

```
┌─────────┐    ┌─────────┐    ┌──────┐    ┌────────┐
│ Backend │    │ Gateway │    │ Edge │    │ Device │
└────┬────┘    └────┬────┘    └───┬──┘    └────┬───┘
     │              │              │            │
     │ 1. command   │              │            │
     │ (complex)    │              │            │
     ├─────────────►│              │            │
     │              │              │            │
     │              │ 2. route to  │            │
     │              │    edge01    │            │
     │              ├─────────────►│            │
     │              │              │            │
     │              │              │ 3. forward │
     │              │              │   to td01  │
     │              │              ├───────────►│
     │              │              │            │
     │              │              │            │ 4. start
     │              │              │            │ execution
     │              │              │            ├─┐
     │              │              │            │ │
     │              │              │            │◄┘
     │              │              │            │
     │              │              │ 5. progress│
     │              │              │  (phase 1) │
     │              │              │◄───────────┤
     │              │              │            │
     │              │ 6. progress  │            │
     │              │◄─────────────┤            │
     │              │              │            │
     │ 7. progress  │              │            │
     │◄─────────────┤              │            │
     │              │              │            │
     │              │              │ 8. progress│
     │              │              │  (phase 2) │
     │              │              │◄───────────┤
     │              │              │            │
     │              │ 9. progress  │            │
     │              │◄─────────────┤            │
     │              │              │            │
     │ 10. progress │              │            │
     │◄─────────────┤              │            │
     │              │              │            │
     │              │              │    ...     │
     │              │              │            │
     │              │              │ 11. final  │
     │              │              │   response │
     │              │              │◄───────────┤
     │              │              │            │
     │              │ 12. response │            │
     │              │◄─────────────┤            │
     │              │              │            │
     │ 13. response │              │            │
     │◄─────────────┤              │            │
     │              │              │            │
```

## 典型应用场景

### 1. 健康检查（HealthCheck）

```json
{
  "type": "COMMAND",
  "requestRef": "health-check-001",
  "targetClientId": "td-01",
  "command": {
    "commandType": "COMPLEX",
    "commandCode": "HealthCheck",
    "parameters": {
      "switchStatus": true,          // 检查开关状态
      "switchConfigInformation": true, // 检查配置信息
      "synchronizerStatus": true,    // 检查同步器状态
      "pillarStatus": true          // 检查立柱状态
    }
  },
  "priority": "NORMAL",
  "timeout": 30000
}
```

### 2. 监播数据导出

```json
{
  "type": "COMMAND",
  "requestRef": "monitor-export-001",
  "targetClientId": "screen-01",
  "command": {
    "commandType": "COMPLEX",
    "commandCode": "ExportMonitorData",
    "parameters": {
      "startTime": "2024-01-01T00:00:00Z",
      "endTime": "2024-01-20T23:59:59Z",
      "format": "csv",
      "includeScreenshots": true
    }
  },
  "priority": "LOW",
  "timeout": 300000  // 5分钟
}
```

### 3. 系统日志收集

```json
{
  "type": "COMMAND",
  "requestRef": "log-collect-001",
  "targetClientId": "td-01",
  "command": {
    "commandType": "COMPLEX",
    "commandCode": "CollectSystemLogs",
    "parameters": {
      "logLevel": "Udebug",
      "maxLines": 10000,
      "components": ["network", "hardware", "application"]
    }
  },
  "priority": "NORMAL",
  "timeout": 60000
}
```

## 进度更新消息

### 健康检查的进度更新

```json
// 第一个进度：检查开关状态
{
  "type": "PROGRESS_UPDATE",
  "requestRef": "health-check-001",
  "status": "IN_PROGRESS",
  "phase": "checking_switch",
  "progress": 25,
  "sourceType": "COMMAND",
  "command": {
    "commandType": "SIMPLE",
    "commandCode": "READ_SWITCH_STATUS",
    "deviceType": "controller",
    "deviceId": 1,
    "operationType": "READ",
    "result": {
      "switchCount": 8,
      "activeCount": 6,
      "inactiveCount": 2,
      "switches": [
        {"id": 1, "status": "on", "lastChange": "2024-01-20T08:00:00Z"},
        {"id": 2, "status": "on", "lastChange": "2024-01-20T08:00:00Z"},
        // ...
      ]
    }
  },
  "report": {
    "level": "INFO",
    "message": "开关状态检查完成"
  },
  "timestamp": "2024-01-20T10:00:01Z",
  "version": "1.0"
}

// 第二个进度：读取配置信息
{
  "type": "PROGRESS_UPDATE",
  "requestRef": "health-check-001",
  "status": "IN_PROGRESS",
  "phase": "reading_config",
  "progress": 50,
  "sourceType": "COMMAND",
  "command": {
    "commandType": "SIMPLE",
    "commandCode": "READ_CONFIG",
    "deviceType": "controller",
    "deviceId": 1,
    "operationType": "READ",
    "result": {
      "version": "2.1.0",
      "lastUpdate": "2024-01-15T10:00:00Z",
      "parameters": {
        "brightness": 80,
        "colorMode": "RGB",
        "refreshRate": 60
      }
    }
  },
  "report": {
    "level": "INFO",
    "message": "配置信息读取完成"
  },
  "timestamp": "2024-01-20T10:00:02Z",
  "version": "1.0"
}

// 更多进度更新...
```

### 监播数据导出的进度更新

```json
{
  "type": "PROGRESS_UPDATE",
  "requestRef": "monitor-export-001",
  "status": "IN_PROGRESS",
  "phase": "exporting_data",
  "progress": 30,
  "sourceType": "SYSTEM",
  "report": {
    "level": "INFO",
    "message": "正在导出第3天的数据，共20天",
    "data": {
      "currentDay": 3,
      "totalDays": 20,
      "recordsExported": 15000,
      "estimatedTotal": 100000
    }
  },
  "timestamp": "2024-01-20T10:05:00Z",
  "version": "1.0"
}
```

## 最终响应

### 成功响应

```json
{
  "type": "COMMAND_RESPONSE",
  "requestRef": "health-check-001",
  "status": "COMPLETED",
  "result": {
    "deviceType": "controller",
    "deviceId": "td-01",
    "commandCode": "HealthCheck",
    "operationType": "READ",
    "data": {
      "summary": "健康检查完成",
      "overallStatus": "healthy",
      "checksPerformed": 4,
      "checksPassed": 4,
      "checksFailed": 0,
      "details": {
        "switchStatus": "passed",
        "configStatus": "passed",
        "synchronizerStatus": "passed",
        "pillarStatus": "passed"
      }
    }
  },
  "executionTime": 5200,
  "timestamp": "2024-01-20T10:00:05Z",
  "version": "1.0"
}
```

### 部分失败响应

```json
{
  "type": "COMMAND_RESPONSE",
  "requestRef": "health-check-001",
  "status": "COMPLETED",
  "result": {
    "deviceType": "controller",
    "deviceId": "td-01",
    "commandCode": "HealthCheck",
    "operationType": "READ",
    "data": {
      "summary": "健康检查完成，发现问题",
      "overallStatus": "Uwarning",
      "checksPerformed": 4,
      "checksPassed": 3,
      "checksFailed": 1,
      "details": {
        "switchStatus": "passed",
        "configStatus": "passed",
        "synchronizerStatus": "Ufailed",
        "pillarStatus": "passed"
      },
      "errors": [
        {
          "component": "synchronizer",
          "Uerror": "Synchronizer offline",
          "timestamp": "2024-01-20T10:00:03Z"
        }
      ]
    }
  },
  "report": {
    "level": "WARNING",
    "message": "健康检查发现1个问题",
    "code": "HEALTH_CHECK_WARNING"
  },
  "executionTime": 5200,
  "timestamp": "2024-01-20T10:00:05Z",
  "version": "1.0"
}
```

## 设备端实现指南

### 基本实现模式

```javascript
class ComplexCommandHandler {
  async handleHealthCheck(command, progressCallback) {
    const totalSteps = 4;
    let currentStep = 0;
    const results = {};
    
    try {
      // Step 1: 检查开关状态
      if (command.parameters.switchStatus) {
        currentStep++;
        const switchResult = await this.checkSwitchStatus();
        
        await progressCallback({
          phase: 'checking_switch',
          progress: (currentStep / totalSteps) * 100,
          command: {
            commandType: 'simple',
            commandCode: 'READ_SWITCH_STATUS',
            deviceType: 'controller',
            deviceId: this.deviceId,
            operationType: 'read',
            result: switchResult
          },
          report: {
            level: 'info',
            message: '开关状态检查完成'
          }
        });
        
        results.switchStatus = switchResult;
      }
      
      // Step 2: 读取配置信息
      if (command.parameters.switchConfigInformation) {
        currentStep++;
        const configResult = await this.readConfiguration();
        
        await progressCallback({
          phase: 'reading_config',
          progress: (currentStep / totalSteps) * 100,
          command: {
            commandType: 'simple',
            commandCode: 'READ_CONFIG',
            deviceType: 'controller',
            deviceId: this.deviceId,
            operationType: 'read',
            result: configResult
          },
          report: {
            level: 'info',
            message: '配置信息读取完成'
          }
        });
        
        results.configStatus = configResult;
      }
      
      // Step 3 & 4: 继续其他检查...
      
      // 返回最终结果
      return {
        summary: '健康检查完成',
        overallStatus: 'healthy',
        checksPerformed: currentStep,
        checksPassed: currentStep,
        checksFailed: 0,
        details: results
      };
      
    } catch (error) {
      // 错误处理
      await progressCallback({
        phase: 'error',
        progress: (currentStep / totalSteps) * 100,
        status: 'failed',
        log: {
          level: 'error',
          message: error.message,
          code: error.code
        }
      });
      
      throw error;
    }
  }
}
```

### 进度回调函数

```javascript
async function sendProgressUpdate(requestRef, progressData) {
  const progressUpdate = {
    type: 'progress_update',
    requestRef,
    status: progressData.status || 'in_progress',
    phase: progressData.phase,
    progress: progressData.progress,
    sourceType: progressData.command ? 'command' : 'system',
    command: progressData.command,
    report: progressData.report,
    timestamp: new Date().toISOString(),
    version: '1.0'
  };
  
  await this.sendToEdge(progressUpdate);
}
```

## 最佳实践

### 1. 进度粒度控制

- 避免发送过多的进度更新（建议每个阶段一次）
- 重要状态变化时才发送更新
- 使用有意义的 phase 名称

### 2. 错误处理

```javascript
// 遇到非致命错误，继续执行但记录警告
if (minorError) {
  await progressCallback({
    phase: currentPhase,
    progress: currentProgress,
    log: {
      level: 'warning',
      message: '检测到非关键问题',
      code: 'MINOR_ERROR',
      data: { error: minorError.message }
    }
  });
  // 继续执行
}

// 遇到致命错误，立即停止并报告
if (fatalError) {
  await progressCallback({
    phase: currentPhase,
    progress: currentProgress,
    status: 'failed',
    log: {
      level: 'error',
      message: '致命错误，检查终止',
      code: 'FATAL_ERROR',
      data: { error: fatalError.message }
    }
  });
  throw fatalError;
}
```

### 3. 超时处理

```javascript
// 设置整体超时
const timeoutHandle = setTimeout(() => {
  throw new Error('Complex command timeout');
}, command.timeout || 30000);

try {
  // 执行命令
  const result = await this.executeComplexCommand(command);
  clearTimeout(timeoutHandle);
  return result;
} catch (error) {
  clearTimeout(timeoutHandle);
  throw error;
}
```

### 4. 资源管理

```javascript
// 确保资源正确释放
let resources = null;
try {
  resources = await this.allocateResources();
  // 执行操作
  return await this.performOperation(resources);
} finally {
  if (resources) {
    await this.releaseResources(resources);
  }
}
```

## 与 Simple 命令的区别

| 特性 | Simple 命令 | Complex 命令 |
|------|------------|-------------|
| 响应次数 | 一次 | 多次（进度更新 + 最终响应） |
| 适用场景 | 快速操作 | 长时间运行操作 |
| 进度反馈 | 无 | 有（progress_update） |
| 实现复杂度 | 低 | 中等 |
| 超时设置 | 通常较短 | 通常较长 |

## 总结

Complex 命令为需要持续反馈的操作提供了标准化的实现模式。通过 progress_update 消息，可以实时向用户展示操作进度，提供更好的用户体验。设备端实现时需要注意：

1. 合理划分执行阶段
2. 及时发送进度更新
3. 正确处理错误情况
4. 最终必须发送 command_response

这种设计既保证了协议的灵活性，又维持了实现的简洁性。