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 totalFrags = Math.max(1, (int) Math.ceil(totalWithCrc / (double) chunkSize));
|
||||
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++) {
|
||||
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;
|
||||
|
||||
+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 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<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) {
|
||||
@@ -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));
|
||||
}
|
||||
|
||||
|
||||
@@ -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<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, Boolean> 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> T runOnMainSync(Callable<T> 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<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() {
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user