<template>
  <view>
    <button @click="printHelloWorld">打印 Hello World</button>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue';

const deviceId = ref(uni.getStorageSync('deviceId'));
const serviceId = ref(uni.getStorageSync('serviceId')); 
const characteristicId = ref(uni.getStorageSync('characteristicId')); 


function stringToByteArray(str) {
  let bytes = [];
  for (let i = 0; i < str.length; ++i) {
    bytes.push(str.charCodeAt(i));
  }
  return bytes;
}


const sendPrintCommand = (commands) => {
  // setTimeout(async () => {
  //   try {
      uni.writeBLECharacteristicValue({
        deviceId: '86:67:7A:48:06:9C',
        serviceId: 'e7810a71-73ae-499d-8c15-faa9aef0c3f2',
        characteristicId: 'bef8d6c9-9c21-4c9e-b632-bd58c1009f9f',
        value: new Uint8Array(commands), 
      });

  //     console.log('发送打印指令成功');
  //   } catch (error) {
  //     console.error('发送打印指令失败', error);
  //   }
  // }, 1000); // 增加延迟以确保连接稳定
};


const printHelloWorld = async () => {
  if (!characteristicId.value) {
    console.error('请先获取特征值ID');
    return;
  }


  const commands = [
    ...[0x1B, 0x40], 
    ...[0x1B, 0x61, 0x00],
    ...stringToByteArray('Hello World\n'),
    ...[0x1D, 0x56, 0x00] 
  ];

  await sendPrintCommand(commands);
};

// // 页面加载时尝试连接设备
// onMounted(async () => {
//   console.log("UID的值为" + characteristicId.value);

//   // 添加一个检查以确认特征值是否有效
//   try {
//     await uni.readBLECharacteristicValue({
//       deviceId: deviceId.value,
//       serviceId: serviceId.value,
//       characteristicId: characteristicId.value,
//     });

//     console.log('读取特征值信息成功');
//   } catch (error) {
//     console.error('读取特征值信息失败', error);
//   }
// });
</script>