uniapp蓝牙连接操作详解

初始化蓝牙

openBluetoothAdapter() {
    
    
	uni.openBluetoothAdapter({
    
     //打开蓝牙适配器接口
		success: (res) => {
    
     //已打开
			
		},
		fail: err => {
    
     //未打开 
			uni.showToast({
    
    
				icon: 'none',
				title: '查看手机蓝牙是否打开'
			});
		}

	})
}

开始搜索蓝牙设备

startBluetoothDeviceDiscovery() {
    
    
	uni.startBluetoothDevicesDiscovery({
    
    
		success: (res) => {
    
    
			// 发现外围设备
			this.onBluetoothDeviceFound()
		},
		fail: err => {
    
    
			console.log(err, '开始搜索蓝牙设备备错误信息')
		}
	})
}

发现外围设备

onBluetoothDeviceFound() {
    
    
	uni.onBluetoothDeviceFound((res) => {
    
    
		// res.devices 是所有的设备
	})
}

连接设备

// item 是要连接的设备数据
createBLEConnection(item) {
    
    
	let that = this;
	uni.showLoading({
    
    
		title: "连接中,请稍等",
		mask: true,
	});
	uni.createBLEConnection({
    
    
		deviceId: item.deviceId,
		success(res) {
    
    
			that.stopBluetoothDevicesDiscovery(); // 停止搜索蓝牙
			that.getBLEDeviceServices(item);	// 获取蓝牙的服务
		},
		fail(res) {
    
    
			uni.showToast({
    
    
				title: item.name + "蓝牙连接失败",
				icon: "none",
			});
			uni.hideLoading()
		}
	});
}

连接成功后停止搜索蓝牙

stopBluetoothDevicesDiscovery() {
    
    
	uni.stopBluetoothDevicesDiscovery({
    
    
		success: e => {
    
    
			this.loading = false
			console.log('停止搜索蓝牙设备:' + e.errMsg);
		},
		fail: e => {
    
    
			console.log('停止搜索蓝牙设备失败,错误码:' + e.errCode);
		}
	});
}

获取蓝牙的所有服务

getBLEDeviceServices(item) {
    
    
	setTimeout(() => {
    
    
		uni.getBLEDeviceServices({
    
    
			// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
			deviceId: item.deviceId,
			success: (res) => {
    
    
				// 可以和做硬件的沟通 他会直接给你一个 也可以自己从res里取值
				// res.services 是所有的服务
				item["serviceId"] = '0000AE30-0000-1000-8000-00805F9B34FB';
				// 	//进入特征
				this.getBLEDeviceCharacteristics(item);
			},
		});
	}, 2000);
}

获取蓝牙特征

getBLEDeviceCharacteristics(item) {
    
    
	let that = this
	setTimeout(() => {
    
    
		uni.getBLEDeviceCharacteristics({
    
    
			deviceId: item.deviceId,
			serviceId: item.serviceId,
			success: (res) => {
    
    
				// res.characteristics 特征值列表
				// 读写都需要用到特征值
			},
			fail: (res) => {
    
    
				console.log(res);
			},
		});
	}, 1000);
}

启用低功耗蓝牙设备特征值变化时的 notify 功能,订阅特征值。

注意:必须设备的特征值支持 notify 或者 indicate 才可以成功调用。

notifyBLECharacteristicValueChange() {
    
    
	let that = this
	uni.notifyBLECharacteristicValueChange({
    
    
		state: true, // 启用 notify 功能
		// 下面三个都是上面获取到的,也可以由硬件工作人员直接提供
		deviceId: ,
		serviceId: ,
		// 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
		characteristicId: ,
		success: (res) => {
    
    
			this.listenValueChange()
		},
		fail: (res) => {
    
    
			console.log("启用 notify 功能失败", res);
			uni.hideLoading();
		},
	});
},

监听低功耗蓝牙设备的特征值变化事件

必须先启用 notifyBLECharacteristicValueChange 接口才能接收到设备推送的 notification。

listenValueChange() {
    
    
	uni.onBLECharacteristicValueChange(res => {
    
    
		let resHex = this.ab2hex(res.value);
		let result = this.hexCharCodeToStr(resHex);

		// result 硬件返回值
	})
},


ab2hex(buffer, split='') {
    
    
	var hexArr = Array.prototype.map.call(new Uint8Array(buffer), function(bit) {
    
    
		return ('00' + bit.toString(16)).slice(-2)
	})
	return hexArr.join(split)
},

写入

write(hexadecimal){
    
    
	const buf = new ArrayBuffer(hexadecimal.length)
	const dataView = new DataView(buf)
	// 有字母的必须转16进制
	// 例如 ["FF", "AA", "03", "00", "40", "02", "00", "45", "FE"]
	// ['06', '01', '01', '01', '00', '00', '00', '00', '00', '00', '00', '00', '00', '00', '00','00'] 这种不转也能识别
	for (var i = 0; i < hexadecimal.length; ++i) {
    
    
		dataView.setUint8(i,parseInt(hexadecimal[i],16) )
	}
	return new Promise((resolve, reject) => {
    
    
		uni.writeBLECharacteristicValue({
    
    
			// 这里的 deviceId 需要在 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
			deviceId: ,
			// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
			serviceId: ,
			// 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
			characteristicId: ,
			// 这里的value是ArrayBuffer类型
			value: buf,
			success(res) {
    
    
				console.log('writeBLECharacteristicValue success', res)
			},
			fail(res) {
    
    
				console.log('失败', res)
			},
		})
	})
},

猜你喜欢

转载自blog.csdn.net/qq_52151772/article/details/132206766