adjust scan intervals and reduce logging

This commit is contained in:
callebtc
2025-07-13 17:16:31 +02:00
parent 0cb4497444
commit 2a0f84b53b
5 changed files with 47 additions and 56 deletions
@@ -189,7 +189,7 @@ class MainActivity : ComponentActivity() {
* Check Bluetooth status and proceed with onboarding flow * Check Bluetooth status and proceed with onboarding flow
*/ */
private fun checkBluetoothAndProceed() { private fun checkBluetoothAndProceed() {
android.util.Log.d("MainActivity", "Checking Bluetooth status") // android.util.Log.d("MainActivity", "Checking Bluetooth status")
// For first-time users, skip Bluetooth check and go straight to permissions // For first-time users, skip Bluetooth check and go straight to permissions
// We'll check Bluetooth after permissions are granted // We'll check Bluetooth after permissions are granted
@@ -148,7 +148,7 @@ class BluetoothConnectionManager(
startPeriodicCleanup() startPeriodicCleanup()
Log.i(TAG, "Power-optimized Bluetooth services started successfully") Log.i(TAG, "Bluetooth services started successfully")
} }
return true return true
@@ -254,7 +254,8 @@ class BluetoothConnectionManager(
*/ */
fun getDebugInfo(): String { fun getDebugInfo(): String {
return buildString { return buildString {
appendLine("=== Power-Optimized Bluetooth Connection Manager ===") appendLine("=== Bluetooth Connection Manager ===")
appendLine("Bluetooth MAC Address: ${bluetoothAdapter?.address}")
appendLine("Active: $isActive") appendLine("Active: $isActive")
appendLine("Bluetooth Enabled: ${bluetoothAdapter?.isEnabled}") appendLine("Bluetooth Enabled: ${bluetoothAdapter?.isEnabled}")
appendLine("Has Permissions: ${hasBluetoothPermissions()}") appendLine("Has Permissions: ${hasBluetoothPermissions()}")
@@ -586,7 +587,6 @@ class BluetoothConnectionManager(
// DEBUG: Log ALL scan results first // DEBUG: Log ALL scan results first
val device = result.device val device = result.device
val rssi = result.rssi val rssi = result.rssi
val scanRecord = result.scanRecord
Log.d(TAG, "Scan result: device: ${device.address}, Name: '${device.name}', RSSI: $rssi") Log.d(TAG, "Scan result: device: ${device.address}, Name: '${device.name}', RSSI: $rssi")
handleScanResult(result) handleScanResult(result)
} }
@@ -675,7 +675,7 @@ class BluetoothConnectionManager(
null null
} }
Log.d(TAG, "Processing bitchat device: $deviceAddress, name: '$deviceName', peerID: $extractedPeerID, RSSI: $rssi") // Log.d(TAG, "Processing bitchat device: $deviceAddress, name: '$deviceName', peerID: $extractedPeerID, RSSI: $rssi")
// Power-aware RSSI filtering // Power-aware RSSI filtering
if (rssi < powerManager.getRSSIThreshold()) { if (rssi < powerManager.getRSSIThreshold()) {
@@ -686,7 +686,7 @@ class BluetoothConnectionManager(
// CRITICAL FIX: Prevent multiple simultaneous connections to same device // CRITICAL FIX: Prevent multiple simultaneous connections to same device
// Check if already connected OR already attempting to connect // Check if already connected OR already attempting to connect
if (connectedDevices.containsKey(deviceAddress)) { if (connectedDevices.containsKey(deviceAddress)) {
Log.d(TAG, "Device $deviceAddress already connected, skipping") // Log.d(TAG, "Device $deviceAddress already connected, skipping")
return return
} }
@@ -717,12 +717,6 @@ class BluetoothConnectionManager(
val attempts = (currentAttempt?.attempts ?: 0) + 1 val attempts = (currentAttempt?.attempts ?: 0) + 1
pendingConnections[deviceAddress] = ConnectionAttempt(attempts) pendingConnections[deviceAddress] = ConnectionAttempt(attempts)
if (extractedPeerID != null) {
Log.i(TAG, "Initiating connection to peer $extractedPeerID at $deviceAddress (RSSI: $rssi, attempt: $attempts)")
} else {
Log.i(TAG, "Initiating connection to device with bitchat service at $deviceAddress (RSSI: $rssi, attempt: $attempts)")
}
// Start connection immediately while holding lock // Start connection immediately while holding lock
connectToDevice(device, rssi) connectToDevice(device, rssi)
} }
@@ -733,6 +727,7 @@ class BluetoothConnectionManager(
if (!hasBluetoothPermissions()) return if (!hasBluetoothPermissions()) return
val deviceAddress = device.address val deviceAddress = device.address
Log.d(TAG, "Connecting to device: $deviceAddress")
val gattCallback = object : BluetoothGattCallback() { val gattCallback = object : BluetoothGattCallback() {
override fun onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) { override fun onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) {
@@ -795,9 +790,7 @@ class BluetoothConnectionManager(
} }
} }
override fun onServicesDiscovered(gatt: BluetoothGatt, status: Int) { override fun onServicesDiscovered(gatt: BluetoothGatt, status: Int) {
Log.d(TAG, "Client: Service discovery completed for $deviceAddress with status: $status")
if (status == BluetoothGatt.GATT_SUCCESS) { if (status == BluetoothGatt.GATT_SUCCESS) {
val service = gatt.getService(SERVICE_UUID) val service = gatt.getService(SERVICE_UUID)
if (service != null) { if (service != null) {
@@ -854,16 +847,16 @@ class BluetoothConnectionManager(
} }
try { try {
Log.d(TAG, "Attempting GATT connection to $deviceAddress with autoConnect=false") Log.d(TAG, "Client: Attempting GATT connection to $deviceAddress with autoConnect=false")
val gatt = device.connectGatt(context, false, gattCallback, BluetoothDevice.TRANSPORT_LE) val gatt = device.connectGatt(context, false, gattCallback, BluetoothDevice.TRANSPORT_LE)
if (gatt == null) { if (gatt == null) {
Log.e(TAG, "connectGatt returned null for $deviceAddress") Log.e(TAG, "connectGatt returned null for $deviceAddress")
pendingConnections.remove(deviceAddress) pendingConnections.remove(deviceAddress)
} else { } else {
Log.d(TAG, "GATT connection initiated successfully for $deviceAddress") Log.d(TAG, "Client: GATT connection initiated successfully for $deviceAddress")
} }
} catch (e: Exception) { } catch (e: Exception) {
Log.e(TAG, "Exception connecting to $deviceAddress: ${e.message}") Log.e(TAG, "Client: Exception connecting to $deviceAddress: ${e.message}")
pendingConnections.remove(deviceAddress) pendingConnections.remove(deviceAddress)
} }
} }
@@ -291,9 +291,7 @@ class BluetoothMeshService(private val context: Context) {
Log.i(TAG, "Starting Bluetooth mesh service with peer ID: $myPeerID") Log.i(TAG, "Starting Bluetooth mesh service with peer ID: $myPeerID")
if (connectionManager.startServices()) { if (connectionManager.startServices()) {
isActive = true isActive = true
Log.i(TAG, "Bluetooth services started successfully")
// Send initial announcements after services are ready // Send initial announcements after services are ready
serviceScope.launch { serviceScope.launch {
delay(1000) delay(1000)
@@ -26,12 +26,12 @@ class PowerManager(private val context: Context) {
private const val MEDIUM_BATTERY = 50 private const val MEDIUM_BATTERY = 50
// Scan duty cycle periods (ms) // Scan duty cycle periods (ms)
private const val SCAN_ON_DURATION_NORMAL = 2000L // 2 seconds on private const val SCAN_ON_DURATION_NORMAL = 8000L // 8 seconds on
private const val SCAN_OFF_DURATION_NORMAL = 8000L // 8 seconds off private const val SCAN_OFF_DURATION_NORMAL = 2000L // 2 seconds off
private const val SCAN_ON_DURATION_POWER_SAVE = 1000L // 1 second on private const val SCAN_ON_DURATION_POWER_SAVE = 2000L // 2 seconds on
private const val SCAN_OFF_DURATION_POWER_SAVE = 15000L // 15 seconds off private const val SCAN_OFF_DURATION_POWER_SAVE = 8000L // 8 seconds off
private const val SCAN_ON_DURATION_ULTRA_LOW = 500L // 0.5 seconds on private const val SCAN_ON_DURATION_ULTRA_LOW = 1000L // 1 second on
private const val SCAN_OFF_DURATION_ULTRA_LOW = 30000L // 30 seconds off private const val SCAN_OFF_DURATION_ULTRA_LOW = 10000L // 10 seconds off
// Connection limits // Connection limits
private const val MAX_CONNECTIONS_NORMAL = 8 private const val MAX_CONNECTIONS_NORMAL = 8
@@ -112,38 +112,38 @@ class PowerManager(private val context: Context) {
/** /**
* Get scan settings optimized for current power mode * Get scan settings optimized for current power mode
*/ */
fun getScanSettings(): ScanSettings { fun getScanSettings(): ScanSettings {
// CRITICAL FIX: Set reportDelay to 0 for all modes. // CRITICAL FIX: Set reportDelay to 0 for all modes.
// When using a custom duty cycle, we want scan results delivered immediately, // When using a custom duty cycle, we want scan results delivered immediately,
// not batched. A non-zero report delay can conflict with the scan window, // not batched. A non-zero report delay can conflict with the scan window,
// causing missed results if the scan stops before the delay is met. // causing missed results if the scan stops before the delay is met.
val builder = ScanSettings.Builder() val builder = ScanSettings.Builder()
.setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES) .setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES)
when (currentMode) { when (currentMode) {
PowerMode.PERFORMANCE -> builder PowerMode.PERFORMANCE -> builder
.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY) .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
.setMatchMode(ScanSettings.MATCH_MODE_AGGRESSIVE) .setMatchMode(ScanSettings.MATCH_MODE_AGGRESSIVE)
.setNumOfMatches(ScanSettings.MATCH_NUM_MAX_ADVERTISEMENT) .setNumOfMatches(ScanSettings.MATCH_NUM_MAX_ADVERTISEMENT)
PowerMode.BALANCED -> builder PowerMode.BALANCED -> builder
.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY) .setScanMode(ScanSettings.SCAN_MODE_BALANCED)
.setMatchMode(ScanSettings.MATCH_MODE_AGGRESSIVE) .setMatchMode(ScanSettings.MATCH_MODE_AGGRESSIVE)
.setNumOfMatches(ScanSettings.MATCH_NUM_ONE_ADVERTISEMENT) .setNumOfMatches(ScanSettings.MATCH_NUM_ONE_ADVERTISEMENT)
PowerMode.POWER_SAVER -> builder PowerMode.POWER_SAVER -> builder
.setScanMode(ScanSettings.SCAN_MODE_LOW_POWER) .setScanMode(ScanSettings.SCAN_MODE_LOW_POWER)
.setMatchMode(ScanSettings.MATCH_MODE_STICKY) .setMatchMode(ScanSettings.MATCH_MODE_STICKY)
.setNumOfMatches(ScanSettings.MATCH_NUM_ONE_ADVERTISEMENT) .setNumOfMatches(ScanSettings.MATCH_NUM_ONE_ADVERTISEMENT)
PowerMode.ULTRA_LOW_POWER -> builder PowerMode.ULTRA_LOW_POWER -> builder
.setScanMode(ScanSettings.SCAN_MODE_OPPORTUNISTIC) .setScanMode(ScanSettings.SCAN_MODE_OPPORTUNISTIC)
.setMatchMode(ScanSettings.MATCH_MODE_STICKY) .setMatchMode(ScanSettings.MATCH_MODE_STICKY)
.setNumOfMatches(ScanSettings.MATCH_NUM_ONE_ADVERTISEMENT) .setNumOfMatches(ScanSettings.MATCH_NUM_ONE_ADVERTISEMENT)
}
return builder.setReportDelay(0).build()
} }
return builder.setReportDelay(0).build()
}
/** /**
* Get advertising settings optimized for current power mode * Get advertising settings optimized for current power mode
@@ -91,7 +91,7 @@ class BluetoothStatusManager(
* This should be called on every app startup * This should be called on every app startup
*/ */
fun checkBluetoothStatus(): BluetoothStatus { fun checkBluetoothStatus(): BluetoothStatus {
Log.d(TAG, "Checking Bluetooth status") // Log.d(TAG, "Checking Bluetooth status")
return when { return when {
bluetoothAdapter == null -> { bluetoothAdapter == null -> {
@@ -103,7 +103,7 @@ class BluetoothStatusManager(
BluetoothStatus.DISABLED BluetoothStatus.DISABLED
} }
else -> { else -> {
Log.d(TAG, "Bluetooth is enabled and ready") // Log.d(TAG, "Bluetooth is enabled and ready")
BluetoothStatus.ENABLED BluetoothStatus.ENABLED
} }
} }