Experience sharing of uni app development 15: Bluetooth printing function of uni app

Time:2021-5-11

Recently, when I was working on the uni app project, I met the need to produce the function of printing files by Bluetooth. I found a tutorial on the Internet, which I can share with you.

Introducing tsc.js

It’s easy to introduce it to the page you need. This time, we only need to go to the tag mode, which also has the billing mode to choose from.

//Bluetooth print command and transcoding
   var tsc = require('@components/gprint/tsc.js')

Preliminary work of Bluetooth adaptation

First of all, we need to initialize the Bluetooth module and search for Bluetooth. When listening to a nearby Bluetooth device, record its name and deviceid.

onBlue(e) {
  uni.openBluetoothAdapter({
    success(res) {
      //Listen for the event of finding a new device
      that.findDevice()
      //Monitor the status change events of local Bluetooth adapter
      that.onStatus()
    }
  })
findDevice(){
  Console.log ("listen for the event of finding a new device --------")
  //Listen for the event of finding a new device
  uni.onBluetoothDeviceFound(function(devices) {
    const {name,deviceId} = devices[0];
    If (name = = unknown device) 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) {
      //When Bluetooth is on
      if (res.available) {
        //If you are searching for a device, stop the search
        if (res.discovering) {
          uni.stopBluetoothDevicesDiscovery()
        }
        //Search Bluetooth
        //Start searching for Bluetooth peripherals nearby
        uni.startBluetoothDevicesDiscovery()
      } else {
        Console.log ('native Bluetooth is not available ')
      }
    },
  })
}

Connect Bluetooth

After searching the nearby Bluetooth devices, obtain the deviceid of the Bluetooth device and transfer it into the createbleconnection method. When connecting Bluetooth devices, we need to pay attention to ensure that we call the createbleconnection and closebleconnection interfaces in pairs as far as possible. If Android calls createbleconnection many times to create a connection, it may cause the system to hold multiple connection instances of the same device, resulting in calling closebleconnection can not really disconnect the connection with the device.
We save the Bluetooth information of successful connection to curdev for direct connection without searching.

onLink(item){
  const {deviceId} = item;
  Console.log ("connect Bluetooth --------" + deviceid ");
  //Connect Low Power Bluetooth devices.
  uni.createBLEConnection({
    deviceId: deviceId,
    complete(res) {
      if (res.errMsg != "createBLEConnection:ok") return
      //When connecting the device, disconnect the device
      uni.closeBLEConnection({
        deviceId
      })
      that.connId = deviceId;
      that.currDev = item
      setTimeout(()=> {
        //Get all services of Bluetooth device
        that.getBLEServices(deviceId)
      }, 2000)
    }
    //Connection closed search successfully
    uni.stopBluetoothDevicesDiscovery()
    })
}
getBLEServices(deviceId) {
  uni.getBLEDeviceServices({
    //The deviceid here needs to have established a link with the corresponding device through the createbleconnection
    deviceId: deviceId,
    complete(res) {
      const {services} = res;
      services.forEach(item=>{
        const {uuid} = item;
        uni.getBLEDeviceCharacteristics({
          //The deviceid here needs to have established a link with the corresponding device through the createbleconnection
          deviceId: deviceId,
          //The serviceid here needs to be obtained from the getbledeviceservices interface
          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,
            });
          }
        })
      })
    }
  })
}

Printing

The printing format needs to be set according to the format of the current device. This chapter uses the form format in tsc.js.

onPrint(){
  if(this.currDev.length == 0){
    uni.showToast({
      Title: 'please connect Bluetooth printer first',
      duration: 2000
    });
    return
  }
  //Label mode
  const {deviceId} = this.currDev;
  const {serviceId,characteristicId} = this.currDev.services[0];
  var command = tsc.jpPrinter.createNew();
  //The Dayin field stores the data we need to print
  let DaYin = JSON.parse(JSON.stringify(this.rowsList));
  let Customer = JSON.stringify(this.Customer);
  //The printing format needs to be changed according to the specific format of the printer. Modify the format in TSC file.
  DaYin.forEach(e=>{
    Command.form (e.recesheetno, ${customer}, ${e.rolls}, ${e.grayid}, ${e.lotno}, ${e.graytypename})
    command.setPagePrint()
  })
  //Transcoding processing
  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 barcode format

//Bar code and text synthesis printing
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)
};

Reproduced in: https://blog.csdn.net/zhanleibo/article/details/103035645