diff --git a/README.md b/README.md new file mode 100644 index 00000000..0a178c62 --- /dev/null +++ b/README.md @@ -0,0 +1,21 @@ +# react-native-star-io10 + +`react-native-star-io10` is a library for supporting application development for Star Micronics devices. + +This library is included in StarXpand SDK. + +## Requirements + +| Platform | Version | +| --- | --- | +| iOS | iOS 12.0 or later | +| Android | Android 6.0 or later | +| Windows | Windows 10 1709 (Fa​​ll Creators Update) or later | + +## Examples + +- [`example` project is located in this directory.](https://github.com/star-micronics/react-native-star-io10/tree/master/example) + +## Copyright + +Copyright 2020 Star Micronics Co., Ltd. All rights reserved. diff --git a/android/README.md b/android/README.md new file mode 100644 index 00000000..ac2fbda3 --- /dev/null +++ b/android/README.md @@ -0,0 +1,14 @@ +README +====== + +If you want to publish the lib as a maven dependency, follow these steps before publishing a new version to npm: + +1. Be sure to have the Android [SDK](https://developer.android.com/studio/index.html) and [NDK](https://developer.android.com/ndk/guides/index.html) installed +2. Be sure to have a `local.properties` file in this folder that points to the Android SDK and NDK +``` +ndk.dir=/Users/{username}/Library/Android/sdk/ndk-bundle +sdk.dir=/Users/{username}/Library/Android/sdk +``` +3. Delete the `maven` folder +4. Run `./gradlew installArchives` +5. Verify that latest set of generated files is in the maven folder with the correct version number diff --git a/android/build.gradle b/android/build.gradle new file mode 100644 index 00000000..e6867db2 --- /dev/null +++ b/android/build.gradle @@ -0,0 +1,133 @@ +buildscript { + // Buildscript is evaluated before everything else so we can't use getExtOrDefault + def kotlin_version = rootProject.ext.has('kotlinVersion') ? rootProject.ext.get('kotlinVersion') : project.properties['StarIO10Module_kotlinVersion'] + + repositories { + google() + jcenter()} + + dependencies { + classpath 'com.android.tools.build:gradle:4.0.1' + // noinspection DifferentKotlinGradleVersion + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" + } +} + +apply plugin: 'com.android.library' +apply plugin: 'kotlin-android' + +def getExtOrDefault(name) { + return rootProject.ext.has(name) ? rootProject.ext.get(name) : project.properties['StarIO10Module_' + name] +} + +def getExtOrIntegerDefault(name) { + return rootProject.ext.has(name) ? rootProject.ext.get(name) : (project.properties['StarIO10Module_' + name]).toInteger() +} + +android { + compileSdkVersion getExtOrIntegerDefault('compileSdkVersion') + buildToolsVersion getExtOrDefault('buildToolsVersion') + defaultConfig { + minSdkVersion 23 + targetSdkVersion getExtOrIntegerDefault('targetSdkVersion') + versionCode 1 + versionName "0.1.0" + + } + + buildTypes { + release { + minifyEnabled false + } + } + lintOptions { + disable 'GradleCompatible' + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + } +} + +repositories { + mavenCentral() + jcenter() + google() + + def found = false + def defaultDir = null + def androidSourcesName = 'React Native sources' + + if (rootProject.ext.has('reactNativeAndroidRoot')) { + defaultDir = rootProject.ext.get('reactNativeAndroidRoot') + } else { + defaultDir = new File( + projectDir, + '/../../../node_modules/react-native/android' + ) + } + + if (defaultDir.exists()) { + maven { + url defaultDir.toString() + name androidSourcesName + } + + logger.info(":${project.name}:reactNativeAndroidRoot ${defaultDir.canonicalPath}") + found = true + } else { + def parentDir = rootProject.projectDir + + 1.upto(5, { + if (found) return true + parentDir = parentDir.parentFile + + def androidSourcesDir = new File( + parentDir, + 'node_modules/react-native' + ) + + def androidPrebuiltBinaryDir = new File( + parentDir, + 'node_modules/react-native/android' + ) + + if (androidPrebuiltBinaryDir.exists()) { + maven { + url androidPrebuiltBinaryDir.toString() + name androidSourcesName + } + + logger.info(":${project.name}:reactNativeAndroidRoot ${androidPrebuiltBinaryDir.canonicalPath}") + found = true + } else if (androidSourcesDir.exists()) { + maven { + url androidSourcesDir.toString() + name androidSourcesName + } + + logger.info(":${project.name}:reactNativeAndroidRoot ${androidSourcesDir.canonicalPath}") + found = true + } + }) + } + + if (!found) { + throw new GradleException( + "${project.name}: unable to locate React Native android sources. " + + "Ensure you have you installed React Native as a dependency in your project and try again." + ) + } +} + +def kotlin_version = getExtOrDefault('kotlinVersion') + +dependencies { + // noinspection GradleDynamicVersion + api 'com.facebook.react:react-native:+' + implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" + implementation files('src/lib/stario10.aar') + def coroutines_version = '1.3.7' //Kotlin coroutines用ライブラリ(async, await)のバージョン + implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutines_version" //Kotlin coroutines用ライブラリ(async, await) + implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:$coroutines_version" +} diff --git a/android/gradle.properties b/android/gradle.properties new file mode 100644 index 00000000..e2082ddb --- /dev/null +++ b/android/gradle.properties @@ -0,0 +1,26 @@ +StarIO10Module_kotlinVersion=1.4.10 +StarIO10Module_compileSdkVersion=30 +StarIO10Module_buildToolsVersion=30.0.2 +StarIO10Module_targetSdkVersion=30 + +# Project-wide Gradle settings. +# IDE (e.g. Android Studio) users: +# Gradle settings configured through the IDE *will override* +# any settings specified in this file. +# For more details on how to configure your build environment visit +# http://www.gradle.org/docs/current/userguide/build_environment.html +# Specifies the JVM arguments used for the daemon process. +# The setting is particularly useful for tweaking memory settings. +org.gradle.jvmargs=-Xmx1536m +# When configured, Gradle will run in incubating parallel mode. +# This option should only be used with decoupled projects. More details, visit +# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects +# org.gradle.parallel=true +# AndroidX package structure to make it clearer which packages are bundled with the +# Android operating system, and which are packaged with your app's APK +# https://developer.android.com/topic/libraries/support-library/androidx-rn +android.useAndroidX=true +# Automatically convert third-party libraries to use AndroidX +android.enableJetifier=true +# Kotlin code style for this project: "official" or "obsolete": +kotlin.code.style=official diff --git a/android/gradle/wrapper/gradle-wrapper.jar b/android/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000..f6b961fd Binary files /dev/null and b/android/gradle/wrapper/gradle-wrapper.jar differ diff --git a/android/gradle/wrapper/gradle-wrapper.properties b/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000..5d059e13 --- /dev/null +++ b/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Mon Sep 14 09:06:54 JST 2020 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-6.3-all.zip diff --git a/android/gradlew b/android/gradlew new file mode 100644 index 00000000..cccdd3d5 --- /dev/null +++ b/android/gradlew @@ -0,0 +1,172 @@ +#!/usr/bin/env sh + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=$(save "$@") + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong +if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then + cd "$(dirname "$0")" +fi + +exec "$JAVACMD" "$@" diff --git a/android/gradlew.bat b/android/gradlew.bat new file mode 100644 index 00000000..f9553162 --- /dev/null +++ b/android/gradlew.bat @@ -0,0 +1,84 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/android/src/lib/stario10.aar b/android/src/lib/stario10.aar new file mode 100644 index 00000000..975d2393 Binary files /dev/null and b/android/src/lib/stario10.aar differ diff --git a/android/src/main/AndroidManifest.xml b/android/src/main/AndroidManifest.xml new file mode 100644 index 00000000..78edf63a --- /dev/null +++ b/android/src/main/AndroidManifest.xml @@ -0,0 +1,4 @@ + + + diff --git a/android/src/main/java/com/stario10module/BezelSettingBuilderWrapper.kt b/android/src/main/java/com/stario10module/BezelSettingBuilderWrapper.kt new file mode 100644 index 00000000..bbf3f755 --- /dev/null +++ b/android/src/main/java/com/stario10module/BezelSettingBuilderWrapper.kt @@ -0,0 +1,52 @@ +package com.stario10module + +import com.facebook.react.bridge.* +import com.starmicronics.stario10.starxpandcommand.BezelSettingBuilder +import com.starmicronics.stario10.starxpandcommand.LedSettingBuilder + +class BezelSettingBuilderWrapper internal constructor(context: ReactApplicationContext) : ReactContextBaseJavaModule(context) { + override fun getName(): String { + return "BezelSettingBuilderWrapper" + } + + @ReactMethod + fun init(promise: Promise) { + val builder = BezelSettingBuilder() + val identifier = InstanceManager.set(builder) + + promise.resolve(identifier) + } + + @ReactMethod + fun dispose(identifier: String, promise: Promise) { + InstanceManager.remove(identifier) + promise.resolve(0) + } + + @ReactMethod + fun settingAutomaticPageLength(identifier: String, enabled: Boolean, promise: Promise) { + val builder = InstanceManager.get(identifier) + + if (builder is BezelSettingBuilder) { + builder.settingAutomaticPageLength(enabled) + promise.resolve(0) + } + else { + promise.reject(ReactNoCrashSoftException("Not found native instance")) + } + } + + @ReactMethod + fun addLed(identifier: String, ledSettingBuilderIdentifier: String, promise: Promise) { + val builder = InstanceManager.get(identifier) + val ledSettingBuilder = InstanceManager.get(ledSettingBuilderIdentifier) + + if (builder is BezelSettingBuilder && ledSettingBuilder is LedSettingBuilder) { + builder.addLed(ledSettingBuilder) + promise.resolve(0) + } + else { + promise.reject(ReactNoCrashSoftException("Not found native instance")) + } + } +} diff --git a/android/src/main/java/com/stario10module/BuzzerBuilderWrapper.kt b/android/src/main/java/com/stario10module/BuzzerBuilderWrapper.kt new file mode 100644 index 00000000..d0c91743 --- /dev/null +++ b/android/src/main/java/com/stario10module/BuzzerBuilderWrapper.kt @@ -0,0 +1,39 @@ +package com.stario10module + +import com.facebook.react.bridge.* +import com.starmicronics.stario10.starxpandcommand.BuzzerBuilder + +class BuzzerBuilderWrapper internal constructor(context: ReactApplicationContext) : ReactContextBaseJavaModule(context) { + override fun getName(): String { + return "BuzzerBuilderWrapper" + } + + @ReactMethod + fun init(promise: Promise) { + val builder = BuzzerBuilder() + val identifier = InstanceManager.set(builder) + + promise.resolve(identifier) + } + + @ReactMethod + fun dispose(identifier: String, promise: Promise) { + InstanceManager.remove(identifier) + promise.resolve(0) + } + + @ReactMethod + fun actionDrive(identifier: String, channel: String, repeat: Int, onTime: Int, offTime: Int, promise: Promise) { + val builder = InstanceManager.get(identifier) + + if (builder is BuzzerBuilder) { + val parameter = StarIO10ValueConverter.toBuzzerDriveParameter(channel, repeat, onTime, offTime) + + builder.actionDrive(parameter) + promise.resolve(0) + } + else { + promise.reject(ReactNoCrashSoftException("Not found native instance")) + } + } +} \ No newline at end of file diff --git a/android/src/main/java/com/stario10module/DocumentBuilderWrapper.kt b/android/src/main/java/com/stario10module/DocumentBuilderWrapper.kt new file mode 100644 index 00000000..a7a9b168 --- /dev/null +++ b/android/src/main/java/com/stario10module/DocumentBuilderWrapper.kt @@ -0,0 +1,164 @@ +package com.stario10module + +import com.facebook.react.bridge.* +import com.starmicronics.stario10.starxpandcommand.* + +class DocumentBuilderWrapper internal constructor(context: ReactApplicationContext) : ReactContextBaseJavaModule(context) { + override fun getName(): String { + return "DocumentBuilderWrapper" + } + + @ReactMethod + fun init(promise: Promise) { + val builder = DocumentBuilder() + val identifier = InstanceManager.set(builder) + + promise.resolve(identifier) + } + + @ReactMethod + fun dispose(identifier: String, promise: Promise) { + InstanceManager.remove(identifier) + promise.resolve(0) + } + + @ReactMethod + fun settingTopMargin(identifier: String, height: Double, promise: Promise) { + val builder = InstanceManager.get(identifier) + + if (builder is DocumentBuilder) { + builder.settingTopMargin(height) + promise.resolve(0) + } + else { + promise.reject(ReactNoCrashSoftException("Not found native instance")) + } + } + + @ReactMethod + fun settingBlackMark(identifier: String, start: Boolean, end: Boolean, position: String, promise: Promise) { + val builder = InstanceManager.get(identifier) + + if (builder is DocumentBuilder) { + val parameter = StarIO10ValueConverter.toPrinterBlackMarkParameter(start, end, position) + + builder.settingBlackMark(parameter) + promise.resolve(0) + } + else { + promise.reject(ReactNoCrashSoftException("Not found native instance")) + } + } + + @ReactMethod + fun settingLabel(identifier: String, start: Boolean, end: Boolean, promise: Promise) { + val builder = InstanceManager.get(identifier) + + if (builder is DocumentBuilder) { + val parameter = StarIO10ValueConverter.toPrinterLabelParameter(start, end) + + builder.settingLabel(parameter) + promise.resolve(0) + } + else { + promise.reject(ReactNoCrashSoftException("Not found native instance")) + } + } + + @ReactMethod + fun settingHoldPrint(identifier: String, enable: Boolean, promise: Promise) { + val builder = InstanceManager.get(identifier) + + if (builder is DocumentBuilder) { + val parameter = StarIO10ValueConverter.toPrinterHoldPrintParameter(enable) + + builder.settingHoldPrint(parameter) + promise.resolve(0) + } + else { + promise.reject(ReactNoCrashSoftException("Not found native instance")) + } + } + + @ReactMethod + fun settingPrintableArea(identifier: String, width: Double, promise: Promise) { + val builder = InstanceManager.get(identifier) + + if (builder is DocumentBuilder) { + builder.settingPrintableArea(width) + promise.resolve(0) + } + else { + promise.reject(ReactNoCrashSoftException("Not found native instance")) + } + } + + @ReactMethod + fun addPrinter(identifier: String, printerIdentifier: String, promise: Promise) { + val documentBuilder = InstanceManager.get(identifier) + val printerBuilder = InstanceManager.get(printerIdentifier) + + if (documentBuilder is DocumentBuilder && printerBuilder is PrinterBuilder) { + documentBuilder.addPrinter(printerBuilder) + promise.resolve(true) + } + else { + promise.reject(ReactNoCrashSoftException("Not found native instance")) + } + } + + @ReactMethod + fun addDrawer(identifier: String, drawerIdentifier: String, promise: Promise) { + val documentBuilder = InstanceManager.get(identifier) + val drawerBuilder = InstanceManager.get(drawerIdentifier) + + if (documentBuilder is DocumentBuilder && drawerBuilder is DrawerBuilder) { + documentBuilder.addDrawer(drawerBuilder) + promise.resolve(true) + } + else { + promise.reject(ReactNoCrashSoftException("Not found native instance")) + } + } + + @ReactMethod + fun addBuzzer(identifier: String, buzzerIdentifier: String, promise: Promise) { + val documentBuilder = InstanceManager.get(identifier) + val buzzerBuilder = InstanceManager.get(buzzerIdentifier) + + if (documentBuilder is DocumentBuilder && buzzerBuilder is BuzzerBuilder) { + documentBuilder.addBuzzer(buzzerBuilder) + promise.resolve(true) + } + else { + promise.reject(ReactNoCrashSoftException("Not found native instance")) + } + } + + @ReactMethod + fun addMelodySpeaker(identifier: String, melodySpeakerIdentifier: String, promise: Promise) { + val documentBuilder = InstanceManager.get(identifier) + val melodySpeakerBuilder = InstanceManager.get(melodySpeakerIdentifier) + + if (documentBuilder is DocumentBuilder && melodySpeakerBuilder is MelodySpeakerBuilder) { + documentBuilder.addMelodySpeaker(melodySpeakerBuilder) + promise.resolve(true) + } + else { + promise.reject(ReactNoCrashSoftException("Not found native instance")) + } + } + + @ReactMethod + fun addRaw(identifier: String, content: ReadableArray, promise: Promise) { + val builder = InstanceManager.get(identifier) + + if (builder is DocumentBuilder) { + builder.addRaw(StarIO10ValueConverter.toList(content)) + promise.resolve(0) + } + else { + promise.reject(ReactNoCrashSoftException("Not found native instance")) + } + } +} diff --git a/android/src/main/java/com/stario10module/DrawerBuilderWrapper.kt b/android/src/main/java/com/stario10module/DrawerBuilderWrapper.kt new file mode 100644 index 00000000..53399bbe --- /dev/null +++ b/android/src/main/java/com/stario10module/DrawerBuilderWrapper.kt @@ -0,0 +1,39 @@ +package com.stario10module + +import com.facebook.react.bridge.* +import com.starmicronics.stario10.starxpandcommand.DrawerBuilder + +class DrawerBuilderWrapper internal constructor(context: ReactApplicationContext) : ReactContextBaseJavaModule(context) { + override fun getName(): String { + return "DrawerBuilderWrapper" + } + + @ReactMethod + fun init(promise: Promise) { + val builder = DrawerBuilder() + val identifier = InstanceManager.set(builder) + + promise.resolve(identifier) + } + + @ReactMethod + fun dispose(identifier: String, promise: Promise) { + InstanceManager.remove(identifier) + promise.resolve(0) + } + + @ReactMethod + fun actionOpen(identifier: String, channel: String, onTime: Int, promise: Promise) { + val builder = InstanceManager.get(identifier) + + if (builder is DrawerBuilder) { + val parameter = StarIO10ValueConverter.toDrawerOpenParameter(channel, onTime) + + builder.actionOpen(parameter) + promise.resolve(0) + } + else { + promise.reject(ReactNoCrashSoftException("Not found native instance")) + } + } +} \ No newline at end of file diff --git a/android/src/main/java/com/stario10module/EventParameter.kt b/android/src/main/java/com/stario10module/EventParameter.kt new file mode 100644 index 00000000..86826a5d --- /dev/null +++ b/android/src/main/java/com/stario10module/EventParameter.kt @@ -0,0 +1,34 @@ +package com.stario10module + +class EventParameter { + companion object { + const val KEY_IDENTIFIER = "identifier" + const val KEY_ERROR_IDENTIFIER = "errorIdentifier" + const val KEY_DRAWER_OPEN_CLOSE_SIGNAL_STATE = "openCloseSignal" + const val KEY_INPUT_DEVICE_DATA = "data" + const val KEY_INTERFACE_TYPE = "interfaceType" + const val KEY_MODEL = "model" + const val KEY_EMULATION = "emulation" + const val KEY_CONNECTION_IDENTIFIER = "connectionIdentifier" + + const val NAME_PRINTER_DELEGATE_READY = "PrinterReady" + const val NAME_PRINTER_DELEGATE_ERROR = "PrinterError" + const val NAME_PRINTER_DELEGATE_PAPER_READY = "PrinterPaperReady" + const val NAME_PRINTER_DELEGATE_PAPER_NEAR_EMPTY = "PrinterPaperNearEmpty" + const val NAME_PRINTER_DELEGATE_PAPER_EMPTY = "PrinterPaperEmpty" + const val NAME_PRINTER_DELEGATE_COVER_OPENED = "PrinterCoverOpened" + const val NAME_PRINTER_DELEGATE_COVER_CLOSED = "PrinterCoverClosed" + const val NAME_PRINTER_DELEGATE_COMMUNICATION_ERROR = "PrinterCommunicationError" + const val NAME_DRAWER_DELEGATE_OPEN_CLOSE_SIGNAL_SWITCHED = "DrawerOpenCloseSignalSwitched" + const val NAME_DRAWER_DELEGATE_COMMUNICATION_ERROR = "DrawerCommunicationError" + const val NAME_INPUT_DEVICE_DELEGATE_CONNECTED = "InputDeviceConnected" + const val NAME_INPUT_DEVICE_DELEGATE_DISCONNECTED = "InputDeviceDisconnected" + const val NAME_INPUT_DEVICE_DELEGATE_DATA_RECEIVED = "InputDeviceDataReceived" + const val NAME_INPUT_DEVICE_DELEGATE_COMMUNICATION_ERROR = "InputDeviceCommunicationError" + const val NAME_DISPLAY_DELEGATE_CONNECTED = "DisplayConnected" + const val NAME_DISPLAY_DELEGATE_DISCONNECTED = "DisplayDisconnected" + const val NAME_DISPLAY_DELEGATE_COMMUNICATION_ERROR = "DisplayCommunicationError" + const val NAME_PRINTER_FOUND = "PrinterFound" + const val NAME_DISCOVERY_FINISHED = "DiscoveryFinished" + } +} \ No newline at end of file diff --git a/android/src/main/java/com/stario10module/InstanceManager.kt b/android/src/main/java/com/stario10module/InstanceManager.kt new file mode 100644 index 00000000..0a95fd66 --- /dev/null +++ b/android/src/main/java/com/stario10module/InstanceManager.kt @@ -0,0 +1,36 @@ +package com.stario10module + +import java.util.UUID +import java.util.concurrent.ConcurrentHashMap + + +class InstanceManager { + companion object { + private var instanceMap: ConcurrentHashMap = ConcurrentHashMap() + + fun set(instance: Any): String { + var identifier: String + + while (true) { + identifier = UUID.randomUUID().toString() + + if(this.instanceMap.putIfAbsent(identifier, instance) == null) { + break + } + + Thread.sleep(10) + } + + return identifier + } + + fun get(identifier: String): Any? { + return this.instanceMap[identifier] + } + + fun remove(identifier: String) { + this.instanceMap.remove(identifier) + } + } + +} \ No newline at end of file diff --git a/android/src/main/java/com/stario10module/LedSettingBuilderWrapper.kt b/android/src/main/java/com/stario10module/LedSettingBuilderWrapper.kt new file mode 100644 index 00000000..d8312150 --- /dev/null +++ b/android/src/main/java/com/stario10module/LedSettingBuilderWrapper.kt @@ -0,0 +1,39 @@ +package com.stario10module + +import com.facebook.react.bridge.* +import com.starmicronics.stario10.starxpandcommand.LedSettingBuilder + +class LedSettingBuilderWrapper internal constructor(context: ReactApplicationContext) : ReactContextBaseJavaModule(context) { + override fun getName(): String { + return "LedSettingBuilderWrapper" + } + + @ReactMethod + fun init(promise: Promise) { + val builder = LedSettingBuilder() + val identifier = InstanceManager.set(builder) + + promise.resolve(identifier) + } + + @ReactMethod + fun dispose(identifier: String, promise: Promise) { + InstanceManager.remove(identifier) + promise.resolve(0) + } + + @ReactMethod + fun settingAutomaticBlink(identifier: String, type: String, onTime: Int, offTime: Int, promise: Promise) { + val builder = InstanceManager.get(identifier) + + if (builder is LedSettingBuilder) { + val parameter = StarIO10ValueConverter.toLedAutomaticBlinkParameter(type, onTime, offTime) + + builder.settingAutomaticBlink(parameter) + promise.resolve(0) + } + else { + promise.reject(ReactNoCrashSoftException("Not found native instance")) + } + } +} \ No newline at end of file diff --git a/android/src/main/java/com/stario10module/MelodySpeakerBuilderWrapper.kt b/android/src/main/java/com/stario10module/MelodySpeakerBuilderWrapper.kt new file mode 100644 index 00000000..0c2595e4 --- /dev/null +++ b/android/src/main/java/com/stario10module/MelodySpeakerBuilderWrapper.kt @@ -0,0 +1,54 @@ +package com.stario10module + +import com.facebook.react.bridge.* +import com.starmicronics.stario10.starxpandcommand.MelodySpeakerBuilder + +class MelodySpeakerBuilderWrapper internal constructor(context: ReactApplicationContext) : ReactContextBaseJavaModule(context) { + override fun getName(): String { + return "MelodySpeakerBuilderWrapper" + } + + @ReactMethod + fun init(promise: Promise) { + val builder = MelodySpeakerBuilder() + val identifier = InstanceManager.set(builder) + + promise.resolve(identifier) + } + + @ReactMethod + fun dispose(identifier: String, promise: Promise) { + InstanceManager.remove(identifier) + promise.resolve(0) + } + + @ReactMethod + fun actionDriveRegisteredSound(identifier: String, area: String, number: Int, volume: Int, promise: Promise) { + val builder = InstanceManager.get(identifier) + + if (builder is MelodySpeakerBuilder) { + val parameter = StarIO10ValueConverter.toMelodySpeakerDriveRegisteredSoundParameter(area, number, volume) + + builder.actionDriveRegisteredSound(parameter) + promise.resolve(0) + } + else { + promise.reject(ReactNoCrashSoftException("Not found native instance")) + } + } + + @ReactMethod + fun actionDriveOneTimeSound(identifier: String, source: ReadableArray, volume: Int, promise: Promise) { + val builder = InstanceManager.get(identifier) + + if (builder is MelodySpeakerBuilder) { + val parameter = StarIO10ValueConverter.toMelodySpeakerDriveOneTimeSoundParameter(source, volume) + + builder.actionDriveOneTimeSound(parameter) + promise.resolve(0) + } + else { + promise.reject(ReactNoCrashSoftException("Not found native instance")) + } + } +} \ No newline at end of file diff --git a/android/src/main/java/com/stario10module/PageModeBuilderWrapper.kt b/android/src/main/java/com/stario10module/PageModeBuilderWrapper.kt new file mode 100644 index 00000000..9931dfb7 --- /dev/null +++ b/android/src/main/java/com/stario10module/PageModeBuilderWrapper.kt @@ -0,0 +1,320 @@ +package com.stario10module + +import com.facebook.react.bridge.* +import com.starmicronics.stario10.StarIO10ArgumentException +import com.starmicronics.stario10.starxpandcommand.PageModeBuilder +import com.starmicronics.stario10.starxpandcommand.printer.CjkCharacterType + +class PageModeBuilderWrapper internal constructor(context: ReactApplicationContext) : ReactContextBaseJavaModule(context) { + override fun getName(): String { + return "PageModeBuilderWrapper" + } + + @ReactMethod + fun init(promise: Promise) { + val builder = PageModeBuilder() + val identifier = InstanceManager.set(builder) + + promise.resolve(identifier) + } + + @ReactMethod + fun dispose(identifier: String, promise: Promise) { + InstanceManager.remove(identifier) + promise.resolve(0) + } + + @ReactMethod + fun settingVerticalPositionTo(identifier: String, position: Double, promise: Promise) { + val builder = InstanceManager.get(identifier) + + if (builder is PageModeBuilder) { + builder.settingVerticalPositionTo(position) + promise.resolve(0) + } + else { + promise.reject(ReactNoCrashSoftException("Not found native instance")) + } + } + + @ReactMethod + fun settingVerticalPositionBy(identifier: String, position: Double, promise: Promise) { + val builder = InstanceManager.get(identifier) + + if (builder is PageModeBuilder) { + builder.settingVerticalPositionBy(position) + promise.resolve(0) + } + else { + promise.reject(ReactNoCrashSoftException("Not found native instance")) + } + } + + @ReactMethod + fun styleFont(identifier: String, type: String, promise: Promise) { + val builder = InstanceManager.get(identifier) + + if (builder is PageModeBuilder) { + builder.styleFont(StarIO10ValueConverter.toPrinterFontType(type)) + promise.resolve(0) + } + else { + promise.reject(ReactNoCrashSoftException("Not found native instance")) + } + } + + @ReactMethod + fun styleBold(identifier: String, enable: Boolean, promise: Promise) { + val builder = InstanceManager.get(identifier) + + if (builder is PageModeBuilder) { + builder.styleBold(enable) + promise.resolve(0) + } + else { + promise.reject(ReactNoCrashSoftException("Not found native instance")) + } + } + + @ReactMethod + fun styleInvert(identifier: String, enable: Boolean, promise: Promise) { + val builder = InstanceManager.get(identifier) + + if (builder is PageModeBuilder) { + builder.styleInvert(enable) + promise.resolve(0) + } + else { + promise.reject(ReactNoCrashSoftException("Not found native instance")) + } + } + + @ReactMethod + fun styleUnderLine(identifier: String, enable: Boolean, promise: Promise) { + val builder = InstanceManager.get(identifier) + + if (builder is PageModeBuilder) { + builder.styleUnderLine(enable) + promise.resolve(0) + } + else { + promise.reject(ReactNoCrashSoftException("Not found native instance")) + } + } + + @ReactMethod + fun styleMagnification(identifier: String, width: Int, height: Int, promise: Promise) { + val builder = InstanceManager.get(identifier) + + if (builder is PageModeBuilder) { + builder.styleMagnification(StarIO10ValueConverter.toMagnificationParameter(width, height)) + promise.resolve(0) + } + else { + promise.reject(ReactNoCrashSoftException("Not found native instance")) + } + } + + @ReactMethod + fun styleCharacterSpace(identifier: String, width: Double, promise: Promise) { + val builder = InstanceManager.get(identifier) + + if (builder is PageModeBuilder) { + builder.styleCharacterSpace(width) + promise.resolve(0) + } + else { + promise.reject(ReactNoCrashSoftException("Not found native instance")) + } + } + + @ReactMethod + fun styleLineSpace(identifier: String, height: Double, promise: Promise) { + val builder = InstanceManager.get(identifier) + + if (builder is PageModeBuilder) { + builder.styleLineSpace(height) + promise.resolve(0) + } + else { + promise.reject(ReactNoCrashSoftException("Not found native instance")) + } + } + + @ReactMethod + fun styleHorizontalPositionTo(identifier: String, position: Double, promise: Promise) { + val builder = InstanceManager.get(identifier) + + if (builder is PageModeBuilder) { + builder.styleHorizontalPositionTo(position) + promise.resolve(0) + } + else { + promise.reject(ReactNoCrashSoftException("Not found native instance")) + } + } + + @ReactMethod + fun styleHorizontalPositionBy(identifier: String, position: Double, promise: Promise) { + val builder = InstanceManager.get(identifier) + + if (builder is PageModeBuilder) { + builder.styleHorizontalPositionBy(position) + promise.resolve(0) + } + else { + promise.reject(ReactNoCrashSoftException("Not found native instance")) + } + } + + @ReactMethod + fun styleHorizontalTabPositions(identifier: String, positions: ReadableArray, promise: Promise) { + val builder = InstanceManager.get(identifier) + + if (builder is PageModeBuilder) { + builder.styleHorizontalTabPositions(StarIO10ValueConverter.toList(positions)) + promise.resolve(0) + } + else { + promise.reject(ReactNoCrashSoftException("Not found native instance")) + } + } + + @ReactMethod + fun styleInternationalCharacter(identifier: String, type: String, promise: Promise) { + val builder = InstanceManager.get(identifier) + + if (builder is PageModeBuilder) { + builder.styleInternationalCharacter(StarIO10ValueConverter.toPrinterInternationalType(type)) + promise.resolve(0) + } + else { + promise.reject(ReactNoCrashSoftException("Not found native instance")) + } + } + + @ReactMethod + fun styleSecondPriorityCharacterEncoding(identifier: String, type: String, promise: Promise) { + val builder = InstanceManager.get(identifier) + + if (builder is PageModeBuilder) { + builder.styleSecondPriorityCharacterEncoding(StarIO10ValueConverter.toPrinterCharacterEncodingType(type)) + promise.resolve(0) + } + else { + promise.reject(ReactNoCrashSoftException("Not found native instance")) + } + } + + @ReactMethod + fun styleCjkCharacterPriority(identifier: String, types: ReadableArray, promise: Promise) { + val builder = InstanceManager.get(identifier) + + if (builder is PageModeBuilder) { + val typeList = mutableListOf() + + for(type in StarIO10ValueConverter.toList(types)) { + typeList.add(StarIO10ValueConverter.toPrinterCjkCharacterType(type)) + } + + builder.styleCjkCharacterPriority(typeList) + promise.resolve(0) + } + else { + promise.reject(ReactNoCrashSoftException("Not found native instance")) + } + } + + @ReactMethod + fun actionPrintText(identifier: String, content: String, promise: Promise) { + val builder = InstanceManager.get(identifier) + + if (builder is PageModeBuilder) { + builder.actionPrintText(content) + promise.resolve(0) + } + else { + promise.reject(ReactNoCrashSoftException("Not found native instance")) + } + } + + @ReactMethod + fun actionPrintBarcode(identifier: String, content: String, symbology: String, printHri: Boolean, barDots: Int, barRatioLevel: String, height: Double, promise: Promise) { + val builder = InstanceManager.get(identifier) + + if (builder is PageModeBuilder) { + val parameter = StarIO10ValueConverter.toPrinterBarcodeParameter(content, symbology, printHri, barDots, barRatioLevel, height) + + builder.actionPrintBarcode(parameter) + promise.resolve(0) + } + else { + promise.reject(ReactNoCrashSoftException("Not found native instance")) + } + } + + @ReactMethod + fun actionPrintPdf417(identifier: String, content: String, column: Int, line: Int, module: Int, aspect: Int, level: String, promise: Promise) { + val builder = InstanceManager.get(identifier) + + if (builder is PageModeBuilder) { + val parameter = StarIO10ValueConverter.toPrinterPdf417Parameter(content, column, line, module, aspect, level) + + builder.actionPrintPdf417(parameter) + promise.resolve(0) + } + else { + promise.reject(ReactNoCrashSoftException("Not found native instance")) + } + } + + @ReactMethod + fun actionPrintQRCode(identifier: String, content: String, model: String, level: String, cellSize: Int, promise: Promise) { + val builder = InstanceManager.get(identifier) + + if (builder is PageModeBuilder) { + val parameter = StarIO10ValueConverter.toPrinterQRCodeParameter(content, model, level, cellSize) + + builder.actionPrintQRCode(parameter) + promise.resolve(0) + } + else { + promise.reject(ReactNoCrashSoftException("Not found native instance")) + } + } + + @ReactMethod + fun actionPrintImage(identifier: String, source: String, width: Int, effectDiffusion: Boolean, threshold: Int, promise: Promise) { + val builder = InstanceManager.get(identifier) + + if (builder is PageModeBuilder) { + try { + val parameter = StarIO10ValueConverter.toPrinterImageParameter(source, width, effectDiffusion, threshold) + builder.actionPrintImage(parameter) + promise.resolve(0) + } + catch (e: Exception) { + val exception = StarIO10ArgumentException("Invalid source.") + val exceptionIdentifier = InstanceManager.set(exception) + promise.reject(exceptionIdentifier, exception) + } + } + else { + promise.reject(ReactNoCrashSoftException("Not found native instance")) + } + } + + @ReactMethod + fun add(identifier: String, pageModeBuilderIdentifier: String, promise: Promise) { + val builder = InstanceManager.get(identifier) + val pageModeBuilder = InstanceManager.get(pageModeBuilderIdentifier) + + if (builder is PageModeBuilder && pageModeBuilder is PageModeBuilder) { + builder.add(pageModeBuilder) + promise.resolve(true) + } + else { + promise.reject(ReactNoCrashSoftException("Not found native instance")) + } + } +} \ No newline at end of file diff --git a/android/src/main/java/com/stario10module/PreSettingBuilderWrapper.kt b/android/src/main/java/com/stario10module/PreSettingBuilderWrapper.kt new file mode 100644 index 00000000..ac6d25d6 --- /dev/null +++ b/android/src/main/java/com/stario10module/PreSettingBuilderWrapper.kt @@ -0,0 +1,55 @@ +package com.stario10module + +import com.facebook.react.bridge.* +import com.starmicronics.stario10.starxpandcommand.BezelSettingBuilder +import com.starmicronics.stario10.starxpandcommand.LedSettingBuilder +import com.starmicronics.stario10.starxpandcommand.PreSettingBuilder +import com.starmicronics.stario10.starxpandcommand.PresenterSettingBuilder + +class PreSettingBuilderWrapper internal constructor(context: ReactApplicationContext) : ReactContextBaseJavaModule(context) { + override fun getName(): String { + return "PreSettingBuilderWrapper" + } + + @ReactMethod + fun init(promise: Promise) { + val builder = PreSettingBuilder() + val identifier = InstanceManager.set(builder) + + promise.resolve(identifier) + } + + @ReactMethod + fun dispose(identifier: String, promise: Promise) { + InstanceManager.remove(identifier) + promise.resolve(0) + } + + @ReactMethod + fun addPresenterSetting(identifier: String, presenterSettingBuilderIdentifier: String, promise: Promise) { + val builder = InstanceManager.get(identifier) + val presenterSettingBuilder = InstanceManager.get(presenterSettingBuilderIdentifier) + + if (builder is PreSettingBuilder && presenterSettingBuilder is PresenterSettingBuilder) { + builder.addPresenterSetting(presenterSettingBuilder) + promise.resolve(0) + } + else { + promise.reject(ReactNoCrashSoftException("Not found native instance")) + } + } + + @ReactMethod + fun addBezelSetting(identifier: String, bezelSettingBuilderIdentifier: String, promise: Promise) { + val builder = InstanceManager.get(identifier) + val bezelSettingBuilder = InstanceManager.get(bezelSettingBuilderIdentifier) + + if (builder is PreSettingBuilder && bezelSettingBuilder is BezelSettingBuilder) { + builder.addBezelSetting(bezelSettingBuilder) + promise.resolve(0) + } + else { + promise.reject(ReactNoCrashSoftException("Not found native instance")) + } + } +} \ No newline at end of file diff --git a/android/src/main/java/com/stario10module/PresenterSettingBuilderWrapper.kt b/android/src/main/java/com/stario10module/PresenterSettingBuilderWrapper.kt new file mode 100644 index 00000000..8a172997 --- /dev/null +++ b/android/src/main/java/com/stario10module/PresenterSettingBuilderWrapper.kt @@ -0,0 +1,54 @@ +package com.stario10module + +import com.facebook.react.bridge.* +import com.starmicronics.stario10.starxpandcommand.LedSettingBuilder +import com.starmicronics.stario10.starxpandcommand.PresenterSettingBuilder + +class PresenterSettingBuilderWrapper internal constructor(context: ReactApplicationContext) : ReactContextBaseJavaModule(context) { + override fun getName(): String { + return "PresenterSettingBuilderWrapper" + } + + @ReactMethod + fun init(promise: Promise) { + val builder = PresenterSettingBuilder() + val identifier = InstanceManager.set(builder) + + promise.resolve(identifier) + } + + @ReactMethod + fun dispose(identifier: String, promise: Promise) { + InstanceManager.remove(identifier) + promise.resolve(0) + } + + @ReactMethod + fun settingMode(identifier: String, loop: Boolean, hold: Boolean, retract: Boolean, holdTime: Int, promise: Promise) { + val builder = InstanceManager.get(identifier) + + if (builder is PresenterSettingBuilder) { + val parameter = StarIO10ValueConverter.toPresenterModeParameter(loop, hold, retract, holdTime) + + builder.settingMode(parameter) + promise.resolve(0) + } + else { + promise.reject(ReactNoCrashSoftException("Not found native instance")) + } + } + + @ReactMethod + fun addLed(identifier: String, ledSettingBuilderIdentifier: String, promise: Promise) { + val builder = InstanceManager.get(identifier) + val ledSettingBuilder = InstanceManager.get(ledSettingBuilderIdentifier) + + if (builder is PresenterSettingBuilder && ledSettingBuilder is LedSettingBuilder) { + builder.addLed(ledSettingBuilder) + promise.resolve(0) + } + else { + promise.reject(ReactNoCrashSoftException("Not found native instance")) + } + } +} \ No newline at end of file diff --git a/android/src/main/java/com/stario10module/PrinterBuilderWrapper.kt b/android/src/main/java/com/stario10module/PrinterBuilderWrapper.kt new file mode 100644 index 00000000..541a2599 --- /dev/null +++ b/android/src/main/java/com/stario10module/PrinterBuilderWrapper.kt @@ -0,0 +1,376 @@ +package com.stario10module + +import com.facebook.react.bridge.* +import com.starmicronics.stario10.StarIO10ArgumentException +import com.starmicronics.stario10.starxpandcommand.* +import com.starmicronics.stario10.starxpandcommand.printer.* + + +class PrinterBuilderWrapper internal constructor(context: ReactApplicationContext) : ReactContextBaseJavaModule(context) { + override fun getName(): String { + return "PrinterBuilderWrapper" + } + + @ReactMethod + fun init(promise: Promise) { + val builder = PrinterBuilder() + val identifier = InstanceManager.set(builder) + + promise.resolve(identifier) + } + + @ReactMethod + fun dispose(identifier: String, promise: Promise) { + InstanceManager.remove(identifier) + promise.resolve(0) + } + + @ReactMethod + fun styleAlignment(identifier: String, alignment: String, promise: Promise) { + val builder = InstanceManager.get(identifier) + + if (builder is PrinterBuilder) { + builder.styleAlignment(StarIO10ValueConverter.toPrinterAlignment(alignment)) + promise.resolve(0) + } + else { + promise.reject(ReactNoCrashSoftException("Not found native instance")) + } + } + + @ReactMethod + fun settingPageMode(identifier: String, x: Double, y: Double, width: Double, height: Double, printDirection: String, pageModeBuilderIdentifier: String, promise: Promise) { + val builder = InstanceManager.get(identifier) + val pageModeBuilder = InstanceManager.get(pageModeBuilderIdentifier) + + if (builder is PrinterBuilder && pageModeBuilder is PageModeBuilder) { + builder.settingPageMode(StarIO10ValueConverter.toPrinterPageModeParameter(x, y, width, height, printDirection), pageModeBuilder) + promise.resolve(true) + } + else { + promise.reject(ReactNoCrashSoftException("Not found native instance")) + } + } + + + @ReactMethod + fun styleFont(identifier: String, type: String, promise: Promise) { + val builder = InstanceManager.get(identifier) + + if (builder is PrinterBuilder) { + builder.styleFont(StarIO10ValueConverter.toPrinterFontType(type)) + promise.resolve(0) + } + else { + promise.reject(ReactNoCrashSoftException("Not found native instance")) + } + } + + @ReactMethod + fun styleBold(identifier: String, enable: Boolean, promise: Promise) { + val builder = InstanceManager.get(identifier) + + if (builder is PrinterBuilder) { + builder.styleBold(enable) + promise.resolve(0) + } + else { + promise.reject(ReactNoCrashSoftException("Not found native instance")) + } + } + + @ReactMethod + fun styleInvert(identifier: String, enable: Boolean, promise: Promise) { + val builder = InstanceManager.get(identifier) + + if (builder is PrinterBuilder) { + builder.styleInvert(enable) + promise.resolve(0) + } + else { + promise.reject(ReactNoCrashSoftException("Not found native instance")) + } + } + + @ReactMethod + fun styleUnderLine(identifier: String, enable: Boolean, promise: Promise) { + val builder = InstanceManager.get(identifier) + + if (builder is PrinterBuilder) { + builder.styleUnderLine(enable) + promise.resolve(0) + } + else { + promise.reject(ReactNoCrashSoftException("Not found native instance")) + } + } + + @ReactMethod + fun styleMagnification(identifier: String, width: Int, height: Int, promise: Promise) { + val builder = InstanceManager.get(identifier) + + if (builder is PrinterBuilder) { + builder.styleMagnification(StarIO10ValueConverter.toMagnificationParameter(width, height)) + promise.resolve(0) + } + else { + promise.reject(ReactNoCrashSoftException("Not found native instance")) + } + } + + @ReactMethod + fun styleCharacterSpace(identifier: String, width: Double, promise: Promise) { + val builder = InstanceManager.get(identifier) + + if (builder is PrinterBuilder) { + builder.styleCharacterSpace(width) + promise.resolve(0) + } + else { + promise.reject(ReactNoCrashSoftException("Not found native instance")) + } + } + + @ReactMethod + fun styleLineSpace(identifier: String, height: Double, promise: Promise) { + val builder = InstanceManager.get(identifier) + + if (builder is PrinterBuilder) { + builder.styleLineSpace(height) + promise.resolve(0) + } + else { + promise.reject(ReactNoCrashSoftException("Not found native instance")) + } + } + + @ReactMethod + fun styleHorizontalPositionTo(identifier: String, position: Double, promise: Promise) { + val builder = InstanceManager.get(identifier) + + if (builder is PrinterBuilder) { + builder.styleHorizontalPositionTo(position) + promise.resolve(0) + } + else { + promise.reject(ReactNoCrashSoftException("Not found native instance")) + } + } + + @ReactMethod + fun styleHorizontalPositionBy(identifier: String, position: Double, promise: Promise) { + val builder = InstanceManager.get(identifier) + + if (builder is PrinterBuilder) { + builder.styleHorizontalPositionBy(position) + promise.resolve(0) + } + else { + promise.reject(ReactNoCrashSoftException("Not found native instance")) + } + } + + @ReactMethod + fun styleHorizontalTabPositions(identifier: String, positions: ReadableArray, promise: Promise) { + val builder = InstanceManager.get(identifier) + + if (builder is PrinterBuilder) { + builder.styleHorizontalTabPositions(StarIO10ValueConverter.toList(positions)) + promise.resolve(0) + } + else { + promise.reject(ReactNoCrashSoftException("Not found native instance")) + } + } + + @ReactMethod + fun styleInternationalCharacter(identifier: String, type: String, promise: Promise) { + val builder = InstanceManager.get(identifier) + + if (builder is PrinterBuilder) { + builder.styleInternationalCharacter(StarIO10ValueConverter.toPrinterInternationalType(type)) + promise.resolve(0) + } + else { + promise.reject(ReactNoCrashSoftException("Not found native instance")) + } + } + + @ReactMethod + fun styleSecondPriorityCharacterEncoding(identifier: String, type: String, promise: Promise) { + val builder = InstanceManager.get(identifier) + + if (builder is PrinterBuilder) { + builder.styleSecondPriorityCharacterEncoding(StarIO10ValueConverter.toPrinterCharacterEncodingType(type)) + promise.resolve(0) + } + else { + promise.reject(ReactNoCrashSoftException("Not found native instance")) + } + } + + @ReactMethod + fun styleCjkCharacterPriority(identifier: String, types: ReadableArray, promise: Promise) { + val builder = InstanceManager.get(identifier) + + if (builder is PrinterBuilder) { + val typeList = mutableListOf() + + for(type in StarIO10ValueConverter.toList(types)) { + typeList.add(StarIO10ValueConverter.toPrinterCjkCharacterType(type)) + } + + builder.styleCjkCharacterPriority(typeList) + promise.resolve(0) + } + else { + promise.reject(ReactNoCrashSoftException("Not found native instance")) + } + } + + @ReactMethod + fun actionCut(identifier: String, type: String, promise: Promise) { + val builder = InstanceManager.get(identifier) + + if (builder is PrinterBuilder) { + builder.actionCut(StarIO10ValueConverter.toPrinterCutType(type)) + promise.resolve(0) + } + else { + promise.reject(ReactNoCrashSoftException("Not found native instance")) + } + } + + @ReactMethod + fun actionFeed(identifier: String, height: Double, promise: Promise) { + val builder = InstanceManager.get(identifier) + + if (builder is PrinterBuilder) { + builder.actionFeed(height) + promise.resolve(0) + } + else { + promise.reject(ReactNoCrashSoftException("Not found native instance")) + } + } + + @ReactMethod + fun actionFeedLine(identifier: String, lines: Int, promise: Promise) { + val builder = InstanceManager.get(identifier) + + if (builder is PrinterBuilder) { + builder.actionFeedLine(lines) + promise.resolve(0) + } + else { + promise.reject(ReactNoCrashSoftException("Not found native instance")) + } + } + + @ReactMethod + fun actionPrintText(identifier: String, content: String, promise: Promise) { + val builder = InstanceManager.get(identifier) + + if (builder is PrinterBuilder) { + builder.actionPrintText(content) + promise.resolve(0) + } + else { + promise.reject(ReactNoCrashSoftException("Not found native instance")) + } + } + + @ReactMethod + fun actionPrintLogo(identifier: String, keyCode: String, promise: Promise) { + val builder = InstanceManager.get(identifier) + + if (builder is PrinterBuilder) { + builder.actionPrintLogo(StarIO10ValueConverter.toPrinterLogoParameter(keyCode)) + promise.resolve(0) + } + else { + promise.reject(ReactNoCrashSoftException("Not found native instance")) + } + } + + @ReactMethod + fun actionPrintBarcode(identifier: String, content: String, symbology: String, printHri: Boolean, barDots: Int, barRatioLevel: String, height: Double, promise: Promise) { + val builder = InstanceManager.get(identifier) + + if (builder is PrinterBuilder) { + val parameter = StarIO10ValueConverter.toPrinterBarcodeParameter(content, symbology, printHri, barDots, barRatioLevel, height) + + builder.actionPrintBarcode(parameter) + promise.resolve(0) + } + else { + promise.reject(ReactNoCrashSoftException("Not found native instance")) + } + } + + @ReactMethod + fun actionPrintPdf417(identifier: String, content: String, column: Int, line: Int, module: Int, aspect: Int, level: String, promise: Promise) { + val builder = InstanceManager.get(identifier) + + if (builder is PrinterBuilder) { + val parameter = StarIO10ValueConverter.toPrinterPdf417Parameter(content, column, line, module, aspect, level) + + builder.actionPrintPdf417(parameter) + promise.resolve(0) + } + else { + promise.reject(ReactNoCrashSoftException("Not found native instance")) + } + } + + @ReactMethod + fun actionPrintQRCode(identifier: String, content: String, model: String, level: String, cellSize: Int, promise: Promise) { + val builder = InstanceManager.get(identifier) + + if (builder is PrinterBuilder) { + val parameter = StarIO10ValueConverter.toPrinterQRCodeParameter(content, model, level, cellSize) + + builder.actionPrintQRCode(parameter) + promise.resolve(0) + } + else { + promise.reject(ReactNoCrashSoftException("Not found native instance")) + } + } + + @ReactMethod + fun actionPrintImage(identifier: String, source: String, width: Int, effectDiffusion: Boolean, threshold: Int, promise: Promise) { + val builder = InstanceManager.get(identifier) + + if (builder is PrinterBuilder) { + try { + val parameter = StarIO10ValueConverter.toPrinterImageParameter(source, width, effectDiffusion, threshold) + builder.actionPrintImage(parameter) + promise.resolve(0) + } + catch (e: Exception) { + val exception = StarIO10ArgumentException("Invalid source.") + val exceptionIdentifier = InstanceManager.set(exception) + promise.reject(exceptionIdentifier, exception) + } + } + else { + promise.reject(ReactNoCrashSoftException("Not found native instance")) + } + } + + @ReactMethod + fun add(identifier: String, printerBuilderIdentifier: String, promise: Promise) { + val builder = InstanceManager.get(identifier) + val printerBuilder = InstanceManager.get(printerBuilderIdentifier) + + if (builder is PrinterBuilder && printerBuilder is PrinterBuilder) { + builder.add(printerBuilder) + promise.resolve(true) + } + else { + promise.reject(ReactNoCrashSoftException("Not found native instance")) + } + } +} + diff --git a/android/src/main/java/com/stario10module/StarDeviceDiscoveryManagerWrapper.kt b/android/src/main/java/com/stario10module/StarDeviceDiscoveryManagerWrapper.kt new file mode 100644 index 00000000..8586f893 --- /dev/null +++ b/android/src/main/java/com/stario10module/StarDeviceDiscoveryManagerWrapper.kt @@ -0,0 +1,99 @@ +package com.stario10module + +import androidx.annotation.Nullable +import com.facebook.react.bridge.* +import com.facebook.react.modules.core.DeviceEventManagerModule +import com.starmicronics.stario10.* + + +class StarDeviceDiscoveryManagerWrapper internal constructor(context: ReactApplicationContext) : ReactContextBaseJavaModule(context) { + override fun getName(): String { + return "StarDeviceDiscoveryManagerWrapper" + } + + @ReactMethod + fun init(interfaceTypes: ReadableArray, promise: Promise) { + val typeList = mutableListOf() + + for(type in StarIO10ValueConverter.toList(interfaceTypes)) { + typeList.add(StarIO10ValueConverter.toInterfaceType(type)) + } + + val manager = StarDeviceDiscoveryManagerFactory.create(typeList, reactApplicationContext) + val identifier = InstanceManager.set(manager) + + promise.resolve(identifier) + } + + @ReactMethod + fun dispose(identifier: String, promise: Promise) { + InstanceManager.remove(identifier) + promise.resolve(0) + } + + @ReactMethod + fun startDiscovery(identifier: String, discoveryTime: Int, promise: Promise) { + val manager = InstanceManager.get(identifier) + + if (manager is StarDeviceDiscoveryManager) { + manager.discoveryTime = discoveryTime + + try { + manager.startDiscovery(object : StarDeviceDiscoveryManager.Callback { + override fun onPrinterFound(printer: StarPrinter) { + val params = Arguments.createMap() + params.putString(EventParameter.KEY_IDENTIFIER, identifier) + params.putString(EventParameter.KEY_INTERFACE_TYPE, StarIO10ValueConverter.toString(printer.connectionSettings.interfaceType)) + params.putString(EventParameter.KEY_CONNECTION_IDENTIFIER, printer.connectionSettings.identifier) + params.putString(EventParameter.KEY_MODEL, StarIO10ValueConverter.toString(printer.information?.model ?: StarPrinterModel.Unknown)) + params.putString(EventParameter.KEY_EMULATION, StarIO10ValueConverter.toString(printer.information?.emulation ?: StarPrinterEmulation.Unknown)) + + sendEvent(EventParameter.NAME_PRINTER_FOUND, params) + } + + override fun onDiscoveryFinished() { + val params = Arguments.createMap() + params.putString(EventParameter.KEY_IDENTIFIER, identifier) + + sendEvent(EventParameter.NAME_DISCOVERY_FINISHED, params) + } + }) + + promise.resolve(0) + } + catch (e: StarIO10Exception) { + val exceptionIdentifier = InstanceManager.set(e) + promise.reject(exceptionIdentifier, e) + } + } + else { + promise.reject(StarIO10Exception("Identifier error")) + } + } + + @ReactMethod + fun stopDiscovery(identifier: String, promise: Promise) { + val manager = InstanceManager.get(identifier) + + if (manager is StarDeviceDiscoveryManager) { + try { + manager.stopDiscovery() + promise.resolve(0) + } + catch (e: StarIO10Exception) { + val exceptionIdentifier = InstanceManager.set(e) + promise.reject(exceptionIdentifier, e) + } + } + else { + promise.reject(StarIO10Exception("Identifier error")) + } + } + + private fun sendEvent(eventName: String, @Nullable params: WritableMap) { + reactApplicationContext + .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java) + .emit(eventName, params) + } +} + diff --git a/android/src/main/java/com/stario10module/StarIO10ErrorWrapper.kt b/android/src/main/java/com/stario10module/StarIO10ErrorWrapper.kt new file mode 100644 index 00000000..2c8ebdc8 --- /dev/null +++ b/android/src/main/java/com/stario10module/StarIO10ErrorWrapper.kt @@ -0,0 +1,84 @@ +package com.stario10module + +import com.facebook.react.bridge.* +import com.starmicronics.stario10.StarPrinterStatus +import com.starmicronics.stario10.* + + +class StarIO10ErrorWrapper internal constructor(context: ReactApplicationContext) : ReactContextBaseJavaModule(context) { + override fun getName(): String { + return "StarIO10ErrorWrapper" + } + + @ReactMethod + fun getType(identifier: String, promise: Promise) { + val type = when (InstanceManager.get(identifier)) { + is StarIO10ArgumentException -> "Argument" + is StarIO10BadResponseException -> "BadResponse" + is StarIO10CommunicationException -> "Communication" + is StarIO10IllegalHostDeviceStateException -> "IllegalDeviceState" + is StarIO10InUseException -> "InUse" + is StarIO10InvalidOperationException -> "InvalidOperation" + is StarIO10NotFoundException -> "NotFound" + is StarIO10UnknownException -> "Unknown" + is StarIO10UnprintableException -> "Unprintable" + else -> { + promise.reject(ReactNoCrashSoftException("Exception is not defined")) + return + } + } + + promise.resolve(type) + } + + @ReactMethod + fun getMessage(identifier: String, promise: Promise) { + val exception = InstanceManager.get(identifier) + + if (exception is StarIO10Exception) { + promise.resolve(exception.message) + } + else { + promise.reject(ReactNoCrashSoftException("Not found $identifier identifier")) + } + } + + @ReactMethod + fun getErrorCode(identifier: String, promise: Promise) { + val exception = InstanceManager.get(identifier) + + if (exception is StarIO10Exception) { + promise.resolve(exception.errorCode.value) + } + else { + promise.reject(ReactNoCrashSoftException("Not found $identifier identifier")) + } + } + + @ReactMethod + fun getStatus(identifier: String, promise: Promise) { + val exception = InstanceManager.get(identifier) + + var status: StarPrinterStatus? = null + + if (exception is StarIO10UnprintableException) { + status = exception.status + } + + if(status == null) { + promise.reject(ReactNoCrashSoftException("status is null.")) + return + } + + val statusIdentifier = InstanceManager.set(status) + promise.resolve(statusIdentifier) + } + + @ReactMethod + fun dispose(identifier: String, promise: Promise) { + InstanceManager.remove(identifier) + + promise.resolve(0) + } +} + diff --git a/android/src/main/java/com/stario10module/StarIO10Package.kt b/android/src/main/java/com/stario10module/StarIO10Package.kt new file mode 100644 index 00000000..9d0d2dc6 --- /dev/null +++ b/android/src/main/java/com/stario10module/StarIO10Package.kt @@ -0,0 +1,34 @@ +package com.stario10module + +import com.facebook.react.ReactPackage +import com.facebook.react.bridge.NativeModule +import com.facebook.react.bridge.ReactApplicationContext +import com.facebook.react.uimanager.ViewManager +import java.util.* + +class StarIO10Package : ReactPackage { + override fun createNativeModules(reactContext: ReactApplicationContext): List { + val modules: MutableList = ArrayList() + + modules.add(BezelSettingBuilderWrapper(reactContext)) + modules.add(BuzzerBuilderWrapper(reactContext)) + modules.add(DocumentBuilderWrapper(reactContext)) + modules.add(DrawerBuilderWrapper(reactContext)) + modules.add(LedSettingBuilderWrapper(reactContext)) + modules.add(MelodySpeakerBuilderWrapper(reactContext)) + modules.add(PageModeBuilderWrapper(reactContext)) + modules.add(PreSettingBuilderWrapper(reactContext)) + modules.add(PrinterBuilderWrapper(reactContext)) + modules.add(StarDeviceDiscoveryManagerWrapper(reactContext)) + modules.add(StarIO10ErrorWrapper(reactContext)) + modules.add(StarXpandCommandBuilderWrapper(reactContext)) + modules.add(StarPrinterStatusWrapper(reactContext)) + modules.add(StarPrinterWrapper(reactContext)) + + return modules + } + + override fun createViewManagers(reactContext: ReactApplicationContext): List> { + return emptyList>() + } +} diff --git a/android/src/main/java/com/stario10module/StarIO10ValueConverter.kt b/android/src/main/java/com/stario10module/StarIO10ValueConverter.kt new file mode 100644 index 00000000..f3422288 --- /dev/null +++ b/android/src/main/java/com/stario10module/StarIO10ValueConverter.kt @@ -0,0 +1,493 @@ +package com.stario10module + +import android.graphics.Bitmap +import android.graphics.BitmapFactory +import android.util.Base64 +import com.facebook.react.bridge.ReadableArray +import com.starmicronics.stario10.InterfaceType +import com.starmicronics.stario10.StarIO10ArgumentException +import com.starmicronics.stario10.StarPrinterEmulation +import com.starmicronics.stario10.StarPrinterModel +import com.starmicronics.stario10.starxpandcommand.MagnificationParameter +import com.starmicronics.stario10.starxpandcommand.display.Contrast +import com.starmicronics.stario10.starxpandcommand.led.AutomaticBlinkParameter +import com.starmicronics.stario10.starxpandcommand.led.Type +import com.starmicronics.stario10.starxpandcommand.melodyspeaker.DriveOneTimeSoundParameter +import com.starmicronics.stario10.starxpandcommand.melodyspeaker.DriveRegisteredSoundParameter +import com.starmicronics.stario10.starxpandcommand.melodyspeaker.SoundStorageArea +import com.starmicronics.stario10.starxpandcommand.presenter.ModeParameter +import com.starmicronics.stario10.starxpandcommand.printer.* +import java.util.ArrayList + +class StarIO10ValueConverter { + companion object { + + private val interfaceTypeMap = mapOf( + "Bluetooth" to InterfaceType.Bluetooth, + "Lan" to InterfaceType.Lan, + "Usb" to InterfaceType.Usb + ) + + fun toInterfaceType(value: String) : InterfaceType { + return interfaceTypeMap[value] ?: throw StarIO10ArgumentException("Undefined parameter '$value'") + } + + fun toString(value: InterfaceType) : String { + var result: String? = null + + for(item in interfaceTypeMap) { + if(item.value == value) { + result = item.key + break + } + } + return result ?: throw StarIO10ArgumentException("Undefined parameter '$value'") + } + + private val printerModelMap = mapOf( + "Unknown" to StarPrinterModel.Unknown, + "TSP650II" to StarPrinterModel.TSP650II, + "TSP700II" to StarPrinterModel.TSP700II, + "TSP800II" to StarPrinterModel.TSP800II, + "FVP10" to StarPrinterModel.FVP10, + "TSP100U" to StarPrinterModel.TSP100U, + "TSP100GT" to StarPrinterModel.TSP100GT, + "TSP100ECO" to StarPrinterModel.TSP100ECO, + "TSP100LAN" to StarPrinterModel.TSP100LAN, + "TSP100IIIW" to StarPrinterModel.TSP100IIIW, + "TSP100IIILAN" to StarPrinterModel.TSP100IIILAN, + "TSP100IIIBI" to StarPrinterModel.TSP100IIIBI, + "TSP100IIIU" to StarPrinterModel.TSP100IIIU, + "mPOP" to StarPrinterModel.mPOP, + "mC_Print2" to StarPrinterModel.mC_Print2, + "mC_Print3" to StarPrinterModel.mC_Print3, + "SM_S210i" to StarPrinterModel.SM_S210i, + "SM_S220i" to StarPrinterModel.SM_S220i, + "SM_S230i" to StarPrinterModel.SM_S230i, + "SM_T300i" to StarPrinterModel.SM_T300i, + "SM_T400i" to StarPrinterModel.SM_T400i, + "SM_L200" to StarPrinterModel.SM_L200, + "SM_L300" to StarPrinterModel.SM_L300, + "BSC10" to StarPrinterModel.BSC10, + "SP700" to StarPrinterModel.SP700 + ) + + fun toString(value: StarPrinterModel) : String { + var result: String? = null + + for(item in printerModelMap) { + if(item.value == value) { + result = item.key + break + } + } + return result ?: throw StarIO10ArgumentException("Undefined parameter '$value'") + } + + private val printerEmulationMap = mapOf( + "Unknown" to StarPrinterEmulation.Unknown, + "StarLine" to StarPrinterEmulation.StarLine, + "StarDot" to StarPrinterEmulation.StarDot, + "StarGraphic" to StarPrinterEmulation.StarGraphic, + "StarPRNT" to StarPrinterEmulation.StarPRNT, + "EscPos" to StarPrinterEmulation.EscPos, + "EscPosMobile" to StarPrinterEmulation.EscPosMobile + ) + + fun toString(value: StarPrinterEmulation) : String { + var result: String? = null + + for(item in printerEmulationMap) { + if(item.value == value) { + result = item.key + break + } + } + return result ?: throw StarIO10ArgumentException("Undefined parameter '$value'") + } + + private val ledTypeMap = mapOf( + "Printing" to Type.Printing, + "Error" to Type.Error, + "Idle" to Type.Idle + ) + + fun toLedType(value: String) : Type { + return ledTypeMap[value] ?: throw StarIO10ArgumentException("Undefined parameter '$value'") + } + + private val printerPageModePrintDirectionMap = mapOf( + "BottomToTop" to PageModePrintDirection.BottomToTop, + "LeftToRight" to PageModePrintDirection.LeftToRight, + "RightToLeft" to PageModePrintDirection.RightToLeft, + "TopToBottom" to PageModePrintDirection.TopToBottom + ) + + fun toPrinterPageModePrintDirection(value: String) : PageModePrintDirection { + return printerPageModePrintDirectionMap[value] ?: throw StarIO10ArgumentException("Undefined parameter '$value'") + } + + private val printerBlackMarkPositionMap = mapOf( + "Front" to BlackMarkPosition.Front, + "Back" to BlackMarkPosition.Back + ) + + fun toPrinterBlackMarkPosition(value: String) : BlackMarkPosition { + return printerBlackMarkPositionMap[value] ?: throw StarIO10ArgumentException("Undefined parameter '$value'") + } + + private val cutTypeMap = mapOf( + "Full" to CutType.Full, + "Partial" to CutType.Partial, + "FullDirect" to CutType.FullDirect, + "PartialDirect" to CutType.PartialDirect + ) + + fun toPrinterCutType(value: String) : CutType { + return cutTypeMap[value] ?: throw StarIO10ArgumentException("Undefined parameter '$value'") + } + + private val alignmentMap = mapOf( + "Left" to Alignment.Left, + "Center" to Alignment.Center, + "Right" to Alignment.Right + ) + + fun toPrinterAlignment(value: String) : Alignment { + return alignmentMap[value] ?: throw StarIO10ArgumentException("Undefined parameter '$value'") + } + + private val characterEncodingTypeMap = mapOf( + "ShiftJis" to CharacterEncodingType.ShiftJis, + "GB18030" to CharacterEncodingType.GB18030, + "Big5" to CharacterEncodingType.Big5, + "Korean" to CharacterEncodingType.Korean, + "CodePage" to CharacterEncodingType.CodePage + ) + + fun toPrinterCharacterEncodingType(value: String) : CharacterEncodingType { + return characterEncodingTypeMap[value] ?: throw StarIO10ArgumentException("Undefined parameter '$value'") + } + + private val cjkCharacterTypeMap = mapOf( + "Hangul" to CjkCharacterType.Hangul, + "Japanese" to CjkCharacterType.Japanese, + "SimplifiedChinese" to CjkCharacterType.SimplifiedChinese, + "TraditionalChinese" to CjkCharacterType.TraditionalChinese + ) + + fun toPrinterCjkCharacterType(value: String) : CjkCharacterType { + return cjkCharacterTypeMap[value] ?: throw StarIO10ArgumentException("Undefined parameter '$value'") + } + + private val fontTypeMap = mapOf( + "A" to FontType.A, + "B" to FontType.B + ) + + fun toPrinterFontType(value: String) : FontType { + return fontTypeMap[value] ?: throw StarIO10ArgumentException("Undefined parameter '$value'") + } + + private val internationalCharacterTypeMap = mapOf( + "Denmark" to InternationalCharacterType.Denmark, + "Denmark2" to InternationalCharacterType.Denmark2, + "France" to InternationalCharacterType.France, + "Germany" to InternationalCharacterType.Germany, + "Ireland" to InternationalCharacterType.Ireland, + "Italy" to InternationalCharacterType.Italy, + "Japan" to InternationalCharacterType.Japan, + "Korea" to InternationalCharacterType.Korea, + "LatinAmerica" to InternationalCharacterType.LatinAmerica, + "Legal" to InternationalCharacterType.Legal, + "Norway" to InternationalCharacterType.Norway, + "Spain" to InternationalCharacterType.Spain, + "Spain2" to InternationalCharacterType.Spain2, + "Sweden" to InternationalCharacterType.Sweden, + "UK" to InternationalCharacterType.UK, + "Usa" to InternationalCharacterType.Usa, + "Slovenia" to InternationalCharacterType.Slovenia, + "Croatia" to InternationalCharacterType.Croatia, + "China" to InternationalCharacterType.China, + "Vietnam" to InternationalCharacterType.Vietnam, + "Arabic" to InternationalCharacterType.Arabic + ) + + fun toPrinterInternationalType(value: String) : InternationalCharacterType { + return internationalCharacterTypeMap[value] ?: throw StarIO10ArgumentException("Undefined parameter '$value'") + } + + private val barcodeSymbologyTypeMap = mapOf( + "Code128" to BarcodeSymbology.Code128, + "Code39" to BarcodeSymbology.Code39, + "Code93" to BarcodeSymbology.Code93, + "Ean13" to BarcodeSymbology.Ean13, + "Ean8" to BarcodeSymbology.Ean8, + "UpcA" to BarcodeSymbology.UpcA, + "UpcE" to BarcodeSymbology.UpcE, + "Itf" to BarcodeSymbology.Itf, + "Jan13" to BarcodeSymbology.Jan13, + "Jan8" to BarcodeSymbology.Jan8, + "NW7" to BarcodeSymbology.NW7 + ) + + fun toPrinterBarcodeSymbology(value: String) : BarcodeSymbology { + return barcodeSymbologyTypeMap[value] ?: throw StarIO10ArgumentException("Undefined parameter '$value'") + } + + private val barcodeBarRatioLevelTypeMap = mapOf( + "Level0" to BarcodeBarRatioLevel.Level0, + "LevelMinus1" to BarcodeBarRatioLevel.LevelMinus1, + "LevelPlus1" to BarcodeBarRatioLevel.LevelPlus1 + ) + + fun toPrinterBarcodeBarRatioLevel(value: String) : BarcodeBarRatioLevel { + return barcodeBarRatioLevelTypeMap[value] ?: throw StarIO10ArgumentException("Undefined parameter '$value'") + } + + private val printerPdf417LevelMap = mapOf( + "Ecc0" to Pdf417Level.Ecc0, + "Ecc1" to Pdf417Level.Ecc1, + "Ecc2" to Pdf417Level.Ecc2, + "Ecc3" to Pdf417Level.Ecc3, + "Ecc4" to Pdf417Level.Ecc4, + "Ecc5" to Pdf417Level.Ecc5, + "Ecc6" to Pdf417Level.Ecc6, + "Ecc7" to Pdf417Level.Ecc7, + "Ecc8" to Pdf417Level.Ecc8 + ) + + fun toPrinterPdf417Level(value: String) : Pdf417Level { + return printerPdf417LevelMap[value] ?: throw StarIO10ArgumentException("Undefined parameter '$value'") + } + + private val printerQRCodeLevelMap = mapOf( + "L" to QRCodeLevel.L, + "M" to QRCodeLevel.M, + "Q" to QRCodeLevel.Q, + "H" to QRCodeLevel.H + ) + + fun toPrinterQRCodeLevel(value: String) : QRCodeLevel { + return printerQRCodeLevelMap[value] ?: throw StarIO10ArgumentException("Undefined parameter '$value'") + } + + private val printerQRCodeModelMap = mapOf( + "Model1" to QRCodeModel.Model1, + "Model2" to QRCodeModel.Model2 + ) + + fun toPrinterQRCodeModel(value: String) : QRCodeModel { + return printerQRCodeModelMap[value] ?: throw StarIO10ArgumentException("Undefined parameter '$value'") + } + + private val buzzerChannelMap = mapOf( + "No1" to com.starmicronics.stario10.starxpandcommand.buzzer.Channel.No1, + "No2" to com.starmicronics.stario10.starxpandcommand.buzzer.Channel.No2 + ) + + fun toBuzzerChannel(value: String) : com.starmicronics.stario10.starxpandcommand.buzzer.Channel { + return buzzerChannelMap[value] ?: throw StarIO10ArgumentException("Undefined parameter '$value'") + } + + private val drawerChannelMap = mapOf( + "No1" to com.starmicronics.stario10.starxpandcommand.drawer.Channel.No1, + "No2" to com.starmicronics.stario10.starxpandcommand.drawer.Channel.No2 + ) + + fun toDrawerChannel(value: String) : com.starmicronics.stario10.starxpandcommand.drawer.Channel { + return drawerChannelMap[value] ?: throw StarIO10ArgumentException("Undefined parameter '$value'") + } + + private val displayInternationalCharacterTypeMap = mapOf( + "Usa" to com.starmicronics.stario10.starxpandcommand.display.InternationalCharacterType.Usa, + "France" to com.starmicronics.stario10.starxpandcommand.display.InternationalCharacterType.France, + "Germany" to com.starmicronics.stario10.starxpandcommand.display.InternationalCharacterType.Germany, + "UK" to com.starmicronics.stario10.starxpandcommand.display.InternationalCharacterType.UK, + "Denmark" to com.starmicronics.stario10.starxpandcommand.display.InternationalCharacterType.Denmark, + "Sweden" to com.starmicronics.stario10.starxpandcommand.display.InternationalCharacterType.Sweden, + "Italy" to com.starmicronics.stario10.starxpandcommand.display.InternationalCharacterType.Italy, + "Spain" to com.starmicronics.stario10.starxpandcommand.display.InternationalCharacterType.Spain, + "Japan" to com.starmicronics.stario10.starxpandcommand.display.InternationalCharacterType.Japan, + "Norway" to com.starmicronics.stario10.starxpandcommand.display.InternationalCharacterType.Norway, + "Denmark2" to com.starmicronics.stario10.starxpandcommand.display.InternationalCharacterType.Denmark2, + "Spain2" to com.starmicronics.stario10.starxpandcommand.display.InternationalCharacterType.Spain2, + "LatinAmerica" to com.starmicronics.stario10.starxpandcommand.display.InternationalCharacterType.LatinAmerica, + "Korea" to com.starmicronics.stario10.starxpandcommand.display.InternationalCharacterType.Korea + ) + + fun toDisplayInternationalCharacterType(value: String) : com.starmicronics.stario10.starxpandcommand.display.InternationalCharacterType { + return displayInternationalCharacterTypeMap[value] ?: throw StarIO10ArgumentException("Undefined parameter '$value'") + } + + private val displayContrastMap = mapOf( + "Plus3" to Contrast.Plus3, + "Plus2" to Contrast.Plus2, + "Plus1" to Contrast.Plus1, + "Default" to Contrast.Default, + "Minus1" to Contrast.Minus1, + "Minus2" to Contrast.Minus2, + "Minus3" to Contrast.Minus3 + ) + + fun toDisplayContrast(value: String) : Contrast { + return displayContrastMap[value] ?: throw StarIO10ArgumentException("Undefined parameter '$value'") + } + + private val melodySpeakerSoundStorageAreaMap = mapOf( + "Area1" to SoundStorageArea.Area1, + "Area2" to SoundStorageArea.Area2 + ) + + fun toMelodySpeakerSoundStorageArea(value: String) : SoundStorageArea { + return melodySpeakerSoundStorageAreaMap[value] ?: throw StarIO10ArgumentException("Undefined parameter '$value'") + } + + fun toPresenterModeParameter(loop: Boolean, hold: Boolean, retract: Boolean, holdTime: Int): ModeParameter { + val parameter = ModeParameter() + parameter.setLoop(loop) + parameter.setHold(hold) + parameter.setRetract(retract) + parameter.setHoldTime(holdTime) + + return parameter + } + + fun toLedAutomaticBlinkParameter(type: String, onTime: Int, offTime: Int): AutomaticBlinkParameter { + val parameter = AutomaticBlinkParameter(toLedType(type)) + parameter.setOnTime(onTime) + parameter.setOffTime(offTime) + + return parameter + } + + fun toPrinterBlackMarkParameter(start: Boolean, end: Boolean, position: String): BlackMarkParameter { + val parameter = BlackMarkParameter() + parameter.setStart(start) + parameter.setEnd(end) + parameter.setPosition(toPrinterBlackMarkPosition(position)) + + return parameter + } + + fun toPrinterLabelParameter(start: Boolean, end: Boolean): LabelParameter { + val parameter = LabelParameter() + parameter.setStart(start) + parameter.setEnd(end) + + return parameter + } + + fun toPrinterPageModeParameter(x: Double, y: Double, width: Double, height: Double, printDirection: String): PageModeParameter { + val parameter = PageModeParameter(width, height) + parameter.setStartPositionX(x) + parameter.setStartPositionY(y) + parameter.setPrintDirection(toPrinterPageModePrintDirection(printDirection)) + + return parameter + } + + fun toPrinterHoldPrintParameter(enable: Boolean): HoldPrintParameter { + return HoldPrintParameter(enable) + } + + fun toMagnificationParameter(width: Int, height: Int): MagnificationParameter { + return MagnificationParameter(width, height) + } + + fun toPrinterLogoParameter(keyCode: String): LogoParameter { + return LogoParameter(keyCode) + } + + fun toPrinterBarcodeParameter(content: String, symbology: String, printHri: Boolean, barDots: Int, barRatioLevel: String, height: Double): BarcodeParameter { + val parameter = BarcodeParameter(content, toPrinterBarcodeSymbology(symbology)) + parameter.setPrintHri(printHri) + parameter.setBarDots(barDots) + parameter.setBarRatioLevel(toPrinterBarcodeBarRatioLevel(barRatioLevel)) + parameter.setHeight(height) + + return parameter + } + + fun toPrinterPdf417Parameter(content: String, column: Int, line: Int, module: Int, aspect: Int, level: String): Pdf417Parameter { + val parameter = Pdf417Parameter(content) + parameter.setColumn(column) + parameter.setLine(line) + parameter.setModule(module) + parameter.setAspect(aspect) + parameter.setLevel(toPrinterPdf417Level(level)) + + return parameter + } + + fun toPrinterQRCodeParameter(content: String, model: String, level: String, cellSize: Int): QRCodeParameter { + val parameter = QRCodeParameter(content) + parameter.setModel(toPrinterQRCodeModel(model)) + parameter.setLevel(toPrinterQRCodeLevel(level)) + parameter.setCellSize(cellSize) + + return parameter + } + + fun toPrinterImageParameter(source: String, width: Int, effectDiffusion: Boolean, threshold: Int): ImageParameter { + val parameter = ImageParameter(base64ToBitmap(source), width) + parameter.setEffectDiffusion(effectDiffusion) + parameter.setThreshold(threshold) + + return parameter + } + + fun toBuzzerDriveParameter(channel: String, repeat: Int, onTime: Int, offTime: Int): com.starmicronics.stario10.starxpandcommand.buzzer.DriveParameter { + val parameter = com.starmicronics.stario10.starxpandcommand.buzzer.DriveParameter() + parameter.setChannel(toBuzzerChannel(channel)) + parameter.setRepeat(repeat) + parameter.setOnTime(onTime) + parameter.setOffTime(offTime) + + return parameter + } + + fun toDrawerOpenParameter(channel: String, onTime: Int): com.starmicronics.stario10.starxpandcommand.drawer.OpenParameter { + val parameter = com.starmicronics.stario10.starxpandcommand.drawer.OpenParameter() + parameter.setChannel(toDrawerChannel(channel)) + parameter.setOnTime(onTime) + + return parameter + } + + fun toDisplayImageParameter(source: String, effectDiffusion: Boolean, threshold: Int): com.starmicronics.stario10.starxpandcommand.display.ImageParameter { + val parameter = com.starmicronics.stario10.starxpandcommand.display.ImageParameter(base64ToBitmap(source)) + parameter.setEffectDiffusion(effectDiffusion) + parameter.setThreshold(threshold) + + return parameter + } + + fun toMelodySpeakerDriveRegisteredSoundParameter(area: String, number: Int, volume: Int): DriveRegisteredSoundParameter { + val parameter = DriveRegisteredSoundParameter(toMelodySpeakerSoundStorageArea(area), number) + parameter.setVolume(volume) + + return parameter + } + + fun toMelodySpeakerDriveOneTimeSoundParameter(source: ReadableArray, volume: Int): DriveOneTimeSoundParameter { + val parameter = DriveOneTimeSoundParameter(toList(source)) + parameter.setVolume(volume) + + return parameter + } + + fun toList(value: ReadableArray): List { + val arrayList = value.toArrayList() as ArrayList + + return arrayList.toList() + } + + private fun base64ToBitmap(value: String): Bitmap { + val bytes = Base64.decode(value, 0) + return BitmapFactory.decodeByteArray(bytes, 0, bytes.size) + } + } + + +} \ No newline at end of file diff --git a/android/src/main/java/com/stario10module/StarPrinterStatusWrapper.kt b/android/src/main/java/com/stario10module/StarPrinterStatusWrapper.kt new file mode 100644 index 00000000..f3e8d199 --- /dev/null +++ b/android/src/main/java/com/stario10module/StarPrinterStatusWrapper.kt @@ -0,0 +1,78 @@ +package com.stario10module + +import com.facebook.react.bridge.* +import com.starmicronics.stario10.StarPrinterStatus + + +class StarPrinterStatusWrapper internal constructor(context: ReactApplicationContext) : ReactContextBaseJavaModule(context) { + override fun getName(): String { + return "StarPrinterStatusWrapper" + } + + @ReactMethod + fun getHasError(identifier: String, promise: Promise) { + val status = InstanceManager.get(identifier) + + if (status is StarPrinterStatus) { + promise.resolve(status.hasError) + } + else { + promise.reject(ReactNoCrashSoftException("Not found $identifier identifier")) + } + } + + @ReactMethod + fun getPaperEmpty(identifier: String, promise: Promise) { + val status = InstanceManager.get(identifier) + + if (status is StarPrinterStatus) { + promise.resolve(status.paperEmpty) + } + else { + promise.reject(ReactNoCrashSoftException("Not found $identifier identifier")) + } + } + + @ReactMethod + fun getPaperNearEmpty(identifier: String, promise: Promise) { + val status = InstanceManager.get(identifier) + + if (status is StarPrinterStatus) { + promise.resolve(status.paperNearEmpty) + } + else { + promise.reject(ReactNoCrashSoftException("Not found $identifier identifier")) + } + } + + @ReactMethod + fun getCoverOpen(identifier: String, promise: Promise) { + val status = InstanceManager.get(identifier) + + if (status is StarPrinterStatus) { + promise.resolve(status.coverOpen) + } + else { + promise.reject(ReactNoCrashSoftException("Not found $identifier identifier")) + } + } + + @ReactMethod + fun getDrawerOpenCloseSignal(identifier: String, promise: Promise) { + val status = InstanceManager.get(identifier) + + if (status is StarPrinterStatus) { + promise.resolve(status.drawerOpenCloseSignal) + } + else { + promise.reject(ReactNoCrashSoftException("Not found $identifier identifier")) + } + } + + @ReactMethod + fun dispose(identifier: String, promise: Promise) { + InstanceManager.remove(identifier) + promise.resolve(0) + } +} + diff --git a/android/src/main/java/com/stario10module/StarPrinterWrapper.kt b/android/src/main/java/com/stario10module/StarPrinterWrapper.kt new file mode 100644 index 00000000..f9ed974c --- /dev/null +++ b/android/src/main/java/com/stario10module/StarPrinterWrapper.kt @@ -0,0 +1,424 @@ +package com.stario10module + +import androidx.annotation.Nullable +import com.facebook.react.bridge.* +import com.facebook.react.modules.core.DeviceEventManagerModule +import com.starmicronics.stario10.* +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.launch + + +class StarPrinterWrapper internal constructor(context: ReactApplicationContext) : ReactContextBaseJavaModule(context) { + override fun getName(): String { + return "StarPrinterWrapper" + } + + @ReactMethod + fun init(promise: Promise) { + val printer = StarPrinter(StarConnectionSettings(), reactApplicationContext) + val identifier = InstanceManager.set(printer) + + promise.resolve(identifier) + } + + @ReactMethod + fun activatePrinterDelegate(identifier: String, promise: Promise) { + val printer = InstanceManager.get(identifier) + + if (printer is StarPrinter) { + printer.printerDelegate = object : PrinterDelegate() { + override fun onReady() { + val params = Arguments.createMap() + params.putString(EventParameter.KEY_IDENTIFIER, identifier) + + sendEvent(EventParameter.NAME_PRINTER_DELEGATE_READY, params) + } + + override fun onError() { + val params = Arguments.createMap() + params.putString(EventParameter.KEY_IDENTIFIER, identifier) + + sendEvent(EventParameter.NAME_PRINTER_DELEGATE_ERROR, params) + } + + override fun onPaperReady() { + val params = Arguments.createMap() + params.putString(EventParameter.KEY_IDENTIFIER, identifier) + + sendEvent(EventParameter.NAME_PRINTER_DELEGATE_PAPER_READY, params) + } + + override fun onPaperNearEmpty() { + val params = Arguments.createMap() + params.putString(EventParameter.KEY_IDENTIFIER, identifier) + + sendEvent(EventParameter.NAME_PRINTER_DELEGATE_PAPER_NEAR_EMPTY, params) + } + + override fun onPaperEmpty() { + val params = Arguments.createMap() + params.putString(EventParameter.KEY_IDENTIFIER, identifier) + + sendEvent(EventParameter.NAME_PRINTER_DELEGATE_PAPER_EMPTY, params) + } + + override fun onCoverOpened() { + val params = Arguments.createMap() + params.putString(EventParameter.KEY_IDENTIFIER, identifier) + + sendEvent(EventParameter.NAME_PRINTER_DELEGATE_COVER_OPENED, params) + } + + override fun onCoverClosed() { + val params = Arguments.createMap() + params.putString(EventParameter.KEY_IDENTIFIER, identifier) + + sendEvent(EventParameter.NAME_PRINTER_DELEGATE_COVER_CLOSED, params) + } + + override fun onCommunicationError(exception: StarIO10Exception) { + val params = Arguments.createMap() + params.putString(EventParameter.KEY_IDENTIFIER, identifier) + + val exceptionIdentifier = InstanceManager.set(exception) + params.putString(EventParameter.KEY_ERROR_IDENTIFIER, exceptionIdentifier) + + sendEvent(EventParameter.NAME_PRINTER_DELEGATE_COMMUNICATION_ERROR, params) + } + } + + promise.resolve(0) + } + else { + promise.reject(StarIO10Exception("Identifier error")) + } + } + + @ReactMethod + fun activateDrawerDelegate(identifier: String, promise: Promise) { + val printer = InstanceManager.get(identifier) + + if (printer is StarPrinter) { + printer.drawerDelegate = object : DrawerDelegate() { + override fun onOpenCloseSignalSwitched(signalState: Boolean) { + val params = Arguments.createMap() + params.putString(EventParameter.KEY_IDENTIFIER, identifier) + params.putBoolean(EventParameter.KEY_DRAWER_OPEN_CLOSE_SIGNAL_STATE, signalState) + + sendEvent(EventParameter.NAME_DRAWER_DELEGATE_OPEN_CLOSE_SIGNAL_SWITCHED, params) + } + + override fun onCommunicationError(exception: StarIO10Exception) { + val params = Arguments.createMap() + params.putString(EventParameter.KEY_IDENTIFIER, identifier) + + val exceptionIdentifier = InstanceManager.set(exception) + params.putString(EventParameter.KEY_ERROR_IDENTIFIER, exceptionIdentifier) + + sendEvent(EventParameter.NAME_DRAWER_DELEGATE_COMMUNICATION_ERROR, params) + } + } + + promise.resolve(0) + } + else { + promise.reject(StarIO10Exception("Identifier error")) + } + } + + @ReactMethod + fun activateInputDeviceDelegate(identifier: String, promise: Promise) { + val printer = InstanceManager.get(identifier) + + if (printer is StarPrinter) { + printer.inputDeviceDelegate = object : InputDeviceDelegate() { + override fun onConnected() { + val params = Arguments.createMap() + params.putString(EventParameter.KEY_IDENTIFIER, identifier) + + sendEvent(EventParameter.NAME_INPUT_DEVICE_DELEGATE_CONNECTED, params) + } + + override fun onDisconnected() { + val params = Arguments.createMap() + params.putString(EventParameter.KEY_IDENTIFIER, identifier) + + sendEvent(EventParameter.NAME_INPUT_DEVICE_DELEGATE_DISCONNECTED, params) + } + + override fun onDataReceived(data: List) { + val reactData = Arguments.createArray() + data.forEach { + reactData.pushInt(it.toInt()) + } + + val params = Arguments.createMap() + params.putString(EventParameter.KEY_IDENTIFIER, identifier) + params.putArray(EventParameter.KEY_INPUT_DEVICE_DATA, reactData) + + sendEvent(EventParameter.NAME_INPUT_DEVICE_DELEGATE_DATA_RECEIVED, params) + } + + override fun onCommunicationError(exception: StarIO10Exception) { + val params = Arguments.createMap() + params.putString(EventParameter.KEY_IDENTIFIER, identifier) + + val exceptionIdentifier = InstanceManager.set(exception) + params.putString(EventParameter.KEY_ERROR_IDENTIFIER, exceptionIdentifier) + + sendEvent(EventParameter.NAME_INPUT_DEVICE_DELEGATE_COMMUNICATION_ERROR, params) + } + } + + promise.resolve(0) + } + else { + promise.reject(StarIO10Exception("Identifier error")) + } + } + + @ReactMethod + fun activateDisplayDelegate(starPrinterIdentifier: String, promise: Promise) { + val starPrinter = InstanceManager.get(starPrinterIdentifier) + + if (starPrinter is StarPrinter) { + starPrinter.displayDelegate = object : DisplayDelegate() { + override fun onConnected() { + val params = Arguments.createMap() + params.putString(EventParameter.KEY_IDENTIFIER, starPrinterIdentifier) + + sendEvent(EventParameter.NAME_DISPLAY_DELEGATE_CONNECTED, params) + } + + override fun onDisconnected() { + val params = Arguments.createMap() + params.putString(EventParameter.KEY_IDENTIFIER, starPrinterIdentifier) + + sendEvent(EventParameter.NAME_DISPLAY_DELEGATE_DISCONNECTED, params) + } + + override fun onCommunicationError(exception: StarIO10Exception) { + val params = Arguments.createMap() + params.putString(EventParameter.KEY_IDENTIFIER, starPrinterIdentifier) + + val exceptionIdentifier = InstanceManager.set(exception) + params.putString(EventParameter.KEY_ERROR_IDENTIFIER, exceptionIdentifier) + + sendEvent(EventParameter.NAME_DISPLAY_DELEGATE_COMMUNICATION_ERROR, params) + } + } + + promise.resolve(0) + } + else { + promise.reject(StarIO10Exception("Identifier error")) + } + } + + @ReactMethod + fun open(identifier: String, interfaceType: String, connectionIdentifier: String, openTimeout: Int, autoSwitchInterface: Boolean, promise: Promise) { + val job = SupervisorJob() + val scope = CoroutineScope(Dispatchers.Default + job) + + scope.launch { + val printer = InstanceManager.get(identifier) + + if (printer is StarPrinter) { + printer.connectionSettings.identifier = connectionIdentifier + printer.connectionSettings.interfaceType = StarIO10ValueConverter.toInterfaceType(interfaceType) + printer.connectionSettings.autoSwitchInterface = autoSwitchInterface + printer.openTimeout = openTimeout + + try { + printer.openAsync().await() + promise.resolve(0) + } + catch (e: StarIO10Exception) { + val exceptionIdentifier = InstanceManager.set(e) + promise.reject(exceptionIdentifier, e) + } + } + else { + promise.reject(StarIO10ArgumentException("Argument error!")) + } + } + } + + @ReactMethod + fun getModel(identifier: String, promise: Promise) { + val printer = InstanceManager.get(identifier) + + if (printer is StarPrinter) { + promise.resolve(StarIO10ValueConverter.toString(printer.information!!.model)) + } + else { + promise.reject(StarIO10Exception("Identifier error")) + } + } + + @ReactMethod + fun getEmulation(identifier: String, promise: Promise) { + val printer = InstanceManager.get(identifier) + + if (printer is StarPrinter) { + promise.resolve(StarIO10ValueConverter.toString(printer.information!!.emulation)) + } + else { + promise.reject(StarIO10Exception("Identifier error")) + } + } + +// @ReactMethod +// fun getMacAddress(identifier: String, promise: Promise) { +// val printer = InstanceManager.get(identifier) +// +// if (printer is StarPrinter) { +// promise.resolve(printer.information!!.connectionIdentifier.macAddress) +// } +// else { +// promise.reject(StarIO10Exception("Identifier error")) +// } +// } +// +// @ReactMethod +// fun getBluetoothAddress(identifier: String, promise: Promise) { +// val printer = InstanceManager.get(identifier) +// +// if (printer is StarPrinter) { +// promise.resolve(printer.information!!.connectionIdentifier.bluetoothAddress) +// } +// else { +// promise.reject(StarIO10Exception("Identifier error")) +// } +// } +// +// @ReactMethod +// fun getUsbSerialNumber(identifier: String, promise: Promise) { +// val printer = InstanceManager.get(identifier) +// +// if (printer is StarPrinter) { +// promise.resolve(printer.information!!.connectionIdentifier.usbSerialNumber) +// } +// else { +// promise.reject(StarIO10Exception("Identifier error")) +// } +// } + + @ReactMethod + fun printRaw(identifier: String, data: ReadableArray, timeout: Int, promise: Promise) { + val job = SupervisorJob() + val scope = CoroutineScope(Dispatchers.Default + job) + + scope.launch { + val printer = InstanceManager.get(identifier) + + if (printer is StarPrinter) { + printer.printTimeout = timeout + + try { + printer.printRawDataAsync(StarIO10ValueConverter.toList(data)).await() + promise.resolve(0) + } + catch (e: StarIO10Exception) { + val exceptionIdentifier = InstanceManager.set(e) + promise.reject(exceptionIdentifier, e) + } + } + else { + promise.reject(StarIO10Exception("Identifier error")) + } + } + } + + @ReactMethod + fun print(identifier: String, code: String, timeout: Int, promise: Promise) { + val job = SupervisorJob() + val scope = CoroutineScope(Dispatchers.Default + job) + + scope.launch { + val printer = InstanceManager.get(identifier) + + if (printer is StarPrinter) { + printer.printTimeout = timeout + + try { + printer.printAsync(code).await() + promise.resolve(0) + } + catch (e: StarIO10Exception) { + val exceptionIdentifier = InstanceManager.set(e) + promise.reject(exceptionIdentifier, e) + } + } + else { + promise.reject(StarIO10Exception("Identifier error")) + } + } + } + + @ReactMethod + fun getStatus(identifier: String, timeout: Int, promise: Promise) { + val job = SupervisorJob() + val scope = CoroutineScope(Dispatchers.Default + job) + + scope.launch { + val printer = InstanceManager.get(identifier) + + if (printer is StarPrinter) { + printer.getStatusTimeout = timeout + + try { + val status = printer.getStatusAsync().await() + val statusIdentifier = InstanceManager.set(status) + + promise.resolve(statusIdentifier) + } + catch (e: StarIO10Exception) { + val exceptionIdentifier = InstanceManager.set(e) + promise.reject(exceptionIdentifier, e) + } + } + else { + promise.reject(StarIO10Exception("Identifier error")) + } + } + } + + @ReactMethod + fun close(identifier: String, promise: Promise) { + val job = SupervisorJob() + val scope = CoroutineScope(Dispatchers.Default + job) + + scope.launch { + val printer = InstanceManager.get(identifier) + + if (printer is StarPrinter) { + try { + printer.closeAsync().await() + promise.resolve(0) + } + catch (e: StarIO10Exception) { + val exceptionIdentifier = InstanceManager.set(e) + promise.reject(exceptionIdentifier, e) + } + } + else { + promise.reject(StarIO10Exception("Identifier error")) + } + } + } + + @ReactMethod + fun dispose(starPrinterIdentifier: String, promise: Promise) { + InstanceManager.remove(starPrinterIdentifier) + promise.resolve(0) + } + + private fun sendEvent(eventName: String, @Nullable params: WritableMap) { + reactApplicationContext + .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java) + .emit(eventName, params) + } +} \ No newline at end of file diff --git a/android/src/main/java/com/stario10module/StarXpandCommandBuilderWrapper.kt b/android/src/main/java/com/stario10module/StarXpandCommandBuilderWrapper.kt new file mode 100644 index 00000000..0afd859e --- /dev/null +++ b/android/src/main/java/com/stario10module/StarXpandCommandBuilderWrapper.kt @@ -0,0 +1,69 @@ +package com.stario10module + +import com.facebook.react.bridge.* +import com.starmicronics.stario10.starxpandcommand.DocumentBuilder +import com.starmicronics.stario10.starxpandcommand.PreSettingBuilder +import com.starmicronics.stario10.starxpandcommand.StarXpandCommandBuilder + + +class StarXpandCommandBuilderWrapper internal constructor(context: ReactApplicationContext) : ReactContextBaseJavaModule(context) { + override fun getName(): String { + return "StarXpandCommandBuilderWrapper" + } + + @ReactMethod + fun init(promise: Promise) { + val builder = StarXpandCommandBuilder() + val identifier = InstanceManager.set(builder) + + promise.resolve(identifier) + } + + @ReactMethod + fun dispose(identifier: String, promise: Promise) { + InstanceManager.remove(identifier) + promise.resolve(0) + } + + @ReactMethod + fun addDocument(identifier: String, documentIdentifier: String, promise: Promise) { + val builder = InstanceManager.get(identifier) + val documentBuilder = InstanceManager.get(documentIdentifier) + + if (builder is StarXpandCommandBuilder && documentBuilder is DocumentBuilder) { + builder.addDocument(documentBuilder) + promise.resolve(true) + } + else { + promise.reject(ReactNoCrashSoftException("Not found native instance")) + } + } + + @ReactMethod + fun setPreSetting(identifier: String, documentIdentifier: String, promise: Promise) { + val builder = InstanceManager.get(identifier) + val preSettingBuilder = InstanceManager.get(documentIdentifier) + + if (builder is StarXpandCommandBuilder && preSettingBuilder is PreSettingBuilder) { + builder.preSetting = preSettingBuilder + promise.resolve(true) + } + else { + promise.reject(ReactNoCrashSoftException("Not found native instance")) + } + } + + @ReactMethod + fun getCommands(identifier: String, promise: Promise) { + val builder = InstanceManager.get(identifier) + + if (builder is StarXpandCommandBuilder) { + promise.resolve(builder.getCommand()) + } + else { + promise.reject(ReactNoCrashSoftException("Not found native instance")) + } + } + +} + diff --git a/example/.buckconfig b/example/.buckconfig new file mode 100644 index 00000000..934256cb --- /dev/null +++ b/example/.buckconfig @@ -0,0 +1,6 @@ + +[android] + target = Google Inc.:Google APIs:23 + +[maven_repositories] + central = https://repo1.maven.org/maven2 diff --git a/example/.eslintrc.js b/example/.eslintrc.js new file mode 100644 index 00000000..18969972 --- /dev/null +++ b/example/.eslintrc.js @@ -0,0 +1,6 @@ +module.exports = { + root: true, + extends: '@react-native-community', + parser: '@typescript-eslint/parser', + plugins: ['@typescript-eslint'], +}; diff --git a/example/.gitattributes b/example/.gitattributes new file mode 100644 index 00000000..d42ff183 --- /dev/null +++ b/example/.gitattributes @@ -0,0 +1 @@ +*.pbxproj -text diff --git a/example/.gitignore b/example/.gitignore new file mode 100644 index 00000000..6a5e410a --- /dev/null +++ b/example/.gitignore @@ -0,0 +1,63 @@ +# OSX +# +.DS_Store + +# Xcode +# +build/ +*.pbxuser +!default.pbxuser +*.mode1v3 +!default.mode1v3 +*.mode2v3 +!default.mode2v3 +*.perspectivev3 +!default.perspectivev3 +xcuserdata +*.xccheckout +*.moved-aside +DerivedData +*.hmap +*.ipa +*.xcuserstate + +# Android/IntelliJ +# +build/ +.idea +.gradle +local.properties +*.iml + +# Visual Studio Code +# +.vscode/ + +# node.js +# +node_modules/ +npm-debug.log +yarn-error.log + +# BUCK +buck-out/ +\.buckd/ +*.keystore +!debug.keystore + +# fastlane +# +# It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the +# screenshots whenever they are needed. +# For more information about the recommended setup visit: +# https://docs.fastlane.tools/best-practices/source-control/ + +*/fastlane/report.xml +*/fastlane/Preview.html +*/fastlane/screenshots + +# Bundle artifact +*.jsbundle + +# CocoaPods +/ios/Pods/ diff --git a/example/.prettierrc.js b/example/.prettierrc.js new file mode 100644 index 00000000..5c4de1a4 --- /dev/null +++ b/example/.prettierrc.js @@ -0,0 +1,6 @@ +module.exports = { + bracketSpacing: false, + jsxBracketSameLine: true, + singleQuote: true, + trailingComma: 'all', +}; diff --git a/example/.watchmanconfig b/example/.watchmanconfig new file mode 100644 index 00000000..9e26dfee --- /dev/null +++ b/example/.watchmanconfig @@ -0,0 +1 @@ +{} \ No newline at end of file diff --git a/example/App.tsx b/example/App.tsx new file mode 100644 index 00000000..2a76b282 --- /dev/null +++ b/example/App.tsx @@ -0,0 +1,183 @@ +import React from 'react'; +import { + View, + Text, + Button, + TextInput, + Image +} from 'react-native'; + +import { + Picker +} from '@react-native-community/picker'; + +import { + InterfaceType, + StarConnectionSettings, + StarXpandCommand, + StarPrinter +} from 'react-native-star-io10'; + +import axios from 'axios'; +import { Buffer } from 'buffer'; + +interface AppProps { +} + +interface AppState { + interfaceType: InterfaceType; + identifier: string; + imageBase64: string; +} + +const imageIndex = require('./logo_01.png') + +class App extends React.Component { + private _onPressPrintButton = async() => { + let imageObj = Image.resolveAssetSource(imageIndex) + + axios.get(imageObj.uri, {responseType: 'arraybuffer'}) + .then(response => { + let imageBase64 = Buffer.from(response.data).toString('base64') + this.setState({ imageBase64: imageBase64 }); + this._Print() + }); + } + + private _Print = async() => { + var settings = new StarConnectionSettings(); + settings.interfaceType = this.state.interfaceType; + settings.identifier = this.state.identifier; + // settings.autoSwitchInterface = true; + + var printer = new StarPrinter(settings); + + try { + var builder = new StarXpandCommand.StarXpandCommandBuilder(); + builder.addDocument(new StarXpandCommand.DocumentBuilder() + .addPrinter(new StarXpandCommand.PrinterBuilder() + .actionPrintImage(new StarXpandCommand.Printer.ImageParameter(this.state.imageBase64, 406)) + .styleInternationalCharacter(StarXpandCommand.Printer.InternationalCharacterType.Usa) + .styleCharacterSpace(0) + .styleAlignment(StarXpandCommand.Printer.Alignment.Center) + .actionPrintText("Star Clothing Boutique\n" + + "123 Star Road\n" + + "City, State 12345\n" + + "\n") + .styleAlignment(StarXpandCommand.Printer.Alignment.Left) + .actionPrintText("Date:MM/DD/YYYY Time:HH:MM PM\n" + + "--------------------------------\n" + + "\n") + .actionPrintText("SKU Description Total\n" + + "300678566 PLAIN T-SHIRT 10.99\n" + + "300692003 BLACK DENIM 29.99\n" + + "300651148 BLUE DENIM 29.99\n" + + "300642980 STRIPED DRESS 49.99\n" + + "300638471 BLACK BOOTS 35.99\n" + + "\n" + + "Subtotal 156.95\n" + + "Tax 0.00\n" + + "--------------------------------\n") + .actionPrintText("Total ") + .add(new StarXpandCommand.PrinterBuilder() + .styleMagnification(new StarXpandCommand.MagnificationParameter(2, 2)) + .actionPrintText(" $156.95\n") + ) + .actionPrintText("--------------------------------\n" + + "\n" + + "Charge\n" + + "156.95\n" + + "Visa XXXX-XXXX-XXXX-0123\n" + + "\n") + .add(new StarXpandCommand.PrinterBuilder() + .styleInvert(true) + .actionPrintText("Refunds and Exchanges\n") + ) + .actionPrintText("Within ") + .add(new StarXpandCommand.PrinterBuilder() + .styleUnderLine(true) + .actionPrintText("30 days") + ) + .actionPrintText(" with receipt\n") + .actionPrintText("And tags attached\n" + + "\n") + .styleAlignment(StarXpandCommand.Printer.Alignment.Center) + .actionPrintBarcode(new StarXpandCommand.Printer.BarcodeParameter('0123456', + StarXpandCommand.Printer.BarcodeSymbology.Jan8) + .setBarDots(3) + .setBarRatioLevel(StarXpandCommand.Printer.BarcodeBarRatioLevel.Level0) + .setHeight(5) + .setPrintHri(true)) + .actionFeedLine(1) + .actionPrintQRCode(new StarXpandCommand.Printer.QRCodeParameter('Hello World.\n') + .setModel(StarXpandCommand.Printer.QRCodeModel.Model2) + .setLevel(StarXpandCommand.Printer.QRCodeLevel.L) + .setCellSize(8)) + .actionCut(StarXpandCommand.Printer.CutType.Partial) + ) + ); + + var commands = await builder.getCommands(); + + await printer.open(); + await printer.print(commands); + + console.log(`Success`); + } + catch(error) { + console.log(`Error: ${String(error)}`); + } + finally { + await printer.close(); + await printer.dispose(); + } + } + + constructor(props: any) { + super(props); + + this.state = { + interfaceType: InterfaceType.Lan, + identifier: '00:11:62:00:00:00', + imageBase64: '' + }; + } + + render() { + return ( + + + Interface + { + this.setState({ interfaceType: value }); + }}> + + + + + + + Identifier + { + this.setState({ identifier: value }); + }} + /> + + +