Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
83 changes: 74 additions & 9 deletions src/lib/modules/device/lib/ble.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,30 @@ export const capacityOf = (name: string | null) =>
/watch (3 pro|pro 3)/i.test(name ?? "") ? WF_CAPACITY_PRO3 : WF_CAPACITY;

const KEY_STORE = "fmc_authkey";
const LISTEN = ["cmdRead", "dataRead", "shellRead", "otaRead"] as const;

type ListenKey = (typeof LISTEN)[number];
// commands and their answers, and the data channel a face delete runs over; the shell to pair
const RESCUE_LISTEN = (keyed: boolean): ListenKey[] =>
keyed ? ["cmdRead", "dataRead"] : ["cmdRead", "dataRead", "shellRead"];
// A live watch answers a subscription in 8–11 ms (emulator); one past its crash, still
// advertising and accepting a link, never does until it reboots. ponytail: 500 ms, not the
// emulator's 300, to leave room for a slow host stack — lower it if real logs show no answer
// ever takes that long.
const RESCUE_SUB_MS = 500;
/** `p`, or `err()` if it hasn't settled within `ms`. */
export const within = <T>(p: Promise<T>, ms: number, err: () => Error): Promise<T> => {
let timer: ReturnType<typeof setTimeout> | undefined;

return Promise.race([
p,
new Promise<never>((_, rej) => (timer = setTimeout(() => rej(err()), ms))),
]).finally(() => clearTimeout(timer));
};
// The watch drops every frame for its first 200 ms on a link (the command channel opens on a
// 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;
// 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 => {
Expand Down Expand Up @@ -299,9 +323,19 @@ export class Watch {
}
throw e;
}
const subscribe = async () => {
for (const key of ["cmdRead", "dataRead", "shellRead", "otaRead"] as const) {
// Rescue listens only where its actions get answers — the shell only when it has to pair, the
// firmware-update channel never — and gives each subscription RESCUE_SUB_MS. On a watch stuck
// in a boot loop this is the first step the watch itself has to answer (Windows can serve the
// service list from its cache), and it answers at once or not before it restarts ~17 s later:
// failing fast leaves time for more tries in the windows it is up.
const subscribed = new Set<string>();
const subscribe = async (
keys: readonly ListenKey[] = rescue ? RESCUE_LISTEN(Boolean(loadKey())) : LISTEN,
) => {
for (const key of keys) {
const ch = this.chars[UUID[key]];

if (subscribed.has(ch?.uuid)) continue;
// shell service is only needed for first-time pairing; some firmwares hide it. The
// firmware-update channel only for a firmware update, which checks for it itself
if (!ch) {
Expand All @@ -314,7 +348,14 @@ export class Watch {
write: ch.properties.write,
writeNoResp: ch.properties.writeWithoutResponse,
});
await ch.startNotifications();
await (rescue
? within(
ch.startNotifications(),
RESCUE_SUB_MS,
() => new Error(`the watch didn't answer the ${key} subscription`),
)
: ch.startNotifications());
subscribed.add(ch.uuid);
ch.addEventListener("characteristicvaluechanged", (e) => {
const value = (e.target as BluetoothRemoteGATTCharacteristic).value!;
const bytes = new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
Expand Down Expand Up @@ -343,7 +384,7 @@ export class Watch {

if (k) {
try {
await this.authenticate(k);
await this.authenticate(k, rescue);
} catch (e) {
// a stale key (the watch was re-paired/reset) shows up as authFailed or silence on the first
// encrypted exchange (authMac = 0x49); other errors don't touch the saved key. On rescue
Expand All @@ -365,9 +406,13 @@ export class Watch {
await connectOrRepick("reconnection");
await subscribe();
}
await subscribe(["shellRead"]);
await this.pair(pairMs);
}
} else await this.pair(pairMs);
} else {
await subscribe(["shellRead"]);
await this.pair(pairMs);
}
if (!rescue) await this.fetchInfo();
} catch (e) {
// without this a failed pair()/authenticate() leaves the physical GATT link hanging:
Expand Down Expand Up @@ -959,7 +1004,8 @@ export class Watch {
await this.authenticate(k1);
}

async authenticate(k1: Uint8Array) {
/** `repeatName`: re-send authName until the watch answers it — see RESCUE_NAME_MS. */
async authenticate(k1: Uint8Array, repeatName = false) {
this.status("authenticating…");
await this.codec.setKey(k1);
// the watch sends authFailed if it can't decrypt with the key — we react immediately instead of waiting for the timeout
Expand All @@ -971,8 +1017,16 @@ export class Watch {
const wait = (key: number) => Promise.race([this.waitFor(key), failed]);

try {
await this.send(CMD.authName, cat(new Uint8Array([MARKER]), utf8("fmc")));
await wait(CMD.authMac);
const name = () => this.send(CMD.authName, cat(new Uint8Array([MARKER]), utf8("fmc")));

await name();
const again = repeatName ? setInterval(() => name().catch(() => {}), RESCUE_NAME_MS) : 0;

try {
await wait(CMD.authMac);
} finally {
clearInterval(again);
}
await this.send(CMD.authNonceReq, new Uint8Array([MARKER]));
const nonce = await wait(CMD.authNonceRep);

Expand All @@ -985,8 +1039,19 @@ export class Watch {
}

// Gadgetbridge's FACTORY_RESET: the marker byte and nothing else. The watch wipes itself and
// reboots; it won't answer, so there is nothing to wait for.
// reboots; it won't answer, so there is nothing to wait for. It ignores the reset until a time
// write has marked the link live (SetLinkFlg in the 0x8004 handler; WP3 firmware, confirmed in
// the cmf-watch-utils emulator), and a clock more than 2 min off takes the time only on the
// second write: so the time twice, then the reset. The payload is the reference client's
// (cmf_watch.py: >ii unix seconds, UTC offset in ms) — a malformed one once reset a watch.
async factoryReset() {
const time = new Uint8Array(8);
const dv = new DataView(time.buffer);

dv.setInt32(0, Math.floor(Date.now() / 1000));
dv.setInt32(4, -new Date().getTimezoneOffset() * 60000);
await this.send(CMD.time, time);
await this.send(CMD.time, time);
await this.send(CMD.factoryReset, new Uint8Array([MARKER]));
}

Expand Down
6 changes: 6 additions & 0 deletions src/lib/modules/device/messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ const en = {
timedOut: (what: string) =>
`${what} timed out — the watch is probably connected to another app or browser tab; close it (phone app, fmc CLI, old editor tab) and retry`,
charNotFound: (key: string) => `characteristic ${key} not found`,
subNoAnswer: (key: string) => `the watch didn't answer the ${key} subscription`,
timeoutWaiting: (cmd: string) => `timeout waiting for ${cmd}`,
pairingNotFound:
"pairing service not found — reconnect and try again; if this keeps happening the watch may be using a new service UUID (see SERVICES in ble.ts)",
Expand Down Expand Up @@ -135,6 +136,7 @@ export const bt = dict(en, {
timedOut: (what) =>
`${what}: время ожидания истекло — вероятно, часы подключены к другому приложению или вкладке; закройте его (приложение на телефоне, fmc CLI, старую вкладку редактора) и повторите`,
charNotFound: (key) => `характеристика ${key} не найдена`,
subNoAnswer: (key) => `часы не ответили на подписку ${key}`,
timeoutWaiting: (cmd) => `нет ответа на ${cmd}`,
pairingNotFound:
"сервис сопряжения не найден — переподключитесь и попробуйте снова; если повторяется, возможно, у часов новый UUID сервиса (см. SERVICES в ble.ts)",
Expand Down Expand Up @@ -230,6 +232,7 @@ export const bt = dict(en, {
timedOut: (what) =>
`${what}: час очікування вичерпано — мабуть, годинник під'єднаний до іншого застосунку чи вкладки; закрийте їх (застосунок на телефоні, fmc CLI, стару вкладку редактора) і повторіть`,
charNotFound: (key) => `характеристику ${key} не знайдено`,
subNoAnswer: (key) => `годинник не відповів на підписку ${key}`,
timeoutWaiting: (cmd) => `немає відповіді на ${cmd}`,
pairingNotFound:
"сервіс сполучення не знайдено — під'єднайтеся знову; якщо це повторюється, можливо, годинник має новий UUID сервісу (див. SERVICES у ble.ts)",
Expand Down Expand Up @@ -325,6 +328,7 @@ export const bt = dict(en, {
timedOut: (what) =>
`${what}: se agotó el tiempo — seguramente el reloj está conectado a otra app o pestaña; ciérrala (la app del teléfono, fmc CLI, una pestaña antigua del editor) y reintenta`,
charNotFound: (key) => `no se encontró la característica ${key}`,
subNoAnswer: (key) => `el reloj no respondió a la suscripción ${key}`,
timeoutWaiting: (cmd) => `sin respuesta a ${cmd}`,
pairingNotFound:
"no se encontró el servicio de emparejamiento — reconecta e inténtalo de nuevo; si se repite, puede que el reloj use un UUID de servicio nuevo (ver SERVICES en ble.ts)",
Expand Down Expand Up @@ -422,6 +426,7 @@ export const bt = dict(en, {
timedOut: (what) =>
`${what}: समय समाप्त — घड़ी शायद किसी दूसरे ऐप या टैब से जुड़ी है; उसे बंद करें (फ़ोन ऐप, fmc CLI, एडिटर का पुराना टैब) और फिर कोशिश करें`,
charNotFound: (key) => `कैरेक्टरिस्टिक ${key} नहीं मिली`,
subNoAnswer: (key) => `घड़ी ने ${key} सब्सक्रिप्शन का जवाब नहीं दिया`,
timeoutWaiting: (cmd) => `${cmd} का जवाब नहीं आया`,
pairingNotFound:
"पेयरिंग सर्विस नहीं मिली — फिर से कनेक्ट करके कोशिश करें; बार-बार हो तो घड़ी शायद नया सर्विस UUID इस्तेमाल कर रही है (ble.ts में SERVICES देखें)",
Expand Down Expand Up @@ -525,6 +530,7 @@ const RULES: Rule[] = [
lit("noWebBluetooth"),
[/^(.+) timed out — the watch is probably connected/, (w, m) => w.timedOut(m[1])],
[/^characteristic (.+) not found$/, (w, m) => w.charNotFound(m[1])],
[/^the watch didn't answer the (.+) subscription$/, (w, m) => w.subNoAnswer(m[1])],
[/^timeout waiting for (\S+)$/, (w, m) => w.timeoutWaiting(m[1])],
lit("pairingNotFound"),
[/^pairing rejected: (.+)$/s, (w, m) => w.pairingRejected(m[1])],
Expand Down
25 changes: 25 additions & 0 deletions tests/ble-factory-reset.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
// The watch ignores a factory reset until a time write marks the link live, and a clock more
// than 2 minutes off takes the time only on the second write (WP3 firmware, in the emulator).
import { expect, test } from "vitest";
import { Watch } from "$lib/modules/device/lib/ble";
import { CMD, MARKER } from "$lib/modules/device/lib/ble-protocol";

test("factory reset goes out after two time writes in the reference format", async () => {
const w = new Watch();
const sent: [number, Uint8Array][] = [];

w.send = async (key: number, payload?: Uint8Array) => {
sent.push([key, payload ?? new Uint8Array()]);
};
const before = Math.floor(Date.now() / 1000);

await w.factoryReset();

expect(sent.map(([k]) => k)).toEqual([CMD.time, CMD.time, CMD.factoryReset]);
const dv = new DataView(sent[0][1].buffer);

expect(sent[0][1].length).toBe(8);
expect(dv.getInt32(0)).toBeGreaterThanOrEqual(before);
expect(dv.getInt32(4)).toBe(-new Date().getTimezoneOffset() * 60000);

Check failure on line 23 in tests/ble-factory-reset.test.ts

View workflow job for this annotation

GitHub Actions / check

[unit] tests/ble-factory-reset.test.ts > factory reset goes out after two time writes in the reference format

AssertionError: expected +0 to be -0 // Object.is equality - Expected + Received - -0 + 0 ❯ tests/ble-factory-reset.test.ts:23:26
expect([...sent[2][1]]).toEqual([MARKER]);
});
12 changes: 12 additions & 0 deletions tests/ble-within.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
// Rescue gives each notification subscription a few seconds: a step the watch never answers must
// end, and one it answers must not leave a late rejection behind.
import { expect, test } from "vitest";
import { within } from "$lib/modules/device/lib/ble";

test("within rejects a promise that doesn't settle in time", async () => {
await expect(within(new Promise(() => {}), 10, () => new Error("late"))).rejects.toThrow("late");
});

test("within passes a prompt answer through", async () => {
await expect(within(Promise.resolve(7), 10, () => new Error("late"))).resolves.toBe(7);
});
Loading