1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071 |
- 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);
- }
- }
- }
-
|