uni-app 蓝牙搜索附近设备无法获取advertisData中的值

uni-app 蓝牙搜索附近设备无法获取advertisData中的值

产品分类

uniapp/App

测试过的手机

iphone7 华为 p40 pro

示例代码

/**
 * 判断初始化蓝牙状态
 */
function initTypes(code, errMsg) {
	switch (code) {
	case 10000:
		toast('未初始化蓝牙适配器');
		break;
	case 10001:
		toast('未检测到蓝牙,请打开蓝牙重试!');
		break;
	case 10002:
		toast('没有找到指定设备');
		break;
	case 10003:
		toast('连接失败');
		break;
	case 10004:
		toast('没有找到指定服务');
		break;
	case 10005:
		toast('没有找到指定特征值');
		break;
	case 10006:
		toast('当前连接已断开');
		break;
	case 10007:
		toast('当前特征值不支持此操作');
		break;
	case 10008:
		toast('其余所有系统上报的异常');
		break;
	case 10009:
		toast('Android 系统特有,系统版本低于 4.3 不支持 BLE');
		break;
	default:
		toast(errMsg);
	}
}

/**
 * 弹出框封装
 */
function toast(content, showCancel = false) {
	uni.showModal({
		title: '提示',
		content,
		showCancel
	});
}

/**
 * 初始化蓝牙适配器
 */
export function initAdapter() {
	uni.closeBluetoothAdapter({
		success(res) {
			console.log(res);
		}
	});
	openBluetoothAdapter();
}

/**
 * 初始化蓝牙设备
 */
function openBluetoothAdapter() {
	uni.openBluetoothAdapter({
		success: e => {
			console.log('初始化蓝牙成功:' + e.errMsg);
			console.log(JSON.stringify(e));
			// 获取蓝牙适配器状态成功后 回调进行蓝牙周围设备扫描
			getBluetoothAdapterState(() => {
				startBluetoothDevicesDiscovery();
			}); // 在 getBluetoothAdapterState 方法的回调函数中调用 startBluetoothDevicesDiscovery 方法
		},
		fail: e => {
			console.log(e);
			console.log('初始化蓝牙失败,错误码:' + (e.errCode || e.errMsg));
			if (e.errCode !== 0) {
				initTypes(e.errCode, e.errMsg);
			}
		}
	});
}

/**
 * 停止搜索蓝牙设备
 */
export function stopBluetoothDevicesDiscovery() {
	uni.stopBluetoothDevicesDiscovery({
		success: e => {
			console.log('停止搜索蓝牙设备:' + e.errMsg);
		},
		fail: e => {
			console.log('停止搜索蓝牙设备失败,错误码:' + e.errCode);
			if (e.errCode !== 0) {
				initTypes(e.errCode);
			}
		}
	});
}

/**
 * 开始搜索蓝牙设备
 */
export function startBluetoothDevicesDiscovery() {
	uni.startBluetoothDevicesDiscovery({
		services: ['00005a30-3c17-d293-8e48-14fe2e4da212'],
		allowDuplicatesKey: true,
		success: e => {
			console.log('开始搜索蓝牙设备:' + e.errMsg);
			onBluetoothDeviceFound();
		},
		fail: e => {
			console.log('搜索蓝牙设备失败,错误码:' + e.errCode);
			if (e.errCode !== 0) {
				initTypes(e.errCode);
			}
		}
	});
}

/**
 * 获取本机蓝牙适配器状态
 */
function getBluetoothAdapterState(callback) {
	console.log('-->');
	uni.getBluetoothAdapterState({
		success: res => {
			console.log('获取本机蓝牙适配器状态成功:' + JSON.stringify(res));
			if (typeof callback === 'function') {
				callback(); // 在回调函数中调用 startBluetoothDevicesDiscovery 方法
			}
		},
		fail: e => {
			console.log('获取本机蓝牙适配器状态失败,错误码:' + e.errCode);
			if (e.errCode !== 0) {
				initTypes(e.errCode);
			}
		}
	});
}

/**
 * 发现外围设备
 */
function onBluetoothDeviceFound() {
	uni.onBluetoothDeviceFound(devices => {
		console.log('搜索到的设备信息:' + JSON.stringify(devices));
		// getBluetoothDevices();
	});
}

/**
 * 获取在蓝牙模块生效期间所有已发现的蓝牙设备。包括已经和本机处于连接状态的设备。
 */
function getBluetoothDevices() {
	uni.getBluetoothDevices({
		success: res => {
			res.devices.forEach(device => {
				if (!device.connected) {
					getApp().globalData.bleDevicesInfo[device.deviceId] = {
						name: device.name,
						mac: device.deviceId,
						signal: device.RSSI,
						connectStatus: false
					};
				}
			});
		},
		fail: e => {
			console.log('获取蓝牙设备错误,错误码:' + e.errCode);
			if (e.errCode !== 0) {
				initTypes(e.errCode);
			}
		}
	});
}

/**
 * 连接低功耗蓝牙
 */
export function createBLEConnection(device, callback) {
	const deviceId = device.mac;
	uni.showToast({
		title: '连接蓝牙...',
		icon: 'loading',
		duration: 99999
	});
	uni.createBLEConnection({
		deviceId,
		success: res => {
			console.log(res);
			console.log('连接蓝牙成功:' + res.errMsg);
			// 停止搜索
			stopBluetoothDevicesDiscovery();
			uni.hideToast();
			uni.showToast({
				title: '连接成功',
				icon: 'success',
				duration: 500
			});
			getApp().globalData.bleDevicesInfo[deviceId].connectStatus = true;
			callback(null, device); // 调用回调函数,传递null表示没有错误
		},
		fail: e => {
			console.log('连接低功耗蓝牙失败,错误码:' + JSON.stringify(e));
			if (e.code == -1) {
				toast("该设备已连接");
			} else if (e.code !== 0) {
				initTypes(e.errCode);
			}
			uni.hideToast();
			callback(e); // 调用回调函数,传递错误对象
		}
	});
}

