charwk
charwk
  • 发布:2020-02-26 11:52
  • 更新:2020-03-30 16:39
  • 阅读:2489

【报Bug】版本号2.6.1.20200226低功耗蓝牙相关api

分类:HBuilderX

详细问题描述

hbuilderX 2.6.1.20200226开启V3编译模式无法使用低功耗蓝牙相关api

1,连接低功耗蓝牙uni.createBLEConnection无法正常返回,不论是success还是fail都没有返回。暂时替代方法uni.onBLEConnectionStateChange方法中收到成功连接状态进行服务扫描。
2,uni.writeBLECharacteristicValue方法fail中报错fail invalid data,please check parameters官方文档中没有找到对应错误码,非v3模式下不报错可以正常发送数据,由于v3模式无法正常发送数据,后续关于蓝牙的相关api无法进行下一步调用

IDE
hbuilderX
[IDE版本号]
2.6.1.20200226

[windows版本号]
win10

代码片段
文件1
<template>
<view style="display: flex;flex-direction: column;">
<view @click="rowClick(item)" v-for="(item, index) in devicesList" :key="index" class="row">
<text style="font-size: 30upx;color: #555555;">设备名称:</text>
<text style="font-size: 30upx;color: #333333;">{{ item.name }}</text>
</view>
</view>
</template>

<script>
export default {
onShow() {
console.log(this.isOpenBle)
let self = this;
uni.openBluetoothAdapter({
success(res) {
console.log('开启蓝牙服务成功:' + JSON.stringify(res));
self.isOpenBle = true;
self.startBluetoothDeviceDiscovery()
},fail(res) {
console.log(JSON.stringify(res))
}
});

},  
onUnload() {  
    this.stopBluetoothDevicesDiscovery(null,false)  
},  
data() {  
    return {  
        isOpenBle: false,  
        devicesList: [],  
    };  
},  
methods: {  
    rowClick(item){  
        this.stopBluetoothDevicesDiscovery(item,true)  
    },  
    /**  
     * 开始搜寻蓝牙  
     */  
    startBluetoothDeviceDiscovery() {  
        //在页面显示的时候判断是都已经初始化完成蓝牙适配器若成功,则开始查找设备  
        let self = this;  
        setTimeout(function() {  
            if (self.isOpenBle) {  
                console.log('开始搜寻智能设备');  
                uni.startBluetoothDevicesDiscovery({  
                    success: res => {  
                        self.onBluetoothDeviceFound();  
                    },  
                    fail: res => {  
                        console.log('查找设备失败!');  
                        uni.showToast({  
                            icon: 'none',  
                            title: '查找设备失败!',  
                            duration: 3000  
                        });  
                    }  
                });  
            } else {  
                console.log('未初始化蓝牙是配饰器:' + self.isOpenBle);  
            }  
        }, 300);  
    },  
    /**  
     * 停止搜索蓝牙设备  
     */  
    stopBluetoothDevicesDiscovery(item,type) {  
        uni.stopBluetoothDevicesDiscovery({  
            success: e => {  
                console.log('停止搜索蓝牙设备:' + e.errMsg);  
                if(type){  
                    uni.navigateTo({  
                        url:'../bluetoothinfo/bluetoothinfo?deviceId='+item.deviceId+'&name='+item.name  
                    })  
                }  
            },  
            fail: e => {  
                console.log('停止搜索蓝牙设备失败,错误码:' + e.errCode);  
            }  
        });  
    },  
    /**  
     * 发现外围设备  
     */  
    onBluetoothDeviceFound() {  
        console.log('监听寻找新设备');  
        uni.onBluetoothDeviceFound(devices => {  
            console.log('开始监听寻找到新设备的事件');  
            this.getBluetoothDevices();  
        });  
    },  
    /**  
     * 获取在蓝牙模块生效期间所有已发现的蓝牙设备。包括已经和本机处于连接状态的设备。  
     */  
    getBluetoothDevices() {  
        console.log('获取蓝牙设备');  
        let self = this  
        uni.getBluetoothDevices({  
            success: res => {  
                console.log('获取蓝牙设备成功:' + res.errMsg);  
                self.devicesList = [];  
                //在这里查找Belter_BT名称的血压仪  
                for (let i = 0; i < res.devices.length; i++) {  
                    let eq = res.devices[i];  
                    if (eq.name.length>0) {  
                        self.devicesList.push(eq)  
                    }  
                }  
            },  
            fail: e => {  
                console.log('获取蓝牙设备错误,错误码:' + e.errCode);  
            }  
        });  
    }  
}  

};
</script>

