wchisp-web 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +1 -0
- package/README.md +103 -0
- package/dist/device.d.ts +61 -0
- package/dist/device.js +116 -0
- package/dist/device.js.map +1 -0
- package/dist/flasher.d.ts +57 -0
- package/dist/flasher.js +227 -0
- package/dist/flasher.js.map +1 -0
- package/dist/format.d.ts +14 -0
- package/dist/format.js +140 -0
- package/dist/format.js.map +1 -0
- package/dist/index.d.ts +341 -0
- package/dist/index.js +1126 -0
- package/dist/index.js.map +1 -0
- package/dist/index.umd.min.js +2 -0
- package/dist/index.umd.min.js.map +1 -0
- package/dist/protocol.d.ts +66 -0
- package/dist/protocol.js +182 -0
- package/dist/protocol.js.map +1 -0
- package/dist/transport.d.ts +11 -0
- package/dist/transport.js +20 -0
- package/dist/transport.js.map +1 -0
- package/dist/webserial.d.ts +44 -0
- package/dist/webserial.js +120 -0
- package/dist/webserial.js.map +1 -0
- package/dist/webusb.d.ts +81 -0
- package/dist/webusb.js +90 -0
- package/dist/webusb.js.map +1 -0
- package/package.json +42 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,1126 @@
|
|
|
1
|
+
//#region src/protocol.ts
|
|
2
|
+
const MAX_PACKET_SIZE = 64;
|
|
3
|
+
const SECTOR_SIZE = 1024;
|
|
4
|
+
const CODE_CHUNK_SIZE = 56;
|
|
5
|
+
const EEPROM_READ_CHUNK_SIZE = 58;
|
|
6
|
+
const CFG_MASK_RDPR_USER_DATA_WPR = 7;
|
|
7
|
+
const CFG_MASK_BTVER = 8;
|
|
8
|
+
const CFG_MASK_UID = 16;
|
|
9
|
+
const CFG_MASK_ALL = 31;
|
|
10
|
+
const CMD = {
|
|
11
|
+
IDENTIFY: 161,
|
|
12
|
+
ISP_END: 162,
|
|
13
|
+
ISP_KEY: 163,
|
|
14
|
+
ERASE: 164,
|
|
15
|
+
PROGRAM: 165,
|
|
16
|
+
VERIFY: 166,
|
|
17
|
+
READ_CONFIG: 167,
|
|
18
|
+
WRITE_CONFIG: 168,
|
|
19
|
+
DATA_ERASE: 169,
|
|
20
|
+
DATA_PROGRAM: 170,
|
|
21
|
+
DATA_READ: 171,
|
|
22
|
+
WRITE_OTP: 195,
|
|
23
|
+
READ_OTP: 196,
|
|
24
|
+
SET_BAUD: 197
|
|
25
|
+
};
|
|
26
|
+
function le16(n) {
|
|
27
|
+
assertUint(n, 65535, "u16");
|
|
28
|
+
return [n & 255, n >>> 8 & 255];
|
|
29
|
+
}
|
|
30
|
+
function le32(n) {
|
|
31
|
+
assertUint(n, 4294967295, "u32");
|
|
32
|
+
return [
|
|
33
|
+
n & 255,
|
|
34
|
+
n >>> 8 & 255,
|
|
35
|
+
n >>> 16 & 255,
|
|
36
|
+
n >>> 24 & 255
|
|
37
|
+
];
|
|
38
|
+
}
|
|
39
|
+
function readLe16(buf, off) {
|
|
40
|
+
requireLength(buf, off + 2, "u16");
|
|
41
|
+
return buf[off] | buf[off + 1] << 8;
|
|
42
|
+
}
|
|
43
|
+
function readLe32(buf, off) {
|
|
44
|
+
requireLength(buf, off + 4, "u32");
|
|
45
|
+
return (buf[off] | buf[off + 1] << 8 | buf[off + 2] << 16 | buf[off + 3] << 24) >>> 0;
|
|
46
|
+
}
|
|
47
|
+
function commandIdentify(deviceId = 0, deviceType = 0) {
|
|
48
|
+
return concatBytes(Uint8Array.from([
|
|
49
|
+
CMD.IDENTIFY,
|
|
50
|
+
18,
|
|
51
|
+
0,
|
|
52
|
+
deviceId & 255,
|
|
53
|
+
deviceType & 255
|
|
54
|
+
]), ascii("MCU ISP & WCH.CN"));
|
|
55
|
+
}
|
|
56
|
+
function commandIspEnd(reason = 1) {
|
|
57
|
+
return Uint8Array.from([
|
|
58
|
+
CMD.ISP_END,
|
|
59
|
+
1,
|
|
60
|
+
0,
|
|
61
|
+
reason & 255
|
|
62
|
+
]);
|
|
63
|
+
}
|
|
64
|
+
function commandIspKey(seed = 30) {
|
|
65
|
+
const key = typeof seed === "number" ? new Uint8Array(seed) : seed;
|
|
66
|
+
return concatBytes(Uint8Array.from([
|
|
67
|
+
CMD.ISP_KEY,
|
|
68
|
+
key.length & 255,
|
|
69
|
+
0
|
|
70
|
+
]), key);
|
|
71
|
+
}
|
|
72
|
+
function commandErase(sectors) {
|
|
73
|
+
return Uint8Array.from([
|
|
74
|
+
CMD.ERASE,
|
|
75
|
+
4,
|
|
76
|
+
0,
|
|
77
|
+
...le32(sectors)
|
|
78
|
+
]);
|
|
79
|
+
}
|
|
80
|
+
function commandReadConfig(mask = 31) {
|
|
81
|
+
return Uint8Array.from([
|
|
82
|
+
CMD.READ_CONFIG,
|
|
83
|
+
2,
|
|
84
|
+
0,
|
|
85
|
+
mask & 255,
|
|
86
|
+
0
|
|
87
|
+
]);
|
|
88
|
+
}
|
|
89
|
+
function commandWriteConfig(mask, data) {
|
|
90
|
+
const len = 1 + data.length;
|
|
91
|
+
return concatBytes(Uint8Array.from([
|
|
92
|
+
CMD.WRITE_CONFIG,
|
|
93
|
+
...le16(len),
|
|
94
|
+
mask & 255,
|
|
95
|
+
0
|
|
96
|
+
]), data);
|
|
97
|
+
}
|
|
98
|
+
function commandProgram(address, data, padding = randomByte()) {
|
|
99
|
+
return commandAddressData(CMD.PROGRAM, address, data, padding);
|
|
100
|
+
}
|
|
101
|
+
function commandVerify(address, data, padding = randomByte()) {
|
|
102
|
+
return commandAddressData(CMD.VERIFY, address, data, padding);
|
|
103
|
+
}
|
|
104
|
+
function commandDataProgram(address, data, padding = randomByte()) {
|
|
105
|
+
return commandAddressData(CMD.DATA_PROGRAM, address, data, padding);
|
|
106
|
+
}
|
|
107
|
+
function commandDataRead(address, len) {
|
|
108
|
+
return Uint8Array.from([
|
|
109
|
+
CMD.DATA_READ,
|
|
110
|
+
6,
|
|
111
|
+
0,
|
|
112
|
+
...le32(address),
|
|
113
|
+
...le16(len)
|
|
114
|
+
]);
|
|
115
|
+
}
|
|
116
|
+
function commandDataErase(sectors) {
|
|
117
|
+
return Uint8Array.from([
|
|
118
|
+
CMD.DATA_ERASE,
|
|
119
|
+
5,
|
|
120
|
+
0,
|
|
121
|
+
0,
|
|
122
|
+
0,
|
|
123
|
+
0,
|
|
124
|
+
0,
|
|
125
|
+
sectors & 255
|
|
126
|
+
]);
|
|
127
|
+
}
|
|
128
|
+
function commandSetBaud(baudrate) {
|
|
129
|
+
return Uint8Array.from([
|
|
130
|
+
CMD.SET_BAUD,
|
|
131
|
+
4,
|
|
132
|
+
0,
|
|
133
|
+
...le32(baudrate)
|
|
134
|
+
]);
|
|
135
|
+
}
|
|
136
|
+
function parseResponse(raw) {
|
|
137
|
+
requireLength(raw, 4, "response header");
|
|
138
|
+
const command = raw[0];
|
|
139
|
+
const status = raw[1];
|
|
140
|
+
const len = readLe16(raw, 2);
|
|
141
|
+
const payload = raw.slice(4);
|
|
142
|
+
if (payload.length !== len) throw new Error(`Invalid response length: expected ${len}, got ${payload.length}`);
|
|
143
|
+
return status === 0 || status === 130 ? {
|
|
144
|
+
ok: true,
|
|
145
|
+
command,
|
|
146
|
+
status,
|
|
147
|
+
payload,
|
|
148
|
+
raw
|
|
149
|
+
} : {
|
|
150
|
+
ok: false,
|
|
151
|
+
command,
|
|
152
|
+
status,
|
|
153
|
+
code: status,
|
|
154
|
+
payload,
|
|
155
|
+
raw
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
function frameSerialRequest(raw) {
|
|
159
|
+
return concatBytes(Uint8Array.from([87, 171]), raw, Uint8Array.from([checksum8(raw)]));
|
|
160
|
+
}
|
|
161
|
+
function parseSerialResponse(frame) {
|
|
162
|
+
requireLength(frame, 7, "serial response");
|
|
163
|
+
if (frame[0] !== 85 || frame[1] !== 170) throw new Error(`Response has invalid serial header ${hex(frame.slice(0, 2))}`);
|
|
164
|
+
const raw = frame.slice(2, frame.length - 1);
|
|
165
|
+
const expected = checksum8(raw);
|
|
166
|
+
const actual = frame[frame.length - 1];
|
|
167
|
+
if (expected !== actual) throw new Error(`Response has incorrect checksum ${hexByte(actual)} != ${hexByte(expected)}`);
|
|
168
|
+
const len = readLe16(raw, 2);
|
|
169
|
+
if (raw.length !== 4 + len) throw new Error(`Invalid serial payload length: expected ${4 + len}, got ${raw.length}`);
|
|
170
|
+
return raw;
|
|
171
|
+
}
|
|
172
|
+
function xorWithKey(raw, key) {
|
|
173
|
+
if (key.length !== 8) throw new Error(`XOR key must be 8 bytes, got ${key.length}`);
|
|
174
|
+
const out = new Uint8Array(raw.length);
|
|
175
|
+
for (let i = 0; i < raw.length; i++) out[i] = raw[i] ^ key[i % 8];
|
|
176
|
+
return out;
|
|
177
|
+
}
|
|
178
|
+
function makeXorKey(chipUid, chipId) {
|
|
179
|
+
const sum = checksum8(chipUid);
|
|
180
|
+
const key = (/* @__PURE__ */ new Uint8Array(8)).fill(sum);
|
|
181
|
+
key[7] = key[7] + (chipId & 255) & 255;
|
|
182
|
+
return key;
|
|
183
|
+
}
|
|
184
|
+
function checksum8(data) {
|
|
185
|
+
let sum = 0;
|
|
186
|
+
for (const b of data) sum = sum + b & 255;
|
|
187
|
+
return sum;
|
|
188
|
+
}
|
|
189
|
+
function ispKeyChecksum(chipUid, chipId) {
|
|
190
|
+
return checksum8(makeXorKey(chipUid, chipId));
|
|
191
|
+
}
|
|
192
|
+
function padToSector(input, fill = 0) {
|
|
193
|
+
const rem = input.length % SECTOR_SIZE;
|
|
194
|
+
if (rem === 0) return input;
|
|
195
|
+
const out = new Uint8Array(input.length + SECTOR_SIZE - rem);
|
|
196
|
+
out.fill(fill & 255);
|
|
197
|
+
out.set(input);
|
|
198
|
+
return out;
|
|
199
|
+
}
|
|
200
|
+
function concatBytes(...chunks) {
|
|
201
|
+
const len = chunks.reduce((n, c) => n + c.length, 0);
|
|
202
|
+
const out = new Uint8Array(len);
|
|
203
|
+
let off = 0;
|
|
204
|
+
for (const c of chunks) {
|
|
205
|
+
out.set(c, off);
|
|
206
|
+
off += c.length;
|
|
207
|
+
}
|
|
208
|
+
return out;
|
|
209
|
+
}
|
|
210
|
+
function hex(data) {
|
|
211
|
+
return Array.from(data, hexByte).join("");
|
|
212
|
+
}
|
|
213
|
+
function hexByte(n) {
|
|
214
|
+
return (n & 255).toString(16).padStart(2, "0");
|
|
215
|
+
}
|
|
216
|
+
function commandAddressData(command, address, data, padding) {
|
|
217
|
+
const len = 5 + data.length;
|
|
218
|
+
return concatBytes(Uint8Array.from([
|
|
219
|
+
command & 255,
|
|
220
|
+
...le16(len),
|
|
221
|
+
...le32(address),
|
|
222
|
+
padding & 255
|
|
223
|
+
]), data);
|
|
224
|
+
}
|
|
225
|
+
function ascii(text) {
|
|
226
|
+
return Uint8Array.from(Array.from(text, (c) => c.charCodeAt(0) & 255));
|
|
227
|
+
}
|
|
228
|
+
function randomByte() {
|
|
229
|
+
const a = /* @__PURE__ */ new Uint8Array(1);
|
|
230
|
+
if (globalThis.crypto?.getRandomValues) globalThis.crypto.getRandomValues(a);
|
|
231
|
+
else a[0] = Math.floor(Math.random() * 256);
|
|
232
|
+
return a[0];
|
|
233
|
+
}
|
|
234
|
+
function requireLength(buf, min, what) {
|
|
235
|
+
if (buf.length < min) throw new Error(`Short ${what}: expected at least ${min}, got ${buf.length}`);
|
|
236
|
+
}
|
|
237
|
+
function assertUint(n, max, what) {
|
|
238
|
+
if (!Number.isInteger(n) || n < 0 || n > max) throw new Error(`Expected ${what}, got ${n}`);
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
//#endregion
|
|
242
|
+
//#region src/transport.ts
|
|
243
|
+
async function delay(ms) {
|
|
244
|
+
if (ms <= 0) return;
|
|
245
|
+
await new Promise((resolve) => setTimeout(resolve, ms));
|
|
246
|
+
}
|
|
247
|
+
async function transfer(transport, request, timeoutMs = 1e3) {
|
|
248
|
+
await transport.sendRaw(request);
|
|
249
|
+
await delay(0);
|
|
250
|
+
const raw = await transport.recvRaw(timeoutMs);
|
|
251
|
+
if (raw[0] !== request[0]) throw new Error(`Response command type mismatch: requested 0x${request[0].toString(16)}, got 0x${raw[0]?.toString(16)}`);
|
|
252
|
+
return parseResponse(raw);
|
|
253
|
+
}
|
|
254
|
+
function assertOk(response, label) {
|
|
255
|
+
if (!response.ok) throw new Error(`${label} failed with status 0x${response.code.toString(16)}`);
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
//#endregion
|
|
259
|
+
//#region src/webusb.ts
|
|
260
|
+
var WebUsbTransport = class WebUsbTransport {
|
|
261
|
+
static {
|
|
262
|
+
this.DEFAULT_VENDOR_IDS = [17224, 6790];
|
|
263
|
+
}
|
|
264
|
+
static {
|
|
265
|
+
this.DEFAULT_PRODUCT_ID = 21984;
|
|
266
|
+
}
|
|
267
|
+
static {
|
|
268
|
+
this.DEFAULT_ENDPOINT_OUT = 2;
|
|
269
|
+
}
|
|
270
|
+
static {
|
|
271
|
+
this.DEFAULT_ENDPOINT_IN = 130;
|
|
272
|
+
}
|
|
273
|
+
static {
|
|
274
|
+
this.DEFAULT_INTERFACE = 0;
|
|
275
|
+
}
|
|
276
|
+
constructor(device, options) {
|
|
277
|
+
this.device = device;
|
|
278
|
+
this.options = options;
|
|
279
|
+
}
|
|
280
|
+
static async request(options = {}) {
|
|
281
|
+
const usb = navigator.usb;
|
|
282
|
+
if (!usb) throw new Error("WebUSB is not available in this browser");
|
|
283
|
+
const vendorIds = options.vendorIds ?? WebUsbTransport.DEFAULT_VENDOR_IDS;
|
|
284
|
+
const productId = options.productId ?? WebUsbTransport.DEFAULT_PRODUCT_ID;
|
|
285
|
+
const device = await usb.requestDevice({ filters: vendorIds.map((vendorId) => ({
|
|
286
|
+
vendorId,
|
|
287
|
+
productId
|
|
288
|
+
})) });
|
|
289
|
+
return WebUsbTransport.openDevice(device, options);
|
|
290
|
+
}
|
|
291
|
+
static async openPaired(options = {}) {
|
|
292
|
+
const usb = navigator.usb;
|
|
293
|
+
if (!usb) throw new Error("WebUSB is not available in this browser");
|
|
294
|
+
const vendorIds = options.vendorIds ?? WebUsbTransport.DEFAULT_VENDOR_IDS;
|
|
295
|
+
const productId = options.productId ?? WebUsbTransport.DEFAULT_PRODUCT_ID;
|
|
296
|
+
const devices = (await usb.getDevices()).filter((d) => vendorIds.includes(d.vendorId) && d.productId === productId);
|
|
297
|
+
return Promise.all(devices.map((device) => WebUsbTransport.openDevice(device, options)));
|
|
298
|
+
}
|
|
299
|
+
static async openDevice(device, options = {}) {
|
|
300
|
+
const normalized = {
|
|
301
|
+
vendorIds: options.vendorIds ?? WebUsbTransport.DEFAULT_VENDOR_IDS,
|
|
302
|
+
productId: options.productId ?? WebUsbTransport.DEFAULT_PRODUCT_ID,
|
|
303
|
+
interfaceNumber: options.interfaceNumber ?? WebUsbTransport.DEFAULT_INTERFACE,
|
|
304
|
+
configurationValue: options.configurationValue ?? 1,
|
|
305
|
+
endpointOut: options.endpointOut ?? WebUsbTransport.DEFAULT_ENDPOINT_OUT,
|
|
306
|
+
endpointIn: options.endpointIn ?? WebUsbTransport.DEFAULT_ENDPOINT_IN
|
|
307
|
+
};
|
|
308
|
+
const t = new WebUsbTransport(device, normalized);
|
|
309
|
+
await t.open();
|
|
310
|
+
return t;
|
|
311
|
+
}
|
|
312
|
+
async open() {
|
|
313
|
+
if (!this.device.opened) await this.device.open();
|
|
314
|
+
if (!this.device.configuration || this.device.configuration.configurationValue !== this.options.configurationValue) await this.device.selectConfiguration(this.options.configurationValue);
|
|
315
|
+
this.validateEndpoints();
|
|
316
|
+
await this.device.claimInterface(this.options.interfaceNumber);
|
|
317
|
+
}
|
|
318
|
+
async sendRaw(raw) {
|
|
319
|
+
const endpoint = endpointNumber(this.options.endpointOut);
|
|
320
|
+
const result = await this.device.transferOut(endpoint, raw);
|
|
321
|
+
if (result.status !== "ok") throw new Error(`USB transferOut failed: ${result.status}`);
|
|
322
|
+
}
|
|
323
|
+
async recvRaw(_timeoutMs = 5e3) {
|
|
324
|
+
const endpoint = endpointNumber(this.options.endpointIn);
|
|
325
|
+
const result = await this.device.transferIn(endpoint, 64);
|
|
326
|
+
if (result.status !== "ok") throw new Error(`USB transferIn failed: ${result.status}`);
|
|
327
|
+
if (!result.data) throw new Error("USB transferIn returned no data");
|
|
328
|
+
return new Uint8Array(result.data.buffer, result.data.byteOffset, result.data.byteLength).slice();
|
|
329
|
+
}
|
|
330
|
+
async close() {
|
|
331
|
+
try {
|
|
332
|
+
await this.device.releaseInterface(this.options.interfaceNumber);
|
|
333
|
+
} catch {}
|
|
334
|
+
try {
|
|
335
|
+
await this.device.close();
|
|
336
|
+
} catch {}
|
|
337
|
+
}
|
|
338
|
+
validateEndpoints() {
|
|
339
|
+
const intf = this.device.configuration?.interfaces.find((i) => i.interfaceNumber === this.options.interfaceNumber);
|
|
340
|
+
if (!intf) throw new Error(`USB interface ${this.options.interfaceNumber} not found`);
|
|
341
|
+
const endpoints = intf.alternates.flatMap((a) => a.endpoints);
|
|
342
|
+
const out = endpoints.some((e) => e.direction === "out" && e.endpointNumber === endpointNumber(this.options.endpointOut));
|
|
343
|
+
const input = endpoints.some((e) => e.direction === "in" && e.endpointNumber === endpointNumber(this.options.endpointIn));
|
|
344
|
+
if (!out || !input) throw new Error(`Required USB endpoints not found (out 0x${this.options.endpointOut.toString(16)}, in 0x${this.options.endpointIn.toString(16)})`);
|
|
345
|
+
}
|
|
346
|
+
};
|
|
347
|
+
function endpointNumber(addr) {
|
|
348
|
+
return addr & 15;
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
//#endregion
|
|
352
|
+
//#region src/webserial.ts
|
|
353
|
+
var WebSerialTransport = class WebSerialTransport {
|
|
354
|
+
constructor(port, options) {
|
|
355
|
+
this.port = port;
|
|
356
|
+
this.options = options;
|
|
357
|
+
this.pending = /* @__PURE__ */ new Uint8Array(0);
|
|
358
|
+
}
|
|
359
|
+
static async request(options = {}) {
|
|
360
|
+
const serial = navigator.serial;
|
|
361
|
+
if (!serial) throw new Error("Web Serial is not available in this browser");
|
|
362
|
+
const port = await serial.requestPort();
|
|
363
|
+
return WebSerialTransport.openPort(port, options);
|
|
364
|
+
}
|
|
365
|
+
static async openPaired(options = {}) {
|
|
366
|
+
const serial = navigator.serial;
|
|
367
|
+
if (!serial) throw new Error("Web Serial is not available in this browser");
|
|
368
|
+
return Promise.all((await serial.getPorts()).map((port) => WebSerialTransport.openPort(port, options)));
|
|
369
|
+
}
|
|
370
|
+
static async openPort(port, options = {}) {
|
|
371
|
+
const normalized = {
|
|
372
|
+
baudRate: Number(options.baudRate ?? 115200),
|
|
373
|
+
dataBits: options.dataBits ?? 8,
|
|
374
|
+
stopBits: options.stopBits ?? 1,
|
|
375
|
+
parity: options.parity ?? "none",
|
|
376
|
+
bufferSize: options.bufferSize ?? 255,
|
|
377
|
+
flowControl: options.flowControl ?? "none"
|
|
378
|
+
};
|
|
379
|
+
const t = new WebSerialTransport(port, normalized);
|
|
380
|
+
await t.open();
|
|
381
|
+
return t;
|
|
382
|
+
}
|
|
383
|
+
async open() {
|
|
384
|
+
await this.port.open(this.options);
|
|
385
|
+
if (!this.port.readable || !this.port.writable) throw new Error("Serial port is not readable/writable");
|
|
386
|
+
this.reader = this.port.readable.getReader();
|
|
387
|
+
this.writer = this.port.writable.getWriter();
|
|
388
|
+
}
|
|
389
|
+
async sendRaw(raw) {
|
|
390
|
+
if (!this.writer) throw new Error("Serial writer is not open");
|
|
391
|
+
await this.writer.write(frameSerialRequest(raw));
|
|
392
|
+
}
|
|
393
|
+
async recvRaw(timeoutMs = 1e3) {
|
|
394
|
+
await this.readUntil(6, timeoutMs);
|
|
395
|
+
const start = this.findHeader();
|
|
396
|
+
if (start < 0) throw new Error("Serial response header not found");
|
|
397
|
+
if (start > 0) this.pending = this.pending.slice(start);
|
|
398
|
+
await this.readUntil(6, timeoutMs);
|
|
399
|
+
const frameLen = 6 + readLe16(this.pending, 4) + 1;
|
|
400
|
+
await this.readUntil(frameLen, timeoutMs);
|
|
401
|
+
const frame = this.pending.slice(0, frameLen);
|
|
402
|
+
this.pending = this.pending.slice(frameLen);
|
|
403
|
+
return parseSerialResponse(frame);
|
|
404
|
+
}
|
|
405
|
+
async close() {
|
|
406
|
+
try {
|
|
407
|
+
await this.reader?.cancel?.();
|
|
408
|
+
} catch {}
|
|
409
|
+
try {
|
|
410
|
+
this.reader?.releaseLock();
|
|
411
|
+
} catch {}
|
|
412
|
+
try {
|
|
413
|
+
this.writer?.releaseLock();
|
|
414
|
+
} catch {}
|
|
415
|
+
try {
|
|
416
|
+
await this.port.close();
|
|
417
|
+
} catch {}
|
|
418
|
+
}
|
|
419
|
+
async readUntil(n, timeoutMs) {
|
|
420
|
+
if (!this.reader) throw new Error("Serial reader is not open");
|
|
421
|
+
const deadline = Date.now() + timeoutMs;
|
|
422
|
+
while (this.pending.length < n) {
|
|
423
|
+
const left = deadline - Date.now();
|
|
424
|
+
if (left <= 0) throw new Error(`Timed out waiting for serial response (${this.pending.length}/${n} bytes)`);
|
|
425
|
+
const res = await withTimeout(this.reader.read(), left);
|
|
426
|
+
if (res.done) throw new Error("Serial stream closed");
|
|
427
|
+
if (res.value?.length) this.pending = concat(this.pending, res.value);
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
findHeader() {
|
|
431
|
+
for (let i = 0; i + 1 < this.pending.length; i++) if (this.pending[i] === 85 && this.pending[i + 1] === 170) return i;
|
|
432
|
+
return -1;
|
|
433
|
+
}
|
|
434
|
+
};
|
|
435
|
+
function concat(a, b) {
|
|
436
|
+
const out = new Uint8Array(a.length + b.length);
|
|
437
|
+
out.set(a);
|
|
438
|
+
out.set(b, a.length);
|
|
439
|
+
return out;
|
|
440
|
+
}
|
|
441
|
+
async function withTimeout(promise, ms) {
|
|
442
|
+
let timer;
|
|
443
|
+
try {
|
|
444
|
+
return await Promise.race([promise, new Promise((_, reject) => {
|
|
445
|
+
timer = setTimeout(() => reject(/* @__PURE__ */ new Error("timeout")), ms);
|
|
446
|
+
})]);
|
|
447
|
+
} finally {
|
|
448
|
+
if (timer) clearTimeout(timer);
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
//#endregion
|
|
453
|
+
//#region src/device.ts
|
|
454
|
+
var ChipDatabase = class ChipDatabase {
|
|
455
|
+
constructor(families = BUILTIN_CHIPS) {
|
|
456
|
+
this.families = families;
|
|
457
|
+
}
|
|
458
|
+
static fromJson(value) {
|
|
459
|
+
if (Array.isArray(value)) return new ChipDatabase(normalizeFamilies(value));
|
|
460
|
+
const obj = value;
|
|
461
|
+
return new ChipDatabase(normalizeFamilies(obj.families ?? obj.chips ?? []));
|
|
462
|
+
}
|
|
463
|
+
find(chipId, deviceType) {
|
|
464
|
+
for (const family of this.families) {
|
|
465
|
+
if ((family.deviceType & 255) !== (deviceType & 255)) continue;
|
|
466
|
+
for (const variant of family.variants) {
|
|
467
|
+
const ids = variant.altChipIds === "*" ? [] : variant.altChipIds ?? [];
|
|
468
|
+
if (variant.altChipIds === "*" || variant.chipId === chipId || ids.includes(chipId)) return mergeFamilyChip(family, variant);
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
};
|
|
473
|
+
function normalizeFamilies(families) {
|
|
474
|
+
return families.map((f) => ({
|
|
475
|
+
...f,
|
|
476
|
+
deviceType: f.deviceType & 255,
|
|
477
|
+
mcuType: f.mcuType & 255,
|
|
478
|
+
variants: (f.variants ?? []).map((c) => ({
|
|
479
|
+
...c,
|
|
480
|
+
deviceType: (c.deviceType ?? f.deviceType) & 255,
|
|
481
|
+
mcuType: (c.mcuType ?? f.mcuType) & 255
|
|
482
|
+
}))
|
|
483
|
+
}));
|
|
484
|
+
}
|
|
485
|
+
function explainConfig(raw, registers = []) {
|
|
486
|
+
const out = [];
|
|
487
|
+
for (const reg of registers) {
|
|
488
|
+
if (raw.length < reg.offset + 4) continue;
|
|
489
|
+
const value = readLe32(raw, reg.offset);
|
|
490
|
+
out.push({
|
|
491
|
+
name: reg.name,
|
|
492
|
+
offset: reg.offset,
|
|
493
|
+
value,
|
|
494
|
+
explanation: lookupExplanation(value, reg.explanation),
|
|
495
|
+
fields: (reg.fields ?? []).map((f) => {
|
|
496
|
+
const [hi, lo] = f.bitRange;
|
|
497
|
+
const width = hi - lo + 1;
|
|
498
|
+
const fv = value >>> lo & (width >= 32 ? 4294967295 : 2 ** width - 1);
|
|
499
|
+
return {
|
|
500
|
+
name: f.name,
|
|
501
|
+
range: f.bitRange,
|
|
502
|
+
value: fv >>> 0,
|
|
503
|
+
explanation: lookupExplanation(fv >>> 0, f.explanation)
|
|
504
|
+
};
|
|
505
|
+
})
|
|
506
|
+
});
|
|
507
|
+
}
|
|
508
|
+
return out;
|
|
509
|
+
}
|
|
510
|
+
function minEraseSectorNumber(chip, deviceType) {
|
|
511
|
+
if (chip?.minEraseSectors) return chip.minEraseSectors;
|
|
512
|
+
const dt = chip?.deviceType ?? deviceType ?? 0;
|
|
513
|
+
return dt === 17 || dt === 18 ? 4 : 8;
|
|
514
|
+
}
|
|
515
|
+
function chipDisplayName(chip, chipId, deviceType) {
|
|
516
|
+
return chip ? `${chip.name}[0x${hex2(chip.chipId)}${hex2(chip.deviceType)}]` : `Unknown[0x${hex2(chipId)}${hex2(deviceType)}]`;
|
|
517
|
+
}
|
|
518
|
+
function mergeFamilyChip(family, chip) {
|
|
519
|
+
return {
|
|
520
|
+
...chip,
|
|
521
|
+
mcuType: chip.mcuType ?? family.mcuType,
|
|
522
|
+
deviceType: chip.deviceType ?? family.deviceType,
|
|
523
|
+
supportUsb: chip.supportUsb ?? family.supportUsb,
|
|
524
|
+
supportSerial: chip.supportSerial ?? family.supportSerial,
|
|
525
|
+
supportNet: chip.supportNet ?? family.supportNet,
|
|
526
|
+
configRegisters: [...family.configRegisters ?? [], ...chip.configRegisters ?? []]
|
|
527
|
+
};
|
|
528
|
+
}
|
|
529
|
+
function lookupExplanation(value, map) {
|
|
530
|
+
if (!map) return void 0;
|
|
531
|
+
const keys = [
|
|
532
|
+
`0x${value.toString(16).toUpperCase()}`,
|
|
533
|
+
`0x${value.toString(16)}`,
|
|
534
|
+
String(value),
|
|
535
|
+
`_`
|
|
536
|
+
];
|
|
537
|
+
for (const k of keys) if (map[k] !== void 0) return map[k];
|
|
538
|
+
}
|
|
539
|
+
function hex2(n) {
|
|
540
|
+
return (n & 255).toString(16).padStart(2, "0");
|
|
541
|
+
}
|
|
542
|
+
const basicConfig = [
|
|
543
|
+
{
|
|
544
|
+
offset: 0,
|
|
545
|
+
name: "RDPR_USER",
|
|
546
|
+
reset: 2673892005,
|
|
547
|
+
fields: [
|
|
548
|
+
{
|
|
549
|
+
name: "RDPR",
|
|
550
|
+
bitRange: [7, 0],
|
|
551
|
+
explanation: {
|
|
552
|
+
"0xA5": "Unprotected",
|
|
553
|
+
"_": "Protected"
|
|
554
|
+
}
|
|
555
|
+
},
|
|
556
|
+
{
|
|
557
|
+
name: "IWDG_SW",
|
|
558
|
+
bitRange: [16, 16]
|
|
559
|
+
},
|
|
560
|
+
{
|
|
561
|
+
name: "STOP_RST",
|
|
562
|
+
bitRange: [17, 17]
|
|
563
|
+
},
|
|
564
|
+
{
|
|
565
|
+
name: "STANDBY_RST",
|
|
566
|
+
bitRange: [18, 18]
|
|
567
|
+
}
|
|
568
|
+
]
|
|
569
|
+
},
|
|
570
|
+
{
|
|
571
|
+
offset: 4,
|
|
572
|
+
name: "DATA"
|
|
573
|
+
},
|
|
574
|
+
{
|
|
575
|
+
offset: 8,
|
|
576
|
+
name: "WRP",
|
|
577
|
+
explanation: { "0xFFFFFFFF": "Unprotected" }
|
|
578
|
+
}
|
|
579
|
+
];
|
|
580
|
+
const BUILTIN_CHIPS = normalizeFamilies([
|
|
581
|
+
{
|
|
582
|
+
name: "CH32V20x",
|
|
583
|
+
mcuType: 2,
|
|
584
|
+
deviceType: 18,
|
|
585
|
+
supportUsb: true,
|
|
586
|
+
supportSerial: true,
|
|
587
|
+
variants: [{
|
|
588
|
+
name: "CH32V203",
|
|
589
|
+
chipId: 32,
|
|
590
|
+
deviceType: 18,
|
|
591
|
+
flashSize: 64 * 1024
|
|
592
|
+
}, {
|
|
593
|
+
name: "CH32V208",
|
|
594
|
+
chipId: 33,
|
|
595
|
+
deviceType: 18,
|
|
596
|
+
flashSize: 128 * 1024
|
|
597
|
+
}],
|
|
598
|
+
configRegisters: basicConfig
|
|
599
|
+
},
|
|
600
|
+
{
|
|
601
|
+
name: "CH32V30x",
|
|
602
|
+
mcuType: 0,
|
|
603
|
+
deviceType: 16,
|
|
604
|
+
supportUsb: true,
|
|
605
|
+
supportSerial: true,
|
|
606
|
+
variants: [{
|
|
607
|
+
name: "CH32V307",
|
|
608
|
+
chipId: 112,
|
|
609
|
+
deviceType: 23,
|
|
610
|
+
flashSize: 256 * 1024,
|
|
611
|
+
eepromSize: 0
|
|
612
|
+
}, {
|
|
613
|
+
name: "CH32V305",
|
|
614
|
+
chipId: 112,
|
|
615
|
+
deviceType: 21,
|
|
616
|
+
flashSize: 256 * 1024,
|
|
617
|
+
eepromSize: 0
|
|
618
|
+
}],
|
|
619
|
+
configRegisters: basicConfig
|
|
620
|
+
},
|
|
621
|
+
{
|
|
622
|
+
name: "CH55x",
|
|
623
|
+
mcuType: 5,
|
|
624
|
+
deviceType: 17,
|
|
625
|
+
supportUsb: true,
|
|
626
|
+
supportSerial: true,
|
|
627
|
+
variants: [
|
|
628
|
+
{
|
|
629
|
+
name: "CH552",
|
|
630
|
+
chipId: 82,
|
|
631
|
+
deviceType: 17,
|
|
632
|
+
flashSize: 16 * 1024,
|
|
633
|
+
eepromSize: 128
|
|
634
|
+
},
|
|
635
|
+
{
|
|
636
|
+
name: "CH554",
|
|
637
|
+
chipId: 84,
|
|
638
|
+
deviceType: 17,
|
|
639
|
+
flashSize: 16 * 1024,
|
|
640
|
+
eepromSize: 128
|
|
641
|
+
},
|
|
642
|
+
{
|
|
643
|
+
name: "CH559",
|
|
644
|
+
chipId: 89,
|
|
645
|
+
deviceType: 17,
|
|
646
|
+
flashSize: 56 * 1024,
|
|
647
|
+
eepromSize: 1024
|
|
648
|
+
}
|
|
649
|
+
],
|
|
650
|
+
configRegisters: basicConfig
|
|
651
|
+
},
|
|
652
|
+
{
|
|
653
|
+
name: "CH57x/CH58x/CH59x",
|
|
654
|
+
mcuType: 8,
|
|
655
|
+
deviceType: 24,
|
|
656
|
+
supportUsb: true,
|
|
657
|
+
supportSerial: true,
|
|
658
|
+
variants: [
|
|
659
|
+
{
|
|
660
|
+
name: "CH573",
|
|
661
|
+
chipId: 115,
|
|
662
|
+
deviceType: 24,
|
|
663
|
+
flashSize: 448 * 1024
|
|
664
|
+
},
|
|
665
|
+
{
|
|
666
|
+
name: "CH579",
|
|
667
|
+
chipId: 121,
|
|
668
|
+
deviceType: 24,
|
|
669
|
+
flashSize: 448 * 1024
|
|
670
|
+
},
|
|
671
|
+
{
|
|
672
|
+
name: "CH582",
|
|
673
|
+
chipId: 130,
|
|
674
|
+
deviceType: 24,
|
|
675
|
+
flashSize: 448 * 1024
|
|
676
|
+
},
|
|
677
|
+
{
|
|
678
|
+
name: "CH592",
|
|
679
|
+
chipId: 146,
|
|
680
|
+
deviceType: 24,
|
|
681
|
+
flashSize: 448 * 1024
|
|
682
|
+
}
|
|
683
|
+
],
|
|
684
|
+
configRegisters: basicConfig
|
|
685
|
+
}
|
|
686
|
+
]);
|
|
687
|
+
|
|
688
|
+
//#endregion
|
|
689
|
+
//#region src/format.ts
|
|
690
|
+
async function readFirmwareFile(file) {
|
|
691
|
+
const name = file.name.toLowerCase();
|
|
692
|
+
const bytes = new Uint8Array(await file.arrayBuffer());
|
|
693
|
+
if (name.endsWith(".hex") || name.endsWith(".ihex")) return parseIntelHex(new TextDecoder().decode(bytes));
|
|
694
|
+
if (name.endsWith(".elf") || looksLikeElf(bytes)) return parseElf(bytes);
|
|
695
|
+
return {
|
|
696
|
+
data: bytes,
|
|
697
|
+
baseAddress: 0,
|
|
698
|
+
format: "bin",
|
|
699
|
+
segments: [{
|
|
700
|
+
address: 0,
|
|
701
|
+
data: bytes
|
|
702
|
+
}]
|
|
703
|
+
};
|
|
704
|
+
}
|
|
705
|
+
function parseFirmware(input, filename = "") {
|
|
706
|
+
const lower = filename.toLowerCase();
|
|
707
|
+
if (typeof input === "string" || lower.endsWith(".hex") || lower.endsWith(".ihex")) return parseIntelHex(typeof input === "string" ? input : new TextDecoder().decode(input));
|
|
708
|
+
if (lower.endsWith(".elf") || looksLikeElf(input)) return parseElf(input);
|
|
709
|
+
return {
|
|
710
|
+
data: input,
|
|
711
|
+
baseAddress: 0,
|
|
712
|
+
format: "bin",
|
|
713
|
+
segments: [{
|
|
714
|
+
address: 0,
|
|
715
|
+
data: input
|
|
716
|
+
}]
|
|
717
|
+
};
|
|
718
|
+
}
|
|
719
|
+
function parseIntelHex(text) {
|
|
720
|
+
let upperLinear = 0;
|
|
721
|
+
let upperSegment = 0;
|
|
722
|
+
const bytes = /* @__PURE__ */ new Map();
|
|
723
|
+
let startAddress = 0;
|
|
724
|
+
for (const [lineNo, rawLine] of text.split(/\r?\n/).entries()) {
|
|
725
|
+
const line = rawLine.trim();
|
|
726
|
+
if (!line) continue;
|
|
727
|
+
if (!line.startsWith(":")) throw new Error(`Intel HEX line ${lineNo + 1}: missing ':'`);
|
|
728
|
+
const rec = hexBytes(line.slice(1));
|
|
729
|
+
if (rec.length < 5) throw new Error(`Intel HEX line ${lineNo + 1}: short record`);
|
|
730
|
+
const count = rec[0];
|
|
731
|
+
if (rec.length !== count + 5) throw new Error(`Intel HEX line ${lineNo + 1}: length mismatch`);
|
|
732
|
+
if (rec.reduce((a, b) => a + b & 255, 0) !== 0) throw new Error(`Intel HEX line ${lineNo + 1}: checksum mismatch`);
|
|
733
|
+
const offset = rec[1] << 8 | rec[2];
|
|
734
|
+
const type = rec[3];
|
|
735
|
+
const data = rec.slice(4, 4 + count);
|
|
736
|
+
if (type === 0) {
|
|
737
|
+
const base = upperLinear + upperSegment + offset;
|
|
738
|
+
for (let i = 0; i < data.length; i++) bytes.set(base + i, data[i]);
|
|
739
|
+
} else if (type === 1) break;
|
|
740
|
+
else if (type === 2) {
|
|
741
|
+
upperSegment = (data[0] << 8 | data[1]) << 4 >>> 0;
|
|
742
|
+
upperLinear = 0;
|
|
743
|
+
} else if (type === 4) {
|
|
744
|
+
upperLinear = (data[0] << 8 | data[1]) << 16 >>> 0;
|
|
745
|
+
upperSegment = 0;
|
|
746
|
+
} else if (type === 3 || type === 5) startAddress = data.reduce((a, b) => (a << 8 | b) >>> 0, 0);
|
|
747
|
+
}
|
|
748
|
+
if (!bytes.size) return {
|
|
749
|
+
data: /* @__PURE__ */ new Uint8Array(),
|
|
750
|
+
baseAddress: startAddress,
|
|
751
|
+
format: "hex",
|
|
752
|
+
segments: []
|
|
753
|
+
};
|
|
754
|
+
const addresses = [...bytes.keys()].sort((a, b) => a - b);
|
|
755
|
+
const segments = [];
|
|
756
|
+
let segStart = addresses[0];
|
|
757
|
+
let prev = addresses[0] - 1;
|
|
758
|
+
let cur = [];
|
|
759
|
+
for (const addr of addresses) {
|
|
760
|
+
if (addr !== prev + 1 && cur.length) {
|
|
761
|
+
segments.push({
|
|
762
|
+
address: segStart,
|
|
763
|
+
data: Uint8Array.from(cur)
|
|
764
|
+
});
|
|
765
|
+
segStart = addr;
|
|
766
|
+
cur = [];
|
|
767
|
+
}
|
|
768
|
+
cur.push(bytes.get(addr));
|
|
769
|
+
prev = addr;
|
|
770
|
+
}
|
|
771
|
+
if (cur.length) segments.push({
|
|
772
|
+
address: segStart,
|
|
773
|
+
data: Uint8Array.from(cur)
|
|
774
|
+
});
|
|
775
|
+
return segmentsToImage(segments, "hex");
|
|
776
|
+
}
|
|
777
|
+
function parseElf(bytes) {
|
|
778
|
+
if (!looksLikeElf(bytes)) throw new Error("Not an ELF file");
|
|
779
|
+
const cls = bytes[4];
|
|
780
|
+
if (bytes[5] !== 1) throw new Error("Only little-endian ELF files are supported");
|
|
781
|
+
if (cls === 1) return parseElf32(bytes);
|
|
782
|
+
if (cls === 2) return parseElf64(bytes);
|
|
783
|
+
throw new Error(`Unsupported ELF class ${cls}`);
|
|
784
|
+
}
|
|
785
|
+
function looksLikeElf(bytes) {
|
|
786
|
+
return bytes.length >= 4 && bytes[0] === 127 && bytes[1] === 69 && bytes[2] === 76 && bytes[3] === 70;
|
|
787
|
+
}
|
|
788
|
+
function parseElf32(b) {
|
|
789
|
+
const phoff = u32(b, 28), phentsize = u16(b, 42), phnum = u16(b, 44);
|
|
790
|
+
const segments = [];
|
|
791
|
+
for (let i = 0; i < phnum; i++) {
|
|
792
|
+
const off = phoff + i * phentsize;
|
|
793
|
+
const type = u32(b, off), pOffset = u32(b, off + 4), pPaddr = u32(b, off + 12), filesz = u32(b, off + 16);
|
|
794
|
+
if (type === 1 && filesz > 0) segments.push({
|
|
795
|
+
address: pPaddr,
|
|
796
|
+
data: b.slice(pOffset, pOffset + filesz)
|
|
797
|
+
});
|
|
798
|
+
}
|
|
799
|
+
return segmentsToImage(segments, "elf");
|
|
800
|
+
}
|
|
801
|
+
function parseElf64(b) {
|
|
802
|
+
const phoff = Number(u64(b, 32)), phentsize = u16(b, 54), phnum = u16(b, 56);
|
|
803
|
+
const segments = [];
|
|
804
|
+
for (let i = 0; i < phnum; i++) {
|
|
805
|
+
const off = phoff + i * phentsize;
|
|
806
|
+
const type = u32(b, off), pOffset = Number(u64(b, off + 8)), pPaddr = Number(u64(b, off + 24)), filesz = Number(u64(b, off + 32));
|
|
807
|
+
if (type === 1 && filesz > 0) segments.push({
|
|
808
|
+
address: pPaddr >>> 0,
|
|
809
|
+
data: b.slice(pOffset, pOffset + filesz)
|
|
810
|
+
});
|
|
811
|
+
}
|
|
812
|
+
return segmentsToImage(segments, "elf");
|
|
813
|
+
}
|
|
814
|
+
function segmentsToImage(segments, format) {
|
|
815
|
+
if (!segments.length) return {
|
|
816
|
+
data: /* @__PURE__ */ new Uint8Array(),
|
|
817
|
+
baseAddress: 0,
|
|
818
|
+
format,
|
|
819
|
+
segments
|
|
820
|
+
};
|
|
821
|
+
const min = Math.min(...segments.map((s) => s.address));
|
|
822
|
+
const max = Math.max(...segments.map((s) => s.address + s.data.length));
|
|
823
|
+
const data = new Uint8Array(max - min);
|
|
824
|
+
for (const s of segments) data.set(s.data, s.address - min);
|
|
825
|
+
return {
|
|
826
|
+
data,
|
|
827
|
+
baseAddress: min,
|
|
828
|
+
format,
|
|
829
|
+
segments
|
|
830
|
+
};
|
|
831
|
+
}
|
|
832
|
+
function hexBytes(s) {
|
|
833
|
+
if (s.length % 2) throw new Error("Odd number of HEX digits");
|
|
834
|
+
const out = [];
|
|
835
|
+
for (let i = 0; i < s.length; i += 2) out.push(parseInt(s.slice(i, i + 2), 16));
|
|
836
|
+
if (out.some(Number.isNaN)) throw new Error("Invalid HEX digit");
|
|
837
|
+
return out;
|
|
838
|
+
}
|
|
839
|
+
function u16(b, o) {
|
|
840
|
+
return b[o] | b[o + 1] << 8;
|
|
841
|
+
}
|
|
842
|
+
function u32(b, o) {
|
|
843
|
+
return (b[o] | b[o + 1] << 8 | b[o + 2] << 16 | b[o + 3] << 24) >>> 0;
|
|
844
|
+
}
|
|
845
|
+
function u64(b, o) {
|
|
846
|
+
return BigInt(u32(b, o)) | BigInt(u32(b, o + 4)) << 32n;
|
|
847
|
+
}
|
|
848
|
+
|
|
849
|
+
//#endregion
|
|
850
|
+
//#region src/flasher.ts
|
|
851
|
+
var WchIspFlasher = class {
|
|
852
|
+
constructor(transport, chipDb = new ChipDatabase()) {
|
|
853
|
+
this.transport = transport;
|
|
854
|
+
this.chipDb = chipDb;
|
|
855
|
+
}
|
|
856
|
+
async connect(progress) {
|
|
857
|
+
progress?.({
|
|
858
|
+
phase: "identify",
|
|
859
|
+
done: 0,
|
|
860
|
+
total: 1,
|
|
861
|
+
message: "Identifying chip"
|
|
862
|
+
});
|
|
863
|
+
const ident = await transfer(this.transport, commandIdentify());
|
|
864
|
+
assertOk(ident, "identify");
|
|
865
|
+
if (ident.payload.length < 2) throw new Error(`identify response too short: ${hex(ident.payload)}`);
|
|
866
|
+
const chipId = ident.payload[0];
|
|
867
|
+
const deviceType = ident.payload[1];
|
|
868
|
+
const chip = this.chipDb.find(chipId, deviceType);
|
|
869
|
+
progress?.({
|
|
870
|
+
phase: "identify",
|
|
871
|
+
done: 1,
|
|
872
|
+
total: 1,
|
|
873
|
+
message: chipDisplayName(chip, chipId, deviceType)
|
|
874
|
+
});
|
|
875
|
+
const config = await this.readConfig(31, progress);
|
|
876
|
+
const codeFlashProtected = Boolean(config.length >= 3 && config[2] !== 165);
|
|
877
|
+
const bootloader = config.slice(14, 18);
|
|
878
|
+
const uid = config.slice(18);
|
|
879
|
+
this.info = {
|
|
880
|
+
chipId,
|
|
881
|
+
deviceType,
|
|
882
|
+
chip,
|
|
883
|
+
name: chipDisplayName(chip, chipId, deviceType),
|
|
884
|
+
uid,
|
|
885
|
+
bootloader,
|
|
886
|
+
configRaw: config,
|
|
887
|
+
codeFlashProtected,
|
|
888
|
+
config: explainConfig(config.slice(2), chip?.configRegisters)
|
|
889
|
+
};
|
|
890
|
+
return this.info;
|
|
891
|
+
}
|
|
892
|
+
async readConfig(mask = 31, progress) {
|
|
893
|
+
progress?.({
|
|
894
|
+
phase: "read-config",
|
|
895
|
+
done: 0,
|
|
896
|
+
total: 1
|
|
897
|
+
});
|
|
898
|
+
const resp = await transfer(this.transport, commandReadConfig(mask));
|
|
899
|
+
assertOk(resp, "read_config");
|
|
900
|
+
progress?.({
|
|
901
|
+
phase: "read-config",
|
|
902
|
+
done: 1,
|
|
903
|
+
total: 1
|
|
904
|
+
});
|
|
905
|
+
return resp.payload;
|
|
906
|
+
}
|
|
907
|
+
async writeConfig(mask, data) {
|
|
908
|
+
assertOk(await transfer(this.transport, commandWriteConfig(mask, data)), "write_config");
|
|
909
|
+
}
|
|
910
|
+
async unprotect(force = false, progress) {
|
|
911
|
+
const info = await this.ensureConnected();
|
|
912
|
+
if (!force && !info.codeFlashProtected) return;
|
|
913
|
+
progress?.({
|
|
914
|
+
phase: "unprotect",
|
|
915
|
+
done: 0,
|
|
916
|
+
total: 1
|
|
917
|
+
});
|
|
918
|
+
const resp = await transfer(this.transport, commandReadConfig(7));
|
|
919
|
+
assertOk(resp, "read_config");
|
|
920
|
+
if (resp.payload.length < 14) throw new Error("read_config response too short for protection registers");
|
|
921
|
+
const config = resp.payload.slice(2, 14);
|
|
922
|
+
config[0] = 165;
|
|
923
|
+
config[1] = 90;
|
|
924
|
+
config.set([
|
|
925
|
+
255,
|
|
926
|
+
255,
|
|
927
|
+
255,
|
|
928
|
+
255
|
|
929
|
+
], 8);
|
|
930
|
+
await this.writeConfig(7, config);
|
|
931
|
+
progress?.({
|
|
932
|
+
phase: "unprotect",
|
|
933
|
+
done: 1,
|
|
934
|
+
total: 1
|
|
935
|
+
});
|
|
936
|
+
await this.reset(1, progress);
|
|
937
|
+
}
|
|
938
|
+
async reset(reason = 1, progress) {
|
|
939
|
+
progress?.({
|
|
940
|
+
phase: "reset",
|
|
941
|
+
done: 0,
|
|
942
|
+
total: 1
|
|
943
|
+
});
|
|
944
|
+
assertOk(await transfer(this.transport, commandIspEnd(reason)), "isp_end");
|
|
945
|
+
progress?.({
|
|
946
|
+
phase: "reset",
|
|
947
|
+
done: 1,
|
|
948
|
+
total: 1
|
|
949
|
+
});
|
|
950
|
+
}
|
|
951
|
+
async setBaudrate(baudrate) {
|
|
952
|
+
const resp = await transfer(this.transport, commandSetBaud(baudrate));
|
|
953
|
+
assertOk(resp, "set_baud");
|
|
954
|
+
return resp.payload[0] !== 254;
|
|
955
|
+
}
|
|
956
|
+
async eraseCode(bytesOrSectors, unit = "bytes", progress) {
|
|
957
|
+
const info = await this.ensureConnected();
|
|
958
|
+
let sectors = unit === "sectors" ? bytesOrSectors : Math.ceil(bytesOrSectors / SECTOR_SIZE);
|
|
959
|
+
sectors = Math.max(minEraseSectorNumber(info.chip, info.deviceType), sectors);
|
|
960
|
+
progress?.({
|
|
961
|
+
phase: "erase",
|
|
962
|
+
done: 0,
|
|
963
|
+
total: sectors * SECTOR_SIZE
|
|
964
|
+
});
|
|
965
|
+
assertOk(await transfer(this.transport, commandErase(sectors), 5e3), "erase");
|
|
966
|
+
progress?.({
|
|
967
|
+
phase: "erase",
|
|
968
|
+
done: sectors * SECTOR_SIZE,
|
|
969
|
+
total: sectors * SECTOR_SIZE
|
|
970
|
+
});
|
|
971
|
+
return sectors;
|
|
972
|
+
}
|
|
973
|
+
async flash(input, options = {}) {
|
|
974
|
+
const info = await this.ensureConnected(options.progress);
|
|
975
|
+
if (options.unprotect) await this.unprotect(false, options.progress);
|
|
976
|
+
const image = await this.normalizeFirmware(input);
|
|
977
|
+
const baseAddress = options.baseAddress ?? image.baseAddress;
|
|
978
|
+
if (baseAddress !== 0) throw new Error(`Only images starting at address 0 are directly flashable; got base address 0x${baseAddress.toString(16)}`);
|
|
979
|
+
const data = options.pad === false ? image.data : padToSector(image.data);
|
|
980
|
+
if (options.erase !== false) await this.eraseCode(data.length, "bytes", options.progress);
|
|
981
|
+
await this.beginIspKey();
|
|
982
|
+
await this.writeCode(data, options.progress);
|
|
983
|
+
if (options.verify !== false) {
|
|
984
|
+
await this.beginIspKey();
|
|
985
|
+
await this.verifyCode(data, options.progress);
|
|
986
|
+
}
|
|
987
|
+
if (options.reset !== false) await this.reset(1, options.progress);
|
|
988
|
+
return info;
|
|
989
|
+
}
|
|
990
|
+
async writeCode(data, progress) {
|
|
991
|
+
const key = await this.xorKey();
|
|
992
|
+
let address = 0;
|
|
993
|
+
for (let off = 0; off < data.length; off += 56) {
|
|
994
|
+
const chunk = data.slice(off, off + 56);
|
|
995
|
+
const xored = xorWithKey(chunk, key);
|
|
996
|
+
assertOk(await transfer(this.transport, commandProgram(address, xored), 300), `program 0x${address.toString(16)}`);
|
|
997
|
+
address += chunk.length;
|
|
998
|
+
progress?.({
|
|
999
|
+
phase: "write",
|
|
1000
|
+
done: address,
|
|
1001
|
+
total: data.length,
|
|
1002
|
+
address
|
|
1003
|
+
});
|
|
1004
|
+
}
|
|
1005
|
+
assertOk(await transfer(this.transport, commandProgram(address, /* @__PURE__ */ new Uint8Array()), 300), `program final 0x${address.toString(16)}`);
|
|
1006
|
+
}
|
|
1007
|
+
async verifyCode(data, progress) {
|
|
1008
|
+
const key = await this.xorKey();
|
|
1009
|
+
let address = 0;
|
|
1010
|
+
for (let off = 0; off < data.length; off += 56) {
|
|
1011
|
+
const chunk = data.slice(off, off + 56);
|
|
1012
|
+
const xored = xorWithKey(chunk, key);
|
|
1013
|
+
const resp = await transfer(this.transport, commandVerify(address, xored));
|
|
1014
|
+
assertOk(resp, "verify response");
|
|
1015
|
+
if (resp.payload[0] !== 0) throw new Error(`Verify failed at 0x${address.toString(16)}`);
|
|
1016
|
+
address += chunk.length;
|
|
1017
|
+
progress?.({
|
|
1018
|
+
phase: "verify",
|
|
1019
|
+
done: address,
|
|
1020
|
+
total: data.length,
|
|
1021
|
+
address
|
|
1022
|
+
});
|
|
1023
|
+
}
|
|
1024
|
+
}
|
|
1025
|
+
async eraseData(progress) {
|
|
1026
|
+
const size = (await this.ensureConnected()).chip?.eepromSize ?? 0;
|
|
1027
|
+
if (!size) throw new Error("Chip does not advertise EEPROM/data flash support");
|
|
1028
|
+
const sectors = Math.max(1, Math.ceil(size / SECTOR_SIZE));
|
|
1029
|
+
progress?.({
|
|
1030
|
+
phase: "eeprom-erase",
|
|
1031
|
+
done: 0,
|
|
1032
|
+
total: size
|
|
1033
|
+
});
|
|
1034
|
+
assertOk(await transfer(this.transport, commandDataErase(sectors), 1e3), "data_erase");
|
|
1035
|
+
progress?.({
|
|
1036
|
+
phase: "eeprom-erase",
|
|
1037
|
+
done: size,
|
|
1038
|
+
total: size
|
|
1039
|
+
});
|
|
1040
|
+
return sectors;
|
|
1041
|
+
}
|
|
1042
|
+
async readData(length, progress) {
|
|
1043
|
+
const info = await this.ensureConnected();
|
|
1044
|
+
const total = length ?? info.chip?.eepromSize ?? 0;
|
|
1045
|
+
if (!total) throw new Error("EEPROM/data flash length is unknown; pass an explicit length");
|
|
1046
|
+
const out = new Uint8Array(total);
|
|
1047
|
+
let address = 0;
|
|
1048
|
+
while (address < total) {
|
|
1049
|
+
const n = Math.min(58, total - address);
|
|
1050
|
+
const resp = await transfer(this.transport, commandDataRead(address, n));
|
|
1051
|
+
assertOk(resp, "data_read");
|
|
1052
|
+
const data = resp.payload.slice(2);
|
|
1053
|
+
if (data.length !== n) throw new Error(`data_read length mismatch: expected ${n}, got ${data.length}`);
|
|
1054
|
+
out.set(data, address);
|
|
1055
|
+
address += n;
|
|
1056
|
+
progress?.({
|
|
1057
|
+
phase: "eeprom-read",
|
|
1058
|
+
done: address,
|
|
1059
|
+
total,
|
|
1060
|
+
address
|
|
1061
|
+
});
|
|
1062
|
+
}
|
|
1063
|
+
return out;
|
|
1064
|
+
}
|
|
1065
|
+
async writeData(data, progress) {
|
|
1066
|
+
await this.ensureConnected();
|
|
1067
|
+
await this.beginIspKey(false);
|
|
1068
|
+
const key = await this.xorKey();
|
|
1069
|
+
let address = 0;
|
|
1070
|
+
for (let off = 0; off < data.length; off += 56) {
|
|
1071
|
+
const chunk = data.slice(off, off + 56);
|
|
1072
|
+
assertOk(await transfer(this.transport, commandDataProgram(address, xorWithKey(chunk, key)), 5), `data_program 0x${address.toString(16)}`);
|
|
1073
|
+
address += chunk.length;
|
|
1074
|
+
progress?.({
|
|
1075
|
+
phase: "eeprom-write",
|
|
1076
|
+
done: address,
|
|
1077
|
+
total: data.length,
|
|
1078
|
+
address
|
|
1079
|
+
});
|
|
1080
|
+
}
|
|
1081
|
+
assertOk(await transfer(this.transport, commandProgram(address, /* @__PURE__ */ new Uint8Array()), 300), `data_program final 0x${address.toString(16)}`);
|
|
1082
|
+
}
|
|
1083
|
+
async resetConfig(registers) {
|
|
1084
|
+
const info = await this.ensureConnected();
|
|
1085
|
+
const regs = registers ?? info.chip?.configRegisters ?? [];
|
|
1086
|
+
const rawResp = await transfer(this.transport, commandReadConfig(7));
|
|
1087
|
+
assertOk(rawResp, "read_config");
|
|
1088
|
+
const raw = rawResp.payload.slice(2);
|
|
1089
|
+
for (const reg of regs) {
|
|
1090
|
+
if (reg.reset === void 0 || raw.length < reg.offset + 4) continue;
|
|
1091
|
+
raw[reg.offset] = reg.reset & 255;
|
|
1092
|
+
raw[reg.offset + 1] = reg.reset >>> 8 & 255;
|
|
1093
|
+
raw[reg.offset + 2] = reg.reset >>> 16 & 255;
|
|
1094
|
+
raw[reg.offset + 3] = reg.reset >>> 24 & 255;
|
|
1095
|
+
}
|
|
1096
|
+
await this.writeConfig(7, raw);
|
|
1097
|
+
}
|
|
1098
|
+
async close() {
|
|
1099
|
+
await this.transport.close?.();
|
|
1100
|
+
}
|
|
1101
|
+
async beginIspKey(checkChecksum = true) {
|
|
1102
|
+
const info = await this.ensureConnected();
|
|
1103
|
+
const resp = await transfer(this.transport, commandIspKey(/* @__PURE__ */ new Uint8Array(30)));
|
|
1104
|
+
assertOk(resp, "isp_key");
|
|
1105
|
+
if (checkChecksum) {
|
|
1106
|
+
const expected = ispKeyChecksum(info.uid, info.chipId);
|
|
1107
|
+
if (resp.payload[0] !== expected) throw new Error(`isp_key checksum failed: expected 0x${expected.toString(16)}, got 0x${(resp.payload[0] ?? 0).toString(16)}`);
|
|
1108
|
+
}
|
|
1109
|
+
}
|
|
1110
|
+
async xorKey() {
|
|
1111
|
+
const info = await this.ensureConnected();
|
|
1112
|
+
return makeXorKey(info.uid, info.chipId);
|
|
1113
|
+
}
|
|
1114
|
+
async ensureConnected(progress) {
|
|
1115
|
+
return this.info ?? this.connect(progress);
|
|
1116
|
+
}
|
|
1117
|
+
async normalizeFirmware(input) {
|
|
1118
|
+
if (typeof File !== "undefined" && input instanceof File) return readFirmwareFile(input);
|
|
1119
|
+
if (typeof input === "object" && "data" in input && "segments" in input) return input;
|
|
1120
|
+
return parseFirmware(input);
|
|
1121
|
+
}
|
|
1122
|
+
};
|
|
1123
|
+
|
|
1124
|
+
//#endregion
|
|
1125
|
+
export { BUILTIN_CHIPS, CFG_MASK_ALL, CFG_MASK_BTVER, CFG_MASK_RDPR_USER_DATA_WPR, CFG_MASK_UID, CMD, CODE_CHUNK_SIZE, ChipDatabase, EEPROM_READ_CHUNK_SIZE, MAX_PACKET_SIZE, SECTOR_SIZE, WchIspFlasher, WebSerialTransport, WebUsbTransport, assertOk, checksum8, chipDisplayName, commandDataErase, commandDataProgram, commandDataRead, commandErase, commandIdentify, commandIspEnd, commandIspKey, commandProgram, commandReadConfig, commandSetBaud, commandVerify, commandWriteConfig, concatBytes, delay, explainConfig, frameSerialRequest, hex, hexByte, ispKeyChecksum, le16, le32, looksLikeElf, makeXorKey, minEraseSectorNumber, normalizeFamilies, padToSector, parseElf, parseFirmware, parseIntelHex, parseResponse, parseSerialResponse, readFirmwareFile, readLe16, readLe32, transfer, xorWithKey };
|
|
1126
|
+
//# sourceMappingURL=index.js.map
|