Ws.uts 12.4 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 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425
import { Logger } from "@/services/logger/LoggerCore.uts";
// import services from "@/services";

import { wsConfig } from "../app.config.uts";
import { normalizeWsUrl, WsMessageType } from "./constants.uts";
import { createDefaultWsCommandRouter, WsCommandContext, WsCommandRouter } from "./workers/CommandHandlers.uts";
import { LiveLogService } from "./workers/handlers/LiveLogService.uts";
import { EMPTY_OBJECT, toObj } from "@/utils/common.uts";

type WsOptions = {
	loginUrl?: string
	onMessage?: (data: UTSJSONObject) => void
	wsUrl?: string
}

export class Ws {
	private deviceId: string = "";
	private isManualClose: boolean = false;
	private isReconnecting: boolean = false;
	private liveLogService = new LiveLogService();
	private logger = Logger.getInstance();
	private loginAddress: string;
	private onMessage: ((data: UTSJSONObject) => void) | null = null;
	private reconnectCount: number = 0;
	private reconnectTimer: null | number = null;
	private router: WsCommandRouter = createDefaultWsCommandRouter();
	private socketTask: null | SocketTask = null;
	private token: string = "";
	private wsAddress: string;
	private heartbeatTimer: null | number = null;

	constructor(options: null | WsOptions = null) {
		this.wsAddress = options?.wsUrl != null ? options.wsUrl as string : wsConfig.wsUrl;
		this.loginAddress = options?.loginUrl != null ? options.loginUrl as string : wsConfig.loginUrl;
		if (options?.onMessage != null) {
			this.onMessage = options.onMessage;
		}
	}

	async close(code: number = 1000, reason: string = "manual close", manual: boolean = true): Promise<void> {
		this.isManualClose = manual;
		this.clearReconnectTimer();
		this.stopHeartbeat(); // ✅ 停止心跳
		this.liveLogService.stop();
		const task = this.socketTask;
		this.socketTask = null;
		if (task == null) {
			return;
		}
		await new Promise<void>((resolve) => {
			task.close({
				code,
				reason,
				complete: () => resolve()
			});
		});
	}

	async connect(): Promise<void> {
		this.isManualClose = false;
		try {
			const loginRes = await this.login();
			const code = `${loginRes.code ?? ""}`;
			if (code != "200" && code != "0") {
				throw new Error(`WebSocket 登录失败 code=${code} response=${JSON.stringify(loginRes)}`);
			}
			const data = toObj(loginRes.data ?? EMPTY_OBJECT);
			if (data == null) {
				throw new Error(`WebSocket 登录返回 data 为空: ${JSON.stringify(loginRes)}`);
			}
			this.deviceId = `${data.id ?? ""}`;
			this.token = `${data.token ?? ""}`;
			if (this.deviceId == "" || this.token == "") {
				throw new Error(`WebSocket 登录返回数据不完整: ${JSON.stringify(loginRes)}`);
			}
			const wsUrlFromLogin = `${data.wsUrl ?? data.ws_url ?? data.socketUrl ?? data.socket_url ?? data.wsAddress ?? data.ws_address ?? ""}`;
			if (wsUrlFromLogin != "") {
				this.wsAddress = wsUrlFromLogin;
			}
			await this.createSocket();
		} catch (error) {
			this.scheduleReconnect();
			throw error;
		}
	}

	async send(data: string | UTSJSONObject, type: string = WsMessageType.Private as string): Promise<boolean> {
		const task = this.socketTask;
		if (task == null) {
			return false;
		}
		const packet = this.buildSendPacket(data, type);
		return await new Promise<boolean>((resolve) => {
			task.send({
				data: packet,
				success: () => resolve(true),
				fail: (error) => {
					this.logger.error(`WebSocket 发送失败: ${JSON.stringify(error)}`, "Ws");
					resolve(false);
				}
			});
		});
	}

	setOnMessage(handler: ((data: UTSJSONObject) => void) | null): void {
		this.onMessage = handler;
	}

	private buildSendPacket(data: string | UTSJSONObject, type: string): string {
		if (typeof data === "string") {
			return data;
		}
		const payload: UTSJSONObject = {};
		for (const key in data) {
			payload[key] = data[key];
		}
		payload.device_id = this.deviceId;
		if (payload.type == null) {
			payload.type = type;
		}
		return JSON.stringify(payload);
	}

	private buildWsUrl(token: string, deviceId: string): string {
		const base = normalizeWsUrl(this.wsAddress);
		const encodedToken = encodeURIComponent(token);
		const encodedDeviceId = encodeURIComponent(deviceId);
		return `${base}?token=${encodedToken}&deviceId=${encodedDeviceId}`;
	}

