uniapp 蓝牙通讯保姆级教程(搜索/连接蓝牙、读、写)

小程序点击蓝牙设备进行通讯

1.初始化蓝牙设备 | | 提醒用户打开蓝牙设备

	player() {
		var that = this;
		uni.openBluetoothAdapter({ //调用微信小程序api 打开蓝牙适配器接口
			success: function(res) {
				// console.log(res)
				uni.showToast({
					title: '初始化成功',
					icon: 'success',
					duration: 800
				})
				that.findBlue(); //2.0
			},
			fail: function(res) { //如果手机上的蓝牙没有打开,可以提醒用户
				uni.showToast({
					title: '请打开蓝牙',
					type: 'error',
					icon: 'none'
				});
			}
		})
	},

2.搜索周边设备(此操作比较耗费系统资源,请在搜索并连接到设备后调用 uni.stopBluetoothDevicesDiscovery 方法停止搜索。)

	findBlue() {
		var that = this
		uni.startBluetoothDevicesDiscovery({
			allowDuplicatesKey: false,
			interval: 0,
			success: function(res) {
				uni.showLoading({
				title: '正在搜索设备',
			})
			that.getBlue() //3.0
			}
		})
	},

3.获取搜索到的设备信息

	getBlue() {
		var that = this
		//uni.getBluetoothDevices获取在蓝牙模块生效期间所有已发现的蓝牙设备。包括已经和本机处于连接状态的设备
		uni.getBluetoothDevices({
			success: function(res) {
				uni.hideLoading();
				// console.log(res)
				that.BluetoothList = res.devices
				//将BluetoothList遍历给用户,当用户点击连接某个蓝牙时调用4.0
			},
			fail: function() {
				console.log("搜索蓝牙设备失败")
			}
		})
	},

4.当用户点击某个设备时将deviceId进行蓝牙连接

	connetBlue(deviceId) {
		// console.log(deviceId)
		var that = this;
		uni.createBLEConnection({
			// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
			deviceId: deviceId, //设备id
			success: function(res) {
				uni.showToast({
				title: '连接成功',
				icon: 'fails',
				duration: 800
			})
			console.log("连接蓝牙成功!-->11111")
			uni.stopBluetoothDevicesDiscovery({
				success: function(res) {
					console.log('连接蓝牙成功之后关闭蓝牙搜索');
				}
			})
			that.deviceId = deviceId;
			that.getServiceId() //5.0
			}
		})
	},

5.连接上需要的蓝牙设备之后,获取这个蓝牙设备的服务uuid

	getServiceId() {
		var that = this
		uni.getBLEDeviceServices({
			// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
			deviceId: that.deviceId,
			success: function(res) {
				console.log(res)
				//需要什么服务就用对应的services 
				that.readyservices = res.services[0].uuid	//因设备而议:该特征值只支持读
				that.services = res.services[1].uuid		//因设备而议:该特征值支持write和notfy服务
				that.getCharacteId() //6.0
			}
		})
	},

6.如果一个蓝牙设备需要进行数据的写入以及数据传输,就必须具有某些特征值,所以通过上面步骤获取的id可以查看当前蓝牙设备的特征值

	getCharacteId() {
		var that = this
		uni.getBLEDeviceCharacteristics({
			// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
			deviceId: that.deviceId,
			// 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
			serviceId: that.services,
			success: function(res) {
				console.log(res)
				for (var i = 0; i < res.characteristics.length; i++) { //2个值
					var model = res.characteristics[i]
					if (model.properties.write) {
						//model.uuid:用来写入的uuid值
						//this.sendMy()给设备写入
						that.sendMy(model.uuid)
					}
					if (model.properties.notify) {
						//model.uuid:用来notify的uuid值
						that.notifyUuid = model.uuid
					}
				}
			}
		})
	},

7.将从后台服务获取的指令写入到蓝牙设备当中

	//buffer允许写入的uuid
	sendMy(buffer) {
		var that = this
		//this.string2buffer-->字符串转换成ArrayBufer(设备接收数据的格式ArrayBufer)
		var buff = that.string2buffer('3a0a0b0c0d02423122');  //9.0
		uni.writeBLECharacteristicValue({
			// 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
			deviceId: that.deviceId,
			// 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
			serviceId: that.services,
			// 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
			characteristicId: buffer, //第二步写入的特征值
			// 这里的value是ArrayBuffer类型
			value: buff,
			success: function(res) {
				//此时设备已接收到你写入的数据
				console.log("写入成功")
				
				that.startNotice()
			},
			fail: function(err) {
				console.log(err)
			},
			complete: function() {
				console.log("调用结束");
			}
		})
	},

8.创建链接,发送指令启用notify 功能接收设备返回的数据

	startNotice() {
		var that = this;
		uni.notifyBLECharacteristicValueChange({
			state: true, // 启用 notify 功能
			// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接 
			deviceId: that.deviceId,
			// 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
			serviceId: that.services,
			// 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
			characteristicId: that.notifyUuid, //第一步 开启监听 notityid  第二步发送指令 write
			success(res) {
				//接收蓝牙返回消息
				uni.onBLECharacteristicValueChange((sjRes)=>{
					// 此时可以拿到蓝牙设备返回来的数据是一个ArrayBuffer类型数据,
					//所以需要通过一个方法转换成字符串
					var nonceId = that.ab2hex(sjRes.value)//10.0
					console.log(sjRes)
					console.log('194行'+nonceId)
				})
			},
			fail(err) {
				console.log(err)
			}
		})
	}

9.将字符串转换成ArrayBufer

	string2buffer(str) {
		let val = ""
		if (!str) return;
		let length = str.length;
		let index = 0;
		let array = []
		while (index < length) {
			array.push(str.substring(index, index + 2));
			index = index + 2;
		}
		val = array.join(",");
		// 将16进制转化为ArrayBuffer
		return new Uint8Array(val.match(/[\da-f]{2}/gi).map(function(h) {
			return parseInt(h, 16)
		})).buffer
	},

10.将ArrayBuffer转换成字符串

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

基本完成连接、写入、读取返回值…其他操作看官网

  • 18
    点赞
  • 125
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值