-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuart.html
More file actions
515 lines (460 loc) · 20 KB
/
Copy pathuart.html
File metadata and controls
515 lines (460 loc) · 20 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
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>WebSerial UART Console</title>
<style>
:root {
--bg:#0b1020; --panel:#151a2b; --border:#222a44; --text:#e6e9f0; --muted:#9aa3b2;
--accent:#70d6ff; --ok:#80ed99; --warn:#ffd166; --err:#ff6b6b;
--radius:8px;
}
*{box-sizing:border-box;margin:0;padding:0}
html,body{height:100%;overflow:hidden}
body{display:flex;flex-direction:column;background:var(--bg);color:var(--text);font:13px/1.4 'Inter',-apple-system,sans-serif}
/* ── Header ── */
header{display:flex;align-items:center;gap:.75rem;padding:.6rem 1rem;background:linear-gradient(90deg,#0b1020,#0e1734);border-bottom:1px solid var(--border);flex-shrink:0}
h1{font-size:15px;margin:0;color:#fff;white-space:nowrap}
.badge{font-size:10px;padding:2px 7px;border-radius:4px;background:rgba(112,214,255,.12);color:var(--accent);font-weight:600}
header .spacer{flex:1}
.stat{font-size:11px;color:var(--muted)}
/* ── Toolbar ── */
.toolbar{display:flex;align-items:center;gap:8px;padding:8px 1rem;background:var(--panel);border-bottom:1px solid var(--border);flex-shrink:0;flex-wrap:wrap}
.toolbar label{font-size:11px;color:var(--muted);white-space:nowrap}
.toolbar select,.toolbar input[type="number"]{background:#0f152a;border:1px solid var(--border);color:var(--text);border-radius:var(--radius);padding:4px 6px;font-size:11px;font-family:'JetBrains Mono',monospace}
.toolbar select{cursor:pointer}
.sep{width:1px;height:22px;background:var(--border);margin:0 4px}
.switch{display:inline-flex;align-items:center;gap:4px;font-size:11px;color:var(--muted);cursor:pointer}
.switch input{accent-color:var(--accent)}
/* ── Buttons ── */
.btn{display:inline-flex;align-items:center;gap:5px;padding:5px 12px;border:1px solid var(--border);border-radius:var(--radius);font:600 11px 'Inter',sans-serif;cursor:pointer;transition:all .15s;white-space:nowrap;color:var(--text);background:#1b2140}
.btn:hover{filter:brightness(1.15)}
.btn:disabled{opacity:.4;cursor:not-allowed;filter:none}
.btn svg{width:13px;height:13px}
.btn-ok{background:linear-gradient(180deg,#1a3a2a,#14291f);border-color:#2a5a3a;color:var(--ok)}
.btn-err{background:linear-gradient(180deg,#3a1a1a,#291414);border-color:#5a2a2a;color:var(--err)}
/* ── Terminal area ── */
.terminal-wrap{flex:1;min-height:0;overflow:hidden;position:relative}
#terminal{height:100%}
/* ── Send bar ── */
.sendbar{display:flex;align-items:center;gap:8px;padding:8px 1rem;background:var(--panel);border-top:1px solid var(--border);flex-shrink:0}
.sendbar input[type="text"]{flex:1;background:#0f152a;border:1px solid var(--border);color:var(--text);border-radius:var(--radius);padding:6px 10px;font:12px 'JetBrains Mono',monospace;outline:none}
.sendbar input[type="text"]:focus{border-color:var(--accent);box-shadow:0 0 0 2px rgba(112,214,255,.12)}
/* ── Status bar ── */
.statusbar{display:flex;align-items:center;justify-content:space-between;padding:3px 12px;background:#0e1228;border-top:1px solid var(--border);font-size:10px;color:var(--muted);flex-shrink:0}
.statusbar-left,.statusbar-right{display:flex;align-items:center;gap:12px}
.dot{display:inline-block;width:7px;height:7px;border-radius:50%;margin-right:4px}
.dot.off{background:#555}
.dot.on{background:var(--ok);box-shadow:0 0 6px rgba(128,237,153,.3)}
/* ── Splash ── */
.splash{position:absolute;inset:0;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:14px;background:rgba(11,16,32,.88);backdrop-filter:blur(4px);z-index:10;transition:opacity .3s}
.splash.hidden{opacity:0;pointer-events:none}
.splash p{color:var(--muted);font-size:12px;max-width:320px;text-align:center;line-height:1.5}
</style>
</head>
<body>
<header>
<h1>⌘ WebSerial UART Console</h1>
<span class="badge">Web Serial API</span>
<div class="spacer"></div>
<span class="stat" id="stats">RX: 0 B TX: 0 B</span>
</header>
<div class="toolbar">
<label>Baud</label>
<select id="baud"><option>115200</option><option>9600</option><option>57600</option><option>230400</option><option>460800</option><option>921600</option></select>
<label>Data</label>
<select id="dataBits"><option selected>8</option><option>7</option></select>
<label>Parity</label>
<select id="parity"><option value="none" selected>none</option><option value="even">even</option><option value="odd">odd</option></select>
<label>Stop</label>
<select id="stopBits"><option value="1" selected>1</option><option value="2">2</option></select>
<label>Flow</label>
<select id="flow"><option value="none" selected>none</option><option value="hardware">rtscts</option></select>
<div class="sep"></div>
<label class="switch"><input type="checkbox" id="dtr">DTR</label>
<label class="switch"><input type="checkbox" id="rts">RTS</label>
<div class="sep"></div>
<label class="switch"><input type="checkbox" id="localEcho">Local Echo</label>
<label class="switch"><input type="checkbox" id="rxHex">RX HEX</label>
<label class="switch"><input type="checkbox" id="timestamp">Timestamp</label>
<div style="flex:1"></div>
<button class="btn" id="btnClear" title="Clear terminal">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-2 14H7L5 6"/></svg>
Clear
</button>
<button class="btn" id="btnSave" title="Save log">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
Save
</button>
<button class="btn btn-ok" id="btnConnect">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M5 12h14M12 5l7 7-7 7"/></svg>
Connect
</button>
</div>
<div class="terminal-wrap" id="terminalWrap">
<div class="splash" id="splash">
<svg width="44" height="44" viewBox="0 0 24 24" fill="none" stroke="var(--accent)" stroke-width="1.5" stroke-linecap="round">
<polyline points="4 17 10 11 4 5"/><line x1="12" y1="19" x2="20" y2="19"/>
</svg>
<p>Click "Connect" to select a USB Serial device.<br>Requires <b>Chrome 89+</b> or <b>Edge 89+</b>.<br>
Page must be served from <b>localhost</b> or <b>HTTPS</b>.</p>
<button class="btn btn-ok" id="btnConnectSplash">Select Device & Connect</button>
<p id="splashStatus" style="font-size:11px;color:var(--accent);margin-top:8px;min-height:1.3em"></p>
</div>
<div id="terminal"></div>
</div>
<div class="sendbar">
<input id="txInput" type="text" placeholder="Type to send... Press Enter to submit" spellcheck="false" autocomplete="off">
<label>
<select id="lineEnding" style="background:#0f152a;border:1px solid var(--border);color:var(--text);border-radius:var(--radius);padding:4px;font-size:11px">
<option value="\r\n" selected>CRLF</option>
<option value="\n">LF</option>
<option value="\r">CR</option>
<option value="">None</option>
</select>
</label>
<label class="switch"><input type="checkbox" id="txHex">TX HEX</label>
<button class="btn" id="btnSend">Send</button>
</div>
<div class="statusbar">
<div class="statusbar-left">
<span><span class="dot off" id="statusDot"></span><span id="statusText">Disconnected</span></span>
</div>
<div class="statusbar-right">
<span id="portInfoBar">—</span>
</div>
</div>
<script>
// ── Resource loader with retry + CDN fallback ──
(function() {
const RETRIES = 3;
const RETRY_MS = 500;
const resources = [
{ type:'css', local:'lib/xterm.min.css', cdn:'https://cdn.jsdelivr.net/npm/@xterm/xterm@5.5.0/css/xterm.min.css', name:'xterm.css' },
{ type:'js', local:'lib/xterm.min.js', cdn:'https://cdn.jsdelivr.net/npm/@xterm/xterm@5.5.0/lib/xterm.min.js', name:'xterm.js' },
{ type:'js', local:'lib/addon-fit.min.js', cdn:'https://cdn.jsdelivr.net/npm/@xterm/addon-fit@0.10.0/lib/addon-fit.min.js', name:'addon-fit.js' },
{ type:'js', local:'lib/addon-web-links.min.js', cdn:'https://cdn.jsdelivr.net/npm/@xterm/addon-web-links@0.11.0/lib/addon-web-links.min.js', name:'addon-web-links.js' },
];
function log(msg) {
const el = document.getElementById('splashStatus');
if (el) el.textContent = msg;
console.log('[loader] ' + msg);
}
function loadOne(url, type) {
return new Promise((resolve, reject) => {
let el;
if (type === 'css') {
el = document.createElement('link');
el.rel = 'stylesheet'; el.href = url;
} else {
el = document.createElement('script');
el.src = url;
}
el.onload = () => resolve();
el.onerror = () => { el.remove(); reject(); };
document.head.appendChild(el);
});
}
async function loadWithRetry(res) {
for (let i = 1; i <= RETRIES; i++) {
try {
log('Loading ' + res.name + ' (local ' + i + '/' + RETRIES + ')...');
await loadOne(res.local, res.type);
log(res.name + ' ✓ local');
return 'local';
} catch(e) {
log(res.name + ' local attempt ' + i + ' failed');
if (i < RETRIES) await new Promise(r => setTimeout(r, RETRY_MS));
}
}
log('Loading ' + res.name + ' from CDN...');
try {
await loadOne(res.cdn, res.type);
log(res.name + ' ✓ CDN');
return 'cdn';
} catch(e) {
log('ERROR: ' + res.name + ' failed!');
throw e;
}
}
async function loadAll() {
const results = [];
for (const res of resources) {
const src = await loadWithRetry(res);
results.push(res.name + '(' + src + ')');
}
log('Ready: ' + results.join(', '));
setTimeout(initApp, 50);
}
loadAll();
})();
function initApp() {
(function() {
'use strict';
// ── DOM refs ──
const $ = id => document.getElementById(id);
const baud = $('baud'), dataBits = $('dataBits'), parity = $('parity');
const stopBits = $('stopBits'), flow = $('flow');
const dtrCb = $('dtr'), rtsCb = $('rts');
const localEchoCb = $('localEcho'), rxHexCb = $('rxHex'), timestampCb = $('timestamp');
const txInput = $('txInput'), txHexCb = $('txHex'), lineEndingSel = $('lineEnding');
// ── State ──
let port = null, reader = null, writer = null, keepReading = false;
let rxCount = 0, txCount = 0;
let logBuf = [];
let atLineStart = true; // track whether next output starts a new line
// ── xterm.js setup ──
const term = new Terminal({
fontFamily: "'JetBrains Mono','Cascadia Code','Fira Code',monospace",
fontSize: 14,
theme: {
background: '#0a0f20',
foreground: '#e6e9f0',
cursor: '#70d6ff',
cursorAccent: '#0a0f20',
selectionBackground: 'rgba(112,214,255,0.25)',
black: '#484f58', red: '#ff6b6b', green: '#80ed99', yellow: '#ffd166',
blue: '#70d6ff', magenta: '#c9a0ff', cyan: '#56d4a0', white: '#e6e9f0',
brightBlack: '#6e7681', brightRed: '#ffa198', brightGreen: '#a8f0c0',
brightYellow: '#ffe599', brightBlue: '#a0d8ff', brightMagenta: '#d9bfff',
brightCyan: '#80e8c8', brightWhite: '#f5f8ff',
},
cursorBlink: true,
scrollback: 20000,
convertEol: true,
});
const fitAddon = new FitAddon.FitAddon();
term.loadAddon(fitAddon);
term.loadAddon(new WebLinksAddon.WebLinksAddon());
term.open($('terminal'));
// ── Auto-fit terminal to container ──
function layoutTerminal() {
fitAddon.fit();
console.log(`[layout] ${term.cols}x${term.rows}`);
$('portInfoBar').textContent = `${term.cols}x${term.rows}`;
}
let resizeTimer;
window.addEventListener('resize', () => { clearTimeout(resizeTimer); resizeTimer = setTimeout(layoutTerminal, 100); });
// Initial layout
requestAnimationFrame(() => {
layoutTerminal();
term.writeln('\x1b[1;32mWebSerial UART Console (xterm.js)\x1b[0m');
term.writeln('');
});
// ── Terminal keyboard input → Serial TX ──
// In interactive mode, each keystroke goes directly to UART
term.onData(data => {
if (!port || !writer) return;
if (localEchoCb.checked) {
if (data === '\r') term.write('\r\n');
else if (data === '\x7f' || data === '\b') term.write('\b \b');
else term.write(data);
}
const bytes = new TextEncoder().encode(data === '\r' ? getLineEnding() : data);
sendBytes(bytes);
});
// ── Helpers ──
function getLineEnding() {
const v = lineEndingSel.value;
return v.replace(/\\r/g, '\r').replace(/\\n/g, '\n');
}
function tsNow() {
const d = new Date();
return d.toLocaleTimeString() + '.' + String(d.getMilliseconds()).padStart(3, '0');
}
function hex4(n) { return (n || 0).toString(16).toUpperCase().padStart(4, '0'); }
function fmtBytes(b) {
if (b < 1024) return b + ' B';
if (b < 1048576) return (b / 1024).toFixed(1) + ' KB';
return (b / 1048576).toFixed(1) + ' MB';
}
function updateStats() {
$('stats').textContent = `RX: ${fmtBytes(rxCount)} TX: ${fmtBytes(txCount)}`;
}
function toHexStr(buf) {
return [...buf].map(b => b.toString(16).padStart(2, '0')).join(' ');
}
function sysMsg(msg) {
const ts = timestampCb.checked ? `[${new Date().toLocaleTimeString()}] ` : '';
term.writeln(`\x1b[90m${ts}${msg}\x1b[0m`);
}
// ── Connect / Disconnect ──
async function connect() {
try {
port = await navigator.serial.requestPort({});
await port.open({
baudRate: parseInt(baud.value, 10) || 115200,
dataBits: parseInt(dataBits.value, 10),
parity: parity.value,
stopBits: parseInt(stopBits.value, 10),
flowControl: flow.value === 'hardware' ? 'hardware' : 'none',
bufferSize: 4096,
});
writer = port.writable.getWriter();
keepReading = true;
readLoop();
await setSignals();
const info = port.getInfo ? port.getInfo() : {};
const vid = hex4(info.usbVendorId);
const pid = hex4(info.usbProductId);
$('statusDot').className = 'dot on';
$('statusText').textContent = 'Connected';
$('portInfoBar').textContent = `VID:0x${vid} PID:0x${pid} @${baud.value}`;
$('splash').classList.add('hidden');
setTimeout(layoutTerminal, 100);
// Swap connect → disconnect
$('btnConnect').className = 'btn btn-err';
$('btnConnect').innerHTML = `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg> Disconnect`;
$('btnConnect').onclick = disconnect;
rxCount = 0; txCount = 0; updateStats();
term.writeln(`\x1b[1;32m● Connected VID=0x${vid} PID=0x${pid} ${baud.value}bps\x1b[0m`);
term.writeln('');
term.focus();
} catch (e) {
if (e.name !== 'NotFoundError') {
sysMsg('Connection failed: ' + e.message);
console.error(e);
}
}
}
async function disconnect() {
keepReading = false;
if (reader) { try { await reader.cancel(); } catch {} reader.releaseLock(); reader = null; }
if (writer) { try { await writer.close(); } catch {} writer.releaseLock(); writer = null; }
if (port) { try { await port.close(); } catch {} }
port = null;
$('statusDot').className = 'dot off';
$('statusText').textContent = 'Disconnected';
$('portInfoBar').textContent = '—';
$('splash').classList.remove('hidden');
setTimeout(layoutTerminal, 100);
$('btnConnect').className = 'btn btn-ok';
$('btnConnect').innerHTML = `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M5 12h14M12 5l7 7-7 7"/></svg> Connect`;
$('btnConnect').onclick = connect;
term.writeln('\r\n\x1b[1;31m● Disconnected\x1b[0m\r\n');
}
async function setSignals() {
try {
if (port && port.setSignals) {
await port.setSignals({ dataTerminalReady: dtrCb.checked, requestToSend: rtsCb.checked });
}
} catch (e) { console.warn('setSignals', e); }
}
// ── Read loop ──
async function readLoop() {
try {
while (port && port.readable && keepReading) {
const r = port.readable.getReader();
reader = r;
try {
while (true) {
const { value, done } = await r.read();
if (done) break;
if (!value || value.length === 0) continue;
rxCount += value.length;
if (rxHexCb.checked) {
const ts = timestampCb.checked ? '\x1b[90m[' + tsNow() + ']\x1b[0m ' : '';
term.writeln(ts + '\x1b[33m' + toHexStr(value) + '\x1b[0m');
atLineStart = true;
} else {
const text = new TextDecoder().decode(value);
if (timestampCb.checked) {
// Insert timestamp only at line boundaries
for (let i = 0; i < text.length; i++) {
const ch = text[i];
if (atLineStart && ch !== '\n' && ch !== '\r') {
term.write('\x1b[90m[' + tsNow() + ']\x1b[0m ');
atLineStart = false;
}
term.write(ch);
if (ch === '\n' || ch === '\r') atLineStart = true;
}
} else {
term.write(text);
}
}
logBuf.push(new TextDecoder().decode(value));
if (logBuf.length > 50000) logBuf.shift();
updateStats();
}
} finally {
r.releaseLock();
reader = null;
}
}
} catch (e) {
sysMsg('Receiving data failed: ' + e.message);
console.error(e);
await disconnect();
}
}
// ── Send bytes ──
async function sendBytes(bytes) {
if (!writer) return;
try {
await writer.write(bytes);
txCount += bytes.length;
updateStats();
} catch (e) {
sysMsg('Sending data failed: ' + e.message);
}
}
// ── Send bar (Text/HEX input field) ──
function sendFromInput() {
const str = txInput.value;
if (!str.length) return;
if (!port || !writer) { sysMsg('Not connected.'); return; }
let bytes;
if (txHexCb.checked) {
const arr = [];
str.trim().split(/\s+/).forEach(t => {
if (t.length) arr.push(parseInt(t, 16) & 0xFF);
});
const le = getLineEnding();
for (let i = 0; i < le.length; i++) arr.push(le.charCodeAt(i));
bytes = new Uint8Array(arr);
} else {
bytes = new TextEncoder().encode(str + getLineEnding());
}
sendBytes(bytes);
if (localEchoCb.checked) {
term.write('\x1b[36m' + str + '\x1b[0m\r\n');
}
txInput.value = '';
}
// ── Save log ──
function saveLog() {
const blob = new Blob([logBuf.join('')], { type: 'text/plain' });
const a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.download = `uart_log_${new Date().toISOString().slice(0,19).replace(/:/g,'-')}.txt`;
a.click();
setTimeout(() => URL.revokeObjectURL(a.href), 500);
}
// ── Wiring ──
$('btnConnect').onclick = connect;
$('btnConnectSplash').onclick = connect;
$('btnClear').onclick = () => { term.clear(); logBuf = []; rxCount = 0; txCount = 0; updateStats(); };
$('btnSave').onclick = saveLog;
$('btnSend').onclick = sendFromInput;
txInput.addEventListener('keydown', e => {
if (e.key === 'Enter') { e.preventDefault(); sendFromInput(); }
});
dtrCb.onchange = setSignals;
rtsCb.onchange = setSignals;
// Device events
navigator.serial?.addEventListener('connect', () => sysMsg('Device attached. Click Connect to select.'));
navigator.serial?.addEventListener('disconnect', () => { sysMsg('Device removed.'); if (port) disconnect(); });
// Feature detection
if (!('serial' in navigator)) {
term.writeln('\x1b[1;31m⚠ Web Serial API is not supported in this browser.\x1b[0m');
term.writeln('\x1b[90mPlease use Chrome 89+ or Edge 89+, served from localhost or HTTPS.\x1b[0m');
$('btnConnect').disabled = true;
$('btnConnectSplash').disabled = true;
}
})();
}
</script>
</body>
</html>