wtt
2025-12-31 96973dca40a1815e9727160e6b2e6dee839b9f8d
components/blueToothConnector/blueToothConnector.vue
@@ -6,7 +6,7 @@
            <view style="width: 5rem;">连接设备: </view>
            <view v-if="$printer.isConnected() === false">无</view>
            <view v-else="$printer.isConnected() === true"
            style="flex: 1;display: inline-flex;flex-direction: row;justify-content: space-between;">
               style="flex: 1;display: inline-flex;flex-direction: row;justify-content: space-between;">
               <view>{{ $printer.connectedDevice().name }}</view>
               <view>{{ $printer.connectedDevice().address }}</view>
            </view>
@@ -18,19 +18,24 @@
         <button class="btn-d" @click="closeBluetooth()">断开连接</button>
      </view>
      <!-- 设备列表 -->
      <view v-for="(device, index) in discoveredDevices" :key="device.address">
         <uni-card :title="device.name" :extra="connectedDeviceId === device.address?'已连接':'未连接'"
            style="margin: 10px;">
            <view class="operation-zone">
               <button class="op1" size="mini" plain @click="connectBT(device)">连接设备</button>
            </view>
         </uni-card>
      </view>
      <scroll-view scroll-y="true" style="height: calc(80vh - 8rem);">
         <view v-for="(device, index) in discoveredDevices" :key="device.address">
            <uni-card :title="device.name" :extra="connectedDeviceId === device.address?'已连接':'未连接'"
               style="margin: 10px;">
               <view class="operation-zone">
                  <button class="op1" size="mini" plain @click="connectBT(device)">连接设备</button>
               </view>
            </uni-card>
         </view>
      </scroll-view>
   </view>
</template>
<script>
   import bluetoothTool from '@/plugins/BluetoothTool.js'
    import printerMeta from "../../static/json/printerMeta.json";
   import {
      CommonUtils
   } from '../../utils/common';
   import permission from '@/plugins/permission.js'
   import {
      InputImage
@@ -42,13 +47,19 @@
      FakeConnectedDevice,
      WriteOptions,
   } from '@psdk/frame-father';
import { getAddress } from '../../utils/auth';
   import {
      getAddress
   } from '../../utils/auth';
   import blueToothTool from '@/plugins/BluetoothTool.js';
import { nextTick } from "vue";
   export default {
      name: "blueToothConnector",
      name: "blueToothPrinterConnector",
      data() {
         return {
            discoveredDevices: [], // 查询到的设备
            connectedDeviceId: "",
            readSuccess: false,
            clock: null,
         };
      },
      methods: {
@@ -82,16 +93,12 @@
                  console.log('start discovery devices');
                  this.discoveredDevices = [];
                  console.log(res)
                  bluetoothTool.discoveryNewDevice();
                  blueToothTool.discoveryNewDevice();
               },
               fail: async (e) => {
                  console.error(e)
                  switch (e.code) {
                     case "10009":
                        this.showToast("此设备不支持设备搜索功能!");
                        break;
                     default:
                        console.error(e);
                  if(e.errCode == 10009) {
                     this.showToast('此设备不支持设备搜索功能!');
                  }
               }
            })