	private clearReconnectTimer(): void {
		const timer = this.reconnectTimer;
		if (timer != null) {
			clearTimeout(timer);
			this.reconnectTimer = null;
		}
	}

	private async connectSocketByUrl(targetUrl: string): Promise<void> {
		await new Promise<void>((resolve, reject) => {
			const task = uni.connectSocket({
				url: targetUrl
			});
			this.socketTask = task;
			let opened = false;
			let settled = false;
			const timer = setTimeout(() => {
				if (settled) {
					return;
				}
				settled = true;
				reject(new Error(`WebSocket 连接超时: ${targetUrl}`));
			}, 8000);
			task.onOpen(() => {
				if (settled) {
					return;
				}
				opened = true;
				settled = true;
				clearTimeout(timer);
				this.reconnectCount = 0;
				this.isReconnecting = false;
				this.logger.info(`WebSocket 连接成功: ${targetUrl}`, "Ws");

				// ✅ 启动心跳定时器(每 20 秒发送一次)
            	this.startHeartbeat();

				resolve();
			});
			task.onMessage((event) => {
				const raw = event.data;
				this.handleMessage(raw).catch((error): void => {
					this.logger.error(`WebSocket 消息处理失败: ${JSON.stringify(error)}`, "Ws");
				});
			});
			task.onError((error) => {
				this.logger.error(`WebSocket 异常 url=${targetUrl} error=${JSON.stringify(error)}`, "Ws");
				if (!opened && !settled) {
					settled = true;
					clearTimeout(timer);
					// ✅ 停止心跳
            		this.stopHeartbeat();
					reject(new Error(`WebSocket onError: ${JSON.stringify(error)}`));
				} else if (opened) {
					this.logger.warn(`WebSocket 连接异常,准备重连`, "Ws");
					if (!this.isManualClose) {
						this.scheduleReconnect();
					}
				}
			});
			task.onClose((closeEvent) => {
				this.logger.warn(`WebSocket 连接关闭: ${JSON.stringify(closeEvent)}`, "Ws");
				// ✅ 停止心跳
            	this.stopHeartbeat();

				if (!opened && !settled) {
					settled = true;
					clearTimeout(timer);
					reject(new Error(`WebSocket onClose before open: ${JSON.stringify(closeEvent)}`));
					return;
				}
				if (!this.isManualClose) {
					this.scheduleReconnect();
				}
			});
		});
	}

	// ✅ 新增:启动心跳
private startHeartbeat(): void {
    this.stopHeartbeat(); // 先清除旧的
	this.logger.warn(`💗 WebSocket 开启客户端心跳 💗`, "Ws");

	// ✅ 立即发送一次心跳
	this.ping();

    this.heartbeatTimer = setInterval(() => {
        this.ping();
    }, 20000); // 每 20 秒发送一次
}

// ✅ 新增:停止心跳
private stopHeartbeat(): void {
    const timer = this.heartbeatTimer;
    if (timer != null) {
        clearInterval(timer);
        this.heartbeatTimer = null;
    }
}

// ✅ 新增:发送心跳消息(提取公共逻辑)
private ping(): void {
	if (this.socketTask != null) {
		this.send(JSON.stringify({
			type: "ping",
			timestamp: Date.now()
		}), WsMessageType.Private as string).catch((error) => {
			this.logger.warn(`心跳发送失败: ${JSON.stringify(error)}`, "Ws");
		});
	}
}

	private async createSocket(): Promise<void> {
		await this.close(1000, "reconnect", false).catch((): void => {});
		this.isManualClose = false;

		const wsUrl = this.buildWsUrl(this.token, this.deviceId);
		await this.connectSocketByUrl(wsUrl);
	}

	private async handleMessage(raw: any): Promise<void> {
		const payload = await this.normalizePayload(raw);
		if(payload.type=='pong'){
			// this.logger.debug(`WebSocket 收到心跳响应: ${JSON.stringify(raw)}`, "Ws");
			return;
		}
		this.logger.info(`WebSocket 收到消息: ${JSON.stringify(payload)}`, "Ws");
		const errorCode = `${payload.errorCode ?? ""}`;
		if (errorCode == "907") {
			this.logger.warn("WebSocket token 过期,准备重连", "Ws");
			this.scheduleReconnect(true);
			return;
		}
		const ctx = {
			deviceId: this.deviceId,
			send: async (data: string | UTSJSONObject, type?: string): Promise<boolean> => {
				const messageType = type != null ? type : WsMessageType.Private as string;
				return await this.send(data, messageType);
			},
			startLiveLog: async (sendLine: (line: string) => Promise<void>): Promise<void> => {
				await this.liveLogService.start(sendLine);
			},
			stopLiveLog: (): void => {
				this.liveLogService.stop();
			}
		} as WsCommandContext;
		try {
			await this.router.handle(ctx, payload);
		} catch (error: any) {
			this.logger.error(`WebSocket 路由处理失败:${JSON.stringify(error)} payload=${JSON.stringify(payload)}`, "Ws");
		}
		if (this.onMessage != null) {
			try {
				this.onMessage(payload);
			} catch (error: any) {
				this.logger.error(`WebSocket onMessage 回调执行异常:${JSON.stringify(error)}`, "Ws");
			}
		}
	}

