diff --git a/src/android/BasePrint.java b/src/android/BasePrint.java index b835cbf..8342004 100644 --- a/src/android/BasePrint.java +++ b/src/android/BasePrint.java @@ -17,29 +17,42 @@ import android.preference.PreferenceManager; import android.util.Log; +import com.brother.ptouch.sdk.CustomPaperInfo; +import com.brother.ptouch.sdk.JNIStatus.BatteryTernary; import com.brother.ptouch.sdk.LabelInfo; +import com.brother.ptouch.sdk.PaperKind; import com.brother.ptouch.sdk.Printer; import com.brother.ptouch.sdk.PrinterInfo; import com.brother.ptouch.sdk.PrinterInfo.ErrorCode; import com.brother.ptouch.sdk.PrinterInfo.Model; import com.brother.ptouch.sdk.PrinterStatus; -import com.brother.ptouch.sdk.TimeoutSetting; +import com.brother.ptouch.sdk.Unit; import com.brother.ptouch.sdk.printdemo.common.Common; import com.brother.ptouch.sdk.printdemo.common.MsgHandle; +import java.util.List; +import java.util.Map; + import static com.threescreens.cordova.plugin.brotherPrinter.BrotherPrinter.TAG; +@SuppressWarnings("ALL") public abstract class BasePrint { + private static final long BLE_RESOLVE_TIMEOUT = 5000; + public static final String TRUE = Boolean.TRUE.toString(); + public static final String FALSE = Boolean.FALSE.toString(); static Printer mPrinter; static boolean mCancel; + final MsgHandle mHandle; private final SharedPreferences sharedPreferences; - private String customSetting; + private final Context mContext; PrinterStatus mPrintResult; + private boolean manualCustomPaperSettingsEnabled; + private String customSetting; private PrinterInfo mPrinterInfo; - final MsgHandle mHandle; BasePrint(Context context, MsgHandle handle) { + mContext = context; mHandle = handle; sharedPreferences = PreferenceManager .getDefaultSharedPreferences(context); @@ -59,19 +72,49 @@ public static void cancel() { protected abstract void doPrint(); + public static class BasePrintResult { + public final boolean success; + public final String errorMessage; + + static BasePrintResult success() { + return new BasePrintResult(true, ""); + } + + static BasePrintResult fail(String message) { + return new BasePrintResult(false, message); + } + + private BasePrintResult(boolean success, String errorMessage) { + this.success = success; + this.errorMessage = errorMessage; + } + } + /** * set PrinterInfo + * + * @return setCustomPaper's result. can ignore other than raster print */ - public void setPrinterInfo() { - + public BasePrintResult setPrinterInfo() { getPreferences(); - setCustomPaper(); - mPrinter.setPrinterInfo(mPrinterInfo); + BasePrintResult customPaperResult = setCustomPaper(); + boolean setPrinterInfoResult = mPrinter.setPrinterInfo(mPrinterInfo); if (mPrinterInfo.port == PrinterInfo.Port.USB) { while (true) { if (Common.mUsbRequest != 0) break; } + if (Common.mUsbRequest != 1) { + } + } + if (!setPrinterInfoResult) { + String errorMessage = mPrinter.getResult().errorCode.toString(); + return BasePrintResult.fail(errorMessage); + } + if (customPaperResult.success == false) { + return customPaperResult; + } else { + return BasePrintResult.success(); } } @@ -87,6 +130,7 @@ public PrinterInfo getPrinterInfo() { * get Printer */ public Printer getPrinter() { + return mPrinter; } @@ -107,6 +151,7 @@ public void setPrintResult(PrinterStatus printResult) { public void setBluetoothAdapter(BluetoothAdapter bluetoothAdapter) { mPrinter.setBluetooth(bluetoothAdapter); + mPrinter.setBluetoothLowEnergy(mContext, bluetoothAdapter, BLE_RESOLVE_TIMEOUT); } @TargetApi(12) @@ -123,12 +168,13 @@ private void getPreferences() { return; } String input; - mPrinterInfo.printerModel = PrinterInfo.Model.valueOf(sharedPreferences + mPrinterInfo.printerModel = Model.valueOf(sharedPreferences .getString("printerModel", "")); mPrinterInfo.port = PrinterInfo.Port.valueOf(sharedPreferences .getString("port", "")); mPrinterInfo.ipAddress = sharedPreferences.getString("address", ""); mPrinterInfo.macAddress = sharedPreferences.getString("macAddress", ""); + mPrinterInfo.setLocalName(sharedPreferences.getString("localName", "")); if (isLabelPrinter(mPrinterInfo.printerModel)) { mPrinterInfo.paperSize = PrinterInfo.PaperSize.CUSTOM; switch (mPrinterInfo.printerModel) { @@ -140,46 +186,84 @@ private void getPreferences() { mPrinterInfo.labelNameIndex = LabelInfo.QL700.valueOf( sharedPreferences.getString("paperSize", LabelInfo.QL700.W62.toString())).ordinal(); mPrinterInfo.isAutoCut = Boolean.parseBoolean(sharedPreferences - .getString("autoCut", new Boolean(true).toString())); + .getString("autoCut", TRUE)); mPrinterInfo.isCutAtEnd = Boolean - .parseBoolean(sharedPreferences.getString("endCut", new Boolean(true).toString())); + .parseBoolean(sharedPreferences.getString("endCut", TRUE)); break; - + case QL_1100: case QL_1110NWB: - mPrinterInfo.labelNameIndex = LabelInfo.QL1100.valueOf( - sharedPreferences.getString("paperSize", LabelInfo.QL1100.W103H164.toString())).ordinal(); - mPrinterInfo.isAutoCut = Boolean.parseBoolean(sharedPreferences - .getString("autoCut", new Boolean(true).toString())); - mPrinterInfo.isCutAtEnd = Boolean - .parseBoolean(sharedPreferences.getString("endCut", new Boolean(true).toString())); - break; - + mPrinterInfo.labelNameIndex = LabelInfo.QL1100.valueOf( + sharedPreferences.getString("paperSize", LabelInfo.QL1100.W103H164.toString())).ordinal(); + mPrinterInfo.isAutoCut = Boolean.parseBoolean(sharedPreferences + .getString("autoCut", TRUE)); + mPrinterInfo.isCutAtEnd = Boolean + .parseBoolean(sharedPreferences.getString("endCut", TRUE)); + break; + case QL_1115NWB: + mPrinterInfo.labelNameIndex = LabelInfo.QL1115.valueOf( + sharedPreferences.getString("paperSize", LabelInfo.QL1115.W62.name())).ordinal(); + mPrinterInfo.isAutoCut = Boolean.parseBoolean(sharedPreferences + .getString("autoCut", TRUE)); + mPrinterInfo.isCutAtEnd = Boolean + .parseBoolean(sharedPreferences.getString("endCut", TRUE)); + break; case PT_E550W: + case PT_E500: case PT_P750W: + case PT_P710BT: + case PT_P715eBT: case PT_D800W: case PT_E800W: case PT_E850TKW: case PT_P900W: case PT_P950NW: - String paper = sharedPreferences.getString("paperSize", ""); + case PT_P910BT: + String paper = sharedPreferences.getString("paperSize", LabelInfo.PT.W24.name()); mPrinterInfo.labelNameIndex = LabelInfo.PT.valueOf(paper) .ordinal(); mPrinterInfo.isAutoCut = Boolean.parseBoolean(sharedPreferences - .getString("autoCut", "")); + .getString("autoCut", TRUE)); mPrinterInfo.isCutAtEnd = Boolean - .parseBoolean(sharedPreferences.getString("endCut", "")); + .parseBoolean(sharedPreferences.getString("endCut", TRUE)); mPrinterInfo.isHalfCut = Boolean.parseBoolean(sharedPreferences - .getString("halfCut", "")); + .getString("halfCut", FALSE)); mPrinterInfo.isSpecialTape = Boolean .parseBoolean(sharedPreferences.getString( - "specialType", "")); + "specialType", FALSE)); + break; + case PT_P300BT: + mPrinterInfo.labelNameIndex = LabelInfo.PT3.valueOf( + sharedPreferences.getString("paperSize", LabelInfo.PT3.W12.name())).ordinal(); + mPrinterInfo.isCutMark = Boolean + .parseBoolean(sharedPreferences.getString( + "cutMark", TRUE)); + mPrinterInfo.isCutAtEnd = Boolean + .parseBoolean(sharedPreferences.getString("endCut", TRUE)); + + input = sharedPreferences.getString("labelMargin", ""); + if (input.equals("")) + input = "0"; + mPrinterInfo.labelMargin = Integer.parseInt(input); + break; default: break; } } else { mPrinterInfo.paperSize = PrinterInfo.PaperSize - .valueOf(sharedPreferences.getString("paperSize", "")); + .valueOf(sharedPreferences.getString("paperSize", PrinterInfo.PaperSize.A4.name())); + switch (mPrinterInfo.printerModel) { + case TD_4410D: + case TD_4420DN: + case TD_4510D: + case TD_4520DN: + case TD_4550DNWB: + mPrinterInfo.isAutoCut = Boolean.parseBoolean(sharedPreferences.getString("autoCut", TRUE)); + mPrinterInfo.isCutAtEnd = Boolean.parseBoolean(sharedPreferences.getString("endCut", TRUE)); + break; + default: + break; + } } mPrinterInfo.orientation = PrinterInfo.Orientation .valueOf(sharedPreferences.getString("orientation", PrinterInfo.Orientation.LANDSCAPE.toString())); @@ -192,7 +276,7 @@ private void getPreferences() { mPrinterInfo.printMode = PrinterInfo.PrintMode .valueOf(sharedPreferences.getString("printMode", PrinterInfo.PrintMode.FIT_TO_PAPER.toString())); mPrinterInfo.pjCarbon = Boolean.parseBoolean(sharedPreferences - .getString("pjCarbon", new Boolean(false).toString())); + .getString("pjCarbon", FALSE)); input = sharedPreferences.getString("pjDensity", ""); if (input.equals("")) input = "5"; @@ -200,13 +284,13 @@ private void getPreferences() { mPrinterInfo.pjFeedMode = PrinterInfo.PjFeedMode .valueOf(sharedPreferences.getString("pjFeedMode", PrinterInfo.PjFeedMode.PJ_FEED_MODE_FIXEDPAGE.toString())); mPrinterInfo.align = PrinterInfo.Align.valueOf(sharedPreferences - .getString("align", PrinterInfo.Align.LEFT.toString())); + .getString("align", PrinterInfo.Align.CENTER.toString())); input = sharedPreferences.getString("leftMargin", ""); if (input.equals("")) input = "0"; mPrinterInfo.margin.left = Integer.parseInt(input); mPrinterInfo.valign = PrinterInfo.VAlign.valueOf(sharedPreferences - .getString("valign", PrinterInfo.VAlign.TOP.toString())); + .getString("valign", PrinterInfo.VAlign.MIDDLE.name())); input = sharedPreferences.getString("topMargin", ""); if (input.equals("")) input = "0"; @@ -214,9 +298,6 @@ private void getPreferences() { input = sharedPreferences.getString("customPaperWidth", ""); if (input.equals("")) input = "0"; - - mPrinterInfo.mirrorPrint = Boolean.parseBoolean(sharedPreferences - .getString("mirrorPrint", new Boolean(false).toString())); mPrinterInfo.customPaperWidth = Integer.parseInt(input); input = sharedPreferences.getString("customPaperLength", "0"); @@ -229,79 +310,63 @@ private void getPreferences() { input = "0"; mPrinterInfo.customFeed = Integer.parseInt(input); + manualCustomPaperSettingsEnabled = Boolean.parseBoolean(sharedPreferences.getString("enableManualCustomPaperSettings", Boolean.FALSE.toString())); customSetting = sharedPreferences.getString("customSetting", ""); mPrinterInfo.paperPosition = PrinterInfo.Align .valueOf(sharedPreferences.getString("paperPosition", PrinterInfo.Align.LEFT.toString())); mPrinterInfo.dashLine = Boolean.parseBoolean(sharedPreferences - .getString("dashLine", "false")); - - mPrinterInfo.enabledTethering = Boolean.parseBoolean(sharedPreferences - .getString("enabledTethering", new Boolean(false).toString())); - - input = sharedPreferences.getString("rjDensity", ""); - if (input.equals("")) - input = "0"; - mPrinterInfo.rjDensity = Integer.parseInt(input); - + .getString("dashLine", FALSE)); + mPrinterInfo.rjDensity = Integer.parseInt(sharedPreferences.getString( + "rjDensity", "0")); mPrinterInfo.rotate180 = Boolean.parseBoolean(sharedPreferences - .getString("rotate180", "")); - - mPrinterInfo.savePrnPath = sharedPreferences.getString("savePrnPath", ""); - + .getString("rotate180", FALSE)); mPrinterInfo.peelMode = Boolean.parseBoolean(sharedPreferences - .getString("peelMode", "")); - - mPrinterInfo.mode9 = Boolean.parseBoolean(sharedPreferences - .getString("mode9", new Boolean(true).toString())); - - mPrinterInfo.overwrite = Boolean.parseBoolean(sharedPreferences - .getString("overwrite", new Boolean(true).toString())); + .getString("peelMode", FALSE)); + mPrinterInfo.mode9 = Boolean.parseBoolean(sharedPreferences.getString( + "mode9", "")); mPrinterInfo.dashLine = Boolean.parseBoolean(sharedPreferences - .getString("dashLine", "")); + .getString("dashLine", FALSE)); input = sharedPreferences.getString("pjSpeed", "2"); mPrinterInfo.pjSpeed = Integer.parseInt(input); + mPrinterInfo.pjPaperKind = PrinterInfo.PjPaperKind + .valueOf(sharedPreferences.getString("pjPaperKind", + PrinterInfo.PjPaperKind.PJ_CUT_PAPER.name())); + mPrinterInfo.rollPrinterCase = PrinterInfo.PjRollCase .valueOf(sharedPreferences.getString("printerCase", - PrinterInfo.PjRollCase.PJ_ROLLCASE_OFF.toString())); + PrinterInfo.PjRollCase.PJ_ROLLCASE_OFF.name())); mPrinterInfo.skipStatusCheck = Boolean.parseBoolean(sharedPreferences - .getString("skipStatusCheck", new Boolean(false).toString())); - - mPrinterInfo.softFocusing = Boolean.parseBoolean(sharedPreferences - .getString("softFocusing", new Boolean(false).toString())); + .getString("skipStatusCheck", FALSE)); mPrinterInfo.checkPrintEnd = PrinterInfo.CheckPrintEnd - .valueOf(sharedPreferences.getString("checkPrintEnd", PrinterInfo.CheckPrintEnd.CPE_CHECK.toString())); + .valueOf(sharedPreferences.getString("checkPrintEnd", PrinterInfo.CheckPrintEnd.CPE_CHECK.name())); mPrinterInfo.printQuality = PrinterInfo.PrintQuality .valueOf(sharedPreferences.getString("printQuality", - PrinterInfo.PrintQuality.NORMAL.toString())); - - mPrinterInfo.rawMode = Boolean.parseBoolean(sharedPreferences - .getString("rawMode", new Boolean(false).toString())); + PrinterInfo.PrintQuality.NORMAL.name())); + mPrinterInfo.overwrite = Boolean.parseBoolean(sharedPreferences + .getString("overwrite", TRUE)); mPrinterInfo.trimTapeAfterData = Boolean.parseBoolean(sharedPreferences - .getString("trimTapeAfterData", new Boolean(false).toString())); + .getString("trimTapeAfterData", FALSE)); input = sharedPreferences.getString("imageThresholding", ""); if (input.equals("")) input = "127"; mPrinterInfo.thresholdingValue = Integer.parseInt(input); - mPrinterInfo.timeout = new TimeoutSetting(); - input = sharedPreferences.getString("scaleValue", ""); if (input.equals("")) - input = "1"; + input = "0"; try { mPrinterInfo.scaleValue = Double.parseDouble(input); } catch (NumberFormatException e) { mPrinterInfo.scaleValue = 1.0; } - if (mPrinterInfo.printerModel == Model.TD_4000 || mPrinterInfo.printerModel == Model.TD_4100N) { mPrinterInfo.isAutoCut = Boolean.parseBoolean(sharedPreferences @@ -310,6 +375,51 @@ private void getPreferences() { .getString("endCut", "")); } + input = sharedPreferences.getString("savePrnPath", ""); + mPrinterInfo.savePrnPath = input; + + + mPrinterInfo.workPath = sharedPreferences.getString("workPath", ""); + //Avoid .ERROR_WORKPATH_NOT_SET. + if ("".equals(mPrinterInfo.workPath)) { + mPrinterInfo.workPath = mContext.getCacheDir().getPath(); + } + + mPrinterInfo.softFocusing = Boolean.parseBoolean(sharedPreferences + .getString("softFocusing", FALSE)); + mPrinterInfo.enabledTethering = Boolean.parseBoolean(sharedPreferences + .getString("enabledTethering", FALSE)); + mPrinterInfo.rawMode = Boolean.parseBoolean(sharedPreferences + .getString("rawMode", FALSE)); + + + input = sharedPreferences.getString("processTimeout", ""); + if (input.equals("")) + input = "60"; + mPrinterInfo.timeout.processTimeoutSec = Integer.parseInt(input); + + input = sharedPreferences.getString("sendTimeout", ""); + if (input.equals("")) + input = "60"; + mPrinterInfo.timeout.sendTimeoutSec = Integer.parseInt(input); + + input = sharedPreferences.getString("receiveTimeout", ""); + if (input.equals("")) + input = "180"; + mPrinterInfo.timeout.receiveTimeoutSec = Integer.parseInt(input); + + input = sharedPreferences.getString("connectionTimeout", ""); + if (input.equals("")) + input = "10000"; + mPrinterInfo.timeout.connectionWaitMSec = Integer.parseInt(input); + + input = sharedPreferences.getString("closeWaitTime", ""); + if (input.equals("")) + input = "3"; + mPrinterInfo.timeout.closeWaitDisusingStatusCheckSec = Integer.parseInt(input); + + mPrinterInfo.useLegacyHalftoneEngine = Boolean.parseBoolean(sharedPreferences + .getString("useLegacyHalftoneEngine", FALSE)); } /** @@ -326,15 +436,25 @@ public void print() { */ public void getPrinterStatus() { mCancel = false; - getStatusThread getTread = new getStatusThread(); + GetStatusThread getTread = new GetStatusThread(); getTread.start(); } /** - * set custom paper for RJ and TD + * Launch the thread to print */ - private void setCustomPaper() { + public void sendFile() { + + + SendFileThread getTread = new SendFileThread(); + getTread.start(); + } + /** + * set custom paper for RJ and TD + */ + private BasePrintResult setCustomPaper() { + BasePrintResult result; switch (mPrinterInfo.printerModel) { case RJ_4030: case RJ_4030Ai: @@ -352,17 +472,84 @@ private void setCustomPaper() { case RJ_2050: case RJ_3050Ai: case RJ_3150Ai: - mPrinterInfo.customPaper = Common.CUSTOM_PAPER_FOLDER + customSetting; + case RJ_4230B: + case RJ_4250WB: + case TD_4410D: + case TD_4420DN: + case TD_4510D: + case TD_4520DN: + case TD_4550DNWB: + if (manualCustomPaperSettingsEnabled) { + result = setManualCustomPaper(mPrinterInfo.printerModel); + } else { + mPrinterInfo.customPaper = Common.CUSTOM_PAPER_FOLDER + customSetting; + result = setManualCustomPaper(null); + } break; default: + result = BasePrintResult.success(); break; } + return result; + } + + private BasePrintResult setManualCustomPaper(Model printerModel) { + if (printerModel == null) { + mPrinterInfo.setCustomPaperInfo(null); + return BasePrintResult.success(); + } + + PaperKind paperKind = PaperKind.valueOf(sharedPreferences.getString("rjPaperKind", "ROLL")); + float width = parseFloat(sharedPreferences.getString("rjPaperWidth", ""), 0.0f); + float length = parseFloat(sharedPreferences.getString("rjPaperLength", ""), 0.0f); + float rightMargin = parseFloat(sharedPreferences.getString("rjPaperRightMargin", ""), 0.0f); + float leftMargin = parseFloat(sharedPreferences.getString("rjPaperLeftMargin", ""), 0.0f); + float topMargin = parseFloat(sharedPreferences.getString("rjPaperTopMargin", ""), 0.0f); + float bottomMargin = parseFloat(sharedPreferences.getString("rjPaperBottomMargin", ""), 0.0f); + float labelPitch = parseFloat(sharedPreferences.getString("rjPaperLabelPitch", ""), 0.0f); + float markPosition = parseFloat(sharedPreferences.getString("rjPaperMarkPosition", ""), 0.0f); + float markHeight = parseFloat(sharedPreferences.getString("rjPaperMarkHeight", ""), 0.0f); + Unit unit = Unit.valueOf(sharedPreferences.getString("rjPaperUnit", Unit.Mm.name())); + + CustomPaperInfo customPaperInfo; + switch (paperKind) { + case DIE_CUT: + customPaperInfo = CustomPaperInfo.newCustomDiaCutPaper(printerModel, unit, width, length, rightMargin, leftMargin, topMargin, bottomMargin, labelPitch); + break; + case MARKED_ROLL: + customPaperInfo = CustomPaperInfo.newCustomMarkRollPaper(printerModel, unit, width, length, rightMargin, leftMargin, topMargin, bottomMargin, markPosition, markHeight); + break; + case ROLL: + default: + customPaperInfo = CustomPaperInfo.newCustomRollPaper(printerModel, unit, width, rightMargin, leftMargin, topMargin); + break; + } + + List> errors = mPrinterInfo.setCustomPaperInfo(customPaperInfo); + if (errors.isEmpty()) { + return BasePrintResult.success(); + } else { + // TODO: Humal Readable + return BasePrintResult.fail(errors.toString()); + } + } + + private float parseFloat(String s, float defaultValue) { + try { + return Float.parseFloat(s); + } catch (NumberFormatException e) { + return defaultValue; + } } /** * get the end message of print */ + @SuppressWarnings("UnusedAssignment") public String showResult() { + if (mPrintResult == null) { + return ""; + } String result; if (mPrintResult.errorCode == ErrorCode.ERROR_NONE) { @@ -379,96 +566,91 @@ public String showResult() { */ public String getBattery() { - String battery = ""; - if (mPrinterInfo.printerModel == PrinterInfo.Model.MW_260 - || mPrinterInfo.printerModel == PrinterInfo.Model.MW_260MFi) { - if (mPrintResult.batteryLevel > 80) { - battery = Common.BatteryStatus.FULL.toString(); - } else if (30 <= mPrintResult.batteryLevel - && mPrintResult.batteryLevel <= 80) { - battery = Common.BatteryStatus.MIDDLE.toString(); - } else if (0 <= mPrintResult.batteryLevel - && mPrintResult.batteryLevel < 30) { - battery = Common.BatteryStatus.WEAK.toString(); - } - } else if (mPrinterInfo.printerModel == Model.RJ_4030 - || mPrinterInfo.printerModel == Model.RJ_4030Ai - || mPrinterInfo.printerModel == Model.RJ_4040 - || mPrinterInfo.printerModel == Model.RJ_3050 - || mPrinterInfo.printerModel == Model.RJ_3150 - || mPrinterInfo.printerModel == Model.PT_E550W - || mPrinterInfo.printerModel == Model.PT_P750W - || mPrinterInfo.printerModel == Model.TD_2020 - || mPrinterInfo.printerModel == Model.TD_2120N - || mPrinterInfo.printerModel == Model.TD_2130N - || mPrinterInfo.printerModel == Model.PJ_722 - || mPrinterInfo.printerModel == Model.PJ_723 - || mPrinterInfo.printerModel == Model.PJ_762 - || mPrinterInfo.printerModel == Model.PJ_763 - || mPrinterInfo.printerModel == Model.PJ_763MFi - || mPrinterInfo.printerModel == Model.PJ_773 - || mPrinterInfo.printerModel == Model.PT_P900W - || mPrinterInfo.printerModel == Model.PT_P950NW - || mPrinterInfo.printerModel == Model.PT_E850TKW - || mPrinterInfo.printerModel == Model.PT_E800W - || mPrinterInfo.printerModel == Model.PT_D800W - || mPrinterInfo.printerModel == Model.QL_800 - || mPrinterInfo.printerModel == Model.QL_810W - || mPrinterInfo.printerModel == Model.QL_820NWB - || mPrinterInfo.printerModel == Model.QL_1110NWB - || mPrinterInfo.printerModel == Model.RJ_2030 - || mPrinterInfo.printerModel == Model.RJ_2050 - || mPrinterInfo.printerModel == Model.RJ_2140 - || mPrinterInfo.printerModel == Model.RJ_2150 - || mPrinterInfo.printerModel == Model.RJ_3050Ai - || mPrinterInfo.printerModel == Model.RJ_3150Ai) { - switch (mPrintResult.batteryLevel) { + if (mPrintResult.isACConnected == BatteryTernary.Yes) { + return Common.BatteryStatus.ACADAPTER.toString(); + } + + if (mPrintResult.maxOfBatteryResidualQuantityLevel == 0) { + return Common.BatteryStatus.FULL.toString(); + } else if (mPrintResult.maxOfBatteryResidualQuantityLevel == 2) { + switch (mPrintResult.batteryResidualQuantityLevel) { case 0: - battery = Common.BatteryStatus.FULL.toString(); - break; + return Common.BatteryStatus.WEAK.toString(); case 1: - battery = Common.BatteryStatus.MIDDLE.toString(); - break; + return Common.BatteryStatus.MIDDLE.toString(); case 2: - battery = Common.BatteryStatus.WEAK.toString(); + return Common.BatteryStatus.FULL.toString(); + default: break; + } + } else if (mPrintResult.maxOfBatteryResidualQuantityLevel == 3) { + switch (mPrintResult.batteryResidualQuantityLevel) { + case 0: + return Common.BatteryStatus.CHARGE.toString(); + case 1: + return Common.BatteryStatus.WEAK.toString(); + case 2: + return Common.BatteryStatus.MIDDLE.toString(); case 3: - battery = Common.BatteryStatus.CHARGE.toString(); - break; - case 4: - battery = Common.BatteryStatus.ACADAPTER.toString(); - break; + return Common.BatteryStatus.FULL.toString(); default: break; } - } else { - switch (mPrintResult.batteryLevel) { + } else if (mPrintResult.maxOfBatteryResidualQuantityLevel == 4) { + switch (mPrintResult.batteryResidualQuantityLevel) { case 0: - battery = Common.BatteryStatus.ACADAPTER.toString(); - break; + return Common.BatteryStatus.CHARGE.toString(); case 1: - battery = Common.BatteryStatus.WEAK.toString(); - break; + return Common.BatteryStatus.WEAK.toString(); case 2: - battery = Common.BatteryStatus.MIDDLE.toString(); - break; + return Common.BatteryStatus.MIDDLE.toString(); case 3: - battery = Common.BatteryStatus.FULL.toString(); - break; + return Common.BatteryStatus.MIDDLE.toString(); + case 4: + return Common.BatteryStatus.FULL.toString(); default: break; } + } else if (mPrintResult.maxOfBatteryResidualQuantityLevel == 100) { + if (mPrintResult.batteryResidualQuantityLevel > 80) { + return Common.BatteryStatus.FULL.toString(); + } else if (30 <= mPrintResult.batteryResidualQuantityLevel + && mPrintResult.batteryResidualQuantityLevel <= 80) { + return Common.BatteryStatus.MIDDLE.toString(); + } else if (0 <= mPrintResult.batteryResidualQuantityLevel + && mPrintResult.batteryResidualQuantityLevel < 30) { + return Common.BatteryStatus.WEAK.toString(); + } + } else { + double ratio = (double) mPrintResult.batteryResidualQuantityLevel / mPrintResult.maxOfBatteryResidualQuantityLevel; + if (ratio > 0.8) { + return Common.BatteryStatus.FULL.toString(); + } else if (0.3 <= ratio && ratio <= 0.8) { + return Common.BatteryStatus.MIDDLE.toString(); + } else if (0 <= ratio && ratio < 0.3) { + return Common.BatteryStatus.WEAK.toString(); + } } - if (mPrintResult.errorCode != ErrorCode.ERROR_NONE) - battery = ""; - return battery; + return ""; } - private boolean isLabelPrinter(PrinterInfo.Model model) { + public String getBatteryDetail() { + if (mPrintResult == null) { + return ""; + } + return String.format("%d/%d(AC=%s,BM=%s)", + mPrintResult.batteryResidualQuantityLevel, + mPrintResult.maxOfBatteryResidualQuantityLevel, + mPrintResult.isACConnected.name(), + mPrintResult.isBatteryMounted.name()); + } + + private boolean isLabelPrinter(Model model) { switch (model) { case QL_710W: case QL_720NW: case PT_E550W: + case PT_E500: case PT_P750W: case PT_D800W: case PT_E800W: @@ -478,7 +660,13 @@ private boolean isLabelPrinter(PrinterInfo.Model model) { case QL_810W: case QL_800: case QL_820NWB: + case PT_P300BT: + case QL_1100: case QL_1110NWB: + case QL_1115NWB: + case PT_P710BT: + case PT_P715eBT: + case PT_P910BT: return true; default: return false; @@ -493,7 +681,12 @@ private class PrinterThread extends Thread { public void run() { try { // set info. for printing - setPrinterInfo(); + BasePrintResult setPrinterInfoResult = setPrinterInfo(); + if (setPrinterInfoResult.success == false) { + mHandle.setResult(setPrinterInfoResult.errorMessage); + mHandle.sendMessage(mHandle.obtainMessage(Common.MSG_PRINT_END)); + return; + } // start message Message msg = mHandle.obtainMessage(Common.MSG_PRINT_START); @@ -511,7 +704,7 @@ public void run() { // end message mHandle.setResult(showResult()); - mHandle.setBattery(getBattery()); + mHandle.setBattery(getBatteryDetail()); msg = mHandle.obtainMessage(Common.MSG_PRINT_END); mHandle.sendMessage(msg); @@ -524,7 +717,7 @@ public void run() { /** * Thread for getting the printer's status */ - private class getStatusThread extends Thread { + private class GetStatusThread extends Thread { @Override public void run() { try { @@ -543,7 +736,7 @@ public void run() { } // end message mHandle.setResult(showResult()); - mHandle.setBattery(getBattery()); + mHandle.setBattery(getBatteryDetail()); msg = mHandle.obtainMessage(Common.MSG_PRINT_END); mHandle.sendMessage(msg); } catch (Throwable throwable) { @@ -552,8 +745,46 @@ public void run() { } } - private void handleUnexpectedError(final String message, Throwable throwable) { + /** + * Thread for getting the printer's status + */ + private class SendFileThread extends Thread { + @Override + public void run() { + try { + // set info. for printing + BasePrintResult setPrinterInfoResult = setPrinterInfo(); + if (setPrinterInfoResult.success == false) { + mHandle.setResult(setPrinterInfoResult.errorMessage); + mHandle.sendMessage(mHandle.obtainMessage(Common.MSG_PRINT_END)); + return; + } + + // start message + Message msg = mHandle.obtainMessage(Common.MSG_PRINT_START); + mHandle.sendMessage(msg); + + mPrintResult = new PrinterStatus(); + + mPrinter.startCommunication(); + doPrint(); + + mPrinter.endCommunication(); + // end message + mHandle.setResult(showResult()); + mHandle.setBattery(getBatteryDetail()); + msg = mHandle.obtainMessage(Common.MSG_PRINT_END); + mHandle.sendMessage(msg); + + + } catch (Throwable throwable) { + handleUnexpectedError("Failed to get printer status: ", throwable); + } + } + } + + private void handleUnexpectedError(final String message, Throwable throwable) { Log.e(TAG, message, throwable); Message msg = mHandle.obtainMessage(Common.MSG_UNEXPECTED_INTERNAL_SYSTEM_ERROR); mHandle.setResult(throwable.getClass().getSimpleName()); diff --git a/src/android/BrotherPrinter.java b/src/android/BrotherPrinter.java index 9ab3998..38f08c4 100644 --- a/src/android/BrotherPrinter.java +++ b/src/android/BrotherPrinter.java @@ -17,6 +17,7 @@ import org.apache.cordova.CordovaInterface; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.CordovaWebView; +import org.apache.cordova.LOG; import org.apache.cordova.PluginResult; import org.json.JSONArray; @@ -36,6 +37,7 @@ import android.graphics.BitmapFactory; import android.os.Build; import android.preference.PreferenceManager; +import android.support.v4.app.ActivityCompat; import android.telecom.Call; import android.util.Base64; import android.util.Log; @@ -54,6 +56,9 @@ import com.brother.ptouch.sdk.printdemo.printprocess.ImageFilePrint; public class BrotherPrinter extends CordovaPlugin { + //token to make it easy to grep logcat + public static final String TAG = "BrotherPrinter"; + private static PrinterInfo.Model[] supportedModels = { PrinterInfo.Model.QL_720NW, PrinterInfo.Model.QL_820NWB, @@ -78,52 +83,58 @@ private boolean isPermitWriteStorage() { @Override public void initialize(CordovaInterface cordova, CordovaWebView webView) { - super.initialize(cordova, webView); - mHandle = new MsgHandle(null); - mBitmapPrint = new ImageBitmapPrint(cordova.getActivity(), mHandle); - mFilePrint = new ImageFilePrint(cordova.getActivity(), mHandle); + try { + super.initialize(cordova, webView); + mHandle = new MsgHandle(null); + mBitmapPrint = new ImageBitmapPrint(cordova.getActivity(), mHandle); + mFilePrint = new ImageFilePrint(cordova.getActivity(), mHandle); - if (!isPermitWriteStorage()) { - cordova.requestPermission(this, PERMISSION_WRITE_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE); + if (!isPermitWriteStorage()) { + cordova.requestPermission(this, PERMISSION_WRITE_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE); + } + } catch (Throwable t) { + LOG.e(TAG, "Failed to initialize label printer " + t); } } - //token to make it easy to grep logcat - public static final String TAG = "BrotherPrinter"; @Override - public boolean execute (String action, JSONArray args, CallbackContext callbackContext) throws JSONException { + public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { - if ("findNetworkPrinters".equals(action)) { - findNetworkPrinters(callbackContext); - return true; - } + try { + if ("findNetworkPrinters".equals(action)) { + findNetworkPrinters(callbackContext); + return true; + } - if ("findBluetoothPrinters".equals(action)) { - findBluetoothPrinters(callbackContext); - return true; - } + if ("findBluetoothPrinters".equals(action)) { + findBluetoothPrinters(callbackContext); + return true; + } - if ("findPrinters".equals(action)) { - findPrinters(callbackContext); - return true; - } + if ("findPrinters".equals(action)) { + findPrinters(callbackContext); + return true; + } - if ("setPrinter".equals(action)) { - setPrinter(args, callbackContext); - return true; - } + if ("setPrinter".equals(action)) { + setPrinter(args, callbackContext); + return true; + } - if ("printViaSDK".equals(action)) { - printViaSDK(args, callbackContext); - return true; - } + if ("printViaSDK".equals(action)) { + printViaSDK(args, callbackContext); + return true; + } - if ("sendUSBConfig".equals(action)) { - sendUSBConfig(args, callbackContext); - return true; - } + if ("sendUSBConfig".equals(action)) { + sendUSBConfig(args, callbackContext); + return true; + } + } catch (Throwable t) { + sendError(callbackContext, t, "Failed while interacting with printer"); + } return false; } @@ -225,7 +236,7 @@ public JSONObject toJSON() throws JSONException { result.put("serialNumber", serNo); result.put("nodeName", nodeName); result.put("location", location); - + result.put("paperLabelName", paperLabelName); return result; } } @@ -290,9 +301,9 @@ private void sendDiscoveredPrinters(final CallbackContext callbackctx, List discoveredPrinters = enumerateNetPrinters(); - sendDiscoveredPrinters(callbackctx, discoveredPrinters); + try { + List discoveredPrinters = enumerateNetPrinters(); + sendDiscoveredPrinters(callbackctx, discoveredPrinters); + } catch (Throwable t) { + sendError(callbackctx, t, "Failed to find network printer"); + } } }); @@ -316,8 +331,12 @@ private void findBluetoothPrinters(final CallbackContext callbackctx) { cordova.getThreadPool().execute(new Runnable() { @Override public void run() { - List discoveredPrinters = enumerateBluetoothPrinters(); - sendDiscoveredPrinters(callbackctx, discoveredPrinters); + try { + List discoveredPrinters = enumerateBluetoothPrinters(); + sendDiscoveredPrinters(callbackctx, discoveredPrinters); + } catch (Throwable t) { + sendError(callbackctx, t, "Failed to find BlueTooth printers"); + } } }); } @@ -326,9 +345,13 @@ private void findPrinters(final CallbackContext callbackctx) { cordova.getThreadPool().execute(new Runnable() { @Override public void run() { - List allPrinters = enumerateNetPrinters(); - allPrinters.addAll(enumerateBluetoothPrinters()); - sendDiscoveredPrinters(callbackctx, allPrinters); + try { + List allPrinters = enumerateNetPrinters(); + allPrinters.addAll(enumerateBluetoothPrinters()); + sendDiscoveredPrinters(callbackctx, allPrinters); + } catch (Throwable t) { + sendError(callbackctx, t, "Failed to find printers"); + } } }); } @@ -354,81 +377,95 @@ private void setPrinter(JSONArray args, final CallbackContext callbackctx) { PluginResult result = new PluginResult(PluginResult.Status.OK, args); callbackctx.sendPluginResult(result); - } catch (JSONException e) { - e.printStackTrace(); - PluginResult result = new PluginResult(PluginResult.Status.ERROR, "An error occurred while trying to set the printer."); - callbackctx.sendPluginResult(result); + } catch (Throwable e) { + sendError(callbackctx, e, "Failed to set the printer."); } } - public static Bitmap bmpFromBase64(String base64){ - try{ + private void sendError(CallbackContext callbackctx, Throwable e, String s) { + String errMessage = e == null ? "" : e.toString(); + Log.e(TAG, errMessage); + PluginResult result = new PluginResult(PluginResult.Status.ERROR, s + " " + errMessage); + callbackctx.sendPluginResult(result); + } + + public Bitmap bmpFromBase64(String base64) { + try { byte[] bytes = Base64.decode(base64, Base64.DEFAULT); InputStream stream = new ByteArrayInputStream(bytes); return BitmapFactory.decodeStream(stream); - }catch(Exception e){ - e.printStackTrace(); + } catch (Exception e) { + Log.e(TAG, e + ""); return null; } } private void printViaSDK(final JSONArray args, final CallbackContext callbackctx) { - SharedPreferences sharedPreferences = PreferenceManager - .getDefaultSharedPreferences(cordova.getActivity()); + cordova.getThreadPool().execute(new Runnable() { + @Override + public void run() { + try { + SharedPreferences sharedPreferences = PreferenceManager + .getDefaultSharedPreferences(cordova.getActivity()); + + String port = sharedPreferences.getString("port", ""); + if ("".equals(port)) { + PluginResult result = new PluginResult(PluginResult.Status.ERROR, "No printer has been set."); + callbackctx.sendPluginResult(result); + return; + } - String port = sharedPreferences.getString("port", ""); - if ("".equals(port)) { - PluginResult result = new PluginResult(PluginResult.Status.ERROR, "No printer has been set."); - callbackctx.sendPluginResult(result); - return; - } + if (PrinterInfo.Port.BLUETOOTH.toString().equals(port)) { + BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); + if (bluetoothAdapter == null) { + PluginResult result = new PluginResult(PluginResult.Status.ERROR, "This device does not have a bluetooth adapter."); + callbackctx.sendPluginResult(result); + return; + } - if (PrinterInfo.Port.BLUETOOTH.toString().equals(port)) { - BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); - if (bluetoothAdapter == null) { - PluginResult result = new PluginResult(PluginResult.Status.ERROR, "This device does not have a bluetooth adapter."); - callbackctx.sendPluginResult(result); - return; - } + if (!bluetoothAdapter.isEnabled()) { + Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); + enableBtIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + cordova.getActivity().startActivity(enableBtIntent); + } - if (!bluetoothAdapter.isEnabled()) { - Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); - enableBtIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - cordova.getActivity().startActivity(enableBtIntent); - } + mBitmapPrint.setBluetoothAdapter(bluetoothAdapter); + mFilePrint.setBluetoothAdapter(bluetoothAdapter); + } - mBitmapPrint.setBluetoothAdapter(bluetoothAdapter); - mFilePrint.setBluetoothAdapter(bluetoothAdapter); - } + Bitmap bitmap = null; + try { + String encodedImg = args.getString(0); + bitmap = bmpFromBase64(encodedImg); + } catch (JSONException e) { + sendError(callbackctx, e, "An error occurred while trying to retrieve the image passed in."); + return; + } - Bitmap bitmap = null; - try { - String encodedImg = args.getString(0); - bitmap = bmpFromBase64(encodedImg); - } catch (JSONException e) { - e.printStackTrace(); - PluginResult result = new PluginResult(PluginResult.Status.ERROR, "An error occurred while trying to retrieve the image passed in."); - callbackctx.sendPluginResult(result); - return; - } + if (bitmap == null) { + PluginResult result = new PluginResult(PluginResult.Status.ERROR, "The passed in data did not seem to be a decodable image. Please ensure it is a base64 encoded string of a supported Android format"); + callbackctx.sendPluginResult(result); + return; + } - if (bitmap == null) { - PluginResult result = new PluginResult(PluginResult.Status.ERROR, "The passed in data did not seem to be a decodable image. Please ensure it is a base64 encoded string of a supported Android format"); - callbackctx.sendPluginResult(result); - return; - } + mHandle.setCallbackContext(callbackctx); - mHandle.setCallbackContext(callbackctx); + List bitmaps = new ArrayList(); + bitmaps.add(bitmap); - List bitmaps = new ArrayList(); - bitmaps.add(bitmap); + mBitmapPrint.setBitmaps(bitmaps); + mBitmapPrint.print(); - mBitmapPrint.setBitmaps(bitmaps); - mBitmapPrint.print(); + } catch (Throwable t) { + sendError(callbackctx, t, "Failed to printViaSDK "); + } + + } + }); } - private void sendUSBConfig(final JSONArray args, final CallbackContext callbackctx){ + private void sendUSBConfig(final JSONArray args, final CallbackContext callbackctx) { cordova.getThreadPool().execute(new Runnable() { public void run() { @@ -484,19 +521,19 @@ public void onReceive(Context context, Intent intent) { myPrinterInfo = myPrinter.getPrinterInfo(); - myPrinterInfo.printerModel = PrinterInfo.Model.QL_720NW; - myPrinterInfo.port = PrinterInfo.Port.USB; - myPrinterInfo.paperSize = PrinterInfo.PaperSize.CUSTOM; + myPrinterInfo.printerModel = PrinterInfo.Model.QL_720NW; + myPrinterInfo.port = PrinterInfo.Port.USB; + myPrinterInfo.paperSize = PrinterInfo.PaperSize.CUSTOM; myPrinter.setPrinterInfo(myPrinterInfo); LabelInfo myLabelInfo = new LabelInfo(); - myLabelInfo.labelNameIndex = myPrinter.checkLabelInPrinter(); - myLabelInfo.isAutoCut = true; - myLabelInfo.isEndCut = true; - myLabelInfo.isHalfCut = false; - myLabelInfo.isSpecialTape = false; + myLabelInfo.labelNameIndex = myPrinter.checkLabelInPrinter(); + myLabelInfo.isAutoCut = true; + myLabelInfo.isEndCut = true; + myLabelInfo.isHalfCut = false; + myLabelInfo.isSpecialTape = false; //label info must be set after setPrinterInfo, it's not in the docs myPrinter.setLabelInfo(myLabelInfo); @@ -513,9 +550,9 @@ public void onReceive(Context context, Intent intent) { PrinterStatus status = myPrinter.printFile(outputFile.toString()); outputFile.delete(); - String status_code = ""+status.errorCode; + String status_code = "" + status.errorCode; - Log.d(TAG, "PrinterStatus: "+status_code); + Log.d(TAG, "PrinterStatus: " + status_code); PluginResult result; result = new PluginResult(PluginResult.Status.OK, status_code);