<template>
</template>

<script>
	export default {
	  data() {
	    return {
	      devices: [], // 存储蓝牙设备列表
	      connectedDeviceId: '', // 已连接蓝牙设备的ID
	      connectedUUID: '', // 已连接蓝牙设备的服务UUID
	      socket: null, // 蓝牙串口
	    };
	  },
	  methods: {
	    // 开始搜索蓝牙设备
	    startBluetoothDevicesDiscovery() {
	      uni.openBluetoothAdapter({
	        success: (res) => {
	          uni.startBluetoothDevicesDiscovery({
	            success: (res) => {
	              console.log('搜索设备成功', res);
	              this.discoverDevices();
	            },
	            fail: (err) => {
	              console.log('搜索设备失败', err);
	            }
	          });
	        },
	        fail: (err) => {
	          console.log('打开蓝牙适配器失败', err);
	        }
	      });
	    },
	 
	    // 连续搜索蓝牙设备
	    discoverDevices() {
	      uni.onBluetoothDeviceFound((devices) => {
	        console.log('发现新蓝牙设备', devices);
	        this.devices = this.devices.concat(devices);
	      });
	    },
	 
	    // 停止搜索蓝牙设备
	    stopBluetoothDevicesDiscovery() {
	      uni.stopBluetoothDevicesDiscovery({
	        success: (res) => {
	          console.log('停止搜索蓝牙设备成功', res);
	        },
	        fail: (err) => {
	          console.log('停止搜索蓝牙设备失败', err);
	        }
	      });
	    },
	 
	    // 连接蓝牙设备
	    connectBLEDevice(deviceId, uuid) {
	      this.connectedDeviceId = deviceId;
	      this.connectedUUID = uuid;
	      uni.createBLEConnection({
	        deviceId: deviceId,
	        success: (res) => {
	          console.log('连接蓝牙设备成功', res);
	          this.writeBLEData();
	        },
	        fail: (err) => {
	          console.log('连接蓝牙设备失败', err);
	        }
	      });
	    },
	 
	    // 向蓝牙设备发送数据
	    writeBLEData() {
	      // 假设你已经准备好了要发送的数据buffer
	      const buffer = new ArrayBuffer(1); // 示例中的数据长度为1字节
	      uni.writeBLECharacteristicValue({
	        deviceId: this.connectedDeviceId,
	        serviceId: this.connectedUUID,
	        characteristicId: 'characteristicId', // 你的特征ID
	        value: buffer,
	        success: (res) => {
	          console.log('发送数据成功', res);
	        },
	        fail: (err) => {
	          console.log('发送数据失败', err);
	        }
	      });
	    }
	  },
	  onUnload() {
	    // 页面销毁时，确保停止蓝牙设备搜索，关闭连接
	    this.stopBluetoothDevicesDiscovery();
	    if (this.connectedDeviceId) {
	      uni.closeBLEConnection({
	        deviceId: this.connectedDeviceId,
	        success: (res) => {
	          console.log('关闭蓝牙连接成功', res);
	        },
	        fail: (err) => {
	          console.log('关闭蓝牙连接失败', err);
	        }
	      });
	    }
	  }
	};
</script>

<style>
</style>