星空5G 导航

微信小程序蓝牙教程--完整版亲测-

2024-07-15编辑:本站
~ #使用mpvue 开发小程序过程中 简单介绍一下微信小程序蓝牙连接过程

#在蓝牙连接的过程中部分api需要加定时器延时1秒到2秒左右再执行,原因为何不知道,小程序有这样的要求

#1.首先是要初始化蓝牙:openBluetoothAdapter()

```js

if (wx.openBluetoothAdapter) {

wx.openBluetoothAdapter({

        success: function(res) {

            /* 获取本机的蓝牙状态 */

            setTimeout(() => {

                getBluetoothAdapterState()

            }, 1000)

        },

        fail: function(err) {

            // 初始化失败

        }

    })

    } else {    

    }

```

#2.检测本机蓝牙是否可用:

#  要在上述的初始化蓝牙成功之后回调里调用

```js

getBluetoothAdapterState() {

    var that= this;

    that.toastTitle= '检查蓝牙状态'

wx.getBluetoothAdapterState({

        success: function(res) {

startBluetoothDevicesDiscovery()

},

        fail(res) {

            console.log(res)

}

})

}

```

#3. 开始搜索蓝牙设备:

```js

startBluetoothDevicesDiscovery() {

    var that= this;

    setTimeout(() => {

wx.startBluetoothDevicesDiscovery({

            success: function(res) {

/* 获取蓝牙设备列表 */

                that.getBluetoothDevices()

},

            fail(res) {

}

})

}, 1000)

}

```

#4. 获取搜索到的蓝牙设备列表

# /* that.deviceName 是获取到的蓝牙设备的名称, 因为蓝牙设备在安卓和苹果手机上搜到的蓝牙地址显示是不一样的,所以根据设备名称匹配蓝牙*/

```js

getBluetoothDevices() {

    var that= this;

    setTimeout(() => {

wx.getBluetoothDevices({

            services: [],

            allowDuplicatesKey: false,

            interval: 0,

            success: function(res) {

                if (res.devices.length> 0) {

                    if (JSON.stringify(res.devices).indexOf(that.deviceName) !== -1) {

                        for (let i = 0; i < res.devices.length; i++) {

                            if (that.deviceName === res.devices[i].name) {

/* 根据指定的蓝牙设备名称匹配到deviceId */

                                that.deviceId = that.devices[i].deviceId;

                                setTimeout(() => {

                                    that.connectTO();

}, 2000);

};

};

} else {

}

} else {

}

},

            fail(res) {

                console.log(res, '获取蓝牙设备列表失败=====')

}

})

}, 2000)

},

```

#5.连接蓝牙

# 匹配到的蓝牙设备ID 发送连接蓝牙的请求, 连接成功之后 应该断开蓝牙搜索的api,然后去获取所连接蓝牙设备的service服务

```js

connectTO() {

wx.createBLEConnection({

        deviceId: deviceId,

        success: function(res) {

            that.connectedDeviceId = deviceId;

/* 4.获取连接设备的service服务 */

that.getBLEDeviceServices();

wx.stopBluetoothDevicesDiscovery({

                success: function(res) {

                    console.log(res, '停止搜索')

},

                fail(res) {

}

})

},

        fail: function(res) {

}

})

}

```

#6. 获取蓝牙设备的service服务,获取的serviceId有多个要试着连接最终确定哪个是稳定版本的service 获取服务完后获取设备特征值

```js

getBLEDeviceServices() {

    setTimeout(() => {

wx.getBLEDeviceServices({

            deviceId: that.connectedDeviceId,

            success: function(res) {

                that.services= res.services

/* 获取连接设备的所有特征值 */

that.getBLEDeviceCharacteristics()

},

            fail: (res) => {

}

})

}, 2000)

},

```

#7.获取蓝牙设备特征值

# 获取到的特征值有多个,最后要用的事能读,能写,能监听的那个值的uuid作为特征值id,

