From 17ca9dc2a7a02d8aa0176462a2522a50237f5a64 Mon Sep 17 00:00:00 2001 From: Egor Kolesnikov Date: Sun, 29 Nov 2026 13:14:06 +0200 Subject: [PATCH] Install firmware and the App Loader on a Watch 3 Pro Every watch with a known board (BOARDS) is flashable now, not only the Watch Pro 2: the stock OTA sequence is the same, and the board gate still holds an image to its record and to the watch on the line. A local image from /dev goes to the watch its board names. The App Loader stub on a Watch 3 Pro answers StubVersion with a 7th byte, its model, and takes DATA on 0x90A9 (stock 1.0.1.77 handles 0x90A2 as Do Not Disturb). readWp2 reads the model, installPackage picks the opcode, and planInstall refuses a loader built for the other model (header byte 0x38) before anything is sent, as cmf-watch-sdk install.py does. Co-Authored-By: Claude Opus 5.5 --- src/lib/modules/device/lib/ble-protocol.ts | 5 +- src/lib/modules/device/lib/ble.ts | 8 ++- src/lib/modules/device/lib/ota-image.ts | 13 ++-- src/lib/modules/device/lib/wp2.ts | 35 ++++++++-- src/lib/modules/device/messages.ts | 17 ++--- src/lib/modules/device/model/dev.model.ts | 8 +-- src/lib/modules/store/i18n.ts | 10 +-- src/lib/modules/store/lib/firmware.ts | 9 ++- tests/firmware-device.browser.test.ts | 38 ++++++----- tests/ota.browser.test.ts | 12 ++-- tests/wp2.browser.test.ts | 76 ++++++++++++++++++++-- 11 files changed, 166 insertions(+), 65 deletions(-) diff --git a/src/lib/modules/device/lib/ble-protocol.ts b/src/lib/modules/device/lib/ble-protocol.ts index 12d3ecd..49066b3 100644 --- a/src/lib/modules/device/lib/ble-protocol.ts +++ b/src/lib/modules/device/lib/ble-protocol.ts @@ -112,13 +112,16 @@ export const CMD = { otaCommit: C(0xffff, 0x9041), otaStatus43: C(0xffff, 0xa043), // terminal, meaning undocumented otaStatus44: C(0xffff, 0xa044), // terminal, meaning undocumented - // the App Loader stub's install channel (cmf-watch-sdk, docs/abi-1.4.md); only INFO is used here + // the App Loader stub's install channel (cmf-watch-sdk, docs/abi-1.4.md); INFO, BEGIN, DATA, END stubInfo: C(0xffff, 0x90a0), stubInfoRep: C(0xffff, 0xb0a0), stubBegin: C(0xffff, 0x90a1), stubBeginRep: C(0xffff, 0xb0a1), stubData: C(0xffff, 0x90a2), stubDataRep: C(0xffff, 0xb0a2), + // DATA on a Watch 3 Pro stub (wp2.ts DATA_OPCODES) + stubDataWp3: C(0xffff, 0x90a9), + stubDataWp3Rep: C(0xffff, 0xb0a9), stubEnd: C(0xffff, 0x90a3), stubEndRep: C(0xffff, 0xb0a3), }; diff --git a/src/lib/modules/device/lib/ble.ts b/src/lib/modules/device/lib/ble.ts index b58fa92..d75632a 100644 --- a/src/lib/modules/device/lib/ble.ts +++ b/src/lib/modules/device/lib/ble.ts @@ -34,6 +34,7 @@ import { planInstall, STATUS_NAMES, parseStubReply, + MODEL_WP3, STATUS_OK, STUB_SLOT, type Wp2Package, @@ -1064,6 +1065,11 @@ export class Watch { const head = new Uint8Array(9), hv = new DataView(head.buffer); + const dataCmds = + state.stub.model === MODEL_WP3 + ? ([CMD.stubDataWp3, CMD.stubDataWp3Rep] as const) + : ([CMD.stubData, CMD.stubDataRep] as const); + head[0] = slot; hv.setUint32(1, data.length, true); hv.setUint32(5, crc32(data), true); @@ -1076,7 +1082,7 @@ export class Watch { new DataView(req.buffer).setUint32(0, off, true); req.set(part, 4); - const r = await call(CMD.stubData, CMD.stubDataRep, req); + const r = await call(...dataCmds, req); const written = new DataView(r.buffer, r.byteOffset).getUint32(1, true); if (written !== off + part.length) diff --git a/src/lib/modules/device/lib/ota-image.ts b/src/lib/modules/device/lib/ota-image.ts index aab7f6b..b0c1ad6 100644 --- a/src/lib/modules/device/lib/ota-image.ts +++ b/src/lib/modules/device/lib/ota-image.ts @@ -30,14 +30,17 @@ export const BOARDS: Record = { watch_pro_2: { board: "jx402_01_3089c", advertised: /watch pro 2/i }, watch_3_pro: { board: "jx402_08", advertised: /watch (3 pro|pro 3)/i }, }; -/** The one watch the OTA path (Watch.flashFirmware) has ever been run against. */ -export const OTA_DEVICE = "watch_pro_2"; -export const OTA_BOARD = BOARDS[OTA_DEVICE].board; +/** The Watch Pro 2's board; the stock OTA sequence (Watch.flashFirmware) is the same on every watch in BOARDS. */ +export const OTA_BOARD = BOARDS.watch_pro_2.board; /** The `device` of a watch by its advertised name, or null when it's none of BOARDS. */ export const watchDevice = (name: string | null) => Object.keys(BOARDS).find((d) => BOARDS[d].advertised.test(name ?? "")) ?? null; +/** The `device` an image's board belongs to, or null. */ +export const boardDevice = (board: string) => + Object.keys(BOARDS).find((d) => BOARDS[d].board === board) ?? null; + const KNOWN_BOARDS = new Set(Object.values(BOARDS).map((b) => b.board)); const label = (device: string) => DEVICES.find((d) => d.value === device)?.label ?? device; @@ -177,7 +180,7 @@ export function inspectOtaImage(d: Uint8Array): OtaImage { * The whole gate before a flash: the image is sound (inspectOtaImage), and its board is the * board of the watch on the line (by its advertised name) and of the record being flashed * (`device`, empty = DEFAULT_DEVICE). Any mismatch, or a watch or record with no known board, - * throws before a byte goes out. Then only OTA_DEVICE passes: the protocol is its alone. + * throws before a byte goes out. */ export function checkOtaTarget(d: Uint8Array, watchName: string | null, device: unknown) { const info = inspectOtaImage(d); @@ -199,7 +202,5 @@ export function checkOtaTarget(d: Uint8Array, watchName: string | null, device: `the image is built for board "${info.board}", but “${name}” is a ` + `${label(watch[0])} (board "${watch[1].board}")`, ); - if (watch[0] !== OTA_DEVICE) - throw new Error(`firmware updates are for the ${label(OTA_DEVICE)} only, this is “${name}”`); return info; } diff --git a/src/lib/modules/device/lib/wp2.ts b/src/lib/modules/device/lib/wp2.ts index 33cce60..01b4857 100644 --- a/src/lib/modules/device/lib/wp2.ts +++ b/src/lib/modules/device/lib/wp2.ts @@ -15,11 +15,26 @@ export const STUB_SLOT = 0xfe; export const STATUS_OK = 0; export const STATUS_BAD_REQUEST = 1; +// the stub's model (a 7th StubVersion byte; a Watch Pro 2 stub sends none) and the opcode it takes DATA on: +// the Watch 3 Pro's stock firmware handles 0x90A2 itself (Do Not Disturb sync), so its stub listens on 0x90A9 +export const MODEL_WP2 = 1; +export const MODEL_WP3 = 2; +export const DATA_OPCODES: Record = { [MODEL_WP2]: 0x90a2, [MODEL_WP3]: 0x90a9 }; +/** Package header byte 0x38: the model a loader is built for (0 Watch Pro 2, 2 Watch 3 Pro); 0 for every app. */ +export const LOADER_MODEL_OFFSET = 0x38; +const LOADER_MODELS: Record = { [MODEL_WP2]: 0, [MODEL_WP3]: 2 }; +const MODEL_NAMES: Record = { + [MODEL_WP2]: "Watch Pro 2", + [MODEL_WP3]: "Watch 3 Pro", +}; + export interface Wp2Stub { /** 1 for every stub from before the release was readable. */ version: number; /** The highest package abi_minor it takes; unknown on stub 1. */ abiMinor: number | null; + /** MODEL_WP2 or MODEL_WP3. */ + model: number; } export interface Wp2Package { @@ -61,9 +76,16 @@ export function parsePackageHeader(h: Uint8Array): Wp2Package | null { export function parseStubReply(r: Uint8Array): Wp2Stub { // an older stub reads 0xFE as a bad slot - if (r[0] === STATUS_BAD_REQUEST) return { version: 1, abiMinor: null }; - if (r.length !== 6 || r[0] !== STATUS_OK) throw new Error("unexpected stub reply"); - return { version: new DataView(r.buffer, r.byteOffset).getUint32(1, true), abiMinor: r[5] }; + if (r[0] === STATUS_BAD_REQUEST) return { version: 1, abiMinor: null, model: MODEL_WP2 }; + const model = r.length === 7 ? r[6] : MODEL_WP2; + + if ((r.length !== 6 && r.length !== 7) || r[0] !== STATUS_OK || !(model in DATA_OPCODES)) + throw new Error("unexpected stub reply"); + return { + version: new DataView(r.buffer, r.byteOffset).getUint32(1, true), + abiMinor: r[5], + model, + }; } /** Is the catalog's build the one on the watch? Same name, same image. */ @@ -120,8 +142,11 @@ export function planInstall(data: Uint8Array, state: Wp2State, crc32: (d: Uint8A let slot: number; - if (pkg.kind === 1) slot = LOADER_SLOT; - else if (pkg.kind === 0) { + if (pkg.kind === 1) { + if (data[LOADER_MODEL_OFFSET] !== LOADER_MODELS[state.stub.model]) + fail(`it's an App Loader for another watch, not the ${MODEL_NAMES[state.stub.model]}`); + slot = LOADER_SLOT; + } else if (pkg.kind === 0) { const same = Object.entries(state.apps).find(([, p]) => p.name === pkg.name); const free = Array.from({ length: APP_SLOTS }, (_, i) => i).find((i) => !state.apps[i]); diff --git a/src/lib/modules/device/messages.ts b/src/lib/modules/device/messages.ts index df31ca4..8e89d0e 100644 --- a/src/lib/modules/device/messages.ts +++ b/src/lib/modules/device/messages.ts @@ -95,8 +95,7 @@ const en = { boardVsWatch: (img: string, name: string, device: string, board: string) => `the image is built for board "${img}", but “${name}” is a ${device} (board "${board}")`, stockOnlyPro3: (name: string) => `this way out is for a CMF Watch 3 Pro, not ${name}`, - otaOnly: (device: string, name: string) => - `firmware updates are for the ${device} only, this is “${name}”`, + loaderModel: (watch: string) => `it's an App Loader for another watch, not the ${watch}`, // apps (the App Loader stub) stubReply: "unexpected stub reply", appRunning: (name: string) => `${name} is running on the watch — leave it and try again`, @@ -210,7 +209,7 @@ export const bt = dict(en, { boardVsWatch: (img, name, device, board) => `образ собран для платы "${img}", а «${name}» — это ${device} (плата "${board}")`, stockOnlyPro3: (name) => `это средство только для CMF Watch 3 Pro, а это ${name}`, - otaOnly: (device, name) => `обновления прошивки только для ${device}, а это «${name}»`, + loaderModel: (watch) => `это App Loader для другой модели часов, не для ${watch}`, stubReply: "неожиданный ответ App Loader", appRunning: (name) => `${name} запущено на часах — выйдите из него и попробуйте снова`, refusedCmd: (cmd, why) => `часы отклонили ${cmd}: ${why}`, @@ -321,7 +320,7 @@ export const bt = dict(en, { boardVsWatch: (img, name, device, board) => `образ зібрано для плати "${img}", а «${name}» — це ${device} (плата "${board}")`, stockOnlyPro3: (name) => `цей спосіб лише для CMF Watch 3 Pro, а це ${name}`, - otaOnly: (device, name) => `оновлення прошивки лише для ${device}, а це «${name}»`, + loaderModel: (watch) => `це App Loader для іншої моделі годинника, не для ${watch}`, stubReply: "неочікувана відповідь App Loader", appRunning: (name) => `${name} запущено на годиннику — вийдіть із нього й спробуйте знову`, refusedCmd: (cmd, why) => `годинник відхилив ${cmd}: ${why}`, @@ -433,8 +432,7 @@ export const bt = dict(en, { boardVsWatch: (img, name, device, board) => `la imagen está hecha para la placa "${img}", pero «${name}» es un ${device} (placa "${board}")`, stockOnlyPro3: (name) => `esta salida es solo para el CMF Watch 3 Pro, no para ${name}`, - otaOnly: (device, name) => - `las actualizaciones de firmware son solo para el ${device}, este es «${name}»`, + loaderModel: (watch) => `es un App Loader para otro modelo de reloj, no para el ${watch}`, stubReply: "respuesta inesperada del App Loader", appRunning: (name) => `${name} está abierta en el reloj — sal de ella y reintenta`, refusedCmd: (cmd, why) => `el reloj rechazó ${cmd}: ${why}`, @@ -545,7 +543,7 @@ export const bt = dict(en, { boardVsWatch: (img, name, device, board) => `इमेज बोर्ड "${img}" के लिए बनी है, पर “${name}” एक ${device} (बोर्ड "${board}") है`, stockOnlyPro3: (name) => `यह तरीका सिर्फ़ CMF Watch 3 Pro के लिए है, ${name} के लिए नहीं`, - otaOnly: (device, name) => `फ़र्मवेयर अपडेट सिर्फ़ ${device} के लिए हैं, यह “${name}” है`, + loaderModel: (watch) => `यह किसी दूसरे घड़ी मॉडल का App Loader है, ${watch} का नहीं`, stubReply: "App Loader से अनपेक्षित जवाब", appRunning: (name) => `${name} घड़ी पर चल रहा है — उससे बाहर निकलें और फिर कोशिश करें`, refusedCmd: (cmd, why) => `घड़ी ने ${cmd} अस्वीकार किया: ${why}`, @@ -669,7 +667,6 @@ const RULES: Rule[] = [ (w, m) => w.boardVsWatch(m[1], m[2], m[3], m[4]), ], [/^this way out is for a CMF Watch 3 Pro, not (.+)$/, (w, m) => w.stockOnlyPro3(m[1])], - [/^firmware updates are for the (.+) only, this is “(.+)”$/, (w, m) => w.otaOnly(m[1], m[2])], lit("stubReply"), [/^(.+) is running on the watch — /, (w, m) => w.appRunning(m[1])], [/^the watch refused (\S+): (.+)$/, (w, m) => w.refusedCmd(m[1], why(w, m[2]))], @@ -678,6 +675,10 @@ const RULES: Rule[] = [ /^can't install this package: it needs app ABI (\S+), the watch's App Loader takes up to (\S+)$/, (w, m) => w.cantInstall(w.needsAbi(m[1], m[2])), ], + [ + /^can't install this package: it's an App Loader for another watch, not the (.+)$/, + (w, m) => w.cantInstall(w.loaderModel(m[1])), + ], [/^can't install this package: (.+)$/, (w, m) => w.cantInstall(why(w, m[1]))], [/^all (\d+) app slots are taken/, (w, m) => w.appSlotsTaken(m[1])], ]; diff --git a/src/lib/modules/device/model/dev.model.ts b/src/lib/modules/device/model/dev.model.ts index 1afcdeb..6b04e4f 100644 --- a/src/lib/modules/device/model/dev.model.ts +++ b/src/lib/modules/device/model/dev.model.ts @@ -4,7 +4,7 @@ // "Install again" after a rebuild reads the file anew, no second pick. import { attach, createEffect, createEvent, createStore, sample } from "effector"; import { reset } from "patronum"; -import { inspectOtaImage, OTA_DEVICE } from "../lib/ota-image"; +import { boardDevice, inspectOtaImage } from "../lib/ota-image"; import { parsePackageHeader } from "../lib/wp2"; import * as ble from "./ble.model"; import { t } from "../i18n"; @@ -138,9 +138,9 @@ sample({ clock: toWatch, source: $riskAccepted, filter: (accepted, { build }) => accepted && build.kind === "firmware", - // a local image has no record: it's for the one watch FMC flashes, and checkOtaTarget still - // matches its board to the watch on the line - fn: (_, { data }) => ({ image: data, device: OTA_DEVICE }), + // a local image has no record: it's for the watch its board names, and checkOtaTarget still + // matches that board to the watch on the line + fn: (_, { data }) => ({ image: data, device: boardDevice(inspectOtaImage(data).board) }), target: ble.firmwareFlashRequested, }); diff --git a/src/lib/modules/store/i18n.ts b/src/lib/modules/store/i18n.ts index aa17644..8b2a31a 100644 --- a/src/lib/modules/store/i18n.ts +++ b/src/lib/modules/store/i18n.ts @@ -76,7 +76,7 @@ export const t = dict( firmwareTitle: (name: string | undefined, device: string) => `${name ?? "Firmware"} — firmware for the ${device}`, onlyFor: (device: string) => - `Only for the ${device}. FMC installs firmware on a Watch Pro 2 only, so this one is a download — and flashing it onto a Watch Pro 2 can brick it.`, + `Only for the ${device}. FMC can't install firmware on that watch, so this one is a download — and flashing it onto another watch can brick it.`, wrongWatch: (name: string, device: string) => `The connected watch is “${name}”, and this firmware is for the ${device}. It can't be installed on this watch from here — download only.`, unnamed: "unnamed", @@ -217,7 +217,7 @@ export const t = dict( tested: { hardware: "Проверено на часах", emulator: "Только эмулятор" }, firmwareTitle: (name, device) => `${name ?? "Прошивка"} — прошивка для ${device}`, onlyFor: (device) => - `Только для ${device}. FMC устанавливает прошивку только на Watch Pro 2, поэтому эту можно лишь скачать — а если прошить её на Watch Pro 2, часы могут превратиться в кирпич.`, + `Только для ${device}. FMC не умеет ставить прошивку на эти часы, поэтому эту можно лишь скачать — а если прошить её на другие часы, они могут превратиться в кирпич.`, wrongWatch: (name, device) => `Подключены часы «${name}», а эта прошивка для ${device}. Отсюда её на эти часы не установить — только скачать.`, unnamed: "без имени", @@ -356,7 +356,7 @@ export const t = dict( tested: { hardware: "Перевірено на годиннику", emulator: "Лише емулятор" }, firmwareTitle: (name, device) => `${name ?? "Прошивка"} — прошивка для ${device}`, onlyFor: (device) => - `Лише для ${device}. FMC встановлює прошивку лише на Watch Pro 2, тож цю можна тільки завантажити — а якщо прошити нею Watch Pro 2, годинник може перетворитися на цеглину.`, + `Лише для ${device}. FMC не вміє встановлювати прошивку на цей годинник, тож цю можна тільки завантажити — а якщо прошити нею інший годинник, він може перетворитися на цеглину.`, wrongWatch: (name, device) => `Під'єднано годинник «${name}», а ця прошивка для ${device}. Звідси її на цей годинник не встановити — лише завантажити.`, unnamed: "без назви", @@ -494,7 +494,7 @@ export const t = dict( tested: { hardware: "Probado en un reloj", emulator: "Solo emulador" }, firmwareTitle: (name, device) => `${name ?? "Firmware"} — firmware para el ${device}`, onlyFor: (device) => - `Solo para el ${device}. FMC solo instala firmware en un Watch Pro 2, así que este es solo para descargar, y flashearlo en un Watch Pro 2 puede dejarlo inservible.`, + `Solo para el ${device}. FMC no puede instalar firmware en ese reloj, así que este es solo para descargar, y flashearlo en otro reloj puede dejarlo inservible.`, wrongWatch: (name, device) => `El reloj conectado es “${name}” y este firmware es para el ${device}. No se puede instalar en este reloj desde aquí, solo descargar.`, unnamed: "sin nombre", @@ -630,7 +630,7 @@ export const t = dict( tested: { hardware: "घड़ी पर टेस्ट किया", emulator: "सिर्फ़ एमुलेटर" }, firmwareTitle: (name, device) => `${name ?? "फ़र्मवेयर"} — ${device} के लिए फ़र्मवेयर`, onlyFor: (device) => - `सिर्फ़ ${device} के लिए। FMC फ़र्मवेयर सिर्फ़ Watch Pro 2 पर इंस्टॉल करता है, इसलिए इसे सिर्फ़ डाउनलोड किया जा सकता है — और इसे Watch Pro 2 पर फ़्लैश करने से घड़ी हमेशा के लिए खराब हो सकती है।`, + `सिर्फ़ ${device} के लिए। FMC उस घड़ी पर फ़र्मवेयर इंस्टॉल नहीं कर सकता, इसलिए इसे सिर्फ़ डाउनलोड किया जा सकता है — और इसे किसी दूसरी घड़ी पर फ़्लैश करने से वह हमेशा के लिए खराब हो सकती है।`, wrongWatch: (name, device) => `कनेक्टेड घड़ी “${name}” है, और यह फ़र्मवेयर ${device} के लिए है। इसे यहां से इस घड़ी पर इंस्टॉल नहीं किया जा सकता — सिर्फ़ डाउनलोड।`, unnamed: "बिना नाम", diff --git a/src/lib/modules/store/lib/firmware.ts b/src/lib/modules/store/lib/firmware.ts index 7d2efc6..b17170b 100644 --- a/src/lib/modules/store/lib/firmware.ts +++ b/src/lib/modules/store/lib/firmware.ts @@ -1,7 +1,7 @@ // What the `kind` and `tested` selects on a firmware record mean to a reader. The keys are the // schema's values (1754000000_store.js in fmc_pocketbase) and change together with it. import { DEFAULT_DEVICE } from "$lib/modules/market/lib/devices"; -import { OTA_DEVICE } from "$lib/modules/device/lib/ota-image"; +import { BOARDS } from "$lib/modules/device/lib/ota-image"; // The words for each kind (label, hint) are in ../i18n.ts under `kinds`, by the same key. const ICONS = { @@ -37,9 +37,8 @@ export const testedKey = (tested: unknown): "hardware" | "emulator" | null => tested === "hardware" || tested === "emulator" ? tested : null; /** - * The one watch FMC can flash: the OTA path (Watch.flashFirmware, ota-image.ts) is the Watch Pro - * 2's alone. A record that doesn't name a device is for DEFAULT_DEVICE, like a face. + * The watches FMC can flash: those with a known board (ota-image.ts BOARDS), whose stock OTA sequence + * Watch.flashFirmware speaks. A record that doesn't name a device is for DEFAULT_DEVICE, like a face. */ -export { OTA_DEVICE } from "$lib/modules/device/lib/ota-image"; export const recordDevice = (device: unknown): string => String(device || DEFAULT_DEVICE); -export const flashable = (device: unknown) => recordDevice(device) === OTA_DEVICE; +export const flashable = (device: unknown) => Object.hasOwn(BOARDS, recordDevice(device)); diff --git a/tests/firmware-device.browser.test.ts b/tests/firmware-device.browser.test.ts index c91f5c7..6dc430d 100644 --- a/tests/firmware-device.browser.test.ts +++ b/tests/firmware-device.browser.test.ts @@ -1,8 +1,8 @@ -// Which watch a firmware record is for decides whether FMC offers to flash it. The OTA path is -// the Watch Pro 2's alone, so another watch's image (the Watch 3 Pro's stock 1.0.1.77) is a -// download with a red plate and no Install button, and the model drops a flash of it even if -// something fires the event — the board check in ota-image.ts is only the second line. A stock -// Watch Pro 2 image goes the ordinary way, and with no stub in it, no badge claims it's there. +// Which watch a firmware record is for decides whether FMC offers to flash it. The Watch Pro 2 and +// the Watch 3 Pro have a known board, so their images get Install; a watch with no known board +// (the original Watch Pro) is a download with a red plate and no Install button, and the model +// drops a flash of it even if something fires the event — the board check in ota-image.ts is only +// the second line. With no stub in a stock image, no badge claims it's there. import { test, expect, vi } from "vitest"; import { render } from "vitest-browser-svelte"; import type { RecordModel } from "pocketbase"; @@ -38,9 +38,10 @@ const fw = (id: string, extra: Record = {}) => const w3p = fw("w3p", { kind: "stock", version: "1.0.1.77", device: "watch_3_pro" }); const wp2Stock = fw("wp2", { kind: "stock", version: "1.0.0.73", device: "watch_pro_2" }); const patched = fw("patched", { kind: "patched", stub: 3 }); +const wp1 = fw("wp1", { kind: "stock", version: "1.0.0.1", device: "watch_pro" }); -storeApi.loadFirmwaresFx.use(() => [w3p, wp2Stock]); -storeApi.loadFirmwareFx.use((id) => [w3p, wp2Stock].find((r) => r.id === id)!); +storeApi.loadFirmwaresFx.use(() => [w3p, wp2Stock, wp1]); +storeApi.loadFirmwareFx.use((id) => [w3p, wp2Stock, wp1].find((r) => r.id === id)!); const connect = async () => { bleModel.connectRequested(); @@ -55,11 +56,11 @@ test("the shelf says which watch each image is for", async () => { expect(screen.container.textContent).not.toMatch(/coming soon/i); }); -test("a Watch 3 Pro image is a download: a red plate, no Install", async () => { +test("an image for a watch with no known board is a download: a red plate, no Install", async () => { await connect(); - const screen = await render(FirmwarePage, { id: "w3p" }); + const screen = await render(FirmwarePage, { id: "wp1" }); - await expect.element(screen.getByText(/Only for the CMF Watch 3 Pro/)).toBeInTheDocument(); + await expect.element(screen.getByText(/Only for the CMF Watch Pro\./)).toBeInTheDocument(); await expect.element(screen.getByRole("button", { name: "Download" })).toBeInTheDocument(); expect(screen.getByRole("button", { name: "Install" }).elements()).toHaveLength(0); expect(screen.getByRole("button", { name: "Connect" }).elements()).toHaveLength(0); @@ -76,7 +77,7 @@ test("a stock Watch Pro 2 image has Install behind the tick", async () => { expect(screen.container.textContent).not.toMatch(/Only for the/); }); -test("the model fetches a Watch Pro 2 image for flashing, never another watch's", async () => { +test("the model fetches an image for flashing only for a watch with a known board", async () => { const fetched: string[] = []; const flash = (rec: RecordModel) => fork({ @@ -92,9 +93,12 @@ test("the model fetches a Watch Pro 2 image for flashing, never another watch's" ], }); - await allSettled(storeModel.flashRequested, { scope: flash(w3p) }); - await allSettled(storeModel.loaderInstallRequested, { scope: flash({ ...w3p, kind: "loader" }) }); + await allSettled(storeModel.flashRequested, { scope: flash(wp1) }); + await allSettled(storeModel.loaderInstallRequested, { scope: flash({ ...wp1, kind: "loader" }) }); expect(fetched).toEqual([]); + await allSettled(storeModel.flashRequested, { scope: flash(w3p) }); + expect(fetched).toEqual(["w3p"]); + fetched.length = 0; const scope = flash(wp2Stock); const handed: unknown[] = []; @@ -106,17 +110,17 @@ test("the model fetches a Watch Pro 2 image for flashing, never another watch's" expect(handed).toEqual(["watch_pro_2"]); }); -test("no Installed/Update badge for a stock image or another watch's", () => { +test("no Installed/Update badge for a stock image or an unflashable watch's", () => { const scope = fork({ values: [ - [bleModel.$wp2, { stub: { version: 3, abiMinor: 0 }, loader: null, apps: {} }], - [storeModel.$firmwares, [wp2Stock, { ...w3p, stub: 4 }, patched]], + [bleModel.$wp2, { stub: { version: 3, abiMinor: 0, model: 1 }, loader: null, apps: {} }], + [storeModel.$firmwares, [wp2Stock, { ...wp1, stub: 4 }, patched]], ], }); expect(scope.getState(storeModel.$firmwaresOnWatch)).toEqual({ wp2: null, - w3p: null, + wp1: null, patched: "installed", }); }); diff --git a/tests/ota.browser.test.ts b/tests/ota.browser.test.ts index 4bba18d..ed4c8fe 100644 --- a/tests/ota.browser.test.ts +++ b/tests/ota.browser.test.ts @@ -119,6 +119,11 @@ test("a Watch Pro 2 image goes to a Watch Pro 2, from its record or an untagged expect(checkOtaTarget(wp2Image(), WP2, "").board).toBe("jx402_01_3089c"); }); +test("a Watch 3 Pro image goes to a Watch 3 Pro, under either advertised name", () => { + expect(checkOtaTarget(wp3Image(), WP3, "watch_3_pro").board).toBe("jx402_08"); + expect(checkOtaTarget(wp3Image(), "CMF Watch 3 Pro-1B2C", "watch_3_pro").board).toBe("jx402_08"); +}); + test.each([ ["a Watch 3 Pro image on a Watch Pro 2", wp3Image, WP2, "watch_pro_2", /"jx402_08".*Watch Pro 2/], ["a Watch 3 Pro image on an untagged record", wp3Image, WP2, "", /"jx402_08".*Watch Pro 2/], @@ -136,13 +141,6 @@ test.each([ "watch_3_pro", /"jx402_01_3089c".*record is for the CMF Watch 3 Pro \(board "jx402_08"\)/, ], - [ - "a Watch 3 Pro image on a Watch 3 Pro: no OTA path for it", - wp3Image, - WP3, - "watch_3_pro", - /Watch Pro 2 only/, - ], [ "a watch with no known board", wp2Image, diff --git a/tests/wp2.browser.test.ts b/tests/wp2.browser.test.ts index e405e79..ca9cbc7 100644 --- a/tests/wp2.browser.test.ts +++ b/tests/wp2.browser.test.ts @@ -6,6 +6,8 @@ import { Watch } from "$lib/modules/device/lib/ble"; import { CMD, crc32 } from "$lib/modules/device/lib/ble-protocol"; import { LOADER_SLOT, + MODEL_WP2, + MODEL_WP3, parsePackageHeader, parseStubReply, planInstall, @@ -43,11 +45,30 @@ test("a package header reads back name, version, kind and image CRC", () => { }); test("the stub's reply: versioned, and an older stub's BadRequest", () => { - expect(parseStubReply(new Uint8Array([0, 2, 0, 0, 0, 3]))).toEqual({ version: 2, abiMinor: 3 }); - expect(parseStubReply(new Uint8Array([1]))).toEqual({ version: 1, abiMinor: null }); + expect(parseStubReply(new Uint8Array([0, 2, 0, 0, 0, 3]))).toEqual({ + version: 2, + abiMinor: 3, + model: MODEL_WP2, + }); + expect(parseStubReply(new Uint8Array([1]))).toEqual({ + version: 1, + abiMinor: null, + model: MODEL_WP2, + }); expect(() => parseStubReply(new Uint8Array([0, 1]))).toThrow(); }); +test("a Watch 3 Pro stub adds its model byte", () => { + expect(parseStubReply(new Uint8Array([0, 10, 0, 0, 0, 3, 2]))).toEqual({ + version: 10, + abiMinor: 3, + model: MODEL_WP3, + }); + expect(() => parseStubReply(new Uint8Array([0, 10, 0, 0, 0, 3, 9]))).toThrow( + /unexpected stub reply/, + ); +}); + test("same build means same name and same CRC", () => { const a = parsePackageHeader(header("workout", 1, 7))!; @@ -92,7 +113,7 @@ test("a watch with the stub reports its release, the loader and the apps by slot }); const state = await w.readWp2(); - expect(state?.stub).toEqual({ version: 2, abiMinor: 3 }); + expect(state?.stub).toEqual({ version: 2, abiMinor: 3, model: MODEL_WP2 }); expect(state?.loader?.name).toBe("loader"); expect(Object.keys(state!.apps)).toEqual(["3"]); expect(state!.apps[3].name).toBe("workout"); @@ -102,7 +123,7 @@ test("a watch with the stub reports its release, the loader and the apps by slot // ---- installing ---- // a whole, valid package the way wp2apps `pack` builds one: header (its own CRC over 0x34 bytes), // image, relocation table; the header's CRC field covers image ‖ table -function pack(name: string, size: number, kind = 0, abiMinor = 3) { +function pack(name: string, size: number, kind = 0, abiMinor = 3, model = 0) { const body = new Uint8Array(size + 8).map((_, i) => (i * 31) & 0xff); // image + 2 relocs const h = new Uint8Array(64); const dv = new DataView(h.buffer); @@ -117,14 +138,19 @@ function pack(name: string, size: number, kind = 0, abiMinor = 3) { dv.setUint32(44, 2, true); dv.setUint32(48, crc32(body), true); dv.setUint32(0x34, crc32(h.subarray(0, 0x34)), true); + h[0x38] = model; // a loader's model, outside the header CRC const out = new Uint8Array(64 + body.length); out.set(h); out.set(body, 64); return out; } -const state = (apps: Record, abiMinor: number | null = 3): Wp2State => ({ - stub: { version: 2, abiMinor }, +const state = ( + apps: Record, + abiMinor: number | null = 3, + model = MODEL_WP2, +): Wp2State => ({ + stub: { version: 2, abiMinor, model }, loader: null, apps: Object.fromEntries( Object.entries(apps).map(([slot, name]) => [slot, parsePackageHeader(pack(name, 64))!]), @@ -137,6 +163,9 @@ test("an app goes to its own slot when it's there, else the first free one; a lo expect(planInstall(p, state({ 0: "a", 4: "workout" }), crc32).slot).toBe(4); expect(planInstall(p, state({ 0: "a", 1: "b" }), crc32).slot).toBe(2); expect(planInstall(pack("loader", 300, 1), state({}), crc32).slot).toBe(LOADER_SLOT); + expect(planInstall(pack("loader", 300, 1, 3, 2), state({}, 3, MODEL_WP3), crc32).slot).toBe( + LOADER_SLOT, + ); }); test.each([ @@ -170,6 +199,18 @@ test.each([ /header checksum/, ], ["a truncated file", pack("x", 64).subarray(0, 100), state({}), /truncated/], + [ + "a Watch 3 Pro loader on a Watch Pro 2", + pack("loader", 64, 1, 3, 2), + state({}), + /App Loader for another watch, not the Watch Pro 2/, + ], + [ + "a Watch Pro 2 loader on a Watch 3 Pro", + pack("loader", 64, 1), + state({}, 3, MODEL_WP3), + /App Loader for another watch, not the Watch 3 Pro/, + ], ] as const)("refuses %s before sending anything", (_, data, st, why) => { expect(() => planInstall(data, st, crc32)).toThrow(why); }); @@ -222,3 +263,26 @@ test("a busy slot says the app is running", async () => { w.waitFor = async () => new Uint8Array([5]); await expect(w.installPackage(pack("workout", 64), state({}))).rejects.toThrow(/running/); }); + +test("a Watch 3 Pro stub takes DATA on 0x90A9", async () => { + const w = new Watch(); + const sent: number[] = []; + let written = 0; + let last = 0; + + w.send = async (key, payload) => { + sent.push(key); + last = key; + if (key === CMD.stubDataWp3) written += payload!.length - 4; + }; + w.waitFor = async () => { + if (last !== CMD.stubDataWp3) return new Uint8Array([0]); + const r = new Uint8Array(5); + + new DataView(r.buffer).setUint32(1, written, true); + return r; + }; + await w.installPackage(pack("hello", 300), state({}, 3, MODEL_WP3)); + expect(sent).toContain(CMD.stubDataWp3); + expect(sent).not.toContain(CMD.stubData); +});