uniapp 蓝牙连接测温仪

需求:app通过蓝牙连接硬件测温仪,使用uniapp的ble蓝牙连接

一、连接蓝牙流程

打开蓝牙 → 搜索蓝牙 → 蓝牙连接 → 停止搜索 → 获取蓝牙设备的uuid → 获取蓝牙特性 → 监听接收数据 → 关闭蓝牙

1.打开蓝牙

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

2. 搜索蓝牙

findBlue() { // 搜索蓝牙
	var that = this
	uni.startBluetoothDevicesDiscovery({
		allowDuplicatesKey: false,
		interval: 0,
		success: function(res) {
			console.log('搜索设备')
			console.log(res)
			uni.showLoading({
				title: '正在搜索设备',
			})
			that.onBluetoothDeviceFound()
		}
	})
},
// 发现外围设备
onBluetoothDeviceFound() {
	const that = this
		uni.onBluetoothDeviceFound(devices => {
				console.log('开始监听寻找到新设备的事件');
				// this.$set(this.disabled, 3, false);
				that.getBlue() //3.0
		});
},
getBlue() { // 获取蓝牙设备
	var that = this
	// uni.getBluetoothDevices获取在蓝牙模块生效期间所有已发现的蓝牙设备。包括已经和本机处于连接状态的设备
	uni.getBluetoothDevices({
		success: function(res) {
			uni.hideLoading();
			console.log('获取蓝牙')
			console.log(res.devices)
			that.BluetoothList = res.devices.filter(item => {
				return item.name
			})
			that.searching = false
			//将BluetoothList遍历给用户,当用户点击连接某个蓝牙时调用4.0
		},
		fail: function() {
			that.searching = false
			console.log("搜索蓝牙设备失败")
		}
	})
},

3.蓝牙连接并停止搜索

connetBlue(deviceId, deviceName) { // 蓝牙连接
	var that = this;
	that.state = 'working'
	that.connecting = true
	that.deviceId = deviceId
	that.deviceName = deviceName
	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.connecting = false
		that.getServiceId() //5.0
		}
	})
},

4. 获取蓝牙设备的uuid(要打印出来看每个uuid对应的特性是不是复合你的需求)

getServiceId() { // 获取这个蓝牙设备的服务uuid
	var that = this
	setTimeout(() => {
		uni.getBLEDeviceServices({
			// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
			deviceId: that.deviceId,
			success: function(res) {
				console.log('获取uuid')
				console.log(res)
				//需要什么服务就用对应的services,这里对应的不一定是第一个,要看你的设备
				that.readyservices = res.services[0].uuid	//因设备而议:该特征值只支持读
				// that.services = res.services[1].uuid		//因设备而议:该特征值支持write和notfy服务
				that.getCharacteId() //6.0
			},
			fail(err) {
				console.log('获取失败' + err)
			}
		})
	}, 2000)
},

5. 获取蓝牙特性(notify或者 indicate必须是true,才能订阅特征值)

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

6. 监听接收数据(这里也有读取数据,不用我没有用到uni.readBLECharacteristicValue)

PS:对于接收到的数据是一个ArrayBuffer类型数据,所以打印出来是value:{},需要用一个方法把将ArrayBuffer转换成字符串。

因为我是连接测温仪,所以我获得的数据要从16进制转成10进制,使用parseInt(beforeNum, 16)

readBLECharacteristicValue() { // 读取数据
	var that = this
	uni.readBLECharacteristicValue({
		// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
		deviceId: that.deviceId,
		// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
		serviceId: that.readyservices,
		// 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
		characteristicId: that.readUuid,
		success(res) {
		console.log('读取数据:', res)
		console.log(res)
		}
	})
},
startNotice() { // 创建链接,发送指令启用notify 功能接收设备返回的数据
	var that = this;
	uni.notifyBLECharacteristicValueChange({
		state: true, // 启用 notify 功能
		// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接 
		deviceId: that.deviceId,
		// 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
		serviceId: that.readyservices,
		// 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
		characteristicId: that.notifyUuid, //第一步 开启监听 notityid  第二步发送指令 write
		success(res) {
			//接收蓝牙返回消息
			console.log('开始接收数据')
			console.log(res)
			uni.onBLECharacteristicValueChange((sjRes)=>{
				// 此时可以拿到蓝牙设备返回来的数据是一个ArrayBuffer类型数据,
				//所以需要通过一个方法转换成字符串
				const beforeNum = that.ab2hex(sjRes.value).substring(8, 10)
				const afterNum = that.ab2hex(sjRes.value).substring(11, 12)
				const temperature = parseInt(beforeNum, 16) + '.' + parseInt(afterNum, 16) // 16进制转10进制
				that.saveRecords(temperature)
			})
		},
		fail(err) {
			console.log(err)
		}
	})
},
ab2hex(buffer) { // 将ArrayBuffer转换成字符串
	const hexArr = Array.prototype.map.call(
		new Uint8Array(buffer),
		function (bit) {
			return ('00' + bit.toString(16)).slice(-2)
		}
	)
	return hexArr.join('')
},

7. 关闭蓝牙

closeBlue() { // 断开蓝牙
	const that = this
	uni.closeBluetoothAdapter({
		success(res) {
			that.showToastInfo({ msg: '已关闭蓝牙', icon: 'success' })
			that.state = 'connecting'
			that.deviceId = ''
			that.BluetoothList = []
		},
		fail(err) {
			console.log(err)
		}
	})
}

二、其他

1. 注意打包的时候要把mainfest.json App模块配置 Bluetooth(低功耗蓝牙)勾上

2. 接收到的数据就是一个ArrayBuffer数据,打印出来value:{},必须通过转化才能看出来

 

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值