UECommunicationService.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. export class UECommunicationService {
  2. constructor(stream) {
  3. this.s = stream;
  4. this.pendingMessages = {};
  5. this.ueCommunicationInitialized = false;
  6. }
  7. // 初始化监听器
  8. initUeCommunication() {
  9. if (!this.ueCommunicationInitialized) {
  10. this.s.addResponseEventListener("ue-response", this.myHandleResponseFunction.bind(this));
  11. this.ueCommunicationInitialized = true;
  12. }
  13. }
  14. // 发送消息到UE
  15. sendToUE(message) {
  16. return new Promise((resolve, reject) => {
  17. const messageId = `msg_${Date.now()}_${Math.floor(Math.random() * 1000)}`;
  18. const ueMessage = {
  19. id: messageId,
  20. type: message.type || 'default',
  21. data: JSON.stringify(message.data) || {},
  22. };
  23. this.pendingMessages[messageId] = { resolve, reject };
  24. const timeoutId = setTimeout(() => {
  25. if (this.pendingMessages[messageId]) {
  26. delete this.pendingMessages[messageId];
  27. reject(new Error('Request timeout'));
  28. }
  29. }, message.timeout || 5000); // 默认5秒超时
  30. this.pendingMessages[messageId].timeoutId = timeoutId;
  31. try {
  32. this.s.emitUIInteraction(ueMessage);
  33. } catch (error) {
  34. clearTimeout(timeoutId);
  35. delete this.pendingMessages[messageId];
  36. reject(error);
  37. }
  38. });
  39. }
  40. // 处理响应消息
  41. myHandleResponseFunction(response) {
  42. try {
  43. const responseObj = JSON.parse(response);
  44. if (responseObj.id && this.pendingMessages[responseObj.id]) {
  45. const { resolve, reject, timeoutId } = this.pendingMessages[responseObj.id];
  46. clearTimeout(timeoutId);
  47. delete this.pendingMessages[responseObj.id];
  48. if (responseObj.status === 'success') {
  49. resolve(responseObj.data);
  50. } else {
  51. reject(new Error(responseObj.error || 'Unknown error'));
  52. }
  53. } else {
  54. // 非响应消息,可能是推送通知
  55. console.log('Received message from UE:', responseObj);
  56. }
  57. } catch (e) {
  58. console.error('Failed to parse UE response:', e);
  59. }
  60. }
  61. }