Ich versuche, einige Daten an ein BLE-Gerät zu senden, aber aus irgendeinem Grund heißt es, dass die Daten erfolgreich gesendet wurden, aber tatsächlich macht das BLE nichts, da ich dasselbe in iOS implementiert habe und es ordnungsgemäß funktioniert.
Ich stelle den Code von iOS und Android zur Verfügung. Bitte helfen Sie mir.
Android-Code
Ich versuche, einige Daten an ein BLE-Gerät zu senden, aber aus irgendeinem Grund heißt es, dass die Daten erfolgreich gesendet wurden, aber tatsächlich macht das BLE nichts, da ich dasselbe in iOS implementiert habe und es ordnungsgemäß funktioniert. Ich stelle den Code von iOS und Android zur Verfügung. Bitte helfen Sie mir. Android-Code [code]private val UART_SERVICE_UUID = UUID.fromString("00000077-0000-1000-8000-00805f9b34fb") private val UART_RX_TX_CHARACTERISTIC_UUID = UUID.fromString("0000ff01-0000-1000-8000-00805f9b34fb") private val CLIENT_CONFIG_DESCRIPTOR_UUID = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb")
class BluetoothManager(private val context: Context) {
private val TAG = "BluetoothManager"
private val systemBluetoothManager = context.getSystemService(Context.BLUETOOTH_SERVICE) as android.bluetooth.BluetoothManager
private val bluetoothAdapter: BluetoothAdapter? = systemBluetoothManager.adapter
// Scanning private val _discoveredDevices = MutableStateFlow(emptyList()) val discoveredDevices: StateFlow = _discoveredDevices.asStateFlow()
// Connection & Data private val _connectionStatus = MutableStateFlow("Disconnected") val connectionStatus: StateFlow = _connectionStatus.asStateFlow()
private val _receivedData = MutableStateFlow("") val receivedData: StateFlow = _receivedData.asStateFlow()
private var gatt: BluetoothGatt? = null private var rxTxCharacteristic: BluetoothGattCharacteristic? = null private var isReadyToSend = false // True only after notifications enabled
private val leScanCallback: ScanCallback = object : ScanCallback() { override fun onScanResult(callbackType: Int, result: ScanResult) { val device = result.device val deviceAddress = device.address val rssi = result.rssi
val deviceName = if (ContextCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED) { device.name ?: "Unknown" } else { "Unknown (Permission Required)" }
if (deviceName.contains("Unknown", ignoreCase = true)) return
val currentList = _discoveredDevices.value.toMutableList() val newDevice = BLEDevice(device, deviceName, deviceAddress, rssi)
@SuppressLint("MissingPermission") fun stopBleScan() { if (ContextCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED) return bluetoothAdapter?.bluetoothLeScanner?.stopScan(leScanCallback) }
fun clearDiscoveredDevices() { _discoveredDevices.value = emptyList() }
// Connection @SuppressLint("MissingPermission") fun connect(device: BluetoothDevice) { if (bluetoothAdapter?.isEnabled != true) { _connectionStatus.value = "Bluetooth Off" return } if (ContextCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) { _connectionStatus.value = "Permission Missing" return }
_connectionStatus.value = "Connecting..." cleanupGatt() gatt = device.connectGatt(context, false, gattCallback) } @SuppressLint("MissingPermission") fun writeData(command: String) { if (!isReadyToSend) { Log.w(TAG, "Not ready to send yet") return }
val char = rxTxCharacteristic ?: return
val fullCommand = "$command\r\n" val data = fullCommand.toByteArray(Charsets.UTF_8) val hex = data.joinToString(" ") { "%02X".format(it) } Log.d(TAG, "Sending Data → HEX: [$hex] Text: \"$fullCommand\"")
char.value = data val success = gatt?.writeCharacteristic(char) ?: false if (!success) Log.e(TAG, "Failed to queue write") }
fun clearReceivedData() { _receivedData.value = "" } } [/code] Der Code ist UUID ist korrekt, weil ich eine Verbindung zum BLE herstellen kann, also muss es noch etwas anderes geben? [code]Button( onClick = { coroutineScope.launch { bluetoothManager.writeData("PLAY") delay(4000) bluetoothManager.writeData("Rd1") delay(4000) bluetoothManager.writeData("Rd0") } }, enabled = isReady ) { Text("Send PLAY → Rd1 → Rd0 Sequence") } [/code] iOS-Code [code]import CoreBluetooth import Foundation
final class BlueToothManager: NSObject {
static let shared = BlueToothManager() var scanningState: Bool = false var centralManager: CBCentralManager! var discoveredDevices: [UUID: BLEDevice] = [:] var deviceConnectionState: ConnectionState = .disconnected weak var bluetoothDelegate: BlueToothManagerDelegate? private var connectionTimeoutTimer: Timer? private override init() { super.init() centralManager = CBCentralManager(delegate: self, queue: .main) } } /// It initiallly check for the state of the bluetooth i.e if its on , off etc. extension BlueToothManager: CBCentralManagerDelegate { func centralManagerDidUpdateState(_ central: CBCentralManager) { switch central.state { case .unknown: print("Bluetooth: Unknown state") case .resetting: print("Bluetooth: Resetting") case .unsupported: print("Bluetooth: Device does NOT support Bluetooth") case .unauthorized: print("Bluetooth: Permission DENIED") case .poweredOff: print("Bluetooth: OFF") case .poweredOn: print("Bluetooth: ON") self.startScanning() @unknown default: break } } }
/// Functions for scanning bluetooth devices extension BlueToothManager { func startScanning(){ guard centralManager.state == .poweredOn else { //TODO: need to show pop-up for turning on the bluetooth return } discoveredDevices = [:] scanningState = true bluetoothDelegate?.onScanningStateChange(scanningState) centralManager .scanForPeripherals( withServices: nil, options: [CBCentralManagerScanOptionAllowDuplicatesKey: false] ) DispatchQueue.main.asyncAfter(deadline: .now() + 8) { self.stopScan() } } func stopScan(){ scanningState = false bluetoothDelegate?.onScanningStateChange(scanningState) centralManager.stopScan() } }
/// manager for showing the devices which we have recived. extension BlueToothManager { func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) { guard let name = peripheral.name else { return } let deviceUuid = peripheral.identifier print("Device: \(name), deviceId: \(deviceUuid)")
if let existing = discoveredDevices[deviceUuid] { // Update RSSI only existing.rssi = RSSI.intValue discoveredDevices[deviceUuid] = existing }else{ let newDevice = BLEDevice( peripheral: peripheral, name: name, deviceUuid: deviceUuid, rssi: RSSI.intValue ) discoveredDevices[deviceUuid] = newDevice } let devicesArray = Array(discoveredDevices.values) .sorted { $0.rssi > $1.rssi } bluetoothDelegate?.onDeviceChange(devicesArray) } }
/// functions for manageing the connection state of the device... extension BlueToothManager { ///extend with this "CBCentralManagerDelegate" if not already extended
print("ERROR: Characteristic \(targetUUIDString) not found in this device") print("Available characteristics:") for (key, _) in device.characteristics { print(" → \(key.uuidString)") } return }
let props = characteristic.properties if !props.contains(.write) && !props.contains(.writeWithoutResponse) { print("ERROR: Characteristic does not support write → \(props)") return }
/// Read data from a specific characteristic of a device func readData(from device: BLEDevice, characteristicUUID: CBUUID) { guard let characteristic = device.characteristics[characteristicUUID], characteristic.properties.contains(.read) else { print("Characteristic not readable") return } device.peripheral.readValue(for: characteristic) }
/// Subscribe for notifications/updates on a characteristic func subscribe(to device: BLEDevice, characteristicUUID: CBUUID) { guard let characteristic = device.characteristics[characteristicUUID], characteristic.properties.contains(.notify) else { print("Characteristic not notifiable") return } device.peripheral.setNotifyValue(true, for: characteristic) }
/// auto data recive extension BlueToothManager { /// need to implemet this "CBPeripheralDelegate" I have already done in prev extention func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) { guard let services = peripheral.services else { return } for service in services { peripheral.discoverCharacteristics(nil, for: service) } }
///In this function we save the characteristic for the write channel func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
guard let characteristics = service.characteristics else { return }
print("=== FOUND CHARACTERISTICS FOR \(peripheral.name ?? "Device") ===")
for characteristic in characteristics {
let props = characteristic.properties
// Save characteristic inside the device model if let device = discoveredDevices[peripheral.identifier] { device.characteristics[characteristic.uuid] = characteristic discoveredDevices[peripheral.identifier] = device }
Ich versuche, einige Daten an ein BLE-Gerät zu senden, aber aus irgendeinem Grund heißt es, dass die Daten erfolgreich gesendet wurden, aber tatsächlich macht das BLE nichts, da ich dasselbe in iOS...
Ich habe eine C#-Websocket-Serveranwendung und eine React-Webclientseite, die eine Verbindung dazu herstellt.
Ein C#-Websocket-Server möchte Konvertieren Sie Videomaterialdaten in Echtzeit in FFmpeg...
Gibt es in Android ein Verfahren zum gleichzeitigen Verbinden mehrerer BLE-Geräte (Erstellen mehrerer Verbindungen)? Da in meiner App mehrere BLE-Leuchten...
Ich verwende die C# Windows.Devices.bluetooth -APIs, um mit einem Gerät über Ble zu kommunizieren. Das Trennen gibt es jedoch keine direkte Option. Die einzige Option scheint zu sein, dass alle...
Ich versuche, einen Server (einen Computer mit Bluetooth) zu erstellen, der Bluetooth-Nachrichten abhört. Ich verwende eine 32-Fuß-Bibliothek. Aber ich erhalte eine Ausnahme und kann sie nicht...