李环宇 發表於 2020-12-30 19:03:00

uni-app 蓝牙打印功能

<h1>uni-app 蓝牙打印功能</h1>
<p>本章主要讲解 uni-app蓝牙API的使用,蓝牙打印的实现思路,了解蓝牙在项目中的使用。支持的蓝牙打印机设备:芝佳蓝牙打印机、佳博打印机,如其他蓝牙打印机,需自己进行调试。<br>感谢qihang666提供的代码。<br>源码来源以及uni-app蓝牙API:</p>
<blockquote>
<p>https://github.com/qihang666/BluetoothPrinter<br>https://uniapp.dcloud.io/api/system/bluetooth?id=openbluetoothadapter</p>

</blockquote>
<h2>引入tsc.js</h2>
<p>简单得引入到自己所需要得页面中去,本次我们只要到了标签模式,他同时还有账单模式可以选择</p>
<pre><code>   // 蓝牙打印 指令和转码
   var tsc = require('@components/gprint/tsc.js')
</code></pre>
<h2>蓝牙适配前期工作</h2>
<p>首先我们需要先初始化蓝牙模块,在进行搜索蓝牙。在监听到附近蓝牙设备时,记录他的名称和deviceId。</p>
<pre><code>onBlue(e) {
uni.openBluetoothAdapter({
    success(res) {
      //监听寻找到新设备的事件
      that.findDevice()
      //监听本机蓝牙适配器状态变化事件
      that.onStatus()
    }
})
</code></pre>
<pre><code>findDevice(){
console.log("监听寻找到新设备的事件---------------")
//监听寻找到新设备的事件
uni.onBluetoothDeviceFound(function(devices) {
    const {name,deviceId} = devices;
    if(name == "未知设备")return;
    if(!name || !name.length){
      that.devices.push({
      name: name,
      deviceId: deviceId,
      services: []
      })
    }
    that.devices.forEach(e=&gt;{
      if(that.devicesList){
      let b = true;
      that.devicesList.forEach(e1=&gt;{
          if(e.name == e1.name){
            b = false;
          }
      });
      if(b)that.devicesList.push(e);
      }else{
      that.devicesList.push(e);
      }
    });
}
}
</code></pre>
<pre><code>onStatus(){
uni.getBluetoothAdapterState({
    success: function(res) {
      //本机蓝牙开启时
      if (res.available) {
      //如在正在搜索设备,则停止搜索
      if (res.discovering) {
          uni.stopBluetoothDevicesDiscovery()
      }
      //搜索蓝牙
      //开始搜寻附近的蓝牙外围设备
      uni.startBluetoothDevicesDiscovery()
      } else {
      console.log('本机蓝牙不可用')
      }
    },
})
}
</code></pre>
<h2>连接蓝牙</h2>
<p>搜索出附近蓝牙设备后,获取蓝牙设备的deviceId传入createBLEConnection方法中。在连接蓝牙设备时,我们需要注意的是保证尽量成对的调用 createBLEConnection 和 closeBLEConnection 接口。安卓如果多次调用 createBLEConnection 创建连接,有可能导致系统持有同一设备多个连接的实例,导致调用 closeBLEConnection 的时候并不能真正的断开与设备的连接。<br>我们将连接成功的蓝牙信息存到currDev中,以便直接连接,无需进行搜索操作。</p>
<pre><code>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(()=&gt; {
      //获取蓝牙设备所有服务(service)
      that.getBLEServices(deviceId)
      }, 2000)
    }
    //连接成功 关闭搜索
    uni.stopBluetoothDevicesDiscovery()
    })
}
</code></pre>
<pre><code>getBLEServices(deviceId) {
uni.getBLEDeviceServices({
    // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
    deviceId: deviceId,
    complete(res) {
      const {services} = res;
      services.forEach(item=&gt;{
      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.deviceId == deviceId) {
                  that.devices.services.push({
                  serviceId: uuid,
                  characteristicId: block.uuid,
                  })
                  break
                }
            }
            }
            uni.setStorage({
            key: 'currDev',
            data: that.devices,
            });
          }
      })
      })
    }
})
}
</code></pre>
<h2>打印</h2>
<p>打印格式需要自己根据当前设备的格式来进行设置打印。本章用到的是tsc.js中的form格式。</p>
<pre><code>onPrint(){
if(this.currDev.length == 0){
    uni.showToast({
      title: '请先连接蓝牙打印机',
      duration: 2000
    });
    return
}
//标签模式
const {deviceId} = this.currDev;
const {serviceId,characteristicId} = this.currDev.services;
var command = tsc.jpPrinter.createNew();
//DaYin这个字段存放我们需要打印的数据
let DaYin = JSON.parse(JSON.stringify(this.rowsList));
let Customer = JSON.stringify(this.Customer);
//打印格式需要根据打印机的特定格式来。在tsc文件中修改格式。
DaYin.forEach(e=&gt;{
    command.form(e.ReceSheetNo,`客    户:${Customer}`,`匹    数:${e.Rolls}`,`坯布品名:${e.GrayID}`,`进仓编号:${e.LotNo}`,`坯布类型:${e.GrayTypeName}`)
    command.setPagePrint()
})
//转码处理
this.senBlData(deviceId, serviceId, characteristicId,command.getData())
}
</code></pre>
<pre><code>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 &lt; datas.length; i += size) {
      result = datas.slice(i, i + size)
      j++
    }
    return result
}
let sendloop = split_array(uint8Buf, 20);
function realWriteData(sendloop, i) {
    let data = sendloop
    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);
},
</code></pre>
<p>form条码格式</p>
<pre><code>// 条形码和文字合成打印
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)
};
</code></pre>
<h2>总结</h2>
<p>整个代码都在git上,不需要改变特别多的源码。一般改打印蓝牙部分的代码和打印格式即可。<br>建议在使用中,封装下代码。<br>如果这篇文章真的帮助到你们的话,请不要忘记给原作者一颗星。https://github.com/qihang666/BluetoothPrinter</p><br><br>
来源:https://www.cnblogs.com/xiondun/p/14213043.html
頁: [1]
查看完整版本: uni-app 蓝牙打印功能