uniapp 调用蓝牙接收数据、向设备发送指令后接收返回结果
一、连接蓝牙设备
1.初始化蓝牙
先判断本机的蓝牙是否打开
initBle() {
console.log('--------------------初始化蓝牙----------------');
this.bleDevs = [];
uni.openBluetoothAdapter({
success: (res) => {
//已打开
uni.getBluetoothAdapterState({
//蓝牙的匹配状态
success: (row) => {
console.log(row)
// 开始搜索蓝牙设备
this.startBluetoothDeviceDiscovery()
},
fail(error) {
uni.showToast({
icon: 'none',
title: '查看手机蓝牙是否打开'
});
}
});
},
fail: err => {
//未打开
uni.showToast({
icon: 'none',
title: '查看手机蓝牙是否打开'
});
}
})
},
2.搜索蓝牙
// 开始搜索蓝牙设备
startBluetoothDeviceDiscovery() {
let _this = this
uni.startBluetoothDevicesDiscovery({
success: (res) => {
console.log('搜索蓝牙外围设备完成', res)
_this.timer1 = setTimeout(() => {
//加个延迟、目的是为了设备搜索完毕再获取列表,不然获取为空列表
// 获取设备列表
_this.onBluetoothDeviceFound()
}, 1000)
},
fail: (err)=> {
console.log(err)
}
})
},
3.获取设备列表
// 获取设备列表
onBluetoothDeviceFound() {
let that = this
uni.getBluetoothDevices({
success: function(res) {
//过滤掉name为空的设备<