Skip to content

Label mode printing for Sunmi devices with integrated printer #66

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions pretixprint/app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,7 @@ dependencies {

implementation 'com.github.anastaciocintra:escpos-coffee:4.0.2'
implementation 'com.sunmi:printerlibrary:1.0.13'
implementation 'com.sunmi:printerx:1.0.12' // Documentation: https://developer.sunmi.com/docs/en-US/xeghjk491/maceghjk502

// Evolis SDK
fullImplementation(project(':EvolisSDK')) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,6 @@ val protocols = listOf<ByteProtocolInterface<*>>(
GraphicePOSPrintXML(),
BrotherRaster(),
PNG(),
SunmiPrinterXLabels(),
ESCLabel(),
)
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ val protocols = listOf<ByteProtocolInterface<*>>(
BrotherRaster(),
EvolisDirect(),
PNG(),
SunmiPrinterXLabels(),
LinkOSCard(),
LinkOS(),
ESCLabel()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import android.content.Context
import android.hardware.usb.UsbDevice
import android.hardware.usb.UsbManager
import com.sunmi.peripheral.printer.SunmiPrinterService
import com.sunmi.printerx.PrinterSdk
import eu.pretix.pretixprint.connections.ConnectionType
import eu.pretix.pretixprint.ui.SetupFragment
import java8.util.concurrent.CompletableFuture
Expand Down Expand Up @@ -38,6 +39,10 @@ interface SunmiByteProtocol<T> : ByteProtocolInterface<T> {
fun sendSunmi(printerService: SunmiPrinterService, pages: List<CompletableFuture<ByteArray>>, conf: Map<String, String>, type: String)
}

interface SunmiPrinterXByteProtocol<T> : ByteProtocolInterface<T> {
fun sendSunmi(printer: PrinterSdk.Printer, pages: List<CompletableFuture<ByteArray>>, conf: Map<String, String>, type: String)
}

fun getProtoClass(proto: String): ByteProtocolInterface<Any> {
for (p in protocols) {
if (p.identifier == proto) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
package eu.pretix.pretixprint.byteprotocols

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.util.Log
import com.sunmi.printerx.PrinterSdk
import com.sunmi.printerx.api.PrintResult
import com.sunmi.printerx.enums.ImageAlgorithm
import com.sunmi.printerx.style.BaseStyle
import com.sunmi.printerx.style.BitmapStyle
import eu.pretix.pretixprint.R
import eu.pretix.pretixprint.connections.ConnectionType
import eu.pretix.pretixprint.connections.SunmiInternalConnection
import eu.pretix.pretixprint.ui.SetupFragment
import eu.pretix.pretixprint.ui.SunmiPrinterXLabelsSettingsFragment
import java8.util.concurrent.CompletableFuture
import java.io.ByteArrayOutputStream
import java.util.concurrent.TimeUnit

// Documentation: https://developer.sunmi.com/docs/en-US/xeghjk491/mameghjk546
class SunmiPrinterXLabels : SunmiPrinterXByteProtocol<Bitmap> {
override val identifier = "SunmiPrinterXLabels"
override val nameResource = R.string.protocol_sunmi_printerx_labels
override val defaultDPI = 300 // Printer is natively 203dpi, but prints look better when rendered at 300dpi
override val demopage = "demopage_8in_3.25in.pdf"

override fun allowedForUsecase(type: String): Boolean {
return type == "badge"
}

override fun allowedForConnection(type: ConnectionType): Boolean {
return type is SunmiInternalConnection
}

override fun convertPageToBytes(img: Bitmap, isLastPage: Boolean, previousPage: Bitmap?, conf: Map<String, String>, type: String): ByteArray {
val stream = ByteArrayOutputStream()
img.compress(Bitmap.CompressFormat.PNG, 100, stream)
val byteArray = stream.toByteArray()
img.recycle()
return byteArray
}

override fun sendSunmi(printer: PrinterSdk.Printer, pages: List<CompletableFuture<ByteArray>>, conf: Map<String, String>, type: String) {
for (f in pages) {
Log.i("PrintService", "Waiting for page to be converted")
val page = f.get(60, TimeUnit.SECONDS)
Log.i("PrintService", "Page ready, sending page")
val bmp = BitmapFactory.decodeByteArray(page, 0, page.size)

// Get configuration parameters
val printWidth = (conf.get("hardware_${type}printer_sunmiprinterxlabels_print_width")!!).toInt()
val rollWidth = (conf.get("hardware_${type}printer_sunmiprinterxlabels_roll_width")!!).toInt()
val labelWidth = (conf.get("hardware_${type}printer_sunmiprinterxlabels_label_width")!!).toInt()
val labelHeight = (conf.get("hardware_${type}printer_sunmiprinterxlabels_label_height")!!).toInt()

// Calculate canvas
val totalPrinterMargin = if (printWidth == 58) 10 else 8
val totalLinerMargin = rollWidth - labelWidth

val totalHorizontalMargin = maxOf(totalPrinterMargin, totalLinerMargin)


val imageWidth = (rollWidth - totalHorizontalMargin) * 8 // 8px per mm
val imageHeight = labelHeight * 8

val x0 = (totalHorizontalMargin - totalPrinterMargin) * (8/2)
val y0 = 0

val canvasWidth = x0 + imageWidth
val canvasHeight = imageHeight

// Print
printer.canvasApi().run {
initCanvas(BaseStyle.getStyle().setWidth(canvasWidth).setHeight(canvasHeight))
renderBitmap(bmp, BitmapStyle.getStyle().setPosX(x0).setPosX(y0).setWidth(imageWidth).setHeight(imageHeight).setAlgorithm(ImageAlgorithm.BINARIZATION))
printCanvas(1, object : PrintResult() {
override fun onResult(resultCode: Int, message: String?) {
if (resultCode == 0) {
// Print successful
} else {
println(printer.queryApi()?.status)
}
}

})
}


}
}

override fun createSettingsFragment(): SetupFragment {
return SunmiPrinterXLabelsSettingsFragment()
}

override fun inputClass(): Class<Bitmap> {
return Bitmap::class.java
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import eu.pretix.pretixprint.R
import eu.pretix.pretixprint.byteprotocols.CustomByteProtocol
import eu.pretix.pretixprint.byteprotocols.StreamByteProtocol
import eu.pretix.pretixprint.byteprotocols.SunmiByteProtocol
import eu.pretix.pretixprint.byteprotocols.SunmiPrinterXByteProtocol
import eu.pretix.pretixprint.byteprotocols.getProtoClass
import eu.pretix.pretixprint.print.lockManager
import eu.pretix.pretixprint.renderers.renderPages
Expand Down Expand Up @@ -119,6 +120,10 @@ class BluetoothConnection : ConnectionType {
is SunmiByteProtocol -> {
throw PrintException("Unsupported combination")
}

is SunmiPrinterXByteProtocol -> {
throw PrintException("Unsupported combination")
}
}
}
} catch (e: TimeoutException) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,9 @@ class NetworkConnection : ConnectionType {
is SunmiByteProtocol -> {
throw PrintException("Unsupported combination")
}
is SunmiPrinterXByteProtocol -> {
throw PrintException("Unsupported combination")
}
}
}
} catch (e: TimeoutException) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,12 @@ package eu.pretix.pretixprint.connections
import android.content.Context
import android.os.Build
import android.util.Log
import androidx.preference.PreferenceManager
import com.sunmi.peripheral.printer.InnerPrinterCallback
import com.sunmi.peripheral.printer.InnerPrinterManager
import com.sunmi.peripheral.printer.InnerResultCallback
import com.sunmi.peripheral.printer.SunmiPrinterService
import com.sunmi.printerx.PrinterSdk
import eu.pretix.pretixprint.PrintException
import eu.pretix.pretixprint.R
import eu.pretix.pretixprint.byteprotocols.*
Expand All @@ -31,37 +33,42 @@ class SunmiInternalConnection : ConnectionType {
return Build.BRAND.uppercase() == "SUNMI"
}

override fun print(tmpfile: File, numPages: Int, context: Context, type: String, settings: Map<String, String>?) {
override fun print(tmpfile: File, numPages: Int, context: Context, useCase: String, settings: Map<String, String>?) {
val conf = settings?.toMutableMap() ?: mutableMapOf()
for (entry in PreferenceManager.getDefaultSharedPreferences(context).all.iterator()) {
if (!conf.containsKey(entry.key)) {
conf[entry.key] = entry.value.toString()
}
}

val future = CompletableFuture<Void>()
val baos = ByteArrayOutputStream()
val bais = ByteArrayInputStream(byteArrayOf())

val mode = if (type == "receipt") "ESC/POS" else "PNG"
val mode = conf.get("hardware_${useCase}printer_mode")!!
val proto = getProtoClass(mode)
val dpi = Integer.valueOf(conf.get("hardware_${type}printer_dpi")
val dpi = Integer.valueOf(conf.get("hardware_${useCase}printer_dpi")
?: proto.defaultDPI.toString()).toFloat()
val rotation = Integer.valueOf(conf.get("hardware_${type}printer_rotation") ?: "0")
val rotation = Integer.valueOf(conf.get("hardware_${useCase}printer_rotation") ?: "0")

Sentry.configureScope { scope ->
scope.setTag("printer.mode", mode)
scope.setTag("printer.type", type)
scope.setTag("printer.type", useCase)
scope.setContexts("printer.dpi", dpi)
scope.setContexts("printer.rotation", rotation)
}

try {
Log.i("PrintService", "Starting renderPages")
val futures = renderPages(proto, tmpfile, dpi, rotation, numPages, conf, type)
val futures = renderPages(proto, tmpfile, dpi, rotation, numPages, conf, useCase)

Log.i("PrintService", "bindService")
InnerPrinterManager.getInstance().bindService(context, object : InnerPrinterCallback() {
override fun onConnected(printerService: SunmiPrinterService) {
Log.i("PrintService", "PrinterService connected")
when (proto) {
is StreamByteProtocol<*> -> {
proto.send(futures, bais, baos, conf, type)
proto.send(futures, bais, baos, conf, useCase)
printerService.sendRAWData(baos.toByteArray(), object : InnerResultCallback() {
override fun onRunResult(p0: Boolean) {
Log.i("PrintService", "PrinterService onRunResult: $p0")
Expand All @@ -84,10 +91,27 @@ class SunmiInternalConnection : ConnectionType {
}

is SunmiByteProtocol<*> -> {
proto.sendSunmi(printerService, futures, conf, type)
proto.sendSunmi(printerService, futures, conf, useCase)
future.complete(null)
}

is SunmiPrinterXByteProtocol<*> -> {
PrinterSdk.getInstance().getPrinter(context, object : PrinterSdk.PrinterListen {

override fun onDefPrinter(printer: PrinterSdk.Printer?) {
if(printer != null) {
proto.sendSunmi(printer, futures, conf, useCase)
future.complete(null)
}
}

override fun onPrinters(printers: MutableList<PrinterSdk.Printer>?) {
}

})

}

is CustomByteProtocol<*> -> {
throw RuntimeException("Combination not supported")
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -398,6 +398,10 @@ open class USBConnection : ConnectionType {
is SunmiByteProtocol -> {
throw PrintException("Unsupported combination")
}

is SunmiPrinterXByteProtocol -> {
throw PrintException("Unsupported combination")
}
}
}
} catch (e: TimeoutException) {
Expand Down
Loading