鸿蒙蓝牙连接
- ble.startBLEScan
startBLEScan(filters: Array, options?: ScanOptions): void
发起BLE扫描流程。
需要权限:ohos.permission.ACCESS_BLUETOOTH
import { BusinessError } from '@ohos.base';
function onReceiveEvent(data: Array<ble.ScanResult>) {
console.info('BLE scan device find result = '+ JSON.stringify(data));
}
try {
ble.on("BLEDeviceFind", onReceiveEvent);
let scanFilter: ble.ScanFilter = {
deviceId:"XX:XX:XX:XX:XX:XX",
name:"test",
serviceUuid:"00001888-0000-1000-8000-00805f9b34fb"
};
let scanOptions: ble.ScanOptions = {
interval: 500,
dutyMode: ble.ScanDuty.SCAN_MODE_LOW_POWER,
matchMode: ble.MatchMode.MATCH_MODE_AGGRESSIVE,
}
ble.startBLEScan([scanFilter],scanOptions);
} catch (err) {
console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}
- ble.stopBLEScan
stopBLEScan(): void
停止BLE扫描流程。
需要权限:ohos.permission.ACCESS_BLUETOOTH
import { BusinessError } from '@ohos.base';
try {
ble.stopBLEScan();
} catch (err) {
console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}
- connect
connect(): void
client端发起连接远端蓝牙低功耗设备。
需要权限:ohos.permission.ACCESS_BLUETOOTH
import { BusinessError } from '@ohos.base';
try {
let device: ble.GattClientDevice = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX');
device.connect();
} catch (err) {
console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}
- disconnect
disconnect(): void
client端断开与远端蓝牙低功耗设备的连接。
需要权限:ohos.permission.ACCESS_BLUETOOTH
import { BusinessError } from '@ohos.base';
try {
let device: ble.GattClientDevice = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX');
device.disconnect();
} catch (err) {
console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}
- 下面是测试例子:
import { BusinessError } from '@ohos.base';
import ble from '@ohos.bluetooth.ble';
import { TAG } from '@ohos/hypium/src/main/Constant';
@Entry
@Component
struct BluetoothText {
@State message: string = '蓝牙测试界面';
@State scanResults: Array<string> = []; // 存储扫描结果
private scannedDeviceIds: Set<string> = new Set(); // 存储已经扫描到的设备ID
private targetDeviceId: string = "7C:87:CE:1D:DF:F2"; // 目标设备的Device ID
private gattClientDevice: ble.GattClientDevice | null = null;
mBorder: BorderOptions = { radius: 10, color: '#385E0F', width: 1 };
fontSize = 16
mColor: string = '#2E8B57'
build() {
Row() {
Column() {
// 显示当前状态信息
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
Row() {
Button("连接")
.fontSize(this.fontSize)
.height('60%')
.width('40%')
.border(this.mBorder)
.backgroundColor(this.mColor)
.onClick(() => {
this.startBLEScan();
});
Button("停止")
.fontSize(this.fontSize)
.height('60%')
.width('40%')
.border(this.mBorder)
.backgroundColor(this.mColor)
.onClick(() => {
this.stopBLEScan();
});
}.width('30%').height('10%').padding({ left: 10, right: 10 })
// 滚动容器,用于显示扫描结果列表
Scroll() {
Column() { // 使用 Column 作为 Scroll 的唯一子组件
ForEach(this.scanResults, (result: string) => {
Text(result)
.fontSize(20)
.fontColor(Color.Black)
.padding(10)
})
}
}
.height('80%') // 设置滚动区域高度
.width('100%')
}
.width('100%')
}
.height('100%')
}
startBLEScan() {// 使用箭头函数定义
try {
ble.on("BLEDeviceFind", this.onReceiveEvent); // 直接传递引用
let scanFilter: ble.ScanFilter = {
deviceId: this.targetDeviceId,
};
let scanOptions: ble.ScanOptions = {
interval: 500,
dutyMode: ble.ScanDuty.SCAN_MODE_LOW_POWER,
matchMode: ble.MatchMode.MATCH_MODE_AGGRESSIVE,
};
ble.startBLEScan([scanFilter], scanOptions);
this.message = 'Scanning...';
} catch (err) {
console.error('errCode: ' + err.code + ', errMessage: ' + err.message);
this.message = 'Scan failed: ' + err.message;
}
}
onReceiveEvent = (data: Array<ble.ScanResult>) => {
console.info('BLE scan device find result = ' + JSON.stringify(data));
let newResults = data.map((device) => {
if (!this.scannedDeviceIds.has(device.deviceId)) {
this.scannedDeviceIds.add(device.deviceId); // 添加设备ID到集合中
if (device.deviceId === this.targetDeviceId) {
// 创建并连接到 GATT 客户端设备
try {
this.gattClientDevice = ble.createGattClientDevice(device.deviceId);
this.gattClientDevice.connect();
console.debug(TAG,"连接成功")
} catch (err) {
console.error('创建GATT客户端设备失败,errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
this.message = '创建GATT客户端设备失败';
}
}
console.debug(TAG,`Device Name: ${device.deviceName || 'Unknown'}, Device ID: ${device.deviceId}`);
return `Device Name: ${device.deviceName || 'Unknown'}, Device ID: ${device.deviceId}`;
}
return null;
}).filter(result => result !== null); // 过滤掉 null 值
this.scanResults = [...this.scanResults, ...newResults as string[]]; // 合并新旧结果
this.message = 'Scan result received!';
}
//停止蓝牙扫描
stopBLEScan(){
try {
ble.stopBLEScan();
this.gattClientDevice?.disconnect();
} catch (err) {
console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}
}
}