package com.shukria.kiosklauncher.ui import android.app.ActivityManager import android.app.PendingIntent import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.hardware.usb.UsbDevice import android.hardware.usb.UsbManager import android.os.Bundle import android.os.Handler import android.os.Looper import android.os.Parcelable import android.text.TextUtils import android.util.Log import android.widget.ArrayAdapter import android.widget.Spinner import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import com.shukria.kiosklauncher.R import com.shukria.kiosklauncher.service.MQTTService import com.shukria.kiosklauncher.util.KioskUtil import com.shukria.kiosklauncher.util.WebSocketManager import org.json.JSONException import org.json.JSONObject import print.Print import print.PublicFunction import java.io.BufferedReader import java.io.FileReader import java.io.IOException import java.util.concurrent.Executors //import com.leon.lfilepickerlibrary.LFilePicker; class MainActivity : AppCompatActivity() { private var thisCon: Context? = null private val PFun: PublicFunction? = null private val PAct: PublicAction? = null private var spnPrinterList: Spinner? = null private val arrPrinterList: ArrayAdapter<*>? = null private var ConnectType = "" private val PrinterName = "" private var mUsbManager: UsbManager? = null private var device: UsbDevice? = null private val ACTION_USB_PERMISSION = "com.PRINTSDKSample" var REQUESTCODE_FROM_ACTIVITY = 1000 var REQUESTCODE_FROM_ACTIVITY_IMAGE = 9999 private val executorService = Executors.newSingleThreadExecutor() private val BITMAP_BLACKW = 0 private val BITMAP_SHAKE = 1 private val BITMAP_GATHER = 2 private val PRINT_SUCCEED = 1 private val PRINT_FAILURE = 0 private val PRINT_THREE_INCH = 576 private val PRINT_TWO_INCH = 384 private val PRINT_FOUR_INCH = 832 private val mPermissionIntent: PendingIntent? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) MQTTService.start(this) initializeWebSocketConnection() initialisePrinter() KioskUtil.startKioskMode(this) } private fun initialisePrinter() { val usbDevice: UsbDevice? = null thisCon = this.applicationContext if(this.connectUSB()) { Print.Initialize(); } } private fun getPrintStatus() { try { var statusStr = "" val bytes = Print.GetRealTimeStatus(2.toByte()) statusStr = if (bytes[0].toInt() and 4 == 4) ({ "Cover is Open" }).toString() else { "Cover is Close" } val bytes1 = Print.GetRealTimeStatus(4.toByte()) statusStr = if (bytes1[0].toInt() and 96 == 96) { "$statusStr No Paper" } else { "$statusStr Paper Available" } statusStr = if (bytes1[0].toInt() and 12 == 12) { "$statusStr Paper Near to End" } else { "$statusStr Paper Available" } if (TextUtils.isEmpty(statusStr)) return showToast(statusStr) } catch (e: java.lang.Exception) { } } private fun printSelf() { try { Print.printSelf() } catch (e: java.lang.Exception) { } } private fun getPrinterSN(): String { var printSN ="" try { printSN = Print.getPrintSN() if (TextUtils.isEmpty(printSN)) { showToast("Printer serial number issue") } else { showToast("Printer serial number issue" + printSN.toString()) return printSN } } catch (e: java.lang.Exception) { } return "" } private fun connectUSB(): Boolean { thisCon = this.applicationContext ConnectType = "USB" //USB not need call "iniPort" mUsbManager = thisCon!!.getSystemService(USB_SERVICE) as UsbManager val deviceList = mUsbManager!!.getDeviceList() val deviceIterator: Iterator = deviceList.values.iterator() var HavePrinter = false while (deviceIterator.hasNext()) { device = deviceIterator.next() val count = device!!.getInterfaceCount() for (i in 0 until count) { val intf = device!!.getInterface(i) if (intf.interfaceClass == 7) { HavePrinter = true if (mPermissionIntent != null) { Log.d( "PRINT_TAG", "vendorID--" + device!!.getVendorId() + "ProductId--" + device!!.getProductId() ) mUsbManager!!.requestPermission(device, mPermissionIntent) } } } } if (!HavePrinter) showToast("print not connected") return HavePrinter } private val mUsbReceiver: BroadcastReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { try { val action = intent.action Log.d("TAG", "action: $action") if (UsbManager.ACTION_USB_DEVICE_ATTACHED == action) { synchronized(this) { device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE) as UsbDevice? if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) { if (Print.PortOpen(thisCon, device) != 0) { showToast("Printer connected Error") return } else showToast("Printer connected ") } else { return } } } if (UsbManager.ACTION_USB_DEVICE_DETACHED == action) { device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE) as UsbDevice? if (device != null) { val count = device!!.interfaceCount for (i in 0 until count) { val intf = device!!.getInterface(i) //Class ID 7代表打印机 if (intf.interfaceClass == 7) { Print.PortClose() showToast(" Print disconnected") } } } } } catch (e: java.lang.Exception) { Log.e( "SDKSample", StringBuilder("Activity_Main --> mUsbReceiver ") .append(e.message).toString() ) } } } private fun initializeWebSocketConnection() { showToast("Initializing WebSocket") val serverUrl = "wss://healthcare.ctrmv.com:9443/?user_id=9008001@bmrcl.com" WebSocketManager.getInstance().initializeWebSocketConnection(serverUrl) WebSocketManager.getInstance().setWebSocketEventListener(object : WebSocketManager.WebSocketEventListener { override fun onWebSocketOpen() { Log.e("WebSocket", "Websocket open") sendDeviceRegistration() startSendingDeviceInformation() } override fun onWebSocketClose(code: Int, reason: String) { Log.e("WebSocket", "Websocket close ") showToast("WebSocket closed: $reason") stopSendingDeviceInformation() } override fun onWebSocketError(ex: Exception) { Log.e("WebSocket", "Error occurred: ${ex.message}") stopSendingDeviceInformation() // showToast("WebSocket error: ${ex.message}") } override fun onWebSocketMessage(message: String) { Log.e("WebSocket", "Websocket Message") // showToast("Message received: $message") } }) } private val handler = Handler(Looper.getMainLooper()) private val interval = 5000L // 5 seconds private var isSendingData = false private fun startSendingDeviceInformation() { isSendingData = true handler.post(object : Runnable { override fun run() { if (isSendingData) { sendDeviceInformation() // Method to send device info handler.postDelayed(this, interval) } } }) } private fun stopSendingDeviceInformation() { isSendingData = false handler.removeCallbacksAndMessages(null) } private fun sendDeviceRegistration() { val deviceName = "Device Name" val randomAmount = Math.random() val deviceId = "90080001@bmrcl.com" // Replace with actual device ID val userId = "prem@gupta.com.pinpoint" val registerMessage = """ { "action": "register", "device_id": "$deviceId", "user_id": "prem@gupta.com.pinpoint", //modify this to broadcast@alluser "device_name": "$deviceName" } """.trimIndent() val registerJson = JSONObject(registerMessage) val transformedRegisterMessage = JSONObject() transformedRegisterMessage.put("userId", userId) registerJson.remove("user_id") transformedRegisterMessage.put("message", registerJson) Log.d("WebSocket", "register Message:${transformedRegisterMessage}") if (WebSocketManager.getInstance().webSocketClient?.isOpen == true) { // WebSocketManager.getInstance().sendMessage("Simple message") WebSocketManager.getInstance().sendMessage(transformedRegisterMessage.toString()) Log.d("WebSocket", "Message sent") } else { Log.d("WebSocket", "WebSocket not open") } } private fun sendDeviceInformation() { // showToast("WebSocket connection opened") // Send registration message val deviceId = "90080001@bmrcl.com" // Replace with actual device ID val userId = "prem@gupta.com.pinpoint" val deviceData = JSONObject() val transformedDeviceData = JSONObject() try { deviceData.put("device_id", deviceId) deviceData.put("user_id", "prem@gupta.com.pinpoint") deviceData.put("ram_usage", getUsedMemory()) deviceData.put("cpu_usage", getCpuUsage()) // deviceData.put("installed_apps", JSONArray(getInstalledApps())) deviceData.put("memory_usage", getMemoryUsage()) // Add other required info transformedDeviceData.put("userId", userId) deviceData.remove("user_id") transformedDeviceData.put("message", deviceData) } catch (e: JSONException) { e.printStackTrace() } if (WebSocketManager.getInstance().webSocketClient?.isOpen == true) { // WebSocketManager.getInstance().sendMessage("Simple message") WebSocketManager.getInstance().sendMessage(transformedDeviceData.toString()) Log.d("WebSocket", "Message sent") } else { Log.d("WebSocket", "WebSocket not open") } } fun getUsedMemory(): Long { val activityManager = getSystemService(ACTIVITY_SERVICE) as ActivityManager val memoryInfo = ActivityManager.MemoryInfo() activityManager.getMemoryInfo(memoryInfo) val totalMem = memoryInfo.totalMem val availMem = memoryInfo.availMem return totalMem-availMem } fun getCpuUsage(): String? { return try { val cpuInfo = readCpuInfo() var totalCpuTime: Long = 0 for (time in cpuInfo) { totalCpuTime += time.toLong() } // Log.d("CPU Usage:", totalCpuTime.toString()) totalCpuTime = Math.random().toLong() "$totalCpuTime" // You can enhance this calculation } catch (e: IOException) { e.printStackTrace() var totalCpuTime = Math.random().toLong() "$totalCpuTime" } } @Throws(IOException::class) private fun readCpuInfo(): Array { val fileReader = FileReader("/proc/stats") val reader = BufferedReader(fileReader) val cpuLine = reader.readLine() reader.close() return cpuLine.split("\\s+".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() } fun getInstalledApps(): List? { val packageManager = packageManager val apps = packageManager.getInstalledApplications(PackageManager.GET_META_DATA) val appNames: MutableList = ArrayList() for (app in apps) { appNames.add(app.packageName) // or app.loadLabel(packageManager).toString() for app names } return appNames } fun getMemoryUsage(): String? { val activityManager = getSystemService(ACTIVITY_SERVICE) as ActivityManager val memoryInfo = ActivityManager.MemoryInfo() activityManager.getMemoryInfo(memoryInfo) val totalMem = memoryInfo.totalMem val availMem = memoryInfo.availMem return "Total: $totalMem, Available: $availMem" } override fun onDestroy() { Log.e("WebSocket", "Websocket destroy and issue") showToast("destroy and issue") super.onDestroy() WebSocketManager.getInstance().closeConnection() } private fun showToast(message: String) { Toast.makeText(this, message, Toast.LENGTH_SHORT).show() } fun PublicAction(con: Context) { } }