Skip to content

Commit

Permalink
refactoring for asynchronous print
Browse files Browse the repository at this point in the history
  • Loading branch information
Franck ALARY committed Jun 23, 2020
1 parent 18ccd95 commit d03c1cf
Show file tree
Hide file tree
Showing 24 changed files with 508 additions and 192 deletions.
10 changes: 5 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -392,8 +392,8 @@ Get a list of USB printers.
#### Constructor : `EscPosPrinter(DeviceConnection printer, int printerDpi, float printingWidthMM, int nbrCharactersPerLine [, EscPosCharsetEncoding charsetEncoding])`
- **param** `DeviceConnection printer` : Instance of a connected printer
- **param** `int printerDpi` : DPI of the connected printer
- **param** `float printingWidthMM` : Printing width in millimeters
- **param** `int nbrCharactersPerLine` : The maximum number of medium sized characters that can be printed on a line.
- **param** `float printerWidthMM` : Printing width in millimeters
- **param** `int printerNbrCharactersPerLine` : The maximum number of medium sized characters that can be printed on a line.
- **param** `EscPosCharsetEncoding charsetEncoding` *(optional)* : Set the charset encoding.

#### Method : `disconnectPrinter()`
Expand All @@ -404,19 +404,19 @@ Close the connection with the printer.
Get the maximum number of characters that can be printed on a line.
- **return** `int`

#### Method : `getPrintingWidthMM()`
#### Method : `getPrinterWidthMM()`
Get the printing width in millimeters
- **return** `float`

#### Method : `getPrinterDpi()`
Get the printer DPI
- **return** `int`

#### Method : `getPrintingWidthPx()`
#### Method : `getPrinterWidthPx()`
Get the printing width in dot
- **return** `int`

#### Method : `getCharSizeWidthPx()`
#### Method : `getPrinterCharSizeWidthPx()`
Get the number of dot that a printed character contain
- **return** `int`

Expand Down
79 changes: 65 additions & 14 deletions app/src/main/java/com/dantsu/thermalprinter/MainActivity.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@

import com.dantsu.escposprinter.EscPosPrinter;
import com.dantsu.escposprinter.connection.DeviceConnection;
import com.dantsu.escposprinter.connection.bluetooth.BluetoothPrintersConnections;
import com.dantsu.escposprinter.connection.tcp.TcpConnection;
import com.dantsu.escposprinter.connection.usb.UsbConnection;
import com.dantsu.escposprinter.connection.usb.UsbPrintersConnections;
Expand All @@ -32,6 +31,10 @@
import com.dantsu.escposprinter.exceptions.EscPosEncodingException;
import com.dantsu.escposprinter.exceptions.EscPosParserException;
import com.dantsu.escposprinter.textparser.PrinterTextParserImg;
import com.dantsu.thermalprinter.async.AsyncBluetoothEscPosPrint;
import com.dantsu.thermalprinter.async.AsyncEscPosPrinter;
import com.dantsu.thermalprinter.async.AsyncTcpEscPosPrint;
import com.dantsu.thermalprinter.async.AsyncUsbEscPosPrint;

public class MainActivity extends AppCompatActivity {

Expand Down Expand Up @@ -67,13 +70,15 @@ public void onClick(View view) {
/*==============================================================================================
======================================BLUETOOTH PART============================================
==============================================================================================*/

public static final int PERMISSION_BLUETOOTH = 1;

public void printBluetooth() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.BLUETOOTH}, MainActivity.PERMISSION_BLUETOOTH);
} else {
this.printIt(BluetoothPrintersConnections.selectFirstPaired());
// this.printIt(BluetoothPrintersConnections.selectFirstPaired());
new AsyncBluetoothEscPosPrint(this).execute(this.getAsyncEscPosPrinter(null));
}
}

