1、打开适配器,初始化蓝牙
uni.openBluetoothAdapter(OBJECT)
2、搜索蓝牙设备
可以设置 services 来指定搜索设备
uni.startBluetoothDevicesDiscovery(OBJECT)
3、当找到蓝牙设备调用
// 回调函数参数就是返回的蓝牙设备数组
uni.onBluetoothDeviceFound(CALLBACK)
4、获取设备信息
uni.getBluetoothDevices({
success:(res)=>{
}
})
5、创建连接
uni.createBLEConnection({
//要连接的设备id
deviceId:deviceId,
success:()=>{
}
})
6、监听蓝牙断开
回调函数参数:设备id,是否连接的布尔
断开则重新创建连接
uni.onBLEConnectionStateChange(CALLBACK)
7、获取设备服务并拿到指定服务特征值
特征值:即服务端定好一个参数,客户端可以对这个参数进行读,写,通知等操作
// 延时调用获取蓝牙的服务,立即获取会导致结果为空
uni.getBLEDeviceServices({
deviceId:deviceId,
success:(res)=>{
//res就是服务列表数组
//获取指定的服务
uni.getBLEDeviceCharacteristics({
deviceId:设备id,
serviceId:设备服务id,
success:(res)=>{
//res为返回的为特征值以及所支持的操作---数组对象
//不同的特征值对应不同的功能
}
})
}
})
8、连接成功关闭搜索
uni.stopBluetoothDevicesDiscovery(OBJECT)
9、开启数据监听
uni.notifyBLECharacteristicValueChange({
state: true,
deviceId,
serviceId,
characteristicId,
success() {
//监听数据,必须在notifyBLECharacteristicValueChange之后执行
//res.value就是最新的特征值
//想要看到数据,需要将ArrayBuffer转换
uni.onBLECharacteristicValueChange((res)=>{
})
},
fail(err) {
}
})
10、使用完毕,取消所有监听