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