flutter安卓USB打印机ESC/POS指令
0. 依赖
- esc_pos_utils_plus
- flutter_usb_printer: https://github.com/kechankrisna/flutter_usb_printer
1. 添加安卓权限
<uses-permission android:name="android.permission.USB_PERMISSION"/>
2. USB列表
private fun getPrinterDeviceList(): ArrayList<HashMap<String, String?>> {
val usbDevices = adapter!!.getDeviceList()
for (usbDevice in usbDevices) {
if (usbDevice.getInterface(0).interfaceClass == 7) {}
...
3. 使用InterfaceClass区分打印机设备
* 表11: USB协议定义的接口类别(bInterfaceClass)
* 值(十六进制) 类别
* -----------------------------------
* 0x01 音频类
* 0x02 CDC控制类
* 0x03 人机接口类(HID)
* 0x05 物理类
* 0x06 图像类
* 0x07 打印机类
* 0x08 大数据存储类
* 0x09 集线器类
* 0x0A CDC数据类
* 0x0B 智能卡类
* 0x0D 安全类
* 0xDC 诊断设备类
* 0xE0 无线控制器类
* 0xFE 特定应用类(包括红外的桥接器等)
* 0xFF 厂商定义的设备
4. 连接
printerUtil.connect(device);
5. 打印命令
var tmp = await checkoutTicket();
var data = Uint8List.fromList(tmp);
await printerUtil.write(data);
Future<List<int>> checkoutTicket() async {
final profile = await CapabilityProfile.load();
final generator = Generator(PaperSize.mm58, profile);
List<int> bytes = [];
bytes += generator.setGlobalCodeTable("utf8");
bytes += generator.text("结算单",
containsChinese: true,
styles: const PosStyles(
bold: true,
fontType: PosFontType.fontB,
width: PosTextSize.size2,
height: PosTextSize.size2,
align: PosAlign.center));
}
fun write(bytes: ByteArray): Boolean {
Log.v(LOG_TAG, "start to print raw data $bytes")
val isConnected = openConnection()
return if (isConnected) {
Log.v(LOG_TAG, "Connected to device")
Thread {
val b = mUsbDeviceConnection!!.bulkTransfer(mEndPoint, bytes, bytes.size, 100000)
Log.i(LOG_TAG, "Return Status: $b")
}.start()
true
} else {
Log.v(LOG_TAG, "failed to connected to device")
false
}
}