G1 support: Preserve connections after flashing, debug

This commit is contained in:
James Babcock committed 2026-11-07 04:16:15 -08:00
1 parent 595b462b2e
commit b353483ac2
38 files changed
+1244 -131

No files matched your search

@@ -48,6 +48,13 @@ class AndroidSessionLink(private val bleManager: FaceclawBleManager) : SessionLi
override fun requestBond(address: String) = bleManager.requestBond(address)
override fun removeBond(address: String): Boolean = bleManager.removeBond(address)
override fun hasCharacteristic(address: String, characteristicUuid: String): Boolean =
bleManager.hasCharacteristic(address, characteristicUuid)
override fun refreshServices(address: String, timeoutMs: Int): Boolean = bleManager.refreshServices(address, timeoutMs)
override fun prepareBenchmarkLink(address: String, mode: Int) = bleManager.prepareBenchmarkLink(address, mode)
override fun recordDisplayFrameSent() = FaceclawBleManager.recordDisplayFrameSent()
@@ -52,6 +52,13 @@ class AndroidStockLink(context: Context) : StockLink, FaceclawBleListener {
override fun requestBond(address: String) = bleManager.requestBond(address)
override fun removeBond(address: String): Boolean = bleManager.removeBond(address)
override fun hasCharacteristic(address: String, characteristicUuid: String): Boolean =
bleManager.hasCharacteristic(address, characteristicUuid)
override fun refreshServices(address: String, timeoutMs: Int): Boolean = bleManager.refreshServices(address, timeoutMs)
override fun disconnect(address: String) = bleManager.disconnect(address)
override fun close() = bleManager.close()
@@ -27,6 +27,11 @@ import java.util.concurrent.atomic.AtomicLong
class FaceclawBleManager(context: Context) {
companion object {
private const val TAG = "FaceclawBle"
/** Not public API, but long stable, and the only way short of sending the user to Settings. */
fun removeBond(device: BluetoothDevice): Boolean =
device.bondState == BluetoothDevice.BOND_NONE || device.javaClass.getMethod("removeBond").invoke(device) == true
private val WRITE_RETRY_DELAYS_MS = intArrayOf(1, 1, 1, 2, 4, 8, 12, 20, 35, 100, 200)
// Gap after each LE 2M PHY request before checking whether it landed and asking
@@ -160,6 +165,21 @@ class FaceclawBleManager(context: Context) {
}
}
/**
* Remove this phone's half of a pairing the other side no longer has. False when the platform refused.
*/
fun removeBond(address: String?): Boolean {
if (address == null || address.trim().isEmpty()) {
return false
}
return try {
removeBond(bluetoothAdapter.getRemoteDevice(address))
} catch (t: Throwable) {
Log.w(TAG, "removeBond failed: $address", t)
false
}
}
/** Start bonding, without waiting: the OS may ask the user, and [isBonded] tells when it is done. */
fun requestBond(address: String?) {
if (address == null || address.trim().isEmpty()) {
@@ -379,6 +399,31 @@ class FaceclawBleManager(context: Context) {
return status == BluetoothGatt.GATT_SUCCESS
}
/** After discovery: whether the service table has this characteristic. */
fun hasCharacteristic(address: String, characteristicUuid: String): Boolean {
synchronized(bluetoothApiLock) {
val gatt = links[address]?.gatt ?: return false
val target = UUID.fromString(characteristicUuid)
return gatt.services.any { it.getCharacteristic(target) != null }
}
}
/**
* Forget the service table Android remembers for a bonded device and read it again. A G1 arm keeps its address across an
* install that changes its services, and a cached table would make new firmware look like the old one.
*/
fun refreshServices(address: String, timeoutMs: Int): Boolean {
synchronized(bluetoothApiLock) {
val gatt = links[address]?.gatt ?: return false
try {
gatt.javaClass.getMethod("refresh").invoke(gatt)
} catch (t: Throwable) {
Log.w(TAG, "refresh failed: $address", t)
}
}
return discoverServices(address, timeoutMs)
}
fun enableNotifications(address: String, characteristicUuid: String, enable: Boolean, timeoutMs: Int): Boolean {
synchronized(bluetoothApiLock) {
val gatt = requireGatt(address)
@@ -141,9 +141,9 @@ class FaceclawDeviceDiscovery(context: Context) {
val upper = name.uppercase()
// A bare "R1" substring also matches unrelated hardware ("Oppo Enco
// R1"), and TS only classifies rings from the stock name prefix.
// Even G1: its stock name, or g1v0's G1v0_L / G1v0S_R (safe mode).
// Even G1: its stock name, or g1v0's G1CFW_L_XXXXXX (before 0.5.66: G1v0_L, G1v0S_R).
return upper.contains("G2") || upper.startsWith("EVEN R1") || upper.startsWith("RAYNEO") ||
upper.startsWith("EVEN G1") || upper.startsWith("G1V0")
upper.startsWith("EVEN G1") || upper.startsWith("G1CFW_") || upper.startsWith("G1V0")
}
private fun buildJson(
@@ -76,6 +76,16 @@ class FaceclawG1Flasher(context: Context, address: String?, side: String?, firmw
}
}
companion object {
/** The phone's pairing with an address these glasses no longer use. */
@JvmStatic
fun forgetPairing(context: Context, address: String?) {
if (address == null) return
val manager = context.applicationContext.getSystemService(Context.BLUETOOTH_SERVICE) as android.bluetooth.BluetoothManager
FaceclawBleManager.removeBond(manager.adapter.getRemoteDevice(address))
}
}
private fun post(action: (FaceclawFirmwareFlasherListener) -> Unit) {
mainHandler.post {
val current = listener
+6 -6
View File
@@ -15,23 +15,23 @@ export type G1FirmwareImage = {
};
export const G1V0_IMAGE: G1FirmwareImage = {
"version": "0.5.65",
"sha256": "b8707c80c3fbde1458e92eb39602125df8f03d809c768dab4f33b15c0e7dff9f",
"size": 582820,
"source": "51596992c1f1+uncommitted",
"version": "0.5.66",
"sha256": "9861a5671ed2fab6a678feae1f22e57d0b41bbb5934d83b898c5108db3a474fd",
"size": 582992,
"source": "ceb74cce6945",
"stockVersion": "1.6.6",
"stockZipUrl": "https://cdn.evenreal.co/firmware/dcfa510c090e476c10a6f6c348a22415.zip",
"stockZipSha256": "748836f2d9d092b0783cbb7672fdccec4f730051cad27f095bbb156ac3e5d316",
"parts": [
{
"offset": 271104,
"offset": 271264,
"length": 226020,
"file": "net_core_app_update.bin",
"fileOffset": 0,
"sha256": "c277749be97a2763742db399afeb10ca6916059abd60d41bbc05c8892c002c77"
},
{
"offset": 497152,
"offset": 497312,
"length": 352,
"file": "app_update.bin",
"fileOffset": 531288,
+1 -1
View File
@@ -1,4 +1,4 @@
// AUTO-GENERATED by tools/g1_firmware_bundle.py -- do not edit by hand.
// The built g1v0 image without Even's parts (g1v0-image.ts), deflated.
export const G1V0_OWN_BYTES_BASE64 = "eNrsfIl/U1X2+H1L1oY2pQXSBXxJWk2biqFlKRQkTdrXJYWWbQZxSwE1BZVgdSytI2FRCugMUhEEGXHQr4goLcsMpdZUwMFxmUlYRjaluIW20nmhhbzsv3NfUmDm+/sLfp8ffG7eue/ee+65555z7jn33tdpRwbeQPgfidDcK1IBRKJiNPQv+v///T/9b88/RYyng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vDedObRAaym9TKrd94ScOFCxe9ePzG30wqoeF9g4/oe7E6dyHkwTt+D Line truncated
+21
View File
@@ -9,6 +9,10 @@ export const G1_SIDES: readonly G1Side[] = ["left", "right"];
export const G1_CASE_INSTRUCTIONS =
"Put the glasses in their charging case with the lid open, and plug the case in. Stay nearby, and leave Faceclaw open.";
/** An arm bonds only once it knows it's in the case, and a full case only says so about every 5 minutes. */
export const G1_CASE_DELAY_HINT =
"A fully charged arm can take up to 5 minutes to notice it's in the case, so this may take a while.";
export const G1_INSTALL_NOTICE =
"This replaces the firmware on both arms, about two minutes each. Going back to Even's firmware later takes a computer, and " +
"may not be the version you have now. Installing custom firmware is not covered by warranty.";
@@ -81,6 +85,23 @@ export function g1FirmwareState(arms: readonly G1FlashResult[], shipped: string)
return arms.some((arm) => compareG1Versions(arm.version ?? "", shipped) < 0) ? "older" : "current";
}
/**
* What the arms' advertising alone says about their firmware, or null when an arm has to be asked: firmware before 0.5.66
* doesn't advertise its version.
*/
export function g1StateFromAdvertising(
pair: Pick<GlassesPairCandidate, "left" | "right">,
shipped: string,
): { state: G1FirmwareState; version: string } | null {
const arms = [pair.left, pair.right];
if (arms.some((arm) => arm?.g1Firmware === "stock")) return { state: "stock", version: "" };
if (arms.some((arm) => arm?.g1Firmware === "g1v0-safe")) return { state: "safe-mode", version: "" };
const versions = arms.map((arm) => arm?.g1Version);
if (!versions[0] || !versions[1]) return null;
const lowest = compareG1Versions(versions[0], versions[1]) <= 0 ? versions[0] : versions[1];
return { state: compareG1Versions(lowest, shipped) < 0 ? "older" : "current", version: lowest };
}
/** Each arm counts for half of the bar. */
export function g1FlashPercent(side: G1Side, bytesSent: number, bytesTotal: number): number {
const within = bytesTotal > 0 ? Math.min(1, bytesSent / bytesTotal) : 0;
+20 -5
View File
@@ -32,7 +32,7 @@ export const EVEN_COMPANY_IDENTIFIER = 0x5245;
export type EvenDeviceRole = "left" | "right" | "ring" | "rayneo-io";
/** The firmware an Even G1 arm's name shows: Even's, or g1v0 (in safe mode: only updates work). */
/** The firmware an Even G1 arm advertises: Even's, or Faceclaw's g1v0 (in safe mode: only updates work). */
export type G1Firmware = "stock" | "g1v0" | "g1v0-safe";
/** True when the manufacturer data opens with Even's `"ER"` marker. */
@@ -79,11 +79,15 @@ export function extractG2AdvertisementFlag(mfg: Uint8Array): number | null {
*
* On Even's firmware the name is `Even G1_<token>_<L|R>_<hex6>` and the manufacturer data `[01 right | 02 left]` +
* the ASCII serial, zero-padded (the first two bytes read as a "company id" that differs per arm). On g1v0 the name
* is `G1v0_L` or `G1v0_R` (`G1v0S_…` in safe mode) and the scan response holds company 0xFFFF, a format byte (1), a
* flags byte, and the pair ID in ASCII: the frame serial, the same on both arms.
* is `G1CFW_<L|R>_<hex6>` with the same digits and address as stock's, and the scan response holds company 0xFFFF, a
* format byte (2), a flags byte (bit 3: safe mode), the firmware's version in three bytes, and the pair ID in ASCII:
* the frame serial, the same on both arms. Before 0.5.66: `G1v0_L` or `G1v0_R` (`G1v0S_…` in safe mode), format 1, no
* version.
*/
export function g1FromName(name: string | null | undefined): { side: "left" | "right"; firmware: G1Firmware } | null {
if (!name) return null;
const custom = /^G1CFW_([LR])_[0-9A-F]{6}$/i.exec(name.trim());
if (custom) return { side: custom[1]!.toUpperCase() === "L" ? "left" : "right", firmware: "g1v0" };
const g1v0 = /^G1V0(S?)_([LR])$/i.exec(name.trim());
if (g1v0) {
return {
@@ -96,9 +100,16 @@ export function g1FromName(name: string | null | undefined): { side: "left" | "r
return side ? { side, firmware: "stock" } : null;
}
/** What g1v0's pair record says beyond the serial; null when there is no record of a format that says it. */
export function parseG1Record(mfg: Uint8Array): { version: string; safeMode: boolean } | null {
if (mfg.length < 7 || mfg[0] !== 0xff || mfg[1] !== 0xff || mfg[2] !== 2) return null;
return { version: `${mfg[4]}.${mfg[5]}.${mfg[6]}`, safeMode: (mfg[3]! & 8) !== 0 };
}
/** The pair's serial from an arm's manufacturer data, on either firmware; null when absent. */
export function extractG1Serial(mfg: Uint8Array, firmware: G1Firmware): string | null {
const start = firmware === "stock" ? 1 : mfg.length >= 4 && mfg[0] === 0xff && mfg[1] === 0xff && mfg[2] === 1 ? 4 : -1;
const record = mfg.length >= 4 && mfg[0] === 0xff && mfg[1] === 0xff;
const start = firmware === "stock" ? 1 : record && mfg[2] === 2 ? 7 : record && mfg[2] === 1 ? 4 : -1;
if (start < 0 || mfg.length <= start) return null;
let serial = "";
for (let i = start; i < mfg.length; i++) {
@@ -259,6 +270,8 @@ export type EvenAdvertisement = {
note: string | null;
/** Set on an Even G1 arm (role left or right): its firmware. */
g1Firmware?: G1Firmware;
/** The version g1v0 advertises (0.5.66+); absent when it doesn't say. */
g1Version?: string;
};
/**
@@ -285,6 +298,7 @@ export function classifyAdvertisement(raw: RawAdvertisement): EvenAdvertisement
const g1 = g1FromName(name);
if (g1) {
const serial = extractG1Serial(mfg, g1.firmware);
const record = g1.firmware === "stock" ? null : parseG1Record(mfg);
return {
address: normalizeMacAddress(raw.address),
name,
@@ -302,7 +316,8 @@ export function classifyAdvertisement(raw: RawAdvertisement): EvenAdvertisement
seenAtMs: raw.seenAtMs,
manufacturerData: raw.manufacturerData ?? "",
note: serial ? null : "no serial in the advertisement (it may still be arriving)",
g1Firmware: g1.firmware,
g1Firmware: record?.safeMode ? "g1v0-safe" : g1.firmware,
...(record ? { g1Version: record.version } : {}),
};
}
+15 -1
View File
@@ -1,12 +1,26 @@
import { classifyAdvertisement, hasEvenManufacturerSignature, type EvenAdvertisement } from './even-advertisement'
import { classifyAdvertisement, g1FromName, hasEvenManufacturerSignature, type EvenAdvertisement } from './even-advertisement'
import { hexToBytes } from '../util/hex-util'
export type IosAdvertisement = { identifier: string; name: string; manufacturerData: string; rssi: number; connectable: boolean }
export type IosDevice = EvenAdvertisement & { identifier: string }
/**
* A G1 arm advertises no full MAC, and CoreBluetooth hides the real one. Faceclaw's addresses are MAC-shaped everywhere, so its
* address on this phone is made from the peripheral identifier. It's stable as long as the identifier is, which on firmware
* 0.5.66 and later is across installs too, and it only has to mean something on this phone: nobody types it in.
*/
export function g1IosAddress(identifier: string): string {
return identifier.replace(/-/g, '').slice(0, 12).toUpperCase().replace(/(..)(?=.)/g, '$1:')
}
/** Only a full vendor-advertised MAC may bind a manually entered address. */
export function identifyIosPeripheral(raw: IosAdvertisement): IosDevice | null {
if (!/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(raw.identifier)) return null
if (g1FromName(raw.name)) {
const arm = classifyAdvertisement({ ...raw, address: g1IosAddress(raw.identifier), source: 'scan', bonded: false,
txPower: null, seenAtMs: Date.now() })
return arm && { ...arm, identifier: raw.identifier.toUpperCase() }
}
if (!hasEvenManufacturerSignature(hexToBytes(raw.manufacturerData))) return null
const candidate = classifyAdvertisement({ ...raw, address: '', source: 'scan', bonded: false,
txPower: null, seenAtMs: Date.now() })
+2 -2
View File
@@ -54,7 +54,7 @@ import { onAnySettingChanged,
previewColorSetting, lockScreenEnabledSetting, getBrightnessPreferences, getStringSettingById,
nightscoutSiteUrlSetting, nightscoutApiTokenSetting, voiceProviderSetting, elevenLabsApiKeySetting,
openAiApiKeySetting, sonioxApiKeySetting, whisperServerApiKeySetting, whisperServerLanguageSetting,
whisperServerModelSetting, whisperServerUrlSetting, ringConnectionModeSetting, saveTranscribeAudioSetting } from '../ui/dashboard-settings'
whisperServerModelSetting, whisperServerUrlSetting, ringConnectionModeSetting, saveTranscribeAudioSetting, glassesTypeSetting } from '../ui/dashboard-settings'
import { transcriptionKey, type VoiceProviderSelection } from '../native/cloud-stt-provider'
import type { PhoneGesture } from '../phone-ui/phone-gestures'
import { claimGlassesOnboardingAutoLaunch, ONBOARDING_APP_ID } from '../apps/onboarding/onboarding-progress'
@@ -881,7 +881,7 @@ export class IosPreviewController {
return
}
if (this.communicator) await this.closeCommunicator()
const communicator = new FaceclawCommunicatorBridge(identifiers)
const communicator = new FaceclawCommunicatorBridge({ ...identifiers, glassesType: glassesTypeSetting.get() })
this.teardownPreviewDisplay()
this.communicator = communicator
this.wearDetectionRequested = false
+3
View File
@@ -7,6 +7,9 @@ export type { G1FlashMode, G1FlasherOptions } from './g1-flasher'
declare const FaceclawKitIosG1Flasher: any, FaceclawKitFaceclawFirmwareFlasherListener: any
/** CoreBluetooth has no way to remove a pairing; iOS Settings does it, and a stale one does no harm. */
export function forgetG1Pairing(_address: string): void {}
/**
* iOS twin of the Android G1Flasher: the shared Kotlin G1ArmFlashFlow over a CoreBluetooth central. As with the G2's
* flasher, the phone must stay in the foreground with the screen awake, and addresses are mapped to peripheral
+6
View File
@@ -15,6 +15,12 @@ export type G1FlasherOptions = {
connectWindowMs: number;
};
/** Removes the phone's pairing with an address the glasses no longer use. */
export function forgetG1Pairing(address: string): void {
const context = Utils.android.getApplicationContext();
if (context) com.faceclaw.app.FaceclawG1Flasher.forgetPairing(context, address);
}
/** TS wrapper around FaceclawG1Flasher: one arm's install, or a question about what it runs. */
export class G1Flasher {
private readonly flasher: any;
+18 -5
View File
@@ -4,13 +4,21 @@ import { G1ArmScanner } from "../g1/arm-scanner";
import { G1V0_IMAGE } from "../g1/firmware/g1v0-image";
import { buildG1Firmware, type BuiltG1Firmware, type G1BuildProgress } from "../g1/firmware-builder";
import { saveG1Arm, saveG1Pair } from "../g1/addresses";
import { G1_CASE_INSTRUCTIONS, G1_INSTALL_NOTICE, G1_SIDES, g1FlashPercent, type G1FlashResult, type G1Side } from "../g1/flash-plan";
import {
G1_CASE_DELAY_HINT,
G1_CASE_INSTRUCTIONS,
G1_INSTALL_NOTICE,
G1_SIDES,
g1FlashPercent,
type G1FlashResult,
type G1Side,
} from "../g1/flash-plan";
import { loadDeviceAddresses, loadPairedGlassesIdentity } from "../g2/device-addresses";
import { downloadAndExtractEvenHubFonts, hasExtractedEvenHubFonts } from "../g2/firmware-builder";
import { type GlassesPairCandidate } from "../g2/pairing-candidates";
import { resumeAutoReconnect, suppressAutoReconnect } from "../g2/reconnect-policy";
import { ensureBlePermissions } from "../native/ble-permissions";
import { G1Flasher, type G1FlasherOptions } from "../native/g1-flasher";
import { forgetG1Pairing, G1Flasher, type G1FlasherOptions } from "../native/g1-flasher";
import { formatErrorMessage } from "../util/format-error";
import { finishOnboardingNavigation } from "./onboarding-navigation";
import { setOnboardingCompleted, setPreviewOnlyMode } from "./onboarding-state";
@@ -190,11 +198,16 @@ export class G1FlashViewModel extends Observable {
"open: an interrupted install finishes by itself. Then retry.");
}
saveG1Arm(side, back);
// Coming from firmware before 0.5.66, which had an address of its own: the phone needn't remember that one.
if (back.address !== arm.address) forgetG1Pairing(arm.address);
if (back.g1Firmware === "g1v0-safe") {
throw new Error(`The ${side} arm came back in safe mode: the new firmware restarted repeatedly. Retry to install it again.`);
}
this.setStatus(`Pairing with the ${side} arm. If your phone asks, accept it.`);
this.setStatus(`Checking the ${side} arm. If your phone asks to pair, accept it. ${G1_CASE_DELAY_HINT}`);
// An arm at a new address has no bond yet (coming from Even's firmware the address is kept from 0.5.66 on, and so is the
// bond). It may refuse one for a while: it's installed either way, and the session pairs it later.
const newAddress = back.address !== arm.address;
let running: G1FlashResult;
try {
running = await this.flash({
@@ -202,10 +215,10 @@ export class G1FlashViewModel extends Observable {
side,
firmwarePath: "",
mode: "probe",
connectWindowMs: fromStock ? FIRST_PAIRING_MS : RETURN_MS,
connectWindowMs: newAddress ? FIRST_PAIRING_MS : RETURN_MS,
});
} catch (error) {
if (!fromStock || !live()) throw error;
if (!newAddress || !live()) throw error;
// Installed, as its advertising shows; it just won't pair yet. The next connection pairs it.
this.appendLog(`${side} arm not paired yet: ${formatErrorMessage(error)}`);
this.unpairedArm = true;
@@ -22,7 +22,15 @@ import { G1Flasher } from "../native/g1-flasher";
import { saveG1Pair } from "../g1/addresses";
import { G1ArmScanner } from "../g1/arm-scanner";
import { G1V0_IMAGE } from "../g1/firmware/g1v0-image";
import { G1_CASE_INSTRUCTIONS, G1_INSTALL_NOTICE, g1FirmwareState, type G1FlashResult, type G1Side } from "../g1/flash-plan";
import {
G1_CASE_DELAY_HINT,
G1_CASE_INSTRUCTIONS,
G1_INSTALL_NOTICE,
g1FirmwareState,
g1StateFromAdvertising,
type G1FlashResult,
type G1Side,
} from "../g1/flash-plan";
import { loadPairedGlassesIdentity } from "../g2/device-addresses";
import { glassesTypeSetting } from "../ui/dashboard-settings";
import { setOnboardingCompleted, setPreviewOnlyMode } from "./onboarding-state";
@@ -213,8 +221,8 @@ export class OnboardingFirmwareCheckViewModel extends Observable {
}
/**
* What each arm's name says first, as that needs no connection: Even's firmware can't be asked in the same way, and an
* arm that is about to be replaced shouldn't have to pair. Only arms on g1v0 are asked which version they run.
* What the arms advertise first, as that needs no connection or pairing. Only firmware from before it advertised its
* version (0.5.66) has to be asked.
*/
private async checkG1(generation: number): Promise<void> {
this.status = "Listening for your glasses...";
@@ -229,13 +237,12 @@ export class OnboardingFirmwareCheckViewModel extends Observable {
return;
}
saveG1Pair(pair);
const named = [pair.left!.g1Firmware, pair.right!.g1Firmware];
if (named.includes("stock")) {
this.showG1Install({ firmware: "stock" });
return;
}
if (named.includes("g1v0-safe")) {
this.showG1Install({ safeMode: true });
const advertised = g1StateFromAdvertising(pair, G1V0_IMAGE.version);
if (advertised) {
if (advertised.state === "current") this.applyClassification("custom", advertised.version, { kind: "none" });
else if (advertised.state === "stock") this.showG1Install({ firmware: "stock" });
else if (advertised.state === "safe-mode") this.showG1Install({ safeMode: true });
else this.showG1Install({ version: advertised.version });
return;
}
const arms: G1FlashResult[] = [];
@@ -245,7 +252,7 @@ export class OnboardingFirmwareCheckViewModel extends Observable {
flasher.onState((state) => {
if (generation !== this.generation) return;
if (state === "pairing") {
this.status = `Pairing with the ${side} arm. If your phone asks, accept it. A G1 pairs only in its case, with the lid open.`;
this.status = `Pairing with the ${side} arm. If your phone asks, accept it. A G1 pairs only in its case, with the lid open. ${G1_CASE_DELAY_HINT}`;
} else {
this.status = `Checking the ${side} arm...`;
}
+4 -3
View File
@@ -383,9 +383,10 @@ export class PairingViewModel extends Observable {
}
}
this.dispose();
if (this.onboarding) {
setPreviewOnlyMode(false);
// Continue the onboarding chain: check the glasses' firmware next.
if (this.onboarding) setPreviewOnlyMode(false);
// Onboarding checks the glasses' firmware next. So does choosing a G1 from anywhere: it may run Even's firmware,
// and whether it does is known without connecting.
if (this.onboarding || pair?.g1Firmware) {
Frame.topmost()?.navigate({ moduleName: "phone-ui/onboarding-firmware-check-page" });
return;
}
+2
View File
@@ -11,6 +11,8 @@
# iOS bundle ID; set one your signing team owns to sideload alongside the
# official build (default com.faceclaw.app). Also used by the iOS config scripts.
#export IOS_BUNDLE_ID=
# Which iPhone scripts target (default: the only one connected)
#export IOS_DEVICE=
# Embed the Apple Watch app in the iOS app. Its link to the phone needs this, and
# signing it needs a watch registered to your team, so it's off by default.
#export FACECLAW_EMBED_WATCH=1
@@ -86,6 +86,12 @@ class G1ArmFlashFlow(
private var controlLatch: Latch? = null
private var nextControlTag = 0
private var stockBattery: Int? = null
private var stockBatteryLatch: Latch? = null
/** The OS's half of a stale pairing goes once per run: a second failure isn't that. */
private var bondRemoved = false
private var linkLost = false
private var heartbeats = 0
private var nextHeartbeatAtMs = 0L
@@ -150,11 +156,11 @@ class G1ArmFlashFlow(
listener.onComplete(true, """{"flashed":false,"version":"$version"}""")
return
}
val battery = batteryPercent()
if (battery != null && battery < MIN_BATTERY_PERCENT) {
throw IllegalStateException("The $side arm's battery is at $battery%, too low to install safely. " +
"Charge both arms to at least $MIN_BATTERY_PERCENT% in the case, then try again.")
}
requireBattery(batteryPercent())
} else {
val battery = stockBatteryPercent()
log(if (battery == null) "battery unknown; going on, as the arm is in the case" else "battery $battery%")
requireBattery(battery)
}
val slots = retrying { images() }
@@ -189,6 +195,13 @@ class G1ArmFlashFlow(
listener.onComplete(true, """{"flashed":true,"version":"$version"}""")
}
private fun requireBattery(percent: Int?) {
if (percent != null && percent < MIN_BATTERY_PERCENT) {
throw IllegalStateException("The $side arm's battery is at $percent%, too low to install safely. " +
"Charge both arms to at least $MIN_BATTERY_PERCENT% in the case, then try again.")
}
}
private fun holdsImage(slots: List<G1Smp.Slot>, hash: ByteArray): Boolean =
slots.any { it.image == 0 && it.slot == 1 && it.hash.contentEquals(hash) }
@@ -263,11 +276,9 @@ class G1ArmFlashFlow(
log("connect attempt $attempt failed: $failure")
quietly { link.disconnect(address) }
if (now() >= deadline) {
throw IllegalStateException("Couldn't reach the $side arm: $failure." + if (mode == Mode.STOCK) {
" If this phone was paired with these glasses before, remove them from its Bluetooth settings and try again."
} else {
""
})
throw IllegalStateException("Couldn't reach the $side arm: $failure. Keep the glasses in the case with the lid open; a fully " +
"charged arm can take up to 5 minutes to notice it's in the case. If this phone was paired with these glasses before and " +
"this keeps happening, remove them from its Bluetooth settings and try again.")
}
sleeper.sleep(timings.retryDelayMs.toLong())
}
@@ -284,16 +295,20 @@ class G1ArmFlashFlow(
if (mode == Mode.STOCK) {
// Even's firmware serves its own service only on an encrypted link, and the heartbeat goes there.
settleBond()
if (!link.enableNotifications(address, G1Smp.NUS_TX_UUID, timings.descriptorTimeoutMs)) {
if (!haveCharacteristic(G1Smp.NUS_TX_UUID)) throw IllegalStateException("no link to Even's service")
if (!subscribe(G1Smp.NUS_TX_UUID)) {
// Bonded and refused: Even's firmware keeps one bond and has lost this one. This run started in the case.
removeStaleBond()
throw IllegalStateException("no link to Even's service")
}
heartbeats = 0
nextHeartbeatAtMs = 0
} else {
if (!link.enableNotifications(address, G1Ble.EVT_CHAR_UUID, timings.descriptorTimeoutMs)) {
if (!haveCharacteristic(G1Ble.EVT_CHAR_UUID)) {
if (!link.isConnected(address)) throw LinkLostException("the link went down")
throw NotG1v0Exception()
}
if (!subscribe(G1Ble.EVT_CHAR_UUID)) throw IllegalStateException("no events from the arm")
// Out of the case the arm obeys only an encrypted link.
settleBond()
val paired = try {
@@ -301,13 +316,71 @@ class G1ArmFlashFlow(
} catch (e: IllegalStateException) {
false
}
if (!paired) throw IllegalStateException("no encrypted link: an arm pairs only in its case")
if (!paired) {
// The OS says bonded and the arm disagrees. Giving that up is safe only where a new bond can be made.
if (link.isConnected(address) && inCaseWithoutEncryption()) removeStaleBond()
throw IllegalStateException("no encrypted link: an arm pairs only in its case")
}
if (mode != Mode.PROBE && !link.enableNotifications(address, G1Smp.SMP_CHAR_UUID, timings.descriptorTimeoutMs)) {
}
if (mode != Mode.PROBE && (!haveCharacteristic(G1Smp.SMP_CHAR_UUID) || !subscribe(G1Smp.SMP_CHAR_UUID))) {
throw IllegalStateException("no update service")
}
}
/** An arm keeps its address across an install, and the OS may remember the services it had before: look again before believing that. */
private fun haveCharacteristic(uuid: String): Boolean {
if (link.hasCharacteristic(address, uuid)) return true
log("no $uuid in the service table: reading it again")
link.refreshServices(address, timings.servicesTimeoutMs)
return link.hasCharacteristic(address, uuid)
}
private fun subscribe(uuid: String): Boolean = try {
link.enableNotifications(address, uuid, timings.descriptorTimeoutMs)
} catch (e: IllegalStateException) {
false
}
private fun removeStaleBond() {
if (bondRemoved || link.bondState(address) != BondState.BONDED) return
if (link.removeBond(address)) {
bondRemoved = true
log("the arm no longer has this phone's pairing: removed it, pairing again")
}
}
/** An unencrypted link gets an answer only from an arm in the case. */
private fun inCaseWithoutEncryption(): Boolean = try {
val hello = G1Protocol.parseHello(control(G1Protocol.OP_HELLO, tries = 1).body)
hello != null && hello.inCase && !hello.encrypted
} catch (e: Exception) {
false
}
/** Null when no answer came, which firmware that doesn't have the query also gives. */
private fun stockBatteryPercent(): Int? {
repeat(timings.controlTries) {
val latch = Latch(1, platform)
lock.withLock {
stockBattery = null
stockBatteryLatch = latch
}
try {
link.writeFrames(address, G1Smp.NUS_RX_UUID, listOf(G1Smp.STOCK_BATTERY_QUERY), GattWriteMode.WITHOUT_RESPONSE, timings.writeTimeoutMs)
} catch (e: IllegalStateException) {
return null
}
latch.await(timings.controlReplyMs.toLong())
throwIfCancelled()
val answer = lock.withLock {
stockBatteryLatch = null
stockBattery
}
if (answer != null) return answer
}
return null
}
/** Asks the OS to pair if it hasn't, and waits for that to end; a platform that doesn't say pairs by itself. */
private fun settleBond() {
if (link.bondState(address) == BondState.NONE) {
@@ -377,8 +450,8 @@ class G1ArmFlashFlow(
}
}
private fun control(op: Int, body: ByteArray = ByteArray(0)): G1Protocol.Reply {
repeat(timings.controlTries) {
private fun control(op: Int, body: ByteArray = ByteArray(0), tries: Int = timings.controlTries): G1Protocol.Reply {
repeat(tries) {
val tag = nextControlTag % 255 + 1
nextControlTag = tag
val latch = Latch(1, platform)
@@ -445,6 +518,12 @@ class G1ArmFlashFlow(
}
}
}
} else if (characteristicUuid.equals(G1Smp.NUS_TX_UUID, ignoreCase = true)) {
val percent = G1Smp.parseStockBattery(data) ?: return
lock.withLock {
stockBattery = percent
stockBatteryLatch?.countDown()
}
} else if (characteristicUuid.equals(G1Ble.EVT_CHAR_UUID, ignoreCase = true)) {
val reply = G1Protocol.parseReply(data) ?: return
lock.withLock {
@@ -168,6 +168,15 @@ object G1Smp {
fun stockHeartbeat(seq: Int): ByteArray =
byteArrayOf(0x25, 0x06, 0x00, seq.toByte(), 0x04, seq.toByte())
/** Even's firmware's battery query; its reply is `2C 66`, then the percentage. The bytes its real firmware answered in emulation. */
val STOCK_BATTERY_QUERY = byteArrayOf(0x2c, 0x04, 0x00, 0x00)
/** The percentage in a reply to [STOCK_BATTERY_QUERY]; null for anything else, or a value that can't be one. */
fun parseStockBattery(data: ByteArray): Int? {
if (data.size < 3 || data[0].toInt() != 0x2c || (data[1].toInt() and 0xff) != 0x66) return null
return (data[2].toInt() and 0xff).takeIf { it in 1..100 }
}
fun frame(op: Int, group: Int, seq: Int, cmd: Int, payload: Map<String, Any?>): ByteArray {
val body = G1Cbor.encode(payload)
val out = ByteArray(HEADER + body.size)
@@ -54,6 +54,15 @@ interface StockLink {
/** Ask the OS to pair with a connected device; a platform that pairs by itself on demand does nothing. */
fun requestBond(address: String) {}
/** Remove this phone's half of a pairing; false where the platform can't or refused. */
fun removeBond(address: String): Boolean = false
/** After discovery: whether the service table has this characteristic. Enabling notifications on one it lacks may throw. */
fun hasCharacteristic(address: String, characteristicUuid: String): Boolean = true
/** Read the service table again, past whatever the OS cached for this address. */
fun refreshServices(address: String, timeoutMs: Int): Boolean = discoverServices(address, timeoutMs)
fun disconnect(address: String)
fun close()
@@ -496,7 +496,7 @@ internal fun GlassesSessionCore.scheduleReconnectLocked(sessionWasReady: Boolean
if (sessionWasReady && now - lastSessionReadyAtMs >= ConnectionOptions.STABLE_SESSION_MS) {
consecutiveReconnects = 0
}
val schedule = ConnectionOptions.RECONNECT_BACKOFF_MS
val schedule = if (isG1) G1Timings.RECONNECT_BACKOFF_MS else ConnectionOptions.RECONNECT_BACKOFF_MS
val delayMs = schedule[minOf(consecutiveReconnects, schedule.size - 1)].toLong()
consecutiveReconnects++
reconnectAfterMs = now + delayMs
@@ -2275,7 +2275,9 @@ class GlassesSessionCore(
return
}
if (!connected && isIo) io.reassembler.reset()
if (!connected) {
if (!connected && isG1 && g1CarryOnWithoutArmLocked(address)) {
// The session goes on; the worker brings this arm back.
} else if (!connected) {
// Before the session is ready, this is an attempt failing (or an arm
// dropping mid-setup): the connect sequence notices on its own and
// schedules the retry, so leave the backoff alone.
@@ -57,6 +57,13 @@ internal class G1SessionState {
/** The right arm's relay is there and this host listens to it. */
var ancsRelay = false
/** When an arm dropped while the session carried on with the other; 0: its link is up. */
val armDownSinceMs = LongArray(2)
/** When to ask for a lost arm's link again. */
val armRetryAtMs = LongArray(2)
/** How long the session carries on with one arm before it starts over. */
var armRecoveryMs = G1Timings.ARM_RECOVERY_MS
fun nextTag(): Int {
tag = tag % 255 + 1
return tag
@@ -75,6 +82,8 @@ internal class G1SessionState {
lastMicRenewAtMs = 0
mic.reset()
ancsRelay = false
armDownSinceMs.fill(0)
armRetryAtMs.fill(0)
}
}
@@ -95,8 +104,18 @@ internal object G1Timings {
const val IDLE_WAKE_MS = 500L
const val LENS_LEFT = 1
const val LENS_RIGHT = 2
const val ARM_RECOVERY_MS = 15_000L
const val ARM_RETRY_MS = 1_000L
/** With the other arm's traffic waiting behind it. */
const val ARM_RECOVERY_WRITE_MS = 5_000
/** An arm advertises fast for a minute after a disconnection, so most links are back at once. */
val RECONNECT_BACKOFF_MS = intArrayOf(500, 1_000, 2_000, 4_000, 8_000)
}
/** An arm bonds only once it knows it's in the case, and a full case only says so about every 5 minutes. */
private const val G1_CASE_DELAY_HINT = "A fully charged arm can take up to 5 minutes to notice it's in the case."
/** What the Install prompt says an arm runs when it isn't g1v0. */
private const val G1_OTHER_FIRMWARE = "Even's firmware"
private val G1_PROPS = intArrayOf(G1Protocol.PROP_BATT_PCT, G1Protocol.PROP_CHARGE, G1Protocol.PROP_IN_CASE, G1Protocol.PROP_WORN)
@@ -120,6 +139,8 @@ internal fun g1SupportsMessage(message: OutboundMessage): Boolean {
private fun GlassesSessionCore.g1ArmAddress(arm: Int): String = if (arm == 0) leftAddress else rightAddress
private fun g1Side(arm: Int): String = if (arm == 0) "left" else "right"
private fun g1Lens(arm: Int): Int = if (arm == 0) G1Timings.LENS_LEFT else G1Timings.LENS_RIGHT
// ---------------------------------------------------------------------------------------------
@@ -141,25 +162,32 @@ private fun GlassesSessionCore.g1WriteControl(address: String, op: Int, tag: Int
* A control request and its reply; worker thread, outside the monitor. Writes on a link the arm doesn't yet obey
* (out of the case, before encryption) are ignored and control requests can be lost, so it asks again.
*/
private fun GlassesSessionCore.g1Control(arm: Int, op: Int, body: ByteArray = ByteArray(0)): G1Protocol.Reply {
private fun GlassesSessionCore.g1Control(arm: Int, op: Int, body: ByteArray = ByteArray(0), tries: Int = G1Timings.CONTROL_TRIES): G1Protocol.Reply {
val address = g1ArmAddress(arm)
repeat(G1Timings.CONTROL_TRIES) {
repeat(tries) {
val tag = monitor.withLock { g1.nextTag() }
val key = arm * 256 + tag
if (!g1WriteControl(address, op, tag, body)) throw IllegalStateException("control $op write failed")
val written = try {
g1WriteControl(address, op, tag, body)
} catch (e: IllegalStateException) {
false
}
if (!written) throw G1ConnectException(g1Side(arm) + " arm dropped", "The " + g1Side(arm) + " arm dropped the connection.")
val deadline = now() + G1Timings.CONTROL_REPLY_MS
monitor.withLock {
while (true) {
g1.replies.remove(key)?.let { return it }
if (!running || userDisconnectRequested) throw IllegalStateException("stopped while waiting for control $op")
if (!(if (arm == 0) leftConnected else rightConnected)) throw IllegalStateException("link lost waiting for control $op")
if (!(if (arm == 0) leftConnected else rightConnected)) {
throw G1ConnectException(g1Side(arm) + " arm dropped", "The " + g1Side(arm) + " arm dropped the connection.")
}
val remaining = deadline - now()
if (remaining <= 0) break
monitor.awaitMs(minOf(remaining, 100L))
}
}
}
throw IllegalStateException("no reply to control $op from the " + (if (arm == 0) "left" else "right") + " arm")
throw G1ConnectException(g1Side(arm) + " arm silent", "The " + g1Side(arm) + " arm isn't answering.")
}
private fun GlassesSessionCore.g1RequestProps(arm: Int, ids: IntArray) {
@@ -176,19 +204,25 @@ private fun GlassesSessionCore.g1RequestProps(arm: Int, ids: IntArray) {
* microphone's lease and writes the properties that were asked for. Worker thread, outside the monitor.
*/
internal fun GlassesSessionCore.g1Maintain() {
g1RecoverArms()
var status = false
var mic: Boolean? = null
var light = false
var imu = false
var sets: List<Pair<Int, ByteArray>> = emptyList()
val up = BooleanArray(2)
monitor.withLock {
if (!sessionReady) return
val now = now()
for (arm in 0..1) up[arm] = g1.armDownSinceMs[arm] == 0L
if (now - g1.lastPropsAtMs >= G1Timings.PROPS_MS) {
status = true
g1.lastPropsAtMs = now
}
if (audioCaptureActive) {
// What only the right arm has waits for it to come back, which starts all of it again.
if (!up[1]) {
// Nothing to do here.
} else if (audioCaptureActive) {
if (now - g1.lastMicRenewAtMs >= G1Timings.MIC_RENEW_MS) {
mic = true
g1.micOn = true
@@ -201,22 +235,21 @@ internal fun GlassesSessionCore.g1Maintain() {
// The sensor only reads while the panel is on; a dark panel keeps the last filtered value.
val interval = if (brightnessDemoPolling) G1Timings.LIGHT_DEMO_MS
else if (brightnessPolicy.automatic) G1Timings.LIGHT_AUTO_MS else G1Timings.LIGHT_MANUAL_MS
if (brightnessSentVisible == true && !chargingMode && !shutdownRequested && now - g1.lastLightAtMs >= interval) {
if (up[1] && brightnessSentVisible == true && !chargingMode && !shutdownRequested && now - g1.lastLightAtMs >= interval) {
light = true
g1.lastLightAtMs = now
}
if (g1.imuPeriodMs > 0 && now - g1.lastImuAtMs >= g1.imuPeriodMs) {
if (up[1] && g1.imuPeriodMs > 0 && now - g1.lastImuAtMs >= g1.imuPeriodMs) {
imu = true
g1.lastImuAtMs = now
}
if (g1.pendingPropSets.isNotEmpty()) {
sets = g1.pendingPropSets.toList()
sets = g1.pendingPropSets.filter { up[it.first] }
g1.pendingPropSets.clear()
}
}
if (status) {
g1RequestProps(0, G1_PROPS)
g1RequestProps(1, G1_PROPS)
for (arm in 0..1) if (up[arm]) g1RequestProps(arm, G1_PROPS)
}
mic?.let { on ->
val tag = monitor.withLock { g1.nextTag() }
@@ -312,7 +345,10 @@ internal fun GlassesSessionCore.g1EnqueueFrameLocked(
val left = scene.composed(packed, width, height, false)
val right = if (scene.hasStereoDepth) scene.composed(packed, width, height, true) else left
composed = arrayOf(left, right)
updates = List(2) { arm -> G1FramePlanner.plan(g1.arms[arm].frame, composed[arm], width, height) }
// An arm that's away gets all of this when it's back: its frame stays unknown until then.
updates = List(2) { arm ->
if (g1.armDownSinceMs[arm] != 0L) emptyList() else G1FramePlanner.plan(g1.arms[arm].frame, composed[arm], width, height)
}
} catch (e: Exception) {
// As in the G2's path: this frame would fail the same way after a reconnect (#42), so drop it.
lastEnqueuedFingerprint = fingerprint
@@ -323,10 +359,12 @@ internal fun GlassesSessionCore.g1EnqueueFrameLocked(
frameTimings.spanEnd(frameId, "compose-lenses")
val force = g1.presentPending
val queues = List(2) { arm ->
ArrayDeque(updates[arm]).also { if (it.isNotEmpty() || force) it.addLast(byteArrayOf(CFW_MSG_PRESENT.toByte())) }
ArrayDeque(updates[arm]).also {
if (g1.armDownSinceMs[arm] == 0L && (it.isNotEmpty() || force)) it.addLast(byteArrayOf(CFW_MSG_PRESENT.toByte()))
}
}
g1.presentPending = false
for (arm in 0..1) g1.arms[arm].frame = composed[arm]
for (arm in 0..1) if (g1.armDownSinceMs[arm] == 0L) g1.arms[arm].frame = composed[arm]
lastEnqueuedFingerprint = fingerprint
val messageCount = queues.sumOf { it.size }
if (messageCount == 0) {
@@ -361,6 +399,7 @@ internal fun GlassesSessionCore.g1EnqueueFrameLocked(
/** Message 30 for both arms, its visibility ordered with the frames around it. */
internal fun GlassesSessionCore.g1EnqueueBrightnessLocked(payload: ByteArray, label: String, visibleChanged: Boolean, onTimeout: MessageCallback) {
for (arm in 0..1) {
if (g1.armDownSinceMs[arm] != 0L) continue
val message = messageBuilder.customMessage("brightness-output", payload, label, -1, arm == 0)
message.cfwRequiredLenses = g1Lens(arm)
message.onTimeout = onTimeout
@@ -429,6 +468,42 @@ internal fun GlassesSessionCore.g1HideBeforeDisconnect() {
/** The arm has no g1v0 service: it runs Even's firmware. */
private class G1OtherFirmwareException : Exception("not g1v0 firmware")
/**
* A connection that failed in a way the wearer can be told: [reason] for the log and counters, [display] for the screen.
* [repairing]: a stale pairing was just removed, and the next attempt makes a new one.
*/
private class G1ConnectException(reason: String, val display: String, val repairing: Boolean = false) : Exception(reason)
/**
* Subscribes to the arm's events, which is also where its firmware shows. An arm keeps its address across an install, and the
* OS may remember the services it had before: read them again before believing the table either way.
*/
private fun GlassesSessionCore.g1SubscribeEvents(arm: Int) {
val address = g1ArmAddress(arm)
val timeoutMs = ConnectionOptions.SERVICES_TIMEOUT_MS
if (!link.hasCharacteristic(address, G1Ble.EVT_CHAR_UUID)) {
logLine("G1 " + g1Side(arm) + " arm: no event characteristic, reading its services again")
link.refreshServices(address, timeoutMs)
}
if (!link.hasCharacteristic(address, G1Ble.EVT_CHAR_UUID)) {
if (!link.isConnected(address)) throw G1ConnectException(g1Side(arm) + " arm dropped", "The " + g1Side(arm) + " arm dropped the connection.")
throw G1OtherFirmwareException()
}
fun subscribe(): Boolean = try {
link.enableNotifications(address, G1Ble.EVT_CHAR_UUID, true, ConnectionOptions.DESCRIPTOR_TIMEOUT_MS)
} catch (e: IllegalStateException) {
false
}
if (subscribe()) return
if (link.isConnected(address)) {
// A table that lists it and an arm that refuses: the table may be old in the other direction.
link.refreshServices(address, timeoutMs)
if (!link.hasCharacteristic(address, G1Ble.EVT_CHAR_UUID)) throw G1OtherFirmwareException()
if (subscribe()) return
}
throw G1ConnectException(g1Side(arm) + " arm dropped", "The " + g1Side(arm) + " arm dropped the connection.")
}
private fun GlassesSessionCore.g1ConnectArm(arm: Int, deadlineMs: Long) {
val address = g1ArmAddress(arm)
val timeoutMs = maxOf(deadlineMs - now(), ConnectionOptions.CONNECT_TIMEOUT_MS.toLong())
@@ -438,12 +513,9 @@ private fun GlassesSessionCore.g1ConnectArm(arm: Int, deadlineMs: Long) {
link.requestHighPriority(address)
link.requestMtu(address, G1Ble.REQUESTED_MTU, ConnectionOptions.CONNECT_TIMEOUT_MS)
if (!link.discoverServices(address, ConnectionOptions.SERVICES_TIMEOUT_MS)) {
throw IllegalStateException("discoverServices failed: $address")
}
if (!link.enableNotifications(address, G1Ble.EVT_CHAR_UUID, true, ConnectionOptions.DESCRIPTOR_TIMEOUT_MS)) {
if (!link.isConnected(address)) throw IllegalStateException("link lost: $address")
throw G1OtherFirmwareException()
throw G1ConnectException(g1Side(arm) + " arm dropped", "The " + g1Side(arm) + " arm dropped the connection.")
}
g1SubscribeEvents(arm)
link.requestLe2mPhy(address)
monitor.withLock {
if (arm == 0) leftConnected = true else rightConnected = true
@@ -455,10 +527,10 @@ private fun GlassesSessionCore.g1ConnectArm(arm: Int, deadlineMs: Long) {
* through whatever the OS does (Android's dialog, iOS's); out of the case the arm refuses a new bond and the write fails.
* Either way this is where the link is known to be encrypted, so the arm obeys everything that follows.
*/
private fun GlassesSessionCore.g1Pair(arm: Int) {
private fun GlassesSessionCore.g1Pair(arm: Int, writeTimeoutMs: Int = G1Timings.PAIRING_MS) {
val address = g1ArmAddress(arm)
if (!link.isBonded(address)) {
logLine("G1 " + (if (arm == 0) "left" else "right") + " arm: asking the OS to pair")
logLine("G1 " + g1Side(arm) + " arm: asking the OS to pair")
setStateDisplay("connecting", "Pairing with the glasses...")
link.requestBond(address)
val deadline = now() + G1Timings.PAIRING_MS
@@ -467,8 +539,167 @@ private fun GlassesSessionCore.g1Pair(arm: Int) {
if (!monitor.withLock { running && !userDisconnectRequested }) throw IllegalStateException("stopped while pairing")
}
}
if (!link.writeFrames(address, G1Ble.PAIR_CHAR_UUID, listOf(byteArrayOf(1)), GattWriteMode.WITH_RESPONSE, G1Timings.PAIRING_MS)) {
throw IllegalStateException("no encrypted link to the " + (if (arm == 0) "left" else "right") + " arm")
val encrypted = try {
link.writeFrames(address, G1Ble.PAIR_CHAR_UUID, listOf(byteArrayOf(1)), GattWriteMode.WITH_RESPONSE, writeTimeoutMs)
} catch (e: IllegalStateException) {
false
}
if (encrypted) return
if (!link.isConnected(address)) {
throw G1ConnectException(g1Side(arm) + " arm dropped", "The " + g1Side(arm) + " arm dropped the connection.")
}
// The link is up and the arm won't encrypt it. If the OS says this phone is bonded, the arm has lost its half: it has
// since paired on Even's firmware or with other hosts. Only an arm in the case can pair again, so that's the only time a
// bond is safe to give up. An unencrypted link gets an answer from nothing else, and this is the only way to ask.
if (link.isBonded(address) && g1InCaseWithoutEncryption(arm) && link.removeBond(address)) {
logLine("G1 " + g1Side(arm) + " arm: it lost this phone's pairing; removed it, pairing again")
throw G1ConnectException(g1Side(arm) + " arm pairing removed", "Pairing with the glasses again.", repairing = true)
}
throw G1ConnectException(g1Side(arm) + " arm stale pairing", "The glasses don't recognize this phone's pairing. Put them in their "
+ "charging case with the lid open to pair again; if that doesn't help, remove them from this phone's Bluetooth settings. "
+ G1_CASE_DELAY_HINT)
}
private fun GlassesSessionCore.g1InCaseWithoutEncryption(arm: Int): Boolean = try {
val hello = G1Protocol.parseHello(g1Control(arm, G1Protocol.OP_HELLO, tries = 1).body)
hello != null && hello.inCase && !hello.encrypted
} catch (e: G1ConnectException) {
false
}
/** What an arm needs to hear each time its link comes up. */
private fun GlassesSessionCore.g1StartArm(arm: Int) {
val events = g1Control(arm, G1Protocol.OP_EVENTS, G1Protocol.eventsRequest(G1Protocol.EVENTS_MASK))
if (events.status != 0) throw G1ConnectException(g1Side(arm) + " arm refused events", "The " + g1Side(arm) + " arm isn't answering.")
// The arm counts a boot healthy only after a host has said so (VM.md §6.4, safe mode).
g1Control(arm, G1Protocol.OP_HEALTH_OK)
// A limit the last session left, when the other eye's panel guard had capped it.
g1Control(arm, G1Protocol.OP_PROP_SET, G1Protocol.propSet(G1Protocol.PROP_BRIGHTNESS_MAX, G1Protocol.BRIGHTNESS_LEVEL_MAX))
}
// ---------------------------------------------------------------------------------------------
// One arm lost
/**
* The arms are independent links, and in crowded 2.4 GHz one often drops alone. Carry on with the other, and bring this one
* back by itself, instead of dropping both and showing the wearer a reconnect for a blip. Whatever was on its way to this
* arm is gone, and so is what the phone knew about its frame. False: the session can't go on without it. Under the monitor,
* on the BLE callback thread.
*/
internal fun GlassesSessionCore.g1CarryOnWithoutArmLocked(address: String): Boolean {
val arm = armIndex(address)
if (arm < 0 || !running || !sessionReady || userDisconnectRequested) return false
val otherUp = g1.armDownSinceMs[1 - arm] == 0L && (if (arm == 0) rightConnected else leftConnected)
if (!otherUp) return false
// The relay's client has to be told to start again, and only a new session tells it.
if (arm == 1 && g1.ancsRelay) return false
if (benchmarkActive) finishBenchmarkLocked(true, "an arm dropped")
g1.armDownSinceMs[arm] = now()
g1.armRetryAtMs[arm] = 0
g1DropArmMessagesLocked(arm)
logLine("G1 " + g1Side(arm) + " arm dropped: carrying on with the other while it comes back")
ConnectionCounters.increment("g1.arm-drop.carried-on")
return true
}
private fun GlassesSessionCore.g1DropArmMessagesLocked(arm: Int) {
val left = arm == 0
val reason = "the " + g1Side(arm) + " arm dropped"
val pending = pendingMessages.iterator()
while (pending.hasNext()) {
val message = pending.next()
if (message.sid != CfwTransport.SID || message.isLeftArmMessage != left) continue
pending.remove()
discardPrewriteIfMatchesLocked(message)
discardImageUpdateStatsLocked(message.imageUpdateId, reason)
magicPool.release(message.sid, message.magic, message.label, reason)
}
val inFlight = inFlightMessages.iterator()
while (inFlight.hasNext()) {
val message = inFlight.next()
if (message.sid != CfwTransport.SID || message.isLeftArmMessage != left) continue
inFlight.remove()
discardImageUpdateStatsLocked(message.imageUpdateId, reason)
magicPool.release(message.sid, message.magic, message.label, reason)
}
cfwTransports[arm].reset()
g1.arms[arm].frame = null
g1.presentPending = true
// What's displayed is no longer what the drive loop thinks; it gets another look.
lastEnqueuedFingerprint = ""
displayedFingerprint = ""
}
/** A message for an arm that's away would only fail the write or wait for an ACK that can't come. */
internal fun GlassesSessionCore.g1ArmIsAway(message: OutboundMessage): Boolean =
monitor.withLock { g1.armDownSinceMs[if (message.isLeftArmMessage) 0 else 1] != 0L }
/** Worker thread, outside the monitor. Blocks the other arm's traffic only for the setup, not while waiting for a link. */
private fun GlassesSessionCore.g1RecoverArms() {
for (arm in 0..1) {
val address = g1ArmAddress(arm)
var downSince = 0L
var retryAt = 0L
var limit = 0L
monitor.withLock {
downSince = if (sessionReady) g1.armDownSinceMs[arm] else 0L
retryAt = g1.armRetryAtMs[arm]
limit = g1.armRecoveryMs
}
if (downSince == 0L) continue
val now = now()
if (now - downSince >= limit) {
handleTransportFailure(g1Side(arm) + " arm lost", "Can't reach the " + g1Side(arm) + " arm of the glasses.")
return
}
if (!link.isConnected(address)) {
if (now >= retryAt) {
monitor.withLock { g1.armRetryAtMs[arm] = now + G1Timings.ARM_RETRY_MS }
link.beginConnect(address, false)
}
continue
}
try {
// A missing bond isn't a blip: that goes to the full connect, which knows what to say and can wait for the OS.
if (!link.isBonded(address)) throw G1ConnectException(g1Side(arm) + " arm not bonded", "The glasses aren't paired.")
g1ConnectArm(arm, now + ConnectionOptions.CONNECT_TIMEOUT_MS)
g1Pair(arm, G1Timings.ARM_RECOVERY_WRITE_MS)
val hello = G1Protocol.parseHello(g1Control(arm, G1Protocol.OP_HELLO).body)
?: throw G1ConnectException(g1Side(arm) + " arm bad hello", "The " + g1Side(arm) + " arm isn't answering.")
g1StartArm(arm)
monitor.withLock {
g1.arms[arm].hello = hello
logLine("G1 " + g1Side(arm) + " arm back after " + (now() - downSince) + " ms")
ConnectionCounters.increment("g1.arm-recovered")
g1.armDownSinceMs[arm] = 0
g1.armRetryAtMs[arm] = 0
cfwTransports[arm].reset()
g1.presentPending = true
// It's had no frames: all of it again, the brightness too. The drive loop sends the desired frame.
brightnessSentLevel = -1
brightnessSentVisible = null
displayedFingerprint = ""
lastEnqueuedFingerprint = ""
imageRetryAfterMs = 0
g1.lastPropsAtMs = 0
if (arm == 1) {
g1.lastLightAtMs = 0
g1.lastMicRenewAtMs = 0
g1.mic.reset()
g1.lastImuAtMs = 0
if (g1.imuPeriodMs > 0) g1.pendingPropSets.add(1 to G1Protocol.propSet(G1Protocol.PROP_IMU_RATE, G1Protocol.IMU_RATE_STREAM))
}
monitor.signalAll()
}
interruptibleSleep.interrupt()
} catch (t: Exception) {
logLine("G1 " + g1Side(arm) + " arm not back yet: " + (t.message ?: t.toString()))
monitor.withLock { g1.armRetryAtMs[arm] = now() + G1Timings.ARM_RETRY_MS }
try {
link.disconnect(address)
} catch (ignored: Exception) {
}
}
}
}
@@ -493,7 +724,8 @@ internal fun GlassesSessionCore.g1ConnectLoopOnce() {
var compatible = true
for (arm in 0..1) {
val reply = g1Control(arm, G1Protocol.OP_HELLO)
val hello = G1Protocol.parseHello(reply.body) ?: throw IllegalStateException("bad HELLO from arm $arm")
val hello = G1Protocol.parseHello(reply.body)
?: throw G1ConnectException(g1Side(arm) + " arm bad hello", "The " + g1Side(arm) + " arm isn't answering.")
monitor.withLock { g1.arms[arm].hello = hello }
versions[arm] = "g1v0 " + hello.version + (if (hello.safeMode) " (safe mode)" else "")
if (hello.leftArm != (arm == 0)) {
@@ -514,14 +746,7 @@ internal fun GlassesSessionCore.g1ConnectLoopOnce() {
monitor.withLock { incompatibleFirmware = firmware }
return
}
for (arm in 0..1) {
val events = g1Control(arm, G1Protocol.OP_EVENTS, G1Protocol.eventsRequest(G1Protocol.EVENTS_MASK))
if (events.status != 0) throw IllegalStateException("EVENTS refused: " + events.status)
// The arm counts a boot healthy only after a host has said so (VM.md §6.4, safe mode).
g1Control(arm, G1Protocol.OP_HEALTH_OK)
// A limit the last session left, when the other eye's panel guard had capped it.
g1Control(arm, G1Protocol.OP_PROP_SET, G1Protocol.propSet(G1Protocol.PROP_BRIGHTNESS_MAX, G1Protocol.BRIGHTNESS_LEVEL_MAX))
}
for (arm in 0..1) g1StartArm(arm)
g1ListenToAncsRelay()
monitor.withLock {
sessionReady = true
@@ -549,15 +774,16 @@ internal fun GlassesSessionCore.g1ConnectLoopOnce() {
emitFirmwareInfo(firmware)
monitor.withLock { incompatibleFirmware = firmware }
} catch (t: Throwable) {
logLine("G1 connect failed: " + safeMessage(t))
val unpaired = firstUnpairedArm()
// The ways this is expected to fail have a reason of their own; the stack is for what isn't expected.
logLine("G1 connect failed: " + (if (t is G1ConnectException) t.message else safeMessage(t)))
val unpaired = if (t is G1ConnectException && t.repairing) null else firstUnpairedArm()
if (unpaired != null) {
logError("G1 connect failed and $unpaired is not paired; suspending reconnect")
ConnectionCounters.increment("g1.unpaired")
monitor.withLock { haltReconnectLocked("arm not paired: $unpaired") }
if (!userDisconnectRequested) {
setStateDisplay("unpaired", "The glasses are not paired with this phone. Put them in their charging case"
+ " with the lid open, then connect: they only pair in the case.")
+ " with the lid open, then connect: they only pair in the case. " + G1_CASE_DELAY_HINT)
}
interruptibleSleep.interrupt()
} else if (t is ArmUnreachableException) {
@@ -568,8 +794,10 @@ internal fun GlassesSessionCore.g1ConnectLoopOnce() {
} else {
handleTransportFailure("glasses not found", "Can't find the glasses. They may be off or out of range.")
}
} else if (t is G1ConnectException) {
handleTransportFailure(t.message, t.display)
} else {
handleTransportFailure("connect failed")
handleTransportFailure("connect failed", "Couldn't connect to the glasses.")
}
}
}
@@ -581,7 +809,8 @@ internal fun GlassesSessionCore.g1ConnectLoopOnce() {
*/
private fun GlassesSessionCore.g1ListenToAncsRelay() {
val wanted = rawFrameTap != null && monitor.withLock { g1.arms[1].hello?.ancs == true }
val listening = wanted && link.enableNotifications(rightAddress, G1Ble.ANCS_CHAR_UUID, true, ConnectionOptions.DESCRIPTOR_TIMEOUT_MS)
val listening = wanted && link.hasCharacteristic(rightAddress, G1Ble.ANCS_CHAR_UUID)
&& link.enableNotifications(rightAddress, G1Ble.ANCS_CHAR_UUID, true, ConnectionOptions.DESCRIPTOR_TIMEOUT_MS)
if (wanted && !listening) logWarn("G1: the right arm has a notification relay, but subscribing to it failed")
monitor.withLock { g1.ancsRelay = listening }
}
@@ -398,6 +398,10 @@ internal fun GlassesSessionCore.writeMessage(message: OutboundMessage): Boolean
ioDropUnsupported(message)
return true
}
if (isG1 && g1ArmIsAway(message)) {
ioDropUnsupported(message)
return true
}
if (isIo && !ioSupportsMessage(message)) {
// G2-only traffic (EvenHub/settings frames, the G2 hardware CFW modes) that a feature
// queued anyway: the iO would NACK it into the replay limit, so it never goes out.
@@ -71,6 +71,15 @@ interface SessionLink {
/** Ask the OS to bond with a connected device, without waiting. A no-op where it pairs on demand only (CoreBluetooth). */
fun requestBond(address: String) {}
/** Remove this phone's half of a pairing; false where the platform can't or refused. */
fun removeBond(address: String): Boolean = false
/** After discovery: whether the service table has this characteristic. Enabling notifications on one it lacks may throw. */
fun hasCharacteristic(address: String, characteristicUuid: String): Boolean = true
/** Read the service table again, past whatever the OS cached for this address. */
fun refreshServices(address: String, timeoutMs: Int): Boolean = discoverServices(address, timeoutMs)
/** Bandwidth-benchmark link tuning; 0: current link, 1: HIGH priority, 2: 2M PHY, 3: both. */
fun prepareBenchmarkLink(address: String, mode: Int)
@@ -464,6 +464,17 @@ class IosBleCentral(private val platform: ProtocolPlatform = IosProtocolPlatform
/** CoreBluetooth pairs by itself when an attribute needs it. */
override fun requestBond(address: String) {}
/** Only iOS Settings can remove a pairing. */
override fun removeBond(address: String): Boolean = false
override fun hasCharacteristic(address: String, characteristicUuid: String): Boolean {
val peer = connectedPeer(address) ?: return false
return cond.withLock { peer.characteristics.containsKey(characteristicUuid.lowercase()) }
}
/** CoreBluetooth follows Service Changed itself; discovering again is all there is. */
override fun refreshServices(address: String, timeoutMs: Int): Boolean = discoverServices(address, timeoutMs)
override fun prepareBenchmarkLink(address: String, mode: Int) {}
override fun recordDisplayFrameSent() {
+6
View File
@@ -102,6 +102,12 @@ Use `--device` / `-d` or set `IOS_DEVICE` when more than one device is connected
Without either, the script selects the only device with an active Xcode tunnel.
For the simulator, add `--simulator` (defaults to `booted`; `--device` selects one).
`scripts/resetOnboardingIos.sh` is the iOS counterpart of `scripts/resetOnboarding.sh`.
It pulls the config, then pushes every `onboarding.*` key that is set back to its empty
value, which the app reads the same as a missing key. Pushes can't remove keys, and the
plist can't be edited directly (see below). Its `--all` uninstalls the app, since iOS has
no equivalent of `pm clear`.
Transfers use `devicectl` app-container access. The app consumes a uniquely
identified request at bootstrap, before loading settings getters and workers;
it applies imports through NSUserDefaults rather than overwriting a plist that
+81 -16
View File
@@ -18,6 +18,7 @@ BUNDLE = os.environ.get('IOS_BUNDLE_ID') or 'com.faceclaw.app'
REMOTE = 'Library/FaceclawConfigPort'
# The app reads requests of up to 8 MiB: a 2 MiB document embedded as an escaped JSON string.
REQUEST_LIMIT = 8 * 1024 * 1024
ONBOARDING_PREFIX = 'onboarding.'
def run(args, tolerate=False):
@@ -46,33 +47,34 @@ def atomic_write(path, data):
temporary.unlink(missing_ok=True)
def transfer(args):
# Parse and validate before touching the device or restarting its app.
document = read_document(args.file) if args.operation == 'push' else None
with tempfile.TemporaryDirectory(prefix='faceclaw-config-') as work:
work = Path(work)
def resolve_device(args, work):
device = args.device or os.environ.get('IOS_DEVICE')
if args.simulator:
device = device or 'booted'
container = Path(run(['simctl', 'get_app_container', device, BUNDLE, 'data']).stdout.strip())
else:
if not device:
return device or 'booted'
if device:
return device
listing = work / 'devices.json'
run(['devicectl', 'list', 'devices', '--json-output', str(listing)])
devices = json.loads(listing.read_text())['result']['devices']
available = [d for d in devices if d.get('connectionProperties', {}).get('tunnelState') == 'connected']
if len(available) != 1:
raise ValueError('Specify the iPhone with --device UDID (or IOS_DEVICE)')
device = available[0]['identifier']
return available[0]['identifier']
def exchange(args, work, device, operation, document=None):
"""Restart the app with one request for it to consume at launch; returns its successful reply."""
if args.simulator:
container = Path(run(['simctl', 'get_app_container', device, BUNDLE, 'data']).stdout.strip())
identifier = str(uuid.uuid4())
payload = {'id': identifier, 'operation': args.operation}
payload = {'id': identifier, 'operation': operation}
if document is not None:
payload['document'] = document
encoded = json.dumps(payload, ensure_ascii=False, allow_nan=False).encode()
if len(encoded) > REQUEST_LIMIT:
raise ValueError('Config request exceeds 8 MiB')
stage = work / 'FaceclawConfigPort'
stage.mkdir(mode=0o700)
stage.mkdir(mode=0o700, exist_ok=True)
atomic_write(stage / 'request.json', encoded)
if args.simulator:
remote = container / REMOTE
@@ -108,34 +110,97 @@ def transfer(args):
if message == 'Invalid config request':
message += ' (does the installed build predate JSON config documents?)'
raise RuntimeError(message)
if args.operation == 'pull':
return response
def pull_document(args, work, device):
response = exchange(args, work, device, 'pull')
if not isinstance(response.get('document'), str):
raise RuntimeError('The installed build predates JSON config documents; update it and retry.')
return response
def transfer(args):
# Parse and validate before touching the device or restarting its app.
document = read_document(args.file) if args.operation == 'push' else None
with tempfile.TemporaryDirectory(prefix='faceclaw-config-') as work:
work = Path(work)
device = resolve_device(args, work)
if args.operation == 'pull':
response = pull_document(args, work, device)
atomic_write(args.file, response['document'].encode())
print(f'Pulled {response.get("count", "?")} settings to {args.file} (mode 600). App restarted.')
else:
response = exchange(args, work, device, 'push', document)
skipped = response.get('skipped') or []
note = f' Left out {len(skipped)} {response.get("sourcePlatform") or "other-platform"}-only settings.' if skipped else ''
print(f'Pushed {response["count"]} settings; app restarted.{note} Unspecified settings preserved; '
f'previous preferences backed up in {REMOTE}/previous.plist.')
def onboarding_reset_document(pulled):
"""A document clearing the onboarding keys set in a pulled config, or None if none are.
Pushes merge, so a key can be overwritten but not removed. Every onboarding key reads the
value written here the same as a missing key: false for flags, "" for the finished version.
"""
cleared = {}
for key, value in json.loads(pulled).get('platformSettings', {}).items():
if not key.startswith(ONBOARDING_PREFIX):
continue
blank = False if isinstance(value, bool) else 0 if isinstance(value, (int, float)) else ''
if value != blank:
cleared[key] = blank
if not cleared:
return None
return json.dumps({'schema': 2, 'platform': 'ios', 'settings': {}, 'platformSettings': cleared})
def reset_onboarding(args):
with tempfile.TemporaryDirectory(prefix='faceclaw-config-') as work:
work = Path(work)
device = resolve_device(args, work)
if args.all:
print(f'Uninstalling {BUNDLE}, which removes ALL of its data...')
if args.simulator:
run(['simctl', 'uninstall', device, BUNDLE])
else:
run(['devicectl', 'device', 'uninstall', 'app', '--device', device, BUNDLE])
print('Done. Reinstall (npm run run:ios) to start from a clean onboarding.')
return
print(f'Clearing onboarding preference keys ({ONBOARDING_PREFIX}*) for {BUNDLE}...')
document = onboarding_reset_document(pull_document(args, work, device)['document'])
if document is None:
print('No onboarding keys were set. App is already in pre-onboarding state.')
return
keys = json.loads(document)['platformSettings']
exchange(args, work, device, 'push', document)
for key in keys:
print(f' cleared {key}')
print(f'Done. Faceclaw has restarted into onboarding; previous preferences backed up in {REMOTE}/previous.plist.')
def main():
os.umask(0o077)
parser = argparse.ArgumentParser(description='Pull/push iOS Faceclaw config; restarts the app. Requires Xcode and an unlocked development device. Push merges supplied keys; accepts Faceclaw JSON from either platform, or legacy Android XML.')
parser.add_argument('operation', choices=['pull', 'push'])
parser = argparse.ArgumentParser(description='Pull/push iOS Faceclaw config, or reset its onboarding state; restarts the app. Requires Xcode and an unlocked development device. Push merges supplied keys; accepts Faceclaw JSON from either platform, or legacy Android XML.')
parser.add_argument('operation', choices=['pull', 'push', 'reset-onboarding'])
parser.add_argument('path', nargs='?')
parser.add_argument('-f', '--file')
parser.add_argument('-d', '--device', help='iPhone UDID/name, or simulator ID with --simulator; defaults to IOS_DEVICE or the only connected device')
parser.add_argument('--simulator', action='store_true', help='Use simctl (default device: booted)')
parser.add_argument('--all', action='store_true', help='With reset-onboarding: uninstall the app, wiping ALL of its data')
args = parser.parse_args()
if args.operation == 'reset-onboarding' and (args.path or args.file):
parser.error('reset-onboarding does not take a file')
if args.all and args.operation != 'reset-onboarding':
parser.error('--all only applies to reset-onboarding')
if args.path and args.file:
parser.error('Specify one file, either positional or with -f')
args.file = args.file or args.path or 'faceclaw_settings.ios.json'
if args.operation == 'pull' and Path(args.file).suffix.lower() == '.xml':
parser.error('Configs are pulled as JSON; choose a .json filename')
try:
transfer(args)
(reset_onboarding if args.operation == 'reset-onboarding' else transfer)(args)
except (OSError, ValueError, RuntimeError, ET.ParseError) as error:
print(f'Error: {error}', file=sys.stderr)
return 1
+19 -7
View File
@@ -15,20 +15,21 @@
# scripts/resetOnboarding.sh --all # full `pm clear` (wipes everything)
# scripts/resetOnboarding.sh -s <device-id> # target a specific adb device
#
# The device id defaults to $FACECLAW_DEVICE_ID, then to the id used by
# build_and_run.sh. adb is located the same way build.sh finds its tools.
# The device id defaults to DEVICE_ID from build_paths.sh, the same device
# build_and_run.sh targets. adb must be on PATH, or added to it in build_paths.sh.
# Sourced ahead of strict mode, since the build scripts source it without one.
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
if [ -f "$ROOT/build_paths.sh" ]; then
source "$ROOT/build_paths.sh"
fi
set -euo pipefail
PACKAGE="com.faceclaw.app"
PREF_KEY_PREFIX="onboarding."
DEVICE_ID="${FACECLAW_DEVICE_ID:-3A101JEHN12330}"
WIPE_ALL=0
# Match build.sh's tool locations so adb is on PATH even from a bare shell.
export ANDROID_HOME="${ANDROID_HOME:-/Users/jbabcock/Library/Android/sdk}"
export PATH="$ANDROID_HOME/platform-tools:$PATH"
while [ $# -gt 0 ]; do
case "$1" in
--all) WIPE_ALL=1; shift ;;
@@ -44,8 +45,19 @@ done
command -v adb >/dev/null 2>&1 || { echo "error: adb not found on PATH" >&2; exit 1; }
if [ -z "${DEVICE_ID:-}" ]; then
echo "error: no adb device; set DEVICE_ID in build_paths.sh or pass -s <device-id>." >&2
exit 2
fi
ADB="adb -s $DEVICE_ID"
# Network devices (host:port) need an explicit connect first. A failure here is
# reported by the connected-device check below.
case "$DEVICE_ID" in
*:*) adb connect "$DEVICE_ID" >/dev/null 2>&1 || true ;;
esac
# Confirm the device is actually there before doing anything.
if ! $ADB get-state >/dev/null 2>&1; then
echo "error: adb device '$DEVICE_ID' not connected." >&2
+35
View File
@@ -0,0 +1,35 @@
#!/usr/bin/env bash
#
# resetOnboardingIos.sh — reset Faceclaw on an iPhone back to its pre-onboarding
# state, for testing the onboarding flow repeatedly. The iOS counterpart of
# resetOnboarding.sh.
#
# By default this only clears the onboarding-related preference keys
# (onboarding.complete, onboarding.previewOnly, the on-glasses onboarding's
# onboarding.glassesFinishedVersion, ...) and leaves everything else, notably
# the saved glasses/ring identities, intact. It restarts Faceclaw twice, and
# leaves it running in onboarding. Pass --all to uninstall the app instead,
# which wipes ALL of its data and permissions; you then have to reinstall it.
#
# Usage:
# scripts/resetOnboardingIos.sh # reset onboarding flags only
# scripts/resetOnboardingIos.sh --all # uninstall (wipes everything)
# scripts/resetOnboardingIos.sh -d <device-id> # target a specific iPhone
# scripts/resetOnboardingIos.sh --simulator # target the booted simulator
#
# The device defaults to IOS_DEVICE from build_paths.sh, then to the only iPhone
# connected. Needs Xcode and an unlocked phone with a development build installed;
# see config-transfer.md.
# Sourced ahead of strict mode, since the build scripts source it without one.
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
if [ -f "$ROOT/build_paths.sh" ]; then
source "$ROOT/build_paths.sh"
fi
set -euo pipefail
# ios_config.py reads these from its environment.
export IOS_DEVICE IOS_BUNDLE_ID
exec python3 "$ROOT/scripts/ios_config.py" reset-onboarding "$@"
+7
View File
@@ -41,6 +41,13 @@ with tempfile.TemporaryDirectory() as d:
try: m.read_document(p)
except (ValueError, m.ET.ParseError): pass
else: raise AssertionError(f'accepted invalid config {invalid!r}')
pulled = {'schema': 2, 'platform': 'ios', 'settings': {'onboarding.lookalike': True, 'display.timeFormat': '24h'}, 'platformSettings': {
'onboarding.complete': True, 'onboarding.previewOnly': False, 'onboarding.glassesFinishedVersion': '0.8.6', 'onboarding.step': 3, 'deviceAddress.left': 'AA'}}
reset = json.loads(ios.onboarding_reset_document(json.dumps(pulled)))
assert reset == {'schema': 2, 'platform': 'ios', 'settings': {}, 'platformSettings': {
'onboarding.complete': False, 'onboarding.glassesFinishedVersion': '', 'onboarding.step': 0}}, reset
assert m.check_document(json.dumps(reset)) == (2, 'ios', 3)
assert ios.onboarding_reset_document(json.dumps({**pulled, 'platformSettings': {'onboarding.complete': False, 'onboarding.glassesFinishedVersion': '', 'deviceAddress.left': 'AA'}})) is None
`], { stdio: 'inherit' });
});
+56 -1
View File
@@ -215,8 +215,63 @@ test("a G1 arm on g1v0: the name says all, the serial is in the 0xFFFF record",
assert.equal(classifyAdvertisement(g1Raw("G1v0S_L", "")).serial, null);
});
const g1Record = (flags, version, serial = "S110LABC030139") => "ffff" + "02" + flags + version + g1Ascii(serial);
test("a G1 arm on g1v0 0.5.66+: its name tells pairs apart, its record says what it runs", () => {
const ad = classifyAdvertisement(g1Raw("G1CFW_L_EF50E5", g1Record("05", "000542")));
assert.equal(ad.role, "left");
assert.equal(ad.g1Firmware, "g1v0");
assert.equal(ad.g1Version, "0.5.66");
assert.equal(ad.serial, "S110LABC030139");
assert.equal(classifyAdvertisement(g1Raw("G1CFW_R_CBE689", g1Record("04", "000542"))).role, "right");
});
test("a G1 arm in safe mode says so in its record, not its name", () => {
const ad = classifyAdvertisement(g1Raw("G1CFW_L_EF50E5", g1Record("0d", "000542")));
assert.equal(ad.g1Firmware, "g1v0-safe");
assert.equal(ad.g1Version, "0.5.66");
});
test("a G1 arm whose record hasn't arrived yet still shows, without a version or serial", () => {
const ad = classifyAdvertisement(g1Raw("G1CFW_L_EF50E5", ""));
assert.equal(ad.g1Firmware, "g1v0");
assert.equal(ad.g1Version, undefined);
assert.equal(ad.serial, null);
});
test("g1v0 before 0.5.66 and Even's firmware advertise no version", () => {
assert.equal(classifyAdvertisement(g1Raw("G1v0_R", "ffff" + "01" + "04" + g1Ascii("S110LABC030139"))).g1Version, undefined);
assert.equal(classifyAdvertisement(g1Raw("Even G1_70_L_EF50E5", "02" + g1Ascii("S110LABC030139"))).g1Version, undefined);
});
test("a G1 pair joins on its serial across firmware, so an install in progress stays one pair", () => {
const stock = classifyAdvertisement(g1Raw("Even G1_70_L_EF50E5", "02" + g1Ascii("S110LABC030139") + "0000000000"));
const custom = classifyAdvertisement(g1Raw("G1CFW_R_CBE689", g1Record("04", "000542")));
assert.equal(stock.serial, custom.serial);
});
test("on iOS a G1 arm gets an address from its peripheral identifier, and is found at all", () => {
const { identifyIosPeripheral, g1IosAddress } = require("../.test-build/app/g2/ios-peripheral-identity.js");
const identifier = "14b99254-0798-d1a8-3eec-b141bdabfae8";
assert.equal(g1IosAddress(identifier), "14:B9:92:54:07:98");
for (const [name, manufacturerData, firmware] of [
["G1CFW_L_EF50E5", g1Record("05", "000542"), "g1v0"],
["Even G1_70_L_EF50E5", "02" + g1Ascii("S110LABC030139"), "stock"],
["G1v0_L", "ffff" + "01" + "05" + g1Ascii("S110LABC030139"), "g1v0"],
]) {
const device = identifyIosPeripheral({ identifier, name, manufacturerData, rssi: -50, connectable: true });
assert.ok(device, name);
assert.equal(device.address, "14:B9:92:54:07:98", name);
assert.equal(device.identifier, identifier.toUpperCase(), name);
assert.equal(device.role, "left", name);
assert.equal(device.g1Firmware, firmware, name);
assert.equal(device.serial, "S110LABC030139", name);
}
assert.equal(identifyIosPeripheral({ identifier: "not-a-uuid", name: "G1CFW_L_EF50E5", manufacturerData: "", rssi: 0, connectable: true }), null);
});
test("names that only look like a G1 are not admitted", () => {
for (const name of ["G1v0_X", "G1v0", "G1 Tracker", "Even G1", "Pixel G1v0_L"]) {
for (const name of ["G1v0_X", "G1v0", "G1 Tracker", "Even G1", "Pixel G1v0_L", "G1CFW_L", "G1CFW_X_EF50E5", "G1CFW_L_EF50E", "Pixel G1CFW_L_EF50E5"]) {
assert.equal(classifyAdvertisement(g1Raw(name, "")), null, name);
}
});
+18
View File
@@ -153,6 +153,24 @@ test('the state of the two arms is that of the arm that needs the most', () => {
assert.equal(state({ firmware: 'stock' }, on('0.5.63', { safeMode: true })), 'stock');
});
test('what the advertising alone says about the arms', () => {
const arm = (g1Firmware, g1Version) => ({ g1Firmware, g1Version });
const state = (left, right) => plan.g1StateFromAdvertising({ left, right }, '0.5.66');
assert.deepEqual(state(arm('g1v0', '0.5.66'), arm('g1v0', '0.5.66')), { state: 'current', version: '0.5.66' });
assert.deepEqual(state(arm('g1v0', '0.5.67'), arm('g1v0', '0.5.66')), { state: 'current', version: '0.5.66' });
assert.deepEqual(state(arm('g1v0', '0.5.66'), arm('g1v0', '0.5.100')), { state: 'current', version: '0.5.66' });
assert.deepEqual(state(arm('stock'), arm('g1v0', '0.5.66')), { state: 'stock', version: '' });
assert.deepEqual(state(arm('g1v0-safe', '0.5.66'), arm('g1v0', '0.5.66')), { state: 'safe-mode', version: '' });
// Firmware before 0.5.66, or a record that hasn't arrived: an arm has to be asked.
assert.equal(state(arm('g1v0'), arm('g1v0', '0.5.66')), null);
assert.equal(state(arm('g1v0'), arm('g1v0')), null);
});
test('an older arm wins over a newer one', () => {
const arm = (g1Version) => ({ g1Firmware: 'g1v0', g1Version });
assert.deepEqual(plan.g1StateFromAdvertising({ left: arm('0.5.67'), right: arm('0.5.65') }, '0.5.66'), { state: 'older', version: '0.5.65' });
});
test('the native flow\'s answer is read, and nonsense is no answer', () => {
assert.deepEqual(plan.parseG1FlashResult('{"flashed":true,"version":"0.5.64"}'), { flashed: true, version: '0.5.64' });
assert.deepEqual(plan.parseG1FlashResult('nonsense'), {});
+15 -2
View File
@@ -21,6 +21,8 @@ const planes = load('app/graphics/plane.ts', { './image': images });
const timings = load('app/native/frame-timings.ts', {});
const LAUNCHER_GRAY = 75;
let glassesType = 'g2';
function fixture() {
const relay = { available: true, starts: 0, client: null, message: undefined };
const observers = new Map(), phoneState = { protectedDataAvailable: true };
@@ -105,7 +107,7 @@ function fixture() {
const noop = () => () => {};
class FaceclawCommunicatorBridge extends Display {
phase = 'disconnected'; listeners = {};
constructor() { super(); bridge = this; }
constructor(addresses) { super(); bridge = this; this.addresses = addresses; }
on(kind, fn) { this.listeners[kind] = fn; return () => { if (this.listeners[kind] === fn) delete this.listeners[kind]; }; }
onStateChange(fn) { return this.on('state', fn); } onRingEvent(fn) { return this.on('ring', fn); }
onWearState(fn) { return this.on('wear', fn); } onBatteryState(fn) { return this.on('battery', fn); } onCaseState(fn) { return this.on('case', fn); } onFirmwareInfo(fn) { return this.on('firmware', fn); }
@@ -176,7 +178,7 @@ function fixture() {
'../apps/all-apps': { ALL_APPS: [{ appId: 'glanceboard', glanceboard: provider }] },
'../apps/onboarding/onboarding-progress': { claimGlassesOnboardingAutoLaunch: () => false },
'../ui/shell/worker-window': {}, '../ui/shell/in-process-window': {},
'../ui/dashboard-settings': { brightnessSetting: { get: () => 'auto' }, brightnessSettingToLevel: () => null, getBrightnessPreferences: () => ({ auto: true, level: 50, minimum: 2, maximum: 100, curve: '0:0,1000:100', fadeMs: 280 }), lockScreenEnabledSetting: { get: () => settings.lock }, ringConnectionModeSetting: { get: () => 'glasses' }, onAnySettingChanged: fn => { settingsChanged = fn; return () => {}; }, previewColorSetting: { get: () => 'white' } },
'../ui/dashboard-settings': { glassesTypeSetting: { get: () => glassesType }, brightnessSetting: { get: () => 'auto' }, brightnessSettingToLevel: () => null, getBrightnessPreferences: () => ({ auto: true, level: 50, minimum: 2, maximum: 100, curve: '0:0,1000:100', fadeMs: 280 }), lockScreenEnabledSetting: { get: () => settings.lock }, ringConnectionModeSetting: { get: () => 'glasses' }, onAnySettingChanged: fn => { settingsChanged = fn; return () => {}; }, previewColorSetting: { get: () => 'white' } },
'../native/phone-battery': { readPhoneBatteryState: () => ({ battery: 80, charging: false }) },
'../apps/ios-availability': { iosAppUnavailableReason: () => null },
'../graphics/glyph-wire': { prepareFrameDraws: () => null },
@@ -222,6 +224,17 @@ function fixture() {
get shellOptions() { return shellOptions; }, registered, inProcessApps,
get bridge() { return bridge; }, connect, wear: wearing => bridge.emitWear(wearing), settingsChanged: () => settingsChanged(), sent, previews, received, boardStats, hardware, phone, advance, render };
}
test('the session is told which glasses it drives, as a G2 session gets nowhere on a G1', async () => {
for (const type of ['g1', 'g2']) {
glassesType = type;
const f = fixture();
await f.connect();
assert.equal(f.bridge.addresses.glassesType, type);
assert.ok('right' in f.bridge.addresses && 'left' in f.bridge.addresses, 'the arms still come with it');
}
glassesType = 'g2';
});
test('a link that comes back asks for the notification relay again; a G1 without one is told to update', async () => {
const f = fixture();
await f.connect();
+10
View File
@@ -57,6 +57,16 @@ function alsRecord(alsValue) {
return body;
}
test('only a G1 session runs the G1 connect path', () => {
for (const [glassesType, expected] of [['g1', 1], ['g2', 0], [undefined, 0]]) {
const { session, FaceclawCommunicatorBridge } = harness();
let used = 0;
session.useG1 = () => { used++; };
new FaceclawCommunicatorBridge({ right: 'r', left: 'l', glassesType });
assert.equal(used, expected, String(glassesType));
}
});
test('the bridge is the active session from start() until close()', async () => {
const h = harness();
const bridge = new h.FaceclawCommunicatorBridge({ right: 'r', left: 'l' });
@@ -72,6 +72,15 @@ private class FakeArm(private val image: ByteArray, var stock: Boolean = false)
var silentAtOffset = -1
var onChunk: (() -> Unit)? = null
var connects = 0
/** The OS remembers a table without g1v0's services, as after an install at the same address. */
var staleTable = false
var refreshes = 0
/** Android says bonded and the arm has lost its half. */
var staleBond = false
var removedBonds = 0
var inCase = false
/** Even's firmware's answer to its battery query; null: it says nothing. */
var stockBatteryReply: ByteArray? = null
val wantHash = G1Smp.imageHash(image)
@@ -83,13 +92,31 @@ private class FakeArm(private val image: ByteArray, var stock: Boolean = false)
}
override fun prepareLink(address: String, desiredMtu: Int, timeoutMs: Int) {}
override fun discoverServices(address: String, timeoutMs: Int): Boolean = connected
/** As FaceclawBleManager: a characteristic the table lacks throws, a refused one (no encryption) returns false. */
override fun enableNotifications(address: String, characteristicUuid: String, timeoutMs: Int): Boolean {
if (!connected) return false
if (stock && characteristicUuid == G1Ble.EVT_CHAR_UUID) return false
if (!stock && characteristicUuid == G1Smp.NUS_TX_UUID) return false
if (!connected) throw IllegalStateException("Not connected")
if (!hasCharacteristic(address, characteristicUuid)) throw IllegalStateException("Characteristic not found: $characteristicUuid")
if (stock && staleBond && characteristicUuid == G1Smp.NUS_TX_UUID) return false
subscribed.add(characteristicUuid)
return true
}
override fun hasCharacteristic(address: String, characteristicUuid: String): Boolean = when (characteristicUuid) {
G1Ble.EVT_CHAR_UUID -> !stock && !staleTable
G1Smp.NUS_TX_UUID -> stock
else -> true
}
override fun refreshServices(address: String, timeoutMs: Int): Boolean {
refreshes++
staleTable = false
return connected
}
override fun removeBond(address: String): Boolean {
removedBonds++
bond = BondState.NONE
staleBond = false
connected = false
return true
}
override fun isConnected(address: String): Boolean = connected
override fun bondState(address: String): BondState = bond
override fun requestBond(address: String) {
@@ -108,8 +135,15 @@ private class FakeArm(private val image: ByteArray, var stock: Boolean = false)
override fun writeFrames(address: String, characteristicUuid: String, frames: List<ByteArray>, mode: GattWriteMode, timeoutMs: Int): Boolean {
if (!connected) throw IllegalStateException("Not connected")
when (characteristicUuid) {
G1Smp.NUS_RX_UUID -> heartbeats.add(frames.single())
G1Ble.PAIR_CHAR_UUID -> return bond == BondState.BONDED
G1Smp.NUS_RX_UUID -> {
val frame = frames.single()
if (frame[0].toInt() == 0x2c) {
stockBatteryReply?.let { inbound?.onNotification(ARM, G1Smp.NUS_TX_UUID, it) }
} else {
heartbeats.add(frame)
}
}
G1Ble.PAIR_CHAR_UUID -> return bond == BondState.BONDED && !staleBond
G1Ble.CTRL_CHAR_UUID -> control(frames.single())
G1Smp.SMP_CHAR_UUID -> {
for (frame in frames) assertTrue(frame.size <= 97, "a write longer than the MTU allows")
@@ -126,7 +160,7 @@ private class FakeArm(private val image: ByteArray, var stock: Boolean = false)
val body = when (op) {
G1Protocol.OP_HELLO -> {
val parts = runningVersion.split(".").map { it.toInt().toByte() }
val flags = (if (safeMode) 1 else 0) or 2 or 64
val flags = (if (safeMode) 1 else 0) or 2 or (if (staleBond) 0 else 64) or (if (inCase) 128 else 0)
byteArrayOf(5, parts[0], parts[1], parts[2], 1, flags.toByte(), 0)
}
G1Protocol.OP_PROPS -> byteArrayOf(battery.toByte(), 0, 0, 0)
@@ -230,6 +264,19 @@ private val FAST = G1FlashTimings(
controlReplyMs = 20, controlTries = 2, uploadReplyMs = 150, smpReplyMs = 150, resetReplyMs = 50, heartbeatMs = 30, pollMs = 5, uploadRetries = 5,
)
class G1SmpStockTest {
@Test
fun stocksBatteryReplyIsReadOnlyWhenItIsOne() {
// What the real firmware answered in emulation (g1-fw BLE_COMMAND_SET_REPORT), first bytes.
assertEquals(100, G1Smp.parseStockBattery(byteArrayOf(0x2c, 0x66, 0x64, 0x64, 0xf9.toByte(), 0x80.toByte())))
assertEquals(null, G1Smp.parseStockBattery(byteArrayOf(0x2c, 0x66, 0)))
assertEquals(null, G1Smp.parseStockBattery(byteArrayOf(0x2c, 0x66, 101)))
assertEquals(null, G1Smp.parseStockBattery(byteArrayOf(0x2c, 0xc9.toByte(), 50)))
assertEquals(null, G1Smp.parseStockBattery(byteArrayOf(0x25, 0x66, 50)))
assertEquals(null, G1Smp.parseStockBattery(byteArrayOf(0x2c, 0x66)))
}
}
class G1SmpTest {
private val sha = ByteArray(32) { it.toByte() }
@@ -519,6 +566,75 @@ class G1ArmFlashFlowTest {
assertTrue("an arm pairs only in its case" in listener.detail, listener.detail)
}
@Test
fun aStaleBondInTheCaseIsRemovedAndMadeAgain() {
val arm = FakeArm(image)
arm.staleBond = true
arm.inCase = true
val result = run(arm, G1ArmFlashFlow.Mode.UPDATE)
assertEquals(true, result.success, result.detail)
assertEquals(1, arm.removedBonds)
assertEquals(1, arm.bondRequests)
confirmIsLast(arm)
}
@Test
fun aBondIsNeverGivenUpOutOfTheCase() {
val arm = FakeArm(image)
arm.staleBond = true
arm.inCase = false
val result = run(arm, G1ArmFlashFlow.Mode.UPDATE, window = 1)
assertEquals(false, result.success)
assertEquals(0, arm.removedBonds, "no new bond can be made out of the case")
}
@Test
fun aStaleBondOnStockIsRemovedAndMadeAgain() {
val arm = FakeArm(image, stock = true)
arm.staleBond = true
val result = run(arm, G1ArmFlashFlow.Mode.STOCK)
assertEquals(true, result.success, result.detail)
assertEquals(1, arm.removedBonds)
assertEquals(1, arm.bondRequests)
}
@Test
fun anOldServiceTableIsReadAgainBeforeItIsBelieved() {
val arm = FakeArm(image)
arm.staleTable = true
val result = run(arm, G1ArmFlashFlow.Mode.PROBE)
assertEquals(true, result.success, result.detail)
assertEquals(1, arm.refreshes)
assertTrue("\"firmware\":\"g1v0\"" in result.detail, result.detail)
}
@Test
fun aLowBatteryOnStockStopsBeforeAnyUpload() {
val arm = FakeArm(image, stock = true)
arm.stockBatteryReply = byteArrayOf(0x2c, 0x66, 12, 12)
val result = run(arm, G1ArmFlashFlow.Mode.STOCK)
assertEquals(false, result.success)
assertTrue("12%" in result.detail, result.detail)
assertFalse("upload" in arm.calls)
}
@Test
fun aChargedArmOnStockGoesOn() {
val arm = FakeArm(image, stock = true)
arm.stockBatteryReply = byteArrayOf(0x2c, 0x66, 100, 100)
val result = run(arm, G1ArmFlashFlow.Mode.STOCK)
assertEquals(true, result.success, result.detail)
assertTrue(result.logs.any { "battery 100%" in it }, result.logs.toString())
}
@Test
fun aStockArmThatSaysNothingAboutItsBatteryGoesOn() {
val arm = FakeArm(image, stock = true)
val result = run(arm, G1ArmFlashFlow.Mode.STOCK)
assertEquals(true, result.success, result.detail)
assertTrue(result.logs.any { "battery unknown" in it }, result.logs.toString())
}
@Test
fun aProbeSaysWhatAnArmRuns() {
val arm = FakeArm(image)
@@ -139,6 +139,19 @@ private class FakeG1Glasses(platform: ProtocolPlatform) : SessionLink {
val ancsWrites = ArrayList<Pair<String, ByteArray>>()
/** Out of the case, or the OS said no: no bond can be made. */
@Volatile var pairingRefused = false
/** Both arms run Even's firmware: no g1v0 service. */
@Volatile var stockFirmware = false
/** The OS remembers a table without g1v0's services, as after an install at the same address. */
@Volatile var staleTable = false
@Volatile var refreshes = 0
@Volatile var removedBonds = 0
/** The OS says bonded and the arm has lost its half: PAIR fails with the link up. */
@Volatile var staleBond = false
@Volatile var helloInCase = false
/** An arm that won't connect, whatever it's asked. */
val away = HashSet<String>()
/** Links up. Everything stays up unless a test takes it down. */
private val up = hashSetOf(LEFT, RIGHT)
private val out = ArrayList<Pair<String, ByteArray>>()
private fun arm(address: String) = if (address == LEFT) leftArm else rightArm
@@ -169,9 +182,53 @@ private class FakeG1Glasses(platform: ProtocolPlatform) : SessionLink {
event(address, G1Protocol.EV_INPUT, body)
}
override fun connect(address: String, timeoutMs: Int): Boolean = true
/** The link drops, as the BLE callback thread reports it. */
fun drop(address: String) {
lock.withLock { up.remove(address) }
core.onConnectionStateChange(address, false)
}
override fun isConnected(address: String): Boolean = true
/** The arm comes back in range: the next connection attempt gets it. */
fun comeBack(address: String) {
lock.withLock { away.remove(address) }
}
override fun connect(address: String, timeoutMs: Int): Boolean = lock.withLock {
if (address in away) return@withLock false
up.add(address)
true
}
override fun beginConnect(address: String, background: Boolean): Boolean {
val connected = connect(address, 0)
if (connected) core.onConnectionStateChange(address, true)
return connected
}
override fun isConnected(address: String): Boolean = lock.withLock { address in up }
override fun hasCharacteristic(address: String, characteristicUuid: String): Boolean = when (characteristicUuid) {
G1Ble.EVT_CHAR_UUID -> !stockFirmware && !staleTable
G1Ble.ANCS_CHAR_UUID -> !ancsCharacteristicMissing
else -> true
}
override fun refreshServices(address: String, timeoutMs: Int): Boolean {
refreshes++
staleTable = false
return true
}
override fun removeBond(address: String): Boolean {
removedBonds++
lock.withLock {
arm(address).bonded = false
up.remove(address)
}
staleBond = false
core.onConnectionStateChange(address, false)
return true
}
override fun requestHighPriority(address: String) {}
@@ -181,24 +238,25 @@ private class FakeG1Glasses(platform: ProtocolPlatform) : SessionLink {
override fun discoverServices(address: String, timeoutMs: Int): Boolean = true
/** As FaceclawBleManager: a characteristic the table lacks throws, it doesn't return false. */
override fun enableNotifications(address: String, characteristicUuid: String, enable: Boolean, timeoutMs: Int): Boolean {
if (characteristicUuid == G1Ble.ANCS_CHAR_UUID && !ancsCharacteristicMissing) {
lock.withLock { ancsSubscribed.add(address) }
if (!isConnected(address)) throw IllegalStateException("Not connected: $address")
if (!hasCharacteristic(address, characteristicUuid)) throw IllegalStateException("Characteristic not found: $characteristicUuid")
if (characteristicUuid == G1Ble.ANCS_CHAR_UUID) lock.withLock { ancsSubscribed.add(address) }
return true
}
return characteristicUuid == G1Ble.EVT_CHAR_UUID
}
override fun requestBond(address: String) {
if (!pairingRefused) lock.withLock { arm(address).bonded = true }
}
override fun writeFrames(address: String, characteristicUuid: String, frames: List<ByteArray>, mode: GattWriteMode, timeoutMs: Int): Boolean {
if (!isConnected(address)) throw IllegalStateException("Not connected: $address")
val a = arm(address)
when (characteristicUuid) {
G1Ble.PAIR_CHAR_UUID -> {
assertEquals(GattWriteMode.WITH_RESPONSE, mode, "only a write with response can make the OS pair")
if (pairingRefused) return false
if (pairingRefused || staleBond) return false
lock.withLock {
a.pairedWrites++
a.bonded = true
@@ -233,7 +291,7 @@ private class FakeG1Glasses(platform: ProtocolPlatform) : SessionLink {
body[2] = 5
body[3] = 63
body[4] = (if (a.left) 1 else 0).toByte()
body[5] = (2 or 64).toByte()
body[5] = (2 or (if (staleBond) 0 else 64) or (if (helloInCase) 128 else 0)).toByte()
body[6] = ((if (a.left) 0 else 4) or (if (hasAncsRelay) 8 else 0)).toByte()
reply(address, op, tag, 0, body)
}
@@ -473,6 +531,199 @@ private class G1Session {
}
}
class G1LinkTest {
private fun started(s: G1Session, seed: Int = 1) {
s.core.monitor.withLock { s.core.g1.armRecoveryMs = 2_000 }
assertTrue(s.core.start())
assertTrue(awaitTrue(5_000) { s.ready() }, "never ready:\n" + s.tail())
s.submit(seed, seed)
assertTrue(awaitTrue(5_000) { s.displayedMatchesDesired() }, "frame never displayed:\n" + s.tail())
}
@Test
fun evensFirmwareSaysWhyInsteadOfRetrying() {
val s = G1Session()
try {
s.glasses.stockFirmware = true
assertTrue(s.core.start())
assertTrue(awaitTrue(5_000) { s.listener.firmware.isNotEmpty() }, "no firmware report:\n" + s.tail())
assertEquals("Even's firmware|Even's firmware|", s.listener.firmware.single())
assertTrue(s.glasses.refreshes >= 1, "the table is read again before it's believed")
assertFalse(s.ready())
} finally {
s.core.disconnect()
}
}
@Test
fun anOldServiceTableIsReadAgain() {
val s = G1Session()
try {
s.glasses.staleTable = true
assertTrue(s.core.start())
assertTrue(awaitTrue(5_000) { s.ready() }, "never ready:\n" + s.tail())
assertEquals(1, s.glasses.refreshes)
assertTrue(s.listener.firmware.single().endsWith("Faceclaw/38"), s.listener.firmware.toString())
} finally {
s.core.disconnect()
}
}
@Test
fun aStalePairingInTheCaseIsRemovedAndMadeAgain() {
val s = G1Session()
try {
s.glasses.leftArm.bonded = true
s.glasses.rightArm.bonded = true
s.glasses.staleBond = true
s.glasses.helloInCase = true
assertTrue(s.core.start())
assertTrue(awaitTrue(8_000) { s.ready() }, "never ready:\n" + s.tail())
assertEquals(1, s.glasses.removedBonds)
assertFalse("unpaired" in s.listener.phases, "this isn't for the wearer to fix: " + s.listener.phases)
} finally {
s.core.disconnect()
}
}
@Test
fun aStalePairingOutOfTheCaseIsKeptAndExplained() {
val s = G1Session()
try {
s.glasses.leftArm.bonded = true
s.glasses.rightArm.bonded = true
s.glasses.staleBond = true
assertTrue(s.core.start())
assertTrue(awaitTrue(8_000) { "charging case" in s.listener.lastStatus }, "status: " + s.listener.lastStatus + "\n" + s.tail())
assertEquals(0, s.glasses.removedBonds, "no new bond can be made out of the case")
assertFalse("Exception" in s.listener.lastStatus, s.listener.lastStatus)
assertFalse("unpaired" in s.listener.phases, s.listener.phases.toString())
} finally {
s.core.disconnect()
}
}
@Test
fun aFailedConnectSaysWhatHappened() {
val s = G1Session()
try {
s.glasses.leftArm.bonded = true
s.glasses.rightArm.bonded = true
s.core.start()
// An arm that goes away during setup, before the session is ready.
s.glasses.drop(RIGHT)
s.glasses.away.add(RIGHT)
assertTrue(awaitTrue(25_000) { "right arm" in s.listener.lastStatus || s.ready() }, "status: " + s.listener.lastStatus)
assertFalse("Exception" in s.listener.lastStatus, s.listener.lastStatus)
} finally {
s.core.disconnect()
}
}
@Test
fun oneArmDroppingLeavesTheSessionAndTheOtherEyeAlone() {
val s = G1Session()
try {
started(s)
val phasesBefore = s.listener.phases.size
val rightBefore = s.glasses.lock.withLock { s.glasses.rightArm.wireBytes }
s.glasses.away.add(LEFT)
s.glasses.drop(LEFT)
assertTrue(s.ready(), "the session goes on")
// The right eye keeps getting frames, and nothing waits for the left.
s.submit(2, 2)
assertTrue(awaitTrue(5_000) { s.glasses.lock.withLock { s.glasses.rightArm.panel.contentEquals(s.expected(2)) } },
"the right eye stopped:\n" + s.tail())
assertTrue(s.glasses.lock.withLock { s.glasses.rightArm.wireBytes } > rightBefore)
assertTrue(s.ready())
assertTrue(s.listener.phases.drop(phasesBefore).none { it == "retrying" || it == "connecting" },
"no reconnect shown for a blip: " + s.listener.phases.drop(phasesBefore))
} finally {
s.core.disconnect()
}
}
@Test
fun anArmThatComesBackCatchesUpByItself() {
val s = G1Session()
try {
started(s)
val leftEvents = s.glasses.lock.withLock { s.glasses.leftArm.healthOk }
val rightPairs = s.glasses.lock.withLock { s.glasses.rightArm.pairedWrites }
s.glasses.away.add(LEFT)
s.glasses.drop(LEFT)
s.submit(2, 2)
assertTrue(awaitTrue(5_000) { s.glasses.lock.withLock { s.glasses.rightArm.panel.contentEquals(s.expected(2)) } })
s.glasses.lock.withLock { s.glasses.leftArm.records.clear() }
s.glasses.comeBack(LEFT)
assertTrue(awaitTrue(5_000) { s.shownOnBoth(s.expected(2)) }, "the left eye never caught up:\n" + s.tail())
assertTrue(s.ready())
assertTrue(s.glasses.lock.withLock { s.glasses.leftArm.healthOk } > leftEvents, "it was set up again")
assertEquals(rightPairs, s.glasses.lock.withLock { s.glasses.rightArm.pairedWrites }, "the other arm wasn't touched")
assertEquals(CFW_MSG_PRESENT, s.glasses.lock.withLock { s.glasses.leftArm.messageTypes.last() })
} finally {
s.core.disconnect()
}
}
@Test
fun theRightArmComingBackStartsItsMicAgain() {
val s = G1Session()
try {
started(s)
val listener = object : FaceclawAudioPacketListener {
override fun onAudioPacket(data: ByteArray?, arm: String?, arrivalMs: Long) {}
}
assertTrue(s.core.g1StartAudioCapture(listener))
assertTrue(awaitTrue(3_000) { s.glasses.lock.withLock { s.glasses.rightArm.micRequests.isNotEmpty() } })
s.glasses.away.add(RIGHT)
s.glasses.drop(RIGHT)
val before = s.glasses.lock.withLock { s.glasses.rightArm.micRequests.size }
s.glasses.comeBack(RIGHT)
assertTrue(awaitTrue(5_000) { s.glasses.lock.withLock { s.glasses.rightArm.micRequests.size } > before }, s.tail())
} finally {
s.core.disconnect()
}
}
@Test
fun anArmThatStaysAwayEndsInAFullReconnect() {
val s = G1Session()
try {
started(s)
s.glasses.away.add(LEFT)
s.glasses.drop(LEFT)
assertTrue(awaitTrue(8_000) { "left arm" in s.listener.lastStatus }, "status: " + s.listener.lastStatus + "\n" + s.tail())
assertFalse("Exception" in s.listener.lastStatus, s.listener.lastStatus)
s.glasses.comeBack(LEFT)
assertTrue(awaitTrue(15_000) { s.ready() }, "never back:\n" + s.tail())
s.submit(3, 3)
assertTrue(awaitTrue(5_000) { s.shownOnBoth(s.expected(3)) }, s.tail())
} finally {
s.core.disconnect()
}
}
@Test
fun bothArmsDroppingIsAFullReconnectAndAFastOne() {
val s = G1Session()
try {
started(s)
s.glasses.drop(LEFT)
s.glasses.drop(RIGHT)
val droppedAt = s.platform.elapsedRealtimeMs()
assertTrue(awaitTrue(5_000) { s.ready() }, "never back:\n" + s.tail())
assertTrue(s.platform.elapsedRealtimeMs() - droppedAt < 3_000, "the first retry comes quickly")
s.submit(4, 4)
assertTrue(awaitTrue(5_000) { s.shownOnBoth(s.expected(4)) }, s.tail())
} finally {
s.core.disconnect()
}
}
}
class G1SessionTest {
@Test
fun pairsOnFirstConnectAndShowsEachLensItsFrame() {
+22
View File
@@ -332,6 +332,28 @@ test("G1 arms on g1v0 join on the frame serial and can be selected", () => {
assert.match(row.armsSummary, /case/);
});
test("G1 arms on current firmware join on the serial, with the arm's own name", () => {
const record = (flags) => "ffff" + "02" + flags + "000542" + ascii(G1_SERIAL);
const aggregator = new DiscoveryAggregator();
aggregator.ingest(g1Arm("G1CFW_L_EF50E5", "C0:66:16:EF:50:E5", record("05")));
aggregator.ingest(g1Arm("G1CFW_R_CBE689", "E4:46:BA:CB:E6:89", record("04")));
const [pair] = aggregator.pairs();
assert.equal(pair.g1Firmware, "g1v0");
assert.equal(pair.completeness, "complete");
assert.equal(pair.left.g1Version, "0.5.66");
assert.equal(glassesRow(pair).canSelect, true);
});
test("a G1 pair halfway through an install is one pair, shown as needing it", () => {
const aggregator = new DiscoveryAggregator();
aggregator.ingest(g1Arm("G1CFW_L_EF50E5", "C0:66:16:EF:50:E5", "ffff" + "02" + "05" + "000542" + ascii(G1_SERIAL)));
aggregator.ingest(g1Arm("Even G1_70_R_CBE689", "E4:46:BA:CB:E6:89", "01" + ascii(G1_SERIAL)));
const pairs = aggregator.pairs();
assert.equal(pairs.length, 1);
assert.equal(pairs[0].g1Firmware, "stock");
assert.equal(glassesRow(pairs[0]).canSelect, true);
});
test("G1 arms on Even's firmware can be selected, to install on", () => {
const aggregator = new DiscoveryAggregator();
aggregator.ingest(g1Arm("Even G1_70_L_EF50E5", "C0:66:16:EF:50:E5", "02" + ascii(G1_SERIAL)));