Uni-App开发BLE低功耗蓝牙步骤
示例文件已上传gitee:https://gitee.com/yan_rookie/uniapp_bluetooth.git
如果对你有记得点个赞哦!
注:微信小程序同样适用,只需吧前缀uni.修改为wx.
最全总结,看此一篇就够!!!!
开发蓝牙很多小伙伴刚开始一头雾水,不知道从何下手,网上可以查的资料少之又少,所以写这篇文章来总结一下BLE低功耗蓝牙开发流程,话不多说,仔细看!!
- 初始化蓝牙 uni.openBluetoothAdapter(OBJECT)
- 开始搜索蓝牙设备 uni.startBluetoothDevicesDiscovery(OBJECT)
- 发现外围设备 uni.onBluetoothDeviceFound(CALLBACK)
- 停止搜寻附近的蓝牙外围设备 uni.stopBluetoothDevicesDiscovery(OBJECT)
- 连接低功耗蓝牙设备 uni.createBLEConnection(OBJECT)
- 获取蓝牙设备所有服务 uni.getBLEDeviceServices(OBJECT)
- 获取蓝牙特征 uni.getBLEDeviceCharacteristics(OBJECT)
- 启用蓝牙设备特征值变化时的 notify 功能 uni.notifyBLECharacteristicValueChange(OBJECT)
- 监听低功耗蓝牙设备的特征值变化 uni.onBLECharacteristicValueChange(CALLBACK)
- 写入蓝牙 uni.writeBLECharacteristicValue(OBJECT)
基本使用步骤我们总结完了,那么接下来就介绍怎么使用
1.初始化蓝牙
这里主要目的就是检测一下手机蓝牙是否打开
uni.openBluetoothAdapter({
success:(res)=> {
//已打开
uni.getBluetoothAdapterState({
//蓝牙的匹配状态
success:(res1)=>{
console.log(res1,'“本机设备的蓝牙已打开”')
// 开始搜索蓝牙设备
this.startBluetoothDeviceDiscovery()
},
fail(error) {
uni.showToast({
icon:'none',title: '查看手机蓝牙是否打开'
}
});
},
fail:err=>{
//未打开
uni.showToast({
icon:'none',title: '查看手机蓝牙是否打开'});
}
})
2.开始搜索蓝牙设备
// 开始搜索蓝牙设备
startBluetoothDeviceDiscovery(){
uni.startBluetoothDevicesDiscovery({
success: (res) => {
console.log('startBluetoothDevicesDiscovery success', res)
// 发现外围设备
this.onBluetoothDeviceFound()
},fail:err=>{
console.log(err,'错误信息')
}
})
}
3.发现外围设备
到这个位置就会搜索到设备了
这个地方重点就是获取到了 deviceId 这是连接蓝牙的重要ID,存起来到data里面后面我们会用到
// 发现外围设备
onBluetoothDeviceFound() {
// console.log("zhixing")
uni.onBluetoothDeviceFound((res) => {
// console.log(res)
// ["name", "deviceId"]
// 吧搜索到的设备存储起来,方便我们在页面上展示