一、小程序蓝牙连接api文档地址
https://developers.weixin.qq.com/miniprogram/dev/api/
二、蓝牙设备ID、服务ID、特征值ID解释
蓝牙有一个唯一的设备ID,这个设备ID下面有多个服务ID,每个服务ID下面有多个特征值ID,每个特征值ID有相应的读、写、监听等权限。
文章来源:https://www.toymoban.com/news/detail-518556.html
小程序和蓝牙连接进行通信,主要是1给蓝牙发送数据 2接收蓝牙发过来的数据,调用了那么多的小程序api,就是为了获取有发送权限write,接收权限notify的特征值ID
文章来源地址https://www.toymoban.com/news/detail-518556.html
三、蓝牙连接步骤说明
流程 | 对应代码方法 | 执行的操作 |
---|---|---|
1 | getUserSetting | 检测蓝牙是否授权 |
2 | initBlue | 初始化蓝牙设备 |
3 | findBlue | 开始搜索蓝牙设备 |
4 | getBlue | 获取搜索到的设备ID |
5 | connetBlue | 连接蓝牙设备、关闭蓝牙搜索(省电)、监听蓝牙设备(断开后自动重连) |
6 | getServiceId | 获取蓝牙服务ID |
7 | getCharacteId | 获取蓝牙特征值ID |
8 | startNotice | 开始监听蓝牙数据 |
9 | sendOrder | 给蓝牙发送数据 |
10 | onLoad | 接收蓝牙数据执行业务逻辑 |
11 | onUnload | 离开页面断开蓝牙连接、取消蓝牙监听(省电) |
四、小程序源代码
/**获取已授权列表*/
getUserSetting() {
console.log("获取已授权列表")
var that = this;
wx.getSetting({
success(res) {
var authSetting = res.authSetting
console.log(res.authSetting)
if (!res.authSetting['scope.bluetooth']) {
//授权获取蓝牙权限
wx.authorize({
scope: 'scope.bluetooth',
success() {
console.log("成功获取蓝牙权限")
that.initBlue()
},
fail() {
console.log("蓝牙权限获取失败")
}
})
} else {
that.initBlue()
}
},
fail(f) {
console.log(f)
}
})
},
/**初始化蓝牙设备*/
initBlue() {
console.log("初始化蓝牙")
var that = this;
wx.openBluetoothAdapter({
success: function (res) {
that.findBlue()
},
fail: function (res) {
console.log("e", "请开启蓝牙定位")
}
})
},
/**开始搜索蓝牙设备*/
findBlue() {
var that = this
wx.startBluetoothDevicesDiscovery({
allowDuplicatesKey: true,
interval: 0,
powerLevel: 'high',
success: function (res) {
console.log("开始搜索蓝牙设备", res)
//加个延时,避免获取数据为空
setTimeout(() => {
that.getBlue()
}, 300)
}
})
},
/**获取搜索到的设备信息*/
getBlue() {
var that = this
wx.getBluetoothDevices({
success: function (res) {
var blueToothList = []
for (var i = 0; i < res.devices.length; i++) {
if (res.devices[i].name != "未知设备") {
console.log("遍历已知蓝牙设备" + i, res.devices[i].deviceId, res.devices[i].name, res.devices[i].RSSI)
}
}
},
fail: function () {
console.log("搜索蓝牙设备失败")
}
})
},
/**获取到设备之后连接蓝牙设备*/
connetBlue() {
setTimeout(() => {
//getBlue里面获取的deviceId
var deviceId = this.data.deviceId
var that = this;
wx.createBLEConnection({
deviceId: deviceId,//设备id
success: function (res) {
console.log("连接蓝牙成功!")
wx.stopBluetoothDevicesDiscovery({
success: function () {
console.log('连接蓝牙成功之后关闭蓝牙搜索,避免耗电');
}
})
//获取蓝牙服务ID
that.getServiceId()
//连接成功,开始监听蓝牙连接状态,断开后重连
that.onStateChange()
},
fail: function (f) {
}
})
}, 200)
},
/**开始监听蓝牙连接状态*/
onStateChange() {
wx.onBLEConnectionStateChange(this.stateChangeFun)
},
/**蓝牙状态监听方法*/
stateChangeFun(res) {
// 该方法回调中可以用于处理连接意外断开等异常情况
var connectStatus = res.connected
if (connectStatus == false) {
console.log('蓝牙断开重连', `device ${res.deviceId} state has changed, connected: ${res.connected}`)
this.reconnectBlue()
}
},
/**蓝牙重连*/
reconnectBlue() {
var deviceId = this.data.deviceId
var that = this;
wx.createBLEConnection({
deviceId: deviceId,
success() {
console.log("蓝牙重连成功!")
},
fail() {
that.reconnectBlue()
}
})
},
/**蓝牙设备的服务uuid*/
getServiceId() {
var that = this
wx.getBLEDeviceServices({
deviceId: that.data.deviceId,
success: function (res) {
console.log("蓝牙服务信息", res)
//[0]这个服务ID下面的特征值ID有notify和write为true的,每个设备不一样,根据你的设备来,可能是[0]也可能是[1]或者其他的
var model = res.services[0]
that.setData({
servicesId: model.uuid,
})
that.getCharacteId()
}
})
},
/**查看蓝牙特征值*/
getCharacteId() {
var that = this
wx.getBLEDeviceCharacteristics({
deviceId: that.data.deviceId,
serviceId: that.data.servicesId,
success: function (res) {
console.log("蓝牙特征值", res)
var model = ""
for (var i = 0; i < res.characteristics.length; i++) {
model = res.characteristics[i]
//接收蓝牙发送过来的数据需要这个uuid
if (model.properties.notify == true) {
that.setData({ notifyId: model.uuid })
}
//给蓝牙发送数据需要这个uuid
if (model.properties.write == true) {
that.setData({ writeId: model.uuid })
}
}
that.startNotice(that.data.notifyId)
}
})
},
/**监听蓝牙数据*/
startNotice(uuid) {
var that = this;
wx.notifyBLECharacteristicValueChange({
state: true, // 启用 notify 功能
deviceId: that.data.deviceId,
serviceId: that.data.servicesId,
characteristicId: uuid,
success: function (res) {
},
fail: function (fail) {
console.log("蓝牙监听失败!")
}
})
},
/**发送数据*/
sendOrder(write) {
let buffer = this.string2buffer(write);
let pos = 0;
let bytes = buffer.byteLength;
var that = this
//因为微信小程序使用蓝牙发送数据限制20字节内的原因,需要对超过20字节的数据拆包进行发送
while (bytes > 0) {
let tmpBuffer;
if (bytes > 20) {
tmpBuffer = buffer.slice(pos, pos + 20);
pos += 20;
bytes -= 20;
} else {
tmpBuffer = buffer.slice(pos, pos + bytes);
pos += bytes;
bytes -= bytes;
}
wx.writeBLECharacteristicValue({
deviceId: that.data.deviceId,
serviceId: that.data.servicesId,
characteristicId: that.data.writeId,
value: tmpBuffer,
success: (res) => {
console.log("写入成功", res)
},
fail: (f) => {
console.log("写入失败")
}
})
}
},
/**将16进制转化为ArrayBuffer*/
string2buffer() {
return new Uint8Array(str.match(/[\da-f]{2}/gi).map(function (h) {
return parseInt(h, 16)
})).buffer
},
/**将ArrayBuffer转换成字符串*/
ab2hex() {
var hexArr = Array.prototype.map.call(
new Uint8Array(buffer),
function (bit) {
return ('00' + bit.toString(16)).slice(-2)
}
)
return hexArr.join('');
},
/**生命周期函数--监听页面加载*/
onLoad(options) {
wx.onBLECharacteristicValueChange(function (res) {
// 此时可以拿到蓝牙设备返回来的数据是一个ArrayBuffer类型数据,所以需要通过一个方法转换成字符串
var data = this.ab2hex(res.value)
//下面写你接收到数据之后的业务逻辑代码
})
},
/**生命周期函数--监听页面隐藏*/
onUnload() {
//关闭蓝牙连接状态监听、蓝牙连接,避免耗电
this.offStateChange()
this.closeBlue()
}
到了这里,关于小程序连接蓝牙(保证能用)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!