Проблема отключения устройства Android BLEAndroid

Форум для тех, кто программирует под Android
Ответить
Anonymous
 Проблема отключения устройства Android BLE

Сообщение Anonymous »

У меня есть приложение для Android в том, что я пытаюсь подключить датчики с помощью сканирования. Он сканирует и находит мое устройство с фильтром, но когда он пытается подключиться, оно отключается и дает состояние ошибки, как 133, 257 или 147, поэтому я очищаю кэш ГАТТ и закрываю ГАТТ и пытаюсь снова подключиться к одному устройству, но он продолжает отключать. Что я могу сделать или как решить эту проблему отключения в Android? Я пытался перезагрузить устройство, и все еще не работало < /p>
всякий раз, когда я получаю состояние отключения, как 133, 257 или 147, затем я очищаю кэш GATT и закрываю GATT и пытаюсь снова подключиться к одному устройству, но он продолжает постоянно провалиться < /p>

private val bleScanCallback = object : ScanCallback(){
override fun onScanResult(callbackType: Int, result: ScanResult) {
super.onScanResult(callbackType, result)
Log.e("ProtocolSwitch","Handle Scan Result method called")
handleScanResult(result)
}

override fun onBatchScanResults(results: MutableList) {
super.onBatchScanResults(results)
for (result in results){
handleScanResult(result)
}
} @SuppressLint("MissingPermission")
private fun startBleScan() {
val scanFilter = ScanFilter.Builder()
.setManufacturerData(0x0DCF, ByteArray(0))
val scanSettings =
ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build()
val scanner = bluetoothAdapter.bluetoothLeScanner

if (scanner != null) {
scanner.startScan(listOf(scanFilter), scanSettings, bleScanCallback)
Log.e("ProtocolSwitch","Starting Ble Scan")
startScanTimer()
} else {
Log.e("BLE", "Bluetooth LE Scanner not available")
}
} @SuppressLint("MissingPermission")
private fun stopBleScan() {
scanTimer?.cancel()
bluetoothAdapter.bluetoothLeScanner?.stopScan(bleScanCallback)
Log.e("ProtocolSwitch","Stopping Ble Scan")
} private fun startScanTimer() {
scanTimer?.cancel() // Cancel any existing timer
scanTimer = object : CountDownTimer(90000, 1000) {
override fun onTick(millisUntilFinished: Long) {
val secondsRemaining = millisUntilFinished / 1000
targetNode?.let { node ->
Log.d("ProtocolSwitch", "Scanning for ${node.sNo}: $secondsRemaining seconds remaining")
}
}

override fun onFinish() {
targetNode?.let { node ->
Log.e("ProtocolSwitch", "Scan timed out for ${node.sNo} - device not found")
}
// Stop BLE scan and move to next node
stopBleScan()
moveToNextNode()
}
}.start()
} @SuppressLint("MissingPermission")
private fun handleScanResult(result: ScanResult) {
Log.e("ProtocolSwicth","Inside the Handle Scan Method")
val manufacturerData = result.scanRecord?.getManufacturerSpecificData(0x0DCF)
val deviceMacId = result.device.address
Log.e("ProtocolSwitch","Manufacturer Data $deviceMacId")
Log.e("ProtocolSwitch","Manufacturer Data TargetDevice $targetDeviceAddress")
if (manufacturerData != null) {
if(deviceMacId.equals(targetDeviceAddress,ignoreCase = true)){
Log.e("ProtocolSwitch","Device Mac Id $deviceMacId")
Log.e("ProtocolSwitch","Target Device Address $targetDeviceAddress")
Log.e("ProtocolSwitch","Target Node $targetNode")
Log.e("ProtocolSwitch","Calling Connect To device Method")
stopBleScan()
targetNode?.let { connectToDevice(targetDeviceAddress, it) }

}
}
} @SuppressLint("MissingPermission")
private val gattCallback = object : BluetoothGattCallback() {
override fun onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) {
if (newState == BluetoothProfile.STATE_CONNECTED){
Log.e("ProtocolSwitch","Connection timer cancel")
scanTimer?.cancel()
stopBleScan()
gatt.discoverServices()
Log.e("SensorUpgradeActivity", "Connected to GATT server.")
}else if (newState == BluetoothProfile.STATE_DISCONNECTED){
bluetoothGatt = null
Log.e("Disconnected", "Disconnected from GATT server. $status")
if(status==133 || status == 147 || status ==257){
clearGattCache(gatt)
bluetoothGatt?.close()
disconnectGatt()
}

}
}
override fun onServicesDiscovered(gatt: BluetoothGatt, status: Int) {
if (status == BluetoothGatt.GATT_SUCCESS){
Log.e("SensorUpgradeActivity", "Services discovered.")
writeEncryptedData()
}
}
} private fun clearGattCache(gatt: BluetoothGatt?) {
try {
val refreshMethod = gatt?.javaClass?.getMethod("refresh")
val result = refreshMethod?.invoke(gatt) as Boolean

Log.i("BLE", "GATT cache cleared: $result")
} catch (exception: Exception) {
Log.e("BLE", "Error clearing GATT cache: ${exception.message}")
}
}


Подробнее здесь: https://stackoverflow.com/questions/796 ... tion-issue
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Android»