在uniAPP中使用使用低功耗蓝牙通讯

在uniAPP中使用使用低功耗蓝牙通讯

1、初始化蓝牙监听器

onLoad(){
    //蓝牙是否在扫描设备
    uni.onBluetoothAdapterStateChange((res)=>{
         console.log("蓝牙"+(res.discovering ? "开启":"关闭")+"搜索")
         this.discovering = res.discovering;
    })
    //监听扫描到的蓝牙设备
    uni.onBluetoothDeviceFound(resd=>{
        //在这里识别你要用到的设备;
        const devices = resd.devices;
    })
    
    //监听蓝牙连接状态
    uni.onBLEConnectionStateChange(res=>{
        console.log(`设备 ${res.deviceId},connected: ${res.connected}`)
        this.Connecting = res.connected;
        this.deviceId = res.deviceId;
    })
}

2、初始化蓝牙适配器

//检查蓝牙打开,初始化蓝牙
openBluetoothAdapter(){
    uni.openBluetoothAdapter({
        success: (res) => {
            //初始化成功,搜索设备
            setTimeout(()=>{
                this.deviceList = [] ; //每次扫描清空设备列表,不然会导致重复
                this.startBluetoothDeviceDiscovery(); //扫描蓝牙设备
            },100);
            //定时关闭搜索设备
            setTimeout(()=>{
                this.stopBluetoothDevicesDiscovery();
            },15*1000);
        },
        fail:err=>{
            uni.showToast({
                title:'请确认手机蓝牙是否打开'
            })
        }
    })
},

3、初始化成功设备后,开始搜索设备,搜索到的设备会在 onBluetoothDeviceFound 方法中回调。

//开启蓝牙搜寻
startBluetoothDeviceDiscovery(){
    uni.startBluetoothDevicesDiscovery({
        success: (resd) => {
            console.log("打开成功",resd);
        },
        fail:err=>{
            console.error("startBluetoothDevicesDiscoveryErr",err);
            this.Toast("请检查蓝牙状态")
        }
    })
},

4、连接蓝牙设备 createBLEConnection

 /*连接低功耗蓝牙设备
   @params deviceId  蓝牙设备id
    0   ok  正常
    10000   not init    未初始化蓝牙适配器
    10001   not available   当前蓝牙适配器不可用
    10002   no device   没有找到指定设备
    10003   connection fail 连接失败
    10004   no service  没有找到指定服务
    10005   no characteristic   没有找到指定特征值
    10006   no connection   当前连接已断开
    10007   property not support    当前特征值不支持此操作
    10008   system error    其余所有系统上报的异常
    10009   system not support  Android 系统特有,系统版本低于 4.3 不支持 BLE
*/
createBLEConnection(deviceId){
    if(this.discovering){
        this.stopBluetoothDevicesDiscovery() //点击连接设备时,若蓝牙仍在扫描,就关闭
    }
    if(this.Connecting){
        this.Toast("设备已连接");
        return
    }
    uni.showLoading({
        title:"连接设备中..."
    })
    uni.createBLEConnection({
        deviceId,
        success:res=>{
            uni.hideLoading();
            this.deviceId = deviceId;
            //获取蓝牙服务
            setTimeout(()=>{
                //延时调用获取蓝牙的服务,立即获取会导致结果为空
                this.getBLEDeviceServices(deviceId); 
            },1500)
        },
        fail:err=>{
            uni.hideLoading();
            this.Toast('设备连接失败,请检查重试')
            if(err.errCode ==-1){
                this.closeBLEConnect(deviceId)
            }
        }
    })
},

5、获取蓝牙服务 和服务中的特征值

/*获取蓝牙设备所有服务(service)。
   连接蓝牙后调用
   @parmas deviceId  蓝牙设备id
*/
getBLEDeviceServices(deviceId){
    const _this = this;
    uni.getBLEDeviceServices({
        deviceId,
        success:res=>{
            //获取特征值
            console.log(res.services);
            let services = res.services; 
            //这里是我要用到的服务,大家根据自己要用的服务调度即可。
            _this.serviceUUID = services[2].uuid; 
            //获取服务中的特征值
             this.getBLEDeviceCharacteristics(deviceId,_this.serviceUUID).then(res=>{
                console.log(res);
                _this.notifyUUid = res.characteristics[0].uuid
                _this.writeUUid = res.characteristics[1].uuid
                uni.notifyBLECharacteristicValueChange({
                    deviceId:deviceId,
                    serviceId:_this.serviceUUID,
                    characteristicId:_this.notifyUUid,
                    state:true,
                    success: (res) => {
                        console.log("广播开启成功")
                        _this.onBLECharacteristicValueChange();
                    },
                    fail: (err) => {
                        console.error(err)
                    }
                })
                setTimeout(()=>{
                    _this.writeBLECharacteristicValue([0x5A,0x03,0xFF])
                },2000)
            })


        },
        fail:err=>{
            console.warn("设备服务Error"+err)
        }
    })
},
    
