微信小程序之蓝牙开发(详细读数据、写数据、附源码)

本文将详细介绍微信小程序的蓝牙开发流程(附源码)
准备:
微信只支持低功耗蓝牙也就是蓝牙4.0,普通的蓝牙模块是用不了的,一定要注意。

蓝牙可以连TTL接到电脑上,再用XCOM调试

一开始定义的变量

var deviceId;
var i=0;
var serviceId=[];
var characteristicId=[];


蓝牙开发流程:
1.打开蓝牙适配器

2.搜索周围蓝牙

3.获取搜索过程中所搜索到的设备信息

4.连接想要连接的设备

5.获取服务、特征值

6.写数据、读数据

 

具体实现:
1.打开蓝牙适配器

wx.openBluetoothAdapter({
success: function(res) {
console.log(res,"success")
},
fail: function (res) {
console.log("fail")
},
})


2.适配器打开后可以开始搜索蓝牙设备了

wx.startBluetoothDevicesDiscovery({
services: [],
success: function (res) {
console.log(res)
},
fail: function (res) {
console.log("fail")
},
})
    sevices里不要填参数,要不然只能搜索特定的设备

3.搜索一小段时间后可以查看搜索到的设备,一般时间很短,1s都不用,搜不到可以多等等

wx.getBluetoothDevices({
success: function (res) {
console.log(res)
i=0;
while (res.devices[i]) {
console.log(i);
console.log(res.devices[i].name,res.devices[i].deviceId);
if(res.devices[i].name=='YahBoom_BL'){
deviceId=res.devices[i].deviceId;
console.log(deviceId);
}
i++;
}
}
})
这一步将所有搜索到的设备的名字和ID输出,并将名字为'YahBoom_BL'的设备的Id存到deviceId里去,这个设备就是我所需要使用的

 

4.现在我们可以获取一个特定设备的所有服务了

wx.getBLEDeviceServices({
deviceId: deviceId,
success: function(res) {
console.log(res.services);
i=0;
while(res.services[i]){
serviceId[i]=res.services[i].uuid;
console.log(serviceId[i]);
i++;
}
},
})
这一步我们获取YahBoom_BL的所有服务并储存到serviceId数组里去

5.现在我们可以针对一个特定服务查看这个服务所支持的操作

wx.getBLEDeviceCharacteristics({
deviceId: deviceId,
serviceId: serviceId[1],
success: function (res) {
i=0;
while(res.characteristics[i]){
characteristicId[i]=res.characteristics[i].uuid;
console.log(characteristicId[i]);
i++;
}
}
})
在这里我们获取YahBoom_BL的第二个服务(第一个服务下标为0,选第二个因为我的设备的第二个服务的第一个特征值支持notif、read、write,可以把一个服务的所有特征值打印出来查看)的特征值,并将特征值ID存到characteristicId数组里去

 

6.开启notify并读取蓝牙发过来的数据,开启这个后我们就能实时获取蓝牙发过来的值了


wx.notifyBLECharacteristicValueChange({
state: true,
deviceId: deviceId,
serviceId: serviceId[1],
characteristicId: characteristicId[0],
success: function (res) {
console.log('notifyBLECharacteristicValueChange success', res.errMsg)
}
})
function ab2hex(buffer) {
var hexArr = Array.prototype.map.call(
new Uint8Array(buffer),
function(bit) {
return ('00' + bit.toString(16)).slice(-2)
}
)
return hexArr.join('');
}
wx.onBLECharacteristicValueChange(function (res) {
console.log('characteristic value comed:', ab2hex(res.value))
})
这里第一个函数是开启notify服务,deviceId、serviceId、characteristicId都是之前我们获取的,第二个函数是将bufferArray类型转为string类型,因为buffer不能直接在console.log里输出,会显示null,第三个函数就是监听蓝牙发送过来的值了,蓝牙每次发送一个值,都会回调这个函数,res.value就是一个bufferArray类型,存的是发送过来的值

7.写数据到蓝牙


let buffer = new ArrayBuffer(3)
let dataView = new DataView(buffer)
dataView.setUint8(1, 100)

wx.writeBLECharacteristicValue({
deviceId: deviceId,
serviceId: serviceId[1],
characteristicId: characteristicId[0],
value: buffer,
success: function (res) {
console.log('writeBLECharacteristicValue success', res.errMsg)
}
})
传数据给蓝牙时只能用buffer类型,let buffer = new ArrayBuffer(3)这句话定义一个三个长度的buffer,dataView.setUint8(1, 100)这句话将第一个值设置为100,所以传递过去的值就是00 64 00 (十六进制)


附录(直接复制粘贴就能运行)

JS源码:


