@phystack/hub-client 4.4.52 → 4.4.54

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 (119) hide show
  1. package/dist/index.d.ts +22 -28
  2. package/dist/index.d.ts.map +1 -1
  3. package/dist/index.js +268 -365
  4. package/dist/index.js.map +1 -1
  5. package/dist/peripheral-twin.d.ts +34 -0
  6. package/dist/peripheral-twin.d.ts.map +1 -0
  7. package/dist/peripheral-twin.js +234 -0
  8. package/dist/peripheral-twin.js.map +1 -0
  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 +91 -0
  68. package/dist/twin-messaging.js.map +1 -0
  69. package/dist/twin-registry.d.ts +9 -0
  70. package/dist/twin-registry.d.ts.map +1 -0
  71. package/dist/twin-registry.js +26 -0
  72. package/dist/twin-registry.js.map +1 -0
  73. package/dist/types/index.d.ts +4 -0
  74. package/dist/types/index.d.ts.map +1 -0
  75. package/dist/types/index.js +20 -0
  76. package/dist/types/index.js.map +1 -0
  77. package/dist/types/twin.types.d.ts +66 -15
  78. package/dist/types/twin.types.d.ts.map +1 -1
  79. package/dist/types/twin.types.js +8 -1
  80. package/dist/types/twin.types.js.map +1 -1
  81. package/docs/webrtc-howto.md +398 -0
  82. package/docs/webrtc-test.md +330 -0
  83. package/package.json +3 -3
  84. package/scripts/webrtc-test.sh +401 -0
  85. package/src/index.ts +399 -540
  86. package/src/peripheral-twin.ts +333 -0
  87. package/src/services/phyhub-connection.service.ts +24 -0
  88. package/src/services/phyhub-direct-connection.service.ts +159 -0
  89. package/src/services/webrtc/data-channel-handler.ts +362 -0
  90. package/src/services/webrtc/index.ts +36 -0
  91. package/src/services/webrtc/media-stream-handler.ts +515 -0
  92. package/src/services/webrtc/peer-connection-manager.ts +463 -0
  93. package/src/services/webrtc/types.ts +270 -0
  94. package/src/services/webrtc/webrtc-globals.ts +108 -0
  95. package/src/services/webrtc/webrtc-manager.ts +490 -0
  96. package/src/test/communication-comprehensive-test.ts +533 -0
  97. package/src/test/webrtc-channel-names-test.ts +266 -0
  98. package/src/test/webrtc-comprehensive-test.ts +494 -0
  99. package/src/test/webrtc-reconnect-test.ts +345 -0
  100. package/src/test/webrtc-test-harness.ts +254 -0
  101. package/src/twin-messaging.ts +188 -0
  102. package/src/twin-registry.ts +39 -0
  103. package/src/types/index.ts +3 -0
  104. package/src/types/twin.types.ts +87 -15
  105. package/dist/services/webrtc/datachannel.d.ts +0 -10
  106. package/dist/services/webrtc/datachannel.d.ts.map +0 -1
  107. package/dist/services/webrtc/datachannel.js +0 -290
  108. package/dist/services/webrtc/datachannel.js.map +0 -1
  109. package/dist/services/webrtc/mediastream.d.ts +0 -10
  110. package/dist/services/webrtc/mediastream.d.ts.map +0 -1
  111. package/dist/services/webrtc/mediastream.js +0 -396
  112. package/dist/services/webrtc/mediastream.js.map +0 -1
  113. package/dist/services/webrtc/peer-connection-ice.d.ts +0 -32
  114. package/dist/services/webrtc/peer-connection-ice.d.ts.map +0 -1
  115. package/dist/services/webrtc/peer-connection-ice.js +0 -483
  116. package/dist/services/webrtc/peer-connection-ice.js.map +0 -1
  117. package/src/services/webrtc/datachannel.ts +0 -421
  118. package/src/services/webrtc/mediastream.ts +0 -602
  119. package/src/services/webrtc/peer-connection-ice.ts +0 -689
