微信小程序之藍牙開發(詳細讀數據、寫數據、附源碼)


本文將詳細介紹微信小程序的藍牙開發流程(附源碼)
准備:
微信只支持低功耗藍牙也就是藍牙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>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM