Repository navigation
Expand file tree
/
Copy pathapp.core.js
More file actions
3127 lines (2873 loc) · 122 KB
/
Copy pathapp.core.js
File metadata and controls
3127 lines (2873 loc) · 122 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
'use strict';
/* ============================================================================
* SerialCanvas - app core (part 1 of 3)
* Opens the application IIFE. Contains constants, application state, DOM
* references and shared utility helpers. The IIFE closure continues in
* app.terminal.js and is closed by app.main.js - load order matters:
* bootstrap.js -> vendor/xterm/* -> app.core.js -> app.terminal.js -> app.main.js
* ==========================================================================*/
(() => {
const VERSION = '0.4.2';
const ONLINE_VERSION_URL = 'https://ra9fael.github.io/SerialCanvas/';
const VERSION_MODAL_SEEN_KEY = 'serialweb:version-modal-seen';
const MAX_DERIVED_LOG_LINES = 320;
const SERIAL_BUFFER_SIZE = 65536;
const PRESET_EXPECTATION_TIMEOUT_MS = 1800;
const PLAYER_STEP_MS = 250;
const PLAYER_FAST_STEP_MS = 1000;
const HIGH_RES_TIME_EPOCH_MS = (typeof performance !== 'undefined' && Number.isFinite(performance.timeOrigin))
? performance.timeOrigin
: (Date.now() - (typeof performance !== 'undefined' ? performance.now() : 0));
const MAX_CHART_HISTORY_MS = 60000;
const MAX_TIME_CHART_HISTORY_MS = 30000;
const MAX_CHART_POINTS = 180000;
const MAX_CHART_RENDER_POINTS = 6000;
const MAX_RX_OPEN_EVENT_BYTES = 2048;
const MAX_RX_OPEN_EVENT_TEXT_CHARS = 2048;
const LOCAL_PREFS_KEY = 'serialweb:prefs';
const LOCAL_PREFS_DEBOUNCE_MS = 500;
const RECEIVE_CONTENT_SCHEMA_VERSION = 1;
const SERIAL_RECONFIGURE_DEBOUNCE_MS = 420;
const SEND_EXTENSION_DEFAULT_HEIGHT = 252;
const SEND_EXTENSION_MIN_HEIGHT = 120;
const SEND_MONITOR_MIN_HEIGHT = 150;
const DOWNLOAD_HTML_FILENAME = 'SerialCanvas串口调试.html';
const CHART_ZOOM_MIN = 0.02;
const CHART_ZOOM_MAX = 240;
const MODE_PULSE_MS = 500;
const CHART_COLORS = ['#1d7af2', '#0e9f6e', '#d97706', '#c2410c', '#8b5cf6', '#ef4444', '#14b8a6'];
const TIMELINE_BIN_MAGIC = new Uint8Array([0x57, 0x53, 0x4c, 0x42, 0x49, 0x4e, 0x31, 0x00]);
const appEl = document.body;
/* Binary frame template.
A binary frame has no textual shape, so a text payload template cannot
describe one — which is why the payload template used to be disabled for
binary scripts and the A5 layout was hard-coded in the script. This is the
replacement: a whitespace-separated list of hex byte groups and
placeholders, expanded per tick.
A5 hex byte group, one or more bytes
{t} temperature x10, clamped to one byte
{h} humidity, rounded and clamped to one byte
{n} tick counter, low byte
{sum} SUM8 of the placeholder-produced bytes so far
{sum} deliberately covers the placeholder bytes and NOT the literal hex
groups. That is the rule the parser applies to a checksum row ("仅覆盖
data 行的字节"), and the two have to agree or every simulated frame would
decode with a red checksum. Summing everything emitted so far looks more
natural and is wrong: it folds the frame header into the checksum.
The default expands to the exact bytes the A5 script used to hard-code —
A5, temp*10, humidity, SUM8 of those two, 5A — and therefore still matches
the script's schema byte for byte. */
const SIMULATION_FRAME_TEMPLATE_DEFAULT = 'A5 {t} {h} {sum} 5A';
const SIMULATION_FRAME_TEMPLATE_MAX = 160;
const SIMULATION_FRAME_PLACEHOLDERS = ['{t}', '{h}', '{n}', '{sum}'];
/* Expands a frame template into bytes.
Returns the default frame when the template is empty or expands to nothing,
so a half-typed template degrades to "still sending the built-in frame"
rather than to silence — silence reads as a stalled simulator. */
function buildSimulationFrame(template, tick) {
const source = String(template || '').trim() || SIMULATION_FRAME_TEMPLATE_DEFAULT;
const temp = 21 + Math.sin(tick / 9) * 3.5;
const hum = 48 + Math.cos(tick / 7) * 6;
const clampByte = (value) => Math.max(0, Math.min(255, Math.round(Number(value) || 0)));
const bytes = [];
// Placeholder bytes only: the checksum domain, matching the parser.
const checksumBytes = [];
const pushValue = (value) => {
bytes.push(value);
checksumBytes.push(value);
};
source.split(/\s+/).forEach((token) => {
if (!token) return;
if (token === '{t}') {
pushValue(clampByte(temp * 10));
return;
}
if (token === '{h}') {
pushValue(clampByte(hum));
return;
}
if (token === '{n}') {
pushValue(((Number(tick) || 0) % 256 + 256) % 256);
return;
}
if (token === '{sum}') {
pushValue(checksumBytes.reduce((sum, byte) => (sum + byte) & 0xff, 0));
return;
}
const literal = safeHexBytes(token);
// Literal bytes are framing, not payload: outside the checksum domain.
if (literal.length) bytes.push(...literal);
});
if (!bytes.length) return buildSimulationFrame(SIMULATION_FRAME_TEMPLATE_DEFAULT, tick);
return Uint8Array.from(bytes);
}
/* Protocol simulation.
Generates RX locally so the parser, the live results and the charts can be
exercised without a device attached. The bytes go through queueRxBytes() -
the same entry point the serial reader uses - so line splitting, parsing,
recording and chart painting all behave exactly as they do for real
traffic. Nothing here re-implements any of that.
Scripts are fixed rather than user-editable for now; what each frame
contains is configurable (see the frame template above and the payload
template in app.main.js). Three are provided: two text grammars and one
binary schema. */
const SIMULATION_SCRIPTS = {
'text-sensor': {
label: '文本:传感器读数',
/* Matches the documented rule "/name0=/float0,/name1=/int0". The
trailing \n matters: frames are split on CR/LF, so without it every tick
would concatenate into one ever-growing display event instead of one
line per reading. Real devices terminate their frames too. */
textRule: '/name0=/float0,/name1=/int0',
// Seeds the payload box. It expands to exactly what build() emits, so
// seeding it changes no bytes — it only makes the format visible and
// editable. That is the whole point: a template the user cannot see is a
// template the user cannot use.
templateDefault: 'temp={temp},humid={hum};',
build: (tick) => {
const temp = 21 + Math.sin(tick / 9) * 3.5;
const hum = 48 + Math.cos(tick / 7) * 6;
return encodeText(`temp=${temp.toFixed(1)},humid=${Math.round(hum)};\n`, 'utf-8');
}
},
'text-json': {
label: '文本:JSON 负载',
// With an empty rule box the parser tries JSON, so this script
// demonstrates that fallback rather than a text rule.
// Same idea as above; {temp} carries one decimal where build() writes
// two, which JSON parsing does not care about.
templateDefault: '{"device":"sim-01","uptime":{n},"temp":{temp}}',
build: (tick) => {
const temp = 21 + Math.sin(tick / 9) * 3.5;
return encodeText(
JSON.stringify({ device: 'sim-01', uptime: tick, temp: Number(temp.toFixed(2)) }) + '\n',
'utf-8'
);
}
},
'binary-frame': {
label: '二进制:A5 帧',
/* Frame layout: A5 / payload / SUM8 / 5A.
The payload is ONE uint16 little-endian field packing temp*10 and
humidity, so it decodes under a single schema row. The previous
version emitted two separate bytes, which cannot match a one-row
schema and therefore produced empty parse cards — the comment here
used to claim it "matches the default seeded schema" and that was
false, because state.parser.binarySchema defaults to [] and no schema
exists until the binary pane is rendered.
schema below is what this script needs. Selecting it fills the table,
so the simulator demonstrates the parser instead of requiring the user
to hand-build a structure to see a decoded value.
Float16 is avoided deliberately: a software decoder plus a hand-built
encoder is a lot of surface for a demo.
The bytes come from frameTemplate rather than from hard-coded literals,
so the frame format is something the user can actually configure. The
default expands to exactly the bytes this script used to hard-code:
A5, temp*10, humidity, SUM8 of those two, 5A — and it therefore still
matches the schema above byte for byte. */
schema: [
{ kind: 'header', value: 'A5' },
// nameAuto false: this is a semantic name the script chose, not one
// derived from the type. updateBinaryRowAutoName() would otherwise
// rewrite it to "uint0" the first time the table renders.
{ kind: 'data', value: '', dataType: 'uint16le', name: 'reading', nameAuto: false },
{ kind: 'checksum', value: 'SUM8', name: 'checksum', nameAuto: false },
{ kind: 'footer', value: '5A' }
],
frameTemplate: SIMULATION_FRAME_TEMPLATE_DEFAULT,
build: (tick) => buildSimulationFrame(state.settings.simulation.frameTemplate, tick)
}
};
const SIMULATION_SCRIPT_IDS = Object.keys(SIMULATION_SCRIPTS);
const SIMULATION_MAX_TICKS = 10000;
/* Simulator pacing.
700ms was arbitrary and unreachable in either direction: a fast protocol
demo wants tens of milliseconds, a slow sensor wants seconds. Burst size
covers the other common shape, where a device answers several frames per
poll and the parser has to cope with the backlog. */
const SIMULATION_INTERVALS = [
{ value: 60, label: '60 毫秒' },
{ value: 200, label: '200 毫秒' },
{ value: 700, label: '700 毫秒' },
{ value: 2000, label: '2 秒' },
{ value: 5000, label: '5 秒' }
];
const SIMULATION_INTERVAL_DEFAULT = 700;
const SIMULATION_BURSTS = [1, 4, 8, 16];
const SIMULATION_BURST_DEFAULT = 1;
/* Payload template placeholders. Text-only by design: the result is always run
through encodeText() before queueRxBytes(), and a template that produced
binary would need an encoding mode. Substitution happens on the plain
string, never on markup. */
const SIMULATION_TEMPLATE_DEFAULT = '';
const SIMULATION_TEMPLATE_MAX = 200;
const SIMULATION_PLACEHOLDERS = ['{n}', '{temp}', '{hum}', '{tick}', '{ts}'];
/* What the template boxes show when the user has not typed in them.
SIMULATION_TEMPLATE_DEFAULT stays '' because that is the persisted
"never touched" value and applySimulationTemplate() reads it as "send the
script's own output". The UI seeds `templateDefault` instead, so neither
box is ever empty: a format you cannot see is a format you cannot edit,
which is exactly why the payload template went unused. Each default
expands to what the script emits anyway, so seeding it changes no bytes.
The frame default is the same idea for the binary script, which has no
text shape to template and is configured through the frame template. */
function simulationTemplateDefault(scriptId) {
return String(SIMULATION_SCRIPTS[scriptId]?.templateDefault || '');
}
function simulationFrameTemplateDefault(scriptId) {
const script = SIMULATION_SCRIPTS[scriptId];
if (!script?.schema) return SIMULATION_FRAME_TEMPLATE_DEFAULT;
return String(script.frameTemplate || SIMULATION_FRAME_TEMPLATE_DEFAULT);
}
/* Keyboard shortcuts.
One table drives both the dispatcher and the shortcut sheet, so the
documented bindings and the working bindings cannot drift apart.
Every binding is chorded (Ctrl and/or Alt). Bare letters are deliberately
NOT used: the existing preset-send handler at app.main.js owns single
keypresses, and a bare letter here would silently shadow a user's preset.
The preset handler runs on document too, so a chord must additionally
consume the event or both handlers fire. */
const SHORTCUT_GROUPS = [
{
title: '应用',
items: [
{ id: 'toggle-sidebar', keys: ['Ctrl', '`'], desc: '折叠 / 展开左侧配置栏', scope: '紧凑模式下切换浮层' },
{ id: 'cycle-corner', keys: ['Ctrl', 'Alt', 'C'], desc: '切换圆角:直角 → 微圆 → 圆润' },
{ id: 'shortcut-sheet', keys: ['?'], desc: '打开本快捷键列表', chorded: false },
{ id: 'close-overlay', keys: ['Esc'], desc: '关闭弹窗 / 菜单', scope: '输入框与终端内不处理' }
]
},
{
title: '串口终端',
items: [
{ id: 'term-clear-line', keys: ['Ctrl', 'U'], desc: '清空当前输入行', scope: '仅本地回显模式' },
{ id: 'term-history-prev', keys: ['↑'], desc: '上一条历史输入', scope: '仅本地回显模式' },
{ id: 'term-history-next', keys: ['↓'], desc: '下一条历史输入', scope: '仅本地回显模式' }
]
},
{
title: '预设发送',
items: [
{ id: 'preset-letter', keys: ['A–Z'], desc: '发送匹配的预设项', scope: '在预设发送开启且焦点不在输入框时' }
]
}
];
/* True when the event target is a text-entry surface, where app-level
chords must not fire. The xterm host counts: xterm owns the keyboard
there and turns chords into bytes on the wire. */
function isTypingTarget(target) {
if (!target) return false;
if (target.isContentEditable) return true;
var tag = target.tagName || '';
if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT') return true;
if (target.closest && target.closest('.xterm')) return true;
return false;
}
const terminalSession = {
buffer: '',
history: [],
historyIndex: -1,
draft: '',
hintShown: false
};
const terminalRuntime = {
term: null,
fitAddon: null,
resizeObserver: null,
pendingApply: false
};
const TERMINAL_HISTORY_MAX = 200;
const TERMINAL_FONT_SIZE_MIN = 8;
const TERMINAL_FONT_SIZE_MAX = 48;
const TERMINAL_FONT_SIZE_DEFAULT = 12;
/* Buffer sizes.
The log budget is a CHARACTER count, not a line count, because line widths
vary by an order of magnitude between a binary dump and a short text reply.
These numbers changed when renderMonitor() stopped assigning innerHTML over
the whole log. The previous table below was measured against a full
rebuild per frame, which made the cap a frame-budget decision:
128K chars -> 8.5k DOM nodes -> 3.1ms
256K -> 17k -> 7.0ms
512K -> 34k -> 13.3ms (a 60Hz frame is 16.7ms)
1M -> 68k -> 26.6ms dropped frames
Appending a row costs one createElement regardless of buffer size, so that
ceiling no longer exists and the limit is memory instead. The default moves
from 256K to 1M.
Note the remaining cost is O(buffer) but not DOM work: getActiveEvents()
plus the visible-window loop still walk every entry each frame. That is why
the default sits well below the 4M cap rather than at it. */
const LIVE_BUFFER_SIZES = [262144, 1048576, 4194304];
const LIVE_BUFFER_DEFAULT = 1048576;
const TERMINAL_SCROLLBACK_SIZES = [5000, 20000, 100000];
const TERMINAL_SCROLLBACK_DEFAULT = 20000;
/* Editable ranges for the combo controls. The *_SIZES lists above are the
menu presets, NOT a validation whitelist any more: a typed value is
clamped into these ranges, because the lists are suggestions and a value
saved by the user must survive a reload. */
const LIVE_BUFFER_MIN = 65536;
const LIVE_BUFFER_MAX = 33554432;
const TERMINAL_SCROLLBACK_MIN = 100;
const TERMINAL_SCROLLBACK_MAX = 1000000;
const SIMULATION_INTERVAL_MIN = 10;
const SIMULATION_INTERVAL_MAX = 60000;
const SIMULATION_BURST_MIN = 1;
const SIMULATION_BURST_MAX = 100;
const TERMINAL_READY_HINT_TEXT = '—— 串口终端已就绪:直接键入即发送(Ctrl+C/Ctrl+D/方向键等原样透传给设备);如设备不回显,请打开“回显” ——';
const refs = {
topbar: document.getElementById('app-topbar'),
serialModeBtn: document.getElementById('serial-mode-btn'),
parserModeBtn: document.getElementById('parser-mode-btn'),
statusPill: document.querySelector('.status-pill'),
logoModeSwitch: document.getElementById('logo-mode-switch'),
serialStatusDot: document.getElementById('serial-status-dot'),
serialStatusText: document.getElementById('serial-status-text'),
themeGroup: document.getElementById('menu-theme-group'),
themeOpts: document.querySelectorAll('#menu-theme-group .menu-theme-opt'),
langGroup: document.getElementById('menu-language-group'),
langOpts: document.querySelectorAll('#menu-language-group .menu-lang-opt'),
cornerGroup: document.getElementById('menu-corner-group'),
cornerOpts: document.querySelectorAll('#menu-corner-group .menu-corner-opt'),
timelineSelect: document.getElementById('timeline-select'),
stopRecordBtn: document.getElementById('stop-record-btn'),
timelinePickerBtn: document.getElementById('timeline-picker-btn'),
timelinePickerPanel: document.getElementById('timeline-picker-panel'),
timelineLabel: document.getElementById('timeline-label'),
timelineStamp: document.getElementById('timeline-stamp'),
timelineRibbonShell: document.getElementById('timeline-ribbon-shell'),
timelineHistoryStrip: document.getElementById('timeline-history-strip'),
timelineLiveIndicator: document.getElementById('timeline-live-indicator'),
timelineFreezeHub: document.getElementById('timeline-freeze-hub'),
timelineFreezeBtn: document.getElementById('timeline-freeze-btn'),
timelineFreezeIcon: document.getElementById('timeline-freeze-icon'),
timelineSlider: document.getElementById('timeline-slider'),
timelineProgress: document.getElementById('timeline-progress'),
systemMenuBtn: document.getElementById('system-menu-btn'),
systemMenu: document.getElementById('system-menu'),
configMenuRow: document.getElementById('config-menu-row'),
configMenuConfirmRow: document.getElementById('config-menu-confirm-row'),
copyUserConfigBtn: document.getElementById('copy-user-config-btn'),
pasteUserConfigBtn: document.getElementById('paste-user-config-btn'),
resetUserConfigBtn: document.getElementById('reset-user-config-btn'),
confirmUserConfigBtn: document.getElementById('confirm-user-config-btn'),
cancelUserConfigBtn: document.getElementById('cancel-user-config-btn'),
downloadLocalLink: document.getElementById('download-local-link'),
versionInfoBtn: document.getElementById('version-info-btn'),
runtimeModeLabel: document.getElementById('runtime-mode-label'),
onlineModeChip: document.getElementById('online-mode-chip'),
versionModalBackdrop: document.getElementById('version-modal-backdrop'),
versionModalClose: document.getElementById('version-modal-close'),
versionModalTitle: document.getElementById('version-modal-title'),
versionCurrentLabel: document.getElementById('version-current-label'),
versionOnlineBox: document.getElementById('version-online-box'),
shortcutModalBackdrop: document.getElementById('shortcut-modal-backdrop'),
shortcutModalClose: document.getElementById('shortcut-modal-close'),
shortcutGroups: document.getElementById('shortcut-groups'),
connectBtn: document.getElementById('connect-btn'),
baudRate: document.getElementById('baud-rate'),
baudRateAnchor: document.getElementById('baud-rate-anchor'),
baudRatePresetBtn: document.getElementById('baud-rate-preset-btn'),
baudRatePresetMenu: document.getElementById('baud-rate-preset-menu'),
dataBits: document.getElementById('data-bits'),
stopBits: document.getElementById('stop-bits'),
parity: document.getElementById('parity'),
releaseOnBlur: document.getElementById('release-on-blur'),
releaseOnBlurChip: document.getElementById('release-on-blur-chip'),
flowControl: document.getElementById('flow-control'),
flowControlChip: document.getElementById('flow-control-chip'),
autoReconnect: document.getElementById('auto-reconnect'),
deviceVid: document.getElementById('device-vid'),
devicePid: document.getElementById('device-pid'),
signalDtr: document.getElementById('signal-dtr'),
signalRts: document.getElementById('signal-rts'),
signalBreak: document.getElementById('signal-break'),
signalDtrChip: document.getElementById('signal-dtr-chip'),
signalRtsChip: document.getElementById('signal-rts-chip'),
signalBreakChip: document.getElementById('signal-break-chip'),
signalCtsReadout: document.getElementById('signal-cts-readout'),
signalDsrReadout: document.getElementById('signal-dsr-readout'),
signalDcdReadout: document.getElementById('signal-dcd-readout'),
signalRiReadout: document.getElementById('signal-ri-readout'),
signalCtsValue: document.getElementById('signal-cts-value'),
signalDsrValue: document.getElementById('signal-dsr-value'),
signalDcdValue: document.getElementById('signal-dcd-value'),
signalRiValue: document.getElementById('signal-ri-value'),
rxDisplayMode: document.getElementById('rx-display-mode'),
textEncoding: document.getElementById('text-encoding'),
appendTimestamp: document.getElementById('append-timestamp'),
sendMode: document.getElementById('send-mode'),
newlineMode: document.getElementById('newline-mode'),
appendNewline: document.getElementById('append-newline'),
layoutToggleBtn: document.getElementById('layout-toggle-btn'),
layoutToggleLabel: document.getElementById('layout-toggle-label'),
leftColumn: document.querySelector('.left-column'),
rightColumn: document.querySelector('.right-column'),
expandedLeftTop: document.querySelector('.expanded-left-top'),
configPanel: document.querySelector('.config-panel'),
parserPanel: document.querySelector('.parser-panel'),
chartsPanel: document.querySelector('.charts-panel'),
monitorPanel: document.querySelector('.monitor-panel'),
mobileConfigBackdrop: document.getElementById('mobile-config-backdrop'),
textParserPane: document.getElementById('text-parser-pane'),
binaryParserPane: document.getElementById('binary-parser-pane'),
parserModeSwitch: document.querySelector('.parser-mode-switch'),
parserPanelToggle: document.getElementById('parser-panel-toggle'),
parserPanelBody: document.getElementById('parser-panel-body'),
simulatorPanelToggle: document.getElementById('simulator-panel-toggle'),
simulatorPanelBody: document.getElementById('simulator-panel-body'),
textRuleOverlay: document.getElementById('text-rule-overlay'),
textParseRule: document.getElementById('text-parse-rule'),
addBinaryRowBtn: document.getElementById('add-binary-row-btn'),
binarySchemaList: document.getElementById('binary-schema-list'),
applyRecommendedRuleBtn: document.getElementById('apply-recommended-rule-btn'),
toggleParserResultsBtn: document.getElementById('toggle-parser-results-btn'),
parserPreview: document.getElementById('parser-preview'),
simulationEnabled: document.getElementById('simulation-enabled'),
simulationScript: document.getElementById('simulation-script'),
simulationStatus: document.getElementById('simulation-status'),
simulationInterval: document.getElementById('simulation-interval'),
simulationBurst: document.getElementById('simulation-burst'),
simulationTemplate: document.getElementById('simulation-template'),
simulationTemplateReset: document.getElementById('simulation-template-reset'),
simulationFrameTemplate: document.getElementById('simulation-frame-template'),
simulationFrameTemplateReset: document.getElementById('simulation-frame-template-reset'),
simulationPreview: document.getElementById('simulation-preview'),
simulationMonitorChip: document.getElementById('simulation-monitor-chip'),
addTimeChartBtn: document.getElementById('add-time-chart-btn'),
addFftChartBtn: document.getElementById('add-fft-chart-btn'),
addBarChartBtn: document.getElementById('add-bar-chart-btn'),
clearChartsBtn: document.getElementById('clear-charts-btn'),
chartList: document.getElementById('chart-list'),
monitorMetaMode: document.getElementById('monitor-meta-mode'),
monitorMetaTx: document.getElementById('monitor-meta-tx'),
monitorMetaRx: document.getElementById('monitor-meta-rx'),
clearLiveLogBtn: document.getElementById('clear-live-log-btn'),
terminalJumpBtn: document.getElementById('terminal-jump-btn'),
terminal: document.getElementById('terminal'),
sendPanel: document.getElementById('send-panel'),
sendResizeHandle: document.getElementById('send-resize-handle'),
sendExtensionShell: document.getElementById('send-extension-shell'),
sendManualPanel: document.getElementById('send-manual-panel'),
sendInput: document.getElementById('send-input'),
sendNowBtn: document.getElementById('send-now-btn'),
monitorViewSwitch: document.getElementById('monitor-view-switch'),
monitorViewTabs: document.querySelectorAll('[data-monitor-view]'),
termInteraction: document.getElementById('term-interaction'),
termOutput: document.getElementById('term-output'),
termNewline: document.getElementById('term-newline'),
termFont: document.getElementById('term-font'),
monoSizeInput: document.getElementById('mono-size-input'),
monoSizeToggle: document.getElementById('mono-size-toggle'),
monoSizeMenu: document.getElementById('mono-size-menu'),
termScrollbackToggle: document.getElementById('term-scrollback-toggle'),
termScrollbackMenu: document.getElementById('term-scrollback-menu'),
liveBufferSizeToggle: document.getElementById('live-buffer-size-toggle'),
liveBufferSizeMenu: document.getElementById('live-buffer-size-menu'),
simulationIntervalToggle: document.getElementById('simulation-interval-toggle'),
simulationIntervalMenu: document.getElementById('simulation-interval-menu'),
simulationBurstToggle: document.getElementById('simulation-burst-toggle'),
simulationBurstMenu: document.getElementById('simulation-burst-menu'),
termSkin: document.getElementById('term-skin'),
termScrollback: document.getElementById('term-scrollback'),
liveBufferSize: document.getElementById('live-buffer-size'),
exportLogBtn: document.getElementById('export-log-btn'),
termLocalEcho: document.getElementById('term-local-echo'),
termKeyBar: document.getElementById('term-key-bar'),
termKeyBarBody: document.getElementById('term-key-bar-body'),
termKeyBarToggle: document.getElementById('term-key-bar-toggle'),
autoSendTile: document.getElementById('auto-send-tile'),
conditionSendTile: document.getElementById('condition-send-tile'),
presetSendTile: document.getElementById('preset-send-tile'),
toggleAutoSendBtn: document.getElementById('toggle-auto-send-btn'),
toggleAutoSendEnableBtn: document.getElementById('toggle-auto-send-enable-btn'),
toggleConditionSendBtn: document.getElementById('toggle-condition-send-btn'),
toggleConditionSendEnableBtn: document.getElementById('toggle-condition-send-enable-btn'),
togglePresetSendBtn: document.getElementById('toggle-preset-send-btn'),
togglePresetSendEnableBtn: document.getElementById('toggle-preset-send-enable-btn'),
autoSendModule: document.getElementById('auto-send-module'),
conditionSendModule: document.getElementById('condition-send-module'),
presetSendModule: document.getElementById('preset-send-module'),
autoSendSwitch: document.getElementById('auto-send-switch'),
conditionSendSwitch: document.getElementById('condition-send-switch'),
presetSendSwitch: document.getElementById('preset-send-switch'),
autoSendInterval: document.getElementById('auto-send-interval'),
addAutoItemBtn: document.getElementById('add-auto-item-btn'),
autoSendQueue: document.getElementById('auto-send-queue'),
addConditionRuleBtn: document.getElementById('add-condition-rule-btn'),
conditionRuleList: document.getElementById('condition-rule-list'),
addPresetItemBtn: document.getElementById('add-preset-item-btn'),
presetSendList: document.getElementById('preset-send-list'),
timelineFileInput: document.getElementById('timeline-file-input'),
toastLayer: document.getElementById('toast-layer')
};
const browserThemeQuery = window.matchMedia('(prefers-color-scheme: dark)');
const initialSavedTheme = (window.__serialWebInitialPrefs && (window.__serialWebInitialPrefs.theme === 'system' || window.__serialWebInitialPrefs.theme === 'dark' || window.__serialWebInitialPrefs.theme === 'light'))
? window.__serialWebInitialPrefs.theme
: 'system';
const initialSavedLocale = ['zh', 'en', 'system'].includes(window.__serialWebInitialLocale)
? window.__serialWebInitialLocale
: 'system';
// Square by default: the reference design this fork adopted has no radius.
// A user upgrading from a build without this key lands on square too.
const CORNER_SETTINGS = ['square', 'soft', 'round'];
const CORNER_LABELS = { square: '直角', soft: '微圆', round: '圆润' };
const initialSavedCorner = CORNER_SETTINGS.includes(window.__serialWebInitialCorner)
? window.__serialWebInitialCorner
: 'square';
const state = {
version: VERSION,
theme: initialSavedTheme,
locale: initialSavedLocale,
cornerRadius: initialSavedCorner,
layoutExpanded: false,
parserMode: 'text',
serial: {
supported: isWebSerialApiAvailable(),
connected: false,
port: null,
portHint: null,
portInfoHint: null,
disconnectedPortRef: null,
reader: null,
writer: null,
disconnecting: false,
reconnectTask: null,
reconnectWakeResolve: null,
reconnectSession: 0,
reconnectCandidate: null,
reconnectPending: false,
reconnectWanted: false,
reconnectPhase: 'idle',
reconnectReason: 'none',
reconnectFailureKind: '',
reconnectFailureDetail: '',
reconnectNoticeShown: false,
reconnectSince: 0,
reconnectResumeElapsedMs: 0,
activeOpenSignature: '',
pendingOpenSignature: '',
reconfigureTimer: 0,
reconfigureTask: null,
reconfigureQueued: false,
signalPollTimer: null,
sendBusy: false,
sendInFlight: Promise.resolve(),
keepReading: false,
connectedAt: 0,
activeFlowControl: 'none',
blurReleaseElapsedMs: 0,
blurReleaseActive: false,
connectionEpoch: 0,
rxActiveEvent: null,
pendingCR: false,
deviceInfo: {
vid: '-',
pid: '-',
description: '浏览器未提供',
online: '离线'
},
signalInputs: {
cts: null,
dsr: null,
dcd: null,
ri: null
}
},
settings: {
baudRate: '115200',
dataBits: 8,
stopBits: 1,
parity: 'none',
releaseSignalsOnBlur: false,
flowControl: 'none',
signalDtr: false,
signalRts: false,
signalBreak: false,
autoReconnect: true,
liveBufferSize: LIVE_BUFFER_DEFAULT,
terminalScrollback: TERMINAL_SCROLLBACK_DEFAULT,
simulation: {
enabled: false,
scriptId: 'text-sensor',
timerId: 0,
tick: 0,
// Cumulative frames emitted, shown next to the switch so a mixed log
// can be accounted for. Session-scoped, not persisted.
totalFrames: 0,
intervalMs: SIMULATION_INTERVAL_DEFAULT,
burst: SIMULATION_BURST_DEFAULT,
// Empty means "use the script's own output". When set, only text
// scripts use it; a binary frame has no meaningful text template.
template: SIMULATION_TEMPLATE_DEFAULT,
// Binary frame layout, in the SIMULATION_FRAME_PLACEHOLDERS notation.
frameTemplate: SIMULATION_FRAME_TEMPLATE_DEFAULT,
/* Whether the user has typed in each box. While false, switching
scripts re-seeds the box with the new script's default; once the user
has written their own template, it survives script switches — a
template they wrote is not something to overwrite because they
looked at another script. Cleared by 恢复默认. */
templateDirty: false,
frameTemplateDirty: false
},
rxDisplayMode: 'text',
textEncoding: 'utf-8',
appendTimestamp: true,
sendMode: 'ascii',
newlineMode: 'rn',
appendNewline: true
},
sendDraft: {
text: '',
hex: ''
},
session: {
startMs: Date.now(),
txBytes: 0,
rxBytes: 0,
rawChunks: [],
liveEvents: []
},
recording: {
active: false,
startedAt: 0,
rawChunks: []
},
timelines: [],
activeTimelineId: 'realtime',
playback: {
playing: false,
positionMs: 0,
lastTick: 0
},
parser: {
textRule: '',
// True while the rule box holds the simulator's suggested rule rather
// than something the user typed. Selecting a simulator script may
// overwrite it; a hand-written rule is never touched.
textRuleIsAuto: false,
binarySchema: []
},
derived: {
availableFields: [],
recommendedRule: '',
numericSeries: {},
chartSeries: {},
chartIntervalMs: 1,
resultCards: []
},
derivedRuntime: {
viewSignature: '',
parserSignature: '',
mode: 'text',
sourceKind: 'realtime',
lastRealtimeRawChunkIndex: 0,
textBaseTimestamp: 0,
binaryBaseTimestamp: 0,
numericSeries: {},
chartFrameCount: 0,
chartFrameFirstTimestamp: 0,
chartFrameLastTimestamp: 0,
chartBatchTimestamp: 0,
chartBatchFrameCount: 0,
chartIntervalAccumMs: 0,
chartIntervalAccumFrames: 0,
chartFrameIntervalMs: 0,
successfulFrames: [],
fieldTypes: new Map(),
latestCards: [],
binaryRemainders: { rx: [], tx: [] }
},
charts: [],
modules: {
autoSendOpen: false,
conditionSendOpen: false,
presetSendOpen: false
},
autoSend: {
enabled: false,
intervalMs: 1000,
queue: [],
timerId: null,
nextIndex: 0
},
conditionSend: {
enabled: false,
rules: []
},
presetSend: {
enabled: false,
items: [],
pendingExpectations: []
},
ui: {
pendingRefresh: false,
clockTimerId: null,
binarySchemaReparseTimerId: null,
dirty: {
status: true,
timelineSelect: true,
stats: true,
timelineBar: true,
derived: true,
monitor: true,
extensionButtons: true,
extensionPanel: true,
extensionHeights: true,
charts: true
},
activeViewCache: {
signature: '',
timeline: null,
events: [],
rawChunks: [],
range: { startTs: 0, endTs: 0, durationMs: 1 }
},
frozenRealtimeView: null,
liveFreezeMode: 'none',
liveFreezeHoverSuppressed: false,
chartRenderSignature: '',
chartPaintPending: false,
chartPaintForce: false,
timelinePickerSignature: '',
timelineExportOpenId: null,
chartPickerOpenId: '',
pendingConfigAction: '',
versionModalMarkOnClose: false,
terminalAtBottom: true,
windowFocused: document.hasFocus(),
textRuleGhostVisible: false,
connectHintUntil: 0,
connectHintText: '',
connectHintKind: 'default',
compactSingle: false,
compactConfigOpen: false,
monitorView: 'terminal',
sidebarCollapsed: false,
parserResultsExpanded: false,
// Open by default now. It was collapsed because the settings took a
// third of the RAIL; they live in the graph view's wide column now, where
// that reasoning does not apply, and arriving at the parse view to find
// it folded away is the same "where is the thing I came for" problem the
// simulator disclosure had. Still collapsible, and still remembered.
parserPanelOpen: true,
// Same reasoning as the parser panel: the simulator is one of the three
// things the parse view is for, and it is the one that cannot be found
// when it starts folded — the whole point of this part is that the user
// can see what is about to be sent.
simulatorPanelOpen: true,
// Terminal key bar starts open; the collapse is a per-user choice about
// panel height, not a default the app should make for them.
termKeyBarOpen: true,
parserResultsCanExpand: false,
chartDrag: null,
sendExtensionHeightOverride: 0,
sendExtensionResize: null,
modePulse: {
auto: { until: 0, tone: 'success', rafId: 0, timerId: 0 },
condition: { until: 0, tone: 'success', rafId: 0, timerId: 0 },
preset: { until: 0, tone: 'success', rafId: 0, timerId: 0 }
},
parserRecommendPromptRule: '',
parserRecommendPromptConnectionEpoch: -1
}
};
let eventIdCounter = 0;
let chartIdCounter = 0;
let queueIdCounter = 0;
let ruleIdCounter = 0;
let schemaRowIdCounter = 0;
let timelineIdCounter = 0;
let playerFrame = null;
let localPrefsTimerId = 0;
let restoringLocalPrefs = false;
let activeReorderDrag = null;
function markUiDirty(next = null) {
const dirty = state.ui.dirty;
if (!next) {
Object.keys(dirty).forEach((key) => { dirty[key] = true; });
return;
}
Object.entries(next).forEach(([key, value]) => {
if (key in dirty && value) dirty[key] = true;
});
}
function uid(prefix) {
if (prefix === 'evt') return `${prefix}-${++eventIdCounter}`;
if (prefix === 'chart') return `${prefix}-${++chartIdCounter}`;
if (prefix === 'queue') return `${prefix}-${++queueIdCounter}`;
if (prefix === 'rule') return `${prefix}-${++ruleIdCounter}`;
if (prefix === 'schema') return `${prefix}-${++schemaRowIdCounter}`;
return `${prefix}-${++timelineIdCounter}`;
}
function resetDerivedRuntime() {
state.derivedRuntime = createDerivedRuntimeSeed(
state.parserMode,
state.activeTimelineId === 'realtime' ? 'realtime' : 'timeline'
);
return state.derivedRuntime;
}
function invalidateDerivedCaches() {
resetDerivedRuntime();
state.ui.activeViewCache.signature = '';
state.ui.chartRenderSignature = '';
if (refs.chartList) delete refs.chartList.dataset.rendered;
state.charts.forEach((chart) => {
chart.fftCache = {};
});
}
function invalidateDerivedDataCaches() {
resetDerivedRuntime();
state.ui.activeViewCache.signature = '';
state.charts.forEach((chart) => {
chart.fftCache = {};
});
}
function clearRealtimeHistoryData() {
state.session.rawChunks = [];
state.session.liveEvents = [];
state.session.txBytes = 0;
state.session.rxBytes = 0;
state.serial.rxActiveEvent = null;
invalidateDerivedCaches();
if (state.activeTimelineId === 'realtime') scheduleRefresh();
requestAnimationFrame(forceTerminalToLatest);
}
/* Current live-buffer budget in characters. Read from state so the toolbar
combo can change it; a saved custom value is clamped into range rather
than rejected, and an unknown value falls back to the default. */
function liveBufferLimit() {
var size = Math.round(Number(state.settings.liveBufferSize));
if (!Number.isFinite(size)) return LIVE_BUFFER_DEFAULT;
return Math.min(LIVE_BUFFER_MAX, Math.max(LIVE_BUFFER_MIN, size));
}
function trimRealtimeRawChunks() {
const chunks = state.session.rawChunks;
if (!chunks.length) return;
const limit = liveBufferLimit();
let totalChars = 0;
let keepFrom = chunks.length;
for (let index = chunks.length - 1; index >= 0; index -= 1) {
totalChars += getRawChunkDisplayLength(chunks[index]);
keepFrom = index;
if (totalChars > limit) {
break;
}
}
if (keepFrom > 0) {
chunks.splice(0, keepFrom);
}
}
function trimLiveEvents() {
const events = state.session.liveEvents;
if (!events.length) return;
const limit = liveBufferLimit();
let totalChars = events.reduce((sum, event) => sum + getEventDisplayText(event).length, 0);
while (events.length > 1 && totalChars > limit) {
totalChars -= getEventDisplayText(events[0]).length;
events.shift();
}
}
function hasDynamicClockUi() {
return Boolean(
state.serial.connected
|| state.serial.blurReleaseActive
|| state.serial.reconnectPhase === 'trying'
|| state.recording.active
|| state.activeTimelineId === 'realtime'
);
}
function ensureUiClockTimer() {
if (state.ui.clockTimerId) return;
state.ui.clockTimerId = window.setInterval(() => {
if (!hasDynamicClockUi()) return;
scheduleRefresh({
status: true,
stats: true,
timelineBar: true
});
}, 250);
}
function escapeHtml(text) {
return String(text)
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
function escapeRegex(text) {
return String(text).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
function clamp(num, min, max) {
return Math.min(max, Math.max(min, num));
}
function formatDuration(ms) {
const total = Math.max(0, Math.floor(ms / 1000));
const h = String(Math.floor(total / 3600)).padStart(2, '0');
const m = String(Math.floor((total % 3600) / 60)).padStart(2, '0');
const s = String(total % 60).padStart(2, '0');
return `${h}:${m}:${s}`;
}
/* Compact "time since" for the status pill: 3s / 12m / 4h. Deliberately
coarser than formatDuration -- the pill answers "is it alive?", not
"exactly when did it connect". */
function formatRelativeAge(ms) {
const seconds = Math.max(0, Math.floor(ms / 1000));
if (seconds < 60) return `${seconds}s`;
const minutes = Math.floor(seconds / 60);
if (minutes < 60) return `${minutes}m`;
const hours = Math.floor(minutes / 60);
if (hours < 24) return `${hours}h`;
return `${Math.floor(hours / 24)}d`;
}
function nowPreciseMs() {
if (typeof performance !== 'undefined' && typeof performance.now === 'function') {
return HIGH_RES_TIME_EPOCH_MS + performance.now();
}
return Date.now();
}
function normalizeTimestampMs(value, fallback = nowPreciseMs()) {
const numeric = Number(value);
return Number.isFinite(numeric) ? numeric : fallback;
}
function formatStamp(ts) {
const date = new Date(normalizeTimestampMs(ts));
const tenths = Math.floor(date.getMilliseconds() / 100);
return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}.${tenths}`;
}
function formatTimelineClock(ms) {
const total = Math.max(0, Math.floor(ms));
const minutes = Math.floor(total / 60000);
const seconds = Math.floor((total % 60000) / 1000);
const millis = total % 1000;
return `${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}.${String(millis).padStart(3, '0')}`;
}