From 3e41b7b30594b7b71b6adfe7a5beb2b17361a706 Mon Sep 17 00:00:00 2001 From: Egor Kolesnikov Date: Sat, 21 Nov 2026 12:33:12 +0200 Subject: [PATCH] Rescue: a way out of the boot loop on a Watch 3 Pro, over the shell The shell characteristic takes the full Zephyr shell with no auth, and it opens ~200 ms into a link, ~100 ms before a looping watch faults. The face list lives in RAM that outlives the crash reboot (WfmPara_Load reads it at 0x3800f73a on fw 1.0.1.77), so streaming `dbg mwb 0x3800f73a 0` breaks its magic and the next boot rebuilds the list from the stock faces alone (WFM _REST). The page then asks the shell its version: only a watch that stopped looping answers. Checked end to end in the emulator: the /rescue page in Chromium, with navigator.bluetooth bridged to the emulated watch, got the write in on its second boot, the third boot loaded stock face 274 and the shell answered. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01CQSU8PSWDYpGNxzMYKE2JL --- src/lib/modules/device/i18n.ts | 30 +++ src/lib/modules/device/lib/ble.ts | 183 +++++++++++++++---- src/lib/modules/device/messages.ts | 6 + src/lib/modules/device/model/rescue.model.ts | 23 ++- src/lib/modules/device/pages/rescue.svelte | 5 + tests/ble-shell-blast.test.ts | 65 +++++++ 6 files changed, 269 insertions(+), 43 deletions(-) create mode 100644 tests/ble-shell-blast.test.ts diff --git a/src/lib/modules/device/i18n.ts b/src/lib/modules/device/i18n.ts index 6fe8f89..b0eea9d 100644 --- a/src/lib/modules/device/i18n.ts +++ b/src/lib/modules/device/i18n.ts @@ -84,6 +84,12 @@ export const t = dict( deleteFacesHint: "Gentler than a reset: only the faces this browser installed go, everything else stays. Not yet confirmed on a stuck watch — if it doesn't help, use the factory reset.", rescueRetrying: (n: number) => `waiting for the watch — attempt ${n}…`, + stockFace: "Switch to a stock face (Watch 3 Pro)", + stockFaceHint: + "For a Watch 3 Pro stuck restarting on a face: the watch forgets its installed faces and starts on a stock one. No key needed, nothing is wiped. Works on firmware 1.0.1.77 in our emulator, not yet confirmed on a real watch — keep the watch near the computer and let it run for a few minutes.", + switchingToStock: "switching to a stock face…", + stockFaceDone: + "Done: the watch stayed connected, so it is no longer restarting. The faces you installed are gone from its list; put back the ones you want.", stopRescue: "Stop", rescueKeyHint: "Coming from another browser, or from the old address fmc.freethinkel.dev? Open /rescue there, copy what it shows and paste it here.", @@ -189,6 +195,12 @@ export const t = dict( deleteFacesHint: "Бережнее сброса: уходят только циферблаты, установленные из этого браузера, всё остальное остаётся. На зависших часах ещё не проверено — если не поможет, сделайте сброс до заводских.", rescueRetrying: (n: number) => `ожидание часов — попытка ${n}…`, + stockFace: "Переключить на стоковый циферблат (Watch 3 Pro)", + stockFaceHint: + "Для Watch 3 Pro, который перезагружается на циферблате по кругу: часы забывают установленные циферблаты и запускаются со стокового. Ключ не нужен, ничего не стирается. Работает на прошивке 1.0.1.77 в нашем эмуляторе, на настоящих часах пока не подтверждено — держите часы рядом с компьютером и дайте поработать несколько минут.", + switchingToStock: "переключение на стоковый циферблат…", + stockFaceDone: + "Готово: часы остались на связи, значит, больше не перезагружаются. Установленных циферблатов в их списке больше нет — поставьте нужные заново.", stopRescue: "Стоп", rescueKeyHint: "Ключ остался в другом браузере или на старом адресе fmc.freethinkel.dev? Откройте там /rescue, скопируйте текст и вставьте сюда.", @@ -292,6 +304,12 @@ export const t = dict( deleteFacesHint: "Дбайливіше за скидання: зникають лише циферблати, встановлені з цього браузера, усе інше лишається. На завислому годиннику ще не перевірено — якщо не допоможе, скиньте до заводських налаштувань.", rescueRetrying: (n: number) => `очікування годинника — спроба ${n}…`, + stockFace: "Перемкнути на стоковий циферблат (Watch 3 Pro)", + stockFaceHint: + "Для Watch 3 Pro, що перезавантажується на циферблаті по колу: годинник забуває встановлені циферблати й запускається зі стокового. Ключ не потрібен, нічого не стирається. Працює на прошивці 1.0.1.77 у нашому емуляторі, на справжньому годиннику ще не підтверджено — тримайте годинник біля комп’ютера й дайте попрацювати кілька хвилин.", + switchingToStock: "перемикання на стоковий циферблат…", + stockFaceDone: + "Готово: годинник лишився на зв’язку, отже, більше не перезавантажується. Встановлених циферблатів у його списку більше немає — поставте потрібні знову.", stopRescue: "Стоп", rescueKeyHint: "Ключ лишився в іншому браузері або на старій адресі fmc.freethinkel.dev? Відкрийте там /rescue, скопіюйте текст і вставте сюди.", @@ -396,6 +414,12 @@ export const t = dict( deleteFacesHint: "Más suave que un restablecimiento: solo se van las esferas que instaló este navegador y todo lo demás se queda. Aún sin confirmar en un reloj bloqueado; si no ayuda, restablece los datos de fábrica.", rescueRetrying: (n: number) => `esperando al reloj — intento ${n}…`, + stockFace: "Cambiar a una esfera de fábrica (Watch 3 Pro)", + stockFaceHint: + "Para un Watch 3 Pro que se reinicia una y otra vez en una esfera: el reloj olvida las esferas instaladas y arranca con una de fábrica. No hace falta clave y no se borra nada. Funciona con el firmware 1.0.1.77 en nuestro emulador, aún sin confirmar en un reloj real: deja el reloj cerca del ordenador unos minutos.", + switchingToStock: "cambiando a una esfera de fábrica…", + stockFaceDone: + "Hecho: el reloj siguió conectado, así que ya no se reinicia. Las esferas que instalaste ya no están en su lista; vuelve a poner las que quieras.", stopRescue: "Detener", rescueKeyHint: "¿La clave quedó en otro navegador o en la dirección antigua fmc.freethinkel.dev? Abre /rescue allí, copia el texto y pégalo aquí.", @@ -495,6 +519,12 @@ export const t = dict( deleteFacesHint: "रीसेट से हल्का: सिर्फ़ इस ब्राउज़र से इंस्टॉल किए गए फ़ेस हटते हैं, बाकी सब रहता है। अटकी घड़ी पर अभी पुष्टि नहीं हुई — अगर मदद न मिले, तो फ़ैक्टरी रीसेट करें।", rescueRetrying: (n: number) => `घड़ी का इंतज़ार — प्रयास ${n}…`, + stockFace: "स्टॉक फ़ेस पर स्विच करें (Watch 3 Pro)", + stockFaceHint: + "उस Watch 3 Pro के लिए जो किसी फ़ेस पर बार-बार रीस्टार्ट होता है: घड़ी इंस्टॉल किए गए फ़ेस भूल जाती है और स्टॉक फ़ेस से शुरू होती है। कुंजी की ज़रूरत नहीं, कुछ भी मिटता नहीं। हमारे एमुलेटर में फ़र्मवेयर 1.0.1.77 पर काम करता है, असली घड़ी पर अभी पुष्टि नहीं हुई — घड़ी को कंप्यूटर के पास रखें और कुछ मिनट चलने दें।", + switchingToStock: "स्टॉक फ़ेस पर स्विच हो रहा है…", + stockFaceDone: + "हो गया: घड़ी जुड़ी रही, यानी अब रीस्टार्ट नहीं हो रही। आपके इंस्टॉल किए फ़ेस उसकी सूची से हट गए हैं; जो चाहिए उन्हें फिर से लगाएँ।", stopRescue: "रोकें", rescueKeyHint: "key किसी और ब्राउज़र में या पुराने पते fmc.freethinkel.dev पर रह गई है? वहाँ /rescue खोलें, जो टेक्स्ट दिखे उसे कॉपी करें और यहाँ पेस्ट करें।", diff --git a/src/lib/modules/device/lib/ble.ts b/src/lib/modules/device/lib/ble.ts index c334864..f19ff38 100644 --- a/src/lib/modules/device/lib/ble.ts +++ b/src/lib/modules/device/lib/ble.ts @@ -100,6 +100,18 @@ export const within = (p: Promise, ms: number, err: () => Error): Promise< // timer in its connected callback; WP3 firmware, seen in the emulator), so on rescue — which // connects as early as it can — authName is re-sent at this pace until it is answered. const RESCUE_NAME_MS = 20; +// The way out of a boot loop on a Watch 3 Pro (fw 1.0.1.77, found in the emulator): the face list +// lives in RAM that outlives the crash reboot — WfmPara_Load reads it at 0x3800f73a, behind a +// magic — and the shell takes `dbg` with no auth. A zero over the magic makes the next boot +// rebuild the list from the stock faces alone (WFM _REST), so the bad face is never loaded again; +// its file stays. ponytail: the address is that firmware's; another build needs its own, and a +// write there lands in RAM only, so a wrong one is lost at the next restart. +export const ESCAPE_CMD = "dbg mwb 0x3800f73a 0"; +// how long a shell blast keeps writing, and how often: the shell opens ~200 ms into a link +const SHELL_BLAST_MS = 1000; +const SHELL_BLAST_EVERY_MS = 15; +// a live watch answers the shell in milliseconds; one past its fault, never +const SHELL_ANSWER_MS = 1500; // how long the rescue page waits for a pairing to be confirmed before it reconnects and asks again const RESCUE_PAIR_MS = 30000; const loadKey = (): Uint8Array | null => { @@ -149,6 +161,7 @@ export class Watch { handlers = new Map void | Promise>(); rx: Promise = Promise.resolve(); // serializes inbound notifications, see subscribe() shellWaiter: ((s: string) => void) | null = null; + shellService: string | null = null; // where shellBlast found the shell, for its next try device: BluetoothDevice | null = null; name: string | null = null; // advertised — the only model id there is battery: number | null = null; @@ -162,7 +175,10 @@ export class Watch { headerCount: number | null = null; get slots(): WatchSlots { - return { used: this.headerCount ?? this.installedWf.length, capacity: this.capacity }; + return { + used: this.headerCount ?? this.installedWf.length, + capacity: this.capacity, + }; } constructor(onStatus: (s: string) => void = () => {}) { @@ -187,6 +203,130 @@ export class Watch { this.onDials?.([...this.installedWf], this.slots); } + // like in fmc CLI: the advertisement doesn't always carry the service, so match by name and by manufacturer id too + private async pick(): Promise { + let d: BluetoothDevice; + + try { + d = await navigator.bluetooth.requestDevice({ + filters: [ + { services: [0xefe7] }, + { namePrefix: "CMF Watch" }, + { manufacturerData: [{ companyIdentifier: 0x0ccb }] }, + ], + optionalServices: SERVICES, + }); + } catch (e) { + dbg("requestDevice failed:", errText(e)); + // the picker closed without a choice (Chromium's NotFoundError), or no permission + if (e instanceof Error && /NotFound|Security|Abort/.test(e.name)) throw e; + // ponytail: a Web BLE browser outside Chromium (Bluefy) refuses some of the above — + // likely the manufacturerData filter or numeric UUIDs; ask again with the plainest form + d = await navigator.bluetooth.requestDevice({ + // this form is the one Bluefy took (3.9.3, iOS 18.7). A watch another app on the phone + // holds stays invisible to it whatever the filters — the help page says to free it + filters: [ + { namePrefix: "CMF Watch" }, + ...SERVICES.map((u) => ({ services: [fullUuid(u)] })), + ], + optionalServices: SERVICES.map(fullUuid), + }); + } + + dbg("device chosen:", d.name, d.id); + d.addEventListener("gattserverdisconnected", () => { + dbg("gattserverdisconnected"); + this.status("disconnected"); + }); + return d; + } + + /** + * Rescue's way out of a boot loop on a Watch 3 Pro: from the moment the link is up, `cmd` goes + * to the shell again and again for SHELL_BLAST_MS — the shell opens ~200 ms into a link and the + * watch faults ~100 ms after that, so only a stream gets a write into that window. Then asks the + * shell its version: true if it answers, which a watch past its fault never does (it keeps the + * link for seconds, until its watchdog restarts it, so a link still up proves nothing). + * again: the watch picked on an earlier call, with no picker. + */ + async shellBlast(cmd: string, again = false): Promise { + const device = again && this.device ? this.device : await this.pick(); + + this.device = device; + this.name = device.name ?? null; + if (!/watch (3 pro|pro 3)/i.test(this.name ?? "")) + throw new Error(`this way out is for a CMF Watch 3 Pro, not ${this.name ?? "this watch"}`); + const server = await within( + device.gatt!.connect(), + 15000, + () => + new Error( + "connection timed out — the watch is probably connected to another app or browser tab; close it (phone app, fmc CLI, old editor tab) and retry", + ), + ); + const start = performance.now(); + const shell: Record = {}; + + // targeted lookup once a full discovery has found the shell's service: fewer round trips, + // and every one of them is out of a window a few hundred ms long + if (this.shellService) { + const svc = await server.getPrimaryService(this.shellService); + + for (const u of [UUID.shellWrite, UUID.shellRead]) shell[u] = await svc.getCharacteristic(u); + } else { + for (const svc of await server.getPrimaryServices()) + for (const c of await svc.getCharacteristics().catch(() => [])) + if (fullUuid(c.uuid) === UUID.shellWrite || fullUuid(c.uuid) === UUID.shellRead) { + shell[fullUuid(c.uuid)] = c; + this.shellService = svc.uuid; + } + } + const [w, r] = [shell[UUID.shellWrite], shell[UUID.shellRead]]; + + if (!w || !r) throw new Error("characteristic shell not found"); + const elapsed = () => Math.round(performance.now() - start); + const write = (line: string) => { + const bytes = utf8(`${line}\r\n`) as BufferSource; + + return w.properties.writeWithoutResponse + ? w.writeValueWithoutResponse(bytes) + : w.writeValueWithResponse(bytes); + }; + let n = 0; + + dbg("shell blast: shell found", elapsed(), "ms in"); + while (device.gatt!.connected && elapsed() < SHELL_BLAST_MS) { + await write(cmd).then( + () => n++, + (e) => dbg("shell blast: write failed:", errText(e)), + ); + await new Promise((res) => setTimeout(res, SHELL_BLAST_EVERY_MS)); + } + dbg("shell blast:", n, "writes,", elapsed(), "ms in"); + if (!device.gatt!.connected) return false; + const answered = new Promise((res) => + r.addEventListener("characteristicvaluechanged", () => { + const s = new TextDecoder().decode(r.value!); + + dbg("shell:", s.trim()); + if (s.includes("GETVERSION:")) res(true); + }), + ); + const silent = () => new Error("timeout waiting for GETVERSION"); + + try { + await within(r.startNotifications(), SHELL_ANSWER_MS, silent); + await write("AT GETVERSION"); + return await within(answered, SHELL_ANSWER_MS, silent); + } catch (e) { + dbg("shell blast:", errText(e)); + // a watch past its fault keeps the link until it restarts; let go, so the next try is a + // fresh link to the next boot and not an instant reconnect to this one + device.gatt!.disconnect(); + return false; + } + } + // rescue: stop right after auth — a watch wedged on a bad face may never answer fwGet/a055, // and the only thing the caller wants to send is factoryReset. again: reconnect to the watch // picked on an earlier call, with no picker — the rescue page retries every time it shows up @@ -196,44 +336,7 @@ export class Watch { "Web Bluetooth isn't available here — open this page in Chrome or Edge, or in Bluefy on an iPhone", ); this.status("requesting device…"); - // like in fmc CLI: the advertisement doesn't always carry the service, so match by name and by manufacturer id too - const pick = async () => { - let d: BluetoothDevice; - - try { - d = await navigator.bluetooth.requestDevice({ - filters: [ - { services: [0xefe7] }, - { namePrefix: "CMF Watch" }, - { manufacturerData: [{ companyIdentifier: 0x0ccb }] }, - ], - optionalServices: SERVICES, - }); - } catch (e) { - dbg("requestDevice failed:", errText(e)); - // the picker closed without a choice (Chromium's NotFoundError), or no permission - if (e instanceof Error && /NotFound|Security|Abort/.test(e.name)) throw e; - // ponytail: a Web BLE browser outside Chromium (Bluefy) refuses some of the above — - // likely the manufacturerData filter or numeric UUIDs; ask again with the plainest form - d = await navigator.bluetooth.requestDevice({ - // this form is the one Bluefy took (3.9.3, iOS 18.7). A watch another app on the phone - // holds stays invisible to it whatever the filters — the help page says to free it - filters: [ - { namePrefix: "CMF Watch" }, - ...SERVICES.map((u) => ({ services: [fullUuid(u)] })), - ], - optionalServices: SERVICES.map(fullUuid), - }); - } - - dbg("device chosen:", d.name, d.id); - d.addEventListener("gattserverdisconnected", () => { - dbg("gattserverdisconnected"); - this.status("disconnected"); - }); - return d; - }; - let device = again && this.device ? this.device : await pick(); + let device = again && this.device ? this.device : await this.pick(); this.device = device; this.name = device.name ?? null; @@ -300,7 +403,7 @@ export class Watch { } catch (e) { if (!/not offered to this origin/i.test((e as Error).message)) throw e; this.status("re-picking device…"); - device = await pick(); + device = await this.pick(); await Promise.race([discover(), timeout(15000, what)]); } }; diff --git a/src/lib/modules/device/messages.ts b/src/lib/modules/device/messages.ts index ae2aa59..ff5e6e1 100644 --- a/src/lib/modules/device/messages.ts +++ b/src/lib/modules/device/messages.ts @@ -80,6 +80,7 @@ const en = { `the image is built for board "${img}", but the record is for the ${device} (board "${board}")`, 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}”`, // apps (the App Loader stub) @@ -180,6 +181,7 @@ export const bt = dict(en, { `образ собран для платы "${img}", а запись для ${device} (плата "${board}")`, boardVsWatch: (img, name, device, board) => `образ собран для платы "${img}", а «${name}» — это ${device} (плата "${board}")`, + stockOnlyPro3: (name) => `это средство только для CMF Watch 3 Pro, а это ${name}`, otaOnly: (device, name) => `обновления прошивки только для ${device}, а это «${name}»`, stubReply: "неожиданный ответ App Loader", appRunning: (name) => `${name} запущено на часах — выйдите из него и попробуйте снова`, @@ -276,6 +278,7 @@ export const bt = dict(en, { `образ зібрано для плати "${img}", а запис для ${device} (плата "${board}")`, boardVsWatch: (img, name, device, board) => `образ зібрано для плати "${img}", а «${name}» — це ${device} (плата "${board}")`, + stockOnlyPro3: (name) => `цей спосіб лише для CMF Watch 3 Pro, а це ${name}`, otaOnly: (device, name) => `оновлення прошивки лише для ${device}, а це «${name}»`, stubReply: "неочікувана відповідь App Loader", appRunning: (name) => `${name} запущено на годиннику — вийдіть із нього й спробуйте знову`, @@ -373,6 +376,7 @@ export const bt = dict(en, { `la imagen está hecha para la placa "${img}", pero el registro es para el ${device} (placa "${board}")`, 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}»`, stubReply: "respuesta inesperada del App Loader", @@ -470,6 +474,7 @@ export const bt = dict(en, { `इमेज बोर्ड "${img}" के लिए बनी है, पर रिकॉर्ड ${device} (बोर्ड "${board}") के लिए है`, boardVsWatch: (img, name, device, board) => `इमेज बोर्ड "${img}" के लिए बनी है, पर “${name}” एक ${device} (बोर्ड "${board}") है`, + stockOnlyPro3: (name) => `यह तरीका सिर्फ़ CMF Watch 3 Pro के लिए है, ${name} के लिए नहीं`, otaOnly: (device, name) => `फ़र्मवेयर अपडेट सिर्फ़ ${device} के लिए हैं, यह “${name}” है`, stubReply: "App Loader से अनपेक्षित जवाब", appRunning: (name) => `${name} घड़ी पर चल रहा है — उससे बाहर निकलें और फिर कोशिश करें`, @@ -580,6 +585,7 @@ const RULES: Rule[] = [ /^the image is built for board "(.+)", but “(.+)” is a (.+) \(board "(.+)"\)$/, (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])], diff --git a/src/lib/modules/device/model/rescue.model.ts b/src/lib/modules/device/model/rescue.model.ts index 72dcef0..c99c791 100644 --- a/src/lib/modules/device/model/rescue.model.ts +++ b/src/lib/modules/device/model/rescue.model.ts @@ -7,7 +7,7 @@ // the user stops it. ponytail: a fixed short pause between attempts — Web Bluetooth can't // watch for the advertisement without a flag, so gatt.connect() itself is the probe. import { attach, createEffect, createEvent, createStore, sample, type StoreValue } from "effector"; -import { hasSavedKey, importKey, Watch } from "../lib/ble"; +import { ESCAPE_CMD, hasSavedKey, importKey, Watch } from "../lib/ble"; import { flashedHere, importFlashed } from "../lib/catalog-names"; import { buildBin, TAG } from "$lib/modules/editor/core/format"; import { dbgListeners } from "../lib/ble-protocol"; @@ -17,8 +17,13 @@ import { bleText, bt } from "../messages"; export const resetRequested = createEvent(); /** The gentler action: delete the faces this browser installed, the bad one among them. */ export const facesRequested = createEvent(); +/** The way out that needs no key: make the next boot fall back to the stock faces (Watch 3 Pro). */ +export const stockRequested = createEvent(); export const stopRequested = createEvent(); -export type RescueResult = { action: "reset" } | { action: "faces"; deleted: number }; +export type RescueResult = + | { action: "reset" } + | { action: "faces"; deleted: number } + | { action: "stock" }; type Words = StoreValue; export const $status = createStore(""); @@ -33,6 +38,8 @@ const RETRY_MS = 300; let stopping = false; // the picker closed without a choice, or no permission: nothing to retry const pickerClosed = (e: unknown) => e instanceof Error && /NotFound|Security|Abort/.test(e.name); +// shellBlast refusing another model: retrying won't change the watch +const wrongModel = (e: unknown) => e instanceof Error && /for a CMF Watch 3 Pro/.test(e.message); const logged = createEvent(); // what the watch pulls during a delete and throws away: the smallest file that parses as a face const FILLER = buildBin({ @@ -61,6 +68,11 @@ const rescueFx = attach({ try { for (let attempt = 1; !stopping; attempt++) { try { + if (action === "stock") { + statusChanged(t.switchingToStock); + if (await w.shellBlast(ESCAPE_CMD, attempt > 1)) return { action }; + throw new Error("the watch went quiet: it is still restarting"); + } await w.connect({ rescue: true, again: attempt > 1 }); if (stopping) break; if (action === "reset") { @@ -76,7 +88,7 @@ const rescueFx = attach({ for (const id of flashedHere()) if (await w.deleteDial(id, FILLER)) deleted++; return { action, deleted }; } catch (e) { - if (pickerClosed(e) || stopping) throw e; + if (pickerClosed(e) || wrongModel(e) || stopping) throw e; logged(`attempt ${attempt} failed: ${(e as Error).message}`); statusChanged(t.rescueRetrying(attempt + 1)); await new Promise((r) => setTimeout(r, RETRY_MS)); @@ -132,6 +144,11 @@ sample({ fn: () => "faces" as const, target: rescueFx, }); +sample({ + clock: stockRequested, + fn: () => "stock" as const, + target: rescueFx, +}); sample({ clock: stopRequested, target: stopFx, diff --git a/src/lib/modules/device/pages/rescue.svelte b/src/lib/modules/device/pages/rescue.svelte index 2363041..5e67b41 100644 --- a/src/lib/modules/device/pages/rescue.svelte +++ b/src/lib/modules/device/pages/rescue.svelte @@ -12,6 +12,7 @@ const { resetRequested, facesRequested, + stockRequested, stopRequested, keyTextChanged, keySubmitted, @@ -59,6 +60,8 @@ {#if $busy} {:else} +

{$t.stockFaceHint}

+ {#if $faces}

{$t.deleteFacesHint}

@@ -69,6 +72,8 @@ {#if $error}

{$error}

{/if} {#if $done?.action === "reset"}

{@html $t.rescueSent(ISSUES)}

+ {:else if $done?.action === "stock"} +

{$t.stockFaceDone}

{:else if $done?.action === "faces"}

{$t.facesDeleted($done.deleted)}

{/if} diff --git a/tests/ble-shell-blast.test.ts b/tests/ble-shell-blast.test.ts new file mode 100644 index 0000000..5068366 --- /dev/null +++ b/tests/ble-shell-blast.test.ts @@ -0,0 +1,65 @@ +// shellBlast streams its command at the shell, then counts the watch alive only if the shell +// answers: a Watch 3 Pro past its fault keeps the link for seconds and answers nothing. +import { expect, test, vi } from "vitest"; +import { Watch } from "$lib/modules/device/lib/ble"; +import { UUID } from "$lib/modules/device/lib/ble-protocol"; + +const fakeWatch = (name: string, answers: boolean) => { + const lines: string[] = []; + const read = Object.assign(new EventTarget(), { + uuid: UUID.shellRead, + value: undefined as DataView | undefined, + startNotifications: async () => read, + }); + const write = { + uuid: UUID.shellWrite, + properties: { writeWithoutResponse: true }, + writeValueWithoutResponse: async (v: Uint8Array) => { + const line = new TextDecoder().decode(v).trim(); + + lines.push(line); + if (answers && line === "AT GETVERSION") + setTimeout(() => { + read.value = new DataView(new TextEncoder().encode("GETVERSION:1.0.1.77,OK").buffer); + read.dispatchEvent(new Event("characteristicvaluechanged")); + }); + }, + }; + const service = { uuid: "fff0", getCharacteristics: async () => [write, read] }; + const gatt = { + connected: false, + connect: async () => ((gatt.connected = true), { getPrimaryServices: async () => [service] }), + disconnect: vi.fn(() => (gatt.connected = false)), + }; + + return { device: { name, gatt }, lines }; +}; +const blast = (name: string, answers: boolean) => { + const fake = fakeWatch(name, answers); + const w = new Watch(); + + w.device = fake.device as unknown as BluetoothDevice; + return { run: () => w.shellBlast("dbg mwb 0x3800f73a 0", true), fake }; +}; + +test("a watch that answers the shell after the stream is a way out", async () => { + const { run, fake } = blast("CMF Watch 3 Pro-4DA4", true); + + expect(await run()).toBe(true); + expect(fake.lines.filter((l) => l === "dbg mwb 0x3800f73a 0").length).toBeGreaterThan(10); + expect(fake.lines.at(-1)).toBe("AT GETVERSION"); +}); + +test("a silent watch is a miss, and the link is let go for the next boot", async () => { + const { run, fake } = blast("CMF Watch 3 Pro-4DA4", false); + + expect(await run()).toBe(false); + expect(fake.device.gatt.disconnect).toHaveBeenCalled(); +}); + +test("another model is refused before anything goes out", async () => { + const { run, fake } = blast("CMF Watch Pro 2-1A2B", true); + + await expect(run()).rejects.toThrow(/Watch 3 Pro/); + expect(fake.lines).toEqual([]); +});