diff --git a/README.md b/README.md index 061b64a..9100934 100644 --- a/README.md +++ b/README.md @@ -12,36 +12,31 @@ _An unofficial React Native library for printing on an EPSON TM printer with the | [![npm version](https://badge.fury.io/js/react-native-esc-pos-printer.svg)](https://badge.fury.io/js/react-native-esc-pos-printer) | |---| - - - - 1. [Installation](./docs/INSTALLATION.md) -2. [Quick Print Example](./docs/QUICK_START.md) 3. [API](./docs/API.md) -4. [SDK information (v2.27.0)](./docs/SDK.md) -5. [List of supported printers for Android](./docs/and2270.pdf) -5. [List of supported printers for iOS](./docs/and2270.pdf) -6. [Expo](./docs/EXPO.md) +4. [Expo](./docs/EXPO.md) +5. [SDK information (v2.27.0)](./docs/SDK.md) +6. [List of supported printers for Android](./docs/and2270.pdf) +7. [List of supported printers for iOS](./docs/and2270.pdf) +8. [Examples](./docs/QUICK_START.md) ## Sponsoring -I have only one device (with LAN interface), that means that I can't check any issues connected with multiple printing devices, Bluetooth, USB, etc. So it will be reasonable to buy some additional devices for testing purposes. Please contact me via email if you want to help me with that. - -Or you can just send any amount to my [BTC acc](bc1qkarm3y9f5pa5frey2na6e830cqyuzlxtwyme4j). +I'm working on the lib at my free time. If you like the lib and want to support me, you can [buy me a cofee](https://buymeacoffee.com/tr3v3r +). Thanks! -## Troubleshooting +## Known issues 1. For now it's not possible to print and discover on Android simulator. But you can always use real device. 2. If you have an issue with using Flipper on iOS real device, please [try this](./docs/flipperWorkaround.md) workaround. ## Roadmap -- [ ] Add expo example +- [x] Add expo example - [ ] Add print from react View example - [x] Reimplement discovering to have implementation close to native SDK -- [ ] Reimplement printing to have implementation close to native SDK -- [ ] Add queue mechanism for quick print +- [x] Reimplement printing to have implementation close to native SDK +- [x] Add queue mechanism for quick print ## License diff --git a/android/src/main/java/com/reactnativeescposprinter/EposStringHelper.java b/android/src/main/java/com/reactnativeescposprinter/EposStringHelper.java index 3cce8cb..89c2bf7 100644 --- a/android/src/main/java/com/reactnativeescposprinter/EposStringHelper.java +++ b/android/src/main/java/com/reactnativeescposprinter/EposStringHelper.java @@ -1,715 +1,354 @@ package com.reactnativeescposprinter; -import static com.reactnativeescposprinter.ePOSCmd.POS_SUCCESS; - -import android.content.Context; - -import androidx.annotation.NonNull; - -import com.epson.epos2.Epos2CallbackCode; -import com.epson.epos2.Epos2Exception; import com.epson.epos2.printer.Printer; import com.epson.epos2.printer.PrinterStatusInfo; +import com.epson.epos2.Epos2CallbackCode; +import com.epson.epos2.Epos2Exception; +import com.epson.epos2.discovery.Discovery; import org.json.JSONException; import org.json.JSONObject; -import java.util.Locale; - -public class EposStringHelper { - - public static JSONObject makeStatusMessage(PrinterStatusInfo statusInfo) { - - String connection = ""; - String online = ""; - String coverOpen = ""; - String paper = ""; - String paperFeed = ""; - String panelSwitch = ""; - String drawer = ""; - String errorStatus = ""; - String autoRecoverErr = ""; - String adapter = ""; - String batteryLevel = ""; - String paperWait = ""; - - - switch (statusInfo.getConnection()) { - case Printer.TRUE: - connection = "CONNECT"; - break; - case Printer.FALSE: - connection = "DISCONNECT"; - break; - case Printer.UNKNOWN: - connection = "UNKNOWN"; - break; - default: - break; - } - - switch (statusInfo.getOnline()) { - case Printer.TRUE: - online = "ONLINE"; - break; - case Printer.FALSE: - online = "OFFLINE"; - break; - case Printer.UNKNOWN: - online = "UNKNOWN"; - break; - default: - break; - } - - switch (statusInfo.getCoverOpen()) { - case Printer.TRUE: - coverOpen = "COVER_OPEN"; - break; - case Printer.FALSE: - coverOpen = "COVER_CLOSE"; - break; - case Printer.UNKNOWN: - coverOpen = "UNKNOWN"; - break; - default: - break; - } - - switch (statusInfo.getPaper()) { - case Printer.PAPER_OK: - paper = "PAPER_OK"; - break; - case Printer.PAPER_NEAR_END: - paper = "PAPER_NEAR_END"; - break; - case Printer.PAPER_EMPTY: - paper = "PAPER_EMPTY"; - break; - case Printer.UNKNOWN: - paper = "UNKNOWN"; - break; - default: - break; - } - - switch (statusInfo.getPaperFeed()) { - case Printer.TRUE: - paperFeed = "PAPER_FEED"; - break; - case Printer.FALSE: - paperFeed = "PAPER_STOP"; - break; - case Printer.UNKNOWN: - paperFeed = "UNKNOWN"; - break; - default: - break; - } +import com.facebook.react.bridge.Arguments; +import com.facebook.react.bridge.WritableMap; +import com.facebook.react.bridge.ReadableMap; +import com.facebook.react.bridge.ReadableMapKeySetIterator; - switch (statusInfo.getPanelSwitch()) { - case Printer.TRUE: - panelSwitch = "SWITCH_ON"; - break; - case Printer.FALSE: - panelSwitch = "SWITCH_OFF"; - break; - case Printer.UNKNOWN: - panelSwitch = "UNKNOWN"; - break; - default: - break; - } - - switch (statusInfo.getDrawer()) { - case Printer.DRAWER_HIGH: - //This status depends on the drawer setting. - drawer = "DRAWER_HIGH(Drawer close)"; - break; - case Printer.DRAWER_LOW: - //This status depends on the drawer setting. - drawer = "DRAWER_LOW(Drawer open)"; - break; - case Printer.UNKNOWN: - drawer = "UNKNOWN"; - break; - default: - break; - } - - switch (statusInfo.getErrorStatus()) { - case Printer.NO_ERR: - errorStatus = "NO_ERR"; - break; - case Printer.MECHANICAL_ERR: - errorStatus = "MECHANICAL_ERR"; - break; - case Printer.AUTOCUTTER_ERR: - errorStatus = "AUTOCUTTER_ERR"; - break; - case Printer.UNRECOVER_ERR: - errorStatus = "UNRECOVER_ERR"; - break; - case Printer.AUTORECOVER_ERR: - errorStatus = "AUTOCUTTER_ERR"; - break; - case Printer.UNKNOWN: - errorStatus = "UNKNOWN"; - break; - default: - break; - } - - switch (statusInfo.getAutoRecoverError()) { - case Printer.HEAD_OVERHEAT: - autoRecoverErr = "HEAD_OVERHEAT"; - break; - case Printer.MOTOR_OVERHEAT: - autoRecoverErr = "MOTOR_OVERHEAT"; - break; - case Printer.BATTERY_OVERHEAT: - autoRecoverErr = "BATTERY_OVERHEAT"; - break; - case Printer.WRONG_PAPER: - autoRecoverErr = "WRONG_PAPER"; - break; - case Printer.COVER_OPEN: - autoRecoverErr = "COVER_OPEN"; - break; - case Printer.UNKNOWN: - autoRecoverErr = "UNKNOWN"; - break; - default: - break; - } - - switch (statusInfo.getAdapter()) { - case Printer.TRUE: - adapter = "AC ADAPTER CONNECT"; - break; - case Printer.FALSE: - adapter = "AC ADAPTER DISCONNECT"; - break; - case Printer.UNKNOWN: - adapter = "UNKNOWN"; - break; - default: - break; - } - - switch (statusInfo.getBatteryLevel()) { - case Printer.BATTERY_LEVEL_0: - batteryLevel = "BATTERY_LEVEL_0"; - break; - case Printer.BATTERY_LEVEL_1: - batteryLevel = "BATTERY_LEVEL_1"; - break; - case Printer.BATTERY_LEVEL_2: - batteryLevel = "BATTERY_LEVEL_2"; - break; - case Printer.BATTERY_LEVEL_3: - batteryLevel = "BATTERY_LEVEL_3"; - break; - case Printer.BATTERY_LEVEL_4: - batteryLevel = "BATTERY_LEVEL_4"; - break; - case Printer.BATTERY_LEVEL_5: - batteryLevel = "BATTERY_LEVEL_5"; - break; - case Printer.BATTERY_LEVEL_6: - batteryLevel = "BATTERY_LEVEL_6"; - break; - case Printer.UNKNOWN: - batteryLevel = "UNKNOWN"; - break; - default: - break; - } - - switch (statusInfo.getRemovalWaiting()) { - case Printer.EVENT_REMOVAL_WAIT_PAPER: - paperWait = "WAITING_FOR_PAPER_REMOVAL"; - break; - case Printer.EVENT_REMOVAL_WAIT_NONE: - paperWait = "NOT_WAITING_FOR_PAPER_REMOVAL"; - break; - case Printer.UNKNOWN: - paperWait = "UNKNOWN"; - break; - default: - break; - } - - JSONObject jsonStatus = new JSONObject(); - try { - jsonStatus.put("connection", connection); - jsonStatus.put("online",online); - jsonStatus.put("coverOpen",coverOpen); - jsonStatus.put("paper",paper); - jsonStatus.put("paperFeed",paperFeed); - jsonStatus.put("panelSwitch",panelSwitch); - jsonStatus.put("drawer",drawer); - jsonStatus.put("errorStatus",errorStatus); - jsonStatus.put("autoRecoverErr",autoRecoverErr); - jsonStatus.put("adapter",adapter); - jsonStatus.put("batteryLevel",batteryLevel); - jsonStatus.put("paperWait",paperWait); - - } catch (JSONException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - return jsonStatus; - - } +import java.util.HashMap; +import java.util.Map; - public static String convertPrintSpeedEnum2String(int speedEnum, @NonNull Context context) { - - String speedStr = "invalid"; - switch (speedEnum) { - case Printer.SETTING_PRINTSPEED_1: - speedStr = "1"; - break; - case Printer.SETTING_PRINTSPEED_2: - speedStr = "2"; - break; - case Printer.SETTING_PRINTSPEED_3: - speedStr = "3"; - break; - case Printer.SETTING_PRINTSPEED_4: - speedStr = "4"; - break; - case Printer.SETTING_PRINTSPEED_5: - speedStr = "5"; - break; - case Printer.SETTING_PRINTSPEED_6: - speedStr = "6"; - break; - case Printer.SETTING_PRINTSPEED_7: - speedStr = "7"; - break; - case Printer.SETTING_PRINTSPEED_8: - speedStr = "8"; - break; - case Printer.SETTING_PRINTSPEED_9: - speedStr = "9"; - break; - case Printer.SETTING_PRINTSPEED_10: - speedStr = "10"; - break; - case Printer.SETTING_PRINTSPEED_11: - speedStr = "11"; - break; - case Printer.SETTING_PRINTSPEED_12: - speedStr = "12"; - break; - case Printer.SETTING_PRINTSPEED_13: - speedStr = "13"; - break; - case Printer.SETTING_PRINTSPEED_14: - speedStr = "14"; - break; - case Printer.SETTING_PRINTSPEED_15: - speedStr = "15"; - break; - case Printer.SETTING_PRINTSPEED_16: - speedStr = "16"; - break; - case Printer.SETTING_PRINTSPEED_17: - speedStr = "17"; - break; - default: - break; - } - - return speedStr; - - } - - public static String convertPaperWidthEnum2String(int paperWidthEnum, @NonNull Context context) { - - String paperWidthStr = "invalid"; - switch (paperWidthEnum) { - case Printer.SETTING_PAPERWIDTH_58_0: - paperWidthStr = "58mm"; - break; - case Printer.SETTING_PAPERWIDTH_60_0: - paperWidthStr = "60mm"; - break; - case Printer.SETTING_PAPERWIDTH_70_0: - paperWidthStr = "70mm"; - break; - case Printer.SETTING_PAPERWIDTH_76_0: - paperWidthStr = "76mm"; - break; - case Printer.SETTING_PAPERWIDTH_80_0: - paperWidthStr = "80mm"; - break; - default: - break; - } - - return paperWidthStr; - } - - public static String convertPrintDensityEnum2String(int densityEnum, @NonNull Context context) { - String deinsityStr = "invalid"; - switch (densityEnum) { - case Printer.SETTING_PRINTDENSITY_DIP: - deinsityStr = "DIP"; - break; - case Printer.SETTING_PRINTDENSITY_70: - deinsityStr = "70%"; - break; - case Printer.SETTING_PRINTDENSITY_75: - deinsityStr = "75%"; - break; - case Printer.SETTING_PRINTDENSITY_80: - deinsityStr = "80%"; - break; - case Printer.SETTING_PRINTDENSITY_85: - deinsityStr = "85%"; - break; - case Printer.SETTING_PRINTDENSITY_90: - deinsityStr = "90%"; - break; - case Printer.SETTING_PRINTDENSITY_95: - deinsityStr = "95%"; - break; - case Printer.SETTING_PRINTDENSITY_100: - deinsityStr = "100%"; - break; - case Printer.SETTING_PRINTDENSITY_105: - deinsityStr = "105%"; - break; - case Printer.SETTING_PRINTDENSITY_110: - deinsityStr = "110%"; - break; - case Printer.SETTING_PRINTDENSITY_115: - deinsityStr = "115%"; - break; - case Printer.SETTING_PRINTDENSITY_120: - deinsityStr = "120%"; - break; - case Printer.SETTING_PRINTDENSITY_125: - deinsityStr = "125%"; - break; - case Printer.SETTING_PRINTDENSITY_130: - deinsityStr = "130%"; - break; - default: - break; - } +public class EposStringHelper { +private static int ERR_INIT = -1; + + + +public static WritableMap convertStatusInfoToWritableMap(PrinterStatusInfo statusInfo) { + WritableMap statusMessage = Arguments.createMap(); + + statusMessage.putInt("connection",statusInfo.getConnection()); + statusMessage.putInt("online",statusInfo.getOnline()); + statusMessage.putInt("coverOpen",statusInfo.getCoverOpen()); + statusMessage.putInt("paper",statusInfo.getPaper()); + statusMessage.putInt("paperFeed",statusInfo.getPaperFeed()); + statusMessage.putInt("panelSwitch",statusInfo.getPanelSwitch()); + statusMessage.putInt("drawer",statusInfo.getDrawer()); + statusMessage.putInt("errorStatus",statusInfo.getErrorStatus()); + statusMessage.putInt("autoRecoverError",statusInfo.getAutoRecoverError()); + statusMessage.putInt("buzzer",statusInfo.getBuzzer()); + statusMessage.putInt("adapter",statusInfo.getAdapter()); + statusMessage.putInt("batteryLevel", statusInfo.getBatteryLevel()); + statusMessage.putInt("removalWaiting", statusInfo.getRemovalWaiting()); + statusMessage.putInt("paperTakenSensor", statusInfo.getPaperTakenSensor()); + statusMessage.putInt("unrecoverError", statusInfo.getUnrecoverError()); + + return statusMessage; +} - return deinsityStr; - } +public static Map getDiscoveryConstants() { + final Map constants = new HashMap<>(); + // filter options + constants.put("PORTTYPE_ALL", Discovery.PORTTYPE_ALL); + constants.put("PORTTYPE_TCP", Discovery.PORTTYPE_TCP); + constants.put("PORTTYPE_BLUETOOTH", Discovery.PORTTYPE_BLUETOOTH); + constants.put("PORTTYPE_USB", Discovery.PORTTYPE_USB); + constants.put("MODEL_ALL", Discovery.MODEL_ALL); + constants.put("TYPE_ALL", Discovery.TYPE_ALL); + constants.put("TYPE_PRINTER", Discovery.TYPE_PRINTER); + constants.put("TYPE_HYBRID_PRINTER", Discovery.TYPE_HYBRID_PRINTER); + constants.put("TYPE_DISPLAY", Discovery.TYPE_DISPLAY); + constants.put("TYPE_KEYBOARD", Discovery.TYPE_KEYBOARD); + constants.put("TYPE_SCANNER", Discovery.TYPE_SCANNER); + constants.put("TYPE_SERIAL", Discovery.TYPE_SERIAL); + constants.put("TYPE_POS_KEYBOARD", Discovery.TYPE_POS_KEYBOARD); + constants.put("TYPE_MSR", Discovery.TYPE_MSR); + constants.put("TYPE_GFE", Discovery.TYPE_GFE); + constants.put("TYPE_OTHER_PERIPHERAL", Discovery.TYPE_OTHER_PERIPHERAL); + constants.put("FILTER_NAME", Discovery.FILTER_NAME); + constants.put("FILTER_NONE", Discovery.FILTER_NONE); + constants.put("TRUE", Discovery.TRUE); + constants.put("FALSE", Discovery.FALSE); + // return values + constants.put("ERR_PARAM", Epos2Exception.ERR_PARAM); + constants.put("ERR_ILLEGAL", Epos2Exception.ERR_ILLEGAL); + constants.put("ERR_MEMORY", Epos2Exception.ERR_MEMORY); + constants.put("ERR_FAILURE", Epos2Exception.ERR_FAILURE); + constants.put("ERR_PROCESSING", Epos2Exception.ERR_PROCESSING); + + return constants; +} - public static String convertEpos2PrinterSettingTypeEnum2String(int printerSettingTypeEnum) { - - String printerSettingTypeStr = "invalid"; - switch (printerSettingTypeEnum) { - case Printer.SETTING_PAPERWIDTH: - printerSettingTypeStr = "SETTING_PAPERWIDTH"; - break; - case Printer.SETTING_PRINTDENSITY: - printerSettingTypeStr = "SETTING_PRINTDENSITY"; - break; - case Printer.SETTING_PRINTSPEED: - printerSettingTypeStr = "SETTING_PRINTSPEED"; - break; - default: - break; - } - - return printerSettingTypeStr; - - } - - - public static String makeStatusMonitorMessage(int type) { - String msg = ""; - - switch (type) { - case Printer.EVENT_ONLINE: - msg += "ONLINE"; - break; - case Printer.EVENT_OFFLINE: - msg += "OFFLINE"; - break; - case Printer.EVENT_POWER_OFF: - msg += "POWER_OFF"; - break; - case Printer.EVENT_COVER_CLOSE: - msg += "COVER_CLOSE"; - break; - case Printer.EVENT_COVER_OPEN: - msg += "COVER_OPEN"; - break; - case Printer.EVENT_PAPER_OK: - msg += "PAPER_OK"; - break; - case Printer.EVENT_PAPER_NEAR_END: - msg += "PAPER_NEAR_END"; - break; - case Printer.EVENT_PAPER_EMPTY: - msg += "PAPER_EMPTY"; - break; - case Printer.EVENT_DRAWER_HIGH: - //This status depends on the drawer setting. - msg += "DRAWER_HIGH(Drawer close)"; - break; - case Printer.EVENT_DRAWER_LOW: - //This status depends on the drawer setting. - msg += "DRAWER_LOW(Drawer open)"; - break; - case Printer.EVENT_BATTERY_ENOUGH: - msg += "BATTERY_ENOUGH"; - break; - case Printer.EVENT_BATTERY_EMPTY: - msg += "BATTERY_EMPTY"; - break; - case Printer.EVENT_REMOVAL_WAIT_PAPER: - msg += "WAITING_FOR_PAPER_REMOVAL"; - break; - case Printer.EVENT_REMOVAL_WAIT_NONE: - msg += "NOT_WAITING_FOR_PAPER_REMOVAL"; - break; - case Printer.EVENT_AUTO_RECOVER_ERROR: - msg += "AUTO_RECOVER_ERROR"; - break; - case Printer.EVENT_AUTO_RECOVER_OK: - msg += "AUTO_RECOVER_OK"; - break; - case Printer.EVENT_UNRECOVERABLE_ERROR: - msg += "UNRECOVERABLE_ERROR"; - break; - default: - break; - } - msg += "\n"; - return msg; - } - - public static String getEposExceptionText(int state) { - String return_text = ""; - switch (state) { - case POS_SUCCESS: - return_text = "SUCCESS"; - break; - case Epos2Exception.ERR_PARAM: - return_text = "ERR_PARAM"; - break; - case Epos2Exception.ERR_CONNECT: - return_text = "ERR_CONNECT"; - break; - case Epos2Exception.ERR_TIMEOUT: - return_text = "ERR_TIMEOUT"; - break; - case Epos2Exception.ERR_MEMORY: - return_text = "ERR_MEMORY"; - break; - case Epos2Exception.ERR_ILLEGAL: - return_text = "ERR_ILLEGAL"; - break; - case Epos2Exception.ERR_PROCESSING: - return_text = "ERR_PROCESSING"; - break; - case Epos2Exception.ERR_NOT_FOUND: - return_text = "ERR_NOT_FOUND"; - break; - case Epos2Exception.ERR_IN_USE: - return_text = "ERR_IN_USE"; - break; - case Epos2Exception.ERR_TYPE_INVALID: - return_text = "ERR_TYPE_INVALID"; - break; - case Epos2Exception.ERR_DISCONNECT: - return_text = "ERR_DISCONNECT"; - break; - case Epos2Exception.ERR_ALREADY_OPENED: - return_text = "ERR_ALREADY_OPENED"; - break; - case Epos2Exception.ERR_ALREADY_USED: - return_text = "ERR_ALREADY_USED"; - break; - case Epos2Exception.ERR_BOX_COUNT_OVER: - return_text = "ERR_BOX_COUNT_OVER"; - break; - case Epos2Exception.ERR_BOX_CLIENT_OVER: - return_text = "ERR_BOX_CLIENT_OVER"; - break; - case Epos2Exception.ERR_UNSUPPORTED: - return_text = "ERR_UNSUPPORTED"; - break; - case Epos2Exception.ERR_FAILURE: - return_text = "ERR_FAILURE"; - break; - default: - return_text = String.format(Locale.ENGLISH, "%d", state); - break; - } - return return_text; - } - public static String getEposResultText(int state) { - String return_text = ""; - switch (state) { - case Epos2CallbackCode.CODE_SUCCESS: - return_text = "PRINT_SUCCESS"; - break; - case Epos2CallbackCode.CODE_PRINTING: - return_text = "PRINTING"; - break; - case Epos2CallbackCode.CODE_ERR_AUTORECOVER: - return_text = "ERR_AUTORECOVER"; - break; - case Epos2CallbackCode.CODE_ERR_COVER_OPEN: - return_text = "ERR_COVER_OPEN"; - break; - case Epos2CallbackCode.CODE_ERR_CUTTER: - return_text = "ERR_CUTTER"; - break; - case Epos2CallbackCode.CODE_ERR_MECHANICAL: - return_text = "ERR_MECHANICAL"; - break; - case Epos2CallbackCode.CODE_ERR_EMPTY: - return_text = "ERR_EMPTY"; - break; - case Epos2CallbackCode.CODE_ERR_UNRECOVERABLE: - return_text = "ERR_UNRECOVERABLE"; - break; - case Epos2CallbackCode.CODE_ERR_FAILURE: - return_text = "ERR_FAILURE"; - break; - case Epos2CallbackCode.CODE_ERR_NOT_FOUND: - return_text = "ERR_NOT_FOUND"; - break; - case Epos2CallbackCode.CODE_ERR_SYSTEM: - return_text = "ERR_SYSTEM"; - break; - case Epos2CallbackCode.CODE_ERR_PORT: - return_text = "ERR_PORT"; - break; - case Epos2CallbackCode.CODE_ERR_TIMEOUT: - return_text = "ERR_TIMEOUT"; - break; - case Epos2CallbackCode.CODE_ERR_JOB_NOT_FOUND: - return_text = "ERR_JOB_NOT_FOUND"; - break; - case Epos2CallbackCode.CODE_ERR_SPOOLER: - return_text = "ERR_SPOOLER"; - break; - case Epos2CallbackCode.CODE_ERR_BATTERY_LOW: - return_text = "ERR_BATTERY_LOW"; - break; - case Epos2CallbackCode.CODE_ERR_TOO_MANY_REQUESTS: - return_text = "ERR_TOO_MANY_REQUESTS"; - break; - case Epos2CallbackCode.CODE_ERR_REQUEST_ENTITY_TOO_LARGE: - return_text = "ERR_REQUEST_ENTITY_TOO_LARGE"; - break; - case Epos2CallbackCode.CODE_CANCELED: - return_text = "CODE_CANCELED"; - break; - case Epos2CallbackCode.CODE_ERR_NO_MICR_DATA: - return_text = "ERR_NO_MICR_DATA"; - break; - case Epos2CallbackCode.CODE_ERR_ILLEGAL_LENGTH: - return_text = "ERR_ILLEGAL_LENGTH"; - break; - case Epos2CallbackCode.CODE_ERR_NO_MAGNETIC_DATA: - return_text = "ERR_NO_MAGNETIC_DATA"; - break; - case Epos2CallbackCode.CODE_ERR_RECOGNITION: - return_text = "ERR_RECOGNITION"; - break; - case Epos2CallbackCode.CODE_ERR_READ: - return_text = "ERR_READ"; - break; - case Epos2CallbackCode.CODE_ERR_NOISE_DETECTED: - return_text = "ERR_NOISE_DETECTED"; - break; - case Epos2CallbackCode.CODE_ERR_PAPER_JAM: - return_text = "ERR_PAPER_JAM"; - break; - case Epos2CallbackCode.CODE_ERR_PAPER_PULLED_OUT: - return_text = "ERR_PAPER_PULLED_OUT"; - break; - case Epos2CallbackCode.CODE_ERR_CANCEL_FAILED: - return_text = "ERR_CANCEL_FAILED"; - break; - case Epos2CallbackCode.CODE_ERR_PAPER_TYPE: - return_text = "ERR_PAPER_TYPE"; - break; - case Epos2CallbackCode.CODE_ERR_WAIT_INSERTION: - return_text = "ERR_WAIT_INSERTION"; - break; - case Epos2CallbackCode.CODE_ERR_ILLEGAL: - return_text = "ERR_ILLEGAL"; - break; - case Epos2CallbackCode.CODE_ERR_INSERTED: - return_text = "ERR_INSERTED"; - break; - case Epos2CallbackCode.CODE_ERR_WAIT_REMOVAL: - return_text = "ERR_WAIT_REMOVAL"; - break; - case Epos2CallbackCode.CODE_ERR_DEVICE_BUSY: - return_text = "ERR_DEVICE_BUSY"; - break; - case Epos2CallbackCode.CODE_ERR_IN_USE: - return_text = "ERR_IN_USE"; - break; - case Epos2CallbackCode.CODE_ERR_CONNECT: - return_text = "ERR_CONNECT"; - break; - case Epos2CallbackCode.CODE_ERR_DISCONNECT: - return_text = "ERR_DISCONNECT"; - break; - case Epos2CallbackCode.CODE_ERR_MEMORY: - return_text = "ERR_MEMORY"; - break; - case Epos2CallbackCode.CODE_ERR_PROCESSING: - return_text = "ERR_PROCESSING"; - break; - case Epos2CallbackCode.CODE_ERR_PARAM: - return_text = "ERR_PARAM"; - break; - case Epos2CallbackCode.CODE_RETRY: - return_text = "RETRY"; - break; - case Epos2CallbackCode.CODE_ERR_DIFFERENT_MODEL: - return_text = "ERR_DIFFERENT_MODEL"; - break; - case Epos2CallbackCode.CODE_ERR_DIFFERENT_VERSION: - return_text = "ERR_DIFFERENT_VERSION"; - break; - case Epos2CallbackCode.CODE_ERR_DATA_CORRUPTED: - return_text = "ERR_DATA_CORRUPTED"; - break; - default: - return_text = String.format("%d", state); - break; - } - return return_text; +public static Map getPrinterConstants() { + final Map constants = new HashMap<>(); + + // init models lang + constants.put("MODEL_ANK", Printer.MODEL_ANK); + constants.put("MODEL_CHINESE", Printer.MODEL_CHINESE); + constants.put("MODEL_TAIWAN", Printer.MODEL_TAIWAN); + constants.put("MODEL_KOREAN", Printer.MODEL_KOREAN); + constants.put("MODEL_THAI", Printer.MODEL_THAI); + constants.put("MODEL_SOUTHASIA", Printer.MODEL_SOUTHASIA); + + // cut types + constants.put("CUT_FEED", Printer.CUT_FEED); + constants.put("CUT_NO_FEED", Printer.CUT_NO_FEED); + constants.put("CUT_RESERVE", Printer.CUT_RESERVE); + constants.put("FULL_CUT_FEED", Printer.FULL_CUT_FEED); + constants.put("FULL_CUT_NO_FEED", Printer.FULL_CUT_NO_FEED); + constants.put("FULL_CUT_RESERVE", Printer.FULL_CUT_RESERVE); + constants.put("PARAM_DEFAULT", Printer.PARAM_DEFAULT); + constants.put("PARAM_UNSPECIFIED", Printer.PARAM_UNSPECIFIED); + + // errors + constants.put("ERR_PARAM", Epos2Exception.ERR_PARAM); + constants.put("ERR_MEMORY", Epos2Exception.ERR_MEMORY); + constants.put("ERR_UNSUPPORTED", Epos2Exception.ERR_UNSUPPORTED); + constants.put("ERR_FAILURE", Epos2Exception.ERR_FAILURE); + constants.put("ERR_PROCESSING", Epos2Exception.ERR_PROCESSING); + constants.put("ERR_CONNECT", Epos2Exception.ERR_CONNECT); + constants.put("ERR_TIMEOUT", Epos2Exception.ERR_TIMEOUT); + constants.put("ERR_ILLEGAL", Epos2Exception.ERR_ILLEGAL); + constants.put("ERR_NOT_FOUND", Epos2Exception.ERR_NOT_FOUND); + constants.put("ERR_IN_USE", Epos2Exception.ERR_IN_USE); + constants.put("ERR_TYPE_INVALID", Epos2Exception.ERR_TYPE_INVALID); + constants.put("ERR_RECOVERY_FAILURE", Epos2Exception.ERR_RECOVERY_FAILURE); + constants.put("ERR_DISCONNECT", Epos2Exception.ERR_DISCONNECT); + constants.put("ERR_INIT", ERR_INIT); + + // code errors + + constants.put("CODE_ERR_AUTORECOVER", Epos2CallbackCode.CODE_ERR_AUTORECOVER); + constants.put("CODE_ERR_COVER_OPEN", Epos2CallbackCode.CODE_ERR_COVER_OPEN); + constants.put("CODE_ERR_CUTTER", Epos2CallbackCode.CODE_ERR_CUTTER); + constants.put("CODE_ERR_MECHANICAL", Epos2CallbackCode.CODE_ERR_MECHANICAL); + constants.put("CODE_ERR_EMPTY", Epos2CallbackCode.CODE_ERR_EMPTY); + constants.put("CODE_ERR_UNRECOVERABLE", Epos2CallbackCode.CODE_ERR_UNRECOVERABLE); + constants.put("CODE_ERR_FAILURE", Epos2CallbackCode.CODE_ERR_FAILURE); + constants.put("CODE_ERR_NOT_FOUND", Epos2CallbackCode.CODE_ERR_NOT_FOUND); + constants.put("CODE_ERR_SYSTEM", Epos2CallbackCode.CODE_ERR_SYSTEM); + constants.put("CODE_ERR_PORT", Epos2CallbackCode.CODE_ERR_PORT); + constants.put("CODE_ERR_TIMEOUT", Epos2CallbackCode.CODE_ERR_TIMEOUT); + constants.put("CODE_ERR_JOB_NOT_FOUND", Epos2CallbackCode.CODE_ERR_JOB_NOT_FOUND); + constants.put("CODE_ERR_SPOOLER", Epos2CallbackCode.CODE_ERR_SPOOLER); + constants.put("CODE_ERR_BATTERY_LOW", Epos2CallbackCode.CODE_ERR_BATTERY_LOW); + constants.put("CODE_ERR_TOO_MANY_REQUESTS", Epos2CallbackCode.CODE_ERR_TOO_MANY_REQUESTS); + constants.put("CODE_ERR_REQUEST_ENTITY_TOO_LARGE", Epos2CallbackCode.CODE_ERR_REQUEST_ENTITY_TOO_LARGE); + constants.put("CODE_ERR_WAIT_REMOVAL", Epos2CallbackCode.CODE_ERR_WAIT_REMOVAL); + constants.put("CODE_PRINTING", Epos2CallbackCode.CODE_PRINTING); + constants.put("CODE_ERR_MEMORY", Epos2CallbackCode.CODE_ERR_MEMORY); + constants.put("CODE_ERR_PROCESSING", Epos2CallbackCode.CODE_ERR_PROCESSING); + constants.put("CODE_ERR_ILLEGAL", Epos2CallbackCode.CODE_ERR_ILLEGAL); + constants.put("CODE_ERR_DEVICE_BUSY", Epos2CallbackCode.CODE_ERR_DEVICE_BUSY); + + // get printer settings + + constants.put("PRINTER_SETTING_PAPERWIDTH", Printer.SETTING_PAPERWIDTH); + constants.put("PRINTER_SETTING_PRINTDENSITY", Printer.SETTING_PRINTDENSITY); + constants.put("PRINTER_SETTING_PRINTSPEED", Printer.SETTING_PRINTSPEED); + + constants.put("PRINTER_SETTING_PAPERWIDTH58_0", Printer.SETTING_PAPERWIDTH_58_0); + constants.put("PRINTER_SETTING_PAPERWIDTH60_0", Printer.SETTING_PAPERWIDTH_60_0); + constants.put("PRINTER_SETTING_PAPERWIDTH70_0", Printer.SETTING_PAPERWIDTH_70_0); + constants.put("PRINTER_SETTING_PAPERWIDTH76_0", Printer.SETTING_PAPERWIDTH_76_0); + constants.put("PRINTER_SETTING_PAPERWIDTH80_0", Printer.SETTING_PAPERWIDTH_80_0); + constants.put("PRINTER_SETTING_PRINTDENSITYDIP", Printer.SETTING_PRINTDENSITY_DIP); + constants.put("PRINTER_SETTING_PRINTDENSITY70", Printer.SETTING_PRINTDENSITY_70); + constants.put("PRINTER_SETTING_PRINTDENSITY75", Printer.SETTING_PRINTDENSITY_75); + constants.put("PRINTER_SETTING_PRINTDENSITY80", Printer.SETTING_PRINTDENSITY_80); + constants.put("PRINTER_SETTING_PRINTDENSITY85", Printer.SETTING_PRINTDENSITY_85); + constants.put("PRINTER_SETTING_PRINTDENSITY90", Printer.SETTING_PRINTDENSITY_90); + constants.put("PRINTER_SETTING_PRINTDENSITY95", Printer.SETTING_PRINTDENSITY_95); + constants.put("PRINTER_SETTING_PRINTDENSITY100", Printer.SETTING_PRINTDENSITY_100); + constants.put("PRINTER_SETTING_PRINTDENSITY105", Printer.SETTING_PRINTDENSITY_105); + constants.put("PRINTER_SETTING_PRINTDENSITY110", Printer.SETTING_PRINTDENSITY_110); + constants.put("PRINTER_SETTING_PRINTDENSITY115", Printer.SETTING_PRINTDENSITY_115); + constants.put("PRINTER_SETTING_PRINTDENSITY120", Printer.SETTING_PRINTDENSITY_120); + constants.put("PRINTER_SETTING_PRINTDENSITY125", Printer.SETTING_PRINTDENSITY_125); + constants.put("PRINTER_SETTING_PRINTDENSITY130", Printer.SETTING_PRINTDENSITY_130); + constants.put("PRINTER_SETTING_PRINTSPEED1", Printer.SETTING_PRINTSPEED_1); + constants.put("PRINTER_SETTING_PRINTSPEED2", Printer.SETTING_PRINTSPEED_2); + constants.put("PRINTER_SETTING_PRINTSPEED3", Printer.SETTING_PRINTSPEED_3); + constants.put("PRINTER_SETTING_PRINTSPEED4", Printer.SETTING_PRINTSPEED_4); + constants.put("PRINTER_SETTING_PRINTSPEED5", Printer.SETTING_PRINTSPEED_5); + constants.put("PRINTER_SETTING_PRINTSPEED6", Printer.SETTING_PRINTSPEED_6); + constants.put("PRINTER_SETTING_PRINTSPEED7", Printer.SETTING_PRINTSPEED_7); + constants.put("PRINTER_SETTING_PRINTSPEED8", Printer.SETTING_PRINTSPEED_8); + constants.put("PRINTER_SETTING_PRINTSPEED9", Printer.SETTING_PRINTSPEED_9); + constants.put("PRINTER_SETTING_PRINTSPEED10", Printer.SETTING_PRINTSPEED_10); + constants.put("PRINTER_SETTING_PRINTSPEED11", Printer.SETTING_PRINTSPEED_11); + constants.put("PRINTER_SETTING_PRINTSPEED12", Printer.SETTING_PRINTSPEED_12); + constants.put("PRINTER_SETTING_PRINTSPEED13", Printer.SETTING_PRINTSPEED_13); + constants.put("PRINTER_SETTING_PRINTSPEED14", Printer.SETTING_PRINTSPEED_14); + constants.put("PRINTER_SETTING_PRINTSPEED15", Printer.SETTING_PRINTSPEED_15); + constants.put("PRINTER_SETTING_PRINTSPEED16", Printer.SETTING_PRINTSPEED_16); + constants.put("PRINTER_SETTING_PRINTSPEED17", Printer.SETTING_PRINTSPEED_17); + + // printer status + + constants.put("TRUE", Printer.TRUE); + constants.put("FALSE", Printer.FALSE); + constants.put("UNKNOWN", Printer.UNKNOWN); + constants.put("PAPER_OK", Printer.PAPER_OK); + constants.put("PAPER_NEAR_END", Printer.PAPER_NEAR_END); + constants.put("PAPER_EMPTY", Printer.PAPER_EMPTY); + constants.put("SWITCH_ON", Printer.SWITCH_ON); + constants.put("SWITCH_OFF", Printer.SWITCH_OFF); + constants.put("DRAWER_HIGH", Printer.DRAWER_HIGH); + constants.put("DRAWER_LOW", Printer.DRAWER_LOW); + constants.put("NO_ERR", Printer.NO_ERR); + constants.put("MECHANICAL_ERR", Printer.MECHANICAL_ERR); + constants.put("AUTOCUTTER_ERR", Printer.AUTOCUTTER_ERR); + constants.put("UNRECOVER_ERR", Printer.UNRECOVER_ERR); + constants.put("AUTORECOVER_ERR", Printer.AUTORECOVER_ERR); + constants.put("HEAD_OVERHEAT", Printer.HEAD_OVERHEAT); + constants.put("MOTOR_OVERHEAT", Printer.MOTOR_OVERHEAT); + constants.put("BATTERY_OVERHEAT", Printer.BATTERY_OVERHEAT); + constants.put("WRONG_PAPER", Printer.WRONG_PAPER); + constants.put("COVER_OPEN", Printer.COVER_OPEN); + constants.put("EPOS2_BATTERY_LEVEL_6", Printer.BATTERY_LEVEL_6); + constants.put("EPOS2_BATTERY_LEVEL_5", Printer.BATTERY_LEVEL_5); + constants.put("EPOS2_BATTERY_LEVEL_4", Printer.BATTERY_LEVEL_4); + constants.put("EPOS2_BATTERY_LEVEL_3", Printer.BATTERY_LEVEL_3); + constants.put("EPOS2_BATTERY_LEVEL_2", Printer.BATTERY_LEVEL_2); + constants.put("EPOS2_BATTERY_LEVEL_1", Printer.BATTERY_LEVEL_1); + constants.put("EPOS2_BATTERY_LEVEL_0", Printer.BATTERY_LEVEL_0); + constants.put("REMOVAL_WAIT_PAPER", Printer.REMOVAL_WAIT_PAPER); + constants.put("REMOVAL_WAIT_NONE", Printer.REMOVAL_WAIT_NONE); + constants.put("REMOVAL_DETECT_PAPER", Printer.REMOVAL_DETECT_PAPER); + constants.put("REMOVAL_DETECT_PAPER_NONE", Printer.REMOVAL_DETECT_PAPER_NONE); + constants.put("REMOVAL_DETECT_UNKNOWN", Printer.REMOVAL_DETECT_UNKNOWN); + constants.put("HIGH_VOLTAGE_ERR", Printer.HIGH_VOLTAGE_ERR); + constants.put("LOW_VOLTAGE_ERR", Printer.LOW_VOLTAGE_ERR); + + + // image + constants.put("COLOR_NONE", Printer.COLOR_NONE); + constants.put("COLOR_1", Printer.COLOR_1); + constants.put("COLOR_2", Printer.COLOR_2); + constants.put("COLOR_3", Printer.COLOR_3); + constants.put("COLOR_4", Printer.COLOR_4); + constants.put("MODE_MONO", Printer.MODE_MONO); + constants.put("MODE_GRAY16", Printer.MODE_GRAY16); + constants.put("MODE_MONO_HIGH_DENSITY", Printer.MODE_MONO_HIGH_DENSITY); + constants.put("HALFTONE_DITHER", Printer.HALFTONE_DITHER); + constants.put("HALFTONE_ERROR_DIFFUSION", Printer.HALFTONE_ERROR_DIFFUSION); + constants.put("HALFTONE_THRESHOLD", Printer.HALFTONE_THRESHOLD); + constants.put("COMPRESS_DEFLATE", Printer.COMPRESS_DEFLATE); + constants.put("COMPRESS_NONE", Printer.COMPRESS_NONE); + constants.put("COMPRESS_AUTO", Printer.COMPRESS_AUTO); + + // barcode + constants.put("BARCODE_UPC_A", Printer.BARCODE_UPC_A); + constants.put("BARCODE_UPC_E", Printer.BARCODE_UPC_E); + constants.put("BARCODE_EAN13", Printer.BARCODE_EAN13); + constants.put("BARCODE_JAN13", Printer.BARCODE_JAN13); + constants.put("BARCODE_EAN8", Printer.BARCODE_EAN8); + constants.put("BARCODE_JAN8", Printer.BARCODE_JAN8); + constants.put("BARCODE_CODE39", Printer.BARCODE_CODE39); + constants.put("BARCODE_ITF", Printer.BARCODE_ITF); + constants.put("BARCODE_CODABAR", Printer.BARCODE_CODABAR); + constants.put("BARCODE_CODE93", Printer.BARCODE_CODE93); + constants.put("BARCODE_CODE128", Printer.BARCODE_CODE128); + constants.put("BARCODE_CODE128_AUTO", Printer.BARCODE_CODE128_AUTO); + constants.put("BARCODE_GS1_128", Printer.BARCODE_GS1_128); + constants.put("BARCODE_GS1_DATABAR_OMNIDIRECTIONAL", Printer.BARCODE_GS1_DATABAR_OMNIDIRECTIONAL); + constants.put("BARCODE_GS1_DATABAR_TRUNCATED", Printer.BARCODE_GS1_DATABAR_TRUNCATED); + constants.put("BARCODE_GS1_DATABAR_LIMITED", Printer.BARCODE_GS1_DATABAR_LIMITED); + constants.put("BARCODE_GS1_DATABAR_EXPANDED", Printer.BARCODE_GS1_DATABAR_EXPANDED); + constants.put("HRI_NONE", Printer.HRI_NONE); + constants.put("HRI_ABOVE", Printer.HRI_ABOVE); + constants.put("HRI_BELOW", Printer.HRI_BELOW); + constants.put("HRI_BOTH", Printer.HRI_BOTH); + + // font + + constants.put("FONT_A", Printer.FONT_A); + constants.put("FONT_B", Printer.FONT_B); + constants.put("FONT_C", Printer.FONT_C); + constants.put("FONT_D", Printer.FONT_D); + constants.put("FONT_E", Printer.FONT_E); + + // symbol + + constants.put("SYMBOL_PDF417_STANDARD", Printer.SYMBOL_PDF417_STANDARD); + constants.put("SYMBOL_PDF417_TRUNCATED", Printer.SYMBOL_PDF417_TRUNCATED); + constants.put("SYMBOL_QRCODE_MODEL_1", Printer.SYMBOL_QRCODE_MODEL_1); + constants.put("SYMBOL_QRCODE_MODEL_2", Printer.SYMBOL_QRCODE_MODEL_2); + constants.put("SYMBOL_QRCODE_MICRO", Printer.SYMBOL_QRCODE_MICRO); + constants.put("SYMBOL_MAXICODE_MODE_2", Printer.SYMBOL_MAXICODE_MODE_2); + constants.put("SYMBOL_MAXICODE_MODE_3", Printer.SYMBOL_MAXICODE_MODE_3); + constants.put("SYMBOL_MAXICODE_MODE_4", Printer.SYMBOL_MAXICODE_MODE_4); + constants.put("SYMBOL_MAXICODE_MODE_5", Printer.SYMBOL_MAXICODE_MODE_5); + constants.put("SYMBOL_MAXICODE_MODE_6", Printer.SYMBOL_MAXICODE_MODE_6); + constants.put("SYMBOL_GS1_DATABAR_STACKED", Printer.SYMBOL_GS1_DATABAR_STACKED); + constants.put("SYMBOL_GS1_DATABAR_STACKED_OMNIDIRECTIONAL", Printer.SYMBOL_GS1_DATABAR_STACKED_OMNIDIRECTIONAL); + constants.put("SYMBOL_GS1_DATABAR_EXPANDED_STACKED", Printer.SYMBOL_GS1_DATABAR_EXPANDED_STACKED); + constants.put("SYMBOL_AZTECCODE_FULLRANGE", Printer.SYMBOL_AZTECCODE_FULLRANGE); + constants.put("SYMBOL_AZTECCODE_COMPACT", Printer.SYMBOL_AZTECCODE_COMPACT); + constants.put("SYMBOL_DATAMATRIX_SQUARE", Printer.SYMBOL_DATAMATRIX_SQUARE); + constants.put("SYMBOL_DATAMATRIX_RECTANGLE_8", Printer.SYMBOL_DATAMATRIX_RECTANGLE_8); + constants.put("SYMBOL_DATAMATRIX_RECTANGLE_12", Printer.SYMBOL_DATAMATRIX_RECTANGLE_12); + constants.put("SYMBOL_DATAMATRIX_RECTANGLE_16", Printer.SYMBOL_DATAMATRIX_RECTANGLE_16); + constants.put("LEVEL_0", Printer.LEVEL_0); + constants.put("LEVEL_1", Printer.LEVEL_1); + constants.put("LEVEL_2", Printer.LEVEL_2); + constants.put("LEVEL_3", Printer.LEVEL_3); + constants.put("LEVEL_4", Printer.LEVEL_4); + constants.put("LEVEL_5", Printer.LEVEL_5); + constants.put("LEVEL_6", Printer.LEVEL_6); + constants.put("LEVEL_7", Printer.LEVEL_7); + constants.put("LEVEL_8", Printer.LEVEL_8); + constants.put("LEVEL_L", Printer.LEVEL_L); + constants.put("LEVEL_M", Printer.LEVEL_M); + constants.put("LEVEL_Q", Printer.LEVEL_Q); + constants.put("LEVEL_H", Printer.LEVEL_H); + + // add pulse + + constants.put("DRAWER_2PIN", Printer.DRAWER_2PIN); + constants.put("DRAWER_5PIN", Printer.DRAWER_5PIN); + constants.put("PULSE_100", Printer.PULSE_100); + constants.put("PULSE_200", Printer.PULSE_200); + constants.put("PULSE_300", Printer.PULSE_300); + constants.put("PULSE_400", Printer.PULSE_400); + constants.put("PULSE_500", Printer.PULSE_500); + + // text align + + constants.put("ALIGN_LEFT", Printer.ALIGN_LEFT); + constants.put("ALIGN_CENTER", Printer.ALIGN_CENTER); + constants.put("ALIGN_RIGHT", Printer.ALIGN_RIGHT); + + // lang + + constants.put("LANG_EN", Printer.LANG_EN); + constants.put("LANG_JA", Printer.LANG_JA); + constants.put("LANG_ZH_CN", Printer.LANG_ZH_CN); + constants.put("LANG_ZH_TW", Printer.LANG_ZH_TW); + constants.put("LANG_KO", Printer.LANG_KO); + constants.put("LANG_TH", Printer.LANG_TH); + constants.put("LANG_VI", Printer.LANG_VI); + constants.put("LANG_MULTI", Printer.LANG_MULTI); + + return constants; } - public static int getPrinterSeries(final String deviceName) { +public static int getPrinterSeries(final String deviceName) { if (deviceName == null || deviceName.isEmpty()) return Printer.TM_T88; - if (deviceName.startsWith("TM-T88VII")) return Printer.TM_T88VII; - if (deviceName.startsWith("TM-m30II")) return Printer.TM_M30II; + if (deviceName.startsWith("TM-m10")) return Printer.TM_M10; if (deviceName.startsWith("TM-m30")) return Printer.TM_M30; - if (deviceName.startsWith("TM-L90LFC")) return Printer.TM_L90LFC; - if (deviceName.startsWith("TM-L90")) return Printer.TM_L90; + if (deviceName.startsWith("TM-m30III")) return Printer.TM_M30III; + if (deviceName.startsWith("TM-m30II")) return Printer.TM_M30II; + if (deviceName.startsWith("TM-m50II")) return Printer.TM_M50II; if (deviceName.startsWith("TM-m50")) return Printer.TM_M50; - if (deviceName.startsWith("TM-L100")) return Printer.TM_L100; - if (deviceName.startsWith("TM-m10")) return Printer.TM_M10; + if (deviceName.startsWith("TM-P20II")) return Printer.TM_P20II; if (deviceName.startsWith("TM-P20")) return Printer.TM_P20; if (deviceName.startsWith("TM-P60II")) return Printer.TM_P60II; if (deviceName.startsWith("TM-P60")) return Printer.TM_P60; + if (deviceName.startsWith("TM-P80II")) return Printer.TM_P80II; if (deviceName.startsWith("TM-P80")) return Printer.TM_P80; if (deviceName.startsWith("TM-T20")) return Printer.TM_T20; if (deviceName.startsWith("TM-T60")) return Printer.TM_T60; @@ -718,16 +357,65 @@ public static int getPrinterSeries(final String deviceName) { if (deviceName.startsWith("TM-T82")) return Printer.TM_T82; if (deviceName.startsWith("TM-T83III")) return Printer.TM_T83III; if (deviceName.startsWith("TM-T83")) return Printer.TM_T83; + if (deviceName.startsWith("TM-T88VII")) return Printer.TM_T88VII; if (deviceName.startsWith("TM-T88")) return Printer.TM_T88; - if (deviceName.startsWith("TM-T90KP")) return Printer.TM_T90KP; if (deviceName.startsWith("TM-T90")) return Printer.TM_T90; + if (deviceName.startsWith("TM-T100")) return Printer.TM_T100; if (deviceName.startsWith("TM-U220")) return Printer.TM_U220; if (deviceName.startsWith("TM-U330")) return Printer.TM_U330; + if (deviceName.startsWith("TM-L90LFC")) return Printer.TM_L90LFC; + if (deviceName.startsWith("TM-L90")) return Printer.TM_L90; + if (deviceName.startsWith("TM-L100")) return Printer.TM_L100; if (deviceName.startsWith("TM-H6000")) return Printer.TM_H6000; - if (deviceName.startsWith("TM-T100")) return Printer.TM_T100; - if (deviceName.startsWith("TS-100")) return Printer.TS_100; return Printer.TM_T88; } + + + public static String convertMapToString(ReadableMap readableMap) { + try{ + JSONObject object = new JSONObject(); + ReadableMapKeySetIterator iterator = readableMap.keySetIterator(); + while (iterator.hasNextKey()) { + String key = iterator.nextKey(); + switch (readableMap.getType(key)) { + case Null: + object.put(key, JSONObject.NULL); + break; + case Boolean: + object.put(key, readableMap.getBoolean(key)); + break; + case Number: + object.put(key, readableMap.getDouble(key)); + break; + case String: + object.put(key, readableMap.getString(key)); + break; + } + } + return object.toString(); + + } catch(Exception e) { + return ""; + } + } + + public static String getErrorTextData(int data, String type) { + String stringData = String.valueOf(data); + if(!type.isEmpty()) { + WritableMap errorData = Arguments.createMap(); + errorData.putString("data", stringData); + errorData.putString("type", type); + + return convertMapToString(errorData); + } + + return stringData; + } + + + public static int getInitErrorResultCode() { + return ERR_INIT; + } } diff --git a/android/src/main/java/com/reactnativeescposprinter/EscPosPrinterDiscoveryModule.java b/android/src/main/java/com/reactnativeescposprinter/EscPosPrinterDiscoveryModule.java index f2b1616..2e73e4a 100644 --- a/android/src/main/java/com/reactnativeescposprinter/EscPosPrinterDiscoveryModule.java +++ b/android/src/main/java/com/reactnativeescposprinter/EscPosPrinterDiscoveryModule.java @@ -6,7 +6,6 @@ import androidx.annotation.NonNull; import androidx.annotation.Nullable; -import com.facebook.react.bridge.Promise; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; @@ -40,6 +39,9 @@ import com.google.android.gms.common.GoogleApiAvailability; import com.google.android.gms.common.ConnectionResult; +import com.reactnativeescposprinter.EposStringHelper; + + @ReactModule(name = EscPosPrinterDiscoveryModule.NAME) public class EscPosPrinterDiscoveryModule extends ReactContextBaseJavaModule implements ActivityEventListener { @@ -56,39 +58,10 @@ public EscPosPrinterDiscoveryModule(ReactApplicationContext reactContext) { reactContext.addActivityEventListener(this); } - @Override - public Map getConstants() { - final Map constants = new HashMap<>(); - // filter options - constants.put("PORTTYPE_ALL", Discovery.PORTTYPE_ALL); - constants.put("PORTTYPE_TCP", Discovery.PORTTYPE_TCP); - constants.put("PORTTYPE_BLUETOOTH", Discovery.PORTTYPE_BLUETOOTH); - constants.put("PORTTYPE_USB", Discovery.PORTTYPE_USB); - constants.put("MODEL_ALL", Discovery.MODEL_ALL); - constants.put("TYPE_ALL", Discovery.TYPE_ALL); - constants.put("TYPE_PRINTER", Discovery.TYPE_PRINTER); - constants.put("TYPE_HYBRID_PRINTER", Discovery.TYPE_HYBRID_PRINTER); - constants.put("TYPE_DISPLAY", Discovery.TYPE_DISPLAY); - constants.put("TYPE_KEYBOARD", Discovery.TYPE_KEYBOARD); - constants.put("TYPE_SCANNER", Discovery.TYPE_SCANNER); - constants.put("TYPE_SERIAL", Discovery.TYPE_SERIAL); - constants.put("TYPE_POS_KEYBOARD", Discovery.TYPE_POS_KEYBOARD); - constants.put("TYPE_MSR", Discovery.TYPE_MSR); - constants.put("TYPE_GFE", Discovery.TYPE_GFE); - constants.put("TYPE_OTHER_PERIPHERAL", Discovery.TYPE_OTHER_PERIPHERAL); - constants.put("FILTER_NAME", Discovery.FILTER_NAME); - constants.put("FILTER_NONE", Discovery.FILTER_NONE); - constants.put("TRUE", Discovery.TRUE); - constants.put("FALSE", Discovery.FALSE); - // return values - constants.put("ERR_PARAM", Epos2Exception.ERR_PARAM); - constants.put("ERR_ILLEGAL", Epos2Exception.ERR_ILLEGAL); - constants.put("ERR_MEMORY", Epos2Exception.ERR_MEMORY); - constants.put("ERR_FAILURE", Epos2Exception.ERR_FAILURE); - constants.put("ERR_PROCESSING", Epos2Exception.ERR_PROCESSING); - - return constants; - } + @Override + public Map getConstants() { + return EposStringHelper.getDiscoveryConstants(); + } @Override @NonNull diff --git a/android/src/main/java/com/reactnativeescposprinter/EscPosPrinterErrorManager.java b/android/src/main/java/com/reactnativeescposprinter/EscPosPrinterErrorManager.java deleted file mode 100644 index 8b97f35..0000000 --- a/android/src/main/java/com/reactnativeescposprinter/EscPosPrinterErrorManager.java +++ /dev/null @@ -1,481 +0,0 @@ -package com.reactnativeescposprinter; - -import com.epson.epos2.Epos2Exception; -import com.epson.epos2.Epos2CallbackCode; -import com.epson.epos2.printer.Printer; -import com.epson.epos2.printer.PrinterStatusInfo; -import com.facebook.react.bridge.Arguments; - -import com.facebook.react.bridge.WritableMap; -public class EscPosPrinterErrorManager { - - public static int getErrorStatus(Epos2Exception e) { - return e.getErrorStatus(); - } - - public static String getEposExceptionText(int state) { - - String return_text = ""; - switch (state) { - case Epos2Exception.ERR_PARAM: - return_text = "ERR_PARAM"; - break; - case Epos2Exception.ERR_CONNECT: - return_text = "ERR_CONNECT"; - break; - case Epos2Exception.ERR_TIMEOUT: - return_text = "ERR_TIMEOUT"; - break; - case Epos2Exception.ERR_MEMORY: - return_text = "ERR_MEMORY"; - break; - case Epos2Exception.ERR_ILLEGAL: - return_text = "ERR_ILLEGAL"; - break; - case Epos2Exception.ERR_PROCESSING: - return_text = "ERR_PROCESSING"; - break; - case Epos2Exception.ERR_NOT_FOUND: - return_text = "ERR_NOT_FOUND"; - break; - case Epos2Exception.ERR_IN_USE: - return_text = "ERR_IN_USE"; - break; - case Epos2Exception.ERR_TYPE_INVALID: - return_text = "ERR_TYPE_INVALID"; - break; - case Epos2Exception.ERR_DISCONNECT: - return_text = "ERR_DISCONNECT"; - break; - case Epos2Exception.ERR_ALREADY_OPENED: - return_text = "ERR_ALREADY_OPENED"; - break; - case Epos2Exception.ERR_ALREADY_USED: - return_text = "ERR_ALREADY_USED"; - break; - case Epos2Exception.ERR_BOX_COUNT_OVER: - return_text = "ERR_BOX_COUNT_OVER"; - break; - case Epos2Exception.ERR_BOX_CLIENT_OVER: - return_text = "ERR_BOX_CLIENT_OVER"; - break; - case Epos2Exception.ERR_UNSUPPORTED: - return_text = "ERR_UNSUPPORTED"; - break; - case Epos2Exception.ERR_FAILURE: - return_text = "ERR_FAILURE"; - break; - default: - return_text = String.format("%d", state); - break; - } - return return_text; - } - - public static String getCodeText(int state) { - String return_text = ""; - switch (state) { - case Epos2CallbackCode.CODE_SUCCESS: - return_text = "PRINT_SUCCESS"; - break; - case Epos2CallbackCode.CODE_PRINTING: - return_text = "PRINTING"; - break; - case Epos2CallbackCode.CODE_ERR_AUTORECOVER: - return_text = "ERR_AUTORECOVER"; - break; - case Epos2CallbackCode.CODE_ERR_COVER_OPEN: - return_text = "ERR_COVER_OPEN"; - break; - case Epos2CallbackCode.CODE_ERR_CUTTER: - return_text = "ERR_CUTTER"; - break; - case Epos2CallbackCode.CODE_ERR_MECHANICAL: - return_text = "ERR_MECHANICAL"; - break; - case Epos2CallbackCode.CODE_ERR_EMPTY: - return_text = "ERR_EMPTY"; - break; - case Epos2CallbackCode.CODE_ERR_UNRECOVERABLE: - return_text = "ERR_UNRECOVERABLE"; - break; - case Epos2CallbackCode.CODE_ERR_FAILURE: - return_text = "ERR_FAILURE"; - break; - case Epos2CallbackCode.CODE_ERR_NOT_FOUND: - return_text = "ERR_NOT_FOUND"; - break; - case Epos2CallbackCode.CODE_ERR_SYSTEM: - return_text = "ERR_SYSTEM"; - break; - case Epos2CallbackCode.CODE_ERR_PORT: - return_text = "ERR_PORT"; - break; - case Epos2CallbackCode.CODE_ERR_TIMEOUT: - return_text = "ERR_TIMEOUT"; - break; - case Epos2CallbackCode.CODE_ERR_JOB_NOT_FOUND: - return_text = "ERR_JOB_NOT_FOUND"; - break; - case Epos2CallbackCode.CODE_ERR_SPOOLER: - return_text = "ERR_SPOOLER"; - break; - case Epos2CallbackCode.CODE_ERR_BATTERY_LOW: - return_text = "ERR_BATTERY_LOW"; - break; - case Epos2CallbackCode.CODE_ERR_TOO_MANY_REQUESTS: - return_text = "ERR_TOO_MANY_REQUESTS"; - break; - case Epos2CallbackCode.CODE_ERR_REQUEST_ENTITY_TOO_LARGE: - return_text = "ERR_REQUEST_ENTITY_TOO_LARGE"; - break; - case Epos2CallbackCode.CODE_CANCELED: - return_text = "CODE_CANCELED"; - break; - case Epos2CallbackCode.CODE_ERR_NO_MICR_DATA: - return_text = "ERR_NO_MICR_DATA"; - break; - case Epos2CallbackCode.CODE_ERR_ILLEGAL_LENGTH: - return_text = "ERR_ILLEGAL_LENGTH"; - break; - case Epos2CallbackCode.CODE_ERR_NO_MAGNETIC_DATA: - return_text = "ERR_NO_MAGNETIC_DATA"; - break; - case Epos2CallbackCode.CODE_ERR_RECOGNITION: - return_text = "ERR_RECOGNITION"; - break; - case Epos2CallbackCode.CODE_ERR_READ: - return_text = "ERR_READ"; - break; - case Epos2CallbackCode.CODE_ERR_NOISE_DETECTED: - return_text = "ERR_NOISE_DETECTED"; - break; - case Epos2CallbackCode.CODE_ERR_PAPER_JAM: - return_text = "ERR_PAPER_JAM"; - break; - case Epos2CallbackCode.CODE_ERR_PAPER_PULLED_OUT: - return_text = "ERR_PAPER_PULLED_OUT"; - break; - case Epos2CallbackCode.CODE_ERR_CANCEL_FAILED: - return_text = "ERR_CANCEL_FAILED"; - break; - case Epos2CallbackCode.CODE_ERR_PAPER_TYPE: - return_text = "ERR_PAPER_TYPE"; - break; - case Epos2CallbackCode.CODE_ERR_WAIT_INSERTION: - return_text = "ERR_WAIT_INSERTION"; - break; - case Epos2CallbackCode.CODE_ERR_ILLEGAL: - return_text = "ERR_ILLEGAL"; - break; - case Epos2CallbackCode.CODE_ERR_INSERTED: - return_text = "ERR_INSERTED"; - break; - case Epos2CallbackCode.CODE_ERR_WAIT_REMOVAL: - return_text = "ERR_WAIT_REMOVAL"; - break; - case Epos2CallbackCode.CODE_ERR_DEVICE_BUSY: - return_text = "ERR_DEVICE_BUSY"; - break; - case Epos2CallbackCode.CODE_ERR_IN_USE: - return_text = "ERR_IN_USE"; - break; - case Epos2CallbackCode.CODE_ERR_CONNECT: - return_text = "ERR_CONNECT"; - break; - case Epos2CallbackCode.CODE_ERR_DISCONNECT: - return_text = "ERR_DISCONNECT"; - break; - case Epos2CallbackCode.CODE_ERR_MEMORY: - return_text = "ERR_MEMORY"; - break; - case Epos2CallbackCode.CODE_ERR_PROCESSING: - return_text = "ERR_PROCESSING"; - break; - case Epos2CallbackCode.CODE_ERR_PARAM: - return_text = "ERR_PARAM"; - break; - case Epos2CallbackCode.CODE_RETRY: - return_text = "RETRY"; - break; - case Epos2CallbackCode.CODE_ERR_DIFFERENT_MODEL: - return_text = "ERR_DIFFERENT_MODEL"; - break; - case Epos2CallbackCode.CODE_ERR_DIFFERENT_VERSION: - return_text = "ERR_DIFFERENT_VERSION"; - break; - case Epos2CallbackCode.CODE_ERR_DATA_CORRUPTED: - return_text = "ERR_DATA_CORRUPTED"; - break; - default: - return_text = String.format("%d", state); - break; - } - return return_text; - } - - public static int getEposGetWidthResult(int resultCode) { - int result = 0; - - switch (resultCode) { - case Printer.SETTING_PAPERWIDTH_58_0: - result = 58; - break; - case Printer.SETTING_PAPERWIDTH_60_0: - result = 60; - break; - case Printer.SETTING_PAPERWIDTH_80_0: - result = 80; - break; - default: - result = 0; - break; - } - - return result; - } - - public static WritableMap makeStatusMassage(PrinterStatusInfo statusInfo) { - WritableMap statusMessage = Arguments.createMap(); - - - String connection = ""; - String online = ""; - String coverOpen = ""; - String paper = ""; - String paperFeed = ""; - String panelSwitch = ""; - String drawer = ""; - String errorStatus = ""; - String autoRecoverErr = ""; - String adapter = ""; - String batteryLevel = ""; - - - switch (statusInfo.getConnection()) { - case Printer.TRUE: - connection = "CONNECT"; - break; - case Printer.FALSE: - connection = "DISCONNECT"; - break; - case Printer.UNKNOWN: - connection = "UNKNOWN"; - break; - default: - break; - } - - switch (statusInfo.getOnline()) { - case Printer.TRUE: - online = "ONLINE"; - break; - case Printer.FALSE: - online = "OFFLINE"; - break; - case Printer.UNKNOWN: - online = "UNKNOWN"; - break; - default: - break; - } - - switch (statusInfo.getCoverOpen()) { - case Printer.TRUE: - coverOpen = "COVER_OPEN"; - break; - case Printer.FALSE: - coverOpen = "COVER_CLOSE"; - break; - case Printer.UNKNOWN: - coverOpen = "UNKNOWN"; - break; - default: - break; - } - - switch (statusInfo.getPaper()) { - case Printer.PAPER_OK: - paper = "PAPER_OK"; - break; - case Printer.PAPER_NEAR_END: - paper = "PAPER_NEAR_END"; - break; - case Printer.PAPER_EMPTY: - paper = "PAPER_EMPTY"; - break; - case Printer.UNKNOWN: - paper = "UNKNOWN"; - break; - default: - break; - } - - switch (statusInfo.getPaperFeed()) { - case Printer.TRUE: - paperFeed = "PAPER_FEED"; - break; - case Printer.FALSE: - paperFeed = "PAPER_STOP"; - break; - case Printer.UNKNOWN: - paperFeed = "UNKNOWN"; - break; - default: - break; - } - - switch (statusInfo.getPanelSwitch()) { - case Printer.TRUE: - panelSwitch = "SWITCH_ON"; - break; - case Printer.FALSE: - panelSwitch = "SWITCH_OFF"; - break; - case Printer.UNKNOWN: - panelSwitch = "UNKNOWN"; - break; - default: - break; - } - - switch (statusInfo.getDrawer()) { - case Printer.DRAWER_HIGH: - //This status depends on the drawer setting. - drawer = "DRAWER_HIGH(Drawer close)"; - break; - case Printer.DRAWER_LOW: - //This status depends on the drawer setting. - drawer = "DRAWER_LOW(Drawer open)"; - break; - case Printer.UNKNOWN: - drawer = "UNKNOWN"; - break; - default: - break; - } - - switch (statusInfo.getErrorStatus()) { - case Printer.NO_ERR: - errorStatus = "NO_ERR"; - break; - case Printer.MECHANICAL_ERR: - errorStatus = "MECHANICAL_ERR"; - break; - case Printer.AUTOCUTTER_ERR: - errorStatus = "AUTOCUTTER_ERR"; - break; - case Printer.UNRECOVER_ERR: - errorStatus = "UNRECOVER_ERR"; - break; - case Printer.AUTORECOVER_ERR: - errorStatus = "AUTOCUTTER_ERR"; - break; - case Printer.UNKNOWN: - errorStatus = "UNKNOWN"; - break; - default: - break; - } - - switch (statusInfo.getAutoRecoverError()) { - case Printer.HEAD_OVERHEAT: - autoRecoverErr = "HEAD_OVERHEAT"; - break; - case Printer.MOTOR_OVERHEAT: - autoRecoverErr = "MOTOR_OVERHEAT"; - break; - case Printer.BATTERY_OVERHEAT: - autoRecoverErr = "BATTERY_OVERHEAT"; - break; - case Printer.WRONG_PAPER: - autoRecoverErr = "WRONG_PAPER"; - break; - case Printer.COVER_OPEN: - autoRecoverErr = "COVER_OPEN"; - break; - case Printer.UNKNOWN: - autoRecoverErr = "UNKNOWN"; - break; - default: - break; - } - - switch (statusInfo.getAdapter()) { - case Printer.TRUE: - adapter = "AC ADAPTER CONNECT"; - break; - case Printer.FALSE: - adapter = "AC ADAPTER DISCONNECT"; - break; - case Printer.UNKNOWN: - adapter = "UNKNOWN"; - break; - default: - break; - } - - switch (statusInfo.getBatteryLevel()) { - case Printer.BATTERY_LEVEL_0: - batteryLevel = "BATTERY_LEVEL_0"; - break; - case Printer.BATTERY_LEVEL_1: - batteryLevel = "BATTERY_LEVEL_1"; - break; - case Printer.BATTERY_LEVEL_2: - batteryLevel = "BATTERY_LEVEL_2"; - break; - case Printer.BATTERY_LEVEL_3: - batteryLevel = "BATTERY_LEVEL_3"; - break; - case Printer.BATTERY_LEVEL_4: - batteryLevel = "BATTERY_LEVEL_4"; - break; - case Printer.BATTERY_LEVEL_5: - batteryLevel = "BATTERY_LEVEL_5"; - break; - case Printer.BATTERY_LEVEL_6: - batteryLevel = "BATTERY_LEVEL_6"; - break; - case Printer.UNKNOWN: - batteryLevel = "UNKNOWN"; - break; - default: - break; - } - - statusMessage.putString("connection",connection); - statusMessage.putString("online",online); - statusMessage.putString("coverOpen",coverOpen); - statusMessage.putString("paper",paper); - statusMessage.putString("paperFeed",paperFeed); - statusMessage.putString("panelSwitch",panelSwitch); - statusMessage.putString("drawer",drawer); - statusMessage.putString("errorStatus",errorStatus); - statusMessage.putString("autoRecoverErr",autoRecoverErr); - statusMessage.putString("adapter",adapter); - statusMessage.putString("batteryLevel",batteryLevel); - - - return statusMessage; - } - - public static WritableMap getOfflineStatusMessage() { - WritableMap statusMessage = Arguments.createMap(); - - statusMessage.putString("connection","DISCONNECT"); - statusMessage.putString("online","OFFLINE"); - statusMessage.putString("coverOpen","UNKNOWN"); - statusMessage.putString("paper","UNKNOWN"); - statusMessage.putString("paperFeed","UNKNOWN"); - statusMessage.putString("panelSwitch","UNKNOWN"); - statusMessage.putString("drawer","UNKNOWN"); - statusMessage.putString("errorStatus","UNKNOWN"); - statusMessage.putString("autoRecoverErr","UNKNOWN"); - statusMessage.putString("adapter","UNKNOWN"); - statusMessage.putString("batteryLevel","UNKNOWN"); - - - return statusMessage; - } -} diff --git a/android/src/main/java/com/reactnativeescposprinter/EscPosPrinterModule.java b/android/src/main/java/com/reactnativeescposprinter/EscPosPrinterModule.java index 979f95d..20f943c 100644 --- a/android/src/main/java/com/reactnativeescposprinter/EscPosPrinterModule.java +++ b/android/src/main/java/com/reactnativeescposprinter/EscPosPrinterModule.java @@ -11,8 +11,6 @@ import com.facebook.react.module.annotations.ReactModule; import com.facebook.react.modules.core.DeviceEventManagerModule; -import java.io.IOException; -import java.io.InputStream; import java.util.HashMap; import java.util.Map; @@ -20,62 +18,22 @@ import com.epson.epos2.printer.Printer; import com.epson.epos2.Epos2Exception; -import com.epson.epos2.Epos2CallbackCode; -import com.epson.epos2.printer.ReceiveListener; -import com.epson.epos2.printer.PrinterStatusInfo; -import com.epson.epos2.printer.PrinterSettingListener; - -import com.facebook.react.bridge.UiThreadUtil; - -import android.content.res.AssetManager; -import android.graphics.Bitmap; -import android.graphics.BitmapFactory; -import android.util.Base64; - -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.Timer; -import java.util.TimerTask; -import com.facebook.react.bridge.WritableMap; -import android.os.Handler; -import java.util.concurrent.Callable; +import com.facebook.react.bridge.WritableMap; import com.facebook.react.bridge.ReadableMap; -import android.util.Log; -import java.net.URL; -class PrintingCommands { - public static final int COMMAND_ADD_TEXT = 0; - public static final int COMMAND_ADD_NEW_LINE = 1; - public static final int COMMAND_ADD_TEXT_STYLE = 2; - public static final int COMMAND_ADD_TEXT_SIZE = 3; - public static final int COMMAND_ADD_ALIGN = 4; - public static final int COMMAND_ADD_IMAGE_BASE_64 = 5; - public static final int COMMAND_ADD_IMAGE_ASSET = 6; - public static final int COMMAND_ADD_CUT = 7; - public static final int COMMAND_ADD_DATA = 8; - public static final int COMMAND_ADD_TEXT_SMOOTH = 9; - public static final int COMMAND_ADD_BARCODE = 10; - public static final int COMMAND_ADD_QRCODE = 11; - public static final int COMMAND_ADD_IMAGE = 12; - public static final int COMMAND_ADD_PULSE = 13; -} + +import com.reactnativeescposprinter.ThePrinterManager; +import com.reactnativeescposprinter.ThePrinter; +import com.reactnativeescposprinter.EposStringHelper; +import com.reactnativeescposprinter.PrinterCallback; + @ReactModule(name = EscPosPrinterModule.NAME) -public class EscPosPrinterModule extends ReactContextBaseJavaModule implements ReceiveListener { - private static final int DISCONNECT_INTERVAL = 500; +public class EscPosPrinterModule extends ReactContextBaseJavaModule { private Context mContext; - public static Printer mPrinter = null; private final ReactApplicationContext reactContext; - private String printerAddress = null; - private Runnable monitor = null; - - ExecutorService tasksQueue = Executors.newSingleThreadExecutor(); - private Boolean mIsMonitoring = false; - interface MyCallbackInterface { - void onSuccess(String result); - void onError(String result); - } - + private ThePrinterManager thePrinterManager_ = ThePrinterManager.getInstance(); + private int ERR_INIT = EposStringHelper.getInitErrorResultCode(); public static final String NAME = "EscPosPrinter"; public EscPosPrinterModule(ReactApplicationContext reactContext) { @@ -92,638 +50,365 @@ public String getName() { @Override public Map getConstants() { - final Map constants = new HashMap<>(); - // Printer series - constants.put("EPOS2_TM_M10", Printer.TM_M10); - constants.put("EPOS2_TM_M30", Printer.TM_M30); - constants.put("EPOS2_TM_P20", Printer.TM_P20); - constants.put("EPOS2_TM_P60", Printer.TM_P60); - constants.put("EPOS2_TM_P60II", Printer.TM_P60II); - constants.put("EPOS2_TM_P80", Printer.TM_P80); - constants.put("EPOS2_TM_T20", Printer.TM_T20); - constants.put("EPOS2_TM_T60", Printer.TM_T60); - constants.put("EPOS2_TM_T70", Printer.TM_T70); - constants.put("EPOS2_TM_T81", Printer.TM_T81); - constants.put("EPOS2_TM_T82", Printer.TM_T82); - constants.put("EPOS2_TM_T83", Printer.TM_T83); - constants.put("EPOS2_TM_T88", Printer.TM_T88); - constants.put("EPOS2_TM_T90", Printer.TM_T90); - constants.put("EPOS2_TM_T90KP", Printer.TM_T90KP); - constants.put("EPOS2_TM_U220", Printer.TM_U220); - constants.put("EPOS2_TM_U330", Printer.TM_U330); - constants.put("EPOS2_TM_L90", Printer.TM_L90); - constants.put("EPOS2_TM_H6000", Printer.TM_H6000); - constants.put("EPOS2_TM_T83III", Printer.TM_T83III); - constants.put("EPOS2_TM_T100", Printer.TM_T100); - constants.put("EPOS2_TM_M30II", Printer.TM_M30II); - constants.put("EPOS2_TS_100", Printer.TS_100); - constants.put("EPOS2_TM_M50", Printer.TM_M50); - constants.put("EPOS2_TM_T88VII", Printer.TM_T88VII); - constants.put("EPOS2_TM_L90LFC", Printer.TM_L90LFC); - constants.put("EPOS2_TM_L100", Printer.TM_L100); - - // Print commands - constants.put("COMMAND_ADD_TEXT", PrintingCommands.COMMAND_ADD_TEXT); - constants.put("COMMAND_ADD_NEW_LINE", PrintingCommands.COMMAND_ADD_NEW_LINE); - constants.put("COMMAND_ADD_TEXT_STYLE", PrintingCommands.COMMAND_ADD_TEXT_STYLE); - constants.put("COMMAND_ADD_TEXT_SIZE", PrintingCommands.COMMAND_ADD_TEXT_SIZE); - constants.put("COMMAND_ADD_TEXT_SMOOTH", PrintingCommands.COMMAND_ADD_TEXT_SMOOTH); - constants.put("COMMAND_ADD_ALIGN", PrintingCommands.COMMAND_ADD_ALIGN); - constants.put("COMMAND_ADD_IMAGE_BASE_64", PrintingCommands.COMMAND_ADD_IMAGE_BASE_64); - constants.put("COMMAND_ADD_IMAGE_ASSET", PrintingCommands.COMMAND_ADD_IMAGE_ASSET); - constants.put("COMMAND_ADD_IMAGE", PrintingCommands.COMMAND_ADD_IMAGE); - constants.put("COMMAND_ADD_BARCODE", PrintingCommands.COMMAND_ADD_BARCODE); - constants.put("COMMAND_ADD_QRCODE", PrintingCommands.COMMAND_ADD_QRCODE); - constants.put("COMMAND_ADD_CUT", PrintingCommands.COMMAND_ADD_CUT); - constants.put("COMMAND_ADD_DATA", PrintingCommands.COMMAND_ADD_DATA); - constants.put("COMMAND_ADD_PULSE", PrintingCommands.COMMAND_ADD_PULSE); - - constants.put("EPOS2_ALIGN_LEFT", Printer.ALIGN_LEFT); - constants.put("EPOS2_ALIGN_RIGHT", Printer.ALIGN_RIGHT); - constants.put("EPOS2_ALIGN_CENTER", Printer.ALIGN_CENTER); - constants.put("EPOS2_TRUE", Printer.TRUE); - constants.put("EPOS2_FALSE", Printer.FALSE); - - // Print languages - constants.put("EPOS2_LANG_EN", Printer.LANG_EN); - constants.put("EPOS2_LANG_JA", Printer.LANG_JA); - constants.put("EPOS2_LANG_ZH_CN", Printer.LANG_ZH_CN); - constants.put("EPOS2_LANG_ZH_TW", Printer.LANG_ZH_TW); - constants.put("EPOS2_LANG_KO", Printer.LANG_KO); - constants.put("EPOS2_LANG_TH", Printer.LANG_TH); - constants.put("EPOS2_LANG_VI", Printer.LANG_VI); - constants.put("EPOS2_LANG_MULTI", Printer.PARAM_DEFAULT); - - // Print Barcodes - constants.put("EPOS2_BARCODE_UPC_A", Printer.BARCODE_UPC_A); - constants.put("EPOS2_BARCODE_UPC_E", Printer.BARCODE_UPC_E); - constants.put("EPOS2_BARCODE_EAN13", Printer.BARCODE_EAN13); - constants.put("EPOS2_BARCODE_JAN13", Printer.BARCODE_JAN13); - constants.put("EPOS2_BARCODE_EAN8", Printer.BARCODE_EAN8); - constants.put("EPOS2_BARCODE_JAN8", Printer.BARCODE_JAN8); - constants.put("EPOS2_BARCODE_CODE39", Printer.BARCODE_CODE39); - constants.put("EPOS2_BARCODE_ITF", Printer.BARCODE_ITF); - constants.put("EPOS2_BARCODE_CODABAR", Printer.BARCODE_CODABAR); - constants.put("EPOS2_BARCODE_CODE93", Printer.BARCODE_CODE93); - constants.put("EPOS2_BARCODE_CODE128", Printer.BARCODE_CODE128); - constants.put("EPOS2_BARCODE_GS1_128", Printer.BARCODE_GS1_128); - constants.put("EPOS2_BARCODE_GS1_DATABAR_OMNIDIRECTIONAL", Printer.BARCODE_GS1_DATABAR_OMNIDIRECTIONAL); - constants.put("EPOS2_BARCODE_GS1_DATABAR_TRUNCATED", Printer.BARCODE_GS1_DATABAR_TRUNCATED); - constants.put("EPOS2_BARCODE_GS1_DATABAR_LIMITED", Printer.BARCODE_GS1_DATABAR_LIMITED); - constants.put("EPOS2_BARCODE_GS1_DATABAR_EXPANDED", Printer.BARCODE_GS1_DATABAR_EXPANDED); - constants.put("EPOS2_BARCODE_CODE128_AUTO", Printer.BARCODE_CODE128_AUTO); - constants.put("EPOS2_HRI_NONE", Printer.HRI_NONE); - constants.put("EPOS2_HRI_ABOVE", Printer.HRI_ABOVE); - constants.put("EPOS2_HRI_BELOW", Printer.HRI_BELOW); - constants.put("EPOS2_HRI_BOTH", Printer.HRI_BOTH); - constants.put("EPOS2_LEVEL_L", Printer.LEVEL_L); - constants.put("EPOS2_LEVEL_M", Printer.LEVEL_M); - constants.put("EPOS2_LEVEL_Q", Printer.LEVEL_Q); - constants.put("EPOS2_LEVEL_H", Printer.LEVEL_H); - constants.put("EPOS2_SYMBOL_QRCODE_MODEL_1", Printer.SYMBOL_QRCODE_MODEL_1); - constants.put("EPOS2_SYMBOL_QRCODE_MODEL_2", Printer.SYMBOL_QRCODE_MODEL_2); - constants.put("EPOS2_SYMBOL_QRCODE_MICRO", Printer.SYMBOL_QRCODE_MICRO); - - // Print image settings - constants.put("EPOS2_COLOR_1", Printer.COLOR_1); - constants.put("EPOS2_COLOR_2", Printer.COLOR_2); - constants.put("EPOS2_COLOR_3", Printer.COLOR_3); - constants.put("EPOS2_COLOR_4", Printer.COLOR_4); - - constants.put("EPOS2_MODE_MONO", Printer.MODE_MONO); - constants.put("EPOS2_MODE_GRAY16", Printer.MODE_GRAY16); - constants.put("EPOS2_MODE_MONO_HIGH_DENSITY", Printer.MODE_MONO_HIGH_DENSITY); - - constants.put("EPOS2_HALFTONE_DITHER", Printer.HALFTONE_DITHER); - constants.put("EPOS2_HALFTONE_ERROR_DIFFUSION", Printer.HALFTONE_ERROR_DIFFUSION); - constants.put("EPOS2_HALFTONE_THRESHOLD", Printer.HALFTONE_THRESHOLD); - - // Add pulse settings - constants.put("EPOS2_DRAWER_2PIN", Printer.DRAWER_2PIN); - constants.put("EPOS2_DRAWER_5PIN", Printer.DRAWER_5PIN); - - return constants; + return EposStringHelper.getPrinterConstants(); } - private void sendEvent(ReactApplicationContext reactContext, - String eventName, - @Nullable String params) { - reactContext - .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class) - .emit(eventName, params); - } - - @ReactMethod - public void init(String target, int series, int language,Promise promise) { - this.finalizeObject(); - this.initializeObject(series, language, new MyCallbackInterface() { - @Override - public void onSuccess(String result) { - promise.resolve(result); - } - @Override - public void onError(String result) { - promise.reject(result); - } - }); - - this.printerAddress = target; - } - - @ReactMethod - public void getPaperWidth(Promise promise) { - - tasksQueue.submit(new Runnable() { - @Override - public void run() { - getPrinterSettings(Printer.SETTING_PAPERWIDTH, new MyCallbackInterface() { - @Override - public void onSuccess(String result) { - promise.resolve(result); - } - @Override - public void onError(String result) { - promise.reject(result); - } - }); - } - }); - - } - - private void initializeObject(int series, int language,MyCallbackInterface callback) { - try { - mPrinter = new Printer(series, Printer.MODEL_ANK, mContext); - mPrinter.addTextLang(language); - } - catch (Epos2Exception e) { - int status = EscPosPrinterErrorManager.getErrorStatus(e); - String errorString = EscPosPrinterErrorManager.getEposExceptionText(status); - callback.onError(errorString); + @ReactMethod + synchronized public void initWithPrinterDeviceName(String target, String deviceName, int lang, Promise promise) { + ThePrinter thePrinter = thePrinterManager_.getObject(target); + try { + if (thePrinter == null) { + thePrinter = new ThePrinter(); + thePrinterManager_.add(thePrinter, target); + int series = EposStringHelper.getPrinterSeries(deviceName); + thePrinter.setupWith(target, series, lang, mContext); } - mPrinter.setReceiveEventListener(this); - callback.onSuccess("init: success"); - } - - private void finalizeObject() { - if(mPrinter == null) { - return; - } - - mPrinter.clearCommandBuffer(); - mPrinter.setReceiveEventListener(null); - mPrinter = null; - } - private void connectPrinter() throws Epos2Exception { - - if (mPrinter == null) { - throw new Epos2Exception(Epos2Exception.ERR_PARAM); - } - - mPrinter.connect(this.printerAddress, Printer.PARAM_DEFAULT); - mPrinter.beginTransaction(); - } - - private void disconnectPrinter() { - if (mPrinter == null) { - return; - } - - try { - mPrinter.endTransaction(); - } catch(Epos2Exception e) { + Printer mPrinter = thePrinter.getEpos2Printer(); + if(mPrinter == null) { + promise.reject(EposStringHelper.getErrorTextData(Epos2Exception.ERR_MEMORY, "")); + } else { + promise.resolve(null); + } + } catch(Exception e) { + processError(promise,e, ""); + } } - while (true) { - try { - mPrinter.disconnect(); - System.out.println("Disconnected!"); - break; - } catch (final Exception e) { - if (e instanceof Epos2Exception) { - //Note: If printer is processing such as printing and so on, the disconnect API returns ERR_PROCESSING. - if (((Epos2Exception) e).getErrorStatus() == Epos2Exception.ERR_PROCESSING) { - try { - Thread.sleep(DISCONNECT_INTERVAL); - } catch (Exception ex) { - } - }else{ - break; + @ReactMethod + synchronized public void connect(String target, int timeout, Promise promise) { + new Thread(new Runnable() { + @Override + synchronized public void run() { + ThePrinter thePrinter = thePrinterManager_.getObject(target); + if (thePrinter == null) { + promise.reject(EposStringHelper.getErrorTextData(ERR_INIT, "")); + } else { + try { + thePrinter.connect(timeout); + promise.resolve(null); + } catch(Exception e) { + processError(promise,e, ""); + } } - }else{ - break; } - } + }).start(); } - - - mPrinter.clearCommandBuffer(); + @ReactMethod + synchronized public void disconnect(String target, Promise promise) { + new Thread(new Runnable() { + @Override + synchronized public void run() { + ThePrinter thePrinter = thePrinterManager_.getObject(target); + if (thePrinter == null) { + promise.reject(EposStringHelper.getErrorTextData(ERR_INIT, "")); + } else { + try { + thePrinter.disconnect(); + promise.resolve(null); + } catch(Exception e) { + processError(promise,e, ""); + } + } + } + }).start(); } - private void printData(final ReadableMap paramsMap) throws Epos2Exception { - int timeout = Printer.PARAM_DEFAULT; - if(paramsMap != null) { - if(paramsMap.hasKey("timeout")) { - timeout = paramsMap.getInt("timeout"); + @ReactMethod + synchronized public void clearCommandBuffer(String target, Promise promise){ + ThePrinter thePrinter = thePrinterManager_.getObject(target); + if (thePrinter == null) { + promise.reject(EposStringHelper.getErrorTextData(ERR_INIT, "")); + } else { + try { + thePrinter.clearCommandBuffer(); + promise.resolve(null); + } catch(Exception e) { + processError(promise, e, ""); } } - - this.connectPrinter(); - mPrinter.sendData(timeout); } - @Override - public void onPtrReceive(final Printer printerObj, final int code, final PrinterStatusInfo status, final String printJobId) { - UiThreadUtil.runOnUiThread(new Runnable() { - @Override - public synchronized void run() { - String result = EscPosPrinterErrorManager.getCodeText(code); - if(code == Epos2CallbackCode.CODE_SUCCESS) { - WritableMap msg = EscPosPrinterErrorManager.makeStatusMassage(status); - - reactContext - .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class) - .emit("onPrintSuccess", msg); - - } else { - sendEvent(reactContext, "onPrintFailure", result); - } - - new Thread(new Runnable() { - @Override - public void run() { - disconnectPrinter(); - } - }).start(); + @ReactMethod + synchronized public void addText(String target, String data, Promise promise) { + ThePrinter thePrinter = thePrinterManager_.getObject(target); + if (thePrinter == null) { + promise.reject(EposStringHelper.getErrorTextData(ERR_INIT, "")); + } else { + try { + thePrinter.addText(data); + promise.resolve(null); + } catch(Exception e) { + processError(promise, e, ""); } - }); - } - - private void getPrinterSettings(int type, MyCallbackInterface callback) { - if (mPrinter == null) { - String errorString = EscPosPrinterErrorManager.getEposExceptionText(Epos2Exception.ERR_PARAM); - callback.onError(errorString); - return; + } } - try { - this.connectPrinter(); - } - catch (Epos2Exception e) { - int status = EscPosPrinterErrorManager.getErrorStatus(e); - String errorString = EscPosPrinterErrorManager.getEposExceptionText(status); - callback.onError(errorString); - return; + @ReactMethod + synchronized public void addTextLang(String target, int lang, Promise promise) { + ThePrinter thePrinter = thePrinterManager_.getObject(target); + if (thePrinter == null) { + promise.reject(EposStringHelper.getErrorTextData(ERR_INIT, "")); + } else { + try { + thePrinter.addTextLang(lang); + promise.resolve(null); + } catch(Exception e) { + processError(promise, e, ""); + } + } } - try { - mPrinter.getPrinterSetting(Printer.PARAM_DEFAULT, type, mSettingListener); - } - catch (Epos2Exception e) { - mPrinter.clearCommandBuffer(); - int status = EscPosPrinterErrorManager.getErrorStatus(e); - String errorString = EscPosPrinterErrorManager.getEposExceptionText(status); - callback.onError(errorString); - this.disconnectPrinter(); - return; + @ReactMethod + synchronized public void addFeedLine(String target, int line, Promise promise) { + ThePrinter thePrinter = thePrinterManager_.getObject(target); + if (thePrinter == null) { + promise.reject(EposStringHelper.getErrorTextData(ERR_INIT, "")); + } else { + try { + thePrinter.addFeedLine(line); + promise.resolve(null); + } catch(Exception e) { + processError(promise, e, ""); + } + } } - String successString = EscPosPrinterErrorManager.getCodeText(Epos2CallbackCode.CODE_SUCCESS); - callback.onSuccess(successString); - - } - - private PrinterSettingListener mSettingListener = new PrinterSettingListener() { - @Override - public void onGetPrinterSetting(int code, int type, int value) { - UiThreadUtil.runOnUiThread(new Runnable() { - @Override - public synchronized void run() { - String result = EscPosPrinterErrorManager.getCodeText(code); - if(code == Epos2CallbackCode.CODE_SUCCESS) { - if(type == Printer.SETTING_PAPERWIDTH) { - int paperWidth = EscPosPrinterErrorManager.getEposGetWidthResult(value); - reactContext - .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class) - .emit("onGetPaperWidthSuccess", paperWidth); - } - } else { - if(type == Printer.SETTING_PAPERWIDTH) { - sendEvent(reactContext, "onGetPaperWidthFailure", result); - } - } - new Thread(new Runnable() { - @Override - public void run() { - disconnectPrinter(); - } - }).start(); - } - }); - + @ReactMethod + synchronized public void addCut(String target, int type, Promise promise) { + ThePrinter thePrinter = thePrinterManager_.getObject(target); + if (thePrinter == null) { + promise.reject(EposStringHelper.getErrorTextData(ERR_INIT, "")); + } else { + try { + thePrinter.addCut(type); + promise.resolve(null); + } catch(Exception e) { + processError(promise, e, ""); + } + } } - @Override public void onSetPrinterSetting(int code) { - // do nothing + @ReactMethod + synchronized public void addCommand(String target, String base64string, Promise promise) { + ThePrinter thePrinter = thePrinterManager_.getObject(target); + if (thePrinter == null) { + promise.reject(EposStringHelper.getErrorTextData(ERR_INIT, "")); + } else { + try { + thePrinter.addCommand(base64string); + promise.resolve(null); + } catch(Exception e) { + processError(promise, e, ""); + } + } } - }; - - private void performMonitoring(int inteval) { - final Handler handler = new Handler(); - monitor = new Runnable(){ - @Override - public void run() { - - if(mIsMonitoring) { - tasksQueue.submit(new Callable() { - @Override - public String call() { - try { - WritableMap msg = getMPrinterStatus(); - reactContext - .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class) - .emit("onMonitorStatusUpdate", msg); - } catch (Epos2Exception e) {} finally { - handler.postDelayed(monitor, inteval); - } - return null; - } - }); + @ReactMethod + synchronized public void addPulse(String target, int drawer, int time, Promise promise) { + ThePrinter thePrinter = thePrinterManager_.getObject(target); + if (thePrinter == null) { + promise.reject(EposStringHelper.getErrorTextData(ERR_INIT, "")); + } else { + try { + thePrinter.addPulse(drawer, time); + promise.resolve(null); + } catch(Exception e) { + processError(promise, e, ""); } } - }; - - monitor.run(); - } + } - public WritableMap getMPrinterStatus() throws Epos2Exception { - try { - connectPrinter(); - PrinterStatusInfo statusInfo = mPrinter.getStatus(); - WritableMap msg = EscPosPrinterErrorManager.makeStatusMassage(statusInfo); - disconnectPrinter(); - return msg; - } catch (Epos2Exception e) { - int errorStatus = ((Epos2Exception) e).getErrorStatus(); - - if (errorStatus != Epos2Exception.ERR_PROCESSING && errorStatus != Epos2Exception.ERR_ILLEGAL) { - - WritableMap msg = EscPosPrinterErrorManager.getOfflineStatusMessage(); - return msg; + @ReactMethod + synchronized public void addTextAlign(String target, int align, Promise promise) { + ThePrinter thePrinter = thePrinterManager_.getObject(target); + if (thePrinter == null) { + promise.reject(EposStringHelper.getErrorTextData(ERR_INIT, "")); + } else { + try { + thePrinter.addTextAlign(align); + promise.resolve(null); + } catch(Exception e) { + processError(promise, e, ""); } - throw e; } - } - - @ReactMethod - public void startMonitorPrinter(int interval, Promise promise) { - - if (mIsMonitoring){ - promise.reject("Already monitoring!"); - return; } - if (mPrinter == null) { - String errorString = EscPosPrinterErrorManager.getEposExceptionText(Epos2Exception.ERR_PARAM); - promise.reject(errorString); - return; + @ReactMethod + synchronized public void addTextSize(String target, int width, int height, Promise promise) { + ThePrinter thePrinter = thePrinterManager_.getObject(target); + if (thePrinter == null) { + promise.reject(EposStringHelper.getErrorTextData(ERR_INIT, "")); + } else { + try { + thePrinter.addTextSize(width, height); + promise.resolve(null); + } catch(Exception e) { + processError(promise, e, ""); + } + } } - mIsMonitoring = true; - this.performMonitoring(interval * 1000); - - - String successString = EscPosPrinterErrorManager.getCodeText(Epos2CallbackCode.CODE_SUCCESS); - promise.resolve(successString); - } - - @ReactMethod - public void stopMonitorPrinter(Promise promise) { - if(!mIsMonitoring) { - promise.reject("Printer is not monitorring!"); - return; + @ReactMethod + synchronized public void addTextSmooth(String target, int smooth, Promise promise) { + ThePrinter thePrinter = thePrinterManager_.getObject(target); + if (thePrinter == null) { + promise.reject(EposStringHelper.getErrorTextData(ERR_INIT, "")); + } else { + try { + thePrinter.addTextSmooth(smooth); + promise.resolve(null); + } catch(Exception e) { + processError(promise, e, ""); + } + } } - mIsMonitoring = false; - monitor = null; - String successString = EscPosPrinterErrorManager.getCodeText(Epos2CallbackCode.CODE_SUCCESS); - promise.resolve(successString); - } - - @ReactMethod - public void getPrinterStatus(Promise promise) { - tasksQueue.submit(new Runnable() { - @Override - public void run() { + @ReactMethod + synchronized public void addTextStyle(String target, int reverse, int ul, int em, int color, Promise promise) { + ThePrinter thePrinter = thePrinterManager_.getObject(target); + if (thePrinter == null) { + promise.reject(EposStringHelper.getErrorTextData(ERR_INIT, "")); + } else { try { - WritableMap msg = getMPrinterStatus(); - promise.resolve(msg); - } catch (Epos2Exception e) { - promise.reject("Failed to get status"); + thePrinter.addTextStyle(reverse, ul, em, color); + promise.resolve(null); + } catch(Exception e) { + processError(promise, e, ""); } } - }); - } + } - @ReactMethod - public void printBuffer(ReadableArray printBuffer, final ReadableMap paramsMap, Promise promise) { - tasksQueue.submit(new Runnable() { - @Override - public void run() { - printFromBuffer(printBuffer, paramsMap, new MyCallbackInterface() { - @Override - public void onSuccess(String result) { - promise.resolve(result); - } - @Override - public void onError(String result) { - promise.reject(result); - } - }); + @ReactMethod + synchronized public void addImage(String target, ReadableMap source, int width, int color, + int mode, int halftone, double brightness, int compress, Promise promise) { + ThePrinter thePrinter = thePrinterManager_.getObject(target); + if (thePrinter == null) { + promise.reject(EposStringHelper.getErrorTextData(ERR_INIT, "")); + } else { + try { + thePrinter.addImage(source, mContext, width, color, mode, halftone, brightness, compress); + promise.resolve(null); + } catch(Exception e) { + processError(promise, e, ""); + } } - }); - } - - public void printFromBuffer(ReadableArray printBuffer, final ReadableMap paramsMap, MyCallbackInterface callback) { - if (mPrinter == null) { - String errorString = EscPosPrinterErrorManager.getEposExceptionText(Epos2Exception.ERR_PARAM); - callback.onError(errorString); - return; } - try { - int bufferLength = printBuffer.size(); - for (int curr = 0; curr < bufferLength; curr++) { - ReadableArray command = printBuffer.getArray(curr); - handleCommand(command.getInt(0), command.getArray(1)); + @ReactMethod + synchronized public void addBarcode(String target, String data, int type, int hri, int font, int width, int height, Promise promise) { + ThePrinter thePrinter = thePrinterManager_.getObject(target); + if (thePrinter == null) { + promise.reject(EposStringHelper.getErrorTextData(ERR_INIT, "")); + } else { + try { + thePrinter.addBarcode(data, type, hri, font, width, height); + promise.resolve(null); + } catch(Exception e) { + processError(promise, e, ""); + } } - } catch (Epos2Exception e) { - mPrinter.clearCommandBuffer(); - int status = EscPosPrinterErrorManager.getErrorStatus(e); - String errorString = EscPosPrinterErrorManager.getEposExceptionText(status); - callback.onError(errorString); - return; - } catch (IOException e){ - mPrinter.clearCommandBuffer(); - callback.onError(e.getMessage()); - return; } - try { - this.printData(paramsMap); - String successString = EscPosPrinterErrorManager.getCodeText(Epos2CallbackCode.CODE_SUCCESS); - callback.onSuccess(successString); - } catch (Epos2Exception e) { - int status = EscPosPrinterErrorManager.getErrorStatus(e); - String errorString = EscPosPrinterErrorManager.getEposExceptionText(status); - callback.onError(errorString); - } - } - - @ReactMethod - public void addListener(String eventName) { - // Keep: Required for RN built in Event Emitter Calls. - } - - @ReactMethod - public void removeListeners(Integer count) { - // Keep: Required for RN built in Event Emitter Calls. - } - - private Bitmap getBitmapFromSource(ReadableMap source) throws Exception { - String uriString = source.getString("uri"); - - if(uriString.startsWith("data")) { - final String pureBase64Encoded = uriString.substring(uriString.indexOf(",") + 1); - byte[] decodedString = Base64.decode(pureBase64Encoded, Base64.DEFAULT); - Bitmap image = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length); - return image; + @ReactMethod + synchronized public void addSymbol(String target, String data, int type, int level, int width, int height, int size, Promise promise) { + ThePrinter thePrinter = thePrinterManager_.getObject(target); + if (thePrinter == null) { + promise.reject(EposStringHelper.getErrorTextData(ERR_INIT, "")); + } else { + try { + thePrinter.addSymbol(data, type, level, width, height, size); + promise.resolve(null); + } catch(Exception e) { + processError(promise, e, ""); + } + } } - if(uriString.startsWith("http") || uriString.startsWith("https")) { - URL url = new URL(uriString); - Bitmap image = BitmapFactory.decodeStream(url.openConnection().getInputStream()); - return image; + @ReactMethod + synchronized public void getStatus(String target, Promise promise) { + new Thread(new Runnable() { + @Override + synchronized public void run() { + ThePrinter thePrinter = thePrinterManager_.getObject(target); + if (thePrinter == null) { + promise.reject(EposStringHelper.getErrorTextData(ERR_INIT, "")); + } else { + try { + WritableMap data = thePrinter.getStatus(); + promise.resolve(data); + } catch(Exception e) { + processError(promise, e, ""); + } + } + } + }).start(); } - if(uriString.startsWith("file")) { - BitmapFactory.Options options = new BitmapFactory.Options(); - options.inPreferredConfig = Bitmap.Config.ARGB_8888; - Bitmap image = BitmapFactory.decodeFile(uriString, options); - - return image; - } + @ReactMethod + synchronized public void sendData(String target, int timeout, Promise promise) { + ThePrinter thePrinter = thePrinterManager_.getObject(target); + if (thePrinter == null) { + promise.reject(EposStringHelper.getErrorTextData(ERR_INIT, "result")); + } else { + try { + thePrinter.sendData(timeout, new PrinterCallback() { + @Override + public void onSuccess(WritableMap returnData) { + promise.resolve(returnData); + } - int resourceId = mContext.getResources().getIdentifier(uriString, "drawable", mContext.getPackageName()); - Bitmap image = BitmapFactory.decodeResource(mContext.getResources(), resourceId); - - return image; - } - - - private void handleCommand(int command, ReadableArray params) throws Epos2Exception, IOException { - switch (command) { - case PrintingCommands.COMMAND_ADD_TEXT: - mPrinter.addText(params.getString(0)); - break; - case PrintingCommands.COMMAND_ADD_PULSE: - mPrinter.addPulse(params.getInt(0), Printer.PARAM_DEFAULT); - break; - case PrintingCommands.COMMAND_ADD_NEW_LINE: - mPrinter.addFeedLine(params.getInt(0)); - break; - case PrintingCommands.COMMAND_ADD_TEXT_STYLE: - mPrinter.addTextStyle(Printer.FALSE, params.getInt(0), params.getInt(1), Printer.COLOR_1); - break; - case PrintingCommands.COMMAND_ADD_TEXT_SIZE: - mPrinter.addTextSize(params.getInt(0), params.getInt(1)); - break; - case PrintingCommands.COMMAND_ADD_ALIGN: - mPrinter.addTextAlign(params.getInt(0)); - break; - - case PrintingCommands.COMMAND_ADD_IMAGE: - ReadableMap source = params.getMap(0); - - int imgWidth = params.getInt(1); - int color = params.getInt(2); - int mode = params.getInt(3); - int halftone = params.getInt(4); - double brightness = params.getDouble(5); - try { - Bitmap imgBitmap = getBitmapFromSource(source); - handlePrintImage(imgBitmap, imgWidth, color, mode, halftone, brightness); + @Override + public void onError(String errorData) { + promise.reject(errorData); + } + }); } catch(Exception e) { - Log.e("MYAPP", "exception", e); // TODO: fallback printing + processError(promise, e, "result"); } + } + } + @ReactMethod + synchronized public void getPrinterSetting(String target, int timeout, int type, Promise promise) { + new Thread(new Runnable() { + @Override + synchronized public void run() { + ThePrinter thePrinter = thePrinterManager_.getObject(target); + if (thePrinter == null) { + promise.reject(EposStringHelper.getErrorTextData(ERR_INIT, "result")); + } else { + try { + thePrinter.getPrinterSetting(timeout, type, new PrinterCallback() { + @Override + public void onSuccess(WritableMap returnData) { + promise.resolve(returnData); + } - break; - case PrintingCommands.COMMAND_ADD_IMAGE_BASE_64: - String uriString = params.getString(0); - final String pureBase64Encoded = uriString.substring(uriString.indexOf(",") + 1); - byte[] decodedString = Base64.decode(pureBase64Encoded, Base64.DEFAULT); - Bitmap bitmap = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length); - int inputWidth = params.getInt(1); - - handlePrintImage(bitmap, inputWidth, Printer.COLOR_1, Printer.MODE_MONO, Printer.HALFTONE_DITHER, Printer.PARAM_DEFAULT); - break; - - case PrintingCommands.COMMAND_ADD_IMAGE_ASSET: - String imageName = params.getString(0); - int width = params.getInt(1); - - AssetManager assetManager = mContext.getAssets(); - InputStream inputStream = assetManager.open(params.getString(0)); - Bitmap assetBitmap = BitmapFactory.decodeStream(inputStream); - inputStream.close(); - - handlePrintImage(assetBitmap, width, Printer.COLOR_1, Printer.MODE_MONO, Printer.HALFTONE_DITHER, Printer.PARAM_DEFAULT); - break; - case PrintingCommands.COMMAND_ADD_CUT: - mPrinter.addCut(Printer.CUT_FEED); - break; - case PrintingCommands.COMMAND_ADD_DATA: - String base64String = params.getString(0); - byte[] data = Base64.decode(base64String, Base64.DEFAULT); - mPrinter.addCommand(data); - break; - case PrintingCommands.COMMAND_ADD_TEXT_SMOOTH: - mPrinter.addTextSmooth(params.getInt(0)); - break; - case PrintingCommands.COMMAND_ADD_BARCODE: - mPrinter.addBarcode(params.getString(0), params.getInt(1), params.getInt(2), Printer.FONT_A, params.getInt(3), params.getInt(4)); - break; - case PrintingCommands.COMMAND_ADD_QRCODE: - mPrinter.addSymbol(params.getString(0), params.getInt(1), params.getInt(2), params.getInt(3), params.getInt(3), params.getInt(3)); - break; - default: - throw new IllegalArgumentException("Invalid Printing Command"); + @Override + public void onError(String errorData) { + promise.reject(errorData); + } + }); + } catch(Exception e) { + processError(promise, e, "result"); + } + } + } + }).start(); + } + + private void processError(Promise promise, Exception e, String errorType) { + int errorCode; + if (e instanceof Epos2Exception) { + errorCode = ((Epos2Exception) e).getErrorStatus(); + } else { + errorCode = Epos2Exception.ERR_FAILURE; + } + promise.reject(EposStringHelper.getErrorTextData(errorCode, errorType)); } - } - - private void handlePrintImage(Bitmap bitmap, int width, int color, int mode, int halftone, double brightness) throws Epos2Exception { - float aspectRatio = bitmap.getWidth() / (float) bitmap.getHeight(); - int newHeight = Math.round(width / aspectRatio); - bitmap = Bitmap.createScaledBitmap(bitmap, width, newHeight, false); - - mPrinter.addImage( - bitmap, - 0, - 0, - width, - newHeight, - color, - mode, - halftone, - brightness, - Printer.COMPRESS_AUTO - ); - } } diff --git a/android/src/main/java/com/reactnativeescposprinter/EscPosPrinterPackage.java b/android/src/main/java/com/reactnativeescposprinter/EscPosPrinterPackage.java index 674b88e..6b2478a 100644 --- a/android/src/main/java/com/reactnativeescposprinter/EscPosPrinterPackage.java +++ b/android/src/main/java/com/reactnativeescposprinter/EscPosPrinterPackage.java @@ -18,7 +18,6 @@ public List createNativeModules(@NonNull ReactApplicationContext r List modules = new ArrayList<>(); modules.add(new EscPosPrinterModule(reactContext)); modules.add(new EscPosPrinterDiscoveryModule(reactContext)); - modules.add(new ThePrinterWrapper(reactContext)); return modules; } diff --git a/android/src/main/java/com/reactnativeescposprinter/ImageManager.java b/android/src/main/java/com/reactnativeescposprinter/ImageManager.java new file mode 100644 index 0000000..aed0eab --- /dev/null +++ b/android/src/main/java/com/reactnativeescposprinter/ImageManager.java @@ -0,0 +1,48 @@ +package com.reactnativeescposprinter; + +import com.facebook.react.bridge.ReadableMap; + +import android.graphics.Bitmap; +import android.graphics.BitmapFactory; +import android.util.Base64; +import android.content.Context; + +import java.net.URL; + + +public class ImageManager { + public static Bitmap getBitmapFromSource(ReadableMap source, Context mContext) throws Exception { + String uriString = source.getString("uri"); + + if(uriString.startsWith("data")) { + final String pureBase64Encoded = uriString.substring(uriString.indexOf(",") + 1); + byte[] decodedString = Base64.decode(pureBase64Encoded, Base64.DEFAULT); + Bitmap image = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length); + + return image; + } + + if(uriString.startsWith("http") || uriString.startsWith("https")) { + URL url = new URL(uriString); + Bitmap image = BitmapFactory.decodeStream(url.openConnection().getInputStream()); + return image; + } + + if(uriString.startsWith("file")) { + String cleanUrl = uriString.replaceAll("file://", ""); + BitmapFactory.Options options = new BitmapFactory.Options(); + options.inPreferredConfig = Bitmap.Config.ARGB_8888; + Bitmap image = BitmapFactory.decodeFile(cleanUrl, options); + + return image; + } + + int resourceId = mContext.getResources().getIdentifier(uriString, "drawable", mContext.getPackageName()); + Bitmap image = BitmapFactory.decodeResource(mContext.getResources(), resourceId); + + return image; + } +} + + + diff --git a/android/src/main/java/com/reactnativeescposprinter/MainActivityState.java b/android/src/main/java/com/reactnativeescposprinter/MainActivityState.java deleted file mode 100644 index 28c6ddd..0000000 --- a/android/src/main/java/com/reactnativeescposprinter/MainActivityState.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.reactnativeescposprinter; - -public enum MainActivityState { - DISCOVERING, - CONNECTING, - CONNECTED, - DISCONNECTING, - PRINTING, - IDLE -} diff --git a/android/src/main/java/com/reactnativeescposprinter/PrinterCallback.java b/android/src/main/java/com/reactnativeescposprinter/PrinterCallback.java new file mode 100644 index 0000000..7c84329 --- /dev/null +++ b/android/src/main/java/com/reactnativeescposprinter/PrinterCallback.java @@ -0,0 +1,8 @@ +package com.reactnativeescposprinter; + +import com.facebook.react.bridge.WritableMap; + +public interface PrinterCallback { + void onSuccess(WritableMap data); + void onError(String data); +} diff --git a/android/src/main/java/com/reactnativeescposprinter/PrinterDelegate.java b/android/src/main/java/com/reactnativeescposprinter/PrinterDelegate.java index 366fae3..503edf0 100644 --- a/android/src/main/java/com/reactnativeescposprinter/PrinterDelegate.java +++ b/android/src/main/java/com/reactnativeescposprinter/PrinterDelegate.java @@ -7,9 +7,6 @@ import org.json.JSONObject; public interface PrinterDelegate { - void onPrinterStartStatusMonitorResult(@NonNull final String objectid, final boolean hasError, final String error); - void onPrinterStopStatusMonitorResult(@NonNull final String objectid, final boolean hasError, final String error); - void onPrinterStatusChange(@NonNull final String objectid, final int status); void onGetPrinterSetting(@NonNull final String objectid, final int code, final int type, final int value); void onPtrReceive(@NonNull final String objectid, final JSONObject data); Context getContext(); diff --git a/android/src/main/java/com/reactnativeescposprinter/ThePrinter.java b/android/src/main/java/com/reactnativeescposprinter/ThePrinter.java index 937c071..0634c09 100644 --- a/android/src/main/java/com/reactnativeescposprinter/ThePrinter.java +++ b/android/src/main/java/com/reactnativeescposprinter/ThePrinter.java @@ -6,30 +6,31 @@ import com.epson.epos2.printer.PrinterStatusInfo; import com.epson.epos2.printer.ReceiveListener; import com.epson.epos2.printer.StatusChangeListener; +import com.epson.epos2.Epos2CallbackCode; -import com.reactnativeescposprinter.ThePrinterState; import com.reactnativeescposprinter.PrinterDelegate; import com.reactnativeescposprinter.EposStringHelper; +import com.reactnativeescposprinter.PrinterCallback; +import com.reactnativeescposprinter.ImageManager; -import org.json.JSONException; -import org.json.JSONObject; +import com.facebook.react.bridge.ReadableMap; +import com.facebook.react.bridge.WritableMap; +import com.facebook.react.bridge.Arguments; -public class ThePrinter implements StatusChangeListener, PrinterSettingListener, ReceiveListener { +import android.content.Context; +import android.graphics.Bitmap; +import android.util.Base64; + +public class ThePrinter implements PrinterSettingListener, ReceiveListener { private Printer epos2Printer_ = null; // Printer private volatile String printerTarget_ = null; // the printer target private boolean isConnected_ = false; // cache if printer is connected - private boolean didStartMonitor_ = false; // did start transactions private boolean didBeginTransaction_ = false; // did start Status Monitor - private boolean isWaitingForPrinterSettings_ = false; // Printer Settings requested - private boolean shutdown_ = false; // removing printer object private static final int DISCONNECT_INTERVAL = 500;//millseconds - private final Object shutdownLock_ = new Object(); // removing printer object - final private Object delegateSync_ = new Object(); //. delegate sync - - private ThePrinterState connectingState_ = ThePrinterState.PRINTER_IDLE; // state of connection - private PrinterDelegate delegate_ = null; // delegate callback + private PrinterCallback printCallback_ = null; // callback + private PrinterCallback getPrinterSettingCallback_ = null; // callback /** * Returns ThePrinter @@ -55,14 +56,9 @@ public void finalize() { @param callback delegate callbacks returns void */ - synchronized public void setupWith(final String printerTarget, final int series, final int lang, final PrinterDelegate callback) throws Epos2Exception { - - connectingState_ = ThePrinterState.PRINTER_IDLE; - synchronized (delegateSync_) { - delegate_ = callback; - } + synchronized public void setupWith(final String printerTarget, final int series, final int lang, Context context) throws Epos2Exception { printerTarget_ = printerTarget; - epos2Printer_ = new Printer(series, lang, callback.getContext()); + epos2Printer_ = new Printer(series, lang, context); epos2Printer_.setReceiveEventListener(this); } @@ -76,35 +72,6 @@ public String getPrinterTarget() { return printerTarget_; } - /** - * Returns void - * Function setBusy set the busy state of the printer - * @param busy set ThePrinterState - * * */ - synchronized public void setBusy(ThePrinterState busy) - { - connectingState_ = busy; - } - - /** - Returns void - Function removeDelegates removes all delegate callbacks. Used when tring to remove object - */ - synchronized public void removeDelegates() - { - - synchronized (delegateSync_) { - delegate_ = null; - } - - if (epos2Printer_ == null) return; - - epos2Printer_.setReceiveEventListener(null); - epos2Printer_.setConnectionEventListener(null); - epos2Printer_.setStatusChangeEventListener(null); - - } - /** Returns BOOL Function isConnected uses getStatus to understand if it is connected or not. @@ -127,90 +94,12 @@ synchronized public boolean isConnected() return isConnected; } - /** - Returns void - Function shutdown disconnects printer and sets flag to shutdown. Used when tring to remove object - @param closeConnection boolean set to disconnect printer - */ - public void shutdown(boolean closeConnection) { - - // set flag; - synchronized (shutdownLock_) { - if (shutdown_) return; - shutdown_ = true; - synchronized (delegateSync_) { - delegate_ = null; - } - } - - synchronized (this) { - - // disconnect - if (closeConnection && isConnected()) { - try { - disconnect(); - } catch (Epos2Exception e) { - e.printStackTrace(); - } - } - } - - } - - /** - Returns bool - Function isPrinterBusy returns if printer is busy doing a long operation - @return bool YES == printer is busy - */ - synchronized public boolean isPrinterBusy() - { - boolean isBusy = false; - - // printer not in idle state - if (connectingState_ != ThePrinterState.PRINTER_IDLE) isBusy = true; - - // waiting for printer settings to callback - if (isWaitingForPrinterSettings_) isBusy = true; - return isBusy; - } - - private void handleStartStatusMonitor(final String msg, final boolean didStart) { - - synchronized (this) { - if (epos2Printer_ == null) return; - - synchronized (delegateSync_) { - if (delegate_ != null) { - delegate_.onPrinterStartStatusMonitorResult(printerTarget_, !didStart, msg); - } - } - } - } - - private void handleStopStatusMonitor(final String msg, final boolean didStop) { - - synchronized (this) { - if (epos2Printer_ == null) return; - - synchronized (delegateSync_) { - if (delegate_ != null) { - delegate_.onPrinterStopStatusMonitorResult(printerTarget_, !didStop, msg); - } - } - } - } - /** throws Epos2Exception if there is an error Function connect tries to connect selected printer @param timeout the amount of time before giving up -- EPOS2_PARAM_DEFAULT - @param startMonitor to Start the realtime statusMonitor */ - public void connect(final int timeout, final boolean startMonitor) throws Epos2Exception { - - synchronized (shutdownLock_) { - if (shutdown_) throw new Epos2Exception(Epos2Exception.ERR_ILLEGAL); - } + public void connect(final int timeout) throws Epos2Exception { synchronized (this) { if (epos2Printer_ == null) throw new Epos2Exception(Epos2Exception.ERR_MEMORY); @@ -221,31 +110,16 @@ public void connect(final int timeout, final boolean startMonitor) throws Epos2E return; } - connectingState_ = ThePrinterState.PRINTER_CONNECTING; - isConnected_ = false; - isWaitingForPrinterSettings_ = false; - didStartMonitor_ = false; - didBeginTransaction_ = false; + try { epos2Printer_.connect(printerTarget_, timeout); isConnected_ = true; } catch (Epos2Exception e) { - connectingState_ = ThePrinterState.PRINTER_IDLE; e.printStackTrace(); isConnected_ = false; throw e; } - - if (!startMonitor) return; - - try { - startMonitor(); - } catch ( Epos2Exception e) { - e.printStackTrace(); - connectingState_ = ThePrinterState.PRINTER_IDLE; - } - } } @@ -259,8 +133,6 @@ synchronized public void disconnect() throws Epos2Exception { if (!isConnected_) return; - connectingState_ = ThePrinterState.PRINTER_DISCONNECTING; - if (didBeginTransaction_) { try { endTransaction(); @@ -269,14 +141,6 @@ synchronized public void disconnect() throws Epos2Exception { } } - if (didStartMonitor_) { - try { - stopMonitor(); - } catch (Epos2Exception e) { - e.printStackTrace(); - } - } - int count = 20; while (true) { try { @@ -288,99 +152,45 @@ synchronized public void disconnect() throws Epos2Exception { if (((Epos2Exception) e).getErrorStatus() == Epos2Exception.ERR_PROCESSING) { count--; try { - Thread.sleep(DISCONNECT_INTERVAL); + Thread.sleep(DISCONNECT_INTERVAL); } catch (Exception ignored) { } } else { - throw e; + if(((Epos2Exception) e).getErrorStatus() != Epos2Exception.ERR_ILLEGAL) { + throw e; + } } } } if (count == 0) { - connectingState_ = ThePrinterState.PRINTER_IDLE; throw new Epos2Exception(Epos2Exception.ERR_DISCONNECT); } - - synchronized (shutdownLock_) { - if (shutdown_) { - break; - } - } } epos2Printer_.clearCommandBuffer(); isConnected_ = false; - isWaitingForPrinterSettings_ = false; - didStartMonitor_ = false; didBeginTransaction_ = false; - connectingState_ = ThePrinterState.PRINTER_IDLE; } - /** - throws Epos2Exception if there is an error - Function Start the realtime Monitor for selected printer - */ - synchronized void startMonitor() throws Epos2Exception { - - synchronized (shutdownLock_) { - if (shutdown_) throw new Epos2Exception(Epos2Exception.ERR_ILLEGAL); - } - - if (didStartMonitor_) return; - - if (epos2Printer_ == null) throw new Epos2Exception(Epos2Exception.ERR_MEMORY); - - String msg = "SUCCESS"; - - Epos2Exception epos2Exception = null; - - try { - epos2Printer_.setStatusChangeEventListener(this); - epos2Printer_.startMonitor(); - didStartMonitor_ = true; - } catch (Epos2Exception e) { - epos2Exception = e; - epos2Printer_.setStatusChangeEventListener(null); - e.printStackTrace(); - msg = EposStringHelper.getEposExceptionText(e.getErrorStatus()); - - didStartMonitor_ = false; - } - - handleStartStatusMonitor(msg, didStartMonitor_); - if (epos2Exception != null) throw epos2Exception; + synchronized public void clearCommandBuffer() throws Epos2Exception { + if (epos2Printer_ == null) throw new Epos2Exception(Epos2Exception.ERR_MEMORY); + epos2Printer_.clearCommandBuffer(); } - /** - throws Epos2Exception if there is an error - Function Stops the realtime Monitor for selected printer - */ - synchronized void stopMonitor() throws Epos2Exception { - + synchronized public void sendData(int timeout, PrinterCallback handler) throws Epos2Exception { if (epos2Printer_ == null) throw new Epos2Exception(Epos2Exception.ERR_MEMORY); - if (!didStartMonitor_) return; - - Epos2Exception epos2Exception = null; - - String msg = "SUCCESS"; - + beginTransaction(); try { - epos2Printer_.setStatusChangeEventListener(null); - epos2Printer_.stopMonitor(); - didStartMonitor_ = false; + epos2Printer_.sendData(timeout); + printCallback_ = handler; } catch (Epos2Exception e) { - msg = EposStringHelper.getEposExceptionText(e.getErrorStatus()); - epos2Exception = e; - e.printStackTrace(); + endTransaction(); + throw e; } - handleStopStatusMonitor(msg, !didStartMonitor_); - - if (epos2Exception != null) throw epos2Exception; - } /** @@ -388,11 +198,6 @@ synchronized void stopMonitor() throws Epos2Exception { Function beginTransaction see ePOS SDK */ synchronized public void beginTransaction() throws Epos2Exception { - - synchronized (shutdownLock_) { - if (shutdown_) throw new Epos2Exception(Epos2Exception.ERR_ILLEGAL); - } - if (epos2Printer_ == null) throw new Epos2Exception(Epos2Exception.ERR_MEMORY); if (didBeginTransaction_) return; @@ -426,144 +231,190 @@ synchronized public void endTransaction() throws Epos2Exception { } } - /** - throws Epos2Exception if there is an error - Function getPrinterSetting see ePOS SDK - */ - synchronized public void getPrinterSetting(int timeout, int type) throws Epos2Exception { + synchronized public void addText(String data) throws Epos2Exception { + if (epos2Printer_ == null) throw new Epos2Exception(Epos2Exception.ERR_MEMORY); + + epos2Printer_.addText(data); + } - synchronized (shutdownLock_) { - if (shutdown_) throw new Epos2Exception(Epos2Exception.ERR_ILLEGAL); - } + synchronized public void addTextLang(int lang) throws Epos2Exception { if (epos2Printer_ == null) throw new Epos2Exception(Epos2Exception.ERR_MEMORY); - if (!isConnected_) { - throw new Epos2Exception(Epos2Exception.ERR_CONNECT); - } + epos2Printer_.addTextLang(lang); + } - // still waiting for previous attempt - if (isWaitingForPrinterSettings_) { - throw new Epos2Exception(Epos2Exception.ERR_PROCESSING); - } + synchronized public void addFeedLine(int line) throws Epos2Exception { + if (epos2Printer_ == null) throw new Epos2Exception(Epos2Exception.ERR_MEMORY); - if (delegate_ == null) { - throw new Epos2Exception(Epos2Exception.ERR_PARAM); - } + epos2Printer_.addFeedLine(line); + } - isWaitingForPrinterSettings_ = true; - epos2Printer_.getPrinterSetting(timeout, type, this); + synchronized public void addCut(int type) throws Epos2Exception { + if (epos2Printer_ == null) throw new Epos2Exception(Epos2Exception.ERR_MEMORY); + + epos2Printer_.addCut(type); } - /** - returns Printer - Function getEpos2Printer - */ - synchronized public Printer getEpos2Printer() - { - return epos2Printer_; + synchronized public void addCommand(String base64string) throws Epos2Exception { + if (epos2Printer_ == null) throw new Epos2Exception(Epos2Exception.ERR_MEMORY); + + byte[] data = Base64.decode(base64string, Base64.DEFAULT); + epos2Printer_.addCommand(data); } + synchronized public void addPulse(int drawer, int time) throws Epos2Exception { + if (epos2Printer_ == null) throw new Epos2Exception(Epos2Exception.ERR_MEMORY); - // region StatusChangeListener - @Override - public void onPtrStatusChange(Printer printer, int eventType) { + epos2Printer_.addPulse(drawer, time); + } - String _objID = Integer.toString(this.hashCode()); - if (connectingState_ == ThePrinterState.PRINTER_CONNECTING) - connectingState_ = ThePrinterState.PRINTER_IDLE; + synchronized public void addTextAlign(int align) throws Epos2Exception { + if (epos2Printer_ == null) throw new Epos2Exception(Epos2Exception.ERR_MEMORY); - synchronized (shutdownLock_) { - if (shutdown_) return; - } + epos2Printer_.addTextAlign(align); + } - new Thread(new Runnable() { - @Override - public void run() { - synchronized (delegateSync_) { - if (delegate_ != null) delegate_.onPrinterStatusChange(_objID, eventType); - } - } - }).start(); + synchronized public void addTextSize(int width, int height) throws Epos2Exception { + if (epos2Printer_ == null) throw new Epos2Exception(Epos2Exception.ERR_MEMORY); + epos2Printer_.addTextSize(width, height); } - // endregion - // region PrinterSettingListener - @Override - public void onGetPrinterSetting(int code, int type, int value) { + synchronized public void addTextSmooth(int smooth) throws Epos2Exception { + if (epos2Printer_ == null) throw new Epos2Exception(Epos2Exception.ERR_MEMORY); - String _objID = Integer.toString(this.hashCode()); + epos2Printer_.addTextSmooth(smooth); + } - synchronized (shutdownLock_) { - if (shutdown_) { - isWaitingForPrinterSettings_ = false; - return; - } - } + synchronized public void addTextStyle(int reverse, int ul, int em, int color) throws Epos2Exception { + if (epos2Printer_ == null) throw new Epos2Exception(Epos2Exception.ERR_MEMORY); + epos2Printer_.addTextStyle(reverse, ul, em, color); + } - new Thread(new Runnable() { - @Override - public void run() { + synchronized public void addImage(ReadableMap source, Context mContext, int width, int color, + int mode, int halftone, double brightness, int compress) throws Epos2Exception { + if (epos2Printer_ == null) throw new Epos2Exception(Epos2Exception.ERR_MEMORY); + + Bitmap bitmap = null; + + try { + bitmap = ImageManager.getBitmapFromSource(source, mContext); + } catch (Exception e) { + throw new Epos2Exception(Epos2Exception.ERR_MEMORY); + } + + float aspectRatio = bitmap.getWidth() / (float) bitmap.getHeight(); + int newHeight = Math.round(width / aspectRatio); + bitmap = Bitmap.createScaledBitmap(bitmap, width, newHeight, false); + + epos2Printer_.addImage(bitmap, 0, 0, width, newHeight, color, mode, halftone, brightness, compress); - synchronized (delegateSync_) { - if (delegate_ != null) delegate_.onGetPrinterSetting(_objID , code, type, value); - } - isWaitingForPrinterSettings_ = false; - } - }).start(); } - @Override - public void onSetPrinterSetting(int code) { + synchronized public void addBarcode(String data, int type, int hri, int font, int width, int height) throws Epos2Exception { + if (epos2Printer_ == null) throw new Epos2Exception(Epos2Exception.ERR_MEMORY); + epos2Printer_.addBarcode(data, type, hri, font, width, height); } - // endregion - // region ReceiveListener - @Override - public void onPtrReceive(Printer printer, int code, PrinterStatusInfo status, String printJobId) { + synchronized public void addSymbol(String data, int type, int level, int width, int height, int size) throws Epos2Exception { + if (epos2Printer_ == null) throw new Epos2Exception(Epos2Exception.ERR_MEMORY); - synchronized (shutdownLock_) { - if (shutdown_) { - connectingState_ = ThePrinterState.PRINTER_IDLE; - return; - } - } + epos2Printer_.addSymbol(data, type, level, width, height, size); + } - String _objID = Integer.toString(this.hashCode()); + synchronized public WritableMap getStatus() throws Epos2Exception { + if (epos2Printer_ == null) throw new Epos2Exception(Epos2Exception.ERR_MEMORY); + PrinterStatusInfo status = epos2Printer_.getStatus(); + WritableMap statusMap = EposStringHelper.convertStatusInfoToWritableMap(status); + return statusMap; + } - if (printJobId == null) { - printJobId = ""; - } + /** + throws Epos2Exception if there is an error + Function getPrinterSetting see ePOS SDK + */ + synchronized public void getPrinterSetting(int timeout, int type, PrinterCallback handler) throws Epos2Exception { + if (epos2Printer_ == null) throw new Epos2Exception(Epos2Exception.ERR_MEMORY); - // store result of printing - JSONObject returnData = new JSONObject(); + beginTransaction(); try { - returnData.put("ResultRawCode", code); - returnData.put("ResultCode", EposStringHelper.getEposResultText(code)); - returnData.put("ResultStatus", EposStringHelper.makeStatusMessage(status)); - returnData.put("printJobId", printJobId); - - } catch (JSONException e) { - // TODO Auto-generated catch block - e.printStackTrace(); + epos2Printer_.getPrinterSetting(timeout, type, this); + getPrinterSettingCallback_ = handler; + } catch (Epos2Exception e) { + endTransaction(); + throw e; } + } + + /** + returns Printer + Function getEpos2Printer + */ + synchronized public Printer getEpos2Printer() + { + return epos2Printer_; + } + + @Override + public void onGetPrinterSetting(int code, int type, int value) { new Thread(new Runnable() { @Override synchronized public void run() { - synchronized (delegateSync_) { - if (delegate_ != null) { - delegate_.onPtrReceive(_objID, returnData); - } else { - connectingState_ = ThePrinterState.PRINTER_IDLE; - } + try { + endTransaction(); + } catch (Exception e) { + e.printStackTrace(); + } + if (getPrinterSettingCallback_ != null) { + if(code == Epos2CallbackCode.CODE_SUCCESS) { + WritableMap returnData = Arguments.createMap(); + returnData.putInt("type", type); + returnData.putInt("value",value); + + getPrinterSettingCallback_.onSuccess(returnData); + } else { + getPrinterSettingCallback_.onError(EposStringHelper.getErrorTextData(code, "code")); + } + getPrinterSettingCallback_ = null; + } + } + }).start(); + } + + // region ReceiveListener + @Override + public void onPtrReceive(Printer printer, int code, PrinterStatusInfo status, String printJobId) { + + new Thread(new Runnable() { + @Override + synchronized public void run() { + try { + endTransaction(); + } catch (Exception e) { + e.printStackTrace(); + } + if (printCallback_ != null) { + if(code == Epos2CallbackCode.CODE_SUCCESS) { + WritableMap returnData = EposStringHelper.convertStatusInfoToWritableMap(status); + printCallback_.onSuccess(returnData); + } else { + printCallback_.onError(EposStringHelper.getErrorTextData(code, "code")); + } + printCallback_ = null; } } }).start(); } - // endregion + + + @Override + public void onSetPrinterSetting(int code) { + + } + } diff --git a/android/src/main/java/com/reactnativeescposprinter/ThePrinterState.java b/android/src/main/java/com/reactnativeescposprinter/ThePrinterState.java deleted file mode 100644 index d0b53ca..0000000 --- a/android/src/main/java/com/reactnativeescposprinter/ThePrinterState.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.reactnativeescposprinter; - -public enum ThePrinterState { - PRINTER_IDLE, - PRINTER_CONNECTING, - PRINTER_DISCONNECTING, - PRINTER_PRINTING, - PRINTER_REMOVING -} diff --git a/android/src/main/java/com/reactnativeescposprinter/ThePrinterWrapper.java b/android/src/main/java/com/reactnativeescposprinter/ThePrinterWrapper.java deleted file mode 100644 index 7d24c08..0000000 --- a/android/src/main/java/com/reactnativeescposprinter/ThePrinterWrapper.java +++ /dev/null @@ -1,829 +0,0 @@ -package com.reactnativeescposprinter; - -import static com.reactnativeescposprinter.ePOSCmd.POS_SUCCESS; - -import com.facebook.react.bridge.Promise; -import com.facebook.react.bridge.ReactApplicationContext; -import com.facebook.react.bridge.ReactContextBaseJavaModule; -import com.facebook.react.bridge.ReactMethod; -import com.facebook.react.bridge.ReadableArray; -import com.facebook.react.bridge.ReadableMap; -import com.facebook.react.module.annotations.ReactModule; - -import android.content.Context; -import android.content.res.AssetManager; -import android.graphics.Bitmap; -import android.graphics.BitmapFactory; -import android.util.Base64; - -import androidx.annotation.NonNull; - -import com.epson.epos2.Epos2Exception; -import com.epson.epos2.printer.Printer; -import com.epson.epos2.printer.PrinterSettingListener; -import com.epson.epos2.printer.PrinterStatusInfo; -import com.epson.epos2.Epos2CallbackCode; -import com.reactnativeescposprinter.ThePrinter; -import com.reactnativeescposprinter.ThePrinterState; -import com.reactnativeescposprinter.PrinterDelegate; -import com.reactnativeescposprinter.ThePrinterWrapperDelegate; -import com.reactnativeescposprinter.EscPosPrinterErrorManager; -import com.reactnativeescposprinter.ThePrinterManager; - -import org.json.JSONObject; - -import java.io.IOException; -import java.io.InputStream; -import java.net.URL; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -@ReactModule(name = ThePrinterWrapper.NAME) -public class ThePrinterWrapper extends ReactContextBaseJavaModule implements PrinterDelegate { - - private Context context_ = null; // Activity object - private final ReactApplicationContext reactContext; - private ThePrinterManager thePrinterManager_ = ThePrinterManager.getInstance(); // manage the ThePrinter objects - ExecutorService tasksQueue = Executors.newSingleThreadExecutor(); - final private Object delegateSync_ = new Object(); // delegate sync lock - - public static final String NAME = "ThePrinterWrapper"; - - interface MyCallbackInterface { - void onSuccess(String result); - void onError(String result); - } - - public ThePrinterWrapperDelegate delegate_ = null; // delegate callback - - public ThePrinterWrapper(ReactApplicationContext reactContext) { - super(reactContext); - context_ = reactContext; - this.reactContext = reactContext; - } - - @Override - @NonNull - public String getName() { - return NAME; - } - - - private void handleNoObject(final String objectid, final String printerTarget) - { - synchronized (delegateSync_) { - if (delegate_ != null) { - delegate_.onMemoryError(objectid, "NoObject Created for: " + printerTarget); - } - } - } - - @ReactMethod - public void init(String target, int series, int language, Promise promise) { - this.initializeObject(target, series, language, new MyCallbackInterface() { - @Override - public void onSuccess(String result) { - promise.resolve(result); - } - @Override - public void onError(String result) { - promise.reject(result); - } - }); - } - - private void initializeObject(String target, int series, int language, MyCallbackInterface callback) { - ThePrinter thePrinter = thePrinterManager_.getObject(target); - try { - if (thePrinter == null) { - try { - ThePrinter newPrinter = new ThePrinter(); - thePrinterManager_.add(newPrinter, target); - newPrinter.setupWith(target, series, language, this); - } catch (Epos2Exception e) { - callback.onError("The printer object couldn't be created"); - } - } - connectPrinter(target, callback); - } catch (Exception e) { - callback.onError(e.getMessage()); - } - } - - @ReactMethod - public void disconnectAndDeallocate(String target, Promise promise) { - this.deallocPrinter(target, new MyCallbackInterface() { - @Override - public void onSuccess(String result) { - promise.resolve(result); - } - @Override - public void onError(String result) { - promise.reject(result); - } - }); - } - /** - Function deallocPrinter tries to delete selected printer from memory and disconnect if connected. - @param printerTarget the printer target - */ - public void deallocPrinter(@NonNull final String printerTarget, MyCallbackInterface callback) { - - try { - ThePrinter thePrinter = null; - synchronized (this) { - - thePrinter = thePrinterManager_.getObject(printerTarget); - if (thePrinter == null) { - String errorString = EscPosPrinterErrorManager.getEposExceptionText(Epos2Exception.ERR_MEMORY); - callback.onError(errorString); - } - - if (thePrinter.isPrinterBusy()) { - String errorString = EscPosPrinterErrorManager.getEposExceptionText(Epos2Exception.ERR_IN_USE); - callback.onError(errorString); - } - - thePrinter.setBusy(ThePrinterState.PRINTER_REMOVING); - - thePrinter.removeDelegates(); - - thePrinterManager_.remove(printerTarget); - } - - thePrinter.shutdown(true); - - try { - Thread.sleep(1000); // give time for any callbacks to finish - } catch (InterruptedException e) { - callback.onError("Interrupted"); - } - thePrinter = null; - callback.onSuccess(EscPosPrinterErrorManager.getCodeText(POS_SUCCESS)); - } catch (Exception e) { - callback.onSuccess(e.getMessage()); - } - } - - @ReactMethod - public void connect(String target, Promise promise) { - this.connectPrinter(target, new MyCallbackInterface() { - @Override - public void onSuccess(String result) { - promise.resolve(result); - } - @Override - public void onError(String result) { - promise.reject(result); - } - }); - } - /** - Function connectPrinter tries to connect selected printer - @param printerTarget the printer target - */ - public void connectPrinter(@NonNull String printerTarget, MyCallbackInterface callback) { - - try { - ThePrinter thePrinter = null; - synchronized (this) { - thePrinter = thePrinterManager_.getObject(printerTarget); - if (thePrinter == null) { - String errorString = EscPosPrinterErrorManager.getEposExceptionText(Epos2Exception.ERR_MEMORY); - callback.onError(errorString); - } - thePrinter.setBusy(ThePrinterState.PRINTER_CONNECTING); - } - try { - thePrinter.connect(Printer.PARAM_DEFAULT, true); - callback.onSuccess(EscPosPrinterErrorManager.getCodeText(POS_SUCCESS)); - } catch (Epos2Exception e) { - String errorString = EscPosPrinterErrorManager.getEposExceptionText(e.getErrorStatus()); - callback.onError(errorString); - } - } catch (Exception e) { - callback.onError(e.getMessage()); - } - } - - @ReactMethod - public void disconnect(String target, Promise promise) { - this.disconnectPrinter(target, new MyCallbackInterface() { - @Override - public void onSuccess(String result) { - promise.resolve(result); - } - @Override - public void onError(String result) { - promise.reject(result); - } - }); - } - /** - Function disconnectPrinter tries to disconnect selected printer - @param printerTarget the printer target - */ - public void disconnectPrinter(@NonNull final String printerTarget, MyCallbackInterface callback) { - - try { - ThePrinter thePrinter = null; - synchronized (this) { - thePrinter = thePrinterManager_.getObject(printerTarget); - if (thePrinter == null) { - String errorString = EscPosPrinterErrorManager.getEposExceptionText(Epos2Exception.ERR_MEMORY); - callback.onError(errorString); - } - - if (thePrinter.isPrinterBusy()) { - String errorString = EscPosPrinterErrorManager.getEposExceptionText(Epos2Exception.ERR_IN_USE); - callback.onError(errorString); - } - thePrinter.setBusy(ThePrinterState.PRINTER_DISCONNECTING); - } - - try { - thePrinter.disconnect(); - callback.onSuccess(EscPosPrinterErrorManager.getCodeText(POS_SUCCESS)); - } catch (Epos2Exception e) { - String errorString = EscPosPrinterErrorManager.getEposExceptionText(e.getErrorStatus()); - callback.onError(errorString); - } - } catch(Exception e) { - callback.onError(e.getMessage()); - } - } - - synchronized public void setBusy(@NonNull final String objectid, ThePrinterState state) { - ThePrinter thePrinter = thePrinterManager_.getObject(objectid); - - if (thePrinter == null) { - return; - } - - thePrinter.setBusy(state); - } - - synchronized public boolean isPrinterBusy(@NonNull final String objectid) { - - ThePrinter thePrinter = thePrinterManager_.getObject(objectid); - - if (thePrinter == null) { - return false; - } - - return thePrinter.isPrinterBusy(); - } - - - /** - Returns void - Function handleStatusMonitorResult is used to inform the UI that the Status real time monitor has started/stop success/failed - please handle in your app - @param printerTarget String the object hash key - @param method String the method that called function - @param hasError boolean if failer has happened will be true - @param error String the error message - */ - void handleStatusMonitorResult(String printerTarget, String method, boolean hasError, String error) - { - - if (method.startsWith("onPrinterStartStatusMonitorResult")) { // Status Monitor Start success/failer - - new Thread (() -> { - synchronized (delegateSync_) { - if (delegate_ != null) delegate_.onPrinterStartStatusMonitorResult(printerTarget, hasError, error); - } - }).start(); - - return; - } - - if (method.startsWith("onPrinterStopStatusMonitorResult")) { // Status Monitor Stop success/failer - new Thread (() -> { - synchronized (delegateSync_) { - if (delegate_ != null) delegate_.onPrinterStopStatusMonitorResult(printerTarget, hasError, error); - } - }).start(); - } - } - - // region Printer Object API - /** - Returns ePOS result int - @param printerTarget the printer target - @return int ePOS result - */ - synchronized public int beginTransaction(@NonNull final String printerTarget) { - - ThePrinter thePrinter = thePrinterManager_.getObject(printerTarget); - if (thePrinter == null) return Epos2Exception.ERR_MEMORY; - - try { - thePrinter.beginTransaction(); - } catch (Epos2Exception e) { - e.printStackTrace(); - return ((Epos2Exception) e).getErrorStatus(); - } - - return POS_SUCCESS; - - } - - synchronized public int addTextAlign(@NonNull final String printerTarget, final int align) { - - ThePrinter thePrinter = thePrinterManager_.getObject(printerTarget); - if (thePrinter == null) return Epos2Exception.ERR_MEMORY; - - Printer printer = thePrinter.getEpos2Printer(); - if (printer == null) return Epos2Exception.ERR_MEMORY; - - try { - printer.addTextAlign(align); - } catch (Epos2Exception e) { - e.printStackTrace(); - return ((Epos2Exception) e).getErrorStatus(); - } - - return POS_SUCCESS; - - } - - synchronized public int addImage(@NonNull final String printerTarget, @NonNull Bitmap data, int x, int y, int width, int height, int color, int mode, int halftone, double brightness, int compress) { - - ThePrinter thePrinter = thePrinterManager_.getObject(printerTarget); - if (thePrinter == null) return Epos2Exception.ERR_MEMORY; - - Printer printer = thePrinter.getEpos2Printer(); - if (printer == null) return Epos2Exception.ERR_MEMORY; - - try { - printer.addImage(data, x, y, width, height, color, mode, halftone, brightness, compress); - } catch (Epos2Exception e) { - e.printStackTrace(); - return ((Epos2Exception) e).getErrorStatus(); - } - - return POS_SUCCESS; - - } - - synchronized public int addFeedLine(@NonNull final String printerTarget, int line) { - - ThePrinter thePrinter = thePrinterManager_.getObject(printerTarget); - if (thePrinter == null) return Epos2Exception.ERR_MEMORY; - - Printer printer = thePrinter.getEpos2Printer(); - if (printer == null) return Epos2Exception.ERR_MEMORY; - - try { - printer.addFeedLine(line); - } catch (Epos2Exception e) { - e.printStackTrace(); - return ((Epos2Exception) e).getErrorStatus(); - } - - return POS_SUCCESS; - - } - - synchronized public int addText(@NonNull final String printerTarget, @NonNull String data) { - ThePrinter thePrinter = thePrinterManager_.getObject(printerTarget); - if (thePrinter == null) return Epos2Exception.ERR_MEMORY; - - Printer printer = thePrinter.getEpos2Printer(); - if (printer == null) return Epos2Exception.ERR_MEMORY; - - try { - printer.addText(data); - } catch (Epos2Exception e) { - e.printStackTrace(); - return ((Epos2Exception) e).getErrorStatus(); - } - - return POS_SUCCESS; - - } - - synchronized public int addTextSize(@NonNull final String printerTarget, int width, int height) { - ThePrinter thePrinter = thePrinterManager_.getObject(printerTarget); - if (thePrinter == null) return Epos2Exception.ERR_MEMORY; - - Printer printer = thePrinter.getEpos2Printer(); - if (printer == null) return Epos2Exception.ERR_MEMORY; - - try { - printer.addTextSize(width, height); - } catch (Epos2Exception e) { - e.printStackTrace(); - return ((Epos2Exception) e).getErrorStatus(); - } - - return POS_SUCCESS; - } - - synchronized public int addBarcode(@NonNull final String printerTarget, String data, int type, int hri, int font, int width, int height) { - - ThePrinter thePrinter = thePrinterManager_.getObject(printerTarget); - if (thePrinter == null) return Epos2Exception.ERR_MEMORY; - - Printer printer = thePrinter.getEpos2Printer(); - if (printer == null) return Epos2Exception.ERR_MEMORY; - - try { - printer.addBarcode(data, type, hri, font, width, height); - } catch (Epos2Exception e) { - e.printStackTrace(); - return ((Epos2Exception) e).getErrorStatus(); - } - - return POS_SUCCESS; - - } - - synchronized public int addCut(@NonNull final String printerTarget, int type) { - - ThePrinter thePrinter = thePrinterManager_.getObject(printerTarget); - if (thePrinter == null) return Epos2Exception.ERR_MEMORY; - - Printer printer = thePrinter.getEpos2Printer(); - if (printer == null) return Epos2Exception.ERR_MEMORY; - - try { - printer.addCut(type); - } catch (Epos2Exception e) { - e.printStackTrace(); - return ((Epos2Exception) e).getErrorStatus(); - } - - return POS_SUCCESS; - } - - synchronized public int clearCommandBuffer(@NonNull final String printerTarget) { - - ThePrinter thePrinter = thePrinterManager_.getObject(printerTarget); - if (thePrinter == null) return Epos2Exception.ERR_MEMORY; - - Printer printer = thePrinter.getEpos2Printer(); - if (printer == null) return Epos2Exception.ERR_MEMORY; - - printer.clearCommandBuffer(); - - return POS_SUCCESS; - } - - synchronized public int endTransaction(@NonNull final String printerTarget) { - ThePrinter thePrinter = thePrinterManager_.getObject(printerTarget); - if (thePrinter == null) return Epos2Exception.ERR_MEMORY; - - try { - thePrinter.endTransaction(); - } catch (Epos2Exception e) { - e.printStackTrace(); - return ((Epos2Exception) e).getErrorStatus(); - } - - return POS_SUCCESS; - - } - - public PrinterStatusInfo getPrinterStatus(@NonNull final String printerTarget) { - - PrinterStatusInfo dummyInfo = new PrinterStatusInfo(); - Printer eposPrinter = null; - - synchronized (this) { - ThePrinter thePrinter = thePrinterManager_.getObject(printerTarget); - if (thePrinter == null) return dummyInfo; - - eposPrinter = thePrinter.getEpos2Printer(); - - if (eposPrinter == null) return dummyInfo; - } - - return eposPrinter.getStatus(); - - } - - synchronized public int getPrinterSetting(@NonNull final String printerTarget, int timeout, int type) { - ThePrinter thePrinter = thePrinterManager_.getObject(printerTarget); - if (thePrinter == null) return Epos2Exception.ERR_MEMORY; - - try { - thePrinter.getPrinterSetting(timeout, type); - } catch (Epos2Exception e) { - e.printStackTrace(); - return ((Epos2Exception) e).getErrorStatus(); - } - - return POS_SUCCESS; - - } - - @ReactMethod - public void printBuffer(ReadableArray printBuffer, final String target, final ReadableMap paramsMap, Promise promise) { - tasksQueue.submit(new Runnable() { - @Override - public void run() { - printFromBuffer(printBuffer, target, paramsMap, new MyCallbackInterface() { - @Override - public void onSuccess(String result) { - promise.resolve(result); - } - - @Override - public void onError(String result) { - promise.reject(result); - } - }); - } - }); - } - - public void printFromBuffer(ReadableArray printBuffer, final String target, final ReadableMap paramsMap, MyCallbackInterface callback) { - try { - ThePrinter thePrinter = thePrinterManager_.getObject(target); - if (thePrinter == null) { - String errorString = EscPosPrinterErrorManager.getEposExceptionText(Epos2Exception.ERR_MEMORY); - callback.onError(errorString); - return; - } - - Printer printer = thePrinter.getEpos2Printer(); - if (printer == null) { - String errorString = EscPosPrinterErrorManager.getEposExceptionText(Epos2Exception.ERR_MEMORY); - callback.onError(errorString); - return; - } - - try { - printer.clearCommandBuffer(); - int bufferLength = printBuffer.size(); - for (int curr = 0; curr < bufferLength; curr++) { - ReadableArray command = printBuffer.getArray(curr); - handleCommand(command.getInt(0), command.getArray(1), target); - } - } catch (Epos2Exception e) { - printer.clearCommandBuffer(); - int status = EscPosPrinterErrorManager.getErrorStatus(e); - String errorString = EscPosPrinterErrorManager.getEposExceptionText(status); - callback.onError(errorString); - return; - } catch (IOException e) { - printer.clearCommandBuffer(); - callback.onError(e.getMessage()); - return; - } - - try { - this.printData(paramsMap, target); - String successString = EscPosPrinterErrorManager.getCodeText(Epos2CallbackCode.CODE_SUCCESS); - callback.onSuccess(successString); - } catch (Epos2Exception e) { - int status = EscPosPrinterErrorManager.getErrorStatus(e); - String errorString = EscPosPrinterErrorManager.getEposExceptionText(status); - callback.onError(errorString); - } - - } catch (Exception e) { - callback.onError(e.getMessage()); - } - } - synchronized public int sendData(@NonNull final String objectid, int timeout) { - ThePrinter thePrinter = thePrinterManager_.getObject(objectid); - if (thePrinter == null) return Epos2Exception.ERR_MEMORY; - - Printer printer = thePrinter.getEpos2Printer(); - if (printer == null) return Epos2Exception.ERR_MEMORY; - - thePrinter.setBusy(ThePrinterState.PRINTER_PRINTING); - - try { - printer.sendData(timeout); - } catch (Epos2Exception e) { - e.printStackTrace(); - return ((Epos2Exception) e).getErrorStatus(); - } - - return POS_SUCCESS; - - } - // endregion - - // region PrinterDelegate - - - /** - Returns void - Function onPrinterStartStatusMonitorResult informs that Start Status monitor has been successfull/failed. - @param printerTarget String the printer target - @param hasError boolean if the status has failed will be false - @param error String contains why start failed - */ - @Override - public void onPrinterStartStatusMonitorResult(@NonNull String printerTarget, boolean hasError, String error) { - handleStatusMonitorResult(printerTarget, "onPrinterStartStatusMonitorResult", hasError, error); - } - - /** - Returns void - Function onPrinterStopStatusMonitorResult informs that Stop Status monitor has been successful/failed. - @param printerTarget String the object hash key - @param hasError boolean if the status has failed will be false - @param error String contains why stop failed - */ - @Override - public void onPrinterStopStatusMonitorResult(@NonNull String printerTarget, boolean hasError, String error) { - handleStatusMonitorResult(printerTarget, "onPrinterStopStatusMonitorResult", hasError, error); - } - - /** - Returns void - Function onPrinterStatusChange informs the UI that the printer status has changed - @param printerTarget String the printer target - @param status int new status - */ - @Override - public void onPrinterStatusChange(@NonNull String printerTarget, int status) { - - new Thread (() -> { - synchronized (delegateSync_) { - if (delegate_ != null) delegate_.onPrinterStatusChange(printerTarget, status); - } - }).start(); - } - - /** - Returns void - Function onGetPrinterSetting informs the UI of the printer settings that where requested - @param printerTarget String the printer target - @param code int ePOS result - @param type int ePOS Settings Type -- EPOS2_PRINTER_SETTING_PAPERWIDTH - @param value int ePOS value -- Printer.SETTING_PAPERWIDTH_58_0 - */ - @Override - public void onGetPrinterSetting(@NonNull String printerTarget, int code, int type, int value) { - - new Thread (() -> { - synchronized (delegateSync_) { - if (delegate_ != null) delegate_.onGetPrinterSetting(printerTarget, code, type, value); - } - }).start(); - - } - - /** - Returns void - Function onPtrReceive informs the UI of the status of the print job that was received - @param printerTarget String the printer target - @param data JSONObject storing the result - */ - @Override - public void onPtrReceive(@NonNull String printerTarget, @NonNull JSONObject data) { - new Thread (() -> { - synchronized (delegateSync_) { - if (delegate_ != null) delegate_.onPtrReceive(printerTarget, data); - } - }).start(); - } - - @Override - synchronized public Context getContext() { - return context_; - } - - private void handleCommand(int command, ReadableArray params, String target) throws Exception { - Printer printer = thePrinterManager_.getObject(target).getEpos2Printer(); - switch (command) { - case PrintingCommands.COMMAND_ADD_TEXT: - printer.addText(params.getString(0)); - break; - case PrintingCommands.COMMAND_ADD_PULSE: - printer.addPulse(params.getInt(0), Printer.PARAM_DEFAULT); - break; - case PrintingCommands.COMMAND_ADD_NEW_LINE: - printer.addFeedLine(params.getInt(0)); - break; - case PrintingCommands.COMMAND_ADD_TEXT_STYLE: - printer.addTextStyle(Printer.FALSE, params.getInt(0), params.getInt(1), Printer.COLOR_1); - break; - case PrintingCommands.COMMAND_ADD_TEXT_SIZE: - printer.addTextSize(params.getInt(0), params.getInt(1)); - break; - case PrintingCommands.COMMAND_ADD_ALIGN: - printer.addTextAlign(params.getInt(0)); - break; - - case PrintingCommands.COMMAND_ADD_IMAGE: - ReadableMap source = params.getMap(0); - - int imgWidth = params.getInt(1); - int color = params.getInt(2); - int mode = params.getInt(3); - int halftone = params.getInt(4); - double brightness = params.getDouble(5); - Bitmap imgBitmap = getBitmapFromSource(source); - handlePrintImage(imgBitmap, imgWidth, color, mode, halftone, brightness, printer); - - break; - case PrintingCommands.COMMAND_ADD_IMAGE_BASE_64: - String uriString = params.getString(0); - final String pureBase64Encoded = uriString.substring(uriString.indexOf(",") + 1); - byte[] decodedString = Base64.decode(pureBase64Encoded, Base64.DEFAULT); - Bitmap bitmap = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length); - int inputWidth = params.getInt(1); - - handlePrintImage(bitmap, inputWidth, Printer.COLOR_1, Printer.MODE_MONO, Printer.HALFTONE_DITHER, Printer.PARAM_DEFAULT, printer); - break; - - case PrintingCommands.COMMAND_ADD_IMAGE_ASSET: - String imageName = params.getString(0); - int width = params.getInt(1); - - AssetManager assetManager = context_.getAssets(); - InputStream inputStream = assetManager.open(params.getString(0)); - Bitmap assetBitmap = BitmapFactory.decodeStream(inputStream); - inputStream.close(); - handlePrintImage(assetBitmap, width, Printer.COLOR_1, Printer.MODE_MONO, Printer.HALFTONE_DITHER, Printer.PARAM_DEFAULT, printer); - break; - case PrintingCommands.COMMAND_ADD_CUT: - printer.addCut(Printer.CUT_FEED); - break; - case PrintingCommands.COMMAND_ADD_DATA: - String base64String = params.getString(0); - byte[] data = Base64.decode(base64String, Base64.DEFAULT); - printer.addCommand(data); - break; - case PrintingCommands.COMMAND_ADD_TEXT_SMOOTH: - printer.addTextSmooth(params.getInt(0)); - break; - case PrintingCommands.COMMAND_ADD_BARCODE: - printer.addBarcode(params.getString(0), params.getInt(1), params.getInt(2), Printer.FONT_A, params.getInt(3), params.getInt(4)); - break; - case PrintingCommands.COMMAND_ADD_QRCODE: - printer.addSymbol(params.getString(0), params.getInt(1), params.getInt(2), params.getInt(3), params.getInt(3), params.getInt(3)); - break; - default: - throw new IllegalArgumentException("Invalid Printing Command"); - } - } - - private void handlePrintImage(Bitmap bitmap, int width, int color, int mode, int halftone, double brightness, Printer printer) throws Epos2Exception { - float aspectRatio = bitmap.getWidth() / (float) bitmap.getHeight(); - int newHeight = Math.round(width / aspectRatio); - bitmap = Bitmap.createScaledBitmap(bitmap, width, newHeight, false); - - printer.addImage( - bitmap, - 0, - 0, - width, - newHeight, - color, - mode, - halftone, - brightness, - Printer.COMPRESS_AUTO - ); - } - - private Bitmap getBitmapFromSource(ReadableMap source) throws Exception { - String uriString = source.getString("uri"); - - if(uriString.startsWith("data")) { - final String pureBase64Encoded = uriString.substring(uriString.indexOf(",") + 1); - byte[] decodedString = Base64.decode(pureBase64Encoded, Base64.DEFAULT); - Bitmap image = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length); - - return image; - } - - if(uriString.startsWith("http") || uriString.startsWith("https")) { - URL url = new URL(uriString); - Bitmap image = BitmapFactory.decodeStream(url.openConnection().getInputStream()); - return image; - } - - if(uriString.startsWith("file")) { - BitmapFactory.Options options = new BitmapFactory.Options(); - options.inPreferredConfig = Bitmap.Config.ARGB_8888; - Bitmap image = BitmapFactory.decodeFile(uriString, options); - - return image; - } - - int resourceId = context_.getResources().getIdentifier(uriString, "drawable", context_.getPackageName()); - Bitmap image = BitmapFactory.decodeResource(context_.getResources(), resourceId); - - return image; - } - - private void printData(final ReadableMap paramsMap, final String target) throws Epos2Exception { - int timeout = Printer.PARAM_DEFAULT; - if(paramsMap != null && paramsMap.hasKey("timeout")) { - timeout = paramsMap.getInt("timeout"); - } - Printer printer = thePrinterManager_.getObject(target).getEpos2Printer(); - printer.sendData(timeout); - } - -} diff --git a/android/src/main/java/com/reactnativeescposprinter/ThePrinterWrapperDelegate.java b/android/src/main/java/com/reactnativeescposprinter/ThePrinterWrapperDelegate.java deleted file mode 100644 index 2d76e28..0000000 --- a/android/src/main/java/com/reactnativeescposprinter/ThePrinterWrapperDelegate.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.reactnativeescposprinter; - -import androidx.annotation.NonNull; - -import org.json.JSONObject; - -public interface ThePrinterWrapperDelegate { - - void onMemoryError(@NonNull final String objectid, @NonNull final String error); - void onPrinterStatusChange(@NonNull final String objectid, final int status); - void onPrinterStartStatusMonitorResult(@NonNull final String objectid, final boolean hasError, final String error); - void onPrinterStopStatusMonitorResult(@NonNull final String objectid, final boolean hasError, final String error); - void onGetPrinterSetting(@NonNull final String objectid, final int code, final int type, final int value); - void onPtrReceive(@NonNull final String objectid, final JSONObject data); -} diff --git a/android/src/main/java/com/reactnativeescposprinter/ePOSCmd.java b/android/src/main/java/com/reactnativeescposprinter/ePOSCmd.java deleted file mode 100644 index 2362751..0000000 --- a/android/src/main/java/com/reactnativeescposprinter/ePOSCmd.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.reactnativeescposprinter; - -public class ePOSCmd { - - public final static int POS_SUCCESS = 0; - -} \ No newline at end of file diff --git a/docs/API.md b/docs/API.md index 94b29c0..7fc0a3b 100644 --- a/docs/API.md +++ b/docs/API.md @@ -1,143 +1,51 @@ # API -1. [discover](./discovery/discovery.md) -2. [init](#init-target-seriesname-language-) -3. [pairingBluetoothPrinter](#pairingbluetoothprinter---ios-only) -4. [getPrinterCharsPerLine](#getprintercharsperlineseriesname) -5. [startMonitorPrinter](#startmonitorprinterinterval-number) -6. [stopMonitorPrinter](#stopmonitorprinter) -7. [instantiate](#instantiate-target-seriesname-language) -8. [printing](./PRINTING.md) -9. [disconnectPrinter](#disconnectprintertarget-string) - -### init({ target, seriesName, language? }) - -Initializes printer using it's target and series name. - -#### arguments - -| Name | Type | Required | Default | Description | -| ------------ | :------: | :------: | :-------------: | :---------------------------------------------------------------------------------------------------------------------------------------------: | -| `target` | `string` | `Yes` | - | The connection target of a device which can be specified by connectAPI: ("TCP:192.168.192.168" "BT:00:22:15:7D:70:9C" "USB:000000000000000000") | -| `seriesName` | `string` | `Yes` | - | Specifies the target printer model. | -| `language` | `string` | `No` | `EPOS2_LANG_EN` | Specifies the language : EPOS2_LANG_EN, EPOS2_LANG_JA, EPOS2_LANG_ZH_CN... | - -```javascript -import EscPosPrinter from 'react-native-esc-pos-printer'; - -EscPosPrinter.init({ - target: 'TCP:192.168.192.168', - seriesName: 'EPOS2_TM_M10', - language: 'EPOS2_LANG_EN', -}) - .then(() => console.log('Init success!')) - .catch((e) => console.log('Init error:', e.message)); -``` - -### pairingBluetoothPrinter() - iOS only - -Shows a list of Bluetooth devices available for pairing and pairs a selected device with the terminal. -Opens native dialog. - -```javascript -import { pairingBluetoothPrinter } from 'react-native-esc-pos-printer'; - -EscPosPrinter.pairingBluetoothPrinter() - .then(() => console.log('pairing success!')) - .catch((e) => console.log('pairing error:', e.message)); -``` - -### getPrinterCharsPerLine(seriesName) - -Returns max characters per line for given printer series (Usefull while building receipt layout). -Supports only `font A` for now. Not recommended to use right before printing since printer could be busy. For better performance use it right after init or add some delay before calling printing task. - -#### arguments - -| Name | Type | Required | Description | -| ------------ | :------: | :------: | :---------------------------------: | -| `seriesName` | `string` | `Yes` | Specifies the target printer model. | - -#### return type - -```typescript -{ - fontA: number; -} -``` - -```javascript -import EscPosPrinter, { - getPrinterSeriesByName, -} from 'react-native-esc-pos-printer'; - -const { name } = printer; - -EscPosPrinter.getPrinterCharsPerLine(getPrinterSeriesByName(name)) - .then((result) => console.log(result)) // { fontA: 48 } - .catch((e) => console.log('error:', e.message)); -``` - -### startMonitorPrinter(interval: number) - -Monitors printer status with a given interval in seconds. - -```javascript -import EscPosPrinter from 'react-native-esc-pos-printer'; - -EscPosPrinter.addPrinterStatusListener((status) => { - console.log(status.connection, status.online, status.paper); // will be executed every 5 sec -}); - -EscPosPrinter.startMonitorPrinter(5) - .then(() => console.log('Start monitor success!')) - .catch((e) => console.log('Start monitor error:', e.message)); -``` - -### stopMonitorPrinter() - -Monitors printer status with a given interval in seconds. - -```javascript -import EscPosPrinter from 'react-native-esc-pos-printer'; - -EscPosPrinter.stopMonitorPrinter() - .then(() => console.log('Stopped!')) - .catch((e) => console.log('Stop error:', e.message)); -``` - -### instantiate({ target, seriesName, language? }) - -Initializes printer using it's target and series name. Using this method you can initialize multiple printers. - -#### arguments - -| Name | Type | Required | Default | Description | -| ------------ | :------: | :------: | :-------------: | :---------------------------------------------------------------------------------------------------------------------------------------------: | -| `target` | `string` | `Yes` | - | The connection target of a device which can be specified by connectAPI: ("TCP:192.168.192.168" "BT:00:22:15:7D:70:9C" "USB:000000000000000000") | -| `seriesName` | `string` | `Yes` | - | Specifies the target printer model. | -| `language` | `string` | `No` | `EPOS2_LANG_EN` | Specifies the language : EPOS2_LANG_EN, EPOS2_LANG_JA, EPOS2_LANG_ZH_CN... | - -```javascript -import EscPosPrinter from 'react-native-esc-pos-printer'; - -EscPosPrinter.instantiate({ - target: 'TCP:192.168.192.168', - seriesName: 'EPOS2_TM_M10', - language: 'EPOS2_LANG_EN', -}) - .then(() => console.log('Init success!')) - .catch((e) => console.log('Init error:', e.message)); -``` - -### disconnectPrinter(target: string) - -Use this method to disconnect and delete the printer object initialized using [instantiate](#instantiate-target-seriesname-language) method. You need to call this function when the printer is no longer needed, but note that after calling this method you would need to re-instantiate the printer again before sending print jobs. - -```javascript -import EscPosPrinter from 'react-native-esc-pos-printer'; - -EscPosPrinter.disconnectPrinter() - .then(() => console.log('Disconnect success')) - .catch((e) => console.log('Disconnect error', e.message)); +1. [discovery](./discovery/discovery.md) +2. [Printer](./printer/Printer.md) + +## Example + +```jsx + import { usePrintersDiscovery, Printer } from 'react-native-esc-pos-printer'; + + ... + + const { start, isDiscovering, printers } = + usePrintersDiscovery(); + + const print = () => { + printersData.forEach(printersData => { + const printerInstance = new Printer({ + target: printersData.target, + deviceName: printersData.deviceName, + }); + + const res = await printerInstance.addQueueTask(async () => { + await Printer.tryToConnectUntil( + printerInstance, + (status) => status.online.statusCode === PrinterConstants.TRUE + ); + await printerInstance.addText('DUDE!'); + await printerInstance.addFeedLine(); + await printerInstance.addCut(); + const result = await printerInstance.sendData(); + await printerInstance.disconnect(); + return result; + }) + }) + } + + return ( + ... +