Page({
data: {
showNav: true,
bluetoothStatus: false
},
openBluetoothAdapter() {
let that = this
wx.openBluetoothAdapter({
success: (res) => {
console.log('蓝牙设备成功', res)
if (res.errMsg == "openBluetoothAdapter:ok") {
that.startBluetoothDevicesDiscovery()
}
},
fail: (res) => {
console.log('蓝牙设备失败', res)
if (res.errCode === 10001) {
that.onBluetoothAdapterStateChange()
}
}
})
},
onBluetoothAdapterStateChange() {
let that = this
wx.onBluetoothAdapterStateChange(function(res) {
console.log('是否开启了蓝牙', res)
if (res.available) {
that.setData({
bluetoothStatus: true
})
that.startBluetoothDevicesDiscovery()
}
})
},
startBluetoothDevicesDiscovery() {
let that = this
wx.startBluetoothDevicesDiscovery({
services: [],
allowDuplicatesKey: false,
success(res) {
console.log('是否处于搜索状态', res)
if (res.errCode == 0) {
that.stopBluetoothDevicesDiscovery()
}
},
fail(res) {
console.log(res)
}
})
},
stopBluetoothDevicesDiscovery() {
let that = this
wx.stopBluetoothDevicesDiscovery({
success(res) {
console.log('停止设备', res)
if (res.errMsg == 'stopBluetoothDevicesDiscovery:ok') {
that.getBluetoothDevices()
}
}
})
},
getBluetoothDevices() {
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)
if (res.errMsg == 'getBluetoothDevices:ok') {
}
if (res.devices[0]) {
console.log(ab2hex(res.devices[0].advertisData))
}
}
})
},
closeBluetoothAdapter() {
wx.closeBluetoothAdapter({
success(res) {
console.log(res)
}
})
},
onLoad: function(options) {
this.openBluetoothAdapter()
},
})