Add a lock screen, controlled by wear-detection

This commit is contained in:
James Babcock committed 2026-08-02 15:38:07 -07:00
1 parent 4302a506d4
commit 960e2fd6e1
10 files changed
+429 -22

No files matched your search

@@ -3,7 +3,11 @@ package com.faceclaw.app;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.app.KeyguardManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Looper;
import android.os.PowerManager;
@@ -41,6 +45,7 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable {
private final Context appContext;
private final PowerManager powerManager;
private final KeyguardManager keyguardManager;
private final FaceclawBleManager bleManager;
private final InterruptibleSleep interruptibleSleep = new InterruptibleSleep();
private final Object lock = new Object();
@@ -116,6 +121,10 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable {
private int headsetCharging = -1;
// Silent mode: 1 = on, 0 = off, -1 = not yet known. See updateSilentModeLocked.
private int silentMode = -1;
private int wearState = -1;
private int phoneLockState = -1;
private long lastPhoneLockCheckAtMs;
private boolean phoneLockReceiverRegistered;
private boolean audioCaptureActive;
private boolean firmwareInfoQueried;
// Glasses are in the charging case: nobody is wearing them, so display
@@ -124,6 +133,13 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable {
private volatile FaceclawAudioPacketListener audioPacketListener;
private PowerManager.WakeLock g2ScreenWakeLock;
private final BroadcastReceiver phoneLockReceiver = new BroadcastReceiver() {
@Override public void onReceive(Context context, Intent intent) {
emitPhoneLockStateIfChanged(true);
interruptibleSleep.interrupt();
}
};
private String displayedFingerprint = "";
// The frame the firmware shadow will hold once the current image pipeline
// drains: the most recently ENQUEUED image (headerless packed 4bpp, see
@@ -162,17 +178,25 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable {
this.appContext = context.getApplicationContext();
FrameTimings.getInstance().init(appContext);
this.powerManager = (PowerManager) appContext.getSystemService(Context.POWER_SERVICE);
this.keyguardManager = (KeyguardManager) appContext.getSystemService(Context.KEYGUARD_SERVICE);
this.bleManager = new FaceclawBleManager(appContext);
this.bleManager.setListener(this);
this.rightAddress = requireAddress("rightAddress", rightAddress);
this.leftAddress = requireAddress("leftAddress", leftAddress);
this.ringAddress = ringAddress == null ? "" : ringAddress.trim();
IntentFilter phoneLockFilter = new IntentFilter();
phoneLockFilter.addAction(Intent.ACTION_SCREEN_ON);
phoneLockFilter.addAction(Intent.ACTION_SCREEN_OFF);
phoneLockFilter.addAction(Intent.ACTION_USER_PRESENT);
appContext.registerReceiver(phoneLockReceiver, phoneLockFilter);
phoneLockReceiverRegistered = true;
}
public void setListener(FaceclawBleCommunicatorListener listener) {
this.listener = listener;
emitState();
emitPhoneLockStateIfChanged(true);
}
public void start() {
@@ -231,6 +255,10 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable {
activeInstance = null;
}
disconnect();
if (phoneLockReceiverRegistered) {
phoneLockReceiverRegistered = false;
appContext.unregisterReceiver(phoneLockReceiver);
}
}
public void setG2ScreenOn(boolean screenOn) {
@@ -407,6 +435,31 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable {
interruptibleSleep.interrupt();
}
/**
* Enable the stock wear detector, then ask CFW to emit its current cached
* state. The queue order matters: the query must run after the setting is
* applied, including on a fresh install where wear detection was disabled.
*/
public void enableWearDetectionAndRequestState() {
synchronized (lock) {
if (!running || !sessionReady) {
logLine("skip wear detector setup; session not ready");
return;
}
clearMessagesOfKindLocked("wear-detection-control");
clearMessagesOfKindLocked("wear-query-control");
OutboundMessage queryLeft = messageBuilder.faceclawWearQuery(true);
OutboundMessage queryRight = messageBuilder.faceclawWearQuery(false);
OutboundMessage enable = messageBuilder.setWearDetection(true);
enable.onTimeout = () -> logLine("wear detection enable ack timeout");
pendingMessages.addFirst(queryLeft);
pendingMessages.addFirst(queryRight);
pendingMessages.addFirst(enable);
logLine("queue wear detection enable + current-state query");
}
interruptibleSleep.interrupt();
}
public void addImuListener(FaceclawImuListener listener) {
if (listener != null) {
imuListeners.add(listener);
@@ -829,6 +882,7 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable {
Log.w(TAG, "Exiting event looop");
break;
}
emitPhoneLockStateIfChanged(false);
if (!sessionReady) {
long now = SystemClock.elapsedRealtime();
if (now < reconnectAfterMs) {
@@ -875,9 +929,15 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable {
}
Log.d(TAG, "onNotification: address=" + address + " characteristicUuid=" + characteristicUuid + " data.length=" + data.length);
BleProtocol.ParsedFrame frame = BleProtocol.parseFrame(data);
int decodedWearState = BleProtocol.parseWearState(frame);
boolean emitWearState = false;
G2Event event = null;
synchronized (lock) {
lastIncomingAtMs = SystemClock.elapsedRealtime();
if (decodedWearState >= 0 && decodedWearState != wearState) {
wearState = decodedWearState;
emitWearState = true;
}
boolean faceclawWakeNotification = false;
if (shutdownRequested
&& frame.ok
@@ -920,6 +980,7 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable {
);
}
if (!faceclawWakeNotification
&& decodedWearState < 0
&& frame.ok
&& frame.sid == BleProtocol.SID_UI_SETTING) {
// Device-initiated settings push. It carries a magic the glasses
@@ -932,6 +993,7 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable {
}
}
if (!faceclawWakeNotification
&& decodedWearState < 0
&& frame.ok
&& frame.msgSeq >= 0
&& frame.flag != BleProtocol.FLAG_NOTIFY
@@ -974,6 +1036,10 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable {
}
}
interruptibleSleep.interrupt();
if (emitWearState) {
logLine(decodedWearState > 0 ? "wear state ON_HEAD" : "wear state OFF_HEAD");
emitWearState(decodedWearState > 0);
}
if (event != null) {
if (event.hasImu) {
emitImuData(event.imuX, event.imuY, event.imuZ, event.eventSource);
@@ -2470,6 +2536,7 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable {
faceclawWakePendingNonce = -1;
lastFaceclawWakeLeaseQueuedAtMs = 0;
faceclawWakeControlSentCount = 0;
wearState = -1;
displayedFingerprint = "";
// Deliberately not clearing silentMode: it is a property of the glasses,
// not of our session, and silent mode blocks app launches, so it can be
@@ -2542,6 +2609,40 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable {
});
}
private void emitWearState(boolean wearing) {
final FaceclawBleCommunicatorListener current = listener;
if (current == null) return;
mainHandler.post(() -> {
try {
current.onWearState(wearing);
} catch (Throwable t) {
Log.w(TAG, "listener onWearState failed", t);
}
});
}
private void emitPhoneLockStateIfChanged(boolean force) {
final boolean locked;
synchronized (lock) {
long now = SystemClock.elapsedRealtime();
if (!force && now - lastPhoneLockCheckAtMs < 1_000) return;
lastPhoneLockCheckAtMs = now;
locked = keyguardManager != null && keyguardManager.isDeviceLocked();
int value = locked ? 1 : 0;
if (!force && value == phoneLockState) return;
phoneLockState = value;
}
final FaceclawBleCommunicatorListener current = listener;
if (current == null) return;
mainHandler.post(() -> {
try {
current.onPhoneLockState(locked);
} catch (Throwable t) {
Log.w(TAG, "listener onPhoneLockState failed", t);
}
});
}
private void emitBatteryState(int headsetBattery, int headsetCharging) {
final FaceclawBleCommunicatorListener current = listener;
if (current == null) {
@@ -6,6 +6,8 @@ public interface FaceclawBleCommunicatorListener {
void onRingEvent(String kind, String containerName, int eventType, int eventSource, int systemExitReasonCode, int frameId);
void onBatteryState(int headsetBattery, int headsetCharging);
void onSilentMode(boolean silent);
void onWearState(boolean wearing);
void onPhoneLockState(boolean locked);
void onEvenAppConflict(String message);
void onFrameMetrics(int paintMs, int transmitMs, int tileCount);
void onFrameFinished(int frameId, String outcome);
@@ -32,6 +32,7 @@ public class BleProtocol {
public static final int SID_EVENHUB = 0xe0;
public static final int SID_UI_SETTING = 0x09;
public static final int SID_STATE_CHANGE = 0x0d;
public static final int SID_ONBOARDING = 0x10;
/** G2SettingPackage.commandId for device-initiated pushes (vs. 2 = app read). */
public static final int SETTINGS_CMD_DEVICE_SEND_TO_APP = 3;
// Private Faceclaw/CFW wake-takeover protocol. Both payloads are unknown
@@ -44,6 +45,7 @@ public class BleProtocol {
public static final int FACECLAW_WAKE_OP_READY = 4;
public static final int FACECLAW_FB_OP_ACQUIRE = 5;
public static final int FACECLAW_FB_OP_RELEASE = 6;
public static final int FACECLAW_WEAR_OP_QUERY = 7;
private static final int FACECLAW_WAKE_EVENT = 1;
private static final int FACECLAW_WAKE_PROTOCOL_VERSION = 1;
// UI_FOREGROUND_EVEN_AI_ID: the stock "Even AI" assistant app. It is a
@@ -306,6 +308,16 @@ public class BleProtocol {
));
}
/** Enable the firmware's wear detector (DeviceReceiveInfoFromAPP field 5). */
public static byte[] buildSetWearDetection(int magic, boolean enabled) {
byte[] wear = encodeVarintField(1, enabled ? 1 : 0);
return concat(CollectionUtils.listOf(
encodeVarintField(1, 1),
encodeVarintField(2, magic),
encodeMessageField(3, encodeMessageField(5, wear))
));
}
public static byte[] buildSettingsQuery(int magic) {
byte[] request = encodeVarintField(1, 1);
return concat(CollectionUtils.listOf(
@@ -356,6 +368,28 @@ public class BleProtocol {
return (event[4] & 0xff) | ((event[5] & 0xff) << 8);
}
/**
* Decode OnboardingDataPackage EVENT/GLS_WEAR_STATUS. Unlike most async
* G2 traffic, stock firmware sends this event with flag 0x00, so callers
* must recognize it by sid and protobuf shape rather than notify flag.
* Returns 0/1, or -1 when the frame is not a wear event.
*/
public static int parseWearState(ParsedFrame frame) {
if (frame == null || !frame.ok || frame.sid != SID_ONBOARDING) {
return -1;
}
byte[] root = stripTrailingCrc(frame.pb);
if (readVarintFieldValue(root, 1, -1) != 3) {
return -1;
}
byte[] event = readFieldBytes(root, 5);
if (event == null || readVarintFieldValue(event, 1, -1) != 1) {
return -1;
}
int wearStatus = readVarintFieldValue(event, 2, -1);
return wearStatus == 0 || wearStatus == 1 ? wearStatus : -1;
}
public static BatterySnapshot parseSettingsBattery(byte[] pb) {
byte[] root = stripTrailingCrc(pb);
byte[] request = readFieldBytes(root, 4);
@@ -137,6 +137,21 @@ public class MessageBuilder {
);
}
public OutboundMessage setWearDetection(boolean enabled) {
int magic = magicPool.allocate();
return new OutboundMessage(
"wear-detection-control",
"wear detection " + (enabled ? "enable" : "disable"),
BleProtocol.SID_UI_SETTING,
BleProtocol.FLAG_REQUEST,
magic,
BleProtocol.buildSetWearDetection(magic, enabled),
ACK_TIMEOUT_MS,
-1,
false
);
}
public OutboundMessage createLayout(BleProtocol.ImageTileOptions... tiles) {
int magic = magicPool.allocate();
return new OutboundMessage(
@@ -224,4 +239,18 @@ public class MessageBuilder {
leftArm
);
}
public OutboundMessage faceclawWearQuery(boolean leftArm) {
return new OutboundMessage(
"wear-query-control",
"wear state query" + (leftArm ? " L" : " R"),
BleProtocol.SID_UI_SETTING,
BleProtocol.FLAG_REQUEST,
0,
BleProtocol.buildFaceclawWakeControl(BleProtocol.FACECLAW_WEAR_OP_QUERY, 0),
ACK_TIMEOUT_MS,
-1,
leftArm
);
}
}