uniapp蓝牙硬件广播扫描

通过蓝牙广播扫描,读取硬件设备的数据

大致步骤如下:
1. 初始化蓝牙适配器
2. 开始搜索设备
3. 发现外围设备
4. 获取所有已发现的蓝牙设备
5. 判断当前设备
6. 解析蓝牙设备的广播数据段中的 ManufacturerData 数据段

接下来代码实现

养成好习惯,先点赞加关注再阅读 o( ̄▽ ̄)d

// 1. 初始化蓝牙适配器
uni.openBluetoothAdapter({
    
    
	success: () => {
    
    
		// 初始化完毕开始搜索
		this.startBluetoothDeviceDiscovery();
	},
	fail: res => {
    
    
		if (res.errCode === 10001) {
    
    
			uni.showToast({
    
    
				title: '请打开蓝牙',
				icon: 'none'
			});
			// 监听蓝牙适配器状态变化事件
			uni.onBluetoothAdapterStateChange(res => {
    
    
				if (res.available) {
    
    
					this.startBluetoothDeviceDiscovery();
				}
			});
		}
	}
});

// 2. 开始搜索设备
startBluetoothDeviceDiscovery() {
    
    
	uni.startBluetoothDevicesDiscovery({
    
    
		allowDuplicatesKey: true, // 为获取设备的实时数据,允许扫描相同设备
		success: res => {
    
    
			this.onBluetoothDeviceFound();
		}
	});
},

// 3. 发现外围设备
onBluetoothDeviceFound() {
    
    
	uni.onBluetoothDeviceFound(devices => {
    
    
		this.getBluetoothDevices();
	});
},

// 4. 获取所有已发现的蓝牙设备
getBluetoothDevices() {
    
    
	uni.getBluetoothDevices({
    
    
		success: res => {
    
    
			res.devices.forEach(item => {
    
    
				// 通过自定义deviceName判断是否当前设备
				if(item.name === this.deviceName) {
    
    
					// ArrayBuffer转16进度字符串
					var bytes = Array.prototype.map.call(new Uint8Array(item.advertisData), bit => ('00' + bit.toString(16)).slice(-2)).join('');
					// TODO: 
					// 解析你的设备数据
				}
			});
		}
	});
},

如果觉得有用随手点个赞吧,谢谢
关注我,不定时分享技术干货~

猜你喜欢

转载自blog.csdn.net/weixin_45295253/article/details/127537228