Retry failed BLE SDK releases and propagate radio command rejection
This commit is contained in:
1 parent
d0b79e83ef
commit
5def266e09
2 files changed
+65
-27
No files matched your search
@@ -26,7 +26,9 @@ object BleRadio {
|
||||
private val worker by lazy { Handler(thread.looper) }
|
||||
@Volatile private var configuredFlags: Int? = null
|
||||
private val context get() = ChatApplication.instance
|
||||
private val adapter get() = context.getSystemService(BluetoothManager::class.java).adapter
|
||||
private val adapter get() = context.getSystemService(BluetoothManager::class.java)?.adapter
|
||||
private val cleanup = BleRadioCleanup(::log)
|
||||
private var cleanupDelay = 250L
|
||||
val state = MutableStateFlow(2) // BLE_CLOSED; тексты выбирает UI.
|
||||
val advertisingState = MutableStateFlow(2)
|
||||
private var generation = 0L
|
||||
@@ -35,7 +37,9 @@ object BleRadio {
|
||||
private var server: BluetoothGattServer? = null
|
||||
private var tx: BluetoothGattCharacteristic? = null
|
||||
private var scan: ScanCallback? = null
|
||||
private var scanner: BluetoothLeScanner? = null
|
||||
private var advertisement: AdvertiseCallback? = null
|
||||
private var advertiser: BluetoothLeAdvertiser? = null
|
||||
private var beacon = byteArrayOf()
|
||||
private var sequence = 0L
|
||||
private var writer: Link? = null
|
||||
@@ -81,12 +85,12 @@ object BleRadio {
|
||||
stop()
|
||||
}
|
||||
}
|
||||
@JvmStatic fun command(op: Int, gen: Long, token: Long, text: String, bytes: ByteArray, arg: Int) {
|
||||
if (!worker.post {
|
||||
@JvmStatic fun command(op: Int, gen: Long, token: Long, text: String, bytes: ByteArray, arg: Int): Boolean {
|
||||
val accepted = worker.post {
|
||||
guarded {
|
||||
when (op) {
|
||||
0 -> if (generation == gen) stop()
|
||||
1 -> { stop(); generation = gen; company = arg; start() }
|
||||
1 -> { stop(); generation = gen; company = arg; check(cleanup.isEmpty) { "Previous BLE cleanup pending" }; start() }
|
||||
6 -> { incoming = arg != 0; if (scan != null) advertise() }
|
||||
7 -> { state.value = arg; log("INFO", "State=$arg reason=$text") }
|
||||
8 -> { advertisingState.value = arg }
|
||||
@@ -103,7 +107,9 @@ object BleRadio {
|
||||
}
|
||||
}
|
||||
}
|
||||
}) log("ERROR", "Worker rejected command=$op")
|
||||
}
|
||||
if (!accepted) log("ERROR", "Worker rejected command=$op")
|
||||
return accepted
|
||||
}
|
||||
private fun start() {
|
||||
check(permitted()) { "Bluetooth permission missing" }
|
||||
@@ -180,7 +186,7 @@ object BleRadio {
|
||||
respond(device, requestId, BluetoothGatt.GATT_REQUEST_NOT_SUPPORTED)
|
||||
}
|
||||
}
|
||||
server = checkNotNull(context.getSystemService(BluetoothManager::class.java).openGattServer(context, callback))
|
||||
server = checkNotNull(context.getSystemService(BluetoothManager::class.java)?.openGattServer(context, callback))
|
||||
val service = BluetoothGattService(serviceUuid, BluetoothGattService.SERVICE_TYPE_PRIMARY)
|
||||
service.addCharacteristic(BluetoothGattCharacteristic(rxUuid, BluetoothGattCharacteristic.PROPERTY_WRITE,
|
||||
BluetoothGattCharacteristic.PERMISSION_WRITE))
|
||||
@@ -200,20 +206,27 @@ object BleRadio {
|
||||
override fun onScanResult(callbackType: Int, result: ScanResult) {
|
||||
val data = result.scanRecord?.getManufacturerSpecificData(company)?.copyOf() ?: return
|
||||
if (data.size !in 11..24 || data[0] != 86.toByte() || data[1] != 67.toByte() || data[2] != 1.toByte()) return
|
||||
worker.post { if (generation == gen) emit(6, arg = result.rssi, text = result.device.address, data = data) }
|
||||
if (!worker.post { if (generation == gen) guarded { emit(6, arg = result.rssi, text = result.device.address, data = data) } })
|
||||
log("ERROR", "Worker rejected scan result")
|
||||
}
|
||||
override fun onScanFailed(errorCode: Int) { worker.post { if (generation == gen) guarded { error("scan error=$errorCode") } } }
|
||||
}
|
||||
val filter = ScanFilter.Builder().setManufacturerData(company, byteArrayOf(86, 67, 1)).build()
|
||||
checkNotNull(adapter?.bluetoothLeScanner).startScan(listOf(filter),
|
||||
scanner = checkNotNull(adapter?.bluetoothLeScanner)
|
||||
scanner!!.startScan(listOf(filter),
|
||||
ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build(), scan)
|
||||
log("INFO", "Scan started generation=$gen incoming=$incoming")
|
||||
}
|
||||
private fun advertise() {
|
||||
val advertiser = adapter?.bluetoothLeAdvertiser
|
||||
advertisement?.let { advertiser?.stopAdvertising(it) }; advertisement = null
|
||||
advertisement?.let { previous ->
|
||||
val owner = checkNotNull(advertiser)
|
||||
cleanup.retain(previous, "advertisement") { owner.stopAdvertising(previous) }
|
||||
advertisement = null
|
||||
check(cleanup.retry()) { "Previous advertising cleanup pending" }
|
||||
}
|
||||
if (!incoming && beacon.isEmpty()) { emit(7, arg = 1, text = "advertisement disabled"); return }
|
||||
checkNotNull(advertiser) { "Advertising unsupported" }
|
||||
val publisher = checkNotNull(adapter?.bluetoothLeAdvertiser) { "Advertising unsupported" }
|
||||
advertiser = publisher
|
||||
val gen = generation
|
||||
val data = AdvertiseData.Builder().setIncludeDeviceName(false)
|
||||
if (beacon.isNotEmpty()) data.addManufacturerData(company, beacon)
|
||||
@@ -228,7 +241,7 @@ object BleRadio {
|
||||
} }
|
||||
}
|
||||
advertisement = callback
|
||||
advertiser.startAdvertising(AdvertiseSettings.Builder().setConnectable(incoming)
|
||||
publisher.startAdvertising(AdvertiseSettings.Builder().setConnectable(incoming)
|
||||
.setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_LOW_LATENCY).setTimeout(0).build(), data.build(), response.build(), callback)
|
||||
}
|
||||
private fun phyResult(role: String, address: String, txPhy: Int, rxPhy: Int, status: Int) {
|
||||
@@ -250,6 +263,7 @@ object BleRadio {
|
||||
} catch (e: RuntimeException) { log("WARN", "PHY tuning unavailable address=${device.address}: ${e.message}") }
|
||||
}
|
||||
private fun connect(token: Long, address: String) {
|
||||
check(cleanup.isEmpty) { "Previous BLE cleanup pending" }
|
||||
check(links.size < 16) { "link limit" }
|
||||
val link = Link(token, checkNotNull(adapter).getRemoteDevice(address), true)
|
||||
links[token] = link
|
||||
@@ -350,10 +364,13 @@ object BleRadio {
|
||||
private fun close(link: Link, reason: String, report: Boolean = true) {
|
||||
links.remove(link.token)
|
||||
log("INFO", "Closed link=${link.token} reason=$reason")
|
||||
try {
|
||||
if (link.outgoing) { link.gatt?.disconnect(); link.gatt?.close() }
|
||||
else server?.cancelConnection(link.device)
|
||||
} catch (e: RuntimeException) { log("WARN", "Close failed: ${e.message}") }
|
||||
if (link.outgoing) link.gatt?.let { gatt ->
|
||||
try { gatt.disconnect() } catch (e: RuntimeException) { log("WARN", "Disconnect failed link=${link.token}: $e") }
|
||||
cleanup.retain(gatt, "client GATT link=${link.token}") { gatt.close() }
|
||||
} else server?.let { owner ->
|
||||
cleanup.retain(link, "incoming link=${link.token}") { if (server === owner) owner.cancelConnection(link.device) }
|
||||
}
|
||||
drainCleanup()
|
||||
if (report) emit(5, link.token, text = reason)
|
||||
pump()
|
||||
}
|
||||
@@ -361,9 +378,26 @@ object BleRadio {
|
||||
generation = 0
|
||||
worker.removeCallbacks(retry); worker.removeCallbacks(writerTimeout)
|
||||
links.values.toList().forEach { close(it, "radio stopped", false) }
|
||||
try { scan?.let { adapter?.bluetoothLeScanner?.stopScan(it) } } catch (e: RuntimeException) { log("WARN", "Stop scan: ${e.message}") }
|
||||
try { advertisement?.let { adapter?.bluetoothLeAdvertiser?.stopAdvertising(it) } } catch (e: RuntimeException) { log("WARN", "Stop advertise: ${e.message}") }
|
||||
try { server?.close() } catch (e: RuntimeException) { log("WARN", "Stop server: ${e.message}") }
|
||||
scan = null; advertisement = null; server = null; tx = null; writer = null; beacon = byteArrayOf(); incomingMtu.clear()
|
||||
scan?.let { callback -> scanner?.let { owner -> cleanup.retain(callback, "scan") { owner.stopScan(callback) } } }
|
||||
advertisement?.let { callback -> advertiser?.let { owner -> cleanup.retain(callback, "advertisement") { owner.stopAdvertising(callback) } } }
|
||||
server?.let { owner -> cleanup.retain(owner, "GATT server") { owner.close() } }
|
||||
scan = null; scanner = null; advertisement = null; advertiser = null; server = null
|
||||
tx = null; writer = null; beacon = byteArrayOf(); incomingMtu.clear()
|
||||
drainCleanup()
|
||||
}
|
||||
private val cleanupRetry = Runnable {
|
||||
if (cleanup.retry()) {
|
||||
cleanupDelay = 250
|
||||
if (generation == 0L && NativeLib.isReady() && !NativeLib.isCoreStopping()) applySettings()
|
||||
} else scheduleCleanup()
|
||||
}
|
||||
private fun drainCleanup() {
|
||||
if (cleanup.retry()) { worker.removeCallbacks(cleanupRetry); cleanupDelay = 250 }
|
||||
else scheduleCleanup()
|
||||
}
|
||||
private fun scheduleCleanup() {
|
||||
worker.removeCallbacks(cleanupRetry)
|
||||
if (!worker.postDelayed(cleanupRetry, cleanupDelay)) log("ERROR", "Cleanup timer rejected; SDK owners retained")
|
||||
cleanupDelay = (cleanupDelay * 2).coerceAtMost(30_000)
|
||||
}
|
||||
}
|
||||
@@ -9,8 +9,8 @@
|
||||
#include <pthread.h>
|
||||
#include <string.h>
|
||||
#include <sys/eventfd.h>
|
||||
#include <unistd.h>
|
||||
#include <errno.h>
|
||||
#include "platform_compat.h"
|
||||
#include "ble/ble_backend.h"
|
||||
#include "ble/ble_identity.h"
|
||||
#include "u_async.h"
|
||||
@@ -58,13 +58,17 @@ static int command(int op, jlong gen, jlong token, const char* text, const uint8
|
||||
jbyteArray data = string ? (*env)->NewByteArray(env, (jsize)len) : NULL;
|
||||
if (string && data) {
|
||||
if (len) (*env)->SetByteArrayRegion(env, data, 0, (jsize)len, (const jbyte*)bytes);
|
||||
if (!(*env)->ExceptionCheck(env)) (*env)->CallStaticVoidMethod(env, radio_class, command_method, op, gen, token, string, data, arg);
|
||||
ok = !(*env)->ExceptionCheck(env);
|
||||
if (!(*env)->ExceptionCheck(env))
|
||||
ok = (*env)->CallStaticBooleanMethod(env, radio_class, command_method, op, gen, token, string, data, arg) == JNI_TRUE;
|
||||
if (!ok && !(*env)->ExceptionCheck(env)) DEBUG_ERROR(CAT, "BLE radio rejected command op=%d", op);
|
||||
}
|
||||
if ((*env)->ExceptionCheck(env)) {
|
||||
(*env)->ExceptionDescribe(env); (*env)->ExceptionClear(env); ok = 0;
|
||||
DEBUG_ERROR(CAT, "BLE JNI command failed op=%d", op);
|
||||
}
|
||||
if ((*env)->ExceptionCheck(env)) { (*env)->ExceptionClear(env); DEBUG_ERROR(CAT, "BLE JNI command failed op=%d", op); }
|
||||
if (string) (*env)->DeleteLocalRef(env, string);
|
||||
if (data) (*env)->DeleteLocalRef(env, data);
|
||||
if (attached) (*vm)->DetachCurrentThread(vm);
|
||||
if (attached && (*vm)->DetachCurrentThread(vm) != JNI_OK) DEBUG_ERROR(CAT, "BLE JNI detach failed op=%d", op);
|
||||
return ok ? 0 : -1;
|
||||
}
|
||||
static struct android_link* by_id(struct ble_backend* b, ble_link_id id) {
|
||||
@@ -131,7 +135,7 @@ static void drain(int fd, void* arg) {
|
||||
JNIEXPORT void JNICALL Java_com_utun_chat_data_BleRadio_nativeInstall(JNIEnv* env, jclass cls) {
|
||||
if (radio_class) return; /* Application устанавливает один раз, до запуска worker. */
|
||||
if ((*env)->GetJavaVM(env, &vm) != JNI_OK) { DEBUG_ERROR(CAT, "BLE GetJavaVM failed"); return; }
|
||||
command_method = (*env)->GetStaticMethodID(env, cls, "command", "(IJJLjava/lang/String;[BI)V");
|
||||
command_method = (*env)->GetStaticMethodID(env, cls, "command", "(IJJLjava/lang/String;[BI)Z");
|
||||
if (!command_method) { DEBUG_ERROR(CAT, "BLE command method unavailable"); return; }
|
||||
radio_class = (*env)->NewGlobalRef(env, cls);
|
||||
if (!radio_class) DEBUG_ERROR(CAT, "BLE global class allocation failed");
|
||||
@@ -258,7 +262,7 @@ static void configure(void* arg) {
|
||||
cfg.callbacks.advertising = advertising;
|
||||
cfg.callbacks.status = status; cfg.callbacks.broadcast = broadcast; cfg.callbacks.validate = validate; cfg.callbacks.received = received;
|
||||
identity_len = ble_identity_encode(identity, cfg.node_id, inst->config->global.name);
|
||||
if (identity_len < 0) return;
|
||||
if (identity_len < 0) { DEBUG_ERROR(CAT, "BLE identity encoding failed node=%016llx", (unsigned long long)cfg.node_id); return; }
|
||||
transport = ble_create(instance_lite_get_uasync(), &cfg);
|
||||
if (transport) { ble_set_incoming(transport, incoming_policy); ble_start(transport); }
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user