<p>示例代码:</p>
<pre><code>wx.getBluetoothAdapterState({
success: function(res) {
console.log('蓝牙适配器状态:', res)
}
})</code></pre>
<ol start="2">
<li>监听蓝牙连接状态变化</li>
</ol>
<p>使用wx.onBLEConnectionStateChange()方法可以监听蓝牙连接森桥哪状态变化事件,当蓝牙连接状态发生变化时,会触发该事件。在事件回调函数中可以获取当前蓝牙连接状态。</p>
<p>示例代码:</p>
<pre><code>wx.onBLEConnectionStateChange(function(res) {
console.log('蓝牙连接状态变化:', res)
})</code></pre>
<p>通过以上两个方法,可以实现在微信小程序中显示蓝牙连接状态。</p>
#使用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 不知道有没有潜在的问题,目前线上运行为发现任何的问题
#今天的蓝牙使用心得到此结束,谢谢
//初始化蓝牙initBlue() {
var that = this
wx.openBluetoothAdapter({ //调用微信小程序api 打开蓝牙适配器接口
success: function (res) {
console.log('1.初始化蓝牙成功')
},
//监听手机蓝牙的开关
monitorTheBlue:function(){
var that =this
wx.onBluetoothAdapterStateChange(function(res){
})
},
//开始获取附近的蓝牙设备
//. 获取到附近的蓝牙数组 通过蓝牙特定的名称获取自己想要连接的蓝牙设备
//. 获取附近蓝牙设备的数组
findBlue() {
console.log(new Date())
var that = this
wx.startBluetoothDevicesDiscovery({
allowDuplicatesKey: false,
interval: 0,
success: function (res) {
console.log('2.正在搜索设备.............')
if (that.data.isFirestShow) {
wx.showLoading({
title: '正在搜索设备'
})
}
},
//搜索获取附近的所有蓝牙设备 获取附近所有的蓝牙设备的相关信息 获取需要连接蓝牙设备的deviceID
//. 通过bluetoothDeviceName 和 localName 来确定制定蓝牙
//. 一般根据制定亏毕设备的名漏空局字去连接 设备的名字 是出产厂家设定
getBlue() {
var that = this
wx.getBluetoothDevices({
success: function (res) {
console.log('3.找到设备列表........')
wx.hideLoading()
// return false
var index = 10
for (var i = 0i <res.devices.lengthi++) {
if (res.devices[i].name &&res.devices[i].localName) {
var arr = res.devices[i].name.split("-")
var secArr = res.devices[i].localName.split("-")
if (arr[0] == that.data.bluetoothDeviceName || secArr[0] == that.data.bluetoothDeviceName) {
},
//连接蓝牙设备
//通过deviceId 连接蓝牙
/**
},
/返让/6 连接上需要的蓝牙设备之后,获取这个蓝牙设备的服务uuid
//获取设备的uuid
getServiceId() {
var that = this
wx.getBLEDeviceServices({
// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
deviceId: that.data.deviceId,
success: function (res) {
var model = res.services[1]
that.setData({
servicesUUID: model.uuid
})
console.log('7.获取设备 uuid 成功....')
that.getCharacteId() //6.0
}
})
},
//7 如果一个蓝牙设备需要进行数据的写入以及数据传输,就必须具有某些特征值,所以通过上面步骤获取的id可以查看当前蓝牙设备的特征值
//notify write read 当只有 notify为true的时候才能 接收蓝牙设备传来的数据,
//write 为true 才能传入数据
//read 为true 才能读取设备数据
getCharacteId() {
var that = this
wx.getBLEDeviceCharacteristics({
// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
deviceId: that.data.deviceId,
// 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
serviceId: that.data.servicesUUID,
success: function (res) {
for (var i = 0i <res.characteristics.lengthi++) { //2个值
var model = res.characteristics[i]
if (model.properties.notify == true) {
that.setData({
characteristicId: model.uuid //监听的值
})
console.log('8.model.properties.notify == true')
that.startNotice(model.uuid) //7.0
}
// if (model.properties.read == true) {
// that.readData(model.uuid)
// }
// if (model.properties.write == true) {
// that.setData({
// writeId: model.uuid//用来写入的值
// })
// }
}
}
})
},
fordateTime1(){
let now = new Date(),hour = now.getHours()
console.log(hour)
let str = ''
if(hour <7){str = '早餐前'}
else if ((7<hour) &&(hour<= 9)){str = '早餐后'}
else if ((9<hour) &&(hour<= 11)){str = '午餐前'}
else if ((11<hour) &&(hour<= 13)){str = '午餐后'}
else if ((13<hour) &&(hour<= 17)){str = '晚餐前'}
else if ((17<hour) &&(hour<= 19)){str = '晚餐后'}
else if ((19<hour) &&(hour<= 24)){str = '睡觉前'}
return str
},
//8 如果一个蓝牙设备需要进行数据的写入以及数据传输,就必须具有某些特征值,所以通过上面步骤获取的id可以查看当前蓝牙设备的特征值
//开启设备数据监听 监听蓝牙设备返回来的数据
startNotice(uuid) {
var that = this
wx.notifyBLECharacteristicValueChanged({
state: true, // 启用 notify 功能
deviceId: that.data.deviceId,
serviceId: that.data.servicesUUID,
characteristicId: uuid, //第一步 开启监听 notityid 第二步发送指令 write
success: function (res) {
// that.closeConnect(that.data.deviceId)
// 设备返回的方法
let tip = 0
wx.onBLECharacteristicValueChange(res1 =>{
},
/**
//监听蓝牙设备是否会异常断开
getTheBlueDisConnectWithAccident() {
},
// 断开设备连接
closeConnect: function(v) {
var that = this
if (v) {
wx.closeBLEConnection({
deviceId: v,
success: function(res) {
console.log("蓝牙断开连接")
that.closeBluetoothAdapter()
},
fail(res) {
}
})
} else {
that.closeBluetoothAdapter()
}
},
// 关闭蓝牙模块
closeBluetoothAdapter:function () {
wx.closeBluetoothAdapter({
success: function(res) {
console.log("关闭蓝牙模块")
},
fail: function(err) {
}
})
},
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)