记录荣耀手机使用uni-app蓝牙连接超时问题

发布时间 2023-09-18 11:50:05作者: 伟衙内

  如上图所示,测试了两款华为荣耀手机,使用之前Uni-app连接蓝牙的代码,总是会报超时,能发现蓝牙信号,但是连接不上,代码如下,

findBluetooth(mac) {
    var ths = this;
    this.showDebugInfo("要匹配的mac:" + mac)
    //3. 监听附近的蓝牙
    uni.onBluetoothDeviceFound(function(devices) {
        var device = devices.devices[0];

        var advertisDataStr = ths.ab2hex(device.advertisData);
        var deviceId = ths.toMacString(advertisDataStr);

        if (device.name == "BleLock" && deviceId == mac) {
            ths.deviceInfo.deviceId = device.deviceId;
            ths.showDebugInfo("匹配到蓝牙")
            ths.showDebugInfoToast("匹配到蓝牙")

            //4. 连接蓝牙
            ths.connectBle();

            //5. 停止搜索
            ths.stopFindBluetooth();
        }
        // uni.hideLoading()
    });
},

  这里错误的原因是第五步——停止搜索,当第四步连接蓝牙时,连接蓝牙是个异步操作,所以第五步停止搜索后一直连接蓝牙不上,所以需要在第四步中连接蓝牙后停止搜索,如下代码所示,把上述代码第五步注释掉,

connectBle() {
    var ths = this;

    uni.createBLEConnection({
        // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
        deviceId: ths.deviceInfo.deviceId,
        success(res) {
            ths.deviceInfo.connect = true;

            ths.showDebugInfo("连接蓝牙成功")
            ths.showDebugInfoToast("连接蓝牙成功")

            ths.showDebugInfo(ths.deviceInfo)

            if (ths.deviceInfo.write.serviceId && ths.deviceInfo.write.characteristicId &&
                ths.deviceInfo.notify.serviceId && ths.deviceInfo.notify.characteristicId
               ) { //已经有信息了,则不再获取
                // ths.notify()
                setTimeout(function() {
                    ths.hideMyLoading(true)
                    uni.showLoading({
                        mask: true,
                        title: ths.$t("bike.unlocking"),
                    })
                    ths.notify();
                }, ths.notifyTimeoutValue)
            } else {
                //此处也需要延迟,刚连接上时,无法获取到特征值
                // ths.getServices();
                setTimeout(function() {
                    ths.getServices();
                }, ths.serviceTimeoutValue)
            }
        },
        fail(res) {
            ths.showDebugInfo(res)
            ths.stopAll()
            ths.hideMyLoading(false);
        },
        complete(res) { //无论有没有连上蓝牙,都要停止搜索
            ths.stopFindBluetooth(); //停止搜索蓝牙
        }
    })
},

  

  不知道是不是华为手机在停止搜索蓝牙后,将蓝牙设备中缓存的信息全部清理掉,导致蓝牙设备缓存中无刚才搜索到的蓝牙信息,从而导致无法连接上蓝牙。