diff --git a/App_Resources/Android/src/main/java/com/faceclaw/app/BleProtocol.java b/App_Resources/Android/src/main/java/com/faceclaw/app/BleProtocol.java index 8b551568..58a65406 100644 --- a/App_Resources/Android/src/main/java/com/faceclaw/app/BleProtocol.java +++ b/App_Resources/Android/src/main/java/com/faceclaw/app/BleProtocol.java @@ -51,22 +51,12 @@ public class BleProtocol { int totalWithCrc = pb.length + 2; int totalFrags = Math.max(1, (int) Math.ceil(totalWithCrc / (double) chunkSize)); List frames = new ArrayList<>(totalFrags); - int offset = 0; + byte[] payload = Arrays.copyOf(pb, totalWithCrc); + payload[pb.length] = crc[0]; + payload[pb.length + 1] = crc[1]; for (int i = 0; i < totalFrags; i++) { - boolean isLast = i == totalFrags - 1; - byte[] chunk; - if (isLast) { - int remaining = pb.length - offset; - chunk = new byte[remaining + 2]; - System.arraycopy(pb, offset, chunk, 0, remaining); - System.arraycopy(crc, 0, chunk, remaining, 2); - } else { - chunk = Arrays.copyOfRange(pb, offset, offset + chunkSize); - offset += chunkSize; - } - if (isLast) { - offset = pb.length; - } + int offset = i * chunkSize; + byte[] chunk = Arrays.copyOfRange(payload, offset, Math.min(offset + chunkSize, payload.length)); byte[] frame = new byte[8 + chunk.length]; frame[0] = (byte) 0xaa; frame[1] = 0x21; diff --git a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawBleCommunicator.java b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawBleCommunicator.java index b93997ee..0ab64930 100644 --- a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawBleCommunicator.java +++ b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawBleCommunicator.java @@ -38,7 +38,8 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable { private static final int WRITE_TIMEOUT_MS = 2_000; private static final int PRELUDE_TIMEOUT_MS = 2_000; private static final int ACK_TIMEOUT_MS = 3_500; - private static final int HEARTBEAT_INTERVAL_MS = 5_000; + private static final int HEARTBEAT_READY_MS = 3_000; + private static final int HEARTBEAT_URGENT_MS = 6_000; private static final int BATTERY_REFRESH_INTERVAL_MS = 5 * 60_000; private static final int BATTERY_INPUT_QUIET_MS = 5_000; private static final int WINDOW_SIZE = 5; @@ -62,6 +63,7 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable { private final FaceclawBleManager bleManager; private final InterruptibleSleep interruptibleSleep = new InterruptibleSleep(); private final Object lock = new Object(); + private final Object nativeBridgeLock = new Object(); private final Handler mainHandler = new Handler(Looper.getMainLooper()); private final String rightAddress; private final String leftAddress; @@ -118,7 +120,7 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable { public FaceclawBleCommunicator(Context context, String rightAddress, String leftAddress, String ringAddress) { this.appContext = context.getApplicationContext(); - this.bleManager = new FaceclawBleManager(appContext); + this.bleManager = new FaceclawBleManager(appContext, false); this.bleManager.setListener(this); this.rightAddress = requireAddress("rightAddress", rightAddress); this.leftAddress = requireAddress("leftAddress", leftAddress); @@ -194,15 +196,17 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable { if (tileBmps == null || tileBmps.size() != DASHBOARD_TILES.length) { throw new IllegalArgumentException("exactly 4 tile bitmaps are required"); } - synchronized (desiredTilesLock) { - desiredTileBmps = emptyTileSet(); - for (int i = 0; i < DASHBOARD_TILES.length; i++) { - byte[] bmp = tileBmps.get(i); - desiredTileBmps[i] = bmp == null ? new byte[0] : Arrays.copyOf(bmp, bmp.length); + synchronized (nativeBridgeLock) { + synchronized (desiredTilesLock) { + desiredTileBmps = emptyTileSet(); + for (int i = 0; i < DASHBOARD_TILES.length; i++) { + byte[] bmp = tileBmps.get(i); + desiredTileBmps[i] = bmp == null ? new byte[0] : Arrays.copyOf(bmp, bmp.length); + } + desiredFingerprint = fingerprint == null ? "" : fingerprint; + desiredForceTiledCommit = forceTiledCommit; + desiredPaintMs = paintMs; } - desiredFingerprint = fingerprint == null ? "" : fingerprint; - desiredForceTiledCommit = forceTiledCommit; - desiredPaintMs = paintMs; } interruptibleSleep.interrupt(); } @@ -237,15 +241,17 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable { boolean forceTiledCommit, int paintMs ) { - synchronized (desiredTilesLock) { - desiredTileBmps = emptyTileSet(); - desiredTileBmps[0] = tile0Bmp == null ? new byte[0] : Arrays.copyOf(tile0Bmp, tile0Bmp.length); - desiredTileBmps[1] = tile1Bmp == null ? new byte[0] : Arrays.copyOf(tile1Bmp, tile1Bmp.length); - desiredTileBmps[2] = tile2Bmp == null ? new byte[0] : Arrays.copyOf(tile2Bmp, tile2Bmp.length); - desiredTileBmps[3] = tile3Bmp == null ? new byte[0] : Arrays.copyOf(tile3Bmp, tile3Bmp.length); - desiredFingerprint = fingerprint == null ? "" : fingerprint; - desiredForceTiledCommit = forceTiledCommit; - desiredPaintMs = paintMs; + synchronized (nativeBridgeLock) { + synchronized (desiredTilesLock) { + desiredTileBmps = emptyTileSet(); + desiredTileBmps[0] = tile0Bmp == null ? new byte[0] : Arrays.copyOf(tile0Bmp, tile0Bmp.length); + desiredTileBmps[1] = tile1Bmp == null ? new byte[0] : Arrays.copyOf(tile1Bmp, tile1Bmp.length); + desiredTileBmps[2] = tile2Bmp == null ? new byte[0] : Arrays.copyOf(tile2Bmp, tile2Bmp.length); + desiredTileBmps[3] = tile3Bmp == null ? new byte[0] : Arrays.copyOf(tile3Bmp, tile3Bmp.length); + desiredFingerprint = fingerprint == null ? "" : fingerprint; + desiredForceTiledCommit = forceTiledCommit; + desiredPaintMs = paintMs; + } } interruptibleSleep.interrupt(); } @@ -421,7 +427,7 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable { try { connectArm(rightAddress, true); connectArm(leftAddress, false); - if (!interruptibleSleep.sleep(800)) { + if (!sleepDuringConnectSettling(800)) { return; } sendPrelude(); @@ -450,6 +456,20 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable { } } //}}} + private boolean sleepDuringConnectSettling(long delayMs) throws InterruptedException { + long deadline = SystemClock.elapsedRealtime() + delayMs; + synchronized (lock) { + while (running && !userDisconnectRequested) { + long remaining = deadline - SystemClock.elapsedRealtime(); + if (remaining <= 0) { + return true; + } + lock.wait(Math.min(remaining, 100)); + } + return false; + } + } + private void connectArm(String address, boolean enableRenderNotify) { if (!bleManager.connect(address, CONNECT_TIMEOUT_MS)) { throw new IllegalStateException("connect failed: " + address); @@ -518,87 +538,139 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable { private long driveSession() { //Log.d(TAG, "driveSession called (pendingMessages.size=" + pendingMessages.size() + " inFlightMessages.size=" + inFlightMessages.size() + ")"); - synchronized (lock) { + while (true) { + OutboundMessage messageToWrite = null; long now = SystemClock.elapsedRealtime(); - if (!inFlightMessages.isEmpty()) { - OutboundMessage oldest = inFlightMessages.peekFirst(); - if (oldest != null && oldest.ackDeadlineAtMs <= now) { - Log.i(TAG, "message timed out: " + oldest.label); - inFlightMessages.removeFirst(); - logLine("message timed out: " + oldest.label); - releaseMagicLocked(oldest, "timeout"); - handleAckTimeoutLocked(oldest); + synchronized (lock) { + if (!inFlightMessages.isEmpty()) { + OutboundMessage oldest = inFlightMessages.peekFirst(); + if (oldest != null && oldest.ackDeadlineAtMs <= now) { + Log.i(TAG, "message timed out: " + oldest.label); + inFlightMessages.removeFirst(); + logLine("message timed out: " + oldest.label); + releaseMagicLocked(oldest, "timeout"); + handleAckTimeoutLocked(oldest); + return 0; + } + } + + if (!shutdownRequested && !fixedLayoutCreated && pendingMessages.isEmpty() && inFlightMessages.isEmpty()) { + Log.i(TAG, "enqueueing create layout"); + enqueueCreateLayoutLocked(); + } + if (!shutdownRequested && fixedLayoutCreated && !warmedUp && pendingMessages.isEmpty() && inFlightMessages.isEmpty()) { + Log.i(TAG, "enqueueing warmup"); + enqueueWarmupLocked(); + } + + boolean heartbeatEligible = !shutdownRequested && warmedUp && fixedLayoutCreated; + boolean heartbeatPending = heartbeatEligible && hasPendingOrInflightKindLocked("heartbeat"); + long heartbeatElapsedMs = now - lastHeartbeatQueuedAtMs; + boolean heartbeatReady = heartbeatEligible && heartbeatElapsedMs >= HEARTBEAT_READY_MS; + boolean heartbeatUrgent = heartbeatEligible && heartbeatElapsedMs >= HEARTBEAT_URGENT_MS; + boolean heartbeatBlocksLeftWrites = heartbeatReady || heartbeatPending; + + if (heartbeatReady && !heartbeatPending && inFlightMessages.isEmpty()) { + Log.i(TAG, "Writing heartbeat"); + messageToWrite = createHeartbeatMessageLocked(); + prepareMessageWriteLocked(messageToWrite, now); + lastHeartbeatQueuedAtMs = now; + } else if (heartbeatUrgent) { + return IDLE_SLEEP_MS; + } else if (sessionReady && inFlightMessages.size() < WINDOW_SIZE && !pendingMessages.isEmpty()) { + OutboundMessage pending = pendingMessages.peekFirst(); + if (heartbeatBlocksLeftWrites && pending != null && isLeftArmMessage(pending)) { + return IDLE_SLEEP_MS; + } + messageToWrite = pendingMessages.removeFirst(); + Log.i(TAG, "sending pending message: " + messageToWrite.label); + prepareMessageWriteLocked(messageToWrite, now); + } else if (!shutdownRequested && fixedLayoutCreated && warmedUp && pendingMessages.isEmpty() && inFlightMessages.isEmpty() + && now >= imageRetryAfterMs + && !getDesiredFingerprint().equals(displayedFingerprint)) { + Log.i(TAG, "Enqueued image update"); + enqueueDesiredImageLocked(); return 0; + } else if (shouldPollBatteryLocked(now)) { + Log.i(TAG, "Writing battery query"); + messageToWrite = createBatteryQueryMessageLocked(); + prepareMessageWriteLocked(messageToWrite, now); + lastBatteryRefreshAtMs = now; + } else if (!pendingMessages.isEmpty() || !inFlightMessages.isEmpty()) { + return IDLE_SLEEP_MS; + } else { + return 250; } } - if (!shutdownRequested && !fixedLayoutCreated && pendingMessages.isEmpty() && inFlightMessages.isEmpty()) { - Log.i(TAG, "enqueueing create layout"); - enqueueStartupProbeLocked(); - } - if (!shutdownRequested && fixedLayoutCreated && !warmedUp && pendingMessages.isEmpty() && inFlightMessages.isEmpty()) { - Log.i(TAG, "enqueueing warmup"); - enqueueWarmupLocked(); - } - - // We always write a heartbeat if it's due, even if this goes in between image fragments - if (!shutdownRequested && !hasPendingOrInflightKindLocked("heartbeat") && now - lastHeartbeatQueuedAtMs >= HEARTBEAT_INTERVAL_MS && warmedUp && fixedLayoutCreated) { - Log.i(TAG, "Writing heartbeat"); - writeHeartbeatLocked(); - return 0; - } - - while (sessionReady && inFlightMessages.size() < WINDOW_SIZE && !pendingMessages.isEmpty()) { - OutboundMessage message = pendingMessages.removeFirst(); - Log.i(TAG, "sending pending message: " + message.label); - if (!writeMessageLocked(message)) { - pendingMessages.addFirst(message); - handleTransportFailureLocked("write failed"); - return 0; + if (!writeMessageFrames(messageToWrite)) { + synchronized (lock) { + if (removePreparedMessageLocked(messageToWrite) || messageToWrite.magic == 0) { + handleTransportFailureLocked("write failed"); + } } - } - if (!shutdownRequested && fixedLayoutCreated && warmedUp && pendingMessages.isEmpty() && inFlightMessages.isEmpty() - && now >= imageRetryAfterMs - && !getDesiredFingerprint().equals(displayedFingerprint)) { - Log.i(TAG, "Enqueued image update"); - enqueueDesiredImageLocked(); return 0; } - if (shouldPollBatteryLocked(now)) { - Log.i(TAG, "Writing battery query"); - writeBatteryQueryLocked(now); - return 0; + synchronized (lock) { + completeMessageWriteLocked(messageToWrite); } - - if (!pendingMessages.isEmpty() || !inFlightMessages.isEmpty()) { - return IDLE_SLEEP_MS; - } - return 250; } } - private boolean writeMessageLocked(OutboundMessage message) { - long writeStartedAtMs = SystemClock.elapsedRealtime(); - String writeAddress = "image".equals(message.kind) ? leftAddress : rightAddress; - if (!bleManager.writeFrames( - writeAddress, - BleProtocol.WRITE_CHAR_UUID, - message.frames, - WRITE_TYPE, - WRITE_TIMEOUT_MS - )) { - return false; - } - message.writeStartedAtMs = writeStartedAtMs; - message.sentAtMs = SystemClock.elapsedRealtime(); - message.ackDeadlineAtMs = message.sentAtMs + message.ackTimeoutMs; + private void prepareMessageWriteLocked(OutboundMessage message, long now) { + message.writeStartedAtMs = now; + message.sentAtMs = now; + message.ackDeadlineAtMs = now + message.ackTimeoutMs + WRITE_TIMEOUT_MS; if (message.magic != 0) { inFlightMessages.addLast(message); } + if (message.imageUpdateId > 0 && message.imageMessageNumber == 1) { + ImageUpdateStats stats = imageUpdateStats.get(message.imageUpdateId); + if (stats != null && stats.firstWriteStartedAtMs <= 0) { + stats.firstWriteStartedAtMs = now; + } + } + } + + private boolean writeMessageFrames(OutboundMessage message) { + String writeAddress = isLeftArmMessage(message) ? leftAddress : rightAddress; + synchronized (nativeBridgeLock) { + return bleManager.writeFrames( + writeAddress, + BleProtocol.WRITE_CHAR_UUID, + message.frames, + WRITE_TYPE, + WRITE_TIMEOUT_MS + ); + } + } + + private boolean isLeftArmMessage(OutboundMessage message) { + return message != null && ("image".equals(message.kind) || "warmup".equals(message.kind)); + } + + private void completeMessageWriteLocked(OutboundMessage message) { + long sentAtMs = SystemClock.elapsedRealtime(); + message.sentAtMs = sentAtMs; + message.ackDeadlineAtMs = sentAtMs + message.ackTimeoutMs; logImageUpdateSendLandmarkLocked(message); - return true; + } + + private boolean removePreparedMessageLocked(OutboundMessage message) { + if (message == null || message.magic == 0) { + return false; + } + Iterator iterator = inFlightMessages.iterator(); + while (iterator.hasNext()) { + if (iterator.next() == message) { + iterator.remove(); + releaseMagicLocked(message, "write failed"); + return true; + } + } + return false; } private void resolveAckLocked(int sid, int magic, byte[] pb) { @@ -854,14 +926,16 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable { if (!synchronizedCommits) { for (TileImagePlan plan : changedTiles) { for (BleProtocol.ImageFragment fragment : plan.fragments) { - boolean requestAck = fragment.index % 2 == 1; + //boolean requestAck = fragment.index % 2 == 1; + boolean requestAck = true; enqueueImageFragmentLocked(plan, fragment, fingerprint, updateId, messageNumber++, messageCount, nextTransportSeq++, requestAck, true); } } } else { for (TileImagePlan plan : changedTiles) { for (int i = 0; i < plan.fragments.size() - 1; i++) { - boolean requestAck = i % 2 == 1; + //boolean requestAck = i % 2 == 1; + boolean requestAck = true; enqueueImageFragmentLocked(plan, plan.fragments.get(i), fingerprint, updateId, messageNumber++, messageCount, nextTransportSeq++, requestAck, false); } } @@ -907,9 +981,9 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable { pendingMessages.addLast(message); } - private void writeHeartbeatLocked() { + private OutboundMessage createHeartbeatMessageLocked() { int magic = nextMagic(); - OutboundMessage heartbeatMessage = new OutboundMessage( + return new OutboundMessage( "heartbeat", "heartbeat", BleProtocol.SID_EVENHUB, @@ -920,8 +994,6 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable { -1, null ); - writeMessageLocked(heartbeatMessage); - lastHeartbeatQueuedAtMs = SystemClock.elapsedRealtime(); } private boolean shouldPollBatteryLocked(long now) { @@ -933,9 +1005,9 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable { && (lastBatteryRefreshAtMs == 0 || now - lastBatteryRefreshAtMs >= BATTERY_REFRESH_INTERVAL_MS); } - private void writeBatteryQueryLocked(long now) { + private OutboundMessage createBatteryQueryMessageLocked() { int magic = nextMagic(); - OutboundMessage batteryMessage = new OutboundMessage( + return new OutboundMessage( "battery", "battery", BleProtocol.SID_UI_SETTING, @@ -951,9 +1023,6 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable { -1, null ); - if (writeMessageLocked(batteryMessage)) { - lastBatteryRefreshAtMs = now; - } } private boolean hasPendingOrInflightKindLocked(String kind) { @@ -1027,6 +1096,9 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable { displayedFingerprint = ""; displayedTileBmps = emptyTileSet(); imageRetryAfterMs = SystemClock.elapsedRealtime() + IMAGE_RETRY_DELAY_MS; + } else if ("heartbeat".equals(message.kind)) { + handleTransportFailureLocked("heartbeat ack timeout"); + return; } if (consecutiveAckTimeouts > MAX_CONSECUTIVE_ACK_TIMEOUTS) { @@ -1408,7 +1480,7 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable { } } - int allocate() { + synchronized int allocate() { Integer magic = available.pollFirst(); if (magic == null) { throw new IllegalStateException("no BLE magic values available"); @@ -1417,7 +1489,7 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable { return magic; } - void release(int sid, int magic, String label, String reason) { + synchronized void release(int sid, int magic, String label, String reason) { if (magic < MIN_MAGIC || magic > MAX_MAGIC) { return; } @@ -1429,7 +1501,7 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable { available.addLast(magic); } - ReleaseRecord getReleaseRecord(int sid, int magic) { + synchronized ReleaseRecord getReleaseRecord(int sid, int magic) { return releaseRecords.get(key(sid, magic)); } diff --git a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawBleManager.java b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawBleManager.java index 7a1004fb..b7945b0b 100644 --- a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawBleManager.java +++ b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawBleManager.java @@ -18,14 +18,9 @@ import android.util.Log; import java.util.List; import java.util.UUID; -import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicReference; @SuppressLint("MissingPermission") public class FaceclawBleManager { @@ -34,10 +29,11 @@ public class FaceclawBleManager { private final Context context; private final BluetoothAdapter bluetoothAdapter; + private final boolean dispatchListenerOnMain; private final Handler mainHandler = new Handler(Looper.getMainLooper()); private final ConcurrentHashMap gattClients = new ConcurrentHashMap<>(); - private final ConcurrentHashMap writeLocks = new ConcurrentHashMap<>(); + private final ConcurrentHashMap gattLocks = new ConcurrentHashMap<>(); private final ConcurrentHashMap connectLatches = new ConcurrentHashMap<>(); private final ConcurrentHashMap connectResults = new ConcurrentHashMap<>(); @@ -57,7 +53,12 @@ public class FaceclawBleManager { private volatile FaceclawBleListener listener; public FaceclawBleManager(Context context) { + this(context, true); + } + + public FaceclawBleManager(Context context, boolean dispatchListenerOnMain) { this.context = context.getApplicationContext(); + this.dispatchListenerOnMain = dispatchListenerOnMain; BluetoothManager bluetoothManager = (BluetoothManager) this.context.getSystemService(Context.BLUETOOTH_SERVICE); if (bluetoothManager == null || bluetoothManager.getAdapter() == null) { throw new IllegalStateException("Bluetooth adapter unavailable"); @@ -73,57 +74,83 @@ public class FaceclawBleManager { if (address == null || address.trim().isEmpty()) { throw new IllegalArgumentException("address is required"); } - BluetoothGatt existing = gattClients.get(address); - if (existing != null) { - return true; - } - - final BluetoothDevice device = bluetoothAdapter.getRemoteDevice(address); - if (device == null) { - throw new IllegalArgumentException("remote device not found: " + address); - } - CountDownLatch latch = new CountDownLatch(1); connectLatches.put(address, latch); connectResults.remove(address); - BluetoothGatt gatt = runOnMainSync(() -> device.connectGatt( - context, - false, - gattCallback, - BluetoothDevice.TRANSPORT_LE, - BluetoothDevice.PHY_LE_2M|BluetoothDevice.PHY_LE_1M - )); + Object gattLock = gattLock(address); + BluetoothGatt gatt; + synchronized (gattLock) { + BluetoothGatt existing = gattClients.get(address); + if (existing != null) { + connectLatches.remove(address); + return true; + } + + final BluetoothDevice device = bluetoothAdapter.getRemoteDevice(address); + if (device == null) { + connectLatches.remove(address); + throw new IllegalArgumentException("remote device not found: " + address); + } + + gatt = device.connectGatt( + context, + false, + gattCallback, + BluetoothDevice.TRANSPORT_LE, + BluetoothDevice.PHY_LE_2M|BluetoothDevice.PHY_LE_1M + ); + if (gatt != null) { + gattClients.put(address, gatt); + } + } if (gatt == null) { connectLatches.remove(address); return false; } - gattClients.put(address, gatt); if (!awaitLatch(latch, timeoutMs)) { connectLatches.remove(address); connectResults.remove(address); + synchronized (gattLock) { + gattClients.remove(address, gatt); + gatt.disconnect(); + gatt.close(); + } return false; } - gatt.readPhy(); Boolean connected = connectResults.remove(address); connectLatches.remove(address); - return Boolean.TRUE.equals(connected); + boolean ok = Boolean.TRUE.equals(connected); + if (ok) { + synchronized (gattLock) { + BluetoothGatt current = gattClients.get(address); + if (current == gatt) { + gatt.readPhy(); + } + } + } + return ok; } public boolean requestConnectionPriority(String address, int priority) { - BluetoothGatt gatt = requireGatt(address); - return runOnMainSync(() -> gatt.requestConnectionPriority(priority)); + synchronized (gattLock(address)) { + BluetoothGatt gatt = requireGatt(address); + return gatt.requestConnectionPriority(priority); + } } public boolean requestMtu(String address, int mtu, int timeoutMs) { - BluetoothGatt gatt = requireGatt(address); CountDownLatch latch = new CountDownLatch(1); mtuLatches.put(address, latch); mtuStatuses.remove(address); - boolean started = runOnMainSync(() -> gatt.requestMtu(mtu)); + boolean started; + synchronized (gattLock(address)) { + BluetoothGatt gatt = requireGatt(address); + started = gatt.requestMtu(mtu); + } if (!started) { mtuLatches.remove(address); return false; @@ -139,12 +166,15 @@ public class FaceclawBleManager { } public boolean discoverServices(String address, int timeoutMs) { - BluetoothGatt gatt = requireGatt(address); CountDownLatch latch = new CountDownLatch(1); servicesLatches.put(address, latch); servicesStatuses.remove(address); - boolean started = runOnMainSync(gatt::discoverServices); + boolean started; + synchronized (gattLock(address)) { + BluetoothGatt gatt = requireGatt(address); + started = gatt.discoverServices(); + } if (!started) { servicesLatches.remove(address); return false; @@ -160,29 +190,36 @@ public class FaceclawBleManager { } public boolean enableNotifications(String address, String characteristicUuid, boolean enable, int timeoutMs) { - BluetoothGatt gatt = requireGatt(address); - BluetoothGattCharacteristic characteristic = requireCharacteristic(gatt, characteristicUuid); - - boolean notificationSet = runOnMainSync(() -> gatt.setCharacteristicNotification(characteristic, enable)); - if (!notificationSet) { - return false; - } - - BluetoothGattDescriptor descriptor = characteristic.getDescriptor(BleProtocol.CCCD_UUID); - if (descriptor == null) { - return true; - } - CountDownLatch latch = new CountDownLatch(1); descriptorLatches.put(address, latch); descriptorStatuses.remove(address); - descriptor.setValue(enable - ? BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE - : BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE); - boolean started = runOnMainSync(() -> gatt.writeDescriptor(descriptor)); + boolean started; + synchronized (gattLock(address)) { + BluetoothGatt gatt = requireGatt(address); + BluetoothGattCharacteristic characteristic = requireCharacteristic(gatt, characteristicUuid); + + boolean notificationSet = gatt.setCharacteristicNotification(characteristic, enable); + if (!notificationSet) { + descriptorLatches.remove(address); + return false; + } + + BluetoothGattDescriptor descriptor = characteristic.getDescriptor(BleProtocol.CCCD_UUID); + if (descriptor == null) { + descriptorLatches.remove(address); + return true; + } + + descriptor.setValue(enable + ? BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE + : BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE); + started = gatt.writeDescriptor(descriptor); + } + if (!started) { descriptorLatches.remove(address); + descriptorStatuses.remove(address); return false; } if (!awaitLatch(latch, timeoutMs)) { @@ -207,14 +244,16 @@ public class FaceclawBleManager { } Log.i(TAG, "Called writeFrames with writeType=" + writeType + ", " + frames.size() + " frames totaling " + frames.stream().mapToInt(frame -> frame != null ? frame.length : 0).sum() + " bytes"); - BluetoothGatt gatt = requireGatt(address); - BluetoothGattCharacteristic characteristic = requireCharacteristic(gatt, characteristicUuid); + synchronized (gattLock(address)) { + BluetoothGatt gatt = requireGatt(address); + BluetoothGattCharacteristic characteristic = requireCharacteristic(gatt, characteristicUuid); - for (int i = 0; i < frames.size(); i++) { - Log.i(TAG, "writeFrames starting frame " + i); - byte[] frame = frames.get(i); - if (!startWrite(gatt, characteristic, address, frame, writeType, timeoutMs)) { - return false; + for (int i = 0; i < frames.size(); i++) { + Log.i(TAG, "writeFrames starting frame " + i); + byte[] frame = frames.get(i); + if (!startWrite(gatt, characteristic, address, frame, writeType, timeoutMs)) { + return false; + } } } return true; @@ -228,41 +267,77 @@ public class FaceclawBleManager { int writeType, int timeoutMs ) { - boolean retry = false; int retryCount = 0; while (true) { + CountDownLatch latch = new CountDownLatch(1); + writeLatches.put(address, latch); + writeStatuses.remove(address); + long currentTime = System.currentTimeMillis(); int result = gatt.writeCharacteristic(characteristic, data, writeType); long timeAsleep = System.currentTimeMillis() - currentTime; //Log.i(TAG, "writeCharacteristic: spent " + timeAsleep + "ms"); if (result == android.bluetooth.BluetoothStatusCodes.ERROR_GATT_WRITE_REQUEST_BUSY) { - if (++retryCount < 25) { - try { - long currentTime2 = System.currentTimeMillis(); - Thread.sleep(1); - long timeAsleep2 = System.currentTimeMillis() - currentTime2; - //Log.i(TAG, "writeCharacteristic: slept for " + timeAsleep2 + "ms"); - } catch (InterruptedException e) {} - } else { + writeLatches.remove(address, latch); + writeStatuses.remove(address); + if (!sleepBeforeWriteRetry(address, "busy", retryCount++)) { return false; } + continue; } else { //Log.i(TAG, "writeCharacteristic with writeType=" + writeType + " result=" + result + " retryCount=" + retryCount); - return result == android.bluetooth.BluetoothStatusCodes.SUCCESS; + if (result != android.bluetooth.BluetoothStatusCodes.SUCCESS) { + writeLatches.remove(address, latch); + writeStatuses.remove(address); + if (!sleepBeforeWriteRetry(address, "start result=" + result, retryCount++)) { + return false; + } + continue; + } + if (!awaitLatch(latch, timeoutMs)) { + writeLatches.remove(address, latch); + writeStatuses.remove(address); + return false; + } + Integer status = writeStatuses.remove(address); + writeLatches.remove(address); + if (status != null && status == BluetoothGatt.GATT_SUCCESS) { + return true; + } + if (!sleepBeforeWriteRetry(address, "callback status=" + status, retryCount++)) { + return false; + } } } } - public void disconnect(String address) { - BluetoothGatt gatt = gattClients.remove(address); - if (gatt == null) { - return; + private boolean sleepBeforeWriteRetry(String address, String reason, int retryIndex) { + if (retryIndex >= WRITE_RETRY_DELAYS_MS.length) { + Log.w(TAG, "writeCharacteristic retry exhausted: address=" + address + " reason=" + reason); + return false; } - runOnMainAsync(() -> { + int delayMs = WRITE_RETRY_DELAYS_MS[retryIndex]; + Log.w(TAG, "writeCharacteristic retry: address=" + address + " reason=" + reason + " delayMs=" + delayMs); + try { + Thread.sleep(delayMs); + return true; + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return false; + } + } + + public void disconnect(String address) { + Object gattLock = gattLock(address); + synchronized (gattLock) { + BluetoothGatt gatt = gattClients.remove(address); + if (gatt == null) { + return; + } gatt.disconnect(); gatt.close(); - }); + } } public void close() { @@ -299,6 +374,10 @@ public class FaceclawBleManager { } } + private Object gattLock(String address) { + return gattLocks.computeIfAbsent(address, ignored -> new Object()); + } + private void runOnMainAsync(Runnable runnable) { if (Looper.myLooper() == Looper.getMainLooper()) { runnable.run(); @@ -307,34 +386,12 @@ public class FaceclawBleManager { } } - private T runOnMainSync(Callable callable) { - if (Looper.myLooper() == Looper.getMainLooper()) { - try { - return callable.call(); - } catch (Exception e) { - throw new RuntimeException(e); - } + private void dispatchListener(Runnable runnable) { + if (dispatchListenerOnMain) { + runOnMainAsync(runnable); + } else { + runnable.run(); } - - CountDownLatch latch = new CountDownLatch(1); - AtomicReference result = new AtomicReference<>(); - AtomicReference error = new AtomicReference<>(); - - mainHandler.post(() -> { - try { - result.set(callable.call()); - } catch (Exception e) { - error.set(new RuntimeException(e)); - } finally { - latch.countDown(); - } - }); - - awaitLatch(latch, 10_000); - if (error.get() != null) { - throw error.get(); - } - return result.get(); } private final BluetoothGattCallback gattCallback = new BluetoothGattCallback() { @@ -358,9 +415,11 @@ public class FaceclawBleManager { if (latch != null) { latch.countDown(); } - gattClients.remove(address); - writeLocks.remove(address); - runOnMainAsync(gatt::close); + Object gattLock = gattLock(address); + synchronized (gattLock) { + gattClients.remove(address, gatt); + gatt.close(); + } dispatchConnectionState(address, false); } } @@ -428,7 +487,7 @@ public class FaceclawBleManager { if (current == null) { return; } - runOnMainAsync(() -> current.onConnectionStateChange(address, connected)); + dispatchListener(() -> current.onConnectionStateChange(address, connected)); } private void dispatchNotification(String address, String characteristicUuid, byte[] data) { @@ -438,6 +497,6 @@ public class FaceclawBleManager { return; } byte[] copy = data != null ? data.clone() : new byte[0]; - runOnMainAsync(() -> current.onNotification(address, characteristicUuid, copy)); + dispatchListener(() -> current.onNotification(address, characteristicUuid, copy)); } } diff --git a/app/g2/dashboard-controller.ts b/app/g2/dashboard-controller.ts index 82bef9cb..7829668a 100644 --- a/app/g2/dashboard-controller.ts +++ b/app/g2/dashboard-controller.ts @@ -50,6 +50,9 @@ type LogLevel = "debug"|"info"|"warn"|"error"; const CONTAINER_NAME = "dashboard"; const DASHBOARD_INTERVAL_MS = 60_000; const SCREEN_TIMEOUT_CHECK_MS = 1_000; +const STOPWATCH_RENDER_INTERVAL_MS = 100; +const FOREGROUND_NOTIFICATION_MIN_UPDATE_MS = 30_000; +const FRAME_TRANSMIT_BACKPRESSURE_TIMEOUT_MS = 6_000; const EVEN_APP_DETECTED_MESSAGE = "The Even Realities app appears to be running. If Faceclaw has trouble connecting, open its app settings and force stop it."; @@ -114,6 +117,7 @@ class DashboardController { private communicator: FaceclawCommunicatorBridge | null = null; private dashboardTimer: ReturnType | null = null; private screenTimeoutTimer: ReturnType | null = null; + private stopwatchRenderTimer: ReturnType | null = null; private offState: (() => void) | null = null; private offLog: (() => void) | null = null; private offRing: (() => void) | null = null; @@ -129,6 +133,7 @@ class DashboardController { private renderInProgress = false; private renderQueued = false; private queuedRenderReason: "initial" | "interval" = "interval"; + private lastForegroundNotificationUpdateAtMs = 0; constructor() { setDashboardActions({ @@ -139,6 +144,7 @@ class DashboardController { startNightscoutApiTokenEdit: () => this.startNightscoutApiTokenEdit(), endTextSettingEdit: () => this.endTextSettingEdit(), setVoiceControlEnabled: (enabled) => this.setVoiceControlEnabled(enabled), + setStopwatchRenderActive: (active) => this.setStopwatchRenderActive(active), }); } @@ -354,6 +360,7 @@ class DashboardController { this.screenTimeoutTimer = setInterval(() => { if (this.phase !== "connected" || !this.communicator) return; if (!applyDashboardScreenTimeout()) return; + this.setStopwatchRenderActive(false); this.endTextSettingEdit(); void this.requestRender("interval").catch((error) => { const message = this.formatError(error); @@ -586,14 +593,13 @@ class DashboardController { const forceTiledCommit = consumeDashboardTiledWakePaint(); const fingerprint = image.fingerprint(); const tiles = image.toEvenHubTiles().map((tile) => tile.bmp); + this.setDisplayPreview(grayImageToPreviewSource(image)); if (this.communicator) { await this.communicator.submitDashboardImage(tiles, fingerprint, forceTiledCommit, paintMs); + await this.communicator.waitForNextFrameMetrics(FRAME_TRANSMIT_BACKPRESSURE_TIMEOUT_MS); } - this.setDisplayPreview(grayImageToPreviewSource(image)); - if (this.phase === "connected") { - updateForegroundNotification(`Connected`); - } + this.updateConnectedForegroundNotification(); this.appendLog(`${reason === "initial" ? "initial" : "scheduled"} dashboard image queued`); } @@ -652,12 +658,26 @@ class DashboardController { private startVoiceControlIfEnabled(): void { if (!this.communicator) return; if (!isDashboardVoiceControlEnabled()) return; - if (this.phase === "connected") { - updateForegroundNotification("Connected"); - } + this.updateConnectedForegroundNotification(); voiceControlBridge.start(); } + private setStopwatchRenderActive(active: boolean): void { + if (!active || this.phase !== "connected" || !this.communicator) { + if (this.stopwatchRenderTimer) { + clearInterval(this.stopwatchRenderTimer); + this.stopwatchRenderTimer = null; + } + return; + } + if (this.stopwatchRenderTimer) return; + this.stopwatchRenderTimer = setInterval(() => { + void this.requestRender("interval").catch((error) => { + this.appendLog(`stopwatch render failed: ${this.formatError(error)}`); + }); + }, STOPWATCH_RENDER_INTERVAL_MS); + } + private clearDashboardTimer(): void { if (this.dashboardTimer) { clearInterval(this.dashboardTimer); @@ -667,6 +687,10 @@ class DashboardController { clearInterval(this.screenTimeoutTimer); this.screenTimeoutTimer = null; } + if (this.stopwatchRenderTimer) { + clearInterval(this.stopwatchRenderTimer); + this.stopwatchRenderTimer = null; + } } private setPhase(phase: ConnectionPhase): void { @@ -681,6 +705,14 @@ class DashboardController { this.emit(); } + private updateConnectedForegroundNotification(): void { + if (this.phase !== "connected") return; + const now = Date.now(); + if (now - this.lastForegroundNotificationUpdateAtMs < FOREGROUND_NOTIFICATION_MIN_UPDATE_MS) return; + this.lastForegroundNotificationUpdateAtMs = now; + updateForegroundNotification("Connected"); + } + private formatFrameMetrics(metrics: FrameMetrics): string { return `paint=${Math.round(metrics.paintMs)}ms, transmit=${Math.round(metrics.transmitMs)}ms, tiles=${Math.round(metrics.tileCount)}`; } diff --git a/app/native/faceclaw-communicator.ts b/app/native/faceclaw-communicator.ts index 1403d7fa..4dde93ff 100644 --- a/app/native/faceclaw-communicator.ts +++ b/app/native/faceclaw-communicator.ts @@ -65,6 +65,8 @@ function nonNegativeNumber(value: number): number { export class FaceclawCommunicatorBridge { private readonly communicator: any; private readonly listenerProxy: any; + private javaCallQueue: Promise = Promise.resolve(); + private readonly frameMetricWaiters = new Set<(metrics: FrameMetrics) => void>(); private readonly logListeners = new Set<(line: string) => void>(); private readonly stateListeners = new Set<(state: CommunicatorState) => void>(); private readonly ringListeners = new Set<(event: RawInputEvent) => void>(); @@ -84,18 +86,14 @@ export class FaceclawCommunicatorBridge { ); this.listenerProxy = new com.faceclaw.app.FaceclawBleCommunicatorListener({ onLog: (line: string) => { - for (const listener of this.logListeners) { - listener(String(line)); - } + this.emitAsync(this.logListeners, String(line)); }, onStateChange: (phase: string, status: string) => { const state = { phase: String(phase) as CommunicatorPhase, status: String(status), }; - for (const listener of this.stateListeners) { - listener(state); - } + this.emitAsync(this.stateListeners, state); }, onRingEvent: ( kind: string, @@ -111,23 +109,17 @@ export class FaceclawCommunicatorBridge { eventSource: Number(eventSource), systemExitReasonCode: Number(systemExitReasonCode), }; - for (const listener of this.ringListeners) { - listener(event); - } + this.emitAsync(this.ringListeners, event); }, onBatteryState: (headsetBattery: number, headsetCharging: number) => { const state = { battery: Number(headsetBattery), chargingStatus: Number(headsetCharging), }; - for (const listener of this.batteryListeners) { - listener(state); - } + this.emitAsync(this.batteryListeners, state); }, onEvenAppConflict: (message: string) => { - for (const listener of this.evenAppConflictListeners) { - listener(String(message)); - } + this.emitAsync(this.evenAppConflictListeners, String(message)); }, onFrameMetrics: (paintMs: number, transmitMs: number, tileCount: number) => { const metrics = { @@ -135,14 +127,46 @@ export class FaceclawCommunicatorBridge { transmitMs: nonNegativeNumber(transmitMs), tileCount: nonNegativeNumber(tileCount), }; - for (const listener of this.frameMetricsListeners) { - listener(metrics); + const waiters = Array.from(this.frameMetricWaiters); + this.frameMetricWaiters.clear(); + for (const waiter of waiters) { + setTimeout(() => waiter(metrics), 0); } + this.emitAsync(this.frameMetricsListeners, metrics); }, }); this.communicator.setListener(this.listenerProxy); } + private emitAsync(listeners: Set<(value: T) => void>, value: T): void { + const snapshot = Array.from(listeners); + setTimeout(() => { + for (const listener of snapshot) { + listener(value); + } + }, 0); + } + + private enqueueJavaCall(operation: () => T): Promise { + const run = () => + new Promise((resolve, reject) => { + setTimeout(() => { + try { + resolve(operation()); + } catch (error) { + reject(error); + } + }, 0); + }); + + const result = this.javaCallQueue.then(run, run); + this.javaCallQueue = result.then( + () => undefined, + () => undefined, + ); + return result; + } + onLog(listener: (line: string) => void): () => void { this.logListeners.add(listener); return () => this.logListeners.delete(listener); @@ -173,34 +197,57 @@ export class FaceclawCommunicatorBridge { return () => this.frameMetricsListeners.delete(listener); } + waitForNextFrameMetrics(timeoutMs: number): Promise { + const delayMs = Math.max(1, Math.round(nonNegativeNumber(timeoutMs))); + return new Promise((resolve) => { + let settled = false; + let timeoutHandle: ReturnType | null = null; + const complete = (metrics: FrameMetrics | null) => { + if (settled) return; + settled = true; + if (timeoutHandle !== null) { + clearTimeout(timeoutHandle); + } + this.frameMetricWaiters.delete(onMetrics); + resolve(metrics); + }; + const onMetrics = (metrics: FrameMetrics) => complete(metrics); + this.frameMetricWaiters.add(onMetrics); + timeoutHandle = setTimeout(() => complete(null), delayMs); + }); + } + async start(): Promise { - this.communicator.start(); + await this.enqueueJavaCall(() => this.communicator.start()); } async submitDashboardImage(tileBmps: Uint8Array[], fingerprint: string, forceTiledCommit = false, paintMs = -1): Promise { if (tileBmps.length !== 4) { throw new Error(`expected 4 dashboard tiles, got ${tileBmps.length}`); } - this.communicator.submitDashboardImage4( - toJavaByteArray(tileBmps[0]!), - toJavaByteArray(tileBmps[1]!), - toJavaByteArray(tileBmps[2]!), - toJavaByteArray(tileBmps[3]!), - fingerprint, - forceTiledCommit, - Math.round(nonNegativeNumber(paintMs)), - ); + const tileSnapshots = tileBmps.map((tile) => new Uint8Array(tile)); + await this.enqueueJavaCall(() => { + this.communicator.submitDashboardImage4( + toJavaByteArray(tileSnapshots[0]!), + toJavaByteArray(tileSnapshots[1]!), + toJavaByteArray(tileSnapshots[2]!), + toJavaByteArray(tileSnapshots[3]!), + fingerprint, + forceTiledCommit, + Math.round(nonNegativeNumber(paintMs)), + ); + }); } async disconnect(): Promise { - this.communicator.disconnect(); + await this.enqueueJavaCall(() => this.communicator.disconnect()); } async sendShutdown(exitMode = 0): Promise { - return Boolean(this.communicator.sendShutdown(exitMode)); + return this.enqueueJavaCall(() => Boolean(this.communicator.sendShutdown(exitMode))); } async close(): Promise { - this.communicator.close(); + await this.enqueueJavaCall(() => this.communicator.close()); } } diff --git a/app/ui/dashboard-plugins.ts b/app/ui/dashboard-plugins.ts index a231e139..c99373e7 100644 --- a/app/ui/dashboard-plugins.ts +++ b/app/ui/dashboard-plugins.ts @@ -149,6 +149,7 @@ const PLUGIN_MAP = new Map( const nightscoutLargeFont = loadEmbeddedTerminus24(); const NIGHTSCOUT_STALE_MS = 15 * 60 * 1000; const NIGHTSCOUT_GRAPH_WINDOW_MS = 2 * 60 * 60 * 1000; +const NIGHTSCOUT_GRAPH_TIME_QUANTUM_MS = 60 * 1000; export function listDashboardPlugins(): DashboardPlugin[] { return [...DASHBOARD_PLUGINS]; @@ -294,8 +295,12 @@ function drawNightscoutGraph( return; } - const windowStartMs = nowMs - NIGHTSCOUT_GRAPH_WINDOW_MS; - const visibleHistory = nightscout.history.filter((point) => point.timestampMs >= windowStartMs && point.timestampMs <= nowMs); + const graphNowMs = minuteBucketTimestampMs(nowMs); + const windowStartMs = graphNowMs - NIGHTSCOUT_GRAPH_WINDOW_MS; + const visibleHistory = nightscout.history.filter((point) => { + const pointTimestampMs = minuteBucketTimestampMs(point.timestampMs); + return pointTimestampMs >= windowStartMs && pointTimestampMs <= graphNowMs; + }); if (visibleHistory.length === 0) { return; } @@ -308,18 +313,14 @@ function drawNightscoutGraph( const paddedMax = max + range * 0.1; image.drawRect(bounds.x, bounds.y, bounds.width, bounds.height, 56); - drawNightscoutBasalOverlay(image, bounds, nightscout.basal, nowMs); + drawNightscoutBasalOverlay(image, bounds, nightscout.basal, graphNowMs); drawNightscoutReferenceLine(image, bounds, paddedMin, paddedMax, 60, 40); drawNightscoutReferenceLine(image, bounds, paddedMin, paddedMax, 100, 40); drawNightscoutReferenceLine(image, bounds, paddedMin, paddedMax, 180, 40); const plotted = visibleHistory.map((point) => ({ point, - x: - bounds.x + - Math.round( - ((point.timestampMs - windowStartMs) / Math.max(1, NIGHTSCOUT_GRAPH_WINDOW_MS)) * Math.max(1, bounds.width - 1), - ), + x: timeToGraphX(bounds, windowStartMs, point.timestampMs), y: bounds.y + bounds.height - @@ -343,8 +344,8 @@ function drawNightscoutGraph( image.fillRect(current.x - 1, current.y - 1, 2, 2, 220); } } - drawNightscoutCarbMarkers(image, bounds, font, nightscout.carbs, nowMs); - drawNightscoutBolusMarkers(image, bounds, font, nightscout.boluses, nowMs); + drawNightscoutCarbMarkers(image, bounds, font, nightscout.carbs, graphNowMs); + drawNightscoutBolusMarkers(image, bounds, font, nightscout.boluses, graphNowMs); } function drawNightscoutBasalOverlay( @@ -353,9 +354,12 @@ function drawNightscoutBasalOverlay( basalEvents: NightscoutState["basal"], nowMs: number, ): void { - const windowStartMs = nowMs - NIGHTSCOUT_GRAPH_WINDOW_MS; + const graphNowMs = minuteBucketTimestampMs(nowMs); + const windowStartMs = graphNowMs - NIGHTSCOUT_GRAPH_WINDOW_MS; const visibleEvents = basalEvents.filter( - (event) => event.timestampMs + event.durationMinutes * 60_000 >= windowStartMs && event.timestampMs <= nowMs, + (event) => + minuteBucketTimestampMs(event.timestampMs + event.durationMinutes * 60_000) >= windowStartMs && + minuteBucketTimestampMs(event.timestampMs) <= graphNowMs, ); if (visibleEvents.length === 0) { return; @@ -367,8 +371,8 @@ function drawNightscoutBasalOverlay( const overlayHeight = Math.max(8, Math.min(18, Math.floor(bounds.height * 0.22))); const bottomY = bounds.y + bounds.height - 2; for (const event of visibleEvents) { - const startMs = Math.max(windowStartMs, event.timestampMs); - const endMs = Math.min(nowMs, event.timestampMs + event.durationMinutes * 60_000); + const startMs = Math.max(windowStartMs, minuteBucketTimestampMs(event.timestampMs)); + const endMs = Math.min(graphNowMs, minuteBucketTimestampMs(event.timestampMs + event.durationMinutes * 60_000)); if (endMs <= startMs) { continue; } @@ -386,13 +390,15 @@ function drawNightscoutCarbMarkers( carbEvents: NightscoutState["carbs"], nowMs: number, ): void { - const windowStartMs = nowMs - NIGHTSCOUT_GRAPH_WINDOW_MS; + const graphNowMs = minuteBucketTimestampMs(nowMs); + const windowStartMs = graphNowMs - NIGHTSCOUT_GRAPH_WINDOW_MS; const baselineY = bounds.y + bounds.height - 2; for (const event of carbEvents) { - if (event.timestampMs < windowStartMs || event.timestampMs > nowMs) { + const eventTimestampMs = minuteBucketTimestampMs(event.timestampMs); + if (eventTimestampMs < windowStartMs || eventTimestampMs > graphNowMs) { continue; } - const x = timeToGraphX(bounds, windowStartMs, event.timestampMs); + const x = timeToGraphX(bounds, windowStartMs, eventTimestampMs); image.drawLine(x, baselineY, x, baselineY - 6, 150); drawTextCentered(image, font, x, Math.max(bounds.y + 2, baselineY - 18), `${Math.round(event.carbs)}`, 150, bounds); } @@ -405,13 +411,15 @@ function drawNightscoutBolusMarkers( bolusEvents: NightscoutState["boluses"], nowMs: number, ): void { - const windowStartMs = nowMs - NIGHTSCOUT_GRAPH_WINDOW_MS; + const graphNowMs = minuteBucketTimestampMs(nowMs); + const windowStartMs = graphNowMs - NIGHTSCOUT_GRAPH_WINDOW_MS; const topY = bounds.y + 1; for (const event of bolusEvents) { - if (event.timestampMs < windowStartMs || event.timestampMs > nowMs) { + const eventTimestampMs = minuteBucketTimestampMs(event.timestampMs); + if (eventTimestampMs < windowStartMs || eventTimestampMs > graphNowMs) { continue; } - const x = timeToGraphX(bounds, windowStartMs, event.timestampMs); + const x = timeToGraphX(bounds, windowStartMs, eventTimestampMs); image.drawLine(x, topY, x, topY + 6, 144); if (event.insulin >= 1) { drawTextCentered( @@ -446,12 +454,19 @@ function timeToGraphX( windowStartMs: number, timestampMs: number, ): number { + const graphTimestampMs = minuteBucketTimestampMs(timestampMs); return ( bounds.x + - Math.round(((timestampMs - windowStartMs) / Math.max(1, NIGHTSCOUT_GRAPH_WINDOW_MS)) * Math.max(1, bounds.width - 1)) + Math.round( + ((graphTimestampMs - windowStartMs) / Math.max(1, NIGHTSCOUT_GRAPH_WINDOW_MS)) * Math.max(1, bounds.width - 1), + ) ); } +function minuteBucketTimestampMs(timestampMs: number): number { + return Math.floor(timestampMs / NIGHTSCOUT_GRAPH_TIME_QUANTUM_MS) * NIGHTSCOUT_GRAPH_TIME_QUANTUM_MS; +} + function drawNightscoutReferenceLine( image: GrayImage, bounds: { x: number; y: number; width: number; height: number }, diff --git a/app/ui/dashboard.ts b/app/ui/dashboard.ts index 93c79bb0..df9a651f 100644 --- a/app/ui/dashboard.ts +++ b/app/ui/dashboard.ts @@ -84,6 +84,7 @@ const dashboardActions: LayerActions = { startNightscoutApiTokenEdit: () => {}, endTextSettingEdit: () => {}, setVoiceControlEnabled: () => {}, + setStopwatchRenderActive: () => {}, }; const dashboardFont = loadEmbeddedTerminus12(); const dashboardSystemFont = loadEmbeddedTerminus16(); @@ -443,12 +444,12 @@ function createRootMenuLayer(): MenuLayer { return new RootMenuLayer( "Menu", [ - /*{ + { label: "Apps", onSelect: (ctx) => { ctx.stack.push(createAppsMenuLayer()); }, - },*/ + }, { label: "Settings", onSelect: (ctx) => { @@ -476,7 +477,80 @@ function createRootMenuLayer(): MenuLayer { } function createAppsMenuLayer(): MenuLayer { - return new MenuLayer("Apps", [], TOP_LEFT_MENU_LAYOUT); + return new MenuLayer( + "Apps", + [ + { + label: "Stopwatch", + onSelect: (ctx) => { + ctx.stack.push(new StopwatchLayer()); + void ctx.actions.setStopwatchRenderActive(true); + }, + }, + ], + TOP_LEFT_MENU_LAYOUT, + ); +} + +class StopwatchLayer implements Layer { + private readonly startedAtMs = Date.now(); + private pausedAtMs: number | null = null; + private pausedDurationMs = 0; + + paint(ctx: LayerContext): GrayImage { + const image = new GrayImage(G2_LENS_WIDTH, G2_LENS_HEIGHT, 0); + const elapsedMs = this.elapsedMs(); + const timeLabel = formatStopwatchElapsed(elapsedMs); + const stateLabel = this.pausedAtMs === null ? "Running" : "Paused"; + + image.drawRect(12, 12, G2_LENS_WIDTH - 24, G2_LENS_HEIGHT - 24, 52); + image.drawText(ctx.font, 24, 24, "Stopwatch", 180); + image.drawText(ctx.font, G2_LENS_WIDTH - 114, 24, stateLabel, this.pausedAtMs === null ? 200 : 120); + + const timeX = Math.max(0, ((G2_LENS_WIDTH - dashboardSystemFont.measureText(timeLabel)) / 2) | 0); + image.drawText(dashboardSystemFont, timeX, 106, timeLabel, 245); + image.drawText(ctx.font, 126, 160, "Click: pause / resume", 150); + image.drawText(ctx.font, 126, 178, "Double-click: back", 120); + image.drawText(ctx.font, 126, 214, "Renders requested every 100ms", 110); + return image; + } + + handleInput(event: DashboardInputEvent, ctx: LayerContext): void { + if (event.type === "double-click") { + void ctx.actions.setStopwatchRenderActive(false); + ctx.stack.pop(); + return; + } + if (event.type === "click") { + if (this.pausedAtMs === null) { + this.pausedAtMs = Date.now(); + void ctx.actions.setStopwatchRenderActive(false); + } else { + this.pausedDurationMs += Date.now() - this.pausedAtMs; + this.pausedAtMs = null; + void ctx.actions.setStopwatchRenderActive(true); + } + } + } + + private elapsedMs(): number { + const now = this.pausedAtMs ?? Date.now(); + return Math.max(0, now - this.startedAtMs - this.pausedDurationMs); + } +} + +function formatStopwatchElapsed(elapsedMs: number): string { + const totalTenths = Math.floor(elapsedMs / 100); + const tenths = totalTenths % 10; + const totalSeconds = Math.floor(totalTenths / 10); + const seconds = totalSeconds % 60; + const totalMinutes = Math.floor(totalSeconds / 60); + const minutes = totalMinutes % 60; + const hours = Math.floor(totalMinutes / 60); + if (hours > 0) { + return `${hours}:${pad2(minutes)}:${pad2(seconds)}.${tenths}`; + } + return `${pad2(minutes)}:${pad2(seconds)}.${tenths}`; } function createSystemMenuLayer(): MenuLayer { diff --git a/app/ui/layers.ts b/app/ui/layers.ts index cb61db55..97efad2e 100644 --- a/app/ui/layers.ts +++ b/app/ui/layers.ts @@ -16,6 +16,7 @@ export type LayerActions = { startNightscoutApiTokenEdit: () => Promise | void; endTextSettingEdit: () => Promise | void; setVoiceControlEnabled: (enabled: boolean) => Promise | void; + setStopwatchRenderActive: (active: boolean) => Promise | void; }; export type PaintBelow = () => GrayImage;