var app = getApp();
var deviceId;
var i=0;
var serviceId=[];
var characteristicId=[];
Page({
data: {

},
onLoad:function(){
wx.onBluetoothAdapterStateChange(function (res) {
console.log('adapterState changed, now is', res)
})

},

openadapter:function(){
wx.openBluetoothAdapter({
success: function(res) {
console.log(res,"success")
},
fail: function (res) {
console.log(res,"fail")
},
})
// wx.getBluetoothAdapterState({
// complete: function (res) {
// console.log("currentstate:",res)
// }
// })
},
closeadapter: function () {
wx.closeBluetoothAdapter({
success: function (res) {
console.log(res, "success")
},
fail: function (res) {
console.log(res, "fail")
},
})
// wx.getBluetoothAdapterState({
// complete: function (res) {
// console.log("currentstate:", res)
// }
// })
},

opendiscovery:function(){
wx.startBluetoothDevicesDiscovery({
services: [],
success: function (res) {
console.log(res)
},
fail: function (res) {
console.log(res, "fail")
},
})
},

closediscovery:function(){
wx.stopBluetoothDevicesDiscovery({
success: function (res) {
console.log(res)
},
fail: function (res) {
console.log(res, "fail")
},
})
},

getdevice:function(){
function ab2hex(buffer) {
var hexArr = Array.prototype.map.call(
new Uint8Array(buffer),
function (bit) {
return ('00' + bit.toString(16)).slice(-2)
}
)
return hexArr.join('');
}
wx.getBluetoothDevices({
success: function (res) {
console.log(res)
i=0;
while (res.devices[i]) {
console.log(i);
console.log(res.devices[i].name,res.devices[i].deviceId);
if(res.devices[i].name=='YahBoom_BL'){
deviceId=res.devices[i].deviceId;
console.log(deviceId);
}
i++;
}
}
})
},

getconnecteddevice:function(){
wx.getConnectedBluetoothDevices({
//services:[],
success: function (res) {
console.log(res)
}
})
},
connecteddevice:function(){
wx.createBLEConnection({
deviceId: deviceId,
success: function(res) {
console.log(res);
},
})
},
getservice:function(){
wx.getBLEDeviceServices({
deviceId: deviceId,
success: function(res) {
console.log(res.services);
i=0;
while(res.services[i]){
serviceId[i]=res.services[i].uuid;
console.log(serviceId[i]);
i++;
}
},
})
},
getcharacteristics:function(){
wx.getBLEDeviceCharacteristics({
deviceId: deviceId,
serviceId: serviceId[0],
success: function (res) {
console.log('device getBLEDeviceCharacteristics:', res.characteristics)
}
})
wx.getBLEDeviceCharacteristics({
deviceId: deviceId,
serviceId: serviceId[1],
success: function (res) {
i=0;
while(res.characteristics[i]){
characteristicId[i]=res.characteristics[i].uuid;
console.log(characteristicId[i]);
i++;
}
}
})
},
startread:function(){
wx.readBLECharacteristicValue({
deviceId: deviceId,
serviceId: serviceId[1],
characteristicId: characteristicId[0],
success: function (res) {
console.log('readBLECharacteristicValue:', res.errCode)
}
})
},
startnotify:function(){
wx.notifyBLECharacteristicValueChange({
state: true,
deviceId: deviceId,
serviceId: serviceId[1],
characteristicId: characteristicId[0],
success: function (res) {
console.log('notifyBLECharacteristicValueChange success', res.errMsg)
}
})
function ab2hex(buffer) {
var hexArr = Array.prototype.map.call(
new Uint8Array(buffer),
function(bit) {
return ('00' + bit.toString(16)).slice(-2)
}
)
return hexArr.join('');
}
wx.onBLECharacteristicValueChange(function (res) {
console.log('characteristic value comed:', ab2hex(res.value))
})
},
startwrite:function(){
let buffer = new ArrayBuffer(3)
let dataView = new DataView(buffer)
dataView.setUint8(1, 100)

wx.writeBLECharacteristicValue({
deviceId: deviceId,
serviceId: serviceId[1],
characteristicId: characteristicId[0],
value: buffer,
success: function (res) {
console.log('writeBLECharacteristicValue success', res.errMsg)
}
})
}

 

})


WXML源码:


<button bindtap='openadapter'>打开适配器</button>
<button bindtap='closeadapter'>关闭适配器</button>
<button bindtap='opendiscovery'>开始搜索</button>
<button bindtap='closediscovery'>关闭搜索</button>
<button bindtap='getdevice'>获取设备</button>
<button bindtap='getconnecteddevice'>获取已连接设备</button>
<button bindtap='connecteddevice'>连接我的设备</button>
<button bindtap='getservice'>获取服务</button>
<button bindtap='getcharacteristics'>获取特征值</button>
<button bindtap='startread'>读取值</button>
<button bindtap='startnotify'>开启notify</button>
<button bindtap='startwrite'>写数据</button>

 

posted @ 2019-03-08 14:57 BigBaHuang 阅读(...) 评论(...) 编辑 收藏