小程序藍牙低功耗藍牙主要有以下幾個步驟以及會用到的接口:
- 打開適配器(openBluetoothAdapter)
- 監聽藍牙適配器狀態變化(onBluetoothAdapterStateChange)
- 搜索藍牙(startBluetoothDevicesDiscovery)
- 尋找到藍牙新設備(onBluetoothDeviceFound)
- 連接藍牙(createBLEConnection)
- 停止搜索搜索藍牙(stopBluetoothDevicesDiscovery)
- 監聽藍牙連接狀態(onBLEConnectionStateChange)
- 獲取藍牙設備所有服務(getBLEDeviceServices)
- 獲取藍牙設備某個服務中所有特徵值(getBLEDeviceCharacteristics)
- 開啓notify(notifyBLECharacteristicValueChange)
- 監聽低功耗藍牙設備的特徵值變化(onBLECharacteristicValueChange)
- 藍牙設備特徵值中寫入二進制數據(writeBLECharacteristicValue)
- 斷開藍牙(closeBLEConnection)
- 關閉藍牙模塊(closeBluetoothAdapter)
1.打開適配器
這是官方關於打開適配器的文檔 點擊這裏
詳細步驟:先判斷當前微信版本是否支持打開適配器,過程需監聽適配器的狀態,打開適配器後再去判斷手機藍牙是否打開,手機藍牙也打開後,去搜索藍牙設備
代碼如下:
openBluetoothAdapterBefore: function() {
var that = this;
if (!wx.openBluetoothAdapter) {
wx.showModal({
title: '提示',
showCancel: false,
content: '當前微信版本過低,無法使用該功能,請升級到最新微信版本後重試。',
})
return;
}
// 初始化小程序藍牙模塊
wx.openBluetoothAdapter({
success: (res) => {
console.log('openBluetoothAdapter success', res)
that.startBluetoothDevicesDiscovery() //搜索藍牙
},
fail: (res) => {
if (res.errCode === 10001) {
wx.showToast({
title: '請開啓手機藍牙',
duration: 5000
})
// 監聽藍牙適配器狀態變化事件
wx.onBluetoothAdapterStateChange(function(res) {
console.log('onBluetoothAdapterStateChange', res)
if (res.available) {
that.startBluetoothDevicesDiscovery() //搜索藍牙
}
})
}
}
})
}
2.監聽藍牙適配器狀態變化
這是官方的監聽藍牙適配器接口文檔 點擊這裏
詳細介紹:在打開適配器後,會出現手機藍牙未打開的情況,這時就需要去監聽適配器的狀態變化,以便於手機藍牙打開後,去搜索藍牙
wx.onBluetoothAdapterStateChange(function(res) {
console.log('onBluetoothAdapterStateChange', res)
if (res.available) {
that.startBluetoothDevicesDiscovery()
}
})
3. 搜索藍牙
這是官方的搜索藍牙接口文檔 點擊這裏
/**開始搜尋附近的藍牙外圍設備 */
startBluetoothDevicesDiscovery: function() {
var that = this;
wx.startBluetoothDevicesDiscovery({
// services: ['FEE7'],
allowDuplicatesKey: false,//不允許重複上報同一設備
success: (res) => {
console.log('startBluetoothDevicesDiscovery success', res)
wx.showLoading({
title: '搜索藍牙...',
})
that.onBluetoothDeviceFound() //連接藍牙
},
})
}
4.尋找到藍牙新設備
這是官方的找藍牙新設備的接口文檔 點擊這裏
注意:若使用該接口找不到之前已經連接過的藍牙設備,可以用這個【getBluetoothDevices】接口,找到已經添加過的藍牙設備去連接
function inArray(arr, key, val) {
for (let i = 0; i < arr.length; i++) {
if (arr[i][key] === val) {
return i
}
}
return -1
}
/** 監聽尋找到新設備的事件 */
onBluetoothDeviceFound: function() {
var that = this;
var devices = data.devices;
var item = [];
console.log("監聽尋找到新設備:",devices)
wx.onBluetoothDeviceFound((res) => {
res.devices.forEach(device => {
if (!device.name && !device.localName) {
return
}
const foundDevices = devices
const idx = inArray(foundDevices, 'deviceId', device.deviceId)
const data = {}
if (idx === -1) {
//這裏可以寫連接此設備的藍牙設備的條件
that.connectBle(devices.deviceId)
} else {
data[`devices[${idx}]`] = device
let ballType = device.localName.substring(0, 1);
}
})
})
}
尋找已經添加的藍牙設備
/** 監聽尋找到已添加的藍牙設備*/
onBleDeviceFound: function() {
var that = this;
wx.getBluetoothDevices({
success: function(res) {
console.log("尋找設備成功:", res)
let devices = res.devices
for (let i = 0; i < devices.length; i++) {
//這裏可以寫連接此設備的藍牙設備的條件
that.connectBle(devices[i].deviceId)
},
fail: function(res) {
console.log("搜索藍牙設備失敗", res)
}
});
},
5.連接藍牙
這是官方連接藍牙接口 點擊這裏
/**連接低功耗藍牙設備 */
connectBle: function(deviceId) {
var that = this;
const name = that.data.deviceName
wx.showLoading({
title: '連接中'
})
wx.createBLEConnection({
deviceId,
timeout: 5000, //設置超時時間
success: function(res) {
wx.showLoading({
title: '連接成功',
icon: 'success',
})
console.log("連接藍牙成功", res)
that.setData({
name,
deviceId,
btnName: "已連接",
})
that.onBleConnectState(); //監聽藍牙連接狀態
that.getBLEDeviceServices(deviceId); //獲取藍牙設備所有 service(服務)
},
fail: function(res) {
console.log("連接失敗", res);
if (res.errCode === 10003) { //連接失敗,有可能是藍牙強度比較低
that.onBleDeviceFound() //獲取已經添加的藍牙設備
} else if (res.errCode === 10012) { //連接過程,低功耗藍牙設備已關閉
wx.showLoading({
title: '請打開藍牙設備'
})
that.onBleDeviceFound() //獲取已經添加的藍牙設備
}
},
complete() {
setTimeout(function() { //延遲兩秒執行,
wx.hideLoading()
}, 2000)
}
})
},
6.停止搜索搜索藍牙
這裏是官方停止搜索藍牙的文檔 點擊這裏
代碼:
/**停止搜尋附近的藍牙外圍設備 */
stopBluetoothDevicesDiscovery: function() {
wx.stopBluetoothDevicesDiscovery({
success:(res)=>{
console.log("停止搜索藍牙成功:",res)
},
fail:(res)=>{
console.log("停止搜索藍牙失敗:",res)
}
})
},
7.監聽藍牙連接狀態
官方的監聽藍牙連接狀態接口文檔 點擊這裏
代碼:
/**@description 監聽藍牙連接狀態 */
onBleConnectState: function() {
let that = this;
wx.onBLEConnectionStateChange(function(res) {
console.log("藍牙連接狀態:", res.connected);
if (!res.connected) {
that.onBleDeviceFound; //自動連接
}
})
},
8. 獲取藍牙設備所有服務
官方獲取藍牙設備所有服務接口文檔 點擊這裏
代碼:
/**獲取藍牙設備所有 service(服務) */
getBLEDeviceServices: function(deviceId) {
var that = this;
wx.getBLEDeviceServices({
deviceId,
success: (res) => {
console.log("獲取藍牙設備所有服務成功", res)
for (let i = 0; i < res.services.length; i++) {
let uuid_slice = res.services[i].uuid.slice(4, 8);
if (uuid_slice != "180A" && uuid_slice != "1800" && uuid_slice != "1801" && uuid_slice != "1802") {
if (res.services[i].isPrimary) {
console.log("serviceId:" + res.services[i].uuid)
that.getBLEDeviceCharacteristics(deviceId, res.services[i].uuid)
return
}
}
}
},
fail:(res)=>{
console.log("獲取藍牙設備所有服務失敗:",res)
}
})
},
9. 獲取藍牙設備某個服務中所有特徵值
官方獲取特徵值的接口文檔 點擊這裏
詳細介紹:分別獲取對藍牙進行讀、寫、notify的特徵值,便於接下來對藍牙進行讀、寫操作
代碼:
/**藍牙設備characteristic(特徵值)信息 */
getBLEDeviceCharacteristics: function(deviceId, serviceId) {
var that = this;
wx.getBLEDeviceCharacteristics({
deviceId,
serviceId,
success: (res) => {
console.log('getBLEDeviceCharacteristics success', res.characteristics)
for (let i = 0; i < res.characteristics.length; i++) {
const item = res.characteristics[i]
//讀
if (item.properties.read) {
wx.readBLECharacteristicValue({
deviceId,
serviceId,
characteristicId: item.uuid,
})
}
//寫
if (item.properties.write) {
if (item.uuid === '6E400002-B5A3-F393-E0A9-E50E24DCCA9E') {
that.setData({
deviceId: deviceId,
serviceId: serviceId,
writeCharacteristicId: item.uuid,
});
}
}
//notify
if (item.properties.notify || item.properties.indicate) {
that.setData({
deviceId: deviceId,
serviceId: serviceId,
characteristicId: item.uuid
})
that.openNotify()
}
}
},
fail(res) {
console.error('getBLEDeviceCharacteristics', res)
}
})
},
10. 開啓notify
官方開啓notify的接口文檔 點擊這裏
代碼:
/** 開啓notify */
openNotify: function() {
var that = this;
wx.notifyBLECharacteristicValueChange({
deviceId: that.data.deviceId,
serviceId: that.data.serviceId,
characteristicId: that.data.characteristicId,
state: true,
success: function(res) {
that.onBLECharacteristicValueChange(); //監聽返回值變化
// 寫入數據 (同步數據)
that.writeData(0xa0, timestamp);
},
fail: function(res) {
console.log("開啓notify失敗", res);
}
})
},
11. 監聽低功耗藍牙設備的特徵值變化
官方的監聽藍牙設備特徵值的接口文檔 點擊這裏
代碼:
/** 監聽返回值變化 */
onBLECharacteristicValueChange: function() {
var that = this;
wx.onBLECharacteristicValueChange(function(res) {
//對數據進行操作
})
},
12. 藍牙設備特徵值中寫入二進制數據
官方寫入數據的接口文檔 點擊這裏
詳細介紹:
代碼:
/** 寫入二進制數據*/
writeData: function(cmd, values) {
// 向藍牙設備發送一個0x00的16進制數據
let buffer = new ArrayBuffer(16)
let dataView = new DataView(buffer)
dataView.setUint8(0, cmd) //命令
dataView.setUint32(1, values) //向藍牙發送命令參數
wx.writeBLECharacteristicValue({
deviceId: that.data.deviceId,
serviceId: that.data.serviceId,
characteristicId: that.data.writeCharacteristicId,
value: buffer,
success: function(res) {
console.log('寫入藍牙特徵值成功:', res.errMsg);
},
fail: function(res) {
console.log('寫入藍牙特徵值失敗:', res.errMsg);
},
})
},
13. 斷開藍牙
官方打開藍牙接口文檔 點擊這裏
詳細介紹:斷開藍牙一般用在主動斷開藍牙
代碼:
/**斷開與低功耗藍牙設備的連接 */
closeBLEConnection: function() {
wx.closeBLEConnection({
success: function(res) {
console.log("斷開藍牙成功", res)
},
fail: function(res) {
console.log("斷開藍牙失敗", res)
}
})
},
14. 關閉藍牙模塊
官方關閉藍牙模塊的接口文檔 點擊這裏
詳細介紹:一般退出當前連接藍牙頁面時,就可關閉藍牙模塊
代碼:
/**關閉藍牙模塊,使其進入未初始化狀態 */
closeBluetoothAdapter: function() {
wx.closeBluetoothAdapter({
success: (res) => {
console.log("關閉適配器成功:", res)
},
fail: (res) => {
console.log("關閉適配器失敗:", res)
}
})
},
以上即 微信小程序藍牙連接過程。。