首页 > 其他分享 >uniapp启用蓝牙

uniapp启用蓝牙

时间:2024-10-08 22:17:42浏览次数:3  
标签:uniapp console 启用 res 蓝牙 devices deviceId uni

<template>
	<view class="container">
		<button class="btn" @click="startBluetoothDevicesDiscovery">搜索蓝牙设备</button>
		<view class="device-list">
			<view v-for="(device, index) in devices" :key="index" class="device-item">
				<text>{{ device.deviceId }}</text>
				<text v-if="device.name">{{ device.name }}</text>
				<text v-else>未命名设备</text>
				<text>{{ device.connectable }}</text>

				<button @click="connectToDevice(device.deviceId)">连接</button>
				<button @click="Status">查看连接状态</button>
			</view>

		</view>
	</view>
</template>

  device.connectable为true表示可以连接

页面

单页面非常的简陋,因为侧重蓝牙模块

	data() {
			return {
				devices: [],
				status: [],
			};
		},

方法

开启蓝牙适配器

	startBluetoothDevicesDiscovery() {
		uni.openBluetoothAdapter({
			success: () => {
			  console.log('蓝牙适配器开启成功');
			  uni.startBluetoothDevicesDiscovery({
			     success: () => {
				  console.log('开始搜索蓝牙设备');
					},
			     fail: (err) => {
			 	  console.error('搜索蓝牙设备失败', err);
					 }
					});
					},
			fail: (err) => {
						console.error('蓝牙适配器开启失败', err);
					}
				});

				uni.onBluetoothDeviceFound((devices) => {
					console.log('找到设备', devices.devices[0]);
					this.devices.push(devices.devices[0]);
				});
			},

点击连接蓝牙设备

connectToDevice(deviceId) {
				uni.showLoading({
					title: '正在连接......'
				})

				uni.createBLEConnection({
					deviceId: deviceId,
					success: (res) => {
						console.log('连接蓝牙设备成功', res);
						wx.hideLoading({

						})

						uni.showToast({
							icon: 'none',
							title: '连接成功!'
						})
						this.getServiceId()
					},
					fail: (err) => {
						console.error('连接蓝牙设备失败', err);
						wx.hideLoading({
							title: '连接蓝牙设备失败!'
						})
					}
				});
			},

查看设备连接状态

	Status() {
				uni.getBluetoothAdapterState({
					success: (res) => {
						console.log(res)
						this.status = res
					}

				})
			},

 getServiceId()

			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
					}
				})
			},

标签:uniapp,console,启用,res,蓝牙,devices,deviceId,uni
From: https://blog.csdn.net/bjxlyy/article/details/142770674

相关文章