content
stringlengths
0
13M
path
stringlengths
4
263
contentHash
stringlengths
1
10
// // Source code recreated from a .class file by IntelliJ IDEA // (powered by Fernflower decompiler) // package com.cloudpos.mvc.base import android.content.Context import com.cloudpos.androidmvcmodel.common.Constants import com.cloudpos.mvc.common.Logger import java.io.PrintWriter import java.io.StringWriter import java.net.UnknownHostException import java.util.concurrent.locks.Condition import java.util.concurrent.locks.ReentrantLock class ActionContext : Runnable { private var action: AbstractAction? = null private var context: Context? = null private var param: Map<String?, Any?>? = null private var callback: ActionCallback? = null var result: Any? = null private var actionUrl: String? = null private var methodName: String? = null private val resultLock = ReentrantLock() private val resultCondition: Condition private var hasReturn: Boolean override fun run() { if (action == null) { Logger.error("Not found action! Please initional ActionContain and register your Action Class") } else { if (callback == null) { Logger.warn("No call back") } try { resultLock.lock() action!!.setContext(context) action!!.doBefore(param, callback) this.invoke() action!!.doAfter(param, callback) } catch (var6: Exception) { val errorMsg = "Invoke method error: " + action!!.javaClass.name + "#" + methodName if (var6.cause == null) { Logger.error(errorMsg, var6) } else if (var6.cause is UnknownHostException) { Logger.error(errorMsg) Logger.error(getStackTraceString(var6.cause)) } else { Logger.error(errorMsg, var6.cause) } callback!!.sendResponse(Constants.HANDLER_LOG_FAILED, var6.cause.toString()) } finally { hasReturn = true resultCondition.signalAll() resultLock.unlock() } } } // fun getResult(): Any? { // resultLock.lock() // try { // if (!hasReturn) { // resultCondition.await() // } // } catch (var5: InterruptedException) { // var5.printStackTrace() // } finally { // resultLock.unlock() // } // return result // } @Throws(Exception::class) private operator fun invoke() { parseActionUrl() var callbackParam: Class<*> = ActionCallback::class.java if (callback != null) { callbackParam = callback!!.javaClass.superclass } val helper = BeanHelper(action) val method = helper.getMethod(methodName, *arrayOf(MutableMap::class.java, callbackParam)) result = method!!.invoke(action, param, callback) } private fun parseActionUrl() { val index = actionUrl!!.indexOf("/") if (index == -1) { methodName = "execute" } else { methodName = actionUrl!!.substring(index + 1) } } fun setParam(param: Map<String?, Any?>?) { this.param = param } fun setCallback(callback: ActionCallback?) { this.callback = callback } fun setActionUrl(actionUrl: String?) { this.actionUrl = actionUrl } fun setContext(context: Context?) { this.context = context } fun setAction(action: AbstractAction?) { this.action = action } companion object { fun parseActionId(actionUrl: String): String { val index = actionUrl.indexOf("/") return if (index == -1) actionUrl else actionUrl.substring(0, index) } fun getStackTraceString(tr: Throwable?): String { return if (tr == null) { "" } else { val sw = StringWriter() val pw = PrintWriter(sw) tr.printStackTrace(pw) sw.toString() } } } init { resultCondition = resultLock.newCondition() hasReturn = false } }
APIDemoForAarBykotlin/app/src/main/java/com/cloudpos/mvc/base/ActionContext.kt
3037818285
// // Source code recreated from a .class file by IntelliJ IDEA // (powered by Fernflower decompiler) // package com.cloudpos.mvc.base import com.cloudpos.mvc.common.Logger import java.lang.reflect.Method import java.util.* internal class BeanHelper { private var mClass: Class<*> private var mObject: Any? = null private lateinit var declaredMethods: Array<Method> constructor(clazz: Class<*>) { mClass = clazz } constructor(obj: Any?) { mObject = obj mClass = mObject!!.javaClass } @Throws(NoSuchMethodException::class) fun getMethod(methodName: String?, vararg classes: Class<*>): Method { declaredMethods = mClass.declaredMethods var result: Method? = null var matchLevel = -1 var isFirst = true var var9: Array<Method> val var8 = declaredMethods.also { var9 = it }.size for (var7 in 0 until var8) { val method = var9[var7] val name = method.name if (name == methodName) { val paramTypes = method.parameterTypes if (paramTypes.size == classes.size) { val tempMatchLevel = matchLevel(paramTypes, classes as Array<Class<*>>) if (tempMatchLevel >= 0) { if (isFirst && matchLevel < tempMatchLevel) { isFirst = false matchLevel = tempMatchLevel } else { if (matchLevel >= tempMatchLevel) { continue } matchLevel = tempMatchLevel } result = method } } } } return result ?: throw NoSuchMethodException(methodName + " " + Arrays.asList(*classes).toString()) } fun getClosestClass(clazz: Class<*>): Class<*> { return clazz.superclass } fun matchLevel(paramTypes: Array<Class<*>>, transferParamTypes: Array<Class<*>>): Int { var matchLevel = -1 for (m in paramTypes.indices) { val paramType = paramTypes[m] val tParamType = transferParamTypes[m] if (paramType == tParamType) { ++matchLevel } else { val superClasses = getAllSuperClass(tParamType) for (n in 1..superClasses.size) { val superClass = superClasses[n - 1] if (superClass != null && superClass != paramType) { break } matchLevel += n } } } return matchLevel } @Throws(Exception::class) operator fun invoke(methodName: String?, vararg args: Any?): Any { val method = getMethod(methodName, *getClassTypes(*args as Array<out Any>)!!) return method.invoke(this, *args) } companion object { fun getClassTypes(vararg args: Any): Array<Class<*>>? { return if (args == null) { null } else { // val classes: Array<Class<*>> = arrayOfNulls(args.size) // for (i in 0 until args.size) { // classes[i] = args[i].javaClass // } return null } } fun getAllSuperClass(clazz: Class<*>): List<Class<*>?> { val classes: ArrayList<Class<*>?> = ArrayList<Class<*>?>() var cla: Class<*>? = clazz do { cla = cla!!.superclass Logger.debug("class: $clazz, super class: $cla") if (cla != null) { classes.add(cla) } } while ((cla == null || cla != Any::class.java) && cla != null) return classes } } }
APIDemoForAarBykotlin/app/src/main/java/com/cloudpos/mvc/base/BeanHelper.kt
253174515
// // Source code recreated from a .class file by IntelliJ IDEA // (powered by Fernflower decompiler) // package com.cloudpos.mvc.base import com.cloudpos.mvc.common.Logger import java.util.* abstract class ActionContainer { protected var actions: HashMap<String?, Any?> = HashMap<String?, Any?>() abstract fun initActions() fun getActions(): Map<String?, Any?> { return actions } @Throws(Exception::class) private fun searchInstance(clazz: Class<out AbstractAction>): Any { val var3: Iterator<*> = actions.entries.iterator() var value: Any do { if (!var3.hasNext()) { return clazz.newInstance() } val entry: Map.Entry<*, *> = var3.next() as Map.Entry<*, *> value = entry.value!! } while (value == null || value.javaClass != clazz) return value } protected fun addAction(actionId: String?, clazz: Class<out AbstractAction>, singleton: Boolean = false): Boolean { if (singleton) { try { actions[actionId] = searchInstance(clazz) } catch (var5: Exception) { Logger.error("build singleton instance occur an error:", var5) return false } } else { actions[actionId] = clazz } return true } protected fun addAction(clazz: Class<out AbstractAction>, singleton: Boolean = false): Boolean { return this.addAction(clazz.name, clazz, singleton) } }
APIDemoForAarBykotlin/app/src/main/java/com/cloudpos/mvc/base/ActionContainer.kt
2853992387
// // Source code recreated from a .class file by IntelliJ IDEA // (powered by Fernflower decompiler) // package com.cloudpos.mvc.base import android.content.Context abstract class AbstractAction { var mContext: Context? = null fun setContext(context: Context?) { mContext = context } open fun doBefore(param: Map<String?, Any?>?, callback: ActionCallback?) {} open fun doAfter(param: Map<String?, Any?>?, callback: ActionCallback?) {} }
APIDemoForAarBykotlin/app/src/main/java/com/cloudpos/mvc/base/AbstractAction.kt
1927642149
package com.cloudpos.apidemo.common import java.util.* object Common { var testBytes = byteArrayOf(0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39) fun createMasterKey(length: Int): ByteArray { val array = ByteArray(length) for (i in 0 until length) { // array[i] = (byte) 0x38; array[i] = testBytes[Random().nextInt(testBytes.size)] } return array } fun transferErrorCode(errorCode: Int): Int { val a = -errorCode val b = a and 0x0000FF return -b } // for (StackTraceElement stackTraceElement : eles) { // Log.e("stackTraceElement", stackTraceElement.getMethodName()); // } val methodName: String get() { val eles = Thread.currentThread().stackTrace // for (StackTraceElement stackTraceElement : eles) { // Log.e("stackTraceElement", stackTraceElement.getMethodName()); // } return eles[5].methodName } }
APIDemoForAarBykotlin/app/src/main/java/com/cloudpos/apidemo/common/Common.kt
569367463
package com.cloudpos.apidemo.action import com.cloudpos.* import com.cloudpos.apidemo.util.StringUtility import com.cloudpos.apidemoforunionpaycloudpossdk.R import com.cloudpos.card.CPUCard import com.cloudpos.card.Card import com.cloudpos.card.SLE4442Card import com.cloudpos.mvc.base.ActionCallback import com.cloudpos.smartcardreader.SmartCardReaderDevice import com.cloudpos.smartcardreader.SmartCardReaderOperationResult /* * PSAM Card * */ class SmartCardAction2 : ActionModel() { private var device: SmartCardReaderDevice? = null private var psamCard: Card? = null var area = SLE4442Card.MEMORY_CARD_AREA_MAIN var address = 0 var length = 10 var logicalID = SmartCardReaderDevice.ID_PSAMCARD override fun doBefore(param: Map<String?, Any?>?, callback: ActionCallback?) { super.doBefore(param, callback) if (device == null) { device = POSTerminal.getInstance(mContext) .getDevice("cloudpos.device.smartcardreader", logicalID) as SmartCardReaderDevice } } fun open(param: Map<String?, Any?>?, callback: ActionCallback?) { try { device!!.open(logicalID) sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun listenForCardPresent(param: Map<String?, Any?>?, callback: ActionCallback?) { try { val listener = OperationListener { arg0 -> if (arg0.resultCode == OperationResult.SUCCESS) { sendSuccessLog2(mContext!!.getString(R.string.find_card_succeed)) psamCard = (arg0 as SmartCardReaderOperationResult).card } else { sendFailedLog2(mContext!!.getString(R.string.find_card_failed)) } } device!!.listenForCardPresent(listener, TimeConstants.FOREVER) sendSuccessLog("") } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun waitForCardPresent(param: Map<String?, Any?>?, callback: ActionCallback?) { try { sendSuccessLog("") val operationResult: OperationResult = device!!.waitForCardPresent(TimeConstants.FOREVER) if (operationResult.resultCode == OperationResult.SUCCESS) { sendSuccessLog2(mContext!!.getString(R.string.find_card_succeed)) psamCard = (operationResult as SmartCardReaderOperationResult).card } else { sendFailedLog2(mContext!!.getString(R.string.find_card_failed)) } } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun cancelRequest(param: Map<String?, Any?>?, callback: ActionCallback?) { try { device!!.cancelRequest() sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun getID(param: Map<String?, Any?>?, callback: ActionCallback?) { try { val cardID = psamCard!!.id sendSuccessLog(mContext!!.getString(R.string.operation_succeed) + " Card ID = " + StringUtility.byteArray2String(cardID)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun getProtocol(param: Map<String?, Any?>?, callback: ActionCallback?) { try { val protocol = psamCard!!.protocol sendSuccessLog(mContext!!.getString(R.string.operation_succeed) + " Protocol = " + protocol) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun getCardStatus(param: Map<String?, Any?>?, callback: ActionCallback?) { try { val cardStatus = psamCard!!.cardStatus sendSuccessLog(mContext!!.getString(R.string.operation_succeed) + " Card Status = " + cardStatus) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun connect(param: Map<String?, Any?>?, callback: ActionCallback?) { try { val atr = (psamCard as CPUCard?)!!.connect() sendSuccessLog(mContext!!.getString(R.string.operation_succeed) + " ATR: " + StringUtility.byteArray2String(atr.bytes)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun transmit(param: Map<String?, Any?>?, callback: ActionCallback?) { val arryAPDU = byteArrayOf( 0x00, 0x84.toByte(), 0x00, 0x00, 0x08 ) val arryAPDU1 = byteArrayOf( 0x00, 0x84.toByte(), 0x00, 0x00, 0x08 ) try { val apduResponse = (psamCard as CPUCard?)!!.transmit(arryAPDU) sendSuccessLog(mContext!!.getString(R.string.operation_succeed) + " APDUResponse: " + StringUtility.byteArray2String(apduResponse)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun disconnect(param: Map<String?, Any?>?, callback: ActionCallback?) { try { sendNormalLog(mContext!!.getString(R.string.rfcard_remove_card)) (psamCard as CPUCard?)!!.disconnect() sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun close(param: Map<String?, Any?>?, callback: ActionCallback?) { try { psamCard = null device!!.close() sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } }
APIDemoForAarBykotlin/app/src/main/java/com/cloudpos/apidemo/action/SmartCardAction2.kt
679833360
package com.cloudpos.apidemo.action import com.cloudpos.* import com.cloudpos.apidemo.util.StringUtility import com.cloudpos.apidemoforunionpaycloudpossdk.R import com.cloudpos.mvc.base.ActionCallback import com.cloudpos.signature.SignatureDevice import com.cloudpos.signature.SignatureOperationResult class SignatureModel : ActionModel() { private var device: SignatureDevice? = null override fun doBefore(param: Map<String?, Any?>?, callback: ActionCallback?) { super.doBefore(param, callback) if (device == null) { device = POSTerminal.getInstance(mContext).getDevice("cloudpos.device.signature") as SignatureDevice } } fun open(param: Map<String?, Any?>?, callback: ActionCallback?) { try { device!!.open() sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun listenSignature(param: Map<String?, Any?>?, callback: ActionCallback?) { try { val listener = OperationListener { operationResult -> if (operationResult.resultCode == OperationResult.SUCCESS) { sendSuccessLog2(mContext!!.getString(R.string.sign_succeed)) val signatureOperationResult = operationResult as SignatureOperationResult val leg = signatureOperationResult.signatureLength val Data = signatureOperationResult.signatureCompressData val bitmap = signatureOperationResult.signature // String str = StringUtility.ByteArrayToString(Data, Data.length); // String string = String.format("leg = %d , Data = %s",leg, str); sendSuccessLog2(String.format("leg = %d , Data = %s", leg, StringUtility.ByteArrayToString(Data, Data.size))) } else { sendFailedLog2(mContext!!.getString(R.string.sign_falied)) } } device!!.listenSignature("sign", listener, TimeConstants.FOREVER) sendSuccessLog("") } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun waitSignature(param: Map<String?, Any?>?, callback: ActionCallback?) { try { sendSuccessLog("") val signatureOperationResult = device!!.waitSignature("sign", TimeConstants.FOREVER) if (signatureOperationResult.resultCode == SignatureOperationResult.SUCCESS) { sendSuccessLog2(mContext!!.getString(R.string.sign_succeed)) val leg = signatureOperationResult.signatureLength val Data = signatureOperationResult.signatureCompressData val bitmap = signatureOperationResult.signature sendSuccessLog2(String.format("leg = %d , Data = %s", leg, StringUtility.ByteArrayToString(Data, Data.size))) } else { sendFailedLog2(mContext!!.getString(R.string.sign_falied)) } } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun cancelRequest(param: Map<String?, Any?>?, callback: ActionCallback?) { try { device!!.cancelRequest() sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun close(param: Map<String?, Any?>?, callback: ActionCallback?) { try { device!!.close() sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } }
APIDemoForAarBykotlin/app/src/main/java/com/cloudpos/apidemo/action/SignatureModel.kt
1333239001
package com.cloudpos.apidemo.action import com.cloudpos.* import com.cloudpos.apidemo.common.Common import com.cloudpos.apidemo.util.StringUtility import com.cloudpos.apidemoforunionpaycloudpossdk.R import com.cloudpos.mvc.base.ActionCallback import com.cloudpos.pinpad.KeyInfo import com.cloudpos.pinpad.PINPadDevice import com.cloudpos.pinpad.PINPadOperationResult import com.cloudpos.pinpad.extend.PINPadExtendDevice import java.nio.charset.StandardCharsets class PINPadAction : ActionModel() { private var device: PINPadExtendDevice? = null private val masterKeyID = 0 private val userKeyID = 0 private val algo = 0 override fun doBefore(param: Map<String?, Any?>?, callback: ActionCallback?) { super.doBefore(param, callback) if (device == null) { device = POSTerminal.getInstance(mContext) .getDevice("cloudpos.device.pinpad") as PINPadExtendDevice } } fun open(param: Map<String?, Any?>?, callback: ActionCallback?) { try { device!!.open() sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun showText(param: Map<String?, Any?>?, callback: ActionCallback?) { try { device!!.showText(0, "密码余额元") device!!.showText(1, "show test") sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun clearText(param: Map<String?, Any?>?, callback: ActionCallback?) { try { device!!.clearText() sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun setPINLength(param: Map<String?, Any?>?, callback: ActionCallback?) { try { device!!.setPINLength(4, 12) sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun getSN(param: Map<String?, Any?>?, callback: ActionCallback?) { try { val sn = device!!.sn sendSuccessLog(mContext!!.getString(R.string.operation_succeed) + " Pinpad SN = " + sn) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun getRandom(param: Map<String?, Any?>?, callback: ActionCallback?) { try { val random = device!!.getRandom(5) sendSuccessLog(mContext!!.getString(R.string.operation_succeed) + " random = " + StringUtility.byteArray2String(random)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun updateUserKey1(param: Map<String?, Any?>?, callback: ActionCallback?) { val userKey = "09 FA 17 0B 03 11 22 76 09 FA 17 0B 03 11 22 76" // String userKey = "CF 5F B3 6E 81 DD A3 C5 B2 D9 F7 3B D9 FF C0 48"; val arryCipherNewUserKey = ByteArray(16) StringUtility.StringToByteArray(userKey, arryCipherNewUserKey) try { device!!.updateUserKey(masterKeyID, userKeyID, arryCipherNewUserKey) sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun updateUserKey2(param: Map<String?, Any?>?, callback: ActionCallback?) { val userKey = "09 FA 17 0B 03 11 22 76 09 FA 17 0B 03 11 22 76" //密文 val arryCipherNewUserKey = ByteArray(16) StringUtility.StringToByteArray(userKey, arryCipherNewUserKey) val checkValue = "A5 17 3A D5" val arryCheckValue = ByteArray(4) StringUtility.StringToByteArray(checkValue, arryCheckValue) try { device!!.updateUserKey(masterKeyID, userKeyID, arryCipherNewUserKey, PINPadDevice.CHECK_TYPE_CUP, arryCheckValue) sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun updateUserKey3(param: Map<String?, Any?>?, callback: ActionCallback?) { val userKey = "09 FA 17 0B 03 11 22 76 09 FA 17 0B 03 11 22 76" val arryCipherNewUserKey = ByteArray(16) StringUtility.StringToByteArray(userKey, arryCipherNewUserKey) val checkValue = "A5 17 3A" val arryCheckValue = ByteArray(3) StringUtility.StringToByteArray(checkValue, arryCheckValue) try { device!!.updateUserKey(masterKeyID, userKeyID, arryCipherNewUserKey, PINPadDevice.CHECK_TYPE_CUP, arryCheckValue) sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun getSessionKeyCheckValue(param: Map<String?, Any?>?, callback: ActionCallback?) { try { val getSessionKeyCheckValue = device!!.getSessionKeyCheckValue(masterKeyID, userKeyID, algo) sendSuccessLog(mContext!!.getString(R.string.operation_succeed) + " getSessionKeyCheckValue = " + StringUtility.byteArray2String(getSessionKeyCheckValue)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun encryptData(param: Map<String?, Any?>?, callback: ActionCallback?) { val keyInfo = KeyInfo(PINPadDevice.KEY_TYPE_MK_SK, 0, 2, AlgorithmConstants.ALG_3DES) val plain = byteArrayOf( 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38) val plain2 = ByteArray(888) val asda = "57 13 45 57 88 05 64 41 63 31 D2 40 52 26 20 68 10 11 00 00 0F 5F 20 0C 50 41 59 57 41 56 45 2F 56 49 53 41 5F 2A 02 01 56 5F 34 01 01 82 02 20 00 84 07 A0 00 00 00 03 10 10 95 05 00 00 00 00 00 9A 03 21 05 31 9B 02 00 00 9C 01 00 9F 01 06 00 00 00 12 34 56 9F 02 06 00 00 00 06 66 66 9F 09 02 00 96 9F 10 07 06 01 0A 03 A0 28 00 9F 15 02 33 33 9F 16 0F 31 32 33 34 35 36 37 38 20 20 20 20 20 20 20 9F 1A 02 01 56 9F 1C 08 30 30 30 30 30 30 32 35 9F 21 03 01 40 02 9F 26 08 46 29 50 27 0A 58 F8 6B 9F 27 01 80 9F 33 03 E0 F0 C8 9F 34 03 00 00 00 9F 35 01 22 9F 36 02 02 7C 9F 37 04 D2 5C 2C 9B 9F 39 01 07 9F 41 04 00 00 00 42 9F 66 04 36 20 C0 00 9F 6C 02 28 40 00 00 00" val i = StringUtility.StringToByteArray(asda, plain2) val plain3 = ByteArray(i) System.arraycopy(plain2, 0, plain3, 0, 0) try { val cipher = device!!.encryptData(keyInfo, plain3, 1, ByteArray(8), 8) sendSuccessLog(mContext!!.getString(R.string.operation_succeed) + " cipher data = " + StringUtility.byteArray2String(cipher)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun calculateMAC(param: Map<String?, Any?>?, callback: ActionCallback?) { val keyInfo = KeyInfo(PINPadDevice.KEY_TYPE_MK_SK, 0, 1, AlgorithmConstants.ALG_3DES) val arryMACInData = Common.createMasterKey(8) try { val mac = device!!.calculateMac(keyInfo, AlgorithmConstants.ALG_MAC_METHOD_X99, arryMACInData) sendSuccessLog(mContext!!.getString(R.string.operation_succeed) + " mac data = " + StringUtility.byteArray2String(mac)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } private val dukptMAC = byteArrayOf(0x34, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x39, 0x44, 0x39, 0x38, 0x37, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00) fun calculateDukptMAC(param: Map<String?, Any?>?, callback: ActionCallback?) { val keyInfo = KeyInfo(PINPadDevice.KEY_TYPE_TDUKPT_2009, 0, 0, AlgorithmConstants.ALG_3DES) try { val mac = device!!.calculateMac(keyInfo, AlgorithmConstants.ALG_MAC_METHOD_SE919, dukptMAC) sendSuccessLog(mContext!!.getString(R.string.operation_succeed) + " mac data = " + StringUtility.byteArray2String(mac)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun verifyResponseMAC(param: Map<String?, Any?>?, callback: ActionCallback?) { val keyInfo = KeyInfo(PINPadDevice.KEY_TYPE_TDUKPT_2009, masterKeyID, 0, AlgorithmConstants.ALG_3DES) try { val mac = device!!.calculateMac(keyInfo, AlgorithmConstants.ALG_MAC_METHOD_SE919, dukptMAC) sendSuccessLog(mContext!!.getString(R.string.operation_succeed) + " mac data = " + StringUtility.byteArray2String(mac)) val verifyRespMACArr = ByteArray(8) StringUtility.StringToByteArray("20 36 42 23 C1 FF 00 FA", verifyRespMACArr) //0001次的response mac val macFlag = 2 val nDirection = 0 val b = device!!.verifyResponseMac(keyInfo, dukptMAC, macFlag, verifyRespMACArr, nDirection) if (b) { sendSuccessLog(mContext!!.getString(R.string.operation_succeed) + " request mac = " + StringUtility.byteArray2String(verifyRespMACArr)) } } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun listenForPinBlock(param: Map<String?, Any?>?, callback: ActionCallback?) { val keyInfo = KeyInfo(PINPadDevice.KEY_TYPE_MK_SK, 0, 0, AlgorithmConstants.ALG_3DES) val pan = "5399834492433446" try { val listener = OperationListener { arg0 -> sendFailedLog2(arg0.resultCode.toString() + "") if (arg0.resultCode == OperationResult.SUCCESS) { val pinBlock = (arg0 as PINPadOperationResult).encryptedPINBlock sendSuccessLog2("PINBlock = " + StringUtility.byteArray2String(pinBlock)) } else { sendFailedLog2(mContext!!.getString(R.string.operation_failed)) } } device!!.listenForPinBlock(keyInfo, pan, false, listener, TimeConstants.FOREVER) sendSuccessLog("") } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun waitForPinBlock(param: Map<String?, Any?>?, callback: ActionCallback?) { val keyInfo = KeyInfo(PINPadDevice.KEY_TYPE_MK_SK, 0, 0, 4) val pan = "0123456789012345678" try { sendSuccessLog("") val operationResult: OperationResult = device!!.waitForPinBlock(keyInfo, pan, false, TimeConstants.FOREVER) if (operationResult.resultCode == OperationResult.SUCCESS) { val pinBlock = (operationResult as PINPadOperationResult).encryptedPINBlock sendSuccessLog2("PINBlock = " + StringUtility.byteArray2String(pinBlock)) } else { sendFailedLog2(mContext!!.getString(R.string.operation_failed)) } } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun setGUIConfiguration(param: Map<String?, Any?>?, callback: ActionCallback?) { try { val flag = 1 val data = ByteArray(1) data[0] = 0x01 val data2 = "test1234560".toByteArray() val b = device!!.setGUIConfiguration(flag, data) if (b) { sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } else { sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } catch (e: Exception) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } var changeSound = 1 fun setGUISound(param: Map<String?, Any?>?, callback: ActionCallback?) { try { changeSound++ val b = device!!.setGUIConfiguration("sound", if (changeSound % 2 == 0) "true" else "false") if (b) { sendSuccessLog(mContext!!.getString(R.string.operation_succeed) + "") } else { sendFailedLog(mContext!!.getString(R.string.operation_failed) + "") } } catch (e: Exception) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun setGUIStyle(param: Map<String?, Any?>?, callback: ActionCallback?) { try { val b = device!!.setGUIConfiguration("style", "dejavoozcredit") if (b) { sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } else { sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } catch (e: Exception) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun getMkStatus(param: Map<String?, Any?>?, callback: ActionCallback?) { try { val mkid = 0 val result = device!!.getMkStatus(mkid) if (result == 0) { sendSuccessLog(mContext!!.getString(R.string.operation_succeed) + ", it does not exist") } else if (result > 0) { sendSuccessLog(mContext!!.getString(R.string.operation_succeed) + ",it exist,mkid = " + mkid) } else { sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } catch (e: Exception) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun getSkStatus(param: Map<String?, Any?>?, callback: ActionCallback?) { try { val mkid = 0 val skid = 0 val result = device!!.getSkStatus(mkid, skid) if (result == 0) { sendSuccessLog(mContext!!.getString(R.string.operation_succeed) + ", it does not exist") } else if (result > 0) { sendSuccessLog(mContext!!.getString(R.string.operation_succeed) + ",it exist,mkid = " + mkid + ",skid = " + skid) } else { sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } catch (e: Exception) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun getDukptStatus(param: Map<String?, Any?>?, callback: ActionCallback?) { try { val mkid = 0 val dukptData = ByteArray(32) val result = device!!.getDukptStatus(mkid, dukptData) if (result == 0) { sendSuccessLog(mContext!!.getString(R.string.operation_succeed) + ", it does not exist") } else if (result > 0) { sendSuccessLog(mContext!!.getString(R.string.operation_succeed) + "getDukptStatus success , KSN = " + StringUtility.ByteArrayToString(dukptData, result)) } else { sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } catch (e: Exception) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun changePin(param: Map<String?, Any?>?, callback: ActionCallback?) { try { val keyInfo = KeyInfo(PINPadDevice.KEY_TYPE_MK_SK, 0, 0, AlgorithmConstants.ALG_3DES) val cardNum = "000000000000000000".toByteArray(StandardCharsets.UTF_8) val pinOld = ByteArray(32) val pinNew = ByteArray(32) val lengthResult = IntArray(2) lengthResult[0] = pinOld.size lengthResult[1] = pinNew.size val timeout = 20000 device!!.changePin(keyInfo, cardNum, pinOld, pinNew, lengthResult, timeout) sendSuccessLog(StringUtility.ByteArrayToString(pinOld, lengthResult[0])) sendSuccessLog(StringUtility.ByteArrayToString(pinNew, lengthResult[1])) sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun createPin(param: Map<String?, Any?>?, callback: ActionCallback?) { try { val keyInfo = KeyInfo(PINPadDevice.KEY_TYPE_MK_SK, 0, 0, AlgorithmConstants.ALG_3DES) val cardNum = "6210333366668888".toByteArray(StandardCharsets.UTF_8) val PinBlock = ByteArray(32) val timeout = 20000 val result = device!!.createPin(keyInfo, cardNum, PinBlock, timeout, 0) if (result >= 0) { sendSuccessLog(mContext!!.getString(R.string.operation_succeed) + "createPin success , PinBlock = " + StringUtility.ByteArrayToString(PinBlock, result)) } else { sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun selectPinblockFormat(param: Map<String?, Any?>?, callback: ActionCallback?) { try { val formatType = 0 //0-5 val result = device!!.selectPinblockFormat(formatType) if (result >= 0) { sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } else { sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun cancelRequest(param: Map<String?, Any?>?, callback: ActionCallback?) { try { device!!.cancelRequest() sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun close(param: Map<String?, Any?>?, callback: ActionCallback?) { try { device!!.close() sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } }
APIDemoForAarBykotlin/app/src/main/java/com/cloudpos/apidemo/action/PINPadAction.kt
3315294992
package com.cloudpos.apidemo.action import android.os.RemoteException import android.util.Log import com.cloudpos.* import com.cloudpos.androidmvcmodel.common.Constants import com.cloudpos.apidemoforunionpaycloudpossdk.R import com.cloudpos.fingerprint.* import com.cloudpos.mvc.base.ActionCallback import com.cloudpos.sdk.util.SystemUtil import java.util.* /** * create by rf.w 19-2-28上午10:24 */ class IsoFingerPrintAction : ActionModel() { private var device: FingerprintDevice? = null private var userID = 9 private val timeout = 60 * 1000 override fun doBefore(param: Map<String?, Any?>?, callback: ActionCallback?) { super.doBefore(param, callback) if (device == null) { device = POSTerminal.getInstance(mContext).getDevice("cloudpos.device.fingerprint") as FingerprintDevice if (SystemUtil.getProperty("wp.fingerprint.model").equals("aratek", ignoreCase = true)) { ISOFINGERPRINT_TYPE_ISO2005 = 0 } } } fun open(param: Map<String?, Any?>?, callback: ActionCallback?) { try { device!!.open(FingerprintDevice.ISO_FINGERPRINT) //清除指纹数据 device!!.delAllFingers() sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun listenForFingerprint(param: Map<String?, Any?>?, callback: ActionCallback?) { sendSuccessLog("") try { val listener = OperationListener { arg0 -> if (arg0.resultCode == OperationResult.SUCCESS) { sendSuccessLog2(mContext!!.getString(R.string.scan_fingerprint_success)) } else { sendFailedLog2(mContext!!.getString(R.string.scan_fingerprint_fail)) } } device!!.listenForFingerprint(listener, TimeConstants.FOREVER) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun waitForFingerprint(param: Map<String?, Any?>?, callback: ActionCallback?) { sendSuccessLog("") try { val operationResult = device!!.waitForFingerprint(TimeConstants.FOREVER) if (operationResult.resultCode == OperationResult.SUCCESS) { sendSuccessLog2(mContext!!.getString(R.string.scan_fingerprint_success)) } else { sendFailedLog2(mContext!!.getString(R.string.scan_fingerprint_fail)) } } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun cancelRequest(param: Map<String?, Any?>?, callback: ActionCallback?) { try { device!!.cancelRequest() sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun enroll(param: Map<String?, Any?>?, callback: ActionCallback) { try { callback.sendResponse(mContext!!.getString(R.string.press_fingerprint)) userID++ device!!.enroll(userID, timeout) sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun listenForEnroll(param: Map<String?, Any?>?, callback: ActionCallback) { try { device!!.listenForEnroll({ operationResult -> if (operationResult is FingerprintPressOperationResult) { callback.sendResponse(mContext!!.getString(R.string.press_fingerprint)) } else if (operationResult is FingerprintRemoveOperationResult) { callback.sendResponse(mContext!!.getString(R.string.remove_fingerprint)) } else if (operationResult is FingerprintNoneOperationResult) { callback.sendResponse(Constants.HANDLER_LOG_FAILED, mContext!!.getString(R.string.scan_fingerprint_fail) + ",retry") //重试 } else if (operationResult is FingerprintTimeoutOperationResult) { callback.sendResponse(Constants.HANDLER_LOG_FAILED, mContext!!.getString(R.string.enroll_timeout)) } else if (operationResult is FingerprintOperationResult) { val fingerprint = operationResult.getFingerprint(100, 100) val feature = fingerprint.feature if (feature != null) { callback.sendResponse(Constants.HANDLER_LOG_SUCCESS, "finger.length=" + feature.size) } else { callback.sendResponse(Constants.HANDLER_LOG_SUCCESS, "finger.length=null") } } }, 10000) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun verifyAgainstUserId(param: Map<String?, Any?>?, callback: ActionCallback) { callback.sendResponse(mContext!!.getString(R.string.press_fingerprint)) try { device!!.verifyAgainstUserId(userID, timeout) sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun verifyAll(param: Map<String?, Any?>?, callback: ActionCallback) { try { callback.sendResponse(mContext!!.getString(R.string.press_fingerprint)) device!!.verifyAll(timeout) sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun getId(param: Map<String?, Any?>?, callback: ActionCallback?) { try { device!!.id sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } var fingerprint1: Fingerprint? = null fun getFingerprint(param: Map<String?, Any?>?, callback: ActionCallback) { callback.sendResponse(mContext!!.getString(R.string.press_fingerprint)) try { fingerprint1 = device!!.getFingerprint(ISOFINGERPRINT_TYPE_DEFAULT) sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun verifyAgainstFingerprint(param: Map<String?, Any?>?, callback: ActionCallback) { callback.sendResponse(mContext!!.getString(R.string.press_fingerprint)) try { device!!.verifyAgainstFingerprint(fingerprint1, timeout) sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun storeFeature(param: Map<String?, Any?>?, callback: ActionCallback?) { try { device!!.storeFeature(userID, fingerprint1) sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun match(param: Map<String?, Any?>?, callback: ActionCallback) { callback.sendResponse(mContext!!.getString(R.string.press_fingerprint)) try { val fingerprint2 = device!!.getFingerprint(ISOFINGERPRINT_TYPE_ISO2005) device!!.match(fingerprint1, fingerprint2) sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun compare(param: Map<String?, Any?>?, callback: ActionCallback) { try { if (fingerprint1 == null) { sendFailedLog(mContext!!.getString(R.string.call_get_fingerprint)) } else { callback.sendResponse(mContext!!.getString(R.string.press_fingerprint)) val fingerprint2 = device!!.getFingerprint(ISOFINGERPRINT_TYPE_ISO2005) val result = device!!.compare(fingerprint1!!.feature, fingerprint2.feature) if (result == 0) { sendSuccessLog(mContext!!.getString(R.string.operation_succeed) + result) } else { sendFailedLog(mContext!!.getString(R.string.operation_failed) + result) } } } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } catch (e: RemoteException) { e.printStackTrace() } } fun identify(param: Map<String?, Any?>?, callback: ActionCallback) { try { val fpList: MutableList<*> = ArrayList<Any?>() callback.sendResponse(mContext!!.getString(R.string.press_fingerprint) + "1") fpList.add(device!!.getFingerprint(ISOFINGERPRINT_TYPE_ISO2005).feature as Nothing) callback.sendResponse(mContext!!.getString(R.string.press_fingerprint) + "2") fpList.add(device!!.getFingerprint(ISOFINGERPRINT_TYPE_ISO2005).feature as Nothing) callback.sendResponse(mContext!!.getString(R.string.press_fingerprint) + "3") fpList.add(device!!.getFingerprint(ISOFINGERPRINT_TYPE_ISO2005).feature as Nothing) callback.sendResponse(mContext!!.getString(R.string.press_fingerprint) + "4") fpList.add(device!!.getFingerprint(ISOFINGERPRINT_TYPE_ISO2005).feature as Nothing) callback.sendResponse(mContext!!.getString(R.string.waiting)) val matchResultIndex = device!!.identify(fingerprint1!!.feature, fpList, 3) Log.d("matchResultIndex", "matchResultIndex = " + matchResultIndex.size) if (matchResultIndex.size > 0) { for (index in matchResultIndex) { sendSuccessLog(mContext!!.getString(R.string.operation_succeed) + " , No." + index) } } else { sendFailedLog(mContext!!.getString(R.string.not_get_match)) } } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } catch (e: RemoteException) { e.printStackTrace() } } fun formatFingerConvert(param: Map<String?, Any?>?, callback: ActionCallback) { try { if (fingerprint1 == null) { sendFailedLog(mContext!!.getString(R.string.call_get_fingerprint)) } else { callback.sendResponse(mContext!!.getString(R.string.press_fingerprint)) val fingerprint2 = device!!.getFingerprint(ISOFINGERPRINT_TYPE_ISO2005) val ss = device!!.convertFormat(fingerprint2.feature, 0, 1) val result = device!!.compare(fingerprint1!!.feature, fingerprint2.feature as Nothing) if (result == 0) { sendSuccessLog(mContext!!.getString(R.string.operation_succeed) + result) } else { sendFailedLog(mContext!!.getString(R.string.operation_failed) + result) } } } catch (e: Exception) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun convertFormat(param: Map<String?, Any?>?, callback: ActionCallback?) { try { val fingerprint2 = Fingerprint() val arryFea = ByteArray(8192) fingerprint2.feature = arryFea device!!.convertFormat(fingerprint1, ISOFINGERPRINT_TYPE_ISO2005, fingerprint2, ISOFINGERPRINT_TYPE_DEFAULT) sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun listAllFingersStatus(param: Map<String?, Any?>?, callback: ActionCallback?) { try { device!!.listAllFingersStatus() sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun delFinger(param: Map<String?, Any?>?, callback: ActionCallback?) { try { device!!.delFinger(userID) sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun delAllFingers(param: Map<String?, Any?>?, callback: ActionCallback?) { try { device!!.delAllFingers() sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun close(param: Map<String?, Any?>?, callback: ActionCallback?) { try { device!!.close() sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } companion object { private const val ISOFINGERPRINT_TYPE_DEFAULT = 0 private var ISOFINGERPRINT_TYPE_ISO2005 = 1 private const val ISOFINGERPRINT_TYPE_ISO2015 = 2 } }
APIDemoForAarBykotlin/app/src/main/java/com/cloudpos/apidemo/action/IsoFingerPrintAction.kt
3249141797
package com.cloudpos.apidemo.action import com.cloudpos.DeviceException import com.cloudpos.POSTerminal import com.cloudpos.apidemoforunionpaycloudpossdk.R import com.cloudpos.led.LEDDevice import com.cloudpos.mvc.base.ActionCallback class LEDAction1 : ActionModel() { private var device: LEDDevice? = null private val logicalID = LEDDevice.ID_BLUE override fun doBefore(param: Map<String?, Any?>?, callback: ActionCallback?) { super.doBefore(param, callback) if (device == null) { device = POSTerminal.getInstance(mContext) .getDevice("cloudpos.device.led", logicalID) as LEDDevice } } fun open(param: Map<String?, Any?>?, callback: ActionCallback?) { try { device!!.open(logicalID) sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun getLogicalID(param: Map<String?, Any?>?, callback: ActionCallback?) { try { val logicalID = device!!.logicalID sendSuccessLog(mContext!!.getString(R.string.operation_succeed) + " Logical ID = " + logicalID) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun startBlink(param: Map<String?, Any?>?, callback: ActionCallback?) { try { device!!.startBlink(100, 100, 10) sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun cancelRequest(param: Map<String?, Any?>?, callback: ActionCallback?) { try { device!!.cancelRequest() sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun cancelBlink(param: Map<String?, Any?>?, callback: ActionCallback?) { try { device!!.cancelBlink() sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun blink(param: Map<String?, Any?>?, callback: ActionCallback?) { try { sendSuccessLog("") device!!.blink(100, 100, 100) sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun getStatus(param: Map<String?, Any?>?, callback: ActionCallback?) { try { val status = device!!.status sendSuccessLog(mContext!!.getString(R.string.operation_succeed) + " Status: " + if (status == LEDDevice.STATUS_ON) "ON" else "OFF") } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun turnOn(param: Map<String?, Any?>?, callback: ActionCallback?) { try { device!!.turnOn() sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun turnOff(param: Map<String?, Any?>?, callback: ActionCallback?) { try { device!!.turnOff() sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun close(param: Map<String?, Any?>?, callback: ActionCallback?) { try { device!!.close() sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } }
APIDemoForAarBykotlin/app/src/main/java/com/cloudpos/apidemo/action/LEDAction1.kt
628692573
package com.cloudpos.apidemo.action import com.cloudpos.* import com.cloudpos.apidemo.util.StringUtility import com.cloudpos.apidemoforunionpaycloudpossdk.R import com.cloudpos.msr.MSRDevice import com.cloudpos.msr.MSROperationResult import com.cloudpos.msr.MSRTrackData import com.cloudpos.mvc.base.ActionCallback class MSRAction : ActionModel() { // private MSRDevice device = new MSRDeviceImpl(); private var device: MSRDevice? = null override fun doBefore(param: Map<String?, Any?>?, callback: ActionCallback?) { super.doBefore(param, callback) if (device == null) { device = POSTerminal.getInstance(mContext) .getDevice("cloudpos.device.msr") as MSRDevice } } fun open(param: Map<String?, Any?>?, callback: ActionCallback?) { try { device!!.open() sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun listenForSwipe(param: Map<String?, Any?>?, callback: ActionCallback?) { try { val listener = OperationListener { arg0 -> if (arg0.resultCode == OperationResult.SUCCESS) { sendSuccessLog2(mContext!!.getString(R.string.find_card_succeed)) val data = (arg0 as MSROperationResult).msrTrackData var trackError = 0 var trackData: ByteArray? = null for (trackNo in 0..2) { trackError = data.getTrackError(trackNo) if (trackError == MSRTrackData.NO_ERROR) { trackData = data.getTrackData(trackNo) sendSuccessLog2(String.format("trackNO = %d, trackData = %s", trackNo, StringUtility.ByteArrayToString(trackData, trackData.size))) } else { sendFailedLog2(String.format("trackNO = %d, trackError = %s", trackNo, trackError)) } } } else { sendFailedLog2(mContext!!.getString(R.string.find_card_failed)) } } device!!.listenForSwipe(listener, TimeConstants.FOREVER) sendSuccessLog("") } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun waitForSwipe(param: Map<String?, Any?>?, callback: ActionCallback?) { try { sendSuccessLog("") val operationResult: OperationResult = device!!.waitForSwipe(TimeConstants.FOREVER) if (operationResult.resultCode == OperationResult.SUCCESS) { sendSuccessLog2(mContext!!.getString(R.string.find_card_succeed)) val data = (operationResult as MSROperationResult).msrTrackData var trackError = 0 var trackData: ByteArray? = null for (trackNo in 0..2) { trackError = data.getTrackError(trackNo) if (trackError == MSRTrackData.NO_ERROR) { trackData = data.getTrackData(trackNo) sendSuccessLog2(String.format("trackNO = %d, trackData = %s", trackNo, StringUtility.ByteArrayToString(trackData, trackData.size))) } else { sendFailedLog2(String.format("trackNO = %d, trackError = %s", trackNo, trackError)) } } } else { sendFailedLog2(mContext!!.getString(R.string.find_card_failed)) } } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun cancelRequest(param: Map<String?, Any?>?, callback: ActionCallback?) { try { device!!.cancelRequest() sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun close(param: Map<String?, Any?>?, callback: ActionCallback?) { try { device!!.close() sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } }
APIDemoForAarBykotlin/app/src/main/java/com/cloudpos/apidemo/action/MSRAction.kt
148792578
package com.cloudpos.apidemo.action import com.cloudpos.DeviceException import com.cloudpos.POSTerminal import com.cloudpos.apidemoforunionpaycloudpossdk.R import com.cloudpos.led.LEDDevice import com.cloudpos.mvc.base.ActionCallback class LEDAction4 : ActionModel() { // private LEDDevice device = new LEDDeviceImpl(); private var device: LEDDevice? = null private val logicalID = LEDDevice.ID_RED override fun doBefore(param: Map<String?, Any?>?, callback: ActionCallback?) { super.doBefore(param, callback) if (device == null) { device = POSTerminal.getInstance(mContext) .getDevice("cloudpos.device.led", logicalID) as LEDDevice } } fun open(param: Map<String?, Any?>?, callback: ActionCallback?) { try { device!!.open(logicalID) sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun getLogicalID(param: Map<String?, Any?>?, callback: ActionCallback?) { try { val logicalID = device!!.logicalID sendSuccessLog(mContext!!.getString(R.string.operation_succeed) + " Logical ID = " + logicalID) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun startBlink(param: Map<String?, Any?>?, callback: ActionCallback?) { try { device!!.startBlink(100, 100, 10) sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun cancelRequest(param: Map<String?, Any?>?, callback: ActionCallback?) { try { device!!.cancelRequest() sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun cancelBlink(param: Map<String?, Any?>?, callback: ActionCallback?) { try { device!!.cancelBlink() sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun blink(param: Map<String?, Any?>?, callback: ActionCallback?) { try { sendSuccessLog("") device!!.blink(100, 100, 100) sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun getStatus(param: Map<String?, Any?>?, callback: ActionCallback?) { try { val status = device!!.status sendSuccessLog(mContext!!.getString(R.string.operation_succeed) + " Status: " + if (status == LEDDevice.STATUS_ON) "ON" else "OFF") } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun turnOn(param: Map<String?, Any?>?, callback: ActionCallback?) { try { device!!.turnOn() sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun turnOff(param: Map<String?, Any?>?, callback: ActionCallback?) { try { device!!.turnOff() sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun close(param: Map<String?, Any?>?, callback: ActionCallback?) { try { device!!.close() sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } }
APIDemoForAarBykotlin/app/src/main/java/com/cloudpos/apidemo/action/LEDAction4.kt
2790611229
package com.cloudpos.apidemo.action import com.cloudpos.DeviceException import com.cloudpos.POSTerminal import com.cloudpos.apidemoforunionpaycloudpossdk.R import com.cloudpos.led.LEDDevice import com.cloudpos.mvc.base.ActionCallback class LEDAction3 : ActionModel() { // private LEDDevice device = new LEDDeviceImpl(); private var device: LEDDevice? = null private val logicalID = LEDDevice.ID_GREEN override fun doBefore(param: Map<String?, Any?>?, callback: ActionCallback?) { super.doBefore(param, callback) if (device == null) { device = POSTerminal.getInstance(mContext) .getDevice("cloudpos.device.led", logicalID) as LEDDevice } } fun open(param: Map<String?, Any?>?, callback: ActionCallback?) { try { device!!.open(logicalID) sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun getLogicalID(param: Map<String?, Any?>?, callback: ActionCallback?) { try { val logicalID = device!!.logicalID sendSuccessLog(mContext!!.getString(R.string.operation_succeed) + " Logical ID = " + logicalID) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun startBlink(param: Map<String?, Any?>?, callback: ActionCallback?) { try { device!!.startBlink(100, 100, 10) sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun cancelRequest(param: Map<String?, Any?>?, callback: ActionCallback?) { try { device!!.cancelRequest() sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun cancelBlink(param: Map<String?, Any?>?, callback: ActionCallback?) { try { device!!.cancelBlink() sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun blink(param: Map<String?, Any?>?, callback: ActionCallback?) { try { sendSuccessLog("") device!!.blink(100, 100, 100) sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun getStatus(param: Map<String?, Any?>?, callback: ActionCallback?) { try { val status = device!!.status sendSuccessLog(mContext!!.getString(R.string.operation_succeed) + " Status: " + if (status == LEDDevice.STATUS_ON) "ON" else "OFF") } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun turnOn(param: Map<String?, Any?>?, callback: ActionCallback?) { try { device!!.turnOn() sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun turnOff(param: Map<String?, Any?>?, callback: ActionCallback?) { try { device!!.turnOff() sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun close(param: Map<String?, Any?>?, callback: ActionCallback?) { try { device!!.close() sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } }
APIDemoForAarBykotlin/app/src/main/java/com/cloudpos/apidemo/action/LEDAction3.kt
1708523454
package com.cloudpos.apidemo.action import com.cloudpos.DeviceException import com.cloudpos.POSTerminal import com.cloudpos.apidemoforunionpaycloudpossdk.R import com.cloudpos.led.LEDDevice import com.cloudpos.mvc.base.ActionCallback class LEDAction2 : ActionModel() { private var device: LEDDevice? = null private val logicalID = LEDDevice.ID_YELLOW override fun doBefore(param: Map<String?, Any?>?, callback: ActionCallback?) { super.doBefore(param, callback) if (device == null) { device = POSTerminal.getInstance(mContext) .getDevice("cloudpos.device.led", logicalID) as LEDDevice } } fun open(param: Map<String?, Any?>?, callback: ActionCallback?) { try { device!!.open(logicalID) sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun getLogicalID(param: Map<String?, Any?>?, callback: ActionCallback?) { try { val logicalID = device!!.logicalID sendSuccessLog(mContext!!.getString(R.string.operation_succeed) + " Logical ID = " + logicalID) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun startBlink(param: Map<String?, Any?>?, callback: ActionCallback?) { try { device!!.startBlink(100, 100, 10) sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun cancelRequest(param: Map<String?, Any?>?, callback: ActionCallback?) { try { device!!.cancelRequest() sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun cancelBlink(param: Map<String?, Any?>?, callback: ActionCallback?) { try { device!!.cancelBlink() sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun blink(param: Map<String?, Any?>?, callback: ActionCallback?) { try { sendSuccessLog("") device!!.blink(100, 100, 100) sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun getStatus(param: Map<String?, Any?>?, callback: ActionCallback?) { try { val status = device!!.status sendSuccessLog(mContext!!.getString(R.string.operation_succeed) + " Status: " + if (status == LEDDevice.STATUS_ON) "ON" else "OFF") } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun turnOn(param: Map<String?, Any?>?, callback: ActionCallback?) { try { device!!.turnOn() sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun turnOff(param: Map<String?, Any?>?, callback: ActionCallback?) { try { device!!.turnOff() sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun close(param: Map<String?, Any?>?, callback: ActionCallback?) { try { device!!.close() sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } }
APIDemoForAarBykotlin/app/src/main/java/com/cloudpos/apidemo/action/LEDAction2.kt
3429624938
package com.cloudpos.apidemo.action import android.content.Context import android.util.Log import com.android.common.utils.special.Eth0Controller import com.cloudpos.AlgorithmConstants import com.cloudpos.DeviceException import com.cloudpos.POSTerminal import com.cloudpos.apidemo.util.ByteConvertStringUtil import com.cloudpos.apidemo.util.CAController import com.cloudpos.apidemo.util.MessageUtil import com.cloudpos.apidemoforunionpaycloudpossdk.R import com.cloudpos.hsm.HSMDevice import com.cloudpos.mvc.base.ActionCallback import org.bouncycastle.jce.PKCS10CertificationRequest import org.bouncycastle.openssl.PEMReader import java.io.ByteArrayInputStream import java.io.IOException import java.io.InputStreamReader import java.security.InvalidKeyException import java.security.NoSuchAlgorithmException import java.security.NoSuchProviderException import java.security.PublicKey import java.util.* import javax.security.auth.x500.X500Principal class HSMModel : ActionModel() { private var device: HSMDevice? = null private lateinit var CSR_buffer: ByteArray var message: String? = null var certificate: ByteArray? = null private lateinit var encryptBuffer: ByteArray override fun doBefore(param: Map<String?, Any?>?, callback: ActionCallback?) { super.doBefore(param, callback) if (device == null) { device = POSTerminal.getInstance(mContext) .getDevice("cloudpos.device.hsm") as HSMDevice } } fun open(param: Map<String?, Any?>?, callback: ActionCallback?) { try { device!!.open() sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() } } fun isTampered(param: Map<String?, Any?>?, callback: ActionCallback?) { try { val isSuccess = device!!.isTampered if (isSuccess == true) { sendSuccessLog2(mContext!!.getString(R.string.isTampered_succeed)) } else { sendFailedLog2(mContext!!.getString(R.string.isTampered_failed)) } } catch (e: DeviceException) { e.printStackTrace() sendFailedLog2(mContext!!.getString(R.string.hsm_falied)) } } fun generateKeyPair(param: Map<String?, Any?>?, callback: ActionCallback?) { try { device!!.generateKeyPair(ALIAS_PRIVATE_KEY, AlgorithmConstants.ALG_RSA, 2048) sendSuccessLog2(mContext!!.getString(R.string.generateKeyPair_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog2(mContext!!.getString(R.string.generateKeyPair_failed)) } } fun injectPublicKeyCertificate(param: Map<String?, Any?>?, callback: ActionCallback?) { try { val bufCert = generatePublicKeyCertificate(mContext) val issuccess1 = device!!.injectPublicKeyCertificate(ALIAS_PRIVATE_KEY, ALIAS_PRIVATE_KEY, bufCert, HSMDevice.CERT_FORMAT_PEM) if (issuccess1 == true) { sendSuccessLog2(mContext!!.getString(R.string.injectPublicKeyCertificate_succeed)) } else { sendFailedLog2(mContext!!.getString(R.string.injectPublicKeyCertificate_failed)) } } catch (e: DeviceException) { e.printStackTrace() sendFailedLog2(mContext!!.getString(R.string.injectPublicKeyCertificate_failed)) } } fun injectRootCertificate(param: Map<String?, Any?>?, callback: ActionCallback?) { try { val `in` = mContext!!.assets.open("testcase_comm_true.crt") val length = `in`.available() val bufCert = ByteArray(length) `in`.read(bufCert) Log.e(Eth0Controller.APP_TAG, "注入证书:文件名 :" + "testcase_comm_true.crt" + " 注入别名:" + "testcase_comm_true") // byte[] bufcert = generatePublicKeyCertificate(mContext); val issuccess2 = device!!.injectRootCertificate(HSMDevice.CERT_TYPE_COMM_ROOT, ALIAS_COMM_KEY, bufCert, HSMDevice.CERT_FORMAT_PEM) if (issuccess2 == true) { sendSuccessLog2(mContext!!.getString(R.string.injectRootCertificate_succeed)) } else { sendFailedLog2(mContext!!.getString(R.string.injectRootCertificate_failed)) } } catch (e: DeviceException) { e.printStackTrace() sendFailedLog2(mContext!!.getString(R.string.injectRootCertificate_failed)) } catch (e: IOException) { e.printStackTrace() } } fun deleteCertificate(param: Map<String?, Any?>?, callback: ActionCallback?) { try { val isSuccess3 = device!!.deleteCertificate(HSMDevice.CERT_TYPE_PUBLIC_KEY, ALIAS_PRIVATE_KEY) val isSuccess4 = device!!.deleteCertificate(HSMDevice.CERT_TYPE_COMM_ROOT, ALIAS_COMM_KEY) if (isSuccess3 == true && isSuccess4 == true) { sendSuccessLog2(mContext!!.getString(R.string.deleteCertificate_succeed)) } else { sendFailedLog2(mContext!!.getString(R.string.deleteCertificate_failed)) } } catch (e: DeviceException) { e.printStackTrace() sendFailedLog2(mContext!!.getString(R.string.deleteCertificate_failed)) } } fun decrypt(param: Map<String?, Any?>?, callback: ActionCallback?) { sendSuccessLog2(mContext!!.getString(R.string.decrypt_data)) try { CSR_buffer = device!!.generateCSR(ALIAS_PRIVATE_KEY, X500Principal("CN=T1,OU=T2,O=T3,C=T4")) val buffer = CSR_buffer val csr = MessageUtil.readPEMCertificateRequest(CSR_buffer) var publicKey: PublicKey? = null try { publicKey = csr!!.publicKey } catch (e: InvalidKeyException) { e.printStackTrace() } catch (e: NoSuchAlgorithmException) { e.printStackTrace() } catch (e: NoSuchProviderException) { e.printStackTrace() } val arryEncrypt = MessageUtil.encryptByKey("123456".toByteArray(), publicKey) Log.e("TAG", """ ${arryEncrypt!!.size} *------*${ByteConvertStringUtil.bytesToHexString(arryEncrypt)} """.trimIndent()) val plain = device!!.decrypt(AlgorithmConstants.ALG_RSA, ALIAS_PRIVATE_KEY, arryEncrypt) // String string = ByteConvertStringUtil.bytesToHexString(plain); val string = String(plain) sendSuccessLog2(mContext!!.getString(R.string.decrypt_succeed)) sendSuccessLog2(string) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog2(mContext!!.getString(R.string.decrypt_failed)) } } fun deleteKeyPair(param: Map<String?, Any?>?, callback: ActionCallback?) { try { val issuccess4 = device!!.deleteKeyPair(ALIAS_PRIVATE_KEY) if (issuccess4 == true) { sendSuccessLog2(mContext!!.getString(R.string.deleteKeyPair_succeed)) } else { sendFailedLog2(mContext!!.getString(R.string.deleteKeyPair_failed)) } } catch (e: DeviceException) { e.printStackTrace() sendFailedLog2(mContext!!.getString(R.string.deleteKeyPair_failed)) } } fun encrypt(param: Map<String?, Any?>?, callback: ActionCallback?) { try { encryptBuffer = device!!.encrypt(AlgorithmConstants.ALG_RSA, ALIAS_PRIVATE_KEY, "123456".toByteArray()) val string = ByteConvertStringUtil.bytesToHexString(encryptBuffer) sendSuccessLog2(""" ${mContext!!.getString(R.string.encrypt_succeed)} $string """.trimIndent()) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog2(mContext!!.getString(R.string.encrypt_failed)) } } fun getEncryptedUniqueCode(param: Map<String?, Any?>?, callback: ActionCallback?) { val spec = POSTerminal.getInstance(mContext).terminalSpec val uniqueCode = spec.uniqueCode try { val code = device!!.getEncryptedUniqueCode(uniqueCode, "123456") sendSuccessLog2(mContext!!.getString(R.string.getEncryptedUniqueCode_succeed)) sendSuccessLog2(code) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog2(mContext!!.getString(R.string.getEncryptedUniqueCode_failed)) } } fun queryCertificates(param: Map<String?, Any?>?, callback: ActionCallback?) { try { val alias = device!!.queryCertificates(HSMDevice.CERT_TYPE_PUBLIC_KEY) for (i in alias.indices) { } sendSuccessLog2(""" ${mContext!!.getString(R.string.queryCertificates_succeed)} ${Arrays.toString(alias)} """.trimIndent()) } catch (e: DeviceException) { sendFailedLog2(mContext!!.getString(R.string.queryCertificates_failed)) } } fun generateRandom(param: Map<String?, Any?>?, callback: ActionCallback?) { try { val buff = device!!.generateRandom(2) // String string = new String(buff); // Log.d("TAG",string); sendSuccessLog2(mContext!!.getString(R.string.generateRandom_succeed)) ByteConvertStringUtil.bytesToHexString(buff)?.let { sendSuccessLog2(it) } } catch (e: DeviceException) { e.printStackTrace() sendFailedLog2(mContext!!.getString(R.string.generateRandom_failed)) } } fun getFreeSpace(param: Map<String?, Any?>?, callback: ActionCallback?) { try { val freeSpace = device!!.freeSpace sendSuccessLog2(mContext!!.getString(R.string.getFreeSpace_succeed) + freeSpace) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog2(mContext!!.getString(R.string.getFreeSpace_failed)) } } fun generateCSR(param: Map<String?, Any?>?, callback: ActionCallback?) { try { CSR_buffer = device!!.generateCSR(ALIAS_PRIVATE_KEY, X500Principal("CN=T1,OU=T2,O=T3,C=T4")) val string = String(CSR_buffer) sendSuccessLog2(""" ${mContext!!.getString(R.string.generateCSR_succeed)} $string """.trimIndent()) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog2(mContext!!.getString(R.string.generateCSR_failed)) } } fun getCertificate(param: Map<String?, Any?>?, callback: ActionCallback?) { try { certificate = device!!.getCertificate(HSMDevice.CERT_TYPE_PUBLIC_KEY, ALIAS_PRIVATE_KEY, HSMDevice.CERT_FORMAT_PEM) Log.e("TAG", certificate.toString() + "") if (certificate != null) { val strings = String(certificate!!) sendSuccessLog2(""" ${mContext!!.getString(R.string.getCertificate_succeed)} $strings """.trimIndent()) } else { sendFailedLog2(mContext!!.getString(R.string.getCertificate_failed)) } } catch (e: DeviceException) { e.printStackTrace() sendFailedLog2(mContext!!.getString(R.string.getCertificate_failed)) } } fun cancelRequest(param: Map<String?, Any?>?, callback: ActionCallback?) { try { device!!.cancelRequest() sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun resetStatus(param: Map<String?, Any?>?, callback: ActionCallback?) { try { val bool = device!!.resetSensorStatus() if (bool) { sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } else { sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun close(param: Map<String?, Any?>?, callback: ActionCallback?) { try { device!!.close() sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun generatePublicKeyCertificate(mContext: Context?): ByteArray? { try { CSR_buffer = device!!.generateCSR(ALIAS_PRIVATE_KEY, X500Principal("CN=T1,OU=T2,O=T3,C=T4")) } catch (e: DeviceException) { e.printStackTrace() } var publicCerts: ByteArray? = null var cSRresult = ByteArray(2048) cSRresult = CSR_buffer val reader = PEMReader(InputStreamReader(ByteArrayInputStream(cSRresult))) try { val obj = reader.readObject() if (obj is PKCS10CertificationRequest) { publicCerts = CAController.getInstance().getPublicCert(mContext!!, obj) } } catch (e: Exception) { e.printStackTrace() } finally { try { reader.close() } catch (e: Exception) { e.printStackTrace() } } return publicCerts } // public int injectServerCert(String fileName, String alias, Context host, int certType){ // int result = -1; // try { // InputStream in = host.getAssets().open(fileName+".crt"); // int length = in.available(); // byte[] bufCert = new byte[length]; // in.read(bufCert); // Log.e(APP_TAG, "inject cert:fileName :"+ fileName + " alias:" + alias); // result = injectServerCert(alias, bufCert,certType); // Log.e(APP_TAG, "result = " + result); // } catch (IOException e) { // e.printStackTrace(); // } // return result; // } companion object { const val ALIAS_PRIVATE_KEY = "hsm_pri" const val ALIAS_COMM_KEY = "testcase_comm_true" } }
APIDemoForAarBykotlin/app/src/main/java/com/cloudpos/apidemo/action/HSMModel.kt
1429380012
package com.cloudpos.apidemo.action import android.graphics.* import android.os.Environment import android.util.Base64 import android.util.Log import com.askjeffreyliu.floydsteinbergdithering.Utils import com.cloudpos.* import com.cloudpos.apidemoforunionpaycloudpossdk.R import com.cloudpos.mvc.base.ActionCallback import com.cloudpos.mvc.common.Logger import com.cloudpos.printer.Format import com.cloudpos.printer.PrinterDevice import com.cloudpos.sdk.printer.impl.PrinterDeviceImpl import com.cloudpos.serialport.SerialPortDevice import com.cloudpos.serialport.SerialPortOperationResult import com.google.zxing.BarcodeFormat import com.google.zxing.EncodeHintType import com.google.zxing.WriterException import com.google.zxing.qrcode.QRCodeWriter import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel import java.io.File import java.io.FileOutputStream import java.io.IOException import java.util.* class PrinterAction : ActionModel() { private var device: PrinterDevice? = null override fun doBefore(param: Map<String?, Any?>?, callback: ActionCallback?) { super.doBefore(param, callback) if (device == null) { device = POSTerminal.getInstance(mContext) .getDevice("cloudpos.device.printer") as PrinterDevice } } fun open(param: Map<String?, Any?>?, callback: ActionCallback?) { try { device!!.open() sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun printText(param: Map<String?, Any?>?, callback: ActionCallback?) { try { device!!.printText( "Demo receipts" + "MERCHANT COPY" + "" + "MERCHANT NAME" + "SHXXXXXXCo.,LTD." + "530310041315039" + "TERMINAL NO" + "50000045" + "OPERATOR" + "50000045" + "" + "CARD NO" + "623020xxxxxx3994 I" + "ISSUER ACQUIRER" + "" + "TRANS TYPE" + "PAY SALE" + "PAY SALE" + "" + "DATE/TIME EXP DATE" + "2005/01/21 16:52:32 2099/12" + "REF NO BATCH NO" + "165232857468 000001" + "VOUCHER AUTH NO" + "000042" + "AMOUT:" + "RMB:0.01" + "" + "BEIZHU" + "SCN:01" + "UMPR NUM:4F682D56" + "TC:EF789E918A548668" + "TUR:008004E000" + "AID:A000000333010101" + "TSI:F800" + "ATC:0440" + "APPLAB:PBOC DEBIT" + "APPNAME:PBOC DEBIT" + "AIP:7C00" + "CUMR:020300" + "IAD:07010103602002010A01000000000005DD79CB" + "TermCap:EOE1C8" + "CARD HOLDER SIGNATURE" + "I ACKNOWLEDGE SATISFACTORY RECEIPT OF RELATIVE GOODS/SERVICE" + "I ACKNOWLEDGE SATISFACTORY RECEIPT OF RELATIVE GOODS/SERVICE" + "I ACKNOWLEDGE SATISFACTORY RECEIPT OF RELATIVE GOODS/SERVICE" + "" + "Demo receipts,do not sign!" + "" + "") sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun printTextForFormat(param: Map<String?, Any?>?, callback: ActionCallback?) { try { val format = Format() format.setParameter(Format.FORMAT_FONT_SIZE, Format.FORMAT_FONT_SIZE_SMALL) format.setParameter(Format.FORMAT_FONT_BOLD, Format.FORMAT_FONT_VAL_TRUE) device!!.printText(format, """ This is printTextForFormat This is printTextForFormat This is printTextForFormat This is printTextForFormat This is printTextForFormat """.trimIndent()) sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun sendESCCommand(param: Map<String?, Any?>?, callback: ActionCallback?) { val command = byteArrayOf( 0x1D.toByte(), 0x4C.toByte(), 10, 1 // (byte) 0x1B, (byte) 0x24, 10,1 ) try { device!!.sendESCCommand(command) sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun saveBitmap(bitmap: Bitmap) { val f = File(Environment.getExternalStorageDirectory().toString() + "/Download/" + System.currentTimeMillis() + ".jpg") Log.d("printermodeldemo", "save img," + f.path) if (f.exists()) { f.delete() } try { val out = FileOutputStream(f) bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out) out.flush() out.close() Log.d("printermodeldemo", "saved ok") } catch (e: IOException) { e.printStackTrace() } } fun queryStatus(param: Map<String?, Any?>?, callback: ActionCallback?) { try { val status = device!!.queryStatus() sendSuccessLog(mContext!!.getString(R.string.operation_succeed) + " Status: " + if (status == PrinterDevice.STATUS_OUT_OF_PAPER) "out of paper" else "paper exists") } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun cutPaper(param: Map<String?, Any?>?, callback: ActionCallback?) { try { device!!.cutPaper() sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun printBitmap(param: Map<String?, Any?>?, callback: ActionCallback?) { try { val format = Format() format.setParameter(Format.FORMAT_ALIGN, Format.FORMAT_ALIGN_CENTER) val bitmap = BitmapFactory.decodeStream(mContext?.resources!!.assets .open("printer_barcode_low.png")) sendSuccessLog(mContext!!.getString(R.string.operation_succeed) + "\ngetWidth = " + bitmap.getWidth() + "\ngetHeight = " + bitmap.getHeight()); } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } catch (e: IOException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun printHtml(param: Map<String?, Any?>?, callback: ActionCallback?) { try { val htmlContent1 = "<div><div><center> <font size='4'><b>ទទួលលុយវេរ </b></font></center></div><div><center> <font size='4'><b>............................................................................ </b></font></center></div><font size='4'> លេខកូដដកប្រាក់៖</font><center><div><font size='5'><b> 12941697</b></font></div></center><font size='4'> ទូរស័ព្ទអ្នកទទួល៖</font><center><div><b><font size='4'> 088-888-8888</font></b></div></center><font size='4'> ទឹកប្រាក់៖</font><center><div><b><font size='4'> 5,000 KHR</font></b></div></center><div><center><font size='3'><b>សូមពិនិត្យព័ត៌មាន និងទឹកប្រាក់មុននឹងចាកចេញ</b></font></center></div><div><center><font size='3'>............................................................................</font></center></div><div><font size='3'>ព័ត៌មានសំខាន់៖</font></div><div><font size='3'>- សូមរក្សាវិកយបត្រ មុនពេលប្រាក់ត្រូវបានដក</font></div><div><font size='3'>- លេខកូដដកប្រាក់មានសុពលភាព ៣០ថ្ងៃ</font></div><div><center><font size='3'>............................................................................</font></center></div><div><font size='3'>TID:78767485 2022-02-11 11:51 </font></div><div><center><font size='3'>............................................................................</font></center></div><div><center><font size='2'>សេវាកម្មអតិថិជន 023 220202</font></center></div><div><center><font size='2'>V2.0.0 (POS)</font></center></div></div>" // new Handler(Looper.getMainLooper()).post(new Runnable() { // @Override // public void run() { try { device!!.printHTML(mContext, htmlContent1) sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: Exception) { sendFailedLog(mContext!!.getString(R.string.operation_failed)) e.printStackTrace() } // } // }); } catch (e: Exception) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun printBarcode(param: Map<String?, Any?>?, callback: ActionCallback?) { try { val format = Format() device!!.printBarcode(format, PrinterDevice.BARCODE_CODE128, "000023123456") device!!.printText("\n\n\n") sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun cancelRequest(param: Map<String?, Any?>?, callback: ActionCallback?) { try { device!!.cancelRequest() sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun close(param: Map<String?, Any?>?, callback: ActionCallback?) { try { device!!.close() sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } companion object { /* *base64 to bitmap * import android.util.Base64; * import android.graphics.Bitmap; * import android.graphics.BitmapFactory; */ fun base64ToBitmap(base64String: String?): Bitmap { val bytes = Base64.decode(base64String, Base64.DEFAULT) return BitmapFactory.decodeByteArray(bytes, 0, bytes.size) } fun buf2StringCompact(buf: ByteArray): String { var i: Int var index: Int val sBuf = StringBuilder() sBuf.append("[") i = 0 while (i < buf.size) { index = if (buf[i] < 0) buf[i] + 256 else buf[i].toInt() if (index < 16) { sBuf.append("0").append(Integer.toHexString(index)) } else { sBuf.append(Integer.toHexString(index)) } sBuf.append(" ") i++ } val substring = sBuf.substring(0, sBuf.length - 1) return substring + "]".toUpperCase() } fun isDarkBitamp1(bitmap: Bitmap?): Boolean { var isDark = false try { if (bitmap != null) { var darkPixelCount = 0 val x = bitmap.width / 2 val y = bitmap.height / 4 //取图⽚0-width/2,竖1个像素点height/4 for (i in 0 until y) { if (bitmap.isRecycled) { break } val pixelValue = bitmap.getPixel(x, i) //取rgb值颜⾊ if (isDark(Color.red(pixelValue), Color.green(pixelValue), Color.blue(pixelValue))) { darkPixelCount++ } } isDark = darkPixelCount > y / 2 Log.i("TAG", "isDartTheme isDark $isDark darkPixelCount = $darkPixelCount") } } catch (e: Exception) { Log.e("TAG", "read wallpaper error") } return isDark } //计算像素点亮度算法 private fun isDark(r: Int, g: Int, b: Int): Boolean { return r * 0.299 + g * 0.578 + b * 0.114 < 192 } fun changeBitmapContrastBrightness(bmp: Bitmap, contrast: Float, brightness: Float): Bitmap { val cm = ColorMatrix(floatArrayOf( contrast, 0f, 0f, 0f, brightness, 0f, contrast, 0f, 0f, brightness, 0f, 0f, contrast, 0f, brightness, 0f, 0f, 0f, 1f, 0f)) val retBitmap = Bitmap.createBitmap(bmp.width, bmp.height, bmp.config) val canvas = Canvas(retBitmap) val paint = Paint() paint.colorFilter = ColorMatrixColorFilter(cm) canvas.drawBitmap(bmp, 0f, 0f, paint) return retBitmap } } }
APIDemoForAarBykotlin/app/src/main/java/com/cloudpos/apidemo/action/PrinterAction.kt
2476275603
package com.cloudpos.apidemo.action import com.cloudpos.DeviceException import com.cloudpos.OperationListener import com.cloudpos.OperationResult import com.cloudpos.POSTerminal import com.cloudpos.apidemoforunionpaycloudpossdk.R import com.cloudpos.mvc.base.ActionCallback import com.cloudpos.mvc.common.Logger import com.cloudpos.mvc.impl.ActionCallbackImpl import com.cloudpos.sdk.common.SystemProperties import com.cloudpos.serialport.SerialPortDevice import com.cloudpos.serialport.SerialPortOperationResult /** * create by rf.w 19-8-7下午3:23 */ class SerialPortAction : ActionModel() { private var device: SerialPortDevice? = null private val timeout = 5000 private val baudrate = 38400 private val testString = "cloudpos" override fun doBefore(param: Map<String?, Any?>?, callback: ActionCallback?) { super.doBefore(param, callback) if (device == null) { device = POSTerminal.getInstance(mContext).getDevice("cloudpos.device.serialport") as SerialPortDevice } } fun open(param: Map<String?, Any?>?, callback: ActionCallback?) { try { /** * int ID_USB_SLAVE_SERIAL = 0; * int ID_USB_HOST_SERIAL = 1; * int ID_SERIAL_EXT = 2; */ device!!.open(SerialPortDevice.ID_SERIAL_EXT) sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun close(param: Map<String?, Any?>?, callback: ActionCallback?) { try { device!!.close() sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun waitForRead(param: Map<String?, Any?>?, callback: ActionCallbackImpl?) { try { val arryData = ByteArray(testString.length) val serialPortOperationResult = device!!.waitForRead(arryData.size, timeout) if (serialPortOperationResult.data != null) { sendSuccessLog("Result = " + String(serialPortOperationResult.data)) sendSuccessLog(mContext!!.getString(R.string.port_waitforread_succeed)) } else { sendFailedLog(mContext!!.getString(R.string.port_waitforread_failed)) } } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun listenForRead(param: Map<String?, Any?>?, callback: ActionCallbackImpl?) { val arryData = ByteArray(testString.length) try { val listener = OperationListener { arg0 -> Logger.debug("arg0 getResultCode = " + arg0.resultCode + "") if (arg0.resultCode == OperationResult.SUCCESS) { val data = (arg0 as SerialPortOperationResult).data sendSuccessLog2(mContext!!.getString(R.string.port_listenforread_succeed)) sendSuccessLog(""" Result = ${String(data)} """.trimIndent()) } else if (arg0.resultCode == OperationResult.ERR_TIMEOUT) { val data = (arg0 as SerialPortOperationResult).data sendSuccessLog2(mContext!!.getString(R.string.port_listenforread_succeed)) sendSuccessLog(""" Result = ${String(data)} """.trimIndent()) } else { sendFailedLog2(mContext!!.getString(R.string.port_listenforread_failed)) } } device!!.write(arryData, 0, arryData.size) device!!.listenForRead(arryData.size, listener, timeout) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun write(param: Map<String?, Any?>?, callback: ActionCallbackImpl?) { try { val arryData = testString.toByteArray() val length = 5 val offset = 2 device!!.write(arryData, 0, length) sendSuccessLog2(mContext!!.getString(R.string.port_write_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } private enum class Mode { SLAVE, HOST } private fun getModelName(mode: Mode): String { // "USB_SLAVE_SERIAL" : slave mode,(USB) // "USB_HOST_SERIAL" : host mode(OTG) var deviceName: String val model = SystemProperties.getSystemPropertie("ro.wp.product.model").trim { it <= ' ' }.replace(" ", "_") if (mode == Mode.SLAVE) { deviceName = "USB_SLAVE_SERIAL" if (model.equals("W1", ignoreCase = true) || model.equals("W1V2", ignoreCase = true)) { deviceName = "DB9" } else if (model.equals("Q1", ignoreCase = true)) { deviceName = "WIZARHANDQ1" } } else { deviceName = "USB_SERIAL" if (model.equals("W1", ignoreCase = true) || model.equals("W1V2", ignoreCase = true)) { deviceName = "GS0_Q1" } } return deviceName } }
APIDemoForAarBykotlin/app/src/main/java/com/cloudpos/apidemo/action/SerialPortAction.kt
3749872537
package com.cloudpos.apidemo.action import com.cloudpos.* import com.cloudpos.apidemoforunionpaycloudpossdk.R import com.cloudpos.fingerprint.Fingerprint import com.cloudpos.fingerprint.FingerprintDevice import com.cloudpos.mvc.base.ActionCallback class FingerPrintAction : ActionModel() { private var device: FingerprintDevice? = null override fun doBefore(param: Map<String?, Any?>?, callback: ActionCallback?) { super.doBefore(param, callback) if (device == null) { device = POSTerminal.getInstance(mContext).getDevice("cloudpos.device.fingerprint") as FingerprintDevice } } fun open(param: Map<String?, Any?>?, callback: ActionCallback?) { try { device!!.open(FingerprintDevice.FINGERPRINT) sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun listenForFingerprint(param: Map<String?, Any?>?, callback: ActionCallback?) { sendSuccessLog("") try { val listener = OperationListener { arg0 -> if (arg0.resultCode == OperationResult.SUCCESS) { sendSuccessLog2(mContext!!.getString(R.string.scan_fingerprint_success)) } else { sendFailedLog2(mContext!!.getString(R.string.scan_fingerprint_fail)) } } device!!.listenForFingerprint(listener, TimeConstants.FOREVER) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun waitForFingerprint(param: Map<String?, Any?>?, callback: ActionCallback?) { sendSuccessLog("") try { val operationResult = device!!.waitForFingerprint(TimeConstants.FOREVER) if (operationResult.resultCode == OperationResult.SUCCESS) { sendSuccessLog2(mContext!!.getString(R.string.scan_fingerprint_success)) } else { sendFailedLog2(mContext!!.getString(R.string.scan_fingerprint_fail)) } } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun match(param: Map<String?, Any?>?, callback: ActionCallback?) { try { sendNormalLog(mContext!!.getString(R.string.scan_fingerprint_first)) val fingerprint1 = fingerprint sendNormalLog(mContext!!.getString(R.string.scan_fingerprint_second)) val fingerprint2 = fingerprint if (fingerprint1 != null && fingerprint2 != null) { val match = device!!.match(fingerprint1, fingerprint2) sendSuccessLog(mContext!!.getString(R.string.match_fingerprint_result) + match) } else { sendFailedLog(mContext!!.getString(R.string.match_fingerprint_fail)) } } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun cancelRequest(param: Map<String?, Any?>?, callback: ActionCallback?) { try { device!!.cancelRequest() sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun close(param: Map<String?, Any?>?, callback: ActionCallback?) { try { device!!.close() sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } private val fingerprint: Fingerprint? private get() { var fingerprint: Fingerprint? = null try { val operationResult = device!!.waitForFingerprint(TimeConstants.FOREVER) if (operationResult.resultCode == OperationResult.SUCCESS) { fingerprint = operationResult.getFingerprint(0, 0) sendSuccessLog2(mContext!!.getString(R.string.scan_fingerprint_success)) } else { sendFailedLog2(mContext!!.getString(R.string.scan_fingerprint_fail)) } } catch (e: DeviceException) { e.printStackTrace() sendFailedLog2(mContext!!.getString(R.string.operation_failed)) } return fingerprint } }
APIDemoForAarBykotlin/app/src/main/java/com/cloudpos/apidemo/action/FingerPrintAction.kt
505971677
package com.cloudpos.apidemo.action import com.cloudpos.androidmvcmodel.common.Constants import com.cloudpos.mvc.base.AbstractAction import com.cloudpos.mvc.base.ActionCallback open class ActionModel : AbstractAction() { protected var mCallback: ActionCallback? = null fun setParameter(callback: ActionCallback?) { if (mCallback == null) { mCallback = callback } } override fun doBefore(param: Map<String?, Any?>?, callback: ActionCallback?) { super.doBefore(param, callback) setParameter(callback) } fun sendSuccessLog(log: String) { // StackTraceElement[] element = Thread.currentThread().getStackTrace(); // for (StackTraceElement stackTraceElement : element) { // Log.e("DEBUG", "method: " + stackTraceElement.getMethodName()); // } mCallback!!.sendResponse(Constants.HANDLER_LOG_SUCCESS, "\t\t" + Thread.currentThread().stackTrace[3].methodName + "\t" + log) } fun sendSuccessLog2(log: String) { // StackTraceElement[] element = Thread.currentThread().getStackTrace(); // for (StackTraceElement stackTraceElement : element) { // Log.e("DEBUG", "method: " + stackTraceElement.getMethodName()); // } mCallback!!.sendResponse(Constants.HANDLER_LOG_SUCCESS, "\t\t" + log) } fun sendFailedLog(log: String) { // StackTraceElement[] element = Thread.currentThread().getStackTrace(); // for (StackTraceElement stackTraceElement : element) { // Log.e("DEBUG", "method: " + stackTraceElement.getMethodName()); // } mCallback!!.sendResponse(Constants.HANDLER_LOG_FAILED, "\t\t" + Thread.currentThread().stackTrace[3].methodName + "\t" + log) } fun sendFailedLog2(log: String) { mCallback!!.sendResponse(Constants.HANDLER_LOG_FAILED, "\t\t" + log) } fun sendNormalLog(log: String) { mCallback!!.sendResponse(Constants.HANDLER_LOG, "\t\t" + log) } }
APIDemoForAarBykotlin/app/src/main/java/com/cloudpos/apidemo/action/ActionModel.kt
3494956289
package com.cloudpos.apidemo.action import com.cloudpos.* import com.cloudpos.apidemo.common.Common import com.cloudpos.apidemo.util.StringUtility import com.cloudpos.apidemoforunionpaycloudpossdk.R import com.cloudpos.card.CPUCard import com.cloudpos.card.Card import com.cloudpos.card.SLE4442Card import com.cloudpos.mvc.base.ActionCallback import com.cloudpos.smartcardreader.SmartCardReaderDevice import com.cloudpos.smartcardreader.SmartCardReaderOperationResult /* * IC Card * */ class SmartCardAction1 : ActionModel() { private var device: SmartCardReaderDevice? = null private var icCard: Card? = null var area = SLE4442Card.MEMORY_CARD_AREA_MAIN var address = 0 var length = 10 var logicalID = SmartCardReaderDevice.ID_SMARTCARD override fun doBefore(param: Map<String?, Any?>?, callback: ActionCallback?) { super.doBefore(param, callback) if (device == null) { device = POSTerminal.getInstance(mContext) .getDevice("cloudpos.device.smartcardreader", logicalID) as SmartCardReaderDevice } } fun open(param: Map<String?, Any?>?, callback: ActionCallback?) { try { device!!.open(logicalID) sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun listenForCardPresent(param: Map<String?, Any?>?, callback: ActionCallback?) { try { val listener = OperationListener { arg0 -> if (arg0.resultCode == OperationResult.SUCCESS) { sendSuccessLog2(mContext!!.getString(R.string.find_card_succeed)) icCard = (arg0 as SmartCardReaderOperationResult).card } else { sendFailedLog2(mContext!!.getString(R.string.find_card_failed)) } } device!!.listenForCardPresent(listener, TimeConstants.FOREVER) sendSuccessLog("") } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun waitForCardPresent(param: Map<String?, Any?>?, callback: ActionCallback?) { try { sendSuccessLog("") val operationResult: OperationResult = device!!.waitForCardPresent(TimeConstants.FOREVER) if (operationResult.resultCode == OperationResult.SUCCESS) { sendSuccessLog2(mContext!!.getString(R.string.find_card_succeed)) icCard = (operationResult as SmartCardReaderOperationResult).card } else { sendFailedLog2(mContext!!.getString(R.string.find_card_failed)) } } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun listenForCardAbsent(param: Map<String?, Any?>?, callback: ActionCallback?) { try { val listener = OperationListener { arg0 -> if (arg0.resultCode == OperationResult.SUCCESS) { sendSuccessLog2(mContext!!.getString(R.string.absent_card_succeed)) icCard = null } else { sendFailedLog2(mContext!!.getString(R.string.absent_card_failed)) } } device!!.listenForCardAbsent(listener, TimeConstants.FOREVER) sendSuccessLog("") } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun waitForCardAbsent(param: Map<String?, Any?>?, callback: ActionCallback?) { try { sendSuccessLog("") val operationResult: OperationResult = device!!.waitForCardAbsent(TimeConstants.FOREVER) if (operationResult.resultCode == OperationResult.SUCCESS) { sendSuccessLog2(mContext!!.getString(R.string.absent_card_succeed)) icCard = null } else { sendFailedLog2(mContext!!.getString(R.string.absent_card_failed)) } } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun cancelRequest(param: Map<String?, Any?>?, callback: ActionCallback?) { try { device!!.cancelRequest() sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun getID(param: Map<String?, Any?>?, callback: ActionCallback?) { try { val cardID = icCard!!.id sendSuccessLog(mContext!!.getString(R.string.operation_succeed) + " Card ID = " + StringUtility.byteArray2String(cardID)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun getProtocol(param: Map<String?, Any?>?, callback: ActionCallback?) { try { val protocol = icCard!!.protocol sendSuccessLog(mContext!!.getString(R.string.operation_succeed) + " Protocol = " + protocol) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun getCardStatus(param: Map<String?, Any?>?, callback: ActionCallback?) { try { val cardStatus = icCard!!.cardStatus sendSuccessLog(mContext!!.getString(R.string.operation_succeed) + " Card Status = " + cardStatus) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun verify(param: Map<String?, Any?>?, callback: ActionCallback?) { val key = byteArrayOf( 0xFF.toByte(), 0xFF.toByte(), 0xFF.toByte(), 0xFF.toByte(), 0xFF.toByte(), 0xFF.toByte() ) try { val verifyResult = (icCard as SLE4442Card?)!!.verify(key) sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun read(param: Map<String?, Any?>?, callback: ActionCallback?) { try { val result = (icCard as SLE4442Card?)!!.read(area, address, length) sendSuccessLog(mContext!!.getString(R.string.operation_succeed) + " (" + area + ", " + address + ") memory data: " + StringUtility.byteArray2String(result)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun write(param: Map<String?, Any?>?, callback: ActionCallback?) { val arryData = Common.createMasterKey(10) try { (icCard as SLE4442Card?)!!.write(area, address, arryData) sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun connect(param: Map<String?, Any?>?, callback: ActionCallback?) { try { val atr = (icCard as CPUCard?)!!.connect() sendSuccessLog(mContext!!.getString(R.string.operation_succeed) + " ATR: " + StringUtility.byteArray2String(atr.bytes)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun transmit(param: Map<String?, Any?>?, callback: ActionCallback?) { val arryAPDU = byteArrayOf( 0x00, 0x84.toByte(), 0x00, 0x00, 0x08 ) try { val apduResponse = (icCard as CPUCard?)!!.transmit(arryAPDU) sendSuccessLog(mContext!!.getString(R.string.operation_succeed) + " APDUResponse: " + StringUtility.byteArray2String(apduResponse)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun disconnect(param: Map<String?, Any?>?, callback: ActionCallback?) { try { sendNormalLog(mContext!!.getString(R.string.rfcard_remove_card)) (icCard as CPUCard?)!!.disconnect() sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } fun close(param: Map<String?, Any?>?, callback: ActionCallback?) { try { icCard = null device!!.close() sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed)) } } }
APIDemoForAarBykotlin/app/src/main/java/com/cloudpos/apidemo/action/SmartCardAction1.kt
3675157050
package com.cloudpos.apidemo.action import com.cloudpos.* import com.cloudpos.apidemo.common.Common import com.cloudpos.apidemo.util.StringUtility import com.cloudpos.apidemoforunionpaycloudpossdk.R import com.cloudpos.card.* import com.cloudpos.mvc.base.ActionCallback import com.cloudpos.mvc.impl.ActionCallbackImpl import com.cloudpos.rfcardreader.RFCardReaderDevice import com.cloudpos.rfcardreader.RFCardReaderOperationResult class RFCardAction : ActionModel() { private var device: RFCardReaderDevice? = null var rfCard: Card? = null /*zh:需要根据实际情况调整索引. *en:The index needs to be adjusted according to the actual situation. * */ // mifare card : 2-63,012; //ultralight card : 0,4-63 var sectorIndex = 0 var blockIndex = 1 private val pinType_level3 = 2 var cardType = -1 override fun doBefore(param: Map<String?, Any?>?, callback: ActionCallback?) { super.doBefore(param, callback) if (device == null) { device = POSTerminal.getInstance(mContext) .getDevice("cloudpos.device.rfcardreader") as RFCardReaderDevice } } fun open(param: Map<String?, Any?>?, callback: ActionCallback?) { try { device!!.open() sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed) + ",sectorIndex=" + sectorIndex + ",blockIndex=" + blockIndex) } } fun listenForCardPresent(param: Map<String?, Any?>?, callback: ActionCallback?) { try { val listener = OperationListener { arg0 -> if (arg0.resultCode == OperationResult.SUCCESS) { rfCard = (arg0 as RFCardReaderOperationResult).card try { val cardTypeValue = device!!.cardTypeValue cardType = cardTypeValue[0] if (cardType == MIFARE_CARD_S50 || cardType == MIFARE_CARD_S70) { sectorIndex = 3 blockIndex = 0 //0,1,2 } else if (cardType == MIFARE_ULTRALIGHT_CARD) { sectorIndex = 0 blockIndex = 5 //4-63 } sendSuccessLog2(mContext!!.getString(R.string.find_card_succeed) + ",cardType=" + cardType + ",sectorIndex=" + sectorIndex + ",blockIndex=" + blockIndex) } catch (e: DeviceException) { e.printStackTrace() } } else { sendFailedLog2(mContext!!.getString(R.string.find_card_failed)) } } device!!.listenForCardPresent(listener, TimeConstants.FOREVER) sendSuccessLog("") } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed) + ",sectorIndex=" + sectorIndex + ",blockIndex=" + blockIndex) } } fun waitForCardPresent(param: Map<String?, Any?>?, callback: ActionCallback?) { try { sendSuccessLog("") val operationResult: OperationResult = device!!.waitForCardPresent(TimeConstants.FOREVER) if (operationResult.resultCode == OperationResult.SUCCESS) { sendSuccessLog2(mContext!!.getString(R.string.find_card_succeed)) rfCard = (operationResult as RFCardReaderOperationResult).card } else { sendFailedLog2(mContext!!.getString(R.string.find_card_failed)) } } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed) + ",sectorIndex=" + sectorIndex + ",blockIndex=" + blockIndex) } } fun listenForCardAbsent(param: Map<String?, Any?>?, callback: ActionCallback?) { try { val listener = OperationListener { arg0 -> if (arg0.resultCode == OperationResult.SUCCESS) { sendSuccessLog2(mContext!!.getString(R.string.absent_card_succeed)) rfCard = null } else { sendFailedLog2(mContext!!.getString(R.string.absent_card_failed)) } } device!!.listenForCardAbsent(listener, TimeConstants.FOREVER) sendSuccessLog("") } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed) + ",sectorIndex=" + sectorIndex + ",blockIndex=" + blockIndex) } } fun waitForCardAbsent(param: Map<String?, Any?>?, callback: ActionCallback?) { try { sendSuccessLog("") val operationResult: OperationResult = device!!.waitForCardAbsent(TimeConstants.FOREVER) if (operationResult.resultCode == OperationResult.SUCCESS) { sendSuccessLog2(mContext!!.getString(R.string.absent_card_succeed)) rfCard = null } else { sendFailedLog2(mContext!!.getString(R.string.absent_card_failed)) } } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed) + ",sectorIndex=" + sectorIndex + ",blockIndex=" + blockIndex) } } fun cancelRequest(param: Map<String?, Any?>?, callback: ActionCallback?) { try { device!!.cancelRequest() sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed) + ",sectorIndex=" + sectorIndex + ",blockIndex=" + blockIndex) } } fun getMode(param: Map<String?, Any?>?, callback: ActionCallback?) { try { val mode = device!!.mode sendSuccessLog(mContext!!.getString(R.string.operation_succeed) + " Mode = " + mode) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed) + ",sectorIndex=" + sectorIndex + ",blockIndex=" + blockIndex) } } fun setSpeed(param: Map<String?, Any?>?, callback: ActionCallback?) { try { device!!.speed = 460800 sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed) + ",sectorIndex=" + sectorIndex + ",blockIndex=" + blockIndex) } } fun getSpeed(param: Map<String?, Any?>?, callback: ActionCallback?) { try { val speed = device!!.speed sendSuccessLog(mContext!!.getString(R.string.operation_succeed) + " Speed = " + speed) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed) + ",sectorIndex=" + sectorIndex + ",blockIndex=" + blockIndex) } } fun getID(param: Map<String?, Any?>?, callback: ActionCallback?) { try { val cardID = rfCard!!.id sendSuccessLog(mContext!!.getString(R.string.operation_succeed) + " Card ID = " + StringUtility.byteArray2String(cardID)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed) + ",sectorIndex=" + sectorIndex + ",blockIndex=" + blockIndex) } } fun getProtocol(param: Map<String?, Any?>?, callback: ActionCallback?) { try { val protocol = rfCard!!.protocol sendSuccessLog(mContext!!.getString(R.string.operation_succeed) + " Protocol = " + protocol) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed) + ",sectorIndex=" + sectorIndex + ",blockIndex=" + blockIndex) } } fun getCardStatus(param: Map<String?, Any?>?, callback: ActionCallback?) { try { val cardStatus = rfCard!!.cardStatus sendSuccessLog(mContext!!.getString(R.string.operation_succeed) + " Card Status = " + cardStatus) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed) + ",sectorIndex=" + sectorIndex + ",blockIndex=" + blockIndex) } } fun verifyKeyA(param: Map<String?, Any?>?, callback: ActionCallback?) { val key = byteArrayOf( 0xFF.toByte(), 0xFF.toByte(), 0xFF.toByte(), 0xFF.toByte(), 0xFF.toByte(), 0xFF.toByte() ) try { val verifyResult = (rfCard as MifareCard?)!!.verifyKeyA(sectorIndex, key) sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed) + ",sectorIndex=" + sectorIndex + ",blockIndex=" + blockIndex) } } fun verifyKeyB(param: Map<String?, Any?>?, callback: ActionCallback?) { val key = byteArrayOf( 0xFF.toByte(), 0xFF.toByte(), 0xFF.toByte(), 0xFF.toByte(), 0xFF.toByte(), 0xFF.toByte() ) try { val verifyResult = (rfCard as MifareCard?)!!.verifyKeyB(sectorIndex, key) sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed) + ",sectorIndex=" + sectorIndex + ",blockIndex=" + blockIndex) } } fun verify_level3(param: Map<String?, Any?>?, callback: ActionCallback?) { val arryKey = byteArrayOf( 0x49.toByte(), 0x45.toByte(), 0x4D.toByte(), 0x4B.toByte(), 0x41.toByte(), 0x45.toByte(), 0x52.toByte(), 0x42.toByte(), 0x21.toByte(), 0x4E.toByte(), 0x41.toByte(), 0x43.toByte(), 0x55.toByte(), 0x4F.toByte(), 0x59.toByte(), 0x46.toByte() ) try { val verifyLevel3Result = (rfCard as MifareUltralightCard?)!!.verifyKey(arryKey) sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed) + ",sectorIndex=" + sectorIndex + ",blockIndex=" + blockIndex) } } fun transmit_level3(param: Map<String?, Any?>?, callback: ActionCallbackImpl?) { val arryAPDU = byteArrayOf( 0x30.toByte(), 0x00.toByte() ) try { var result: ByteArray? = null if (rfCard is CPUCard) { result = (rfCard as CPUCard).transmit(arryAPDU, 0) } else if (rfCard is MifareCard) { result = (rfCard as MifareCard).transmit(arryAPDU, 0) } else if (rfCard is MifareUltralightCard) { result = (rfCard as MifareUltralightCard).transmit(arryAPDU, 0) } else { //result = (Real Card Type) rfCard.transmit(arryAPDU, 0); } sendSuccessLog(mContext!!.getString(R.string.operation_succeed) + " (" + sectorIndex + ", " + blockIndex + ")transmit_level3: " + StringUtility.byteArray2String(result)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed) + ",sectorIndex=" + sectorIndex + ",blockIndex=" + blockIndex) } } fun sendControlCommand(param: Map<String?, Any?>?, callback: ActionCallbackImpl?) { val cmdID = 0x80 val command = byteArrayOf( 0x01.toByte() ) try { val result = device!!.sendControlCommand(cmdID, command) sendSuccessLog(mContext!!.getString(R.string.operation_succeed) + result) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed) + ",sectorIndex=" + sectorIndex + ",blockIndex=" + blockIndex) } } fun readBlock(param: Map<String?, Any?>?, callback: ActionCallback?) { try { val result = (rfCard as MifareCard?)!!.readBlock(sectorIndex, blockIndex) sendSuccessLog(mContext!!.getString(R.string.operation_succeed) + " (" + sectorIndex + ", " + blockIndex + ")Block data: " + StringUtility.byteArray2String(result)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed) + ",sectorIndex=" + sectorIndex + ",blockIndex=" + blockIndex) } } fun writeBlock(param: Map<String?, Any?>?, callback: ActionCallback?) { val arryData = Common.createMasterKey(16) // 随机创造16个字节的数组 try { (rfCard as MifareCard?)!!.writeBlock(sectorIndex, blockIndex, arryData) sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed) + ",sectorIndex=" + sectorIndex + ",blockIndex=" + blockIndex) } } fun readValue(param: Map<String?, Any?>?, callback: ActionCallback?) { try { val value = (rfCard as MifareCard?)!!.readValue(sectorIndex, blockIndex) sendSuccessLog(mContext!!.getString(R.string.operation_succeed) + " value = " + value.money + " user data: " + StringUtility.byteArray2String(value.userData)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed) + ",sectorIndex=" + sectorIndex + ",blockIndex=" + blockIndex) } } fun writeValue(param: Map<String?, Any?>?, callback: ActionCallback?) { try { val value = MoneyValue(byteArrayOf( 0x39.toByte() ), 1024) (rfCard as MifareCard?)!!.writeValue(sectorIndex, blockIndex, value) sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed) + ",sectorIndex=" + sectorIndex + ",blockIndex=" + blockIndex) } } fun incrementValue(param: Map<String?, Any?>?, callback: ActionCallback?) { try { (rfCard as MifareCard?)!!.increaseValue(sectorIndex, blockIndex, 10) sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed) + ",sectorIndex=" + sectorIndex + ",blockIndex=" + blockIndex) } } fun decrementValue(param: Map<String?, Any?>?, callback: ActionCallback?) { try { (rfCard as MifareCard?)!!.decreaseValue(sectorIndex, blockIndex, 10) sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed) + ",sectorIndex=" + sectorIndex + ",blockIndex=" + blockIndex) } } fun read(param: Map<String?, Any?>?, callback: ActionCallback?) { try { val result = (rfCard as MifareUltralightCard?)!!.read(blockIndex) sendSuccessLog(mContext!!.getString(R.string.operation_succeed) + " (" + sectorIndex + ", " + blockIndex + ")Block data: " + StringUtility.byteArray2String(result)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed) + ",sectorIndex=" + sectorIndex + ",blockIndex=" + blockIndex) } } fun write(param: Map<String?, Any?>?, callback: ActionCallback?) { val arryData = Common.createMasterKey(4) // 随机创造4个字节的数组 try { (rfCard as MifareUltralightCard?)!!.write(blockIndex, arryData) sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed) + ",sectorIndex=" + sectorIndex + ",blockIndex=" + blockIndex) } } fun connect(param: Map<String?, Any?>?, callback: ActionCallback?) { try { val atr = (rfCard as CPUCard?)!!.connect() sendSuccessLog(mContext!!.getString(R.string.operation_succeed) + " ATR: " + StringUtility.byteArray2String(atr.bytes)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed) + ",sectorIndex=" + sectorIndex + ",blockIndex=" + blockIndex) } } fun transmit(param: Map<String?, Any?>?, callback: ActionCallback?) { val arryAPDU = byteArrayOf( 0x00.toByte(), 0xA4.toByte(), 0x04.toByte(), 0x00.toByte(), 0x0E.toByte(), 0x32.toByte(), 0x50.toByte(), 0x41.toByte(), 0x59.toByte(), 0x2E.toByte(), 0x53.toByte(), 0x59.toByte(), 0x53.toByte(), 0x2E.toByte(), 0x44.toByte(), 0x44.toByte(), 0x46.toByte(), 0x30.toByte(), 0x31.toByte() ) //byte[] FelicaArryAPDU1 = new byte[]{(byte) 0x01, (byte) 0x00, (byte) 0x06, (byte) 0x01, (byte) 0x0B, (byte) 0x00, (byte) 0x01, (byte) 0x80, (byte) 0x04}; try { val apduResponse = (rfCard as CPUCard?)!!.transmit(arryAPDU) sendSuccessLog(mContext!!.getString(R.string.operation_succeed) + " APDUResponse: " + StringUtility.byteArray2String(apduResponse)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed) + ",sectorIndex=" + sectorIndex + ",blockIndex=" + blockIndex) } } fun disconnect(param: Map<String?, Any?>?, callback: ActionCallback?) { try { sendNormalLog(mContext!!.getString(R.string.rfcard_remove_card)) (rfCard as CPUCard?)!!.disconnect() sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed) + ",sectorIndex=" + sectorIndex + ",blockIndex=" + blockIndex) } } fun close(param: Map<String?, Any?>?, callback: ActionCallback?) { try { rfCard = null device!!.close() sendSuccessLog(mContext!!.getString(R.string.operation_succeed)) } catch (e: DeviceException) { e.printStackTrace() sendFailedLog(mContext!!.getString(R.string.operation_failed) + ",sectorIndex=" + sectorIndex + ",blockIndex=" + blockIndex) } } companion object { /* * 0x0000 CONTACTLESS_CARD_TYPE_B_CPU 0x0100 * CONTACTLESS_CARD_TYPE_A_CLASSIC_MINI 0x0001 * CONTACTLESS_CARD_TYPE_A_CLASSIC_1K 0x0002 * CONTACTLESS_CARD_TYPE_A_CLASSIC_4K 0x0003 * CONTACTLESS_CARD_TYPE_A_UL_64 0x0004 */ private const val CPU_CARD = 0 private const val MIFARE_CARD_S50 = 6 private const val MIFARE_CARD_S70 = 3 private const val MIFARE_ULTRALIGHT_CARD = 4 } }
APIDemoForAarBykotlin/app/src/main/java/com/cloudpos/apidemo/action/RFCardAction.kt
2638693428
package com.voduchuy.appcalculator import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.voduchuy.appcalculator", appContext.packageName) } }
app-calculator/app/src/androidTest/java/com/voduchuy/appcalculator/ExampleInstrumentedTest.kt
1602277277
package com.voduchuy.appcalculator import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
app-calculator/app/src/test/java/com/voduchuy/appcalculator/ExampleUnitTest.kt
1019613699
package com.voduchuy.appcalculator import androidx.room.Entity import androidx.room.PrimaryKey @Entity(tableName = "calculator") data class Calculator( @PrimaryKey(autoGenerate = true) var id: Int=0, var calculation:String?=null, var result: String?=null, var time:String?=null ) { }
app-calculator/app/src/main/java/com/voduchuy/appcalculator/Calculator.kt
1957175626
package com.voduchuy.appcalculator enum class CalculateOperation { ADDITION, SUBTRACTION, MULTIPLICATION, DIVISION, }
app-calculator/app/src/main/java/com/voduchuy/appcalculator/CalculateOperation.kt
2322064092
package com.voduchuy.appcalculator.room import androidx.lifecycle.LiveData import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import com.voduchuy.appcalculator.Calculator @Dao interface Dao { @Insert suspend fun insert(calculator: Calculator) @Query("SELECT * FROM calculator") fun realCalculator(): LiveData<List<Calculator>> }
app-calculator/app/src/main/java/com/voduchuy/appcalculator/room/Dao.kt
4190283210
package com.voduchuy.appcalculator.room import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.viewModelScope import com.voduchuy.appcalculator.Calculator import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch class HistoryViewModelFactory(private val calculateDatabase: CalculateDatabase):ViewModelProvider.Factory{ override fun <T : ViewModel> create(modelClass: Class<T>): T { return HistoryViewModel(calculateDatabase) as T } } class HistoryViewModel(private val calculateDatabase: CalculateDatabase):ViewModel() { private val listCalculate=calculateDatabase.dao().realCalculator() fun insertCalculate(calculator: Calculator){ viewModelScope.launch{ calculateDatabase.dao().insert(calculator) } } fun realCalculate():LiveData<List<Calculator>>{ return listCalculate } }
app-calculator/app/src/main/java/com/voduchuy/appcalculator/room/HistoryViewModel.kt
4237062105
package com.voduchuy.appcalculator.room import android.content.Context import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase import com.voduchuy.appcalculator.Calculator import java.math.MathContext @Database(entities = [Calculator::class], version = 1, exportSchema = false) abstract class CalculateDatabase:RoomDatabase() { abstract fun dao():Dao companion object{ @Volatile private var INSTANCE:CalculateDatabase?=null fun getCalculateDatabase(context: Context):CalculateDatabase{ var instance= INSTANCE if (instance!=null){ return instance } synchronized(this){ val newInstance=Room.databaseBuilder( context.applicationContext, CalculateDatabase::class.java, "table_calculate" ).build() instance=newInstance return newInstance } } } }
app-calculator/app/src/main/java/com/voduchuy/appcalculator/room/CalculateDatabase.kt
3639452298
package com.voduchuy.appcalculator import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.RecyclerView class CalculateAdapter():RecyclerView.Adapter<CalculateAdapter.ViewHolder>() { private var lístCalculate= mutableListOf<Calculator>() fun setList(lístCalculate:MutableList<Calculator>){ this.lístCalculate=lístCalculate notifyDataSetChanged() } class ViewHolder(itemView: View) :RecyclerView.ViewHolder(itemView) { val tvCalculation=itemView.findViewById<TextView>(R.id.tv_calculation) val tvItemResult=itemView.findViewById<TextView>(R.id.tv_item_result) val tvTime=itemView.findViewById<TextView>(R.id.tv_time) fun bind(item:Calculator){ tvCalculation.text=item.calculation tvItemResult.text= item.result.toString() tvTime.text= item.time.toString() } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view=LayoutInflater.from(parent.context).inflate(R.layout.item_calculate,parent,false) return ViewHolder(view) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { TODO("Not yet implemented") } override fun getItemCount(): Int { return lístCalculate.size } }
app-calculator/app/src/main/java/com/voduchuy/appcalculator/CalculateAdapter.kt
2893717029
package com.voduchuy.appcalculator import android.os.Bundle import androidx.activity.enableEdgeToEdge import androidx.appcompat.app.AppCompatActivity import androidx.core.view.ViewCompat import androidx.core.view.WindowInsetsCompat import androidx.lifecycle.ViewModelProvider import androidx.recyclerview.widget.LinearLayoutManager import com.voduchuy.appcalculator.databinding.ActivityHistoryBinding import com.voduchuy.appcalculator.room.CalculateDatabase import com.voduchuy.appcalculator.room.HistoryViewModel import com.voduchuy.appcalculator.room.HistoryViewModelFactory class HistoryActivity : AppCompatActivity() { private lateinit var binding: ActivityHistoryBinding private lateinit var calculateAdapter: CalculateAdapter private lateinit var historyViewModel: HistoryViewModel override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding=ActivityHistoryBinding.inflate(layoutInflater) setContentView(binding.root) val historyViewModelFactory= HistoryViewModelFactory(CalculateDatabase.getCalculateDatabase(this)) historyViewModel= ViewModelProvider(this,historyViewModelFactory)[HistoryViewModel::class.java] calculateAdapter= CalculateAdapter() binding.recyclerCalculator.layoutManager=LinearLayoutManager(this) binding.recyclerCalculator.adapter=calculateAdapter historyViewModel.realCalculate().observe(this){ calculateAdapter.setList(it as MutableList<Calculator>) } } }
app-calculator/app/src/main/java/com/voduchuy/appcalculator/HistoryActivity.kt
3474749312
package com.voduchuy.appcalculator import android.annotation.SuppressLint import android.os.Bundle import android.util.Log import androidx.activity.enableEdgeToEdge import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.ViewModelProvider import com.voduchuy.appcalculator.databinding.ActivityCalculateBinding import com.voduchuy.appcalculator.room.CalculateDatabase import com.voduchuy.appcalculator.room.HistoryViewModel import com.voduchuy.appcalculator.room.HistoryViewModelFactory class CalculateActivity : AppCompatActivity() { private lateinit var binding: ActivityCalculateBinding private lateinit var historyViewModel: HistoryViewModel override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityCalculateBinding.inflate(layoutInflater) setContentView(binding.root) val historyViewModelFactory=HistoryViewModelFactory(CalculateDatabase.getCalculateDatabase(this)) historyViewModel=ViewModelProvider(this,historyViewModelFactory)[HistoryViewModel::class.java] setCalculation() deleteCalculation() showResult() } private fun showResult() { binding.btnResult.setOnClickListener { val input = binding.edtCalculation.text.toString() val numbers = input.split("[+\\-x/]".toRegex()).map { it.toInt() }.toMutableList() val operators = input.split("\\d+".toRegex()).filter { it.isNotBlank() } var result = numbers.first() for (i in operators.indices) { val operator = operators[i] val nextNumber = numbers[i + 1] // Perform operation based on the current operator result = when (operator) { "+" -> operationInt(CalculateOperation.ADDITION, result, nextNumber) "-" -> operationInt(CalculateOperation.SUBTRACTION, result, nextNumber) "x" -> operationInt(CalculateOperation.MULTIPLICATION, result, nextNumber) "/" -> operationInt(CalculateOperation.DIVISION, result, nextNumber) else -> { // Handle unknown operators Log.d("operators", "Unknown operator: $operator") result // Keep the result unchanged } } } binding.tvResult.text = result.toString() val time=System.currentTimeMillis() historyViewModel.insertCalculate(Calculator(calculation = input, result = result, time = time)) } } private fun deleteCalculation() { binding.btnDelete.setOnClickListener { val calculation = binding.edtCalculation.text.toString() if (calculation.isNotEmpty()) { val currentText = calculation.length val newText = calculation.substring(0, currentText - 1) binding.edtCalculation.setText(newText) } } } @SuppressLint("SetTextI18n") private fun setCalculation() { binding.btn0.setOnClickListener { val btn0 = binding.btn0.text.toString() binding.edtCalculation.append(btn0) } binding.btn1.setOnClickListener { val btn1 = binding.btn1.text.toString() binding.edtCalculation.append(btn1) } binding.btn2.setOnClickListener { val btn2 = binding.btn2.text.toString() binding.edtCalculation.append(btn2) } binding.btn3.setOnClickListener { val btn3 = binding.btn3.text.toString() binding.edtCalculation.append(btn3) } binding.btn4.setOnClickListener { val btn4 = binding.btn4.text.toString() binding.edtCalculation.append(btn4) } binding.btn5.setOnClickListener { val btn5 = binding.btn5.text.toString() binding.edtCalculation.append(btn5) } binding.btn6.setOnClickListener { val btn6 = binding.btn6.text.toString() binding.edtCalculation.append(btn6) } binding.btn7.setOnClickListener { val btn7 = binding.btn7.text.toString() binding.edtCalculation.append(btn7) } binding.btn8.setOnClickListener { val btn8 = binding.btn8.text.toString() binding.edtCalculation.append(btn8) } binding.btn9.setOnClickListener { val btn9 = binding.btn9.text.toString() binding.edtCalculation.append(btn9) } binding.btnAddition.setOnClickListener { onClickCalculation('+') } binding.btnSubtraction.setOnClickListener { onClickCalculation('-') } binding.btnMultiplication.setOnClickListener { onClickCalculation('x') } binding.btnDivision.setOnClickListener { onClickCalculation('/') } } private fun operationInt( calculateOperation: CalculateOperation, number1: Int, number2: Int ): Int { return when (calculateOperation) { CalculateOperation.ADDITION -> number1 + number2 CalculateOperation.SUBTRACTION -> number1 - number2 CalculateOperation.MULTIPLICATION -> number1 * number2 CalculateOperation.DIVISION -> number1 / number2 } } private fun operationDouble( calculateOperation: CalculateOperation, number1: Double, number2: Double ): Double { return when (calculateOperation) { CalculateOperation.ADDITION -> number1 + number2 CalculateOperation.SUBTRACTION -> number1 - number2 CalculateOperation.MULTIPLICATION -> number1 * number2 CalculateOperation.DIVISION -> number1 / number2 } } private fun onClickCalculation(char: Char) { val currentText = binding.edtCalculation.text.toString() if (currentText.isNotEmpty()) { val lastChar = currentText.last() if (lastChar == '+' || lastChar == '-' || lastChar == 'x' || lastChar == '/') { val newText = currentText.substring(0, currentText.length - 1) + char binding.edtCalculation.setText(newText) } else { val newText = currentText.substring(0, currentText.length) + char binding.edtCalculation.setText(newText) } } } }
app-calculator/app/src/main/java/com/voduchuy/appcalculator/CalculateActivity.kt
3115641314
package com.nexus.farmap.newui class NewUI { }
nexus-farmap/app/src/main/java/com/nexus/farmap/newui/NewUI.kt
205971884
package com.nexus.farmap.newui.arnavigation
nexus-farmap/app/src/main/java/com/nexus/farmap/newui/arnavigation/ARNav.kt
685549071
package com.nexus.farmap.newui.startup
nexus-farmap/app/src/main/java/com/nexus/farmap/newui/startup/StartUp.kt
499597626
package com.nexus.farmap.newui.placeselect
nexus-farmap/app/src/main/java/com/nexus/farmap/newui/placeselect/PlaceSelect.kt
3123276182
package com.nexus.farmap.data.repository import com.nexus.farmap.data.App import com.nexus.farmap.data.model.TreeNodeDto import com.nexus.farmap.domain.repository.GraphRepository import com.nexus.farmap.domain.tree.TreeNode import com.nexus.farmap.domain.use_cases.convert import com.nexus.farmap.domain.use_cases.opposite import dev.romainguy.kotlin.math.Float3 import dev.romainguy.kotlin.math.Quaternion import io.github.sceneview.math.toFloat3 import io.github.sceneview.math.toOldQuaternion import io.github.sceneview.math.toVector3 class GraphImpl : GraphRepository { private val dao = App.instance?.getDatabase()?.graphDao!! override suspend fun getNodes(): List<TreeNodeDto> { return dao.getNodes() ?: listOf() } override suspend fun insertNodes( nodes: List<TreeNode>, translocation: Float3, rotation: Quaternion, pivotPosition: Float3 ) { val transNodes = nodes.toMutableList() val undoTranslocation = translocation * -1f val undoQuaternion = rotation.opposite() dao.insertNodes(transNodes.map { node -> when (node) { is TreeNode.Entry -> { TreeNodeDto.fromTreeNode( node = node, position = undoPositionConvert( node.position, undoTranslocation, undoQuaternion, pivotPosition ), forwardVector = node.forwardVector.convert(undoQuaternion) ) } is TreeNode.Path -> { TreeNodeDto.fromTreeNode( node = node, position = undoPositionConvert( node.position, undoTranslocation, undoQuaternion, pivotPosition ) ) } } }) } override suspend fun deleteNodes(nodes: List<TreeNode>) { dao.deleteNodes(nodes.map { node -> TreeNodeDto.fromTreeNode(node) }) } override suspend fun updateNodes( nodes: List<TreeNode>, translocation: Float3, rotation: Quaternion, pivotPosition: Float3 ) { val transNodes = nodes.toMutableList() val undoTranslocation = translocation * -1f val undoQuarterion = rotation.opposite() dao.updateNodes(transNodes.map { node -> when (node) { is TreeNode.Entry -> { TreeNodeDto.fromTreeNode( node = node, position = undoPositionConvert( node.position, undoTranslocation, undoQuarterion, pivotPosition ), forwardVector = node.forwardVector.convert(undoQuarterion) ) } is TreeNode.Path -> { TreeNodeDto.fromTreeNode( node = node, position = undoPositionConvert( node.position, undoTranslocation, undoQuarterion, pivotPosition ) ) } } }) } override suspend fun clearNodes() { dao.clearNodes() } private fun undoPositionConvert( position: Float3, translocation: Float3, quaternion: Quaternion, pivotPosition: Float3 ): Float3 { return (com.google.ar.sceneform.math.Quaternion.rotateVector( quaternion.toOldQuaternion(), (position - pivotPosition - translocation).toVector3() ).toFloat3() + pivotPosition) } }
nexus-farmap/app/src/main/java/com/nexus/farmap/data/repository/GraphImpl.kt
2075227562
package com.nexus.farmap.data import android.app.Application import androidx.room.Room import com.nexus.farmap.data.data_source.GraphDatabase import com.nexus.farmap.data.ml.classification.TextAnalyzer import com.nexus.farmap.data.pathfinding.AStarImpl import com.nexus.farmap.data.repository.GraphImpl import com.nexus.farmap.domain.tree.Tree import com.nexus.farmap.domain.use_cases.* class App : Application() { private lateinit var database: GraphDatabase private lateinit var repository: GraphImpl private lateinit var tree: Tree lateinit var findWay: FindWay private lateinit var pathfinder: AStarImpl lateinit var hitTest: HitTest private lateinit var objectDetector: TextAnalyzer lateinit var analyzeImage: AnalyzeImage lateinit var getDestinationDesc: GetDestinationDesc lateinit var smoothPath: SmoothPath override fun onCreate() { super.onCreate() instance = this database = Room.databaseBuilder(this, GraphDatabase::class.java, DATABASE_NAME) //.createFromAsset(DATABASE_DIR) .allowMainThreadQueries().build() repository = GraphImpl() tree = Tree(repository) smoothPath = SmoothPath() pathfinder = AStarImpl() findWay = FindWay(pathfinder) hitTest = HitTest() objectDetector = TextAnalyzer() analyzeImage = AnalyzeImage(objectDetector) getDestinationDesc = GetDestinationDesc() } fun getDatabase(): GraphDatabase { return database } fun getTree(): Tree { return tree } companion object { var instance: App? = null const val DATABASE_NAME = "nodes" const val DATABASE_DIR = "database/nodes.db" const val ADMIN_MODE = "ADMIN" const val USER_MODE = "USER" var mode = ADMIN_MODE } }
nexus-farmap/app/src/main/java/com/nexus/farmap/data/App.kt
247382506
package com.nexus.farmap.data.data_source import androidx.room.* import com.nexus.farmap.data.model.TreeNodeDto @Dao interface GraphDao { @Query("SELECT * FROM treenodedto") fun getNodes(): List<TreeNodeDto>? @Insert(onConflict = OnConflictStrategy.REPLACE) fun insertNodes(nodes: List<TreeNodeDto>) @Delete fun deleteNodes(nodes: List<TreeNodeDto>) @Update(onConflict = OnConflictStrategy.REPLACE) fun updateNodes(nodes: List<TreeNodeDto>) @Query("DELETE FROM treenodedto") fun clearNodes() }
nexus-farmap/app/src/main/java/com/nexus/farmap/data/data_source/GraphDao.kt
343462125
package com.nexus.farmap.data.data_source import androidx.room.Database import androidx.room.RoomDatabase import androidx.room.TypeConverters import com.nexus.farmap.data.model.NeighboursConverter import com.nexus.farmap.data.model.TreeNodeDto @Database( entities = [TreeNodeDto::class], version = 1 ) @TypeConverters(NeighboursConverter::class) abstract class GraphDatabase : RoomDatabase() { abstract val graphDao: GraphDao companion object { const val DATABASE_NAME = "gdb" } }
nexus-farmap/app/src/main/java/com/nexus/farmap/data/data_source/GraphDatabase.kt
1763120903
package com.nexus.farmap.data.pathfinding import com.nexus.farmap.domain.tree.TreeNode import kotlin.math.abs class AStarNode( val node: TreeNode, finalNode: AStarNode? ) { var g = 0f private set var f = 0f private set var h = 0f private set var parent: AStarNode? = null private set init { finalNode?.let { calculateHeuristic(finalNode) } } fun calculateHeuristic(finalNode: AStarNode) { h = abs(finalNode.node.position.x - node.position.x) + abs(finalNode.node.position.y - node.position.y) + abs( finalNode.node.position.z - node.position.z ) } fun setNodeData(currentNode: AStarNode, cost: Float) { g = currentNode.g + cost parent = currentNode calculateFinalCost() } fun checkBetterPath(currentNode: AStarNode, cost: Float): Boolean { val gCost = currentNode.g + cost if (gCost < g) { setNodeData(currentNode, cost) return true } return false } private fun calculateFinalCost() { f = g + h } override fun equals(other: Any?): Boolean { val otherNode: AStarNode? = other as AStarNode? otherNode?.let { return this.node == otherNode.node } return false } }
nexus-farmap/app/src/main/java/com/nexus/farmap/data/pathfinding/AStarNode.kt
829548030
package com.nexus.farmap.data.pathfinding import com.nexus.farmap.data.App import com.nexus.farmap.domain.pathfinding.Path import com.nexus.farmap.domain.pathfinding.Pathfinder import com.nexus.farmap.domain.tree.Tree class AStarImpl : Pathfinder { private val smoothPath = App.instance!!.smoothPath override suspend fun findWay(from: String, to: String, tree: Tree): Path? { val finalNode = AStarNode(tree.getEntry(to)!!, null) val initialNode = AStarNode(tree.getEntry(from)!!, finalNode) val openList: MutableList<AStarNode> = mutableListOf() val closedSet: MutableSet<AStarNode> = mutableSetOf() openList.add(initialNode) while (openList.isNotEmpty()) { val currentNode = getNextAStarNode(openList) openList.remove(currentNode) closedSet.add(currentNode) if (currentNode == finalNode) { return Path(smoothPath(getPath(currentNode).map { aStarNode -> aStarNode.node })) } else { addAdjacentNodes(currentNode, openList, closedSet, finalNode, tree) } } return null } private fun getPath(node: AStarNode): List<AStarNode> { var currentNode = node val path: MutableList<AStarNode> = mutableListOf() path.add(currentNode) while (currentNode.parent != null) { path.add(0, currentNode.parent!!) currentNode = currentNode.parent!! } return path } private fun addAdjacentNodes( currentNode: AStarNode, openList: MutableList<AStarNode>, closedSet: Set<AStarNode>, finalNode: AStarNode, tree: Tree ) { currentNode.node.neighbours.forEach { nodeId -> tree.getNode(nodeId)?.let { node -> val nodeClosed = closedSet.find { it.node.id == nodeId } val nodeOpen = openList.find { it.node.id == nodeId } if (nodeClosed == null && nodeOpen == null) { checkNode(currentNode, AStarNode(node, finalNode), openList, closedSet) } else if (nodeOpen != null && nodeClosed == null) { checkNode(currentNode, nodeOpen, openList, closedSet) } } } } private fun checkNode( parentNode: AStarNode, node: AStarNode, openList: MutableList<AStarNode>, closedSet: Set<AStarNode> ) { if (!closedSet.contains(node)) { if (!openList.contains(node)) { node.setNodeData(parentNode, 1f) openList.add(node) } else { node.checkBetterPath(parentNode, 1f) } } } private fun getNextAStarNode(openList: List<AStarNode>): AStarNode { return openList.sortedBy { node -> node.f }[0] } }
nexus-farmap/app/src/main/java/com/nexus/farmap/data/pathfinding/AStarImpl.kt
454987697
package com.nexus.farmap.data.utils sealed class Reaction<out T> { data class Success<out T>(val data: T) : Reaction<T>() data class Error(val error: Exception) : Reaction<Nothing>() }
nexus-farmap/app/src/main/java/com/nexus/farmap/data/utils/Reaction.kt
4033653855
package com.nexus.farmap.data.ml.classification import android.graphics.Bitmap import android.graphics.Rect import android.media.Image import com.nexus.farmap.data.ml.classification.utils.ImageUtils import com.nexus.farmap.data.model.DetectedObjectResult import com.nexus.farmap.domain.ml.ObjectDetector import com.google.mlkit.vision.common.InputImage import com.google.mlkit.vision.text.Text import com.google.mlkit.vision.text.TextRecognition import com.google.mlkit.vision.text.latin.TextRecognizerOptions import dev.romainguy.kotlin.math.Float2 import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.tasks.await import kotlinx.coroutines.withContext /** * Analyzes the frames passed in from the camera and returns any detected text within the requested * crop region. */ class TextAnalyzer : ObjectDetector { private val options = TextRecognizerOptions.Builder().build() private val detector = TextRecognition.getClient(options) override suspend fun analyze( mediaImage: Image, rotationDegrees: Int, imageCropPercentages: Pair<Int, Int>, displaySize: Pair<Int, Int> ): Result<DetectedObjectResult> { var text: Text? var cropRect: Rect? var croppedBit: Bitmap? withContext(Dispatchers.Default) { // Calculate the actual ratio from the frame to appropriately // crop the image. val imageHeight = mediaImage.height val imageWidth = mediaImage.width val actualAspectRatio = imageWidth / imageHeight val convertImageToBitmap = ImageUtils.convertYuv420888ImageToBitmap(mediaImage) cropRect = Rect(0, 0, imageWidth, imageHeight) // In case image has wider aspect ratio, then crop less the height. // In case image has taller aspect ratio, just handle it as is. var currentCropPercentages = imageCropPercentages if (actualAspectRatio > 3) { val originalHeightCropPercentage = currentCropPercentages.first val originalWidthCropPercentage = currentCropPercentages.second currentCropPercentages = Pair(originalHeightCropPercentage / 2, originalWidthCropPercentage) } // Image rotation compensation. Swapping height and width on landscape orientation. val cropPercentages = currentCropPercentages val heightCropPercent = cropPercentages.first val widthCropPercent = cropPercentages.second val (widthCrop, heightCrop) = when (rotationDegrees) { 90, 270 -> Pair(heightCropPercent / 100f, widthCropPercent / 100f) else -> Pair(widthCropPercent / 100f, heightCropPercent / 100f) } cropRect!!.inset( (imageWidth * widthCrop / 2).toInt(), (imageHeight * heightCrop / 2).toInt() ) val croppedBitmap = ImageUtils.rotateAndCrop(convertImageToBitmap, rotationDegrees, cropRect!!) croppedBit = croppedBitmap text = detector.process(InputImage.fromBitmap(croppedBitmap, 0)).await() } return if (text != null) { if (text!!.textBlocks.isNotEmpty()) { val textBlock = text!!.textBlocks.firstOrNull { textBlock -> usingFormat(textBlock) } if (textBlock != null) { val boundingBox = textBlock.boundingBox if (boundingBox != null) { val croppedRatio = Float2( boundingBox.centerX() / croppedBit!!.width.toFloat(), boundingBox.centerY() / croppedBit!!.height.toFloat() ) val x = displaySize.first * croppedRatio.x val y = displaySize.second * croppedRatio.y Result.success( DetectedObjectResult( label = textBlock.text, centerCoordinate = Float2(x, y) ) ) } else { Result.failure(Exception("Cant detect bounding box")) } } else { Result.failure(Exception("No digits found")) } } else { Result.failure(Exception("No detected objects")) } } else { Result.failure(Exception("Null text")) } } private fun usingFormat(text: Text.TextBlock): Boolean { return text.text[0].isLetterOrDigit() } }
nexus-farmap/app/src/main/java/com/nexus/farmap/data/ml/classification/TextAnalyzer.kt
716042741
package com.nexus.farmap.data.ml.classification.utils import android.graphics.Bitmap import android.graphics.ImageFormat import android.graphics.Matrix import android.graphics.Rect import android.media.Image import androidx.annotation.ColorInt import java.io.ByteArrayOutputStream object ImageUtils { /** * Creates a new [Bitmap] by rotating the input bitmap [rotation] degrees. * If [rotation] is 0, the input bitmap is returned. */ fun rotateBitmap(bitmap: Bitmap, rotation: Int): Bitmap { if (rotation == 0) return bitmap val matrix = Matrix() matrix.postRotate(rotation.toFloat()) return Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, matrix, false) } /** * Converts a [Bitmap] to [ByteArray] using [Bitmap.compress]. */ fun Bitmap.toByteArray(): ByteArray = ByteArrayOutputStream().use { stream -> this.compress(Bitmap.CompressFormat.JPEG, 100, stream) stream.toByteArray() } private val CHANNEL_RANGE = 0 until (1 shl 18) fun convertYuv420888ImageToBitmap(image: Image): Bitmap { require(image.format == ImageFormat.YUV_420_888) { "Unsupported image format $(image.format)" } val planes = image.planes // Because of the variable row stride it's not possible to know in // advance the actual necessary dimensions of the yuv planes. val yuvBytes = planes.map { plane -> val buffer = plane.buffer val yuvBytes = ByteArray(buffer.capacity()) buffer[yuvBytes] buffer.rewind() // Be kind… yuvBytes } val yRowStride = planes[0].rowStride val uvRowStride = planes[1].rowStride val uvPixelStride = planes[1].pixelStride val width = image.width val height = image.height @ColorInt val argb8888 = IntArray(width * height) var i = 0 for (y in 0 until height) { val pY = yRowStride * y val uvRowStart = uvRowStride * (y shr 1) for (x in 0 until width) { val uvOffset = (x shr 1) * uvPixelStride argb8888[i++] = yuvToRgb( yuvBytes[0][pY + x].toIntUnsigned(), yuvBytes[1][uvRowStart + uvOffset].toIntUnsigned(), yuvBytes[2][uvRowStart + uvOffset].toIntUnsigned() ) } } val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888) bitmap.setPixels(argb8888, 0, width, 0, 0, width, height) return bitmap } fun rotateAndCrop( bitmap: Bitmap, imageRotationDegrees: Int, cropRect: Rect ): Bitmap { val matrix = Matrix() matrix.preRotate(imageRotationDegrees.toFloat()) return Bitmap.createBitmap( bitmap, cropRect.left, cropRect.top, cropRect.width(), cropRect.height(), matrix, true ) } @ColorInt private fun yuvToRgb(nY: Int, nU: Int, nV: Int): Int { var nY = nY var nU = nU var nV = nV nY -= 16 nU -= 128 nV -= 128 nY = nY.coerceAtLeast(0) // This is the floating point equivalent. We do the conversion in integer // because some Android devices do not have floating point in hardware. // nR = (int)(1.164 * nY + 2.018 * nU); // nG = (int)(1.164 * nY - 0.813 * nV - 0.391 * nU); // nB = (int)(1.164 * nY + 1.596 * nV); var nR = 1192 * nY + 1634 * nV var nG = 1192 * nY - 833 * nV - 400 * nU var nB = 1192 * nY + 2066 * nU // Clamp the values before normalizing them to 8 bits. nR = nR.coerceIn(CHANNEL_RANGE) shr 10 and 0xff nG = nG.coerceIn(CHANNEL_RANGE) shr 10 and 0xff nB = nB.coerceIn(CHANNEL_RANGE) shr 10 and 0xff return -0x1000000 or (nR shl 16) or (nG shl 8) or nB } } private fun Byte.toIntUnsigned(): Int { return toInt() and 0xFF }
nexus-farmap/app/src/main/java/com/nexus/farmap/data/ml/classification/utils/ImageUtils.kt
3185327492
package com.nexus.farmap.data.ml.classification.utils object VertexUtils { /** * Rotates a coordinate pair according to [imageRotation]. */ fun Pair<Int, Int>.rotateCoordinates( imageWidth: Int, imageHeight: Int, imageRotation: Int, ): Pair<Int, Int> { val (x, y) = this return when (imageRotation) { 0 -> x to y 180 -> imageWidth - x to imageHeight - y 90 -> y to imageWidth - x 270 -> imageHeight - y to x else -> error("Invalid imageRotation $imageRotation") } } }
nexus-farmap/app/src/main/java/com/nexus/farmap/data/ml/classification/utils/VertexUtils.kt
2069768871
package com.nexus.farmap.data.ml.classification import android.content.Context import android.graphics.Bitmap import android.graphics.ImageFormat import android.graphics.Rect import android.media.Image import android.renderscript.Allocation import android.renderscript.Element import android.renderscript.RenderScript import android.renderscript.ScriptIntrinsicYuvToRGB import android.renderscript.Type /** * Helper class used to efficiently convert a [Media.Image] object from * [ImageFormat.YUV_420_888] format to an RGB [Bitmap] object. * * The [yuvToRgb] method is able to achieve the same FPS as the CameraX image * analysis use case on a Pixel 3 XL device at the default analyzer resolution, * which is 30 FPS with 640x480. * * NOTE: This has been tested in a limited number of devices and is not * considered production-ready code. It was created for illustration purposes, * since this is not an efficient camera pipeline due to the multiple copies * required to convert each frame. */ class YuvToRgbConverter(context: Context) { private val rs = RenderScript.create(context) private val scriptYuvToRgb = ScriptIntrinsicYuvToRGB.create(rs, Element.U8_4(rs)) private var pixelCount: Int = -1 private lateinit var yuvBuffer: ByteArray private lateinit var inputAllocation: Allocation private lateinit var outputAllocation: Allocation @Synchronized fun yuvToRgb(image: Image, output: Bitmap) { // Ensure that the intermediate output byte buffer is allocated if (!::yuvBuffer.isInitialized) { pixelCount = image.width * image.height // Bits per pixel is an average for the whole image, so it's useful to compute the size // of the full buffer but should not be used to determine pixel offsets val pixelSizeBits = ImageFormat.getBitsPerPixel(ImageFormat.YUV_420_888) yuvBuffer = ByteArray(pixelCount * pixelSizeBits / 8) } // Get the YUV data in byte array form using NV21 format imageToByteArray(image, yuvBuffer) // Ensure that the RenderScript inputs and outputs are allocated if (!::inputAllocation.isInitialized) { // Explicitly create an element with type NV21, since that's the pixel format we use val elemType = Type.Builder(rs, Element.YUV(rs)).setYuvFormat(ImageFormat.NV21).create() inputAllocation = Allocation.createSized(rs, elemType.element, yuvBuffer.size) } if (!::outputAllocation.isInitialized) { outputAllocation = Allocation.createFromBitmap(rs, output) } // Convert NV21 format YUV to RGB inputAllocation.copyFrom(yuvBuffer) scriptYuvToRgb.setInput(inputAllocation) scriptYuvToRgb.forEach(outputAllocation) outputAllocation.copyTo(output) } private fun imageToByteArray(image: Image, outputBuffer: ByteArray) { assert(image.format == ImageFormat.YUV_420_888) val imageCrop = Rect(0, 0, image.width, image.height) val imagePlanes = image.planes imagePlanes.forEachIndexed { planeIndex, plane -> // How many values are read in input for each output value written // Only the Y plane has a value for every pixel, U and V have half the resolution i.e. // // Y Plane U Plane V Plane // =============== ======= ======= // Y Y Y Y Y Y Y Y U U U U V V V V // Y Y Y Y Y Y Y Y U U U U V V V V // Y Y Y Y Y Y Y Y U U U U V V V V // Y Y Y Y Y Y Y Y U U U U V V V V // Y Y Y Y Y Y Y Y // Y Y Y Y Y Y Y Y // Y Y Y Y Y Y Y Y val outputStride: Int // The index in the output buffer the next value will be written at // For Y it's zero, for U and V we start at the end of Y and interleave them i.e. // // First chunk Second chunk // =============== =============== // Y Y Y Y Y Y Y Y V U V U V U V U // Y Y Y Y Y Y Y Y V U V U V U V U // Y Y Y Y Y Y Y Y V U V U V U V U // Y Y Y Y Y Y Y Y V U V U V U V U // Y Y Y Y Y Y Y Y // Y Y Y Y Y Y Y Y // Y Y Y Y Y Y Y Y var outputOffset: Int when (planeIndex) { 0 -> { outputStride = 1 outputOffset = 0 } 1 -> { outputStride = 2 // For NV21 format, U is in odd-numbered indices outputOffset = pixelCount + 1 } 2 -> { outputStride = 2 // For NV21 format, V is in even-numbered indices outputOffset = pixelCount } else -> { // Image contains more than 3 planes, something strange is going on return@forEachIndexed } } val planeBuffer = plane.buffer val rowStride = plane.rowStride val pixelStride = plane.pixelStride // We have to divide the width and height by two if it's not the Y plane val planeCrop = if (planeIndex == 0) { imageCrop } else { Rect( imageCrop.left / 2, imageCrop.top / 2, imageCrop.right / 2, imageCrop.bottom / 2 ) } val planeWidth = planeCrop.width() val planeHeight = planeCrop.height() // Intermediate buffer used to store the bytes of each row val rowBuffer = ByteArray(plane.rowStride) // Size of each row in bytes val rowLength = if (pixelStride == 1 && outputStride == 1) { planeWidth } else { // Take into account that the stride may include data from pixels other than this // particular plane and row, and that could be between pixels and not after every // pixel: // // |---- Pixel stride ----| Row ends here --> | // | Pixel 1 | Other Data | Pixel 2 | Other Data | ... | Pixel N | // // We need to get (N-1) * (pixel stride bytes) per row + 1 byte for the last pixel (planeWidth - 1) * pixelStride + 1 } for (row in 0 until planeHeight) { // Move buffer position to the beginning of this row planeBuffer.position( (row + planeCrop.top) * rowStride + planeCrop.left * pixelStride ) if (pixelStride == 1 && outputStride == 1) { // When there is a single stride value for pixel and output, we can just copy // the entire row in a single step planeBuffer.get(outputBuffer, outputOffset, rowLength) outputOffset += rowLength } else { // When either pixel or output have a stride > 1 we must copy pixel by pixel planeBuffer.get(rowBuffer, 0, rowLength) for (col in 0 until planeWidth) { outputBuffer[outputOffset] = rowBuffer[col * pixelStride] outputOffset += outputStride } } } } } }
nexus-farmap/app/src/main/java/com/nexus/farmap/data/ml/classification/YuvToRgbConverter.kt
825656715
package com.nexus.farmap.data.ml.classification import android.app.Activity import androidx.lifecycle.DefaultLifecycleObserver import androidx.lifecycle.LifecycleOwner import com.google.ar.core.ArCoreApk import com.google.ar.core.Session import com.google.ar.core.exceptions.CameraNotAvailableException /** * Manages an ARCore Session using the Android Lifecycle API. * Before starting a Session, this class requests an install of ARCore, if necessary, * and asks the user for permissions, if necessary. */ class ARCoreSessionLifecycleHelper( private val activity: Activity, private val features: Set<Session.Feature> = setOf() ) : DefaultLifecycleObserver { var installRequested = false var sessionCache: Session? = null private set // Creating a Session may fail. In this case, sessionCache will remain null, and this function will be called with an exception. // See https://developers.google.com/ar/reference/java/com/google/ar/core/Session#Session(android.content.Context) // for more information. var exceptionCallback: ((Exception) -> Unit)? = null // After creating a session, but before Session.resume is called is the perfect time to setup a session. // Generally, you would use Session.configure or setCameraConfig here. // https://developers.google.com/ar/reference/java/com/google/ar/core/Session#public-void-configure-config-config // https://developers.google.com/ar/reference/java/com/google/ar/core/Session#setCameraConfig(com.google.ar.core.CameraConfig) var beforeSessionResume: ((Session) -> Unit)? = null // Creates a session. If ARCore is not installed, an installation will be requested. fun tryCreateSession(): Session? { // Request an installation if necessary. when (ArCoreApk.getInstance().requestInstall(activity, !installRequested)) { ArCoreApk.InstallStatus.INSTALL_REQUESTED -> { installRequested = true // tryCreateSession will be called again, so we return null for now. return null } ArCoreApk.InstallStatus.INSTALLED -> { // Left empty; nothing needs to be done } } // Create a session if ARCore is installed. return try { Session(activity, features) } catch (e: Exception) { exceptionCallback?.invoke(e) null } } override fun onResume(owner: LifecycleOwner) { val session = tryCreateSession() ?: return try { beforeSessionResume?.invoke(session) session.resume() sessionCache = session } catch (e: CameraNotAvailableException) { exceptionCallback?.invoke(e) } } override fun onPause(owner: LifecycleOwner) { sessionCache?.pause() } override fun onDestroy(owner: LifecycleOwner) { // Explicitly close ARCore Session to release native resources. // Review the API reference for important considerations before calling close() in apps with // more complicated lifecycle requirements: // https://developers.google.com/ar/reference/java/arcore/reference/com/google/ar/core/Session#close() sessionCache?.close() sessionCache = null } }
nexus-farmap/app/src/main/java/com/nexus/farmap/data/ml/classification/ARCoreSessionLifecycleHelper.kt
2830144001
package com.nexus.farmap.data.model import dev.romainguy.kotlin.math.Float2 data class DetectedObjectResult( val label: String, val centerCoordinate: Float2, )
nexus-farmap/app/src/main/java/com/nexus/farmap/data/model/DetectedObjectResult.kt
3927555452
package com.nexus.farmap.data.model import androidx.room.* import com.nexus.farmap.domain.tree.TreeNode import dev.romainguy.kotlin.math.Float3 import dev.romainguy.kotlin.math.Quaternion @Entity class TreeNodeDto( @PrimaryKey val id: Int, val x: Float, val y: Float, val z: Float, val type: String = TYPE_PATH, val number: String? = null, val neighbours: MutableList<Int> = mutableListOf(), val forwardVector: Quaternion? = null ) { companion object { val TYPE_PATH = "path" val TYPE_ENTRY = "entry" fun fromTreeNode( node: TreeNode, position: Float3? = null, forwardVector: Quaternion? = null ): TreeNodeDto { return TreeNodeDto( id = node.id, x = position?.x ?: node.position.x, y = position?.y ?: node.position.y, z = position?.z ?: node.position.z, forwardVector = forwardVector ?: if (node is TreeNode.Entry) node.forwardVector else null, type = if (node is TreeNode.Entry) TYPE_ENTRY else TYPE_PATH, number = if (node is TreeNode.Entry) node.number else null, neighbours = node.neighbours ) } } }
nexus-farmap/app/src/main/java/com/nexus/farmap/data/model/TreeNodeDto.kt
1439495250
package com.nexus.farmap.data.model import androidx.room.TypeConverter import dev.romainguy.kotlin.math.Quaternion class NeighboursConverter { companion object { @TypeConverter @JvmStatic fun storedStringToNeighbours(value: String): MutableList<Int> { return value.split(",").filter { it != "" }.mapIfNotEmpty { it.toInt() }.toMutableList() } @TypeConverter @JvmStatic fun neighboursToStoredString(list: MutableList<Int>): String { var value = "" for (id in list) value += "$id," return value.dropLast(1) } @TypeConverter @JvmStatic fun storedStringtoQuaternion(value: String): Quaternion? { return if (value == "") { null } else { val data = value.split(" ").map { it.toFloat() } Quaternion(data[0], data[1], data[2], data[3]) } } @TypeConverter @JvmStatic fun quaternionToString(value: Quaternion?): String { return if (value == null) "" else "${value.x} ${value.y} ${value.z} ${value.w}" } } } inline fun <T, R> List<T>.mapIfNotEmpty(transform: (T) -> R): List<R> { return when (size) { 0 -> listOf() else -> map(transform) } }
nexus-farmap/app/src/main/java/com/nexus/farmap/data/model/NeighboursConverter.kt
2189388547
package com.nexus.farmap.domain.tree import com.nexus.farmap.domain.utils.getApproxDif import dev.romainguy.kotlin.math.Float3 class TreeDiffUtils( private val tree: Tree ) { private var closestNodes = mutableMapOf<Int, TreeNode>() suspend fun getNearNodes(position: Float3, radius: Float): List<TreeNode> { if (!tree.initialized) { return listOf() } else { val nodes = tree.getNodeFromEachRegion().toMutableMap() closestNodes.keys.forEach { key -> if (nodes.containsKey(key)) { nodes[key] = closestNodes[key]!! } } closestNodes = nodes closestNodes.forEach { item -> closestNodes[item.key] = getNewCentralNode(position, item.value) } val nearNodes = mutableListOf<TreeNode>() closestNodes.values.forEach { node -> getNodesByRadius(position, node, radius, nearNodes) } return nearNodes } } private fun getNodesByRadius(position: Float3, central: TreeNode, radius: Float, list: MutableList<TreeNode>) { if (position.getApproxDif(central.position) > radius) { return } list.add(central) central.neighbours.forEach { id -> tree.getNode(id)?.let { node -> if (!list.contains(node)) { getNodesByRadius(position, node, radius, list) } } } } private fun getNewCentralNode(position: Float3, central: TreeNode): TreeNode { var min = Pair(central, position.getApproxDif(central.position)) central.neighbours.forEach { id -> tree.getNode(id)?.let { node -> searchClosestNode(position, node, min.second)?.let { res -> if (res.second < min.second) { min = res } } } } return min.first } private fun searchClosestNode(position: Float3, node: TreeNode, lastDist: Float): Pair<TreeNode, Float>? { val dist = position.getApproxDif(node.position) if (dist >= lastDist) { return null } else { var min: Pair<TreeNode, Float>? = null node.neighbours.forEach { id -> tree.getNode(id)?.let { node2 -> searchClosestNode(position, node2, dist)?.let { res -> if (min != null) { if (res.second < min!!.second) { min = res } } else { min = res } } } } min?.let { if (it.second < dist) { return min } } return Pair(node, dist) } } }
nexus-farmap/app/src/main/java/com/nexus/farmap/domain/tree/TreeDiffUtils.kt
1764139161
package com.nexus.farmap.domain.tree data class WrongEntryException( val availableEntries: Set<String> ) : Exception() { override val message = "Wrong entry number. Available: $availableEntries" }
nexus-farmap/app/src/main/java/com/nexus/farmap/domain/tree/WrongEntryException.kt
2317237383
package com.nexus.farmap.domain.tree import android.util.Log import com.nexus.farmap.data.model.TreeNodeDto import com.nexus.farmap.domain.repository.GraphRepository import com.nexus.farmap.domain.use_cases.convert import com.nexus.farmap.domain.use_cases.inverted import dev.romainguy.kotlin.math.Float3 import dev.romainguy.kotlin.math.Quaternion import io.github.sceneview.math.* import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext class Tree( private val repository: GraphRepository ) { private val _entryPoints: MutableMap<String, TreeNode.Entry> = mutableMapOf() private val _allPoints: MutableMap<Int, TreeNode> = mutableMapOf() private val _links: MutableMap<Int, MutableList<Int>> = mutableMapOf() //Nodes without links. Needed for near nodes calculation in TreeDiffUtils private val _freeNodes: MutableList<Int> = mutableListOf() private val _regions: MutableMap<Int, Int> = mutableMapOf() private val _translocatedPoints: MutableMap<TreeNode, Boolean> = mutableMapOf() private var availableId = 0 private var availableRegion = 0 var initialized = false private set var preloaded = false private set var translocation = Float3(0f, 0f, 0f) private set var pivotPosition = Float3(0f, 0f, 0f) private set var rotation = Float3(0f, 0f, 0f).toQuaternion() private set val diffUtils: TreeDiffUtils by lazy { TreeDiffUtils(this) } suspend fun preload() = withContext(Dispatchers.IO) { if (initialized) { throw Exception("Already initialized, cant preload") } preloaded = false val rawNodesList = repository.getNodes() for (nodeDto in rawNodesList) { var node: TreeNode if (nodeDto.type == TreeNodeDto.TYPE_ENTRY && nodeDto.number != null && nodeDto.forwardVector != null) { node = TreeNode.Entry( number = nodeDto.number, forwardVector = nodeDto.forwardVector, id = nodeDto.id, position = Float3(nodeDto.x, nodeDto.y, nodeDto.z), neighbours = nodeDto.neighbours ) _entryPoints[node.number] = node } else { node = TreeNode.Path( id = nodeDto.id, position = Float3(nodeDto.x, nodeDto.y, nodeDto.z), neighbours = nodeDto.neighbours ) } _allPoints[node.id] = node _links[node.id] = node.neighbours if (node.neighbours.isEmpty()) { _freeNodes.add(node.id) } if (node.id + 1 > availableId) { availableId = node.id + 1 } } _allPoints.keys.forEach { id -> setRegion(id) } preloaded = true } suspend fun initialize(entryNumber: String, position: Float3, newRotation: Quaternion): Result<Unit?> { initialized = false if (_entryPoints.isEmpty()) { clearTree() initialized = true return Result.success(null) } else { val entry = _entryPoints[entryNumber] ?: return Result.failure( exception = WrongEntryException(_entryPoints.keys) ) pivotPosition = entry.position translocation = entry.position - position rotation = entry.forwardVector.convert(newRotation.inverted()) * -1f rotation.w *= -1f initialized = true return Result.success(null) } } private fun setRegion(nodeId: Int, region: Int? = null, overlap: Boolean = false, blacklist: List<Int> = listOf()) { _regions[nodeId]?.let { r -> if (blacklist.contains(r) || !overlap) { return } } val reg = region ?: getRegionNumber() _regions[nodeId] = reg //Not using getNode() because translocation is not needed _allPoints[nodeId]?.neighbours?.forEach { id -> setRegion(id, reg) } } private fun getRegionNumber(): Int { return availableRegion.also { availableRegion++ } } fun getNode(id: Int): TreeNode? { if (!initialized) { throw Exception("Tree isnt initialized") } val node = _allPoints[id] return if (_translocatedPoints.containsKey(node)) { node } else { if (node == null) { null } else { translocateNode(node) node } } } fun getEntry(number: String): TreeNode.Entry? { if (!initialized) { throw Exception("Tree isnt initialized") } val entry = _entryPoints[number] return if (entry != null) { getNode(entry.id) as TreeNode.Entry } else { null } } fun getNodes(nodes: List<Int>): List<TreeNode> { if (!initialized) { throw Exception("Tree isnt initialized") } return nodes.mapNotNull { getNode(it) } } fun getFreeNodes(): List<TreeNode> { if (!initialized) { throw Exception("Tree isnt initialized") } return _freeNodes.mapNotNull { id -> getNode(id) } } fun getAllNodes(): List<TreeNode> { if (!initialized) { throw Exception("Tree isnt initialized") } val nodes = mutableListOf<TreeNode>() for (key in _allPoints.keys) { getNode(key)?.let { nodes.add(it) } } return nodes } fun getEntriesNumbers(): Set<String> { return _entryPoints.keys } fun getNodesWithLinks(): List<TreeNode> { if (!initialized) { throw Exception("Tree isnt initialized") } return _links.keys.mapNotNull { getNode(it) } } fun getNodeLinks(node: TreeNode): List<TreeNode>? { return _links[node.id]?.mapNotNull { getNode(it) } } fun getNodeFromEachRegion(): Map<Int, TreeNode> { return _regions.entries.distinctBy { it.value }.filter { getNode(it.key) != null } .associate { it.value to getNode(it.key)!! } } fun hasEntry(number: String): Boolean { return _entryPoints.keys.contains(number) } private fun translocateNode(node: TreeNode) { node.position = convertPosition(node.position, translocation, rotation, pivotPosition) if (node is TreeNode.Entry) { node.forwardVector = node.forwardVector.convert(rotation) } _translocatedPoints[node] = true } suspend fun addNode( position: Float3, number: String? = null, forwardVector: Quaternion? = null ): TreeNode { if (!initialized) { throw Exception("Tree isnt initialized") } if (_allPoints.values.find { it.position == position } != null) { throw Exception("Position already taken") } val newNode: TreeNode if (number == null) { newNode = TreeNode.Path( availableId, position ) } else { if (_entryPoints[number] != null) { throw Exception("Entry point already exists") } if (forwardVector == null) { throw Exception("Null forward vector") } newNode = TreeNode.Entry( number, forwardVector, availableId, position ) _entryPoints[newNode.number] = newNode } _allPoints[newNode.id] = newNode _translocatedPoints[newNode] = true _freeNodes.add(newNode.id) setRegion(newNode.id) availableId++ repository.insertNodes(listOf(newNode), translocation, rotation, pivotPosition) return newNode } suspend fun removeNode( node: TreeNode ) { if (!initialized) { throw Exception("Tree isnt initialized") } removeAllLinks(node) _translocatedPoints.remove(node) _allPoints.remove(node.id) _freeNodes.remove(node.id) _regions.remove(node.id) if (node is TreeNode.Entry) { _entryPoints.remove(node.number) } repository.deleteNodes(listOf(node)) } suspend fun addLink( node1: TreeNode, node2: TreeNode ): Boolean { if (!initialized) { throw Exception("Tree isnt initialized") } if (_links[node1.id] == null) { _links[node1.id] = mutableListOf() } else { if (_links[node1.id]!!.contains(node2.id)) { throw Exception("Link already exists") } } if (_links[node2.id] == null) { _links[node2.id] = mutableListOf() } else { if (_links[node2.id]!!.contains(node1.id)) throw Exception("Link already exists") } node1.neighbours.add(node2.id) node2.neighbours.add(node1.id) _links[node1.id] = node1.neighbours _links[node2.id] = node2.neighbours _freeNodes.remove(node1.id) _freeNodes.remove(node2.id) val reg = _regions[node2.id]!! setRegion(node1.id, reg, overlap = true, blacklist = listOf(reg)) repository.updateNodes(listOf(node1, node2), translocation, rotation, pivotPosition) return true } private suspend fun removeAllLinks(node: TreeNode) { if (!initialized) { throw Exception("Tree isnt initialized") } if (_links[node.id] == null) { return } val nodesForUpdate = getNodes(node.neighbours.toMutableList()).toMutableList() nodesForUpdate.add(node) node.neighbours.forEach { id -> _allPoints[id]?.let { it.neighbours.remove(node.id) _links[it.id] = it.neighbours if (it.neighbours.isEmpty()) { _freeNodes.add(it.id) } } } node.neighbours.clear() _links[node.id] = node.neighbours _freeNodes.add(node.id) //Change regions. val blacklist = mutableListOf<Int>() for (i in 0 until nodesForUpdate.size) { val id = nodesForUpdate[i].id setRegion(id, overlap = true, blacklist = blacklist) _regions[id]?.let { blacklist.add(it) } } repository.updateNodes(nodesForUpdate, translocation, rotation, pivotPosition) } private suspend fun clearTree() { Log.d(TAG, "Tree cleared") _links.clear() _allPoints.clear() _entryPoints.clear() _translocatedPoints.clear() _freeNodes.clear() availableId = 0 availableRegion = 0 translocation = Float3(0f, 0f, 0f) rotation = Float3(0f, 0f, 0f).toQuaternion() pivotPosition = Float3(0f, 0f, 0f) repository.clearNodes() } private fun convertPosition( position: Float3, translocation: Float3, quaternion: Quaternion, pivotPosition: Float3 ): Float3 { return (com.google.ar.sceneform.math.Quaternion.rotateVector( quaternion.toOldQuaternion(), (position - pivotPosition).toVector3() ).toFloat3() + pivotPosition) - translocation } companion object { const val TAG = "TREE" } }
nexus-farmap/app/src/main/java/com/nexus/farmap/domain/tree/Tree.kt
1492515084
package com.nexus.farmap.domain.tree import dev.romainguy.kotlin.math.Float3 import dev.romainguy.kotlin.math.Quaternion sealed class TreeNode( val id: Int, var position: Float3, var neighbours: MutableList<Int> = mutableListOf() ) { class Entry( var number: String, var forwardVector: Quaternion, id: Int, position: Float3, neighbours: MutableList<Int> = mutableListOf(), ) : TreeNode(id, position, neighbours) { fun copy( number: String = this.number, id: Int = this.id, position: Float3 = this.position, neighbours: MutableList<Int> = this.neighbours, forwardVector: Quaternion = this.forwardVector ): Entry { return Entry( number, forwardVector, id, position, neighbours, ) } } class Path( id: Int, position: Float3, neighbours: MutableList<Int> = mutableListOf() ) : TreeNode(id, position, neighbours) { fun copy( id: Int = this.id, position: Float3 = this.position, neighbours: MutableList<Int> = this.neighbours ): Path { return Path( id, position, neighbours ) } } }
nexus-farmap/app/src/main/java/com/nexus/farmap/domain/tree/TreeNode.kt
68562136
package com.nexus.farmap.domain.repository import com.nexus.farmap.data.model.TreeNodeDto import com.nexus.farmap.domain.tree.TreeNode import dev.romainguy.kotlin.math.Float3 import dev.romainguy.kotlin.math.Quaternion interface GraphRepository { suspend fun getNodes(): List<TreeNodeDto> suspend fun insertNodes( nodes: List<TreeNode>, translocation: Float3, rotation: Quaternion, pivotPosition: Float3 ) suspend fun deleteNodes(nodes: List<TreeNode>) suspend fun updateNodes( nodes: List<TreeNode>, translocation: Float3, rotation: Quaternion, pivotPosition: Float3 ) suspend fun clearNodes() }
nexus-farmap/app/src/main/java/com/nexus/farmap/domain/repository/GraphRepository.kt
1604210196
package com.nexus.farmap.domain.pathfinding import com.nexus.farmap.domain.hit_test.OrientatedPosition import com.nexus.farmap.domain.utils.getApproxDif import dev.romainguy.kotlin.math.Float3 class Path(val nodes: List<OrientatedPosition>) { private var lastNodeId: Int? = null fun getNearNodes(number: Int, position: Float3): List<OrientatedPosition> { val central = linearNodeSearch(position, lastNodeId ?: 0) lastNodeId = central return grabNearNodes(number, central) } private fun grabNearNodes(number: Int, centralId: Int): List<OrientatedPosition> { val sides = number - 1 var left = centralId - sides / 2 var right = centralId + sides / 2 + if (sides % 2 == 0) 0 else 1 if (left < 0) left = 0 if (right > nodes.size - 1) { right = nodes.size - 1 } return List(right - left + 1) { nodes[it + left] } } private fun linearNodeSearch(pos: Float3, start: Int = 0): Int { if (nodes.isEmpty()) { throw Exception("Nodes list is empty") } val left = if (start > 0) pos.getApproxDif(nodes[start - 1].position) else null val right = if (start < nodes.size - 1) pos.getApproxDif(nodes[start + 1].position) else null val toRight = when { left == null -> { true } right == null -> { false } else -> { left >= right } } val searchIds = if (toRight) start + 1 until nodes.size else start - 1 downTo 0 var prevId = start var prev = pos.getApproxDif(nodes[prevId].position) for (i in searchIds) { val curr = pos.getApproxDif(nodes[i].position) if (curr >= prev) { break } else { prevId = i prev = curr } } return prevId } }
nexus-farmap/app/src/main/java/com/nexus/farmap/domain/pathfinding/Path.kt
3950698785
package com.nexus.farmap.domain.pathfinding import com.nexus.farmap.domain.tree.Tree interface Pathfinder { suspend fun findWay( from: String, to: String, tree: Tree ): Path? }
nexus-farmap/app/src/main/java/com/nexus/farmap/domain/pathfinding/Pathfinder.kt
390416065
package com.nexus.farmap.domain.smoothing import dev.benedikt.math.bezier.vector.Vector3D data class BezierPoint( val t: Double, var pos: Vector3D )
nexus-farmap/app/src/main/java/com/nexus/farmap/domain/smoothing/BezierPoint.kt
724503624
package com.nexus.farmap.domain.utils import dev.romainguy.kotlin.math.Float3 import dev.romainguy.kotlin.math.pow import kotlin.math.abs import kotlin.math.sqrt fun Float3.getApproxDif(pos: Float3): Float { return sqrt( +abs(pow(x - pos.x, 2f)) + abs(pow(z - pos.z, 2f)) ) }
nexus-farmap/app/src/main/java/com/nexus/farmap/domain/utils/FloatExt.kt
468572702
package com.nexus.farmap.domain.hit_test import dev.romainguy.kotlin.math.Float3 import dev.romainguy.kotlin.math.Quaternion data class OrientatedPosition( val position: Float3, val orientation: Quaternion )
nexus-farmap/app/src/main/java/com/nexus/farmap/domain/hit_test/OrientatedPosition.kt
3683246756
package com.nexus.farmap.domain.hit_test import com.google.ar.core.HitResult data class HitTestResult( val orientatedPosition: OrientatedPosition, val hitResult: HitResult )
nexus-farmap/app/src/main/java/com/nexus/farmap/domain/hit_test/HitTestResult.kt
725745218
package com.nexus.farmap.domain.ml import android.media.Image import com.nexus.farmap.data.model.DetectedObjectResult /** * Describes a common interface for [GoogleCloudVisionDetector] and [MLKitObjectDetector] that can * infer object labels in a given [Image] and gives results in a list of [DetectedObjectResult]. */ interface ObjectDetector { /** * Infers a list of [DetectedObjectResult] given a camera image frame, which contains a confidence level, * a label, and a pixel coordinate on the image which is believed to be the center of the object. */ suspend fun analyze( mediaImage: Image, rotationDegrees: Int, imageCropPercentages: Pair<Int, Int>, displaySize: Pair<Int, Int> ): Result<DetectedObjectResult> }
nexus-farmap/app/src/main/java/com/nexus/farmap/domain/ml/ObjectDetector.kt
560058351
package com.nexus.farmap.domain.ml import com.nexus.farmap.data.model.DetectedObjectResult import com.google.ar.core.Frame data class DetectedText( val detectedObjectResult: DetectedObjectResult, val frame: Frame )
nexus-farmap/app/src/main/java/com/nexus/farmap/domain/ml/DetectedText.kt
3141089637
package com.nexus.farmap.domain.use_cases import android.content.Context import com.nexus.farmap.R class GetDestinationDesc { operator fun invoke(number: String, context: Context): String { val building = number[0] val floor = number[1] val room = number.drop(2) val floorStr = context.getString(R.string.floor) val roomStr = context.getString(R.string.room) return "$building, $floorStr$floor, $roomStr$room" } }
nexus-farmap/app/src/main/java/com/nexus/farmap/domain/use_cases/GetDestinationDesc.kt
3816662283
package com.nexus.farmap.domain.use_cases import com.nexus.farmap.domain.hit_test.HitTestResult import com.nexus.farmap.domain.hit_test.OrientatedPosition import com.google.ar.sceneform.math.Quaternion import com.google.ar.sceneform.math.Vector3 import dev.romainguy.kotlin.math.Float2 import io.github.sceneview.ar.arcore.ArFrame import io.github.sceneview.math.toFloat3 import io.github.sceneview.math.toNewQuaternion class HitTest { operator fun invoke(arFrame: ArFrame, targetPos: Float2): Result<HitTestResult> { arFrame.frame.let { frame -> val hitResult1 = frame.hitTest(targetPos.x, targetPos.y) val hitResult2 = frame.hitTest(targetPos.x - 5, targetPos.y) val hitResult3 = frame.hitTest(targetPos.x, targetPos.y + 5) if (hitResult1.isNotEmpty() && hitResult2.isNotEmpty() && hitResult3.isNotEmpty()) { val result1 = hitResult1.first() val result2 = hitResult2.first() val result3 = hitResult3.first() val pos1 = Vector3( result1.hitPose.tx(), result1.hitPose.ty(), result1.hitPose.tz() ) val pos2 = Vector3( result2.hitPose.tx(), result2.hitPose.ty(), result2.hitPose.tz() ) val pos3 = Vector3( result3.hitPose.tx(), result3.hitPose.ty(), result3.hitPose.tz() ) val vector1 = Vector3.subtract(pos1, pos2).normalized() val vector2 = Vector3.subtract(pos1, pos3).normalized() val vectorForward = Vector3.cross(vector1, vector2).normalized() vectorForward.y = 0f val orientation = Quaternion.lookRotation( vectorForward, Vector3.up() ).toNewQuaternion() val orientatedPosition = OrientatedPosition(pos1.toFloat3(), orientation) return Result.success(HitTestResult(orientatedPosition, result1)) } else { return Result.failure(Exception("Null hit result")) } } } }
nexus-farmap/app/src/main/java/com/nexus/farmap/domain/use_cases/HitTest.kt
812868667
package com.nexus.farmap.domain.use_cases import com.google.ar.sceneform.math.Vector3 import dev.romainguy.kotlin.math.Quaternion import dev.romainguy.kotlin.math.inverse import io.github.sceneview.math.toNewQuaternion import io.github.sceneview.math.toOldQuaternion fun Quaternion.convert(quaternion2: Quaternion): Quaternion { return this * quaternion2 } fun Quaternion.inverted(): Quaternion { return toOldQuaternion().inverted().toNewQuaternion() } fun Quaternion.opposite(): Quaternion { return inverse(this) } fun Quaternion.Companion.lookRotation(forward: Vector3, up: Vector3 = Vector3.up()): Quaternion { val rotationFromAtoB = com.google.ar.sceneform.math.Quaternion.lookRotation(forward, up) return com.google.ar.sceneform.math.Quaternion.multiply( rotationFromAtoB, com.google.ar.sceneform.math.Quaternion.axisAngle(Vector3(1.0f, 0.0f, 0.0f), 270f) ).toNewQuaternion() }
nexus-farmap/app/src/main/java/com/nexus/farmap/domain/use_cases/QuaternionExtensions.kt
3751114170
package com.nexus.farmap.domain.use_cases import android.media.Image import com.nexus.farmap.data.model.DetectedObjectResult import com.nexus.farmap.domain.ml.ObjectDetector class AnalyzeImage( private val objectDetector: ObjectDetector, ) { suspend operator fun invoke( image: Image, imageRotation: Int, imageCropPercentage: Pair<Int, Int>, displaySize: Pair<Int, Int> ): Result<DetectedObjectResult> { return objectDetector.analyze( image, imageRotation, imageCropPercentage, displaySize ) } }
nexus-farmap/app/src/main/java/com/nexus/farmap/domain/use_cases/AnalyzeImage.kt
200799845
package com.nexus.farmap.domain.use_cases import com.google.ar.sceneform.math.Quaternion.lookRotation import com.google.ar.sceneform.math.Quaternion.multiply import com.google.ar.sceneform.math.Quaternion.axisAngle import com.nexus.farmap.domain.hit_test.OrientatedPosition import com.nexus.farmap.domain.smoothing.BezierPoint import com.nexus.farmap.domain.tree.TreeNode import com.google.ar.sceneform.math.Vector3 import dev.benedikt.math.bezier.curve.BezierCurve import dev.benedikt.math.bezier.curve.Order import dev.benedikt.math.bezier.math.DoubleMathHelper import dev.benedikt.math.bezier.vector.Vector3D import dev.romainguy.kotlin.math.Float3 import dev.romainguy.kotlin.math.Quaternion import io.github.sceneview.math.toFloat3 import io.github.sceneview.math.toNewQuaternion import io.github.sceneview.math.toVector3 private const val ROUTE_STEP = 0.3f class SmoothPath { operator fun invoke( nodes: List<TreeNode> ): List<OrientatedPosition> { val list = mutableListOf<OrientatedPosition>() if (nodes.size > 3) { for (i in 1 until nodes.size - 2) { val node1 = nodes[i] val node2 = nodes[i + 1] val fromVector = node1.position.toVector3() val toVector = node2.position.toVector3() val lineLength = Vector3.subtract(fromVector, toVector).length() if (lineLength < ROUTE_STEP) { continue } val nodesAmount = (lineLength / ROUTE_STEP).toInt() val dx = (toVector.x - fromVector.x) / nodesAmount val dy = (toVector.y - fromVector.y) / nodesAmount val dz = (toVector.z - fromVector.z) / nodesAmount val difference = Vector3.subtract(toVector, fromVector) val directionFromTopToBottom = difference.normalized() val rotationFromAToB: com.google.ar.sceneform.math.Quaternion = lookRotation( directionFromTopToBottom, Vector3.up() ) val rotation = multiply( rotationFromAToB, axisAngle(Vector3(1.0f, 0.0f, 0.0f), 270f) ).toNewQuaternion() val lowStep = if (nodesAmount < 3) 0 else if (nodesAmount == 3) 1 else 2 val highStep = if (nodesAmount < 3) 1 else if (nodesAmount == 3) 2 else 3 for (j in 0..nodesAmount - highStep) { val position = Float3( fromVector.x + dx * j, fromVector.y + dy * j, fromVector.z + dz * j ) if (list.isEmpty() || i == 1) { val pos = OrientatedPosition(position, rotation) list.add(pos) } else if (j == lowStep) { list.addAll( getBezierSmoothPoints( list.removeLast().position, position, fromVector.toFloat3(), ROUTE_STEP ) ) } else if (j > lowStep) { val pos = OrientatedPosition(position, rotation) list.add(pos) } } if (i == nodes.size - 3) { for (j in nodesAmount - highStep until nodesAmount) { val position = Float3( fromVector.x + dx * j, fromVector.y + dy * j, fromVector.z + dz * j ) val pos = OrientatedPosition(position, rotation) list.add(pos) } } } } return list } private fun getBezierSmoothPoints( start: Float3, end: Float3, point: Float3, step: Float ): List<OrientatedPosition> { val curve = bezierCurve( start, end, point ) val curveLen = curve.length val rawPointsAmount = 50 val rawStep = curveLen / rawPointsAmount val rawPoints = mutableListOf<BezierPoint>() var i = 0.0 while (i < curveLen) { val t = i / curveLen val pos = curve.getCoordinatesAt(t) rawPoints.add(BezierPoint(t, pos)) i += rawStep } val endPoint = BezierPoint(1.0, curve.getCoordinatesAt(1.0)) return walkCurve(endPoint, rawPoints, step.toDouble()).map { rawPoint -> val pos = rawPoint.pos.toFloat3() val tangent = curve.getTangentAt(rawPoint.t) pos.x = pos.x tangent.y = tangent.y OrientatedPosition( rawPoint.pos.toFloat3(), Quaternion.lookRotation(curve.getTangentAt(rawPoint.t).toVector3()) ) } } private fun bezierCurve( start: Float3, end: Float3, point: Float3 ): BezierCurve<Double, Vector3D> { val curve = BezierCurve( Order.QUADRATIC, start.toVector3D(), end.toVector3D(), listOf(point.toVector3D()), 20, DoubleMathHelper() ) curve.computeLength() return curve } private fun walkCurve( end: BezierPoint, points: List<BezierPoint>, spacing: Double, offset: Double = 0.0 ): List<BezierPoint> { val result = mutableListOf<BezierPoint>() val space = if (spacing > 0.00001) spacing else 0.00001 var distanceNeeded = offset while (distanceNeeded < 0) { distanceNeeded += space } var current = points[0] var next = points[1] var i = 1 val last = points.count() - 1 while (true) { val diff = next.pos - current.pos val dist = diff.magnitude() if (dist >= distanceNeeded) { current.pos += diff * (distanceNeeded / dist) result.add(current) distanceNeeded = spacing } else if (i != last) { distanceNeeded -= dist current = next next = points[++i] } else { break } } val dist = (result.last().pos - end.pos).magnitude() if (dist < spacing / 2) { result.removeLast() result.add(end) } else { result.add(end) } return result } private fun Float3.toVector3D(): Vector3D { return Vector3D( this.x.toDouble(), this.y.toDouble(), this.z.toDouble() ) } private fun Vector3D.toFloat3(): Float3 { return Float3( this.x.toFloat(), this.y.toFloat(), this.z.toFloat() ) } private fun Vector3D.toVector3(): Vector3 { return Vector3( this.x.toFloat(), this.y.toFloat(), this.z.toFloat() ) } }
nexus-farmap/app/src/main/java/com/nexus/farmap/domain/use_cases/SmoothPath.kt
852601568
package com.nexus.farmap.domain.use_cases import com.nexus.farmap.domain.pathfinding.Path import com.nexus.farmap.domain.pathfinding.Pathfinder import com.nexus.farmap.domain.tree.Tree class FindWay( private val pathfinder: Pathfinder ) { suspend operator fun invoke( from: String, to: String, tree: Tree ): Path? { return pathfinder.findWay(from, to, tree) } }
nexus-farmap/app/src/main/java/com/nexus/farmap/domain/use_cases/FindWay.kt
352211757
package com.nexus.farmap.presentation import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import com.nexus.farmap.R import com.nexus.farmap.data.ml.classification.ARCoreSessionLifecycleHelper import com.google.ar.core.CameraConfig import com.google.ar.core.CameraConfigFilter import com.google.ar.core.Config class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val arCoreSessionHelper = ARCoreSessionLifecycleHelper(this) arCoreSessionHelper.beforeSessionResume = { session -> session.configure(session.config.apply { // To get the best image of the object in question, enable autofocus. focusMode = Config.FocusMode.AUTO if (session.isDepthModeSupported(Config.DepthMode.AUTOMATIC)) { depthMode = Config.DepthMode.AUTOMATIC } }) val filter = CameraConfigFilter(session).setFacingDirection(CameraConfig.FacingDirection.BACK) val configs = session.getSupportedCameraConfigs(filter) val sort = compareByDescending<CameraConfig> { it.imageSize.width }.thenByDescending { it.imageSize.height } session.cameraConfig = configs.sortedWith(sort)[0] } } }
nexus-farmap/app/src/main/java/com/nexus/farmap/presentation/MainActivity.kt
2753884513
package com.nexus.farmap.presentation import com.nexus.farmap.domain.hit_test.OrientatedPosition import com.google.ar.core.Anchor import io.github.sceneview.ar.node.ArNode data class LabelObject( val label: String, val pos: OrientatedPosition, var node: ArNode? = null, var anchor: Anchor? = null )
nexus-farmap/app/src/main/java/com/nexus/farmap/presentation/LabelObject.kt
3468524420
package com.nexus.farmap.presentation.confirmer import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.activity.OnBackPressedCallback import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.lifecycle.Lifecycle import androidx.lifecycle.lifecycleScope import androidx.lifecycle.repeatOnLifecycle import androidx.navigation.fragment.findNavController import androidx.navigation.fragment.navArgs import com.nexus.farmap.databinding.FragmentConfirmBinding import com.nexus.farmap.presentation.preview.MainEvent import com.nexus.farmap.presentation.preview.MainShareModel import com.nexus.farmap.presentation.preview.MainUiEvent import kotlinx.coroutines.launch class ConfirmFragment : Fragment() { private val mainModel: MainShareModel by activityViewModels() private var _binding: FragmentConfirmBinding? = null private val binding get() = _binding!! private val args: ConfirmFragmentArgs by navArgs() private val confType by lazy { args.confirmType } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val callback: OnBackPressedCallback = object : OnBackPressedCallback(true) { override fun handleOnBackPressed() { mainModel.onEvent(MainEvent.RejectConfObject(confType)) findNavController().popBackStack() } } requireActivity().onBackPressedDispatcher.addCallback(this, callback) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentConfirmBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { setEnabled(true) binding.acceptButton.setOnClickListener { setEnabled(false) mainModel.onEvent(MainEvent.AcceptConfObject(confType)) } binding.rejectButton.setOnClickListener { setEnabled(false) mainModel.onEvent(MainEvent.RejectConfObject(confType)) findNavController().popBackStack() } viewLifecycleOwner.lifecycleScope.launch { viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) { mainModel.mainUiEvents.collect { uiEvent -> when (uiEvent) { is MainUiEvent.InitSuccess -> { val action = ConfirmFragmentDirections.actionConfirmFragmentToRouterFragment() findNavController().navigate(action) } is MainUiEvent.InitFailed -> { findNavController().popBackStack() } is MainUiEvent.EntryCreated -> { val action = ConfirmFragmentDirections.actionConfirmFragmentToRouterFragment() findNavController().navigate(action) } is MainUiEvent.EntryAlreadyExists -> { val action = ConfirmFragmentDirections.actionConfirmFragmentToRouterFragment() findNavController().navigate(action) } else -> {} } } } } } private fun setEnabled(enabled: Boolean) { binding.acceptButton.isEnabled = enabled binding.rejectButton.isEnabled = enabled } companion object { const val CONFIRM_INITIALIZE = 0 const val CONFIRM_ENTRY = 1 } }
nexus-farmap/app/src/main/java/com/nexus/farmap/presentation/confirmer/ConfirmFragment.kt
3710963181
package com.nexus.farmap.presentation.search.adapters import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import com.nexus.farmap.R class EntriesAdapter( private val onItemClick: (String) -> Unit ) : ListAdapter<EntryItem, EntriesAdapter.ItemViewholder>(DiffCallback()) { private var rawList = listOf<EntryItem>() private var filter: String = "" override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemViewholder { return ItemViewholder( onItemClick, LayoutInflater.from(parent.context).inflate(R.layout.entry_item, parent, false) ) } override fun onBindViewHolder(holder: ItemViewholder, position: Int) { holder.bind(getItem(position)) } class ItemViewholder(private val onItemClick: (String) -> Unit, itemView: View) : RecyclerView.ViewHolder(itemView) { fun bind(item: EntryItem) = with(itemView) { val textView: TextView = this.findViewById(R.id.entry_number) val descTextView: TextView = this.findViewById(R.id.description_text) textView.text = item.number descTextView.text = item.description setOnClickListener { onItemClick(item.number) } } } fun changeList(entries: List<EntryItem>) { rawList = entries filter = "" submitList(rawList) } fun applyFilter(filter: String) { this.filter = filter submitList(rawList.filter { it.number.startsWith(filter) }.sortedBy { it.number.length }) } } class DiffCallback : DiffUtil.ItemCallback<EntryItem>() { override fun areItemsTheSame(oldItem: EntryItem, newItem: EntryItem): Boolean { return oldItem.number == newItem.number } override fun areContentsTheSame(oldItem: EntryItem, newItem: EntryItem): Boolean { return oldItem == newItem } }
nexus-farmap/app/src/main/java/com/nexus/farmap/presentation/search/adapters/EntriesAdapter.kt
4245969851
package com.nexus.farmap.presentation.search.adapters data class EntryItem( val number: String, val description: String )
nexus-farmap/app/src/main/java/com/nexus/farmap/presentation/search/adapters/EntryItem.kt
1746303821
package com.nexus.farmap.presentation.search import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.inputmethod.EditorInfo import androidx.activity.OnBackPressedCallback import androidx.core.widget.doOnTextChanged import androidx.fragment.app.activityViewModels import androidx.lifecycle.Lifecycle import androidx.lifecycle.lifecycleScope import androidx.lifecycle.repeatOnLifecycle import androidx.navigation.fragment.findNavController import androidx.navigation.fragment.navArgs import androidx.recyclerview.widget.LinearLayoutManager import com.nexus.farmap.R import com.nexus.farmap.data.App import com.nexus.farmap.databinding.FragmentSearchBinding import com.nexus.farmap.presentation.search.adapters.EntriesAdapter import com.nexus.farmap.presentation.search.adapters.EntryItem import com.nexus.farmap.presentation.common.helpers.viewHideInput import com.nexus.farmap.presentation.common.helpers.viewRequestInput import com.nexus.farmap.presentation.preview.MainEvent import com.nexus.farmap.presentation.preview.MainShareModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.launch import kotlinx.coroutines.withContext class SearchFragment : Fragment() { private val destinationDesc = App.instance!!.getDestinationDesc private val mainModel: MainShareModel by activityViewModels() private var _binding: FragmentSearchBinding? = null private val binding get() = _binding!! private val adapter = EntriesAdapter { number -> processSearchResult(number) } private val args: SearchFragmentArgs by navArgs() val changeType by lazy { args.changeType } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val callback: OnBackPressedCallback = object : OnBackPressedCallback(true) { override fun handleOnBackPressed() { findNavController().popBackStack() } } requireActivity().onBackPressedDispatcher.addCallback(this, callback) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentSearchBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { with(binding.searchInput) { doOnTextChanged { text, _, _, _ -> adapter.applyFilter(text.toString()) } setOnEditorActionListener { v, actionId, event -> var handled = false if (actionId == EditorInfo.IME_ACTION_SEARCH) { processSearchResult(text.toString()) handled = true } handled } binding.searchLayout.hint = if (changeType == TYPE_END) getString(R.string.to) else getString(R.string.from) } binding.entryRecyclerView.adapter = adapter binding.entryRecyclerView.layoutManager = LinearLayoutManager( requireActivity().applicationContext ) var entriesList = listOf<EntryItem>() viewLifecycleOwner.lifecycleScope.launch { withContext(Dispatchers.IO) { entriesList = mainModel.entriesNumber.map { number -> EntryItem(number, destinationDesc(number, requireActivity().applicationContext)) } } adapter.changeList(entriesList) } binding.searchInput.viewRequestInput() viewLifecycleOwner.lifecycleScope.launch { viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) { mainModel.searchUiEvents.collectLatest { uiEvent -> when (uiEvent) { is SearchUiEvent.SearchSuccess -> { binding.searchLayout.error = null binding.searchInput.viewHideInput() findNavController().popBackStack() } is SearchUiEvent.SearchInvalid -> { binding.searchLayout.error = resources.getString(R.string.incorrect_number) binding.searchInput.viewRequestInput() } } } } } } private fun processSearchResult(number: String) { mainModel.onEvent(MainEvent.TrySearch(number, changeType)) } companion object { const val TYPE_START = 0 const val TYPE_END = 1 } }
nexus-farmap/app/src/main/java/com/nexus/farmap/presentation/search/SearchFragment.kt
1214577843
package com.nexus.farmap.presentation.search sealed class SearchUiEvent { object SearchSuccess : SearchUiEvent() object SearchInvalid : SearchUiEvent() }
nexus-farmap/app/src/main/java/com/nexus/farmap/presentation/search/SearchUiEvent.kt
587209771
package com.nexus.farmap.presentation.common.helpers import android.content.Context import android.view.View import android.view.inputmethod.InputMethodManager fun View.viewRequestInput() { viewHideInput() isActivated = true val hasFocus = requestFocus() hasFocus.let { val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager imm.showSoftInput(this, 0) } } fun View.viewHideInput() { val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager imm.hideSoftInputFromWindow(this.windowToken, 0) }
nexus-farmap/app/src/main/java/com/nexus/farmap/presentation/common/helpers/InputFunctions.kt
677422124
package com.nexus.farmap.presentation.common.helpers import android.content.Context import android.hardware.camera2.CameraAccessException import android.hardware.camera2.CameraCharacteristics import android.hardware.camera2.CameraManager import android.hardware.display.DisplayManager import android.hardware.display.DisplayManager.DisplayListener import android.view.Display import android.view.Surface import android.view.WindowManager import com.google.ar.core.Session /** * Helper to track the display rotations. In particular, the 180 degree rotations are not notified * by the onSurfaceChanged() callback, and thus they require listening to the android display * events. */ class DisplayRotationHelper(context: Context) : DisplayListener { private var viewportChanged = false private var viewportWidth = 0 private var viewportHeight = 0 private val display: Display private val displayManager: DisplayManager private val cameraManager: CameraManager /** Registers the display listener. Should be called from [Activity.onResume]. */ fun onResume() { displayManager.registerDisplayListener(this, null) } /** Unregisters the display listener. Should be called from [Activity.onPause]. */ fun onPause() { displayManager.unregisterDisplayListener(this) } /** * Records a change in surface dimensions. This will be later used by [ ][.updateSessionIfNeeded]. Should be called from [ ]. * * @param width the updated width of the surface. * @param height the updated height of the surface. */ fun onSurfaceChanged(width: Int, height: Int) { viewportWidth = width viewportHeight = height viewportChanged = true } /** * Updates the session display geometry if a change was posted either by [ ][.onSurfaceChanged] call or by [.onDisplayChanged] system callback. This * function should be called explicitly before each call to [Session.update]. This * function will also clear the 'pending update' (viewportChanged) flag. * * @param session the [Session] object to update if display geometry changed. */ fun updateSessionIfNeeded(session: Session) { if (viewportChanged) { val displayRotation = display.rotation session.setDisplayGeometry(displayRotation, viewportWidth, viewportHeight) viewportChanged = false } } /** * Returns the aspect ratio of the GL surface viewport while accounting for the display rotation * relative to the device camera sensor orientation. */ fun getCameraSensorRelativeViewportAspectRatio(cameraId: String?): Float { val aspectRatio: Float val cameraSensorToDisplayRotation = getCameraSensorToDisplayRotation(cameraId) aspectRatio = when (cameraSensorToDisplayRotation) { 90, 270 -> viewportHeight.toFloat() / viewportWidth.toFloat() 0, 180 -> viewportWidth.toFloat() / viewportHeight.toFloat() else -> throw RuntimeException("Unhandled rotation: $cameraSensorToDisplayRotation") } return aspectRatio } /** * Returns the rotation of the back-facing camera with respect to the display. The value is one of * 0, 90, 180, 270. */ fun getCameraSensorToDisplayRotation(cameraId: String?): Int { val characteristics: CameraCharacteristics characteristics = try { cameraManager.getCameraCharacteristics(cameraId!!) } catch (e: CameraAccessException) { throw RuntimeException("Unable to determine display orientation", e) } // Camera sensor orientation. val sensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION)!! // Current display orientation. val displayOrientation = toDegrees(display.rotation) // Make sure we return 0, 90, 180, or 270 degrees. return (sensorOrientation - displayOrientation + 360) % 360 } private fun toDegrees(rotation: Int): Int { return when (rotation) { Surface.ROTATION_0 -> 0 Surface.ROTATION_90 -> 90 Surface.ROTATION_180 -> 180 Surface.ROTATION_270 -> 270 else -> throw RuntimeException("Unknown rotation $rotation") } } override fun onDisplayAdded(displayId: Int) {} override fun onDisplayRemoved(displayId: Int) {} override fun onDisplayChanged(displayId: Int) { viewportChanged = true } /** * Constructs the DisplayRotationHelper but does not register the listener yet. * * @param context the Android [Context]. */ init { displayManager = context.getSystemService(Context.DISPLAY_SERVICE) as DisplayManager cameraManager = context.getSystemService(Context.CAMERA_SERVICE) as CameraManager val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager display = windowManager.defaultDisplay } }
nexus-farmap/app/src/main/java/com/nexus/farmap/presentation/common/helpers/DisplayRotationHelper.kt
628908911
package com.nexus.farmap.presentation.common.helpers import android.graphics.Color import android.widget.TextView import androidx.cardview.widget.CardView import androidx.fragment.app.Fragment import androidx.lifecycle.lifecycleScope import com.nexus.farmap.R import com.nexus.farmap.domain.hit_test.OrientatedPosition import com.nexus.farmap.domain.tree.TreeNode import com.google.ar.core.Anchor import com.google.ar.sceneform.math.Quaternion import com.google.ar.sceneform.math.Vector3 import com.google.ar.sceneform.rendering.* import com.uchuhimo.collections.MutableBiMap import io.github.sceneview.ar.ArSceneView import io.github.sceneview.ar.node.ArNode import io.github.sceneview.ar.scene.destroy import io.github.sceneview.math.Position import io.github.sceneview.math.Scale import io.github.sceneview.math.toNewQuaternion import io.github.sceneview.math.toVector3 import kotlinx.coroutines.Job import kotlinx.coroutines.delay import kotlinx.coroutines.future.await import kotlinx.coroutines.launch class DrawerHelper( private val fragment: Fragment, ) { private var labelScale = Scale(0.15f, 0.075f, 0.15f) private var arrowScale = Scale(0.5f, 0.5f, 0.5f) private var labelAnimationDelay = 2L private var arrowAnimationDelay = 2L private var labelAnimationPart = 10 private var arrowAnimationPart = 15 private val animationJobs = mutableMapOf<ArNode, Job>() suspend fun drawNode( treeNode: TreeNode, surfaceView: ArSceneView, anchor: Anchor? = null ): ArNode { return when (treeNode) { is TreeNode.Path -> { drawPath(treeNode, surfaceView, anchor) } is TreeNode.Entry -> { drawEntry(treeNode, surfaceView, anchor) } } } suspend fun removeLink( pair: Pair<ArNode, ArNode>, modelsToLinkModels: MutableBiMap<Pair<ArNode, ArNode>, ArNode> ) { modelsToLinkModels[pair]?.destroy() modelsToLinkModels.remove(pair) } private suspend fun drawPath( treeNode: TreeNode.Path, surfaceView: ArSceneView, anchor: Anchor? = null ): ArNode { val modelNode = ArNode() modelNode.loadModel( context = fragment.requireContext(), glbFileLocation = "models/nexus.glb", ) modelNode.position = treeNode.position modelNode.modelScale = Scale(0.1f) if (anchor != null) { modelNode.anchor = anchor } else { modelNode.anchor = modelNode.createAnchor() } modelNode.model?.let { it.isShadowCaster = false it.isShadowReceiver = false } surfaceView.addChild(modelNode) return modelNode } private suspend fun drawEntry( treeNode: TreeNode.Entry, surfaceView: ArSceneView, anchor: Anchor? = null ): ArNode { return placeLabel( treeNode.number, OrientatedPosition(treeNode.position, treeNode.forwardVector), surfaceView ) } suspend fun placeLabel( label: String, pos: OrientatedPosition, surfaceView: ArSceneView, anchor: Anchor? = null ): ArNode = placeRend( label = label, pos = pos, surfaceView = surfaceView, scale = labelScale, anchor = anchor ) suspend fun placeArrow( pos: OrientatedPosition, surfaceView: ArSceneView ): ArNode = placeRend( pos = pos, surfaceView = surfaceView, scale = arrowScale ) private suspend fun placeRend( label: String? = null, pos: OrientatedPosition, surfaceView: ArSceneView, scale: Scale, anchor: Anchor? = null ): ArNode { var node: ArNode? = null ViewRenderable.builder() .setView(fragment.requireContext(), if (label != null) R.layout.text_sign else R.layout.route_node) .setSizer { Vector3(0f, 0f, 0f) }.setVerticalAlignment(ViewRenderable.VerticalAlignment.CENTER) .setHorizontalAlignment(ViewRenderable.HorizontalAlignment.CENTER).build() .thenAccept { renderable: ViewRenderable -> renderable.let { it.isShadowCaster = false it.isShadowReceiver = false } if (label != null) { val cardView = renderable.view as CardView val textView: TextView = cardView.findViewById(R.id.signTextView) textView.text = label } val textNode = ArNode().apply { setModel( renderable = renderable ) model position = Position(pos.position.x, pos.position.y, pos.position.z) quaternion = pos.orientation if (anchor != null) { this.anchor = anchor } else { this.anchor = this.createAnchor() } } surfaceView.addChild(textNode) node = textNode textNode.animateViewAppear( scale, if (label != null) labelAnimationDelay else arrowAnimationDelay, if (label != null) labelAnimationPart else arrowAnimationPart ) }.await() return node!! } fun removeNode(node: ArNode) { node.destroy() node.anchor?.destroy() animationJobs[node]?.cancel() } fun removeArrowWithAnim(node: ArNode) { node.model as ViewRenderable? ?: throw Exception("No view renderable") node.animateViewDisappear(arrowScale, arrowAnimationDelay, arrowAnimationPart) } fun drawLine( from: ArNode, to: ArNode, modelsToLinkModels: MutableBiMap<Pair<ArNode, ArNode>, ArNode>, surfaceView: ArSceneView ) { val fromVector = from.position.toVector3() val toVector = to.position.toVector3() // Compute a line's length val lineLength = Vector3.subtract(fromVector, toVector).length() // Prepare a color val colorOrange = Color(Color.parseColor("#ffffff")) // 1. make a material by the color MaterialFactory.makeOpaqueWithColor(fragment.requireContext(), colorOrange).thenAccept { material: Material? -> // 2. make a model by the material val model = ShapeFactory.makeCylinder( 0.01f, lineLength, Vector3(0f, lineLength / 2, 0f), material ) model.isShadowCaster = false model.isShadowReceiver = false // 3. make node val node = ArNode() node.setModel(model) node.parent = from surfaceView.addChild(node) // 4. set rotation val difference = Vector3.subtract(toVector, fromVector) val directionFromTopToBottom = difference.normalized() val rotationFromAToB: Quaternion = Quaternion.lookRotation( directionFromTopToBottom, Vector3.up() ) val rotation = Quaternion.multiply( rotationFromAToB, Quaternion.axisAngle(Vector3(1.0f, 0.0f, 0.0f), 270f) ) node.modelQuaternion = rotation.toNewQuaternion() node.position = from.position modelsToLinkModels[Pair(from, to)] = node } } private fun ArNode.animateViewAppear(targetScale: Scale, delay: Long, part: Int) { animateView(true, targetScale, delay, part, end = null) } private fun ArNode.animateViewDisappear(targetScale: Scale, delay: Long, part: Int) { animateView(false, targetScale, delay, part) { removeNode(it) } } private fun ArNode.animateView( appear: Boolean, targetScale: Scale, delay: Long, part: Int, end: ((ArNode) -> Unit)? ) { val renderable = this.model as ViewRenderable? ?: throw Exception("No view renderable") var size = renderable.sizer.getSize(renderable.view) val xPart = targetScale.x / part val yPart = targetScale.y / part val zPart = targetScale.z / part animationJobs[this]?.cancel() animationJobs[this] = fragment.viewLifecycleOwner.lifecycleScope.launch { while (true) { if (size.x >= targetScale.toVector3().x && appear) { break } else if (size.x <= 0 && !appear) { break } renderable.sizer = ViewSizer { if (appear) size.addConst(xPart, yPart, zPart) else size.addConst(xPart, yPart, zPart, -1) } delay(delay) size = renderable.sizer.getSize(renderable.view) } if (end != null) { end(this@animateView) } } } private fun Vector3.addConst(xValue: Float, yValue: Float, zValue: Float, modifier: Int = 1): Vector3 { return Vector3( x + xValue * modifier, y + yValue * modifier, z + zValue * modifier ) } }
nexus-farmap/app/src/main/java/com/nexus/farmap/presentation/common/helpers/DrawerHelper.kt
1092554644
package com.nexus.farmap.presentation.preview import com.nexus.farmap.domain.tree.TreeNode import com.google.ar.core.Anchor sealed interface MainUiEvent { object InitSuccess : MainUiEvent object InitFailed : MainUiEvent object PathNotFound : MainUiEvent object EntryAlreadyExists : MainUiEvent object EntryCreated : MainUiEvent class NodeCreated(val treeNode: TreeNode, val anchor: Anchor? = null) : MainUiEvent class LinkCreated(val node1: TreeNode, val node2: TreeNode) : MainUiEvent class NodeDeleted(val node: TreeNode) : MainUiEvent }
nexus-farmap/app/src/main/java/com/nexus/farmap/presentation/preview/MainUiEvent.kt
2290684724
package com.nexus.farmap.presentation.preview import android.annotation.SuppressLint import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.nexus.farmap.data.App import com.nexus.farmap.domain.hit_test.HitTestResult import com.nexus.farmap.domain.tree.TreeNode import com.nexus.farmap.presentation.LabelObject import com.nexus.farmap.presentation.confirmer.ConfirmFragment import com.nexus.farmap.presentation.preview.state.PathState import com.nexus.farmap.presentation.search.SearchFragment import com.nexus.farmap.presentation.search.SearchUiEvent import dev.romainguy.kotlin.math.Float3 import dev.romainguy.kotlin.math.Quaternion import io.github.sceneview.ar.arcore.ArFrame import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.flow.* import kotlinx.coroutines.launch import kotlinx.coroutines.withContext class MainShareModel : ViewModel() { private val findWay = App.instance!!.findWay private var _pathState = MutableStateFlow(PathState()) val pathState = _pathState.asStateFlow() private var _frame = MutableStateFlow<ArFrame?>(null) val frame = _frame.asStateFlow() private var _mainUiEvents = MutableSharedFlow<MainUiEvent>() val mainUiEvents = _mainUiEvents.asSharedFlow() private var _searchUiEvents = MutableSharedFlow<SearchUiEvent>() val searchUiEvents = _searchUiEvents.asSharedFlow() @SuppressLint("StaticFieldLeak") private var _confirmationObject = MutableStateFlow<LabelObject?>(null) val confirmationObject = _confirmationObject.asStateFlow() private var _selectedNode = MutableStateFlow<TreeNode?>(null) val selectedNode = _selectedNode.asStateFlow() private var _linkPlacementMode = MutableStateFlow(false) val linkPlacementMode = _linkPlacementMode.asStateFlow() private var tree = App.instance!!.getTree() val treeDiffUtils = tree.diffUtils val entriesNumber = tree.getEntriesNumbers() private var pathfindJob: Job? = null init { preload() } fun onEvent(event: MainEvent) { when (event) { is MainEvent.NewFrame -> { viewModelScope.launch { _frame.emit(event.frame) } } is MainEvent.NewConfirmationObject -> { _confirmationObject.update { event.confObject } } is MainEvent.TrySearch -> { viewModelScope.launch { processSearch(event.number, event.changeType) } } is MainEvent.AcceptConfObject -> { when (event.confirmType) { ConfirmFragment.CONFIRM_INITIALIZE -> { viewModelScope.launch { _confirmationObject.value?.let { initialize( it.label, it.pos.position, it.pos.orientation ) _confirmationObject.update { null } } } } ConfirmFragment.CONFIRM_ENTRY -> { viewModelScope.launch { _confirmationObject.value?.let { createNode( number = it.label, position = it.pos.position, orientation = it.pos.orientation ) _confirmationObject.update { null } } } } } } is MainEvent.RejectConfObject -> { viewModelScope.launch { _confirmationObject.update { null } } } is MainEvent.NewSelectedNode -> { viewModelScope.launch { _selectedNode.update { event.node } } } is MainEvent.ChangeLinkMode -> { viewModelScope.launch { _linkPlacementMode.update { !linkPlacementMode.value } } } is MainEvent.CreateNode -> { viewModelScope.launch { createNode( number = event.number, position = event.position, orientation = event.orientation, hitTestResult = event.hitTestResult ) } } is MainEvent.LinkNodes -> { viewModelScope.launch { linkNodes(event.node1, event.node2) } } is MainEvent.DeleteNode -> { viewModelScope.launch { removeNode(event.node) } } } } private suspend fun processSearch(number: String, changeType: Int) { val entry = tree.getEntry(number) if (entry == null) { _searchUiEvents.emit(SearchUiEvent.SearchInvalid) return } else { if (changeType == SearchFragment.TYPE_START) { val endEntry = pathState.value.endEntry _pathState.update { PathState( startEntry = entry, endEntry = if (entry.number == endEntry?.number) null else endEntry ) } } else { val startEntry = pathState.value.startEntry _pathState.update { PathState( startEntry = if (entry.number == startEntry?.number) null else startEntry, endEntry = entry ) } } //Search successes pathfindJob?.cancel() pathfindJob = viewModelScope.launch { pathfind() } _searchUiEvents.emit(SearchUiEvent.SearchSuccess) } } private suspend fun pathfind() { val from = pathState.value.startEntry?.number ?: return val to = pathState.value.endEntry?.number ?: return if (tree.getEntry(from) != null && tree.getEntry(to) != null) { val path = findWay(from, to, tree) if (path != null) { _pathState.update { it.copy( path = path ) } } else { _mainUiEvents.emit(MainUiEvent.PathNotFound) } } else { throw Exception("Unknown tree nodes") } } private suspend fun createNode( number: String? = null, position: Float3? = null, orientation: Quaternion? = null, hitTestResult: HitTestResult? = null, ) { if (position == null && hitTestResult == null) { throw Exception("No position was provided") } if (number != null && tree.hasEntry(number)) { _mainUiEvents.emit(MainUiEvent.EntryAlreadyExists) return } val treeNode = tree.addNode( position ?: hitTestResult!!.orientatedPosition.position, number, orientation ) treeNode.let { if (number != null) { _mainUiEvents.emit(MainUiEvent.EntryCreated) } _mainUiEvents.emit( MainUiEvent.NodeCreated( treeNode, hitTestResult?.hitResult?.createAnchor() ) ) } } private suspend fun linkNodes(node1: TreeNode, node2: TreeNode) { if (tree.addLink(node1, node2)) { _linkPlacementMode.update { false } _mainUiEvents.emit(MainUiEvent.LinkCreated(node1, node2)) } } private suspend fun removeNode(node: TreeNode) { tree.removeNode(node) _mainUiEvents.emit(MainUiEvent.NodeDeleted(node)) if (node == selectedNode.value) { _selectedNode.update { null } } if (node == pathState.value.endEntry) { _pathState.update { it.copy(endEntry = null, path = null) } } else if (node == pathState.value.startEntry) { _pathState.update { it.copy(startEntry = null, path = null) } } } private suspend fun initialize(entryNumber: String, position: Float3, newOrientation: Quaternion): Boolean { var result: Result<Unit?> withContext(Dispatchers.IO) { result = tree.initialize(entryNumber, position, newOrientation) } if (result.isFailure) { _mainUiEvents.emit(MainUiEvent.InitFailed) return false } _mainUiEvents.emit(MainUiEvent.InitSuccess) val entry = tree.getEntry(entryNumber) if (entry != null) { _pathState.update { PathState( startEntry = entry ) } } else { _pathState.update { PathState() } } return true } private fun preload() { viewModelScope.launch { tree.preload() } } }
nexus-farmap/app/src/main/java/com/nexus/farmap/presentation/preview/MainShareModel.kt
263953695
package com.nexus.farmap.presentation.preview.state import com.nexus.farmap.domain.pathfinding.Path import com.nexus.farmap.domain.tree.TreeNode data class PathState( val startEntry: TreeNode.Entry? = null, val endEntry: TreeNode.Entry? = null, val path: Path? = null )
nexus-farmap/app/src/main/java/com/nexus/farmap/presentation/preview/state/PathState.kt
3782352864
package com.nexus.farmap.presentation.preview import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.lifecycle.Lifecycle import androidx.lifecycle.lifecycleScope import androidx.lifecycle.repeatOnLifecycle import com.nexus.farmap.R import com.nexus.farmap.data.App import com.nexus.farmap.databinding.FragmentPreviewBinding import com.nexus.farmap.domain.tree.TreeNode import com.nexus.farmap.presentation.LabelObject import com.nexus.farmap.presentation.common.helpers.DrawerHelper import com.nexus.farmap.presentation.preview.nodes_adapters.PathAdapter import com.nexus.farmap.presentation.preview.nodes_adapters.TreeAdapter import com.nexus.farmap.presentation.preview.state.PathState import com.nexus.farmap.presentation.preview.MainShareModel import com.nexus.farmap.presentation.preview.MainUiEvent import com.nexus.farmap.presentation.preview.MainEvent import com.google.android.material.snackbar.Snackbar import com.google.ar.core.TrackingState import com.google.ar.core.exceptions.* import com.uchuhimo.collections.MutableBiMap import com.uchuhimo.collections.mutableBiMapOf import dev.romainguy.kotlin.math.Float3 import io.github.sceneview.ar.arcore.ArFrame import io.github.sceneview.ar.node.ArNode import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.launch class PreviewFragment : Fragment() { private val mainModel: MainShareModel by activityViewModels() private var _binding: FragmentPreviewBinding? = null private val binding get() = _binding!! private val drawerHelper = DrawerHelper(this) private var endPlacingJob: Job? = null private var startPlacingJob: Job? = null private var wayBuildingJob: Job? = null private var treeBuildingJob: Job? = null private var currentPathState: PathState? = null private var lastPositionTime = 0L private lateinit var pathAdapter: PathAdapter private lateinit var treeAdapter: TreeAdapter private var lastConfObject: LabelObject? = null private var confObjectJob: Job? = null private val treeNodesToModels: MutableBiMap<TreeNode, ArNode> = mutableBiMapOf() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentPreviewBinding.inflate(inflater, container, false) return binding.root } override fun onResume() { super.onResume() binding.sceneView.onResume(this) } override fun onPause() { super.onPause() binding.sceneView.onPause(this) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { //TODO process pause and resume pathAdapter = PathAdapter( drawerHelper, binding.sceneView, VIEWABLE_PATH_NODES, viewLifecycleOwner.lifecycleScope ) treeAdapter = TreeAdapter( drawerHelper, binding.sceneView, DEFAULT_BUFFER_SIZE, viewLifecycleOwner.lifecycleScope ) binding.sceneView.apply { planeRenderer.isVisible = true instructions.enabled = false onArFrame = { frame -> onDrawFrame(frame) } onTouch = { node, _ -> if (App.mode == App.ADMIN_MODE) { node?.let { it -> if (!mainModel.linkPlacementMode.value) { selectNode(it as ArNode) } else { val treeNode = mainModel.selectedNode.value treeAdapter.getArNode(treeNode)?.let { node1 -> linkNodes(node1, it as ArNode) } } } } true } onArSessionFailed = { exception -> val message = when (exception) { is UnavailableArcoreNotInstalledException, is UnavailableUserDeclinedInstallationException -> getString( R.string.install_arcode ) is UnavailableApkTooOldException -> getString(R.string.update_arcode) is UnavailableSdkTooOldException -> getString(R.string.update_app) is UnavailableDeviceNotCompatibleException -> getString(R.string.no_arcore_support) is CameraNotAvailableException -> getString(R.string.camera_not_available) is SecurityException -> getString(R.string.provide_camera_permission) else -> getString(R.string.failed_to_create_session) } Toast.makeText(requireContext(), message, Toast.LENGTH_LONG).show() } } selectNode(null) viewLifecycleOwner.lifecycleScope.launch { viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) { mainModel.pathState.collectLatest { pathState -> //All entry labels are drawn automatically in ADMIN_MODE. if (currentPathState?.endEntry != pathState.endEntry) { endPlacingJob?.cancel() currentPathState?.endEntry?.let { end -> treeNodesToModels[end]?.let { drawerHelper.removeNode(it) } } endPlacingJob = viewLifecycleOwner.lifecycleScope.launch { pathState.endEntry?.let { end -> treeNodesToModels[end] = drawerHelper.drawNode( end, binding.sceneView, ) } } } if (currentPathState?.startEntry != pathState.startEntry) { startPlacingJob?.cancel() currentPathState?.startEntry?.let { start -> treeNodesToModels[start]?.let { drawerHelper.removeNode(it) } } startPlacingJob = viewLifecycleOwner.lifecycleScope.launch { pathState.startEntry?.let { start -> treeNodesToModels[start] = drawerHelper.drawNode( start, binding.sceneView, ) } } } currentPathState = pathState } } } viewLifecycleOwner.lifecycleScope.launch { viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) { mainModel.mainUiEvents.collectLatest { uiEvent -> when (uiEvent) { is MainUiEvent.InitFailed -> { showSnackbar(getString(R.string.init_failed)) } is MainUiEvent.NodeCreated -> { showSnackbar(getString(R.string.node_created)) } is MainUiEvent.LinkCreated -> { viewLifecycleOwner.lifecycleScope.launch { treeAdapter.createLink(uiEvent.node1, uiEvent.node2) showSnackbar(getString(R.string.link_created)) } } is MainUiEvent.NodeDeleted -> { showSnackbar(getString(R.string.node_deleted)) } is MainUiEvent.PathNotFound -> { showSnackbar(getString(R.string.no_path)) } is MainUiEvent.EntryAlreadyExists -> { showSnackbar(getString(R.string.entry_already_exists)) } else -> {} } } } } viewLifecycleOwner.lifecycleScope.launch { viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) { mainModel.confirmationObject.collectLatest { confObject -> confObjectJob?.cancel() confObjectJob = viewLifecycleOwner.lifecycleScope.launch { lastConfObject?.node?.let { drawerHelper.removeNode(it) } confObject?.let { it.node = drawerHelper.placeLabel( confObject.label, confObject.pos, binding.sceneView ) lastConfObject = it } } } } } } private fun onDrawFrame(frame: ArFrame) { val camera = frame.camera // Handle tracking failures. if (camera.trackingState != TrackingState.TRACKING) { return } mainModel.onEvent( MainEvent.NewFrame(frame) ) val userPos = Float3( frame.camera.displayOrientedPose.tx(), frame.camera.displayOrientedPose.ty(), frame.camera.displayOrientedPose.tz() ) if (System.currentTimeMillis() - lastPositionTime > POSITION_DETECT_DELAY) { lastPositionTime = System.currentTimeMillis() changeViewablePath(userPos) if (App.mode == App.ADMIN_MODE) { changeViewableTree(userPos) mainModel.selectedNode.value?.let { node -> checkSelectedNode(node) } } } } private fun selectNode(node: ArNode?) { // User selected entry can be stored in PreviewFragment nodes map, // if this node displayed as PathState start or end val treeNode = treeNodesToModels.inverse[node] ?: treeAdapter.getTreeNode(node) mainModel.onEvent(MainEvent.NewSelectedNode(treeNode)) } private fun checkSelectedNode(treeNode: TreeNode) { if (treeAdapter.getArNode(treeNode) == null) { mainModel.onEvent(MainEvent.NewSelectedNode(null)) } } private fun linkNodes(node1: ArNode, node2: ArNode) { viewLifecycleOwner.lifecycleScope.launch { val path1: TreeNode? = treeAdapter.getTreeNode(node1) val path2: TreeNode? = treeAdapter.getTreeNode(node2) if (path1 != null && path2 != null) { mainModel.onEvent(MainEvent.LinkNodes(path1, path2)) } } } private fun changeViewablePath(userPosition: Float3) { wayBuildingJob?.cancel() wayBuildingJob = viewLifecycleOwner.lifecycleScope.launch(Dispatchers.Default) { val nodes = currentPathState?.path?.getNearNodes( number = VIEWABLE_PATH_NODES, position = userPosition ) pathAdapter.commit(nodes ?: listOf()) } } //ONLY FOR ADMIN MODE private fun changeViewableTree(userPosition: Float3) { if (treeBuildingJob?.isCompleted == true || treeBuildingJob?.isCancelled == true || treeBuildingJob == null) { treeBuildingJob?.cancel() treeBuildingJob = viewLifecycleOwner.lifecycleScope.launch(Dispatchers.Default) { val nodes = mainModel.treeDiffUtils.getNearNodes( radius = VIEWABLE_ADMIN_NODES, position = userPosition ) treeAdapter.commit(nodes) } } } private fun showSnackbar(message: String) { Snackbar.make(binding.sceneView, message, Snackbar.LENGTH_SHORT).show() } companion object { //How many path nodes will be displayed at the moment const val VIEWABLE_PATH_NODES = 32 //Distance of viewable nodes for admin mode const val VIEWABLE_ADMIN_NODES = 8f //How often the check for path and tree redraw will be in millisecond const val POSITION_DETECT_DELAY = 100L //Image crop percentage for recognition val DESIRED_CROP = Pair(0, 0) } }
nexus-farmap/app/src/main/java/com/nexus/farmap/presentation/preview/PreviewFragment.kt
4123906793
package com.nexus.farmap.presentation.preview.nodes_adapters import androidx.lifecycle.LifecycleCoroutineScope import com.nexus.farmap.domain.hit_test.OrientatedPosition import com.nexus.farmap.presentation.common.helpers.DrawerHelper import io.github.sceneview.ar.ArSceneView import io.github.sceneview.ar.node.ArNode class PathAdapter( drawerHelper: DrawerHelper, previewView: ArSceneView, bufferSize: Int, scope: LifecycleCoroutineScope, ) : NodesAdapter<OrientatedPosition>(drawerHelper, previewView, bufferSize, scope) { override suspend fun onInserted(item: OrientatedPosition): ArNode = drawerHelper.placeArrow(item, previewView) override suspend fun onRemoved(item: OrientatedPosition, node: ArNode) = drawerHelper.removeArrowWithAnim(node) }
nexus-farmap/app/src/main/java/com/nexus/farmap/presentation/preview/nodes_adapters/PathAdapter.kt
3658976602
package com.nexus.farmap.presentation.preview.nodes_adapters import androidx.lifecycle.LifecycleCoroutineScope import com.nexus.farmap.presentation.common.helpers.DrawerHelper import io.github.sceneview.ar.ArSceneView import io.github.sceneview.ar.node.ArNode import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.channels.BufferOverflow import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.withContext abstract class NodesAdapter<T>( val drawerHelper: DrawerHelper, val previewView: ArSceneView, bufferSize: Int, scope: LifecycleCoroutineScope ) { protected val nodes = mutableMapOf<T, ArNode>() private val changesFlow = MutableSharedFlow<DiffOperation<T>>( replay = 0, extraBufferCapacity = bufferSize, onBufferOverflow = BufferOverflow.DROP_OLDEST ) init { scope.launchWhenStarted { changesFlow.collect { change -> when (change) { is DiffOperation.Deleted -> { nodes[change.item]?.let { nodes.remove(change.item) onRemoved(change.item, it) } } is DiffOperation.Added -> { if (nodes[change.item] == null) { nodes[change.item] = onInserted(change.item) } } } } } } suspend fun commit(newList: List<T>) { calculateChanges(newList) } private suspend fun calculateChanges(newList: List<T>) = withContext(Dispatchers.Default) { nodes.keys.asSequence().minus(newList).map { item -> DiffOperation.Deleted(item) }.forEach { change -> changesFlow.tryEmit(change) } newList.asSequence().minus(nodes.keys).map { item -> DiffOperation.Added(item) } .forEach { change -> changesFlow.tryEmit(change) } } abstract suspend fun onInserted(item: T): ArNode abstract suspend fun onRemoved(item: T, node: ArNode) sealed class DiffOperation<out T> { class Added<out T>(val item: T) : DiffOperation<T>() class Deleted<out T>(val item: T) : DiffOperation<T>() } }
nexus-farmap/app/src/main/java/com/nexus/farmap/presentation/preview/nodes_adapters/NodesAdapter.kt
632047783
package com.nexus.farmap.presentation.preview.nodes_adapters import androidx.lifecycle.LifecycleCoroutineScope import com.nexus.farmap.domain.tree.TreeNode import com.nexus.farmap.presentation.common.helpers.DrawerHelper import com.uchuhimo.collections.MutableBiMap import com.uchuhimo.collections.mutableBiMapOf import io.github.sceneview.ar.ArSceneView import io.github.sceneview.ar.node.ArNode class TreeAdapter( drawerHelper: DrawerHelper, previewView: ArSceneView, bufferSize: Int, scope: LifecycleCoroutineScope, ) : NodesAdapter<TreeNode>(drawerHelper, previewView, bufferSize, scope) { private val modelsToLinkModels: MutableBiMap<Pair<ArNode, ArNode>, ArNode> = mutableBiMapOf() override suspend fun onInserted(item: TreeNode): ArNode { val node1 = drawerHelper.drawNode(item, previewView) for (id in item.neighbours) { nodes.keys.firstOrNull { it.id == id }?.let { treeNode -> nodes[treeNode]?.let { node2 -> if (modelsToLinkModels[Pair(node1, node2)] == null) { drawerHelper.drawLine( node1, node2, modelsToLinkModels, previewView ) } } } } return node1 } override suspend fun onRemoved(item: TreeNode, node: ArNode) { drawerHelper.removeNode(node) modelsToLinkModels.keys.filter { it.first == node || it.second == node }.forEach { pair -> drawerHelper.removeLink(pair, modelsToLinkModels) } } suspend fun createLink(treeNode1: TreeNode, treeNode2: TreeNode) { val node1 = nodes[treeNode1] val node2 = nodes[treeNode2] if (node1 != null && node2 != null) { drawerHelper.drawLine( node1, node2, modelsToLinkModels, previewView ) } } fun getArNode(treeNode: TreeNode?): ArNode? = nodes[treeNode] fun getTreeNode(node: ArNode?): TreeNode? { node?.let { return nodes.entries.find { it.value == node }?.key } return null } }
nexus-farmap/app/src/main/java/com/nexus/farmap/presentation/preview/nodes_adapters/TreeAdapter.kt
367282932
package com.nexus.farmap.presentation.preview import com.nexus.farmap.domain.hit_test.HitTestResult import com.nexus.farmap.domain.tree.TreeNode import com.nexus.farmap.presentation.LabelObject import dev.romainguy.kotlin.math.Float3 import dev.romainguy.kotlin.math.Quaternion import io.github.sceneview.ar.arcore.ArFrame sealed interface MainEvent { class NewFrame(val frame: ArFrame) : MainEvent class NewConfirmationObject(val confObject: LabelObject) : MainEvent class TrySearch(val number: String, val changeType: Int) : MainEvent class AcceptConfObject(val confirmType: Int) : MainEvent class RejectConfObject(val confirmType: Int) : MainEvent class NewSelectedNode(val node: TreeNode?) : MainEvent object ChangeLinkMode : MainEvent class CreateNode( val number: String? = null, val position: Float3? = null, val orientation: Quaternion? = null, val hitTestResult: HitTestResult ) : MainEvent class DeleteNode(val node: TreeNode) : MainEvent class LinkNodes(val node1: TreeNode, val node2: TreeNode) : MainEvent }
nexus-farmap/app/src/main/java/com/nexus/farmap/presentation/preview/MainEvent.kt
1161096757
package com.nexus.farmap.presentation.scanner import android.content.Context import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.lifecycle.Lifecycle import androidx.lifecycle.lifecycleScope import androidx.lifecycle.repeatOnLifecycle import androidx.navigation.fragment.findNavController import androidx.navigation.fragment.navArgs import com.nexus.farmap.data.App import com.nexus.farmap.databinding.FragmentScannerBinding import com.nexus.farmap.domain.hit_test.HitTestResult import com.nexus.farmap.domain.ml.DetectedText import com.nexus.farmap.presentation.LabelObject import com.nexus.farmap.presentation.common.helpers.DisplayRotationHelper import com.nexus.farmap.presentation.confirmer.ConfirmFragment import com.nexus.farmap.presentation.preview.MainEvent import com.nexus.farmap.presentation.preview.MainShareModel import com.nexus.farmap.presentation.preview.PreviewFragment import com.google.ar.core.TrackingState import com.google.ar.core.exceptions.NotYetAvailableException import dev.romainguy.kotlin.math.Float2 import io.github.sceneview.ar.arcore.ArFrame import kotlinx.coroutines.Job import kotlinx.coroutines.launch private const val SMOOTH_DELAY = 0.5 class ScannerFragment : Fragment() { private val mainModel: MainShareModel by activityViewModels() private var _binding: FragmentScannerBinding? = null private val binding get() = _binding!! private val args: ScannerFragmentArgs by navArgs() private val scanType by lazy { args.scanType } private val hitTest = App.instance!!.hitTest private val analyzeImage = App.instance!!.analyzeImage private lateinit var displayRotationHelper: DisplayRotationHelper private var lastDetectedObject: DetectedText? = null private var scanningNow: Boolean = false private var currentScanSmoothDelay: Double = 0.0 private var scanningJob: Job? = null private var lastFrameTime = System.currentTimeMillis() private var navigating = false override fun onAttach(context: Context) { super.onAttach(context) displayRotationHelper = DisplayRotationHelper(context) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentScannerBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { viewLifecycleOwner.lifecycleScope.launch { viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) { mainModel.frame.collect { frame -> frame?.let { onFrame(it) } } } } } override fun onResume() { lastDetectedObject = null scanningNow = false currentScanSmoothDelay = 0.0 scanningJob?.cancel() scanningJob = null navigating = false super.onResume() displayRotationHelper.onResume() } override fun onPause() { super.onPause() displayRotationHelper.onPause() } private fun onFrame(frame: ArFrame) { if (currentScanSmoothDelay > 0) { currentScanSmoothDelay -= getFrameInterval() } if (!scanningNow) { if (scanningJob?.isActive != true) { scanningJob?.cancel() scanningJob = viewLifecycleOwner.lifecycleScope.launch { if (currentScanSmoothDelay <= 0 && lastDetectedObject != null) { val res = hitTestDetectedObject(lastDetectedObject!!, frame) if (res != null && !navigating) { val confirmationObject = LabelObject( label = lastDetectedObject!!.detectedObjectResult.label, pos = res.orientatedPosition, anchor = res.hitResult.createAnchor() ) mainModel.onEvent( MainEvent.NewConfirmationObject( confirmationObject ) ) toConfirm( when (scanType) { TYPE_INITIALIZE -> { ConfirmFragment.CONFIRM_INITIALIZE } TYPE_ENTRY -> { ConfirmFragment.CONFIRM_ENTRY } else -> { throw IllegalArgumentException("Unrealised type") } } ) } else { currentScanSmoothDelay = SMOOTH_DELAY } } else { scanningNow = true val detectedObject = tryGetDetectedObject(frame) if (lastDetectedObject == null) { lastDetectedObject = detectedObject currentScanSmoothDelay = SMOOTH_DELAY } else if (detectedObject == null) { currentScanSmoothDelay = SMOOTH_DELAY } else { if (lastDetectedObject!!.detectedObjectResult.label != detectedObject.detectedObjectResult.label) { currentScanSmoothDelay = SMOOTH_DELAY } lastDetectedObject = detectedObject } scanningNow = false } } } } } private fun toConfirm(type: Int) { if (!navigating) { navigating = true val action = ScannerFragmentDirections.actionScannerFragmentToConfirmFragment( type ) findNavController().navigate(action) } } private suspend fun tryGetDetectedObject(frame: ArFrame): DetectedText? { val camera = frame.camera val session = frame.session if (camera.trackingState != TrackingState.TRACKING) { return null } val cameraImage = frame.tryAcquireCameraImage() if (cameraImage != null) { val cameraId = session.cameraConfig.cameraId val imageRotation = displayRotationHelper.getCameraSensorToDisplayRotation(cameraId) val displaySize = Pair( session.displayWidth, session.displayHeight ) val detectedResult = analyzeImage( cameraImage, imageRotation, PreviewFragment.DESIRED_CROP, displaySize ) cameraImage.close() detectedResult.getOrNull()?.let { return DetectedText(it, frame.frame) } return null } cameraImage?.close() return null } private fun hitTestDetectedObject(detectedText: DetectedText, frame: ArFrame): HitTestResult? { val detectedObject = detectedText.detectedObjectResult return useHitTest( detectedObject.centerCoordinate.x, detectedObject.centerCoordinate.y, frame ).getOrNull() } private fun useHitTest( x: Float, y: Float, frame: ArFrame ): Result<HitTestResult> { return hitTest(frame, Float2(x, y)) } private fun getFrameInterval(): Long { val frameTime = System.currentTimeMillis() - lastFrameTime lastFrameTime = System.currentTimeMillis() return frameTime } private fun ArFrame.tryAcquireCameraImage() = try { frame.acquireCameraImage() } catch (e: NotYetAvailableException) { null } catch (e: Throwable) { throw e } companion object { const val SCAN_TYPE = "scanType" const val TYPE_INITIALIZE = 0 const val TYPE_ENTRY = 1 } }
nexus-farmap/app/src/main/java/com/nexus/farmap/presentation/scanner/ScannerFragment.kt
3321419975
package com.nexus.farmap.presentation.router import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.view.isGone import androidx.core.view.isVisible import androidx.fragment.app.activityViewModels import androidx.lifecycle.Lifecycle import androidx.lifecycle.lifecycleScope import androidx.lifecycle.repeatOnLifecycle import androidx.navigation.fragment.findNavController import com.nexus.farmap.R import com.nexus.farmap.data.App import com.nexus.farmap.databinding.FragmentRouterBinding import com.nexus.farmap.domain.hit_test.HitTestResult import com.nexus.farmap.presentation.preview.MainEvent import com.nexus.farmap.presentation.preview.MainShareModel import com.nexus.farmap.presentation.scanner.ScannerFragment import com.nexus.farmap.presentation.search.SearchFragment import dev.romainguy.kotlin.math.Float2 import dev.romainguy.kotlin.math.Float3 import dev.romainguy.kotlin.math.Quaternion import io.github.sceneview.ar.arcore.ArFrame import kotlinx.coroutines.launch class RouterFragment : Fragment() { private val destinationDesc = App.instance!!.getDestinationDesc private val hitTest = App.instance!!.hitTest private val mainModel: MainShareModel by activityViewModels() private var _binding: FragmentRouterBinding? = null private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentRouterBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { if (App.mode == App.ADMIN_MODE) { binding.adminPanel.isVisible = true } else { binding.adminPanel.isGone = true } binding.adminButton.setOnClickListener { toggleAdmin() } binding.deleteButton.setOnClickListener { removeSelectedNode() } binding.linkButton.setOnClickListener { changeLinkPlacementMode() } binding.placeButton.setOnClickListener { viewLifecycleOwner.lifecycleScope.launch { createNode() } } binding.entryButton.setOnClickListener { val bundle = Bundle() bundle.putInt( ScannerFragment.SCAN_TYPE, ScannerFragment.TYPE_ENTRY ) findNavController().navigate(R.id.action_global_scannerFragment, args = bundle) } binding.fromInput.setOnFocusChangeListener { _, b -> if (b) { binding.fromInput.isActivated = false binding.fromInput.clearFocus() search(SearchFragment.TYPE_START) } } binding.toInput.setOnFocusChangeListener { _, b -> if (b) { binding.toInput.isActivated = false binding.toInput.clearFocus() search(SearchFragment.TYPE_END) } } viewLifecycleOwner.lifecycleScope.launch { viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) { mainModel.pathState.collect { pathState -> binding.fromInput.setText(pathState.startEntry?.number ?: "") binding.toInput.setText(pathState.endEntry?.number ?: "") if (pathState.path != null) { binding.destinationText.isVisible = true binding.destinationText.text = resources.getString( R.string.going, destinationDesc(pathState.endEntry!!.number, requireContext()) ) } else { binding.destinationText.isGone = true } } } } viewLifecycleOwner.lifecycleScope.launch { viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) { mainModel.selectedNode.collect { treeNode -> binding.linkButton.isEnabled = treeNode != null binding.deleteButton.isEnabled = treeNode != null } } } viewLifecycleOwner.lifecycleScope.launch { viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) { mainModel.linkPlacementMode.collect { link -> binding.linkButton.text = if (link) getString(R.string.cancel) else getString(R.string.link) } } } } private fun search(type: Int) { val action = RouterFragmentDirections.actionRouterFragmentToSearchFragment( type ) findNavController().navigate(action) } private fun changeLinkPlacementMode() { mainModel.onEvent(MainEvent.ChangeLinkMode) } private fun toggleAdmin() { if (App.mode == App.ADMIN_MODE) App.mode = App.USER_MODE else App.mode = App.ADMIN_MODE } private fun removeSelectedNode() { mainModel.selectedNode.value?.let { mainModel.onEvent(MainEvent.DeleteNode(it)) } } private fun createNode( number: String? = null, position: Float3? = null, orientation: Quaternion? = null, ) { viewLifecycleOwner.lifecycleScope.launch { mainModel.frame.value?.let { frame -> val result = useHitTest(frame).getOrNull() if (result != null) { mainModel.onEvent( MainEvent.CreateNode( number, position, orientation, result ) ) } } } } private fun useHitTest( frame: ArFrame, x: Float = frame.session.displayWidth / 2f, y: Float = frame.session.displayHeight / 2f, ): Result<HitTestResult> { return hitTest(frame, Float2(x, y)) } }
nexus-farmap/app/src/main/java/com/nexus/farmap/presentation/router/RouterFragment.kt
3337784668
fun printYearCalendar(year: Int) { println("---------------------\n") println("-----------$year----------\n") println("---------------------\n") for (i in 1..12) { printMonthCalendar(year, i) println() } }
problem_solvingLev3/src/YearCalender.kt
1283245231
fun getDate(year: Int, totalDays: Int): String { var startMonth = 1 var daysInMonth: Int var reminder = totalDays val days: Int; while (true) { daysInMonth = daysInMonth(year, startMonth) if (reminder > daysInMonth) { reminder -= daysInMonth startMonth++ } else { days = reminder break } } return "date for [$totalDays] : $days/$startMonth/$year" }
problem_solvingLev3/src/getDateFromTotelOfDays.kt
2765007750
fun totalDayFromBeginningOfYear(day: Int, month: Int, year: Int): Int { var counter = 0 for (i in 1..<month) { counter += daysInMonth(year, i) } counter += day return counter }
problem_solvingLev3/src/TotalDays.kt
546277472
fun daysInYear(year: Int): Int { return if (isLeapYear(year)) 366 else 365 } fun hours(year: Int) = daysInYear(year) * 24 fun minutes(year: Int) = hours(year) * 60 fun seconds(year: Int) = minutes(year) * 60
problem_solvingLev3/src/PrintDataInLeapYear.kt
3393515367
//TIP To <b>Run</b> code, press <shortcut actionId="Run"/> or // click the <icon src="AllIcons.Actions.Execute"/> icon in the gutter. fun readNumber(msg: String): Int { print(msg) val number = readln().toInt() return number } fun main() { }
problem_solvingLev3/src/Main.kt
1088117531
fun monthDayName(month: Int): String { val monthName = listOf( "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ) return monthName[month-1] } fun printMonthCalendar(year: Int, month: Int) { val current = gregorianCalender(1, month, year) val numberOfDaysInMonth = daysInMonth(year, month) println("----------${monthDayName(month)}-----------") print("Sun Mon Tue Wed The Fri Sat\n") var index = current for (j in 1..current) { print(" ") } for (i in 1..numberOfDaysInMonth) { print("$i ") if (++index == 7) { index = 0 println() } } println("\n--------------------------------") }
problem_solvingLev3/src/MonthCalender.kt
3031277457
fun getDateAfterAddMoreDays(year: Int, totalDays: Int): String { var currentYear = year var startMonth = 1 var daysInMonth: Int var reminder = totalDays val days: Int while (true) { daysInMonth = daysInMonth(currentYear, startMonth) if (reminder > daysInMonth) { reminder -= daysInMonth startMonth++ if (startMonth == 12) currentYear++ } else { days = reminder break } } return "date for [$totalDays] : $days/$startMonth/$currentYear" }
problem_solvingLev3/src/getDateAfterAddingMoreDays.kt
4214981724
fun gregorianCalender(day: Int, month: Int, year: Int): Int { val a = (14 - month) / 12 val y = year - a val m = month + (12 * a) - 2 return (day + y + (y / 4) - (y / 100) + (y / 400) + ((31 * m) / 12)) % 7 } fun shortDayName(day: Int): String { val arrayOfDay = listOf("Sun", "Mon", "Tue", "Wed", "The", "Fri", "Sat") return arrayOfDay[day] }
problem_solvingLev3/src/dayInWeek.kt
1665738101
/* * * Check is The Year User entered Is Leap or not * * */ fun isLeapYear(year: Int): Boolean { return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0 }
problem_solvingLev3/src/isLeapYear.kt
1861209480
fun daysInMonth(year: Int, month: Int): Int { if (month < 1 || month > 12) return 0 if (month == 2) { return if (isLeapYear(year)) 29 else 28 } else if (month == 4 || month == 6 || month == 9 || month == 11) return 30 return 31 } fun hours(year: Int, month: Int) = daysInMonth(year, month) * 24 fun minutes(year: Int, month: Int) = hours(year, month) * 60 fun seconds(year: Int, month: Int) = minutes(year, month) * 60
problem_solvingLev3/src/PrintNumberInMonth.kt
242581140
package app.xlei.vipexam.core.ui import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("app.xlei.vipexam.core.ui.test", appContext.packageName) } }
vipexam/core/ui/src/androidTest/java/app/xlei/vipexam/core/ui/ExampleInstrumentedTest.kt
3447633109