/*获取蓝牙设备某个服务中所有特征值(characteristic)。
     @parmas deviceId 设备id
     @parmas serviceId 蓝牙服务uuid ,需要使用getBLEDeviceServices 获取
*/
    getBLEDeviceCharacteristics(deviceId,serviceId){
        const _this = this;
        return new Promise((resolve,reject)=>{
            uni.getBLEDeviceCharacteristics({
                deviceId,
                serviceId,
                success:res=>{
                    resolve(res);
                },
                fail:err=>{
                    console.log("获取特征值失败",err)
                    reject(err);
                }
            })
        })
    },
        

// 监测低功耗蓝牙设备变化
//此方法要在 notifyBLECharacteristicValueChange 调用成功后调用
onBLECharacteristicValueChange(){
    uni.onBLECharacteristicValueChange(res=>{
      console.log(`监听低功耗蓝牙设备的特征值变化事件 ${res.characteristicId} has changed, now is ${res.value}`)
      console.log(this.ab2hex(res.value));
      //得到数据回复,在这里写我们自己的逻辑即可
   })
},
    
 ab2hex(buffer) {
     const hexArr = Array.prototype.map.call(
         new Uint8Array(buffer),
         function(bit) {
             return ('00' + bit.toString(16)).slice(-2)
         }
     )
     return hexArr.join('')
 },

特征值解析

"characteristics": [{
    "uuid": "00002A00-0000-1000-8000-00805F9B34FB",
    "properties": {
        "read": false, //读取
        "write": true, //写入
        "notify": true, //广播
        "indicate": false
    }
}]

6、写入数据交互

/*向蓝牙设备中写入数据
    @parmas  deviceId 蓝牙设备 id
    @parmas  serviceId  蓝牙特征值对应服务的 uuid
    @parmas  characteristicId 蓝牙特征值的 uuid
    @parmas  value  ArrayBuffer 蓝牙设备特征值对应的二进制值
*/

//写入成功后,设备就会通过广播 onBLECharacteristicValueChange方法 将数据返回给我们
writeBLECharacteristicValue(value){
    // 向蓝牙设备发送一个0x00的16进制数据
    let  buffer = new ArrayBuffer(1)
    let dataView = new DataView(buffer)
    dataView.setInt8(0x01)
    uni.writeBLECharacteristicValue({
        deviceId:this.deviceId,
        serviceId:this.serviceUUID,
        characteristicId:this.writeUUid,
        value:buffer,
        success:res=>{
            console.log("写入成功",res)
        },
        fail:err=>{
            console.error("写入失败",err)
        }
    })
},

7、在卸载页面中记得断开连接

onUnload() {
    if(this.discovering){
        this.stopBluetoothDevicesDiscovery();
    }
    if(this.Connecting){
        this.closeBLEConnect(this.deviceId);
    }
},

8、最后我们贴上完整代码

