@phystack/hub-client 4.4.53 → 4.4.55

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/dist/index.d.ts +18 -25
  2. package/dist/index.d.ts.map +1 -1
  3. package/dist/index.js +252 -188
  4. package/dist/index.js.map +1 -1
  5. package/dist/peripheral-twin.d.ts +10 -9
  6. package/dist/peripheral-twin.d.ts.map +1 -1
  7. package/dist/peripheral-twin.js +24 -54
  8. package/dist/peripheral-twin.js.map +1 -1
  9. package/dist/services/phyhub-connection.service.d.ts +1 -0
  10. package/dist/services/phyhub-connection.service.d.ts.map +1 -1
  11. package/dist/services/phyhub-connection.service.js +17 -0
  12. package/dist/services/phyhub-connection.service.js.map +1 -1
  13. package/dist/services/phyhub-direct-connection.service.d.ts +21 -0
  14. package/dist/services/phyhub-direct-connection.service.d.ts.map +1 -0
  15. package/dist/services/phyhub-direct-connection.service.js +101 -0
  16. package/dist/services/phyhub-direct-connection.service.js.map +1 -0
  17. package/dist/services/webrtc/data-channel-handler.d.ts +45 -0
  18. package/dist/services/webrtc/data-channel-handler.d.ts.map +1 -0
  19. package/dist/services/webrtc/data-channel-handler.js +260 -0
  20. package/dist/services/webrtc/data-channel-handler.js.map +1 -0
  21. package/dist/services/webrtc/index.d.ts +8 -0
  22. package/dist/services/webrtc/index.d.ts.map +1 -0
  23. package/dist/services/webrtc/index.js +18 -0
  24. package/dist/services/webrtc/index.js.map +1 -0
  25. package/dist/services/webrtc/media-stream-handler.d.ts +57 -0
  26. package/dist/services/webrtc/media-stream-handler.d.ts.map +1 -0
  27. package/dist/services/webrtc/media-stream-handler.js +367 -0
  28. package/dist/services/webrtc/media-stream-handler.js.map +1 -0
  29. package/dist/services/webrtc/peer-connection-manager.d.ts +40 -0
  30. package/dist/services/webrtc/peer-connection-manager.d.ts.map +1 -0
  31. package/dist/services/webrtc/peer-connection-manager.js +335 -0
  32. package/dist/services/webrtc/peer-connection-manager.js.map +1 -0
  33. package/dist/services/webrtc/types.d.ts +133 -0
  34. package/dist/services/webrtc/types.d.ts.map +1 -0
  35. package/dist/services/webrtc/types.js +12 -0
  36. package/dist/services/webrtc/types.js.map +1 -0
  37. package/dist/services/webrtc/webrtc-globals.d.ts +4 -0
  38. package/dist/services/webrtc/webrtc-globals.d.ts.map +1 -0
  39. package/dist/services/webrtc/webrtc-globals.js +72 -0
  40. package/dist/services/webrtc/webrtc-globals.js.map +1 -0
  41. package/dist/services/webrtc/webrtc-manager.d.ts +35 -0
  42. package/dist/services/webrtc/webrtc-manager.d.ts.map +1 -0
  43. package/dist/services/webrtc/webrtc-manager.js +274 -0
  44. package/dist/services/webrtc/webrtc-manager.js.map +1 -0
  45. package/dist/test/communication-comprehensive-test.d.ts +8 -0
  46. package/dist/test/communication-comprehensive-test.d.ts.map +1 -0
  47. package/dist/test/communication-comprehensive-test.js +356 -0
  48. package/dist/test/communication-comprehensive-test.js.map +1 -0
  49. package/dist/test/webrtc-channel-names-test.d.ts +2 -0
  50. package/dist/test/webrtc-channel-names-test.d.ts.map +1 -0
  51. package/dist/test/webrtc-channel-names-test.js +177 -0
  52. package/dist/test/webrtc-channel-names-test.js.map +1 -0
  53. package/dist/test/webrtc-comprehensive-test.d.ts +2 -0
  54. package/dist/test/webrtc-comprehensive-test.d.ts.map +1 -0
  55. package/dist/test/webrtc-comprehensive-test.js +328 -0
  56. package/dist/test/webrtc-comprehensive-test.js.map +1 -0
  57. package/dist/test/webrtc-reconnect-test.d.ts +4 -0
  58. package/dist/test/webrtc-reconnect-test.d.ts.map +1 -0
  59. package/dist/test/webrtc-reconnect-test.js +244 -0
  60. package/dist/test/webrtc-reconnect-test.js.map +1 -0
  61. package/dist/test/webrtc-test-harness.d.ts +4 -0
  62. package/dist/test/webrtc-test-harness.d.ts.map +1 -0
  63. package/dist/test/webrtc-test-harness.js +169 -0
  64. package/dist/test/webrtc-test-harness.js.map +1 -0
  65. package/dist/twin-messaging.d.ts +23 -0
  66. package/dist/twin-messaging.d.ts.map +1 -0
  67. package/dist/twin-messaging.js +96 -0
  68. package/dist/twin-messaging.js.map +1 -0
  69. package/dist/types/twin.types.d.ts +36 -20
  70. package/dist/types/twin.types.d.ts.map +1 -1
  71. package/dist/types/twin.types.js.map +1 -1
  72. package/docs/webrtc-howto.md +398 -0
  73. package/docs/webrtc-test.md +330 -0
  74. package/package.json +3 -3
  75. package/scripts/webrtc-test.sh +401 -0
  76. package/src/index.ts +370 -259
  77. package/src/peripheral-twin.ts +44 -67
  78. package/src/services/phyhub-connection.service.ts +24 -0
  79. package/src/services/phyhub-direct-connection.service.ts +159 -0
  80. package/src/services/webrtc/data-channel-handler.ts +362 -0
  81. package/src/services/webrtc/index.ts +36 -0
  82. package/src/services/webrtc/media-stream-handler.ts +515 -0
  83. package/src/services/webrtc/peer-connection-manager.ts +463 -0
  84. package/src/services/webrtc/types.ts +270 -0
  85. package/src/services/webrtc/webrtc-globals.ts +108 -0
  86. package/src/services/webrtc/webrtc-manager.ts +490 -0
  87. package/src/test/communication-comprehensive-test.ts +533 -0
  88. package/src/test/webrtc-channel-names-test.ts +266 -0
  89. package/src/test/webrtc-comprehensive-test.ts +494 -0
  90. package/src/test/webrtc-reconnect-test.ts +345 -0
  91. package/src/test/webrtc-test-harness.ts +254 -0
  92. package/src/twin-messaging.ts +193 -0
  93. package/src/types/twin.types.ts +59 -20
  94. package/dist/services/webrtc/datachannel.d.ts +0 -10
  95. package/dist/services/webrtc/datachannel.d.ts.map +0 -1
  96. package/dist/services/webrtc/datachannel.js +0 -290
  97. package/dist/services/webrtc/datachannel.js.map +0 -1
  98. package/dist/services/webrtc/mediastream.d.ts +0 -10
  99. package/dist/services/webrtc/mediastream.d.ts.map +0 -1
  100. package/dist/services/webrtc/mediastream.js +0 -396
  101. package/dist/services/webrtc/mediastream.js.map +0 -1
  102. package/dist/services/webrtc/peer-connection-ice.d.ts +0 -32
  103. package/dist/services/webrtc/peer-connection-ice.d.ts.map +0 -1
  104. package/dist/services/webrtc/peer-connection-ice.js +0 -483
  105. package/dist/services/webrtc/peer-connection-ice.js.map +0 -1
  106. package/src/services/webrtc/datachannel.ts +0 -421
  107. package/src/services/webrtc/mediastream.ts +0 -602
  108. package/src/services/webrtc/peer-connection-ice.ts +0 -689
