forked from Blendman974/faceclaw
Connection reliability and thread safety fixes
This commit is contained in:
1 parent
0d0b55c2da
commit
aa0b1d6874
8 files changed
+567
-277
No files matched your search
@@ -51,22 +51,12 @@ public class BleProtocol {
|
|||||||
int totalWithCrc = pb.length + 2;
|
int totalWithCrc = pb.length + 2;
|
||||||
int totalFrags = Math.max(1, (int) Math.ceil(totalWithCrc / (double) chunkSize));
|
int totalFrags = Math.max(1, (int) Math.ceil(totalWithCrc / (double) chunkSize));
|
||||||
List<byte[]> frames = new ArrayList<>(totalFrags);
|
List<byte[]> 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++) {
|
for (int i = 0; i < totalFrags; i++) {
|
||||||
boolean isLast = i == totalFrags - 1;
|
int offset = i * chunkSize;
|
||||||
byte[] chunk;
|
byte[] chunk = Arrays.copyOfRange(payload, offset, Math.min(offset + chunkSize, payload.length));
|
||||||
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;
|
|
||||||
}
|
|
||||||
byte[] frame = new byte[8 + chunk.length];
|
byte[] frame = new byte[8 + chunk.length];
|
||||||
frame[0] = (byte) 0xaa;
|
frame[0] = (byte) 0xaa;
|
||||||
frame[1] = 0x21;
|
frame[1] = 0x21;
|
||||||
|
|||||||
+169
-97
@@ -38,7 +38,8 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable {
|
|||||||
private static final int WRITE_TIMEOUT_MS = 2_000;
|
private static final int WRITE_TIMEOUT_MS = 2_000;
|
||||||
private static final int PRELUDE_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 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_REFRESH_INTERVAL_MS = 5 * 60_000;
|
||||||
private static final int BATTERY_INPUT_QUIET_MS = 5_000;
|
private static final int BATTERY_INPUT_QUIET_MS = 5_000;
|
||||||
private static final int WINDOW_SIZE = 5;
|
private static final int WINDOW_SIZE = 5;
|
||||||
@@ -62,6 +63,7 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable {
|
|||||||
private final FaceclawBleManager bleManager;
|
private final FaceclawBleManager bleManager;
|
||||||
private final InterruptibleSleep interruptibleSleep = new InterruptibleSleep();
|
private final InterruptibleSleep interruptibleSleep = new InterruptibleSleep();
|
||||||
private final Object lock = new Object();
|
private final Object lock = new Object();
|
||||||
|
private final Object nativeBridgeLock = new Object();
|
||||||
private final Handler mainHandler = new Handler(Looper.getMainLooper());
|
private final Handler mainHandler = new Handler(Looper.getMainLooper());
|
||||||
private final String rightAddress;
|
private final String rightAddress;
|
||||||
private final String leftAddress;
|
private final String leftAddress;
|
||||||
@@ -118,7 +120,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);
|
this.bleManager = new FaceclawBleManager(appContext, false);
|
||||||
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);
|
||||||
@@ -194,15 +196,17 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable {
|
|||||||
if (tileBmps == null || tileBmps.size() != DASHBOARD_TILES.length) {
|
if (tileBmps == null || tileBmps.size() != DASHBOARD_TILES.length) {
|
||||||
throw new IllegalArgumentException("exactly 4 tile bitmaps are required");
|
throw new IllegalArgumentException("exactly 4 tile bitmaps are required");
|
||||||
}
|
}
|
||||||
synchronized (desiredTilesLock) {
|
synchronized (nativeBridgeLock) {
|
||||||
desiredTileBmps = emptyTileSet();
|
synchronized (desiredTilesLock) {
|
||||||
for (int i = 0; i < DASHBOARD_TILES.length; i++) {
|
desiredTileBmps = emptyTileSet();
|
||||||
byte[] bmp = tileBmps.get(i);
|
for (int i = 0; i < DASHBOARD_TILES.length; i++) {
|
||||||
desiredTileBmps[i] = bmp == null ? new byte[0] : Arrays.copyOf(bmp, bmp.length);
|
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();
|
interruptibleSleep.interrupt();
|
||||||
}
|
}
|
||||||
@@ -237,15 +241,17 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable {
|
|||||||
boolean forceTiledCommit,
|
boolean forceTiledCommit,
|
||||||
int paintMs
|
int paintMs
|
||||||
) {
|
) {
|
||||||
synchronized (desiredTilesLock) {
|
synchronized (nativeBridgeLock) {
|
||||||
desiredTileBmps = emptyTileSet();
|
synchronized (desiredTilesLock) {
|
||||||
desiredTileBmps[0] = tile0Bmp == null ? new byte[0] : Arrays.copyOf(tile0Bmp, tile0Bmp.length);
|
desiredTileBmps = emptyTileSet();
|
||||||
desiredTileBmps[1] = tile1Bmp == null ? new byte[0] : Arrays.copyOf(tile1Bmp, tile1Bmp.length);
|
desiredTileBmps[0] = tile0Bmp == null ? new byte[0] : Arrays.copyOf(tile0Bmp, tile0Bmp.length);
|
||||||
desiredTileBmps[2] = tile2Bmp == null ? new byte[0] : Arrays.copyOf(tile2Bmp, tile2Bmp.length);
|
desiredTileBmps[1] = tile1Bmp == null ? new byte[0] : Arrays.copyOf(tile1Bmp, tile1Bmp.length);
|
||||||
desiredTileBmps[3] = tile3Bmp == null ? new byte[0] : Arrays.copyOf(tile3Bmp, tile3Bmp.length);
|
desiredTileBmps[2] = tile2Bmp == null ? new byte[0] : Arrays.copyOf(tile2Bmp, tile2Bmp.length);
|
||||||
desiredFingerprint = fingerprint == null ? "" : fingerprint;
|
desiredTileBmps[3] = tile3Bmp == null ? new byte[0] : Arrays.copyOf(tile3Bmp, tile3Bmp.length);
|
||||||
desiredForceTiledCommit = forceTiledCommit;
|
desiredFingerprint = fingerprint == null ? "" : fingerprint;
|
||||||
desiredPaintMs = paintMs;
|
desiredForceTiledCommit = forceTiledCommit;
|
||||||
|
desiredPaintMs = paintMs;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
interruptibleSleep.interrupt();
|
interruptibleSleep.interrupt();
|
||||||
}
|
}
|
||||||
@@ -421,7 +427,7 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable {
|
|||||||
try {
|
try {
|
||||||
connectArm(rightAddress, true);
|
connectArm(rightAddress, true);
|
||||||
connectArm(leftAddress, false);
|
connectArm(leftAddress, false);
|
||||||
if (!interruptibleSleep.sleep(800)) {
|
if (!sleepDuringConnectSettling(800)) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
sendPrelude();
|
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) {
|
private void connectArm(String address, boolean enableRenderNotify) {
|
||||||
if (!bleManager.connect(address, CONNECT_TIMEOUT_MS)) {
|
if (!bleManager.connect(address, CONNECT_TIMEOUT_MS)) {
|
||||||
throw new IllegalStateException("connect failed: " + address);
|
throw new IllegalStateException("connect failed: " + address);
|
||||||
@@ -518,87 +538,139 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable {
|
|||||||
|
|
||||||
private long driveSession() {
|
private long driveSession() {
|
||||||
//Log.d(TAG, "driveSession called (pendingMessages.size=" + pendingMessages.size() + " inFlightMessages.size=" + inFlightMessages.size() + ")");
|
//Log.d(TAG, "driveSession called (pendingMessages.size=" + pendingMessages.size() + " inFlightMessages.size=" + inFlightMessages.size() + ")");
|
||||||
synchronized (lock) {
|
while (true) {
|
||||||
|
OutboundMessage messageToWrite = null;
|
||||||
long now = SystemClock.elapsedRealtime();
|
long now = SystemClock.elapsedRealtime();
|
||||||
|
|
||||||
if (!inFlightMessages.isEmpty()) {
|
synchronized (lock) {
|
||||||
OutboundMessage oldest = inFlightMessages.peekFirst();
|
if (!inFlightMessages.isEmpty()) {
|
||||||
if (oldest != null && oldest.ackDeadlineAtMs <= now) {
|
OutboundMessage oldest = inFlightMessages.peekFirst();
|
||||||
Log.i(TAG, "message timed out: " + oldest.label);
|
if (oldest != null && oldest.ackDeadlineAtMs <= now) {
|
||||||
inFlightMessages.removeFirst();
|
Log.i(TAG, "message timed out: " + oldest.label);
|
||||||
logLine("message timed out: " + oldest.label);
|
inFlightMessages.removeFirst();
|
||||||
releaseMagicLocked(oldest, "timeout");
|
logLine("message timed out: " + oldest.label);
|
||||||
handleAckTimeoutLocked(oldest);
|
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;
|
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()) {
|
if (!writeMessageFrames(messageToWrite)) {
|
||||||
Log.i(TAG, "enqueueing create layout");
|
synchronized (lock) {
|
||||||
enqueueStartupProbeLocked();
|
if (removePreparedMessageLocked(messageToWrite) || messageToWrite.magic == 0) {
|
||||||
}
|
handleTransportFailureLocked("write failed");
|
||||||
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 (!shutdownRequested && fixedLayoutCreated && warmedUp && pendingMessages.isEmpty() && inFlightMessages.isEmpty()
|
|
||||||
&& now >= imageRetryAfterMs
|
|
||||||
&& !getDesiredFingerprint().equals(displayedFingerprint)) {
|
|
||||||
Log.i(TAG, "Enqueued image update");
|
|
||||||
enqueueDesiredImageLocked();
|
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (shouldPollBatteryLocked(now)) {
|
synchronized (lock) {
|
||||||
Log.i(TAG, "Writing battery query");
|
completeMessageWriteLocked(messageToWrite);
|
||||||
writeBatteryQueryLocked(now);
|
|
||||||
return 0;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!pendingMessages.isEmpty() || !inFlightMessages.isEmpty()) {
|
|
||||||
return IDLE_SLEEP_MS;
|
|
||||||
}
|
|
||||||
return 250;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private boolean writeMessageLocked(OutboundMessage message) {
|
private void prepareMessageWriteLocked(OutboundMessage message, long now) {
|
||||||
long writeStartedAtMs = SystemClock.elapsedRealtime();
|
message.writeStartedAtMs = now;
|
||||||
String writeAddress = "image".equals(message.kind) ? leftAddress : rightAddress;
|
message.sentAtMs = now;
|
||||||
if (!bleManager.writeFrames(
|
message.ackDeadlineAtMs = now + message.ackTimeoutMs + WRITE_TIMEOUT_MS;
|
||||||
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;
|
|
||||||
if (message.magic != 0) {
|
if (message.magic != 0) {
|
||||||
inFlightMessages.addLast(message);
|
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);
|
logImageUpdateSendLandmarkLocked(message);
|
||||||
return true;
|
}
|
||||||
|
|
||||||
|
private boolean removePreparedMessageLocked(OutboundMessage message) {
|
||||||
|
if (message == null || message.magic == 0) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
Iterator<OutboundMessage> 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) {
|
private void resolveAckLocked(int sid, int magic, byte[] pb) {
|
||||||
@@ -854,14 +926,16 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable {
|
|||||||
if (!synchronizedCommits) {
|
if (!synchronizedCommits) {
|
||||||
for (TileImagePlan plan : changedTiles) {
|
for (TileImagePlan plan : changedTiles) {
|
||||||
for (BleProtocol.ImageFragment fragment : plan.fragments) {
|
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);
|
enqueueImageFragmentLocked(plan, fragment, fingerprint, updateId, messageNumber++, messageCount, nextTransportSeq++, requestAck, true);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
for (TileImagePlan plan : changedTiles) {
|
for (TileImagePlan plan : changedTiles) {
|
||||||
for (int i = 0; i < plan.fragments.size() - 1; i++) {
|
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);
|
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);
|
pendingMessages.addLast(message);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void writeHeartbeatLocked() {
|
private OutboundMessage createHeartbeatMessageLocked() {
|
||||||
int magic = nextMagic();
|
int magic = nextMagic();
|
||||||
OutboundMessage heartbeatMessage = new OutboundMessage(
|
return new OutboundMessage(
|
||||||
"heartbeat",
|
"heartbeat",
|
||||||
"heartbeat",
|
"heartbeat",
|
||||||
BleProtocol.SID_EVENHUB,
|
BleProtocol.SID_EVENHUB,
|
||||||
@@ -920,8 +994,6 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable {
|
|||||||
-1,
|
-1,
|
||||||
null
|
null
|
||||||
);
|
);
|
||||||
writeMessageLocked(heartbeatMessage);
|
|
||||||
lastHeartbeatQueuedAtMs = SystemClock.elapsedRealtime();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private boolean shouldPollBatteryLocked(long now) {
|
private boolean shouldPollBatteryLocked(long now) {
|
||||||
@@ -933,9 +1005,9 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable {
|
|||||||
&& (lastBatteryRefreshAtMs == 0 || now - lastBatteryRefreshAtMs >= BATTERY_REFRESH_INTERVAL_MS);
|
&& (lastBatteryRefreshAtMs == 0 || now - lastBatteryRefreshAtMs >= BATTERY_REFRESH_INTERVAL_MS);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void writeBatteryQueryLocked(long now) {
|
private OutboundMessage createBatteryQueryMessageLocked() {
|
||||||
int magic = nextMagic();
|
int magic = nextMagic();
|
||||||
OutboundMessage batteryMessage = new OutboundMessage(
|
return new OutboundMessage(
|
||||||
"battery",
|
"battery",
|
||||||
"battery",
|
"battery",
|
||||||
BleProtocol.SID_UI_SETTING,
|
BleProtocol.SID_UI_SETTING,
|
||||||
@@ -951,9 +1023,6 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable {
|
|||||||
-1,
|
-1,
|
||||||
null
|
null
|
||||||
);
|
);
|
||||||
if (writeMessageLocked(batteryMessage)) {
|
|
||||||
lastBatteryRefreshAtMs = now;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private boolean hasPendingOrInflightKindLocked(String kind) {
|
private boolean hasPendingOrInflightKindLocked(String kind) {
|
||||||
@@ -1027,6 +1096,9 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable {
|
|||||||
displayedFingerprint = "";
|
displayedFingerprint = "";
|
||||||
displayedTileBmps = emptyTileSet();
|
displayedTileBmps = emptyTileSet();
|
||||||
imageRetryAfterMs = SystemClock.elapsedRealtime() + IMAGE_RETRY_DELAY_MS;
|
imageRetryAfterMs = SystemClock.elapsedRealtime() + IMAGE_RETRY_DELAY_MS;
|
||||||
|
} else if ("heartbeat".equals(message.kind)) {
|
||||||
|
handleTransportFailureLocked("heartbeat ack timeout");
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (consecutiveAckTimeouts > MAX_CONSECUTIVE_ACK_TIMEOUTS) {
|
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();
|
Integer magic = available.pollFirst();
|
||||||
if (magic == null) {
|
if (magic == null) {
|
||||||
throw new IllegalStateException("no BLE magic values available");
|
throw new IllegalStateException("no BLE magic values available");
|
||||||
@@ -1417,7 +1489,7 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable {
|
|||||||
return magic;
|
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) {
|
if (magic < MIN_MAGIC || magic > MAX_MAGIC) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -1429,7 +1501,7 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable {
|
|||||||
available.addLast(magic);
|
available.addLast(magic);
|
||||||
}
|
}
|
||||||
|
|
||||||
ReleaseRecord getReleaseRecord(int sid, int magic) {
|
synchronized ReleaseRecord getReleaseRecord(int sid, int magic) {
|
||||||
return releaseRecords.get(key(sid, magic));
|
return releaseRecords.get(key(sid, magic));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -18,14 +18,9 @@ import android.util.Log;
|
|||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
import java.util.concurrent.Callable;
|
|
||||||
import java.util.concurrent.ConcurrentHashMap;
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
import java.util.concurrent.CountDownLatch;
|
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.TimeUnit;
|
||||||
import java.util.concurrent.atomic.AtomicReference;
|
|
||||||
|
|
||||||
@SuppressLint("MissingPermission")
|
@SuppressLint("MissingPermission")
|
||||||
public class FaceclawBleManager {
|
public class FaceclawBleManager {
|
||||||
@@ -34,10 +29,11 @@ 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<>();
|
||||||
private final ConcurrentHashMap<String, Object> writeLocks = new ConcurrentHashMap<>();
|
private final ConcurrentHashMap<String, Object> gattLocks = new ConcurrentHashMap<>();
|
||||||
|
|
||||||
private final ConcurrentHashMap<String, CountDownLatch> connectLatches = new ConcurrentHashMap<>();
|
private final ConcurrentHashMap<String, CountDownLatch> connectLatches = new ConcurrentHashMap<>();
|
||||||
private final ConcurrentHashMap<String, Boolean> connectResults = new ConcurrentHashMap<>();
|
private final ConcurrentHashMap<String, Boolean> connectResults = new ConcurrentHashMap<>();
|
||||||
@@ -57,7 +53,12 @@ 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");
|
||||||
@@ -73,57 +74,83 @@ public class FaceclawBleManager {
|
|||||||
if (address == null || address.trim().isEmpty()) {
|
if (address == null || address.trim().isEmpty()) {
|
||||||
throw new IllegalArgumentException("address is required");
|
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);
|
CountDownLatch latch = new CountDownLatch(1);
|
||||||
connectLatches.put(address, latch);
|
connectLatches.put(address, latch);
|
||||||
connectResults.remove(address);
|
connectResults.remove(address);
|
||||||
|
|
||||||
BluetoothGatt gatt = runOnMainSync(() -> device.connectGatt(
|
Object gattLock = gattLock(address);
|
||||||
context,
|
BluetoothGatt gatt;
|
||||||
false,
|
synchronized (gattLock) {
|
||||||
gattCallback,
|
BluetoothGatt existing = gattClients.get(address);
|
||||||
BluetoothDevice.TRANSPORT_LE,
|
if (existing != null) {
|
||||||
BluetoothDevice.PHY_LE_2M|BluetoothDevice.PHY_LE_1M
|
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) {
|
if (gatt == null) {
|
||||||
connectLatches.remove(address);
|
connectLatches.remove(address);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
gattClients.put(address, gatt);
|
|
||||||
|
|
||||||
if (!awaitLatch(latch, timeoutMs)) {
|
if (!awaitLatch(latch, timeoutMs)) {
|
||||||
connectLatches.remove(address);
|
connectLatches.remove(address);
|
||||||
connectResults.remove(address);
|
connectResults.remove(address);
|
||||||
|
synchronized (gattLock) {
|
||||||
|
gattClients.remove(address, gatt);
|
||||||
|
gatt.disconnect();
|
||||||
|
gatt.close();
|
||||||
|
}
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
gatt.readPhy();
|
|
||||||
Boolean connected = connectResults.remove(address);
|
Boolean connected = connectResults.remove(address);
|
||||||
connectLatches.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) {
|
public boolean requestConnectionPriority(String address, int priority) {
|
||||||
BluetoothGatt gatt = requireGatt(address);
|
synchronized (gattLock(address)) {
|
||||||
return runOnMainSync(() -> gatt.requestConnectionPriority(priority));
|
BluetoothGatt gatt = requireGatt(address);
|
||||||
|
return gatt.requestConnectionPriority(priority);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean requestMtu(String address, int mtu, int timeoutMs) {
|
public boolean requestMtu(String address, int mtu, int timeoutMs) {
|
||||||
BluetoothGatt gatt = requireGatt(address);
|
|
||||||
CountDownLatch latch = new CountDownLatch(1);
|
CountDownLatch latch = new CountDownLatch(1);
|
||||||
mtuLatches.put(address, latch);
|
mtuLatches.put(address, latch);
|
||||||
mtuStatuses.remove(address);
|
mtuStatuses.remove(address);
|
||||||
|
|
||||||
boolean started = runOnMainSync(() -> gatt.requestMtu(mtu));
|
boolean started;
|
||||||
|
synchronized (gattLock(address)) {
|
||||||
|
BluetoothGatt gatt = requireGatt(address);
|
||||||
|
started = gatt.requestMtu(mtu);
|
||||||
|
}
|
||||||
if (!started) {
|
if (!started) {
|
||||||
mtuLatches.remove(address);
|
mtuLatches.remove(address);
|
||||||
return false;
|
return false;
|
||||||
@@ -139,12 +166,15 @@ public class FaceclawBleManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public boolean discoverServices(String address, int timeoutMs) {
|
public boolean discoverServices(String address, int timeoutMs) {
|
||||||
BluetoothGatt gatt = requireGatt(address);
|
|
||||||
CountDownLatch latch = new CountDownLatch(1);
|
CountDownLatch latch = new CountDownLatch(1);
|
||||||
servicesLatches.put(address, latch);
|
servicesLatches.put(address, latch);
|
||||||
servicesStatuses.remove(address);
|
servicesStatuses.remove(address);
|
||||||
|
|
||||||
boolean started = runOnMainSync(gatt::discoverServices);
|
boolean started;
|
||||||
|
synchronized (gattLock(address)) {
|
||||||
|
BluetoothGatt gatt = requireGatt(address);
|
||||||
|
started = gatt.discoverServices();
|
||||||
|
}
|
||||||
if (!started) {
|
if (!started) {
|
||||||
servicesLatches.remove(address);
|
servicesLatches.remove(address);
|
||||||
return false;
|
return false;
|
||||||
@@ -160,29 +190,36 @@ public class FaceclawBleManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public boolean enableNotifications(String address, String characteristicUuid, boolean enable, int timeoutMs) {
|
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);
|
CountDownLatch latch = new CountDownLatch(1);
|
||||||
descriptorLatches.put(address, latch);
|
descriptorLatches.put(address, latch);
|
||||||
descriptorStatuses.remove(address);
|
descriptorStatuses.remove(address);
|
||||||
|
|
||||||
descriptor.setValue(enable
|
boolean started;
|
||||||
? BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE
|
synchronized (gattLock(address)) {
|
||||||
: BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE);
|
BluetoothGatt gatt = requireGatt(address);
|
||||||
boolean started = runOnMainSync(() -> gatt.writeDescriptor(descriptor));
|
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) {
|
if (!started) {
|
||||||
descriptorLatches.remove(address);
|
descriptorLatches.remove(address);
|
||||||
|
descriptorStatuses.remove(address);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
if (!awaitLatch(latch, timeoutMs)) {
|
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");
|
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);
|
synchronized (gattLock(address)) {
|
||||||
BluetoothGattCharacteristic characteristic = requireCharacteristic(gatt, characteristicUuid);
|
BluetoothGatt gatt = requireGatt(address);
|
||||||
|
BluetoothGattCharacteristic characteristic = requireCharacteristic(gatt, characteristicUuid);
|
||||||
|
|
||||||
for (int i = 0; i < frames.size(); i++) {
|
for (int i = 0; i < frames.size(); i++) {
|
||||||
Log.i(TAG, "writeFrames starting frame " + i);
|
Log.i(TAG, "writeFrames starting frame " + i);
|
||||||
byte[] frame = frames.get(i);
|
byte[] frame = frames.get(i);
|
||||||
if (!startWrite(gatt, characteristic, address, frame, writeType, timeoutMs)) {
|
if (!startWrite(gatt, characteristic, address, frame, writeType, timeoutMs)) {
|
||||||
return false;
|
return false;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
@@ -228,41 +267,77 @@ public class FaceclawBleManager {
|
|||||||
int writeType,
|
int writeType,
|
||||||
int timeoutMs
|
int timeoutMs
|
||||||
) {
|
) {
|
||||||
boolean retry = false;
|
|
||||||
int retryCount = 0;
|
int retryCount = 0;
|
||||||
while (true) {
|
while (true) {
|
||||||
|
CountDownLatch latch = new CountDownLatch(1);
|
||||||
|
writeLatches.put(address, latch);
|
||||||
|
writeStatuses.remove(address);
|
||||||
|
|
||||||
long currentTime = System.currentTimeMillis();
|
long currentTime = System.currentTimeMillis();
|
||||||
int result = gatt.writeCharacteristic(characteristic, data, writeType);
|
int result = gatt.writeCharacteristic(characteristic, data, writeType);
|
||||||
long timeAsleep = System.currentTimeMillis() - currentTime;
|
long timeAsleep = System.currentTimeMillis() - currentTime;
|
||||||
//Log.i(TAG, "writeCharacteristic: spent " + timeAsleep + "ms");
|
//Log.i(TAG, "writeCharacteristic: spent " + timeAsleep + "ms");
|
||||||
|
|
||||||
if (result == android.bluetooth.BluetoothStatusCodes.ERROR_GATT_WRITE_REQUEST_BUSY) {
|
if (result == android.bluetooth.BluetoothStatusCodes.ERROR_GATT_WRITE_REQUEST_BUSY) {
|
||||||
if (++retryCount < 25) {
|
writeLatches.remove(address, latch);
|
||||||
try {
|
writeStatuses.remove(address);
|
||||||
long currentTime2 = System.currentTimeMillis();
|
if (!sleepBeforeWriteRetry(address, "busy", retryCount++)) {
|
||||||
Thread.sleep(1);
|
|
||||||
long timeAsleep2 = System.currentTimeMillis() - currentTime2;
|
|
||||||
//Log.i(TAG, "writeCharacteristic: slept for " + timeAsleep2 + "ms");
|
|
||||||
} catch (InterruptedException e) {}
|
|
||||||
} else {
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
continue;
|
||||||
} else {
|
} else {
|
||||||
//Log.i(TAG, "writeCharacteristic with writeType=" + writeType + " result=" + result + " retryCount=" + retryCount);
|
//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) {
|
private boolean sleepBeforeWriteRetry(String address, String reason, int retryIndex) {
|
||||||
BluetoothGatt gatt = gattClients.remove(address);
|
if (retryIndex >= WRITE_RETRY_DELAYS_MS.length) {
|
||||||
if (gatt == null) {
|
Log.w(TAG, "writeCharacteristic retry exhausted: address=" + address + " reason=" + reason);
|
||||||
return;
|
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.disconnect();
|
||||||
gatt.close();
|
gatt.close();
|
||||||
});
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void 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) {
|
private void runOnMainAsync(Runnable runnable) {
|
||||||
if (Looper.myLooper() == Looper.getMainLooper()) {
|
if (Looper.myLooper() == Looper.getMainLooper()) {
|
||||||
runnable.run();
|
runnable.run();
|
||||||
@@ -307,34 +386,12 @@ public class FaceclawBleManager {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private <T> T runOnMainSync(Callable<T> callable) {
|
private void dispatchListener(Runnable runnable) {
|
||||||
if (Looper.myLooper() == Looper.getMainLooper()) {
|
if (dispatchListenerOnMain) {
|
||||||
try {
|
runOnMainAsync(runnable);
|
||||||
return callable.call();
|
} else {
|
||||||
} catch (Exception e) {
|
runnable.run();
|
||||||
throw new RuntimeException(e);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
CountDownLatch latch = new CountDownLatch(1);
|
|
||||||
AtomicReference<T> result = new AtomicReference<>();
|
|
||||||
AtomicReference<RuntimeException> 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() {
|
private final BluetoothGattCallback gattCallback = new BluetoothGattCallback() {
|
||||||
@@ -358,9 +415,11 @@ public class FaceclawBleManager {
|
|||||||
if (latch != null) {
|
if (latch != null) {
|
||||||
latch.countDown();
|
latch.countDown();
|
||||||
}
|
}
|
||||||
gattClients.remove(address);
|
Object gattLock = gattLock(address);
|
||||||
writeLocks.remove(address);
|
synchronized (gattLock) {
|
||||||
runOnMainAsync(gatt::close);
|
gattClients.remove(address, gatt);
|
||||||
|
gatt.close();
|
||||||
|
}
|
||||||
dispatchConnectionState(address, false);
|
dispatchConnectionState(address, false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -428,7 +487,7 @@ public class FaceclawBleManager {
|
|||||||
if (current == null) {
|
if (current == null) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
runOnMainAsync(() -> 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) {
|
||||||
@@ -438,6 +497,6 @@ public class FaceclawBleManager {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
byte[] copy = data != null ? data.clone() : new byte[0];
|
byte[] copy = data != null ? data.clone() : new byte[0];
|
||||||
runOnMainAsync(() -> current.onNotification(address, characteristicUuid, copy));
|
dispatchListener(() -> current.onNotification(address, characteristicUuid, copy));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -50,6 +50,9 @@ type LogLevel = "debug"|"info"|"warn"|"error";
|
|||||||
const CONTAINER_NAME = "dashboard";
|
const CONTAINER_NAME = "dashboard";
|
||||||
const DASHBOARD_INTERVAL_MS = 60_000;
|
const DASHBOARD_INTERVAL_MS = 60_000;
|
||||||
const SCREEN_TIMEOUT_CHECK_MS = 1_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 =
|
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.";
|
"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 communicator: FaceclawCommunicatorBridge | null = null;
|
||||||
private dashboardTimer: ReturnType<typeof setInterval> | null = null;
|
private dashboardTimer: ReturnType<typeof setInterval> | null = null;
|
||||||
private screenTimeoutTimer: ReturnType<typeof setInterval> | null = null;
|
private screenTimeoutTimer: ReturnType<typeof setInterval> | null = null;
|
||||||
|
private stopwatchRenderTimer: ReturnType<typeof setInterval> | null = null;
|
||||||
private offState: (() => void) | null = null;
|
private offState: (() => void) | null = null;
|
||||||
private offLog: (() => void) | null = null;
|
private offLog: (() => void) | null = null;
|
||||||
private offRing: (() => void) | null = null;
|
private offRing: (() => void) | null = null;
|
||||||
@@ -129,6 +133,7 @@ class DashboardController {
|
|||||||
private renderInProgress = false;
|
private renderInProgress = false;
|
||||||
private renderQueued = false;
|
private renderQueued = false;
|
||||||
private queuedRenderReason: "initial" | "interval" = "interval";
|
private queuedRenderReason: "initial" | "interval" = "interval";
|
||||||
|
private lastForegroundNotificationUpdateAtMs = 0;
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
setDashboardActions({
|
setDashboardActions({
|
||||||
@@ -139,6 +144,7 @@ class DashboardController {
|
|||||||
startNightscoutApiTokenEdit: () => this.startNightscoutApiTokenEdit(),
|
startNightscoutApiTokenEdit: () => this.startNightscoutApiTokenEdit(),
|
||||||
endTextSettingEdit: () => this.endTextSettingEdit(),
|
endTextSettingEdit: () => this.endTextSettingEdit(),
|
||||||
setVoiceControlEnabled: (enabled) => this.setVoiceControlEnabled(enabled),
|
setVoiceControlEnabled: (enabled) => this.setVoiceControlEnabled(enabled),
|
||||||
|
setStopwatchRenderActive: (active) => this.setStopwatchRenderActive(active),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -354,6 +360,7 @@ class DashboardController {
|
|||||||
this.screenTimeoutTimer = setInterval(() => {
|
this.screenTimeoutTimer = setInterval(() => {
|
||||||
if (this.phase !== "connected" || !this.communicator) return;
|
if (this.phase !== "connected" || !this.communicator) return;
|
||||||
if (!applyDashboardScreenTimeout()) return;
|
if (!applyDashboardScreenTimeout()) return;
|
||||||
|
this.setStopwatchRenderActive(false);
|
||||||
this.endTextSettingEdit();
|
this.endTextSettingEdit();
|
||||||
void this.requestRender("interval").catch((error) => {
|
void this.requestRender("interval").catch((error) => {
|
||||||
const message = this.formatError(error);
|
const message = this.formatError(error);
|
||||||
@@ -586,14 +593,13 @@ class DashboardController {
|
|||||||
const forceTiledCommit = consumeDashboardTiledWakePaint();
|
const forceTiledCommit = consumeDashboardTiledWakePaint();
|
||||||
const fingerprint = image.fingerprint();
|
const fingerprint = image.fingerprint();
|
||||||
const tiles = image.toEvenHubTiles().map((tile) => tile.bmp);
|
const tiles = image.toEvenHubTiles().map((tile) => tile.bmp);
|
||||||
|
this.setDisplayPreview(grayImageToPreviewSource(image));
|
||||||
if (this.communicator) {
|
if (this.communicator) {
|
||||||
await this.communicator.submitDashboardImage(tiles, fingerprint, forceTiledCommit, paintMs);
|
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") {
|
this.updateConnectedForegroundNotification();
|
||||||
updateForegroundNotification(`Connected`);
|
|
||||||
}
|
|
||||||
this.appendLog(`${reason === "initial" ? "initial" : "scheduled"} dashboard image queued`);
|
this.appendLog(`${reason === "initial" ? "initial" : "scheduled"} dashboard image queued`);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -652,12 +658,26 @@ class DashboardController {
|
|||||||
private startVoiceControlIfEnabled(): void {
|
private startVoiceControlIfEnabled(): void {
|
||||||
if (!this.communicator) return;
|
if (!this.communicator) return;
|
||||||
if (!isDashboardVoiceControlEnabled()) return;
|
if (!isDashboardVoiceControlEnabled()) return;
|
||||||
if (this.phase === "connected") {
|
this.updateConnectedForegroundNotification();
|
||||||
updateForegroundNotification("Connected");
|
|
||||||
}
|
|
||||||
voiceControlBridge.start();
|
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 {
|
private clearDashboardTimer(): void {
|
||||||
if (this.dashboardTimer) {
|
if (this.dashboardTimer) {
|
||||||
clearInterval(this.dashboardTimer);
|
clearInterval(this.dashboardTimer);
|
||||||
@@ -667,6 +687,10 @@ class DashboardController {
|
|||||||
clearInterval(this.screenTimeoutTimer);
|
clearInterval(this.screenTimeoutTimer);
|
||||||
this.screenTimeoutTimer = null;
|
this.screenTimeoutTimer = null;
|
||||||
}
|
}
|
||||||
|
if (this.stopwatchRenderTimer) {
|
||||||
|
clearInterval(this.stopwatchRenderTimer);
|
||||||
|
this.stopwatchRenderTimer = null;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private setPhase(phase: ConnectionPhase): void {
|
private setPhase(phase: ConnectionPhase): void {
|
||||||
@@ -681,6 +705,14 @@ class DashboardController {
|
|||||||
this.emit();
|
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 {
|
private formatFrameMetrics(metrics: FrameMetrics): string {
|
||||||
return `paint=${Math.round(metrics.paintMs)}ms, transmit=${Math.round(metrics.transmitMs)}ms, tiles=${Math.round(metrics.tileCount)}`;
|
return `paint=${Math.round(metrics.paintMs)}ms, transmit=${Math.round(metrics.transmitMs)}ms, tiles=${Math.round(metrics.tileCount)}`;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -65,6 +65,8 @@ function nonNegativeNumber(value: number): number {
|
|||||||
export class FaceclawCommunicatorBridge {
|
export class FaceclawCommunicatorBridge {
|
||||||
private readonly communicator: any;
|
private readonly communicator: any;
|
||||||
private readonly listenerProxy: any;
|
private readonly listenerProxy: any;
|
||||||
|
private javaCallQueue: Promise<void> = Promise.resolve();
|
||||||
|
private readonly frameMetricWaiters = new Set<(metrics: FrameMetrics) => void>();
|
||||||
private readonly logListeners = new Set<(line: string) => void>();
|
private readonly logListeners = new Set<(line: string) => void>();
|
||||||
private readonly stateListeners = new Set<(state: CommunicatorState) => void>();
|
private readonly stateListeners = new Set<(state: CommunicatorState) => void>();
|
||||||
private readonly ringListeners = new Set<(event: RawInputEvent) => void>();
|
private readonly ringListeners = new Set<(event: RawInputEvent) => void>();
|
||||||
@@ -84,18 +86,14 @@ export class FaceclawCommunicatorBridge {
|
|||||||
);
|
);
|
||||||
this.listenerProxy = new com.faceclaw.app.FaceclawBleCommunicatorListener({
|
this.listenerProxy = new com.faceclaw.app.FaceclawBleCommunicatorListener({
|
||||||
onLog: (line: string) => {
|
onLog: (line: string) => {
|
||||||
for (const listener of this.logListeners) {
|
this.emitAsync(this.logListeners, String(line));
|
||||||
listener(String(line));
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
onStateChange: (phase: string, status: string) => {
|
onStateChange: (phase: string, status: string) => {
|
||||||
const state = {
|
const state = {
|
||||||
phase: String(phase) as CommunicatorPhase,
|
phase: String(phase) as CommunicatorPhase,
|
||||||
status: String(status),
|
status: String(status),
|
||||||
};
|
};
|
||||||
for (const listener of this.stateListeners) {
|
this.emitAsync(this.stateListeners, state);
|
||||||
listener(state);
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
onRingEvent: (
|
onRingEvent: (
|
||||||
kind: string,
|
kind: string,
|
||||||
@@ -111,23 +109,17 @@ export class FaceclawCommunicatorBridge {
|
|||||||
eventSource: Number(eventSource),
|
eventSource: Number(eventSource),
|
||||||
systemExitReasonCode: Number(systemExitReasonCode),
|
systemExitReasonCode: Number(systemExitReasonCode),
|
||||||
};
|
};
|
||||||
for (const listener of this.ringListeners) {
|
this.emitAsync(this.ringListeners, event);
|
||||||
listener(event);
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
onBatteryState: (headsetBattery: number, headsetCharging: number) => {
|
onBatteryState: (headsetBattery: number, headsetCharging: number) => {
|
||||||
const state = {
|
const state = {
|
||||||
battery: Number(headsetBattery),
|
battery: Number(headsetBattery),
|
||||||
chargingStatus: Number(headsetCharging),
|
chargingStatus: Number(headsetCharging),
|
||||||
};
|
};
|
||||||
for (const listener of this.batteryListeners) {
|
this.emitAsync(this.batteryListeners, state);
|
||||||
listener(state);
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
onEvenAppConflict: (message: string) => {
|
onEvenAppConflict: (message: string) => {
|
||||||
for (const listener of this.evenAppConflictListeners) {
|
this.emitAsync(this.evenAppConflictListeners, String(message));
|
||||||
listener(String(message));
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
onFrameMetrics: (paintMs: number, transmitMs: number, tileCount: number) => {
|
onFrameMetrics: (paintMs: number, transmitMs: number, tileCount: number) => {
|
||||||
const metrics = {
|
const metrics = {
|
||||||
@@ -135,14 +127,46 @@ export class FaceclawCommunicatorBridge {
|
|||||||
transmitMs: nonNegativeNumber(transmitMs),
|
transmitMs: nonNegativeNumber(transmitMs),
|
||||||
tileCount: nonNegativeNumber(tileCount),
|
tileCount: nonNegativeNumber(tileCount),
|
||||||
};
|
};
|
||||||
for (const listener of this.frameMetricsListeners) {
|
const waiters = Array.from(this.frameMetricWaiters);
|
||||||
listener(metrics);
|
this.frameMetricWaiters.clear();
|
||||||
|
for (const waiter of waiters) {
|
||||||
|
setTimeout(() => waiter(metrics), 0);
|
||||||
}
|
}
|
||||||
|
this.emitAsync(this.frameMetricsListeners, metrics);
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
this.communicator.setListener(this.listenerProxy);
|
this.communicator.setListener(this.listenerProxy);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private emitAsync<T>(listeners: Set<(value: T) => void>, value: T): void {
|
||||||
|
const snapshot = Array.from(listeners);
|
||||||
|
setTimeout(() => {
|
||||||
|
for (const listener of snapshot) {
|
||||||
|
listener(value);
|
||||||
|
}
|
||||||
|
}, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
private enqueueJavaCall<T>(operation: () => T): Promise<T> {
|
||||||
|
const run = () =>
|
||||||
|
new Promise<T>((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 {
|
onLog(listener: (line: string) => void): () => void {
|
||||||
this.logListeners.add(listener);
|
this.logListeners.add(listener);
|
||||||
return () => this.logListeners.delete(listener);
|
return () => this.logListeners.delete(listener);
|
||||||
@@ -173,34 +197,57 @@ export class FaceclawCommunicatorBridge {
|
|||||||
return () => this.frameMetricsListeners.delete(listener);
|
return () => this.frameMetricsListeners.delete(listener);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
waitForNextFrameMetrics(timeoutMs: number): Promise<FrameMetrics | null> {
|
||||||
|
const delayMs = Math.max(1, Math.round(nonNegativeNumber(timeoutMs)));
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
let settled = false;
|
||||||
|
let timeoutHandle: ReturnType<typeof setTimeout> | 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<void> {
|
async start(): Promise<void> {
|
||||||
this.communicator.start();
|
await this.enqueueJavaCall(() => this.communicator.start());
|
||||||
}
|
}
|
||||||
|
|
||||||
async submitDashboardImage(tileBmps: Uint8Array[], fingerprint: string, forceTiledCommit = false, paintMs = -1): Promise<void> {
|
async submitDashboardImage(tileBmps: Uint8Array[], fingerprint: string, forceTiledCommit = false, paintMs = -1): Promise<void> {
|
||||||
if (tileBmps.length !== 4) {
|
if (tileBmps.length !== 4) {
|
||||||
throw new Error(`expected 4 dashboard tiles, got ${tileBmps.length}`);
|
throw new Error(`expected 4 dashboard tiles, got ${tileBmps.length}`);
|
||||||
}
|
}
|
||||||
this.communicator.submitDashboardImage4(
|
const tileSnapshots = tileBmps.map((tile) => new Uint8Array(tile));
|
||||||
toJavaByteArray(tileBmps[0]!),
|
await this.enqueueJavaCall(() => {
|
||||||
toJavaByteArray(tileBmps[1]!),
|
this.communicator.submitDashboardImage4(
|
||||||
toJavaByteArray(tileBmps[2]!),
|
toJavaByteArray(tileSnapshots[0]!),
|
||||||
toJavaByteArray(tileBmps[3]!),
|
toJavaByteArray(tileSnapshots[1]!),
|
||||||
fingerprint,
|
toJavaByteArray(tileSnapshots[2]!),
|
||||||
forceTiledCommit,
|
toJavaByteArray(tileSnapshots[3]!),
|
||||||
Math.round(nonNegativeNumber(paintMs)),
|
fingerprint,
|
||||||
);
|
forceTiledCommit,
|
||||||
|
Math.round(nonNegativeNumber(paintMs)),
|
||||||
|
);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
async disconnect(): Promise<void> {
|
async disconnect(): Promise<void> {
|
||||||
this.communicator.disconnect();
|
await this.enqueueJavaCall(() => this.communicator.disconnect());
|
||||||
}
|
}
|
||||||
|
|
||||||
async sendShutdown(exitMode = 0): Promise<boolean> {
|
async sendShutdown(exitMode = 0): Promise<boolean> {
|
||||||
return Boolean(this.communicator.sendShutdown(exitMode));
|
return this.enqueueJavaCall(() => Boolean(this.communicator.sendShutdown(exitMode)));
|
||||||
}
|
}
|
||||||
|
|
||||||
async close(): Promise<void> {
|
async close(): Promise<void> {
|
||||||
this.communicator.close();
|
await this.enqueueJavaCall(() => this.communicator.close());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+36
-21
@@ -149,6 +149,7 @@ const PLUGIN_MAP = new Map<DashboardPluginId, DashboardPlugin>(
|
|||||||
const nightscoutLargeFont = loadEmbeddedTerminus24();
|
const nightscoutLargeFont = loadEmbeddedTerminus24();
|
||||||
const NIGHTSCOUT_STALE_MS = 15 * 60 * 1000;
|
const NIGHTSCOUT_STALE_MS = 15 * 60 * 1000;
|
||||||
const NIGHTSCOUT_GRAPH_WINDOW_MS = 2 * 60 * 60 * 1000;
|
const NIGHTSCOUT_GRAPH_WINDOW_MS = 2 * 60 * 60 * 1000;
|
||||||
|
const NIGHTSCOUT_GRAPH_TIME_QUANTUM_MS = 60 * 1000;
|
||||||
|
|
||||||
export function listDashboardPlugins(): DashboardPlugin[] {
|
export function listDashboardPlugins(): DashboardPlugin[] {
|
||||||
return [...DASHBOARD_PLUGINS];
|
return [...DASHBOARD_PLUGINS];
|
||||||
@@ -294,8 +295,12 @@ function drawNightscoutGraph(
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const windowStartMs = nowMs - NIGHTSCOUT_GRAPH_WINDOW_MS;
|
const graphNowMs = minuteBucketTimestampMs(nowMs);
|
||||||
const visibleHistory = nightscout.history.filter((point) => point.timestampMs >= windowStartMs && point.timestampMs <= 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) {
|
if (visibleHistory.length === 0) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -308,18 +313,14 @@ function drawNightscoutGraph(
|
|||||||
const paddedMax = max + range * 0.1;
|
const paddedMax = max + range * 0.1;
|
||||||
|
|
||||||
image.drawRect(bounds.x, bounds.y, bounds.width, bounds.height, 56);
|
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, 60, 40);
|
||||||
drawNightscoutReferenceLine(image, bounds, paddedMin, paddedMax, 100, 40);
|
drawNightscoutReferenceLine(image, bounds, paddedMin, paddedMax, 100, 40);
|
||||||
drawNightscoutReferenceLine(image, bounds, paddedMin, paddedMax, 180, 40);
|
drawNightscoutReferenceLine(image, bounds, paddedMin, paddedMax, 180, 40);
|
||||||
|
|
||||||
const plotted = visibleHistory.map((point) => ({
|
const plotted = visibleHistory.map((point) => ({
|
||||||
point,
|
point,
|
||||||
x:
|
x: timeToGraphX(bounds, windowStartMs, point.timestampMs),
|
||||||
bounds.x +
|
|
||||||
Math.round(
|
|
||||||
((point.timestampMs - windowStartMs) / Math.max(1, NIGHTSCOUT_GRAPH_WINDOW_MS)) * Math.max(1, bounds.width - 1),
|
|
||||||
),
|
|
||||||
y:
|
y:
|
||||||
bounds.y +
|
bounds.y +
|
||||||
bounds.height -
|
bounds.height -
|
||||||
@@ -343,8 +344,8 @@ function drawNightscoutGraph(
|
|||||||
image.fillRect(current.x - 1, current.y - 1, 2, 2, 220);
|
image.fillRect(current.x - 1, current.y - 1, 2, 2, 220);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
drawNightscoutCarbMarkers(image, bounds, font, nightscout.carbs, nowMs);
|
drawNightscoutCarbMarkers(image, bounds, font, nightscout.carbs, graphNowMs);
|
||||||
drawNightscoutBolusMarkers(image, bounds, font, nightscout.boluses, nowMs);
|
drawNightscoutBolusMarkers(image, bounds, font, nightscout.boluses, graphNowMs);
|
||||||
}
|
}
|
||||||
|
|
||||||
function drawNightscoutBasalOverlay(
|
function drawNightscoutBasalOverlay(
|
||||||
@@ -353,9 +354,12 @@ function drawNightscoutBasalOverlay(
|
|||||||
basalEvents: NightscoutState["basal"],
|
basalEvents: NightscoutState["basal"],
|
||||||
nowMs: number,
|
nowMs: number,
|
||||||
): void {
|
): void {
|
||||||
const windowStartMs = nowMs - NIGHTSCOUT_GRAPH_WINDOW_MS;
|
const graphNowMs = minuteBucketTimestampMs(nowMs);
|
||||||
|
const windowStartMs = graphNowMs - NIGHTSCOUT_GRAPH_WINDOW_MS;
|
||||||
const visibleEvents = basalEvents.filter(
|
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) {
|
if (visibleEvents.length === 0) {
|
||||||
return;
|
return;
|
||||||
@@ -367,8 +371,8 @@ function drawNightscoutBasalOverlay(
|
|||||||
const overlayHeight = Math.max(8, Math.min(18, Math.floor(bounds.height * 0.22)));
|
const overlayHeight = Math.max(8, Math.min(18, Math.floor(bounds.height * 0.22)));
|
||||||
const bottomY = bounds.y + bounds.height - 2;
|
const bottomY = bounds.y + bounds.height - 2;
|
||||||
for (const event of visibleEvents) {
|
for (const event of visibleEvents) {
|
||||||
const startMs = Math.max(windowStartMs, event.timestampMs);
|
const startMs = Math.max(windowStartMs, minuteBucketTimestampMs(event.timestampMs));
|
||||||
const endMs = Math.min(nowMs, event.timestampMs + event.durationMinutes * 60_000);
|
const endMs = Math.min(graphNowMs, minuteBucketTimestampMs(event.timestampMs + event.durationMinutes * 60_000));
|
||||||
if (endMs <= startMs) {
|
if (endMs <= startMs) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -386,13 +390,15 @@ function drawNightscoutCarbMarkers(
|
|||||||
carbEvents: NightscoutState["carbs"],
|
carbEvents: NightscoutState["carbs"],
|
||||||
nowMs: number,
|
nowMs: number,
|
||||||
): void {
|
): 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;
|
const baselineY = bounds.y + bounds.height - 2;
|
||||||
for (const event of carbEvents) {
|
for (const event of carbEvents) {
|
||||||
if (event.timestampMs < windowStartMs || event.timestampMs > nowMs) {
|
const eventTimestampMs = minuteBucketTimestampMs(event.timestampMs);
|
||||||
|
if (eventTimestampMs < windowStartMs || eventTimestampMs > graphNowMs) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
const x = timeToGraphX(bounds, windowStartMs, event.timestampMs);
|
const x = timeToGraphX(bounds, windowStartMs, eventTimestampMs);
|
||||||
image.drawLine(x, baselineY, x, baselineY - 6, 150);
|
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);
|
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"],
|
bolusEvents: NightscoutState["boluses"],
|
||||||
nowMs: number,
|
nowMs: number,
|
||||||
): void {
|
): void {
|
||||||
const windowStartMs = nowMs - NIGHTSCOUT_GRAPH_WINDOW_MS;
|
const graphNowMs = minuteBucketTimestampMs(nowMs);
|
||||||
|
const windowStartMs = graphNowMs - NIGHTSCOUT_GRAPH_WINDOW_MS;
|
||||||
const topY = bounds.y + 1;
|
const topY = bounds.y + 1;
|
||||||
for (const event of bolusEvents) {
|
for (const event of bolusEvents) {
|
||||||
if (event.timestampMs < windowStartMs || event.timestampMs > nowMs) {
|
const eventTimestampMs = minuteBucketTimestampMs(event.timestampMs);
|
||||||
|
if (eventTimestampMs < windowStartMs || eventTimestampMs > graphNowMs) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
const x = timeToGraphX(bounds, windowStartMs, event.timestampMs);
|
const x = timeToGraphX(bounds, windowStartMs, eventTimestampMs);
|
||||||
image.drawLine(x, topY, x, topY + 6, 144);
|
image.drawLine(x, topY, x, topY + 6, 144);
|
||||||
if (event.insulin >= 1) {
|
if (event.insulin >= 1) {
|
||||||
drawTextCentered(
|
drawTextCentered(
|
||||||
@@ -446,12 +454,19 @@ function timeToGraphX(
|
|||||||
windowStartMs: number,
|
windowStartMs: number,
|
||||||
timestampMs: number,
|
timestampMs: number,
|
||||||
): number {
|
): number {
|
||||||
|
const graphTimestampMs = minuteBucketTimestampMs(timestampMs);
|
||||||
return (
|
return (
|
||||||
bounds.x +
|
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(
|
function drawNightscoutReferenceLine(
|
||||||
image: GrayImage,
|
image: GrayImage,
|
||||||
bounds: { x: number; y: number; width: number; height: number },
|
bounds: { x: number; y: number; width: number; height: number },
|
||||||
|
|||||||
+77
-3
@@ -84,6 +84,7 @@ const dashboardActions: LayerActions = {
|
|||||||
startNightscoutApiTokenEdit: () => {},
|
startNightscoutApiTokenEdit: () => {},
|
||||||
endTextSettingEdit: () => {},
|
endTextSettingEdit: () => {},
|
||||||
setVoiceControlEnabled: () => {},
|
setVoiceControlEnabled: () => {},
|
||||||
|
setStopwatchRenderActive: () => {},
|
||||||
};
|
};
|
||||||
const dashboardFont = loadEmbeddedTerminus12();
|
const dashboardFont = loadEmbeddedTerminus12();
|
||||||
const dashboardSystemFont = loadEmbeddedTerminus16();
|
const dashboardSystemFont = loadEmbeddedTerminus16();
|
||||||
@@ -443,12 +444,12 @@ function createRootMenuLayer(): MenuLayer {
|
|||||||
return new RootMenuLayer(
|
return new RootMenuLayer(
|
||||||
"Menu",
|
"Menu",
|
||||||
[
|
[
|
||||||
/*{
|
{
|
||||||
label: "Apps",
|
label: "Apps",
|
||||||
onSelect: (ctx) => {
|
onSelect: (ctx) => {
|
||||||
ctx.stack.push(createAppsMenuLayer());
|
ctx.stack.push(createAppsMenuLayer());
|
||||||
},
|
},
|
||||||
},*/
|
},
|
||||||
{
|
{
|
||||||
label: "Settings",
|
label: "Settings",
|
||||||
onSelect: (ctx) => {
|
onSelect: (ctx) => {
|
||||||
@@ -476,7 +477,80 @@ function createRootMenuLayer(): MenuLayer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function createAppsMenuLayer(): 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 {
|
function createSystemMenuLayer(): MenuLayer {
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ export type LayerActions = {
|
|||||||
startNightscoutApiTokenEdit: () => Promise<void> | void;
|
startNightscoutApiTokenEdit: () => Promise<void> | void;
|
||||||
endTextSettingEdit: () => Promise<void> | void;
|
endTextSettingEdit: () => Promise<void> | void;
|
||||||
setVoiceControlEnabled: (enabled: boolean) => Promise<void> | void;
|
setVoiceControlEnabled: (enabled: boolean) => Promise<void> | void;
|
||||||
|
setStopwatchRenderActive: (active: boolean) => Promise<void> | void;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type PaintBelow = () => GrayImage;
|
export type PaintBelow = () => GrayImage;
|
||||||
|
|||||||
Reference in new issue
Block a user