ws-native.controller.ts 2.36 KB
import { Controller, Post, Body, Get } from '@nestjs/common';
import { WsNativeService } from './ws-native.service';
import { WsMessageType } from '../../common/enums';

@Controller('ws-native')
export class WsNativeController {
  constructor(private readonly wsNativeService: WsNativeService) {}

  /**
   * 获取在线设备列表
   */
  @Get('online-devices')
  getOnlineDevices() {
    return {
      devices: this.wsNativeService.getOnlineDevices(),
      count: this.wsNativeService.getOnlineDevices().length,
    };
  }

  /**
   * 发送消息给指定设备
   */
  @Post('send-to-device')
  sendToDevice(@Body() body: { deviceId: string; message: any }) {
    const { deviceId, message } = body;
    const sent = this.wsNativeService.sendToDevice(deviceId, {
      type: WsMessageType.Private,
      data: message,
    });
    return {
      success: sent,
      message: sent ? 'Message sent' : 'Device not found or offline',
    };
  }

  /**
   * 发送指令给客户端 - 请求日志
   */
  @Post('request-logs')
  requestLogs(@Body() body: { deviceId: string; logType?: string }) {
    const result = this.wsNativeService.requestLogs(body.deviceId, body.logType);
    return {
      ...result,
      message: result.success ? 'Log request sent' : 'Device not found or offline',
    };
  }

  /**
   * 发送指令给客户端 - 请求设备信息
   */
  @Post('request-device-info')
  requestDeviceInfo(@Body() body: { deviceId: string }) {
    const result = this.wsNativeService.requestDeviceInfo(body.deviceId);
    return {
      ...result,
      message: result.success ? 'Device info request sent' : 'Device not found or offline',
    };
  }

  /**
   * 发送自定义指令给客户端
   */
  @Post('send-command')
  sendCommand(@Body() body: { deviceId: string; command: string; params?: any }) {
    const result = this.wsNativeService.sendCommand(body.deviceId, body.command, body.params);
    return {
      ...result,
      message: result.success ? 'Command sent' : 'Device not found or offline',
    };
  }

  /**
   * 广播消息给所有在线设备
   */
  @Post('broadcast')
  broadcast(@Body() body: { message: any }) {
    this.wsNativeService.broadcast({
      type: WsMessageType.System,
      data: body.message,
    });
    return {
      success: true,
      message: 'Broadcast sent',
      recipients: this.wsNativeService.getOnlineDevices().length,
    };
  }
}