<style scoped>
.row {
margin-left: 20upx;
height: 88upx;
align-items: center;
display: flex;
flex-direction: row;
border-bottom-width: 1upx;
border-bottom-color: #C0C0C0;
border-bottom-style: solid;
}
</style>
文件2
<template>
<view>
<view @click="sendText">
<text>{{ deviceName }}</text>
</view>
</view>
</template>

<script>
export default {
onLoad(params) {
this.deviceName = params.name;
this.deviceId = params.deviceId;
},
onReady() {
this.createBLEConnection();
this.onBLEConnectionStateChange();
},
onUnload() {
this.closeBluetoothAdapter();
},
data() {
return {
deviceName: '',
deviceId: '',
//服务Id
serviceId: '0000FFF0-0000-1000-8000-00805F9B34FB',
//特征值ID
characteristicId: [
{
//支持写入操作的特征值
writeId: '0000FFF2-0000-1000-8000-00805F9B34FB',
//支持notify操作的特征值
notifyId: '0000FFF1-0000-1000-8000-00805F9B34FB'
}
]
};
},
methods: {
sendText() {
let text = this.strToHexCharCode('hello')
console.log(text)
this.writeBLECharacteristicValue();
},
strToHexCharCode(str) {
  if(str === "")
    return "";
  var hexCharCode = [];
  hexCharCode.push("0x");
  for(var i = 0; i < str.length; i++) {
    hexCharCode.push((str.charCodeAt(i)).toString(16));
  }
  return hexCharCode.join("");
},
//字符串转buffer 十六进制
stringToHexBuffer(data) {
// var data = 'AA5504B10000B5'
var typedArray = new Uint8Array(
data.match(/[\da-f]{2}/gi).map(function(h) {
return parseInt(h, 16);
})
);

        return typedArray.buffer;  
    },  
    /**  
     * 写入控制命令  
     * writeCode 写入的控制命令  
     */  
    writeBLECharacteristicValue(writeCode) {  
        let deviceId = this.deviceId;  
        let serviceId = this.serviceId;  
        let characteristicId = this.characteristicId[0].writeId;  

        var hex = this.strToHexCharCode('hello');  

        var buffer = this.stringToHexBuffer(hex);  

        uni.writeBLECharacteristicValue({  
            // 这里的 deviceId 需要在 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取  
            deviceId,  
            // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取  
            serviceId,  
            // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取  
            characteristicId,  
            // 这里的value是ArrayBuffer类型  
            value: buffer,  
            success(res) {  
                console.log('writeBLECharacteristicValue success', res.errMsg);  
                console.log('writeBLECharacteristicValue success', JSON.stringify(res));  
                //this.notifyCharacteristicValueChange();  
            },  
            fail(res) {  
                console.log('写入数据失败', res.errMsg);  
            }  
        });  
    },  

    /**  
     * 连接设备  
     */  
    createBLEConnection() {  
        console.log('开始连接设备:' + this.deviceName + '---' + this.deviceId);  
        //设备deviceId  
        let deviceId = this.deviceId;  
        let self = this;  
        uni.createBLEConnection({  
            // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接  
            deviceId,  
            success: res => {  
                console.log('设备连接成功!');  
            },  
            fail: res => {  
                console.log(JSON.stringify(res));  
                console.log('设备连接失败!');  
            }  
        });  
    },  
    /**  
     * 获取设备的服务ID  
     */  
    getBLEDeviceServices() {  
        let deviceId = this.deviceId;  
        let serviceList = [];  
        let self = this;  
        uni.getBLEDeviceServices({  
            // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接  
            deviceId,  
            success: res => {  
                console.log(JSON.stringify(res));  
                serviceList = res.services;  
                for (let i = 0; i < serviceList.length; i++) {  
                    let service = serviceList[i];  
                    console.log(JSON.stringify(service) + '----serviceID:' + service.uuid);  
                    //比对service是否是FFF0服务  
                    if (service.uuid.indexOf('0000FFF0-0000-1000-8000-00805F9B34FB') != -1) {  
                        self.serviceId = service.uuid;  
                        console.log('设备的serviceId: ' + self.serviceId);  
                        //开始获取指定服务的特征值  
                        self.getBLEDeviceCharacteristics();  
                        break;  
                    }  
                }  
            },  
            fail: res => {  
                console.log('device services:', res.services);  
            }  
        });  
    },  
    /**  
     * 获取指定服务的特征值  
     */  
    getBLEDeviceCharacteristics() {  
        let deviceId = this.deviceId;  
        let serviceId = this.serviceId;  
        let characteristicsList = [];  
        let self = this;  
        uni.getBLEDeviceCharacteristics({  
            // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接  
            deviceId,  
            // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取  
            serviceId,  
            success: res => {  
                console.log(JSON.stringify(res));  
                console.log('获取的' + serviceId + '服务的特征值:' + JSON.stringify(res.characteristics));  
                characteristicsList = res.characteristics;  
                for (let i = 0; i < characteristicsList.length; i++) {  
                    let characteristic = characteristicsList[i];  
                    //判断服务特征值中的特征值FFF3 和 FFF4  
                    if (characteristic.uuid.indexOf('0000FFF2-0000-1000-8000-00805F9B34FB') != -1) {  
                        self.characteristicId[0].writeId = characteristic.uuid;  
                        console.log('设备的特征值写入ID: ' + self.characteristicId[0].writeId);  
                    }  
                    if (characteristic.uuid.indexOf('0000FFF1-0000-1000-8000-00805F9B34FB') != -1) {  
                        self.characteristicId[0].notifyId = characteristic.uuid;  
                        console.log('设备的特征值notifyID: ' + self.characteristicId[0].notifyId);  
                    }  
                }  
                this.notifyBLECharacteristicValue();  
            },  
            fail: res => {  
                console.log('获取设备特征值失败');  
                console.log('device getBLEDeviceCharacteristics failed:', JSON.stringify(res));  
            }  
        });  
    },  
    buf2hex(buffer) {  
        // buffer is an ArrayBuffer  
        return Array.prototype.map.call(new Uint8Array(buffer), x => ('00' + x.toString(16)).slice(-2)).join('');  
    },  
    /**  
     * 开启订阅特征值  
     */  
    notifyBLECharacteristicValue() {  
        let deviceId = this.deviceId;  
        let serviceId = this.serviceId;  
        let characteristicId = this.characteristicId[0].notifyId;  
        let notify = true;  
        let self = this;  
        uni.notifyBLECharacteristicValueChange({  
            state: true, // 启用 notify 功能  
            // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接  
            deviceId,  
            // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取  
            serviceId,  
            // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取  
            characteristicId,  
            success(res) {  
                console.log('订阅特征值成功');  
                console.log('notifyBLECharacteristicValueChange success:' + JSON.stringify(res));  

                uni.onBLECharacteristicValueChange(function(valueRes) {  
                    console.log("特征值发生改变")  
                    var value = Array.prototype.map.call(new Uint8Array(valueRes.value), x => ('00' + x.toString(16)).slice(-2)).join('');  
                    console.log(value);  

                    console.log('----------------------------------------------');  
                });  
            },  
            fail(res) {  
                console.log('notifyBLECharacteristicValueChange failed:' + res.errMsg);  
                //var value = ab2hex(res.value);  
                console.log(value);  
            }  
        });  
    },  
    /**  
     * 监听低功耗蓝牙连接状态的改变事件。包括开发者主动连接或断开连接,设备丢失,连接异常断开等等  
     */  
    onBLEConnectionStateChange() {  
        let self = this;  
        let count = 0;  
        uni.onBLEConnectionStateChange(res => {  
            // 该方法回调中可以用于处理连接意外断开等异常情况  
            console.log(`蓝牙连接状态 -------------------------->`);  
            console.log(JSON.stringify(res));  
            if (!res.connected) {  
                if (this.isStop) return;  
                console.log('断开低功耗蓝牙成功:');  

                uni.showToast({  
                    icon: 'none',  
                    title: '蓝牙已经断开!',  
                    mask: false,  
                    duration: 3000  
                });  
                //关闭连接  
                this.closeBluetoothAdapter();  
            } else {  
                if (count == 0) {  
                    //延迟1.5s获取设备的services  
                    setTimeout(function() {  
                        console.log('获取设备的services');  
                        count++;  
                        self.getBLEDeviceServices();  
                    }, 1500);  
                }  
            }  
        });  
    },  
    /**  
     * 断开蓝牙连接  
     */  
    closeBluetoothAdapter() {  
        uni.closeBluetoothAdapter({  
            success: res => {  
                console.log('断开蓝牙模块成功');  

                uni.showToast({  
                    icon: 'none',  
                    title: '蓝牙已经断开!',  
                    mask: false,  
                    duration: 3000  
                });  
            }  
        });  
    }  
}  

};
</script>

<style></style>

手机型号华为mete20pro
Android 9

联系方式

[QQ]272352688

2020-02-26 11:52 负责人:无 分享
已邀请:
DCloud_UNI_CHB

DCloud_UNI_CHB

关闭v3模式后,问题是否可解决?

  • charwk (作者)

    可以关闭v3可以解决

    2020-02-26 14:02

VICTORICA

VICTORICA - 90后IT

getBLEDeviceServices:fail invalid data,please check parameters,关了V3后,回调函数都没了,咋整啊

  • charwk (作者)

    把uni全部替换成plus.bluetooth可以解决问题

    2020-03-15 14:04

9***@qq.com

9***@qq.com

请问如何关闭v3模式?

该问题目前已经被锁定, 无法添加新回复