DCloud UniAPP Android 蓝牙连接ESCPOS打印机

 1.蓝牙打印引用文件 btprinter.js

import context from "@/common/context.js" //上下文处理 用来保存绑定的蓝牙设备地址

function searchDevices() {
	var main = plus.android.runtimeMainActivity();
	var IntentFilter = plus.android.importClass('android.content.IntentFilter');
	var BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter");
	var BluetoothDevice = plus.android.importClass("android.bluetooth.BluetoothDevice");
	var BAdapter = BluetoothAdapter.getDefaultAdapter();
	console.log("开始搜索设备");
	var des = BAdapter.getBondedDevices();
	var devices = [];
	console.log(des);
	if (des) {
		var iter = plus.android.invoke(des, "iterator");
		console.log(iter);
		while (plus.android.invoke(iter, "hasNext")) {
			var next = plus.android.invoke(iter, "next");
			var dename = plus.android.invoke(next, "getName");
			console.log(dename);
			var deaddr = plus.android.invoke(next, "getAddress");
			console.log(deaddr);
			var bind = false;
			if (context.printer_mac) {
				console.log(context.printer_mac)
				if (deaddr == context.printer_mac) {
					bind = true
				}
			}
			devices.push({
				addr: deaddr,
				name: dename,
				bind: bind
			})
		}
	}
	return devices;
}

function setPrinter(mac_address) {
	if (mac_address) {
		context.printer_mac = mac_address;
	}
}

function printImg(img) {
	var mac_address = context.printer_mac;
	if (!mac_address) {
		return '蓝牙打印机未连接';
	}
	if (img) {
		var main = plus.android.runtimeMainActivity();
		var BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter");
		var UUID = plus.android.importClass("java.util.UUID");
		var uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
		var BAdapter = BluetoothAdapter.getDefaultAdapter();
		var device = BAdapter.getRemoteDevice(mac_address);
		plus.android.importClass(device);

		var bluetoothSocket = device.createRfcommSocketToServiceRecord(uuid);
		plus.android.importClass(bluetoothSocket);

		if (!bluetoothSocket.isConnected()) {
			console.log('检测到设备未连接,尝试连接....');
			bluetoothSocket.connect();
		}

		console.log('设备已连接');

		if (bluetoothSocket.isConnected()) {
			var outputStream = bluetoothSocket.getOutputStream();
			plus.android.importClass(outputStream);

			var reset = [0x1b, 0x40]
			var print = [0x0a]
			outputStream.write(reset);
			outputStream.flush();
			outputStream.write(print);
			console.log("write img")
			outputStream.write(img);


			outputStream.write(reset);
			//走纸
			outputStream.write(print);
			outputStream.write(print);
			outputStream.flush();
			console.log('end print2')
			device = null //这里关键  
			bluetoothSocket.close(); //必须关闭蓝牙连接否则意外断开的话打印错误 
			console.log('end print3')
			return "1";
		}
	} else {
		return "没有输入打印内容";
	}
}