@@ -117,24 +124,24 @@
            uni.showLoading({
               title: '连接中'
            });
            bluetoothTool.connDevice(device.address, (result) => {
            blueToothTool.connDevice(device.address, (result) => {
               console.log("设备MAC地址: ", device.address)
               console.log("printer:",vm.$printer._connectedDevice)
               console.log("printer:", vm.$printer._connectedDevice)
               uni.hideLoading()
               if (result) {
                  //    // console.log(result);
                  bluetoothTool.cancelDiscovery();
                  blueToothTool.cancelDiscovery();
                  // console.log(vm.$printer)
                  vm.$printer.init(new FakeConnectedDevice());
                  vm.connectedDeviceId = device.address;
                  vm.$printer._connectedDevice.address = device.address
                  vm.$printer._connectedDevice.name = device.name
                  console.log("printer:",vm.$printer._connectedDevice)
                  console.log("printer:", vm.$printer._connectedDevice)
                  uni.showToast({
                     icon: 'none',
                     title: '连接成功'
                  })
               } else {
                  uni.showToast({
                     icon: 'none',
@@ -145,44 +152,16 @@
         },
         stopSearchBT() {
            console.log("停止搜寻附近的蓝牙外围设备---------------")
            bluetoothTool.cancelDiscovery();
            blueToothTool.cancelDiscovery();
         },
         closeBluetooth() {
            console.log("停止蓝牙连接")
            const vm = this;
            if (vm.connectedDeviceId != '') {
               bluetoothTool.closeBtSocket();
               blueToothTool.closeBtSocket();
               vm.connectedDeviceId = "";
               vm.$printer._connectedDevice = null
            }
         },
         labelPrint() {
            // 打印
            // 检查蓝牙连接
            let btStatus = bluetoothTool.getBluetoothStatus()
            if (btStatus != true) {
               this.showToast("蓝牙连接异常!")
               return
            }
            // 检查是否连接设备
            let pairedDevices = bluetoothTool.getPairedDevices()
            if (pairedDevices.length < 1) {
               this.showToast("无设备连接!")
               return
            }
            // 检查表单项是否有空值
            for (var key in this.hform) {
               if (this.hform[key] == "") {
                  // todo 提示表单项不能为空
                  this.showToast("表单不能有空值!")
                  return
               }
            }
            this.printWrite()
         },
         showToast(msg, status = "none") {
@@ -192,7 +171,60 @@
               duration: 2000
            });
         },
         ///转成安卓有符号的
         async checkReadSuccess(count) {
            // 批量插入时,如果前一次发送成功,则清除前一次的时钟
            if (this.clock != null) {
               this.clock.stop();
               this.clock = null;
            }
            let that = this
            return new Promise((resolve, reject) => {
               let currentCount = 0;
               that.clock = new CommonUtils.timeClock(() => {
                  console.log(that.readSuccess)
                  currentCount++;
                  if (that.readSuccess == true) {
                     that.clock.stop();
                     resolve(true);
                  } else if (currentCount >= count) {
                     that.clock.stop();
                     reject(new Error('读取超时'));
                  }
               }, printerMeta['timeoutPerMillSecond']);
               // 启动时钟
               that.clock.start();
            });
         },
         async sendMessage(cmd) {
            cmd = Array.from(this.uint8ArrayToSignedArray(cmd))
            uni.showLoading({
               title: "发送中..."
            })
            // console.log("msg: " + cmd);
            let that = this
            return new Promise((resolve, reject) => {
               const result = blueToothTool.sendByteData(cmd);
               if (!result) {
                        this.clock.stop();
                  reject("发送失败,请重试...")
               }
               that.checkReadSuccess(printerMeta['timeoutCount'])
                  .then((res) => {
                     if (res === true) {
                        resolve(true)
                     }
                  })
                  .catch((err) => {
                     this.clock.stop();
                     reject('设备异常,请检查设备状态...')
                  })
                  .finally(() => {
                     that.readSuccess = false
                  })
            })
         },
         uint8ArrayToSignedArray(uint8Array) {
            let signedArray = new Array(uint8Array.length);
            for (let i = 0; i < uint8Array.length; i++) {
@@ -204,105 +236,39 @@
            }
            return signedArray;
         },
         async printWrite(type = "cpcl") {
            const vm = this;
            console.log("开始打印------------------")
            switch (type) {
               case "cpcl":
                  await vm.writeCpclModel();
                  break;
            }
         },
         async writeCpclModel() {
            const vm = this;
            try {
               const cpcl = await vm.$printer.cpcl().clear()
                  .page(new CPage({
                     width: 608,
                     height: 260
                  }))
                  .text(new CText({
                     x: 54,
                     y: 40,
                     content: "物料代码: " + vm.hform.HMaterCode,
                     font: CFont.TSS24
                  }))
                  .text(new CText({
                     x: 54,
                     y: 80,
                     content: "名    称: " + vm.hform.HMaterName,
                     font: CFont.TSS24
                  }))
                  .text(new CText({
                     x: 54,
                     y: 120,
                     content: "规格型号: " + vm.hform.HMaterType,
                     font: CFont.TSS24
                  }))
                  .text(new CText({
                     x: 54,
                     y: 160,
                     content: "数    量: " + vm.hform.HNumber,
                     font: CFont.TSS24
                  }))
                  .bar(new CBar({
                     x: 120,
                     y: 200,
                     lineWidth: 1,
                     height: 80,
                     content: vm.hform.HBarCode,
                     codeRotation: CCodeRotation.ROTATION_0,
                     codeType: CCodeType.CODE128
                  }))
                  .form(new CForm()) //标签纸需要加定位指令
                  .print();
               console.log(cpcl.command().string());
               var binary = cpcl.command().binary();
               await this.sendMessage(Array.from(this.uint8ArrayToSignedArray(binary)));
            } catch (e) {
               console.error(e);
               uni.showToast({
                  title: '失败',
               });
            }
         },
         async sendMessage(cmd) {
            console.log(cmd);
            const result = bluetoothTool.sendByteData(cmd);
            uni.showToast({
               icon: 'none',
               title: result ? '发送成功!' : '发送失败...'
            })
         },
      },
      async mounted() {
         //#ifdef APP-PLUS
         // 蓝牙
         console.log("蓝牙初始化")
         bluetoothTool.init({
         blueToothTool.init({
            listenBTStatusCallback: (state) => {
               if (state == 'STATE_ON') {
                  console.log(state);
               }
               if (state == 'STATE_OFF') {
                  console.log(state);
                  this.closeBluetooth()
               }
            },
            discoveryDeviceCallback: this.onDevice,
            discoveryFinishedCallback: function() {
               console.log("搜索完成");
            },
            readDataCallback: function(dataByteArr) {
               /* if(that.receiveDataArr.length >= 200) {
                  that.receiveDataArr = [];
               }
               that.receiveDataArr.push.apply(that.receiveDataArr, dataByteArr); */
            readDataCallback: (dataByteArr) => {
               // if(that.receiveDataArr.length >= 200) {
               //    that.receiveDataArr = [];
               // }
               // that.receiveDataArr.push.apply(that.receiveDataArr, dataByteArr);
               this.readSuccess = true
               console.log("读取完成" + dataByteArr);
            },
            connExceptionCallback: function(e) {
               console.log(e);
            }
         });
         console.log(this.$printer)
         if(this.$printer.isConnected()){
         if (this.$printer.isConnected()) {
            this.connectedDeviceId = this.$printer.connectedDevice().address
         }
         //#endif