@ray-js/robot-data-stream 0.0.17-beta.9 → 0.1.0-beta.1

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 (53) hide show
  1. package/README.md +23 -1
  2. package/lib/api/index.d.ts +1 -0
  3. package/lib/api/p2pApi.d.ts +30 -7
  4. package/lib/api/p2pApi.js +68 -28
  5. package/lib/api/sweeperP2p.d.ts +31 -1
  6. package/lib/api/sweeperP2p.js +360 -35
  7. package/lib/index.d.ts +15 -9
  8. package/lib/index.js +65 -3
  9. package/lib/mqtt/createCommonOptions.d.ts +2 -20
  10. package/lib/mqtt/createCommonOptions.js +17 -5
  11. package/lib/mqtt/defineRobotCommand.d.ts +52 -0
  12. package/lib/mqtt/defineRobotCommand.js +71 -0
  13. package/lib/mqtt/hooks/useStructuredMessage.d.ts +5 -1
  14. package/lib/mqtt/hooks/useStructuredMessage.js +22 -10
  15. package/lib/mqtt/index.d.ts +7 -1
  16. package/lib/mqtt/index.js +11 -1
  17. package/lib/mqtt/promise.d.ts +21 -6
  18. package/lib/mqtt/promise.js +47 -12
  19. package/lib/mqtt/type/protocols/carpetProtocol.d.ts +2 -0
  20. package/lib/mqtt/type/protocols/index.d.ts +2 -0
  21. package/lib/mqtt/type/protocols/index.js +3 -1
  22. package/lib/mqtt/type/protocols/thresholdProtocol.d.ts +22 -0
  23. package/lib/mqtt/type/protocols/thresholdProtocol.js +1 -0
  24. package/lib/mqtt/type/requestType.d.ts +4 -0
  25. package/lib/mqtt/type/requestType.js +7 -0
  26. package/lib/mqtt/useCarpet.js +12 -4
  27. package/lib/mqtt/useCarpetClean.js +6 -2
  28. package/lib/mqtt/useCruise.js +3 -1
  29. package/lib/mqtt/useCustomCommand.d.ts +39 -0
  30. package/lib/mqtt/useCustomCommand.js +45 -0
  31. package/lib/mqtt/useDeviceModel.js +3 -1
  32. package/lib/mqtt/useFurnitureModel.js +3 -1
  33. package/lib/mqtt/useHistoryMap.js +9 -3
  34. package/lib/mqtt/usePartDivision.js +3 -1
  35. package/lib/mqtt/usePartMerge.js +3 -1
  36. package/lib/mqtt/usePassword.js +6 -2
  37. package/lib/mqtt/usePurifierSchedule.js +3 -1
  38. package/lib/mqtt/useQuiteHours.js +3 -1
  39. package/lib/mqtt/useResetMap.js +3 -1
  40. package/lib/mqtt/useRoomProperty.js +3 -1
  41. package/lib/mqtt/useSchedule.js +3 -1
  42. package/lib/mqtt/useSelectRoomClean.js +3 -1
  43. package/lib/mqtt/useSpotClean.js +3 -1
  44. package/lib/mqtt/useSpotPolygons.js +3 -1
  45. package/lib/mqtt/useThreshold.d.ts +10 -0
  46. package/lib/mqtt/useThreshold.js +90 -0
  47. package/lib/mqtt/useVirtualArea.js +3 -1
  48. package/lib/mqtt/useVirtualWall.js +3 -1
  49. package/lib/mqtt/useVoice.js +3 -1
  50. package/lib/mqtt/useWifiMap.js +3 -1
  51. package/lib/mqtt/useZoneClean.js +3 -1
  52. package/lib/utils/index.d.ts +7 -7
  53. package/package.json +5 -1
