1、初始化藍牙
不管是ios操作系統(tǒng)還是安卓操作系統(tǒng),第一步都需要初始化藍牙文章來源:http://www.zghlxwxcb.cn/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、獲取藍牙適配器狀態(tài)
// 獲取本機藍牙適配器狀態(tài)
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和安卓的操作系統(tǒng)對藍牙的連接方式不同
- 安卓是直接對設備的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是根據(jù)設備發(fā)送藍牙廣播的時間頻率有關,很重要
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++) {
// 這里需要根據(jù)設備提供的服務進行判斷,比如(讀寫服務)
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、向藍牙寫入數(shù)據(jù)
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.分辨系統(tǒng)
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 => {
// 連接成功后藍牙監(jiān)聽
wx.onBLEConnectionStateChange(function (res) {
// 該方法回調中可以用于處理連接意外斷開等異常情況
if (!res.connected) {
console.log('藍牙已經(jīng)斷開----')
that.setData({
disabled: true, // 支付按鈕置灰
})
}
})
// 獲取藍牙服務,并且開啟notify
getBLEDeviceServices(deviceid).then(openBleNotify).then(ids => {
// 這里可以向設備寫一些數(shù)據(jù)進去連接確認
// 模擬成功后寫入特征值后設備返回的數(shù)據(jù)
wx.onBLECharacteristicValueChange(function(res) {
console.log(res, '返回的arrayBuffer')
})
resolve()
})
}).catch((err) => { // 重開
// 當連接時間超過timeout以后需要重新進行連接,藍牙優(yōu)化
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)
})
})
},
如果還有不懂的可以私信我哦~文章來源地址http://www.zghlxwxcb.cn/news/detail-557740.html
到了這里,關于微信小程序之藍牙連接全過程封裝的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!