收藏
回答

低功耗蓝牙连接成功后经常会自动断开。

框架类型 问题类型 API/组件名称 终端类型 微信版本 基础库版本
小程序 Bug API 微信iOS客户端 8.0.18 2.22.0

我用小程序开发连接低功耗的蓝牙设备,通过 wx.createBLEConnection方法成功建立连接后。在通过wx.onBLEConnectionStateChange 监听会发现,建立的蓝牙连接,经常会发生断开。错误码10003错误,提示The specified device has disconnected from us. ,我尝试过很多蓝牙都会出现这种情况。并且断开时间不固定,有时候1分钟有时候几十秒,有时候长一些。可以确定是蓝牙是正常的,手机小程序是一直开着,手机没有熄屏。 下面是代码。

// pages/mian/test/index.js


var isConnectting=false;

Page({


    /**

     * 页面的初始数据

     */

    data: {

        list:[]

    },


    /**

     * 生命周期函数--监听页面加载

     */

    onLoad: function (options) {

        this.startConnect();

    },


    /**

     * 生命周期函数--监听页面初次渲染完成

     */

    onReady: function () {


    },


    /**

     * 生命周期函数--监听页面显示

     */

    onShow: function () {


    },


    /**

     * 生命周期函数--监听页面隐藏

     */

    onHide: function () {


    },


    /**

     * 生命周期函数--监听页面卸载

     */

    onUnload: function () {


    },


    /**

     * 页面相关事件处理函数--监听用户下拉动作

     */

    onPullDownRefresh: function () {


    },


    /**

     * 页面上拉触底事件的处理函数

     */

    onReachBottom: function () {


    },


    /**

     * 用户点击右上角分享

     */

    onShareAppMessage: function () {


    },

    startConnect: function () {


        var that = this;


        wx.showLoading({


            title: '开启蓝牙适配'


        });


        wx.openBluetoothAdapter({


            success: function (res) {


                console.log("初始化蓝牙适配器");


                console.log(res);


                that.getBluetoothAdapterState();


            },


            fail: function (err) {


                console.log(err);


                wx.showToast({


                    title: '蓝牙初始化失败',


                    icon: 'success',


                    duration: 2000


                })


                setTimeout(function () {


                    wx.hideToast()

                }, 2000)

            }

        });

        wx.onBluetoothAdapterStateChange(function (res) {

            var available = res.available;

            if (available{

                that.getBluetoothAdapterState();

            }

        })

    },

    getBluetoothAdapterState: function () {


        var that = this;


        wx.getBluetoothAdapterState({


            success: function (res) {


                var available = res.available,


                    discovering = res.discovering;


                if (!available{


                    wx.showToast({


                        title: '设备无法开启蓝牙连接',


                        icon: 'success',


                        duration: 2000


                    })


                    setTimeout(function () {


                        wx.hideToast()


                    }, 2000)


                } else {


                    if (!discovering{


                        that.startBluetoothDevicesDiscovery();


                        that.getConnectedBluetoothDevices();


                    }


                }


            }


        })


    }, startBluetoothDevicesDiscovery: function () {


        var that = this;


        wx.showLoading({


            title: '蓝牙搜索'


        });


        wx.startBluetoothDevicesDiscovery({


            services: [],


            allowDuplicatesKey: false,


            success: function (res) {


                if (!res.isDiscovering{


                    that.getBluetoothAdapterState();


                } else {


                    that.onBluetoothDeviceFound();


                }


            },


            fail: function (err) {


                console.log(err);


            }


        });


    }, getConnectedBluetoothDevices: function () {


        var that = this;


        wx.getConnectedBluetoothDevices({


            services: [that.serviceId],


            success: function (res) {


                console.log("获取处于连接状态的设备", res);


                var devices = res['devices'], flag = false, index = 0, conDevList = [];


                devices.forEach(function (value, index, array) {


                    if (value['name'].indexOf('FeiZhi'!= -1{


                        // 如果存在包含FeiZhi字段的设备


                        flag = true;


                        index += 1;


                        conDevList.push(value['deviceId']);


                        that.deviceId = value['deviceId'];


                        return;


                    }


                });


                if (flag{


                    this.connectDeviceIndex = 0;


                    that.loopConnect(conDevList);


                } else {


                    if (!this.getConnectedTimer{


                        that.getConnectedTimer = setTimeout(function () {


                            that.getConnectedBluetoothDevices();


                        }, 5000);


                    }


                }


            },


            fail: function (err) {


                if (!this.getConnectedTimer{


                    that.getConnectedTimer = setTimeout(function () {


                        that.getConnectedBluetoothDevices();


                    }, 5000);


                }


            }


        });


    }, onBluetoothDeviceFound: function () {


        var that = this;


        console.log('onBluetoothDeviceFound');

        let list=[];

        wx.onBluetoothDeviceFound(function (res) {


            console.log('new device list has founded')


            console.log(res);


            res.devices.forEach(item => {

              

                var name = item['name'];

                list.push(item);

                that.setData({list})

                if (name != ''{


                    if (name.indexOf('Look1'!= -1{

                        console.log("-----------------")

                        var deviceId = item['deviceId'];


                        that.deviceId = deviceId;


                        console.log(that.deviceId);


                        that.startConnectDevices();

                        return;

                    }


                }

            });


        })


    }, startConnectDevices: function (ltype, array) {

        debugger

        var that = this;


        clearTimeout(that.getConnectedTimer);


        that.getConnectedTimer = null;


        clearTimeout(that.discoveryDevicesTimer);


        //that.stopBluetoothDevicesDiscovery();

            // 取消蓝牙监听事件

    wx.offBluetoothDeviceFound(function(){})

    wx.stopBluetoothDevicesDiscovery({

        success:function(){

          console.log("取消成功");

        }

      })


        this.isConnectting = true;


        wx.createBLEConnection({


            deviceId: that.deviceId,


            success: function (res) {


                if (res.errCode == 0{


                    setTimeout(function () {


                        that.getService(that.deviceId);


                    }, 5000)


                }


            },


            fail: function (err) {


            },


            complete: function () {


            }


        });


    }, getService: function (deviceId) {


        var that = this;


        // 监听蓝牙连接


        wx.onBLEConnectionStateChange(function (res) {

            console.log("蓝牙状态变化")

            // 该方法回调中可以用于处理连接意外断开等异常情况

            console.log(`device ${res.deviceId} state has changed, connected: ${res.connected}`)

            console.log(res);


        });


        // 获取蓝牙设备service值


        // wx.getBLEDeviceServices({


        //     deviceId: deviceId,


        //     success: function (res) {


        //         that.getCharacter(deviceId, res.services);


        //     }


        // })


    }, getCharacter: function (deviceId, services) {


        var that = this;


        services.forEach(function (value, index, array) {


            if (value == that.serviceId{


                that.serviceId = array[index];


            }


        });


        wx.getBLEDeviceCharacteristics({


            deviceId: deviceId,


            serviceId: that.serviceId,


            success: function (res) {


                that.writeBLECharacteristicValue(deviceId, that.serviceId, that.characterId_write);


                that.openNotifyService(deviceId, that.serviceId, that.characterId_read);


            },


            fail: function (err) {


                console.log(err);


            },


            complete: function () {


                console.log('complete');


            }


        })


    }, loopConnect: function (devicesId) {


        var that = this;


        var listLen = devicesId.length;


        if (devicesId[this.connectDeviceIndex]) {


            this.deviceId = devicesId[this.connectDeviceIndex];


            this.startConnectDevices('loop', devicesId);


        } else {


            console.log('已配对的设备小程序蓝牙连接失败');


            that.startBluetoothDevicesDiscovery();


            that.getConnectedBluetoothDevices();


        }


    }

})

"The

啊 specified device has disconnected from us."

回答关注问题邀请回答
收藏

1 个回答

  • 神经蛙
    神经蛙
    2022-02-27

    2022-02-27
    有用
    回复 1
    • 小船舱
      小船舱
      2023-08-28
      是这样重新调取wx.createBLEConnection吗?重新调取链接返回错误:errCode: 10003
      errMsg: "createBLEConnection:fail:connection fail status:8"
      errno: 1509001
      2023-08-28
      回复
登录 后发表内容