diff --git a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawFirmwareFlasher.java b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawFirmwareFlasher.java index 3a941ac6..91f5bcaa 100644 --- a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawFirmwareFlasher.java +++ b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawFirmwareFlasher.java @@ -133,7 +133,8 @@ public class FaceclawFirmwareFlasher implements FaceclawBleListener { cancel(); try { bleManager.close(); - } catch (Exception ignored) { + } catch (Exception e) { + Log.w(TAG, "close: ble manager close failed", e); } } @@ -207,7 +208,8 @@ public class FaceclawFirmwareFlasher implements FaceclawBleListener { emitLog(lens + " lens: all components verified"); try { bleManager.disconnect(address); - } catch (Exception ignored) { + } catch (Exception e) { + Log.w(TAG, "disconnect after " + lens + " lens failed: address=" + address, e); } } @@ -349,7 +351,9 @@ public class FaceclawFirmwareFlasher implements FaceclawBleListener { emitLog(lens + " connect attempt " + attempt + " failed (" + lastError + "); retrying..."); try { bleManager.disconnect(address); - } catch (Exception ignored) { + } catch (Exception e) { + // Routine between retries: the link is usually already gone. + Log.d(TAG, "disconnect before retry failed: address=" + address, e); } sleepInterruptibly(RETRY_DELAY_MS); } @@ -545,6 +549,8 @@ public class FaceclawFirmwareFlasher implements FaceclawBleListener { } BleProtocol.ParsedFrame frame = BleProtocol.parseFrame(data); if (!frame.ok || frame.pb.length < 2) { + // Dropped acks surface upstream as an unexplained timeout, so say so here. + Log.d(TAG, "ignoring ack frame: ok=" + frame.ok + " len=" + frame.pb.length); return; } dataAcks.add(Arrays.copyOf(frame.pb, Math.min(frame.pb.length, 2))); @@ -552,9 +558,7 @@ public class FaceclawFirmwareFlasher implements FaceclawBleListener { @Override public void onConnectionStateChange(String address, boolean connected) { - if (!connected) { - Log.i(TAG, "disconnected: " + address); - } + Log.i(TAG, (connected ? "connected: " : "disconnected: ") + address); } // ---- helpers ------------------------------------------------------------- @@ -562,7 +566,8 @@ public class FaceclawFirmwareFlasher implements FaceclawBleListener { private void teardown() { try { bleManager.close(); - } catch (Exception ignored) { + } catch (Exception e) { + Log.w(TAG, "teardown: ble manager close failed", e); } } @@ -665,6 +670,13 @@ public class FaceclawFirmwareFlasher implements FaceclawBleListener { private void emitProgress(String lens, int componentIndex, int componentCount, int blockIndex, int blockCount, long bytesSent, long bytesTotal) { + // Per-block, so DEBUG and behind isLoggable: thousands of these per flash, and + // without the guard the message is built every time even when nobody reads it. + // The component boundaries are the interesting ones and emitLog reports those. + if (Log.isLoggable(TAG, Log.DEBUG)) { + Log.d(TAG, "progress " + lens + " component " + (componentIndex + 1) + "/" + componentCount + + " block " + (blockIndex + 1) + "/" + blockCount + " " + bytesSent + "/" + bytesTotal + " bytes"); + } mainHandler.post(() -> { FaceclawFirmwareFlasherListener current = listener; if (current != null) { @@ -675,6 +687,13 @@ public class FaceclawFirmwareFlasher implements FaceclawBleListener { private void emitState(String state, String detail) { final String safeDetail = detail == null ? "" : detail; + // These went only to the in-app listener, so a failed flash left its reason on + // the phone screen and nowhere a log could be read from afterwards. + if ("error".equals(state)) { + Log.e(TAG, "state=" + state + (safeDetail.isEmpty() ? "" : " -- " + safeDetail)); + } else { + Log.i(TAG, "state=" + state + (safeDetail.isEmpty() ? "" : " -- " + safeDetail)); + } mainHandler.post(() -> { FaceclawFirmwareFlasherListener current = listener; if (current != null) { @@ -685,6 +704,13 @@ public class FaceclawFirmwareFlasher implements FaceclawBleListener { private void emitComplete(boolean success, String detail) { final String safeDetail = detail == null ? "" : detail; + // The single most important line of a flash, and it used to be invisible to + // logcat: on failure this carries the reason. + if (success) { + Log.i(TAG, "complete success -- " + safeDetail); + } else { + Log.e(TAG, "complete FAILED -- " + safeDetail); + } mainHandler.post(() -> { FaceclawFirmwareFlasherListener current = listener; if (current != null) { diff --git a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawFlashPromptCommunicator.java b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawFlashPromptCommunicator.java index ef342706..833a34b2 100644 --- a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawFlashPromptCommunicator.java +++ b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawFlashPromptCommunicator.java @@ -4,6 +4,7 @@ import android.bluetooth.BluetoothGatt; import android.content.Context; import android.os.Handler; import android.os.Looper; +import android.os.SystemClock; import android.util.Log; import java.util.List; @@ -54,6 +55,15 @@ public class FaceclawFlashPromptCommunicator implements FaceclawBleListener { private static final int SELECTION_TIMEOUT_MS = 120_000; private static final int CREATE_ACK_TIMEOUT_MS = 3_000; private static final int BATTERY_ACK_TIMEOUT_MS = 3_000; + /** + * A single connect attempt is not enough. The lens is routinely unavailable for a + * moment right after a previous link to it closed, which is exactly the situation + * this class is in whenever the user retries. FaceclawFirmwareFlasher already + * retries within a window for the same reason; this matches it rather than + * failing on the first refusal. + */ + private static final int ARM_CONNECT_WINDOW_MS = 30_000; + private static final int ARM_RETRY_DELAY_MS = 2_500; private final Context context; private final String rightAddress; @@ -75,6 +85,14 @@ public class FaceclawFlashPromptCommunicator implements FaceclawBleListener { private volatile boolean rightConnected = false; private volatile boolean leftConnected = false; private volatile boolean rightLost = false; + /** + * True while the arms are still being brought up. connectArmResilient disconnects + * between retries, which fires onConnectionStateChange, and that callback latches + * rightLost AND finished -- so without this guard a deliberate retry-disconnect + * ends the whole run, even when the very next attempt connects. Only a drop AFTER + * both arms are up is a lost connection. + */ + private volatile boolean establishing = true; private volatile Boolean approved = null; private volatile ScheduledExecutorService heartbeatExecutor; @@ -121,7 +139,8 @@ public class FaceclawFlashPromptCommunicator implements FaceclawBleListener { stopHeartbeat(); try { bleManager.close(); - } catch (Exception ignored) { + } catch (Exception e) { + Log.w(TAG, "close: ble manager close failed", e); } } @@ -148,6 +167,8 @@ public class FaceclawFlashPromptCommunicator implements FaceclawBleListener { } } + // Both arms are up: from here a disconnect really is a lost connection. + establishing = false; emitState("connected", ""); // Auth both arms now (pairing prompts, if any, happen here) before // anything else, so both bonds exist by the time flashing starts. @@ -185,7 +206,10 @@ public class FaceclawFlashPromptCommunicator implements FaceclawBleListener { } try { sendShutdown(); - } catch (Exception ignored) { + } catch (Exception e) { + // The lens is about to be torn down either way, but a shutdown that + // never lands is why it can come back up in an odd state. + Log.w(TAG, "sendShutdown failed", e); } if (!Boolean.TRUE.equals(approved)) { emitResult(false); @@ -224,9 +248,7 @@ public class FaceclawFlashPromptCommunicator implements FaceclawBleListener { } private void connectArm(String address, String arm) { - if (!bleManager.connect(address, ConnectionOptions.CONNECT_TIMEOUT_MS)) { - throw new IllegalStateException("could not connect to the " + arm + " arm (" + address + ")"); - } + connectArmResilient(address, arm); bleManager.requestConnectionPriority(address, BluetoothGatt.CONNECTION_PRIORITY_HIGH); bleManager.requestMtu(address, ConnectionOptions.DESIRED_MTU, ConnectionOptions.CONNECT_TIMEOUT_MS); if (!bleManager.discoverServices(address, ConnectionOptions.SERVICES_TIMEOUT_MS)) { @@ -238,6 +260,51 @@ public class FaceclawFlashPromptCommunicator implements FaceclawBleListener { emitLog("connected " + arm + " arm"); } + private void sleepInterruptibly(int ms) { + try { + Thread.sleep(ms); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + + /** + * Keep trying to open the link until the window closes, reporting each attempt. + * Mirrors FaceclawFirmwareFlasher.connectLensResilient. + */ + private void connectArmResilient(String address, String arm) { + long deadline = SystemClock.elapsedRealtime() + ARM_CONNECT_WINDOW_MS; + String lastError = "unknown"; + int attempt = 0; + while (SystemClock.elapsedRealtime() < deadline && !cancelled) { + attempt++; + try { + if (bleManager.connect(address, ConnectionOptions.CONNECT_TIMEOUT_MS)) { + if (attempt > 1) { + emitLog("connected " + arm + " arm (attempt " + attempt + ")"); + } + return; + } + lastError = "connect refused"; + } catch (Exception e) { + lastError = e.getMessage() == null ? e.toString() : e.getMessage(); + } + emitLog(arm + " arm connect attempt " + attempt + " failed (" + lastError + "); retrying..."); + try { + bleManager.disconnect(address); + } catch (Exception e) { + // Expected between retries: the link is usually already gone. + Log.d(TAG, "disconnect before retry failed: address=" + address, e); + } + sleepInterruptibly(ARM_RETRY_DELAY_MS); + } + if (cancelled) { + throw new IllegalStateException("Cancelled."); + } + throw new IllegalStateException( + "could not connect to the " + arm + " arm after " + attempt + " attempts: " + lastError); + } + /** * Security-auth exchange on sid=0x80: firmware 2.2.9 will not run a * session (and closes the link after ~30 s) without it, and on an @@ -412,7 +479,8 @@ public class FaceclawFlashPromptCommunicator implements FaceclawBleListener { stopHeartbeat(); try { bleManager.close(); - } catch (Exception ignored) { + } catch (Exception e) { + Log.w(TAG, "teardown: ble manager close failed", e); } rightConnected = false; leftConnected = false; @@ -485,7 +553,7 @@ public class FaceclawFlashPromptCommunicator implements FaceclawBleListener { if (address.equalsIgnoreCase(rightAddress)) { rightConnected = false; synchronized (lock) { - if (!finished && !cancelled) { + if (!establishing && !finished && !cancelled) { rightLost = true; finished = true; selectionLatch.countDown(); @@ -518,6 +586,8 @@ public class FaceclawFlashPromptCommunicator implements FaceclawBleListener { private void emitState(String state, String detail) { final String safeDetail = detail == null ? "" : detail; + // Listener-only until now, so a prompt that never appeared left no trace in a log. + Log.i(TAG, "state=" + state + (safeDetail.isEmpty() ? "" : " -- " + safeDetail)); mainHandler.post(() -> { FaceclawFlashPromptListener current = listener; if (current != null) { @@ -536,6 +606,7 @@ public class FaceclawFlashPromptCommunicator implements FaceclawBleListener { } private void emitResult(boolean approvedResult) { + Log.i(TAG, "result=" + (approvedResult ? "approved" : "declined")); mainHandler.post(() -> { FaceclawFlashPromptListener current = listener; if (current != null) { diff --git a/app/phone-ui/onboarding-flash-view-model.ts b/app/phone-ui/onboarding-flash-view-model.ts index 3249c97c..a99e4880 100644 --- a/app/phone-ui/onboarding-flash-view-model.ts +++ b/app/phone-ui/onboarding-flash-view-model.ts @@ -56,6 +56,8 @@ export class OnboardingFlashViewModel extends Observable { private flasher: FirmwareFlasher | null = null; private flasherUnsubscribers: Array<() => void> = []; private retryAction: () => void = () => this.beginPrompt(); + /** Overrides the error screen's "Retry" when the action is not a retry. */ + private primaryLabelOverride: string | null = null; constructor(options?: { mode?: FlashMode; fromOnboarding?: boolean; autoStart?: boolean }) { super(); @@ -174,7 +176,7 @@ export class OnboardingFlashViewModel extends Observable { case "flashed": return "Finish"; case "error": - return "Retry"; + return this.primaryLabelOverride ?? "Retry"; default: return ""; } @@ -329,6 +331,25 @@ export class OnboardingFlashViewModel extends Observable { break; case "error": this.busy = false; + // An unacked prompt page is not a connection failure. The lens accepts the + // write at the GATT layer and then never answers, which is what firmware + // older than the revision this build needs does -- measured on revision 13, + // four writes accepted with status 0 and no reply, nothing shown on the lens. + // Flashing is the only way OFF that firmware, so failing here leaves the + // glasses permanently unupgradable. Fall back to the phone-side confirmation + // that the low-battery retry already uses, and say plainly what is being + // given up: the on-lens step is what proves these are the wearer's glasses. + if (/prompt page not acked/i.test(detail)) { + this.toError( + "Your glasses are on older firmware that can't show the confirmation prompt, so it can't be " + + "confirmed on the lens. You can confirm here instead. Only continue if these are your glasses " + + "and you want to install Faceclaw's custom firmware.", + () => this.beginPrompt({ skipPrompt: true }), + "Confirm On Your Phone", + "Confirm & Install", + ); + break; + } this.toError(detail || "Connection failed.", () => this.beginPrompt({ skipPrompt })); break; } @@ -569,7 +590,13 @@ export class OnboardingFlashViewModel extends Observable { }); } - private toError(message: string, retry: () => void, headline = "Something Went Wrong"): void { + private toError( + message: string, + retry: () => void, + headline = "Something Went Wrong", + primaryLabel: string | null = null, + ): void { + this.primaryLabelOverride = primaryLabel; this.retryAction = retry; this.status = message; this.setPhase("error"); diff --git a/tests/flash-prompt-fallback.test.cjs b/tests/flash-prompt-fallback.test.cjs new file mode 100644 index 00000000..a82151a8 --- /dev/null +++ b/tests/flash-prompt-fallback.test.cjs @@ -0,0 +1,62 @@ +// The flash cannot always ask for confirmation on the lens: firmware older than +// the revision this build needs accepts the create-prompt write and then never +// answers it. Flashing is the only way off that firmware, so an unacked prompt +// must not be a dead end. These cover the decision at that seam. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { loader } = require('./helpers/load-typescript.cjs'); + +function fixture() { + class Observable { notifyPropertyChange() {} } + const load = loader({}, { + '@nativescript/core': { Observable, Frame: { topmost: () => null } }, + './onboarding-navigation': { finishOnboardingNavigation() {} }, + './onboarding-state': { setOnboardingCompleted() {}, setPreviewOnlyMode() {} }, + '../native/ble-permissions': { ensureBlePermissions: async () => {} }, + '../g2/device-addresses': { + isValidMacAddress: () => true, + loadDeviceAddresses: () => ({ right: 'R', left: 'L' }), + saveDeviceAddresses() {}, + }, + '../g2/firmware-builder': { + buildCustomFirmware: async () => '', buildStockFirmware: async () => '', + FirmwareBuildError: class extends Error {}, FirmwareProgress: {}, + }, + '../native/device-discovery': { buildAddressSet: () => new Set(), DeviceDiscoveryBridge: class {} }, + '../native/firmware-flasher': { FirmwareFlasher: class {} }, + '../native/flash-prompt-communicator': { FlashPromptCommunicator: class {} }, + '../g2/reconnect-policy': { resumeAutoReconnect() {}, suppressAutoReconnect() {} }, + '../util/format-error': { formatErrorMessage: (e) => String(e) }, + }); + const mod = load('app/phone-ui/onboarding-flash-view-model.ts'); + const Model = mod.OnboardingFlashViewModel ?? Object.values(mod).find((v) => typeof v === 'function'); + const model = new Model(); + const beginArgs = []; + model.beginPrompt = async (options) => { beginArgs.push(options); }; + return { model, beginArgs }; +} + +test('an unacked prompt page offers the phone-side confirmation instead of dead-ending', () => { + const { model, beginArgs } = fixture(); + model.handlePromptState('error', 'prompt page not acked: AA:BB:CC:DD:EE:FF', false); + assert.equal(model.phase, 'error'); + assert.equal(model.headline, 'Confirm On Your Phone'); + assert.equal(model.primaryLabel, 'Confirm & Install', 'the action is a confirmation, not a retry'); + assert.match(model.status, /can't show the confirmation prompt/i); + model.retryAction(); + // The loader runs the module in its own vm realm, so the options object has that + // realm's prototype and deepStrictEqual would reject it. Compare the field. + assert.equal(beginArgs.length, 1); + assert.equal(beginArgs[0].skipPrompt, true, 'confirming must skip the lens prompt, not re-ask for it'); +}); + +test('any other prompt failure still reports as an ordinary retry', () => { + const { model, beginArgs } = fixture(); + model.handlePromptState('error', 'discoverServices failed: right arm', false); + assert.equal(model.phase, 'error'); + assert.equal(model.headline, 'Something Went Wrong'); + assert.equal(model.primaryLabel, 'Retry'); + model.retryAction(); + assert.equal(beginArgs.length, 1); + assert.equal(beginArgs[0].skipPrompt, false, 'an ordinary failure must not silently skip the lens prompt'); +});