	private async login(retryCount: number = 3, retryDelay: number = 2000): Promise<UTSJSONObject> {
		const sysInfo = uni.getSystemInfoSync();
		const sn = "85021F6039BB89866048E0410707025E";
		if (sn == "") {
			throw new Error("未获取到设备 deviceId");
		}

		const loginUrl = this.loginAddress;
		if (loginUrl == null || loginUrl == "") {
			throw new Error("WebSocket 登录地址为空");
		}

		let lastErrorMessage: string = "";
		for (let attempt = 1; attempt <= retryCount; attempt++) {
			try {
				this.logger.info(`WebSocket 登录第 ${attempt} 次尝试: ${sn} url=${loginUrl}`, "Ws");

				const response = await new Promise<UTSJSONObject>((resolve, reject) => {
					uni.request({
						url: loginUrl,
						method: "POST",
						data: { sn },
						success: (response) => {
							try {
								const rawData = response.data;

								if (rawData == null) {
									resolve(EMPTY_OBJECT);
									return;
								}

								// ✅ 使用工具函数安全转换
								const data = toObj(rawData);
								resolve(data);
							} catch (e) {
								resolve(EMPTY_OBJECT);
							}
						},
						fail: (error) => {
							reject(error);
						}
					});
				});

				const code = `${response.code ?? ""}`;
				if (code == "200" || code == "0") {
					return response;
				}

				const msg = `${response.message ?? response.msg ?? "未知错误"}`;
				lastErrorMessage = `WebSocket 登录失败(${msg}),url=${loginUrl},response=${JSON.stringify(response)}`;
				this.logger.warn(lastErrorMessage, "Ws");
			} catch (error: any) {
				lastErrorMessage = `WebSocket 登录请求异常,url=${loginUrl},error=${JSON.stringify(error)}`;
				this.logger.warn(lastErrorMessage, "Ws");
			}

			if (attempt < retryCount) {
				this.logger.warn(`WebSocket 登录失败,${retryDelay}ms 后重试,attempt=${attempt}`, "Ws");
				await new Promise<void>((resolve) => {
					setTimeout(() => resolve(), retryDelay);
				});
			}
		}

		if (lastErrorMessage != "") {
			throw new Error(lastErrorMessage);
		}
		throw new Error(`WebSocket 登录失败,url=${loginUrl}`);
	}

	private async normalizePayload(raw: any): Promise<UTSJSONObject> {
		if (raw == null) {
			return { command: "message", data: null };
		}

		let parsed: UTSJSONObject;

		if (typeof raw === "string") {
			try {
				parsed = toObj(raw);
			} catch {
				return { command: "message", raw };
			}
		} else {
			try {
				const decoded = new TextDecoder("utf-8").decode(raw as ArrayBuffer);
				parsed = toObj(decoded);
			} catch {
				return { command: "message", raw: `${raw}` };
			}
		}

		// 处理服务端格式:{ event: "private", data: { command: "xxx", ... } }
		if (parsed.event != null && parsed.data != null) {
			const data = toObj(parsed.data ?? EMPTY_OBJECT);
			// 直接返回 data 部分,这里包含 command
			return data;
		}

		// 处理包装格式:{ code: 200, data: { event: "private", data: { command: "xxx" } } }
		if (parsed.code != null && parsed.data != null) {
			const outerData = toObj(parsed.data ?? EMPTY_OBJECT);
			if (outerData.data != null) {
				const innerData = toObj(outerData.data ?? EMPTY_OBJECT);
				return innerData;
			}
			return outerData;
		}

		// 如果没有任何特殊字段,直接返回解析后的对象
		return parsed;
	}

	private scheduleReconnect(force: boolean = false): void {
		if (this.isManualClose) {
			return;
		}
		if (this.isReconnecting && !force) {
			return;
		}
		this.isReconnecting = true;
		this.clearReconnectTimer();
		this.reconnectCount += 1;
		const delay = Math.min(30_000, this.reconnectCount * 2000);
		this.reconnectTimer = setTimeout(() => {
			this.connect().catch((error): void => {
				this.logger.error(`WebSocket 重连失败: ${JSON.stringify(error)}`, "Ws");
			});
		}, delay);
	}
}

const wsSingleton = new Ws();
export default wsSingleton;