Repository navigation
Expand file tree
/
Copy pathapp.main.js
More file actions
8973 lines (8537 loc) · 364 KB
/
Copy pathapp.main.js
File metadata and controls
8973 lines (8537 loc) · 364 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 main (part 3 of 3)
* Serial lifecycle, monitor/parser UI, charts, prefs persistence, event
* bindings and bootstrap. Closes the IIFE opened in app.core.js.
* ==========================================================================*/
function getRxEventTextLength(event) {
return String(event?.rawText || event?.text || '').length;
}
function getRxEventByteLength(event) {
return Array.isArray(event?.bytes) ? event.bytes.length : 0;
}
function shouldRollRxLengths(textLength, byteLength) {
return (Number(textLength) || 0) >= MAX_RX_OPEN_EVENT_TEXT_CHARS
|| (Number(byteLength) || 0) >= MAX_RX_OPEN_EVENT_BYTES;
}
function shouldRollRxActiveEvent(event) {
return shouldRollRxLengths(getRxEventTextLength(event), getRxEventByteLength(event));
}
function forEachRxDisplayChunk(segmentBytes, handler) {
const bytes = segmentBytes instanceof Uint8Array ? segmentBytes : Uint8Array.from(segmentBytes || []);
if (!bytes.length) return;
const segmentCount = Math.max(1, Math.ceil(bytes.length / MAX_RX_OPEN_EVENT_BYTES));
let segmentIndex = 0;
for (let offset = 0; offset < bytes.length; offset += MAX_RX_OPEN_EVENT_BYTES) {
handler(bytes.slice(offset, offset + MAX_RX_OPEN_EVENT_BYTES), segmentIndex, segmentCount);
segmentIndex += 1;
}
}
function queueRxBytes(bytes, timestamp = nowPreciseMs(), metadata = {}) {
if (!bytes?.length) return;
const rawChunk = recordRawChunk('rx', bytes, timestamp, metadata);
const source = bytes instanceof Uint8Array ? bytes : Uint8Array.from(bytes || []);
const baseTimestamp = normalizeTimestampMs(timestamp);
let frameIndex = 0;
const finalizeLine = (lineTimestamp, syntheticSplit = false) => {
finalizeRxActiveEvent(lineTimestamp, { processRules: true, syntheticSplit });
};
const upsertLine = (segmentBytes, lineTimestamp) => {
if (!segmentBytes?.length) return;
const chunkBytes = segmentBytes instanceof Uint8Array ? segmentBytes : Uint8Array.from(segmentBytes || []);
let event = state.serial.rxActiveEvent;
const nextByteLength = chunkBytes.length;
const nextTextLength = normalizeRxSegmentText(decodeBytes(chunkBytes, state.settings.textEncoding)).length;
if (event && shouldRollRxLengths(getRxEventTextLength(event) + nextTextLength, getRxEventByteLength(event) + nextByteLength)) {
finalizeLine(lineTimestamp, true);
event = null;
}
if (!event) {
event = createRxEventFromSegment(chunkBytes, lineTimestamp, rawChunk.id || '', metadata);
state.serial.rxActiveEvent = event;
state.session.liveEvents.push(event);
} else {
appendRxSegmentToEvent(event, chunkBytes, lineTimestamp, rawChunk.id || '', metadata);
}
if (shouldRollRxActiveEvent(event)) {
finalizeLine(lineTimestamp, true);
}
};
let segmentStart = 0;
let index = 0;
// If the previous chunk ended with a lone CR and this chunk starts with LF,
// they were originally one CRLF split by the read boundary: consume the LF
// to avoid emitting extra blank-line events.
if (state.serial.pendingCR) {
state.serial.pendingCR = false;
if (source[0] === 0x0a) {
index = 1;
segmentStart = 1;
}
}
while (index < source.length) {
const value = source[index];
if (value === 0x0d || value === 0x0a) {
const endIndex = value === 0x0d && index + 1 < source.length && source[index + 1] === 0x0a
? index + 2
: index + 1;
const segmentBytes = source.slice(segmentStart, endIndex);
if (segmentBytes.length) {
forEachRxDisplayChunk(segmentBytes, (displayChunk) => {
upsertLine(displayChunk, baseTimestamp + frameIndex);
frameIndex += 1;
});
}
finalizeLine(baseTimestamp + frameIndex, false);
frameIndex += 1;
// Note: this chunk ended with a lone CR; the LF of a CRLF may arrive in the next read
state.serial.pendingCR = value === 0x0d && endIndex === index + 1 && endIndex === source.length;
index = endIndex;
segmentStart = endIndex;
continue;
}
index += 1;
}
if (segmentStart < source.length) {
const tailBytes = source.slice(segmentStart);
forEachRxDisplayChunk(tailBytes, (displayChunk) => {
upsertLine(displayChunk, baseTimestamp + frameIndex);
frameIndex += 1;
});
}
trimLiveEvents();
state.session.rxBytes += source.length;
scheduleRefresh({
stats: true,
timelineBar: true,
derived: true,
monitor: true,
charts: true,
extensionButtons: true,
extensionPanel: true
});
}
/* ---- Protocol simulation -----------------------------------------------
The generated bytes go through queueRxBytes() with the same
{ source: 'serial-read' } marker the real reader uses, so everything
downstream - line splitting, the parser, chart painting, timeline
recording - runs its normal path. Nothing is special-cased for simulated
data beyond the metadata flag, which only appears in log entries.
A real connection wins: if a port opens while simulation is running, the
timer pauses so two sources cannot interleave bytes into the same stream. */
function isSimulationAvailable() {
return SIMULATION_SCRIPT_IDS.includes(state.settings.simulation.scriptId);
}
function simulationScript() {
return SIMULATION_SCRIPTS[state.settings.simulation.scriptId] || SIMULATION_SCRIPTS['text-sensor'];
}
/* Writes the parser configuration a script needs.
The simulator exists to demonstrate the parser, so requiring the user to
hand-build a structure table before seeing a decoded value defeats it.
Each script declares textRule and/or schema, and selecting it applies them.
Only applied when the target is empty or already auto-generated, so a
hand-written rule the user typed is never overwritten. */
function applySimulationScriptConfig(scriptId) {
const script = SIMULATION_SCRIPTS[scriptId];
if (!script) return;
if (script.textRule && refs.textParseRule) {
const current = String(refs.textParseRule.value || '').trim();
if (!current || state.parser.textRuleIsAuto) {
refs.textParseRule.value = script.textRule;
state.parser.textRule = script.textRule;
state.parser.textRuleIsAuto = true;
invalidateDerivedCaches();
renderTextRuleOverlay();
}
}
if (Array.isArray(script.schema) && script.schema.length) {
const current = state.parser.binarySchema || [];
/* Replaceable when the table is empty, or when every row is still either
the bare seed ensureBinarySchemaRow() creates or a previous script's.
A row blocks replacement when the user has given it a name of their own
that is not auto-derived — keyed on name/nameAuto rather than on a flag,
because the seeded rows predate any flag. An earlier version tested
row.__autoFromScript for this, which the seeded rows do not carry, so
selecting a binary script silently did nothing at all. */
const allReplaceable = current.length === 0
|| current.every((row) => row.__autoFromScript
|| row.name === ''
|| row.nameAuto === true
|| row.name === undefined);
// A previous script's rows are marked, so re-selecting a script replaces
// its own rows even though they carry a fixed name.
// A previous script's rows are marked, so re-selecting a script replaces
// its own rows even though they carry a fixed name.
if (allReplaceable) {
state.parser.binarySchema = script.schema.map((row) => {
const created = createBinarySchemaRow(row.kind);
created.value = row.value ?? created.value;
if (row.dataType) created.dataType = row.dataType;
if (row.name !== undefined) {
created.name = row.name;
created.nameAuto = Boolean(row.nameAuto);
}
created.__autoFromScript = true;
return created;
});
// The binary frame can only be decoded in binary mode. Selecting a
// binary script and staying in text mode is what made the previous
// version look like it produced data but decoded nothing.
state.parserMode = 'binary';
updateParserModeUI();
invalidateDerivedCaches();
scheduleBinarySchemaReparse(true);
}
} else if (state.parserMode === 'binary') {
// A text script has no schema, so the binary table would not apply.
state.parserMode = 'text';
updateParserModeUI();
invalidateDerivedCaches();
scheduleRefresh();
}
}
/* Expands the payload template.
Plain string substitution on the text a script produces, never on markup:
the result goes straight to encodeText() and then queueRxBytes(), so there
is no HTML path. Placeholders are {n} (tick), {temp}, {hum}, {tick} and
{ts} (frame counter).
Applies to text scripts only. A binary frame has no textual shape to
template, so the binary script ignores it rather than pretending.
A trailing newline is appended when the template does not end in one.
Frames are split on CR/LF, so an unterminated template would concatenate
every tick into one ever-growing display event — the same trap the
built-in text script already had to be fixed for. */
function applySimulationTemplate(text, tick) {
const template = String(state.settings.simulation.template || '').trim();
if (!template) return text;
const temp = 21 + Math.sin(tick / 9) * 3.5;
const hum = 48 + Math.cos(tick / 7) * 6;
const expanded = template
.split('{n}').join(String(tick))
.split('{temp}').join(temp.toFixed(1))
.split('{hum}').join(String(Math.round(hum)))
.split('{tick}').join(String(tick))
.split('{ts}').join(String(state.settings.simulation.totalFrames));
return /[\r\n]$/.test(expanded) ? expanded : `${expanded}\n`;
}
function emitSimulationFrame() {
const sim = state.settings.simulation;
if (!sim.enabled || !isSimulationAvailable()) return;
// Yield to a real device if one is attached.
if (state.serial.connected) return;
const script = simulationScript();
// A burst emits several frames per tick, which is how a device that answers
// more than once per poll looks. Each goes through queueRxBytes() separately
// so line splitting and parsing behave exactly as they would on the wire.
const burstRaw = Math.round(Number(sim.burst));
const burst = Number.isFinite(burstRaw)
? Math.min(SIMULATION_BURST_MAX, Math.max(SIMULATION_BURST_MIN, burstRaw))
: SIMULATION_BURST_DEFAULT;
for (let index = 0; index < burst; index += 1) {
// Captured before the increment: the template's {n}/{tick} must agree
// with the counter the frame itself was built from. It used to be read
// after `sim.tick += 1`, so a JSON payload reported an uptime one ahead
// of the frame that carried it.
const tick = sim.tick;
const frame = script.build(sim.tick);
sim.tick += 1;
if (sim.tick > SIMULATION_MAX_TICKS) sim.tick = 0;
/* The text scripts encode inside build(), so their return value is a
Uint8Array just like the binary script's. Branching on the instance
would therefore send every text script down the binary path and the
template could never apply. The binary script is identified by having a
schema instead — that is what actually distinguishes the two. */
const isBinaryScript = Boolean(script.schema);
const payload = isBinaryScript
? frame
: encodeText(
applySimulationTemplate(decodeBytes(frame, state.settings.textEncoding), tick),
state.settings.textEncoding
);
sim.totalFrames += 1;
queueRxBytes(payload, nowPreciseMs(), { source: 'serial-read', simulated: true });
}
syncSimulationUi();
}
/* Previews the next frame.
Both template notations are small, and a notation you cannot see the result
of is a notation you cannot debug: a mistyped placeholder or a stray hex
digit produced silence before, with nothing on screen to say which.
Rendering the frame the simulator is about to send makes the template
editable instead of guesswork.
Binary previews as hex, text previews as the line itself — the text path
runs the real expansion (script bytes → payload template), so what is shown
is what will actually be queued, not a second implementation of it. */
function simulationNextFrame() {
const sim = state.settings.simulation;
const script = SIMULATION_SCRIPTS[sim.scriptId];
if (script?.schema) {
const template = String(sim.frameTemplate || '').trim() || SIMULATION_FRAME_TEMPLATE_DEFAULT;
const bytes = buildSimulationFrame(template, sim.tick);
return { text: bytesToCompactHex(bytes), bytes: bytes.length };
}
const built = script ? script.build(sim.tick) : new Uint8Array(0);
const expanded = applySimulationTemplate(decodeBytes(built, state.settings.textEncoding), sim.tick);
const payload = expanded.replace(/\r?\n$/, '').replace(/\r/g, '\\r');
return { text: payload, bytes: encodeText(expanded, state.settings.textEncoding).length };
}
/* Seeds the template boxes with the chosen script's defaults.
Only while the user has not typed in a box: a template they wrote survives
a script switch. Both boxes are seeded, not just the visible one, so
switching to the binary script shows a filled frame template rather than
an empty box that would fall back to the built-in frame. */
function seedSimulationTemplates() {
const sim = state.settings.simulation;
if (!sim.templateDirty) sim.template = simulationTemplateDefault(sim.scriptId);
if (!sim.frameTemplateDirty) sim.frameTemplate = simulationFrameTemplateDefault(sim.scriptId);
}
function simulationIntervalMs() {
const value = Number(state.settings.simulation.intervalMs);
const clamped = Math.min(SIMULATION_INTERVAL_MAX, Math.max(SIMULATION_INTERVAL_MIN, Math.round(value)));
return Number.isFinite(value) ? clamped : SIMULATION_INTERVAL_DEFAULT;
}
function startSimulation() {
const sim = state.settings.simulation;
if (sim.timerId) return;
emitSimulationFrame();
sim.timerId = window.setInterval(emitSimulationFrame, simulationIntervalMs());
}
function stopSimulation() {
const sim = state.settings.simulation;
if (!sim.timerId) return;
clearInterval(sim.timerId);
sim.timerId = 0;
}
function setSimulationEnabled(enabled) {
const sim = state.settings.simulation;
sim.enabled = Boolean(enabled);
if (sim.enabled) {
sim.tick = 0;
startSimulation();
} else {
stopSimulation();
}
}
/* Frame counter and yield state.
A toast fired at switch-on is gone by the time the log fills, and the
question this answers — "are these rows from the device or from the
simulator" — recurs continuously while watching the log. So the state is
rendered next to the switch instead. */
function syncSimulationUi() {
const sim = state.settings.simulation;
if (refs.simulationEnabled) refs.simulationEnabled.checked = sim.enabled;
if (refs.simulationScript) refs.simulationScript.value = sim.scriptId;
if (refs.simulationInterval) refs.simulationInterval.value = String(simulationIntervalMs());
if (refs.simulationBurst) {
const burstRaw = Math.round(Number(sim.burst));
const burst = Number.isFinite(burstRaw)
? Math.min(SIMULATION_BURST_MAX, Math.max(SIMULATION_BURST_MIN, burstRaw))
: SIMULATION_BURST_DEFAULT;
refs.simulationBurst.value = String(burst);
}
// Only write the template field when it differs, so typing is not
// interrupted by the frame counter refresh that runs on every emit.
if (refs.simulationTemplate && refs.simulationTemplate.value !== String(sim.template || '')) {
refs.simulationTemplate.value = String(sim.template || '');
}
// A binary frame has no textual shape and a text line has no hex layout, so
// each script has exactly one template that means anything. Show that one
// and hide the other rather than disabling it: a disabled field is a dead
// end that tells the user nothing about why, and it was the reason the
// payload template read as unusable.
const isBinary = Boolean(SIMULATION_SCRIPTS[sim.scriptId]?.schema);
document.querySelectorAll('[data-sim-template]').forEach((field) => {
const wantsText = field.dataset.simTemplate === 'text';
field.classList.toggle('hidden', wantsText ? isBinary : !isBinary);
});
if (refs.simulationFrameTemplate && refs.simulationFrameTemplate.value !== String(sim.frameTemplate || '')) {
refs.simulationFrameTemplate.value = String(sim.frameTemplate || '');
}
if (refs.simulationPreview) {
const preview = simulationNextFrame();
refs.simulationPreview.textContent = `${t('下一帧预览')}: ${preview.text} (${preview.bytes}B)`;
}
const yielded = sim.enabled && state.serial.connected;
const parts = [];
if (sim.totalFrames > 0) {
parts.push(t('已产生 {{count}} 帧', { count: sim.totalFrames }));
}
if (yielded) {
parts.push(t('串口已连接,模拟让位'));
}
const statusText = parts.join(' · ');
if (refs.simulationStatus) {
refs.simulationStatus.textContent = statusText;
refs.simulationStatus.classList.toggle('is-yielded', yielded);
}
applySimulationMonitorChip();
}
/* Read-only mirror of the simulator state for the monitor view.
The switch lives in the parse view, but the frames it produces land in the
monitor's log — so the question "is this stream a device or the simulator"
has to be answerable where the stream is watched. The chip answers it and
nothing more: it is not a control, because two switches for one setting is
the duplication it exists to prevent. Both monitor sub-views show it — it
sits in the toolbar row above the log, outside the terminal canvas, so it
reads as application state rather than as something the connected device
printed. Hidden entirely when the simulator is off, so it costs no
attention in the common case. */
function applySimulationMonitorChip() {
const chip = refs.simulationMonitorChip;
if (!chip) return;
// The parse view has the real switch; a chip beside it would be noise.
if (state.layoutExpanded) {
chip.hidden = true;
chip.textContent = '';
chip.classList.remove('is-active', 'is-yielded');
return;
}
const sim = state.settings.simulation;
const active = Boolean(sim.enabled);
chip.hidden = !active;
chip.classList.toggle('is-active', active);
const yielded = active && state.serial.connected;
chip.classList.toggle('is-yielded', yielded);
if (!active) {
chip.textContent = '';
return;
}
// No frame count: the RX counter already says how much arrived, and the
// chip answers one question — is this stream real or generated.
chip.textContent = yielded ? t('模拟已让位') : t('模拟中');
}
function syncBufferUi() {
if (refs.termScrollback) refs.termScrollback.value = String(getTerminalScrollback());
if (refs.liveBufferSize) refs.liveBufferSize.value = String(liveBufferLimit());
}
function populateSimulationScripts() {
const host = refs.simulationScript;
if (host && !host.options.length) {
SIMULATION_SCRIPT_IDS.forEach((id) => {
const option = document.createElement('option');
option.value = id;
option.textContent = t(SIMULATION_SCRIPTS[id].label);
host.appendChild(option);
});
}
// Combo presets, not option lists: the interval/burst inputs are typed
// numbers, and these menus only offer the common shapes.
const intervalMenu = refs.simulationIntervalMenu;
if (intervalMenu && !intervalMenu.children.length) {
SIMULATION_INTERVALS.forEach((item) => {
const button = document.createElement('button');
button.type = 'button';
button.dataset.comboValue = String(item.value);
button.textContent = t(item.label);
intervalMenu.appendChild(button);
});
}
const burstMenu = refs.simulationBurstMenu;
if (burstMenu && !burstMenu.children.length) {
SIMULATION_BURSTS.forEach((count) => {
const button = document.createElement('button');
button.type = 'button';
button.dataset.comboValue = String(count);
button.textContent = String(count);
burstMenu.appendChild(button);
});
}
}
function buildEvent(direction, bytes, displayText, extra = {}) {
const timestamp = normalizeTimestampMs(extra.timestamp);
const text = displayText ?? decodeBytes(bytes, state.settings.textEncoding);
return {
id: uid('evt'),
timestamp,
direction,
type: direction,
bytes: Array.from(bytes || []),
text,
rawText: text,
hex: bytesToHex(bytes),
metadata: extra.metadata || {}
};
}
function getEventDisplayText(event) {
return String(event?.rawText || event?.text || '');
}
function createRxEventFromSegment(segmentBytes, timestamp, rawChunkId = '', metadataExtra = {}) {
const bytes = segmentBytes instanceof Uint8Array ? segmentBytes : Uint8Array.from(segmentBytes);
const text = normalizeRxSegmentText(decodeBytes(bytes, state.settings.textEncoding));
return buildEvent('rx', bytes, text, {
timestamp,
metadata: {
...(metadataExtra || {}),
rxOpen: true,
rawChunkIds: rawChunkId ? [rawChunkId] : []
}
});
}
function appendRxSegmentToEvent(event, segmentBytes, timestamp, rawChunkId = '', metadataExtra = {}) {
const bytes = segmentBytes instanceof Uint8Array ? segmentBytes : Uint8Array.from(segmentBytes);
const segmentText = normalizeRxSegmentText(decodeBytes(bytes, state.settings.textEncoding));
const segmentHex = bytesToHex(bytes);
event.bytes.push(...Array.from(bytes));
const nextText = `${getEventDisplayText(event)}${segmentText}`;
event.text = nextText;
event.rawText = nextText;
event.hex = event.hex ? `${event.hex} ${segmentHex}` : segmentHex;
event.timestamp = normalizeTimestampMs(timestamp);
event.metadata = {
...(event.metadata || {}),
...(metadataExtra || {}),
rxOpen: true,
rawChunkIds: [
...new Set([...(event.metadata?.rawChunkIds || []), ...(rawChunkId ? [rawChunkId] : [])])
]
};
return event;
}
function finalizeRxActiveEvent(timestamp = nowPreciseMs(), options = {}) {
const processRules = options.processRules !== false;
const syntheticSplit = options.syntheticSplit === true;
const event = state.serial.rxActiveEvent;
if (!event) return;
event.timestamp = normalizeTimestampMs(timestamp);
event.metadata = {
...(event.metadata || {}),
rxOpen: false,
lineClosedAt: normalizeTimestampMs(timestamp),
syntheticSplit
};
state.serial.rxActiveEvent = null;
if (processRules) {
processPresetExpectations(event);
processConditionRules(event);
}
}
function rebuildEventsFromRawChunks(rawChunks = []) {
const events = [];
let activeRxEvent = null;
let pendingCR = false;
const closeActiveRxEvent = (timestamp, syntheticSplit = false) => {
if (!activeRxEvent) return;
activeRxEvent.timestamp = normalizeTimestampMs(timestamp, activeRxEvent.timestamp);
activeRxEvent.metadata = {
...(activeRxEvent.metadata || {}),
rxOpen: false,
lineClosedAt: normalizeTimestampMs(timestamp, activeRxEvent.timestamp),
syntheticSplit
};
activeRxEvent = null;
};
const appendRxSegment = (segmentBytes, timestamp, rawChunkId = '', metadataExtra = {}) => {
if (!segmentBytes?.length) return;
const bytes = segmentBytes instanceof Uint8Array ? segmentBytes : Uint8Array.from(segmentBytes);
const nextByteLength = bytes.length;
const nextTextLength = normalizeRxSegmentText(decodeBytes(bytes, state.settings.textEncoding)).length;
if (activeRxEvent && shouldRollRxLengths(getRxEventTextLength(activeRxEvent) + nextTextLength, getRxEventByteLength(activeRxEvent) + nextByteLength)) {
closeActiveRxEvent(timestamp, true);
}
if (!activeRxEvent) {
activeRxEvent = createRxEventFromSegment(bytes, timestamp, rawChunkId, metadataExtra);
events.push(activeRxEvent);
} else {
appendRxSegmentToEvent(activeRxEvent, bytes, timestamp, rawChunkId, metadataExtra);
}
if (activeRxEvent && shouldRollRxActiveEvent(activeRxEvent)) {
closeActiveRxEvent(timestamp, true);
}
};
(rawChunks || []).forEach((chunk) => {
if (chunk.direction !== 'rx' && chunk.direction !== 'tx') return;
const bytes = Uint8Array.from(chunk.bytes || []);
const timestamp = normalizeTimestampMs(chunk.timestamp);
if (chunk.direction === 'tx') {
if (activeRxEvent) closeActiveRxEvent(timestamp, true);
events.push(buildEvent('tx', bytes, decodeBytes(bytes, state.settings.textEncoding), {
timestamp,
metadata: {
...(chunk.metadata || {}),
rawChunkIds: chunk.id ? [chunk.id] : []
}
}));
return;
}
let segmentStart = 0;
let index = 0;
// Keep consistent with the live path: a CRLF split across chunks consumes the trailing LF to avoid extra blank lines
if (pendingCR) {
pendingCR = false;
if (bytes[0] === 0x0a) {
index = 1;
segmentStart = 1;
}
}
while (index < bytes.length) {
const value = bytes[index];
if (value === 0x0d || value === 0x0a) {
const endIndex = value === 0x0d && index + 1 < bytes.length && bytes[index + 1] === 0x0a
? index + 2
: index + 1;
const segmentBytes = bytes.slice(segmentStart, endIndex);
if (segmentBytes.length) {
forEachRxDisplayChunk(segmentBytes, (displayChunk) => {
appendRxSegment(displayChunk, timestamp, chunk.id || '', chunk.metadata || {});
});
}
closeActiveRxEvent(timestamp, false);
pendingCR = value === 0x0d && endIndex === index + 1 && endIndex === bytes.length;
index = endIndex;
segmentStart = endIndex;
continue;
}
index += 1;
}
if (segmentStart < bytes.length) {
const tailBytes = bytes.slice(segmentStart);
forEachRxDisplayChunk(tailBytes, (displayChunk) => {
appendRxSegment(displayChunk, timestamp, chunk.id || '', chunk.metadata || {});
});
}
});
if (activeRxEvent) {
activeRxEvent.metadata = {
...(activeRxEvent.metadata || {}),
rxOpen: true
};
}
return events;
}
function expandTextSamplesFromRawChunks(rawChunks = []) {
return rebuildEventsFromRawChunks(rawChunks)
.filter((event) => event.direction === 'rx' || event.direction === 'tx')
.map((event) => createTextSampleFromEvent(event));
}
function expandTextSamplesFromEvents(events = []) {
return (events || [])
.filter((event) => event.direction === 'rx' || event.direction === 'tx')
.map((event) => createTextSampleFromEvent(event));
}
function createTextSampleFromEvent(event) {
const bytes = Array.isArray(event?.bytes) ? event.bytes : [];
const text = getEventDisplayText(event);
return {
timestamp: normalizeTimestampMs(event?.timestamp),
direction: event?.direction,
byteLength: bytes.length,
byteSum: bytes.reduce((acc, value) => acc + value, 0),
firstByte: bytes[0] ?? 0,
text,
rawText: text
};
}
function processConditionRules(event) {
if (!state.conditionSend.enabled || !state.serial.connected || state.serial.disconnecting) return;
state.conditionSend.rules.forEach((rule) => {
if (!rule.enabled || !hasByteBackedValue(rule.pattern, rule.patternRawHex) || !hasByteBackedValue(rule.response, rule.responseRawHex)) return;
const matched = matchesConditionRule(event, rule);
if (matched) {
const conditionDescription = getConditionRuleDescription(rule);
event.metadata = {
...(event.metadata || {}),
conditionMatched: true,
conditionDescription
};
mergeRawChunkMetadata(event.metadata.rawChunkIds, {
conditionMatched: true,
conditionDescription
});
const { payload, sendOptions } = getSendRecordPayloadArgs(rule, 'response', 'responseRawHex');
sendPayload(payload, 'condition', sendOptions, {
conditionSend: true,
conditionDescription
}).then((success) => {
if (success) pulseMode('condition');
});
}
});
}
function captureEvent(direction, bytes, displayText, extra = {}) {
const event = buildEvent(direction, bytes, displayText, extra);
processPresetExpectations(event);
state.session.liveEvents.push(event);
trimLiveEvents();
if (direction === 'tx') state.session.txBytes += event.bytes.length || 0;
if (direction === 'rx') {
state.session.rxBytes += event.bytes.length || 0;
processConditionRules(event);
}
scheduleRefresh({
stats: true,
timelineBar: true,
derived: true,
monitor: true,
charts: true,
extensionButtons: true,
extensionPanel: true
});
return event;
}
function updateSerialStatus() {
refs.serialStatusDot.className = `status-dot ${state.serial.connected ? 'connected' : (state.serial.supported ? 'warn' : 'offline')}`;
// The pill answers "is it alive?" faster than a clock alone: state plus age.
// Driven by the existing 250ms status clock, so no new timer is involved.
refs.serialStatusText.textContent = state.serial.connected
? t('串口已连接 · {{age}}', { age: formatRelativeAge(Date.now() - state.serial.connectedAt) })
: (state.serial.supported ? t('就绪,等待连接') : t('不支持 Web Serial API'));
refs.deviceVid.textContent = state.serial.deviceInfo.vid;
refs.devicePid.textContent = state.serial.deviceInfo.pid;
const hintActive = Date.now() < state.ui.connectHintUntil && !!state.ui.connectHintText;
const releaseActive = Boolean(state.serial.blurReleaseActive);
const reconnecting = !state.serial.connected && state.serial.reconnectPhase === 'trying';
const applyingOptions = reconnecting && isSerialOptionsApplyReason(state.serial.reconnectReason);
refs.connectBtn.classList.toggle('is-disconnect', state.serial.connected && !releaseActive && !hintActive);
refs.connectBtn.classList.toggle('is-release-hold', releaseActive || reconnecting);
refs.connectBtn.classList.toggle('is-hint-error', !state.serial.supported || (hintActive && state.ui.connectHintKind === 'error'));
if (!state.serial.supported) {
refs.connectBtn.textContent = t('不支持 Web Serial API');
refs.connectBtn.title = t('推荐使用 Chrome 或 Edge,并访问在线最新版本:{{url}}', { url: ONLINE_VERSION_URL });
updateSignalControlsUI();
return;
}
refs.connectBtn.title = state.serial.connected ? t('断开串口连接') : t('连接串口设备');
if (hintActive) {
refs.connectBtn.textContent = state.ui.connectHintText;
updateSignalControlsUI();
return;
}
if (reconnecting) {
refs.connectBtn.textContent = applyingOptions
? t('正在应用参数 | 请稍候')
: (
state.serial.reconnectFailureKind && state.serial.reconnectFailureKind !== 'missing'
? t('重连失败 | 串口可能被占用')
: t('正在重连 | 点击取消重连')
);
} else if (releaseActive) {
refs.connectBtn.textContent = t('失焦断连 | {{elapsed}}', { elapsed: formatDuration(state.serial.blurReleaseElapsedMs) });
} else if (state.serial.connected) {
const elapsed = formatDuration(Date.now() - state.serial.connectedAt);
refs.connectBtn.textContent = t('断开连接 | {{elapsed}}', { elapsed });
} else {
refs.connectBtn.textContent = t('连接设备 | 当前未连接');
}
updateSignalControlsUI();
// The simulation yield notice depends on the connection state, and this
// function runs on every status repaint - which is the one place guaranteed
// to fire on both connect and disconnect.
syncSimulationUi();
}
/* Three states, not two.
null means getSignals() has not reported this pin yet — the port is closed,
or the read failed. That must not render as "off", because a driver that
does not report modem status returns all-false rather than throwing, and
that is indistinguishable from a genuine "all low". Making the unknown
state explicit is the difference between "the link is broken" and "I do
not know yet". */
function signalValueLabel(value) {
if (value === true) return t('开');
if (value === false) return t('关');
// An em dash rather than the word: four of these share a 274px row and
// "Unknown" wraps and squashes the box. The full word stays in the title.
return '\u2014';
}
function signalValueTitle(value) {
if (value === true) return t('高电平');
if (value === false) return t('低电平');
return t('未知:串口未连接或驱动不报告该信号');
}
function isAutoHardwareFlowControlActive() {
if (state.serial.connected) {
return state.serial.activeFlowControl === 'hardware';
}
return state.settings.flowControl === 'hardware';
}
function isSignalReleaseActive() {
return state.settings.releaseSignalsOnBlur
&& (!state.ui.windowFocused || document.visibilityState === 'hidden');
}
function getEffectiveSignalOutputs() {
const releaseActive = isSignalReleaseActive();
const autoHardwareFlow = isAutoHardwareFlowControlActive();
return {
releaseActive,
autoHardwareFlow,
dtr: releaseActive ? false : Boolean(state.settings.signalDtr),
rts: releaseActive ? false : (autoHardwareFlow ? false : Boolean(state.settings.signalRts)),
break: releaseActive ? false : Boolean(state.settings.signalBreak)
};
}
function updateSignalControlsUI() {
const effective = getEffectiveSignalOutputs();
const autoHardwareFlowConfigured = state.settings.flowControl === 'hardware';
const rtsManaged = effective.autoHardwareFlow;
refs.releaseOnBlur.checked = state.settings.releaseSignalsOnBlur;
refs.releaseOnBlur.disabled = !state.serial.supported;
refs.releaseOnBlurChip.classList.toggle('is-disabled', !state.serial.supported);
refs.flowControl.checked = autoHardwareFlowConfigured;
refs.flowControl.disabled = !state.serial.supported;
refs.flowControlChip.classList.toggle('is-disabled', !state.serial.supported);
const outputDefs = [
{ input: refs.signalDtr, chip: refs.signalDtrChip, value: effective.dtr, disabled: !state.serial.supported },
{ input: refs.signalRts, chip: refs.signalRtsChip, value: effective.rts, disabled: !state.serial.supported || rtsManaged },
{ input: refs.signalBreak, chip: refs.signalBreakChip, value: effective.break, disabled: !state.serial.supported }
];
outputDefs.forEach(({ input, chip, value, disabled }) => {
input.checked = value;
input.disabled = disabled;
chip.classList.toggle('is-disabled', disabled);
});
refs.signalRtsChip.title = rtsManaged
? t('RTS/CTS 流控生效时,RTS 由系统自动接管。')
: t('手动控制 RTS');
const inputDefs = [
{ el: refs.signalCtsReadout, valueEl: refs.signalCtsValue, value: state.serial.signalInputs.cts },
{ el: refs.signalDsrReadout, valueEl: refs.signalDsrValue, value: state.serial.signalInputs.dsr },
{ el: refs.signalDcdReadout, valueEl: refs.signalDcdValue, value: state.serial.signalInputs.dcd },
{ el: refs.signalRiReadout, valueEl: refs.signalRiValue, value: state.serial.signalInputs.ri }
];
inputDefs.forEach(({ el, valueEl, value }) => {
valueEl.textContent = signalValueLabel(value);
el.title = signalValueTitle(value);
el.classList.toggle('is-on', value === true);
el.classList.toggle('is-unknown', value === null || value === undefined);
});
}
async function applySerialSignalOutputs() {
if (!state.serial.connected || !state.serial.port || typeof state.serial.port.setSignals !== 'function') return;
try {
const effective = getEffectiveSignalOutputs();
const signalPayload = {
dataTerminalReady: effective.dtr,
break: effective.break
};
if (effective.releaseActive || !effective.autoHardwareFlow) {
signalPayload.requestToSend = effective.rts;
}
await state.serial.port.setSignals(signalPayload);
updateSignalControlsUI();
} catch (error) {
console.warn('setSignals failed', error);
}
}
async function refreshSerialSignalInputs() {
if (!state.serial.connected || !state.serial.port || typeof state.serial.port.getSignals !== 'function') {
state.serial.signalInputs.cts = null;
state.serial.signalInputs.dsr = null;
state.serial.signalInputs.dcd = null;
state.serial.signalInputs.ri = null;
updateSignalControlsUI();
return;
}
try {
const signals = await state.serial.port.getSignals();
state.serial.signalInputs.cts = typeof signals.clearToSend === 'boolean' ? signals.clearToSend : null;
state.serial.signalInputs.dsr = typeof signals.dataSetReady === 'boolean' ? signals.dataSetReady : null;
state.serial.signalInputs.dcd = typeof signals.dataCarrierDetect === 'boolean' ? signals.dataCarrierDetect : null;
state.serial.signalInputs.ri = typeof signals.ringIndicator === 'boolean' ? signals.ringIndicator : null;
updateSignalControlsUI();
} catch (error) {
console.warn('getSignals failed', error);
}
}
function startSerialSignalPolling() {
stopSerialSignalPolling();
if (!state.serial.connected) return;
refreshSerialSignalInputs();
state.serial.signalPollTimer = window.setInterval(() => {
refreshSerialSignalInputs();
}, 800);
}
function stopSerialSignalPolling() {
if (state.serial.signalPollTimer) {
clearInterval(state.serial.signalPollTimer);
state.serial.signalPollTimer = null;
}
}
function normalizeSerialBaudRate(value, fallback = state.settings.baudRate) {
const fallbackValue = Math.max(1, Math.floor(Number(fallback) || 115200));
const parsed = Number(String(value ?? '').trim());
if (!Number.isFinite(parsed) || parsed < 1) return fallbackValue;
return Math.max(1, Math.floor(parsed));
}
function normalizeSerialDataBits(value) {
const parsed = Number(value);
return [7, 8].includes(parsed) ? parsed : 8;
}
function normalizeSerialStopBits(value) {
const parsed = Number(value);
return [1, 2].includes(parsed) ? parsed : 1;
}
function normalizeSerialParity(value) {
return ['none', 'even', 'odd'].includes(value) ? value : 'none';
}
function getSerialOpenOptions({ commit = false } = {}) {
const options = {
baudRate: normalizeSerialBaudRate(refs.baudRate?.value, state.settings.baudRate),
dataBits: normalizeSerialDataBits(refs.dataBits?.value || state.settings.dataBits),
stopBits: normalizeSerialStopBits(refs.stopBits?.value || state.settings.stopBits),
parity: normalizeSerialParity(refs.parity?.value || state.settings.parity),
flowControl: refs.flowControl?.checked ? 'hardware' : 'none',
bufferSize: SERIAL_BUFFER_SIZE
};
if (commit) {
refs.baudRate.value = String(options.baudRate);
refs.dataBits.value = String(options.dataBits);
refs.stopBits.value = String(options.stopBits);
refs.parity.value = options.parity;
refs.flowControl.checked = options.flowControl === 'hardware';
syncCustomSelects(refs.configPanel || document);
}
return options;
}
function getSerialOpenOptionsSignature(options = getSerialOpenOptions()) {
return [
options.baudRate,
options.dataBits,
options.stopBits,
options.parity,
options.flowControl
].join('|');
}
function isSerialOptionsApplyReason(reason) {
return reason === 'serial-options-apply' || reason === 'flow-control-apply';
}
function clearSerialReconfigureTimer() {
if (state.serial.reconfigureTimer) {
clearTimeout(state.serial.reconfigureTimer);
state.serial.reconfigureTimer = 0;
}
}
function setSerialOptionsApplyState(reason) {
state.serial.reconnectWanted = true;
state.serial.reconnectPending = true;
state.serial.reconnectPhase = 'trying';
state.serial.reconnectReason = isSerialOptionsApplyReason(reason) ? reason : 'serial-options-apply';
state.serial.reconnectFailureKind = '';
state.serial.reconnectFailureDetail = '';
state.serial.reconnectNoticeShown = false;
state.serial.reconnectSince = 0;
state.serial.reconnectResumeElapsedMs = state.serial.connectedAt
? Math.max(0, Date.now() - state.serial.connectedAt)
: 0;
updateSerialStatus();
}
async function applySerialOpenOptionsNow(reason = 'serial-options-change') {
clearSerialReconfigureTimer();
const options = syncSerialOptionState(getSerialOpenOptions({ commit: true }));
const nextSignature = getSerialOpenOptionsSignature(options);
state.serial.pendingOpenSignature = nextSignature;
updateSignalControlsUI();
if (state.serial.reconfigureTask) {
state.serial.reconfigureQueued = true;
return state.serial.reconfigureTask;
}
if (!state.serial.connected || state.serial.disconnecting || state.serial.blurReleaseActive) {
state.serial.pendingOpenSignature = '';
return false;