uni-app 蓝牙连接设备

连接蓝牙设备总共需要一下几步

uni-app官方文档

1.先查看系统蓝牙状态 uni.openBluetoothAdapter(obj)
2.搜索附近的蓝牙设备并且监听寻找到新设备的事件
uni.startBluetoothDevicesDiscovery(obj)搜索附近的蓝牙设备 uni.onBluetoothDeviceFound(obj)监听寻找到新设备的事件
3.成功找到对应蓝牙设备后 需关闭搜索
uni.stopBluetoothDevicesDiscovery(obj) 停止搜寻附近的蓝牙外围设备
4.连接低功耗蓝牙设备 连接成功后调用uni.getBLEDeviceServices来获取蓝牙设备所有服务
uni.createBLEConnection(obj) 连接低功耗蓝牙设备
uni.getBLEDeviceServices(obj) 获取蓝牙设备所有服务(service)。
5.获取蓝牙设备某个服务中所有特征值

1.先查看系统蓝牙状态
uni.openBluetoothAdapter(obj)

				uni.openBluetoothAdapter({
					success: function(res) {
						console.log('是否开启蓝牙', res)
					},
					fail: function(msg) {
						console.log(msg)
					}
				})

2.搜索附近的蓝牙设备 并且监听寻找到新设备的事件

				let that = this
				uni.startBluetoothDevicesDiscovery({
					success: function(res) {
						console.log('搜索设备---', res)
						uni.onBluetoothDeviceFound(function(el) {
							console.log('new device list has founded')
							console.log(el)
							console.log(that.ab2hex(el.devices[0].advertisData))
							//找到对应蓝牙设备名字
							if (el.devices[0].name == '云音乐ME01-1384') {
								console.log("成功-------", el)
								//成功后存储设备id
								that.deviceId = el.devices[0].deviceId
								that.stop()//关闭搜索 第三步方法名
							}
						})
					},
				})

3.成功找到对应蓝牙设备后 需关闭搜索附近设备

uni.stopBluetoothDevicesDiscovery({
					success(res) {
						console.log('停止搜索---', res)
					}
				})

4.连接低功耗蓝牙设备 连接成功后调用uni.getBLEDeviceServices来获取蓝牙设备所有服务

				let that = this
				uni.createBLEConnection({
					deviceId: this.deviceId,
					success: (res) => {
						console.log('连接成功---', JSON.stringify(res))
						//需延时连接,不然会报错
						setTimeout(function() {
							uni.getBLEDeviceServices({
								deviceId: that.deviceId,
								success: (res) => {
									console.log('获取蓝牙设备所有服务', res)
									that.uuid = res.services[0].uuid
									that.huoqu(res.services[0].uuid) //第五步方法名
								}

							})
						}, 1000)
					}
				})

5.获取蓝牙设备某个服务中所有特征值

				let that = this
				let deviceId = this.deviceId
				uni.getBLEDeviceCharacteristics({
					deviceId: this.deviceId,
					serviceId: uuid,
					success: (res) => {
						that.characteristics = res.characteristics[0].uuid
						console.log('获取--------', res)
					},
					fail: (res) => {
						console.log('失败1--------', res)
					}

				})
  • 5
    点赞
  • 41
    收藏
    觉得还不错? 一键收藏
  • 7
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值