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

微信小程序蓝牙教程--完整版亲测,第1张

#使用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 = 0i <res.devices.lengthi++) {

                            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 = 0i <res.characteristics.lengthi++) {

                            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 = 0i <leni = 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 = 0i <str.lengthi++) {

        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 不知道有没有潜在的问题,目前线上运行为发现任何的问题

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

蓝蔽散牙适配器接口是基础库版本 1.1.0 开始支持。

iOS 微信客户端 6.5.6 版本开始支持,Android 客户端暂不支持

蓝牙总共增加了18个api接口。

Api分类

搜索类者坦

连接类

通信类

案例实现

搜索蓝牙设备

/**

* 搜首并桐索设备界面

*/

Page({

data: {

logs: [],

list:[],

},

onLoad: function () {

console.log('onLoad')

var that = this

// const SDKVersion = wx.getSystemInfoSync().SDKVersion || '1.0.0'

// const [MAJOR, MINOR, PATCH] = SDKVersion.split('.').map(Number)

// console.log(SDKVersion)

// console.log(MAJOR)

// console.log(MINOR)

// console.log(PATCH)

// const canIUse = apiName =>{

// if (apiName === 'showModal.cancel') {

// return MAJOR >= 1 &&MINOR >= 1

// }

// return true

// }

// wx.showModal({

// success: function(res) {

// if (canIUse('showModal.cancel')) {

// console.log(res.cancel)

// }

// }

// })

//获取适配器

wx.openBluetoothAdapter({

success: function(res){

// success

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

console.log(res)

//开始搜索

wx.startBluetoothDevicesDiscovery({

services: [],

success: function(res){

// success

console.log("-----startBluetoothDevicesDiscovery--success----------")

console.log(res)

},

fail: function(res) {

// fail

console.log(res)

},

complete: function(res) {

// complete

console.log(res)

}

})

},

fail: function(res) {

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

// fail

console.log(res)

},

complete: function(res) {

// complete

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

console.log(res)

}

})

wx.getBluetoothDevices({

success: function(res){

// success

//{devices: Array[11], errMsg: "getBluetoothDevices:ok"}

console.log("getBluetoothDevices")

console.log(res)

that.setData({

list:res.devices

})

console.log(that.data.list)

},

fail: function(res) {

// fail

},

complete: function(res) {

// complete

}

})

},

onShow:function(){

},

//点击事件处理

bindViewTap: function(e) {

console.log(e.currentTarget.dataset.title)

console.log(e.currentTarget.dataset.name)

console.log(e.currentTarget.dataset.advertisData)

var title = e.currentTarget.dataset.title

var name = e.currentTarget.dataset.name

wx.redirectTo({

url: '../conn/conn?deviceId='+title+'&name='+name,

success: function(res){

// success

},

fail: function(res) {

// fail

},

complete: function(res) {

// complete

}

})

},

})

连接 获取数据

/**

* 连接设备。获取数据

*/

Page({

data: {

motto: 'Hello World',

userInfo: {},

deviceId: '',

name: '',

serviceId: '',

services: [],

cd20: '',

cd01: '',

cd02: '',

cd03: '',

cd04: '',

characteristics20: null,

characteristics01: null,

characteristics02: null,

characteristics03: null,

characteristics04: null,

result,

},

onLoad: function (opt) {

var that = this

console.log("onLoad")

console.log('deviceId=' + opt.deviceId)

console.log('name=' + opt.name)

that.setData({ deviceId: opt.deviceId })

/**

* 监听设备的连接状态

*/

wx.onBLEConnectionStateChanged(function (res) {

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

})

/**

* 连接设备

*/

wx.createBLEConnection({

deviceId: that.data.deviceId,

success: function (res) {

// success

console.log(res)

/**

* 连接成功,后开始获取设备的服务列表

*/

wx.getBLEDeviceServices({

// 这里的 deviceId 需要在上面的 getBluetoothDevices中获取

deviceId: that.data.deviceId,

success: function (res) {

console.log('device services:', res.services)

that.setData({ services: res.services })

console.log('device services:', that.data.services[1].uuid)

that.setData({ serviceId: that.data.services[1].uuid })

console.log('--------------------------------------')

console.log('device设备的id:', that.data.deviceId)

console.log('device设备的服务id:', that.data.serviceId)

/**

* 延迟3秒,根据服务获取特征

*/

setTimeout(function () {

wx.getBLEDeviceCharacteristics({

// 这里的 deviceId 需要在上面的 getBluetoothDevices

deviceId: that.data.deviceId,

// 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取

serviceId: that.data.serviceId,

success: function (res) {

console.log('000000000000' + that.data.serviceId)

console.log('device getBLEDeviceCharacteristics:', res.characteristics)

for (var i = 0i <5i++) {

if (res.characteristics[i].uuid.indexOf("cd20") != -1) {

that.setData({

cd20: res.characteristics[i].uuid,

characteristics20: res.characteristics[i]

})

}

if (res.characteristics[i].uuid.indexOf("cd01") != -1) {

that.setData({

cd01: res.characteristics[i].uuid,

characteristics01: res.characteristics[i]

})

}

if (res.characteristics[i].uuid.indexOf("cd02") != -1) {

that.setData({

cd02: res.characteristics[i].uuid,

characteristics02: res.characteristics[i]

})

} if (res.characteristics[i].uuid.indexOf("cd03") != -1) {

that.setData({

cd03: res.characteristics[i].uuid,

characteristics03: res.characteristics[i]

})

}

if (res.characteristics[i].uuid.indexOf("cd04") != -1) {

that.setData({

cd04: res.characteristics[i].uuid,

characteristics04: res.characteristics[i]

})

}

}

console.log('cd01= ' + that.data.cd01 + 'cd02= ' + that.data.cd02 + 'cd03= ' + that.data.cd03 + 'cd04= ' + that.data.cd04 + 'cd20= ' + that.data.cd20)

/**

* 回调获取 设备发过来的数据

*/

wx.onBLECharacteristicValueChange(function (characteristic) {

console.log('characteristic value comed:', characteristic.value)

//{value: ArrayBuffer, deviceId: "D8:00:D2:4F:24:17", serviceId: "ba11f08c-5f14-0b0d-1080-007cbe238851-0x600000460240", characteristicId: "0000cd04-0000-1000-8000-00805f9b34fb-0x60800069fb80"}

/**

* 监听cd04cd04中的结果

*/

if (characteristic.characteristicId.indexOf("cd01") != -1) {

const result = characteristic.value

const hex = that.buf2hex(result)

console.log(hex)

}

if (characteristic.characteristicId.indexOf("cd04") != -1) {

const result = characteristic.value

const hex = that.buf2hex(result)

console.log(hex)

that.setData({ result: hex })

}

})

/**

* 顺序开发设备特征notifiy

*/

wx.notifyBLECharacteristicValueChanged({

deviceId: that.data.deviceId,

serviceId: that.data.serviceId,

characteristicId: that.data.cd01,

state: true,

success: function (res) {

// success

console.log('notifyBLECharacteristicValueChanged success', res)

},

fail: function (res) {

// fail

},

complete: function (res) {

// complete

}

})

wx.notifyBLECharacteristicValueChanged({

deviceId: that.data.deviceId,

serviceId: that.data.serviceId,

characteristicId: that.data.cd02,

state: true,

success: function (res) {

// success

console.log('notifyBLECharacteristicValueChanged success', res)

},

fail: function (res) {

// fail

},

complete: function (res) {

// complete

}

})

wx.notifyBLECharacteristicValueChanged({

deviceId: that.data.deviceId,

serviceId: that.data.serviceId,

characteristicId: that.data.cd03,

state: true,

success: function (res) {

// success

console.log('notifyBLECharacteristicValueChanged success', res)

},

fail: function (res) {

// fail

},

complete: function (res) {

// complete

}

})

wx.notifyBLECharacteristicValueChanged({

// 启用 notify 功能

// 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取

deviceId: that.data.deviceId,

serviceId: that.data.serviceId,

characteristicId: that.data.cd04,

state: true,

success: function (res) {

console.log('notifyBLECharacteristicValueChanged success', res)

}

})

}, fail: function (res) {

console.log(res)

}

})

}

, 1500)

}

})

},

fail: function (res) {

// fail

},

complete: function (res) {

// complete

}

})

},

/**

* 发送 数据到设备中

*/

bindViewTap: function () {

var that = this

var hex = 'AA5504B10000B5'

var typedArray = new Uint8Array(hex.match(/[\da-f]{2}/gi).map(function (h) {

return parseInt(h, 16)

}))

console.log(typedArray)

console.log([0xAA, 0x55, 0x04, 0xB1, 0x00, 0x00, 0xB5])

var buffer1 = typedArray.buffer

console.log(buffer1)

wx.writeBLECharacteristicValue({

deviceId: that.data.deviceId,

serviceId: that.data.serviceId,

characteristicId: that.data.cd20,

value: buffer1,

success: function (res) {

// success

console.log("success 指令发送成功")

console.log(res)

},

fail: function (res) {

// fail

console.log(res)

},

complete: function (res) {

// complete

}

})

},

/**

* ArrayBuffer 转换为 Hex

*/

buf2hex: function (buffer) { // buffer is an ArrayBuffer

return Array.prototype.map.call(new Uint8Array(buffer), x =>('00' + x.toString(16)).slice(-2)).join('')

}

})

效果展示

发送校验指令。获取结果


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/yw/12442227.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-25
下一篇 2023-05-25

发表评论

登录后才能评论

评论列表(0条)

保存