22.42
<template>
  <view>
    <button @click="startPrinting">打印订单</button>
  </view>
</template>

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

// 定义响应式变量
const deviceId = ref(uni.getStorageSync('deviceId')); // 从存储中获取设备ID
const serviceId = ref(uni.getStorageSync('serviceId')); // 打印机服务ID
const characteristicId = ref(uni.getStorageSync('characteristicId'));  // 特征值ID

// 开始打印的方法
const startPrinting = () => {
  if (!characteristicId.value) {
    console.error('请先获取特征值ID');
    return;
  }

  const orderNumber = '123456'; // 示例订单编号
  const itemName = '麻辣烫'; // 示例商品名称
  const price = '10.00'; // 示例价格

  sendPrintCommand(orderNumber, itemName, price);
};

// 生成打印数据
const generatePrintData = (orderNumber, itemName, price) => {
  try {
    let priceString;

    // 如果价格是负数，则添加负号
    if (price < 0) {
      priceString = (-Math.abs(price)).toFixed(2);
    } else {
      priceString = (price).toFixed(2);
    }

    const bufferLength = orderNumber.length + itemName.length + priceString.length + 7; // 包含额外的控制字符
    const buffer = new ArrayBuffer(bufferLength);
    const dataView = new DataView(buffer);

    // 设置初始化指令
    dataView.setUint8(0, 0x1B);
    dataView.setUint8(1, 0x40);

    // 设置订单编号
    dataView.setUint8(2, 0x1B);
    dataView.setUint8(3, 0x21);
    dataView.setUint8(4, orderNumber.length);
    for (let i = 0; i < orderNumber.length; i++) {
      dataView.setUint8(i + 5, orderNumber.charCodeAt(i));
    }

    // 设置商品名称
    dataView.setUint8(orderNumber.length + 5, 0x1B);
    dataView.setUint8(orderNumber.length + 6, 0x29);
    dataView.setUint8(orderNumber.length + 7, itemName.length);
    for (let i = 0; i < itemName.length; i++) {
      dataView.setUint8(i + orderNumber.length + 8, itemName.charCodeAt(i));
    }

    // 设置价格
    dataView.setUint8(itemName.length + orderNumber.length + 8, 0x1B);
    dataView.setUint8(itemName.length + orderNumber.length + 9, 0x2A);
    dataView.setUint8(itemName.length + orderNumber.length + 10, priceString.length);
    for (let i = 0; i < priceString.length; i++) {
      dataView.setUint8(i + itemName.length + orderNumber.length + 10, priceString.charCodeAt(i));
    }

    return buffer;
  } catch (error) {
    console.error('生成打印数据出错', error);
    return null;
  }
};

// 发送打印指令
const sendPrintCommand = (orderNumber, itemName, price) => {
  try {
    const buffer = generatePrintData(orderNumber, itemName, price);
    if (!buffer) {
      return;
    }

    const dataView = new DataView(buffer);

    uni.writeBLECharacteristicValue({
      deviceId: deviceId.value,
      serviceId: serviceId.value,
      characteristicId: characteristicId.value, // 使用正确的变量名
      value: Array.from(new Uint8Array(buffer)),
      success: (res) => {
        console.log('发送打印指令成功', res);
      },
      fail: (err) => {
        console.error('发送打印指令失败', err);
      }
    });
  } catch (error) {
    console.error('发送打印指令出错', error);
  }
};

// 获取特征值ID
const getCharacteristicId = async () => {
  try {
    await uni.getBLEDeviceCharacteristics({
      deviceId: deviceId.value,
      serviceId: serviceId.value,
      success: (res) => {
        const characteristics = res.characteristics;
        for (let i = 0; i < characteristics.length; i++) {
          // 假设你知道哪个特征值用于打印
          if (characteristics[i].uuid === '已知的特征值UUID') {
            characteristicId.value = characteristics[i].uuid;
            console.log('找到特征值ID:', characteristicId.value);
            // 获取到特征值后发送打印指令
            sendPrintCommand(); // 使用正确的变量名
            break;
          }
        }
      },
      fail: (err) => {
        console.error('获取特征值失败', err);
      }
    });
  } catch (error) {
    console.error('获取特征值出错', error);
  }
};

// 页面加载时尝试连接设备
onMounted(async () => {
  if (deviceId.value && serviceId.value) {
    // 如果已经知道特征值ID，可以直接设置
    if (characteristicId.value) {
      console.log('已知特征值ID:', characteristicId.value);
    } else {
      // 否则，获取特征值ID
      await getCharacteristicId();
    }
  }
});
</script>