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
5 changes: 4 additions & 1 deletion src/lib/modules/device/lib/ble-protocol.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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),
};
Expand Down
8 changes: 7 additions & 1 deletion src/lib/modules/device/lib/ble.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ import {
planInstall,
STATUS_NAMES,
parseStubReply,
MODEL_WP3,
STATUS_OK,
STUB_SLOT,
type Wp2Package,
Expand Down Expand Up @@ -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);
Expand All @@ -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)
Expand Down
13 changes: 7 additions & 6 deletions src/lib/modules/device/lib/ota-image.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,14 +30,17 @@ export const BOARDS: Record<string, { board: string; advertised: RegExp }> = {
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;

Expand Down Expand Up @@ -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);
Expand All @@ -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;
}
35 changes: 30 additions & 5 deletions src/lib/modules/device/lib/wp2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<number, number> = { [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<number, number> = { [MODEL_WP2]: 0, [MODEL_WP3]: 2 };
const MODEL_NAMES: Record<number, string> = {
[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 {
Expand Down Expand Up @@ -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. */
Expand Down Expand Up @@ -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]);

Expand Down
17 changes: 9 additions & 8 deletions src/lib/modules/device/messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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`,
Expand Down Expand Up @@ -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}`,
Expand Down Expand Up @@ -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}`,
Expand Down Expand Up @@ -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}`,
Expand Down Expand Up @@ -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}`,
Expand Down Expand Up @@ -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]))],
Expand All @@ -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])],
];
Expand Down
8 changes: 4 additions & 4 deletions src/lib/modules/device/model/dev.model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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,
});

Expand Down
10 changes: 5 additions & 5 deletions src/lib/modules/store/i18n.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -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: "без имени",
Expand Down Expand Up @@ -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: "без назви",
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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: "बिना नाम",
Expand Down
9 changes: 4 additions & 5 deletions src/lib/modules/store/lib/firmware.ts
Original file line number Diff line number Diff line change
@@ -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 = {
Expand Down Expand Up @@ -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));
Loading
Loading