HarmonyOS鸿蒙Next中JS接口低功耗蓝牙透传问题

HarmonyOS鸿蒙Next中JS接口低功耗蓝牙透传问题

测试环境,API8 ,真机系统版本 鸿蒙3.0.0.215,DevEco Studio 版本 3.1.0.500

问题1: bluetooth.BLE.on(‘BLEDeviceFind’) 回调函数错误,文档和编辑器识别都错了

问题2: GattClientDevice.on(“BLECharacteristicChange”) 回调不会触发,透传数据是有的 具体例子:

import bluetooth from '@ohos.bluetooth';
import Logger from '../Logger'
@Entry
@Componentstruct Index {
  BluetoothName = ""
  ServiceUuid = ""
  NotifyCharacteristicUuid = ""
  @State deviceId: string = ""
  private device: any = null
  private service: any = null
  @State serviceStr: string = ""
  openBLE() {
    let enable = bluetooth.enableBluetooth();
    if (enable) {
      bluetooth.BLE.on('BLEDeviceFind', (err, data) => {
        const deviceId = data[0].deviceId
        const device = bluetooth.BLE.createGattClientDevice(deviceId)
        device.getDeviceName((err, name)=> {
          if (!err) {
            if (name === this.BluetoothName) {
              this.deviceId = deviceId
              bluetooth.BLE.stopBLEScan()
            }
          }
        })
      });
      bluetooth.BLE.startBLEScan(null)
    }
  }
  connectBLE() {
    const device = bluetooth.BLE.createGattClientDevice(this.deviceId)
    device.connect()
    device.setBLEMtuSize(100)
    setTimeout(() => {
      device.getServices((code, services) => {
        const service = services.find(service => service.serviceUuid === this.ServiceUuid)
        this.service = service
        this.serviceStr = JSON.stringify(service)
      })
    }, 2000)
    this.device = device
  }
  handleBLE() {
    const characteristic = this.service.characteristics.find(c => c.characteristicUuid === this.NotifyCharacteristicUuid)
    let res = this.device.setNotifyCharacteristicChanged(characteristic, true)
    Logger.info("setNotifyCharacteristicChanged", res ? "success" : "fail")
    this.device.on('BLECharacteristicChange', (res, data) => {
      Logger.info("BLECharacteristicChange", JSON.stringify(res))
      Logger.info("BLECharacteristicChange", JSON.stringify(data))
    })
  }
  build() {
    Row() {
      Column() {
        Text(this.deviceId).fontSize(15)
        Text(this.serviceStr).fontSize(15)
        Button("扫描蓝牙")
          .onClick(() => {
            this.openBLE()
          })
        Button("连接蓝牙")
          .onClick(() => {
            this.connectBLE()
          })
        Button("打开监听")
          .onClick(() => {
            this.handleBLE()
          })
      }
      .width('100%')
    }
    .height('100%')
  }
}

因为正在开发的软件需要用到,还请有知道如何解决的回复一下,谢谢


更多关于HarmonyOS鸿蒙Next中JS接口低功耗蓝牙透传问题的实战教程也可以访问 https://www.itying.com/category-93-b0.html

10 回复

楼主您好,该问题已反馈处理中。

更多关于HarmonyOS鸿蒙Next中JS接口低功耗蓝牙透传问题的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


我把解决后的代码贴出来,后来人少踩点坑

