最近做的微信小程序要調用手機自帶的4.0藍牙發送、接收數據
4.0藍牙又叫BLE,整理了下,藍牙連接要經過如下步驟:
初始化藍牙
檢查藍牙是否初始化成功
開始搜索附近藍牙設備
顯示掃描得到的藍牙
選擇連接特定MAC地址的藍牙設備
連接成功后,獲取service ID
然后獲取characteristic ID
write/read data
*每個步驟對應的操作在js代碼中有注釋
我遇到的坑:一定要啟用notify功能,否則只能發送,無法接收數據!!!
index.json為空,只上傳了index.wxml,index.wxss,index.js三個文件,源碼如下
index.wxml
藍牙開關
{{searchingstatus?"搜索中":"搜索藍牙"}}
{{index}}:\n
設備名稱: {{item.name}}\n
MAC地址: {{item.deviceId}}
bindtap="connectTO"> {{deviceconnected?"已連接":"連接"}}
\n\n數據接收\n
{{receive_data}}\n
\n\n數據發送:
發送
清空
index.wxss
view {
display: inline-block;
}
.container {
padding: 0;
margin: 0;
align-items: flex-start;
}
.section {
display: inline-block;
width: 100%;
margin-top: 50rpx;
position: relative;
}
.connection {
margin-left: 90rpx;
}
.list {
margin-left: 20rpx;
}
.content {
margin-left: 100rpx;
padding: auto;
position: absolute;
top: 5rpx;
left: 10rpx;
}
.switch {
position: relative;
float: right;
margin-right: 100rpx;
}
button {
background: red\;
}
.list-item {
margin-top: 20rpx;
margin-bottom: 20rpx;
display: flex;
flex-direction: column;
box-sizing: border-box;
border: 1px dashed #000;
}
.list-item text {
margin-top: 10rpx;
}
.list-item button {
margin-right: 10rpx;
}
.deviceconnected{
background-color:sandybrown
}
.recieve{
width: 100%
}
.recieve_textarea{
width: 100%;
margin-top: 10dpx;
}
input{
display: block;
border: 1px dashed;
width: 200px;
}
index.js
var app = getApp()
var temp = []
var string_temp=""
var serviceId = "0000ffe0-0000-1000-8000-00805f9b34fb"
var characteristicId = "0000ffe1-0000-1000-8000-00805f9b34fb"
Page({
data: {
isbluetoothready: false,
defaultSize: 'default',
primarySize: 'default',
warnSize: 'default',
disabled: false,
plain: false,
loading: false,
searchingstatus: false,
receivedata: '666',
onreceiving: false,
id_text: string_temp,
list: [],
receive_data:'none '
},
onLoad: function () {
},
open_BLE: function () {
var that = this
that.setData({
isbluetoothready: !that.data.isbluetoothready,
})
if (that.data.isbluetoothready) {
//開啟藍牙模塊並初始化
wx.openBluetoothAdapter({
success: function (res) {
},
fail: function (res) {
wx.showModal({
title: '提示',
content: '請檢查手機藍牙是否打開',
})
}
})
//開啟藍牙模塊並初始化
//檢查藍牙模塊是否初始化成功
wx.getBluetoothAdapterState({
success: function (res) {
var available = res.available
if (!available) {
wx.showToast({
title: '藍牙初始化失敗',
icon: 'loading',
duration: 2000
})
}
else {
wx.showToast({
title: '藍牙初始化成功',
icon: 'success',
duration: 2000
})
}
}
})
//檢查藍牙模塊是否初始化成功
}
else{
wx.closeBLEConnection({
deviceId: that.data.connectedDeviceId,
complete: function (res) {
that.setData({
deviceconnected: false,
connectedDeviceId: ""
})
wx.showToast({
title: '藍牙連接斷開',
icon: 'success',
duration: 2000
})
}
})
setTimeout(function () {
that.setData({
list: []
})
//釋放藍牙適配器
wx.closeBluetoothAdapter({
success: function (res) {
that.setData({
isbluetoothready: false,
deviceconnected: false,
devices: [],
searchingstatus: false,
receivedata: ''
})
wx.showToast({
title: '藍牙適配器釋放',
icon: 'success',
duration: 2000
})
},
fail: function (res) {
}
})
//釋放藍牙適配器
}, 1000)
}
},
search_BLE: function () {
temp = []
var that = this
if (!that.data.searchingstatus) {
var that = this
//開始搜索附近藍牙設備
wx.startBluetoothDevicesDiscovery({
success: function (res) {
wx.showToast({
title: '開始搜索BLE',
icon: 'loading',
duration: 2000
})
that.setData({
searchingstatus: !that.data.searchingstatus
})
}
})
//開始搜索附近藍牙設備
} else {
//停止搜索附近藍牙設備
wx.stopBluetoothDevicesDiscovery({
success: function (res) {
wx.showToast({
title: '停止搜索BLE',
icon: 'success',
duration: 2000
})
that.setData({
searchingstatus: !that.data.searchingstatus
})
}
})
//停止搜索附近藍牙設備
setTimeout(function () {
//獲取發現的藍牙設備
wx.getBluetoothDevices({
success: function (res) {
for(var i=0;i<100;i++){
if (res.devices[i]) {
string_temp = string_temp + '\n' + res.devices[i].deviceId
}
}
that.setData({
id_text: string_temp,
list: res.devices
})
}
})
//獲取發現的藍牙設備
}, 1000)
}
},
connectTO: function (e) {
var that = this
wx.showLoading({
title: '連接藍牙設備中...',
})
wx.createBLEConnection({
deviceId: e.currentTarget.id,
success: function (res) {
wx.hideLoading()
wx.showToast({
title: '連接成功',
icon: 'success',
duration: 1000
})
that.setData({
deviceconnected: true,
connectedDeviceId: e.currentTarget.id
})
// 啟用 notify 功能
wx.notifyBLECharacteristicValueChanged({
state: true,
deviceId: that.data.connectedDeviceId,
serviceId: serviceId,
characteristicId: characteristicId,
success: function (res) {
}
})
// 啟用 notify 功能
// ArrayBuffer轉為16進制數
function ab2hex(buffer) {
var hexArr = Array.prototype.map.call(
new Uint8Array(buffer),
function (bit) {
return ('00' + bit.toString(16)).slice(-2)
}
)
return hexArr.join('');
}
// 16進制數轉ASCLL碼
function hexCharCodeToStr(hexCharCodeStr) {
var trimedStr = hexCharCodeStr.trim();
var rawStr = trimedStr.substr(0, 2).toLowerCase() === "0x" ? trimedStr.substr(2) : trimedStr;
var len = rawStr.length;
var curCharCode;
var resultStr = [];
for (var i = 0; i < len; i = i + 2) {
curCharCode = parseInt(rawStr.substr(i, 2), 16);
resultStr.push(String.fromCharCode(curCharCode));
}
return resultStr.join("");
}
//監聽回調,接收數據
wx.onBLECharacteristicValueChange(function (characteristic) {
var hex = ab2hex(characteristic.value)
that.setData({
receive_data: hexCharCodeToStr(hex)
})
})
},
fail: function (res) {
wx.hideLoading()
wx.showToast({
title: '連接設備失敗',
icon: 'success',
duration: 1000
})
that.setData({
connected: false
})
}
})
wx.stopBluetoothDevicesDiscovery({
success: function (res) {
}
})
},
formSubmit: function (e) {
var senddata = e.detail.value.senddata;
var that = this
let buffer = new ArrayBuffer(senddata.length)
let dataView = new DataView(buffer)
for (var i = 0; i < senddata.length; i++) {
dataView.setUint8(i, senddata.charAt(i).charCodeAt())
}
wx.writeBLECharacteristicValue({
deviceId: that.data.connectedDeviceId,
serviceId: serviceId,
characteristicId: characteristicId,
value: buffer,
success: function (res) {
wx.showToast({
title: '發送成功',
icon: 'success',
duration: 2000
})
}
})
},
receiveMessages: function () {
var that = this;
wx.readBLECharacteristicValue({
deviceId: that.data.connectedDeviceId,
serviceId: serviceId,
characteristicId: characteristicId,
success: function (res) {
}
})
},
})