package/dist/index.js CHANGED
@@ -1,43 +1,15 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.connectPhyClient = exports.PhyHubClient = void 0;
3
+ exports.createTwinMessaging = exports.WebRTCManager = exports.TwinMessageResultStatus = exports.connectPhyClient = exports.PhyHubClient = void 0;
4
4
  const twin_types_1 = require("./types/twin.types");
5
+ Object.defineProperty(exports, "TwinMessageResultStatus", { enumerable: true, get: function () { return twin_types_1.TwinMessageResultStatus; } });
5
6
  const phyhub_connection_service_1 = require("./services/phyhub-connection.service");
7
+ const phyhub_direct_connection_service_1 = require("./services/phyhub-direct-connection.service");
6
8
  const signals_service_1 = require("./services/signals.service");
7
9
  const signal_types_1 = require("./types/signal.types");
8
- const datachannel_1 = require("./services/webrtc/datachannel");
9
- const mediastream_1 = require("./services/webrtc/mediastream");
10
- (async function initializeWebRTCGlobals() {
11
- if (typeof window !== 'undefined')
12
- return;
13
- try {
14
- const wrtc = require('@roamhq/wrtc');
15
- if (typeof global.MediaStream === 'undefined' && wrtc.MediaStream) {
16
- global.MediaStream = wrtc.MediaStream;
17
- console.log('Global MediaStream initialized');
18
- }
19
- if (typeof global.RTCPeerConnection === 'undefined' && wrtc.RTCPeerConnection) {
20
- global.RTCPeerConnection = wrtc.RTCPeerConnection;
21
- console.log('Global RTCPeerConnection initialized');
22
- }
23
- if (typeof global.RTCSessionDescription === 'undefined' && wrtc.RTCSessionDescription) {
24
- global.RTCSessionDescription = wrtc.RTCSessionDescription;
25
- console.log('Global RTCSessionDescription initialized');
26
- }
27
- if (typeof global.RTCIceCandidate === 'undefined' && wrtc.RTCIceCandidate) {
28
- global.RTCIceCandidate = wrtc.RTCIceCandidate;
29
- console.log('Global RTCIceCandidate initialized');
30
- }
31
- if (typeof global.RTCVideoSource === 'undefined' && wrtc.nonstandard.RTCVideoSource) {
32
- global.RTCVideoSource = wrtc.nonstandard.RTCVideoSource;
33
- console.log('Global RTCVideoSource initialized');
34
- }
35
- console.log('WebRTC globals successfully initialized');
36
- }
37
- catch (error) {
38
- console.error('Failed to initialize WebRTC globals:', error);
39
- }
40
- })().catch(err => console.error('Error in WebRTC globals initialization:', err));
10
+ const webrtc_1 = require("./services/webrtc");
11
+ const twin_registry_1 = require("./twin-registry");
12
+ const twin_messaging_1 = require("./twin-messaging");
41
13
  class PhyHubClient {
42
14
  constructor(params = {}) {
43
15
  this.instanceId = undefined;
@@ -50,8 +22,9 @@ class PhyHubClient {
50
22
  this.subscribedTwins = new Set();
51
23
  this.twinMessageListeners = {};
52
24
  this.instances = new Map();
53
- this.peripheralInstances = new Map();
54
25
  this.twinUpdateListeners = {};
26
+ this.twinInstancesRegistry = null;
27
+ this.webrtcManager = null;
55
28
  this.EVENTS = {
56
29
  PING: 'ping',
57
30
  PONG: 'pong',
@@ -109,51 +82,21 @@ class PhyHubClient {
109
82
  this.signals = new signals_service_1.SignalsService(this, initSignalsPayload);
110
83
  return this.signals;
111
84
  };
112
- this.getDataChannel = async (targetTwinId) => {
113
- const options = {
114
- targetTwinId,
115
- sendTwinMessage: this.sendTwinMessage.bind(this),
116
- subscribeTwin: this.subscribeTwin.bind(this),
117
- onTwinMessage: this.onTwinMessage.bind(this),
118
- offTwinMessage: this.offTwinMessage.bind(this),
119
- useStun: true,
120
- isInitiator: true,
121
- channelPrefix: 'channel',
122
- mediaOptions: { isMediaConnection: false },
123
- };
124
- const result = (await (0, datachannel_1.createWebRTCDataChannelConnection)(options));
125
- return result.dataChannel;
85
+ this.getDataChannel = async (targetTwinId, channelName) => {
86
+ const manager = await this.getWebRTCManager();
87
+ return manager.createDataChannel(targetTwinId, channelName);
126
88
  };
127
- this.onDataChannel = async (sourceTwinId, callback) => {
128
- const options = {
129
- targetTwinId: sourceTwinId,
130
- sendTwinMessage: this.sendTwinMessage.bind(this),
131
- subscribeTwin: this.subscribeTwin.bind(this),
132
- onTwinMessage: this.onTwinMessage.bind(this),
133
- offTwinMessage: this.offTwinMessage.bind(this),
134
- useStun: true,
135
- isInitiator: false,
136
- channelPrefix: 'channel',
137
- mediaOptions: { isMediaConnection: false },
138
- };
139
- const result = (await (0, datachannel_1.createWebRTCDataChannelConnection)(options));
140
- 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);
141
93
  };
142
- this.onMediaStream = async (sourceTwinId, callback) => {
143
- const options = {
144
- targetTwinId: sourceTwinId,
145
- sendTwinMessage: this.sendTwinMessage.bind(this),
146
- subscribeTwin: this.subscribeTwin.bind(this),
147
- onTwinMessage: this.onTwinMessage.bind(this),
148
- offTwinMessage: this.offTwinMessage.bind(this),
149
- isInitiator: false,
150
- channelPrefix: 'media',
151
- mediaOptions: {
152
- isMediaConnection: true,
153
- },
154
- };
155
- const result = await (0, mediastream_1.createWebRTCMediaStreamConnection)(options);
156
- 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);
157
100
  };
158
101
  this.instanceId = params.instanceId;
159
102
  if (!this.instanceId) {
@@ -202,6 +145,9 @@ class PhyHubClient {
202
145
  this.setupSocketListeners((value) => value, (reason) => {
203
146
  throw reason;
204
147
  });
148
+ if (phyhub_direct_connection_service_1.PhyHubDirectConnection.isEnabled()) {
149
+ await this.initializeDirectConnectionTwin();
150
+ }
205
151
  return this;
206
152
  }
207
153
  catch (err) {
@@ -247,23 +193,44 @@ class PhyHubClient {
247
193
  this.socket.on(this.EVENTS.DISCONNECT, () => {
248
194
  this.socketConnected = false;
249
195
  });
250
- this.socket.on(this.EVENTS.TWIN_MESSAGE, (payload) => {
251
- if (payload.twinId && payload.data) {
252
- const listeners = this.twinMessageListeners[payload.twinId];
253
- if (listeners) {
254
- listeners.forEach(callback => {
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
+ });
203
+ let result = null;
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
+ }
211
+ if (listeners === null || listeners === void 0 ? void 0 : listeners.size) {
212
+ console.log(`[TWIN_MESSAGE] Executing ${listeners.size} listeners`);
213
+ listeners.forEach(listener => {
255
214
  try {
256
- callback(payload);
215
+ listener(payload);
216
+ result = { status: twin_types_1.TwinMessageResultStatus.Success, message: 'Action completed' };
257
217
  }
258
218
  catch (error) {
259
- console.error(`Error in twin message listener for ${payload.twinId}:`, error);
219
+ console.error(`[TWIN_MESSAGE] Error in listener:`, error);
220
+ result = { status: twin_types_1.TwinMessageResultStatus.Error, message: (error === null || error === void 0 ? void 0 : error.message) || 'An error occurred' };
260
221
  }
261
222
  });
262
223
  }
263
224
  else {
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);
264
230
  }
265
231
  }
266
232
  else {
233
+ console.log('[TWIN_MESSAGE] Invalid payload (no data):', payload);
267
234
  }
268
235
  });
269
236
  this.socket.on('twinUpdated', (payload) => {
@@ -297,6 +264,7 @@ class PhyHubClient {
297
264
  if (!PhyHubClient.instance) {
298
265
  PhyHubClient.instance = new PhyHubClient(params);
299
266
  await PhyHubClient.instance.initializeConnection();
267
+ PhyHubClient.instance.twinInstancesRegistry = new twin_registry_1.TwinRegistry(PhyHubClient.instance);
300
268
  console.info(`connect(): Connection to phyhub initialized`);
301
269
  }
302
270
  return PhyHubClient.instance;
@@ -352,26 +320,43 @@ class PhyHubClient {
352
320
  });
353
321
  });
354
322
  }
355
- async getMediaStream(targetTwinId) {
356
- const options = {
357
- targetTwinId,
358
- sendTwinMessage: this.sendTwinMessage.bind(this),
359
- subscribeTwin: this.subscribeTwin.bind(this),
360
- onTwinMessage: this.onTwinMessage.bind(this),
361
- offTwinMessage: this.offTwinMessage.bind(this),
362
- isInitiator: true,
363
- channelPrefix: 'media',
364
- mediaOptions: {
365
- isMediaConnection: true,
366
- mediaDirection: 'recvonly',
367
- },
368
- };
369
- 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);
370
328
  return {
371
- stream: result.mediaStream,
372
- close: result.close,
329
+ stream,
330
+ close: () => stream.close(),
373
331
  };
374
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
+ }
375
360
  async getInstance() {
376
361
  if (!this.instanceId) {
377
362
  throw new Error('Instance ID not set');
@@ -382,40 +367,12 @@ class PhyHubClient {
382
367
  await this.assureSocketConnection();
383
368
  let instance;
384
369
  let instanceTwin = await this.getTwinById(this.instanceId);
385
- const edgeInstanceTypePrefix = 'edgeInstance';
386
- const edgeTwinEmit = (type, payload) => {
387
- const { id: twinId } = instanceTwin;
388
- const edgeTwinMessagePayload = {
389
- type: `${edgeInstanceTypePrefix}:${type}`,
390
- sourceTwinId: twinId,
391
- sourceDeviceId: instanceTwin.deviceId,
392
- data: payload,
393
- };
394
- this.sendTwinMessage(twinId, edgeTwinMessagePayload);
395
- };
396
- const edgeTwinOn = (type, callback) => {
397
- const { id: twinId } = instanceTwin;
398
- const onEdgeTwinMessage = (payload) => {
399
- var _a, _b;
400
- const messageType = ((_a = payload.data) === null || _a === void 0 ? void 0 : _a.type) || payload.type;
401
- if (messageType === `${edgeInstanceTypePrefix}:${type}`) {
402
- callback(((_b = payload.data) === null || _b === void 0 ? void 0 : _b.data) || payload.data);
403
- }
404
- else {
405
- }
406
- };
407
- this.onTwinMessage(twinId, onEdgeTwinMessage);
408
- };
409
- const edgeTwinTo = (targetTwinId) => ({
410
- emit: (type, payload) => {
411
- const edgeTwinMessagePayload = {
412
- type: `${edgeInstanceTypePrefix}:${type}`,
413
- sourceTwinId: instanceTwin.id,
414
- sourceDeviceId: instanceTwin.deviceId,
415
- data: payload,
416
- };
417
- this.sendTwinMessage(targetTwinId, edgeTwinMessagePayload);
418
- },
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',
419
376
  });
420
377
  const getPeripheralTwins = async () => {
421
378
  const payload = {
@@ -464,23 +421,23 @@ class PhyHubClient {
464
421
  });
465
422
  });
466
423
  };
467
- const getDataChannel = async () => {
468
- return await this.getDataChannel(instanceTwin.id);
424
+ const getDataChannel = async (channelName) => {
425
+ return await this.getDataChannel(instanceTwin.id, channelName);
469
426
  };
470
- const onDataChannel = async (callback) => {
471
- return await this.onDataChannel(instanceTwin.id, callback);
427
+ const onDataChannel = async (callback, channelName) => {
428
+ return await this.onDataChannel(instanceTwin.id, callback, channelName);
472
429
  };
473
- const getMediaStream = async () => {
430
+ const getMediaStream = async (channelName) => {
474
431
  if (!instance) {
475
432
  throw new Error('Instance not initialized');
476
433
  }
477
- return await this.getMediaStream(instance.id);
434
+ return await this.getMediaStream(instance.id, { channelName });
478
435
  };
479
- const onMediaStream = async (callback) => {
436
+ const onMediaStream = async (callback, channelName) => {
480
437
  if (!instance) {
481
438
  throw new Error('Instance not initialized');
482
439
  }
483
- await this.onMediaStream(instance.id, callback);
440
+ await this.onMediaStream(instance.id, callback, { channelName });
484
441
  };
485
442
  const updateReported = async (properties) => {
486
443
  const newReported = {
@@ -492,9 +449,9 @@ class PhyHubClient {
492
449
  };
493
450
  instance = {
494
451
  ...instanceTwin,
495
- emit: edgeTwinEmit,
496
- on: edgeTwinOn,
497
- to: edgeTwinTo,
452
+ emit: messaging.emit,
453
+ on: messaging.on,
454
+ to: messaging.to,
498
455
  createPeripheralTwin,
499
456
  updateReported,
500
457
  getPeripheralTwins,
@@ -513,211 +470,10 @@ class PhyHubClient {
513
470
  return this.getInstance();
514
471
  }
515
472
  async getPeripheralInstance(peripheralTwinId) {
516
- if (this.peripheralInstances.has(peripheralTwinId)) {
517
- return this.peripheralInstances.get(peripheralTwinId);
473
+ if (!this.twinInstancesRegistry) {
474
+ throw new Error('PhyHubClient instance is not initialized yet');
518
475
  }
519
- let peripheralInstance;
520
- const edgeInstance = await this.getInstance();
521
- if (!edgeInstance) {
522
- console.error('Edge instance not found');
523
- throw new Error('Edge instance not found');
524
- }
525
- const peripheralTwin = await this.getTwinById(peripheralTwinId);
526
- if (!peripheralTwin) {
527
- console.error(`Peripheral twin with id ${peripheralTwinId} not found`);
528
- throw new Error(`Peripheral twin with id ${peripheralTwinId} not found`);
529
- }
530
- if (peripheralTwin.type !== twin_types_1.TwinTypeEnum.Peripheral) {
531
- throw new Error(`Twin ${peripheralTwinId} is not a peripheral twin`);
532
- }
533
- await this.subscribeTwin(peripheralTwinId);
534
- const instanceTypePrefix = 'peripheralInstance';
535
- const peripheralTwinEmit = (type, payload) => {
536
- const messagePayload = {
537
- type: `${instanceTypePrefix}:${peripheralTwin.id}:${type}`,
538
- sourceTwinId: peripheralTwin.id,
539
- sourceDeviceId: edgeInstance.deviceId,
540
- data: payload,
541
- };
542
- this.sendTwinMessage(peripheralTwin.id, messagePayload);
543
- };
544
- const peripheralTwinOn = (type, callback) => {
545
- console.log(`Setting up listener for peripheral ${peripheralTwinId} event: ${type}`);
546
- const onMessage = (payload) => {
547
- var _a, _b;
548
- const messageType = ((_a = payload.data) === null || _a === void 0 ? void 0 : _a.type) || payload.type;
549
- if (messageType === `${instanceTypePrefix}:${peripheralTwin.id}:${type}`) {
550
- callback(((_b = payload.data) === null || _b === void 0 ? void 0 : _b.data) || payload.data);
551
- }
552
- else {
553
- }
554
- };
555
- this.onTwinMessage(peripheralTwin.id, onMessage);
556
- };
557
- const peripheralTwinTo = (targetTwinId) => ({
558
- emit: (type, payload) => {
559
- const messagePayload = {
560
- type: `${instanceTypePrefix}:${peripheralTwin.id}:${type}`,
561
- sourceTwinId: edgeInstance.id,
562
- sourceDeviceId: edgeInstance.deviceId,
563
- data: payload,
564
- };
565
- this.sendTwinMessage(targetTwinId, messagePayload);
566
- },
567
- });
568
- const getDataChannel = async () => {
569
- return await this.getDataChannel(peripheralTwin.id);
570
- };
571
- const onDataChannel = async (callback) => {
572
- return await this.onDataChannel(peripheralTwin.id, callback);
573
- };
574
- const getMediaStream = async () => {
575
- if (!peripheralInstance) {
576
- throw new Error('Peripheral instance not initialized');
577
- }
578
- return await this.getMediaStream(peripheralInstance.id);
579
- };
580
- const onMediaStream = async (callback) => {
581
- if (!peripheralInstance) {
582
- throw new Error('Peripheral instance not initialized');
583
- }
584
- await this.onMediaStream(peripheralInstance.id, callback);
585
- };
586
- const updateReported = async (properties) => {
587
- const newReported = {
588
- ...properties,
589
- };
590
- const result = await this.updateReportedProperties(peripheralTwin.id, newReported);
591
- Object.assign(peripheralInstance, result);
592
- return result;
593
- };
594
- const onUpdateReported = (callback) => {
595
- let previousProperties = undefined;
596
- console.log(`[onUpdateReported] Registering handler for all reported properties`);
597
- this.onTwinUpdate(peripheralTwin.id, (twin) => {
598
- console.log(`[onUpdateReported] Twin update received for ${peripheralTwin.id}`);
599
- if (twin.id !== peripheralTwin.id) {
600
- console.log(`[onUpdateReported] Twin ID mismatch: ${twin.id} !== ${peripheralTwin.id}`);
601
- return;
602
- }
603
- const reported = twin.properties.reported;
604
- if (reported) {
605
- if (previousProperties === undefined) {
606
- console.log(`[onUpdateReported] First update - calling callback`);
607
- previousProperties = JSON.parse(JSON.stringify(reported));
608
- callback(reported);
609
- return;
610
- }
611
- const currentPropertiesStr = JSON.stringify(reported);
612
- const previousPropertiesStr = JSON.stringify(previousProperties);
613
- console.log(`[onUpdateReported] Current (end): ...${currentPropertiesStr.substring(currentPropertiesStr.length - 100)}`);
614
- console.log(`[onUpdateReported] Previous (end): ...${previousPropertiesStr.substring(previousPropertiesStr.length - 100)}`);
615
- if (currentPropertiesStr.length !== previousPropertiesStr.length) {
616
- console.log(`[onUpdateReported] String length changed: ${currentPropertiesStr.length} vs ${previousPropertiesStr.length}`);
617
- }
618
- const hasChanged = currentPropertiesStr !== previousPropertiesStr;
619
- console.log(`[onUpdateReported] Properties comparison:`, hasChanged ? 'CHANGED' : 'UNCHANGED');
620
- if (hasChanged) {
621
- previousProperties = JSON.parse(currentPropertiesStr);
622
- console.log(`[onUpdateReported] Calling callback with updated reported properties`);
623
- callback(reported);
624
- }
625
- else {
626
- console.log(`[onUpdateReported] No change detected in properties`);
627
- }
628
- }
629
- else {
630
- console.log(`[onUpdateReported] No reported properties found`);
631
- }
632
- });
633
- };
634
- const onUpdateDesired = (callback) => {
635
- let previousProperties = undefined;
636
- console.log(`[onUpdateDesired] Registering handler for all desired properties`);
637
- this.onTwinUpdate(peripheralTwin.id, (twin) => {
638
- console.log(`[onUpdateDesired] Twin update received for ${peripheralTwin.id}`);
639
- if (twin.id !== peripheralTwin.id) {
640
- console.log(`[onUpdateDesired] Twin ID mismatch: ${twin.id} !== ${peripheralTwin.id}`);
641
- return;
642
- }
643
- const desired = twin.properties.desired;
644
- if (desired) {
645
- if (previousProperties === undefined) {
646
- console.log(`[onUpdateDesired] First update - calling callback`);
647
- previousProperties = JSON.parse(JSON.stringify(desired));
648
- callback(desired);
649
- return;
650
- }
651
- const currentPropertiesStr = JSON.stringify(desired);
652
- const previousPropertiesStr = JSON.stringify(previousProperties);
653
- console.log(`[onUpdateDesired] Current (end): ...${currentPropertiesStr.substring(currentPropertiesStr.length - 100)}`);
654
- console.log(`[onUpdateDesired] Previous (end): ...${previousPropertiesStr.substring(previousPropertiesStr.length - 100)}`);
655
- if (currentPropertiesStr.length !== previousPropertiesStr.length) {
656
- console.log(`[onUpdateDesired] String length changed: ${currentPropertiesStr.length} vs ${previousPropertiesStr.length}`);
657
- }
658
- const hasChanged = currentPropertiesStr !== previousPropertiesStr;
659
- console.log(`[onUpdateDesired] Properties comparison:`, hasChanged ? 'CHANGED' : 'UNCHANGED');
660
- if (hasChanged) {
661
- previousProperties = JSON.parse(currentPropertiesStr);
662
- console.log(`[onUpdateDesired] Calling callback with updated desired properties`);
663
- callback(desired);
664
- }
665
- else {
666
- console.log(`[onUpdateDesired] No change detected in properties`);
667
- }
668
- }
669
- else {
670
- console.log(`[onUpdateDesired] No desired properties found`);
671
- }
672
- });
673
- };
674
- const remove = async () => {
675
- const payload = {
676
- data: { twinId: peripheralTwin.id },
677
- };
678
- return new Promise((resolve, reject) => {
679
- var _a;
680
- this.emit('deletePeripheralTwin', payload, (response) => {
681
- const { twin } = response;
682
- resolve(twin);
683
- });
684
- (_a = this.socket) === null || _a === void 0 ? void 0 : _a.on('error', (error) => {
685
- reject(error);
686
- });
687
- });
688
- };
689
- const updateDesired = async (properties) => {
690
- const payload = {
691
- twinId: peripheralTwin.id,
692
- data: properties,
693
- };
694
- return new Promise((resolve, reject) => {
695
- var _a;
696
- this.emit('updatePeripheralTwinDesired', payload, (response) => {
697
- const { twin } = response;
698
- resolve(twin || {});
699
- });
700
- (_a = this.socket) === null || _a === void 0 ? void 0 : _a.on('error', (error) => {
701
- reject(error);
702
- });
703
- });
704
- };
705
- peripheralInstance = {
706
- ...peripheralTwin,
707
- emit: peripheralTwinEmit,
708
- on: peripheralTwinOn,
709
- to: peripheralTwinTo,
710
- updateReported,
711
- updateDesired,
712
- onUpdateReported,
713
- onUpdateDesired,
714
- remove,
715
- getDataChannel,
716
- onDataChannel,
717
- getMediaStream,
718
- onMediaStream,
719
- };
720
- this.peripheralInstances.set(peripheralTwinId, peripheralInstance);
476
+ const peripheralInstance = await this.twinInstancesRegistry.getPeripheralInstance(peripheralTwinId);
721
477
  return peripheralInstance;
722
478
  }
723
479
  getGridApp() {
@@ -732,7 +488,7 @@ class PhyHubClient {
732
488
  break;
733
489
  currentWindow = currentWindow.parent;
734
490
  }
735
- catch (e) {
491
+ catch (_a) {
736
492
  break;
737
493
  }
738
494
  }
@@ -799,10 +555,17 @@ class PhyHubClient {
799
555
  console.error('emit(): Socket not created');
800
556
  return;
801
557
  }
802
- const event = this.instanceId;
803
558
  const callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined;
804
- const payload = { method, ...args[0] };
805
- 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
+ }
806
569
  if (callback) {
807
570
  emitArgs.push(callback);
808
571
  }
@@ -854,15 +617,37 @@ class PhyHubClient {
854
617
  }
855
618
  return result;
856
619
  }
857
- 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');
858
643
  const edgeInstance = await this.getInstance();
859
644
  if (!edgeInstance) {
860
- console.error('sendTwinMessage failed: Edge instance not found');
645
+ console.error('[request] Edge instance not found');
861
646
  throw new Error('Edge instance not found');
862
647
  }
863
648
  const { id: edgeTwinId, deviceId } = edgeInstance;
864
649
  if (!deviceId) {
865
- console.error('sendTwinMessage failed: Device ID not available');
650
+ console.error('[request] Device ID not available');
866
651
  throw new Error('Device ID not available - ensure device is connected');
867
652
  }
868
653
  const payload = {
@@ -875,19 +660,72 @@ class PhyHubClient {
875
660
  this.emit(this.EVENTS.TWIN_MESSAGE, payload, (response) => {
876
661
  callback(response);
877
662
  });
663
+ return;
878
664
  }
879
- else {
880
- return new Promise((resolve, reject) => {
665
+ return new Promise((resolve, reject) => {
666
+ var _a;
667
+ const ACTION_TIMEOUT = 10 * 1000;
668
+ const timeoutId = setTimeout(() => {
881
669
  var _a;
882
- this.emit(this.EVENTS.TWIN_MESSAGE, payload, (response) => {
883
- resolve(response);
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`
884
676
  });
885
- (_a = this.socket) === null || _a === void 0 ? void 0 : _a.on('error', (error) => {
886
- console.error('sendTwinMessage socket error:', error);
887
- reject(error);
677
+ }, ACTION_TIMEOUT);
678
+ if (this.socket) {
679
+ this.socket.on(payload.data.type, (response) => {
680
+ var _a;
681
+ if (response && response.status !== twin_types_1.TwinMessageResultStatus.Warning) {
682
+ clearTimeout(timeoutId);
683
+ (_a = this.socket) === null || _a === void 0 ? void 0 : _a.off(payload.data.type);
684
+ resolve(response);
685
+ }
888
686
  });
687
+ }
688
+ this.emit(this.EVENTS.TWIN_MESSAGE, payload, (response) => {
689
+ var _a;
690
+ clearTimeout(timeoutId);
691
+ if (this.socket) {
692
+ (_a = this.socket) === null || _a === void 0 ? void 0 : _a.off(payload.data.type);
693
+ }
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);
889
724
  });
890
725
  }
726
+ else {
727
+ this.emit(this.EVENTS.TWIN_MESSAGE, payload);
728
+ }
891
729
  }
892
730
  async onTwinMessage(targetTwinId, callback) {
893
731
  var _a;
@@ -964,12 +802,14 @@ class PhyHubClient {
964
802
  }
965
803
  }
966
804
  async getTwinById(twinId) {
805
+ console.log(`[getTwinById] Fetching twin: ${twinId}`);
967
806
  const payload = {
968
807
  data: { twinId },
969
808
  };
970
809
  return new Promise((resolve, reject) => {
971
810
  var _a;
972
811
  this.emit(this.EVENTS.GET_TWIN_BY_ID, payload, (response) => {
812
+ console.log(`[getTwinById] Response for ${twinId}:`, response);
973
813
  const { twin } = response;
974
814
  if (!twin) {
975
815
  reject(new Error(`Twin with id ${twinId} not found`));
@@ -978,6 +818,7 @@ class PhyHubClient {
978
818
  resolve(twin);
979
819
  });
980
820
  (_a = this.socket) === null || _a === void 0 ? void 0 : _a.on('error', (error) => {
821
+ console.error(`[getTwinById] Socket error for ${twinId}:`, error);
981
822
  reject(error);
982
823
  });
983
824
  });
@@ -1002,6 +843,64 @@ class PhyHubClient {
1002
843
  });
1003
844
  });
1004
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
+ }
1005
904
  }
1006
905
  exports.PhyHubClient = PhyHubClient;
1007
906
  PhyHubClient.instance = null;
@@ -1010,4 +909,8 @@ exports.connectPhyClient = connectPhyClient;
1010
909
  exports.default = {
1011
910
  connectPhyClient: exports.connectPhyClient,
1012
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; } });
1013
916
  //# sourceMappingURL=index.js.map