Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
1546 lines (1420 loc) · 72.3 KB
/
Copy pathapp.js
File metadata and controls
1546 lines (1420 loc) · 72.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* ═══════════════════════════════════════════════════════════════
* app.js — 应用主控制器
*
* 职责:装配通信、解析、数据缓冲和视图,处理页面交互。
*
* 代码结构:
* 1. 工具函数(纯函数,无副作用)
* 2. 模块实例化 & 全局状态
* 3. DOM 引用(按 UI 区域分组)
* 4. 统计面板(RX/TX 速率、帧率、校验失败率)
* 5. Tab 切换
* 6. 可拖拽分隔条
* 7. 连接类型切换
* 8. 帧格式配置
* 9. 通道配置 UI
* 10. 配置控制器的装配及 JSON 文件导入导出
* 11. 数据路由 & 解析器回调
* 12. 连接管理(串口 / 网络)
* 13. 工具栏(暂停、清空、导出 CSV)
* 14. 字节流日志与发送控制器
* 15. 初始化
* ═══════════════════════════════════════════════════════════════ */
document.addEventListener('DOMContentLoaded', () => {
const { Limits, FrameBuffer, Plotter, SerialEngine, NetEngine, DataParser,
MonitorView, MonitorSearch, SendController, ConfigStore, exportFrameCsv, writeFrameCsv,
collectConfigFromView, applyConfigToView, updatePlotOptionVisibility,
parseIntInRange, parsePort, validateConfig, yRangeError, normalizeYConfig } = globalThis.SerialPlotter;
/* ─────────────────────────────────────────────────────────
* 1. 工具函数(纯函数,无副作用)
* ───────────────────────────────────────────────────────── */
/** 格式化字节数为人类可读字符串(B / KB / MB) */
const formatBytes = (n) => {
if (n < 1024) return n + ' B';
if (n < 1024 * 1024) return (n / 1024).toFixed(1) + ' KB';
return (n / (1024 * 1024)).toFixed(1) + ' MB';
};
/** 安全地格式化数值:非有限数返回 '--',否则 toFixed + 右对齐 */
const fmtFixed = (value, digits, width) => {
if (!Number.isFinite(value)) return '--'.padStart(width, ' ');
return value.toFixed(digits).padStart(width, ' ');
};
/** 返回当前时间的 "HH:MM:SS.mmm" 格式字符串 */
const formatMonitorTime = () => {
const now = new Date();
return [now.getHours(), now.getMinutes(), now.getSeconds()]
.map(n => n.toString().padStart(2, '0')).join(':')
+ '.' + now.getMilliseconds().toString().padStart(3, '0');
};
/* ─────────────────────────────────────────────────────────
* 2. 模块实例化 & 全局状态
* ───────────────────────────────────────────────────────── */
const serialAdapter = new SerialEngine(); // 串口通信适配器
const netAdapter = new NetEngine(); // 网络通信适配器(通过 bridge.js)
const parser = new DataParser(); // 二进制帧解析器
const frames = new FrameBuffer(1, 1000);
const plotter = new Plotter('waveform-canvas', frames); // 波形绘图引擎
let activeEngine = null; // 当前激活的通信引擎(serialAdapter 或 netAdapter)
let connecting = false;
let capturePaused = false; // 是否暂停数据采集
/* ─────────────────────────────────────────────────────────
* 3. DOM 引用(按 UI 区域分组)
* ───────────────────────────────────────────────────────── */
// —— 通讯 Tab ——
const connTypeSelect = document.getElementById('conn-type');
const serialConfigDiv = document.getElementById('config-serial');
const netConfigDiv = document.getElementById('config-net');
const localPortWrap = document.getElementById('wrap-local-port');
const connectBtn = document.getElementById('btn-connect');
const statusIndicator = document.getElementById('connection-indicator');
const statusText = document.getElementById('connection-status');
// —— 帧格式 Tab ——
const headerChk = document.getElementById('chk-header');
const headerConfigDiv = document.getElementById('header-config');
const headerInput = document.getElementById('frame-header');
const footerChk = document.getElementById('chk-footer');
const footerConfigDiv = document.getElementById('footer-config');
const footerInput = document.getElementById('frame-footer');
const checksumChk = document.getElementById('chk-checksum');
const dataTypeSelect = document.getElementById('data-type');
const endiannessSelect = document.getElementById('endianness');
const channelsInput = document.getElementById('channels-count');
const maxPointsInput = document.getElementById('max-points');
const plotWindowPointsInput = document.getElementById('plot-window-points');
const applyBtn = document.getElementById('btn-apply-format');
// —— 通道 Tab ——
const channelListDiv = document.getElementById('channel-config-list');
const channelsAllOnBtn = document.getElementById('btn-channels-all-on');
const channelsAllOffBtn = document.getElementById('btn-channels-all-off');
const plotViewMode = document.getElementById('plot-view-mode');
const plotYScaleMode = document.getElementById('plot-y-scale-mode');
const plotTimeXUnit = document.getElementById('plot-time-x-unit');
const plotFreqXUnit = document.getElementById('plot-freq-x-unit');
const plotFreqXScale = document.getElementById('plot-freq-x-scale');
const plotFreqYScale = document.getElementById('plot-freq-y-scale');
const plotFftWindow = document.getElementById('plot-fft-window');
const wrapPlotTimeAxis = document.getElementById('wrap-plot-time-axis');
const wrapPlotFreqAxis = document.getElementById('wrap-plot-frequency-axis');
const plotFftRemoveDc = document.getElementById('plot-fft-remove-dc');
const wrapFftRemoveDc = document.getElementById('wrap-fft-remove-dc');
const wrapPlotYBounds = document.getElementById('wrap-plot-y-bounds');
const plotYMin = document.getElementById('plot-y-min');
const plotYMax = document.getElementById('plot-y-max');
const plotYRangeStatus = document.getElementById('plot-y-range-status');
const plotChannelStats = document.getElementById('plot-channel-stats');
const plotInfoRow = document.getElementById('plot-info-row');
const plotFpsLabel = document.getElementById('stat-plot-fps');
const plotChoiceGroups = [...document.querySelectorAll('[data-plot-choice]')];
const syncPlotChoices = () => {
for (const group of plotChoiceGroups) {
const value = document.getElementById(group.dataset.plotChoice).value;
group.querySelectorAll('input[type="radio"]').forEach(radio => {
radio.checked = radio.value === value;
});
}
};
for (const group of plotChoiceGroups) group.addEventListener('change', event => {
if (!event.target.checked) return;
const control = document.getElementById(group.dataset.plotChoice);
control.value = event.target.value;
control.dispatchEvent(new Event('change'));
});
// 时域/频域独立的 Y 轴范围(字符串值,与 UI 输入框同步)
let plotYBounds = {
time: { min: '-1', max: '1', scaleMode: 'auto' },
frequency: { min: '0.001', max: '1', scaleMode: 'auto' }
};
// —— 工具栏 ——
const pauseBtn = document.getElementById('btn-pause');
const clearBtn = document.getElementById('btn-clear');
const exportBtn = document.getElementById('btn-export');
// —— 配置导入导出 ——
const exportCfgBtn = document.getElementById('btn-export-cfg');
const importCfgBtn = document.getElementById('btn-import-cfg');
const cfgFileInput = document.getElementById('cfg-file-input');
const cfgStatusText = document.getElementById('cfg-save-status');
// —— 字节流监视台 ——
const logContent = document.getElementById('data-log');
const monitor = new MonitorView(logContent, frames);
let monitorOrder = 0;
const waveformToggle = document.getElementById('show-waveform');
const monitorDisplayMode = document.getElementById('monitor-display-mode');
const monitorSearchQuery = document.getElementById('monitor-search-query');
const monitorSearchTolerance = document.getElementById('monitor-search-tolerance');
const monitorSearchChannel = document.getElementById('monitor-search-channel');
const monitorSearchChannelToggle = document.getElementById('monitor-search-channel-toggle');
const monitorSearchChannelOptions = document.getElementById('monitor-search-channel-options');
const monitorSearchStatus = document.getElementById('monitor-search-status');
let searchOrigin = 'byte';
for (const origin of ['wave', 'byte']) {
const choice = document.getElementById(`monitor-search-origin-${origin}`);
choice.checked = origin === searchOrigin;
choice.addEventListener('change', () => {
if (!choice.checked) return;
searchOrigin = origin;
for (const value of ['wave', 'byte'])
document.getElementById(`monitor-search-origin-${value}`).checked = value === origin;
});
}
const bindVisibleChoice = (fieldId, values) => {
const field = document.getElementById(fieldId);
const choices = values.map(value => document.getElementById(`${fieldId}-${value}`));
const sync = () => choices.forEach((choice, index) => {
choice.checked = field.value === values[index];
});
choices.forEach((choice, index) => choice.addEventListener('change', () => {
if (!choice.checked) return;
field.value = values[index];
field.dispatchEvent(new Event('change'));
}));
field.addEventListener('change', sync);
sync();
return sync;
};
bindVisibleChoice('monitor-display-mode', ['hex', 'ascii', 'number']);
bindVisibleChoice('send-mode', ['hex', 'text']);
const syncSendIntervalUnit = bindVisibleChoice('send-interval-unit', ['s', 'hz']);
// —— 发送面板 ——
const sendModeSelect = document.getElementById('send-mode');
const sendIntervalInput = document.getElementById('send-interval');
const sendIntervalUnit = document.getElementById('send-interval-unit');
const sendInput = document.getElementById('send-input');
const sendBtn = document.getElementById('btn-send');
const loadFileBtn = document.getElementById('btn-load-file');
const sendFileInput = document.getElementById('send-file-input');
// —— 布局分隔条 ——
const sidebar = document.getElementById('sidebar');
const mainDisplay = document.getElementById('main-display');
const hResizer = document.getElementById('h-resizer');
const rightResizer = document.getElementById('right-resizer');
const channelSidebar = document.getElementById('channel-sidebar');
const canvasWrapper = document.getElementById('canvas-wrapper');
const plotHeader = document.getElementById('plot-header');
const vResizer = document.getElementById('v-resizer');
const navigationPanel = document.getElementById('navigation-panel');
const navTimeTools = document.getElementById('nav-time-tools');
const navSearchTools = document.getElementById('nav-search-tools');
const monitorPanel = document.getElementById('monitor-panel');
const monitorHeader = document.getElementById('monitor-header');
const monitorStats = document.getElementById('monitor-stats');
const sendPanel = document.getElementById('send-panel');
/* ─────────────────────────────────────────────────────────
* 4. 统计面板(RX/TX 速率、帧率、校验失败率)
*
* 每秒计算一次,暂停时只更新基准值,不刷新显示。
* ───────────────────────────────────────────────────────── */
const stats = {
rxBytes: 0, txBytes: 0, // 累计收发字节数
_rxLast: 0, _txLast: 0, // 上次计算时的快照
_framesLast: 0, _failsLast: 0, // 上次计算时的帧数/失败数快照
_period: 1000, // 计算周期(ms)
framesPerSec: 0 // 最新帧率
};
/* 定时刷新字节流监视台统计面板。 */
const rxValue = document.getElementById('stat-rx-value');
const txValue = document.getElementById('stat-tx-value');
const frameRateValue = document.getElementById('stat-fps-value');
const failureValue = document.getElementById('stat-fail-value');
const plotFrameCount = () => plotter.displayMode === 'frequency'
? plotter.completedSpectrumDraws : plotter.completedDraws;
let plotFpsLastMode = plotter.displayMode;
let plotFpsLastDraws = plotFrameCount();
let plotFpsLastAt = performance.now();
setInterval(() => {
const now = performance.now();
const elapsed = Math.max(1, now - plotFpsLastAt);
const mode = plotter.displayMode;
const currentDraws = plotFrameCount();
const drawCount = mode === plotFpsLastMode ? currentDraws - plotFpsLastDraws : 0;
plotFpsLabel.textContent = `绘图帧率: ${(drawCount * 1000 / elapsed).toFixed(1)} FPS`;
plotFpsLabel.title = mode === 'frequency'
? '频域统计实际更新并绘制的新频谱,不计重复绘制的缓存频谱。'
: '时域统计已完成的画布绘制。';
plotFpsLastDraws = currentDraws;
plotFpsLastMode = mode;
plotFpsLastAt = now;
if (capturePaused) {
// 暂停期间只同步基准值,避免恢复后出现瞬时峰值
stats._rxLast = stats.rxBytes;
stats._txLast = stats.txBytes;
stats._framesLast = parser.frameCount;
stats._failsLast = parser.failCount;
return;
}
const rxBps = stats.rxBytes - stats._rxLast;
const txBps = stats.txBytes - stats._txLast;
const frames = (parser.frameCount - stats._framesLast) / (stats._period / 1000);
const fails = parser.failCount - stats._failsLast;
const total = frames + fails;
const failPct = total > 0 ? ((fails / total) * 100).toFixed(1) : '0.0';
rxValue.textContent = `${formatBytes(rxBps)}/s`;
txValue.textContent = `${formatBytes(txBps)}/s`;
frameRateValue.textContent = `${frames} f/s`;
failureValue.textContent = `${failPct}%`;
stats._rxLast = stats.rxBytes;
stats._txLast = stats.txBytes;
stats._framesLast = parser.frameCount;
stats._failsLast = parser.failCount;
stats.framesPerSec = frames;
plotter.setSampleRateHz(frames);
}, stats._period);
/** 渲染波形统计信息到绘图区标题栏(单通道时显示) */
const renderPlotStats = (statsData) => {
if (!statsData) {
if (!plotInfoRow.hidden) plotInfoRow.hidden = true;
return;
}
// 主频跟随频域单位;主周期跟随时域单位,两者都使用同一 FFT 结果。
const frequencyUnit = plotter.freqXUnit === 'bins' ? 'Bin' : 'Hz';
const periodUnit = plotter.timeXUnit === 's' ? 's' : 'Sample';
const frequencyValue = frequencyUnit === 'Bin' ? statsData.dominantBin
: statsData.freq != null && plotter.sampleRateHz > 0
? statsData.freq * plotter.sampleRateHz : null;
const periodValue = periodUnit === 'Sample' ? statsData.period
: statsData.period != null && plotter.sampleRateHz > 0
? statsData.period / plotter.sampleRateHz : null;
const frequencyText = frequencyValue == null ? '--'
: fmtFixed(frequencyValue, frequencyUnit === 'Bin' ? 0 : 6, 15);
const periodText = periodValue == null ? '--'
: fmtFixed(periodValue, periodUnit === 'Sample' ? 0 : 6, 15);
const segments = [
['通道:', statsData.channelLabel],
['最大值:', fmtFixed(statsData.max, 6, 15)],
['最小值:', fmtFixed(statsData.min, 6, 15)],
['峰峰值:', fmtFixed(statsData.pp, 6, 15)],
['均值:', fmtFixed(statsData.mean, 6, 15)],
['标准差:', fmtFixed(statsData.stdDev, 6, 15)],
['主频:', `${frequencyText} ${frequencyUnit}`],
['主周期:', `${periodText} ${periodUnit}`]
];
if (!plotChannelStats.children.length) {
const cells = segments.map(([label]) => {
const cell = document.createElement('span');
cell.className = 'plot-info-segment monitor-stat-item';
const name = document.createElement('span');
name.className = 'monitor-stat-label';
name.textContent = label;
const value = document.createElement('span');
value.className = 'monitor-stat-value';
cell.append(name, value);
return cell;
});
plotChannelStats.replaceChildren(...cells);
}
segments.forEach(([, value], index) => {
plotChannelStats.children[index].children[1].textContent = index === 0
? value : String(value).trim();
});
if (plotInfoRow.hidden) plotInfoRow.hidden = false;
};
plotter.onStatsUpdate = renderPlotStats;
/* ─────────────────────────────────────────────────────────
* 5. Tab 切换(通讯 / 帧格式 / 通道)
* ───────────────────────────────────────────────────────── */
document.querySelectorAll('.tab-btn').forEach(btn => {
btn.addEventListener('click', () => {
document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));
btn.classList.add('active');
document.getElementById(btn.dataset.tab).classList.add('active');
});
});
/* ─────────────────────────────────────────────────────────
* 6. 可拖拽分隔条
*
* 水平分隔条:调整侧栏宽度(180~500px)
* 垂直分隔条:调整波形区 / 监视台高度比例
* ───────────────────────────────────────────────────────── */
// —— 水平分隔条(左侧设置 ↔ 主区域 ↔ 右侧通道)——
let hDragging = false, hStartX = 0, hStartW = 0;
let rightDragging = false, rightStartX = 0, rightStartW = 0;
const appContainer = document.querySelector('.app-container');
const minPlotWidth = 320;
const dividerWidth = () => hResizer.offsetWidth + rightResizer.offsetWidth;
/** 应用侧栏宽度并触发波形重绘,与 applyVerticalHeights 对应 */
const applySidebarWidth = (newW) => {
const available = appContainer.clientWidth - channelSidebar.offsetWidth -
dividerWidth() - minPlotWidth;
const w = Math.max(180, Math.min(500, available, newW));
sidebar.style.width = sidebar.style.minWidth = sidebar.style.maxWidth = w + 'px';
plotter.resize();
};
const applyRightWidth = newW => {
const available = appContainer.clientWidth - sidebar.offsetWidth -
dividerWidth() - minPlotWidth;
const width = Math.max(240, Math.min(520, available, newW));
channelSidebar.style.width = channelSidebar.style.minWidth =
channelSidebar.style.maxWidth = width + 'px';
plotter.resize();
};
/* 窗口缩小时约束侧栏宽度不超出可用空间 */
window.addEventListener('resize', () => {
applyRightWidth(channelSidebar.offsetWidth);
applySidebarWidth(sidebar.offsetWidth);
});
hResizer.addEventListener('mousedown', (e) => {
hDragging = true;
hStartX = e.clientX;
hStartW = sidebar.offsetWidth;
document.body.style.cursor = 'ew-resize';
document.body.style.userSelect = 'none';
e.preventDefault();
});
rightResizer.addEventListener('mousedown', e => {
rightDragging = true;
rightStartX = e.clientX;
rightStartW = channelSidebar.offsetWidth;
document.body.style.cursor = 'ew-resize';
document.body.style.userSelect = 'none';
e.preventDefault();
});
document.addEventListener('mousemove', (e) => {
if (!hDragging) return;
applySidebarWidth(hStartW + (e.clientX - hStartX));
});
document.addEventListener('mousemove', e => {
if (!rightDragging) return;
applyRightWidth(rightStartW - (e.clientX - rightStartX));
});
document.addEventListener('mouseup', () => {
if (!hDragging) return;
hDragging = false;
document.body.style.cursor = '';
document.body.style.userSelect = '';
});
document.addEventListener('mouseup', () => {
if (!rightDragging) return;
rightDragging = false;
document.body.style.cursor = '';
document.body.style.userSelect = '';
});
applyRightWidth(channelSidebar.offsetWidth);
applySidebarWidth(sidebar.offsetWidth);
// —— 垂直分隔条(波形区 ↔ 监视台)——
let vDragging = false, vStartY = 0, vStartH = 0;
let canvasH = null;
let canvasRatio = 0.62;
let manualVerticalSplit = false;
let waveformVisible = true;
const minLogHeight = 92; // 四条 20px 记录行和上下各 6px 内边距
const mainDisplayVerticalPadding = 16; // 对应 .main-display 的上下各 8px
const minimumMonitorHeight = () => monitorHeader.offsetHeight + monitorStats.offsetHeight +
sendPanel.offsetHeight + navigationPanel.offsetHeight + minLogHeight + 8;
const minimumCanvasHeight = () => Math.max(60, plotHeader.offsetHeight + 24);
const verticalUsableHeight = () => Math.max(140, mainDisplay.clientHeight -
mainDisplayVerticalPadding - vResizer.offsetHeight);
/** 根据 canvasH 重新分配波形区和监视台的高度,与 applySidebarWidth 对应 */
const applyVerticalHeights = () => {
if (!waveformVisible) {
canvasWrapper.hidden = true;
vResizer.hidden = true;
monitorPanel.style.flex = '1';
monitorPanel.style.height = '';
return;
}
canvasWrapper.hidden = false;
vResizer.hidden = false;
const usable = verticalUsableHeight();
const minMonitorH = Math.max(minimumMonitorHeight(), manualVerticalSplit ? 0
: Math.min(320, Math.max(180, usable * 0.42)));
canvasH = Math.max(minimumCanvasHeight(), Math.min(usable - minMonitorH,
Math.round(usable * canvasRatio)));
const monH = Math.max(minMonitorH, usable - canvasH);
canvasWrapper.style.flex = 'none';
canvasWrapper.style.height = canvasH + 'px';
monitorPanel.style.flex = 'none';
monitorPanel.style.height = monH + 'px';
plotter.resize();
};
applyVerticalHeights();
window.addEventListener('resize', applyVerticalHeights);
if (typeof ResizeObserver !== 'undefined') {
const toolsResizeObserver = new ResizeObserver(() => applyVerticalHeights());
for (const section of [plotHeader, navigationPanel, monitorHeader, monitorStats,
sendPanel]) toolsResizeObserver.observe(section);
}
waveformToggle.addEventListener('change', () => {
waveformVisible = waveformToggle.checked;
plotter.isVisible = waveformVisible;
applyVerticalHeights();
if (waveformVisible) plotter.resize();
});
const focusFrameInBothMonitors = index => {
if (plotViewMode.value !== 'time') {
plotViewMode.value = 'time';
plotViewMode.dispatchEvent(new Event('change'));
}
plotter.jumpToFrame(index);
monitor.jumpToFrame(index);
};
const bindTimeJump = () => {
const mode = document.getElementById('nav-jump-mode');
const absolute = document.getElementById('nav-jump-absolute');
const relative = document.getElementById('nav-jump-relative');
const relativeUnit = document.getElementById('nav-jump-relative-unit');
const status = document.getElementById('nav-jump-status');
for (const value of ['absolute', 'relative']) {
const choice = document.getElementById(`nav-jump-mode-${value}`);
choice.addEventListener('change', () => {
if (!choice.checked) return;
mode.value = value;
mode.dispatchEvent(new Event('change'));
});
}
mode.addEventListener('change', () => {
for (const value of ['absolute', 'relative'])
document.getElementById(`nav-jump-mode-${value}`).checked = mode.value === value;
absolute.hidden = mode.value !== 'absolute';
relative.hidden = mode.value !== 'relative';
relativeUnit.hidden = mode.value !== 'relative';
applyVerticalHeights();
});
document.getElementById('nav-jump-button').addEventListener('click', () => {
if (!capturePaused) return;
if (!frames.length || !Number.isFinite(frames.originTimestamp)) {
status.textContent = '尚无带时间戳的采样帧';
return;
}
const seconds = Number(relative.value);
const target = mode.value === 'absolute' ? new Date(absolute.value).getTime()
: relative.value.trim() !== '' && Number.isFinite(seconds) && seconds >= 0
? frames.originTimestamp + seconds * 1000 : NaN;
if (!Number.isFinite(target)) {
status.textContent = '请输入有效时间';
return;
}
const index = frames.nearestTimestampIndex(target);
const order = frames.orderAt(index);
monitor.cursorOrder = order;
plotter.setNavigationMarkers({ timeOrder: order,
matches: searchMatches, currentMatch: selectedMatch }, false);
focusFrameInBothMonitors(index);
status.textContent = `已定位第 ${index + 1} 帧,共 ${frames.length} 帧`;
});
};
bindTimeJump();
const defaultJumpDateTime = () => {
const latestTimestamp = frames.timestampAt(frames.length - 1);
const hasFrameTime = Number.isFinite(latestTimestamp);
const date = hasFrameTime ? new Date(latestTimestamp) : new Date();
const pad = (value, width = 2) => String(value).padStart(width, '0');
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}` +
`T${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}.` +
pad(date.getMilliseconds(), 3);
};
let channelCheckboxes = [];
const toolPanels = [navTimeTools, navSearchTools];
const toolControlIds = [
'nav-jump-mode-absolute', 'nav-jump-mode-relative',
'nav-jump-absolute', 'nav-jump-relative', 'nav-jump-button',
'monitor-search-query', 'monitor-search-tolerance', 'monitor-search-channel-toggle',
'monitor-search-nearest', 'monitor-search-prev', 'monitor-search-next',
'monitor-search-origin-wave', 'monitor-search-origin-byte'
];
const syncTimeTools = () => {
for (const tools of toolPanels)
tools.classList[capturePaused ? 'remove' : 'add']('tools-disabled');
for (const id of toolControlIds)
document.getElementById(id).disabled = !capturePaused;
for (const { input } of channelCheckboxes) input.disabled = !capturePaused;
if (!capturePaused) {
monitorSearchChannelOptions.hidden = true;
monitorSearchChannelToggle.ariaExpanded = 'false';
}
if (capturePaused) {
const value = defaultJumpDateTime();
document.getElementById('nav-jump-absolute').value = value;
}
};
syncTimeTools();
let selectedSearchChannels = null; // null means all channels
const selectedChannelFilter = () => selectedSearchChannels === null
? -1 : [...selectedSearchChannels].sort((left, right) => left - right);
const syncSearchChannelSelection = () => {
const all = selectedSearchChannels === null;
for (const { input, channel } of channelCheckboxes)
input.checked = channel < 0 ? all : !all && selectedSearchChannels.has(channel);
const names = all ? [] : [...selectedSearchChannels]
.sort((left, right) => left - right).map(channel => `CH${channel + 1}`);
monitorSearchChannelToggle.textContent = all ? '全部通道' :
names.length <= 2 ? names.join('、') : `已选 ${names.length} 通道`;
monitorSearchChannelToggle.title = all ? '搜索全部通道' : names.join('、');
};
const populateSearchChannels = () => {
if (selectedSearchChannels !== null) {
selectedSearchChannels = new Set([...selectedSearchChannels]
.filter(channel => channel < frames.channelCount));
if (!selectedSearchChannels.size) selectedSearchChannels = null;
}
channelCheckboxes = [];
monitorSearchChannelOptions.replaceChildren();
for (let channel = -1; channel < frames.channelCount; channel++) {
const label = document.createElement('label');
const input = document.createElement('input');
input.type = 'checkbox';
input.value = String(channel);
input.disabled = !capturePaused;
label.append(input, channel < 0 ? '全部通道' : `CH${channel + 1}`);
input.addEventListener('change', () => {
if (channel < 0) selectedSearchChannels = null;
else {
if (selectedSearchChannels === null) selectedSearchChannels = new Set();
if (input.checked) selectedSearchChannels.add(channel);
else selectedSearchChannels.delete(channel);
if (!selectedSearchChannels.size) selectedSearchChannels = null;
}
syncSearchChannelSelection();
invalidateSearch();
});
channelCheckboxes.push({ input, channel });
monitorSearchChannelOptions.appendChild(label);
}
syncSearchChannelSelection();
};
monitorSearchChannelToggle.addEventListener('click', () => {
monitorSearchChannelOptions.hidden = !monitorSearchChannelOptions.hidden;
monitorSearchChannelToggle.ariaExpanded = String(!monitorSearchChannelOptions.hidden);
});
document.addEventListener('click', event => {
if (monitorSearchChannelOptions.hidden || monitorSearchChannel.contains(event.target)) return;
monitorSearchChannelOptions.hidden = true;
monitorSearchChannelToggle.ariaExpanded = 'false';
});
document.addEventListener('keydown', event => {
if (event.key !== 'Escape') return;
monitorSearchChannelOptions.hidden = true;
monitorSearchChannelToggle.ariaExpanded = 'false';
});
populateSearchChannels();
let searchSession = null;
let searchGeneration = 0;
let searchMatches = [];
let selectedMatch = -1;
let searchKey = null;
let searchReady = false;
let pendingSearchAction = null;
const syncSearchFields = () => {
const numeric = monitorDisplayMode.value === 'number';
monitorSearchTolerance.hidden = !numeric;
monitorSearchChannel.hidden = !numeric;
if (!numeric) {
monitorSearchChannelOptions.hidden = true;
monitorSearchChannelToggle.ariaExpanded = 'false';
}
monitorSearchQuery.placeholder = numeric ? '目标数值' :
monitorDisplayMode.value === 'ascii' ? 'ASCII 文本' : '十六进制字节';
if (numeric) populateSearchChannels();
applyVerticalHeights();
};
const invalidateSearch = () => {
searchGeneration++;
searchSession = null;
searchMatches = [];
selectedMatch = -1;
searchKey = null;
searchReady = false;
pendingSearchAction = null;
monitor.setSearchResults([]);
plotter.setNavigationMarkers({ timeOrder: plotter.navigationMarkers.timeOrder,
matches: [], currentMatch: -1 });
monitorSearchStatus.textContent = '';
};
for (const input of [monitorSearchQuery, monitorSearchTolerance])
input.addEventListener('input', invalidateSearch);
monitorDisplayMode.addEventListener('change', () => {
monitor.setMode(monitorDisplayMode.value);
invalidateSearch();
syncSearchFields();
});
syncSearchFields();
const showSearchMatch = index => {
if (!capturePaused) return;
if (!searchMatches.length) {
monitorSearchStatus.textContent = '无匹配结果';
return;
}
selectedMatch = (index + searchMatches.length) % searchMatches.length;
const match = searchMatches[selectedMatch];
const frame = frames.indexAtOrAfterOrder(match.startOrder);
if (frames.orderAt(frame) !== match.startOrder) {
monitorSearchStatus.textContent = '该结果已被缓冲区覆盖,请重新搜索';
return;
}
monitor.selectSearchMatch(selectedMatch);
plotter.setNavigationMarkers({ timeOrder: plotter.navigationMarkers.timeOrder,
matches: searchMatches, currentMatch: selectedMatch }, false);
focusFrameInBothMonitors(frame);
monitorSearchStatus.textContent = `${selectedMatch + 1} / ${searchMatches.length}`;
};
const searchInsertionIndex = frame => {
let low = 0, high = searchMatches.length;
while (low < high) {
const mid = Math.floor((low + high) / 2);
if (searchMatches[mid].startFrame < frame) low = mid + 1;
else high = mid;
}
return low;
};
const nearestSearchIndex = frame => {
const next = searchInsertionIndex(frame);
let candidate = next;
if (next >= searchMatches.length) candidate = searchMatches.length - 1;
else if (next > 0 && frame - searchMatches[next - 1].startFrame <=
searchMatches[next].startFrame - frame) candidate = next - 1;
// Select the first result in a frame, including multiple channels or byte matches.
return searchInsertionIndex(searchMatches[candidate].startFrame);
};
const navigateSearch = ({ action, frame }) => {
if (!searchMatches.length) {
monitorSearchStatus.textContent = '无匹配结果';
return;
}
if (action !== 'nearest' && selectedMatch >= 0) {
showSearchMatch(selectedMatch + (action === 'next' ? 1 : -1));
return;
}
const nearest = nearestSearchIndex(frame);
const offset = action === 'prev' ? 1 : action === 'next' ? -1 : 0;
showSearchMatch(nearest + offset);
};
const requestSearch = action => {
if (!capturePaused) return;
try {
const options = MonitorSearch.parseMonitorSearch(monitorDisplayMode.value,
monitorSearchQuery.value, monitorSearchTolerance.value,
selectedChannelFilter());
const key = JSON.stringify([monitorDisplayMode.value, monitorSearchQuery.value,
monitorSearchTolerance.value, selectedChannelFilter(), frames.version]);
const request = { action, frame: searchOrigin === 'wave'
? plotter.currentFrameIndex() : monitor.currentFrameIndex() };
if (key === searchKey) {
if (searchReady) navigateSearch(request);
else if (searchSession) pendingSearchAction = request;
return;
}
const session = new MonitorSearch.MonitorSearchSession(frames, options);
searchKey = key;
searchReady = false;
pendingSearchAction = request;
searchSession = session;
searchMatches = [];
selectedMatch = -1;
monitor.setSearchResults([]);
plotter.setNavigationMarkers({ timeOrder: plotter.navigationMarkers.timeOrder,
matches: [], currentMatch: -1 });
const generation = ++searchGeneration;
const scan = () => {
if (generation !== searchGeneration || !capturePaused) return;
try {
let done = false;
for (let batch = 0; batch < 8 && !done; batch++) done = session.step(512);
if (done) {
searchMatches = session.matches;
searchSession = null;
searchReady = true;
monitor.setSearchResults(searchMatches);
navigateSearch(pendingSearchAction);
pendingSearchAction = null;
} else {
monitorSearchStatus.textContent = `搜索中 ${session.position} / ${session.length}`;
setTimeout(scan, 0);
}
} catch (error) {
searchSession = null;
searchKey = null;
searchReady = false;
pendingSearchAction = null;
monitorSearchStatus.textContent = error.message;
}
};
scan();
} catch (error) { monitorSearchStatus.textContent = error.message; }
};
for (const action of ['nearest', 'prev', 'next'])
document.getElementById(`monitor-search-${action}`).addEventListener('click', () =>
requestSearch(action));
vResizer.addEventListener('mousedown', (e) => {
vDragging = true;
vStartY = e.clientY;
vStartH = canvasWrapper.offsetHeight;
document.body.style.cursor = 'ns-resize';
document.body.style.userSelect = 'none';
e.preventDefault();
});
document.addEventListener('mousemove', (e) => {
if (!vDragging) return;
const usable = verticalUsableHeight();
const minMonitorH = minimumMonitorHeight();
canvasH = Math.max(minimumCanvasHeight(), Math.min(usable - minMonitorH,
vStartH + (e.clientY - vStartY)));
canvasRatio = canvasH / usable;
manualVerticalSplit = true;
applyVerticalHeights();
});
document.addEventListener('mouseup', () => {
if (!vDragging) return;
vDragging = false;
document.body.style.cursor = '';
document.body.style.userSelect = '';
});
/* ─────────────────────────────────────────────────────────
* 7. 连接类型切换(Serial ↔ TCP/UDP)
*
* 切换时显示/隐藏对应的配置面板,并保存配置。
* ───────────────────────────────────────────────────────── */
const updateConnectionModeUI = () => {
const v = connTypeSelect.value;
serialConfigDiv.style.display = v === 'serial' ? '' : 'none';
netConfigDiv.style.display = v !== 'serial' ? '' : 'none';
// UDP 和 TCP Server 需要额外配置本地端口
localPortWrap.style.display = (v === 'udp' || v === 'tcp-server') ? 'flex' : 'none';
};
connTypeSelect.addEventListener('change', () => {
updateConnectionModeUI();
saveConfig();
});
/* ─────────────────────────────────────────────────────────
* 8. 帧格式配置
*
* 包括:帧头/帧尾启用切换、校验位、数据类型、端序、通道数。
* 点击"应用"后将配置同步给 DataParser 和 Plotter。
* ───────────────────────────────────────────────────────── */
/** 切换帧头/帧尾配置区的启用状态(禁用时半透明 + 不可交互) */
const toggleConfigSection = (checkbox, container) => {
container.style.opacity = checkbox.checked ? '1' : '0.4';
container.style.pointerEvents = checkbox.checked ? '' : 'none';
};
headerChk.addEventListener('change', () => { toggleConfigSection(headerChk, headerConfigDiv); saveConfig(); });
footerChk.addEventListener('change', () => { toggleConfigSection(footerChk, footerConfigDiv); saveConfig(); });
// 初始化时根据 checkbox 状态设置样式
toggleConfigSection(headerChk, headerConfigDiv);
toggleConfigSection(footerChk, footerConfigDiv);
/** 将当前 UI 上的帧格式配置同步给 parser 和 plotter */
const updateParserSettings = () => {
const ch = parseIntInRange(channelsInput.value, Limits.minChannels, Limits.maxChannels, '通道数');
const maxPoints = parseIntInRange(maxPointsInput.value, Limits.minPoints, Limits.maxPoints, '采样点数');
const plotWindowPoints = parseIntInRange(plotWindowPointsInput.value,
Limits.minPoints, Limits.maxPlotWindowPoints, '波形监视台内采样点数');
parser.setFormat({
enableHeader: headerChk.checked,
headerHex: headerInput.value,
enableFooter: footerChk.checked,
footerHex: footerInput.value,
dataType: dataTypeSelect.value,
isLittleEndian: endiannessSelect.value === 'little',
channelsCount: ch,
enableChecksum: checksumChk.checked
});
plotter.setChannelCount(ch);
populateSearchChannels();
plotter.setMaxPoints(maxPoints);
plotter.setPlotWindowPoints(Math.min(plotWindowPoints, maxPoints));
plotWindowPointsInput.value = String(plotter.plotWindowPoints);
plotWindowPointsInput.max = String(Math.min(maxPoints, Limits.maxPlotWindowPoints));
rebuildChannelList();
syncPlotDisplaySettings();
};
maxPointsInput.addEventListener('change', () => {
try {
plotter.setMaxPoints(parseIntInRange(maxPointsInput.value, Limits.minPoints, Limits.maxPoints, '采样点数'));
plotWindowPointsInput.value = String(plotter.plotWindowPoints);
plotWindowPointsInput.max = String(Math.min(plotter.maxPoints, Limits.maxPlotWindowPoints));
monitor.render();
saveConfig();
} catch (error) {
maxPointsInput.value = plotter.maxPoints;
alert(error.message);
}
});
plotWindowPointsInput.addEventListener('change', () => {
try {
plotter.setPlotWindowPoints(parseIntInRange(plotWindowPointsInput.value,
Limits.minPoints, Math.min(plotter.maxPoints, Limits.maxPlotWindowPoints),
'波形监视台内采样点数'));
saveConfig();
} catch (error) {
plotWindowPointsInput.value = String(plotter.plotWindowPoints);
alert(error.message);
}
});
applyBtn.addEventListener('click', () => {
try { updateParserSettings(); }
catch (error) { alert(error.message); return; }
saveConfig();
// 短暂反馈,让用户知道配置已生效
applyBtn.textContent = '✓ 已应用';
setTimeout(() => { applyBtn.textContent = '应用帧格式配置'; }, 1200);
});
/* ─────────────────────────────────────────────────────────
* 9. 通道配置 UI
*
* 根据 plotter 中的通道数据动态生成配置行:
* - 颜色选择器
* - 名称输入框
* - 可见性复选框
* ───────────────────────────────────────────────────────── */
/** 将绘图显示选项同步给 plotter(时域/频域、Y 轴策略、Y 轴范围等) */
const syncPlotDisplaySettings = ({ resetYZoom = false } = {}) => {
const errors = {};
for (const mode of ['time', 'frequency']) {
const bounds = plotYBounds[mode];
errors[mode] = bounds.scaleMode === 'manual'
? yRangeError(bounds.min, bounds.max, mode === 'frequency' && plotFreqYScale.value === 'log') : '';
}
const mode = plotViewMode.value === 'frequency' ? 'frequency' : 'time';
plotYRangeStatus.textContent = errors[mode] ? `${errors[mode]},当前范围未应用,暂用自动范围。` : '';
plotYRangeStatus.hidden = !errors[mode];
plotter.setDisplayOptions({
displayMode: plotViewMode.value,
yScaleModeTime: errors.time ? 'auto' : plotYBounds.time.scaleMode,
yScaleModeFreq: errors.frequency ? 'auto' : plotYBounds.frequency.scaleMode,
resetYZoom,
timeXUnit: plotTimeXUnit.value,
freqXUnit: plotFreqXUnit.value,
freqXScale: plotFreqXScale.value,
freqYScale: plotFreqYScale.value,
removeDcForFft: plotFftRemoveDc.checked,
fftWindow: plotFftWindow.value,
yMinTime: plotYBounds.time.min, yMaxTime: plotYBounds.time.max,
yMinFreq: plotYBounds.frequency.min, yMaxFreq: plotYBounds.frequency.max
});
};
/** 重建通道配置列表 UI(在通道数变化或应用帧格式时调用) */
const expandedChannelIndices = new Set();
const rebuildChannelList = () => {
channelListDiv.innerHTML = '';
const metas = plotter.getChannelMeta();
for (const index of expandedChannelIndices)
if (index >= metas.length) expandedChannelIndices.delete(index);
if (metas.length === 0) {
const p = document.createElement('p');
p.className = 'hint-text';
p.textContent = '请先在帧格式页设置通道数并点击应用。';
channelListDiv.appendChild(p);
return;
}
metas.forEach(meta => {
const row = document.createElement('div');
row.className = 'channel-row';
// CH 按钮展开该通道的放大与偏移设置。
const channelToggle = document.createElement('button');
channelToggle.type = 'button';
channelToggle.className = 'channel-row-label channel-expand-toggle';
channelToggle.textContent = `CH${meta.index + 1}`;
channelToggle.ariaExpanded = String(expandedChannelIndices.has(meta.index));
channelToggle.style.opacity = meta.visible ? '1' : '0.4';
// 颜色选择器
const colorInput = document.createElement('input');
colorInput.type = 'color';
colorInput.className = 'channel-color-swatch';
colorInput.value = meta.color;
colorInput.title = '点击更改颜色';
colorInput.addEventListener('input', () => {
plotter.setChannelColor(meta.index, colorInput.value);
saveConfig();
});
// 名称输入框
const nameInput = document.createElement('input');
nameInput.type = 'text';
nameInput.className = 'channel-name-input';
nameInput.value = meta.name;
nameInput.placeholder = `CH${meta.index + 1}`;
nameInput.addEventListener('change', () => {