1、初始化蓝牙
不管是ios操作系统还是安卓操作系统,第一步都需要初始化蓝牙文章来源:https://www.toymoban.com/news/detail-557740.html
// 蓝牙设备初始化
export function openBluetoothAdapter () {
return new Promise((resolve, reject) => {
wx.openBluetoothAdapter({
success: function (res) {
console.log(res, '蓝牙初始化成功')
resolve()
},
fail: function () {
wx.showToast({
title: '请打开蓝牙',
icon: "success",
duration: 2000
})
setTimeout(function () {
wx.hideToast()
}, 2000)
}
})
})
}
2、获取蓝牙适配器状态
// 获取本机蓝牙适配器状态
export function getBleAdapterState () {
return new Promise((resolve, reject) => {
wx.getBluetoothAdapterState({
success: function(res) {
let available = res.available
if (!available) {
wx.showToast({
title: '设备无法开启蓝牙连接',
icon: 'success',
duration: 2000
})
setTimeout(function() {
wx.hideToast()
}, 2000)
} else {
resolve()
}
}
})
})
}
3、ios和安卓的操作系统对蓝牙的连接方式不同
- 安卓是直接对设备的macAddress进行连接
- ios需要对周边的蓝牙设备就行搜索:
export function startBluetoothDevicesDiscovery () {
return new Promise((resolve, reject) =>{
wx.startBluetoothDevicesDiscovery({
services: [],
success: function () {
console.log('开始搜索蓝牙')
wx.onBluetoothDeviceFound(function (res) {
console.log(res, '搜索蓝牙相关设备')
for (let i = 0; i < res.devices.length; i++) {
// app.globalData.bleConfig.name 这里提前就获取了设备的name
if (res.devices[i].localName == app.globalData.bleConfig.name) {
var deviceId = res.devices[i].deviceId
// 将设备的deviceId存在globalData里面
app.globalData.bleConfig.deviceId = deviceId
// ios搜索出目标设备后,将停止搜索,否则影响手机性能
wx.stopBluetoothDevicesDiscovery({
success: function() {
}
})
resolve()
}
}
})
},
})
})
}
4、蓝牙连接
export function createBleConnection (deviceId) {
return new Promise((resolve, reject) => {
wx.createBLEConnection({
// 这个连接时间timeout是根据设备发送蓝牙广播的时间频率有关,很重要
timeout: 5000,
deviceId: deviceId,
success: function (res) {
// 连接成功后返回deviceId,供后面获取蓝牙服务需要
resolve(deviceId)
},
fail: function (err) {
reject(err)
}
})
})
}
5、获取蓝牙多个service
export function getBLEDeviceServices (deviceId) {
return new Promise((resolve, reject) => {
wx.getBLEDeviceServices({
deviceId: deviceId,
success: function (res) {
for (var i = 0; i <= res.services.length - 1; i++) {
// 这里需要根据设备提供的服务进行判断,比如(读写服务)
if (res.services[i].uuid.indexOf("B5A3") >= 0) {
let serviceId = res.services[i].uuid
// 将serviceId 存在globalData
app.globalData.bleConfig.serviceId = serviceId
resolve({serviceId, deviceId})
}
}
}
})
})
}
6、开启notify
export function openBleNotify (ids) {
return new Promise((resolve, reject) => {
wx.getBLEDeviceCharacteristics({
deviceId: ids.deviceId,
serviceId: ids.serviceId,
success: function (res) {
let FF3 = res.characteristics[0].uuid //notify支持
let characteristicId = res.characteristics[1].uuid //可以写 可以读
app.globalData.bleConfig.FF3 = FF3
app.globalData.bleConfig.characteristicId = characteristicId
wx.notifyBLECharacteristicValueChanged({
deviceId: ids.deviceId,
serviceId: ids.serviceId,
characteristicId: FF3,
state: true,
success: function (res) {
console.log("notify成功")
resolve({...ids, ...{characteristicId}})
}
})
},
fail: function (res) {
}
})
})
}
7、向蓝牙写入数据
export function writeBleValue (bleData) {
return new Promise((resolve, reject) => {
wx.writeBLECharacteristicValue({
deviceId: bleData.deviceId,
serviceId: bleData.serviceId,
characteristicId: bleData.characteristicId,
// 写入arrayBuffer
value: bleData.buffer,
success: function (res) {
resolve()
},
fail: function (err) {
console.log(err)
}
})
})
}
最后
onLoad(options) {
this.bleConnect()
},
// 蓝牙连接
bleConnect () {
// 1.分辨系统
getSystemInfo().then(res => {
if (res === 'ios') {
openBluetoothAdapter().then(getBleAdapterState).then(startBluetoothDevicesDiscovery)
.then(() =>{
this.bleConnectSuccess()
})
} else {
openBluetoothAdapter().then(getBleAdapterState).then(() =>{
this.bleConnectSuccess()
})
}
})
},
bleConnectSuccess () {
let that = this
let deviceId = app.globalData.bleConfig.deviceId
new Promise((resolve, reject) => {
createBleConnection(deviceId).then(deviceid => {
// 连接成功后蓝牙监听
wx.onBLEConnectionStateChange(function (res) {
// 该方法回调中可以用于处理连接意外断开等异常情况
if (!res.connected) {
console.log('蓝牙已经断开----')
that.setData({
disabled: true, // 支付按钮置灰
})
}
})
// 获取蓝牙服务,并且开启notify
getBLEDeviceServices(deviceid).then(openBleNotify).then(ids => {
// 这里可以向设备写一些数据进去连接确认
// 模拟成功后写入特征值后设备返回的数据
wx.onBLECharacteristicValueChange(function(res) {
console.log(res, '返回的arrayBuffer')
})
resolve()
})
}).catch((err) => { // 重开
// 当连接时间超过timeout以后需要重新进行连接,蓝牙优化
that.data.connecttimes++
that.setData({
connecttimes: that.data.connecttimes
})
if (that.data.connecttimes === 5) {
wx.showModal({
title: '提示',
content: '请检查设备是否断电和手机蓝牙再进行连接',
showCancel: false,
success: function (res) {
if (res.confirm) {
wx.reLaunch({
url: '../index/index',
})
}
}
})
return false
}
that.bleConnectSuccess(app.globalData.bleConfig.deviceId)
})
})
},
如果还有不懂的可以私信我哦~文章来源地址https://www.toymoban.com/news/detail-557740.html
到了这里,关于微信小程序之蓝牙连接全过程封装的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!