A truly modular keyboard
C
app: update the Keyword firmware over BLE OTA
Nathanb50b13b09daf
diff --git a/app/PROTOCOL.md b/app/PROTOCOL.mdindex 6a0d4a3..81b7d89 100644--- a/app/PROTOCOL.md+++ b/app/PROTOCOL.md@@ -70,7 +70,7 @@ The Keyword lists the features it supports in `HELLO`'s `caps`. The app only sen`KEYWORD v=<fw> proto=1 caps=<comma list> kb=<n>`-- `caps` can include `batt`, `hold`, `macro` and `flash`.+- `caps` can include `batt`, `hold`, `macro`, `flash` and `ota`. `ota` is listed only while the BLE stack runs on CPU2.- `kb` is the version of the Keybit image the Keyword carries. A Keybit reporting a lower `v` is shown as outdated.- `KEY+` may carry `v=<n>`, the Keybit firmware version (Keybit register 0x01).@@ -81,6 +81,10 @@ The Keyword lists the features it supports in `HELLO`'s `caps`. The app only sen| `macro` | `MACRO uid=<uid> seq=<MMKK,MMKK,…>` | `OK MACRO uid=<uid>` || `flash` | `FLASH uid=<uid>` | `FLASH uid=<uid> pct=<n>` progress, then `OK FLASH uid=<uid>` or `ERR flash <reason>` |+| `ota` | `OTA` | `OK OTA`, then the Keyword restarts into the OTA bootloader after about 500 ms. `ERR no BLE stack on CPU2, use DFU` if it can't |+| (any) | `DFU` | `OK DFU`, then the Keyword restarts into the ROM USB DFU bootloader |+| (any) | `STACK?` | `STACK ble v=1.24.0 fus=2.2.0`, `STACK none fus=<x.y.z>` or `STACK unknown` |+How each one behaves:- **Hold (tap/hold).**@@ -93,6 +97,25 @@ How each one behaves:- **`MAP?`** can answer with several lines for one key: a `MAP`, `MAPC` or `MACRO` line, followed by a `HOLD` line if a hold action is set.- **Programming a single key,** the app sends `UNMAP`, then the key's commands, then `SAVE`. That way a stale macro or hold never survives an edit.+## Keyword firmware update (BLE OTA)++After `OK OTA` the Keyword erases its app (4-5 s) and restarts into ST's BLE_Ota bootloader. That works whichever link sent `OTA`, but the image itself always goes over Bluetooth.++- **Finding it:** it advertises as `Keyword OTA`, at the Keyword's BD address + 1, with ST manufacturer data (device ID 0x86). No pairing is needed.+- **GATT:** service `0000fe20-cc7a-482a-984a-7f2ed5b3e58f`+ - Base address `0000fe22-8e22-4541-9d4c-21edae82ed19`: write without response, 4 bytes `[cmd, offset>>16, offset>>8, offset]`, offset from 0x08000000. Start = `02 00 70 00`, finish = `07 00 00 00`, cancel = `08 00 00 00`.+ - Raw data `0000fe24-8e22-4541-9d4c-21edae82ed19`: write without response, up to MTU-3 bytes per write, appended in order.+ - Confirm `0000fe23-8e22-4541-9d4c-21edae82ed19`: indicate, 1 byte, `01` when the image is accepted.+- **Sequence:** connect, enable indications on fe23, write start, stream `firmware/release/keyword_app.bin` to fe24, write finish, wait for `01`. The Keyword then restarts into the new app. A bad image brings it back as `Keyword OTA`.+- **Pacing:** there's no flow control, so the host waits about 3 ms per 248 bytes, the bootloader's flash time.++How the app does it (Settings → **Update Keyword firmware…**, or File → Update Keyword Firmware…):++- It checks the file first: a Cortex-M vector table whose reset handler is inside 0x08007000 plus the image size. That rejects `keyword_full.bin`, which is for USB DFU.+- It sends writes of 240 bytes (176 on macOS, whose usual MTU is 185), stepping down to 176 and then 16 if the first write is refused. Every write is a multiple of 8, and the last one is padded with `FF`, because the bootloader programs flash 8 bytes at a time.+- If the Keyword reports no BLE stack, the app offers **Restart into USB DFU** instead.+- With no Keyword connected, it goes straight to finding `Keyword OTA`, so it can recover a Keyword stuck in the bootloader.+## Computer actions (no protocol)Some actions run on the computer rather than on the Keyword: open a URL, open an app, run a command, or switch profile.diff --git a/app/README.md b/app/README.mdindex 2708f8e..9e8a463 100644--- a/app/README.md+++ b/app/README.md@@ -88,6 +88,7 @@ Settings (`Cmd/Ctrl+,`) has:- keep running in the tray / menu bar when the window is closed- open at login- reset press counts, and open the data folder+- **Update Keyword firmware…**: pick `firmware/release/keyword_app.bin`, and the app restarts the Keyword into its Bluetooth bootloader and sends the image, with progress. It works when you're connected over USB too, since the image always goes over Bluetooth. If the Keyword has no Bluetooth stack, the app offers USB DFU instead. A Keyword stuck in update mode (showing as `Keyword OTA`) can be recovered from here without connecting firstThe window remembers its size and position.@@ -98,11 +99,7 @@ The window remembers its size and position.## Firmware status- **Done in the Keyword firmware:** BLE (HID keyboard, Nordic UART Service and keymap table) and USB CDC (`0483:5740`, "Keyword"). Both speak the same protocol, so either connection works.-- **Optional features** arrive as the firmware adds them, and the app turns each one on when it appears in `caps`:- - hold and macros are in progress- - Keybit versions are coming- - battery is waiting on the charger's I2C bus- - reflashing has no firmware support yet+- **Optional features** are switched on by the app when they appear in `caps`. The Keyword firmware now reports `batt`, `hold`, `macro` and `ota`, plus `kb=` for the Keybit image it carries. Reflashing Keybits from the app (`flash`) isn't reported yet.- **The Keybit side** (assigned addresses, and the side register 0x07) lives in `firmware/keybit/`.**Demo** works without any firmware.diff --git a/app/main.js b/app/main.jsindex 96cdb65..d84f849 100644--- a/app/main.js+++ b/app/main.js@@ -182,6 +182,8 @@ function buildMenu() {{ label: 'Import Profiles…', accelerator: 'CmdOrCtrl+O', click: m('import') },{ label: 'Export Profile…', accelerator: 'CmdOrCtrl+E', click: m('export') },{ label: 'Export All Profiles…', accelerator: 'CmdOrCtrl+Shift+E', click: m('export-all') },+ { type: 'separator' },+ { label: 'Update Keyword Firmware…', click: m('update-firmware') },...(IS_MAC ? [] : [{ type: 'separator' }, { label: 'Settings…', accelerator: 'Ctrl+,', click: m('settings') },{ type: 'separator' }, { role: 'quit' }]),],diff --git a/app/renderer/app.js b/app/renderer/app.jsindex 4160bf3..918d97f 100644--- a/app/renderer/app.js+++ b/app/renderer/app.js@@ -1,5 +1,5 @@/* global KeywordProtocol, Hid, Profiles, Templates */-const { SIDES, NUS, LineBuffer, parseLine, cmd, entryCommands, profileCommands, hasHold, MAX_MACRO_STEPS, DEFAULT_HOLD_MS } = KeywordProtocol;+const { SIDES, NUS, OTA, LineBuffer, parseLine, cmd, entryCommands, profileCommands, hasHold, MAX_MACRO_STEPS, DEFAULT_HOLD_MS, otaBaseCommand, checkAppImage, otaChunks } = KeywordProtocol;const POLL_MS = 2000; // ask for SIDES? this often in case a push was missedconst KEYS_POLL_MS = 10000; // full KEYS? resync@@ -174,7 +174,7 @@ class DemoTransport {for (const line of text.split('\n').map((s) => s.trim()).filter(Boolean)) {const [c] = line.split(' ');const f = Object.fromEntries(line.split(' ').slice(1).map((p) => p.split('=')));- if (c === 'HELLO') this.emit(`KEYWORD v=demo proto=1 caps=batt,hold,macro,flash kb=${this.kb}`);+ if (c === 'HELLO') this.emit(`KEYWORD v=demo proto=1 caps=batt,hold,macro,flash,ota kb=${this.kb}`);else if (c === 'SIDES?') this.emit(this.sidesLine());else if (c === 'BATT?') this.emit(this.battLine());else if (c === 'KEYS?') {@@ -186,12 +186,58 @@ class DemoTransport {else if (c === 'CLEAR') { this.maps = {}; this.emit('OK CLEAR'); }else if (c === 'SAVE') this.emit('OK SAVE');else if (c === 'FLASH') this.flash(f.uid);+ else if (c === 'STACK?') this.emit('STACK ble v=1.24.0 fus=2.2.0');+ else if (c === 'OTA') this.emit('OK OTA');+ else if (c === 'DFU') this.emit('OK DFU');else this.emit(`ERR unknown command ${c}`);}}async close() { clearInterval(this.battTimer); this.onText = null; }}+// ---- Keyword firmware update targets: connect(), start(), write(chunk), finish(), cancel(), close() ----++// ST's BLE_Ota bootloader, which the Keyword restarts into after OTA.+class BleOtaTarget {+ async connect() {+ this.device = await navigator.bluetooth.requestDevice({+ filters: [{ name: OTA.name }],+ optionalServices: [OTA.service],+ });+ const server = await this.device.gatt.connect();+ const svc = await server.getPrimaryService(OTA.service);+ this.base = await svc.getCharacteristic(OTA.base);+ this.raw = await svc.getCharacteristic(OTA.raw);+ this.confirm = await svc.getCharacteristic(OTA.confirm);+ this.confirmed = new Promise((resolve) => {+ this.confirm.addEventListener('characteristicvaluechanged', (e) => resolve(e.target.value.getUint8(0)));+ });+ await this.confirm.startNotifications(); // indications, as far as Web Bluetooth is concerned+ this.lost = new Promise((resolve) => this.device.addEventListener('gattserverdisconnected', resolve, { once: true }));+ }+ async writeBase(bytes) {+ if (this.base.writeValueWithoutResponse) await this.base.writeValueWithoutResponse(bytes);+ else await this.base.writeValue(bytes);+ }+ start() { return this.writeBase(otaBaseCommand(OTA.START, OTA.APP_OFFSET)); }+ write(chunk) { return this.raw.writeValueWithoutResponse ? this.raw.writeValueWithoutResponse(chunk) : this.raw.writeValue(chunk); }+ finish() { return this.writeBase(otaBaseCommand(OTA.FINISH)); }+ cancel() { return this.writeBase(otaBaseCommand(OTA.CANCEL)).catch(() => {}); }+ close() { if (this.device?.gatt.connected) this.device.gatt.disconnect(); }+}++// Stands in for the bootloader in Demo mode.+class DemoOtaTarget {+ async connect() { await sleep(400); this.bytes = 0; }+ async start() { this.bytes = 0; }+ async write(chunk) { this.bytes += chunk.length; }+ async finish() { await sleep(300); this.confirmed = Promise.resolve(this.bytes > 0 ? 1 : 0); this.lost = new Promise(() => {}); }+ async cancel() {}+ close() {}+}++const sleep = (ms) => new Promise((r) => setTimeout(r, ms));+// ---- Saved state (main.js writes it to disk; localStorage when run in a browser) ----const storage = bridge@@ -490,10 +536,20 @@ async function copyUid(uid) {// ---- Protocol handling ----+// Lets a flow wait for a particular reply. pred returns true to take the message.+const waiters = new Set();+function waitForMessage(pred, ms) {+ return new Promise((resolve) => {+ const w = { pred, resolve, timer: setTimeout(() => { waiters.delete(w); resolve(null); }, ms) };+ waiters.add(w);+ });+}+function handleLine(line) {lastRx = Date.now();log('<-', line);const msg = parseLine(line);+ for (const w of [...waiters]) if (w.pred(msg)) { clearTimeout(w.timer); waiters.delete(w); w.resolve(msg); }switch (msg.type) {case 'hello': {const first = !device.fw;@@ -765,7 +821,7 @@ async function autoConnectOnLaunch() {// A Keyword plugged back in over USB reconnects straight away.if ('serial' in navigator) {navigator.serial.addEventListener('connect', async () => {- if (transport || !settings().autoReconnect || settings().lastConnection?.kind !== 'serial') return;+ if (transport || ota.busy || !settings().autoReconnect || settings().lastConnection?.kind !== 'serial') return;const port = await findSerialPort();if (port) connect(new SerialTransport(port), { auto: true }).catch((e) => log('!!', e.message));});@@ -1243,6 +1299,212 @@ function useTemplate(t, uids, asNew) {$('#p-library').onclick = openLibrary;$('#library-close').onclick = () => closeDialog($('#library'));+// ---- Keyword firmware update (BLE OTA) ----++// The Keyword restarts into ST's BLE_Ota bootloader on OTA, erasing its app first (4-5 s).+// From there the image goes over Bluetooth whatever link the app was using.+const OTA_RESTART_MS = 6500;+const ota = { busy: false, image: null, fileName: '', stage: 'pick', target: null, demo: false, cancelled: false };++function otaSet(text, { error = false, pct = null } = {}) {+ const st = $('#ota-status');+ st.textContent = text;+ st.classList.toggle('error-text', error);+ $('#ota-progress').hidden = pct == null;+ if (pct != null) $('#ota-progress').value = pct;+}++function otaButtons() {+ const go = $('#ota-go');+ const realLink = transport && !(transport instanceof DemoTransport);+ const labels = {+ pick: realLink || transport ? 'Start update' : `Find ${OTA.name}`,+ find: `Find ${OTA.name}`,+ sending: 'Sending…', done: 'Done', waiting: 'Restarting…',+ };+ go.textContent = labels[ota.stage];+ go.disabled = ota.stage === 'sending' || ota.stage === 'waiting' || (ota.stage !== 'done' && !ota.image);+ $('#ota-cancel').textContent = ota.stage === 'sending' ? 'Cancel' : 'Close';+ $('#ota-file').disabled = ota.busy;+}++async function openOta() {+ if (ota.busy) { $('#ota').showModal(); return; }+ Object.assign(ota, { stage: 'pick', cancelled: false, demo: transport instanceof DemoTransport });+ $('#ota-dfu').hidden = true;+ $('#ota-stack').textContent = '';+ otaSet(transport+ ? (can('ota') ? '' : 'This Keyword firmware does not report OTA support. The update will be tried anyway.')+ : `Not connected. If the Keyword is already in update mode (it shows up as "${OTA.name}"), pick the image and find it.`);+ otaButtons();+ closeDialog($('#settings'));+ $('#ota').showModal();+ if (transport && device.fw) {+ send(cmd.stack());+ const m = await waitForMessage((x) => x.type === 'stack' || (x.type === 'error' && /stack/i.test(x.message)), 2000);+ if (m?.type === 'stack') {+ $('#ota-stack').textContent = `Keyword firmware ${device.fw} · wireless stack ${m.stack === 'ble' ? `BLE ${m.v || ''}` : m.stack}${m.fus ? ` · FUS ${m.fus}` : ''}`;+ if (m.stack === 'none') {+ otaSet('The Keyword has no Bluetooth stack on its radio core, so it can only be updated over USB DFU.', { error: true });+ $('#ota-dfu').hidden = false;+ }+ } else $('#ota-stack').textContent = `Keyword firmware ${device.fw}`;+ }+}++$('#ota-file').onchange = async (e) => {+ const f = e.target.files[0];+ ota.image = null;+ if (f) {+ const bytes = new Uint8Array(await f.arrayBuffer());+ const check = checkAppImage(bytes);+ if (check.ok) {+ ota.image = bytes;+ ota.fileName = f.name;+ $('#ota-file-info').textContent = `${f.name} · ${(bytes.length / 1024).toFixed(1)} KB`;+ if ($('#ota-dfu').hidden) otaSet('');+ } else {+ $('#ota-file-info').textContent = '';+ otaSet(check.error, { error: true });+ }+ }+ otaButtons();+};++$('#ota-go').onclick = async () => {+ if (ota.stage === 'done') return closeDialog($('#ota'));+ if (ota.stage === 'pick' && transport) return otaRestartKeyword();+ return otaSend();+};++$('#ota-cancel').onclick = async () => {+ if (ota.stage === 'sending') {+ ota.cancelled = true;+ return;+ }+ closeDialog($('#ota'));+};+$('#ota').addEventListener('cancel', (e) => { if (ota.busy) e.preventDefault(); });++$('#ota-dfu').onclick = async () => {+ if (!transport) return;+ if (!confirm('Restart the Keyword into its USB DFU bootloader? It stops working as a keyboard until it is flashed with STM32CubeProgrammer (or dfu-util) and restarted.')) return;+ send(cmd.dfu());+ const m = await waitForMessage((x) => (x.type === 'ok' && x.what === 'DFU') || x.type === 'error', 2000);+ if (m?.type === 'ok') {+ await disconnect();+ otaSet('The Keyword is in USB DFU mode. Flash keyword_full.bin at 0x08000000 with STM32CubeProgrammer.');+ } else otaSet(m ? `Keyword: ${m.message}` : 'No reply from the Keyword.', { error: true });+};++// Step 1: ask the running Keyword to restart into the bootloader.+async function otaRestartKeyword() {+ ota.busy = true;+ ota.stage = 'waiting';+ otaButtons();+ otaSet('Asking the Keyword to restart into update mode…');+ send(cmd.ota());+ const m = await waitForMessage((x) => (x.type === 'ok' && x.what === 'OTA') || x.type === 'error', 3000);+ if (m?.type !== 'ok') {+ ota.busy = false;+ ota.stage = 'pick';+ otaButtons();+ if (m && /no BLE stack/i.test(m.message)) {+ otaSet('The Keyword has no Bluetooth stack on its radio core, so it can only be updated over USB DFU.', { error: true });+ $('#ota-dfu').hidden = false;+ } else otaSet(m ? `Keyword: ${m.message}` : 'The Keyword did not answer. Its firmware may be too old for OTA.', { error: true });+ return;+ }+ ota.demo = transport instanceof DemoTransport;+ await disconnect();+ activity('Keyword restarting into update mode');+ const until = Date.now() + (ota.demo ? 1500 : OTA_RESTART_MS);+ while (Date.now() < until) {+ otaSet(`The Keyword is erasing its app and restarting into update mode… ${Math.ceil((until - Date.now()) / 1000)}`);+ await sleep(250);+ }+ ota.stage = 'find';+ otaButtons();+ // Web Bluetooth only opens its picker from a click, so the user presses Find.+ otaSet(`Ready. Click "Find ${OTA.name}" and pick it from the list.`);+}++// Step 2: send the image to the bootloader.+async function otaSend() {+ if (!ota.image) return;+ if (!ota.demo && !('bluetooth' in navigator)) return otaSet('Web Bluetooth is not available here.', { error: true });+ ota.busy = true;+ ota.cancelled = false;+ stopReconnect();+ const target = ota.demo ? new DemoOtaTarget() : new BleOtaTarget();+ ota.target = target;+ try {+ otaSet(`Connecting to ${OTA.name}…`);+ ota.stage = 'waiting';+ otaButtons();+ await target.connect();+ ota.stage = 'sending';+ otaButtons();+ await target.start();+ // There's no flow control, so pace the writes to the bootloader's flash speed (~3 ms per 248 bytes).+ // Chunks fit common MTUs; if a size is refused, step down to a smaller one.+ const sizes = MAC ? [176, 16] : [240, 176, 16];+ let chunks = otaChunks(ota.image, sizes[0]);+ let size = 0;+ let sent = 0;+ const t0 = Date.now();+ for (let i = 0; i < chunks.length; i++) {+ if (ota.cancelled) throw new Error('cancelled');+ try {+ await target.write(chunks[i]);+ } catch (e) {+ if (i > 0 || size + 1 >= sizes.length) throw e;+ size++;+ log('!!', `OTA write of ${chunks[i].length} B refused (${e.message}), trying ${sizes[size]}`);+ chunks = otaChunks(ota.image, sizes[size]);+ i = -1;+ continue;+ }+ sent += chunks[i].length;+ await sleep(Math.max(2, Math.ceil(chunks[i].length / 248 * 3) + 1));+ if (i % 8 === 0 || i === chunks.length - 1) {+ const rate = sent / Math.max(1, Date.now() - t0); // bytes per ms+ const left = Math.ceil((ota.image.length - sent) / rate / 1000);+ otaSet(`Sending ${ota.fileName}… ${Math.round(sent / 1024)} of ${Math.round(ota.image.length / 1024)} KB${left > 1 ? ` · about ${left} s left` : ''}`,+ { pct: Math.min(100, Math.round(sent / ota.image.length * 100)) });+ }+ }+ otaSet('Checking the image…', { pct: 100 });+ await target.finish();+ const ack = await Promise.race([target.confirmed, target.lost.then(() => 'lost'), sleep(15000).then(() => 'timeout')]);+ if (ack === 1) {+ ota.stage = 'done';+ otaSet('Updated. The Keyword is restarting with the new firmware.');+ activity('Keyword firmware updated', 'add');+ toast('Keyword firmware updated');+ target.close();+ setTimeout(() => { if (!ota.demo) autoConnectOnLaunch(); else connect(new DemoTransport()); }, 3000);+ } else {+ throw new Error(ack === 'lost' ? 'the Keyword disconnected before confirming'+ : ack === 'timeout' ? 'no confirmation from the Keyword' : `the Keyword rejected the image (${ack})`);+ }+ } catch (e) {+ await target.cancel?.();+ target.close();+ ota.stage = 'find';+ if (e.name === 'NotFoundError') otaSet(`Didn't find ${OTA.name}. Click Find to try again.`);+ else if (e.message === 'cancelled') otaSet(`Cancelled. The Keyword stays in update mode (as "${OTA.name}") until it gets a good image.`);+ else otaSet(`Update failed: ${e.message}. The Keyword stays in update mode, so you can try again.`, { error: true });+ log('!!', `OTA: ${e.message}`);+ } finally {+ ota.busy = false;+ ota.target = null;+ otaButtons();+ }+}++$('#set-ota').onclick = openOta;+// ---- Settings ----function applySettings() {@@ -1336,6 +1598,7 @@ function onMenu(command, arg) {case 'library': openLibrary(); break;case 'apply': applyProfile(false); break;case 'toggle-theme': toggleTheme(); break;+ case 'update-firmware': openOta(); break;case 'find': $('#key-filter').focus(); $('#key-filter').select(); break;}}diff --git a/app/renderer/index.html b/app/renderer/index.htmlindex 492aec3..f7fba9a 100644--- a/app/renderer/index.html+++ b/app/renderer/index.html@@ -173,6 +173,7 @@<label class="check"><input type="checkbox" id="set-closeToTray"> Keep running in the menu bar / tray when closed</label><label class="check"><input type="checkbox" id="set-launchAtLogin"> Open at login</label><div class="btn-row">+ <button id="set-ota" class="ghost small">Update Keyword firmware…</button><button id="set-export-all" class="ghost small">Export all profiles…</button><button id="set-reset-stats" class="ghost small">Reset press counts</button><button id="set-data" class="ghost small">Open data folder</button>@@ -181,6 +182,22 @@<div class="dialog-actions"><button id="settings-close">Done</button></div></dialog>+ <dialog id="ota">+ <h2>Update Keyword firmware</h2>+ <p class="hint">Sends a new firmware image to the Keyword over Bluetooth, even when you're connected over USB. Pick <code>keyword_app.bin</code> from <code>firmware/release</code>.</p>+ <p id="ota-stack" class="hint small-text"></p>+ <label class="field">Firmware image <input type="file" id="ota-file" accept=".bin"></label>+ <p id="ota-file-info" class="hint small-text"></p>+ <progress id="ota-progress" max="100" value="0" hidden></progress>+ <p id="ota-status" class="small-text" aria-live="polite"></p>+ <div class="dialog-actions">+ <button id="ota-dfu" class="ghost" hidden>Restart into USB DFU</button>+ <span class="spacer"></span>+ <button id="ota-cancel" class="ghost">Close</button>+ <button id="ota-go">Start update</button>+ </div>+ </dialog>+<dialog id="prompt"><h2 id="prompt-title"></h2><input id="prompt-input" maxlength="80" list="prompt-list">diff --git a/app/renderer/protocol.js b/app/renderer/protocol.jsindex 3cf6070..d2d71d0 100644--- a/app/renderer/protocol.js+++ b/app/renderer/protocol.js@@ -10,6 +10,49 @@tx: '6e400003-b5a3-f393-e0a9-e50e24dcca9e', // keyword notifies here};+ // ST BLE_Ota bootloader on the Keyword, reached with the OTA command. See PROTOCOL.md.+ const OTA = {+ name: 'Keyword OTA',+ service: '0000fe20-cc7a-482a-984a-7f2ed5b3e58f',+ base: '0000fe22-8e22-4541-9d4c-21edae82ed19', // write: [cmd, offset >> 16, >> 8, offset]+ confirm: '0000fe23-8e22-4541-9d4c-21edae82ed19', // indicate: 0x01 once the image is accepted+ raw: '0000fe24-8e22-4541-9d4c-21edae82ed19', // write without response: image bytes, in order+ START: 0x02, FINISH: 0x07, CANCEL: 0x08,+ FLASH_BASE: 0x08000000,+ APP_OFFSET: 0x7000, // the app lives at 0x08007000, behind the bootloader+ MAX_SIZE: 0x08100000 - 0x08007000,+ };+ const otaBaseCommand = (op, offset = 0) => new Uint8Array([op, (offset >> 16) & 0xff, (offset >> 8) & 0xff, offset & 0xff]);++ // Sanity checks an app image before sending it: the right file, linked for 0x08007000.+ function checkAppImage(bytes) {+ if (!bytes || bytes.length < 64) return { ok: false, error: 'The file is too small to be a Keyword firmware image.' };+ if (bytes.length > OTA.MAX_SIZE) return { ok: false, error: 'The file is too big for the Keyword.' };+ const word = (i) => (bytes[i] | (bytes[i + 1] << 8) | (bytes[i + 2] << 16) | (bytes[i + 3] << 24)) >>> 0;+ const sp = word(0), reset = word(4);+ if (sp < 0x20000000 || sp > 0x20040000 || !(reset & 1)) {+ return { ok: false, error: "This doesn't look like a Keyword firmware image (no vector table at the start)." };+ }+ const appStart = OTA.FLASH_BASE + OTA.APP_OFFSET;+ if (reset < appStart || reset >= appStart + bytes.length) {+ return { ok: false, error: reset < appStart+ ? 'This image starts at 0x08000000, so it is the full image for USB DFU. Pick keyword_app.bin instead.'+ : 'This image is not linked for 0x08007000.' };+ }+ return { ok: true, size: bytes.length };+ }++ // Splits an image into OTA writes. The bootloader programs flash 8 bytes at a time,+ // so chunks are multiples of 8 and the tail is padded with 0xFF (erased flash).+ function otaChunks(bytes, size) {+ const step = Math.max(8, size - (size % 8));+ const padded = new Uint8Array(Math.ceil(bytes.length / 8) * 8).fill(0xff);+ padded.set(bytes);+ const out = [];+ for (let i = 0; i < padded.length; i += step) out.push(padded.subarray(i, i + step));+ return out;+ }+const MAX_MACRO_STEPS = 16;const DEFAULT_HOLD_MS = 200;@@ -59,6 +102,9 @@mapQuery: (uid) => `MAP? uid=${uid}`,unmap: (uid) => `UNMAP uid=${uid}`,flash: (uid) => `FLASH uid=${uid}`,+ ota: () => 'OTA',+ dfu: () => 'DFU',+ stack: () => 'STACK?',clear: () => 'CLEAR',save: () => 'SAVE',};@@ -149,6 +195,9 @@case 'FLASH':if (!uid) break;return { type: 'flashProgress', uid, pct: Math.max(0, Math.min(100, int(f.pct))) };+ case 'STACK':+ // STACK ble v=1.24.0 fus=2.2.0 | STACK none fus=x.y.z | STACK unknown+ return { type: 'stack', stack: parts[1] || 'unknown', v: f.v || null, fus: f.fus || null };case 'OK':return { type: 'ok', what: parts[1] || '', ...parseFields(parts.slice(2)) };case 'ERR':@@ -160,6 +209,7 @@const api = {SIDES, NUS, MAX_MACRO_STEPS, DEFAULT_HOLD_MS, LineBuffer, parseLine, cmd,mapCommand, entryCommands, profileCommands, isUid, hasHold,+ OTA, otaBaseCommand, checkAppImage, otaChunks,};if (typeof module !== 'undefined' && module.exports) module.exports = api;else root.KeywordProtocol = api;diff --git a/app/renderer/style.css b/app/renderer/style.cssindex 7edaa31..1f54ac6 100644--- a/app/renderer/style.css+++ b/app/renderer/style.css@@ -225,3 +225,11 @@ dialog > * + * { margin-top: 8px; }.library li p { margin: 2px 0 0; }.library .preview { font-size: 12px; color: var(--muted); font-family: ui-monospace, Menlo, monospace; }.library .btns { display: flex; flex-direction: column; gap: 6px; flex: none; }++/* Firmware update */+#ota progress { width: 100%; height: 8px; appearance: none; border: none; border-radius: 4px; background: var(--line); overflow: hidden; }+#ota progress::-webkit-progress-bar { background: var(--line); border-radius: 4px; }+#ota progress::-webkit-progress-value { background: var(--accent); border-radius: 4px; transition: width 0.2s; }+#ota input[type=file] { display: block; margin-top: 4px; font: inherit; color: var(--text); }+#ota code { font-size: 12px; }+.error-text { color: var(--danger); }diff --git a/app/test/protocol.test.js b/app/test/protocol.test.jsindex 2b66127..cb29b02 100644--- a/app/test/protocol.test.js+++ b/app/test/protocol.test.js@@ -97,3 +97,26 @@ test('relayed Keybits', () => {assert.deepStrictEqual(parseLine('KEY+ uid=D00DF00D at=X via=91C7002DE4B3A75C0A33B7E2 depth=2 v=3'),{ type: 'keyAdd', uid: 'D00DF00D', at: null, v: 3, via: '91C7002DE4B3A75C0A33B7E2', depth: 2 });});++test('OTA: stack reply, image checks and chunks', () => {+ const { OTA, otaBaseCommand, checkAppImage, otaChunks } = require('../renderer/protocol.js');+ assert.deepStrictEqual(parseLine('STACK ble v=1.24.0 fus=2.2.0'), { type: 'stack', stack: 'ble', v: '1.24.0', fus: '2.2.0' });+ assert.deepStrictEqual(parseLine('STACK none fus=2.2.0'), { type: 'stack', stack: 'none', v: null, fus: '2.2.0' });+ assert.deepStrictEqual([...otaBaseCommand(OTA.START, OTA.APP_OFFSET)], [0x02, 0x00, 0x70, 0x00]);+ assert.deepStrictEqual([...otaBaseCommand(OTA.FINISH)], [0x07, 0, 0, 0]);++ const image = (sp, reset, len = 1000) => {+ const b = new Uint8Array(len);+ new DataView(b.buffer).setUint32(0, sp, true);+ new DataView(b.buffer).setUint32(4, reset, true);+ return b;+ };+ assert.ok(checkAppImage(image(0x20030000, 0x08007119)).ok);+ assert.match(checkAppImage(image(0x20030000, 0x08000119)).error, /keyword_app\.bin/);+ assert.match(checkAppImage(image(0x12345678, 0x08007119)).error, /vector table/);+ assert.match(checkAppImage(new Uint8Array(10)).error, /too small/);++ const chunks = otaChunks(new Uint8Array(500).fill(1), 244);+ assert.deepStrictEqual(chunks.map((c) => c.length), [240, 240, 24]);+ assert.deepStrictEqual([...chunks[2].slice(18)], [1, 1, 0xff, 0xff, 0xff, 0xff]);+});