ScanningActivity 9.76 KB
package com.printer.sdk.usb

import android.annotation.SuppressLint
import android.app.Activity
import android.bluetooth.BluetoothDevice
import android.content.Context
import android.hardware.usb.UsbDevice
import android.os.Bundle
import android.os.Handler
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 androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import etelligens.com.foodsafety.PrintLabel.PrintClasses.DiscoveryCallback
import etelligens.com.foodsafety.R
import java.io.File

class ScanningActivity : AppCompatActivity() {
    private lateinit var usbPort: UsbPort
    private var devices = ArrayList<UsbDevice>()
    var toolbar: Toolbar? = null
    var printers: ListView? = null

    // var refreshLayout: SwipeRefreshLayout? = null
    private lateinit var usbAdapter: UsbDevicesAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_scanning)
        toolbar = findViewById(R.id.my_toolbar) as Toolbar?
        printers = findViewById(R.id.printers)
        usbAdapter = UsbDevicesAdapter(this)
        usbPort = UsbPort(this)
        setup()
    }

    private fun setup() {
        initViews()
        initListeners()
        initDeviceCallback()
    }

    private fun initDeviceCallback() {
        usbPort.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() {
                TODO("Not yet implemented")
            }

            override fun onSerialDiscoveryFinished() {
                TODO("Not yet implemented")
            }

            override fun onSerialDeviceFound(device: File) {
                TODO("Not yet implemented")
            }

            override fun onSerialDevicePaired(device: File) {
                TODO("Not yet implemented")
            }

            override fun onSerialDeviceUnpaired(device: File) {
                TODO("Not yet implemented")
            }

            override fun onSerialError(message: String) {
                TODO("Not yet implemented")
            }

            override fun onUsbDiscoveryStarted() {
                // refreshLayout?.isRefreshing = true
                toolbar?.title = "Scanning.."
                devices.clear()
             //   devices.addAll(bluetooth.pairedDevices)
            //    Log.e("devices===", devices.toString())
                usbAdapter.notifyDataSetChanged()
            }

            override fun onUsbDiscoveryFinished() {
                toolbar?.title = if (devices.isNotEmpty()) "Select a Printer" else "No devices"
                // refreshLayout?.isRefreshing = false
            }

            override fun onUsbDeviceFound(device: UsbDevice) {
                if (!devices.contains(device)) {
                    devices.add(device)
                    usbAdapter.notifyDataSetChanged()
                }
            }

            override fun onUsbError(message: String) {
                Toast.makeText(this@ScanningActivity, "Error while pairing", Toast.LENGTH_SHORT).show()
                usbAdapter.notifyDataSetChanged()
            }
        })
    }

    private fun initListeners() {
        // refreshLayout?.setOnRefreshListener { bluetooth.startScanning() }
        printers?.setOnItemClickListener { _, _, i, _ ->
            val device = devices[i]
            val vid=device.vendorId;
            val pid=device.productId;
            FinalPrint.setPrinter(device.deviceName,"vid:$vid\npid:$pid");
            setResult(Activity.RESULT_OK)
            this@ScanningActivity.finish()
            usbAdapter.notifyDataSetChanged()
        }
    }

    private fun initViews() {
        printers?.adapter = usbAdapter

    }

    override fun onStart() {
        super.onStart()

        usbPort.onStart()
        Handler().postDelayed({
            usbPort.startScanning()
        }, 1000)


    }

    override fun onStop() {
        super.onStop()
        usbPort.onStop()
    }

    companion object {
        const val SCANNING_FOR_PRINTER = 115
    }

    /* inner class BluetoothDevicesAdapter(private val devices: List<BluetoothDevice>) : RecyclerView.Adapter<BluetoothDevicesAdapter.ViewHolder>() {

         // 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<BluetoothDevice>) : 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<TextView>(R.id.name).text = if (device[position].name.isNullOrEmpty()) device[position].address else device[position].name
                     findViewById<TextView>(R.id.pairStatus).visibility = if (device[position].bondState != BluetoothDevice.BOND_NONE) View.VISIBLE else View.INVISIBLE
                     findViewById<TextView>(R.id.pairStatus).text = when (device[position].bondState) {
                         BluetoothDevice.BOND_BONDED -> "Paired"
                         BluetoothDevice.BOND_BONDING -> "Pairing.."
                         else -> ""
                     }
                 }
         }
     }*/

    inner class UsbDevicesAdapter(context: Context) : ArrayAdapter<UsbDevice>(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];
            val name=device.deviceName;
            val vid=device.vendorId;
            val pid=device.productId;
            val textShowStr="$name\nvid:$vid,pid:$pid";
            return LayoutInflater.from(context)
                    .inflate(R.layout.bluetooth_device_row, parent, false).apply {
                        findViewById<TextView>(R.id.name).text = textShowStr;
                        findViewById<TextView>(R.id.pairStatus).visibility = View.INVISIBLE
//                        findViewById<TextView>(R.id.pairStatus).text = when (devices[position].bondState) {
//                            BluetoothDevice.BOND_BONDED -> "Paired"
//                            BluetoothDevice.BOND_BONDING -> "Pairing.."
//                            else -> ""
//                        }
                        findViewById<ImageView>(R.id.pairedPrinter).visibility = View.GONE
                    }
        }
    }
}