主要方法函数讲解
使用Uni-app开发BLE流程
开发BLE的流程大致如下,以下是对下列流程中用到的主要方法函数做一个讲解。
1、初始化蓝牙 uni.openBluetoothAdapter(OBJECT)
2、开始搜索蓝牙设备 uni.startBluetoothDevicesDiscovery(OBJECT)
3、发现外围设备 uni.onBluetoothDeviceFound(CALLBACK)
4、停止搜寻附近的蓝牙外围设备
uni.stopBluetoothDevicesDiscovery(OBJECT)
5、连接低功耗蓝牙设备 uni.createBLEConnection(OBJECT)
6、获取蓝牙设备所有服务 uni.getBLEDeviceServices(OBJECT)
7、获取蓝牙特征 uni.getBLEDeviceCharacteristics(OBJECT)
8、启用蓝牙设备特征值变化时的 notify 功能 uni.notifyBLECharacteristicValueChange(OBJECT)
9、监听低功耗蓝牙设备的特征值变化 uni.onBLECharacteristicValueChange(CALLBACK)
10、写入蓝牙 uni.writeBLECharacteristicValue(OBJECT)
1、初始化蓝牙模块函数
函数名:uni.openBluetoothAdapter(OBJECT)
函数作用:该函数是最开始时必须要进行初始化的函数,也就是其他方法函数API必须等待该初始化函数调用之后才能进行使用,否则会返回报错errCode=10000;如果用户没有打开手机蓝牙,那么该初始化函数会返回报错errCode=10001,标识蓝牙功能当前不可用。
示例代码如下:
uni.openBluetoothAdapter({
success: (res) => {
if (res.errMsg == 'openBluetoothAdapter:ok') {}
}
})
2、搜索周围的蓝牙设备
函数名:uni.startBluetoothDevicesDiscovery(OBJECT)
函数作用:搜索附近的蓝牙外围设备,但是需要在后面通过调用stopBluetoothDeviceDiscovery方法停止搜索,来节省系统资源。
示例代码如下:
uni.startBluetoothDevicesDiscovery({
allowDuplicatesKey: true, //是否允许重复上报同一设备
interval: 0, //搜索间隔
success: (res2) => {
if (res2.errMsg == 'startBluetoothDevicesDiscovery:ok') {
this.monitor()
}
}
})
3、监听BLE蓝牙连接状态变化函数
函数名:uni.onBLEConnectionStateChange
使用该函数可以监听蓝牙的状态变化情况,即当前蓝牙状态是否断开等。是一个回调函数。
示例代码:
uni.onBLEConnectionStateChange((res) => {
if (res.connected == false) {
this.cut = true
uni.showModal({
title: "蓝牙连接断开",
content: "是否重新搜索",
success: (res) => {
if (res.confirm) this.search()
}
})
}
})
4、监听寻找到的新设备的方函数
函数名:uni.onBluetoothDeviceFound(CALLBACK)
函数说明:若在uni.onBluetoothDeviceFound回调了某个设备,则此设备会添加到uni.getBluetoothDevices 接口获取到的数组中。
示例代码:
uni.onBluetoothDeviceFound((res) => {
res.devices.forEach(result => {
if ((result.name != '') && (result.localName != '')) {
let idx = util.inArray(this.booth.list, 'deviceId', result.deviceId)
if (idx === -1) {
this.booth.list.push(result)
} else {
this.booth.list[idx] = result
}
}
})
})
5、停止搜索附近的蓝牙设备
函数说明:搜索蓝牙是很费资源的行为,若已经找到需要的蓝牙设备并不需要继续搜索时,建议调用该接口停止蓝牙搜索。
函数名:uni.stopBluetoothDevicesDiscovery(OBJECT)
示例代码:
uni.stopBluetoothDevicesDiscovery({
success(res) {
console.log(res)
}
})
6、连接BLE低功耗蓝牙
函数名:uni.createBLEConnection(OBJECT)
函数说明:尽量成对的调用连接和断开的接口,如果多次调用连接接口,有可能导致系统持有同一设备多个连接的实例,导致调用断开接口失效
示例代码:
uni.createBLEConnection({
deviceId: this.uuid.deviceId,
success: (res) => {
if (res.errMsg == 'createBLEConnection:ok') {
setTimeout(() => {
this.Service()
this.BLEChange()
}, 2000)
}
}
})
7、获取蓝牙设备的所有服务
函数名:uni.getBLEDeviceServices(OBJECT)。
连接设备成功后,不能立即调用uni.getBLEDeviceServices(OBJECT),否则获取不到任何服务。解决方法:连接成功后,等个几秒(看设备的情况)在调用uni.getBLEDeviceServices(OBJECT)
示例代码:
uni.getBLEDeviceServices({
deviceId: this.uuid.deviceId,
success: (res) => {
if (res.services.length == 0) {
util.showError("找不到服务")
} else {
let booth = true
for (let i = 0; i < res.services.length; i++) {
if (res.services[i].uuid == this.uuid.service) {
booth = false
this.Character()
break;
}
}
if (booth) util.showError("服务uuid错误")
}
}
})
8、获取蓝牙设备中某个服务中的所有特征值
函数名:uni.getBLEDeviceCharacteristics(OBJECT)
示例代码:
uni.getBLEDeviceServices({
deviceId: this.uuid.deviceId,
success: (res) => {
if (res.services.length == 0) {
util.showError("找不到服务")
} else {
let booth = true
for (let i = 0; i < res.services.length; i++) {
if (res.services[i].uuid == this.uuid.service) {
booth = false
this.Character()
break;
}
}
if (booth) util.showError("服务uuid错误")
}
}
})
9、启用低功耗蓝牙设备特征值变化时的 notify 功能
函数名:uni.notifyBLECharacteristicValueChange(OBJECT)
函数说明:必须设备的特征值支持 notify 或者 indicate 才可以成功调用。
订阅操作成功后需要设备主动更新特征值的 value,才会触发uni.onBLECharacteristicValueChange(后续监听设备的返回消息)回调。
安卓平台上,在调用notifyBLECharacteristicValueChange成功后立即调用writeBLECharacteristicValue(向设备发送信息)接口,在部分机型上会发生 10008 系统错误
连接蓝牙设备的过程到此结束。
示例代码:
uni.notifyBLECharacteristicValueChange({
state: true, // 启用 notify 功能
// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
deviceId,
// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
serviceId,
// 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
characteristicId,
success(res) {
console.log('notifyBLECharacteristicValueChange success', res.errMsg)
}
})
10、监听低功耗蓝牙设备特征值变化函数
函数名:uni.onBLECharacteristicValueChange(CALLBACK)
实例代码:
function ab2hex(buffer) {
const hexArr = Array.prototype.map.call(
new Uint8Array(buffer),
function (bit) {
return ('00' + bit.toString(16)).slice(-2)
}
)
return hexArr.join('')
}
uni.onBLECharacteristicValueChange(function (res) {
console.log(`characteristic ${res.characteristicId} has changed, now is ${res.value}`)
console.log(ab2hex(res.value))
})
11、向BLE蓝牙写入数据
函数名:uni.writeBLECharacteristicValue(OBJECT)
实例代码:
// 向蓝牙设备发送一个0x00的16进制数据
const buffer = new ArrayBuffer(1)
const dataView = new DataView(buffer)
dataView.setUint8(0, 0)
uni.writeBLECharacteristicValue({
// 这里的 deviceId 需要在 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
deviceId,
// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
serviceId,
// 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
characteristicId,
// 这里的value是ArrayBuffer类型
value: buffer,
success(res) {
console.log('writeBLECharacteristicValue success', res.errMsg)
}
})