<template>
	<view>
		<button @click="searchBle">搜索蓝牙</button>
		<view class="">
			已连接：{{connectDeviceId}}
		</view>
		<view style="margin-top: 30upx;" :key="index" v-for="(item,index) in devices">
			<button style="width: 400upx; color: #000000;" @click="onConn(item)">{{item.name}}</button>
		</view>
	</view>
</template>
 
<script>
	export default {
		data() {
			return {
				//搜索的蓝牙列表
				devices: [],
				// 连接的蓝牙设备
				connectDeviceId: ""
			}
		},
		methods: {
			destroyed: function() {
				let that = this
				// 离开页面断开蓝牙连接
				if (that.connectDeviceId != '') {
					// 断开与低功耗蓝牙设备的连接
					uni.closeBLEConnection({
						deviceId: that.connectDeviceId,
						success(res) {
							that.connectDeviceId=""
						}
					})
				}
			},
			// 搜索蓝牙
			searchBle() {
				var that = this
				// 初始化蓝牙模块
				uni.openBluetoothAdapter({
					success(res) {
						console.log(res, "初始化蓝牙模块")
						// 监听搜索到新设备的事件
						that.onDevice()
						// 获取本机蓝牙适配器状态
						uni.getBluetoothAdapterState({
							success: function(res) {
								console.log(res, '获取本机蓝牙适配器状态')
								// 判断蓝牙适配器是否可用
								if (res.available) {
									// 是否正在搜索设备
									if (res.discovering) {
										// 停止搜索
										that.stopFindBule()
									}
									//开始搜寻附近的蓝牙外围设备
									uni.startBluetoothDevicesDiscovery({
										success(res) {
											console.log(res, '开始搜寻附近的蓝牙外围设备')
										}
									})
								} else {
									console.log('本机蓝牙不可用')
								}
							},
						})
					}
				})
			},
			// 监听搜索到新设备的事件
			onDevice() {
				console.log("监听搜索到新设备的事件---------------")
				var that = this
				//监听搜索到新设备的事件
				uni.onBluetoothDeviceFound(function(devices) {
					console.log('--------------new-----------------------' + JSON.stringify(devices))
					var re = JSON.parse(JSON.stringify(devices))
					console.log(re.devices[0].name + "  " + re.devices[0].deviceId)
					let name = re.devices[0].name
					if ((name != "未知设备")&&(name != "")&&(name == "PaperTakingMachine")) {
						let deviceId = re.devices[0].deviceId
						that.devices.push({
							name: name,
							deviceId: deviceId,
							services: []
						})
					}
				})
			},
			// 停止搜寻附近的蓝牙外围设备
			stopFindBule() {
				uni.stopBluetoothDevicesDiscovery({
					success(res) {
						console.log(res, '停止搜寻附近的蓝牙外围设备')
					}
				})
			},
			// 连接蓝牙
			onConn(item) {
				uni.showLoading()
				var that = this
				let deviceId = item.deviceId
				uni.createBLEConnection({
					deviceId: deviceId,
					complete(res) {
						uni.hideLoading()
						if (res.errMsg == "createBLEConnection:ok") {
							console.log("连接蓝牙-[" + item.name + "]--成功")
							// 当前连接成功的设备ID
							that.connectDeviceId = deviceId;
							setTimeout(function() {
								uni.showLoading({
									title:"连接中",
								})
								// 获取蓝牙设备的所有服务/特征值
								that.getBLEServices(deviceId)
							}, 2000)
						}else{
							console.log(res,'createBLEConnection')
						}
						
						//连接成功 关闭搜索
						that.stopFindBule()
					},
				})
			},
			// 获取蓝牙设备的所有服务/特征值
			getBLEServices(_deviceId) {
				var that = this;
				let deviceId = _deviceId
				// 获取蓝牙设备的所有服务
				uni.getBLEDeviceServices({
					// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
					deviceId: deviceId,
					complete(res) {
						console.log(res, '获取蓝牙设备' + deviceId + '的所有服务')
						for (var s = 0; s < res.services.length; s++) {
							let serviceId = res.services[s].uuid
							// 获取蓝牙设备指定服务中所有特征值
							uni.getBLEDeviceCharacteristics({
								// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
								deviceId: deviceId,
								// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
								serviceId: serviceId,
								success: (res) => {
									let characteristics = res.characteristics;
 
									console.log(
										`deviceId = [${deviceId}]  serviceId = [${serviceId}]`);
 
									for (let c = 0; c < characteristics.length; c++) {
										if (characteristics[c].properties.write === true) {
											let uuid = characteristics[c].uuid;
											console.log(
												`deviceId = [${deviceId}]  serviceId = [${serviceId}] characteristics=[${uuid}]`
											);
											that.updateDevices(deviceId, serviceId, uuid);
										}
									}
								},
								fail: (err) => {
									uni.showToast({
										title:"连接失败",
										icon:"none"
									})
									console.error(
										`Failed to get characteristics for deviceId = [${deviceId}]  serviceId = [${serviceId}]`,
										err);
								}
							})
						}
					},
					fail(res) {
						console.log(res)
					},
				})
			},
			// 更新设备信息
			updateDevices(deviceId, serviceId, characteristicId) {
				let that = this
				for (let index in that.devices) {
					if (that.devices[index].deviceId === deviceId) {
						that.devices[index].services.push({
							serviceId: serviceId,
							characteristicId: characteristicId
						});
						break;
					}
				}
				uni.showToast({
					title:"连接成功",
					icon:"none"
				})
				console.log(JSON.stringify(that.devices),'成功1');
			}
		}
	}
</script>

<style>
</style>