uniapp 调用蓝牙接收数据、发送指令后接收返回结果

一、连接蓝牙设备

1.初始化蓝牙

先判断本机的蓝牙是否打开

           initBle() {
   
				console.log('--------------------初始化蓝牙----------------');
				this.bleDevs = [];
				uni.openBluetoothAdapter({
   
					success: (res) => {
    //已打开
						uni.getBluetoothAdapterState({
    //蓝牙的匹配状态
							success: (row) => {
   
								console.log(row)
								// 开始搜索蓝牙设备
								this.startBluetoothDeviceDiscovery()
							},
							fail(error) {
   
								uni.showToast({
   
									icon: 'none',
									title: '查看手机蓝牙是否打开'
								});
							}
						});

					},
					fail: err => {
    //未打开 
						uni.showToast({
   
							icon: 'none',
							title: '查看手机蓝牙是否打开'
						});
					}
				})
			},

2.搜索蓝牙

// 开始搜索蓝牙设备
			startBluetoothDeviceDiscovery() {
   
				let _this = this
				uni.startBluetoothDevicesDiscovery({
   
					success: (res) => {
   
						console.log('搜索蓝牙外围设备完成', res)
						_this.timer1 = setTimeout(() => {
    //加个延迟、目的是为了设备搜索完毕再获取列表,不然获取为空列表
							// 获取设备列表
							_this.onBluetoothDeviceFound()

						}, 1000)

					},
					fail: (err)=> {
   
						console.log(err)
					}
				})
			},

3.获取设备列表

// 获取设备列表
			onBluetoothDeviceFound() {
   
				let that = this
				uni.getBluetoothDevices({
   
					success: function(res) {
   
						//过滤掉name为空的设备<
评论 24
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值