This is the second day of my participation in the Gwen ChallengeSee more,challenge
Uni-app Bluetooth printing function
This chapter mainly explains the use of UNI-App Bluetooth API, the implementation ideas of Bluetooth printing, and the use of Bluetooth in the project. Supported Bluetooth printer equipment: Zhijia Bluetooth printer, Jiabo printer, such as other Bluetooth printers, you need to debug by yourself. Thanks qihang666 for the code. Uni-app Bluetooth API
Github.com/qihang666/B… Uniapp. Dcloud. IO/API/system /…
The introduction of TSC. Js
Simple to introduce into their own needs to the page, this time we just to the TAB mode, he also has the billing mode to choose
Var TSC = require('@components/gprint/tsc.js')Copy the code
Bluetooth adapter preliminary work
First of all, we need to initialize the Bluetooth module and search for Bluetooth. Record his name and deviceId when he listens to a nearby Bluetooth device.
OnBlue (e) {uni.openbluetoothAdapter ({success(res) {// Listen for the event that a new device was found that.findDevice() // Listen for the event that the status of the native Bluetooth adapter changed that.onStatus() }})Copy the code
FindDevice () {the console. The log (" event monitor to find new equipment -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- ") / / listen to find new equipment event 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); }}); }}Copy the code
onStatus(){ uni.getBluetoothAdapterState({ success: Function (res) {// If (res.available) {// If (res.available) {// If (res.available) { To stop search the if (res) discovering) {uni. StopBluetoothDevicesDiscovery ()} / bluetooth / / / search started to search for nearby bluetooth peripheral devices Uni. StartBluetoothDevicesDiscovery ()} else {the console. The log (' native bluetooth unavailable ')}},})}Copy the code
Connect the bluetooth
After searching for nearby Bluetooth devices, pass the deviceId of the device into the createBLEConnection method. When connecting to bluetooth devices, we need to ensure that the createBLEConnection and closeBLEConnection interfaces are called in pairs as much as possible. If You call createBLEConnection multiple times to create a connection, the system may have multiple connection instances of the same device. As a result, when you call closeBLEConnection, you will not be able to disconnect the device. We saved the bluetooth information of successful connection in currDev for direct connection without searching operation.
onLink(item){ const {deviceId} = item; Console. log(" Connect bluetooth ---------------" + deviceId); // Connect a low-power Bluetooth device. uni.createBLEConnection({ deviceId: deviceId, complete(res) { if (res.errMsg ! CloseBLEConnection ({deviceId}) that. ConnId = deviceId; uni. CloseBLEConnection ({deviceId}) that. That. CurrDev = item setTimeout(()=> {getBLEServices(deviceId)}, 2000)} / / connection successfully closed search uni stopBluetoothDevicesDiscovery ()})}Copy the code
GetBLEServices (deviceId) {uni.getbleDeviceservices ({createBLEConnection: deviceId) {uni.getbleDeviceservices ({createBLEConnection: deviceId) {uni.getbleDeviceservices ({createBLEConnection: deviceId) {uni. deviceId, complete(res) { const {services} = res; services.forEach(item=>{ const {uuid} = item; Uni. GetBLEDeviceCharacteristics ({/ / deviceId need here has been through createBLEConnection establish links with the corresponding equipment deviceId: DeviceId, // The serviceId needs to be retrieved from the getBLEDeviceServices interface: 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, }); }})})}})}Copy the code
The print 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} // tag pattern const {deviceId} = this.currDev; const {serviceId,characteristicId} = this.currDev.services[0]; var command = tsc.jpPrinter.createNew(); Parse (json.stringify (this.rowslist)); DaYin = json.parse (json.stringify (this.rowslist)); let Customer = JSON.stringify(this.Customer); // The print format depends on the printer's specific format. Modify the format in the TSC file. Dayin. forEach(e=>{command. Form (e.recesheetno, 'Customer :${Customer}', 'PIP Number: ${" e.R olls} `, ` fabric name: ${um participant rayID} `, ` into the warehouse number: ${e.L otNo} `, ` fabric types: ${um participant rayTypeName} `) command. SetPagePrint ()}) / / transcoding processing this.senBlData(deviceId, serviceId, characteristicId,command.getData()) }Copy the 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 < 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);
},
Copy the code
Form Barcode format
/ / print bar code and text synthesis 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) };Copy the code
conclusion
The entire code is in Git, and you don’t need to change much source code. Generally, change the code and print format of bluetooth part. It is recommended to encapsulate the code in use. If this article really helps you, please don’t forget to give the original author one star. Github.com/qihang666/B…