如何格式化要发送到 BLE 设备上的特征的字节数组?

How do I format a byte array to be sent to a characteristic on a BLE device?

我连接到我的设备并尝试写入其特征:

scanSubscription = rxBleClient.scanBleDevices(
  ScanSettings.Builder()
  // .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY) // change if needed
  // .setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES) // change if needed
  .build()
  // add filters if needed
 )
 .filter {
  scanResult -> scanResult.bleDevice.name == "MyDevice"
 } // Filter for devices named MyDevice
 .subscribe({
  scanResult ->
  // Print list of available devices
  println("Scan Result: ${scanResult.bleDevice.bluetoothDevice.name}")
  val charUUID = UUID.fromString("49535343-1e4d-4bd9-ba61-23c647249616")
  println("UUID: $charUUID")

  // Connect to MyDevice
  val macAddress = scanResult.bleDevice.bluetoothDevice.address //34:81:F4:55:04:9A
  println("MAC Address: $macAddress")
  val rxBleDevice = rxBleClient.getBleDevice(macAddress)

  val charset = Charsets.UTF_8
  val bytesToWrite = "cmdl000".toByteArray(charset)
  println("Bytes: $bytesToWrite")

  rxBleDevice.establishConnection(false)
  .flatMapSingle {
   rxBleConnection -> rxBleConnection.writeCharacteristic(charUUID, bytesToWrite)
  }

 }, {
  throwable ->
  // Handle an error here.
  println("Scan Error: $throwable")
 })

输出:

I/System.out: Scan Result: MyDevice
    UUID: 49535343-1e4d-4bd9-ba61-23c647249616
    MAC Address: 34:81:F4:55:04:9A
I/System.out: Bytes: [B@4973078

我不确定发送到特征的字节数组的格式是否正确。当我打印它时,我得到以下信息并且我的设备没有按照我的预期进行响应。这是正确的吗?

从上面的代码来看,你遇到的问题还是比较小的。所有 Observable 个对象都需要订阅才能真正执行。您已正确订阅扫描流程,但未连接。

  rxBleDevice.establishConnection(false)
    .flatMapSingle {
      rxBleConnection -> rxBleConnection.writeCharacteristic(charUUID, bytesToWrite)
    }
    .subscribe(
      { /* done */ },
      { /* encountered error */ }
    )

您可以用一个 .subscribe() 连接整个流程(扫描、连接、写入特性)。它可能看起来像:

val charUUID = UUID.fromString("49535343-1e4d-4bd9-ba61-23c647249616")
val bytesToWrite = "cmdl000".toByteArray(charset)

subscription = rxBleClient.scanBleDevices(
    ScanSettings.Builder().build(),
    ScanFilter.Builder().setDeviceName("MyDevice").build() // Filter for devices named MyDevice
)
    .take(1) // stop the scan when a matching device will be scanned for the first time
    .flatMap {
        val device = it.bleDevice
        println("MAC Address: ${device.macAddress}")
        device.establishConnection(false)
            .flatMapSingle { rxBleConnection -> rxBleConnection.writeCharacteristic(charUUID, bytesToWrite) }
            .take(1) // disconnect after the write
    }
    .subscribe(
        { /* written */ },
        { throwable ->
            // Handle an error here.
            println("Scan Error: $throwable")
        }
    )