HarmonyOS鸿蒙Next Ble蓝牙demo
HarmonyOS鸿蒙Next Ble蓝牙demo 有没有官方的ble蓝牙通信demo?
Ble蓝牙相关资料可参考:https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V13/js-apis-bluetooth-ble-V13#blestartblescan以及https://gitee.com/openharmony/docs/tree/master/zh-cn/application-dev/connectivity/bluetooth,
以下是一个相对完整的蓝牙通信ble的样例:
demo代码总共有4个页面。一个util
主页MainPage
上:
import { ble } from '@kit.ConnectivityKit';
import { BusinessError } from '@kit.BasicServicesKit';
@Entry
@Component
struct Client {
@State clientInstanceSwitch: boolean = false;
@State scanSwitch: boolean = false;
@State deviceFindSwitch: boolean = false;
@State bleDevices: Array<ble.ScanResult> = []
build() {
Column({ space: 15 }) {
Row() {
Text('BLE扫描')
Blank()
Toggle({ type: ToggleType.Switch, isOn: this.scanSwitch })
.onChange((isOn: boolean) => {
if (isOn) {
this.startScan()
} else {
this.stopScan()
}
console.info('ble server instanceSwitch status:' + isOn)
})
}
.itemStyle()
Column() {
Row() {
Text('订阅BLE设备')
Blank()
Toggle({ type: ToggleType.Switch, isOn: this.deviceFindSwitch })
.onChange((isOn: boolean) => {
if (isOn) {
this.onBLEDeviceFind()
} else {
this.offBLEDeviceFind()
}
console.info('ble server instanceSwitch status:' + isOn)
})
}
.itemStyle()
.borderRadius({ topLeft: 10, topRight: 10 })
Divider()
Scroll() {
if (this.bleDevices.length > 0) {
List() {
ForEach(this.bleDevices, (item: ble.ScanResult) => {
ListItem() {
Navigator({ target: 'pages/ClientDetail', type: NavigationType.Push }) {
Text(item.deviceId)
.width('100%').textAlign(TextAlign.Start)
}
.params(item)
}
})
}
} else {
Text('暂无设备发现')
}
}
.itemStyle()
.height(380)
.borderRadius({ bottomLeft: 10, bottomRight: 10 })
.scrollBar(BarState.Off)
}
}
.height('100%')
.width('100%')
MainPage
中:
.padding({ left: 15, right: 15, top: 20, bottom: 20 })
.backgroundColor($r('app.color.light_gray'))
/**
* 发起BLE扫描流程
*/
startScan() {
try {
let scanFilter: ble.ScanFilter = {
serviceUuid: "00001810-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);
console.info('ble Client start BLE Scan success')
this.scanSwitch = true;
} catch (err) {
console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}
}
/**
* 关闭BLE扫描流程
*/
stopScan() {
try {
ble.stopBLEScan();
console.info('ble Client stop BLE Scan success')
this.scanSwitch = false;
} catch (err) {
console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}
}
/**
* 取消订阅BLE设备发现
*/
onBLEDeviceFind() {
ble.on('BLEDeviceFind', (data: Array<ble.ScanResult>) => {
console.info('bluetooth device find on = ' + JSON.stringify(data));
this.bleDevices = data;
});
this.deviceFindSwitch = true;
}
MainPage
下:
/**
* 取消订阅BLE设备发现
*/
offBLEDeviceFind() {
ble.off('BLEDeviceFind', (data: Array<ble.ScanResult>) => {
console.info('bluetooth device find off = ' + JSON.stringify(data));
// this.bleDevices = data;
});
this.deviceFindSwitch = false;
}
@Styles
function itemStyle() {
.width('100%')
.padding({ left: 15, right: 15, top: 8, bottom: 8 })
.backgroundColor($r('app.color.white'))
.borderRadius(10)
}
上面发的是client
页面
mainpage
页面:
import { router } from '@kit.ArkUI'
import PermissionsUtil from '../utils/PermissionsUtil'
@Entry
@Component
struct MainPage {
aboutToAppear(): void {
PermissionsUtil.requestPermissions(['ohos.permission.ACCESS_BLUETOOTH'])
}
build() {
Column() {
Button('客户端').onClick((event: ClickEvent) => {
router.pushUrl({ url: "pages/Client" })
})
.width('50%')
Button('服务端').onClick((event: ClickEvent) => {
router.pushUrl({ url: "pages/Server" })
})
.width('50%')
}
.height('100%')
.width('100%')
.justifyContent(FlexAlign.SpaceAround)
}
}
ClientDetail
页面代码:
import { ble, constant } from '@kit.ConnectivityKit';
import { router } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit';
@Entry
@Component
struct ClientDetail {
device: ble.ScanResult = router.getParams() as ble.ScanResult;
@State gattClient: ble.GattClientDevice | undefined = undefined;
@State deviceName: string = '';
@State gattServiceInfo: ble.GattService | undefined = undefined;
@State connectSwitch: boolean = false;
@State stateListenSwitch: boolean = false;
@State connectStateSwitch: boolean = false;
@State bleCharChangeSwitch: boolean = false;
@State connectState: ble.ProfileConnectionState = constant.ProfileConnectionState.STATE_DISCONNECTED;
@State characteristicValue: string = '';
private serviceUuid = "00001810-0000-1000-8000-00805F9B34FB";
@State writeValue: string = ''
aboutToAppear(): void {
if (!this.gattClient) {
this.gattClient = ble.createGattClientDevice(this.device?.deviceId);
this.getDeviceName()
}
}
build() {
Scroll() {
Column({ space: 10 }) {
Text() {
Span('设备名称: ')
Span(this.deviceName)
}
.itemStyle()
Row() {
Text('连接状态监听')
Blank()
Toggle({ type: ToggleType.Switch, isOn: this.stateListenSwitch })
.onChange((isOn: boolean) => {
if (isOn) {
this.onBLEConnectionStateChange()
} else {
this.offBLEConnectionStateChange()
}
console.info('ble server instanceSwitch status:' + isOn)
})
}
.itemStyle()
Row() {
Text('连接状态')
Blank()
if (this.connectState == constant.ProfileConnectionState.STATE_CONNECTING) {
LoadingProgress().height(15).width(15)
} else {
Toggle({ type: ToggleType.Switch, isOn: this.connectStateSwitch })
.enabled(false)
}
}
.itemStyle()
Row() {
Text('连接开关')
Blank()
Toggle({ type: ToggleType.Switch, isOn: this.connectSwitch })
.onChange((isOn: boolean) => {
if (isOn) {
this.connectServer()
} else {
this.disconnectServer()
}
console.info('ble server instanceSwitch status:' + isOn)
})
}
.itemStyle()
Column({ space: 10 }) {
Button('服务发现').onClick((event: ClickEvent) => {
this.getServices()
})
Scroll() {
if (this.gattServiceInfo) {
Text(JSON.stringify(this.gattServiceInfo))
} else {
Text('暂无数据')
}
}
.height(100)
.scrollBar(BarState.Off)
}
.itemStyle()
Column({ space: 10 }) {
Button('client端读取蓝牙低功耗设备特定服务的特征值').onClick((event: ClickEvent) => {
this.readCharacteristicValue()
})
Scroll() {
if (this.characteristicValue) {
Text(JSON.stringify(this.characteristicValue))
} else {
Text('暂无数据')
}
}
.height(100)
.scrollBar(BarState.Off)
}
.itemStyle()
Button('写描述符').onClick((event: ClickEvent) => {
this.writeDescriptorValue()
})
}
}
}
}
更多关于HarmonyOS鸿蒙Next Ble蓝牙demo的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
HarmonyOS鸿蒙Next的Ble蓝牙demo展示了如何在鸿蒙系统中实现低功耗蓝牙(BLE)通信。该demo主要包括设备扫描、连接、数据读写等基本操作。鸿蒙系统提供了ohos.bluetooth.ble
API来支持BLE功能,开发者可以通过这些API实现蓝牙设备的发现、连接、服务发现以及数据交互。
在鸿蒙Next中,BLE通信的核心步骤包括:
- 初始化蓝牙适配器:使用
BluetoothHost
类初始化蓝牙适配器,并检查设备是否支持BLE。 - 扫描设备:通过
BluetoothHost.startBLEScan()
方法启动BLE扫描,获取附近的BLE设备列表。 - 连接设备:使用
BluetoothDevice.connectGatt()
方法连接到指定的BLE设备。 - 发现服务:连接成功后,通过
BluetoothGatt.discoverServices()
方法发现设备的GATT服务。 - 数据交互:通过
BluetoothGattCharacteristic
和BluetoothGattDescriptor
进行数据的读写操作。
鸿蒙系统的BLE API设计简洁,开发者可以通过回调函数处理蓝牙设备的状态变化和数据传输。具体的API使用可以参考鸿蒙官方文档中的ohos.bluetooth.ble
模块。
HarmonyOS Next 提供了完整的蓝牙开发框架,开发者可通过 @ohos.bluetooth
和 @ohos.bluetoothManager
模块实现BLE设备管理与数据传输。核心步骤包括:初始化蓝牙适配器、扫描BLE设备、连接设备、发现服务与特征值、读写数据等。使用 bluetoothManager
进行权限申请和设备管理,通过 bluetooth
模块进行具体操作。建议参考官方文档和示例代码,确保权限配置正确,并遵循BLE协议规范进行开发。