├── .gitignore ├── .gitattributes ├── release.bat ├── images ├── check-small.svg ├── cross-small.svg ├── config-read.svg ├── config-write.svg ├── flash-erase.svg ├── flash-verify.svg ├── flash-write.svg ├── cross-red.svg ├── check-green.svg ├── github.svg └── dtr-rts-sequence.svg ├── banner.txt ├── modules ├── devices.js ├── logger.js ├── packet.js ├── util.js ├── parsers │ ├── intelhex.js │ ├── elf.js │ └── srecord.js ├── transceiver.js ├── response.js ├── command.js ├── firmware.js ├── session.js └── devices.json ├── README.md ├── style.css ├── wchisp.js ├── index.html └── LICENSE.txt /.gitignore: -------------------------------------------------------------------------------- 1 | dist/* 2 | release/* 3 | server.bat 4 | TODO.txt 5 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /release.bat: -------------------------------------------------------------------------------- 1 | @echo off 2 | 3 | set ZIP=C:\Program Files\7-Zip\7z.exe 4 | set OUTDIR=dist 5 | set RELDIR=release 6 | 7 | mkdir "%RELDIR%" 8 | "%ZIP%" a "%RELDIR%\wch-web-isp.zip" "%OUTDIR%\*" "README.md" "LICENSE.txt" 9 | -------------------------------------------------------------------------------- /images/check-small.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /images/cross-small.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /images/config-read.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /images/config-write.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /images/flash-erase.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /images/flash-verify.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /images/flash-write.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /images/cross-red.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /images/check-green.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /images/github.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /banner.txt: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * 3 | * WCH RISC-V Microcontroller Web Serial ISP 4 | * Copyright (c) 2025 Basil Hussain 5 | * 6 | * This program is free software: you can redistribute it and/or modify it under 7 | * the terms of the GNU Affero General Public License as published by the Free 8 | * Software Foundation, either version 3 of the License, or (at your option) any 9 | * later version. 10 | * 11 | * This program is distributed in the hope that it will be useful, but WITHOUT 12 | * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 13 | * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more 14 | * details. 15 | * 16 | * You should have received a copy of the GNU Affero General Public License 17 | * along with this program. If not, see . 18 | * 19 | * SPDX-License-Identifier: AGPL-3.0-or-later 20 | * 21 | ******************************************************************************/ 22 | 23 | -------------------------------------------------------------------------------- /modules/devices.js: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * 3 | * WCH RISC-V Microcontroller Web Serial ISP 4 | * Copyright (c) 2025 Basil Hussain 5 | * 6 | * This program is free software: you can redistribute it and/or modify it under 7 | * the terms of the GNU Affero General Public License as published by the Free 8 | * Software Foundation, either version 3 of the License, or (at your option) any 9 | * later version. 10 | * 11 | * This program is distributed in the hope that it will be useful, but WITHOUT 12 | * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 13 | * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more 14 | * details. 15 | * 16 | * You should have received a copy of the GNU Affero General Public License 17 | * along with this program. If not, see . 18 | * 19 | * SPDX-License-Identifier: AGPL-3.0-or-later 20 | * 21 | ******************************************************************************/ 22 | 23 | import { Formatter } from "./util.js"; 24 | import { default as database } from "./devices.json"; 25 | 26 | export class DevicesDatabase { 27 | #devices = database; 28 | 29 | constructor() { } 30 | 31 | populateDeviceList(list) { 32 | this.#devices.forEach((fam, famIdx) => { 33 | const grp = document.createElement("optgroup"); 34 | grp.setAttribute("label", fam["family"]); 35 | 36 | fam["devices"].forEach((dev, devIdx) => { 37 | const opt = document.createElement("option"); 38 | opt.setAttribute("value", famIdx.toString() + ":" + devIdx.toString()); 39 | opt.textContent = dev["name"] + " (" + dev["package"] + ", " + Formatter.byteSize(dev["flash"]["size"]) + ")"; 40 | grp.appendChild(opt); 41 | }); 42 | 43 | list.appendChild(grp); 44 | }); 45 | } 46 | 47 | findDeviceByIndex(val) { 48 | const [famIdx, devIdx] = val.split(":").map((str) => Number.parseInt(str)); 49 | 50 | if(famIdx >= 0 && devIdx >= 0) { 51 | const family = this.#devices.at(famIdx); 52 | if(family) { 53 | const device = family["devices"].at(devIdx); 54 | if(device) { 55 | return device; 56 | } 57 | } 58 | } 59 | 60 | throw new Error("Device not found or invalid index string"); 61 | } 62 | 63 | findDeviceIndexByName(name) { 64 | name = name.trim().toLowerCase(); 65 | 66 | let famIdx, devIdx; 67 | 68 | famIdx = this.#devices.findIndex((fam) => { 69 | devIdx = fam["devices"].findIndex((dev) => dev["name"].toLowerCase() === name); 70 | return (devIdx >= 0); 71 | }); 72 | 73 | return (famIdx >= 0 && devIdx >= 0 ? famIdx + ":" + devIdx : null); 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /modules/logger.js: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * 3 | * WCH RISC-V Microcontroller Web Serial ISP 4 | * Copyright (c) 2024 Basil Hussain 5 | * 6 | * This program is free software: you can redistribute it and/or modify it under 7 | * the terms of the GNU Affero General Public License as published by the Free 8 | * Software Foundation, either version 3 of the License, or (at your option) any 9 | * later version. 10 | * 11 | * This program is distributed in the hope that it will be useful, but WITHOUT 12 | * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 13 | * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more 14 | * details. 15 | * 16 | * You should have received a copy of the GNU Affero General Public License 17 | * along with this program. If not, see . 18 | * 19 | * SPDX-License-Identifier: AGPL-3.0-or-later 20 | * 21 | ******************************************************************************/ 22 | 23 | export class LoggerLevel { 24 | static Info = new LoggerLevel("Info", " INFO"); 25 | static Warning = new LoggerLevel("Warning", " WARN"); 26 | static Error = new LoggerLevel("Error", "ERROR"); 27 | static Debug = new LoggerLevel("Debug", "DEBUG"); 28 | 29 | #name; 30 | #shortName; 31 | 32 | constructor(name, shortName) { 33 | this.#name = name; 34 | this.#shortName = shortName; 35 | } 36 | 37 | get name() { 38 | return this.#name; 39 | } 40 | 41 | get shortName() { 42 | return this.#shortName; 43 | } 44 | } 45 | 46 | export class Logger { 47 | #output = console.log; 48 | 49 | constructor(outputCallback) { 50 | if(!(outputCallback instanceof Function)) { 51 | throw new Error("Output argument must be a callback function"); 52 | } 53 | this.#output = outputCallback; 54 | } 55 | 56 | #outputMessage(msg, level = undefined) { 57 | if(!(level instanceof LoggerLevel)) level = LoggerLevel.Info; 58 | this.#output(msg, new Date(), level.name, level.shortName); 59 | } 60 | 61 | log(...messages) { 62 | for(const msg of messages) { 63 | this.#outputMessage(msg, LoggerLevel.Info); 64 | } 65 | } 66 | 67 | info(...messages) { 68 | for(const msg of messages) { 69 | this.#outputMessage(msg, LoggerLevel.Info); 70 | } 71 | } 72 | 73 | warn(...messages) { 74 | for(const msg of messages) { 75 | this.#outputMessage(msg, LoggerLevel.Warning); 76 | } 77 | } 78 | 79 | error(...messages) { 80 | for(const msg of messages) { 81 | this.#outputMessage(msg, LoggerLevel.Error); 82 | } 83 | } 84 | 85 | debug(...messages) { 86 | for(const msg of messages) { 87 | this.#outputMessage(msg, LoggerLevel.Debug); 88 | } 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # WCH RISC-V Microcontroller Web Serial ISP 2 | 3 | This is a serial ISP flashing tool for WCH RISC-V microcontrollers that runs in a web browser. Entirely self-contained, with no additional software, libraries, or drivers required. 4 | 5 | It uses the JavaScript [Web Serial](https://developer.mozilla.org/en-US/docs/Web/API/SerialPort) browser API, and so requires support for this feature by the browser. At time of writing, only the following browsers feature support for the Web Serial API: Chrome version 89+, Edge version 89+, Opera version 76+. This tool does not work in FireFox and Safari, due to lack of support for the API. 6 | 7 | > [!NOTE] 8 | > **You can find a hosted version of this tool on my website, at: [https://www.stasisleak.uk/wchisp/](https://www.stasisleak.uk/wchisp/).** 9 | 10 | ## Features 11 | 12 | * Connect using any available serial port (e.g. COM/TTY) interface. 13 | * Write, verify, and erase user application flash. 14 | * Read and write configuration option bytes. 15 | * Loads firmware images in these formats: 16 | * Intel Hex 17 | * S-Record 18 | * ELF 19 | * Raw binary 20 | * Load firmware from local file or external URL. 21 | * Can take query string parameters to auto-select device and/or auto-load firmware from URL. 22 | * Hex preview listing of loaded firmware image. 23 | * Optional DTR/RTS sequence for auto-reset into bootloader. 24 | 25 | Currently supported RISC-V WCH microcontrollers: 26 | 27 | * CH32V00x 28 | * CH32L103 29 | * CH32V103 30 | * CH32V20x 31 | * CH32V30x 32 | * CH32X03x 33 | 34 | ## Limitations 35 | 36 | * This tool only works with the WCH factory bootloader. If you have overwritten a chip's bootloader code (the 'BOOT' flash area) with a custom bootloader, this tool will not be compatible. 37 | * The WCH bootloader protocol does not support *reading* user application flash. There is no command within the bootloader to do so. 38 | * Native USB communication is not supported. 39 | 40 | ## Building 41 | 42 | > [!NOTE] 43 | > **A pre-built copy can be found in the Releases section of the GitHub repository.** 44 | 45 | Building requires the bundling tool [esbuild](https://esbuild.github.io/), a copy of which will need to be installed in a `tools` sub-folder of the project - see below for details. 46 | 47 | ### Windows 48 | 49 | You must have a copy of the `esbuild.exe` binary executable in a `tools\esbuild` sub-folder. 50 | 51 | 1. Open a command prompt in the project folder. 52 | 2. Run `build.bat`. 53 | 3. The resultant HTML, JS, and CSS files will be output to the `dist` sub-folder. 54 | 55 | ### Linux 56 | 57 | You must have a copy of the `esbuild` binary executable in a `tools/esbuild/bin` sub-folder. 58 | 59 | 1. Open a terminal and navigate to the project folder. 60 | 2. Run `build.sh`. You may need to first add 'execute' permissions to the script file (e.g. `chmod a+x build.sh`). 61 | 3. The resultant HTML, JS, and CSS files will be output to the `dist` sub-folder. 62 | 63 | The Linux build script may also be useful on other Unix-like platforms - e.g. Mac, BSDs, etc. - but has not been tested with any of them. 64 | 65 | ## Running 66 | 67 | If you downloaded a pre-built release, first extract the contents of the zip file to a location of your choice. 68 | 69 | Open in your web browser the `index.html` file from the `dist` folder. 70 | 71 | If you want to deploy a copy of this tool to be hosted on your own web server, simply upload all files within the `dist` folder to a location of your choice on your web server. 72 | 73 | ## Licence 74 | 75 | This work is licenced under the [GNU Affero General Public License v3.0](https://www.gnu.org/licenses/agpl-3.0.html). See LICENSE.txt for details. 76 | -------------------------------------------------------------------------------- /modules/packet.js: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * 3 | * WCH RISC-V Microcontroller Web Serial ISP 4 | * Copyright (c) 2024 Basil Hussain 5 | * 6 | * This program is free software: you can redistribute it and/or modify it under 7 | * the terms of the GNU Affero General Public License as published by the Free 8 | * Software Foundation, either version 3 of the License, or (at your option) any 9 | * later version. 10 | * 11 | * This program is distributed in the hope that it will be useful, but WITHOUT 12 | * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 13 | * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more 14 | * details. 15 | * 16 | * You should have received a copy of the GNU Affero General Public License 17 | * along with this program. If not, see . 18 | * 19 | * SPDX-License-Identifier: AGPL-3.0-or-later 20 | * 21 | ******************************************************************************/ 22 | 23 | import { Command } from "./command.js"; 24 | import { ResponseType } from "./response.js"; 25 | import { Formatter } from "./util.js"; 26 | 27 | export class PacketType { 28 | static Command = new PacketType('Command', [0x57, 0xAB]); 29 | static Response = new PacketType('Response', [0x55, 0xAA]); 30 | 31 | #name; 32 | #header; 33 | 34 | constructor(name, header) { 35 | this.#name = name; 36 | this.#header = header; 37 | } 38 | 39 | toString() { 40 | return "PacketType." + this.#name; 41 | } 42 | 43 | get header() { 44 | return this.#header; 45 | } 46 | } 47 | 48 | export class Packet { 49 | #type; 50 | #header = []; 51 | #payload = []; 52 | #checksum = 0; 53 | 54 | constructor(payload, type = PacketType.Command) { 55 | this.#type = type; 56 | this.#header = type.header; 57 | this.#payload = payload; 58 | this.#checksum = this.calculateChecksum(); 59 | } 60 | 61 | calculateChecksum() { 62 | return this.#payload.reduce((acc, val) => acc = (acc + val) % 256, 0); 63 | } 64 | 65 | // TODO: maybe change this to a read-only property? 66 | isValid() { 67 | return ( 68 | this.#header.length == this.#type.header.length && 69 | this.#header.every((val, idx) => val == this.#type.header[idx]) && 70 | this.#checksum == this.calculateChecksum() 71 | ); 72 | } 73 | 74 | toBytes() { 75 | const packet = new Uint8Array(this.#payload.length + 3); 76 | packet.set(this.#header, 0); 77 | packet.set(this.#payload, 2); 78 | packet[this.#payload.length + 2] = this.#checksum; 79 | return packet; 80 | } 81 | 82 | toString() { 83 | let str = ""; 84 | str += Formatter.hex(this.#header, 2); 85 | str += Formatter.hex(this.#payload, 2); 86 | str += Formatter.hex(this.#checksum, 2); 87 | return str; 88 | } 89 | 90 | get length() { 91 | return this.#header.length + this.#payload.length + 1; 92 | } 93 | 94 | get payload() { 95 | return this.#payload; 96 | } 97 | 98 | static fromCommand(cmd) { 99 | return new this(cmd.toBytes()); 100 | } 101 | 102 | static fromBytes(bytes) { 103 | if(bytes.length >= 3) { 104 | const packet = new this(bytes.slice(2, -1), PacketType.Response); 105 | packet.#header = bytes.slice(0, 2); 106 | packet.#checksum = bytes.at(-1); 107 | return packet; 108 | } else { 109 | return undefined; 110 | } 111 | } 112 | 113 | static sizeForResponseType(type) { 114 | return type.size + 3; 115 | } 116 | } 117 | 118 | export class InvalidPacketError extends Error { 119 | constructor() { 120 | super("Invalid packet; bad header or checksum"); 121 | } 122 | } 123 | -------------------------------------------------------------------------------- /modules/util.js: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * 3 | * WCH RISC-V Microcontroller Web Serial ISP 4 | * Copyright (c) 2024 Basil Hussain 5 | * 6 | * This program is free software: you can redistribute it and/or modify it under 7 | * the terms of the GNU Affero General Public License as published by the Free 8 | * Software Foundation, either version 3 of the License, or (at your option) any 9 | * later version. 10 | * 11 | * This program is distributed in the hope that it will be useful, but WITHOUT 12 | * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 13 | * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more 14 | * details. 15 | * 16 | * You should have received a copy of the GNU Affero General Public License 17 | * along with this program. If not, see . 18 | * 19 | * SPDX-License-Identifier: AGPL-3.0-or-later 20 | * 21 | ******************************************************************************/ 22 | 23 | const BYTE_UNITS = ["B", "KiB", "MiB"]; 24 | 25 | export class Formatter { 26 | static hex(values, minLen = 0) { 27 | // Check if values argument is iterable with reduce() - e.g. Array, 28 | // Uint8Array, etc. Otherwise, make it a single element array. 29 | if(!values.reduce) values = [values]; 30 | 31 | // Hexadecimal encode and pad with zeroes to given minimum length. 32 | return values.reduce((str, val) => { 33 | return str + val.toString(16).padStart(minLen, "0"); 34 | }, "").toUpperCase(); 35 | } 36 | 37 | static binary(values) { 38 | // Check if values argument is iterable with reduce() - e.g. Array, 39 | // Uint8Array, etc. Otherwise, make it a single element array. 40 | if(!values.reduce) values = [values]; 41 | 42 | return values.reduce((str, val) => str + val.toString(2), ""); 43 | } 44 | 45 | static printableText(values, non = ".") { 46 | // Check if values argument is iterable with reduce() - e.g. Array, 47 | // Uint8Array, etc. Otherwise, make it a single element array. 48 | if(!values.reduce) values = [values]; 49 | 50 | // Only output text for printable ASCII characters, otherwise supplied 51 | // non-printable character string argument. 52 | return values.reduce((str, val) => { 53 | return str + ((val >= 0x20 && val <= 0x7E) ? String.fromCharCode(val) : non); 54 | }, ""); 55 | } 56 | 57 | static byteSize(value) { 58 | const exponent = Math.min(Math.floor(Math.log(value) / Math.log(1024)), BYTE_UNITS.length - 1); 59 | value /= 1024 ** exponent; 60 | return value.toLocaleString() + " " + BYTE_UNITS[exponent]; 61 | } 62 | } 63 | 64 | export class Delay { 65 | static milliseconds(ms) { 66 | return new Promise((r) => setTimeout(r, ms)); 67 | } 68 | } 69 | 70 | export class ContentDispositionDecoder { 71 | static #entityDecode(str) { 72 | return new Uint8Array( 73 | // Find all percent-hex-encoded values, or regular characters, and 74 | // decode the hex digits to, or convert chars to, integers. 75 | str 76 | .match(/((?:%[0-9a-fA-F]{2})|.)/g) 77 | .map((val) => val.startsWith("%") ? parseInt(val.slice(-2), 16) : val.charCodeAt(0)) 78 | ); 79 | } 80 | 81 | static #getFilenameParam(str) { 82 | let name = null; 83 | 84 | // Look for a filename parameter with either a quoted or plain name. 85 | // Capture two groups: first will be quoted name, or second will be 86 | // plain name. 87 | const match = str.match(/filename=(?:"((?:[^"]|\\")+)"|([^ ]+))(?:;|$)/); 88 | 89 | if(match) { 90 | if(match[1]) { 91 | // For a quoted name, replace all backslash-escaped characters 92 | // with the plain character. 93 | name = match[1].replaceAll(/\\(.)/g, "$1"); 94 | } else if(match[2]) { 95 | name = match[2]; 96 | } 97 | } 98 | 99 | return name; 100 | } 101 | 102 | static #getEncodedFilenameParam(str) { 103 | let name = null; 104 | 105 | // Look for a filename parameter encoded according to RFC5987, section 106 | // 3.2 - with charset, optional language, and entity-encoded name. 107 | // Capture three groups, one for each of the aforementioned values. 108 | const match = str.match(/filename\*=([\w-]+)'([\w-]*)'(.+?)(?:;|$)/); 109 | 110 | if(match && match[1] && match[3]) { 111 | // Decode the name using the given charset. 112 | const bytes = this.#entityDecode(match[3]); 113 | name = new TextDecoder(match[1]).decode(bytes); 114 | } 115 | 116 | return name; 117 | } 118 | 119 | static getFilename(value) { 120 | // In order of priority, return either: 121 | // 1. an encoded "filename*=" parameter, or; 122 | // 2. a plain or quoted-string "filename=" parameter, or; 123 | // 3. a default name if neither of the above could be found. 124 | return this.#getEncodedFilenameParam(value) || this.#getFilenameParam(value) || "[unknown]"; 125 | } 126 | } 127 | -------------------------------------------------------------------------------- /modules/parsers/intelhex.js: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * 3 | * WCH RISC-V Microcontroller Web Serial ISP 4 | * Copyright (c) 2024 Basil Hussain 5 | * 6 | * This program is free software: you can redistribute it and/or modify it under 7 | * the terms of the GNU Affero General Public License as published by the Free 8 | * Software Foundation, either version 3 of the License, or (at your option) any 9 | * later version. 10 | * 11 | * This program is distributed in the hope that it will be useful, but WITHOUT 12 | * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 13 | * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more 14 | * details. 15 | * 16 | * You should have received a copy of the GNU Affero General Public License 17 | * along with this program. If not, see . 18 | * 19 | * SPDX-License-Identifier: AGPL-3.0-or-later 20 | * 21 | ******************************************************************************/ 22 | 23 | class IntelHexRecordType { 24 | static Data = new this("Data", 0); 25 | static EndOfFile = new this("End Of File", 1); 26 | static ExtSegmentAddr = new this("Extended Segment Address", 2); 27 | static StartSegmentAddr = new this("Start Segment Address", 3); 28 | static ExtLinearAddr = new this("Extended Linear Address", 4); 29 | static StartLinearAddr = new this("Start Linear Address", 5); 30 | 31 | #name; 32 | #value; 33 | 34 | constructor(name, value) { 35 | this.#name = name; 36 | this.#value = value; 37 | } 38 | 39 | get name() { 40 | return this.#name; 41 | } 42 | 43 | get value() { 44 | return this.#value; 45 | } 46 | 47 | static isValidType(value) { 48 | for(let t in this) { 49 | if(this[t].#value == value) return true; 50 | } 51 | return false; 52 | } 53 | } 54 | 55 | export class IntelHexParser { 56 | static #calcRecordChecksum(bytes) { 57 | return (~bytes.reduce((sum, val) => sum = (sum + val) % 256, 0) + 1) & 0xFF; 58 | } 59 | 60 | static parse(txt, maxSize = 1048576, minSize = 64, fillVal = 0xFF) { 61 | const lines = txt.split(/\r\n|\r|\n/); 62 | const output = new ArrayBuffer(minSize, { maxByteLength: maxSize }); 63 | let idx = 0, eof = false, addrBase = 0; 64 | 65 | // Because buffer is resizeable, this array view of it will always track 66 | // its length whenever the buffer is resized, so we can create one now 67 | // and use it later to fill resized areas. 68 | const filler = new Uint8Array(output); 69 | filler.fill(fillVal); 70 | 71 | for(const line of lines) { 72 | ++idx; 73 | 74 | // Skip blank lines. 75 | if(line.length == 0) continue; 76 | 77 | // Does the line meet the minimum length for a record, and does it 78 | // begin with a record start indicator? 79 | if(line.length < 11 || line[0] != ':') { 80 | throw new Error("Non-record or incomplete record on line " + idx); 81 | } 82 | 83 | // Parse the record bytes from hex digit pairs, then extract the 84 | // values of the individual fields. 85 | const bytes = new Uint8Array(line.match(/[0-9a-f]{2}/gi).map((hex) => Number.parseInt(hex, 16))); 86 | const count = bytes.at(0); 87 | const addr = new DataView(bytes.buffer, 1, 2).getUint16(0); 88 | const type = bytes.at(3); 89 | const data = bytes.subarray(4, -1); 90 | const checksum = bytes.at(-1); 91 | 92 | // Check the record is valid and bail out if not. 93 | if(count != data.length) { 94 | throw new Error("Byte count and length of data mismatch on line " + idx); 95 | } 96 | if(!IntelHexRecordType.isValidType(type)) { 97 | throw new Error("Invalid record type on line " + idx); 98 | } 99 | if(this.#calcRecordChecksum(bytes.subarray(0, -1)) != checksum) { 100 | throw new Error("Checksum mismatch on line " + idx); 101 | } 102 | 103 | switch(type) { 104 | case IntelHexRecordType.Data.value: 105 | // Resize the buffer if necessary (will throw exception 106 | // if max size exceeded), then fill resized area, and 107 | // finally stuff the data into it at the specified offset. 108 | if(addrBase + addr + count > output.byteLength) { 109 | const fillFrom = output.byteLength; 110 | try { 111 | output.resize(addrBase + addr + count); 112 | } catch(err) { 113 | if(err instanceof RangeError) { 114 | err = new Error("Maximum size of " + output.maxByteLength.toLocaleString() + " bytes exceeded"); 115 | } 116 | throw err; 117 | } 118 | filler.fill(fillVal, fillFrom); 119 | } 120 | new Uint8Array(output, addrBase + addr, count).set(data); 121 | break; 122 | case IntelHexRecordType.EndOfFile.value: 123 | eof = true; 124 | break; 125 | case IntelHexRecordType.ExtSegmentAddr.value: 126 | throw new Error("Extended Segment Address record type not supported"); 127 | break; 128 | case IntelHexRecordType.StartSegmentAddr.value: 129 | throw new Error("Start Segment Address record type not supported"); 130 | break; 131 | case IntelHexRecordType.ExtLinearAddr.value: 132 | // Record's data bytes are the upper 16 bits (i.e. base 133 | // address) of the address of all subsequent records. 134 | addrBase = new DataView(bytes.buffer, 4, 2).getUint16(0) << 16; 135 | break; 136 | case IntelHexRecordType.StartLinearAddr.value: 137 | // Ignored, do nothing. 138 | break; 139 | } 140 | 141 | if(eof) break; 142 | } 143 | 144 | // Did we parse all file lines without encountering an EOF record? 145 | if(!eof) throw new Error("Unexpected end of file (missing EOF record) on line " + idx); 146 | 147 | return new Uint8Array(output); 148 | } 149 | 150 | static get forText() { 151 | return true; 152 | } 153 | 154 | static get formatName() { 155 | return "Intel Hex"; 156 | } 157 | } 158 | -------------------------------------------------------------------------------- /modules/parsers/elf.js: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * 3 | * WCH RISC-V Microcontroller Web Serial ISP 4 | * Copyright (c) 2024 Basil Hussain 5 | * 6 | * This program is free software: you can redistribute it and/or modify it under 7 | * the terms of the GNU Affero General Public License as published by the Free 8 | * Software Foundation, either version 3 of the License, or (at your option) any 9 | * later version. 10 | * 11 | * This program is distributed in the hope that it will be useful, but WITHOUT 12 | * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 13 | * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more 14 | * details. 15 | * 16 | * You should have received a copy of the GNU Affero General Public License 17 | * along with this program. If not, see . 18 | * 19 | * SPDX-License-Identifier: AGPL-3.0-or-later 20 | * 21 | ******************************************************************************/ 22 | 23 | const ELF_MAGIC = 0x7F454C46; // 0x7F, 'E', 'L', 'F' 24 | const ELF_CLASS_32BIT = 0x1; 25 | const ELF_DATA_LITTLE_ENDIAN = 0x1; 26 | const ELF_IDENT_VERSION_V1 = 0x1; 27 | const ELF_TYPE_EXECUTABLE = 0x2; 28 | const ELF_MACHINE_RISCV = 0xF3; 29 | const ELF_VERSION_V1 = 0x1; 30 | const ELF_SECTION_TYPE_LOADABLE = 0x1; 31 | const ELF_HEADER_SIZE = 52; 32 | const ELF_PROGRAM_HEADER_SIZE = 32; 33 | 34 | export class ElfRiscVParser { 35 | static parse(buf, maxSize = 1048576, minSize = 64, fillVal = 0xFF) { 36 | const output = new ArrayBuffer(minSize, { maxByteLength: maxSize }); 37 | 38 | // Because buffer is resizeable, this array view of it will always track 39 | // its length whenever the buffer is resized, so we can create one now 40 | // and use it later to fill resized areas. 41 | const filler = new Uint8Array(output); 42 | filler.fill(fillVal); 43 | 44 | const header = new DataView(buf, 0, ELF_HEADER_SIZE); 45 | 46 | // Check ELF header information to ensure we're dealing with a suitable 47 | // kind of ELF file. 48 | if(header.getUint32(0, false) !== ELF_MAGIC) throw new Error("Not an ELF file; non-matching magic bytes"); 49 | if(header.getUint8(4) !== ELF_CLASS_32BIT) throw new Error("ELF must be 32-bit; 64-bit unsupported"); 50 | if(header.getUint8(5) !== ELF_DATA_LITTLE_ENDIAN) throw new Error("ELF must be in little-endian format; big-endian unsupported"); 51 | if(header.getUint8(6) !== ELF_IDENT_VERSION_V1) throw new Error("ELF ident version must be 1"); 52 | if(header.getUint16(16, true) !== ELF_TYPE_EXECUTABLE) throw new Error("ELF object type is not executable"); 53 | if(header.getUint16(18, true) !== ELF_MACHINE_RISCV) throw new Error("ELF machine ISA is not RISC-V"); 54 | if(header.getUint32(20, true) !== ELF_VERSION_V1) throw new Error("ELF version must be 1"); 55 | if(header.getUint16(40, true) !== ELF_HEADER_SIZE) throw new Error("ELF header size is unusual; not " + ELF_HEADER_SIZE + " bytes"); // Not sure if this worth validating? 56 | 57 | // const entryPoint = header.getUint32(24, true); 58 | const programHeaderOffset = header.getUint32(28, true); 59 | // const sectionHeaderOffset = header.getUint32(32, true); 60 | const programHeaderSize = header.getUint16(42, true); 61 | const programHeaderCount = header.getUint16(44, true); 62 | 63 | // console.debug(programHeaderOffset, programHeaderSize, programHeaderCount); 64 | 65 | // Sanity check the program header information. 66 | if(programHeaderSize !== ELF_PROGRAM_HEADER_SIZE) throw new Error("Unusual program header table entry size; not " + ELF_PROGRAM_HEADER_SIZE + " bytes"); 67 | if(programHeaderCount === 0) throw new Error("Program header table entry count is zero"); 68 | if((programHeaderOffset < ELF_HEADER_SIZE) || (programHeaderOffset >= buf.byteLength - (programHeaderSize * programHeaderCount))) { 69 | throw new Error("Invalid program header table offset"); 70 | } 71 | 72 | for(let i = 0; i < programHeaderCount; i++) { 73 | const progHeader = new DataView(buf, programHeaderOffset + (i * programHeaderSize), programHeaderSize); 74 | 75 | const type = progHeader.getUint32(0, true); 76 | const offset = progHeader.getUint32(4, true); 77 | const virtualAddr = progHeader.getUint32(8, true); 78 | const physicalAddr = progHeader.getUint32(12, true); 79 | const fileSize = progHeader.getUint32(16, true); 80 | const memSize = progHeader.getUint32(20, true); 81 | const flags = progHeader.getUint32(24, true); 82 | 83 | // console.debug(type, offset, virtualAddr, physicalAddr, fileSize, memSize, flags); 84 | 85 | // Ensure it's a loadable segment comprised of some data in the ELF 86 | // file. Ignore other segments, as they are other stuff that doesn't 87 | // need to be loaded. 88 | if(type === ELF_SECTION_TYPE_LOADABLE && fileSize > 0) { 89 | if(offset >= buf.byteLength) throw new Error("Invalid segment offset; past end of file"); 90 | 91 | // Resize the output buffer if necessary (will throw exception 92 | // if max size exceeded), then fill resized area, and finally 93 | // stuff the segment's data into it at the specified address. 94 | if(physicalAddr + fileSize > output.byteLength) { 95 | const fillFrom = output.byteLength; 96 | try { 97 | output.resize(physicalAddr + fileSize); 98 | } catch(err) { 99 | if(err instanceof RangeError) { 100 | err = new Error("Maximum size of " + output.maxByteLength.toLocaleString() + " bytes exceeded"); 101 | } 102 | throw err; 103 | } 104 | filler.fill(fillVal, fillFrom); 105 | } 106 | const data = new Uint8Array(buf, offset, fileSize); 107 | new Uint8Array(output, physicalAddr, fileSize).set(data); 108 | } 109 | } 110 | 111 | return new Uint8Array(output); 112 | } 113 | 114 | static get forText() { 115 | return false; 116 | } 117 | 118 | static get formatName() { 119 | return "ELF"; 120 | } 121 | } 122 | -------------------------------------------------------------------------------- /modules/transceiver.js: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * 3 | * WCH RISC-V Microcontroller Web Serial ISP 4 | * Copyright (c) 2025 Basil Hussain 5 | * 6 | * This program is free software: you can redistribute it and/or modify it under 7 | * the terms of the GNU Affero General Public License as published by the Free 8 | * Software Foundation, either version 3 of the License, or (at your option) any 9 | * later version. 10 | * 11 | * This program is distributed in the hope that it will be useful, but WITHOUT 12 | * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 13 | * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more 14 | * details. 15 | * 16 | * You should have received a copy of the GNU Affero General Public License 17 | * along with this program. If not, see . 18 | * 19 | * SPDX-License-Identifier: AGPL-3.0-or-later 20 | * 21 | ******************************************************************************/ 22 | 23 | import { Packet } from "./packet.js"; 24 | import { Delay } from "./util.js"; 25 | 26 | // Some USB-UART interfaces for unknown reason don't like to have their port 27 | // reading stream flushed and will hang indefinitely and not return from 28 | // readable.cancel(). This shall be a list of USB devices for which we will 29 | // avoid doing that. 30 | // 31 | // Tested works with flush: 32 | // - Non-USB COM port (e.g. mobo on-board) 33 | // - WCHLink-E COM port: USB\VID_1A86&PID_8010&MI_01 34 | // - WCH CH340G: USB\VID_1A86&PID_7523 35 | // - FTDI FT2232H: FTDIBUS\COMPORT&VID_0403&PID_6010 36 | // Doesn't work: 37 | // - Silabs CP2102N: USB\VID_10C4&PID_EA60 38 | const PORT_FLUSH_BLOCKLIST = [ 39 | // Silicon Labs CP2102N 40 | { vid: 0x10C4, pid: 0xEA60 }, 41 | { vid: 0x10C4, pid: 0xEA61 }, 42 | { vid: 0x10C4, pid: 0xEA63 }, 43 | ]; 44 | 45 | export class Transceiver { 46 | #port; 47 | #dtrRtsReset = false; 48 | 49 | constructor(dtrRtsReset = false) { 50 | this.#dtrRtsReset = dtrRtsReset; 51 | } 52 | 53 | #canFlushPort(vid, pid) { 54 | // If the given VID/PID are in the list, we should not attempt to flush. 55 | return !PORT_FLUSH_BLOCKLIST.some((elem) => elem.vid === vid && elem.pid === pid); 56 | } 57 | 58 | async #resetWithDtrRts(resetPeriodMs = 100, delayPeriodMs = 100) { 59 | // When target device is equipped with ESP-style auto-reset circuit to 60 | // manipulate RST, BOOT0/1 lines, toggle DTR and RTS serial control 61 | // signals in a sequence to get the device to reset and enter 62 | // the bootloader. 63 | try { 64 | await this.#port.setSignals({ 65 | dataTerminalReady: false, 66 | requestToSend: true 67 | }); 68 | await Delay.milliseconds(resetPeriodMs); 69 | await this.#port.setSignals({ 70 | dataTerminalReady: true, 71 | requestToSend: false 72 | }); 73 | await Delay.milliseconds(delayPeriodMs); 74 | await this.#port.setSignals({ 75 | dataTerminalReady: false 76 | }); 77 | } catch(err) { 78 | throw new Error("Error occurred attempting to toggle DTR/RTS sequence for reset into bootloader", { cause: err }); 79 | } 80 | } 81 | 82 | async open() { 83 | if(!("serial" in navigator)) { 84 | throw new Error("Web Serial API is unsupported by this browser"); 85 | } 86 | 87 | try { 88 | this.#port = await navigator.serial.requestPort(); 89 | } catch(err) { 90 | throw new Error("Serial port selection cancelled or permission denied", { cause: err }); 91 | } 92 | 93 | const portInfo = this.#port.getInfo(); 94 | 95 | try { 96 | await this.#port.open({ 97 | baudRate: 115200, 98 | dataBits: 8, 99 | stopBits: 1, 100 | parity: "none", 101 | flowControl: "none" 102 | }); 103 | 104 | if(this.#canFlushPort(portInfo.usbVendorId, portInfo.usbProductId)) { 105 | // Flush the port's reading stream. For some reason, sometimes 106 | // spurious bytes are already waiting, which messes up receiving 107 | // packets (because more data than expected is received). 108 | await this.#port.readable.cancel(); 109 | } 110 | } catch(err) { 111 | throw new Error("Error occurred attempting to open serial port", { cause: err }); 112 | } 113 | 114 | if(this.#dtrRtsReset) { 115 | await this.#resetWithDtrRts(); 116 | } 117 | } 118 | 119 | async transmitPacket(packet) { 120 | const writer = this.#port.writable.getWriter(); 121 | 122 | await writer.write(packet.toBytes()); 123 | 124 | writer.releaseLock(); 125 | } 126 | 127 | async receivePacket(length, timeout_ms = 3000) { 128 | const bytes = new Uint8Array(length); 129 | let offset = 0, stop = false, error; 130 | // let iterations = 0; 131 | 132 | const reader = this.#port.readable.getReader(); 133 | 134 | const timer = setTimeout(() => { 135 | // Timeout expired, so stop reading by releasing the reader lock. 136 | // This will cause any waiting reader.read() to throw an error. 137 | stop = true; 138 | reader.releaseLock(); 139 | }, timeout_ms); 140 | 141 | while(!stop && offset < bytes.length) { 142 | try { 143 | const { value: chunk, done } = await reader.read(); 144 | 145 | // console.debug(iterations, chunk); 146 | 147 | if(done) break; 148 | if(offset + chunk.length <= bytes.length) { 149 | bytes.set(chunk, offset); 150 | offset += chunk.length; 151 | } else { 152 | error = new Error("Unexpected data; received more than " + bytes.length + " bytes"); 153 | break; 154 | } 155 | } catch(err) { 156 | // Catch the error thrown by the reader on timeout (or other 157 | // error) and re-throw a more suitable error. 158 | error = new Error("Timed-out after " + timeout_ms + " ms waiting to receive, or read failure", { cause: err }); 159 | break; 160 | } 161 | 162 | // iterations++; 163 | } 164 | 165 | clearTimeout(timer); 166 | reader.releaseLock(); 167 | 168 | if(error) throw error; 169 | 170 | return Packet.fromBytes(bytes); 171 | } 172 | 173 | async close() { 174 | if(this.#port !== undefined) { 175 | await this.#port.close(); 176 | } 177 | } 178 | } 179 | -------------------------------------------------------------------------------- /modules/response.js: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * 3 | * WCH RISC-V Microcontroller Web Serial ISP 4 | * Copyright (c) 2024 Basil Hussain 5 | * 6 | * This program is free software: you can redistribute it and/or modify it under 7 | * the terms of the GNU Affero General Public License as published by the Free 8 | * Software Foundation, either version 3 of the License, or (at your option) any 9 | * later version. 10 | * 11 | * This program is distributed in the hope that it will be useful, but WITHOUT 12 | * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 13 | * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more 14 | * details. 15 | * 16 | * You should have received a copy of the GNU Affero General Public License 17 | * along with this program. If not, see . 18 | * 19 | * SPDX-License-Identifier: AGPL-3.0-or-later 20 | * 21 | ******************************************************************************/ 22 | 23 | import { Packet } from "./packet.js"; 24 | 25 | export class ResponseType { 26 | static Identify = new ResponseType("Identify", 0xA1, 6); 27 | static End = new ResponseType("End", 0xA2, 6); 28 | static Key = new ResponseType("Key", 0xA3, 6); 29 | static FlashErase = new ResponseType("FlashErase", 0xA4, 6); 30 | static FlashWrite = new ResponseType("FlashWrite", 0xA5, 6); 31 | static FlashVerify = new ResponseType("FlashVerify", 0xA6, 6); 32 | static ConfigRead = new ResponseType("ConfigRead", 0xA7, 30); 33 | static ConfigWrite = new ResponseType("ConfigWrite", 0xA8, 6); 34 | 35 | #name; 36 | #code; 37 | #size; 38 | 39 | constructor(name, code, size) { 40 | this.#name = name; 41 | this.#code = code; 42 | this.#size = size; 43 | } 44 | 45 | toString() { 46 | return "ResponseType." + this.#name; 47 | } 48 | 49 | get code() { 50 | return this.#code; 51 | } 52 | 53 | get size() { 54 | return this.#size; 55 | } 56 | 57 | static fromCode(code) { 58 | for(let t in ResponseType) { 59 | if(ResponseType[t].#code == code) return ResponseType[t]; 60 | } 61 | return undefined; 62 | } 63 | } 64 | 65 | export class Response { 66 | #type; 67 | #data = []; 68 | #length = 0; 69 | 70 | constructor(type, data, length = data.length) { 71 | this.#type = type; 72 | this.#data = data; 73 | this.#length = length; 74 | } 75 | 76 | // TODO: maybe change this to a read-only property? 77 | isValid() { 78 | return ( 79 | this.#type instanceof ResponseType && 80 | this.#length > 0 && 81 | this.#data.length > 0 && 82 | this.#length == this.#data.length 83 | ); 84 | } 85 | 86 | get data() { 87 | return this.#data; 88 | } 89 | 90 | get length() { 91 | return this.#length; 92 | } 93 | 94 | static fromPacket(packet) { 95 | return this.fromBytes(packet.payload); 96 | } 97 | 98 | static fromBytes(bytes) { 99 | if(bytes.length >= 4) { 100 | return new this( 101 | ResponseType.fromCode(bytes[0]), 102 | bytes.slice(4), 103 | new DataView(bytes.buffer).getUint16(2, true) // little-endian 104 | ); 105 | } else { 106 | return undefined; 107 | } 108 | } 109 | } 110 | 111 | export class IdentifyResponse extends Response { 112 | get success() { 113 | // Bootloader returns 0xF1 for incorrect password. 114 | return (this.length == 2 && this.data[0] < 0xF0); 115 | } 116 | 117 | get deviceVariant() { 118 | return this.data[0]; 119 | } 120 | 121 | get deviceType() { 122 | return this.data[1]; 123 | } 124 | } 125 | 126 | export class EndResponse extends Response { 127 | get success() { 128 | return (this.length == 2 && this.data[0] == 0x00); 129 | } 130 | } 131 | 132 | export class KeyResponse extends Response { 133 | get success() { 134 | // Bootloader returns 0xFE for seed too short. 135 | // Impossible to differentiate between a key checksum that happens to be 136 | // 0xFE and error response, so instead consider anything non-zero a 137 | // success response. 138 | return (this.length == 2 && this.data[0] > 0x00); 139 | } 140 | 141 | get keyChecksum() { 142 | return this.data[0]; 143 | } 144 | } 145 | 146 | export class FlashEraseResponse extends Response { 147 | get success() { 148 | return (this.length == 2 && this.data[0] == 0x00); 149 | } 150 | } 151 | 152 | export class FlashWriteResponse extends Response { 153 | get success() { 154 | return (this.length == 2 && this.data[0] == 0x00); 155 | } 156 | } 157 | 158 | export class FlashVerifyResponse extends Response { 159 | get success() { 160 | // Bootloader returns 0xF5 or 0xFE on error. 161 | return (this.length == 2 && this.data[0] == 0x00); 162 | } 163 | } 164 | 165 | export class ConfigReadResponse extends Response { 166 | get success() { 167 | // Command always requests 'all' config data (0x1F), so length should 168 | // always be 26. 169 | return (this.length == 26 && this.data[0] > 0x00); 170 | } 171 | 172 | get optionBytesRaw() { 173 | // Return a simple array of the bytes, omitting all of the inverse 'n' 174 | // values. 175 | return [ 176 | this.data[2], this.data[4], this.data[6], this.data[8] 177 | ].concat(Array.from(this.data.subarray(10, 14))); 178 | } 179 | 180 | get optionBytes() { 181 | return { 182 | "rdpr": this.data[2], 183 | "user": this.data[4], 184 | "data": [this.data[6], this.data[8]], 185 | "wrpr": Array.from(this.data.subarray(10, 14)) 186 | }; 187 | } 188 | 189 | get bootloaderVersion() { 190 | return { 191 | "major": (this.data[14] * 10) + this.data[15], 192 | "minor": (this.data[16] * 10) + this.data[17] 193 | }; 194 | } 195 | 196 | get chipUniqueID() { 197 | return this.data.slice(18); 198 | } 199 | } 200 | 201 | export class ConfigWriteResponse extends Response { 202 | get success() { 203 | return (this.length == 2 && this.data[0] == 0x00); 204 | } 205 | } 206 | 207 | export class InvalidResponseError extends Error { 208 | constructor() { 209 | super("Invalid response; unknown type or bad data length"); 210 | } 211 | } 212 | 213 | export class UnsuccessfulResponseError extends Error { 214 | constructor() { 215 | super("Unsuccessful response; command returned error"); 216 | } 217 | } 218 | -------------------------------------------------------------------------------- /modules/parsers/srecord.js: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * 3 | * WCH RISC-V Microcontroller Web Serial ISP 4 | * Copyright (c) 2024 Basil Hussain 5 | * 6 | * This program is free software: you can redistribute it and/or modify it under 7 | * the terms of the GNU Affero General Public License as published by the Free 8 | * Software Foundation, either version 3 of the License, or (at your option) any 9 | * later version. 10 | * 11 | * This program is distributed in the hope that it will be useful, but WITHOUT 12 | * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 13 | * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more 14 | * details. 15 | * 16 | * You should have received a copy of the GNU Affero General Public License 17 | * along with this program. If not, see . 18 | * 19 | * SPDX-License-Identifier: AGPL-3.0-or-later 20 | * 21 | ******************************************************************************/ 22 | 23 | class SRecordRecordType { 24 | static Header = new this("Header", 0); 25 | static Data16BitAddr = new this("Data (16-bit Address)", 1); 26 | static Data24BitAddr = new this("Data (24-bit Address)", 2); 27 | static Data32BitAddr = new this("Data (32-bit Address)", 3); 28 | static Reserved = new this("Reserved", 4); 29 | static RecordCount16Bit = new this("Record Count (16-bit)", 5); 30 | static RecordCount24Bit = new this("Record Count (24-bit)", 6); 31 | static StartAddr32Bit = new this("Start Address (32-bit)", 7); 32 | static StartAddr24Bit = new this("Start Address (24-bit)", 8); 33 | static StartAddr16Bit = new this("Start Address (16-bit)", 9); 34 | 35 | #name; 36 | #value; 37 | 38 | constructor(name, value) { 39 | this.#name = name; 40 | this.#value = value; 41 | } 42 | 43 | get name() { 44 | return this.#name; 45 | } 46 | 47 | get value() { 48 | return this.#value; 49 | } 50 | 51 | static isValidType(value) { 52 | for(let t in this) { 53 | if(this[t].#value == value) return true; 54 | } 55 | return false; 56 | } 57 | } 58 | 59 | export class SRecordParser { 60 | static #calcRecordChecksum(bytes) { 61 | return 0xFF - bytes.reduce((sum, val) => sum = (sum + val) % 256, 0); 62 | } 63 | 64 | static parse(txt, maxSize = 1048576, minSize = 64, fillVal = 0xFF) { 65 | const lines = txt.split(/\r\n|\r|\n/); 66 | const output = new ArrayBuffer(minSize, { maxByteLength: maxSize }); 67 | let idx = 0, eof = false; 68 | 69 | // Because buffer is resizeable, this array view of it will always track 70 | // its length whenever the buffer is resized, so we can create one now 71 | // and use it later to fill resized areas. 72 | const filler = new Uint8Array(output); 73 | filler.fill(fillVal); 74 | 75 | for(const line of lines) { 76 | ++idx; 77 | 78 | // Skip blank lines. 79 | if(line.length == 0) continue; 80 | 81 | // Does the line meet the minimum length for a record, and does it 82 | // begin with a record start indicator? 83 | if(line.length < 10 || line[0] != 'S') { 84 | throw new Error("Non-record or incomplete record on line " + idx); 85 | } 86 | 87 | // Parse the record bytes from hex digit pairs, then extract the 88 | // values of the individual fields. 89 | const type = line.charCodeAt(1) - 0x30; 90 | const bytes = new Uint8Array(line.slice(2).match(/[0-9a-f]{2}/gi).map((hex) => Number.parseInt(hex, 16))); 91 | const count = bytes.at(0); 92 | const checksum = bytes.at(-1); 93 | 94 | // Check the record is valid and bail out if not. 95 | if(!SRecordRecordType.isValidType(type)) { 96 | throw new Error("Invalid record type on line " + idx); 97 | } 98 | if(count != bytes.length - 1) { 99 | throw new Error("Byte count and length of data mismatch on line " + idx); 100 | } 101 | if(this.#calcRecordChecksum(bytes.subarray(0, -1)) != checksum) { 102 | throw new Error("Checksum mismatch on line " + idx); 103 | } 104 | 105 | const mergeDataToOutput = (addr, data) => { 106 | if(addr + data.length > output.byteLength) { 107 | const fillFrom = output.byteLength; 108 | try { 109 | output.resize(addr + data.length); 110 | } catch(err) { 111 | if(err instanceof RangeError) { 112 | err = new Error("Maximum size of " + output.maxByteLength.toLocaleString() + " bytes exceeded"); 113 | } 114 | throw err; 115 | } 116 | filler.fill(fillVal, fillFrom); 117 | } 118 | new Uint8Array(output, addr, data.length).set(data); 119 | }; 120 | 121 | switch(type) { 122 | case SRecordRecordType.Data16BitAddr.value: 123 | mergeDataToOutput( 124 | new DataView(bytes.buffer, 1, 2).getUint16(0), 125 | bytes.subarray(3, -1) 126 | ); 127 | break; 128 | case SRecordRecordType.Data24BitAddr.value: 129 | // There is no 24-bit integer support in DataView, so we 130 | // instead read as a 32-bit integer and shift off the excess 131 | // byte. 132 | mergeDataToOutput( 133 | new DataView(bytes.buffer, 1, 4).getUint32(0) >> 8, 134 | bytes.subarray(4, -1) 135 | ); 136 | break; 137 | case SRecordRecordType.Data32BitAddr.value: 138 | mergeDataToOutput( 139 | new DataView(bytes.buffer, 1, 4).getUint32(0), 140 | bytes.subarray(5, -1) 141 | ); 142 | break; 143 | case SRecordRecordType.Header.value: 144 | case SRecordRecordType.Reserved.value: 145 | case SRecordRecordType.RecordCount16Bit.value: 146 | case SRecordRecordType.RecordCount24Bit.value: 147 | // Ignored, do nothing. 148 | break; 149 | case SRecordRecordType.StartAddr32Bit.value: 150 | case SRecordRecordType.StartAddr24Bit.value: 151 | case SRecordRecordType.StartAddr16Bit.value: 152 | eof = true; 153 | break; 154 | } 155 | 156 | if(eof) break; 157 | } 158 | 159 | // Did we parse all file lines without encountering a termination record? 160 | if(!eof) throw new Error("Unexpected end of file (missing termination record) on line " + idx); 161 | 162 | return new Uint8Array(output); 163 | } 164 | 165 | static get forText() { 166 | return true; 167 | } 168 | 169 | static get formatName() { 170 | return "S-Record"; 171 | } 172 | } 173 | -------------------------------------------------------------------------------- /modules/command.js: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * 3 | * WCH RISC-V Microcontroller Web Serial ISP 4 | * Copyright (c) 2024 Basil Hussain 5 | * 6 | * This program is free software: you can redistribute it and/or modify it under 7 | * the terms of the GNU Affero General Public License as published by the Free 8 | * Software Foundation, either version 3 of the License, or (at your option) any 9 | * later version. 10 | * 11 | * This program is distributed in the hope that it will be useful, but WITHOUT 12 | * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 13 | * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more 14 | * details. 15 | * 16 | * You should have received a copy of the GNU Affero General Public License 17 | * along with this program. If not, see . 18 | * 19 | * SPDX-License-Identifier: AGPL-3.0-or-later 20 | * 21 | ******************************************************************************/ 22 | 23 | export class CommandType { 24 | static Identify = new CommandType("Identify", 0xA1); 25 | static End = new CommandType("End", 0xA2); 26 | static Key = new CommandType("Key", 0xA3); 27 | static FlashErase = new CommandType("FlashErase", 0xA4); 28 | static FlashWrite = new CommandType("FlashWrite", 0xA5); 29 | static FlashVerify = new CommandType("FlashVerify", 0xA6); 30 | static ConfigRead = new CommandType("ConfigRead", 0xA7); 31 | static ConfigWrite = new CommandType("ConfigWrite", 0xA8); 32 | 33 | #name; 34 | #code; 35 | 36 | constructor(name, code) { 37 | this.#name = name; 38 | this.#code = code; 39 | } 40 | 41 | toString() { 42 | return "CommandType." + this.#name; 43 | } 44 | 45 | get code() { 46 | return this.#code; 47 | } 48 | 49 | static isValidCode(code) { 50 | for(let t in CommandType) { 51 | if(CommandType[t].#code == code) return true; 52 | } 53 | return false; 54 | } 55 | } 56 | 57 | export class Command { 58 | #type; 59 | #data = []; 60 | #length = 0; 61 | 62 | constructor(type, data, length = data.length) { 63 | this.#type = type; 64 | this.#data = data; 65 | this.#length = length; 66 | } 67 | 68 | toBytes() { 69 | const buf = new ArrayBuffer(this.#length + 3); 70 | const bytes = new Uint8Array(buf); 71 | 72 | // Set the length in 16-bit little-endian format. 73 | bytes[0] = this.#type.code; 74 | new DataView(buf).setUint16(1, this.#length, true); 75 | bytes.set(this.#data, 3); 76 | 77 | return bytes; 78 | } 79 | 80 | get data() { 81 | return this.#data; 82 | } 83 | 84 | get length() { 85 | return this.#length; 86 | } 87 | } 88 | 89 | export class IdentifyCommand extends Command { 90 | constructor(dev_variant, dev_type) { 91 | const passwd = "MCU ISP & WCH.CN"; 92 | 93 | const data = new Uint8Array(2 + passwd.length); 94 | data[0] = dev_variant; 95 | data[1] = dev_type; 96 | new TextEncoder().encodeInto(passwd, data.subarray(2)); 97 | 98 | super(CommandType.Identify, data); 99 | } 100 | } 101 | 102 | export class EndCommand extends Command { 103 | constructor(do_reset) { 104 | super(CommandType.End, [(do_reset ? 0x01 : 0x00)]); 105 | } 106 | } 107 | 108 | export class KeyCommand extends Command { 109 | #key = new Uint8Array(8); 110 | #key_checksum = 0; 111 | 112 | constructor(unique_id, dev_variant, seed_len = 60) { 113 | // Ensure the given seed length is within allowable bounds, then 114 | // determine parameters for the encryption according to seed length. 115 | // Finally, generate random seed data of the appropriate length. 116 | seed_len = Math.min(Math.max(seed_len, 30), 60); 117 | const a = Math.floor(seed_len / 5); 118 | const b = Math.floor(seed_len / 7); 119 | const seed = crypto.getRandomValues(new Uint8Array(seed_len)); 120 | 121 | super(CommandType.Key, seed); 122 | 123 | // Calculate a simple checksum of all the given unique ID bytes. 124 | const unique_id_checksum = unique_id.reduce((acc, val) => acc = (acc + val) % 256, 0); 125 | 126 | // Calculate the encryption key according to previously determined 127 | // parameters and seed. 128 | this.#key[0] = unique_id_checksum ^ seed[b * 4]; 129 | this.#key[1] = unique_id_checksum ^ seed[a]; 130 | this.#key[2] = unique_id_checksum ^ seed[b]; 131 | this.#key[3] = unique_id_checksum ^ seed[b * 6]; 132 | this.#key[4] = unique_id_checksum ^ seed[b * 3]; 133 | this.#key[5] = unique_id_checksum ^ seed[a * 3]; 134 | this.#key[6] = unique_id_checksum ^ seed[b * 5]; 135 | this.#key[7] = (this.#key[0] + dev_variant) % 256; 136 | 137 | // Calculate a simple checksum of the key. 138 | this.#key_checksum = this.#key.reduce((acc, val) => acc = (acc + val) % 256, 0); 139 | } 140 | 141 | get key() { 142 | return this.#key; 143 | } 144 | 145 | get keyChecksum() { 146 | return this.#key_checksum; 147 | } 148 | } 149 | 150 | export class FlashEraseCommand extends Command { 151 | constructor(num_sectors) { 152 | // Count of sectors parameter is a 32-bit little-endian integer. 153 | const buf = new ArrayBuffer(4); 154 | new DataView(buf).setUint32(0, num_sectors, true); 155 | 156 | super(CommandType.FlashErase, new Uint8Array(buf)); 157 | } 158 | } 159 | 160 | export class FlashWriteCommand extends Command { 161 | constructor(addr, data, key) { 162 | // Set flash address/offset as 32-bit little-endian integer, and 163 | // XOR-encrypt the provided data (which may be zero-length) with the 164 | // given key. 165 | const buf = new ArrayBuffer(5 + data.length); 166 | new DataView(buf).setUint32(0, addr, true); 167 | if(data.length > 0 && key.length > 0) { 168 | new Uint8Array(buf, 5, data.length).set(data.map((val, idx) => val ^ key[idx % key.length])); 169 | } 170 | 171 | super(CommandType.FlashWrite, new Uint8Array(buf)); 172 | } 173 | } 174 | 175 | export class FlashVerifyCommand extends Command { 176 | constructor(addr, data, key) { 177 | // Set flash address/offset as 32-bit little-endian integer, and 178 | // XOR-encrypt the provided data (which may be zero-length) with the 179 | // given key. 180 | const buf = new ArrayBuffer(5 + data.length); 181 | new DataView(buf).setUint32(0, addr, true); 182 | if(data.length > 0 && key.length > 0) { 183 | new Uint8Array(buf, 5, data.length).set(data.map((val, idx) => val ^ key[idx % key.length])); 184 | } 185 | 186 | super(CommandType.FlashVerify, new Uint8Array(buf)); 187 | } 188 | } 189 | 190 | export class ConfigReadCommand extends Command { 191 | constructor() { 192 | // Bit-mask values: 193 | // USER & RDPR = 0x01 194 | // DATA0 & DATA1 = 0x02 195 | // WRPR = 0x04 196 | // BTVER = 0x08 197 | // UNIID = 0x10 198 | // ALL = 0x1F 199 | // Just read 'all' config items for now. 200 | super(CommandType.ConfigRead, [0x1F, 0x00]); 201 | } 202 | } 203 | 204 | export class ConfigWriteCommand extends Command { 205 | constructor(config) { 206 | const data = new Uint8Array(14); 207 | 208 | // Just write 'all' config items for now. 209 | data[0] = 0x07; // Bit-mask 210 | data[2] = config[0]; // RDPR 211 | data[3] = ~config[0]; // nRDPR 212 | data[4] = config[1]; // USER 213 | data[5] = ~config[1]; // nUSER 214 | data[6] = config[2]; // DATA0 215 | data[7] = ~config[2]; // nDATA0 216 | data[8] = config[3]; // DATA1 217 | data[9] = ~config[3]; // nDATA1 218 | data.set(config.slice(4, 8), 10); // WRPR0-3 (no 'n' inverse) 219 | 220 | super(CommandType.ConfigWrite, data); 221 | } 222 | } 223 | -------------------------------------------------------------------------------- /style.css: -------------------------------------------------------------------------------- 1 | body { 2 | display: flex; 3 | flex-direction: column; 4 | align-items: center; 5 | justify-content: center; 6 | background-color: white; 7 | color: black; 8 | font-family: sans-serif; 9 | font-size: 10pt; 10 | } 11 | 12 | main { 13 | width: 760px; 14 | } 15 | 16 | h1 { 17 | font-size: 1.8em; 18 | } 19 | 20 | div#unsupported { 21 | background-color: #FFEF00; 22 | border: 4px dashed black; 23 | padding: 1em; 24 | font-size: 1.5em; 25 | text-align: center; 26 | } 27 | 28 | div#unsupported p:first-child { 29 | font-weight: bold; 30 | } 31 | 32 | div#unsupported.hidden { 33 | display: none; 34 | } 35 | 36 | #form section { 37 | margin: 1em 0; 38 | border: 2px solid #AF0000; 39 | } 40 | 41 | #form section > h2:first-child { 42 | margin: 0 0 0.5em 0; 43 | padding: 0.25em; 44 | background-color: #AF0000; 45 | color: white; 46 | font-size: 1em; 47 | } 48 | 49 | #form section > p, section > div, section > table { 50 | margin: 0.5em; 51 | } 52 | 53 | input, select, button { 54 | border: 1px solid #767676; 55 | border-radius: 0; 56 | color: black; 57 | background-color: #EDEDED; 58 | padding: 0.25em 0.4em; 59 | } 60 | 61 | input:focus, select:focus, button:focus { 62 | outline-color: black; 63 | outline-width: 3px; 64 | } 65 | 66 | button:hover { 67 | background-color: #E2E2E2; 68 | } 69 | 70 | button:active { 71 | background-color: #D8D8D8; 72 | } 73 | 74 | button:disabled, select:disabled { 75 | color: #1010104C; 76 | } 77 | 78 | p.device_ctrls { 79 | display: flex; 80 | flex-direction: row; 81 | align-items: center; 82 | justify-content: space-between; 83 | } 84 | 85 | div.fw_tabs > input[type="radio"] { 86 | position: absolute; 87 | left: -200vw; 88 | } 89 | 90 | div.fw_tabs > label { 91 | display: inline-block; 92 | cursor: pointer; 93 | padding: 0.2em 0.5em; 94 | border: 1px solid transparent; 95 | border-radius: 0.5em 0.5em 0 0; 96 | margin-bottom: -1px; 97 | } 98 | 99 | div.fw_tabs > input[type="radio"]:checked + label { 100 | font-weight: bold; 101 | border-color: #767676; 102 | border-bottom: 1px solid white; 103 | } 104 | 105 | div.fw_tabs div.fw_tab_panels { 106 | border: 1px solid #767676; 107 | padding: 0.5em; 108 | } 109 | 110 | div.fw_tabs div.fw_tab_panel { 111 | display: none; 112 | } 113 | 114 | div.fw_tabs div.fw_tab_panel > div { 115 | display: flex; 116 | flex-direction: row; 117 | align-items: center; 118 | justify-content: space-between; 119 | } 120 | 121 | div.fw_tabs div.fw_tab_panel > progress { 122 | width: 100%; 123 | height: 1em; 124 | } 125 | 126 | div.fw_tabs > input[type="radio"]:nth-child(1):checked ~ div.fw_tab_panels > div.fw_tab_panel:nth-child(1), 127 | div.fw_tabs > input[type="radio"]:nth-child(3):checked ~ div.fw_tab_panels > div.fw_tab_panel:nth-child(2) { 128 | display: block; 129 | } 130 | 131 | div.fw_tabs input[type="file"]#fw_file, div.fw_tabs input[type="url"]#fw_url { 132 | width: 100%; 133 | } 134 | 135 | div.fw_tabs button#fw_url_load { 136 | margin-left: 0.5em; 137 | } 138 | 139 | p.fw_info { 140 | display: flex; 141 | flex-direction: row; 142 | align-items: center; 143 | justify-content: space-between; 144 | } 145 | 146 | p.fw_info span.fw_size { 147 | margin-left: 0.5em; 148 | white-space: nowrap; 149 | } 150 | 151 | div.hex { 152 | height: 25ex; 153 | overflow-y: scroll; 154 | border: 1px solid black; 155 | padding: 0 0.2em; 156 | font-family: monospace; 157 | white-space: pre; 158 | } 159 | 160 | div.hex > span.o { 161 | font-weight: bold; 162 | margin-right: 0.5em; 163 | border-right: 1px solid black; 164 | padding-right: 0.5em; 165 | } 166 | 167 | div.hex > span.p { 168 | font-style: italic; 169 | margin-left: 0.5em; 170 | border-left: 1px solid black; 171 | padding-left: 0.5em; 172 | } 173 | 174 | table.config { 175 | border-spacing: 0.5em 0.2em; 176 | } 177 | 178 | table.config td:nth-child(odd) { 179 | text-align: right; 180 | } 181 | 182 | table.config td input[type="text"] { 183 | width: 4em; 184 | background-repeat: no-repeat; 185 | background-position: right center; 186 | background-size: contain; 187 | } 188 | 189 | table.config td input[type="text"]:valid { 190 | background-image: url("images/check-small.svg"); 191 | } 192 | 193 | table.config td input[type="text"]:invalid { 194 | background-image: url("images/cross-small.svg"); 195 | } 196 | 197 | p#actions { 198 | display: flex; 199 | flex-direction: row; 200 | align-items: center; 201 | justify-content: flex-start; 202 | } 203 | 204 | p#actions > button { 205 | margin-right: 1em; 206 | padding-left: 1.95em; 207 | background-repeat: no-repeat; 208 | background-position: 0.25em center; 209 | background-size: 1.5em; 210 | height: 2.1em; 211 | } 212 | 213 | p#actions > button:last-child { 214 | margin-right: 0; 215 | } 216 | 217 | p#actions > button:disabled { 218 | background-blend-mode: overlay; 219 | } 220 | 221 | p#actions > button#config_read { 222 | background-image: url("images/config-read.svg"); 223 | } 224 | 225 | p#actions > button#config_write { 226 | background-image: url("images/config-write.svg"); 227 | } 228 | 229 | p#actions > button#flash_write { 230 | background-image: url("images/flash-write.svg"); 231 | } 232 | 233 | p#actions > button#flash_verify { 234 | background-image: url("images/flash-verify.svg"); 235 | } 236 | 237 | p#actions > button#flash_erase { 238 | background-image: url("images/flash-erase.svg"); 239 | } 240 | 241 | p.progress { 242 | display: flex; 243 | flex-direction: row; 244 | align-items: center; 245 | } 246 | 247 | p.progress progress#progress_bar { 248 | width: 100%; 249 | height: 1.5em; 250 | } 251 | 252 | p.progress #progress_pct { 253 | margin-left: 0.5em; 254 | } 255 | 256 | p.progress #progress_result { 257 | display: none; 258 | width: 1.5em; 259 | height: 1.5em; 260 | margin-right: 0.5em; 261 | background-repeat: no-repeat; 262 | background-position: center; 263 | background-size: contain; 264 | } 265 | 266 | p.progress #progress_result.success { 267 | display: block; 268 | background-image: url("images/check-green.svg"); 269 | } 270 | 271 | p.progress #progress_result.failure { 272 | display: block; 273 | background-image: url("images/cross-red.svg"); 274 | } 275 | 276 | div#log { 277 | height: 25ex; 278 | overflow: scroll; 279 | border: 1px solid black; 280 | font-family: monospace; 281 | } 282 | 283 | div#log > p { 284 | margin: 0; 285 | white-space: pre; 286 | } 287 | 288 | div#log > p > .time { 289 | color: #808080; 290 | } 291 | 292 | div#log > p > .level { 293 | font-weight: bold; 294 | } 295 | 296 | div#log > p > .level.info { 297 | color: #0072BF; 298 | } 299 | 300 | div#log > p > .level.warning { 301 | color: #BF9F00; 302 | } 303 | 304 | div#log > p > .level.error { 305 | color: #BF0000; 306 | } 307 | 308 | div#log > p > .level.debug { 309 | color: #BF00A5; 310 | } 311 | 312 | p.log_ctrls { 313 | display: flex; 314 | flex-direction: row; 315 | align-items: center; 316 | justify-content: space-between; 317 | } 318 | 319 | section.help > h2 { 320 | border-bottom: 1px solid #767676; 321 | padding-bottom: 0.2em; 322 | } 323 | 324 | section.help > div { 325 | margin: 0; 326 | } 327 | 328 | section.help div p, section.help div ul, section.help div ol, section.help div table { 329 | margin-left: 3em; 330 | } 331 | 332 | section.help div table { 333 | border: 1px solid #767676; 334 | border-spacing: 0; 335 | border-collapse: collapse; 336 | } 337 | 338 | section.help div table td, section.help div table th { 339 | border: 1px solid #767676; 340 | padding: 0.2em 0.5em; 341 | vertical-align: middle; 342 | } 343 | 344 | section.help div table th { 345 | font-weight: bold; 346 | white-space: nowrap; 347 | vertical-align: bottom; 348 | } 349 | 350 | section.help div p span.note { 351 | font-size: 0.8em; 352 | font-style: italic; 353 | } 354 | 355 | footer.footer { 356 | border-top: 1px solid #767676; 357 | font-size: 0.8em; 358 | text-align: center; 359 | color: #767676; 360 | } 361 | 362 | footer.footer p { 363 | margin: 0.5em 0; 364 | } 365 | 366 | footer.footer a.github { 367 | padding-left: 1.4em; 368 | background-repeat: no-repeat; 369 | background-position: left center; 370 | background-size: contain; 371 | background-image: url("images/github.svg"); 372 | } 373 | -------------------------------------------------------------------------------- /modules/firmware.js: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * 3 | * WCH RISC-V Microcontroller Web Serial ISP 4 | * Copyright (c) 2024 Basil Hussain 5 | * 6 | * This program is free software: you can redistribute it and/or modify it under 7 | * the terms of the GNU Affero General Public License as published by the Free 8 | * Software Foundation, either version 3 of the License, or (at your option) any 9 | * later version. 10 | * 11 | * This program is distributed in the hope that it will be useful, but WITHOUT 12 | * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 13 | * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more 14 | * details. 15 | * 16 | * You should have received a copy of the GNU Affero General Public License 17 | * along with this program. If not, see . 18 | * 19 | * SPDX-License-Identifier: AGPL-3.0-or-later 20 | * 21 | ******************************************************************************/ 22 | 23 | import { ContentDispositionDecoder } from "./util.js"; 24 | 25 | const MAX_SIZE_BYTES = 1048576; 26 | 27 | export class Firmware { 28 | #bytes; 29 | #name; 30 | #extension; 31 | #format; 32 | 33 | constructor(bytes, name, format) { 34 | this.#bytes = bytes; 35 | this.#name = name; 36 | this.#extension = this.#getFilenameExtension(name); 37 | this.#format = format; 38 | } 39 | 40 | #getFilenameExtension(name) { 41 | const nameDotPos = name.lastIndexOf("."); 42 | return (nameDotPos >= 0 ? name.slice(nameDotPos + 1).toLowerCase() : ""); 43 | } 44 | 45 | fillToEndOfSegment(segmentSize, fillVal = 0xFF) { 46 | if(this.#bytes.length % segmentSize != 0) { 47 | const oldSize = this.#bytes.length; 48 | const newSize = Math.ceil(this.#bytes.length / segmentSize) * segmentSize; 49 | // We need to use transfer() here to make a new buffer of the 50 | // desired new size, because we might have a non-resizeable 51 | // ArrayBuffer (because a raw binary was loaded by parse()), so 52 | // can't use resize(). If it was resizeable, and of big-enough 53 | // capacity, then the same buffer is reused by transfer(). 54 | this.#bytes = new Uint8Array(this.#bytes.buffer.transfer(newSize)); 55 | this.#bytes.fill(fillVal, oldSize); 56 | } 57 | } 58 | 59 | getPageCount(pageSize) { 60 | return Math.ceil(this.#bytes.length / pageSize); 61 | } 62 | 63 | getSectorCount(sectorSize) { 64 | return Math.ceil(this.#bytes.length / sectorSize); 65 | } 66 | 67 | get fileName() { 68 | return this.#name; 69 | } 70 | 71 | get fileExtension() { 72 | return this.#extension; 73 | } 74 | 75 | get size() { 76 | return this.#bytes.length; 77 | } 78 | 79 | get bytes() { 80 | return this.#bytes; 81 | } 82 | 83 | get format() { 84 | return this.#format; 85 | } 86 | } 87 | 88 | export class FirmwareLoader extends EventTarget { 89 | #parsers = new Map(); 90 | 91 | constructor() { 92 | super(); 93 | } 94 | 95 | #getFilenameExtension(name) { 96 | const nameDotPos = name.lastIndexOf("."); 97 | return (nameDotPos >= 0 ? name.slice(nameDotPos + 1).toLowerCase() : ""); 98 | } 99 | 100 | #getUrlResponseFilename(response) { 101 | // First, try to extract a filename given in any Content-Disposition 102 | // header present in the HTTP response. 103 | if(response.headers.has("Content-Disposition")) { 104 | return ContentDispositionDecoder.getFilename(response.headers.get("Content-Disposition")); 105 | } 106 | 107 | // Otherwise, try to extract a filename from the last part of the URL 108 | // path. 109 | const url = new URL(response.url); 110 | const slashPos = url.pathname.lastIndexOf("/"); 111 | if(url.pathname.length > 1 && slashPos >= 0) { 112 | return url.pathname.slice(slashPos + 1); 113 | } 114 | 115 | // Failing all the above, just return a default name. 116 | return "[unknown]"; 117 | } 118 | 119 | #progressEvent(incr, total) { 120 | this.dispatchEvent(new CustomEvent("progress", { 121 | detail: { 122 | increment: incr, 123 | total: total 124 | } 125 | })); 126 | } 127 | 128 | async #parseBlob(blob, name) { 129 | if(blob.size == 0) throw new Error("No data to parse; file is empty"); 130 | 131 | const extension = this.#getFilenameExtension(name); 132 | let bytes, format; 133 | 134 | if(this.#parsers.has(extension)) { 135 | // We have a parser for the file extension, so use it on the 136 | // contents of the blob. If the parser is for text-based files, read 137 | // the blob as a string; otherwise read binary bytes. 138 | const parser = this.#parsers.get(extension); 139 | if(parser.forText) { 140 | bytes = parser.parse(await blob.text(), MAX_SIZE_BYTES); 141 | } else { 142 | bytes = parser.parse(await blob.arrayBuffer(), MAX_SIZE_BYTES); 143 | } 144 | format = parser.formatName; 145 | } else { 146 | // No parser, just use the raw bytes of the file. 147 | if(blob.size > MAX_SIZE_BYTES) { 148 | throw new Error("Maximum size of " + MAX_SIZE_BYTES.toLocaleString() + " bytes exceeded"); 149 | } 150 | bytes = new Uint8Array(await blob.arrayBuffer()); 151 | format = "Raw Binary"; 152 | } 153 | 154 | return { bytes: bytes, format: format }; 155 | } 156 | 157 | addParser(extensions, parser) { 158 | for(const ext of extensions) { 159 | this.#parsers.set(ext.trim().toLowerCase(), parser); 160 | } 161 | } 162 | 163 | async fromFile(file) { 164 | const { bytes, format } = await this.#parseBlob(file, file.name); 165 | 166 | return new Firmware(bytes, file.name, format); 167 | } 168 | 169 | async fromUrl(urlStr) { 170 | // See if the given URL string starts with a protocol. If not, then add 171 | // "http://" prefix. If it does, but it's not HTTP, then error. 172 | const protoMatch = urlStr.match(/^([a-z]+):\/\//i); 173 | if(!protoMatch) { 174 | urlStr = "http://" + urlStr; 175 | } else if(protoMatch[1].toLowerCase() !== "http" && protoMatch[1].toLowerCase() !== "https") { 176 | throw new Error("Loading from non-HTTP protocol URLs not supported"); 177 | } 178 | 179 | // Parse the given URL to check that it's actually valid. 180 | const url = URL.parse(urlStr); 181 | if(!url) throw new Error("URL \"" + urlStr + "\" is not valid"); 182 | 183 | // Trigger an initial progress event with indeterminate state in case of 184 | // slow-responding server. 185 | this.#progressEvent(null, null); 186 | 187 | // Make the HTTP request. 188 | const response = await window.fetch(url); 189 | if(!response.ok) { 190 | throw new Error("Server response: " + response.status + " " + response.statusText); 191 | } 192 | 193 | const reader = response.body.getReader(); 194 | 195 | // Get the length of the content (if stated by server). When the 196 | // response body is encoded (e.g. gzip), we don't know what the actual 197 | // uncompressed length will be, so estimate it to be 2:1 compressed. 198 | let totalLength = Number.parseInt(response.headers.get("Content-Length")) || 0; 199 | if(response.headers.has("Content-Encoding")) totalLength *= 2; 200 | 201 | let chunks = []; 202 | let receivedLength = 0; 203 | 204 | this.#progressEvent(receivedLength, totalLength); 205 | 206 | while(true) { 207 | const { value: chunk, done } = await reader.read(); 208 | if(done) break; 209 | 210 | // Append the chunk to the list. In the unusual case that the 211 | // received length is now greater than the total length, then just 212 | // set the total length to be the received length so far. 213 | chunks.push(chunk); 214 | receivedLength += chunk.length; 215 | totalLength = Math.max(receivedLength, totalLength); 216 | 217 | this.#progressEvent(receivedLength, totalLength); 218 | } 219 | 220 | // One last progress call to ensure we finish off to 100%. 221 | this.#progressEvent(totalLength, totalLength); 222 | 223 | // Create our own Blob object out of all the chunks received. 224 | const name = this.#getUrlResponseFilename(response); 225 | const blob = new Blob(chunks, { 226 | type: response.headers.get("Content-Type"), 227 | endings: "native" 228 | }); 229 | 230 | const { bytes, format } = await this.#parseBlob(blob, name); 231 | 232 | return new Firmware(bytes, name, format); 233 | } 234 | } 235 | -------------------------------------------------------------------------------- /images/dtr-rts-sequence.svg: -------------------------------------------------------------------------------- 1 | DTRRTS100ms100msNRSTBOOT0BOOT1(Don’t Care)(Don’t Care) -------------------------------------------------------------------------------- /modules/session.js: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * 3 | * WCH RISC-V Microcontroller Web Serial ISP 4 | * Copyright (c) 2025 Basil Hussain 5 | * 6 | * This program is free software: you can redistribute it and/or modify it under 7 | * the terms of the GNU Affero General Public License as published by the Free 8 | * Software Foundation, either version 3 of the License, or (at your option) any 9 | * later version. 10 | * 11 | * This program is distributed in the hope that it will be useful, but WITHOUT 12 | * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 13 | * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more 14 | * details. 15 | * 16 | * You should have received a copy of the GNU Affero General Public License 17 | * along with this program. If not, see . 18 | * 19 | * SPDX-License-Identifier: AGPL-3.0-or-later 20 | * 21 | ******************************************************************************/ 22 | 23 | import { PacketType, Packet, InvalidPacketError } from "./packet.js"; 24 | import { 25 | CommandType, Command, IdentifyCommand, EndCommand, KeyCommand, 26 | FlashEraseCommand, FlashWriteCommand, FlashVerifyCommand, ConfigReadCommand, 27 | ConfigWriteCommand 28 | } from "./command.js"; 29 | import { 30 | ResponseType, Response, IdentifyResponse, EndResponse, KeyResponse, 31 | FlashEraseResponse, FlashWriteResponse, FlashVerifyResponse, 32 | ConfigReadResponse, ConfigWriteResponse, InvalidResponseError, 33 | UnsuccessfulResponseError 34 | } from "./response.js"; 35 | import { Transceiver } from "./transceiver.js"; 36 | import { Logger } from "./logger.js"; 37 | import { Formatter } from "./util.js"; 38 | 39 | const CHUNK_SIZE = 56; 40 | 41 | export class Session extends EventTarget { 42 | #trx; 43 | #device; 44 | #logger = console; 45 | #optBytes; 46 | #bootVer; 47 | #chipUID; 48 | #key; 49 | #sequence = 0; 50 | 51 | constructor(deviceVariant, deviceType, deviceDtrRtsReset) { 52 | super(); 53 | 54 | this.#trx = new Transceiver(deviceDtrRtsReset); 55 | this.#device = { variant: deviceVariant, type: deviceType }; 56 | } 57 | 58 | #logPacket(prefix, packet) { 59 | this.#logger.debug(prefix + " (" + packet.length + " bytes): " + packet.toString()); 60 | } 61 | 62 | #progressEvent(incr, total) { 63 | this.dispatchEvent(new CustomEvent("progress", { 64 | detail: { 65 | increment: incr, 66 | total: total 67 | } 68 | })); 69 | } 70 | 71 | setLogger(logger) { 72 | if(!(logger instanceof Logger)) throw new Error("Logger argument must be a Logger object"); 73 | this.#logger = logger; 74 | } 75 | 76 | async start() { 77 | this.#logger.info("Starting new session"); 78 | await this.#trx.open(); 79 | this.#sequence = 0; 80 | } 81 | 82 | async end() { 83 | await this.#trx.close(); 84 | this.#logger.info("Ended session"); 85 | } 86 | 87 | async identify() { 88 | this.#logger.debug(++this.#sequence + ": Identify"); 89 | 90 | let packet, cmd, resp; 91 | 92 | this.#progressEvent(null, null); 93 | 94 | // Send the command with expected device variant and type. 95 | cmd = new IdentifyCommand(this.#device.variant, this.#device.type); 96 | packet = Packet.fromCommand(cmd); 97 | this.#logPacket("TX", packet); 98 | await this.#trx.transmitPacket(packet); 99 | 100 | // Get response to the command. 101 | packet = await this.#trx.receivePacket(Packet.sizeForResponseType(ResponseType.Identify)); 102 | this.#logPacket("RX", packet); 103 | if(!packet.isValid()) throw new InvalidPacketError(); 104 | resp = IdentifyResponse.fromPacket(packet); 105 | if(!resp.isValid()) throw new InvalidResponseError(); 106 | if(!resp.success) throw new UnsuccessfulResponseError(); 107 | 108 | this.#logger.info( 109 | "Device variant: 0x" + Formatter.hex(resp.deviceVariant, 2) + 110 | ", type: 0x" + Formatter.hex(resp.deviceType, 2) 111 | ); 112 | 113 | // Error if type mismatch, warn if only variant mismatch. 114 | if(resp.deviceType != this.#device.type) { 115 | throw new Error("Reported device type does not match selected device"); 116 | } else if(resp.deviceVariant != this.#device.variant) { 117 | this.#logger.warn("Reported device variant does not match selected device"); 118 | } 119 | 120 | // Save what device variant and type the bootloader identified as. 121 | this.#device = { 122 | variant: resp.deviceVariant, 123 | type: resp.deviceType 124 | }; 125 | 126 | this.#progressEvent(100, 100); 127 | 128 | return this.#device; 129 | } 130 | 131 | async reset(doReset) { 132 | this.#logger.debug(++this.#sequence + ": Reset"); 133 | 134 | let packet, cmd, resp; 135 | 136 | this.#progressEvent(null, null); 137 | 138 | // Send the command with parameter indicating whether reset wanted. 139 | cmd = new EndCommand(doReset); 140 | packet = Packet.fromCommand(cmd); 141 | this.#logPacket("TX", packet); 142 | await this.#trx.transmitPacket(packet); 143 | 144 | // Get response to the command. 145 | packet = await this.#trx.receivePacket(Packet.sizeForResponseType(ResponseType.End)); 146 | this.#logPacket("RX", packet); 147 | if(!packet.isValid()) throw new InvalidPacketError(); 148 | resp = EndResponse.fromPacket(packet); 149 | if(!resp.isValid()) throw new InvalidResponseError(); 150 | if(!resp.success) throw new UnsuccessfulResponseError(); 151 | 152 | this.#progressEvent(100, 100); 153 | } 154 | 155 | async keyGenerate() { 156 | this.#logger.debug(++this.#sequence + ": Key Generate"); 157 | 158 | let packet, cmd, resp; 159 | 160 | this.#progressEvent(null, null); 161 | 162 | // Send the command. Provide chip unique ID and device variant to key 163 | // calculation routine. 164 | cmd = new KeyCommand(this.#chipUID, this.#device.variant); 165 | packet = Packet.fromCommand(cmd); 166 | this.#logPacket("TX", packet); 167 | await this.#trx.transmitPacket(packet); 168 | 169 | // Save the generated key for later use by flash write/verify. 170 | this.#key = cmd.key; 171 | 172 | // Get response to the command. 173 | packet = await this.#trx.receivePacket(Packet.sizeForResponseType(ResponseType.Key)); 174 | this.#logPacket("RX", packet); 175 | if(!packet.isValid()) throw new InvalidPacketError(); 176 | resp = KeyResponse.fromPacket(packet); 177 | if(!resp.isValid()) throw new InvalidResponseError(); 178 | if(!resp.success) throw new UnsuccessfulResponseError(); 179 | 180 | // As a sanity check, verify that the received checksum of the key 181 | // calculated by the bootloader matches our own. 182 | if(cmd.keyChecksum != resp.keyChecksum) throw new Error("Key checksum mismatch"); 183 | 184 | this.#progressEvent(100, 100); 185 | 186 | return this.#key; 187 | } 188 | 189 | async flashErase(sectorCount) { 190 | this.#logger.debug(++this.#sequence + ": Flash Erase"); 191 | 192 | let packet, cmd, resp; 193 | 194 | this.#progressEvent(null, null); 195 | 196 | // Send the command with given number of 1K sectors to be erased. 197 | cmd = new FlashEraseCommand(sectorCount); 198 | packet = Packet.fromCommand(cmd); 199 | this.#logPacket("TX", packet); 200 | await this.#trx.transmitPacket(packet); 201 | 202 | // Get response to the command. 203 | packet = await this.#trx.receivePacket(Packet.sizeForResponseType(ResponseType.FlashErase)); 204 | this.#logPacket("RX", packet); 205 | if(!packet.isValid()) throw new InvalidPacketError(); 206 | resp = FlashEraseResponse.fromPacket(packet); 207 | if(!resp.isValid()) throw new InvalidResponseError(); 208 | if(!resp.success) throw new UnsuccessfulResponseError(); 209 | 210 | this.#progressEvent(100, 100); 211 | } 212 | 213 | async flashWrite(bytes) { 214 | this.#logger.debug(++this.#sequence + ": Flash Write"); 215 | 216 | let packet, cmd, resp; 217 | 218 | for(let offset = 0; offset < bytes.length; offset += CHUNK_SIZE) { 219 | // Call the progress callback with two arguments: the current number 220 | // of bytes so far, and the total number. 221 | this.#progressEvent(offset, bytes.length); 222 | 223 | // Send the command using current chunk's offset, chunk data, and 224 | // the key to encrypt it with. 225 | cmd = new FlashWriteCommand(offset, bytes.subarray(offset, offset + CHUNK_SIZE), this.#key); 226 | packet = Packet.fromCommand(cmd); 227 | this.#logPacket("TX", packet); 228 | await this.#trx.transmitPacket(packet); 229 | 230 | // Get response to the command. 231 | packet = await this.#trx.receivePacket(Packet.sizeForResponseType(ResponseType.FlashWrite)); 232 | this.#logPacket("RX", packet); 233 | if(!packet.isValid()) throw new InvalidPacketError(); 234 | resp = FlashWriteResponse.fromPacket(packet); 235 | if(!resp.isValid()) throw new InvalidResponseError(); 236 | if(!resp.success) throw new UnsuccessfulResponseError(); 237 | } 238 | 239 | // Send one final write command with zero-length data and offset at the 240 | // end of the data, in order to get bootloader to write any still 241 | // buffered data to flash. 242 | cmd = new FlashWriteCommand(bytes.length, new Uint8Array(0), this.#key); 243 | packet = Packet.fromCommand(cmd); 244 | this.#logPacket("TX", packet); 245 | await this.#trx.transmitPacket(packet); 246 | 247 | // Get response to the finalisation command. 248 | packet = await this.#trx.receivePacket(Packet.sizeForResponseType(ResponseType.FlashWrite)); 249 | this.#logPacket("RX", packet); 250 | if(!packet.isValid()) throw new InvalidPacketError(); 251 | resp = FlashWriteResponse.fromPacket(packet); 252 | if(!resp.isValid()) throw new InvalidResponseError(); 253 | if(!resp.success) throw new UnsuccessfulResponseError(); 254 | 255 | // One last progress call to finish off to 100%. 256 | this.#progressEvent(bytes.length, bytes.length); 257 | } 258 | 259 | async flashVerify(bytes) { 260 | this.#logger.debug(++this.#sequence + ": Flash Verify"); 261 | 262 | let packet, cmd, resp; 263 | 264 | for(let offset = 0; offset < bytes.length; offset += CHUNK_SIZE) { 265 | // Call the progress callback with two arguments: the current number 266 | // of bytes so far, and the total number. 267 | this.#progressEvent(offset, bytes.length); 268 | 269 | // Send the command using current chunk's offset, chunk data, and 270 | // the key to encrypt it with. 271 | cmd = new FlashVerifyCommand(offset, bytes.subarray(offset, offset + CHUNK_SIZE), this.#key); 272 | packet = Packet.fromCommand(cmd); 273 | this.#logPacket("TX", packet); 274 | await this.#trx.transmitPacket(packet); 275 | 276 | // Get response to the command. 277 | packet = await this.#trx.receivePacket(Packet.sizeForResponseType(ResponseType.FlashVerify)); 278 | this.#logPacket("RX", packet); 279 | if(!packet.isValid()) throw new InvalidPacketError(); 280 | resp = FlashVerifyResponse.fromPacket(packet); 281 | if(!resp.isValid()) throw new InvalidResponseError(); 282 | if(!resp.success) throw new UnsuccessfulResponseError(); 283 | } 284 | 285 | // One last progress call to finish off to 100%. 286 | this.#progressEvent(bytes.length, bytes.length); 287 | } 288 | 289 | async configRead() { 290 | this.#logger.debug(++this.#sequence + ": Config Read"); 291 | 292 | let packet, cmd, resp; 293 | 294 | this.#progressEvent(null, null); 295 | 296 | // Send the command. 297 | cmd = new ConfigReadCommand(); 298 | packet = Packet.fromCommand(cmd); 299 | this.#logPacket("TX", packet); 300 | await this.#trx.transmitPacket(packet); 301 | 302 | // Get response to the command. 303 | packet = await this.#trx.receivePacket(Packet.sizeForResponseType(ResponseType.ConfigRead)); 304 | this.#logPacket("RX", packet); 305 | if(!packet.isValid()) throw new InvalidPacketError(); 306 | resp = ConfigReadResponse.fromPacket(packet); 307 | if(!resp.isValid()) throw new InvalidResponseError(); 308 | if(!resp.success) throw new UnsuccessfulResponseError(); 309 | 310 | // Verify the chip unique ID checksum and warn if mismatch. 311 | if(resp.chipUniqueID.length == 8) { 312 | const uidWords = new Uint16Array(resp.chipUniqueID.buffer, 0, 4); 313 | if((uidWords[0] + uidWords[1] + uidWords[2]) % 65536 != uidWords[3]) { 314 | this.#logger.warn("Possibly invalid chip unique ID; checksum mismatch"); 315 | } 316 | } 317 | 318 | // Save the option bytes, bootloader version, and chip unique ID data. 319 | this.#optBytes = resp.optionBytesRaw; 320 | this.#bootVer = resp.bootloaderVersion; 321 | this.#chipUID = resp.chipUniqueID; 322 | 323 | this.#logger.info("Device configuration:"); 324 | this.#logger.info(" RDPR: 0x" + Formatter.hex(this.#optBytes[0], 2)); 325 | this.#logger.info(" USER: 0x" + Formatter.hex(this.#optBytes[1], 2)); 326 | this.#logger.info(" DATA0: 0x" + Formatter.hex(this.#optBytes[2], 2)); 327 | this.#logger.info(" DATA1: 0x" + Formatter.hex(this.#optBytes[3], 2)); 328 | this.#logger.info(" WRPR0: 0x" + Formatter.hex(this.#optBytes[4], 2)); 329 | this.#logger.info(" WRPR1: 0x" + Formatter.hex(this.#optBytes[5], 2)); 330 | this.#logger.info(" WRPR2: 0x" + Formatter.hex(this.#optBytes[6], 2)); 331 | this.#logger.info(" WRPR3: 0x" + Formatter.hex(this.#optBytes[7], 2)); 332 | this.#logger.info(" BTVER: " + this.#bootVer["major"] + "." + this.#bootVer["minor"]); 333 | this.#logger.info(" UNIID: " + Formatter.hex(this.#chipUID, 2)); 334 | 335 | this.#progressEvent(100, 100); 336 | 337 | return { 338 | optionBytes: this.#optBytes, 339 | bootloaderVersion: this.#bootVer, 340 | chipUniqueID: this.#chipUID 341 | }; 342 | } 343 | 344 | async configWrite(config) { 345 | this.#logger.debug(++this.#sequence + ": Config Write"); 346 | 347 | let packet, cmd, resp; 348 | 349 | this.#progressEvent(null, null); 350 | 351 | // Send the command with given config data. 352 | cmd = new ConfigWriteCommand(config); 353 | packet = Packet.fromCommand(cmd); 354 | this.#logPacket("TX", packet); 355 | await this.#trx.transmitPacket(packet); 356 | 357 | // Get response to the command. 358 | packet = await this.#trx.receivePacket(Packet.sizeForResponseType(ResponseType.ConfigWrite)); 359 | this.#logPacket("RX", packet); 360 | if(!packet.isValid()) throw new InvalidPacketError(); 361 | resp = ConfigWriteResponse.fromPacket(packet); 362 | if(!resp.isValid()) throw new InvalidResponseError(); 363 | if(!resp.success) throw new UnsuccessfulResponseError(); 364 | 365 | this.#progressEvent(100, 100); 366 | } 367 | } 368 | -------------------------------------------------------------------------------- /modules/devices.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "family": "CH32V00x", 4 | "devices": [ 5 | { 6 | "name": "CH32V002A4M6", 7 | "package": "SOP16", 8 | "type": 33, 9 | "variant": 34, 10 | "flash": { 11 | "size": 16384, 12 | "page_size": 256, 13 | "page_count": 64, 14 | "sector_size": 1024, 15 | "sector_count": 16 16 | } 17 | }, 18 | { 19 | "name": "CH32V002D4U6", 20 | "package": "QFN12", 21 | "type": 33, 22 | "variant": 35, 23 | "flash": { 24 | "size": 16384, 25 | "page_size": 256, 26 | "page_count": 64, 27 | "sector_size": 1024, 28 | "sector_count": 16 29 | } 30 | }, 31 | { 32 | "name": "CH32V002F4P6", 33 | "package": "TSSOP20", 34 | "type": 33, 35 | "variant": 32, 36 | "flash": { 37 | "size": 16384, 38 | "page_size": 256, 39 | "page_count": 64, 40 | "sector_size": 1024, 41 | "sector_count": 16 42 | } 43 | }, 44 | { 45 | "name": "CH32V002F4U6", 46 | "package": "QFN20", 47 | "type": 33, 48 | "variant": 33, 49 | "flash": { 50 | "size": 16384, 51 | "page_size": 256, 52 | "page_count": 64, 53 | "sector_size": 1024, 54 | "sector_count": 16 55 | } 56 | }, 57 | { 58 | "name": "CH32V002J4M6", 59 | "package": "SOP8", 60 | "type": 33, 61 | "variant": 36, 62 | "flash": { 63 | "size": 16384, 64 | "page_size": 256, 65 | "page_count": 64, 66 | "sector_size": 1024, 67 | "sector_count": 16 68 | } 69 | }, 70 | { 71 | "name": "CH32V003F4P6", 72 | "package": "TSSOP20", 73 | "type": 33, 74 | "variant": 48, 75 | "flash": { 76 | "size": 16384, 77 | "page_size": 64, 78 | "page_count": 256, 79 | "sector_size": 1024, 80 | "sector_count": 16 81 | } 82 | }, 83 | { 84 | "name": "CH32V003F4U6", 85 | "package": "QFN20", 86 | "type": 33, 87 | "variant": 49, 88 | "flash": { 89 | "size": 16384, 90 | "page_size": 64, 91 | "page_count": 256, 92 | "sector_size": 1024, 93 | "sector_count": 16 94 | } 95 | }, 96 | { 97 | "name": "CH32V003A4M6", 98 | "package": "SOP16", 99 | "type": 33, 100 | "variant": 50, 101 | "flash": { 102 | "size": 16384, 103 | "page_size": 64, 104 | "page_count": 256, 105 | "sector_size": 1024, 106 | "sector_count": 16 107 | } 108 | }, 109 | { 110 | "name": "CH32V003J4M6", 111 | "package": "SOP8", 112 | "type": 33, 113 | "variant": 51, 114 | "flash": { 115 | "size": 16384, 116 | "page_size": 64, 117 | "page_count": 256, 118 | "sector_size": 1024, 119 | "sector_count": 16 120 | } 121 | }, 122 | { 123 | "name": "CH32V004F6P1", 124 | "package": "TSSOP20", 125 | "type": 33, 126 | "variant": 64, 127 | "flash": { 128 | "size": 32768, 129 | "page_size": 256, 130 | "page_count": 128, 131 | "sector_size": 1024, 132 | "sector_count": 32 133 | } 134 | }, 135 | { 136 | "name": "CH32V004F6U1", 137 | "package": "QFN20", 138 | "type": 33, 139 | "variant": 65, 140 | "flash": { 141 | "size": 32768, 142 | "page_size": 256, 143 | "page_count": 128, 144 | "sector_size": 1024, 145 | "sector_count": 32 146 | } 147 | }, 148 | { 149 | "name": "CH32V005D6U6", 150 | "package": "QFN12", 151 | "type": 33, 152 | "variant": 83, 153 | "flash": { 154 | "size": 32768, 155 | "page_size": 256, 156 | "page_count": 128, 157 | "sector_size": 1024, 158 | "sector_count": 32 159 | } 160 | }, 161 | { 162 | "name": "CH32V005E6R6", 163 | "package": "QSOP24", 164 | "type": 33, 165 | "variant": 80, 166 | "flash": { 167 | "size": 32768, 168 | "page_size": 256, 169 | "page_count": 128, 170 | "sector_size": 1024, 171 | "sector_count": 32 172 | } 173 | }, 174 | { 175 | "name": "CH32V005F6P6", 176 | "package": "TSSOP20", 177 | "type": 33, 178 | "variant": 82, 179 | "flash": { 180 | "size": 32768, 181 | "page_size": 256, 182 | "page_count": 128, 183 | "sector_size": 1024, 184 | "sector_count": 32 185 | } 186 | }, 187 | { 188 | "name": "CH32V005F6U6", 189 | "package": "QFN20", 190 | "type": 33, 191 | "variant": 81, 192 | "flash": { 193 | "size": 32768, 194 | "page_size": 256, 195 | "page_count": 128, 196 | "sector_size": 1024, 197 | "sector_count": 32 198 | } 199 | }, 200 | { 201 | "name": "CH32V006E8R6", 202 | "package": "QSOP24", 203 | "type": 33, 204 | "variant": 97, 205 | "flash": { 206 | "size": 63488, 207 | "page_size": 256, 208 | "page_count": 248, 209 | "sector_size": 1024, 210 | "sector_count": 62 211 | } 212 | }, 213 | { 214 | "name": "CH32V006F8P6", 215 | "package": "TSSOP20", 216 | "type": 33, 217 | "variant": 99, 218 | "flash": { 219 | "size": 63488, 220 | "page_size": 256, 221 | "page_count": 248, 222 | "sector_size": 1024, 223 | "sector_count": 62 224 | } 225 | }, 226 | { 227 | "name": "CH32V006F8U6", 228 | "package": "QFN20", 229 | "type": 33, 230 | "variant": 98, 231 | "flash": { 232 | "size": 63488, 233 | "page_size": 256, 234 | "page_count": 248, 235 | "sector_size": 1024, 236 | "sector_count": 62 237 | } 238 | }, 239 | { 240 | "name": "CH32V006K8U6", 241 | "package": "QFN32", 242 | "type": 33, 243 | "variant": 96, 244 | "flash": { 245 | "size": 63488, 246 | "page_size": 256, 247 | "page_count": 248, 248 | "sector_size": 1024, 249 | "sector_count": 62 250 | } 251 | }, 252 | { 253 | "name": "CH32V007E8R6", 254 | "package": "QSOP24", 255 | "type": 33, 256 | "variant": 113, 257 | "flash": { 258 | "size": 63488, 259 | "page_size": 256, 260 | "page_count": 248, 261 | "sector_size": 1024, 262 | "sector_count": 62 263 | } 264 | }, 265 | { 266 | "name": "CH32V007K8U6", 267 | "package": "QFN32", 268 | "type": 33, 269 | "variant": 114, 270 | "flash": { 271 | "size": 63488, 272 | "page_size": 256, 273 | "page_count": 248, 274 | "sector_size": 1024, 275 | "sector_count": 62 276 | } 277 | } 278 | ] 279 | }, 280 | { 281 | "family": "CH32L103", 282 | "devices": [ 283 | { 284 | "name": "CH32L103C8T6", 285 | "package": "LQFP48", 286 | "type": 37, 287 | "variant": 49, 288 | "flash": { 289 | "size": 65536, 290 | "page_size": 256, 291 | "page_count": 256, 292 | "sector_size": 1024, 293 | "sector_count": 64 294 | } 295 | }, 296 | { 297 | "name": "CH32L103F8P6", 298 | "package": "TSSOP20", 299 | "type": 37, 300 | "variant": 58, 301 | "flash": { 302 | "size": 65536, 303 | "page_size": 256, 304 | "page_count": 256, 305 | "sector_size": 1024, 306 | "sector_count": 64 307 | } 308 | }, 309 | { 310 | "name": "CH32L103F8U6", 311 | "package": "QFN20", 312 | "type": 37, 313 | "variant": 61, 314 | "flash": { 315 | "size": 65536, 316 | "page_size": 256, 317 | "page_count": 256, 318 | "sector_size": 1024, 319 | "sector_count": 64 320 | } 321 | }, 322 | { 323 | "name": "CH32L103G8R6", 324 | "package": "QSOP28", 325 | "type": 37, 326 | "variant": 59, 327 | "flash": { 328 | "size": 65536, 329 | "page_size": 256, 330 | "page_count": 256, 331 | "sector_size": 1024, 332 | "sector_count": 64 333 | } 334 | }, 335 | { 336 | "name": "CH32L103K8U6", 337 | "package": "QFN32", 338 | "type": 37, 339 | "variant": 50, 340 | "flash": { 341 | "size": 65536, 342 | "page_size": 256, 343 | "page_count": 256, 344 | "sector_size": 1024, 345 | "sector_count": 64 346 | } 347 | } 348 | ] 349 | }, 350 | { 351 | "family": "CH32V103", 352 | "devices": [ 353 | { 354 | "name": "CH32V103C6T6", 355 | "package": "LQFP48", 356 | "type": 21, 357 | "variant": 50, 358 | "flash": { 359 | "size": 32768, 360 | "page_size": 128, 361 | "page_count": 256, 362 | "sector_size": 1024, 363 | "sector_count": 32 364 | } 365 | }, 366 | { 367 | "name": "CH32V103C8T6", 368 | "package": "LQFP48", 369 | "type": 21, 370 | "variant": 63, 371 | "flash": { 372 | "size": 65536, 373 | "page_size": 128, 374 | "page_count": 512, 375 | "sector_size": 1024, 376 | "sector_count": 64 377 | } 378 | }, 379 | { 380 | "name": "CH32V103C8U6", 381 | "package": "QFN48", 382 | "type": 21, 383 | "variant": 63, 384 | "flash": { 385 | "size": 65536, 386 | "page_size": 128, 387 | "page_count": 512, 388 | "sector_size": 1024, 389 | "sector_count": 64 390 | } 391 | }, 392 | { 393 | "name": "CH32V103R8T6", 394 | "package": "LQFP64M", 395 | "type": 21, 396 | "variant": 63, 397 | "flash": { 398 | "size": 65536, 399 | "page_size": 128, 400 | "page_count": 512, 401 | "sector_size": 1024, 402 | "sector_count": 64 403 | } 404 | } 405 | ] 406 | }, 407 | { 408 | "family": "CH32V203", 409 | "devices": [ 410 | { 411 | "name": "CH32V203C6T6", 412 | "package": "LQFP48", 413 | "type": 25, 414 | "variant": 51, 415 | "flash": { 416 | "size": 229376, 417 | "page_size": 256, 418 | "page_count": 128, 419 | "sector_size": 4096, 420 | "sector_count": 8 421 | } 422 | }, 423 | { 424 | "name": "CH32V203C8T6", 425 | "package": "LQFP48", 426 | "type": 25, 427 | "variant": 49, 428 | "flash": { 429 | "size": 229376, 430 | "page_size": 256, 431 | "page_count": 256, 432 | "sector_size": 4096, 433 | "sector_count": 16 434 | } 435 | }, 436 | { 437 | "name": "CH32V203C8U6", 438 | "package": "QFN48", 439 | "type": 25, 440 | "variant": 48, 441 | "flash": { 442 | "size": 229376, 443 | "page_size": 256, 444 | "page_count": 256, 445 | "sector_size": 4096, 446 | "sector_count": 16 447 | } 448 | }, 449 | { 450 | "name": "CH32V203F6P6", 451 | "package": "TSSOP20", 452 | "type": 25, 453 | "variant": 55, 454 | "flash": { 455 | "size": 229376, 456 | "page_size": 256, 457 | "page_count": 128, 458 | "sector_size": 4096, 459 | "sector_count": 8 460 | } 461 | }, 462 | { 463 | "name": "CH32V203F8P6", 464 | "package": "TSSOP20", 465 | "type": 25, 466 | "variant": 58, 467 | "flash": { 468 | "size": 229376, 469 | "page_size": 256, 470 | "page_count": 256, 471 | "sector_size": 4096, 472 | "sector_count": 16 473 | } 474 | }, 475 | { 476 | "name": "CH32V203F8U6", 477 | "package": "QFN20", 478 | "type": 25, 479 | "variant": 62, 480 | "flash": { 481 | "size": 229376, 482 | "page_size": 256, 483 | "page_count": 256, 484 | "sector_size": 4096, 485 | "sector_count": 16 486 | } 487 | }, 488 | { 489 | "name": "CH32V203G6U6", 490 | "package": "QFN28", 491 | "type": 25, 492 | "variant": 54, 493 | "flash": { 494 | "size": 229376, 495 | "page_size": 256, 496 | "page_count": 128, 497 | "sector_size": 4096, 498 | "sector_count": 8 499 | } 500 | }, 501 | { 502 | "name": "CH32V203G8R6", 503 | "package": "QSOP28", 504 | "type": 25, 505 | "variant": 59, 506 | "flash": { 507 | "size": 229376, 508 | "page_size": 256, 509 | "page_count": 256, 510 | "sector_size": 4096, 511 | "sector_count": 16 512 | } 513 | }, 514 | { 515 | "name": "CH32V203K6T6", 516 | "package": "LQFP32", 517 | "type": 25, 518 | "variant": 53, 519 | "flash": { 520 | "size": 229376, 521 | "page_size": 256, 522 | "page_count": 128, 523 | "sector_size": 4096, 524 | "sector_count": 8 525 | } 526 | }, 527 | { 528 | "name": "CH32V203K8T6", 529 | "package": "LQFP32", 530 | "type": 25, 531 | "variant": 50, 532 | "flash": { 533 | "size": 229376, 534 | "page_size": 256, 535 | "page_count": 256, 536 | "sector_size": 4096, 537 | "sector_count": 16 538 | } 539 | }, 540 | { 541 | "name": "CH32V203RBT6", 542 | "package": "LQFP64M", 543 | "type": 25, 544 | "variant": 52, 545 | "flash": { 546 | "size": 229376, 547 | "page_size": 256, 548 | "page_count": 512, 549 | "sector_size": 4096, 550 | "sector_count": 32 551 | } 552 | } 553 | ] 554 | }, 555 | { 556 | "family": "CH32V208", 557 | "devices": [ 558 | { 559 | "name": "CH32V208CBU6", 560 | "package": "QFN48", 561 | "type": 25, 562 | "variant": 130, 563 | "flash": { 564 | "size": 491520, 565 | "page_size": 256, 566 | "page_count": 512, 567 | "sector_size": 4096, 568 | "sector_count": 32 569 | } 570 | }, 571 | { 572 | "name": "CH32V208GBU6", 573 | "package": "QFN28", 574 | "type": 25, 575 | "variant": 131, 576 | "flash": { 577 | "size": 491520, 578 | "page_size": 256, 579 | "page_count": 512, 580 | "sector_size": 4096, 581 | "sector_count": 32 582 | } 583 | }, 584 | { 585 | "name": "CH32V208RBT6", 586 | "package": "LQFP64M", 587 | "type": 25, 588 | "variant": 129, 589 | "flash": { 590 | "size": 491520, 591 | "page_size": 256, 592 | "page_count": 512, 593 | "sector_size": 4096, 594 | "sector_count": 32 595 | } 596 | }, 597 | { 598 | "name": "CH32V208WBU6", 599 | "package": "QFN68", 600 | "type": 25, 601 | "variant": 128, 602 | "flash": { 603 | "size": 491520, 604 | "page_size": 256, 605 | "page_count": 512, 606 | "sector_size": 4096, 607 | "sector_count": 32 608 | } 609 | } 610 | ] 611 | }, 612 | { 613 | "family": "CH32V30x", 614 | "devices": [ 615 | { 616 | "name": "CH32V303CBT6", 617 | "package": "LQFP48", 618 | "type": 23, 619 | "variant": 51, 620 | "flash": { 621 | "size": 491520, 622 | "page_size": 256, 623 | "page_count": 512, 624 | "sector_size": 4096, 625 | "sector_count": 32 626 | } 627 | }, 628 | { 629 | "name": "CH32V303RBT6", 630 | "package": "LQFP64M", 631 | "type": 23, 632 | "variant": 50, 633 | "flash": { 634 | "size": 491520, 635 | "page_size": 256, 636 | "page_count": 512, 637 | "sector_size": 4096, 638 | "sector_count": 32 639 | } 640 | }, 641 | { 642 | "name": "CH32V303RCT6", 643 | "package": "LQFP64M", 644 | "type": 23, 645 | "variant": 49, 646 | "flash": { 647 | "size": 491520, 648 | "page_size": 256, 649 | "page_count": 1024, 650 | "sector_size": 4096, 651 | "sector_count": 64 652 | } 653 | }, 654 | { 655 | "name": "CH32V303VCT6", 656 | "package": "LQFP100", 657 | "type": 23, 658 | "variant": 48, 659 | "flash": { 660 | "size": 491520, 661 | "page_size": 256, 662 | "page_count": 1024, 663 | "sector_size": 4096, 664 | "sector_count": 64 665 | } 666 | }, 667 | { 668 | "name": "CH32V305FBP6", 669 | "package": "TSSOP20", 670 | "type": 23, 671 | "variant": 82, 672 | "flash": { 673 | "size": 491520, 674 | "page_size": 256, 675 | "page_count": 512, 676 | "sector_size": 4096, 677 | "sector_count": 32 678 | } 679 | }, 680 | { 681 | "name": "CH32V305GBU6", 682 | "package": "QFN28", 683 | "type": 23, 684 | "variant": 91, 685 | "flash": { 686 | "size": 491520, 687 | "page_size": 256, 688 | "page_count": 512, 689 | "sector_size": 4096, 690 | "sector_count": 32 691 | } 692 | }, 693 | { 694 | "name": "CH32V305RBT6", 695 | "package": "LQFP64M", 696 | "type": 23, 697 | "variant": 80, 698 | "flash": { 699 | "size": 491520, 700 | "page_size": 256, 701 | "page_count": 512, 702 | "sector_size": 4096, 703 | "sector_count": 32 704 | } 705 | }, 706 | { 707 | "name": "CH32V307FBP6", 708 | "package": "TSSOP20", 709 | "type": 23, 710 | "variant": 114, 711 | "flash": { 712 | "size": 491520, 713 | "page_size": 256, 714 | "page_count": 512, 715 | "sector_size": 4096, 716 | "sector_count": 32 717 | } 718 | }, 719 | { 720 | "name": "CH32V307RCT6", 721 | "package": "LQFP64M", 722 | "type": 23, 723 | "variant": 113, 724 | "flash": { 725 | "size": 491520, 726 | "page_size": 256, 727 | "page_count": 1024, 728 | "sector_size": 4096, 729 | "sector_count": 64 730 | } 731 | }, 732 | { 733 | "name": "CH32V307WCU6", 734 | "package": "QFN68", 735 | "type": 23, 736 | "variant": 115, 737 | "flash": { 738 | "size": 491520, 739 | "page_size": 256, 740 | "page_count": 1024, 741 | "sector_size": 4096, 742 | "sector_count": 64 743 | } 744 | }, 745 | { 746 | "name": "CH32V307VCT6", 747 | "package": "LQFP100", 748 | "type": 23, 749 | "variant": 112, 750 | "flash": { 751 | "size": 491520, 752 | "page_size": 256, 753 | "page_count": 1024, 754 | "sector_size": 4096, 755 | "sector_count": 64 756 | } 757 | } 758 | ] 759 | }, 760 | { 761 | "family": "CH32X03x", 762 | "devices": [ 763 | { 764 | "name": "CH32X033F8P6", 765 | "package": "TSSOP20", 766 | "type": 35, 767 | "variant": 90, 768 | "flash": { 769 | "size": 63488, 770 | "page_size": 256, 771 | "page_count": 248, 772 | "sector_size": 1024, 773 | "sector_count": 62 774 | } 775 | }, 776 | { 777 | "name": "CH32X035C8T6", 778 | "package": "LQFP48", 779 | "type": 35, 780 | "variant": 81, 781 | "flash": { 782 | "size": 63488, 783 | "page_size": 256, 784 | "page_count": 248, 785 | "sector_size": 1024, 786 | "sector_count": 62 787 | } 788 | }, 789 | { 790 | "name": "CH32X035F7P6", 791 | "package": "TSSOP20", 792 | "type": 35, 793 | "variant": 87, 794 | "flash": { 795 | "size": 63488, 796 | "page_size": 256, 797 | "page_count": 248, 798 | "sector_size": 1024, 799 | "sector_count": 62 800 | } 801 | }, 802 | { 803 | "name": "CH32X035F8U6", 804 | "package": "QFN20", 805 | "type": 35, 806 | "variant": 94, 807 | "flash": { 808 | "size": 63488, 809 | "page_size": 256, 810 | "page_count": 248, 811 | "sector_size": 1024, 812 | "sector_count": 62 813 | } 814 | }, 815 | { 816 | "name": "CH32X035G8R6", 817 | "package": "QSOP28", 818 | "type": 35, 819 | "variant": 91, 820 | "flash": { 821 | "size": 63488, 822 | "page_size": 256, 823 | "page_count": 248, 824 | "sector_size": 1024, 825 | "sector_count": 62 826 | } 827 | }, 828 | { 829 | "name": "CH32X035G8U6", 830 | "package": "QFN28", 831 | "type": 35, 832 | "variant": 86, 833 | "flash": { 834 | "size": 63488, 835 | "page_size": 256, 836 | "page_count": 248, 837 | "sector_size": 1024, 838 | "sector_count": 62 839 | } 840 | }, 841 | { 842 | "name": "CH32X035R8T6", 843 | "package": "LQFP64M", 844 | "type": 35, 845 | "variant": 80, 846 | "flash": { 847 | "size": 63488, 848 | "page_size": 256, 849 | "page_count": 248, 850 | "sector_size": 1024, 851 | "sector_count": 62 852 | } 853 | } 854 | ] 855 | } 856 | ] 857 | -------------------------------------------------------------------------------- /wchisp.js: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * 3 | * WCH RISC-V Microcontroller Web Serial ISP 4 | * Copyright (c) 2025 Basil Hussain 5 | * 6 | * This program is free software: you can redistribute it and/or modify it under 7 | * the terms of the GNU Affero General Public License as published by the Free 8 | * Software Foundation, either version 3 of the License, or (at your option) any 9 | * later version. 10 | * 11 | * This program is distributed in the hope that it will be useful, but WITHOUT 12 | * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 13 | * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more 14 | * details. 15 | * 16 | * You should have received a copy of the GNU Affero General Public License 17 | * along with this program. If not, see . 18 | * 19 | * SPDX-License-Identifier: AGPL-3.0-or-later 20 | * 21 | ******************************************************************************/ 22 | 23 | import { IntelHexParser } from "./modules/parsers/intelhex.js"; 24 | import { SRecordParser } from "./modules/parsers/srecord.js"; 25 | import { ElfRiscVParser } from "./modules/parsers/elf.js"; 26 | import { FirmwareLoader, Firmware } from "./modules/firmware.js"; 27 | import { Session } from "./modules/session.js"; 28 | import { DevicesDatabase } from "./modules/devices.js"; 29 | import { Logger } from "./modules/logger.js"; 30 | import { Formatter } from "./modules/util.js"; 31 | 32 | /******************************************************************************/ 33 | 34 | function clearHexListing() { 35 | document.getElementById("fw_hex").replaceChildren(); 36 | } 37 | 38 | function createHexListing(bytes, fileName) { 39 | const container = document.getElementById("fw_hex"); 40 | const offset_max_digits = bytes.length.toString(16).length; 41 | const groups_count = 8; 42 | const row_size = groups_count * 2; 43 | 44 | // console.time("createHexListing"); 45 | 46 | for(let i = 0; i < bytes.length; i += row_size) { 47 | let data = "", text = ""; 48 | for(let j = 0; j < groups_count; j++) { 49 | const n = i + (j * 2); 50 | if(n < bytes.length) { 51 | data += Formatter.hex(bytes[n], 2); 52 | text += Formatter.printableText(bytes[n], "·"); 53 | } 54 | if(n + 1 < bytes.length) { 55 | data += Formatter.hex(bytes[n + 1], 2); 56 | text += Formatter.printableText(bytes[n + 1], "·"); 57 | } 58 | data += " "; 59 | } 60 | 61 | const offset = document.createElement("span"); 62 | offset.classList.add("o"); 63 | offset.textContent = "0x" + Formatter.hex(i, offset_max_digits); 64 | 65 | const printable = document.createElement("span"); 66 | printable.classList.add("p"); 67 | printable.textContent = text; 68 | 69 | const br = document.createElement("br"); 70 | 71 | container.append(offset, data.trimEnd(), printable, br); 72 | } 73 | 74 | // console.timeEnd("createHexListing"); 75 | 76 | document.getElementById("fw_name_val").textContent = fileName; 77 | document.getElementById("fw_size_val").textContent = bytes.length.toLocaleString(); 78 | } 79 | 80 | function updateUrlLoadProgress(event) { 81 | const bar = document.getElementById("fw_url_progress"); 82 | 83 | // When either event value is null, make the progress bar 'indeterminate' 84 | // by removing its 'value' attribute. Otherwise, set its value accordingly. 85 | if(event.detail.increment === null || event.detail.total === null) { 86 | bar.removeAttribute("value"); 87 | } else { 88 | const val = Math.min(event.detail.increment / event.detail.total, 1.0); 89 | bar.setAttribute("value", val); 90 | } 91 | } 92 | 93 | function configInputIds() { 94 | const inputIds = [ 95 | "cfg_rdpr", "cfg_user", "cfg_data0", "cfg_data1", 96 | "cfg_wrpr0", "cfg_wrpr1", "cfg_wrpr2", "cfg_wrpr3" 97 | ]; 98 | return inputIds; 99 | } 100 | 101 | function populateConfig(config) { 102 | if("optionBytes" in config) { 103 | configInputIds().forEach((id, idx) => { 104 | document.getElementById(id).value = "0x" + Formatter.hex(config.optionBytes[idx], 2) 105 | }); 106 | } 107 | } 108 | 109 | function getConfigIsValid() { 110 | // Return whether all config input fields are valid according to their 111 | // constraints, and that their value parses successfully as a hex string. 112 | return configInputIds().every((id) => { 113 | const input = document.getElementById(id); 114 | return input.checkValidity() && !Number.isNaN(Number.parseInt(input.value, 16)); 115 | }); 116 | } 117 | 118 | function getConfigBytes() { 119 | if(!getConfigIsValid()) { 120 | throw new Error("One or more configuration option byte values is missing or invalid"); 121 | } 122 | 123 | return configInputIds().map((id) => Number.parseInt(document.getElementById(id).value, 16)); 124 | } 125 | 126 | function setActionButtonsEnabled(enable, ids = null) { 127 | const buttons = document.querySelectorAll("#actions > button"); 128 | const prevState = new Array(buttons.length); 129 | 130 | buttons.forEach((btn, idx) => { 131 | prevState[idx] = btn.disabled; 132 | 133 | // Enable/disable either all buttons if only boolean arg given, or if 134 | // additional arg array given, only buttons with those given ids. 135 | if(!Array.isArray(ids) || ids.includes(btn.id)) { 136 | btn.disabled = !enable; 137 | } 138 | }); 139 | 140 | return prevState; 141 | } 142 | 143 | function restoreActionButtonsEnabled(prevState) { 144 | document.querySelectorAll("#actions > button").forEach((btn, idx) => { 145 | btn.disabled = prevState[idx]; 146 | }); 147 | } 148 | 149 | function checkFirmwareSize(fwSize, flashSize) { 150 | if(fwSize > flashSize) { 151 | window.alert( 152 | "Currently loaded firmware file size is LARGER than device flash size!\n\n" + 153 | "Firmware size: " + Formatter.byteSize(fwSize) + "\n" + 154 | "Device flash size: " + Formatter.byteSize(flashSize) 155 | ); 156 | setActionButtonsEnabled(false, ["flash_write", "flash_verify"]); 157 | } else { 158 | setActionButtonsEnabled(true, ["flash_write", "flash_verify"]); 159 | } 160 | } 161 | 162 | function updateOperationProgress(event) { 163 | const bar = document.getElementById("progress_bar"); 164 | const pct = document.getElementById("progress_pct"); 165 | const icon = document.getElementById("progress_result"); 166 | 167 | // When either event value is null, make the progress bar 'indeterminate' 168 | // by removing its 'value' attribute. Otherwise, set its value accordingly. 169 | if(event.detail.increment === null || event.detail.total === null) { 170 | bar.removeAttribute("value"); 171 | pct.textContent = "∞"; 172 | } else { 173 | const val = Math.min(event.detail.increment / event.detail.total, 1.0); 174 | bar.setAttribute("value", val); 175 | pct.textContent = Math.floor(val * 100) + "%"; 176 | } 177 | 178 | icon.classList.remove("failure", "success"); 179 | icon.removeAttribute("title"); 180 | } 181 | 182 | function updateOperationResult(success) { 183 | const icon = document.getElementById("progress_result"); 184 | 185 | icon.classList.remove("failure", "success"); 186 | icon.classList.add(success ? "success" : "failure"); 187 | icon.setAttribute("title", "Operation " + (success ? "succeeded" : "failed")); 188 | 189 | if(!success) window.alert( 190 | "Operation failed!\n\n" + 191 | "See log for details." 192 | ); 193 | } 194 | 195 | function logMessage(msg, date, levelName, levelShortName) { 196 | const log = document.getElementById("log"); 197 | const debug = document.getElementById("log_debug"); 198 | 199 | if(levelName !== "Debug" || (debug.checked && levelName === "Debug")) { 200 | const line = document.createElement("p"); 201 | 202 | const time = document.createElement("span"); 203 | time.classList.add("time"); 204 | time.textContent = date.toLocaleTimeString([], { 205 | hour: "2-digit", 206 | minute: "2-digit", 207 | second: "2-digit", 208 | fractionalSecondDigits: 3 209 | }); 210 | 211 | const level = document.createElement("span"); 212 | level.classList.add("level", levelName.toLowerCase()); 213 | level.textContent = levelShortName; 214 | 215 | line.append("[", time, "][", level, "] ", msg); 216 | log.appendChild(line); 217 | log.scrollTop = log.scrollHeight; 218 | } 219 | } 220 | 221 | function clearLog() { 222 | document.getElementById("log").replaceChildren(); 223 | } 224 | 225 | /******************************************************************************/ 226 | 227 | const loader = new FirmwareLoader(); 228 | const logger = new Logger(logMessage); 229 | const devices = new DevicesDatabase(); 230 | const params = new URLSearchParams(window.location.search); 231 | 232 | loader.addParser(["hex", "ihx"], IntelHexParser); 233 | loader.addParser(["srec", "s19", "s28", "s37"], SRecordParser); 234 | loader.addParser(["elf"], ElfRiscVParser); 235 | loader.addEventListener("progress", updateUrlLoadProgress); 236 | 237 | const windowLoaded = new Promise((resolve) => window.addEventListener("load", resolve, false)); 238 | 239 | windowLoaded 240 | .then(() => { 241 | const deviceList = document.getElementById("device_list"); 242 | const deviceDtrRtsReset = document.getElementById("device_dtr_rts_reset"); 243 | const fwTabFile = document.getElementById("fw_tab_file"); 244 | const fwTabUrl = document.getElementById("fw_tab_url"); 245 | const fwUrl = document.getElementById("fw_url"); 246 | const fwUrlLoad = document.getElementById("fw_url_load"); 247 | const fwFile = document.getElementById("fw_file"); 248 | const fwHex = document.getElementById("fw_hex"); 249 | const configRead = document.getElementById("config_read"); 250 | const configWrite = document.getElementById("config_write"); 251 | const flashWrite = document.getElementById("flash_write"); 252 | const flashVerify = document.getElementById("flash_verify"); 253 | const flashErase = document.getElementById("flash_erase"); 254 | const logClear = document.getElementById("log_clear"); 255 | 256 | let device, firmware; 257 | 258 | devices.populateDeviceList(deviceList); 259 | device = devices.findDeviceByIndex(deviceList.value); 260 | 261 | fwUrl.addEventListener("input", (event) => { 262 | fwUrlLoad.disabled = !event.target.validity.valid; 263 | }); 264 | 265 | fwUrl.addEventListener("keydown", (event) => { 266 | if(event.key == "Enter" && event.target.validity.valid) { 267 | fwUrlLoad.dispatchEvent(new Event("click")); 268 | } 269 | }); 270 | 271 | fwUrlLoad.addEventListener("click", (event) => { 272 | clearHexListing(); 273 | 274 | loader.fromUrl(fwUrl.value) 275 | .then((fw) => { 276 | logger.info("Loaded " + fw.format + " firmware file from \"" + fwUrl.value + "\""); 277 | fw.fillToEndOfSegment(1024); 278 | createHexListing(fw.bytes, fw.fileName); 279 | checkFirmwareSize(fw.size, device["flash"]["size"]); 280 | firmware = fw; 281 | }) 282 | .catch((err) => { 283 | logger.error("Failed to load firmware from URL \"" + fwUrl.value + "\""); 284 | logger.error(err.message); 285 | window.alert( 286 | "Failed to load firmware from URL \"" + fwUrl.value + "\".\n\n" + 287 | "See log for details." 288 | ); 289 | firmware = undefined; 290 | setActionButtonsEnabled(false, ["flash_write", "flash_verify"]); 291 | }); 292 | }); 293 | 294 | fwFile.addEventListener("change", (event) => { 295 | if(fwFile.files.length > 0) { 296 | clearHexListing(); 297 | 298 | loader.fromFile(fwFile.files[0]) 299 | .then((fw) => { 300 | logger.info("Loaded " + fw.format + " firmware file from \"" + fwFile.files[0].name + "\""); 301 | fw.fillToEndOfSegment(1024); 302 | createHexListing(fw.bytes, fw.fileName); 303 | checkFirmwareSize(fw.size, device["flash"]["size"]); 304 | firmware = fw; 305 | }) 306 | .catch((err) => { 307 | logger.error("Failed to load firmware from file \"" + fwFile.files[0].name + "\""); 308 | logger.error(err.message); 309 | window.alert( 310 | "Failed to load firmware from file \"" + fwFile.files[0].name + "\".\n\n" + 311 | "See log for details." 312 | ); 313 | firmware = undefined; 314 | setActionButtonsEnabled(false, ["flash_write", "flash_verify"]); 315 | }); 316 | } 317 | }); 318 | 319 | fwHex.addEventListener("dragover", (event) => { 320 | event.dataTransfer.dropEffect = (event.dataTransfer.types.includes("Files") ? "copy" : "none"); 321 | event.preventDefault(); 322 | }); 323 | 324 | fwHex.addEventListener("drop", (event) => { 325 | for(const item of event.dataTransfer.items) { 326 | if(item.kind === "string" && item.type === "text/uri-list") { 327 | // Set the dropped URI as URL input value and trigger its 328 | // input event. 329 | // Why can't getAsString() just return the damned string!? 330 | item.getAsString((uri) => { 331 | fwTabUrl.checked = true; 332 | fwUrl.value = uri; 333 | fwUrl.dispatchEvent(new Event("input")); 334 | fwUrlLoad.dispatchEvent(new Event("click")); 335 | }); 336 | 337 | // Don't continue to look at any other items. 338 | break; 339 | } else if(item.kind === "file") { 340 | // Assign the dropped file(s) to file input and manually 341 | // trigger its change event. 342 | fwTabFile.checked = true; 343 | fwFile.files = event.dataTransfer.files; 344 | fwFile.dispatchEvent(new Event("change")); 345 | 346 | // Don't continue to look at any other items. 347 | break; 348 | } 349 | } 350 | 351 | event.preventDefault(); 352 | }); 353 | 354 | deviceList.addEventListener("change", (event) => { 355 | device = devices.findDeviceByIndex(deviceList.value); 356 | 357 | logger.info( 358 | "Selected device changed to: " + 359 | device["name"] + " (" + device["package"] + ", " + Formatter.byteSize(device["flash"]["size"]) + " flash)" 360 | ); 361 | 362 | if(firmware !== undefined) { 363 | checkFirmwareSize(firmware.size, device["flash"]["size"]); 364 | } 365 | }); 366 | 367 | [ 368 | "cfg_rdpr", "cfg_user", "cfg_data0", "cfg_data1", 369 | "cfg_wrpr0", "cfg_wrpr1", "cfg_wrpr2", "cfg_wrpr3" 370 | ].forEach((id) => { 371 | document.getElementById(id).addEventListener("input", (event) => { 372 | setActionButtonsEnabled(getConfigIsValid(), ["config_write"]); 373 | }); 374 | }); 375 | 376 | configRead.addEventListener("click", (event) => { 377 | const btnState = setActionButtonsEnabled(false); 378 | let success = true; 379 | const sess = new Session(device["variant"], device["type"], deviceDtrRtsReset.checked); 380 | sess.setLogger(logger); 381 | sess.addEventListener("progress", updateOperationProgress); 382 | sess.start() 383 | .then(() => sess.identify()) 384 | .then(() => sess.configRead()) 385 | .then((config) => { 386 | populateConfig(config); 387 | return sess.reset(true); 388 | }) 389 | .catch((err) => { 390 | logger.error(err.message); 391 | success = false; 392 | }) 393 | .finally(() => { 394 | sess.end(); 395 | updateOperationResult(success); 396 | restoreActionButtonsEnabled(btnState); 397 | setActionButtonsEnabled(getConfigIsValid(), ["config_write"]); 398 | }); 399 | }); 400 | 401 | configWrite.addEventListener("click", (event) => { 402 | const btnState = setActionButtonsEnabled(false); 403 | let success = true; 404 | const sess = new Session(device["variant"], device["type"], deviceDtrRtsReset.checked); 405 | sess.setLogger(logger); 406 | sess.addEventListener("progress", updateOperationProgress); 407 | sess.start() 408 | .then(() => sess.identify()) 409 | .then(() => sess.configRead()) 410 | .then(() => sess.configWrite(getConfigBytes())) 411 | .then(() => sess.reset(true)) 412 | .catch((err) => { 413 | logger.error(err.message); 414 | success = false; 415 | }) 416 | .finally(() => { 417 | sess.end(); 418 | updateOperationResult(success); 419 | restoreActionButtonsEnabled(btnState); 420 | }); 421 | }); 422 | 423 | flashWrite.addEventListener("click", (event) => { 424 | const btnState = setActionButtonsEnabled(false); 425 | let success = true; 426 | const sess = new Session(device["variant"], device["type"], deviceDtrRtsReset.checked); 427 | sess.setLogger(logger); 428 | sess.addEventListener("progress", updateOperationProgress); 429 | sess.start() 430 | .then(() => sess.identify()) 431 | .then(() => sess.configRead()) 432 | .then(() => sess.keyGenerate()) 433 | .then(() => sess.flashErase(firmware.getSectorCount(1024))) 434 | .then(() => sess.flashWrite(firmware.bytes)) 435 | .then(() => sess.keyGenerate()) 436 | .then(() => sess.flashVerify(firmware.bytes)) 437 | .then(() => sess.reset(true)) 438 | .catch((err) => { 439 | logger.error(err.message); 440 | success = false; 441 | }) 442 | .finally(() => { 443 | sess.end(); 444 | updateOperationResult(success); 445 | restoreActionButtonsEnabled(btnState); 446 | }); 447 | }); 448 | 449 | flashVerify.addEventListener("click", (event) => { 450 | const btnState = setActionButtonsEnabled(false); 451 | let success = true; 452 | const sess = new Session(device["variant"], device["type"], deviceDtrRtsReset.checked); 453 | sess.setLogger(logger); 454 | sess.addEventListener("progress", updateOperationProgress); 455 | sess.start() 456 | .then(() => sess.identify()) 457 | .then(() => sess.configRead()) 458 | .then(() => sess.keyGenerate()) 459 | .then(() => sess.flashVerify(firmware.bytes)) 460 | .then(() => sess.reset(true)) 461 | .catch((err) => { 462 | logger.error(err.message); 463 | success = false; 464 | }) 465 | .finally(() => { 466 | sess.end(); 467 | updateOperationResult(success); 468 | restoreActionButtonsEnabled(btnState); 469 | }); 470 | }); 471 | 472 | flashErase.addEventListener("click", (event) => { 473 | if(window.confirm( 474 | "Are you sure you want to ERASE the device?\n\n" + 475 | "This will destroy ALL data in the user application flash!" 476 | )) { 477 | const btnState = setActionButtonsEnabled(false); 478 | let success = true; 479 | const sess = new Session(device["variant"], device["type"], deviceDtrRtsReset.checked); 480 | sess.setLogger(logger); 481 | sess.addEventListener("progress", updateOperationProgress); 482 | sess.start() 483 | .then(() => sess.identify()) 484 | .then(() => sess.configRead()) 485 | .then(() => sess.flashErase(Math.ceil(device["flash"]["size"] / 1024))) 486 | .then(() => sess.reset(true)) 487 | .catch((err) => { 488 | logger.error(err.message); 489 | success = false; 490 | }) 491 | .finally(() => { 492 | sess.end(); 493 | updateOperationResult(success); 494 | restoreActionButtonsEnabled(btnState); 495 | }); 496 | } 497 | }); 498 | 499 | logClear.addEventListener("click", (event) => { 500 | clearLog(); 501 | }); 502 | 503 | // Wait a moment after page has fully loaded to allow browser auto-fill 504 | // of form inputs to occur, then try and take actions where necessary 505 | // according to their values. This is a bit of a hack, because there's 506 | // no event for that. 507 | setTimeout(() => { 508 | if(params.has("dev")) { 509 | // When a device name was given in URL parameter, find it and 510 | // automatically select it in the list. 511 | const idx = devices.findDeviceIndexByName(params.get("dev")); 512 | if(idx) { 513 | deviceList.value = idx; 514 | deviceList.dispatchEvent(new Event("change")); 515 | } else { 516 | throw new Error("Couldn't find device with name \"" + params.get("dev") + "\""); 517 | } 518 | } else { 519 | // Otherwise, update with any auto-filled device selection. 520 | if(deviceList.selectedOptions.length > 0) { 521 | deviceList.dispatchEvent(new Event("change")); 522 | } 523 | } 524 | 525 | if(params.has("fw")) { 526 | // When a firmware file URL was given in URL parameter, select 527 | // the 'URL' tab and load that firmware. 528 | fwTabUrl.checked = true; 529 | fwUrl.value = params.get("fw"); 530 | fwUrl.dispatchEvent(new Event("input")); 531 | fwUrlLoad.dispatchEvent(new Event("click")); 532 | } else { 533 | // Otherwise, if the Local File tab is currently selected, 534 | // update with any auto-filled firmware filename. Or, if the URL 535 | // tab is selected, process auto-filled firmware URL. 536 | if(fwTabFile.checked && fwFile.files.length > 0) { 537 | fwFile.dispatchEvent(new Event("change")); 538 | } else if(fwTabUrl.checked && fwUrl.validity.valid) { 539 | fwUrl.dispatchEvent(new Event("input")); 540 | fwUrlLoad.dispatchEvent(new Event("click")); 541 | } 542 | } 543 | }, 250); 544 | }) 545 | .catch((err) => { 546 | console.error(err); 547 | logger.error(err.message); 548 | if(err.cause instanceof Error) { 549 | logger.error(err.cause.message); 550 | } 551 | }); 552 | -------------------------------------------------------------------------------- /index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | WCH RISC-V Microcontroller Web Serial ISP 6 | 7 | 8 | 9 | 10 |
11 |
12 |

WCH RISC-V Microcontroller Web Serial ISP

13 | 14 |
15 |

Your browser does not appear to support the Web Serial API

16 |

17 | Currently, only the following browsers feature support:
18 | Chrome (v89+), Edge (v89+), Opera (v76+) 19 |

20 |
21 |
22 | 23 | 28 | 29 |
30 |
31 |

Device

32 |

33 | 34 | 38 |

39 |
40 | 41 |
42 |

Firmware File

43 |

Load from local file or URL, or drag-and-drop a file into area below.

44 |
45 | 46 | 47 | 48 | 49 |
50 |
51 |
52 | 53 |
54 |
55 |
56 |
57 | 58 | 59 |
60 | 61 |
62 |
63 |
64 |

Supported formats are: Intel Hex, S-Record, ELF, raw binary.

65 |
66 |

67 | 68 | 0 bytes 69 |

70 |
71 | 72 |
73 |

Configuration Option Bytes

74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 |
96 |

Values are in hexadecimal. See device reference manual for interpretation and appropriate values.

97 |
98 | 99 |
100 |

Actions

101 |

102 | 103 | 104 | 105 | 106 | 107 |

108 |
109 | 110 |
111 |

Progress

112 |

113 | 114 | 115 | 0% 116 |

117 |
118 | 119 |
120 |

Log

121 |
122 |

123 | 124 | 128 |

129 |
130 |
131 | 132 |
133 |

Help / FAQ

134 | 135 |
136 |

How do I get my device to run the bootloader?

137 |

Methods vary between device families. Bootloader entry at reset is typically controlled by the state of one or more pins. Consult table below, or see your device's documentation.

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 |
Device FamilyControl Pins1UART Pins2Notes
CH32V00xN/ATX = PD5,
RX = PD6
User application code must instruct device to enter the bootloader via setting FLASH_STATR.MODE flag and performing a software reset.
CH32V002N/ATX = PD0,
RX = PD1
Only for CH32V002D4U6 (QFN12). For all other CH32V002, see CH32V00x.
CH32V005N/ATX = PD0,
RX = PD1
Only for CH32V005D6U6 (QFN12). For all other CH32V005, see CH32V00x.
CH32L103BOOT0 = 1,
BOOT1 = 0
TX = PA2,
RX = PA3
CH32V103BOOT0 = 1,
BOOT1 = 0
TX = PA9,
RX = PA10
CH32V20xBOOT0 = 1,
BOOT1 = 0
TX = PA9,
RX = PA10
For CH32V203F6P6 (TSSOP20), UART communication with bootloader not possible because it does not expose pins for PA9 and PA10.
CH32V30xBOOT0 = 1,
BOOT1 = 0
TX = PA9,
RX = PA10
CH32X03xPC16 = 0,
PC17 = 1
TX = PA2,
RX = PA3
Bootloader only executes upon power-on reset, not from external (NRST) reset. Control pins are read by bootloader (not hardware). To take effect, pin states must be maintained for several milliseconds after power-on. If application flash is blank, control pins are ignored and bootloader always entered.
198 |

199 | 1. '0' indicates logic-low voltage level, '1' indicates logic-high voltage level.
200 | 2. 'TX' is transmit output from the device, 'RX' is receive input to the device.
201 |

202 |

For devices with BOOT0 and BOOT1 control pins, some package variants may have BOOT1 internally tied to GND, with only BOOT0 exposed. Other packages may not have either pin exposed, with BOOT0 tied internally to GND, effectively rendering the bootloader unusable.

203 |
204 | 205 |
206 |

What does the DTR/RTS reset sequence option do?

207 |

For devices equipped with a DTR/RTS "auto-download" reset circuit that controls NRST and BOOT0/1 pins, when this option is enabled it will, each time the serial connection is opened, give a special sequence of signals on the serial DTR and RTS lines to cause the device to be automatically reset into the bootloader.

208 |

The exact construction of such a circuit will not be covered here, but the output NRST and BOOT0/1 signal states of any circuit used, given the input DTR/RTS signals shown, should match that depicted in the diagram below.

209 |

DTRRTS100ms100msNRSTBOOT0BOOT1(Don’t Care)(Don’t Care)

210 |

Note that this is not compatible with the "Serial Port One-Click Download" CH340X circuit that is recommended by WCH for use with its WCHISPStudio software.

211 |
212 | 213 |
214 |

Why is my loaded firmware larger than it should be?

215 |

When a firmware file is loaded it is padded to the next 1,024 byte boundary. For example, a 4,835 byte firmware will be padded to 5,120 bytes.

216 |

Due to the nature of flash memory, before it can be written, an area corresponding to the size of data to be written must first be erased. However, the WCH factory bootloader only performs erasure on sizes that are multiples of 1,024 bytes. Therefore, the firmware is padded to meet the bounds of the erased area.

217 |

Padding is done with 0xFF bytes.

218 |
219 | 220 |
221 |

Why are the listed flash sizes for CH32V20x and CH32V30x larger than specified in the datasheet?

222 |

These families actually use a dual-die configuration inside the package: one for the microcontroller only, and a second for the flash memory. The MCU also features a large amount of RAM, greater than what is available to the user. At start-up, they automatically copy a certain portion of this 'external' flash into a reserved area of RAM, and code is executed from there, as if it were flash. This caching permits higher microcontroller speed than would otherwise be possible with such an 'external' flash.

223 |

For some devices in these families, the relative proportion of code flash to RAM can be configured in the option bytes (see reference manual for details). For example, less flash but more RAM, or more flash but less RAM. The datasheet specification tables list the default size allocated to the flash RAM cache, not the physical flash capacity.

224 |

The larger, actual flash capacity is utilised by this tool so that the entire capacity of flash is capable of being written to, regardless of configured flash-RAM split.

225 |
226 | 227 |
228 |

I tried to load a firmware file, but I get a maximum size exceeded error.

229 |

You may have loaded an Intel Hex or S-Record file that specifies the firmware image to be loaded at an address of 0x8000000 and onwards. Because this tool expects addressing to be relative, not absolute, such a file will cause it to first try and fill the range from 0x0 to 0x7FFFFFF with blank data before processing the file's data. Because that amount of data is larger than the maximum allowed, an error occurs.

230 |

Your firmware image should instead be based at 0x0, using relative addressing, not absolute.

231 |
232 | 233 |
234 |

Why do I get a warning in the log about the reported device variant not matching the selected device?

235 |

The specific device you have selected does not exactly match the one you are talking to.

236 |

Ensure you have selected the correct package variant for the device in question. For example, if you are using an 8-pin CH32V003J4M6, but have 20-pin CH32V003F4P6 selected, you will get this warning.

237 |

Ignoring this warning may be detrimental, due to some device families not having identical flash sizes for all their variants.

238 |
239 | 240 |
241 |

I loaded a firmware file, but the button to write to flash is disabled.

242 |

The size of the firmware is too large for the currently selected device. You will have been warned about this when loading the firmware file.

243 |

Make sure you select the correct device variant. Some families do not have an identical flash size for all their devices.

244 |

A warning is also issued if you subsequently change device to one too small after having loaded a firmware file.

245 |
246 | 247 |
248 |

I disabled read-protection by changing RDPR to 0xA5 and then writing the new config. Why does my microcontroller now no longer work?

249 |

Because your flash memory got erased!

250 |

When the RDPR option byte is changed to un-protected (value 0xA5) from previously protected (any other value), the microcontroller will automatically perform a full erasure of the user application flash memory.

251 |
252 | 253 |
254 |

Why is there no option to read flash?

255 |

The WCH bootloader does not support reading out the contents of flash — there is no command in the protocol to accomplish that.

256 |
257 | 258 |
259 |

Does my firmware data get uploaded to or saved on the server?

260 |

No. Although it is hosted on a web server, this tool runs locally in your web browser, and any firmware file you load never leaves your computer, nor is it retained anywhere.

261 |
262 | 263 |
264 |

Can I create a link to here which auto-selects a device and/or auto-loads a firmware URL?

265 |

Yes. A query string can be added to this page's URL to auto-select a device, auto-load a firmware file from an external URL, or both. Append a question-mark character (?) and then one or both of the following parameters:

266 |
    267 |
  • dev=device — replace 'device' with the full number of the desired part (e.g. dev=CH32X035C8T6). Device names specified this way are not case-sensitive.
  • 268 |
  • fw=url — replace 'url' with the full entity-encoded URL of the firmware file (e.g. fw=http%3A%2F%2Fexample.com%2Ffirmware.hex).
  • 269 |
270 |

Both parameters may be combined by separating them with an ampersand character (&). 271 |

272 | 273 |
274 |

The device I want to program is not listed.

275 |

If your device's factory bootloader supports serial UART communication, then you can request it to be added by opening a new Issue on the GitHub repository.

276 |
277 |
278 | 279 |
280 |

Copyright © 2025 Basil Hussain. Licenced under GNU AGPLv3.

281 |

No frameworks, no libraries, no BS — just plain JavaScript. Source code available on GitHub.

282 |

For more about the WCH bootloader serial protocol, see my 'missing manual' for the CH32V003 Factory Bootloader.

283 |
284 |
285 | 286 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published by 637 | the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | --------------------------------------------------------------------------------