-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserial-core.js
More file actions
101 lines (87 loc) · 2.72 KB
/
serial-core.js
File metadata and controls
101 lines (87 loc) · 2.72 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
// serial-core.js — Minimal Web Serial API wrapper for uConsole
// Provides: open(baudRate), close(), send(data), onData, onError
class SerialCore {
constructor() {
this.port = null;
this.reader = null;
this.isOpen = false;
// Callbacks
this.onData = null; // (data: Uint8Array) => void
this.onError = null; // (error: Error) => void
this.onClose = null; // () => void
}
/**
* Request port from user and open with given baud rate
* @param {number} baudRate
* @returns {Promise<boolean>}
*/
async open(baudRate = 9600) {
try {
// Must be triggered by user gesture
this.port = await navigator.serial.requestPort();
await this.port.open({
baudRate: baudRate,
dataBits: 8,
stopBits: 1,
parity: 'none',
flowControl: 'none'
});
this.isOpen = true;
// Start reading
this.reader = this.port.readable.getReader();
this._readLoop();
return true;
} catch (err) {
this.isOpen = false;
if (this.onError) this.onError(err);
throw err;
}
}
/**
* Send raw bytes to port
* @param {Uint8Array} data
*/
async send(data) {
if (!this.isOpen || !this.port) throw new Error('Port not open');
const writer = this.port.writable.getWriter();
await writer.write(data);
writer.releaseLock();
}
/**
* Internal read loop — pushes every received chunk to onData immediately
*/
async _readLoop() {
try {
while (true) {
const { value, done } = await this.reader.read();
if (done) break;
if (this.onData && value && value.length > 0) {
this.onData(value);
}
}
} catch (err) {
if (err.name === 'NetworkError' || err.name === 'AbortError') {
// Port disconnected — normal
} else if (this.onError) {
this.onError(err);
}
}
this.isOpen = false;
if (this.onClose) this.onClose();
}
/**
* Close the port and release all resources
*/
async close() {
if (this.reader) {
try { this.reader.cancel(); } catch (e) { /* ignore */ }
try { this.reader.releaseLock(); } catch (e) { /* ignore */ }
this.reader = null;
}
if (this.port) {
try { await this.port.close(); } catch (e) { /* ignore */ }
this.port = null;
}
this.isOpen = false;
}
}