```js

getBLEDeviceCharacteristics() {

            setTimeout(() => {

wx.getBLEDeviceCharacteristics({

                    deviceId: connectedDeviceId,

                    serviceId: services[2].uuid,

                    success: function(res) {

                        for (var i = 0; i < res.characteristics.length; i++) {

                            if ((res.characteristics[i].properties.notify || res.characteristics[i].properties.indicate) &&

                                (res.characteristics[i].properties.read && res.characteristics[i].properties.write)) {

                                console.log(res.characteristics[i].uuid, '蓝牙特征值 ==========')

/* 获取蓝牙特征值 */

                                that.notifyCharacteristicsId = res.characteristics[i].uuid

// 启用低功耗蓝牙设备特征值变化时的 notify 功能

that.notifyBLECharacteristicValueChange()

}

}

},

                    fail: function(res) {

}

})

}, 1000)

},

```

#8.启动notify 蓝牙监听功能 然后使用 wx.onBLECharacteristicValueChange用来监听蓝牙设备传递数据

#接收到的数据和发送的数据必须是二级制数据, 页面展示的时候需要进行转换

```js

notifyBLECharacteristicValueChange() { // 启用低功耗蓝牙设备特征值变化时的 notify 功能

            var that= this;

            console.log('6.启用低功耗蓝牙设备特征值变化时的 notify 功能')

wx.notifyBLECharacteristicValueChange({

                state: true,

                deviceId: that.connectedDeviceId,

                serviceId: that.notifyServicweId,

                characteristicId: that.notifyCharacteristicsId,

                complete(res) {

/*用来监听手机蓝牙设备的数据变化*/

wx.onBLECharacteristicValueChange(function(res) {

/**/

                        that.balanceData += that.buf2string(res.value)

                        that.hexstr += that.receiveData(res.value)

})

},

                fail(res) {

                    console.log(res, '启用低功耗蓝牙设备监听失败')

                    that.measuringTip(res)

}

})

},

/*转换成需要的格式*/

buf2string(buffer) {

                    var arr = Array.prototype.map.call(new Uint8Array(buffer), x => x)

                    return arr.map((char, i) => {

                        return String.fromCharCode(char);

                    }).join('');

},

receiveData(buf) {

return this.hexCharCodeToStr(this.ab2hex(buf))

},

/*转成二进制*/

ab2hex (buffer) {

              var hexArr = Array.prototype.map.call(

                  new Uint8Array(buffer), function (bit) {

                      return ('00' + bit.toString(16)).slice(-2)

}

)

              return hexArr.join('')

},

/*转成可展会的文字*/

hexCharCodeToStr(hexCharCodeStr) {

              var trimedStr = hexCharCodeStr.trim();

              var rawStr = trimedStr.substr(0, 2).toLowerCase() === '0x' ? trimedStr.substr(2) : trimedStr;

              var len = rawStr.length;

              var curCharCode;

              var resultStr= [];

              for (var i = 0; i < len; i = i+ 2) {

                  curCharCode = parseInt(rawStr.substr(i, 2), 16);

                  resultStr.push(String.fromCharCode(curCharCode));

}

              return resultStr.join('');

},

```

# 向蓝牙设备发送数据

```js

sendData(str) {

    let that= this;

    let dataBuffer = new ArrayBuffer(str.length)

    let dataView = new DataView(dataBuffer)

    for (var i = 0; i < str.length; i++) {

        dataView.setUint8(i, str.charAt(i).charCodeAt())

}

    let dataHex = that.ab2hex(dataBuffer);

    this.writeDatas = that.hexCharCodeToStr(dataHex);

wx.writeBLECharacteristicValue({

        deviceId: that.connectedDeviceId,

        serviceId: that.notifyServicweId,

        characteristicId: that.notifyCharacteristicsId,

        value: dataBuffer,

        success: function (res) {

            console.log('发送的数据:' + that.writeDatas)

            console.log('message发送成功')

},

        fail: function (res) {

},

        complete: function (res) {

}

})

},

```

# 当不需要连接蓝牙了后就要关闭蓝牙,并关闭蓝牙模块

```js

// 断开设备连接

closeConnect() {

if (that.connectedDeviceId) {

wx.closeBLEConnection({

            deviceId: that.connectedDeviceId,

            success: function(res) {

that.closeBluetoothAdapter()

},

            fail(res) {

}

})

} else {

that.closeBluetoothAdapter()

}

},

// 关闭蓝牙模块

closeBluetoothAdapter() {

wx.closeBluetoothAdapter({

        success: function(res) {

},

        fail: function(err) {

}

})

},

```

#在向蓝牙设备传递数据和接收数据的过程中,并未使用到read的API 不知道有没有潜在的问题,目前线上运行为发现任何的问题