/**
 * 断开蓝牙
 */
export function closeBLEConnection(deviceId) {
	uni.closeBLEConnection({
		deviceId,
		success: res => {
			console.log(res);
			console.log('断开低功耗蓝牙成功:' + res.errMsg);
			getApp().globalData.bleDevicesInfo[deviceId].connectStatus = true;
		},
		fail: e => {
			console.log('断开低功耗蓝牙成功,错误码:' + e.errCode);
			if (e.errCode !== 0) {
				initTypes(e.errCode);
			}
		}
	});
}

/**
 * 监听连接的蓝牙设备状态
 */
export function onBLEConnectionStateChange() {
	uni.onBLEConnectionStateChange(function(res) {
		// 该方法回调中可以用于处理连接意外断开等异常情况
		console.log(`device ${res.deviceId} state has changed, connected: ${res.connected}`);
		getApp().globalData.bleDevicesInfo[res.deviceId].connectStatus = res.connected;
	})
}

/**
 * 读取低功耗蓝牙设备的特征值的二进制数据值。注意:必须设备的特征值支持 read 才可以成功调用
 */
export function readBLECharacteristicValue(deviceId, serviceId, characteristicId) {
	console.log(deviceId);
	console.log(serviceId);
	console.log(characteristicId);
	uni.readBLECharacteristicValue({
		// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
		deviceId,
		// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
		serviceId,
		// 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
		characteristicId,
		success: res => {
			console.log('读取设备数据值成功');
			console.log(JSON.stringify(res));
			this.notifyBLECharacteristicValueChange();
		},
		fail(e) {
			console.log('读取设备数据值失败,错误码:' + e.errCode);
			if (e.errCode !== 0) {
				initTypes(e.errCode);
			}
		}
	});
	this.onBLECharacteristicValueChange();
}

/**
 * 订阅特征值变化
 */
export function notifyBLECharacteristicValueChange(deviceId, serviceId, characteristicId) {
	console.log(deviceId);
	console.log(serviceId);
	console.log(characteristicId);

	uni.notifyBLECharacteristicValueChange({
		state: true, // 启用 notify 功能
		// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
		deviceId,
		// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
		serviceId,
		// 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
		characteristicId,
		success(res) {
			console.log('notifyBLECharacteristicValueChange success:' + res.errMsg);
			console.log(JSON.stringify(res));
		}
	});
}

/**
 * 监听特征值的特征值数据变化
 */
export function onBLECharacteristicValueChange() {
	// 必须在这里的回调才能获取
	uni.onBLECharacteristicValueChange(characteristic => {
		console.log('监听低功耗蓝牙设备的特征值变化事件成功');
		console.log(JSON.stringify(characteristic));
		this.valueChangeData = characteristic;
	});
}

/**
 * 发送数据到蓝牙设备
 */

更多关于uni-app 蓝牙搜索附近设备无法获取advertisData中的值的实战教程也可以访问 https://www.itying.com/category-93-b0.html

1 回复

更多关于uni-app 蓝牙搜索附近设备无法获取advertisData中的值的实战教程也可以访问 https://www.itying.com/category-93-b0.html


uni-app 中,使用蓝牙 API 搜索附近设备时,可能会遇到无法获取 advertisData 中的值的问题。这通常是由于平台限制或 API 实现方式不同导致的。以下是一些可能的原因和解决方案:

1. 平台限制

不同平台(如 iOS 和 Android)对蓝牙广告数据的处理方式不同,可能会导致某些数据无法获取。

  • iOS:iOS 对蓝牙广告数据的访问有较多限制,可能无法直接获取 advertisData 中的某些字段。
  • Android:Android 通常对蓝牙广告数据的访问较为宽松,但具体实现可能因设备或系统版本而异。

2. API 实现

uni-app 的蓝牙 API 是对原生平台 API 的封装,因此其行为可能受到原生平台 API 的限制。

3. 解决方案

3.1 检查平台差异

在代码中检查当前运行的平台,并根据平台差异采取不同的处理方式。

// 判断平台
if (uni.getSystemInfoSync().platform === 'ios') {
    // iOS 平台的特殊处理
} else {
    // Android 平台的特殊处理
}

3.2 使用 manufacturerData

如果 advertisData 无法获取,可以尝试使用 manufacturerData,它通常包含设备制造商的数据。

uni.onBluetoothDeviceFound(function(devices) {
    devices.forEach(device => {
        console.log('Device Name:', device.name);
        console.log('Device ID:', device.deviceId);
        console.log('Manufacturer Data:', device.manufacturerData);
    });
});

3.3 使用原生插件

如果 uni-app 的蓝牙 API 无法满足需求,可以考虑使用原生插件来访问蓝牙设备。uni-app 支持使用原生插件,可以通过编写原生代码来获取更详细的蓝牙数据。

3.4 调试和日志

在开发过程中,可以通过调试和日志来查看 advertisData 的具体内容,以确定问题所在。

uni.onBluetoothDeviceFound(function(devices) {
    devices.forEach(device => {
        console.log('Device:', device);
    });
});
回到顶部