1. 程式人生 > 實用技巧 >uni-app 藍芽列印功能

uni-app 藍芽列印功能

uni-app 藍芽列印功能

本章主要講解 uni-app藍芽API的使用,藍芽列印的實現思路,瞭解藍芽在專案中的使用。支援的藍芽印表機裝置:芝佳藍芽印表機、佳博印表機,如其他藍芽印表機,需自己進行除錯。
感謝qihang666提供的程式碼。
原始碼來源以及uni-app藍芽API:

https://github.com/qihang666/BluetoothPrinter
https://uniapp.dcloud.io/api/system/bluetooth?id=openbluetoothadapter

引入tsc.js

簡單得引入到自己所需要得頁面中去,本次我們只要到了標籤模式,他同時還有賬單模式可以選擇

   // 藍芽列印 指令和轉碼
   var tsc = require('@components/gprint/tsc.js')

藍芽適配前期工作

首先我們需要先初始化藍芽模組,在進行搜尋藍芽。在監聽到附近藍芽裝置時,記錄他的名稱和deviceId。

onBlue(e) {
  uni.openBluetoothAdapter({
    success(res) {
      //監聽尋找到新裝置的事件
      that.findDevice()
      //監聽本機藍芽介面卡狀態變化事件
      that.onStatus()
    }
  })
findDevice(){
  console.log("監聽尋找到新裝置的事件---------------")
  //監聽尋找到新裝置的事件
  uni.onBluetoothDeviceFound(function(devices) {
    const {name,deviceId} = devices[0];
    if(name == "未知裝置")return;
    if(!name || !name.length){
      that.devices.push({
        name: name,
        deviceId: deviceId,
        services: []
      })
    }
    that.devices.forEach(e=>{
      if(that.devicesList){
        let b = true;
        that.devicesList.forEach(e1=>{
          if(e.name == e1.name){
            b = false;
          }
        });
        if(b)that.devicesList.push(e);
      }else{
        that.devicesList.push(e);
      }
    });
  }
}
onStatus(){
  uni.getBluetoothAdapterState({
    success: function(res) {
      //本機藍芽開啟時
      if (res.available) {
        //如在正在搜尋裝置,則停止搜尋
        if (res.discovering) {
          uni.stopBluetoothDevicesDiscovery()
        }
        //搜尋藍芽
        //開始搜尋附近的藍芽外圍裝置
        uni.startBluetoothDevicesDiscovery()
      } else {
        console.log('本機藍芽不可用')
      }
    },
  })
}

連線藍芽

搜尋出附近藍芽裝置後,獲取藍芽裝置的deviceId傳入createBLEConnection方法中。在連線藍芽裝置時,我們需要注意的是保證儘量成對的呼叫 createBLEConnection 和 closeBLEConnection 介面。安卓如果多次呼叫 createBLEConnection 建立連線,有可能導致系統持有同一裝置多個連線的例項,導致呼叫 closeBLEConnection 的時候並不能真正的斷開與裝置的連線。
我們將連線成功的藍芽資訊存到currDev中,以便直接連線,無需進行搜尋操作。

onLink(item){
  const {deviceId} = item;
  console.log("連線藍芽---------------" + deviceId);
  //連線低功耗藍芽裝置。
  uni.createBLEConnection({
    deviceId: deviceId,
    complete(res) {
      if (res.errMsg != "createBLEConnection:ok") return
      //連線裝置時,需斷開本機連線裝置
      uni.closeBLEConnection({
        deviceId
      })
      that.connId = deviceId;
      that.currDev = item
      setTimeout(()=> {
        //獲取藍芽裝置所有服務(service)
        that.getBLEServices(deviceId)
      }, 2000)
    }
    //連線成功 關閉搜尋
    uni.stopBluetoothDevicesDiscovery()
    })
}
getBLEServices(deviceId) {
  uni.getBLEDeviceServices({
    // 這裡的 deviceId 需要已經通過 createBLEConnection 與對應裝置建立連結
    deviceId: deviceId,
    complete(res) {
      const {services} = res;
      services.forEach(item=>{
        const {uuid} = item;
        uni.getBLEDeviceCharacteristics({
          // 這裡的 deviceId 需要已經通過 createBLEConnection 與對應裝置建立連結
          deviceId: deviceId,
          // 這裡的 serviceId 需要在 getBLEDeviceServices 介面中獲取
          serviceId: uuid,
          success(res) {
                const {characteristics} = res;
            for(let block of characteristics){
              if(!block.properties.write)return
              for (let index in that.devices) {
                if (that.devices[index].deviceId == deviceId) {
                  that.devices[index].services.push({
                    serviceId: uuid,
                    characteristicId: block.uuid,
                  })
                  break
                }
              }
            }
            uni.setStorage({
              key: 'currDev',
              data: that.devices,
            });
          }
        })
      })
    }
  })
}

列印

列印格式需要自己根據當前裝置的格式來進行設定列印。本章用到的是tsc.js中的form格式。

onPrint(){
  if(this.currDev.length == 0){
    uni.showToast({
      title: '請先連線藍芽印表機',
      duration: 2000
    });
    return
  }
  //標籤模式
  const {deviceId} = this.currDev;
  const {serviceId,characteristicId} = this.currDev.services[0];
  var command = tsc.jpPrinter.createNew();
  //DaYin這個欄位存放我們需要列印的資料
  let DaYin = JSON.parse(JSON.stringify(this.rowsList));
  let Customer = JSON.stringify(this.Customer);
  //列印格式需要根據印表機的特定格式來。在tsc檔案中修改格式。
  DaYin.forEach(e=>{
    command.form(e.ReceSheetNo,`客    戶:${Customer}`,`匹    數:${e.Rolls}`,`坯布品名:${e.GrayID}`,`進倉編號:${e.LotNo}`,`坯布型別:${e.GrayTypeName}`)
    command.setPagePrint()
  })
  //轉碼處理
  this.senBlData(deviceId, serviceId, characteristicId,command.getData())
}
senBlData(deviceId, serviceId, characteristicId,uint8Array) {
  let uint8Buf = Array.from(uint8Array);
  function split_array(datas,size){
    let result = {};
    let j = 0
    for (var i = 0; i < datas.length; i += size) {
      result[j] = datas.slice(i, i + size)
      j++
    }
    return result
  }
  let sendloop = split_array(uint8Buf, 20);
  function realWriteData(sendloop, i) {
    let data = sendloop[i]
    if(typeof(data) == "undefined"){
      return
    }
    let buffer = new ArrayBuffer(data.length)
    let dataView = new DataView(buffer)
    uni.writeBLECharacteristicValue({
      deviceId,
      serviceId,
      characteristicId,
      value: buffer,
      success(res) {
        realWriteData(sendloop, i + 1);
      }
    })
  }
  let i = 0;
  realWriteData(sendloop, i);
},

form條碼格式

// 條形碼和文字合成列印
jpPrinter.form = function (content,text1,text2,text3,text4) {
  data = header + "LEFT" + "\r\n" + "GAR-SENSE" + "\r\n" + barcodeText +
    "BARCODE " + 128 + " " + 1 + " " + 1 + " " + 125 + " " + 125 + " " + 0 + " " + 
    content + "\r\n" + 
        "TEXT " + " " + 12 + " " + 0 + " " + 125 + " " + 180 + " " + text1 + "\r\n" + 
        "TEXT " + " " + 12 + " " + 2 + " " + 125 + " " + 210 + " " + text2 + "\r\n" + 
        "TEXT " + " " + 12 + " " + 2 + " " + 125 + " " + 240 + " " + text3 + "\r\n" + 
        "TEXT " + " " + 12 + " " + 2 + " " + 125 + " " + 270 + " " + text4 + "\r\n" + 
        "FORM" + "\r\n" ; 
        jpPrinter.addCommand(data)
};

總結

整個程式碼都在git上,不需要改變特別多的原始碼。一般改列印藍芽部分的程式碼和列印格式即可。
建議在使用中,封裝下程式碼。
如果這篇文章真的幫助到你們的話,請不要忘記給原作者一顆星。https://github.com/qihang666/BluetoothPrinter