path
stringlengths
4
297
contentHash
stringlengths
1
10
content
stringlengths
0
13M
AndroidSt_Calculator/app/src/main/java/com/example/ivanov_calc/MainActivity.kt
681265143
package com.example.ivanov_calc import androidx.appcompat.app.AppCompatActivity import android.os.Bundle class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } }
MyKotlinNotes/src/Ch15.kt
574656394
/***** Interface resolve conflict *****/ interface A{ fun callMe(){ println("From interface A") } } interface B { fun callMe(){ println("From interface B") } } class C:A,B{ override fun callMe() { super<A>.callMe() super<B>.callMe() } } fun main() { val obj = C() obj.callMe() }
MyKotlinNotes/src/Ch11.kt
905894744
/****** Inheritance with Primary and Secondary Constructor with overriding *******/ open class Father2(_car: String, _money: Int) { // Properties open var car: String = _car var money: Int = _money // Member Function open fun disp() { println("Father Class Disp") } } class Son2 : Father2 { // Properties var bike: String override var car:String = "BMW" // Overriding Properties of father var fcar:String = super.car // Secondary Constructor constructor(_car: String, _money: Int, _bike: String) : super(_car, _money) { this.bike = _bike } // Member Function fun show() { println("Son bike: $bike") println("Son car: $car") println("Father car: $fcar") println("Father Money: $money") } override fun disp (){ println("Son Class Disp") } } fun main() { println("*********") // Using the secondary constructor val s1 = Son2("Alt 100", 1000, "K10") s1.show() s1.disp() println("*********") val f1 = Father2("ZLX Super",5000) f1.disp() }
MyKotlinNotes/src/Ch1.kt
3212940844
import java.util.Scanner /* Main Function An entry point of a kotlin application is the main function */ //TIP To <b>Run</b> code, press <shortcut actionId="Run"/> or // click the <icon src="AllIcons.Actions.Execute"/> icon in the gutter. //fun main() { // println("Hello, Kotlin !") //} fun main(array: Array<String>) { // var - Variables that can be reassigned // Dynamic Type // var roll = 10 //Integer // var mobilenumber = 9000L //Long // var price = 83.12f //float // var totalcost = 6324.3215 //double // var gender = 'F' //char // var name = "Vivek" //string // var isActive = true //boolean println("Hello, Kotlin !") // println(roll) // println(mobilenumber) // roll = 125 // mobilenumber = 9876543210 // println("*** value reassigned ***") // println(roll) // println(mobilenumber) // variable() // value() // add() // arithemeticOperations() // comparisonOperations() //// userInput() // stringOperations() // conditionalOperations() // loops() // val multi = multi(b=10,a=20) // function with named arguments // println(multi) // // h0F(12,15, :: add) // calling higher order function // // val addl = { a:Int, b:Int -> a + b} // Lambda expression // println(addl(20,30)) // // val addl2:(Int,Int)-> Int = {a,b -> a+b} // Lambda expression // println(addl2(12,28)) // // h0F(10,20) { a: Int, b: Int -> a + b } // Higher order function with Lambda Expressions // // val sum = fun( a:Int, b:Int):Int{ return a+b} // println(sum(22,32)) // nullSafety() // arrays() // lists() // sets() // maps() } /**** Function - Kotlin functions are declared using the fun keyword ****/ // Functions are with and without parameters fun variable(){ // Spesific data Type var roll:Int = 10 //Integer var mobilenumber:Long = 9990000000L //Long var price:Float = 83.12f //float var totalcost:Double = 6324.3215 //double var gender:Char = 'F' //char var name:String = "Vivek" //string var isActive:Boolean = true //boolean println(roll) println(mobilenumber) roll = 125 println("*** Integer Value only can be assigned to roll number ***") println(roll) } fun value(){ // val can't be reassigned val roll = 123 val mobile = 9638527410 val price:Float = 83.12f println("Printing the val assigned data types...") println(roll) println(mobile) println(price) } fun add(){ println("** Printing the values **") println(" Hello Vivek ") val a = 12 val b = 20 println(" Hello "+a) println(" Hello $a") println(" Addition of $a + $b") println(" Addition is ${a+b}") } fun arithemeticOperations(){ println(" ** Arithemetic Operations **") val a = 5 val b = 2 val addition = a + b println("Addition "+ addition) print("Difference is ") println(a-b) println("Multiplication is ${a*b}") println(b..a) print("Range is ") for (i in b..a) print(i) println() } fun comparisonOperations(){ var a = 5 val b = 3 val c = 5 println("*** Printing the Comparison operations ***") println(a > b) println(a != b) println( (a>b) && (a<c) ) // Increment and decrement operatora println(++a) println(a--) // assigment operator a+=5 println(a) } fun userInput(){ print("Enter your name: ") val name: String? = readLine() print("Enter your roll: ") val roll = readLine()!!.toInt() println("Name: $name") println("Roll: $roll") println(name!!::class.simpleName) println(roll::class.simpleName) val scanner = Scanner(System.`in`) print("Enter your branch: ") val branch = scanner.next() println("Branch: $branch") println(name::class.simpleName) print("Enter the fees: ") val fee = scanner.nextFloat() println("Fee is $fee") } fun stringOperations(){ /* Strings ara immutable. Once you initialize a string, you can't change the value or assign a new value to it. All operations that transform strings return their results in an new String object, leaving the original string unchanged. */ val str = "Hello" val str2 = " Kotlin" print(str) print(str[1]) println("\nThis is "+ str + str2 + 50) //String Literals println("Hello\t World") //Raw String val message = """ Dear Sir/Madam, I would like to request you kindly recheck my exam copy and reevaluate the marks. """.trimMargin() print(message) //String Template val str3 = "Kotlin" val cart = 50 val quantity = 3 println("\nThis is ${str3.uppercase()}, your cart value is $cart. \nand total price is: $cart * $quantity = ${cart*quantity}") } fun conditionalOperations(){ val a = 10 val b = 15 var max = 0 if (a < b){ println("This is IF Expressions") } // if(a>b) max = a // else max = b max = if(a>b) a else b println("Max expressions is $max") if (a>b) println("\nThis is If statement: , $a") else println("This is else statement: , $b") // Other Method for If-else statement max = if(a>b){ a } else{ b } println(max) //**** When Expression **** print("Enter the number: ") val x = readlnOrNull()?.toInt() when(x){ 1 -> print("One") 2 -> print("Two") 3 -> print("Three") 4,5 -> print("Four or Five") in 6..8 -> { print("Six ") print("or Seven ") print("or Eight") } else -> print("Not Valid") } when("Monday"){ "Sunday" -> println("Holiday") "Monday" -> println("Workday") } } fun loops(){ /**** for loop ****/ // Syntax :- for ( item in collection ) print ( item) for( item in 1..5) println(item) for( item in 5 downTo 1){ print("Step: ") println(item) } /**** while loop ****/ var x = 0 while (x<5){ x++ println(x) } // while(true){ // println("Always True") // } /**** do while ****/ do{ x++ println(x) } while (x < 5) // do{ // println("Always True") // } while (true) /**** Break and Continue ****/ while (x<10){ x++ if (x == 5) continue if (x == 8) break println(x) } } fun multi(a:Int,b:Int=5): String{ // Funtion with return type, arguments and default value of arguments return("Multiplication of $a and $b is: ${a*b}") } fun add (a:Int, b:Int= 10): Int{ return a+b } // higher order function fun h0F(a:Int, b:Int, callback:(Int, Int)-> Int){ println(callback(a,b)) } fun nullSafety(){ /****** Null Safety ******/ var name1:String = "Sonal" // name1 = null // Not Allowed var name2:String? = "Rahul Kumar" name2 = null // Allowed println(name1.length) // will not work on null variable println(if(name2 !=null)name2.length else -1) // Option 1 println(name2?.length) // Option 2 : Safe Call // println(name2!!.length) // Option 3: The !! Operator : Throws exception if null } fun arrays(){ /***** Array ******/ val names = arrayOf("Sonam","Rahul","Gaurav", 399,'M') names.forEach {name -> println(name) } val num = arrayOf<Int>(20,399,21) // array of integers num[1]= 25 // updating the value of index num.set(0,22) // set method for setting in the indexes for (i in num.indices){ println("In Index $i = ${num[i]}") } println(num.size) println(names.get(0)) //get method /***** Array Constructor*****/ val roll1 = Array(5,{ i -> i*2}) for (rl in roll1){ println(rl) } /****** Built-in Methods ******/ val roll2 = intArrayOf(101,102,103) for (rl in roll2){ println(rl) } val gender2 = charArrayOf('M','F') /******** User Input Array ********/ print("Enter Number of Student: ") val num3 = readln().toInt() println("The Student Name: ") val students = Array(num3) { readln() } for (student in students){ println(student) } } fun lists(){ /********* List *********/ // List is an ordered collection with access to elements by indices - integer numbers that reflect position. Elements can occur more than once in a list. val data = listOf("Sonam", "Sumit", 100, 'M',"Sonam") println(data) // All values in a list are printed but this will not in case of Array println("${data.get(0)} and Size: "+data.size) // data[0] = "Sona" //cannot add or modify to this List i.e. Immutable data.indices.forEach{dt -> print("$dt = ${data[dt]}\t")} // printing using for loop and indices val data2 = listOf<String>("Sonal","Sonam","Soan","Sona", 20.toString()) val s = data2.size for (i in 0..s-1){ println("$i = ${data2[i]}") } /**** Mutable List ****/ val data3 = mutableListOf(40,"Sonal","Sonam","Soan","Sona") data3[0]="Sonu" // updating the list data3.add(data3.size,"Solution") // adding in the list data3.removeAt(1) // removing the data data3.forEach{dt -> println(dt) } /**** User Input List ****/ print("Enter Number of Student: ") val nd4 = readln().toInt() println("The Student Name: ") val data4 = List<String>(nd4) { readln() } for (student in data4){ println(student) } } fun sets(){ /******* Set *******/ // Set is a collection of unique elements. It reflects the mathematical abstraction of set: a group of objects without repetitions. Generally, the order of set elements has no significance. also there is no index in sets val data5 = mutableSetOf("Sonam","Rahul", "Sonam", "Sumit","Rahul",20,50) // SetOf can also be used for immutable set println("Data is: "+data5 +" and size is: "+ data5.size) // It will print after removing all the duplicates data5.add("Saurav") data5.remove("Sonam") println(data5) } fun maps(){ /***** Map or Dictionary *****/ // Map (or dictionary) is a set of key-value pairs. Keys are unique, and each of them maps to exactly one value. The values can be duplicates. Maps are useful for storing logical connections between objects, for example, an employee's ID and their positions. val data6 = mapOf(1 to "Sonal", "key2" to "Sumit", "key3" to "Rahul", 4 to 100) print("Size: "+data6.size+", Values: "+data6) println(data6.get(5)) data6.forEach{dt -> print("Key: "+dt.key+", "); print("Value: "+dt.value+ " \n") } val data7 = mutableMapOf<Int,String>(1 to "Abhi", 2 to "Raj", 3 to "Kallu", 4 to "Shyam") data7[2] = "Raju" // update data7.put(1, "Abhiraj") // update data7.put(5,"Kavalya") //add data7.remove(3) //remove data7.keys.remove(4) // can be removed on the basis of either keys or values println(data7) }
MyKotlinNotes/src/Ch10.kt
376030567
/******* Inheritance with Primary Constructor *******/ open class Father1(_car:String, _money:Int){ // Properties var car:String = _car var money:Int = _money // Member Function fun disp(){ println("Father Car: $car") println("Father Money: $money") } } class Son1(_car: String, _money: Int, _bike:String):Father1(_car,_money){ // Properties var bike:String = _bike // Member Function fun show(){ println("Son bike: $bike") } } fun main() { println("*********") val s1 = Son1("Alt 100",1000,"K10") s1.show() // s1.car = "ZSV" // s1.money = 8000 s1.disp() println("*********") }
MyKotlinNotes/src/Ch5.kt
2856020050
// Secondary Constructor class People{ // Properties var gender:String = "Female" var name: String var hAge: Int constructor(name:String, age: Int){ println("Secondary Constructor Called") this.name = name hAge = age } // Member Function fun disp(){ println("Name = $name") println("Age = $hAge") println("Gender = $gender") } } fun main(){ val p1 = People("Sonam",28) p1.disp() }
MyKotlinNotes/src/Ch14.kt
1523953790
/***** Interface *****/ interface Father5 { //Properties var car:String //by default Abstract Property: cannot be initialized in interface class //Member Function fun disp(){ println("Father Car: $car") } fun hello() //Abstract Method } class Son5: Father5{ //Properties var bike:String = "K10" // Member Function fun show(){ println("Son's Member Function") } // Implementing Father's Abstract Property override var car: String = "Alt 100" // Implementing Father's Abstract Method override fun hello() { println("Father's Abstract Method Hello") } } fun main() { val s1= Son5() s1.show() s1.disp() s1.hello() // val f1 = Father5() // Object of Interface cann't be created }
MyKotlinNotes/src/Ch2.kt
261186507
/****** Class and Object ******/ // Creating Class class Mobile{ // Properties var model : String = "LG 100K" var price : Float = 1233.50F // Member Function fun disp(){ println("Model = $model") println("Price = $price") } } fun main(){ val lg = Mobile() // Creating Object lg.model = "LG K38" // Assessing Properties using Object lg.price = 3999.60f // Accessing Properties using Object lg.disp() // Calling Function Member using Object val realme = Mobile() // Creating another Object realme.model = "Real 10t" realme.price = 11000f realme.disp() }
MyKotlinNotes/src/Ch13.kt
325562403
/******* Abstract Class and Abstract Method ******/ //5:56:30 //Abstract classes are by default open abstract class Father4{ // Properties var car: String = "Alt 100" // Member Function fun disp(){ println("Father car: $car") } //Abstract Method abstract fun hello() } class Son4:Father4(){ // Member Function fun show(){ println("Father car: $car") } override fun hello() { //Override is used to rewrite the inherited function println("Father's Abstract Method Hello! ") } } fun main() { val s1= Son4() s1.show() s1.disp() s1.hello() }
MyKotlinNotes/src/Ch6.kt
2511556182
/******* Constructor ******/ // Primary & Secondary Constructor class Registration(email:String, password:String){ // Properties var hName:String = "" var hAge:Int? = null var hEmail:String = email var hPassword:String var gender:String = "Female" // Secondary Constructor constructor(name:String, age:Int, email: String, password: String):this(email,password){ hName = name hAge = age } // Initializer Block init { hPassword = password } // Member Function fun disp(){ println("Name = $hName") println("Age = $hAge") println("Email = $hEmail") println("Password = $hPassword") println("Gender = $gender") } } fun main() { val user1 = Registration("Aashu",21,"[email protected]","123456") user1.disp() }
MyKotlinNotes/src/Ch17.kt
330533819
fun main() { val result = try { val a = 10/0 a }catch (e:Exception){ e.message } finally { println("Finally Always Executes") } println(result) }
MyKotlinNotes/src/Ch7.kt
93765279
/******* Constructor ******/ // Primary & Secondary Constructor class Registration2(_email:String, _password:String){ // Properties var name:String = "" var age:Int? = null var email:String = _email var password:String var gender:String = "Female" // Secondary Constructor constructor(name:String, age:Int, _email: String, _password: String):this(_email,_password){ this.name = name this.age = age } // Initializer Block init { this.password = _password } // Member Function fun disp(){ println("Name = $name") println("Age = $age") println("Email = $email") println("Password = $password") println("Gender = $gender") } } fun main() { val user1 = Registration2("Aashu",21,"[email protected]","123456") user1.disp() }
MyKotlinNotes/src/Ch16.kt
2430976629
/***** Data Class *****/ // Where you need to create a class solely to hold data data class Employee(val name:String, val age:Int) fun main() { val emp = Employee("Sonam", 26) println("Name: ${emp.name}") println(emp.toString()) // Destructuring val(name, age) = emp println("Name: $name") println("Age: $age") }
MyKotlinNotes/src/Ch3.kt
427471244
/****** Constructor ******/ // Primary Constructor class Person constructor(val name:String, val age:Int) { // Properties var gender: String = "Female" // Member Function fun disp() { println("Name = $name") println("Age = $age") println("Gender = $gender") } } class Human (name: String, age: Int){ // Properties var hName: String var hAge: Int = age var gender: String = "Female" // Initializer Block init { hName = name } // Member Function fun disp(){ println("Name = $hName") println("Age = $hAge") println("Gender = $gender") } } fun main (){ val p1 = Person("Sonam", 27) p1.disp() val p2 = Person("Rahul", 20) p2.gender = "Male" println(p2.name) println(p2.age) println(p2.gender) val h1 = Human("Sonal", 26 ) h1.disp() val h2 = Human("Rani", 20 ) h2.disp() }
MyKotlinNotes/src/Ch12.kt
2605057291
/******* Visibility Modifiers *******/ /* * private means visible inside this class only (including all its members). * protected is the same as private but is also visible in subclasses. * internal means that any client inside this module who seed the declaring class sees its internal members. * public means that any client who sees the declaring class sees its public members. * */ open class Father3{ // Properties private var a:Int = 10 // private can be access inside this class only protected var b:Int = 20 // protected can be used inside inherited classes only internal var c: Int = 30 // internal can be accessed inside this module only var d: Int = 40 // public can be accessed from anywhere // Member Function fun disp(){ println("A: $a") println("B: $b") println("C: $c") println("D: $d") } fun hello(){ println("Hello Father !") } } class Son3:Father3(){ // Properties var bike:String = "K 10" // Member Function fun show(){ // println("A: $a") // cannot be access as it is private println("B: $b") // protected can be used inside inherited classes only println("C: $c") println("D: $d") hello() } } fun main() { val s1 = Son3() s1.show() // s1.a = 100 // cannot be access as it is private // s1.b = 101 // protected can be used inside inherited classes only s1.c = 102 // internal can be accessed inside this module only s1.d = 103 s1.disp() s1.hello() val f1 = Father3() // f1.a = 110 // can't be accessed as it is private // f1.b = 111 // can't be accesses as it is protected f1.c = 123 } //class Father3 private constructor(a:Int){....} //constructor keyword must be used if using visibility modifier in primary constructor
MyKotlinNotes/src/Ch8.kt
3939561779
/****** Getter and Setter ******/ class User(_id:Int, _name:String, _age:Int){ val id:Int = _id get() = field var name:String = _name get() = field set(value) { field = value } var age:Int = _age get() = field set(value){ field = value } } fun main() { val u1 = User(1,"Sonam", 27) println("Id: "+u1.id+" Name: "+u1.name+" Age: "+u1.age) // get Property u1.name = "Roshni" u1.age = 23 println(u1.name) println(u1.age) }
MyKotlinNotes/src/com/company/utils/ut.kt
262039424
package com.company.utils import com.company.services.openingyt as op fun openingyt(){ println("Opened function from util package") } fun main() { openingyt() op() }
MyKotlinNotes/src/com/company/services/openyt.kt
1336070095
package com.company.services fun openingyt(){ println("Opened function from services package") }
MyKotlinNotes/src/Ch9.kt
4003778196
/******* Inheritance *******/ open class Father{ // Properties var car:String = "Alt 100" var money:Int = 10000 // Member Function fun disp(){ println("Father Car: $car") println("Father Money: $money") } } class Son:Father(){ // Properties var bike:String = "K 20" // Member Function fun show(){ println("Son bike: $bike") } } class Daughter : Father(){ // Properties var bike:String = "KT9" fun show(){ println("Daughter bike: $bike") } } fun main() { println("*********") val f1 = Father() f1.disp() println("*********") val s1 = Son() s1.show() s1.car = "ZSV" s1.money = 8000 s1.disp() println("*********") val d1 = Daughter() d1.show() d1.disp() // 5:20:30 }
MyKotlinNotes/src/Ch18.kt
237277789
/***** Calling Java from Kotlin (MyJava) *****/ /***** Calling Kotlin from Java (MyJava) *****/ fun main() { val obj = MyJava() obj.setValue(10) println(obj.getValue()) } fun addition(a:Int,b:Int):Int{ return (a+b) }
Organizer/app/src/androidTest/java/com/serhiitymoshenko/organizer/ExampleInstrumentedTest.kt
2933404260
package com.serhiitymoshenko.organizer 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.serhiitymoshenko.organizer", appContext.packageName) } }
Organizer/app/src/test/java/com/serhiitymoshenko/organizer/ExampleUnitTest.kt
1666843731
package com.serhiitymoshenko.organizer 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) } }
Organizer/app/src/main/java/com/serhiitymoshenko/organizer/MainActivity.kt
3814523391
package com.serhiitymoshenko.organizer import androidx.appcompat.app.AppCompatActivity import android.os.Bundle class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } }
APIDemoForAarBykotlin/app/src/main/java/com/askjeffreyliu/floydsteinbergdithering/Utils.kt
3836361771
package com.askjeffreyliu.floydsteinbergdithering import android.graphics.* import com.cloudpos.mvc.common.Logger class Utils { fun floydSteinbergDithering(originalColorBitmap: Bitmap): Bitmap { val bmpGrayScaled = toGrayscale(originalColorBitmap) floydSteinbergNative(bmpGrayScaled) return bmpGrayScaled } fun binaryBlackAndWhite(originalColorBitmap: Bitmap): Bitmap { val bmpGrayScaled = toGrayscale(originalColorBitmap) binaryBlackAndWhiteNative(bmpGrayScaled) return bmpGrayScaled } fun toGrayscale(bmpOriginal: Bitmap): Bitmap { val bmpGrayscale = Bitmap.createBitmap(bmpOriginal.width, bmpOriginal.height, Bitmap.Config.ARGB_8888) val c = Canvas(bmpGrayscale) val paint = Paint() val cm = ColorMatrix() cm.setSaturation(0.0f) val f = ColorMatrixColorFilter(cm) paint.colorFilter = f c.drawBitmap(bmpOriginal, 0.0f, 0.0f, paint) return bmpGrayscale } companion object { private external fun floydSteinbergNative(var1: Bitmap) private external fun binaryBlackAndWhiteNative(var1: Bitmap) } init { Logger.debug("loadLibrary+++") System.loadLibrary("fsdither") Logger.debug("loadLibrary---") } }
APIDemoForAarBykotlin/app/src/main/java/com/cloudpos/androidmvcmodel/MainActivity.kt
894793661
package com.cloudpos.androidmvcmodel import android.app.Activity import android.content.ComponentName import android.content.Context import android.content.Intent import android.os.Bundle import android.os.Handler import android.text.method.ScrollingMovementMethod import android.util.Log import android.view.* import android.widget.* import android.widget.AdapterView.OnItemClickListener import com.android.common.utils.PackageUtils import com.cloudpos.androidmvcmodel.adapter.ListViewAdapter import com.cloudpos.androidmvcmodel.common.Constants import com.cloudpos.androidmvcmodel.entity.MainItem import com.cloudpos.androidmvcmodel.helper.LanguageHelper import com.cloudpos.androidmvcmodel.helper.LogHelper import com.cloudpos.apidemoforunionpaycloudpossdk.R import com.cloudpos.mvc.base.ActionCallback import com.cloudpos.mvc.base.ActionManager import com.cloudpos.mvc.common.Logger import com.cloudpos.mvc.impl.ActionCallbackImpl import java.util.* class MainActivity : Activity(), OnItemClickListener { var txtLog: TextView? = null // var txtIntroduction: TextView? = null var lvwTestItems: ListView? = null var context: Context? = null var adapter: ListViewAdapter? = null private var isMain = true private var clickedPosition = 0 private var scrollPosition = 0 private var clickedMainItem: MainItem? = null private var handler: Handler? = null private var actionCallback: ActionCallback? = null private var testParameters: MutableMap<String?, Any?>? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) initParameter() initView() initUI() } private fun initParameter() { Logger.debug("initParameter +") context = this@MainActivity adapter = ListViewAdapter(context as MainActivity) handler = Handler(handlerCallback) actionCallback = ActionCallbackImpl(context, handler!!) testParameters = HashMap() Logger.debug("initParameter -") } private fun initView() { Logger.debug("initView +") txtLog = findViewById<View>(R.id.txt_log) as TextView // txtIntroduction = findViewById<View>(R.id.txt_introduction) as TextView lvwTestItems = findViewById<View>(R.id.lvw_test_items) as ListView Logger.debug("initView -") } private fun initUI() { Logger.debug("initUI +") txtLog!!.movementMethod = ScrollingMovementMethod.getInstance() lvwTestItems!!.adapter = adapter lvwTestItems!!.onItemClickListener = this lvwTestItems!!.setOnScrollListener(onTestItemsScrollListener) Logger.debug("initUI -") } override fun onCreateOptionsMenu(menu: Menu): Boolean { val cleanLogMenu = menu.addSubMenu(MENU_GROUP_ID, MENU_CLEAN_LOG, Menu.NONE, R.string.clean_log) cleanLogMenu.setIcon(android.R.drawable.ic_menu_revert) val uninstallMenu = menu.addSubMenu(MENU_GROUP_ID, MENU_UNINSTALL, Menu.NONE, R.string.uninstall_app) uninstallMenu.setIcon(android.R.drawable.ic_menu_delete) return super.onCreateOptionsMenu(menu) } override fun onMenuItemSelected(featureId: Int, item: MenuItem): Boolean { when (item.itemId) { MENU_CLEAN_LOG -> txtLog!!.text = "" MENU_UNINSTALL -> PackageUtils.uninstall(context, context!!.packageName) else -> { } } return super.onMenuItemSelected(featureId, item) } override fun onItemClick(parent: AdapterView<*>?, view: View, position: Int, id: Long) { clickedPosition = position if (isMain) { performMainItemClick() } else { performSubItemClick() } } override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean { if (keyCode == KeyEvent.KEYCODE_BACK) { onBackKeyClick() return true } return super.onKeyDown(keyCode, event) } private fun onBackKeyClick() { if (isMain) { System.exit(0) } else { isMain = true displayIntroduction() adapter!!.refreshView(ListViewAdapter.Companion.INDEX_NONE) setListViewSelection() actionCallback!!.sendResponse(context!!.getString(R.string.test_end)) } } private fun setListViewSelection() { lvwTestItems!!.adapter = adapter lvwTestItems!!.setSelection(scrollPosition) } private fun performMainItemClick() { isMain = false clickedMainItem = MainApplication.Companion.testItems!!.get(clickedPosition) actionCallback!!.sendResponse(context!!.getString(R.string.welcome_to) + "\t" + clickedMainItem!!.getDisplayName(LanguageHelper.getLanguageType(context))) displayIntroduction() if (clickedMainItem!!.isActivity()) { // if the test item is a activity, jump by package-name property. val cn = ComponentName(context, clickedMainItem!!.packageName) val intent = Intent() intent.component = cn intent.putExtra(Constants.MAIN_ITEM, clickedMainItem!!.command) startActivityForResult(intent, clickedPosition) } else { // otherwise jump to SubItem page and automatically execute autoTest // item if exsies adapter!!.refreshView(clickedPosition) lvwTestItems!!.setSelection(0) lvwTestItems!!.adapter = adapter // setLayoutIntroductionIfExists(); } } private fun performSubItemClick() { testParameters!!.clear() testParameters!![Constants.MAIN_ITEM] = clickedMainItem!!.command val subItemCommand = clickedMainItem!!.getSubItem(clickedPosition).command testParameters!![Constants.SUB_ITEM] = subItemCommand Log.e(TAG, "itemPressed : " + clickedMainItem!!.command + "/" + subItemCommand) ActionManager.Companion.doSubmit(clickedMainItem!!.command + "/" + subItemCommand, context, testParameters, actionCallback) } /** * 显示Introduction信息<br></br> * 如果isMain == true,则隐藏,否则显示 */ private fun displayIntroduction() { // if (txtIntroduction != null) { // if (isMain) { // txtIntroduction!!.visibility = View.GONE // } else { // txtIntroduction!!.visibility = View.VISIBLE // txtIntroduction!!.text = """ // ${context!!.getString(R.string.welcome_to)} // ${clickedMainItem!!.getDisplayName(LanguageHelper.getLanguageType(context))} // """.trimIndent() // } // } } private val onTestItemsScrollListener: AbsListView.OnScrollListener = object : AbsListView.OnScrollListener { override fun onScrollStateChanged(view: AbsListView, scrollState: Int) { // position which records the position of the visible top line if (isMain) { scrollPosition = lvwTestItems!!.firstVisiblePosition } } override fun onScroll(view: AbsListView, firstVisibleItem: Int, visibleItemCount: Int, totalItemCount: Int) { } } private val handlerCallback = Handler.Callback { msg -> when (msg.what) { Constants.HANDLER_LOG -> LogHelper.infoAppendMsg(msg.obj as String, txtLog) Constants.HANDLER_LOG_SUCCESS -> LogHelper.infoAppendMsgForSuccess(msg.obj as String, txtLog) Constants.HANDLER_LOG_FAILED -> LogHelper.infoAppendMsgForFailed(msg.obj as String, txtLog) else -> { } } true } companion object { private const val TAG = "DEBUG" private const val MENU_CLEAN_LOG = Menu.FIRST private const val MENU_UNINSTALL = Menu.FIRST + 1 private const val MENU_GROUP_ID = 0 } }
APIDemoForAarBykotlin/app/src/main/java/com/cloudpos/androidmvcmodel/entity/SubItem.kt
1009020284
package com.cloudpos.androidmvcmodel.entity class SubItem : TestItem() { var isNeedTest = false }
APIDemoForAarBykotlin/app/src/main/java/com/cloudpos/androidmvcmodel/entity/TestItem.kt
2692581469
package com.cloudpos.androidmvcmodel.entity import com.cloudpos.androidmvcmodel.helper.LanguageHelper open class TestItem { var command: String? = null private var displayNameCN: String? = null private var displayNameEN: String? = null fun getDisplayName(languageType: Int): String? { return if (languageType == LanguageHelper.LANGUAGE_TYPE_CN) { displayNameCN } else { displayNameEN } } fun setDisplayNameCN(displayNameCN: String?) { this.displayNameCN = displayNameCN } fun setDisplayNameEN(displayNameEN: String?) { this.displayNameEN = displayNameEN } override fun toString(): String { return String.format("command = %s, displayCN = %s, displyEN = %s", command, displayNameCN, displayNameEN) } }
APIDemoForAarBykotlin/app/src/main/java/com/cloudpos/androidmvcmodel/entity/MainItem.kt
1343875790
package com.cloudpos.androidmvcmodel.entity import java.util.* class MainItem : TestItem() { private var isActivity = false private val subItems: MutableList<SubItem> = ArrayList() var packageName: String? = null private var isUnique = false fun isActivity(): Boolean { return isActivity } fun setActivity(isActivity: Boolean) { this.isActivity = isActivity } fun getSubItem(position: Int): SubItem { return subItems[position] } fun getSubItems(): List<SubItem> { return subItems } val testSubItems: List<SubItem> get() { val testSubItems: MutableList<SubItem> = ArrayList() for (subItem in subItems) { if (subItem.isNeedTest) { testSubItems.add(subItem) } } return testSubItems } fun addSubItem(subItem: SubItem) { subItems.add(subItem) } fun isUnique(): Boolean { return isUnique } fun setUnique(isUnique: Boolean) { this.isUnique = isUnique } }
APIDemoForAarBykotlin/app/src/main/java/com/cloudpos/androidmvcmodel/adapter/ListViewAdapter.kt
1336731872
package com.cloudpos.androidmvcmodel.adapter import android.content.Context import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.BaseAdapter import android.widget.TextView import com.cloudpos.androidmvcmodel.MainApplication import com.cloudpos.androidmvcmodel.entity.MainItem import com.cloudpos.androidmvcmodel.helper.LanguageHelper import com.cloudpos.apidemoforunionpaycloudpossdk.R import java.util.logging.Logger class ListViewAdapter(private val context: Context) : BaseAdapter() { private val inflater: LayoutInflater // private DBHelper dbHelper; private var mainItemIndex = INDEX_NONE override fun getCount(): Int { var count = 0 count = if (mainItemIndex <= INDEX_NONE) { MainApplication.Companion.testItems!!.size } else { MainApplication.Companion.testItems!!.get(mainItemIndex)!!.getSubItems().size } return count } override fun getItem(position: Int): Any { val item: Any? item = if (mainItemIndex <= INDEX_NONE) { MainApplication.Companion.testItems.get(position) } else { MainApplication.Companion.testItems.get(mainItemIndex).getSubItem(position) } return item } override fun getItemId(position: Int): Long { return position.toLong() } override fun getView(position: Int, convertView: View?, parent: ViewGroup): View?{ var convertView = convertView if (convertView == null) { convertView = inflater.inflate(R.layout.item_test, null) } // TextView txtSignature = (TextView) // convertView.findViewById(R.id.txt_signature); val txtButton = convertView!!.findViewById<View>(R.id.txt_button) as TextView // setDisplayedSignature(position, txtSignature); setDisplayedButton(position, txtButton) return convertView } /** * refresh listview when switching from MainItem page and SubItem page */ fun refreshView(index: Int) { mainItemIndex = index Log.e(TAG, "mainItemIndex = $mainItemIndex") notifyDataSetChanged() } /** * refresh specified item when changed */ fun refreshChangedItemView(position: Int, convertView: View, parent: ViewGroup) { getView(position, convertView, parent) } // private void setDisplayedSignature(int position, TextView txtSignature) { // String testResult = getTestResult(position); // Log.e(TAG, "setDisplayedSignature testResult = " + testResult); // if (testResult.equals(SqlConstants.RESULT_SUCCESS)) { // txtSignature.setText("√"); // txtSignature.setTextColor(Color.rgb(0, 0, 0)); // } else if (testResult.equals(SqlConstants.RESULT_FAILED)) { // txtSignature.setText("X"); // txtSignature.setTextColor(Color.rgb(255, 0, 0)); // } else if (testResult.equals(SqlConstants.RESULT_EXCEPTION)) { // txtSignature.setText("O"); // txtSignature.setTextColor(Color.rgb(255, 255, 255)); // } else { // txtSignature.setText(""); // txtSignature.setTextColor(Color.rgb(0, 0, 0)); // } // } private fun setDisplayedButton(position: Int, txtButton: TextView) { val mainItem = getMainItem(position) // txtButton.setText(mainItem.getDisplayName(LanguageHelper.getLanguageType(context))); if (mainItemIndex <= INDEX_NONE) { txtButton.text = mainItem!!.getDisplayName(LanguageHelper.getLanguageType(context)) } else { txtButton.text = mainItem!!.getSubItem(position).getDisplayName( LanguageHelper.getLanguageType(context)) // txtButton.setTag(mainItem.getSubItem(position).getDisplayName(LanguageHelper.getLanguageType(context))); } } /** * get test result from sqlite database<br></br> */ // private String getTestResult(int position) { // MainItem mainItem = getMainItem(position); // // String testResult = dbHelper.queryTestResultByMainItem(mainItem); // return testResult; // } private fun getMainItem(position: Int): MainItem? { var mainItem: MainItem? = null mainItem = if (mainItemIndex <= INDEX_NONE) { MainApplication.Companion.testItems!!.get(position) } else { MainApplication.Companion.testItems!!.get(mainItemIndex) } return mainItem } companion object { private const val TAG = "ListViewAdapter" const val INDEX_NONE = -1 } init { inflater = LayoutInflater.from(context) // dbHelper = DBHelper.getInstance(); } }
APIDemoForAarBykotlin/app/src/main/java/com/cloudpos/androidmvcmodel/common/Constants.kt
2906566477
package com.cloudpos.androidmvcmodel.common object Constants { const val AUTO_TEST = "autoTest" const val CLOSE = "close" const val MAIN_ITEM = "MainItem" const val SUB_ITEM = "SubItem" const val TEST_RESULT = "TestResult" const val MAIN_ITEM_DISPLAY_NAME = "MainItem displayName" const val CLICK_POSITION = "ClickPosition" const val HANDLER_LOG = 1 const val HANDLER_LOG_SUCCESS = 2 const val HANDLER_LOG_FAILED = 3 const val HANDLER_ALERT_SOUND = 4 }
APIDemoForAarBykotlin/app/src/main/java/com/cloudpos/androidmvcmodel/callback/HandlerCallback.kt
1969464748
package com.cloudpos.androidmvcmodel.callback import android.content.Context import android.os.Handler import android.os.Message import android.widget.TextView import com.cloudpos.androidmvcmodel.helper.LogHelper class HandlerCallback /** * 将信息输出到显示屏上 */(private val context: Context, private val txtResult: TextView) : Handler.Callback { override fun handleMessage(msg: Message): Boolean { when (msg.what) { LOG -> LogHelper.infoAppendMsg(msg.obj as String, txtResult) LOG_SUCCESS -> LogHelper.infoAppendMsgForSuccess(msg.obj as String, txtResult) LOG_FAILED -> LogHelper.infoAppendMsgForFailed(msg.obj as String, txtResult) ALERT_SOUND -> showDialog(msg.obj.toString()) else -> LogHelper.infoAppendMsg(msg.obj as String, txtResult) } return true } private fun showDialog(testItem: String) { val showMsgAndItems = testItem.split("/").toTypedArray() // new AlertDialog.Builder(context) // .setTitle(showMsgAndItems[0]) // .setPositiveButton(context.getString(R.string.sound_btn_success), // new DialogInterface.OnClickListener() { // // @Override // public void onClick(DialogInterface dialog, int which) { // setSuccessfullResult(showMsgAndItems[1], showMsgAndItems[2]); // } // }) // .setNegativeButton(context.getString(R.string.sound_btn_failed), // new DialogInterface.OnClickListener() { // // @Override // public void onClick(DialogInterface dialog, int which) { // setFailedResult(showMsgAndItems[1], showMsgAndItems[2]); // } // }).show(); } private fun setSuccessfullResult(mainItem: String, subItem: String) { // DBHelper.getInstance().saveTestResult(mainItem, subItem, SqlConstants.RESULT_SUCCESS); } private fun setFailedResult(mainItem: String, subItem: String) { // DBHelper.getInstance().saveTestResult(mainItem, subItem, SqlConstants.RESULT_FAILED); } companion object { const val LOG = 1 const val LOG_SUCCESS = 2 const val LOG_FAILED = 3 const val ALERT_SOUND = 4 } }
APIDemoForAarBykotlin/app/src/main/java/com/cloudpos/androidmvcmodel/MainApplication.kt
1139541490
package com.cloudpos.androidmvcmodel import android.app.Application import android.content.Context import android.util.Log import com.cloudpos.androidmvcmodel.entity.MainItem import com.cloudpos.androidmvcmodel.helper.LanguageHelper import com.cloudpos.androidmvcmodel.helper.TerminalHelper import com.cloudpos.androidmvcmodel.helper.XmlPullParserHelper import com.cloudpos.mvc.base.ActionManager import com.cloudpos.mvc.impl.ActionContainerImpl import java.util.* class MainApplication : Application() { private var context: Context? = null override fun onCreate() { super.onCreate() initParameter() ActionManager.Companion.initActionContainer(ActionContainerImpl(context)) } private fun initParameter() { context = this testItems = XmlPullParserHelper.getTestItems(context as MainApplication, TerminalHelper.terminalType) for (mainItem in testItems) { Log.e("DEBUG", "" + mainItem.getDisplayName(LanguageHelper.getLanguageType(context))) } } companion object { var testItems: MutableList<MainItem> = ArrayList() } }
APIDemoForAarBykotlin/app/src/main/java/com/cloudpos/androidmvcmodel/helper/SystemPropertyHelper.kt
1227181031
package com.cloudpos.androidmvcmodel.helper import android.util.Log object SystemPropertyHelper { operator fun get(propertyName: String): String { var property: Any? = null try { val systemProperties = Class.forName("android.os.SystemProperties") Log.i("systemProperties", systemProperties.toString()) property = systemProperties.getMethod("get", *arrayOf<Class<*>>( String::class.java, String::class.java )).invoke(systemProperties, *arrayOf<Any>( propertyName, "unknown" )) Log.i("bootloaderVersion", property.javaClass.toString()) } catch (e: Exception) { property = "" e.printStackTrace() } return property.toString() } }
APIDemoForAarBykotlin/app/src/main/java/com/cloudpos/androidmvcmodel/helper/LogHelper.kt
3524246946
/** * */ package com.cloudpos.androidmvcmodel.helper import android.graphics.* import android.text.Spannable import android.text.Spanned import android.text.style.ForegroundColorSpan import android.widget.TextView /** * @author john 打印信息的格式控制类。 红色:出现的问题。 绿色:正常的信息。 黄色:可能出现的问题。 1 : color is black 2 * : color is yellow 3 : color is blue 4 : color is red other number : * color is black; */ object LogHelper { /** * TestView changed color and info message. Called after the TestView is * created and whenever the TextView changes. Set your TextView's message * here. * * @param TextView text * @param String infoMsg : color is red < color name="red">#FF0000< /color>< * !--红色 --> */ @Deprecated("") fun infoException(text: TextView, infoMsg: String) { text.setText(infoMsg, TextView.BufferType.SPANNABLE) val start = text.text.length val end = start + infoMsg.length val style = text.text as Spannable style.setSpan(ForegroundColorSpan(Color.RED), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) } /** * @param TextView text * @param String infoMsg : color is black */ @Deprecated("") fun info(text: TextView, infoMsg: String?) { // int start = text.getText().length(); // int end = start +infoMsg.length(); text.text = infoMsg } /** * @param TextView text * @param String infoMsg : color is yellow */ @Deprecated("") fun infoWarning(text: TextView, infoMsg: String) { text.text = infoMsg val style = text.text as Spannable val start = text.text.length val end = start + infoMsg.length style.setSpan(ForegroundColorSpan(Color.YELLOW), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) } /** * @param TextView text * @param String infoMsg * @param order :set background color. 1 : color is black. 2 : color is * yellow. 3 : color is blue .4 : color is red .other number : * color is black; */ fun infoMsgAndColor(text: TextView, infoMsg: String, order: Int) { text.text = infoMsg val style = text.text as Spannable val start = 0 val end = start + infoMsg.length val color: ForegroundColorSpan color = when (order) { 1 -> ForegroundColorSpan(Color.BLACK) 2 -> ForegroundColorSpan(Color.YELLOW) 3 -> ForegroundColorSpan(Color.BLUE) 4 -> ForegroundColorSpan(Color.RED) else -> ForegroundColorSpan(Color.BLACK) } style.setSpan(color, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) } fun infoAppendMsgAndColor(text: TextView, infoMsg: String, order: Int) { var start = 0 if (text.text.length == 0) { } else { start = text.text.length } text.append(infoMsg) val style = text.text as Spannable val end = start + infoMsg.length val color: ForegroundColorSpan color = when (order) { 1 -> ForegroundColorSpan(Color.BLACK) 2 -> ForegroundColorSpan(Color.YELLOW) 3 -> ForegroundColorSpan(Color.BLUE) 4 -> ForegroundColorSpan(Color.RED) 5 -> ForegroundColorSpan(Color.RED) else -> ForegroundColorSpan(Color.YELLOW) } style.setSpan(color, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) } /** * 蓝色字体打印成功信息 * * @param msg * @param text */ fun infoAppendMsgForSuccess(msg: String, text: TextView?) { // TextView text = PreMainActivity.txtResult; var start = 0 if (text!!.text.length == 0) { } else { start = text.text.length } if (start > 1000) { text.text = "" start = 0 } text.append(msg) val style = text.text as Spannable val end = start + msg.length val color: ForegroundColorSpan color = ForegroundColorSpan(Color.BLUE) style.setSpan(color, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) moveScroller(text) // text.setScrollY(text.getScrollY()+text.getLineHeight()); } /** * 红色字体打印失败信息 * * @param msg * @param text */ fun infoAppendMsgForFailed(msg: String, text: TextView?) { // TextView text = PreMainActivity.txtResult; var start = 0 if (text!!.text.length == 0) { } else { start = text.text.length } if (start > 1000) { text.text = "" start = 0 } text.append(msg) val style = text.text as Spannable val end = start + msg.length val color: ForegroundColorSpan color = ForegroundColorSpan(Color.RED) style.setSpan(color, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) moveScroller(text) // Scroller scr = text. // text.setScrollY(text.getScrollY()+text.getLineHeight()); } /** * 给textresult上用黑色写上命令。 */ fun infoAppendMsg(msg: String, text: TextView?) { // TextView text = PreMainActivity.txtResult; var start = 0 if (text!!.text.length == 0) { } else { start = text.text.length } if (start > 1000) { text.text = "" start = 0 } text.append(msg) val style = text.text as Spannable val end = start + msg.length val color: ForegroundColorSpan color = ForegroundColorSpan(Color.BLACK) style.setSpan(color, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) moveScroller(text) // } private fun moveScroller(text: TextView?) { // find the amount we need to scroll. This works by // asking the TextView's internal layout for the position // of the final line and then subtracting the TextView's height val scrollAmount = (text!!.layout.getLineTop(text.lineCount) - text.height) // if there is no need to scroll, scrollAmount will be <=0 if (scrollAmount > 0) { text.scrollTo(0, scrollAmount + 30) } else { text.scrollTo(0, 0) } } }
APIDemoForAarBykotlin/app/src/main/java/com/cloudpos/androidmvcmodel/helper/LanguageHelper.kt
2467269118
package com.cloudpos.androidmvcmodel.helper import android.content.Context object LanguageHelper { const val LANGUAGE_TYPE_OTHER = 0 const val LANGUAGE_TYPE_CN = 1 private const val LANGUAGE_TYPE_NONE = -1 private var languageType = LANGUAGE_TYPE_NONE fun getLanguageType(context: Context?): Int { if (languageType == LANGUAGE_TYPE_NONE) { languageType = LANGUAGE_TYPE_OTHER val locale = context!!.resources.configuration.locale val language = locale.language if (language.endsWith("zh")) { languageType = LANGUAGE_TYPE_CN } } return languageType } }
APIDemoForAarBykotlin/app/src/main/java/com/cloudpos/androidmvcmodel/helper/TerminalHelper.kt
456664042
package com.cloudpos.androidmvcmodel.helper import android.util.Log object TerminalHelper { const val TERMINAL_TYPE_WIZARPOS_1 = 0 const val TERMINAL_TYPE_WIZARHAND_Q1 = 1 const val TERMINAL_TYPE_WIZARHAND_M0 = 2 const val TERMINAL_TYPE_WIZARPAD_1 = 3 const val TERMINAL_TYPE_NONE = -1// 找到对应的设备类型WIZARPOS,WIZARPAD,... // 判断是否为手持 /** * 获取设备类型<br></br> * [.TERMINAL_TYPE_WIZARPOS_1]<br></br> * [.TERMINAL_TYPE_WIZARHAND_Q1]<br></br> * [.TERMINAL_TYPE_WIZARHAND_M0]<br></br> * [.TERMINAL_TYPE_WIZARPAD_1]<br></br> */ var terminalType = TERMINAL_TYPE_NONE get() { if (field == TERMINAL_TYPE_NONE) { field = TERMINAL_TYPE_WIZARPOS_1 productModel = getProductModel() Log.d("model", productModel) // 找到对应的设备类型WIZARPOS,WIZARPAD,... // 判断是否为手持 if (productModel == "WIZARHAND_Q1" || productModel == "MSM8610" || productModel == "WIZARHAND_Q0") { field = TERMINAL_TYPE_WIZARHAND_Q1 } else if (productModel == "FARS72_W_KK" || productModel == "WIZARHAND_M0") { field = TERMINAL_TYPE_WIZARHAND_M0 } else if (productModel == "WIZARPOS1" || productModel == "WIZARPOS_1") { field = TERMINAL_TYPE_WIZARPOS_1 } else if (productModel == "WIZARPAD1" || productModel == "WIZARPAD_1") { field = TERMINAL_TYPE_WIZARPAD_1 } } return field } private set private var productModel: String? = null /** * 获取设备的model<br></br> * 通过读取 ro.product.model 属性 获得 */ fun getProductModel(): String? { if (productModel == null) { productModel = SystemPropertyHelper.get("ro.product.model").trim { it <= ' ' } productModel = productModel!!.replace(" ", "_") productModel = productModel!!.toUpperCase() } return productModel } }
APIDemoForAarBykotlin/app/src/main/java/com/cloudpos/androidmvcmodel/helper/XmlPullParserHelper.kt
3270034868
package com.cloudpos.androidmvcmodel.helper import android.content.Context import android.util.Log import com.cloudpos.androidmvcmodel.common.Constants import com.cloudpos.androidmvcmodel.entity.MainItem import com.cloudpos.androidmvcmodel.entity.SubItem import com.cloudpos.apidemoforunionpaycloudpossdk.R import org.xmlpull.v1.XmlPullParser import org.xmlpull.v1.XmlPullParserException import org.xmlpull.v1.XmlPullParserFactory import java.util.* object XmlPullParserHelper { @Throws(XmlPullParserException::class) fun getXmlPullParser(context: Context, terminalType: Int): XmlPullParser { var xmlPullParser = XmlPullParserFactory.newInstance().newPullParser() xmlPullParser = when (terminalType) { TerminalHelper.TERMINAL_TYPE_WIZARHAND_Q1 -> context.resources.getXml(R.xml.wizarhand_q1) TerminalHelper.TERMINAL_TYPE_WIZARPAD_1 -> context.resources.getXml(R.xml.wizarpad_1) TerminalHelper.TERMINAL_TYPE_WIZARHAND_M0 -> context.resources.getXml(R.xml.wizarhand_m0) else -> context.resources.getXml(R.xml.wizarpos_1) } return xmlPullParser } fun parseToMainItem(xmlPullParser: XmlPullParser): MainItem { val mainItem = MainItem() val nameCN = xmlPullParser.getAttributeValue(null, "name_CN") val nameEN = xmlPullParser.getAttributeValue(null, "name_EN") val command = xmlPullParser.getAttributeValue(null, "command") val isActivity = xmlPullParser.getAttributeValue(null, "isActivity") mainItem.setDisplayNameCN(nameCN) mainItem.setDisplayNameEN(nameEN) mainItem.command = command if (isActivity != null && isActivity == "true") { mainItem.setActivity(true) } else { mainItem.setActivity(false) } return mainItem } fun parseToSubItem(xmlPullParser: XmlPullParser): SubItem { val subItem = SubItem() val nameCN = xmlPullParser.getAttributeValue(null, "name_CN") val nameEN = xmlPullParser.getAttributeValue(null, "name_EN") val command = xmlPullParser.getAttributeValue(null, "command") val needTest = xmlPullParser.getAttributeValue(null, "needTest") subItem.setDisplayNameCN(nameCN) subItem.setDisplayNameEN(nameEN) subItem.command = command if (needTest != null && needTest == "true") { subItem.isNeedTest = true } else { subItem.isNeedTest = false } return subItem } fun getTestItems(context: Context, terminalType: Int): MutableList<MainItem> { Log.d("DEBUG", "getTestItems") val testItems: MutableList<MainItem> = ArrayList() try { val xmlPullParser = getXmlPullParser(context, terminalType) var mEventType = xmlPullParser.eventType var mainItem = MainItem() var tagName: String? = null while (mEventType != XmlPullParser.END_DOCUMENT) { if (mEventType == XmlPullParser.START_TAG) { tagName = xmlPullParser.name if (tagName == Constants.MAIN_ITEM) { mainItem = parseToMainItem(xmlPullParser) // Log.d("DEBUG", "" + mainItem.getDisplayName(1)); } else if (tagName == Constants.SUB_ITEM) { val subItem = parseToSubItem(xmlPullParser) mainItem!!.addSubItem(subItem) } } else if (mEventType == XmlPullParser.END_TAG) { tagName = xmlPullParser.name if (tagName == Constants.MAIN_ITEM) { testItems.add(mainItem) } } mEventType = xmlPullParser.next() } } catch (e: Exception) { e.printStackTrace() } return testItems } }
APIDemoForAarBykotlin/app/src/main/java/com/cloudpos/mvc/impl/ActionCallbackImpl.kt
2887882404
package com.cloudpos.mvc.impl import android.content.Context import android.os.Handler import com.cloudpos.androidmvcmodel.common.Constants import com.cloudpos.mvc.base.ActionCallback class ActionCallbackImpl(override var context: Context?, private val handler: Handler) : ActionCallback() { override fun sendResponse(code: Int) { handler.obtainMessage(code).sendToTarget() } override fun sendResponse(code: Int, msg: String?) { handler.obtainMessage(code, """ $msg """).sendToTarget() } override fun sendResponse(msg: String?) { sendResponse(Constants.HANDLER_LOG, msg) } // public void sendLog(String log) { // handler.obtainMessage(Constants.HANDLER_LOG, "\t\t" + log + "\n").sendToTarget(); // } // // public void sendSuccessLog(String successLog) { // handler.obtainMessage(Constants.HANDLER_LOG_SUCCESS, "\t\t" + successLog + "\n") // .sendToTarget(); // } // // public void sendFailedLog(String failedLog) { // handler.obtainMessage(Constants.HANDLER_LOG_FAILED, "\t\t" + failedLog + "\n") // .sendToTarget(); // } }
APIDemoForAarBykotlin/app/src/main/java/com/cloudpos/mvc/impl/ActionContainerImpl.kt
2101387920
package com.cloudpos.mvc.impl import android.content.Context import android.util.Log import com.cloudpos.androidmvcmodel.MainApplication import com.cloudpos.androidmvcmodel.entity.MainItem import com.cloudpos.apidemoforunionpaycloudpossdk.R import com.cloudpos.mvc.base.AbstractAction import com.cloudpos.mvc.base.ActionContainer class ActionContainerImpl(private val context: Context?) : ActionContainer() { override fun initActions() { for (mainItem in MainApplication.Companion.testItems) { try { val classPath = getClassPath(mainItem) val clazz = Class.forName(classPath) if (mainItem != null) { addAction(mainItem.command, clazz as Class<out AbstractAction>, true) } } catch (e: Exception) { e.printStackTrace() Log.e(TAG, "Can't find this action") } } } private fun getClassPath(mainItem: MainItem): String? { var classPath: String? = null classPath = if (mainItem.isUnique()) { mainItem.packageName } else { (context!!.resources.getString(R.string.action_package_name) + mainItem.command) } return classPath } companion object { private const val TAG = "ActionContainerImpl" } }
APIDemoForAarBykotlin/app/src/main/java/com/cloudpos/mvc/common/MVCException.kt
4283945064
// // Source code recreated from a .class file by IntelliJ IDEA // (powered by Fernflower decompiler) // package com.cloudpos.mvc.common class MVCException : RuntimeException { constructor() {} constructor(msg: String?) : super(msg) {} constructor(cause: Throwable?) : super(cause) {} constructor(msg: String?, cause: Throwable?) : super(msg, cause) {} companion object { private const val serialVersionUID = -5923896637917336703L } }
APIDemoForAarBykotlin/app/src/main/java/com/cloudpos/mvc/common/Logger.kt
3932621486
// // Source code recreated from a .class file by IntelliJ IDEA // (powered by Fernflower decompiler) // package com.cloudpos.mvc.common import android.util.Log object Logger { var level = 3 fun debug(msg: String?) { if (level <= 3) { Log.d(createTag(), msg) } } fun debug(msg: String?, tr: Throwable?) { if (level <= 3) { Log.d(createTag(), msg, tr) } } fun info(msg: String?) { if (level <= 4) { Log.i(createTag(), msg) } } fun info(msg: String?, tr: Throwable?) { if (level <= 4) { Log.i(createTag(), msg, tr) } } fun warn(msg: String?) { if (level <= 5) { Log.w(createTag(), msg) } } fun warn(msg: String?, tr: Throwable?) { if (level <= 5) { Log.w(createTag(), msg, tr) } } fun error(msg: String?) { if (level <= 6) { Log.e(createTag(), msg) } } fun error(msg: String?, tr: Throwable?) { if (level <= 6) { Log.e(createTag(), msg, tr) } } private fun createTag(): String? { val sts = Thread.currentThread().stackTrace return if (sts == null) { null } else { val var3 = sts.size for (var2 in 0 until var3) { val st = sts[var2] if (!st.isNativeMethod && st.className != Thread::class.java.name && st.className != Logger::class.java.name) { return st.lineNumber.toString() + ":" + st.fileName } } "" } } }
APIDemoForAarBykotlin/app/src/main/java/com/cloudpos/mvc/base/ActionManager.kt
3921670354
// // 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.mvc.common.Logger import com.cloudpos.mvc.common.MVCException import java.util.* class ActionManager { private val actionScheduler: ActionScheduler = ActionScheduler.Companion.instance protected var mActionContainer: HashMap<Any?, Any?> = HashMap<Any?, Any?>() private var isStart = false private fun start() { actionScheduler.start() } private fun newActionContext(actionUrl: String, context: Context?, param: Map<String?, Any?>?, callback: ActionCallback?): ActionContext? { val acontext = ActionContext() acontext.setActionUrl(actionUrl) acontext.setParam(param) acontext.setCallback(callback) if (acontext != null) { acontext.setContext(context) } setAction(actionUrl, acontext) actionScheduler.setActionContext(acontext) return acontext } private fun setAction(actionUrl: String, context: ActionContext?) { val actionId: String = ActionContext.Companion.parseActionId(actionUrl) val obj = mActionContainer[actionId] if (obj == null) { throw MVCException("Not found actionId in ActionContainer. The actionId is [$actionId].") } else { if (Class::class.java.isInstance(obj)) { try { context!!.setAction((Class::class.java.cast(obj) as Class<*>).newInstance() as AbstractAction) } catch (var6: Exception) { Logger.error("build instance error:", var6) } } else { context!!.setAction(obj as AbstractAction?) } } } companion object { private val actionManager = ActionManager() private val instance: ActionManager private get() { if (!actionManager.isStart) { actionManager.start() actionManager.isStart = true } return actionManager } fun initActionContainer(actions: ActionContainer) { actions.initActions() instance.mActionContainer.putAll(actions.getActions()) } fun doSubmit(actionUrl: String, param: Map<String?, Any?>?, callback: ActionCallback?) { doSubmit(actionUrl, null as Context?, param, callback) } fun doSubmit(clazz: Class<out AbstractAction?>, methodName: String, param: Map<String?, Any?>?, callback: ActionCallback?) { doSubmit(clazz.name + "/" + methodName, param, callback) } fun doSubmit(actionUrl: String, context: Context?, param: Map<String?, Any?>?, callback: ActionCallback?) { instance.newActionContext(actionUrl, context, param, callback) } fun doSubmit(clazz: Class<out AbstractAction?>, methodName: String, context: Context?, param: Map<String?, Any?>?, callback: ActionCallback?) { doSubmit(clazz.name + "/" + methodName, context, param, callback) } fun <T> doSubmitForResult(actionUrl: String, param: Map<String?, Any?>?, callback: ActionCallback?): T? { return doSubmitForResult(actionUrl, null as Context?, param, callback) } fun <T> doSubmitForResult(clazz: Class<out AbstractAction?>, methodName: String, param: Map<String?, Any?>?, callback: ActionCallback?): T? { return doSubmitForResult(clazz.name + "/" + methodName, param, callback) } fun <T> doSubmitForResult(actionUrl: String, context: Context?, param: Map<String?, Any?>?, callback: ActionCallback?): T? { val acontext = instance.newActionContext(actionUrl, context, param, callback) return acontext!!.result as T } fun <T> doSubmitForResult(clazz: Class<out AbstractAction?>, methodName: String, context: Context?, param: Map<String?, Any?>?, callback: ActionCallback?): T? { return doSubmitForResult(clazz.name + "/" + methodName, context, param, callback) } } }
APIDemoForAarBykotlin/app/src/main/java/com/cloudpos/mvc/base/ActionCallback.kt
1378663942
// // Source code recreated from a .class file by IntelliJ IDEA // (powered by Fernflower decompiler) // package com.cloudpos.mvc.base import android.content.Context import android.os.Handler abstract class ActionCallback { open var context: Context? = null open fun ActionCallback() {} open fun ActionCallback(context: Context?) { this.context = context } open fun callbackInHandler(methodName: String?, vararg args: Any?) { val handler = Handler() handler.post(object : Runnable { override fun run() { try { BeanHelper(this).invoke(methodName, *args) } catch (var2: Exception) { var2.printStackTrace() } } }) } open fun sendResponse(code: Int) {} open fun sendResponse(msg: String?) {} open fun sendResponse(code: Int, msg: String?) {} }
APIDemoForAarBykotlin/app/src/main/java/com/cloudpos/mvc/base/ActionScheduler.kt
670071464
// // 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.concurrent.Executors import java.util.concurrent.LinkedBlockingQueue class ActionScheduler : Thread() { private val mActionQueue: LinkedBlockingQueue<ActionContext?> = LinkedBlockingQueue<ActionContext?>(20) private val service = Executors.newFixedThreadPool(30) override fun run() { var mContext: ActionContext? = null while (true) { while (true) { try { mContext = mActionQueue.take() service.submit(mContext) } catch (var3: Exception) { Logger.error("调度器发生错误", var3) } } } } fun setActionContext(context: ActionContext?) { if (context != null) { try { mActionQueue.put(context) } catch (var3: InterruptedException) { var3.printStackTrace() } } } companion object { val instance = ActionScheduler() } }
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 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/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.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/ActionContainer.kt
2853992387
// // 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/AbstractAction.kt
1927642149
// // 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/apidemo/common/Common.kt
569367463
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/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.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/SignatureModel.kt
1333239001
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/PINPadAction.kt
3315294992
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/IsoFingerPrintAction.kt
3249141797
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/LEDAction1.kt
628692573
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/MSRAction.kt
148792578
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/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 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/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 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/LEDAction2.kt
3429624938
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/HSMModel.kt
1429380012
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/PrinterAction.kt
2476275603
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/SerialPortAction.kt
3749872537
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/FingerPrintAction.kt
505971677
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/ActionModel.kt
3494956289
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/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.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/RFCardAction.kt
2638693428
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 } }
app-calculator/app/src/androidTest/java/com/voduchuy/appcalculator/ExampleInstrumentedTest.kt
1602277277
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/test/java/com/voduchuy/appcalculator/ExampleUnitTest.kt
1019613699
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/main/java/com/voduchuy/appcalculator/Calculator.kt
1957175626
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/CalculateOperation.kt
2322064092
package com.voduchuy.appcalculator enum class CalculateOperation { ADDITION, SUBTRACTION, MULTIPLICATION, DIVISION, }
app-calculator/app/src/main/java/com/voduchuy/appcalculator/room/Dao.kt
4190283210
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/HistoryViewModel.kt
4237062105
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/CalculateDatabase.kt
3639452298
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/CalculateAdapter.kt
2893717029
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/HistoryActivity.kt
3474749312
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/CalculateActivity.kt
3115641314
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) } } } }
nexus-farmap/app/src/main/java/com/nexus/farmap/newui/NewUI.kt
205971884
package com.nexus.farmap.newui class NewUI { }
nexus-farmap/app/src/main/java/com/nexus/farmap/newui/arnavigation/ARNav.kt
685549071
package com.nexus.farmap.newui.arnavigation
nexus-farmap/app/src/main/java/com/nexus/farmap/newui/startup/StartUp.kt
499597626
package com.nexus.farmap.newui.startup
nexus-farmap/app/src/main/java/com/nexus/farmap/newui/placeselect/PlaceSelect.kt
3123276182
package com.nexus.farmap.newui.placeselect
nexus-farmap/app/src/main/java/com/nexus/farmap/data/repository/GraphImpl.kt
2075227562
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/App.kt
247382506
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/data_source/GraphDao.kt
343462125
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/GraphDatabase.kt
1763120903
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/pathfinding/AStarNode.kt
829548030
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/AStarImpl.kt
454987697
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/utils/Reaction.kt
4033653855
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/ml/classification/TextAnalyzer.kt
716042741
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/utils/ImageUtils.kt
3185327492
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/VertexUtils.kt
2069768871
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/YuvToRgbConverter.kt
825656715
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/ARCoreSessionLifecycleHelper.kt
2830144001
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/model/DetectedObjectResult.kt
3927555452
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/TreeNodeDto.kt
1439495250
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/NeighboursConverter.kt
2189388547
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/domain/tree/TreeDiffUtils.kt
1764139161
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/WrongEntryException.kt
2317237383
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/Tree.kt
1492515084
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/TreeNode.kt
68562136
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/repository/GraphRepository.kt
1604210196
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/pathfinding/Path.kt
3950698785
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 } }