package com.printer.sdk.serial import android.Manifest import android.annotation.SuppressLint import android.app.Activity import android.app.ProgressDialog import android.content.Context import android.content.pm.PackageManager import android.os.Build import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.* import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.Toolbar import com.gainscha.sdk2.ConnectionListener import com.gainscha.sdk2.Printer import com.gainscha.sdk2.PrinterFinder import com.gainscha.sdk2.model.* import etelligens.com.foodsafety.R import etelligens.com.foodsafety.model.MacAddressModal import java.io.File import java.io.IOException import javax.crypto.Mac class ScanningActivity : AppCompatActivity() { private val finder: PrinterFinder = PrinterFinder() // private lateinit var serialPort: SerialPort private var devices = ArrayList() var toolbar: Toolbar? = null private lateinit var printers: ListView private var progress: ProgressDialog? = null // var refreshLayout: SwipeRefreshLayout? = null private lateinit var serialAdapter: SerialDevicesAdapter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_scanning) toolbar = findViewById(R.id.my_toolbar) printers = findViewById(R.id.printers) serialAdapter = SerialDevicesAdapter(this) // serialPort = SerialPort(this) printers.adapter = serialAdapter setup() } private fun setup() { initViews() initListeners() //initDeviceCallback() // add printer connection listener //设置输出日志,日志文件 Printer.setLogEnable(true, File("/sdcard/printer/printer.log")) Printer.addConnectionListener(connectionListener) // find printer devices(bluetooth wifi usb serial_port) if (checkBluetoothPermission()) { loaderShow() finder.searchPrinters(searchPrinterListener) } } private val connectionListener: ConnectionListener = object : ConnectionListener{ override fun onPrinterConnected(p0: Printer?) { //TODO("Not yet implemented") Log.d("ScanningActivity", "onPrinterConnected:$p0") runOnUiThread { setResult(Activity.RESULT_OK) loaderHide() finish() showToast("Connected") } } override fun onPrinterConnectFail(p0: Printer?) { //TODO("Not yet implemented") Log.d("ScanningActivity", "onPrinterConnectFail:$p0") runOnUiThread { loaderHide() showToast("connect failed") } } override fun onPrinterDisconnect(p0: Printer?) { // TODO("Not yet implemented") Log.d("ScanningActivity", "onPrinterDisconnect:$p0") } } private fun showToast(res:String){ Toast.makeText(this,res,Toast.LENGTH_LONG).show() } private val searchPrinterListener: PrinterFinder.SearchPrinterResultListener = object : PrinterFinder.SearchPrinterResultListener { override fun onSearchBluetoothPrinter(device: BluetoothPrinterDevice?) { if (device != null) { devices.add(device) // 获取 SharedPreferences 对象 val sharedPreferences = getSharedPreferences("connection_printer_mac", Context.MODE_PRIVATE) // 获取 SharedPreferences.Editor 对象,用于编辑数据 val editor = sharedPreferences.edit() // 存储数据(键值对) editor.putString("mac", device.bluetoothDevice.address) // 存储字符串 // 应用编辑(提交保存) editor.apply() serialAdapter.notifyDataSetChanged() } } override fun onSearchUsbPrinter(device: UsbPrinterDevice?) { //TODO("Not yet implemented") if (device != null) { devices.add(device) serialAdapter.notifyDataSetChanged() } } override fun onSearchUsbPrinter(device: UsbAccessoryPrinterDevice?) { //TODO("Not yet implemented") } override fun onSearchNetworkPrinter(device: WifiPrinterDevice?) { //TODO("Not yet implemented") } override fun onSearchSerialPortPrinter(device: SerialPortPrinterDevice?) { //TODO("Not yet implemented") } override fun onSearchCompleted() { loaderHide() } } private fun initDeviceCallback() { // serialPort.setDiscoveryCallback(object : DiscoveryCallback { // override fun onDiscoveryStarted() { // // } // // override fun onDiscoveryFinished() { // // } // // override fun onDeviceFound(device: BluetoothDevice) { // // } // // override fun onDevicePaired(device: BluetoothDevice) { //// FinalPrint.setPrinter(device.name, device.address) //// Toast.makeText(this@ScanningActivity, "Device Paired", Toast.LENGTH_SHORT).show() //// bluetoothAdapter.notifyDataSetChanged() //// setResult(Activity.RESULT_OK) //// this@ScanningActivity.finish() // } // // override fun onDeviceUnpaired(device: BluetoothDevice) { //// Toast.makeText(this@ScanningActivity, "Device unpaired", Toast.LENGTH_SHORT).show() //// val pairedPrinter = FinalPrint.getPairedPrinter() //// if (pairedPrinter != null && pairedPrinter.address == device.address) //// FinalPrint.removeCurrentPrinter() //// devices.remove(device) //// bluetoothAdapter.notifyDataSetChanged() //// bluetooth.startScanning() // } // // override fun onError(message: String) { // // } // // override fun onSerialDiscoveryStarted() { // // refreshLayout?.isRefreshing = true // toolbar?.title = "Scanning.." // devices.clear() // // devices.addAll(bluetooth.pairedDevices) // // Log.e("devices===", devices.toString()) // serialAdapter.notifyDataSetChanged() // } // // override fun onSerialDiscoveryFinished() { // toolbar?.title = if (devices.isNotEmpty()) "Select a Printer" else "No devices" // // refreshLayout?.isRefreshing = false // } // // override fun onSerialDeviceFound(device: String) { //// if (!devices.contains(device)) { //// devices.add(device) //// serialAdapter.notifyDataSetChanged() //// } // } // // override fun onSerialDevicePaired(device: String) { // TODO("Not yet implemented") // } // // override fun onSerialDeviceUnpaired(device: String) { // TODO("Not yet implemented") // } // override fun onSerialError(message: String) { // Toast.makeText(this@ScanningActivity, "Error while pairing", Toast.LENGTH_SHORT).show() // serialAdapter.notifyDataSetChanged() // } // // override fun onUsbDiscoveryStarted() { // // } // // override fun onUsbDiscoveryFinished() { // // } // // override fun onUsbDeviceFound(device: UsbDevice) { // // } // // override fun onUsbError(message: String) { // // } // }) } private fun initListeners() { // refreshLayout?.setOnRefreshListener { bluetooth.startScanning() } printers?.setOnItemClickListener { _, _, i, _ -> val device = devices[i] loaderShow() Printer.connect(device) } } private fun initViews() { printers?.adapter = serialAdapter } fun loaderShow() { if (progress == null) { progress = ProgressDialog(this, R.style.progressTheme) } progress!!.setTitle("Food Safety") progress!!.setMessage(getString(R.string.loading)) progress!!.show() } fun loaderHide() { if (progress == null) { progress = ProgressDialog(this) } progress!!.dismiss() } private fun checkBluetoothPermission(): Boolean { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { return true } val pms: Array = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { arrayOf( Manifest.permission.BLUETOOTH_SCAN, Manifest.permission.BLUETOOTH_CONNECT, Manifest.permission.ACCESS_FINE_LOCATION ) } else { arrayOf( Manifest.permission.BLUETOOTH, Manifest.permission.ACCESS_FINE_LOCATION ) } for (pm in pms) { if (checkSelfPermission(pm) != PackageManager.PERMISSION_GRANTED) { requestPermissions(pms, 100) return false } } return true } override fun onRequestPermissionsResult( requestCode: Int, permissions: Array, grantResults: IntArray ) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) if (requestCode == 100) { var grantAll = true for (r in grantResults) { if (r != PackageManager.PERMISSION_GRANTED) { grantAll = false break } } if (grantAll) { finder.searchPrinters(searchPrinterListener) } } } override fun onStart() { super.onStart() // serialPort.onStart() // Handler().postDelayed({ // serialPort.startScanning() // }, 1000) } override fun onStop() { super.onStop() // serialPort.onStop() } override fun onDestroy() { super.onDestroy() // stop find printer device finder.stopSearchDevice() Printer.removeConnectionListener(connectionListener) } companion object { const val SCANNING_FOR_PRINTER = 115 } /* inner class BluetoothDevicesAdapter(private val devices: List) : RecyclerView.Adapter() { // create new views override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { // inflates the card_view_design view // that is used to hold list item val view = LayoutInflater.from(parent.context) .inflate(R.layout.bluetooth_device_row, parent, false) return ViewHolder(view) } // binds the list items to a view override fun onBindViewHolder(holder: ViewHolder, position: Int) { val BluetoothDevice = devices[position] if (devices[position].name.isNullOrEmpty()){ holder.name.setText(devices[position].address) }else{ holder.name.setText(devices[position].name) } when (devices[position].bondState) { BluetoothDevice.BOND_BONDED -> "Paired" BluetoothDevice.BOND_BONDING -> "Pairing.." // sets the image to the imageview from our itemHolder class // holder.imageView.setImageResource(ItemsViewModel.image) // sets the text to the textview from our itemHolder class // holder.textView.text = ItemsViewModel.text } // return the number of the items in the list override fun getItemCount(): Int { return devices.size } // Holds the views for adding it to image and text inner class ViewHolder(ItemView: View) : RecyclerView.ViewHolder(ItemView) { val name: TextView = itemView.findViewById(R.id.name) val deviceStatus: TextView = itemView.findViewById(R.id.pairStatus) } } */ /* inner class BluetoothDevicesAdapter(private val context: Context, private val device: ArrayList) : BaseAdapter() { override fun getCount(): Int { Log.e("size==", device.size.toString()) return device.size } override fun getItem(position: Int): Any { return position } override fun getItemId(position: Int): Long { return position.toLong() } override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { return LayoutInflater.from(context) .inflate(R.layout.bluetooth_device_row, parent, false).apply { findViewById(R.id.name).text = if (device[position].name.isNullOrEmpty()) device[position].address else device[position].name findViewById(R.id.pairStatus).visibility = if (device[position].bondState != BluetoothDevice.BOND_NONE) View.VISIBLE else View.INVISIBLE findViewById(R.id.pairStatus).text = when (device[position].bondState) { BluetoothDevice.BOND_BONDED -> "Paired" BluetoothDevice.BOND_BONDING -> "Pairing.." else -> "" } } } }*/ inner class SerialDevicesAdapter(context: Context) : ArrayAdapter(context, android.R.layout.simple_list_item_1) { override fun getCount(): Int { return devices.size } @SuppressLint("ViewHolder", "CutPasteId") override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { val device = devices[position]; return LayoutInflater.from(context) .inflate(R.layout.bluetooth_device_row, parent, false).apply { findViewById(R.id.name).text = device.printerName findViewById(R.id.pairStatus).visibility = View.INVISIBLE // findViewById(R.id.pairStatus).text = when (devices[position].bondState) { // BluetoothDevice.BOND_BONDED -> "Paired" // BluetoothDevice.BOND_BONDING -> "Pairing.." // else -> "" // } findViewById(R.id.pairedPrinter).visibility = View.GONE } } } }