feat: store scanning results
This commit is contained in:
@@ -27,6 +27,8 @@ import androidx.navigation.ui.AppBarConfiguration
|
||||
import androidx.navigation.ui.navigateUp
|
||||
import androidx.navigation.ui.setupActionBarWithNavController
|
||||
import com.example.sensortestingapp.databinding.ActivityMainBinding
|
||||
import java.util.stream.Collectors
|
||||
import java.util.stream.Collectors.toList
|
||||
|
||||
private const val ENABLE_BLUETOOTH_REQUEST_CODE = 1
|
||||
|
||||
@@ -46,6 +48,7 @@ fun Context.hasRequiredRuntimePermissions(): Boolean {
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressLint("MissingPermission")
|
||||
class MainActivity : AppCompatActivity() {
|
||||
|
||||
private lateinit var appBarConfiguration: AppBarConfiguration
|
||||
@@ -72,6 +75,8 @@ class MainActivity : AppCompatActivity() {
|
||||
}
|
||||
}
|
||||
|
||||
private var scanResults: MutableMap<String, ScanResult> = HashMap();
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
WindowCompat.setDecorFitsSystemWindows(window, false)
|
||||
super.onCreate(savedInstanceState)
|
||||
@@ -186,26 +191,45 @@ class MainActivity : AppCompatActivity() {
|
||||
@SuppressLint("MissingPermission")
|
||||
val scanCallback = object : ScanCallback() {
|
||||
override fun onScanResult(callbackType: Int, result: ScanResult) {
|
||||
with(result.device) {
|
||||
Log.i(
|
||||
"ScanCallback",
|
||||
"Found BLE device! Name: ${name ?: "Unnamed"}, address: $address"
|
||||
)
|
||||
}
|
||||
|
||||
scanResults.merge(result.device.address, result, fun(o, n): ScanResult {
|
||||
return if (n.rssi >= o.rssi) n else o;
|
||||
})
|
||||
val displayScanResults = getDisplayScanResults();
|
||||
Log.i(
|
||||
"ScanCallback",
|
||||
"Found BLE device ${result.device.name ?: result.device.address} (rssi: ${result.rssi}). Current scan results (${displayScanResults.size}): ${
|
||||
toDebugScanResults(displayScanResults)
|
||||
}"
|
||||
)
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressLint("MissingPermission")
|
||||
private fun getDisplayScanResults(): List<ScanResult> {
|
||||
return scanResults.values.stream()
|
||||
.filter { r -> r.rssi > -80 }
|
||||
.sorted { r1, r2 -> Integer.compare(r2.rssi, r1.rssi) }
|
||||
.collect(toList())
|
||||
}
|
||||
|
||||
private fun toDebugScanResults(scanResults: List<ScanResult>): String {
|
||||
return scanResults.stream()
|
||||
.map { r -> "${r.device.name ?: r.device.address} (${r.rssi})" }
|
||||
.collect(Collectors.joining(", "))
|
||||
}
|
||||
|
||||
|
||||
private fun startBleScan() {
|
||||
if (!hasRequiredRuntimePermissions()) {
|
||||
requestRelevantRuntimePermissions()
|
||||
} else {
|
||||
scanResults.clear()
|
||||
bleScanner.startScan(null, scanSettings, scanCallback)
|
||||
isScanning = true
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressLint("MissingPermission")
|
||||
private fun stopBleScan() {
|
||||
bleScanner.stopScan(scanCallback)
|
||||
isScanning = false
|
||||
|
||||
Reference in New Issue
Block a user