ws-native.service.ts
5.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
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);
}
}