package com.reactlibrary.verifone import android.annotation.SuppressLint import android.content.Context import android.net.wifi.WifiManager import android.util.Log import com.reactlibrary.verifone.Ttk.BerTlv2 import com.reactlibrary.verifone.Ttk.TtkResponse import com.reactlibrary.verifone.utils.TransactionMode import com.reactlibrary.verifone.utils.Utils import kotlinx.coroutines.TimeoutCancellationException import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withTimeout import org.jetbrains.anko.doAsync import java.io.IOException import java.io.InputStream import java.io.OutputStream import java.net.* import java.util.* class WirelessConnection private constructor(private var ip: ByteArray, private var port: Int = 0) : Thread() { private lateinit var sin: InputStream private lateinit var sout: OutputStream private var ipAddress: InetAddress? = null private lateinit var socket: Socket private lateinit var cntx: Context private var mTimer: Timer? = null private var timeoutTask: TimeOutTask? = null var isConnected: Boolean = false enum class ConnectStatus { CONNECTED, ERROR, NOT_CONNECTED, NOT_READABLE } fun setIpAddress(ip: ByteArray, port: Int) { this.ip = ip this.port = port } @Throws(IOException::class) private fun writeData(bytes: ByteArray, event: VerifoneTCP.OnMessageReceived?, operationName: String): TtkResponse? { try { sout.write(bytes) var len: Int val buffer = ByteArray(8192) reloadTimer() len = sin.read(buffer) while (len > 0) { val b = ByteArray(len) for (i in 0 until len) { b[i] = buffer[i] } val res = TtkResponse(b) if (res.isStatusMessage() && event !== null) { event.messageReceived(res) } if (res.isBreakingPayment) { Log.e("ru.lab24.vxlib", "PAN DETECTED ") stopTimer() return res } if (res.isApprove) { Log.e("ru.lab24.vxlib", "APPROVE") stopTimer() return res } if (res.isTransactionError()) { Log.e("ru.lab24.vxlib", "isTransactionError") stopTimer() return res } if (res.isOperationName(operationName)) { Log.e("ru.lab24.vxlib", "isOperationName " + res.id) stopTimer() return res } reloadTimer() len = sin.read(buffer) } return null } catch (e: SocketException) { Log.e("ru.lad24.vxlib error", Utils.getStackTrace(e)) disconnect() } return null } private fun connectionMonitoring(cntx: Context) { doAsync { while (true) { if (!checkWifiOnAndConnected(cntx)) { isConnected = false Log.e("ru.lab24.vxlib", "wifi $isConnected") break } if (socket.isConnected) { if (!socket.isBound) { isConnected = false Log.e("ru.lab24.vxlib", "isBound $isConnected") break } if (!socket.isConnected) { isConnected = false Log.e("ru.lab24.vxlib", "isConnected$isConnected") break } if (socket.isClosed) { isConnected = false Log.e("ru.lab24.vxlib", "isClosed$isConnected") break } // if (!isConecctedToInternet(getStringIp(ip))) { // isConnected = false // Log.e("ru.lab24.vxlib", "isConecctedToPinPad $isConnected") // break // } isConnected = true // Log.e("ru.lab24.vxlib", "" + isConnected) } else { isConnected = false } } return@doAsync } } private fun Byte.toPositiveInt() = toInt() and 0xFF private fun getStringIp(ip: ByteArray): String { return "${ip[0].toPositiveInt()}.${ip[1].toPositiveInt()}.${ip[2].toPositiveInt()}.${ip[3].toPositiveInt()}" } @SuppressLint("WifiManagerPotentialLeak") private fun checkWifiOnAndConnected(cntx: Context): Boolean { val wifiMgr = cntx.getSystemService(Context.WIFI_SERVICE) as WifiManager return if (wifiMgr.isWifiEnabled) { // Wi-Fi adapter is ON val wifiInfo = wifiMgr.connectionInfo wifiInfo.networkId != -1 } else { false // Wi-Fi adapter is OFF } } private fun isConecctedToInternet(ip: String): Boolean { val runtime = Runtime.getRuntime() try { val ipProcess = runtime.exec("/system/bin/ping -c 1 $ip") val exitValue = ipProcess.waitFor() return exitValue == 0 } catch (e: IOException) { e.printStackTrace() } catch (e: InterruptedException) { e.printStackTrace() } return false } private fun checkSockets(): TtkResponse? { return this.writeData( BerTlv2.Builder() .addOperationType("INF") .addTransactionMode(TransactionMode .Builder() .make()) .buildCommandByteArray() , null, "INF" ) } @Throws(TimeoutCancellationException::class) fun connectV2(context: Context, timeout: Int): ConnectStatus { return runBlocking { return@runBlocking withTimeout(timeout.toLong()) { cntx = context ipAddress = InetAddress.getByAddress(ip) socket = Socket() socket.connect(InetSocketAddress(ipAddress, port), timeout) Log.e("ru.lad24.vxlib", "socket ${socket.isConnected}") if (socket.isConnected) { sin = socket.getInputStream() val count: Int = sin.available() Log.e("ru.lad24.vxlib", "count $count") if (count == -1) { return@withTimeout ConnectStatus.NOT_READABLE } sout = socket.getOutputStream() socket.soTimeout = 3000 isConnected = count >= 0 && checkSockets() !== null socket.soTimeout = 0 if (isConnected) { connectionMonitoring(cntx) return@withTimeout ConnectStatus.CONNECTED } else { return@withTimeout ConnectStatus.NOT_CONNECTED } } else { return@withTimeout ConnectStatus.NOT_CONNECTED } } } } @Throws(IOException::class) fun disconnect() { Log.d("ru.lad24.vxlib", "disconnect") socket.close() sin.close() sout.close() isConnected = false } @Throws(IOException::class) fun write(bytes: ByteArray, event: VerifoneTCP.OnMessageReceived, operationName: String): TtkResponse? { Log.d("ru.lad24.vxlib", "write bytes") return writeData(bytes, event, operationName) } private inner class TimeOutTask : TimerTask() { override fun run() { Log.d("ru.lad24.vxlib", "Timer") disconnect() } } private fun reloadTimer() { Log.d("ru.lad24.vxlib", "reload timer") if (mTimer != null) { mTimer!!.cancel() mTimer = null } mTimer = Timer() timeoutTask = TimeOutTask() mTimer!!.schedule(timeoutTask, SHEDULER.toLong()) } private fun stopTimer() { Log.d("ru.lad24.vxlib", "stop timer") if (mTimer != null) { mTimer!!.cancel() mTimer = null } } companion object { private const val SHEDULER = 120000 fun init(ip: ByteArray, port: Int): WirelessConnection { return WirelessConnection(ip, port) } } }