ScanningActivity.kt 14.8 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
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<PrinterDevice>()
    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<Toolbar>(R.id.my_toolbar)
        printers = findViewById<ListView>(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<String> = 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<String?>,
        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<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 SerialDevicesAdapter(context: Context) : ArrayAdapter<PrinterDevice>(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<TextView>(R.id.name).text = device.printerName
                        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
                    }
        }
    }
}