Add the Android nearby Bluetooth device list
This commit is contained in:
1 parent
328a757564
commit
236016e670
3 files changed
+92
-2
No files matched your search
@@ -257,6 +257,8 @@ object NativeLib {
|
||||
fun transferAdmin(channelId: String, nodeId: Long) { nativeTransferAdmin(channelId, nodeId) }
|
||||
fun deleteChannel(channelId: String) { nativeDeleteChannel(channelId) }
|
||||
fun getMemberLinks(nodeId: Long): String = checkNotNull(nativeGetMemberLinks(nodeId)) { "Member links unavailable node=$nodeId" }
|
||||
/** Свежие BLE-соседи; синхронный запрос worker, вызывать на IO. Адрес обновляется каждым объявлением. */
|
||||
fun getBluetoothPeers(): String = checkNotNull(nativeGetBluetoothPeers()) { "Bluetooth devices snapshot unavailable" }
|
||||
|
||||
/* ── Local sockets (for auto-mode display) ── */
|
||||
fun requestLocalSockets() = nativeRequestLocalSockets()
|
||||
@@ -499,6 +501,7 @@ object NativeLib {
|
||||
private external fun nativeRegenerateKeys(configText: String): Boolean
|
||||
private external fun nativeClearDatabase(dbPath: String): Boolean
|
||||
private external fun nativeGetMyNodeId(): Long
|
||||
private external fun nativeGetBluetoothPeers(): String?
|
||||
private external fun nativeRequestInviteCandidates(channelId: String): Boolean
|
||||
private external fun nativeRequestInviteLink(channelId: String, targetNodeId: Long, requestId: Long): Boolean
|
||||
private external fun nativeRequestLocalDevices(): Boolean
|
||||
|
||||
+53
-1
@@ -6,16 +6,29 @@ import android.content.Intent
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.text.selection.SelectionContainer
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalLifecycleOwner
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import com.utun.chat.ChatApplication
|
||||
import com.utun.chat.R
|
||||
import com.utun.chat.data.BleRadio
|
||||
import com.utun.chat.data.LogManager
|
||||
import com.utun.chat.data.NativeLib
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.isActive
|
||||
import kotlinx.coroutines.withContext
|
||||
import org.json.JSONArray
|
||||
|
||||
private data class BluetoothPeer(val id: String, val name: String, val address: String, val rssi: Int)
|
||||
|
||||
/** Снимок DataStore без чтения диска на main; принятые записи принадлежат Application.
|
||||
* Разрешения/включение адаптера подтверждаются Android, ошибки запуска показываются в этой вкладке. */
|
||||
@@ -33,6 +46,30 @@ fun BluetoothSettingsTab() {
|
||||
val settingFailed by provider.changes.failed.collectAsState()
|
||||
val state by BleRadio.state.collectAsState()
|
||||
val advertisingState by BleRadio.advertisingState.collectAsState()
|
||||
val lifecycle by LocalLifecycleOwner.current.lifecycle.currentStateFlow.collectAsState()
|
||||
var peers by remember { mutableStateOf(emptyList<BluetoothPeer>()) }
|
||||
var peersFailed by remember { mutableStateOf(false) }
|
||||
LaunchedEffect(state, lifecycle) {
|
||||
if (state != 1) { peers = emptyList(); peersFailed = false; return@LaunchedEffect }
|
||||
if (!lifecycle.isAtLeast(Lifecycle.State.STARTED)) return@LaunchedEffect
|
||||
while (isActive) {
|
||||
try {
|
||||
peers = withContext(Dispatchers.IO) {
|
||||
val snapshot = JSONArray(NativeLib.getBluetoothPeers())
|
||||
List(snapshot.length()) { i ->
|
||||
val peer = snapshot.getJSONObject(i)
|
||||
BluetoothPeer(peer.getString("id"), peer.getString("name"), peer.getString("address"), peer.getInt("rssi"))
|
||||
}.sortedWith(compareBy<BluetoothPeer> { it.name }.thenBy { it.id })
|
||||
}
|
||||
peersFailed = false
|
||||
} catch (e: CancellationException) { throw e }
|
||||
catch (e: Exception) {
|
||||
peersFailed = true
|
||||
LogManager.addLog("WARN", "discovery", "BLE devices snapshot failed: $e")
|
||||
}
|
||||
delay(1000)
|
||||
}
|
||||
}
|
||||
fun save(bit: Int, enabled: Boolean) { provider.changes.submit("Bluetooth settings") { provider.setBleFlag(bit, enabled) } }
|
||||
val enable = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) {
|
||||
if (it.resultCode == android.app.Activity.RESULT_OK) { denied = false; save(1, true) } else denied = true
|
||||
@@ -48,7 +85,7 @@ fun BluetoothSettingsTab() {
|
||||
try { if (BleRadio.permitted()) activate() else denied = true }
|
||||
catch (e: Exception) { failed = true; LogManager.addLog("ERROR", "discovery", "Bluetooth permission result failed: $e") }
|
||||
}
|
||||
Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
Column(Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
|
||||
Text(stringResource(R.string.ble_enabled))
|
||||
Switch(enabled = confirmedFlags != null, checked = flags and 1 != 0, onCheckedChange = {
|
||||
@@ -82,5 +119,20 @@ fun BluetoothSettingsTab() {
|
||||
if (confirmedFlags == null) LinearProgressIndicator(Modifier.fillMaxWidth())
|
||||
if (settingFailed) Text(stringResource(R.string.settings_update_failed), color = MaterialTheme.colorScheme.error)
|
||||
if (failed || (state == 1 && flags and 2 != 0 && advertisingState == 2)) Text(stringResource(R.string.ble_failed), color = MaterialTheme.colorScheme.error)
|
||||
if (state == 1) {
|
||||
HorizontalDivider()
|
||||
Text(stringResource(R.string.ble_devices), style = MaterialTheme.typography.titleMedium)
|
||||
if (peersFailed) Text(stringResource(R.string.ble_devices_failed), color = MaterialTheme.colorScheme.error)
|
||||
else if (peers.isEmpty()) Text(stringResource(R.string.ble_devices_empty), style = MaterialTheme.typography.bodySmall)
|
||||
peers.forEach { peer ->
|
||||
key(peer.id) {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||
Text(peer.name.ifEmpty { peer.id }, style = MaterialTheme.typography.bodyLarge)
|
||||
SelectionContainer { Text(peer.address, style = MaterialTheme.typography.bodyMedium) }
|
||||
Text("${peer.id} · ${if (peer.rssi == 127) "?" else peer.rssi} dBm", style = MaterialTheme.typography.bodySmall)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -61,6 +61,8 @@
|
||||
#include <jni.h>
|
||||
#include <android/log.h>
|
||||
#include <pthread.h>
|
||||
#include "android_ble.h"
|
||||
#include "../../cgathui_common/ble_etcp.h"
|
||||
#define LOG_TAG "utun-bridge"
|
||||
#else
|
||||
#define ANDROID_LOG_VERBOSE 2
|
||||
@@ -1596,8 +1598,29 @@ static jobject g_event_callback = NULL;
|
||||
static jmethodID g_event_mid = NULL;
|
||||
static pthread_mutex_t g_event_callback_lock = PTHREAD_MUTEX_INITIALIZER;
|
||||
|
||||
/* Только worker: свежая таблица BLE, включая текущий адрес объявления и неизвестный RSSI=127. */
|
||||
static char* bluetooth_peers_json(void) {
|
||||
struct ble_neighbor peers[BLE_NEIGHBORS_MAX];
|
||||
size_t count = ble_etcp_neighbors(android_ble_driver(), peers, BLE_NEIGHBORS_MAX);
|
||||
struct strbuf out = strbuf_new();
|
||||
if (strbuf_addf(&out, "[") < 0) goto failed;
|
||||
for (size_t i = 0; i < count; i++) {
|
||||
const struct ble_neighbor* p = &peers[i];
|
||||
if (strbuf_addf(&out, "%s{\"id\":\"%016llx\",\"name\":", i ? "," : "", (unsigned long long)p->identity.node_id) < 0 ||
|
||||
strbuf_add_json_string(&out, p->identity.name) < 0 || strbuf_addf(&out, ",\"address\":") < 0 ||
|
||||
strbuf_add_json_string(&out, p->endpoint.id) < 0 || strbuf_addf(&out, ",\"rssi\":%d}", p->rssi) < 0) goto failed;
|
||||
}
|
||||
if (strbuf_addf(&out, "]") < 0) goto failed;
|
||||
DEBUG_DEBUG(DEBUG_CATEGORY_DISCOVERY, "BLE devices snapshot count=%zu", count);
|
||||
return strbuf_detach(&out);
|
||||
failed:
|
||||
DEBUG_ERROR(DEBUG_CATEGORY_DISCOVERY, "BLE devices snapshot allocation/serialization failed count=%zu", count);
|
||||
strbuf_free(&out); return NULL;
|
||||
}
|
||||
|
||||
enum bridge_query_kind { QUERY_CHANNELS, QUERY_MESSAGES, QUERY_MEMBERS, QUERY_DETAIL, QUERY_LINKS, QUERY_NODE, QUERY_SET_NICK, QUERY_DM_START,
|
||||
QUERY_OWNER, QUERY_MEMBERSHIP, QUERY_SETTING, QUERY_SOUND, QUERY_RADIO_SUBSCRIBERS, QUERY_RADIO_START };
|
||||
QUERY_OWNER, QUERY_MEMBERSHIP, QUERY_SETTING, QUERY_SOUND, QUERY_RADIO_SUBSCRIBERS, QUERY_RADIO_START,
|
||||
QUERY_BLUETOOTH_PEERS };
|
||||
/* Строки/ID заимствованы до возврата instance_lite_call; JSON становится собственностью JNI caller. */
|
||||
struct bridge_query {
|
||||
enum bridge_query_kind kind;
|
||||
@@ -1617,6 +1640,7 @@ static void bridge_query_run(void* arg) {
|
||||
case QUERY_MEMBERS: q->json = utun_bridge_get_channel_members_json(q->channel); break;
|
||||
case QUERY_DETAIL: q->json = utun_bridge_get_member_detail_json(q->channel, q->node); break;
|
||||
case QUERY_LINKS: q->json = utun_bridge_get_member_links_json(q->node); break;
|
||||
case QUERY_BLUETOOTH_PEERS: q->json = bluetooth_peers_json(); break;
|
||||
case QUERY_NODE: q->number = (int64_t)utun_bridge_get_my_node_id(); break;
|
||||
case QUERY_SET_NICK: utun_bridge_set_member_nick(q->channel, q->node, q->value); break;
|
||||
case QUERY_DM_START:
|
||||
@@ -2889,6 +2913,17 @@ JNIEXPORT jstring JNICALL Java_com_utun_chat_data_NativeLib_nativeGetMemberLinks
|
||||
return result;
|
||||
}
|
||||
|
||||
/* Синхронный снимок из worker; Kotlin вызывает на Dispatchers.IO, UTF-8 не теряется в JNI. */
|
||||
JNIEXPORT jstring JNICALL Java_com_utun_chat_data_NativeLib_nativeGetBluetoothPeers(JNIEnv* env, jobject thiz) {
|
||||
(void)thiz;
|
||||
struct bridge_query query = {.kind = QUERY_BLUETOOTH_PEERS};
|
||||
if (bridge_query_call(&query) || !query.json) return NULL;
|
||||
jstring result = jni_text(env, query.json);
|
||||
u_free(query.json);
|
||||
if (!result) DEBUG_ERROR(DEBUG_CATEGORY_DISCOVERY, "BLE devices snapshot: Java string allocation failed");
|
||||
return result;
|
||||
}
|
||||
|
||||
/* ── Local sockets JSON ── */
|
||||
|
||||
static void local_sockets_trampoline(void* arg) {
|
||||
|
||||
Reference in new issue
Block a user