package/dist/index.js CHANGED
@@ -1,59 +1,15 @@
1
1
  "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
- };
16
2
  Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.connectPhyClient = exports.PhyHubClient = void 0;
3
+ exports.createTwinMessaging = exports.WebRTCManager = exports.TwinMessageResultStatus = exports.connectPhyClient = exports.PhyHubClient = void 0;
18
4
  const twin_types_1 = require("./types/twin.types");
5
+ Object.defineProperty(exports, "TwinMessageResultStatus", { enumerable: true, get: function () { return twin_types_1.TwinMessageResultStatus; } });
19
6
  const phyhub_connection_service_1 = require("./services/phyhub-connection.service");
7
+ const phyhub_direct_connection_service_1 = require("./services/phyhub-direct-connection.service");
20
8
  const signals_service_1 = require("./services/signals.service");
21
9
  const signal_types_1 = require("./types/signal.types");
22
- const datachannel_1 = require("./services/webrtc/datachannel");
23
- const mediastream_1 = require("./services/webrtc/mediastream");
10
+ const webrtc_1 = require("./services/webrtc");
24
11
  const twin_registry_1 = require("./twin-registry");
25
- __exportStar(require("./types"), exports);
26
- (async function initializeWebRTCGlobals() {
27
- if (typeof window !== 'undefined')
28
- return;
29
- try {
30
- const wrtc = require('@roamhq/wrtc');
31
- if (typeof global.MediaStream === 'undefined' && wrtc.MediaStream) {
32
- global.MediaStream = wrtc.MediaStream;
33
- console.log('Global MediaStream initialized');
34
- }
35
- if (typeof global.RTCPeerConnection === 'undefined' && wrtc.RTCPeerConnection) {
36
- global.RTCPeerConnection = wrtc.RTCPeerConnection;
37
- console.log('Global RTCPeerConnection initialized');
38
- }
39
- if (typeof global.RTCSessionDescription === 'undefined' && wrtc.RTCSessionDescription) {
40
- global.RTCSessionDescription = wrtc.RTCSessionDescription;
41
- console.log('Global RTCSessionDescription initialized');
42
- }
43
- if (typeof global.RTCIceCandidate === 'undefined' && wrtc.RTCIceCandidate) {
44
- global.RTCIceCandidate = wrtc.RTCIceCandidate;
45
- console.log('Global RTCIceCandidate initialized');
46
- }
47
- if (typeof global.RTCVideoSource === 'undefined' && wrtc.nonstandard.RTCVideoSource) {
48
- global.RTCVideoSource = wrtc.nonstandard.RTCVideoSource;
49
- console.log('Global RTCVideoSource initialized');
50
- }
51
- console.log('WebRTC globals successfully initialized');
52
- }
53
- catch (error) {
54
- console.error('Failed to initialize WebRTC globals:', error);
55
- }
56
- })().catch(err => console.error('Error in WebRTC globals initialization:', err));
12
+ const twin_messaging_1 = require("./twin-messaging");
57
13
  class PhyHubClient {
58
14
  constructor(params = {}) {
59
15
  this.instanceId = undefined;
@@ -68,6 +24,7 @@ class PhyHubClient {
68
24
  this.instances = new Map();
69
25
  this.twinUpdateListeners = {};
70
26
  this.twinInstancesRegistry = null;
27
+ this.webrtcManager = null;
71
28
  this.EVENTS = {
72
29
  PING: 'ping',
73
30
  PONG: 'pong',
@@ -125,51 +82,21 @@ class PhyHubClient {
125
82
  this.signals = new signals_service_1.SignalsService(this, initSignalsPayload);
126
83
  return this.signals;
127
84
  };
128
- this.getDataChannel = async (targetTwinId) => {
129
- const options = {
130
- targetTwinId,
131
- sendTwinMessage: this.sendTwinMessage.bind(this),
132
- subscribeTwin: this.subscribeTwin.bind(this),
133
- onTwinMessage: this.onTwinMessage.bind(this),
134
- offTwinMessage: this.offTwinMessage.bind(this),
135
- useStun: true,
136
- isInitiator: true,
137
- channelPrefix: 'channel',
138
- mediaOptions: { isMediaConnection: false },
139
- };
140
- const result = (await (0, datachannel_1.createWebRTCDataChannelConnection)(options));
141
- return result.dataChannel;
85
+ this.getDataChannel = async (targetTwinId, channelName) => {
86
+ const manager = await this.getWebRTCManager();
87
+ return manager.createDataChannel(targetTwinId, channelName);
142
88
  };
143
- this.onDataChannel = async (sourceTwinId, callback) => {
144
- const options = {
145
- targetTwinId: sourceTwinId,
146
- sendTwinMessage: this.sendTwinMessage.bind(this),
147
- subscribeTwin: this.subscribeTwin.bind(this),
148
- onTwinMessage: this.onTwinMessage.bind(this),
149
- offTwinMessage: this.offTwinMessage.bind(this),
150
- useStun: true,
151
- isInitiator: false,
152
- channelPrefix: 'channel',
153
- mediaOptions: { isMediaConnection: false },
154
- };
155
- const result = (await (0, datachannel_1.createWebRTCDataChannelConnection)(options));
156
- callback(result.dataChannel);
89
+ this.onDataChannel = async (sourceTwinId, callback, channelName) => {
90
+ const manager = await this.getWebRTCManager();
91
+ const channel = await manager.acceptDataChannel(sourceTwinId, channelName);
92
+ callback(channel);
157
93
  };
158
- this.onMediaStream = async (sourceTwinId, callback) => {
159
- const options = {
160
- targetTwinId: sourceTwinId,
161
- sendTwinMessage: this.sendTwinMessage.bind(this),
162
- subscribeTwin: this.subscribeTwin.bind(this),
163
- onTwinMessage: this.onTwinMessage.bind(this),
164
- offTwinMessage: this.offTwinMessage.bind(this),
165
- isInitiator: false,
166
- channelPrefix: 'media',
167
- mediaOptions: {
168
- isMediaConnection: true,
169
- },
170
- };
171
- const result = await (0, mediastream_1.createWebRTCMediaStreamConnection)(options);
172
- callback(result.mediaStream);
94
+ this.onMediaStream = async (sourceTwinId, callback, options) => {
95
+ var _a;
96
+ const manager = await this.getWebRTCManager();
97
+ const channelName = (_a = options === null || options === void 0 ? void 0 : options.channelName) !== null && _a !== void 0 ? _a : 'default';
98
+ const stream = await manager.acceptMediaStream(sourceTwinId, options, channelName);
99
+ callback(stream);
173
100
  };
174
101
  this.instanceId = params.instanceId;
175
102
  if (!this.instanceId) {
@@ -218,6 +145,9 @@ class PhyHubClient {
218
145
  this.setupSocketListeners((value) => value, (reason) => {
219
146
  throw reason;
220
147
  });
148
+ if (phyhub_direct_connection_service_1.PhyHubDirectConnection.isEnabled()) {
149
+ await this.initializeDirectConnectionTwin();
150
+ }
221
151
  return this;
222
152
  }
223
153
  catch (err) {
@@ -264,27 +194,43 @@ class PhyHubClient {
264
194
  this.socketConnected = false;
265
195
  });
266
196
  this.socket.on(this.EVENTS.TWIN_MESSAGE, (payload, callback) => {
197
+ var _a;
198
+ console.log('[TWIN_MESSAGE] Received:', {
199
+ twinId: payload.twinId,
200
+ sourceTwinId: payload.sourceTwinId,
201
+ dataType: (_a = payload.data) === null || _a === void 0 ? void 0 : _a.type,
202
+ });
267
203
  let result = null;
268
- if (payload.twinId && payload.data) {
269
- const listeners = this.twinMessageListeners[payload.twinId];
204
+ if (payload.data) {
205
+ const sourceTwinId = payload.sourceTwinId;
206
+ const targetTwinId = payload.twinId;
207
+ let listeners = sourceTwinId ? this.twinMessageListeners[sourceTwinId] : undefined;
208
+ if (!listeners && targetTwinId) {
209
+ listeners = this.twinMessageListeners[targetTwinId];
210
+ }
270
211
  if (listeners === null || listeners === void 0 ? void 0 : listeners.size) {
212
+ console.log(`[TWIN_MESSAGE] Executing ${listeners.size} listeners`);
271
213
  listeners.forEach(listener => {
272
214
  try {
273
215
  listener(payload);
274
216
  result = { status: twin_types_1.TwinMessageResultStatus.Success, message: 'Action completed' };
275
217
  }
276
218
  catch (error) {
277
- console.error(`Error in twin message listener for ${payload.twinId}:`, error);
219
+ console.error(`[TWIN_MESSAGE] Error in listener:`, error);
278
220
  result = { status: twin_types_1.TwinMessageResultStatus.Error, message: (error === null || error === void 0 ? void 0 : error.message) || 'An error occurred' };
279
221
  }
280
222
  });
281
223
  }
282
224
  else {
283
- result = { status: twin_types_1.TwinMessageResultStatus.Warning, message: `No listeners found for twin ${payload.twinId} on this socket` };
225
+ console.log(`[TWIN_MESSAGE] No listeners found for source=${sourceTwinId} or target=${targetTwinId}`);
226
+ result = { status: twin_types_1.TwinMessageResultStatus.Warning, message: `No listeners found` };
227
+ }
228
+ if (callback) {
229
+ callback(result);
284
230
  }
285
- callback(result);
286
231
  }
287
232
  else {
233
+ console.log('[TWIN_MESSAGE] Invalid payload (no data):', payload);
288
234
  }
289
235
  });
290
236
  this.socket.on('twinUpdated', (payload) => {
@@ -374,26 +320,43 @@ class PhyHubClient {
374
320
  });
375
321
  });
376
322
  }
377
- async getMediaStream(targetTwinId) {
378
- const options = {
379
- targetTwinId,
380
- sendTwinMessage: this.sendTwinMessage.bind(this),
381
- subscribeTwin: this.subscribeTwin.bind(this),
382
- onTwinMessage: this.onTwinMessage.bind(this),
383
- offTwinMessage: this.offTwinMessage.bind(this),
384
- isInitiator: true,
385
- channelPrefix: 'media',
386
- mediaOptions: {
387
- isMediaConnection: true,
388
- mediaDirection: 'recvonly',
389
- },
390
- };
391
- const result = await (0, mediastream_1.createWebRTCMediaStreamConnection)(options);
323
+ async getMediaStream(targetTwinId, options) {
324
+ var _a;
325
+ const manager = await this.getWebRTCManager();
326
+ const channelName = (_a = options === null || options === void 0 ? void 0 : options.channelName) !== null && _a !== void 0 ? _a : 'default';
327
+ const stream = await manager.createMediaStream(targetTwinId, options, channelName);
392
328
  return {
393
- stream: result.mediaStream,
394
- close: result.close,
329
+ stream,
330
+ close: () => stream.close(),
395
331
  };
396
332
  }
333
+ async getWebRTCManager(options) {
334
+ if (!this.webrtcManager) {
335
+ await this.assureSocketConnection();
336
+ const twinMessaging = {
337
+ sendMessage: async (targetTwinId, data) => {
338
+ await this.sendTwinMessage(targetTwinId, data);
339
+ },
340
+ subscribe: async (twinId) => {
341
+ await this.subscribeTwin(twinId);
342
+ },
343
+ onMessage: (twinId, callback) => {
344
+ this.onTwinMessage(twinId, callback);
345
+ },
346
+ offMessage: (twinId, callback) => {
347
+ this.offTwinMessage(twinId, callback);
348
+ },
349
+ getOwnTwinId: () => {
350
+ if (!this.instanceId) {
351
+ throw new Error('Instance ID not set');
352
+ }
353
+ return this.instanceId;
354
+ },
355
+ };
356
+ this.webrtcManager = new webrtc_1.WebRTCManager(twinMessaging, options);
357
+ }
358
+ return this.webrtcManager;
359
+ }
397
360
  async getInstance() {
398
361
  if (!this.instanceId) {
399
362
  throw new Error('Instance ID not set');
@@ -404,40 +367,12 @@ class PhyHubClient {
404
367
  await this.assureSocketConnection();
405
368
  let instance;
406
369
  let instanceTwin = await this.getTwinById(this.instanceId);
407
- const edgeInstanceTypePrefix = 'edgeInstance';
408
- const edgeTwinEmit = (type, payload) => {
409
- const { id: twinId } = instanceTwin;
410
- const edgeTwinMessagePayload = {
411
- type: `${edgeInstanceTypePrefix}:${type}`,
412
- sourceTwinId: twinId,
413
- sourceDeviceId: instanceTwin.deviceId,
414
- data: payload,
415
- };
416
- this.sendTwinMessage(twinId, edgeTwinMessagePayload);
417
- };
418
- const edgeTwinOn = (type, callback) => {
419
- const { id: twinId } = instanceTwin;
420
- const onEdgeTwinMessage = (payload) => {
421
- var _a, _b;
422
- const messageType = ((_a = payload.data) === null || _a === void 0 ? void 0 : _a.type) || payload.type;
423
- if (messageType === `${edgeInstanceTypePrefix}:${type}`) {
424
- callback(((_b = payload.data) === null || _b === void 0 ? void 0 : _b.data) || payload.data);
425
- }
426
- else {
427
- }
428
- };
429
- this.onTwinMessage(twinId, onEdgeTwinMessage);
430
- };
431
- const edgeTwinTo = (targetTwinId) => ({
432
- emit: (type, payload) => {
433
- const edgeTwinMessagePayload = {
434
- type: `${edgeInstanceTypePrefix}:${type}`,
435
- sourceTwinId: instanceTwin.id,
436
- sourceDeviceId: instanceTwin.deviceId,
437
- data: payload,
438
- };
439
- this.sendTwinMessage(targetTwinId, edgeTwinMessagePayload);
440
- },
370
+ const messaging = (0, twin_messaging_1.createTwinMessaging)({
371
+ sendEvent: (targetTwinId, payload) => this.sendEvent(targetTwinId, payload),
372
+ onTwinMessage: (twinId, callback) => this.onTwinMessage(twinId, callback),
373
+ twinId: instanceTwin.id,
374
+ deviceId: instanceTwin.deviceId,
375
+ typePrefix: 'edgeInstance',
441
376
  });
442
377
  const getPeripheralTwins = async () => {
443
378
  const payload = {
@@ -486,23 +421,23 @@ class PhyHubClient {
486
421
  });
487
422
  });
488
423
  };
489
- const getDataChannel = async () => {
490
- return await this.getDataChannel(instanceTwin.id);
424
+ const getDataChannel = async (channelName) => {
425
+ return await this.getDataChannel(instanceTwin.id, channelName);
491
426
  };
492
- const onDataChannel = async (callback) => {
493
- return await this.onDataChannel(instanceTwin.id, callback);
427
+ const onDataChannel = async (callback, channelName) => {
428
+ return await this.onDataChannel(instanceTwin.id, callback, channelName);
494
429
  };
495
- const getMediaStream = async () => {
430
+ const getMediaStream = async (channelName) => {
496
431
  if (!instance) {
497
432
  throw new Error('Instance not initialized');
498
433
  }
499
- return await this.getMediaStream(instance.id);
434
+ return await this.getMediaStream(instance.id, { channelName });
500
435
  };
501
- const onMediaStream = async (callback) => {
436
+ const onMediaStream = async (callback, channelName) => {
502
437
  if (!instance) {
503
438
  throw new Error('Instance not initialized');
504
439
  }
505
- await this.onMediaStream(instance.id, callback);
440
+ await this.onMediaStream(instance.id, callback, { channelName });
506
441
  };
507
442
  const updateReported = async (properties) => {
508
443
  const newReported = {
@@ -514,9 +449,9 @@ class PhyHubClient {
514
449
  };
515
450
  instance = {
516
451
  ...instanceTwin,
517
- emit: edgeTwinEmit,
518
- on: edgeTwinOn,
519
- to: edgeTwinTo,
452
+ emit: messaging.emit,
453
+ on: messaging.on,
454
+ to: messaging.to,
520
455
  createPeripheralTwin,
521
456
  updateReported,
522
457
  getPeripheralTwins,
@@ -553,7 +488,7 @@ class PhyHubClient {
553
488
  break;
554
489
  currentWindow = currentWindow.parent;
555
490
  }
556
- catch (e) {
491
+ catch (_a) {
557
492
  break;
558
493
  }
559
494
  }
@@ -620,10 +555,17 @@ class PhyHubClient {
620
555
  console.error('emit(): Socket not created');
621
556
  return;
622
557
  }
623
- const event = this.instanceId;
624
558
  const callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined;
625
- const payload = { method, ...args[0] };
626
- const emitArgs = [event, payload];
559
+ let emitArgs;
560
+ if (phyhub_direct_connection_service_1.PhyHubDirectConnection.isEnabled()) {
561
+ const payload = args[0] || {};
562
+ emitArgs = [method, payload];
563
+ }
564
+ else {
565
+ const event = this.instanceId;
566
+ const payload = { method, ...args[0] };
567
+ emitArgs = [event, payload];
568
+ }
627
569
  if (callback) {
628
570
  emitArgs.push(callback);
629
571
  }
@@ -675,15 +617,37 @@ class PhyHubClient {
675
617
  }
676
618
  return result;
677
619
  }
678
- async sendTwinMessage(targetTwinId, data, callback) {
620
+ sendEvent(targetTwinId, data) {
621
+ var _a;
622
+ const instanceId = this.instanceId;
623
+ if (!instanceId) {
624
+ console.error('[sendEvent] Instance ID not set, cannot send event');
625
+ return;
626
+ }
627
+ const cachedInstance = this.instances.get(instanceId);
628
+ const deviceId = (cachedInstance === null || cachedInstance === void 0 ? void 0 : cachedInstance.deviceId) || ((_a = this.lastDeviceStatusResponse) === null || _a === void 0 ? void 0 : _a.deviceId);
629
+ if (!deviceId) {
630
+ console.error('[sendEvent] Device ID not available, cannot send event');
631
+ return;
632
+ }
633
+ const payload = {
634
+ twinId: targetTwinId,
635
+ sourceTwinId: instanceId,
636
+ sourceDeviceId: deviceId,
637
+ data,
638
+ };
639
+ this.emit(this.EVENTS.TWIN_MESSAGE, payload);
640
+ }
641
+ async request(targetTwinId, data, callback) {
642
+ console.log('[request] Sending to:', targetTwinId, 'data type:', (data === null || data === void 0 ? void 0 : data.type) || 'unknown');
679
643
  const edgeInstance = await this.getInstance();
680
644
  if (!edgeInstance) {
681
- console.error('sendTwinMessage failed: Edge instance not found');
645
+ console.error('[request] Edge instance not found');
682
646
  throw new Error('Edge instance not found');
683
647
  }
684
648
  const { id: edgeTwinId, deviceId } = edgeInstance;
685
649
  if (!deviceId) {
686
- console.error('sendTwinMessage failed: Device ID not available');
650
+ console.error('[request] Device ID not available');
687
651
  throw new Error('Device ID not available - ensure device is connected');
688
652
  }
689
653
  const payload = {
@@ -696,37 +660,72 @@ class PhyHubClient {
696
660
  this.emit(this.EVENTS.TWIN_MESSAGE, payload, (response) => {
697
661
  callback(response);
698
662
  });
663
+ return;
699
664
  }
700
- else {
701
- return new Promise((resolve, reject) => {
665
+ return new Promise((resolve, reject) => {
666
+ var _a;
667
+ const ACTION_TIMEOUT = 10 * 1000;
668
+ const timeoutId = setTimeout(() => {
702
669
  var _a;
703
- const twinMessageTimeout = 10 * 1000;
704
- const twinMessageTimeoutId = setTimeout(() => {
670
+ if (this.socket) {
671
+ (_a = this.socket) === null || _a === void 0 ? void 0 : _a.off(payload.data.type);
672
+ }
673
+ reject({
674
+ status: twin_types_1.TwinMessageResultStatus.Error,
675
+ message: `Request timed out after ${ACTION_TIMEOUT}ms`
676
+ });
677
+ }, ACTION_TIMEOUT);
678
+ if (this.socket) {
679
+ this.socket.on(payload.data.type, (response) => {
705
680
  var _a;
706
- if (this.socket) {
681
+ if (response && response.status !== twin_types_1.TwinMessageResultStatus.Warning) {
682
+ clearTimeout(timeoutId);
707
683
  (_a = this.socket) === null || _a === void 0 ? void 0 : _a.off(payload.data.type);
684
+ resolve(response);
708
685
  }
709
- reject({ status: twin_types_1.TwinMessageResultStatus.Error, message: `twinMessage failed to complete in specified time (${twinMessageTimeout} ms)` });
710
- }, twinMessageTimeout);
686
+ });
687
+ }
688
+ this.emit(this.EVENTS.TWIN_MESSAGE, payload, (response) => {
689
+ var _a;
690
+ clearTimeout(timeoutId);
711
691
  if (this.socket) {
712
- this.socket.on(payload.data.type, (response) => {
713
- var _a;
714
- if (response && response.status !== twin_types_1.TwinMessageResultStatus.Warning) {
715
- clearTimeout(twinMessageTimeoutId);
716
- (_a = this.socket) === null || _a === void 0 ? void 0 : _a.off(payload.data.type);
717
- resolve(response);
718
- }
719
- });
692
+ (_a = this.socket) === null || _a === void 0 ? void 0 : _a.off(payload.data.type);
720
693
  }
721
- this.emit(this.EVENTS.TWIN_MESSAGE, payload, (response) => {
722
- console.log('sendTwinMessage promise received response:', response);
723
- });
724
- (_a = this.socket) === null || _a === void 0 ? void 0 : _a.on('error', (error) => {
725
- console.error('sendTwinMessage socket error:', error);
726
- reject(error);
727
- });
694
+ resolve(response);
695
+ });
696
+ (_a = this.socket) === null || _a === void 0 ? void 0 : _a.on('error', (error) => {
697
+ clearTimeout(timeoutId);
698
+ console.error('[request] Socket error:', error);
699
+ reject(error);
700
+ });
701
+ });
702
+ }
703
+ async sendTwinMessage(targetTwinId, data, callback) {
704
+ console.log('[sendTwinMessage] Sending to:', targetTwinId, 'data type:', (data === null || data === void 0 ? void 0 : data.type) || 'unknown');
705
+ const edgeInstance = await this.getInstance();
706
+ if (!edgeInstance) {
707
+ console.error('sendTwinMessage failed: Edge instance not found');
708
+ throw new Error('Edge instance not found');
709
+ }
710
+ const { id: edgeTwinId, deviceId } = edgeInstance;
711
+ if (!deviceId) {
712
+ console.error('sendTwinMessage failed: Device ID not available');
713
+ throw new Error('Device ID not available - ensure device is connected');
714
+ }
715
+ const payload = {
716
+ twinId: targetTwinId,
717
+ sourceTwinId: edgeTwinId,
718
+ sourceDeviceId: deviceId,
719
+ data,
720
+ };
721
+ if (callback) {
722
+ this.emit(this.EVENTS.TWIN_MESSAGE, payload, (response) => {
723
+ callback(response);
728
724
  });
729
725
  }
726
+ else {
727
+ this.emit(this.EVENTS.TWIN_MESSAGE, payload);
728
+ }
730
729
  }
731
730
  async onTwinMessage(targetTwinId, callback) {
732
731
  var _a;
@@ -803,12 +802,14 @@ class PhyHubClient {
803
802
  }
804
803
  }
805
804
  async getTwinById(twinId) {
805
+ console.log(`[getTwinById] Fetching twin: ${twinId}`);
806
806
  const payload = {
807
807
  data: { twinId },
808
808
  };
809
809
  return new Promise((resolve, reject) => {
810
810
  var _a;
811
811
  this.emit(this.EVENTS.GET_TWIN_BY_ID, payload, (response) => {
812
+ console.log(`[getTwinById] Response for ${twinId}:`, response);
812
813
  const { twin } = response;
813
814
  if (!twin) {
814
815
  reject(new Error(`Twin with id ${twinId} not found`));
@@ -817,6 +818,7 @@ class PhyHubClient {
817
818
  resolve(twin);
818
819
  });
819
820
  (_a = this.socket) === null || _a === void 0 ? void 0 : _a.on('error', (error) => {
821
+ console.error(`[getTwinById] Socket error for ${twinId}:`, error);
820
822
  reject(error);
821
823
  });
822
824
  });
@@ -841,6 +843,64 @@ class PhyHubClient {
841
843
  });
842
844
  });
843
845
  }
846
+ async initializeDirectConnectionTwin() {
847
+ console.log('[initializeDirectConnectionTwin] Waiting for authentication...');
848
+ await new Promise((resolve, reject) => {
849
+ var _a;
850
+ const timeout = setTimeout(() => {
851
+ reject(new Error('Timeout waiting for deviceAuthenticated'));
852
+ }, 10000);
853
+ (_a = this.socket) === null || _a === void 0 ? void 0 : _a.once('deviceAuthenticated', (data) => {
854
+ clearTimeout(timeout);
855
+ console.log('[initializeDirectConnectionTwin] Authenticated:', data);
856
+ resolve();
857
+ });
858
+ });
859
+ console.log('[initializeDirectConnectionTwin] Calling connectDevice...');
860
+ return new Promise((resolve, reject) => {
861
+ var _a;
862
+ const timeout = setTimeout(() => {
863
+ reject(new Error('Timeout waiting for connectDevice response'));
864
+ }, 10000);
865
+ (_a = this.socket) === null || _a === void 0 ? void 0 : _a.emit('connectDevice', (response) => {
866
+ var _a;
867
+ clearTimeout(timeout);
868
+ console.log('[initializeDirectConnectionTwin] connectDevice response:', JSON.stringify(response, null, 2));
869
+ if ((response === null || response === void 0 ? void 0 : response.status) === 'success' && ((_a = response === null || response === void 0 ? void 0 : response.twins) === null || _a === void 0 ? void 0 : _a.length) > 0) {
870
+ const deviceTwin = response.twins.find((t) => t.type === 'Device');
871
+ if (deviceTwin) {
872
+ const actualTwinId = deviceTwin.id || deviceTwin._id;
873
+ console.log(`[initializeDirectConnectionTwin] Got device twin. DeviceId: ${deviceTwin.deviceId}, TwinId: ${actualTwinId}`);
874
+ this.instanceId = actualTwinId;
875
+ resolve();
876
+ }
877
+ else {
878
+ console.error('[initializeDirectConnectionTwin] No device twin found in twins array');
879
+ reject(new Error('No device twin found for this device'));
880
+ }
881
+ }
882
+ else if ((response === null || response === void 0 ? void 0 : response.status) === 'error') {
883
+ const errorMessage = (response === null || response === void 0 ? void 0 : response.message) || 'Unknown error';
884
+ console.error('[initializeDirectConnectionTwin] connectDevice failed:', errorMessage);
885
+ if (errorMessage.includes('Failed to find device twin')) {
886
+ console.error('\n=== DEVICE TWIN NOT FOUND ===');
887
+ console.error('This device exists in the legacy database but has not been');
888
+ console.error('properly migrated to PhyHub. The device twins need to be created.');
889
+ console.error('');
890
+ console.error('To fix this:');
891
+ console.error('1. Reset isMigratedToPhyhub flag in legacy DB, OR');
892
+ console.error('2. Use a different device that has been properly migrated');
893
+ console.error('==============================\n');
894
+ }
895
+ reject(new Error(errorMessage));
896
+ }
897
+ else {
898
+ console.error('[initializeDirectConnectionTwin] Unexpected response:', response);
899
+ reject(new Error('Failed to connect device'));
900
+ }
901
+ });
902
+ });
903
+ }
844
904
  }
845
905
  exports.PhyHubClient = PhyHubClient;
846
906
  PhyHubClient.instance = null;
@@ -849,4 +909,8 @@ exports.connectPhyClient = connectPhyClient;
849
909
  exports.default = {
850
910
  connectPhyClient: exports.connectPhyClient,
851
911
  };
912
+ var webrtc_2 = require("./services/webrtc");
913
+ Object.defineProperty(exports, "WebRTCManager", { enumerable: true, get: function () { return webrtc_2.WebRTCManager; } });
914
+ var twin_messaging_2 = require("./twin-messaging");
915
+ Object.defineProperty(exports, "createTwinMessaging", { enumerable: true, get: function () { return twin_messaging_2.createTwinMessaging; } });
852
916
  //# sourceMappingURL=index.js.map