lantiannb 2 týždňov pred
commit
a1d2d3d39c
1 zmenil súbory, kde vykonal 71 pridanie a 0 odobranie
  1. 71 0
      UECommunicationService.js

+ 71 - 0
UECommunicationService.js

@@ -0,0 +1,71 @@
+export class UECommunicationService {
+    constructor(stream) {
+      this.s = stream;
+      this.pendingMessages = {};
+      this.ueCommunicationInitialized = false;
+    }
+  
+    // 初始化监听器
+    initUeCommunication() {
+      if (!this.ueCommunicationInitialized) {
+        this.s.addResponseEventListener("ue-response", this.myHandleResponseFunction.bind(this));
+        this.ueCommunicationInitialized = true;
+      }
+    }
+  
+    // 发送消息到UE
+    sendToUE(message) {
+      return new Promise((resolve, reject) => {
+        const messageId = `msg_${Date.now()}_${Math.floor(Math.random() * 1000)}`;
+        const ueMessage = {
+          id: messageId,
+          type: message.type || 'default',
+          data: JSON.stringify(message.data) || {},
+        };
+  
+        this.pendingMessages[messageId] = { resolve, reject };
+  
+        const timeoutId = setTimeout(() => {
+          if (this.pendingMessages[messageId]) {
+            delete this.pendingMessages[messageId];
+            reject(new Error('Request timeout'));
+          }
+        }, message.timeout || 5000); // 默认5秒超时
+  
+        this.pendingMessages[messageId].timeoutId = timeoutId;
+  
+        try {
+          this.s.emitUIInteraction(ueMessage);
+        } catch (error) {
+          clearTimeout(timeoutId);
+          delete this.pendingMessages[messageId];
+          reject(error);
+        }
+      });
+    }
+  
+    // 处理响应消息
+    myHandleResponseFunction(response) {
+      try {
+        const responseObj = JSON.parse(response);
+  
+        if (responseObj.id && this.pendingMessages[responseObj.id]) {
+          const { resolve, reject, timeoutId } = this.pendingMessages[responseObj.id];
+          clearTimeout(timeoutId);
+          delete this.pendingMessages[responseObj.id];
+  
+          if (responseObj.status === 'success') {
+            resolve(responseObj.data);
+          } else {
+            reject(new Error(responseObj.error || 'Unknown error'));
+          }
+        } else {
+          // 非响应消息,可能是推送通知
+          console.log('Received message from UE:', responseObj);
+        }
+      } catch (e) {
+        console.error('Failed to parse UE response:', e);
+      }
+    }
+  }
+