最近一個師兄要求做一個藍牙通訊功能的微信小程序,記載如下
參考CSDN范例
微信官方的藍牙API文檔
實現(xiàn)功能:
- 對方設(shè)備向手機暴露藍牙
- 微信小程序打開藍牙搜索設(shè)備
- 當?shù)玫皆O(shè)備的相應(yīng)信息后,主動發(fā)起連接
- 通過小程序設(shè)置相應(yīng)信息,將修改的結(jié)果顯示數(shù)據(jù)到設(shè)備上
1、測試是否能搜索到藍牙設(shè)備
index.wxml
<!--index.wxml-->
<view class="container">
<view class="section">
<view class="content">
<text>藍牙初始化:</text>
<text>{{isbluetoothready?"ok":"尚未初始化"}}</text>
</view>
<view class="switch">
<switch checked="{{isbluetoothready}}" bindchange="switchBlueTooth" />
</view>
</view>
<view class="section" hidden="{{!isbluetoothready}}">
<button type="default" size="{{primarySize}}" loading="{{searchingstatus}}" plain="{{plain}}" disabled="{{disabled}}" bindtap="searchbluetooth"> {{searchingstatus?"搜索中":"搜索藍牙"}} </button>
</view>
<block>
<view class="section" hidden="{{!isbluetoothready}}">
<view class="list-item {{deviceconnected?'deviceconnected':''}}">
<text>設(shè)備名稱:{{item.deviceId}}</text>
<text>設(shè)備名稱:{{item.deviceId}}</text>
<button id="{{item.deviceId}}" type="default" size="mini" bindtap="connectTO">{{deviceconnected?"已連接":"鏈接"}}</button>
</view>
</view>
</block>
</view>
index.wcss
/**index.wxss**/
view {
display: inline-block;
}
.container {
padding: 0;
margin: 0;
align-items: flex-start;
}
.section {
display: inline-block;
width: 100%;
position: relative;
}
.content {
margin: auto;
padding: auto;
position: absolute;
top: 5px;
left: 10px;
}
.switch {
position: relative;
float: right;
right: 0px;
}
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;
}
<strong>藍牙開發(fā)注意事項</strong>:
微信小程序藍牙的開發(fā)是指基于藍牙4.0的低功耗藍牙開發(fā)。
通常對藍牙涉獵不深的人來看將BLE等同于藍牙4.0,其實不然。藍牙4.0協(xié)議包含BLE,BLE隸屬于藍牙4.0協(xié)議的一部分
藍牙4.0是協(xié)議,4.0是協(xié)議版本號,藍牙4.0是2010年6月由SIG(Special Interest Group)發(fā)布的藍牙標準,它有兩種模式:
- 1、BLE(Bluetooth low energy)只能與4.0協(xié)議設(shè)備通信,適應(yīng)節(jié)能且僅收發(fā)少量數(shù)據(jù)的設(shè)備(如手環(huán)、智能體溫計),稱之為低功耗藍牙;
- 2、BR/EDR(Basic Rate / Enhanced Data Rate),向下兼容(能與3.0/2.1/2.0通信),適應(yīng)收發(fā)數(shù)據(jù)較多的設(shè)備(如耳機、手機、平板)。這個模式常常也有人稱之為“傳統(tǒng)藍牙”或“經(jīng)典藍牙”;
編寫JS思路
- 通過wx.openBluetoothAdapter初始化藍牙設(shè)備。
- 通過wx.onBluetoothAdapterStateChange藍牙適配器狀態(tài)變化事件
- 通過wx.onBluetoothDeviceFound搜索回調(diào)事件可以得到搜索到的藍牙設(shè)備,如果是小米手環(huán)一代(設(shè)備名:MI1A),則進行記錄該設(shè)備信息。
index.js
var app = getApp()
var temp = []
var serviceId = "00002A00-0000-1000-8000-00805F9B34FB"
var characteristicId = "00002A00-0000-1000-8000-00805F9B34FB"
Page({
data: {
isbluetoothready: false,
defaultSize: 'default',
primarySize: 'default',
warnSize: 'default',
disabled: false,
plain: false,
loading: false,
searchingstatus: false,
receivedata: '',
onreceiving: false
},
onLoad: function () {
// var str = "A13";
// // var code = str.charCodeAt();
// console.log(str.length)
// console.log(str.charAt(0))
// wx.showToast({
// title: '連接成功',
// icon: 'success',
// duration: 2000
// })
// let buffer = new ArrayBuffer(16)
// let dataView = new DataView(buffer)
// dataView.setUint8(1, 6)
//console.log(dataView.getUint8(1))
},
switchBlueTooth: function () {
var that = this
that.setData({
isbluetoothready: !that.data.isbluetoothready,
})
if (that.data.isbluetoothready) {
wx.openBluetoothAdapter({
success: function (res) {
console.log("初始化藍牙適配器成功")
wx.onBluetoothAdapterStateChange(function (res) {
console.log("藍牙適配器狀態(tài)變化", res)
that.setData({
isbluetoothready: res.available,
searchingstatus: res.discovering
})
})
wx.onBluetoothDeviceFound(function (devices) {
console.log(devices)
temp.push(devices)
that.setData({
devices: temp
})
console.log('發(fā)現(xiàn)新藍牙設(shè)備')
console.log('設(shè)備id' + devices.deviceId)
console.log('設(shè)備name' + devices.name)
}),
fail: function (res) {
console.log("初始化藍牙適配器失敗")
wx.showModal({
title: '提示',
content: '請檢查手機藍牙是否打開',
success: function (res) {
that.setData({
isbluetoothready: false,
searchingstatus: false
})
}
})
}
})
} else {
temp = []
//先關(guān)閉設(shè)備連接
wx.closeBLEConnection({
deviceId: that.data.connectedDeviceId,
complete: function (res) {
console.log(res)
that.setData({
deviceconnected: false,
connectedDeviceId: ""
})
}
})
wx.closeBluetoothAdapter({
success: function (res) {
console.log(res)
that.setData({
isbluetoothready: false,
deviceconnected: false,
devices: [],
searchingstatus: false,
receivedata: ''
})
},
fail: function (res) {
wx.showModal({
title: '提示',
content: '請檢查手機藍牙是否打開',
success: function (res) {
that.setData({
isbluetoothready: false
})
}
})
}
})
}
},
searchbluetooth: function () {
temp = []
var that = this
if (!that.data.searchingstatus) {
var that = this
wx.startBluetoothDevicesDiscovery({
success: function (res) {
console.log("開始搜索附近藍牙設(shè)備")
console.log(res)
that.setData({
searchingstatus: !that.data.searchingstatus
})
}
})
} else {
wx.stopBluetoothDevicesDiscovery({
success: function (res) {
console.log("停止藍牙搜索")
console.log(res)
}
})
}
},
connectTO: function (e) {
var that = this
if (that.data.deviceconnected) {
wx.notifyBLECharacteristicValueChanged({
state: false, // 停用notify 功能
deviceId: that.data.connectedDeviceId,
serviceId: serviceId,
characteristicId: characteristicId,
success: function (res) {
console.log("停用notify 功能")
}
})
wx.closeBLEConnection({
deviceId: e.currentTarget.id,
complete: function (res) {
console.log("斷開設(shè)備")
console.log(res)
that.setData({
deviceconnected: false,
connectedDeviceId: "",
receivedata: ""
})
}
})
} else {
wx.showLoading({
title: '連接藍牙設(shè)備中...',
})
wx.createBLEConnection({
deviceId: e.currentTarget.id,
success: function (res) {
wx.hideLoading()
wx.showToast({
title: '連接成功',
icon: 'success',
duration: 1000
})
console.log("連接設(shè)備成功")
console.log(res)
that.setData({
deviceconnected: true,
connectedDeviceId: e.currentTarget.id
})
wx.notifyBLECharacteristicValueChanged({
state: true, // 啟用 notify 功能
deviceId: that.data.connectedDeviceId,
serviceId: serviceId,
characteristicId: characteristicId,
success: function (res) {
console.log("啟用notify")
}
})
},
fail: function (res) {
wx.hideLoading()
wx.showToast({
title: '連接設(shè)備失敗',
icon: 'success',
duration: 1000
})
console.log("連接設(shè)備失敗")
console.log(res)
that.setData({
connected: false
})
}
})
wx.stopBluetoothDevicesDiscovery({
success: function (res) {
console.log("停止藍牙搜索")
console.log(res)
}
})
}
},
formSubmit: function (e) {
console.log('form發(fā)生了submit事件,攜帶數(shù)據(jù)為:', e.detail.value.senddata)
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) {
console.log(res)
console.log('writeBLECharacteristicValue success', res.errMsg)
}
})
},
formReset: function () {
console.log('form發(fā)生了reset事件')
}
})
function getNowFormatDate() {
var date = new Date();
var seperator1 = "-";
var seperator2 = ":";
var month = date.getMonth() + 1;
var strDate = date.getDate();
if (month >= 1 && month <= 9) {
month = "0" + month;
}
if (strDate >= 0 && strDate <= 9) {
strDate = "0" + strDate;
}
var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
+ " " + date.getHours() + seperator2 + date.getMinutes()
+ seperator2 + date.getSeconds();
return currentdate;
}
console output

OneTest.png
查詢文檔回調(diào)方法wx.onBluetoothDeviceFound與wx.getBluetoothDevices
嘗試使用getBluetoothDevices獲取所有已發(fā)現(xiàn)的藍牙設(shè)備,包括已經(jīng)和本機處于連接狀態(tài)的設(shè)備fgdfgdf