import bluetooth from '@ohos.bluetooth';
import { Logger } from '../Logger'
@Entry
@Component
struct Index {
  BluetoothName = ""
  ServiceUuid = ""
  NotifyCharacteristicUuid = ""
  @State deviceId: string = ""
  private device: bluetooth.GattClientDevice = null
  private service: any = null
  @State serviceStr: string = ""
  openBLE() {
    let enable = bluetooth.enableBluetooth();
    if (enable) {
      // @ts-ignore
      bluetooth.BLE.on('BLEDeviceFind', (err, data) => {
        const deviceId = data[0].deviceId
        const device = bluetooth.BLE.createGattClientDevice(deviceId)
        device.getDeviceName((err, name)=> {
          if (!err) {
            if (name === this.BluetoothName) {
              this.deviceId = deviceId
              bluetooth.BLE.stopBLEScan()
            }
          }
        })
      });
      bluetooth.BLE.startBLEScan(null)
    }
  }
  connectBLE() {
    const device = bluetooth.BLE.createGattClientDevice(this.deviceId)
    device.connect()
    device.setBLEMtuSize(100)
    setTimeout(() => {
      device.getServices((code, services) => {
        const service = services.find(service => service.serviceUuid === this.ServiceUuid)
        this.service = service
        this.serviceStr = JSON.stringify(service)
      })
    }, 2000)
    this.device = device
  }
  handleBLE() {
    const characteristic = this.service.characteristics.find(c => c.characteristicUuid === this.NotifyCharacteristicUuid)
    let res = this.device.setNotifyCharacteristicChanged(characteristic, true)
    Logger.info("setNotifyCharacteristicChanged", res ? "success" : "fail")
    characteristic.descriptors.forEach(descriptor => {
      Logger.info("descriptor", JSON.stringify(descriptor))
      descriptor["descriptorValue"] = [0x01, 0x00]
      this.device.writeDescriptorValue(descriptor);
    })
    // @ts-ignore
    this.device.on('BLECharacteristicChange', (res, data) => {
      let value = new Uint8Array(data.characteristicValue)
      Logger.info("BLECharacteristicChange", JSON.stringify(value))
    })
  }
  build() {
    Row() {
      Column() {
        Text(this.deviceId).fontSize(15)
        Text(this.serviceStr).fontSize(15)
        Button("扫描蓝牙")
          .onClick(() => {
            this.openBLE()
          })
        Button("连接蓝牙")
          .onClick(() => {
            this.connectBLE()
          })
        Button("打开监听")
          .onClick(() => {
            this.handleBLE()
          })
      }
      .width('100%')
    }
    .height('100%')
  }
}

找HarmonyOS工作还需要会Flutter的哦,有需要Flutter教程的可以学学大地老师的教程,很不错,B站免费学的哦:BV1S4411E7LY/?p=17

微信图片_20230622171349.png

官方没有给出解决方案,我软件都用java重构了,今天研究了才发现java的也有这个问题,而且还很多人知道,就真的很气人,但凡有人提一下我也不至于浪费那么多时间

楼主您好,是反馈回调函数的入参与实际不一致吗?

是的,第一个问题是反馈这个 但是我现在卡在第二个问题,回调函数没有触发,我设置了通知使能,蓝牙传数据过来,device.on(‘BLECharacteristicChange’)没有触发

device.setNotifyCharacteristicChanged(characteristic, true) 这个是设置成功了的,我蓝牙也有传数据,按道理device.on(‘BLECharacteristicChange’)要触发

请提供更详细信息,比如hilog日志信息和server端设备类型等。

在HarmonyOS鸿蒙Next中,JS接口低功耗蓝牙透传问题主要涉及如何使用JS API进行蓝牙数据的传输。鸿蒙提供了@ohos.bluetooth模块来支持低功耗蓝牙(BLE)操作。通过该模块,开发者可以扫描、连接、发送和接收数据。

  1. 初始化蓝牙:使用bluetooth.startBluetoothDiscovery()启动蓝牙扫描,并通过bluetooth.on('bluetoothDeviceFind')监听发现的设备。

  2. 连接设备:使用bluetooth.createGattClient()创建GATT客户端,并通过gattClient.connect()连接到目标设备。

  3. 数据透传:连接成功后,使用gattClient.writeCharacteristicValue()向设备写入数据,通过gattClient.on('characteristicChange')监听设备返回的数据。

  4. 断开连接:使用gattClient.disconnect()断开连接,释放资源。

代码示例:

import bluetooth from '@ohos.bluetooth';

// 启动蓝牙扫描
bluetooth.startBluetoothDiscovery();

// 监听发现的设备
bluetooth.on('bluetoothDeviceFind', (device) => {
  if (device.deviceName === '目标设备名称') {
    // 创建GATT客户端
    let gattClient = bluetooth.createGattClient(device.deviceId);

    // 连接设备
    gattClient.connect();

    // 写入数据
    gattClient.writeCharacteristicValue(serviceUuid, characteristicUuid, value);

    // 监听数据返回
    gattClient.on('characteristicChange', (data) => {
      console.log('Received data:', data);
    });

    // 断开连接
    gattClient.disconnect();
  }
});

以上是鸿蒙Next中JS接口低功耗蓝牙透传的基本操作流程。

在HarmonyOS鸿蒙Next中,使用JS接口进行低功耗蓝牙(BLE)透传时,需确保设备已正确配对并连接。通过bluetooth模块的createBLEConnection建立连接后,使用writeBLECharacteristicValue方法发送数据,并通过onBLECharacteristicValueChange监听接收数据。注意确保UUID和特征值正确,并处理连接中断或超时情况,以优化数据传输效率和稳定性。

回到顶部