# API 参考文档

本文档提供 JRSoft Subway Protocol 的完整 API 参考。

## 目录

- [枚举类型](#枚举类型)
- [接口定义](#接口定义)
- [类型别名](#类型别名)
- [工厂函数](#工厂函数)
- [验证函数](#验证函数)
- [类型守卫](#类型守卫)

## 枚举类型

### MessageType

消息类型枚举，定义所有支持的消息类型。

```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'
}
```

### ClientType

客户端类型枚举。

```typescript
export enum ClientType {
  DEVICE = 'DEVICE',    // 终端设备
  BACKEND = 'BACKEND',  // 后端服务
  EDGE = 'EDGE',        // 边缘节点
  GATEWAY = 'GATEWAY'   // 网关服务
}
```

### CommandType

命令类型枚举。

```typescript
export enum CommandType {
  SIMPLE = 'SIMPLE',     // 简单命令（单次响应）
  BATCH = 'BATCH',       // 批量命令（多设备）
  COMPLEX = 'COMPLEX'    // 复杂命令（多次响应）
}
```

### OperationType

操作类型枚举。

```typescript
export enum OperationType {
  READ = 'READ',    // 读取操作
  WRITE = 'WRITE'   // 写入操作
}
```

### Priority

优先级枚举。

```typescript
export enum Priority {
  LOW = 'LOW',
  NORMAL = 'NORMAL',
  HIGH = 'HIGH',
  CRITICAL = 'CRITICAL'
}
```

### CommandStatus

命令状态枚举。

```typescript
export enum CommandStatus {
  COMPLETED = 'COMPLETED',      // 已完成
  FAILED = 'FAILED',            // 失败
  TIMEOUT = 'TIMEOUT',          // 超时
  CANCELLED = 'CANCELLED',      // 已取消
  IN_PROGRESS = 'IN_PROGRESS'   // 执行中
}
```

### ProgressStatus

进度状态枚举。

```typescript
export enum ProgressStatus {
  PENDING = 'PENDING',
  IN_PROGRESS = 'IN_PROGRESS',
  PAUSED = 'PAUSED',
  COMPLETED = 'COMPLETED',
  FAILED = 'FAILED',
  CANCELLED = 'CANCELLED'
}
```

### ProgressPhase

进度阶段枚举。

```typescript
export enum ProgressPhase {
  DOWNLOAD = 'DOWNLOAD',      // 下载
  DECOMPRESS = 'DECOMPRESS',  // 解压
  PREPROCESS = 'PREPROCESS',  // 预处理
  FRAMES = 'FRAMES',          // 创建帧
  UPLOAD = 'UPLOAD',          // 上传
  STATS = 'STATS'             // 统计
}
```

### ReportLevel

日志级别枚举。

```typescript
export enum ReportLevel {
  DEBUG = 'DEBUG',
  INFO = 'INFO',
  WARNING = 'WARNING',
  ERROR = 'ERROR',
  CRITICAL = 'CRITICAL'
}
```

### ProgramType

程序类型枚举。

```typescript
export enum ProgramType {
  DYNAMIC = 'DYNAMIC',  // 动态节目
  STATIC = 'STATIC'     // 静态节目
}
```

### ProgramDirection

程序方向枚举。

```typescript
export enum ProgramDirection {
  LEFT_TO_RIGHT = 'LEFT_TO_RIGHT',
  RIGHT_TO_LEFT = 'RIGHT_TO_LEFT'
}
```

## 接口定义

### BaseMessage

所有消息的基础接口。

```typescript
export interface BaseMessage {
  type: MessageType;     // 消息类型
  timestamp: string;     // ISO 8601 时间戳
  version: string;       // 协议版本，固定 "1.0"
}
```

### RegisterMessage

客户端注册消息。

```typescript
export interface RegisterMessage extends BaseMessage {
  type: MessageType.REGISTER;
  clientId: string;              // 客户端唯一标识
  clientType: ClientType;        // 客户端类型
  clientInfo?: ClientInfo;       // 客户端信息（可选）
  edgeInfo?: EdgeInfo;          // Edge 信息（设备通过 Edge 注册时）
}
```

### RegisterAckMessage

注册确认消息。

```typescript
export interface RegisterAckMessage extends BaseMessage {
  type: MessageType.REGISTER_ACK;
  clientId: string;
  success: boolean;
  sessionId?: string;            // 会话ID（成功时）
  error?: {
    code: string;
    message: string;
  };
  serverInfo?: {
    version: string;
    capabilities: string[];
    currentLoad?: number;
    maxClients?: number;
  };
}
```

### CommandMessage

命令请求消息。

```typescript
export interface CommandMessage extends BaseMessage {
  type: MessageType.COMMAND;
  requestRef: string;            // 请求引用ID
  targetClientId: string;        // 目标客户端ID
  command: Command;              // 命令详情
  priority: Priority;            // 优先级
  timeout: number;               // 超时时间（毫秒）
  retryCount?: number;           // 重试次数
  callback: string;              // 回调URL
  metadata?: Record<string, any>; // 元数据
}
```

### CommandResponseMessage

命令响应消息。

```typescript
export interface CommandResponseMessage extends BaseMessage {
  type: MessageType.COMMAND_RESPONSE;
  requestRef: string;            // 原始请求引用
  status: CommandStatus;         // 执行状态
  result?: CommandResult;        // 执行结果
  report?: ReportMessage;        // 日志信息
  executionTime?: number;        // 执行时间（毫秒）
}
```

### ProgressUpdateMessage

进度更新消息。

```typescript
export interface ProgressUpdateMessage extends BaseMessage {
  type: MessageType.PROGRESS_UPDATE;
  requestRef: string;
  status: ProgressStatus;
  phase: ProgressPhase | string;  // 支持自定义阶段
  progress: number;               // 0-100
  sourceType: 'COMMAND' | 'SYSTEM';
  context?: ProgramContext;       // 程序上下文
  command?: DeviceOperationRecord; // 设备操作记录
  report?: ReportMessage;         // 日志信息
}
```

### ErrorMessage

错误消息。

```typescript
export interface ErrorMessage extends BaseMessage {
  type: MessageType.ERROR;
  code: string;                   // 错误代码
  message: string;                // 错误描述
  severity?: string;              // 严重级别
  category?: string;              // 错误类别
  context?: any;                  // 错误上下文
  retryable?: boolean;            // 是否可重试
}
```

### 辅助接口

#### ClientInfo

```typescript
export interface ClientInfo {
  name?: string;
  version?: string;
  platform?: string;
  capabilities?: string[];
  deviceType?: string;
  description?: string;
  metadata?: Record<string, any>;
}
```

#### EdgeInfo

```typescript
export interface EdgeInfo {
  edgeId: string;
  edgeVersion?: string;
  connectionTime?: string;
}
```

#### Command

```typescript
export type Command = SpecificCommand | GenericCommand;

export interface GenericCommand {
  commandType: CommandType;
  commandCode: string;
  deviceType?: string;
  deviceId?: number | string;
  operationType?: OperationType;
  parameters?: Record<string, any>;
}
```

#### CommandResult

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

#### ReportMessage

```typescript
export interface ReportMessage {
  level: ReportLevel;
  message: string;
  code?: string;
  data?: Record<string, any>;
}
```

#### ProgramContext

```typescript
export interface ProgramContext {
  taskId: string;
  programId: string;
  programName: string;
  programNo: number;
  programType: ProgramType;
}
```

#### DeviceOperationRecord

```typescript
export interface DeviceOperationRecord {
  commandType: CommandType;
  commandCode: string;
  deviceType: string;
  deviceId: number | string;
  operationType: OperationType;
  result?: Record<string, any>;
}
```

## 工厂函数

### createSimpleCommand

创建简单命令。

```typescript
function createSimpleCommand(options: {
  requestRef: string;
  targetClientId: string;
  commandCode: string;
  deviceType: string;
  deviceId: number | string;
  operationType: OperationType;
  parameters?: Record<string, any>;
  priority?: Priority;
  timeout?: number;
  callback: string;
}): CommandMessage
```

**示例：**

```typescript
const command = createSimpleCommand({
  requestRef: 'req-123',
  targetClientId: 'td-01',
  commandCode: 'SET_BRIGHTNESS',
  deviceType: 'screen',
  deviceId: 1,
  operationType: OperationType.WRITE,
  parameters: { brightness: 80 },
  callback: 'http://backend/callback'
});
```

### createBatchCommand

创建批量命令。

```typescript
function createBatchCommand(options: {
  requestRef: string;
  targetClientId: string;
  commandCode: string;
  deviceType: string;
  deviceId: string;  // 范围字符串，如 "1-10,20,30-40"
  operationType: OperationType;
  parameters?: Record<string, any>;
  priority?: Priority;
  timeout?: number;
  callback: string;
}): CommandMessage
```

### createComplexCommand

创建复杂命令。

```typescript
function createComplexCommand(options: {
  requestRef: string;
  targetClientId: string;
  commandCode: string;
  parameters?: Record<string, any>;
  priority?: Priority;
  timeout?: number;
  callback: string;
}): CommandMessage
```

### 强类型命令工厂

基于 C# 模型生成的强类型命令工厂。

```typescript
// LED 开关命令
function createLedSwitchCommand(
  requestRef: string,
  targetClientId: string,
  deviceId: number,
  switch: 'ON' | 'OFF',
  operationType: 'read' | 'write'
): CommandMessage

// 更多强类型命令...
```

## 验证函数

### validateMessage

验证消息基本结构。

```typescript
function validateMessage(message: any): message is BaseMessage
```

### validateRegisterMessage

验证注册消息。

```typescript
function validateRegisterMessage(message: any): message is RegisterMessage
```

### validateCommandMessage

验证命令消息。

```typescript
function validateCommandMessage(message: any): message is CommandMessage
```

## 类型守卫

### 消息类型守卫

```typescript
function isRegisterMessage(msg: any): msg is RegisterMessage
function isRegisterAckMessage(msg: any): msg is RegisterAckMessage
function isUnregisterMessage(msg: any): msg is UnregisterMessage
function isUnregisterAckMessage(msg: any): msg is UnregisterAckMessage
function isHeartbeatMessage(msg: any): msg is HeartbeatMessage
function isHeartbeatAckMessage(msg: any): msg is HeartbeatAckMessage
function isCommandMessage(msg: any): msg is CommandMessage
function isCommandResponseMessage(msg: any): msg is CommandResponseMessage
function isProgramMessage(msg: any): msg is ProgramMessage
function isProgramResponseMessage(msg: any): msg is ProgramResponseMessage
function isProgressUpdateMessage(msg: any): msg is ProgressUpdateMessage
function isErrorMessage(msg: any): msg is ErrorMessage
```

**使用示例：**

```typescript
const message = JSON.parse(websocketData);

if (isCommandMessage(message)) {
  // TypeScript 知道 message 是 CommandMessage 类型
  console.log(message.requestRef);
  console.log(message.command.commandCode);
}
```

## 常量

### 协议版本

```typescript
export const PROTOCOL_VERSION = '1.0';
```

### 默认值

```typescript
export const DEFAULT_TIMEOUT = 30000;        // 30秒
export const DEFAULT_PRIORITY = Priority.NORMAL;
export const HEARTBEAT_INTERVAL = 30000;    // 30秒
export const HEARTBEAT_TIMEOUT = 90000;     // 90秒
```

## 错误代码

### 设备错误

- `DEVICE_OFFLINE` - 设备离线
- `DEVICE_NOT_FOUND` - 设备不存在
- `DEVICE_BUSY` - 设备忙
- `DEVICE_ERROR` - 设备内部错误

### 命令错误

- `COMMAND_TIMEOUT` - 命令超时
- `COMMAND_INVALID` - 无效命令
- `COMMAND_FAILED` - 命令执行失败
- `COMMAND_CANCELLED` - 命令被取消

### 协议错误

- `PROTOCOL_INVALID` - 消息格式错误
- `PROTOCOL_VERSION` - 版本不兼容
- `PROTOCOL_SEQUENCE` - 消息顺序错误

### 系统错误

- `SYSTEM_OVERLOAD` - 系统过载
- `SYSTEM_MAINTENANCE` - 系统维护
- `SYSTEM_ERROR` - 内部错误