export default {
        data() {
            return {
                discovering:false, //蓝牙是否处于搜索状态
                deviceList:[],  //设备列表 
                deviceId:'', //已连接的蓝牙设备
                Connecting:false, // 蓝牙连接状态
                serviceUUID:'', //蓝牙服务的UUID
                writeUUid:'', //写入UUID
                notifyUUid:'' //广播UUID
            }
        },
        methods: {
            seachDevice(){
                   if(!this.discovering){
                      this.openBluetoothAdapter();
                      if(this.Connecting){
                          this.closeBLEConnect(this.deviceId);
                      }
                   }else{
                       this.Toast("正在扫描中,请等待");
                   }
                   
            },
            //检查蓝牙打开,初始化蓝牙
            openBluetoothAdapter(){
                uni.openBluetoothAdapter({
                    success: (res) => {
                        //初始化成功,搜索设备
                        setTimeout(()=>{
                            this.deviceList = [] ; //每次扫描清空设备列表,不然会导致重复
                            this.startBluetoothDeviceDiscovery();
                        },100);
                        //定时关闭搜索设备
                        setTimeout(()=>{
                            this.stopBluetoothDevicesDiscovery();
                        },15*1000);
                    },
                    fail:err=>{
                       uni.showToast({
                        title:'请确认手机蓝牙是否打开'
                       })
                    }
                })
            },
            //这里是开启蓝牙搜寻  
            startBluetoothDeviceDiscovery(){
                uni.startBluetoothDevicesDiscovery({
                    success: (resd) => {
                        console.log("打开成功",resd);
                    },
                    fail:err=>{
                        console.error("startBluetoothDevicesDiscoveryErr",err);
                        this.Toast("请检查蓝牙状态")
                    }
                })
            },
            //关闭蓝牙搜索
            stopBluetoothDevicesDiscovery(){
                uni.stopBluetoothDevicesDiscovery({
                    success:res=>{
                        
                    }
                })
            },
            
            //监听连接状态
            onBLEConnectionStateChange(){
                uni.onBLEConnectionStateChange(res=>{
                    console.log(`设备 ${res.deviceId},connected: ${res.connected}`)
                    this.Connecting = res.connected;
                    this.deviceId = res.deviceId;
                })
            },
            /*连接低功耗蓝牙设备
              @params deviceId  蓝牙设备id
              0 ok  正常
              10000 not init    未初始化蓝牙适配器
              10001 not available   当前蓝牙适配器不可用
              10002 no device   没有找到指定设备
              10003 connection fail 连接失败
              10004 no service  没有找到指定服务
              10005 no characteristic   没有找到指定特征值
              10006 no connection   当前连接已断开
              10007 property not support    当前特征值不支持此操作
              10008 system error    其余所有系统上报的异常
              10009 system not support  Android 系统特有,系统版本低于 4.3 不支持 BLE
            */
             createBLEConnection(deviceId){
                 if(this.discovering){
                     this.stopBluetoothDevicesDiscovery()
                 }
                if(this.Connecting){
                    this.Toast("设备已连接");
                    return
                }
                uni.showLoading({
                    title:"连接设备中..."
                })
                uni.createBLEConnection({
                    deviceId,
                    success:res=>{
                        uni.hideLoading();
                        this.Toast('设备连接成功')
                        this.deviceId = deviceId;
                        //获取蓝牙服务
                        setTimeout(()=>{
                            this.getBLEDeviceServices(deviceId);
                        },1500)
                        
                    },
                    fail:err=>{
                        uni.hideLoading();
                        this.Toast('设备连接失败,请检查重试')
                        if(err.errCode ==-1){
                            this.closeBLEConnect(deviceId)
                        }
                    }
                })
            },
            /*获取蓝牙设备所有服务(service)。
              连接蓝牙后调用
             @parmas deviceId  蓝牙设备id
            */
            getBLEDeviceServices(deviceId){
                const _this = this;
                    uni.getBLEDeviceServices({
                        deviceId,
                        success:res=>{
                            //获取特征值
                            console.log(res.services);
                            let services = res.services;
                            _this.serviceUUID = services[2].uuid;
                            this.getBLEDeviceCharacteristics(deviceId,_this.serviceUUID).then(res=>{
                                console.log(res);
                                _this.notifyUUid = res.characteristics[0].uuid
                                _this.writeUUid = res.characteristics[1].uuid
                                uni.notifyBLECharacteristicValueChange({
                                    deviceId:deviceId,
                                    serviceId:_this.serviceUUID,
                                    characteristicId:_this.notifyUUid,
                                    state:true,
                                    success: (res) => {
                                        console.log("广播开启成功")
                                        _this.onBLECharacteristicValueChange();
                                    },
                                    fail: (err) => {
                                        console.error(err)
                                    }
                                })
                                setTimeout(()=>{
                                    _this.writeBLECharacteristicValue([0x5A,0x03,0xFF])
                                },2000)
                            })
                            
                            
                        },
                        fail:err=>{
                            console.warn("设备服务Error"+err)
                        }
                    })
            },
            /*向蓝牙设备中写入数据
                @parmas  deviceId 蓝牙设备 id
                @parmas  serviceId  蓝牙特征值对应服务的 uuid
                @parmas  characteristicId 蓝牙特征值的 uuid
                @parmas  value  ArrayBuffer 蓝牙设备特征值对应的二进制值
            */
            writeBLECharacteristicValue(value){
                // 向蓝牙设备发送一个0x00的16进制数据
                let  buffer = new ArrayBuffer(1)
                let dataView = new DataView(buffer)
                dataView.setInt8(0x01)
                uni.writeBLECharacteristicValue({
                    deviceId:this.deviceId,
                    serviceId:this.serviceUUID,
                    characteristicId:this.writeUUid,
                    value:buffer,
                    success:res=>{
                        console.log("写入成功",res)
                    },
                    fail:err=>{
                        console.error("写入失败",err)
                    }
                })
            },
            // 监测低功耗蓝牙设备变化
            onBLECharacteristicValueChange(){
                uni.onBLECharacteristicValueChange(res=>{
                    console.log(`监听低功耗蓝牙设备的特征值变化事件 ${res.characteristicId} has changed, now is ${res.value}`)
                    console.log(this.ab2hex(res.value));
                })
            },
             ab2hex(buffer) {
                const hexArr = Array.prototype.map.call(
                    new Uint8Array(buffer),
                    function(bit) {
                        return ('00' + bit.toString(16)).slice(-2)
                    }
                )
                return hexArr.join('')
            },
            /*获取蓝牙设备某个服务中所有特征值(characteristic)。
              @parmas deviceId 设备id
              @parmas serviceId 蓝牙服务uuid ,需要使用getBLEDeviceServices 获取
            */
            getBLEDeviceCharacteristics(deviceId,serviceId){
                const _this = this;
                return new Promise((resolve,reject)=>{
                    uni.getBLEDeviceCharacteristics({
                        deviceId,
                        serviceId,
                        success:res=>{
                          resolve(res);
                        },
                        fail:err=>{
                            console.log("获取特征值失败",err)
                            reject(err);
                        }
                    })
                })
            },
            /*断开蓝牙设备连接
              @params deviceId
            */
            closeBLEConnect(deviceId){
                uni.closeBLEConnection({
                    deviceId,
                    success:res=>{
                        this.deviceId = "";
                        console.log("断开成功",res);
                    },
                    fail:err=>{
                        console.error("断开错误",err);
                    }
                })
            },
            /*获取蓝牙设备信号强度 @parmas deviceId 设备id */
            getBLEDeviceRssi(deviceId){
                uni.getBLEDeviceRSSI({
                    deviceId,
                    success:res=>{
                        console.log("获取蓝牙设备强度成功",res);
                    },
                    fail:err=>{
                        console.error("获取蓝牙强度失败,",err);
                    }
                })
            },
            /*读取蓝牙设备特征值的二进制数据
              @parmas deviceId  蓝牙设备Id
              @params serviceId  蓝牙特征值 对应服务的uuid
              @params characteristicId 蓝牙特征值的 uuid
            */
            readBLEDeviceData(deviceId,serviceId,characteristicId){
                uni.readBLECharacteristicValue({
                    deviceId,
                    serviceId,
                    characteristicId,
                    success:res=>{
                        console.log("读取设备值成功",res);
                    },
                    fail:err=>{
                        console.error("读取设备值err",err)
                    }
                })
            },
            
            Toast(title){
                uni.showToast({
                    title,
                    position:'bottom',
                    icon:'none'
                })
            },
            
        },
        onLoad() {
            //监听蓝牙是否搜索
            uni.onBluetoothAdapterStateChange((res)=>{
                console.log("蓝牙"+(res.discovering ? "开启":"关闭")+"搜索")
                this.discovering = res.discovering;
            })
            //监听扫描到的蓝牙设备
            uni.onBluetoothDeviceFound(resd=>{
                const devices = resd.devices;
            })
            this.onBLEConnectionStateChange();
            this.seachDevice()
            // this.onBLECharacteristicValueChange()
        },
        onUnload() {
            if(this.discovering){
                this.stopBluetoothDevicesDiscovery();
            }
            if(this.Connecting){
                this.closeBLEConnect(this.deviceId);
            }
        },
        
    }

你可能感兴趣的:(在uniAPP中使用使用低功耗蓝牙通讯)