function print(print_texts) {
	var mac_address = context.printer_mac;
	if (!mac_address) {
		return '蓝牙打印机未连接';
	}
	if (print_texts) {
		var main = plus.android.runtimeMainActivity();
		var BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter");
		var UUID = plus.android.importClass("java.util.UUID");
		var uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
		var BAdapter = BluetoothAdapter.getDefaultAdapter();
		var device = BAdapter.getRemoteDevice(mac_address);
		plus.android.importClass(device);

		var bluetoothSocket = device.createRfcommSocketToServiceRecord(uuid);
		plus.android.importClass(bluetoothSocket);

		if (!bluetoothSocket.isConnected()) {
			console.log('检测到设备未连接,尝试连接....');
			bluetoothSocket.connect();
		}

		console.log('设备已连接');

		if (bluetoothSocket.isConnected()) {
			var outputStream = bluetoothSocket.getOutputStream();
			plus.android.importClass(outputStream);
			var arr = [];
			if (Array.isArray(print_texts)) {
				// console.log("start print Text  lines:" + print_texts.length)
				arr = print_texts;
			} else {
				// console.log("start print one Text")
				arr.push(print_texts.toString());
			}
			console.log("start print arr:" + arr)
			var reset = [0x1b, 0x40]
			var print = [0x0a]
			outputStream.write(reset);
			//一行行的打印
			for (var i = 0; i < arr.length; i++) {
				var datastr = arr[i];
				console.log("start print arr:" + arr[i] + ";" + arr)
				if (Array.isArray(datastr)) {
					//带字体大小定义
					var first = datastr[0];
					if (datastr.length > 2) {
						//行内自定义
						for (var j = 0; j < datastr.length; j += 2) {
							if (datastr.length > j + 1) {
								var tfirst = datastr[j];
								var tstr = datastr[j + 1];
								writeBig(tfirst, tstr, outputStream, false); //false标示不换行
							}
						}
						outputStream.write(print); //全部打完再换行
						console.log('end print')
					} else if (datastr.length > 1) {
						writeBig(first, datastr[1], outputStream, true);
					}
				} else {
					outputStream.write(0x1c);
					outputStream.write(0x21);
					outputStream.write(1);
					var bytes = plus.android.invoke(datastr, 'getBytes', 'gbk');
					outputStream.write(bytes);
					outputStream.write(print);
				}
			}
			//走纸
			outputStream.write(print);
			outputStream.write(print);
			outputStream.flush();
			console.log('end print2')
			device = null //这里关键  
			bluetoothSocket.close(); //必须关闭蓝牙连接否则意外断开的话打印错误 
			console.log('end print3')
			return "1";
		}
	} else {
		return "没有输入打印内容";
	}
}

function writeBig(first, str, outputStream, br) {
	var print = [0x0a]
	outputStream.write(0x1c);
	outputStream.write(0x21);
	outputStream.write(1);
	if (first.toLowerCase() == "n") {
		//正常大小
		var bytes = plus.android.invoke(str, 'getBytes', 'gbk');
		outputStream.write(bytes);
		if (br)
			outputStream.write(print);
	} else if (first.toLowerCase() == "w") {
		//横向加宽
		outputStream.write(0x1c);
		outputStream.write(0x21);
		outputStream.write(4);
		var bytes = plus.android.invoke(str, 'getBytes', 'gbk');
		outputStream.write(bytes);
		if (br)
			outputStream.write(print);
	} else if (first.toLowerCase() == "h") {
		//纵向加高
		outputStream.write(0x1c);
		outputStream.write(0x21);
		outputStream.write(8);
		var bytes = plus.android.invoke(str, 'getBytes', 'gbk');
		outputStream.write(bytes);
		if (br)
			outputStream.write(print);
	} else if (first.toLowerCase() == "wh") {
		//横向加宽并纵向加高
		outputStream.write(0x1c);
		outputStream.write(0x21);
		outputStream.write(12);
		var bytes = plus.android.invoke(str, 'getBytes', 'gbk');
		outputStream.write(bytes);
		if (br)
			outputStream.write(print);
	}

}

const printer = {
	print: print,
	searchDevices: searchDevices,
	setPrinter: setPrinter,
	printImg: printImg
}
module.exports = printer

使用该蓝牙处理类,需要先将设备配对蓝牙打印设备,方法说明如下:

searchDevices() 用于搜索已配对蓝牙设备
setPrinter() 指定已配对设备为当前打印设备
print() 打印文本
printImg() 打印图片

打印文本示例

import printer from "btprinter.js"


//打印单行
var res = printer.print("系统测试页打印");
//打印多行
var arr = [
					"软件测试页打印",
					["w", "aaa加宽"],
					["h", "bbb加高"],
					["wh", "加大"],
					new Date().toDateString(),
					["n", "默认大小", "w", "加宽", "h", "加高", "wh", "加大", "n", "默认大小"]
				];
var res = printer.print(arr); 
if (res == "1") {} else {
    uni.showModal({
    showCancel: false,
    title: "打印测试页失败",
    content: res
    })
}

打印图片

var img=XXXXX //图片点阵灰度数据
printer.printImg(img);

图片点阵数据如何生成,如何打印二维码数据

下一篇:UniAPP Android 蓝牙 ESCPOS打印机 打印图片和二维码

你可能感兴趣的:(移动开发,uni-app,蓝牙)