@@ -69,6 +69,15 @@ export class SweeperP2p extends P2pApi {
69
69
  this.exitFiles = [];
70
70
  this.firstPackageTime = Date.now();
71
71
  this.enableCustomLog = false;
72
+ this.mismatchCount = 0;
73
+ this.reDownloadCount = 0;
74
+ this.isReDownloading = false;
75
+ this.isReconnecting = false;
76
+ this.isStopped = false;
77
+ this.lastReDownloadTime = 0;
78
+ this.packetStallTimers = new Map();
79
+ this.reDownloadScheduleTimer = null;
80
+ this.recoveryVerifyTimer = null;
72
81
  this.packetTotalMap = new Map([['map.bin', -1], ['map_structured.bin', -1], ['cleanPath.bin', -1], ['ai.bin', -1], ['aiHD_XXXX_YYYY.bin', -1], ['map.bin.stream', -1], ['map_structured.bin.stream', -1], ['cleanPath.bin.stream', -1], ['ai.bin.stream', -1], ['aiHD_XXXX_YYYY.bin.stream', -1]]);
73
82
  this.packetSerialNumberCacheMap = new Map([['map.bin', -1], ['map_structured.bin', -1], ['cleanPath.bin', -1], ['ai.bin', -1], ['aiHD_XXXX_YYYY.bin', -1], ['map.bin.stream', -1], ['map_structured.bin.stream', -1], ['cleanPath.bin.stream', -1], ['ai.bin.stream', -1], ['aiHD_XXXX_YYYY.bin.stream', -1]]);
74
83
  this.fileLengthCacheMap = new Map([['map.bin', -1], ['map_structured.bin', -1], ['cleanPath.bin', -1], ['ai.bin', -1], ['aiHD_XXXX_YYYY.bin', -1], ['map.bin.stream', -1], ['map_structured.bin.stream', -1], ['cleanPath.bin.stream', -1], ['ai.bin.stream', -1], ['aiHD_XXXX_YYYY.bin.stream', -1]]);
@@ -211,17 +220,15 @@ export class SweeperP2p extends P2pApi {
211
220
  */
212
221
  sessionStatusCallback = data => {
213
222
  logger('info', {
214
- msg: 'sessionStatusCallback ==>',
215
- data
223
+ msg: `sessionStatusCallback: devId=${data === null || data === void 0 ? void 0 : data.deviceId}, status=${data === null || data === void 0 ? void 0 : data.status}`
216
224
  }, this.onLogger);
217
225
  if (data) {
218
226
  const {
219
227
  status
220
228
  } = data;
221
229
  if (status < 0) {
222
- logger('info', {
223
- msg: 'receive disconnect notice ==>',
224
- status
230
+ logger('error', {
231
+ msg: `receive disconnect notice: status=${status}`
225
232
  }, this.onLogger);
226
233
  logP2PDataIfEnabled(this.enableCustomLog, this.devId, 'session_status_disconnect', `Session disconnected, status: ${status}`);
227
234
  this.isConnected = false;
@@ -230,7 +237,7 @@ export class SweeperP2p extends P2pApi {
230
237
  this.reconnectP2p(() => {
231
238
  logP2PDataIfEnabled(this.enableCustomLog, this.devId, 'session_reconnect_success', 'Reconnected successfully, restarting data observer');
232
239
  // 重连之后重新开启文件下载, 这里的成功不需要注册断开事件
233
- this.startObserverSweeperDataByP2P(this.downloadType, this.devId, this.onReceiveMapData, this.onReceivePathData, this.onReceiveAIPicData, this.onReceiveAIPicHDData, this.onReceiveWifiMapData);
240
+ this.startObserverSweeperDataByP2P(this.downloadType, this.devId, this.onReceiveMapData, this.onReceivePathData, this.onReceiveAIPicData, this.onReceiveAIPicHDData, this.onReceiveWifiMapData, this.onDefineStructuredMode);
234
241
  }, '');
235
242
  } else {
236
243
  logger('warn', {
@@ -242,6 +249,61 @@ export class SweeperP2p extends P2pApi {
242
249
  }
243
250
  };
244
251
 
252
+ /**
253
+ * 重连设备并重新开启数据观察
254
+ */
255
+ reconnectAndResume = (() => {
256
+ var _this = this;
257
+ return async function () {
258
+ let reason = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'reconnectAndResume';
259
+ if (_this.isReconnecting || _this.isStopped) {
260
+ logger('info', {
261
+ msg: `reconnectAndResume skipped: reason=${reason}, isReconnecting=${_this.isReconnecting}, isStopped=${_this.isStopped}`
262
+ }, _this.onLogger);
263
+ return;
264
+ }
265
+ _this.isReconnecting = true;
266
+ _this.clearPacketStallTimer();
267
+ _this.clearRecoveryTimers();
268
+ logger('info', {
269
+ msg: `reconnectAndResume start: reason=${reason}`
270
+ }, _this.onLogger);
271
+ logP2PDataIfEnabled(_this.enableCustomLog, _this.devId, 'reconnect_and_resume', `Reconnecting device and resuming stream, reason: ${reason}`);
272
+ _this.removeP2pDownloadEvent();
273
+ try {
274
+ await _this.disconnectDevice();
275
+ } catch (e) {
276
+ logger('error', {
277
+ msg: `reconnectAndResume disconnectDevice error: ${JSON.stringify(e)}`
278
+ }, _this.onLogger);
279
+ }
280
+ if (_this.isStopped) {
281
+ _this.isReconnecting = false;
282
+ return;
283
+ }
284
+ _this.isConnected = false;
285
+ _this.isConnecting = false;
286
+ const resumeObserver = () => {
287
+ _this.isReconnecting = false;
288
+ if (_this.isStopped) return;
289
+ logger('info', {
290
+ msg: `reconnectAndResume connected, resuming observer: reason=${reason}`
291
+ }, _this.onLogger);
292
+ _this.startObserverSweeperDataByP2P(_this.downloadType, _this.devId, _this.onReceiveMapData, _this.onReceivePathData, _this.onReceiveAIPicData, _this.onReceiveAIPicHDData, _this.onReceiveWifiMapData, _this.onDefineStructuredMode);
293
+ };
294
+ _this.connectDevice(resumeObserver, () => {
295
+ if (_this.isStopped) {
296
+ _this.isReconnecting = false;
297
+ return;
298
+ }
299
+ logger('error', {
300
+ msg: `reconnectAndResume connectDevice failed (reason=${reason}), fallback to reconnectP2p`
301
+ }, _this.onLogger);
302
+ _this.reconnectP2p(resumeObserver, '');
303
+ });
304
+ };
305
+ })();
306
+
245
307
  /**
246
308
  * 开始进行文件下载
247
309
  * @param downloadType
@@ -249,6 +311,7 @@ export class SweeperP2p extends P2pApi {
249
311
  */
250
312
  startObserverSweeperDataByP2P = async (downloadType, devId, onReceiveMapData, onReceivePathData, onReceiveAIPicData, onReceiveAIPicHDData, onReceiveWifiMapData, onDefineStructuredMode) => {
251
313
  var _this$file$items;
314
+ this.isStopped = false;
252
315
  if (![0, 1].some(item => item === downloadType)) {
253
316
  logger('warn', {
254
317
  msg: 'download type must be 0 or 1'
@@ -285,6 +348,21 @@ export class SweeperP2p extends P2pApi {
285
348
  this.file = await this.queryAlbumFileIndexs(this.albumName);
286
349
  logP2PDataIfEnabled(this.enableCustomLog, devId, 'query_album_files', `Query album files completed, file count: ${((_this$file = this.file) === null || _this$file === void 0 || (_this$file = _this$file.items) === null || _this$file === void 0 ? void 0 : _this$file.length) || 0}`);
287
350
  }
351
+ if (!this.file || !this.file.items || this.file.items.length === 0) {
352
+ logger('warn', {
353
+ msg: 'startObserverSweeperDataByP2P: queryAlbumFileIndexs failed or returned empty items'
354
+ }, this.onLogger);
355
+ logP2PDataIfEnabled(this.enableCustomLog, devId, 'query_album_files_failed', 'queryAlbumFileIndexs failed or returned empty items');
356
+ // queryAlbumFileIndexs 底层失败已自动透传 QUERY_ALBUM_TIMEOUT
357
+ // 若是相册成功返回但列表为空,则透传 NO_ALBUM_FILES
358
+ if (this.file && (!this.file.items || this.file.items.length === 0)) {
359
+ this.emitError({
360
+ code: 'NO_ALBUM_FILES',
361
+ message: 'queryAlbumFileIndexs returned empty items'
362
+ });
363
+ }
364
+ return;
365
+ }
288
366
  if (this.file && ((_this$file$items = this.file.items) === null || _this$file$items === void 0 ? void 0 : _this$file$items.length) > 0) {
289
367
  if (this.downloadType === 0) {
290
368
  const exitFiles = this.queryNeedFiles(this.file.items);
@@ -307,16 +385,11 @@ export class SweeperP2p extends P2pApi {
307
385
  msg: `${downloadType} p2p downloadStream failed and try reConnect Device===>`
308
386
  }, this.onLogger);
309
387
  logP2PDataIfEnabled(this.enableCustomLog, devId, 'download_stream_fail', `Stream download failed, attempting reconnect, downloadType: ${downloadType}`);
310
- this.removeP2pDownloadEvent();
311
- this.disconnectDevice().then(() => {
312
- this.isConnected = false;
313
- this.isConnecting = false;
314
- logP2PDataIfEnabled(this.enableCustomLog, devId, 'download_stream_reconnect', 'Reconnecting device after stream download failure');
315
- this.connectDevice(() => {
316
- // 重连之后重新开启文件下载, 这里的成功不需要注册断开事件
317
- this.startObserverSweeperDataByP2P(this.downloadType, this.devId, this.onReceiveMapData, this.onReceivePathData, this.onReceiveAIPicData, this.onReceiveAIPicHDData, this.onReceiveWifiMapData);
318
- });
388
+ this.emitError({
389
+ code: 'DOWNLOAD_STREAM_FAILED',
390
+ message: `downloadStream failed for downloadType ${downloadType}`
319
391
  });
392
+ this.reconnectAndResume(`download_stream_fail_${downloadType}`);
320
393
  });
321
394
  } else if (await this.initFilePath(this.dataFilePath)) {
322
395
  logP2PDataIfEnabled(this.enableCustomLog, devId, 'download_file_start', `Starting file download, files count: ${exitFiles.length}`);
@@ -350,16 +423,11 @@ export class SweeperP2p extends P2pApi {
350
423
  msg: `${downloadType} p2p downloadStream failed and try reConnect Device===>`
351
424
  }, this.onLogger);
352
425
  logP2PDataIfEnabled(this.enableCustomLog, devId, 'download_stream_fail', `Stream download failed, attempting reconnect, downloadType: ${downloadType}`);
353
- this.removeP2pDownloadEvent();
354
- this.disconnectDevice().then(() => {
355
- this.isConnected = false;
356
- this.isConnecting = false;
357
- logP2PDataIfEnabled(this.enableCustomLog, devId, 'download_stream_reconnect', 'Reconnecting device after stream download failure');
358
- this.connectDevice(() => {
359
- // 重连之后重新开启文件下载, 这里的成功不需要注册断开事件
360
- this.startObserverSweeperDataByP2P(this.downloadType, this.devId, this.onReceiveMapData, this.onReceivePathData, this.onReceiveAIPicData, this.onReceiveAIPicHDData, this.onReceiveWifiMapData);
361
- });
426
+ this.emitError({
427
+ code: 'DOWNLOAD_STREAM_FAILED',
428
+ message: `downloadStream failed for downloadType ${downloadType}`
362
429
  });
430
+ this.reconnectAndResume(`download_stream_fail_${downloadType}`);
363
431
  });
364
432
  } else if (await this.initFilePath(this.streamFilePath)) {
365
433
  // 每次要下载前都需要先检查文件目录是否存在 防止中间过程被删除掉文件目录
@@ -390,6 +458,177 @@ export class SweeperP2p extends P2pApi {
390
458
  files: [...this.exitFiles, ...files]
391
459
  }, this.albumName, successCb, failCb);
392
460
  };
461
+ clearPacketStallTimer = fileName => {
462
+ if (fileName) {
463
+ const timer = this.packetStallTimers.get(fileName);
464
+ if (timer) {
465
+ clearTimeout(timer);
466
+ this.packetStallTimers.delete(fileName);
467
+ }
468
+ return;
469
+ }
470
+ this.packetStallTimers.forEach(timer => clearTimeout(timer));
471
+ this.packetStallTimers.clear();
472
+ };
473
+ clearRecoveryTimers = () => {
474
+ if (this.reDownloadScheduleTimer) {
475
+ clearTimeout(this.reDownloadScheduleTimer);
476
+ this.reDownloadScheduleTimer = null;
477
+ }
478
+ if (this.recoveryVerifyTimer) {
479
+ clearTimeout(this.recoveryVerifyTimer);
480
+ this.recoveryVerifyTimer = null;
481
+ }
482
+ };
483
+
484
+ /**
485
+ * 刷新单文件组包防卡死定时器(3000ms 内若半包未凑齐且无后续新包,触发自愈)
486
+ */
487
+ refreshPacketStallTimer = fileName => {
488
+ this.clearPacketStallTimer(fileName);
489
+ const timer = setTimeout(() => {
490
+ this.packetStallTimers.delete(fileName);
491
+ if (this.isStopped || !this.isConnected || this.isReDownloading || this.isReconnecting) {
492
+ return;
493
+ }
494
+ const cachePacketMap = this.packetDataCacheMap.get(fileName);
495
+ const receivedPackets = (cachePacketMap === null || cachePacketMap === void 0 ? void 0 : cachePacketMap.size) || 0;
496
+ const packetTotal = this.packetTotalMap.get(fileName);
497
+ const expectedBytes = this.fileLengthCacheMap.get(fileName);
498
+ const serial = this.packetSerialNumberCacheMap.get(fileName);
499
+ logger('error', {
500
+ msg: `packet assembly stalled (3000ms): file=${fileName}, serial=${serial}, receivedPackets=${receivedPackets}, packetTotal=${packetTotal}, expectedBytes=${expectedBytes}`
501
+ }, this.onLogger);
502
+ logP2PDataIfEnabled(this.enableCustomLog, this.devId, 'packet_assembly_stalled', `Packet assembly stalled for ${fileName}, serial: ${serial}, receivedPackets: ${receivedPackets}, packetTotal: ${packetTotal}, expectedBytes: ${expectedBytes}`);
503
+ cachePacketMap === null || cachePacketMap === void 0 || cachePacketMap.clear();
504
+ this.packetTotalMap.set(fileName, -1);
505
+ this.emitError({
506
+ code: 'PACKET_ASSEMBLY_TIMEOUT',
507
+ message: `Packet assembly stalled for ${fileName} after 3000ms`,
508
+ originalError: {
509
+ fileName,
510
+ serial,
511
+ receivedPackets,
512
+ packetTotal,
513
+ expectedBytes
514
+ }
515
+ });
516
+ this.reDownloadStream('packet_assembly_stalled');
517
+ }, 3000);
518
+ this.packetStallTimers.set(fileName, timer);
519
+ };
520
+ scheduleReDownload = (reason, delayMs) => {
521
+ if (this.isStopped || !this.isConnected || this.isReDownloading || this.isReconnecting) {
522
+ return;
523
+ }
524
+ if (this.reDownloadScheduleTimer) {
525
+ clearTimeout(this.reDownloadScheduleTimer);
526
+ }
527
+ logger('info', {
528
+ msg: `scheduleReDownload: reason=${reason}, delay=${delayMs}ms`
529
+ }, this.onLogger);
530
+ this.reDownloadScheduleTimer = setTimeout(() => {
531
+ this.reDownloadScheduleTimer = null;
532
+ this.reDownloadStream(reason);
533
+ }, delayMs);
534
+ };
535
+
536
+ /**
537
+ * 渐进式平滑自愈:重新拉取数据流
538
+ * 优先尝试轻量 cancelDownloadTask -> downloadStream,并启动 3000ms 验收兜底;
539
+ * 若重试超过 2 次,升级为 disconnectDevice -> connectDevice 彻底重连
540
+ */
541
+ reDownloadStream = (() => {
542
+ var _this2 = this;
543
+ return async function () {
544
+ let reason = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'unknown';
545
+ if (_this2.isStopped || _this2.isReDownloading || _this2.isReconnecting || !_this2.isConnected) {
546
+ return;
547
+ }
548
+ _this2.isReDownloading = true;
549
+ _this2.lastReDownloadTime = Date.now();
550
+ logger('info', {
551
+ msg: `reDownloadStream start: reason=${reason}, retryCount=${_this2.reDownloadCount}`
552
+ }, _this2.onLogger);
553
+ logP2PDataIfEnabled(_this2.enableCustomLog, _this2.devId, 'redownload_stream_trigger', `reDownloadStream triggered, reason: ${reason}, retryCount: ${_this2.reDownloadCount}`);
554
+ if (_this2.reDownloadCount >= 2) {
555
+ logger('error', {
556
+ msg: `reDownloadStream exceeded max retries (2) on reason=${reason}, escalating to reconnectAndResume`
557
+ }, _this2.onLogger);
558
+ logP2PDataIfEnabled(_this2.enableCustomLog, _this2.devId, 'redownload_stream_escalate', 'Exceeded max retries, escalating to full reconnect');
559
+ _this2.reDownloadCount = 0;
560
+ _this2.mismatchCount = 0;
561
+ _this2.isReDownloading = false;
562
+ await _this2.reconnectAndResume(`redownload_escalate:${reason}`);
563
+ return;
564
+ }
565
+ _this2.reDownloadCount += 1;
566
+ _this2.clearPacketCache();
567
+ try {
568
+ await _this2.cancelDownloadTask();
569
+ } catch (e) {
570
+ // ignore
571
+ }
572
+ if (_this2.isStopped || !_this2.isConnected) {
573
+ _this2.isReDownloading = false;
574
+ return;
575
+ }
576
+ if (!_this2.exitFiles || _this2.exitFiles.length === 0) {
577
+ var _this2$file;
578
+ if (!_this2.file || !_this2.file.items || _this2.file.items.length === 0) {
579
+ // @ts-ignore
580
+ _this2.file = await _this2.queryAlbumFileIndexs(_this2.albumName);
581
+ }
582
+ if ((_this2$file = _this2.file) !== null && _this2$file !== void 0 && (_this2$file = _this2$file.items) !== null && _this2$file !== void 0 && _this2$file.length) {
583
+ _this2.exitFiles = _this2.queryNeedFiles(_this2.file.items);
584
+ }
585
+ }
586
+ if (!_this2.exitFiles || _this2.exitFiles.length === 0) {
587
+ logger('error', {
588
+ msg: 'reDownloadStream: no exitFiles found to download'
589
+ }, _this2.onLogger);
590
+ _this2.isReDownloading = false;
591
+ return;
592
+ }
593
+ try {
594
+ await _this2.downloadStream({
595
+ files: _this2.exitFiles
596
+ }, _this2.albumName, () => {
597
+ logger('info', {
598
+ msg: `reDownloadStream downloadStream success (retry ${_this2.reDownloadCount}), files=[${_this2.exitFiles.join(',')}]`
599
+ }, _this2.onLogger);
600
+ logP2PDataIfEnabled(_this2.enableCustomLog, _this2.devId, 'redownload_stream_success', `reDownloadStream success on retry ${_this2.reDownloadCount}`);
601
+ _this2.isReDownloading = false;
602
+ // 验收闭环:如果重拉后 3000ms 内仍无任何完整有效帧回来(例如原生同 Session 静默卡死),自动继续升级
603
+ if (!_this2.isStopped && _this2.isConnected) {
604
+ if (_this2.recoveryVerifyTimer) {
605
+ clearTimeout(_this2.recoveryVerifyTimer);
606
+ }
607
+ _this2.recoveryVerifyTimer = setTimeout(() => {
608
+ _this2.recoveryVerifyTimer = null;
609
+ if (!_this2.isStopped && _this2.isConnected && !_this2.isReDownloading && !_this2.isReconnecting) {
610
+ logger('error', {
611
+ msg: `recovery verify timeout (3000ms) after reDownloadStream(${reason}), retryCount=${_this2.reDownloadCount}`
612
+ }, _this2.onLogger);
613
+ _this2.reDownloadStream('recovery_verify_timeout');
614
+ }
615
+ }, 3000);
616
+ }
617
+ }, () => {
618
+ logger('error', {
619
+ msg: `reDownloadStream downloadStream failed (retry ${_this2.reDownloadCount})`
620
+ }, _this2.onLogger);
621
+ logP2PDataIfEnabled(_this2.enableCustomLog, _this2.devId, 'redownload_stream_fail', `reDownloadStream failed on retry ${_this2.reDownloadCount}`);
622
+ _this2.isReDownloading = false;
623
+ });
624
+ } catch (e) {
625
+ logger('error', {
626
+ msg: `reDownloadStream error: ${JSON.stringify(e)}`
627
+ }, _this2.onLogger);
628
+ _this2.isReDownloading = false;
629
+ }
630
+ };
631
+ })();
393
632
 
394
633
  /**
395
634
  * 注册下载有关的监听
@@ -416,13 +655,10 @@ export class SweeperP2p extends P2pApi {
416
655
  };
417
656
 
418
657
  /**
419
- * 移除下载有关的监听
658
+ * 清空分包缓存与组包进度
420
659
  */
421
- removeP2pDownloadEvent = () => {
422
- logger('info', {
423
- msg: 'removeP2pDownloadEvent ==>'
424
- }, this.onLogger);
425
- logP2PDataIfEnabled(this.enableCustomLog, this.devId, 'remove_download_event', 'Removing download events');
660
+ clearPacketCache = () => {
661
+ this.clearPacketStallTimer();
426
662
  if (shouldDownloadStream) {
427
663
  [...this.packetSerialNumberCacheMap.keys()].forEach(key => {
428
664
  this.packetSerialNumberCacheMap.set(key, -1);
@@ -438,6 +674,17 @@ export class SweeperP2p extends P2pApi {
438
674
  });
439
675
  }
440
676
  this.cacheData = {};
677
+ };
678
+
679
+ /**
680
+ * 移除下载有关的监听
681
+ */
682
+ removeP2pDownloadEvent = () => {
683
+ logger('info', {
684
+ msg: 'removeP2pDownloadEvent ==>'
685
+ }, this.onLogger);
686
+ logP2PDataIfEnabled(this.enableCustomLog, this.devId, 'remove_download_event', 'Removing download events');
687
+ this.clearPacketCache();
441
688
  this.offFileDownloadComplete && this.offFileDownloadComplete();
442
689
  this.offP2pStreamPacketReceive && this.offP2pStreamPacketReceive();
443
690
 
@@ -484,6 +731,32 @@ export class SweeperP2p extends P2pApi {
484
731
  let {
485
732
  fileName
486
733
  } = data;
734
+ if (!fileName) {
735
+ logger('error', {
736
+ msg: `corrupted packet header (empty fileName): serial=${fileSerialNumber}, index=${packetIndex}, type=${packetType}, fileLength=${fileLength}, packetLength=${data === null || data === void 0 ? void 0 : data.packetLength}`
737
+ }, this.onLogger);
738
+ logP2PDataIfEnabled(this.enableCustomLog, this.devId, 'packet_header_corrupted', `Empty fileName packet received, serial: ${fileSerialNumber}, index: ${packetIndex}, type: ${packetType}`);
739
+ this.emitError({
740
+ code: 'PACKET_HEADER_CORRUPTED',
741
+ message: 'Received P2P stream packet with empty fileName',
742
+ originalError: {
743
+ fileSerialNumber,
744
+ packetIndex,
745
+ packetType,
746
+ fileLength,
747
+ packetLength: data === null || data === void 0 ? void 0 : data.packetLength
748
+ }
749
+ });
750
+ // 协议头损坏时原生流线程往往紧接着以 -30061 退出;按方案 A 延迟 500ms 直接重建 P2P Session
751
+ this.clearPacketCache();
752
+ if (!this.isStopped && this.isConnected && !this.reDownloadScheduleTimer && !this.isReconnecting) {
753
+ this.reDownloadScheduleTimer = setTimeout(() => {
754
+ this.reDownloadScheduleTimer = null;
755
+ this.reconnectAndResume('corrupted_packet_header');
756
+ }, 500);
757
+ }
758
+ return;
759
+ }
487
760
  if (fileName.startsWith('map')) {
488
761
  var _FILE_NAME_MAP$fileNa;
489
762
  this.initStructuredMode(((_FILE_NAME_MAP$fileNa = FILE_NAME_MAP[fileName]) === null || _FILE_NAME_MAP$fileNa === void 0 ? void 0 : _FILE_NAME_MAP$fileNa.type) === 6);
@@ -491,6 +764,9 @@ export class SweeperP2p extends P2pApi {
491
764
 
492
765
  // 记录第一个包和最后一个包的接收
493
766
  if (packetType === 1 || packetType === 3) {
767
+ logger('info', {
768
+ msg: `stream packet start: file=${fileName}, serial=${fileSerialNumber}, expectedBytes=${fileLength}, type=${packetType}`
769
+ }, this.onLogger);
494
770
  logP2PDataIfEnabled(this.enableCustomLog, this.devId, 'packet_first_received', `First packet received, fileName: ${fileName}, fileSerialNumber: ${fileSerialNumber}, packetIndex: ${packetIndex}`);
495
771
  }
496
772
 
@@ -503,8 +779,8 @@ export class SweeperP2p extends P2pApi {
503
779
  }
504
780
  const cachePacketMap = this.packetDataCacheMap.get(fileName);
505
781
  if (!cachePacketMap) {
506
- logger('warn', {
507
- msg: `p2pStreamPacketReceiveCallback: fileName : ${fileName} is not support`
782
+ logger('error', {
783
+ msg: `p2pStreamPacketReceiveCallback: unsupported fileName=${fileName}, serial=${fileSerialNumber}, index=${packetIndex}, type=${packetType}`
508
784
  }, this.onLogger);
509
785
  logP2PDataIfEnabled(this.enableCustomLog, this.devId, 'packet_unsupported_file', `Unsupported file name: ${fileName}`);
510
786
  return;
@@ -527,10 +803,12 @@ export class SweeperP2p extends P2pApi {
527
803
  }
528
804
  const packetTotal = this.packetTotalMap.get(fileName);
529
805
  cachePacketMap.set(packetIndex, packetData);
806
+ this.refreshPacketStallTimer(fileName);
530
807
  if (packetTotal > -1) {
531
808
  // 说明收到过末尾包了,只需要验证总包数是否吻合
532
809
  const packetDatas = [...cachePacketMap.entries()];
533
810
  if (packetDatas.length === packetTotal) {
811
+ this.clearPacketStallTimer(fileName);
534
812
  packetDatas.sort((a, b) => a[0] - b[0]);
535
813
 
536
814
  // 排序 - 组装 - 发出
@@ -540,12 +818,47 @@ export class SweeperP2p extends P2pApi {
540
818
  }).join('');
541
819
  const cacheFileLength = this.fileLengthCacheMap.get(fileName);
542
820
  if (cacheFileLength > 0 && hexValue.length !== cacheFileLength * 2) {
543
- logger('warn', {
544
- msg: `p2pStreamPacketReceiveCallback: fileName : ${fileName} length mismatch, expected: ${cacheFileLength * 2}, received: ${hexValue.length}`
821
+ // 清理受损文件的组包缓存,防止污染后续数据
822
+ cachePacketMap.clear();
823
+ this.packetTotalMap.set(fileName, -1);
824
+ this.mismatchCount += 1;
825
+ logger('error', {
826
+ msg: `packet length mismatch: file=${fileName}, serial=${fileSerialNumber}, packets=${packetDatas.length}/${packetTotal}, expectedHex=${cacheFileLength * 2}, receivedHex=${hexValue.length}, mismatchCount=${this.mismatchCount}`
545
827
  }, this.onLogger);
546
828
  logP2PDataIfEnabled(this.enableCustomLog, this.devId, 'packet_length_mismatch', `Packet length mismatch, fileName: ${fileName}, expected: ${cacheFileLength * 2}, received: ${hexValue.length}`);
829
+ this.emitError({
830
+ code: 'PACKET_LENGTH_MISMATCH',
831
+ message: `Packet length mismatch for ${fileName}: expected ${cacheFileLength * 2}, received ${hexValue.length}`,
832
+ originalError: {
833
+ fileName,
834
+ expected: cacheFileLength * 2,
835
+ received: hexValue.length,
836
+ mismatchCount: this.mismatchCount
837
+ }
838
+ });
839
+ if (this.mismatchCount >= 2) {
840
+ logger('error', {
841
+ msg: `consecutive length mismatch reached ${this.mismatchCount}, triggering reDownloadStream`
842
+ }, this.onLogger);
843
+ this.mismatchCount = 0;
844
+ this.clearRecoveryTimers();
845
+ this.reDownloadStream('consecutive_length_mismatch');
846
+ } else {
847
+ // 仅发生 1 次时开启 2000ms 兜底检查:若流线程伴随 -30061 死掉则 2s 后自动重拉;若后续帧正常抵达则自动取消
848
+ this.scheduleReDownload('packet_mismatch_stalled', 2000);
849
+ }
547
850
  return;
548
851
  }
852
+
853
+ // 校验通过,取消恢复观察窗并重置 mismatchCount;reDownloadCount 采用稳定期保护(cleanPath 恢复或超过 5s 后清零)
854
+ this.clearRecoveryTimers();
855
+ this.mismatchCount = 0;
856
+ if (this.reDownloadCount > 0 && (fileName.indexOf('cleanPath') !== -1 || Date.now() - this.lastReDownloadTime > 5000)) {
857
+ logger('info', {
858
+ msg: `stream recovered stably on file=${fileName}, resetting reDownloadCount (was ${this.reDownloadCount})`
859
+ }, this.onLogger);
860
+ this.reDownloadCount = 0;
861
+ }
549
862
  if (this.firstPackageTime > 0 && fileName.indexOf('map') !== -1) {
550
863
  const packageTime = Date.now() - this.firstPackageTime;
551
864
  logger('info', {
@@ -564,12 +877,15 @@ export class SweeperP2p extends P2pApi {
564
877
  if (this.cacheData[type] !== hexValue) {
565
878
  logP2PDataIfEnabled(this.enableCustomLog, this.devId, 'data_received', `Data received and processed, fileName: ${fileName}, type: ${type}, dataLength: ${hexValue.length}`);
566
879
  if (type === 0 || type === 6) {
880
+ logger('info', {
881
+ msg: `push new map data: file=${fileName}, serial=${fileSerialNumber}, packets=${packetDatas.length}, bytes=${hexValue.length / 2}`
882
+ }, this.onLogger);
567
883
  this.onReceiveMapData(hexValue);
568
884
  this.cacheData[type] = hexValue;
569
885
  }
570
886
  if (type === 1) {
571
887
  logger('info', {
572
- msg: `push new path data`
888
+ msg: `push new path data: file=${fileName}, serial=${fileSerialNumber}, packets=${packetDatas.length}, bytes=${hexValue.length / 2}`
573
889
  }, this.onLogger);
574
890
  this.onReceivePathData(hexValue);
575
891
  this.cacheData[type] = hexValue;
@@ -734,7 +1050,16 @@ export class SweeperP2p extends P2pApi {
734
1050
  logP2PDataIfEnabled(this.enableCustomLog, this.devId, 'stop_observer_disconnect', 'Disconnecting device');
735
1051
  this.disconnectDevice();
736
1052
  }
1053
+ this.isStopped = true;
1054
+ this.clearPacketStallTimer();
1055
+ this.clearRecoveryTimers();
737
1056
  this.removeP2pDownloadEvent();
1057
+ this.mismatchCount = 0;
1058
+ this.reDownloadCount = 0;
1059
+ this.isReDownloading = false;
1060
+ this.isReconnecting = false;
1061
+ this.lastReDownloadTime = 0;
1062
+ this.file = undefined;
738
1063
  // 没有必要cancelDownloadTask,只需要调用断连
739
1064
  // this.cancelDownloadTask();
740
1065
 
package/lib/index.d.ts CHANGED
@@ -1,16 +1,22 @@
1
+ import { P2pError, P2pErrorCode } from './api';
1
2
  export * from './mqtt';
2
3
  export * from './mqtt/type/requestType';
4
+ export { pointsToString, pickWaterFields } from './utils';
3
5
  type TOnLogger = (type: 'warn' | 'error' | 'info', data: string) => void;
4
- declare const useP2PDataStream: (devId: string, onReceiveMapData: (data: string) => void, onReceivePathData: (data: string) => void, opt?: {
5
- logTag?: string | undefined;
6
- enableCustomLog?: boolean | undefined;
7
- onReceiveAIPicData?: ((data: string) => void) | undefined;
8
- onReceiveAIPicHDData?: ((data: string) => void) | undefined;
9
- onReceiveWifiMapData?: ((data: string) => void) | undefined;
10
- onLogger?: TOnLogger | undefined;
11
- onDefineStructuredMode?: ((isStructured: boolean) => void) | undefined;
12
- } | undefined) => {
6
+ export interface P2PDataStreamOptions {
7
+ logTag?: string;
8
+ enableCustomLog?: boolean;
9
+ onReceiveAIPicData?: (data: string) => void;
10
+ onReceiveAIPicHDData?: (data: string) => void;
11
+ onReceiveWifiMapData?: (data: string) => void;
12
+ onLogger?: TOnLogger;
13
+ onDefineStructuredMode?: (isStructured: boolean) => void;
14
+ onError?: (error: P2pError) => void;
15
+ firstFrameTimeout?: number;
16
+ }
17
+ declare const useP2PDataStream: (devId: string, onReceiveMapData: (data: string) => void, onReceivePathData: (data: string) => void, opt?: P2PDataStreamOptions) => {
13
18
  appendDownloadStreamDuringTask: (files: Array<string>, successCb?: () => void, failedCb?: () => void) => Promise<boolean> | void;
14
19
  };
15
20
  declare const StreamDataNotificationCenter: import("mitt").Emitter<Record<import("mitt").EventType, unknown>>;
21
+ export type { P2PDataStreamOptions, P2pError, P2pErrorCode };
16
22
  export { StreamDataNotificationCenter, useP2PDataStream };