Expand All @@ -92,6 +97,7 @@ public void onRequestPermissionsResult(int requestCode, @NonNull String[] permis
/*==============================================================================================
===========================================USB PART=============================================
==============================================================================================*/

private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
private final BroadcastReceiver usbReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
Expand All @@ -102,7 +108,9 @@ public void onReceive(Context context, Intent intent) {
UsbDevice usbDevice = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
if (usbManager != null && usbDevice != null) {
printIt(new UsbConnection(usbManager, usbDevice));
// printIt(new UsbConnection(usbManager, usbDevice));
new AsyncUsbEscPosPrint(context)
.execute(getAsyncEscPosPrinter(new UsbConnection(usbManager, usbDevice)));
}
}
}
Expand All @@ -113,12 +121,19 @@ public void onReceive(Context context, Intent intent) {
public void printUsb() {
UsbConnection usbConnection = UsbPrintersConnections.selectFirstConnected(this);
UsbManager usbManager = (UsbManager) this.getSystemService(Context.USB_SERVICE);
if (usbConnection != null && usbManager != null) {
PendingIntent permissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(MainActivity.ACTION_USB_PERMISSION), 0);
IntentFilter filter = new IntentFilter(MainActivity.ACTION_USB_PERMISSION);
registerReceiver(this.usbReceiver, filter);
usbManager.requestPermission(usbConnection.getDevice(), permissionIntent);

if (usbConnection == null || usbManager == null) {
new AlertDialog.Builder(this)
.setTitle("USB Connection")
.setMessage("No USB printer found.")
.show();
return;
}

PendingIntent permissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(MainActivity.ACTION_USB_PERMISSION), 0);
IntentFilter filter = new IntentFilter(MainActivity.ACTION_USB_PERMISSION);
registerReceiver(this.usbReceiver, filter);
usbManager.requestPermission(usbConnection.getDevice(), permissionIntent);
}

/*==============================================================================================
Expand All @@ -130,12 +145,9 @@ public void printTcp() {
final EditText portAddress = (EditText) this.findViewById(R.id.edittext_tcp_port);

try {
new Thread(new Runnable() {
public void run() {
TcpConnection tcpConnection = new TcpConnection(ipAddress.getText().toString(), Integer.parseInt(portAddress.getText().toString()));
printIt(tcpConnection);
}
}).start();
// this.printIt(new TcpConnection(ipAddress.getText().toString(), Integer.parseInt(portAddress.getText().toString())));
new AsyncTcpEscPosPrint(this)
.execute(this.getAsyncEscPosPrinter(new TcpConnection(ipAddress.getText().toString(), Integer.parseInt(portAddress.getText().toString()))));
} catch (NumberFormatException e) {
new AlertDialog.Builder(this)
.setTitle("Invalid TCP port address")
Expand All @@ -149,6 +161,10 @@ public void run() {
===================================ESC/POS PRINTER PART=========================================
==============================================================================================*/


