The printer uses USB connection and ESC/POS commands, I can send commands with BulkTransfer:
val usbManager = context.getSystemService(Context.USB_SERVICE) as UsbManager
val device: UsbDevice? =
usbManager.deviceList.values.firstOrNull { it.vendorId == vid && it.productId == pid }
if (device != null) {
var textToPrint = text("Prueba")
textToPrint = appendCommands(textToPrint, printAndNLinesFeedForward("6"))
textToPrint = appendCommands(textToPrint, paperCut("0"))
val connection: UsbDeviceConnection = usbManager.openDevice(device)
connection.claimInterface(device.getInterface(0), true)
val con = connection.bulkTransfer(
device.getInterface(0).getEndpoint(0),
textToPrint.toByteArray(),
textToPrint.size,
0
)
println(con)
connection.releaseInterface(device.getInterface(0))
connection.close()
} else {
Log.e("errores", "device=null")
}
textToprint has the commands to send, appendCommands is a function that add commands and returns an array with the added command
private fun appendCommands(byteArray1: UByteArray, byteArray2: UByteArray): UByteArray {
var byteArray = byteArray1
for (byte in byteArray2) {
byteArray += byte
}
return byteArray
}
private fun text(text: String): UByteArray {
val charset = Charsets.UTF_8
return text.toByteArray(charset).toUByteArray()
}
private fun printAndNLinesFeedForward(linesToFeed: String): UByteArray {
return ubyteArrayOf("1B".hexAsUByte, "64".hexAsUByte, linesToFeed.hexAsUByte)
}
private fun paperCut(typeCut: String): UByteArray {
return ubyteArrayOf("1D".hexAsUByte, "56".hexAsUByte, typeCut.hexAsUByte)
}
this those commands in each function have hexadecimal codes provided by the printer manual
However, I don't know how to listen to the printer's response in the event that it doesn't have paper, for example, because the functions that I issue to listen do not return anything or I don't know where to pick it up
private fun receiveData(pid: Int, vid: Int, context: Context) {
val usbManager = context.getSystemService(Context.USB_SERVICE) as UsbManager
val device: UsbDevice? =
usbManager.deviceList.values.firstOrNull { it.vendorId == vid && it.productId == pid }
if (device != null) {
val buffer = byteArrayOf("1D".hexAsByte, "72".hexAsByte, "1".hexAsByte)
val connection: UsbDeviceConnection = usbManager.openDevice(device)
connection.claimInterface(device.getInterface(0), true)
connection.bulkTransfer(
device.getInterface(0).getEndpoint(1),
buffer,
buffer.size,
0
)
connection.releaseInterface(device.getInterface(0))
connection.close()
} else {
Log.e("errores", "device=null")
}
}
here i connect another endpoint, this endpoint is to receive data, and the command in buffer is this:
I dont know how to receive code errors from the printer