ws-native.service.ts 5.13 KB
import { Injectable, Logger } from '@nestjs/common';
import { Server } from 'ws';
import { WsMessageType, WsStatus } from '../../common/enums';

@Injectable()
export class WsNativeService {
  private readonly logger = new Logger(WsNativeService.name);
  public server: Server;
  
  // 存储客户端连接 deviceId -> client
  private clients: Map<string, any> = new Map();
  
  // 存储客户端信息 client -> { deviceId, token }
  private clientInfo: WeakMap<any, { deviceId: string; token: string }> = new WeakMap();

  /**
   * 用户登录
   */
  login(client: any, token: string, deviceId: string) {
    this.logger.log(`Device ${deviceId} logged in`);
    
    // 如果该设备已经连接,断开旧连接
    const existingClient = this.clients.get(deviceId);
    if (existingClient && existingClient !== client) {
      this.logger.warn(`Device ${deviceId} already connected, closing old connection`);
      existingClient.close();
    }

    // 保存新连接
    this.clients.set(deviceId, client);
    this.clientInfo.set(client, { deviceId, token });

    // 发送连接成功消息
    this.sendToClient(client, {
      type: WsMessageType.System,
      data: {
        status: WsStatus.Online,
        message: 'Connected successfully',
        deviceId,
      },
    });

    return {
      status: WsStatus.Online,
      message: 'Connected',
      device_id: deviceId,
    };
  }

  /**
   * 用户登出
   */
  logout(client: any) {
    const info = this.clientInfo.get(client);
    if (info) {
      this.logger.log(`Device ${info.deviceId} logged out`);
      this.clients.delete(info.deviceId);
      this.clientInfo.delete(client);
    }
  }

  /**
   * 处理客户端消息
   */
  onMessage(client: any, message: any) {
    const info = this.clientInfo.get(client);
    if (!info) {
      this.logger.warn('Received message from unknown client');
      return;
    }

    this.logger.log(`Received message from ${info.deviceId}: ${JSON.stringify(message)}`);

    // 根据消息类型处理
    const { type, data, requestId } = message;

    switch (type) {
      case 'response':
        // 客户端响应服务端指令
        this.handleClientResponse(info.deviceId, data, requestId);
        break;
      case 'log_upload':
        // 客户端上传日志
        this.handleLogUpload(info.deviceId, data);
        break;
      case 'heartbeat':
        // 心跳
        this.sendToClient(client, {
          type: 'heartbeat',
          data: { timestamp: Date.now() },
        });
        break;
      default:
        this.logger.warn(`Unknown message type: ${type}`);
    }
  }

  /**
   * 处理客户端响应
   */
  private handleClientResponse(deviceId: string, data: any, requestId: string) {
    this.logger.log(`Device ${deviceId} response for request ${requestId}: ${JSON.stringify(data)}`);
    // 这里可以触发事件或回调,通知等待响应的服务
  }

  /**
   * 处理日志上传
   */
  private handleLogUpload(deviceId: string, data: any) {
    this.logger.log(`Device ${deviceId} uploaded logs: ${JSON.stringify(data)}`);
    // 这里可以保存日志到数据库或文件系统
  }

  /**
   * 发送消息给指定客户端
   */
  sendToClient(client: any, message: any) {
    if (client.readyState === 1) { // WebSocket.OPEN
      client.send(JSON.stringify(message));
    }
  }

  /**
   * 发送消息给指定设备
   */
  sendToDevice(deviceId: string, message: any) {
    const client = this.clients.get(deviceId);
    if (client) {
      this.sendToClient(client, message);
      return true;
    }
    return false;
  }

  /**
   * 广播消息给所有连接的客户端
   */
  broadcast(message: any) {
    const data = JSON.stringify(message);
    this.clients.forEach((client) => {
      if (client.readyState === 1) {
        client.send(data);
      }
    });
  }

  /**
   * 获取在线设备列表
   */
  getOnlineDevices(): string[] {
    return Array.from(this.clients.keys());
  }

  /**
   * 重置所有客户端连接
   */
  resetClients() {
    this.clients.forEach((client) => {
      client.close();
    });
    this.clients.clear();
  }

  /**
   * 发送指令给客户端(带请求ID,用于追踪响应)
   */
  sendCommand(deviceId: string, command: string, params?: any): { success: boolean; requestId?: string } {
    const client = this.clients.get(deviceId);
    if (!client) {
      return { success: false };
    }

    const requestId = `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
    
    this.sendToClient(client, {
      type: 'command',
      requestId,
      data: {
        command,
        params,
        timestamp: Date.now(),
      },
    });

    return { success: true, requestId };
  }

  /**
   * 请求客户端上传日志
   */
  requestLogs(deviceId: string, logType?: string) {
    return this.sendCommand(deviceId, 'get_logs', { logType: logType || 'all' });
  }

  /**
   * 请求客户端设备信息
   */
  requestDeviceInfo(deviceId: string) {
    return this.sendCommand(deviceId, 'get_device_info');
  }

  /**
   * 请求客户端执行操作
   */
  requestAction(deviceId: string, action: string, params?: any) {
    return this.sendCommand(deviceId, action, params);
  }
}