微信小程序實現藍牙BLE
步驟:
1、wx.openBluetoothAdapter//藍牙初始化
2、 wx.onBluetoothDeviceFound //監聽尋找到新設備的事件
3、 wx.startBluetoothDevicesDiscovery //開始搜尋附近的藍牙外圍設備
4、 wx.getBluetoothDevices//獲取在藍牙模塊生效期間所有已發現的藍牙設備。包括已經和本機處於連接狀態的設備。
5、wx.stopBluetoothDevicesDiscovery//停止搜尋附近的藍牙外圍設備。搜索到需要設備時或者連接時候停止搜索
6、wx.createBLEConnection //連接設備
7、 wx.getBLEDeviceServices //獲取所有服務列表
8、wx.getBLEDeviceCharacteristics//獲取藍牙設備某個服務中的所有特徵值
9、wx.onBLEConnectionStateChange //監聽設備連接狀態(本人用小米2手環測試經常斷)
10、 wx.notifyBLECharacteristicValueChange // 啓用低功耗藍牙設備特徵值變化是的notify功能
11、 wx.onBLECharacteristicValueChange//開始監聽特徵值的變化
12、 wx.writeBLECharacteristicValue//寫入特徵值
13、wx.readBLECharacteristicValue//讀取特徵值
以下是demo代碼:
onLoad: function (options) {
var that=this
//藍牙初始化
wx.openBluetoothAdapter({
success: function(res) {
console.log(res)
//監聽尋找到新設備的事件
wx.onBluetoothDeviceFound(function (res) {
// console.log(res)
})
},
fail:function(res){
wx.showModal({
title: '提示',
content: '請檢查手機藍牙是否打開',
})
}
})
},
點擊搜索設備按鈕(lanya):
lanya: function () {
wx.showLoading({
title: '搜索中',
})
setTimeout(function(){
wx.hideLoading()
},1500)
//開始搜尋附近的藍牙外圍設備
wx.startBluetoothDevicesDiscovery({
success: function (res) {
console.log('搜索完成')
//獲取在藍牙模塊生效期間所有已發現的藍牙設備。包括已經和本機處於連接狀態的設備。
wx.getBluetoothDevices({
success: function (res) {
if(res.devices.length==0){
wx.showModal({
title: '提示',
content: '沒有搜索到設備,請重試',
})
wx.navigateTo({
url: '../index/index',
})
}
console.log(res)
//console.log(res.devices[0].deviceId)
// console.log(res.devices[0].name)
console.log(res.devices)
var data=res.devices
wx.navigateTo({
url: '../lanya/lanya?data=' + JSON.stringify(data),
})
//停止搜尋附近的藍牙外圍設備。若已經找到需要的藍牙設備並不需要繼續搜索時,建議調用該接口停止藍牙搜索。
// wx.stopBluetoothDevicesDiscovery({
// success: function(res) {
// console.log('已經停止搜索')
// },
// })
},
fail:function(res){
console.log('沒有找到設備')
}
})
},
fail: function (fa) {
console.log(fa)
}
})
},
onLoad: function (options) {
var Id=[]
var Name=[]
var data = JSON.parse(options.data)
console.log(data)
var that=this
console.log(data)
that.setData({
array:data
})
},
點擊連接設備按鈕:
sub:function(e){
var deviceId = e.currentTarget.id
app.globalData.deviceId=deviceId
console.log(e.currentTarget.id)
//連接設備
wx.createBLEConnection({
deviceId:deviceId,
success: function(res) {
console.log(res)
//獲取服務列表
wx.navigateTo({
url: '../res/res?id='+deviceId,
})
console.log('id:' + deviceId)
},
fail:function(res){
wx.showModal({
title: '提示',
content: '連接超時,請重試',
})
// console.log('id:' + deviceId)
console.log(res)
}
})
},
onLoad: function (options) {
var deviceId=options.id
var that=this
//獲取所有服務
wx.getBLEDeviceServices({
deviceId: deviceId,
success: function (res) {
// console.log(res)
console.log(res.services)
that.setData({
array:res.services
})
},
})
},
進入某個服務
sub:function(e){
var that = this
var serviceId=e.target.id
//獲取藍牙設備某個服務中的所有特徵值
wx.getBLEDeviceCharacteristics({
deviceId:app.globalData.deviceId,
serviceId:serviceId,
success: function(res) {
console.log(res)
that.data.characteristics=res.characteristics//獲取characteristic
wx.navigateTo({
url: '../notify/notify?ct=' + JSON.stringify(that.data.characteristics) + '&serviceId=' + serviceId,
})
},
fail:function(res){
console.log(res)
}
})
//監聽設備連接狀態
wx.onBLEConnectionStateChange(function (res) {
console.log(res)
if (res.connected == false) {
wx.showModal({
title: '提示',
content: '設備連接已斷開',
})
}
})
},
onLoad: function (options) {
var ct = JSON.parse(options.ct)
serviceId=options.serviceId
var that=this
that.setData({
array:ct,
serviceId:serviceId,
})
},
進入某個特徵值
sub:function(e){
var that = this
var cht = e.target.id
var deviceId = app.globalData.deviceId
// 啓用低功耗藍牙設備特徵值變化是的notify功能
wx.notifyBLECharacteristicValueChange({
deviceId: deviceId,
serviceId: serviceId,
characteristicId: cht,
state: true,
success: function (res) {
//開始監聽
wx.onBLECharacteristicValueChange(function (characteristics) {
console.log(characteristics.value)
var a = characteristics.value
var int8array = new Int8Array(a);
console.log("監聽到特徵值更新:" + int8array[0])
// var hex = ab2str(a);
// console.log("返回的值: ".hex)
})
console.log(res)
wx.navigateTo({
url: '../write/write?cht=' + cht + '&serviceId=' + serviceId + '&deviceId=' + deviceId,
})
},
fail:function(res){
console.log(res)
},
})
},
**```
onLoad: function (options) {
var that=this
var cht = options.cht
var deviceId=options.deviceId
var serviceId = options.serviceId
that.setData({
deviceId:deviceId,
cht:cht,
serviceId:serviceId
})
},
向該特徵值寫入數據:**
formSubmit:function(e){
var that = this
var value=e.detail.value.psw
console.log(value)
//寫入數據
wx.writeBLECharacteristicValue({
deviceId: that.data.deviceId,
serviceId: that.data.serviceId,
characteristicId: that.data.cht,
value: that.str2ab(value),
success: function (res) {
console.log(res)
},
fail:function(res){
console.log(res)
}
});
wx.readBLECharacteristicValue({
deviceId: that.data.deviceId,
serviceId: that.data.serviceId,
characteristicId: that.data.cht,
success: function(e) {
console.log(e)
},
})
},
重點寫入的字符串要轉換成Arraybuffer
// 字符串轉爲ArrayBuffer對象,參數爲字符串
str2ab: function(str) {
var buf = new ArrayBuffer(str.length * 2); // 每個字符佔用2個字節
var bufView = new Uint16Array(buf);
for(var i = 0, strLen=str.length; i<strLen; i++) {
bufView[i] = str.charCodeAt(i);
}
return buf;
},
**監聽的特徵值變化回調是ArrayBuffer也要轉換爲字符串,可是我直接寫下標就能獲取,寫轉換獲得就是undefined
function ab2str(arrayBuffer) {
return String.fromCharCode.apply(null, new Uint8Array(arrayBuffer));
// let unit8Arr = new Uint8Array(arrayBuffer);
// let encodedString = String.fromCharCode.apply(null, unit8Arr),
// decodedString = decodeURIComponent(escape((encodedString)));//沒有這一步中文會亂碼
// return decodedString;
}