2025-03-JS-SDK-PDA/common/BluetoothPrint.js

101 lines
3.1 KiB
JavaScript
Raw Permalink Normal View History

2025-03-11 09:45:29 +08:00
var device = null,
BAdapter = null,
BluetoothAdapter = null,
UUID=null,
uuid = null,
main = null,
bluetoothSocket = null;
/*
调用实例
let printStr = '! 0 200 200 640 1\n'
+'PAGE-WIDTH 640\n'
+'PW 848\n'
+'TONE 0\n'
+'SPEED 0\n'
+'GAP-SENSE\n'
+'NO-PACE\n'
+'POSTFEED 0\n'
+'LEFT\n'
+'T 65 1 20 20 物料编码:\n'
+'SETBOLD 2\n'
+'T 65 1 135 20 44-02929-1\n'
+'SETBOLD 0\n'
+'T 65 0 20 50 物料描述:\n'
+'T 65 1 135 50 面板440220101\n'
+'T 65 1 20 80 供应商代码:\n'
+'T 65 1 160 80 S00001 \n'
+'T 65 0 20 110 供应商:\n'
+'T 65 1 135 110 成都京东方科技公司\n'
+'T 65 0 20 140 制造日期:\n'
+'T 65 1 135 140 2023.01.06 00:00\n'
+'T 65 0 20 170 有效期至:\n'
+'T 65 1 135 170 2024.01.06 00:00\n'
+'T 65 0 20 200 批次:\n'
+'T 65 1 135 200 LOT102901\n'
+'T 65 0 20 230 数量:\n'
+'T 65 1 135 230 300\n'
+'T 65 0 20 260 SN\n'
+'T 65 1 135 260 BXX2212150006001\n'
+'SETBOLD 2\n'
+'SETBOLD 0\n'
+'B QR 20 290 M 12 H 4\n'
+'MA,BXX2212150006001\n'
+'ENDQR\n'
+'B 128 2 1 50 50 560 BXX2212150006001\n'
+'T 65 1 200 620 BXX2212150006001\n'
+'FORM\n'
+'PRINT\n';
2025-03-11 17:57:17 +08:00
print("00:21:76:63:88:22",printStr) //mac地址可以在打印机上看;
2025-03-11 09:45:29 +08:00
适用于蓝牙打印机CPLP协议指令集
*/
function print(mac_address,printStr) {
if (!mac_address) {
mui.toast('请选择蓝牙打印机');
return false;
}
2025-03-11 17:57:17 +08:00
2025-03-11 09:45:29 +08:00
main = plus.android.runtimeMainActivity();
BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter");
UUID = plus.android.importClass("java.util.UUID");
uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
2025-03-11 17:57:17 +08:00
BAdapter = BluetoothAdapter.getDefaultAdapter()
device = BAdapter.getRemoteDevice(mac_address)
plus.android.importClass(device);
bluetoothSocket = device.createInsecureRfcommSocketToServiceRecord(uuid);
2025-03-11 09:45:29 +08:00
plus.android.importClass(bluetoothSocket);
if (!bluetoothSocket.isConnected()) {
console.log('检测到设备未连接,尝试连接....');
2025-03-11 17:57:17 +08:00
bluetoothSocket.connect();
2025-03-11 09:45:29 +08:00
}
2025-03-11 17:57:17 +08:00
if (bluetoothSocket.isConnected()) {
console.log('设备已连接');
}
2025-03-11 09:45:29 +08:00
if (bluetoothSocket.isConnected()) {
var outputStream = bluetoothSocket.getOutputStream();
2025-03-11 17:57:17 +08:00
plus.android.importClass(outputStream);
2025-03-11 09:45:29 +08:00
var bytes = plus.android.invoke(printStr, 'getBytes', 'gbk');
2025-03-11 17:57:17 +08:00
console.log('打印的标签是'+printStr);
2025-03-11 09:45:29 +08:00
outputStream.write(bytes);
outputStream.flush();
device = null //这里关键
bluetoothSocket.close(); //必须关闭蓝牙连接否则意外断开的话打印错误
return true;
}
else
{
return false;
}
}
export {
print,
//getDefaultPrinterIndex
}