/**
* Synchronous printing
*/
public void printIt(DeviceConnection printerConnection) {
try {
EscPosPrinter printer = new EscPosPrinter(printerConnection, 203, 48f, 32);
Expand Down Expand Up @@ -207,4 +223,39 @@ public void printIt(DeviceConnection printerConnection) {
.show();
}
}

/**
* Asynchronous printing
*/
public AsyncEscPosPrinter getAsyncEscPosPrinter(DeviceConnection printerConnection) {
AsyncEscPosPrinter printer = new AsyncEscPosPrinter(printerConnection, 203, 48f, 32);
return printer.setTextToPrint(
"[C]<img>" + PrinterTextParserImg.bitmapToHexadecimalString(printer, this.getApplicationContext().getResources().getDrawableForDensity(R.drawable.logo, DisplayMetrics.DENSITY_MEDIUM)) + "</img>\n" +
"[L]\n" +
"[C]<u><font size='big'>ORDER N°045</font></u>\n" +
"[L]\n" +
"[C]================================\n" +
"[L]\n" +
"[L]<b>BEAUTIFUL SHIRT</b>[R]9.99e\n" +
"[L] + Size : S\n" +
"[L]\n" +
"[L]<b>AWESOME HAT</b>[R]24.99e\n" +
"[L] + Size : 57/58\n" +
"[L]\n" +
"[C]--------------------------------\n" +
"[R]TOTAL PRICE :[R]34.98e\n" +
"[R]TAX :[R]4.23e\n" +
"[L]\n" +
"[C]================================\n" +
"[L]\n" +
"[L]<font size='tall'>Customer :</font>\n" +
"[L]Raymond DUPONT\n" +
"[L]5 rue des girafes\n" +
"[L]31547 PERPETES\n" +
"[L]Tel : +33801201456\n" +
"[L]\n" +
"[C]<barcode type='ean13' height='10'>831254784551</barcode>\n" +
"[C]<qrcode size='20'>http://www.developpeur-web.dantsu.com/</qrcode>"
);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package com.dantsu.thermalprinter.async;

import android.content.Context;

import com.dantsu.escposprinter.connection.DeviceConnection;
import com.dantsu.escposprinter.connection.bluetooth.BluetoothPrintersConnections;

public class AsyncBluetoothEscPosPrint extends AsyncEscPosPrint {
public AsyncBluetoothEscPosPrint(Context context) {
super(context);
}

protected Integer doInBackground(AsyncEscPosPrinter... printersData) {
if (printersData.length == 0) {
return AsyncEscPosPrint.FINISH_NO_PRINTER;
}

AsyncEscPosPrinter printerData = printersData[0];

DeviceConnection deviceConnection = printerData.getPrinterConnection();

if(deviceConnection == null) {
this.publishProgress(AsyncEscPosPrint.PROGRESS_CONNECTING);

printersData[0] = new AsyncEscPosPrinter(
BluetoothPrintersConnections.selectFirstPaired(),
printerData.getPrinterDpi(),
printerData.getPrinterWidthMM(),
printerData.getPrinterNbrCharactersPerLine()
);
printersData[0].setTextToPrint(printerData.getTextToPrint());
}

return super.doInBackground(printersData);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
package com.dantsu.thermalprinter.async;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;

import com.dantsu.escposprinter.EscPosPrinter;
import com.dantsu.escposprinter.connection.DeviceConnection;
import com.dantsu.escposprinter.connection.bluetooth.BluetoothPrintersConnections;
import com.dantsu.escposprinter.exceptions.EscPosBarcodeException;
import com.dantsu.escposprinter.exceptions.EscPosConnectionException;
import com.dantsu.escposprinter.exceptions.EscPosEncodingException;
import com.dantsu.escposprinter.exceptions.EscPosParserException;

import java.lang.ref.WeakReference;

public abstract class AsyncEscPosPrint extends AsyncTask<AsyncEscPosPrinter, Integer, Integer> {
protected final static int FINISH_SUCCESS = 1;
protected final static int FINISH_NO_PRINTER = 2;
protected final static int FINISH_PRINTER_DISCONNECTED = 3;
protected final static int FINISH_PARSER_ERROR = 4;
protected final static int FINISH_ENCODING_ERROR = 5;
protected final static int FINISH_BARCODE_ERROR = 6;

protected final static int PROGRESS_CONNECTING = 1;
protected final static int PROGRESS_CONNECTED = 2;
protected final static int PROGRESS_PRINTING = 3;
protected final static int PROGRESS_PRINTED = 4;

protected ProgressDialog dialog;
protected WeakReference<Context> weakContext;


public AsyncEscPosPrint(Context context) {
this.weakContext = new WeakReference<>(context);
}

protected Integer doInBackground(AsyncEscPosPrinter... printersData) {
if (printersData.length == 0) {
return AsyncEscPosPrint.FINISH_NO_PRINTER;
}

this.publishProgress(AsyncEscPosPrint.PROGRESS_CONNECTING);

AsyncEscPosPrinter printerData = printersData[0];

try {
DeviceConnection deviceConnection = printerData.getPrinterConnection();

if(deviceConnection == null) {
deviceConnection = BluetoothPrintersConnections.selectFirstPaired();
}

if(deviceConnection == null) {
return AsyncEscPosPrint.FINISH_NO_PRINTER;
}

EscPosPrinter printer = new EscPosPrinter(deviceConnection, printerData.getPrinterDpi(), printerData.getPrinterWidthMM(), printerData.getPrinterNbrCharactersPerLine());

this.publishProgress(AsyncEscPosPrint.PROGRESS_PRINTING);

printer.printFormattedText(printerData.getTextToPrint());

this.publishProgress(AsyncEscPosPrint.PROGRESS_PRINTED);

} catch (EscPosConnectionException e) {
e.printStackTrace();
return AsyncEscPosPrint.FINISH_PRINTER_DISCONNECTED;
} catch (EscPosParserException e) {
e.printStackTrace();
return AsyncEscPosPrint.FINISH_PARSER_ERROR;
} catch (EscPosEncodingException e) {
e.printStackTrace();
return AsyncEscPosPrint.FINISH_ENCODING_ERROR;
} catch (EscPosBarcodeException e) {
e.printStackTrace();
return AsyncEscPosPrint.FINISH_BARCODE_ERROR;
}

return AsyncEscPosPrint.FINISH_SUCCESS;
}

protected void onPreExecute() {
if (this.dialog == null) {
Context context = weakContext.get();

if (context == null) {
return;
}

this.dialog = new ProgressDialog(context);
this.dialog.setTitle("Printing in progress...");
this.dialog.setMessage("...");
this.dialog.setProgressNumberFormat("%1d / %2d");
this.dialog.setCancelable(false);
this.dialog.setIndeterminate(false);
this.dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
this.dialog.show();
}
}

protected void onProgressUpdate(Integer... progress) {
switch (progress[0]) {
case AsyncEscPosPrint.PROGRESS_CONNECTING:
this.dialog.setMessage("Connecting printer...");
break;
case AsyncEscPosPrint.PROGRESS_CONNECTED:
this.dialog.setMessage("Printer is connected...");
break;
case AsyncEscPosPrint.PROGRESS_PRINTING:
this.dialog.setMessage("Printer is printing...");
break;
case AsyncEscPosPrint.PROGRESS_PRINTED:
this.dialog.setMessage("Printer has finished...");
break;
}
this.dialog.setProgress(progress[0]);
this.dialog.setMax(4);
}

protected void onPostExecute(Integer result) {
this.dialog.dismiss();
this.dialog = null;

Context context = weakContext.get();

if (context == null) {
return;
}

switch (result) {
case AsyncEscPosPrint.FINISH_SUCCESS:
new AlertDialog.Builder(context)
.setTitle("Success")
.setMessage("Congratulation ! The text is printed !")
.show();
break;
case AsyncEscPosPrint.FINISH_NO_PRINTER:
new AlertDialog.Builder(context)
.setTitle("No printer")
.setMessage("The application can't find any printer connected.")
.show();
break;
case AsyncEscPosPrint.FINISH_PRINTER_DISCONNECTED:
new AlertDialog.Builder(context)
.setTitle("Broken connection")
.setMessage("Unable to connect the printer.")
.show();
break;
case AsyncEscPosPrint.FINISH_PARSER_ERROR:
new AlertDialog.Builder(context)
.setTitle("Invalid formatted text")
.setMessage("It seems to be an invalid syntax problem.")
.show();
break;
case AsyncEscPosPrint.FINISH_ENCODING_ERROR:
new AlertDialog.Builder(context)
.setTitle("Bad selected encoding")
.setMessage("The selected encoding character returning an error.")
.show();
break;
case AsyncEscPosPrint.FINISH_BARCODE_ERROR:
new AlertDialog.Builder(context)
.setTitle("Invalid barcode")
.setMessage("Data send to be converted to barcode or QR code seems to be invalid.")
.show();
break;
}
}
}
Loading

0 comments on commit d03c1cf

Please sign in to comment.