#今天的蓝牙使用心得到此结束,谢谢

  • vivos12pro微信小程序蓝牙连不上
  • 答:可参考以下无法连接蓝牙设备处理步骤:1、确认蓝牙设备电量与连接范围确认蓝牙设备电量充足,蓝牙连接有效距离一般为10米左右,如果双方设备距离较远或中间存在障碍物,则可能搜索不到蓝牙设备。2、确认蓝牙设备连接状态确保没有其他手机连接此蓝牙设备。3、重新配对蓝牙设备请参考蓝牙设备说明书操作,确保设备...

  • 农村信用社新大陆云音箱怎么连接微信使用
  • 答:首先需要点击进入手机“设置”按钮,如下图所示。接下来需要选择上方的“蓝牙”选项进入,如下图所示。接着点击打开蓝牙开关按钮,如下图所示。接下来需要选择“农业银行云音箱”点击链接,如下图所示。首先,完成S1收款音箱的扫码绑定,确保手机已经连接WiFi。打开微信小程序中的【收款小账本】。进入【收款...

  • 微信小程序说请打开蓝牙但开着蓝牙
  • 答:重新连接。有时候在显示过程中打开蓝牙,小程序未能及时接收到信息,从而出现打开仍旧提醒的情况。具体步骤:设置---权限管理--微信--开启蓝牙--允许“。

  • 粤通卡微信小程序续卡蓝牙显示网络连接失败,怎么连接?
  • 答:1. 打开蓝牙和位置服务:确保您的手机蓝牙和位置服务已打开并允许微信小程序使用。2. 接近读卡器和屏幕:将手机和读卡器尽量靠近,并确保没有物理障碍干扰信号。3. 重新尝试连接:尝试断开蓝牙连接并重新连接,如果仍然连接失败,可以尝试重启你的手机。4. 确认读卡器可用:确保读卡器已充电并处于可用状态,...

  • 微信小程序功耗蓝牙界面不响应
  • 答:微信小程序说请打开蓝牙但开着蓝牙微信小程序说请打开蓝牙但开着蓝牙你说的这种情况,是你在微信中启用的小程序,运行的时候需要蓝牙支持,当你打开微信中的该程序时,系统检测到你没有开启手机蓝牙,提示你检查并打开手机蓝牙。第一步,打开手机,找到的“系统工具”并打开。第二步,打开“系统工具”后...

  • 小程序蓝牙接收不完整怎么回事
  • 答:手机没有开启开放检测。手机CPU占用太高导致无法连接。进行对比测试同时使用两个无配对记录的手机搜索,如果其他手机也不能搜索到设备,则可能是蓝牙设备故障。重置网络设置进入设置--系统管理--备份与重置--重置网络设置--重置设置,再使用查看。题主是否想询问“微信小程序功耗蓝牙界面不响应解决方法”方法...

  • 微信小程序蓝牙入坑总结
  • 答:   微信小程序的蓝牙流程按着官网的说明写就可以了,具体参看文档: 小程序开发文档 坑列表:    1.成对调用需要注意, wx.openBluetoothAdapter 与 wx.closeBluetoothAdapter             ...

  • 微信申请蓝牙权限我拒绝了,然后怎么再打开
  • 答:其实开启微信蓝牙权限的方法很简单。但是还是有一些小伙伴不知道,下面我将所知道的方法分享给你,希望能对你有所帮助。 详细步骤如下: 1、我们打开应用管理后,找到微信应用点击一下。 2、在应用信息界面点击【权限管理】 3、接着点击【开启蓝牙】 4、最后勾选为【始终允许】就可以开启微信蓝牙权限了! 1 已赞过 ...

  • 微信小程序手机提示蓝牙未开启
  • 答:蓝牙没有打开需要打开的话直接把手机主屏幕拉下来然后打开蓝牙。

  • 微信小程序雷恩之家搜不到蓝牙
  • 答:打开蓝牙开关。查看收是否打开了蓝牙开关,再看一下微信app是否允许使用了蓝牙的选项。腾讯微信(faq)是一种更快速的短邮,具有跨平台沟通、显示实时输入状态等功能,与传统的短信沟通方式相比,更灵活、智能,且节省资费。

    相关内容

    首页 新知 身健
    返回顶部

    © 星空5G w.xkyn.com