openBluetoothAdapter,startBluetoothDevicesDiscovery,onBluetoothDeviceFound,createBLEConnection和监听onBluetoothAdapterStateChange整个流程在在uni-app中onBluetoothAdapterStateChange是完全监听不到的,有时onBluetoothDeviceFound是没有回调结果的,搜索设备为空值。安卓手机在真机调试遇到的问题。
<script>
export default {
data() {
return {
bds:[]
}
},
created() {},
methods: {
openBluebooth() {
var self = this;
uni.openBluetoothAdapter({
success: function(res) {
console.log('--开启蓝牙适配' + JSON.stringify(res))
// 搜索设备
self.startSearchBLE()
// 监听函数启用
// 监听本机蓝牙状态改变
uni.onBluetoothAdapterStateChange(function(e) {
console.log('onBluetoothAdapterStateChange: ' + JSON.stringify(e));
});
// 监听搜索到新设备
uni.onBluetoothDeviceFound(function(e) {
var devices = e.devices;
console.log('onBluetoothDeviceFound: ' + JSON.stringify(e));
});
// 监听低功耗蓝牙设备连接状态变化
uni.onBLEConnectionStateChange(function(e) {
console.log('onBLEConnectionStateChange: ' + JSON.stringify(e));
if (e.connected) { // 处于链接状态, 做搜索服务 -> 状态 -> 连贯开锁
self.deviceId = e.deviceId
setTimeout(() => {
self.getServes()
}, 30)
} else { // 断开 -> 重连
}
});
// 监听低功耗蓝牙设备的特征值变化
uni.onBLECharacteristicValueChange(function(e) {
console.log('onBLECharacteristicValueChange: ' + JSON.stringify(e));
});
},
fail: function(err) {
console.log('openBluebooth fail')
},
})
},
// 搜索设备
startSearchBLE() {
var self = this;
uni.startBluetoothDevicesDiscovery({
services: self.services,
success: function(e) {
console.log('搜索附近设备成功' + JSON.stringify(e));
console.log(e);
setTimeout(() => {
self.searchDevices();
}, 300)
},
fail: function(e) {
console.log('搜索附近设备失败' + JSON.stringify(e))
}
})
},
// 搜索设备
searchDevices() {
var self = this;
// // ArrayBuffer转16进度字符串示例
function ab2hex(buffer) {
const hexArr = Array.prototype.map.call(
new Uint8Array(buffer),
function (bit) {
return ('00' + bit.toString(16)).slice(-2)
}
)
return hexArr.join('')
}
uni.getBluetoothDevices({
success(res) {
console.log('获取搜索的设备' + JSON.stringify(res))
var devices = res.devices;
console.log(res)
if (res.devices[0]) {
console.log(ab2hex(res.devices[0].advertisData))
}
}
})
},
}
}
</script>
<style>
.content {
text-align: center;
height: 400upx;
}
.logo {
height: 200upx;
width: 200upx;
margin-top: 200upx;
}
.title {
font-size: 36upx;
color: #8f8f94;
}
</style>
0 个回复