This commit is contained in:
James Babcock committed 2026-05-02 02:29:22 -07:00
1 parent 9c199cd195
commit 29f911185f
5 files changed
+23 -80

No files matched your search

@@ -122,7 +122,7 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable {
public FaceclawBleCommunicator(Context context, String rightAddress, String leftAddress, String ringAddress) { public FaceclawBleCommunicator(Context context, String rightAddress, String leftAddress, String ringAddress) {
this.appContext = context.getApplicationContext(); this.appContext = context.getApplicationContext();
this.bleManager = new FaceclawBleManager(appContext, false); this.bleManager = new FaceclawBleManager(appContext);
this.bleManager.setListener(this); this.bleManager.setListener(this);
this.rightAddress = requireAddress("rightAddress", rightAddress); this.rightAddress = requireAddress("rightAddress", rightAddress);
this.leftAddress = requireAddress("leftAddress", leftAddress); this.leftAddress = requireAddress("leftAddress", leftAddress);
@@ -198,7 +198,7 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable {
return false; return false;
} }
audioPacketListener = listener; audioPacketListener = listener;
magic = nextMagic(); magic = magicPool.allocate();
pendingMessages.addFirst(createAudioControlMessageLocked(true, magic)); pendingMessages.addFirst(createAudioControlMessageLocked(true, magic));
logLine("queue G2 mic enable"); logLine("queue G2 mic enable");
lock.notifyAll(); lock.notifyAll();
@@ -214,7 +214,7 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable {
audioCaptureActive = false; audioCaptureActive = false;
clearMessagesOfKindLocked("audio-control"); clearMessagesOfKindLocked("audio-control");
if (running && sessionReady) { if (running && sessionReady) {
magic = nextMagic(); magic = magicPool.allocate();
pendingMessages.addFirst(createAudioControlMessageLocked(false, magic)); pendingMessages.addFirst(createAudioControlMessageLocked(false, magic));
logLine("queue G2 mic disable"); logLine("queue G2 mic disable");
lock.notifyAll(); lock.notifyAll();
@@ -276,7 +276,7 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable {
} }
shutdownRequested = true; shutdownRequested = true;
clearPendingMessagesLocked("shutdown requested"); clearPendingMessagesLocked("shutdown requested");
magic = nextMagic(); magic = magicPool.allocate();
pendingMessages.addFirst(new OutboundMessage( pendingMessages.addFirst(new OutboundMessage(
"shutdown", "shutdown",
"shutdown mode=" + exitMode, "shutdown mode=" + exitMode,
@@ -633,7 +633,7 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable {
Log.i(TAG, "message timed out: " + oldest.label); Log.i(TAG, "message timed out: " + oldest.label);
inFlightMessages.removeFirst(); inFlightMessages.removeFirst();
logLine("message timed out: " + oldest.label); logLine("message timed out: " + oldest.label);
releaseMagicLocked(oldest, "timeout"); magicPool.release(oldest.sid, oldest.magic, oldest.label, "timeout");
handleAckTimeoutLocked(oldest); handleAckTimeoutLocked(oldest);
return 0; return 0;
} }
@@ -752,7 +752,7 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable {
while (iterator.hasNext()) { while (iterator.hasNext()) {
if (iterator.next() == message) { if (iterator.next() == message) {
iterator.remove(); iterator.remove();
releaseMagicLocked(message, "write failed"); magicPool.release(message.sid, message.magic, message.label, "write failed");
return true; return true;
} }
} }
@@ -768,7 +768,7 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable {
Log.i(TAG, "Got ACK for " + message.label); Log.i(TAG, "Got ACK for " + message.label);
iterator.remove(); iterator.remove();
message.ackPayload = pb == null ? new byte[0] : Arrays.copyOf(pb, pb.length); message.ackPayload = pb == null ? new byte[0] : Arrays.copyOf(pb, pb.length);
releaseMagicLocked(message, "ack"); magicPool.release(message.sid, message.magic, message.label, "ack");
onMessageAckLocked(message); onMessageAckLocked(message);
return; return;
} }
@@ -895,7 +895,7 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable {
} }
private void enqueueCreateLayoutLocked() { private void enqueueCreateLayoutLocked() {
int magic = nextMagic(); int magic = magicPool.allocate();
pendingMessages.addLast(new OutboundMessage( pendingMessages.addLast(new OutboundMessage(
"create-layout", "create-layout",
"create-layout", "create-layout",
@@ -918,7 +918,7 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable {
private void enqueueStartupProbeLocked() { private void enqueueStartupProbeLocked() {
enqueueCreateLayoutLocked(); enqueueCreateLayoutLocked();
int magic = nextMagic(); int magic = magicPool.allocate();
pendingMessages.addLast(new OutboundMessage( pendingMessages.addLast(new OutboundMessage(
"startup-text-probe", "startup-text-probe",
"startup text probe", "startup text probe",
@@ -952,7 +952,7 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable {
int sessionId = nextMapSessionId(); int sessionId = nextMapSessionId();
List<BleProtocol.ImageFragment> fragments = BleImageOptimizer.planImageFragments(bmp, IMAGE_FRAGMENT_SIZE); List<BleProtocol.ImageFragment> fragments = BleImageOptimizer.planImageFragments(bmp, IMAGE_FRAGMENT_SIZE);
for (BleProtocol.ImageFragment fragment : fragments) { for (BleProtocol.ImageFragment fragment : fragments) {
int magic = nextMagic(); int magic = magicPool.allocate();
pendingMessages.addLast(new OutboundMessage( pendingMessages.addLast(new OutboundMessage(
"warmup", "warmup",
"warmup " + tile.name + "#" + fragment.index, "warmup " + tile.name + "#" + fragment.index,
@@ -1054,7 +1054,7 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable {
boolean requestAck, boolean requestAck,
boolean isLast boolean isLast
) { ) {
int magic = requestAck ? nextMagic() : 0; int magic = requestAck ? magicPool.allocate() : 0;
OutboundMessage message = new OutboundMessage( OutboundMessage message = new OutboundMessage(
"image", "image",
"image " + plan.tile.name + "#" + fragment.index, "image " + plan.tile.name + "#" + fragment.index,
@@ -1076,7 +1076,7 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable {
} }
private OutboundMessage createHeartbeatMessageLocked() { private OutboundMessage createHeartbeatMessageLocked() {
int magic = nextMagic(); int magic = magicPool.allocate();
return new OutboundMessage( return new OutboundMessage(
"heartbeat", "heartbeat",
"heartbeat", "heartbeat",
@@ -1119,7 +1119,7 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable {
} }
private OutboundMessage createBatteryQueryMessageLocked() { private OutboundMessage createBatteryQueryMessageLocked() {
int magic = nextMagic(); int magic = magicPool.allocate();
return new OutboundMessage( return new OutboundMessage(
"battery", "battery",
"battery", "battery",
@@ -1228,7 +1228,7 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable {
if ("image".equals(kind)) { if ("image".equals(kind)) {
imageUpdateStats.remove(message.imageUpdateId); imageUpdateStats.remove(message.imageUpdateId);
} }
releaseMagicLocked(message, "cleared pending " + kind); magicPool.release(message.sid, message.magic, message.label, "cleared pending " + kind);
} }
} }
Iterator<OutboundMessage> inFlightIterator = inFlightMessages.iterator(); Iterator<OutboundMessage> inFlightIterator = inFlightMessages.iterator();
@@ -1239,7 +1239,7 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable {
if ("image".equals(kind)) { if ("image".equals(kind)) {
imageUpdateStats.remove(message.imageUpdateId); imageUpdateStats.remove(message.imageUpdateId);
} }
releaseMagicLocked(message, "cleared inflight " + kind); magicPool.release(message.sid, message.magic, message.label, "cleared inflight " + kind);
} }
} }
} }
@@ -1251,23 +1251,18 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable {
private void clearPendingMessagesLocked(String reason) { private void clearPendingMessagesLocked(String reason) {
while (!pendingMessages.isEmpty()) { while (!pendingMessages.isEmpty()) {
releaseMagicLocked(pendingMessages.removeFirst(), "cleared pending: " + reason); var message = pendingMessages.removeFirst();
magicPool.release(message.sid, message.magic, message.label, "cleared pending: " + reason);
} }
} }
private void clearInFlightMessagesLocked(String reason) { private void clearInFlightMessagesLocked(String reason) {
while (!inFlightMessages.isEmpty()) { while (!inFlightMessages.isEmpty()) {
releaseMagicLocked(inFlightMessages.removeFirst(), "cleared inflight: " + reason); var message = inFlightMessages.removeFirst();
magicPool.release(message.sid, message.magic, message.label, "cleared inflight: " + reason);
} }
} }
private void releaseMagicLocked(OutboundMessage message, String reason) {
if (message == null || message.magic < BleMagicPool.MIN_MAGIC || message.magic > BleMagicPool.MAX_MAGIC) {
return;
}
magicPool.release(message.sid, message.magic, message.label, reason);
}
private void recordUnexpectedAckLocked(int sid, int magic) { private void recordUnexpectedAckLocked(int sid, int magic) {
if (magic < BleMagicPool.MIN_MAGIC || magic > BleMagicPool.MAX_MAGIC) { if (magic < BleMagicPool.MIN_MAGIC || magic > BleMagicPool.MAX_MAGIC) {
return; return;
@@ -1461,9 +1456,6 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable {
private void logLine(String line) { private void logLine(String line) {
Log.i(TAG, line); Log.i(TAG, line);
if (!shouldForwardLogLineToJavascript(line)) {
return;
}
final FaceclawBleCommunicatorListener current = listener; final FaceclawBleCommunicatorListener current = listener;
if (current == null) { if (current == null) {
return; return;
@@ -1477,34 +1469,11 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable {
}); });
} }
private boolean shouldForwardLogLineToJavascript(String line) {
if (line == null || line.isEmpty()) {
return false;
}
return line.startsWith("communicator start")
|| line.startsWith("communicator stop")
|| line.startsWith("connect failed")
|| line.startsWith("session ready")
|| line.startsWith("message timed out")
|| line.startsWith("create layout timed out")
|| line.startsWith("unexpected ACK")
|| line.startsWith("late ACK")
|| line.startsWith("duplicate ACK")
|| line.startsWith("skip shutdown")
|| line.startsWith("shutdown")
|| line.startsWith("Even Realities")
|| line.startsWith("communicator loop error");
}
private static String timestamp(long elapsedMs) { private static String timestamp(long elapsedMs) {
long wallMs = System.currentTimeMillis(); long wallMs = System.currentTimeMillis();
return String.format(Locale.US, "%tF %tT.%tL elapsed=%dms", wallMs, wallMs, wallMs, elapsedMs); return String.format(Locale.US, "%tF %tT.%tL elapsed=%dms", wallMs, wallMs, wallMs, elapsedMs);
} }
private int nextMagic() {
return magicPool.allocate();
}
private int nextMapSessionId() { private int nextMapSessionId() {
int id = nextMapSessionId; int id = nextMapSessionId;
nextMapSessionId = (nextMapSessionId + 1) & 0xff; nextMapSessionId = (nextMapSessionId + 1) & 0xff;
@@ -29,7 +29,6 @@ public class FaceclawBleManager {
private final Context context; private final Context context;
private final BluetoothAdapter bluetoothAdapter; private final BluetoothAdapter bluetoothAdapter;
private final boolean dispatchListenerOnMain;
private final Handler mainHandler = new Handler(Looper.getMainLooper()); private final Handler mainHandler = new Handler(Looper.getMainLooper());
private final ConcurrentHashMap<String, BluetoothGatt> gattClients = new ConcurrentHashMap<>(); private final ConcurrentHashMap<String, BluetoothGatt> gattClients = new ConcurrentHashMap<>();
@@ -53,12 +52,7 @@ public class FaceclawBleManager {
private volatile FaceclawBleListener listener; private volatile FaceclawBleListener listener;
public FaceclawBleManager(Context context) { public FaceclawBleManager(Context context) {
this(context, true);
}
public FaceclawBleManager(Context context, boolean dispatchListenerOnMain) {
this.context = context.getApplicationContext(); this.context = context.getApplicationContext();
this.dispatchListenerOnMain = dispatchListenerOnMain;
BluetoothManager bluetoothManager = (BluetoothManager) this.context.getSystemService(Context.BLUETOOTH_SERVICE); BluetoothManager bluetoothManager = (BluetoothManager) this.context.getSystemService(Context.BLUETOOTH_SERVICE);
if (bluetoothManager == null || bluetoothManager.getAdapter() == null) { if (bluetoothManager == null || bluetoothManager.getAdapter() == null) {
throw new IllegalStateException("Bluetooth adapter unavailable"); throw new IllegalStateException("Bluetooth adapter unavailable");
@@ -366,22 +360,6 @@ public class FaceclawBleManager {
return bluetoothApiLock; return bluetoothApiLock;
} }
private void runOnMainAsync(Runnable runnable) {
if (Looper.myLooper() == Looper.getMainLooper()) {
runnable.run();
} else {
mainHandler.post(runnable);
}
}
private void dispatchListener(Runnable runnable) {
if (dispatchListenerOnMain) {
runOnMainAsync(runnable);
} else {
runnable.run();
}
}
private final BluetoothGattCallback gattCallback = new BluetoothGattCallback() { private final BluetoothGattCallback gattCallback = new BluetoothGattCallback() {
@Override @Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) { public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
@@ -472,18 +450,14 @@ public class FaceclawBleManager {
private void dispatchConnectionState(String address, boolean connected) { private void dispatchConnectionState(String address, boolean connected) {
FaceclawBleListener current = listener; FaceclawBleListener current = listener;
if (current == null) { if (current == null) return;
return; current.onConnectionStateChange(address, connected);
}
dispatchListener(() -> current.onConnectionStateChange(address, connected));
} }
private void dispatchNotification(String address, String characteristicUuid, byte[] data) { private void dispatchNotification(String address, String characteristicUuid, byte[] data) {
FaceclawBleListener current = listener; FaceclawBleListener current = listener;
if (current == null) { if (current == null) return;
return;
}
byte[] copy = data != null ? data.clone() : new byte[0]; byte[] copy = data != null ? data.clone() : new byte[0];
dispatchListener(() -> current.onNotification(address, characteristicUuid, copy)); current.onNotification(address, characteristicUuid, copy);
} }
} }