@phystack/hub-client 4.5.19-dev → 4.5.21-dev

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 +252 -378
  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 +383 -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 +336 -0
  32. package/dist/services/webrtc/peer-connection-manager.js.map +1 -0
  33. package/dist/services/webrtc/types.d.ts +134 -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 +20 -0
  66. package/dist/twin-messaging.d.ts.map +1 -0
  67. package/dist/twin-messaging.js +94 -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 +62 -14
  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 +378 -568
  86. package/src/peripheral-twin.ts +337 -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 +536 -0
  92. package/src/services/webrtc/peer-connection-manager.ts +467 -0
  93. package/src/services/webrtc/types.ts +273 -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 +184 -0
  102. package/src/twin-registry.ts +39 -0
  103. package/src/types/index.ts +3 -0
  104. package/src/types/twin.types.ts +80 -14
  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,28 @@ 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) => {
196
+ this.socket.on(this.EVENTS.TWIN_MESSAGE, (payload, callback) => {
197
+ let result = null;
251
198
  if (payload.twinId && payload.data) {
252
199
  const listeners = this.twinMessageListeners[payload.twinId];
253
- if (listeners) {
254
- listeners.forEach(callback => {
200
+ if (listeners === null || listeners === void 0 ? void 0 : listeners.size) {
201
+ listeners.forEach(listener => {
255
202
  try {
256
- callback(payload);
203
+ listener(payload);
204
+ result = { status: twin_types_1.TwinMessageResultStatus.Success, message: 'Action completed' };
257
205
  }
258
206
  catch (error) {
259
- console.error(`Error in twin message listener for ${payload.twinId}:`, error);
207
+ console.error(`[TWIN_MESSAGE] Error in listener for ${payload.twinId}:`, error);
208
+ result = { status: twin_types_1.TwinMessageResultStatus.Error, message: (error === null || error === void 0 ? void 0 : error.message) || 'An error occurred' };
260
209
  }
261
210
  });
262
211
  }
263
212
  else {
213
+ result = { status: twin_types_1.TwinMessageResultStatus.Warning, message: `No listeners found for twin ${payload.twinId}` };
214
+ }
215
+ if (callback) {
216
+ callback(result);
264
217
  }
265
- }
266
- else {
267
218
  }
268
219
  });
269
220
  this.socket.on('twinUpdated', (payload) => {
@@ -297,6 +248,7 @@ class PhyHubClient {
297
248
  if (!PhyHubClient.instance) {
298
249
  PhyHubClient.instance = new PhyHubClient(params);
299
250
  await PhyHubClient.instance.initializeConnection();
251
+ PhyHubClient.instance.twinInstancesRegistry = new twin_registry_1.TwinRegistry(PhyHubClient.instance);
300
252
  console.info(`connect(): Connection to phyhub initialized`);
301
253
  }
302
254
  return PhyHubClient.instance;
@@ -352,26 +304,43 @@ class PhyHubClient {
352
304
  });
353
305
  });
354
306
  }
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);
307
+ async getMediaStream(targetTwinId, options) {
308
+ var _a;
309
+ const manager = await this.getWebRTCManager();
310
+ const channelName = (_a = options === null || options === void 0 ? void 0 : options.channelName) !== null && _a !== void 0 ? _a : 'default';
311
+ const stream = await manager.createMediaStream(targetTwinId, options, channelName);
370
312
  return {
371
- stream: result.mediaStream,
372
- close: result.close,
313
+ stream,
314
+ close: () => stream.close(),
373
315
  };
374
316
  }
317
+ async getWebRTCManager(options) {
318
+ if (!this.webrtcManager) {
319
+ await this.assureSocketConnection();
320
+ const twinMessaging = {
321
+ sendMessage: async (targetTwinId, data) => {
322
+ await this.sendTwinMessage(targetTwinId, data);
323
+ },
324
+ subscribe: async (twinId) => {
325
+ await this.subscribeTwin(twinId);
326
+ },
327
+ onMessage: (twinId, callback) => {
328
+ this.onTwinMessage(twinId, callback);
329
+ },
330
+ offMessage: (twinId, callback) => {
331
+ this.offTwinMessage(twinId, callback);
332
+ },
333
+ getOwnTwinId: () => {
334
+ if (!this.instanceId) {
335
+ throw new Error('Instance ID not set');
336
+ }
337
+ return this.instanceId;
338
+ },
339
+ };
340
+ this.webrtcManager = new webrtc_1.WebRTCManager(twinMessaging, options);
341
+ }
342
+ return this.webrtcManager;
343
+ }
375
344
  async getInstance() {
376
345
  if (!this.instanceId) {
377
346
  throw new Error('Instance ID not set');
@@ -382,40 +351,12 @@ class PhyHubClient {
382
351
  await this.assureSocketConnection();
383
352
  let instance;
384
353
  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
- },
354
+ const messaging = (0, twin_messaging_1.createTwinMessaging)({
355
+ sendEvent: (targetTwinId, payload) => this.sendEvent(targetTwinId, payload),
356
+ onTwinMessage: (twinId, callback) => this.onTwinMessage(twinId, callback),
357
+ twinId: instanceTwin.id,
358
+ deviceId: instanceTwin.deviceId,
359
+ typePrefix: 'edgeInstance',
419
360
  });
420
361
  const getPeripheralTwins = async () => {
421
362
  const payload = {
@@ -464,23 +405,23 @@ class PhyHubClient {
464
405
  });
465
406
  });
466
407
  };
467
- const getDataChannel = async () => {
468
- return await this.getDataChannel(instanceTwin.id);
408
+ const getDataChannel = async (channelName) => {
409
+ return await this.getDataChannel(instanceTwin.id, channelName);
469
410
  };
470
- const onDataChannel = async (callback) => {
471
- return await this.onDataChannel(instanceTwin.id, callback);
411
+ const onDataChannel = async (callback, channelName) => {
412
+ return await this.onDataChannel(instanceTwin.id, callback, channelName);
472
413
  };
473
- const getMediaStream = async () => {
414
+ const getMediaStream = async (channelName) => {
474
415
  if (!instance) {
475
416
  throw new Error('Instance not initialized');
476
417
  }
477
- return await this.getMediaStream(instance.id);
418
+ return await this.getMediaStream(instance.id, { channelName });
478
419
  };
479
- const onMediaStream = async (callback) => {
420
+ const onMediaStream = async (callback, channelName) => {
480
421
  if (!instance) {
481
422
  throw new Error('Instance not initialized');
482
423
  }
483
- await this.onMediaStream(instance.id, callback);
424
+ await this.onMediaStream(instance.id, callback, { channelName });
484
425
  };
485
426
  const updateReported = async (properties) => {
486
427
  const newReported = {
@@ -492,9 +433,9 @@ class PhyHubClient {
492
433
  };
493
434
  instance = {
494
435
  ...instanceTwin,
495
- emit: edgeTwinEmit,
496
- on: edgeTwinOn,
497
- to: edgeTwinTo,
436
+ emit: messaging.emit,
437
+ on: messaging.on,
438
+ to: messaging.to,
498
439
  createPeripheralTwin,
499
440
  updateReported,
500
441
  getPeripheralTwins,
@@ -513,211 +454,10 @@ class PhyHubClient {
513
454
  return this.getInstance();
514
455
  }
515
456
  async getPeripheralInstance(peripheralTwinId) {
516
- if (this.peripheralInstances.has(peripheralTwinId)) {
517
- return this.peripheralInstances.get(peripheralTwinId);
518
- }
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');
457
+ if (!this.twinInstancesRegistry) {
458
+ throw new Error('PhyHubClient instance is not initialized yet');
524
459
  }
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);
460
+ const peripheralInstance = await this.twinInstancesRegistry.getPeripheralInstance(peripheralTwinId);
721
461
  return peripheralInstance;
722
462
  }
723
463
  getGridApp() {
@@ -732,7 +472,7 @@ class PhyHubClient {
732
472
  break;
733
473
  currentWindow = currentWindow.parent;
734
474
  }
735
- catch (e) {
475
+ catch (_a) {
736
476
  break;
737
477
  }
738
478
  }
@@ -799,10 +539,17 @@ class PhyHubClient {
799
539
  console.error('emit(): Socket not created');
800
540
  return;
801
541
  }
802
- const event = this.instanceId;
803
542
  const callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined;
804
- const payload = { method, ...args[0] };
805
- const emitArgs = [event, payload];
543
+ let emitArgs;
544
+ if (phyhub_direct_connection_service_1.PhyHubDirectConnection.isEnabled()) {
545
+ const payload = args[0] || {};
546
+ emitArgs = [method, payload];
547
+ }
548
+ else {
549
+ const event = this.instanceId;
550
+ const payload = { method, ...args[0] };
551
+ emitArgs = [event, payload];
552
+ }
806
553
  if (callback) {
807
554
  emitArgs.push(callback);
808
555
  }
@@ -854,15 +601,37 @@ class PhyHubClient {
854
601
  }
855
602
  return result;
856
603
  }
857
- async sendTwinMessage(targetTwinId, data, callback) {
604
+ sendEvent(targetTwinId, data) {
605
+ var _a;
606
+ const instanceId = this.instanceId;
607
+ if (!instanceId) {
608
+ console.error('[sendEvent] Instance ID not set, cannot send event');
609
+ return;
610
+ }
611
+ const cachedInstance = this.instances.get(instanceId);
612
+ const deviceId = (cachedInstance === null || cachedInstance === void 0 ? void 0 : cachedInstance.deviceId) || ((_a = this.lastDeviceStatusResponse) === null || _a === void 0 ? void 0 : _a.deviceId);
613
+ if (!deviceId) {
614
+ console.error('[sendEvent] Device ID not available, cannot send event');
615
+ return;
616
+ }
617
+ const payload = {
618
+ twinId: targetTwinId,
619
+ sourceTwinId: instanceId,
620
+ sourceDeviceId: deviceId,
621
+ data,
622
+ };
623
+ this.emit(this.EVENTS.TWIN_MESSAGE, payload);
624
+ }
625
+ async request(targetTwinId, data, callback) {
626
+ console.log('[request] Sending to:', targetTwinId, 'data type:', (data === null || data === void 0 ? void 0 : data.type) || 'unknown');
858
627
  const edgeInstance = await this.getInstance();
859
628
  if (!edgeInstance) {
860
- console.error('sendTwinMessage failed: Edge instance not found');
629
+ console.error('[request] Edge instance not found');
861
630
  throw new Error('Edge instance not found');
862
631
  }
863
632
  const { id: edgeTwinId, deviceId } = edgeInstance;
864
633
  if (!deviceId) {
865
- console.error('sendTwinMessage failed: Device ID not available');
634
+ console.error('[request] Device ID not available');
866
635
  throw new Error('Device ID not available - ensure device is connected');
867
636
  }
868
637
  const payload = {
@@ -875,32 +644,78 @@ class PhyHubClient {
875
644
  this.emit(this.EVENTS.TWIN_MESSAGE, payload, (response) => {
876
645
  callback(response);
877
646
  });
647
+ return;
878
648
  }
879
- else {
880
- return new Promise((resolve, reject) => {
649
+ return new Promise((resolve, reject) => {
650
+ var _a;
651
+ const ACTION_TIMEOUT = 10 * 1000;
652
+ const timeoutId = setTimeout(() => {
881
653
  var _a;
882
- this.emit(this.EVENTS.TWIN_MESSAGE, payload, (response) => {
883
- resolve(response);
654
+ if (this.socket) {
655
+ (_a = this.socket) === null || _a === void 0 ? void 0 : _a.off(payload.data.type);
656
+ }
657
+ reject({
658
+ status: twin_types_1.TwinMessageResultStatus.Error,
659
+ message: `Request timed out after ${ACTION_TIMEOUT}ms`
884
660
  });
885
- (_a = this.socket) === null || _a === void 0 ? void 0 : _a.on('error', (error) => {
886
- console.error('sendTwinMessage socket error:', error);
887
- reject(error);
661
+ }, ACTION_TIMEOUT);
662
+ if (this.socket) {
663
+ this.socket.on(payload.data.type, (response) => {
664
+ var _a;
665
+ if (response && response.status !== twin_types_1.TwinMessageResultStatus.Warning) {
666
+ clearTimeout(timeoutId);
667
+ (_a = this.socket) === null || _a === void 0 ? void 0 : _a.off(payload.data.type);
668
+ resolve(response);
669
+ }
888
670
  });
671
+ }
672
+ this.emit(this.EVENTS.TWIN_MESSAGE, payload, (response) => {
673
+ var _a;
674
+ clearTimeout(timeoutId);
675
+ if (this.socket) {
676
+ (_a = this.socket) === null || _a === void 0 ? void 0 : _a.off(payload.data.type);
677
+ }
678
+ resolve(response);
679
+ });
680
+ (_a = this.socket) === null || _a === void 0 ? void 0 : _a.on('error', (error) => {
681
+ clearTimeout(timeoutId);
682
+ console.error('[request] Socket error:', error);
683
+ reject(error);
684
+ });
685
+ });
686
+ }
687
+ async sendTwinMessage(targetTwinId, data, callback) {
688
+ console.log('[sendTwinMessage] Sending to:', targetTwinId, 'data type:', (data === null || data === void 0 ? void 0 : data.type) || 'unknown');
689
+ const edgeInstance = await this.getInstance();
690
+ if (!edgeInstance) {
691
+ console.error('sendTwinMessage failed: Edge instance not found');
692
+ throw new Error('Edge instance not found');
693
+ }
694
+ const { id: edgeTwinId, deviceId } = edgeInstance;
695
+ if (!deviceId) {
696
+ console.error('sendTwinMessage failed: Device ID not available');
697
+ throw new Error('Device ID not available - ensure device is connected');
698
+ }
699
+ const payload = {
700
+ twinId: targetTwinId,
701
+ sourceTwinId: edgeTwinId,
702
+ sourceDeviceId: deviceId,
703
+ data,
704
+ };
705
+ if (callback) {
706
+ this.emit(this.EVENTS.TWIN_MESSAGE, payload, (response) => {
707
+ callback(response);
889
708
  });
890
709
  }
710
+ else {
711
+ this.emit(this.EVENTS.TWIN_MESSAGE, payload);
712
+ }
891
713
  }
892
714
  async onTwinMessage(targetTwinId, callback) {
893
- var _a;
894
- console.log('onTwinMessage called for twin:', {
895
- targetTwinId,
896
- existingListeners: ((_a = this.twinMessageListeners[targetTwinId]) === null || _a === void 0 ? void 0 : _a.size) || 0,
897
- });
898
715
  if (!this.twinMessageListeners[targetTwinId]) {
899
716
  this.twinMessageListeners[targetTwinId] = new Set();
900
717
  }
901
718
  this.twinMessageListeners[targetTwinId].add(callback);
902
- console.log(`Added new callback. Total listeners: ${this.twinMessageListeners[targetTwinId].size}`);
903
- this.twinMessageListeners[targetTwinId].add(callback);
904
719
  }
905
720
  offTwinMessage(targetTwinId, callback) {
906
721
  console.log(`Removing message listener for twin ${targetTwinId}`);
@@ -928,9 +743,6 @@ class PhyHubClient {
928
743
  }
929
744
  }
930
745
  async subscribeTwin(targetTwinId, callback) {
931
- console.log(`[subscribeTwin] Starting subscription to twin ${targetTwinId}`);
932
- console.log(`[subscribeTwin] Current subscribed twins:`, Array.from(this.subscribedTwins));
933
- console.log(`[subscribeTwin] Current listeners:`, Object.keys(this.twinMessageListeners));
934
746
  this.subscribedTwins.add(targetTwinId);
935
747
  const edgeInstance = await this.getInstance();
936
748
  if (!edgeInstance) {
@@ -942,10 +754,8 @@ class PhyHubClient {
942
754
  sourceTwinId: edgeTwinId,
943
755
  sourceDeviceId: deviceId,
944
756
  };
945
- console.log(`[subscribeTwin] Emitting TWIN_SUBSCRIBE with payload:`, payload);
946
757
  if (callback) {
947
758
  this.emit(this.EVENTS.TWIN_SUBSCRIBE, payload, (response) => {
948
- console.log(`[subscribeTwin] Subscription callback response:`, response);
949
759
  callback(response);
950
760
  });
951
761
  }
@@ -953,7 +763,6 @@ class PhyHubClient {
953
763
  return new Promise((resolve, reject) => {
954
764
  var _a;
955
765
  this.emit(this.EVENTS.TWIN_SUBSCRIBE, payload, (response) => {
956
- console.log(`[subscribeTwin] Subscription promise response:`, response);
957
766
  resolve(response);
958
767
  });
959
768
  (_a = this.socket) === null || _a === void 0 ? void 0 : _a.on('error', (error) => {
@@ -964,12 +773,14 @@ class PhyHubClient {
964
773
  }
965
774
  }
966
775
  async getTwinById(twinId) {
776
+ console.log(`[getTwinById] Fetching twin: ${twinId}`);
967
777
  const payload = {
968
778
  data: { twinId },
969
779
  };
970
780
  return new Promise((resolve, reject) => {
971
781
  var _a;
972
782
  this.emit(this.EVENTS.GET_TWIN_BY_ID, payload, (response) => {
783
+ console.log(`[getTwinById] Response for ${twinId}:`, response);
973
784
  const { twin } = response;
974
785
  if (!twin) {
975
786
  reject(new Error(`Twin with id ${twinId} not found`));
@@ -978,6 +789,7 @@ class PhyHubClient {
978
789
  resolve(twin);
979
790
  });
980
791
  (_a = this.socket) === null || _a === void 0 ? void 0 : _a.on('error', (error) => {
792
+ console.error(`[getTwinById] Socket error for ${twinId}:`, error);
981
793
  reject(error);
982
794
  });
983
795
  });
@@ -1002,6 +814,64 @@ class PhyHubClient {
1002
814
  });
1003
815
  });
1004
816
  }
817
+ async initializeDirectConnectionTwin() {
818
+ console.log('[initializeDirectConnectionTwin] Waiting for authentication...');
819
+ await new Promise((resolve, reject) => {
820
+ var _a;
821
+ const timeout = setTimeout(() => {
822
+ reject(new Error('Timeout waiting for deviceAuthenticated'));
823
+ }, 10000);
824
+ (_a = this.socket) === null || _a === void 0 ? void 0 : _a.once('deviceAuthenticated', (data) => {
825
+ clearTimeout(timeout);
826
+ console.log('[initializeDirectConnectionTwin] Authenticated:', data);
827
+ resolve();
828
+ });
829
+ });
830
+ console.log('[initializeDirectConnectionTwin] Calling connectDevice...');
831
+ return new Promise((resolve, reject) => {
832
+ var _a;
833
+ const timeout = setTimeout(() => {
834
+ reject(new Error('Timeout waiting for connectDevice response'));
835
+ }, 10000);
836
+ (_a = this.socket) === null || _a === void 0 ? void 0 : _a.emit('connectDevice', (response) => {
837
+ var _a;
838
+ clearTimeout(timeout);
839
+ console.log('[initializeDirectConnectionTwin] connectDevice response:', JSON.stringify(response, null, 2));
840
+ 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) {
841
+ const deviceTwin = response.twins.find((t) => t.type === 'Device');
842
+ if (deviceTwin) {
843
+ const actualTwinId = deviceTwin.id || deviceTwin._id;
844
+ console.log(`[initializeDirectConnectionTwin] Got device twin. DeviceId: ${deviceTwin.deviceId}, TwinId: ${actualTwinId}`);
845
+ this.instanceId = actualTwinId;
846
+ resolve();
847
+ }
848
+ else {
849
+ console.error('[initializeDirectConnectionTwin] No device twin found in twins array');
850
+ reject(new Error('No device twin found for this device'));
851
+ }
852
+ }
853
+ else if ((response === null || response === void 0 ? void 0 : response.status) === 'error') {
854
+ const errorMessage = (response === null || response === void 0 ? void 0 : response.message) || 'Unknown error';
855
+ console.error('[initializeDirectConnectionTwin] connectDevice failed:', errorMessage);
856
+ if (errorMessage.includes('Failed to find device twin')) {
857
+ console.error('\n=== DEVICE TWIN NOT FOUND ===');
858
+ console.error('This device exists in the legacy database but has not been');
859
+ console.error('properly migrated to PhyHub. The device twins need to be created.');
860
+ console.error('');
861
+ console.error('To fix this:');
862
+ console.error('1. Reset isMigratedToPhyhub flag in legacy DB, OR');
863
+ console.error('2. Use a different device that has been properly migrated');
864
+ console.error('==============================\n');
865
+ }
866
+ reject(new Error(errorMessage));
867
+ }
868
+ else {
869
+ console.error('[initializeDirectConnectionTwin] Unexpected response:', response);
870
+ reject(new Error('Failed to connect device'));
871
+ }
872
+ });
873
+ });
874
+ }
1005
875
  }
1006
876
  exports.PhyHubClient = PhyHubClient;
1007
877
  PhyHubClient.instance = null;
@@ -1010,4 +880,8 @@ exports.connectPhyClient = connectPhyClient;
1010
880
  exports.default = {
1011
881
  connectPhyClient: exports.connectPhyClient,
1012
882
  };
883
+ var webrtc_2 = require("./services/webrtc");
884
+ Object.defineProperty(exports, "WebRTCManager", { enumerable: true, get: function () { return webrtc_2.WebRTCManager; } });
885
+ var twin_messaging_2 = require("./twin-messaging");
886
+ Object.defineProperty(exports, "createTwinMessaging", { enumerable: true, get: function () { return twin_messaging_2.createTwinMessaging; } });
1013
887
  //# sourceMappingURL=index.js.map