@ray-js/robot-data-stream 0.1.0-beta.0 → 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.
@@ -1,4 +1,4 @@
1
- export type P2pErrorCode = 'QUERY_ALBUM_TIMEOUT' | 'PACKET_LENGTH_MISMATCH' | 'DOWNLOAD_STREAM_FAILED' | 'FIRST_FRAME_TIMEOUT' | 'NO_ALBUM_FILES' | string;
1
+ export type P2pErrorCode = 'QUERY_ALBUM_TIMEOUT' | 'PACKET_LENGTH_MISMATCH' | 'PACKET_HEADER_CORRUPTED' | 'PACKET_ASSEMBLY_TIMEOUT' | 'DOWNLOAD_STREAM_FAILED' | 'FIRST_FRAME_TIMEOUT' | 'NO_ALBUM_FILES' | string;
2
2
  export interface P2pError {
3
3
  code: P2pErrorCode;
4
4
  message: string;
package/lib/api/p2pApi.js CHANGED
@@ -1,3 +1,4 @@
1
+ import "core-js/modules/esnext.iterator.map.js";
1
2
  /* eslint-disable consistent-return */
2
3
  /* eslint-disable @typescript-eslint/explicit-module-boundary-types */
3
4
  /* eslint-disable prefer-promise-reject-errors */
@@ -131,8 +132,8 @@ export default class P2pApi {
131
132
  resolve(true);
132
133
  },
133
134
  fail: params => {
134
- logger('warn', {
135
- msg: `p2p connectDevice failed ==> ${JSON.stringify(params.innerError)}`
135
+ logger('error', {
136
+ msg: `p2p connectDevice failed: ${JSON.stringify((params === null || params === void 0 ? void 0 : params.innerError) || params || {})}`
136
137
  }, this.onLogger);
137
138
  this.isConnecting = false;
138
139
  typeof failCb === 'function' && failCb();
@@ -220,9 +221,8 @@ export default class P2pApi {
220
221
  resolve(true);
221
222
  },
222
223
  fail: params => {
223
- logger('warn', {
224
- msg: 'p2p downloadStream failed===>',
225
- params
224
+ logger('error', {
225
+ msg: `p2p downloadStream failed: ${JSON.stringify((params === null || params === void 0 ? void 0 : params.innerError) || params || {})}`
226
226
  }, this.onLogger);
227
227
  trace.pointFn({
228
228
  devId: this.devId,
@@ -448,16 +448,17 @@ export default class P2pApi {
448
448
  deviceId: _this.devId,
449
449
  albumName,
450
450
  success: params => {
451
+ var _params$count;
452
+ const fileNames = ((params === null || params === void 0 ? void 0 : params.items) || []).map(item => item === null || item === void 0 ? void 0 : item.filename).join(',');
451
453
  logger('info', {
452
- msg: `queryAlbumFileIndexs success (attempt ${attempt}) ==>`,
453
- params
454
+ msg: `queryAlbumFileIndexs success (attempt ${attempt}): count=${(_params$count = params === null || params === void 0 ? void 0 : params.count) !== null && _params$count !== void 0 ? _params$count : 0}, files=[${fileNames}]`
454
455
  }, _this.onLogger);
455
456
  resolve(params);
456
457
  },
457
458
  fail: params => {
458
- logger('warn', {
459
- msg: `queryAlbumFileIndexs failed (attempt ${attempt}) ==>`,
460
- params
459
+ const errDetail = JSON.stringify((params === null || params === void 0 ? void 0 : params.innerError) || params || {});
460
+ logger('info', {
461
+ msg: `queryAlbumFileIndexs failed (attempt ${attempt}): ${errDetail}`
461
462
  }, _this.onLogger);
462
463
  if (attempt < retries && _this.isConnected) {
463
464
  logger('info', {
@@ -467,6 +468,9 @@ export default class P2pApi {
467
468
  doQuery(attempt + 1).then(resolve);
468
469
  }, delay);
469
470
  } else {
471
+ logger('error', {
472
+ msg: `queryAlbumFileIndexs failed after ${attempt + 1} attempt(s): ${errDetail}`
473
+ }, _this.onLogger);
470
474
  _this.emitError({
471
475
  code: 'QUERY_ALBUM_TIMEOUT',
472
476
  message: `queryAlbumFileIndexs failed after ${attempt + 1} attempt(s)`,
@@ -85,6 +85,12 @@ export declare class SweeperP2p extends P2pApi {
85
85
  mismatchCount: number;
86
86
  reDownloadCount: number;
87
87
  isReDownloading: boolean;
88
+ private isReconnecting;
89
+ private isStopped;
90
+ private lastReDownloadTime;
91
+ private packetStallTimers;
92
+ private reDownloadScheduleTimer;
93
+ private recoveryVerifyTimer;
88
94
  constructor();
89
95
  private setStreamFilePath;
90
96
  private setDataFilePath;
@@ -149,9 +155,16 @@ export declare class SweeperP2p extends P2pApi {
149
155
  * @returns
150
156
  */
151
157
  appendDownloadStreamDuringTask: (files: Array<string>, successCb?: () => void, failCb?: () => void) => Promise<boolean> | void;
158
+ private clearPacketStallTimer;
159
+ private clearRecoveryTimers;
160
+ /**
161
+ * 刷新单文件组包防卡死定时器(3000ms 内若半包未凑齐且无后续新包,触发自愈)
162
+ */
163
+ private refreshPacketStallTimer;
164
+ private scheduleReDownload;
152
165
  /**
153
166
  * 渐进式平滑自愈:重新拉取数据流
154
- * 优先尝试轻量 cancelDownloadTask -> downloadStream,
167
+ * 优先尝试轻量 cancelDownloadTask -> downloadStream,并启动 3000ms 验收兜底;
155
168
  * 若重试超过 2 次,升级为 disconnectDevice -> connectDevice 彻底重连
156
169
  */
157
170
  reDownloadStream: (reason?: string) => Promise<void>;
@@ -72,6 +72,12 @@ export class SweeperP2p extends P2pApi {
72
72
  this.mismatchCount = 0;
73
73
  this.reDownloadCount = 0;
74
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;
75
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]]);
76
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]]);
77
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]]);
@@ -214,17 +220,15 @@ export class SweeperP2p extends P2pApi {
214
220
  */
215
221
  sessionStatusCallback = data => {
216
222
  logger('info', {
217
- msg: 'sessionStatusCallback ==>',
218
- data
223
+ msg: `sessionStatusCallback: devId=${data === null || data === void 0 ? void 0 : data.deviceId}, status=${data === null || data === void 0 ? void 0 : data.status}`
219
224
  }, this.onLogger);
220
225
  if (data) {
221
226
  const {
222
227
  status
223
228
  } = data;
224
229
  if (status < 0) {
225
- logger('info', {
226
- msg: 'receive disconnect notice ==>',
227
- status
230
+ logger('error', {
231
+ msg: `receive disconnect notice: status=${status}`
228
232
  }, this.onLogger);
229
233
  logP2PDataIfEnabled(this.enableCustomLog, this.devId, 'session_status_disconnect', `Session disconnected, status: ${status}`);
230
234
  this.isConnected = false;
@@ -252,20 +256,50 @@ export class SweeperP2p extends P2pApi {
252
256
  var _this = this;
253
257
  return async function () {
254
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();
255
268
  logger('info', {
256
- msg: `reconnectAndResume triggered, reason: ${reason}`
269
+ msg: `reconnectAndResume start: reason=${reason}`
257
270
  }, _this.onLogger);
258
271
  logP2PDataIfEnabled(_this.enableCustomLog, _this.devId, 'reconnect_and_resume', `Reconnecting device and resuming stream, reason: ${reason}`);
259
272
  _this.removeP2pDownloadEvent();
260
273
  try {
261
274
  await _this.disconnectDevice();
262
275
  } catch (e) {
263
- // ignore
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;
264
283
  }
265
284
  _this.isConnected = false;
266
285
  _this.isConnecting = false;
267
- _this.connectDevice(() => {
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);
268
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, '');
269
303
  });
270
304
  };
271
305
  })();
@@ -277,6 +311,7 @@ export class SweeperP2p extends P2pApi {
277
311
  */
278
312
  startObserverSweeperDataByP2P = async (downloadType, devId, onReceiveMapData, onReceivePathData, onReceiveAIPicData, onReceiveAIPicHDData, onReceiveWifiMapData, onDefineStructuredMode) => {
279
313
  var _this$file$items;
314
+ this.isStopped = false;
280
315
  if (![0, 1].some(item => item === downloadType)) {
281
316
  logger('warn', {
282
317
  msg: 'download type must be 0 or 1'
@@ -423,33 +458,108 @@ export class SweeperP2p extends P2pApi {
423
458
  files: [...this.exitFiles, ...files]
424
459
  }, this.albumName, successCb, failCb);
425
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
+ };
426
535
 
427
536
  /**
428
537
  * 渐进式平滑自愈:重新拉取数据流
429
- * 优先尝试轻量 cancelDownloadTask -> downloadStream,
538
+ * 优先尝试轻量 cancelDownloadTask -> downloadStream,并启动 3000ms 验收兜底;
430
539
  * 若重试超过 2 次,升级为 disconnectDevice -> connectDevice 彻底重连
431
540
  */
432
541
  reDownloadStream = (() => {
433
542
  var _this2 = this;
434
543
  return async function () {
435
544
  let reason = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'unknown';
436
- if (_this2.isReDownloading || !_this2.isConnected) {
545
+ if (_this2.isStopped || _this2.isReDownloading || _this2.isReconnecting || !_this2.isConnected) {
437
546
  return;
438
547
  }
439
548
  _this2.isReDownloading = true;
549
+ _this2.lastReDownloadTime = Date.now();
440
550
  logger('info', {
441
- msg: `reDownloadStream triggered, reason: ${reason}, retryCount: ${_this2.reDownloadCount}`
551
+ msg: `reDownloadStream start: reason=${reason}, retryCount=${_this2.reDownloadCount}`
442
552
  }, _this2.onLogger);
443
553
  logP2PDataIfEnabled(_this2.enableCustomLog, _this2.devId, 'redownload_stream_trigger', `reDownloadStream triggered, reason: ${reason}, retryCount: ${_this2.reDownloadCount}`);
444
554
  if (_this2.reDownloadCount >= 2) {
445
- logger('warn', {
446
- msg: 'reDownloadStream exceeded max retries (2), escalating to full reconnect'
555
+ logger('error', {
556
+ msg: `reDownloadStream exceeded max retries (2) on reason=${reason}, escalating to reconnectAndResume`
447
557
  }, _this2.onLogger);
448
558
  logP2PDataIfEnabled(_this2.enableCustomLog, _this2.devId, 'redownload_stream_escalate', 'Exceeded max retries, escalating to full reconnect');
449
559
  _this2.reDownloadCount = 0;
450
560
  _this2.mismatchCount = 0;
451
561
  _this2.isReDownloading = false;
452
- await _this2.reconnectAndResume('redownload_stream_escalate');
562
+ await _this2.reconnectAndResume(`redownload_escalate:${reason}`);
453
563
  return;
454
564
  }
455
565
  _this2.reDownloadCount += 1;
@@ -459,7 +569,7 @@ export class SweeperP2p extends P2pApi {
459
569
  } catch (e) {
460
570
  // ignore
461
571
  }
462
- if (!_this2.isConnected) {
572
+ if (_this2.isStopped || !_this2.isConnected) {
463
573
  _this2.isReDownloading = false;
464
574
  return;
465
575
  }
@@ -474,7 +584,7 @@ export class SweeperP2p extends P2pApi {
474
584
  }
475
585
  }
476
586
  if (!_this2.exitFiles || _this2.exitFiles.length === 0) {
477
- logger('warn', {
587
+ logger('error', {
478
588
  msg: 'reDownloadStream: no exitFiles found to download'
479
589
  }, _this2.onLogger);
480
590
  _this2.isReDownloading = false;
@@ -485,12 +595,27 @@ export class SweeperP2p extends P2pApi {
485
595
  files: _this2.exitFiles
486
596
  }, _this2.albumName, () => {
487
597
  logger('info', {
488
- msg: `reDownloadStream downloadStream success (retry ${_this2.reDownloadCount})`
598
+ msg: `reDownloadStream downloadStream success (retry ${_this2.reDownloadCount}), files=[${_this2.exitFiles.join(',')}]`
489
599
  }, _this2.onLogger);
490
600
  logP2PDataIfEnabled(_this2.enableCustomLog, _this2.devId, 'redownload_stream_success', `reDownloadStream success on retry ${_this2.reDownloadCount}`);
491
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
+ }
492
617
  }, () => {
493
- logger('warn', {
618
+ logger('error', {
494
619
  msg: `reDownloadStream downloadStream failed (retry ${_this2.reDownloadCount})`
495
620
  }, _this2.onLogger);
496
621
  logP2PDataIfEnabled(_this2.enableCustomLog, _this2.devId, 'redownload_stream_fail', `reDownloadStream failed on retry ${_this2.reDownloadCount}`);
@@ -498,8 +623,7 @@ export class SweeperP2p extends P2pApi {
498
623
  });
499
624
  } catch (e) {
500
625
  logger('error', {
501
- msg: 'reDownloadStream error ==>',
502
- e
626
+ msg: `reDownloadStream error: ${JSON.stringify(e)}`
503
627
  }, _this2.onLogger);
504
628
  _this2.isReDownloading = false;
505
629
  }
@@ -534,6 +658,7 @@ export class SweeperP2p extends P2pApi {
534
658
  * 清空分包缓存与组包进度
535
659
  */
536
660
  clearPacketCache = () => {
661
+ this.clearPacketStallTimer();
537
662
  if (shouldDownloadStream) {
538
663
  [...this.packetSerialNumberCacheMap.keys()].forEach(key => {
539
664
  this.packetSerialNumberCacheMap.set(key, -1);
@@ -606,6 +731,32 @@ export class SweeperP2p extends P2pApi {
606
731
  let {
607
732
  fileName
608
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
+ }
609
760
  if (fileName.startsWith('map')) {
610
761
  var _FILE_NAME_MAP$fileNa;
611
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);
@@ -613,6 +764,9 @@ export class SweeperP2p extends P2pApi {
613
764
 
614
765
  // 记录第一个包和最后一个包的接收
615
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);
616
770
  logP2PDataIfEnabled(this.enableCustomLog, this.devId, 'packet_first_received', `First packet received, fileName: ${fileName}, fileSerialNumber: ${fileSerialNumber}, packetIndex: ${packetIndex}`);
617
771
  }
618
772
 
@@ -625,8 +779,8 @@ export class SweeperP2p extends P2pApi {
625
779
  }
626
780
  const cachePacketMap = this.packetDataCacheMap.get(fileName);
627
781
  if (!cachePacketMap) {
628
- logger('warn', {
629
- msg: `p2pStreamPacketReceiveCallback: fileName : ${fileName} is not support`
782
+ logger('error', {
783
+ msg: `p2pStreamPacketReceiveCallback: unsupported fileName=${fileName}, serial=${fileSerialNumber}, index=${packetIndex}, type=${packetType}`
630
784
  }, this.onLogger);
631
785
  logP2PDataIfEnabled(this.enableCustomLog, this.devId, 'packet_unsupported_file', `Unsupported file name: ${fileName}`);
632
786
  return;
@@ -649,10 +803,12 @@ export class SweeperP2p extends P2pApi {
649
803
  }
650
804
  const packetTotal = this.packetTotalMap.get(fileName);
651
805
  cachePacketMap.set(packetIndex, packetData);
806
+ this.refreshPacketStallTimer(fileName);
652
807
  if (packetTotal > -1) {
653
808
  // 说明收到过末尾包了,只需要验证总包数是否吻合
654
809
  const packetDatas = [...cachePacketMap.entries()];
655
810
  if (packetDatas.length === packetTotal) {
811
+ this.clearPacketStallTimer(fileName);
656
812
  packetDatas.sort((a, b) => a[0] - b[0]);
657
813
 
658
814
  // 排序 - 组装 - 发出
@@ -662,15 +818,14 @@ export class SweeperP2p extends P2pApi {
662
818
  }).join('');
663
819
  const cacheFileLength = this.fileLengthCacheMap.get(fileName);
664
820
  if (cacheFileLength > 0 && hexValue.length !== cacheFileLength * 2) {
665
- logger('warn', {
666
- msg: `p2pStreamPacketReceiveCallback: fileName : ${fileName} length mismatch, expected: ${cacheFileLength * 2}, received: ${hexValue.length}`
667
- }, this.onLogger);
668
- logP2PDataIfEnabled(this.enableCustomLog, this.devId, 'packet_length_mismatch', `Packet length mismatch, fileName: ${fileName}, expected: ${cacheFileLength * 2}, received: ${hexValue.length}`);
669
-
670
821
  // 清理受损文件的组包缓存,防止污染后续数据
671
822
  cachePacketMap.clear();
672
823
  this.packetTotalMap.set(fileName, -1);
673
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}`
827
+ }, this.onLogger);
828
+ logP2PDataIfEnabled(this.enableCustomLog, this.devId, 'packet_length_mismatch', `Packet length mismatch, fileName: ${fileName}, expected: ${cacheFileLength * 2}, received: ${hexValue.length}`);
674
829
  this.emitError({
675
830
  code: 'PACKET_LENGTH_MISMATCH',
676
831
  message: `Packet length mismatch for ${fileName}: expected ${cacheFileLength * 2}, received ${hexValue.length}`,
@@ -682,18 +837,28 @@ export class SweeperP2p extends P2pApi {
682
837
  }
683
838
  });
684
839
  if (this.mismatchCount >= 2) {
685
- logger('warn', {
840
+ logger('error', {
686
841
  msg: `consecutive length mismatch reached ${this.mismatchCount}, triggering reDownloadStream`
687
842
  }, this.onLogger);
688
843
  this.mismatchCount = 0;
844
+ this.clearRecoveryTimers();
689
845
  this.reDownloadStream('consecutive_length_mismatch');
846
+ } else {
847
+ // 仅发生 1 次时开启 2000ms 兜底检查:若流线程伴随 -30061 死掉则 2s 后自动重拉;若后续帧正常抵达则自动取消
848
+ this.scheduleReDownload('packet_mismatch_stalled', 2000);
690
849
  }
691
850
  return;
692
851
  }
693
852
 
694
- // 校验通过,重置 mismatchCount 和 reDownloadCount
853
+ // 校验通过,取消恢复观察窗并重置 mismatchCount;reDownloadCount 采用稳定期保护(cleanPath 恢复或超过 5s 后清零)
854
+ this.clearRecoveryTimers();
695
855
  this.mismatchCount = 0;
696
- this.reDownloadCount = 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
+ }
697
862
  if (this.firstPackageTime > 0 && fileName.indexOf('map') !== -1) {
698
863
  const packageTime = Date.now() - this.firstPackageTime;
699
864
  logger('info', {
@@ -712,12 +877,15 @@ export class SweeperP2p extends P2pApi {
712
877
  if (this.cacheData[type] !== hexValue) {
713
878
  logP2PDataIfEnabled(this.enableCustomLog, this.devId, 'data_received', `Data received and processed, fileName: ${fileName}, type: ${type}, dataLength: ${hexValue.length}`);
714
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);
715
883
  this.onReceiveMapData(hexValue);
716
884
  this.cacheData[type] = hexValue;
717
885
  }
718
886
  if (type === 1) {
719
887
  logger('info', {
720
- msg: `push new path data`
888
+ msg: `push new path data: file=${fileName}, serial=${fileSerialNumber}, packets=${packetDatas.length}, bytes=${hexValue.length / 2}`
721
889
  }, this.onLogger);
722
890
  this.onReceivePathData(hexValue);
723
891
  this.cacheData[type] = hexValue;
@@ -882,10 +1050,15 @@ export class SweeperP2p extends P2pApi {
882
1050
  logP2PDataIfEnabled(this.enableCustomLog, this.devId, 'stop_observer_disconnect', 'Disconnecting device');
883
1051
  this.disconnectDevice();
884
1052
  }
1053
+ this.isStopped = true;
1054
+ this.clearPacketStallTimer();
1055
+ this.clearRecoveryTimers();
885
1056
  this.removeP2pDownloadEvent();
886
1057
  this.mismatchCount = 0;
887
1058
  this.reDownloadCount = 0;
888
1059
  this.isReDownloading = false;
1060
+ this.isReconnecting = false;
1061
+ this.lastReDownloadTime = 0;
889
1062
  this.file = undefined;
890
1063
  // 没有必要cancelDownloadTask,只需要调用断连
891
1064
  // this.cancelDownloadTask();
package/lib/index.js CHANGED
@@ -33,13 +33,18 @@ const useP2PDataStream = (devId, onReceiveMapData, onReceivePathData, opt) => {
33
33
  onErrorRef.current = onError;
34
34
  const firstFrameTimer = useRef(null);
35
35
  const hasReceivedFirstFrame = useRef(false);
36
- const clearFirstFrameTimer = useCallback(() => {
36
+ const clearFirstFrameTimer = useCallback(source => {
37
37
  if (firstFrameTimer.current) {
38
38
  clearTimeout(firstFrameTimer.current);
39
39
  firstFrameTimer.current = null;
40
+ if (source) {
41
+ logger('info', {
42
+ msg: `first frame watchdog cleared by ${source}`
43
+ }, onLogger);
44
+ }
40
45
  }
41
46
  hasReceivedFirstFrame.current = true;
42
- }, []);
47
+ }, [onLogger]);
43
48
  const startFirstFrameWatchdog = useCallback(() => {
44
49
  clearFirstFrameTimer();
45
50
  hasReceivedFirstFrame.current = false;
@@ -47,7 +52,7 @@ const useP2PDataStream = (devId, onReceiveMapData, onReceivePathData, opt) => {
47
52
  firstFrameTimer.current = setTimeout(() => {
48
53
  if (!hasReceivedFirstFrame.current) {
49
54
  var _onErrorRef$current;
50
- logger('warn', {
55
+ logger('error', {
51
56
  msg: `First frame timeout (${firstFrameTimeout}ms), triggering reDownloadStream`
52
57
  }, onLogger);
53
58
  logP2PDataIfEnabled(enableCustomLog, devId, 'first_frame_timeout', `First frame timeout after ${firstFrameTimeout}ms, triggering reDownloadStream`);
@@ -63,14 +68,14 @@ const useP2PDataStream = (devId, onReceiveMapData, onReceivePathData, opt) => {
63
68
  const handleReceiveMapData = useCallback(data => {
64
69
  var _onReceiveMapDataRef$;
65
70
  if (data && data.length > 0) {
66
- clearFirstFrameTimer();
71
+ clearFirstFrameTimer('map');
67
72
  }
68
73
  (_onReceiveMapDataRef$ = onReceiveMapDataRef.current) === null || _onReceiveMapDataRef$ === void 0 || _onReceiveMapDataRef$.call(onReceiveMapDataRef, data);
69
74
  }, [clearFirstFrameTimer]);
70
75
  const handleReceivePathData = useCallback(data => {
71
76
  var _onReceivePathDataRef;
72
77
  if (data && data.length > 0) {
73
- clearFirstFrameTimer();
78
+ clearFirstFrameTimer('path');
74
79
  }
75
80
  (_onReceivePathDataRef = onReceivePathDataRef.current) === null || _onReceivePathDataRef === void 0 || _onReceivePathDataRef.call(onReceivePathDataRef, data);
76
81
  }, [clearFirstFrameTimer]);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ray-js/robot-data-stream",
3
- "version": "0.1.0-beta.0",
3
+ "version": "0.1.0-beta.1",
4
4
  "description": "扫地机P2P数据流标准化组件",
5
5
  "main": "lib/index",
6
6
  "files": [