1 package jp.osdn.gokigen.thetathoughtshutter.bluetooth.connection
3 import android.app.Activity
4 import android.bluetooth.BluetoothAdapter
5 import android.bluetooth.BluetoothDevice
6 import android.bluetooth.BluetoothManager
7 import android.bluetooth.le.BluetoothLeScanner
8 import android.bluetooth.le.ScanCallback
9 import android.bluetooth.le.ScanResult
10 import android.content.Context
11 import android.util.Log
13 class BluetoothDeviceFinder(private val context: Activity, private val scanResult: IBluetoothScanResult) : BluetoothAdapter.LeScanCallback, ScanCallback()
18 private val TAG = BluetoothDeviceFinder::class.java.simpleName
20 private lateinit var targetDeviceName: String
21 private var foundBleDevice = false
22 private var scanner : BluetoothLeScanner? = null
26 foundBleDevice = false
33 Log.v(TAG, " stopScan()")
34 val btMgr: BluetoothManager = context.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
35 btMgr.adapter.cancelDiscovery()
36 scanner?.flushPendingScanResults(this)
37 scanner?.stopScan(this)
45 fun startScan(targetDeviceName: String)
49 this.targetDeviceName = targetDeviceName
50 val btAdapter = BluetoothAdapter.getDefaultAdapter()
51 if (!btAdapter.isEnabled)
53 // Bluetoothの設定がOFFだった
54 Log.v(TAG, " BLUETOOTH SETTING IS OFF")
55 scanResult.notFindBluetoothDevice()
59 val btMgr: BluetoothManager = context.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
60 scanBluetoothDevice(btMgr)
68 private fun scanBluetoothDevice(btMgr: BluetoothManager)
72 Log.v(TAG, " scanBluetoothDevice() ")
75 foundBleDevice = false
76 val adapter = btMgr.adapter
77 if (adapter.isDiscovering)
79 adapter.cancelDiscovery()
81 //adapter.startDiscovery()
82 scanner = adapter.bluetoothLeScanner
83 scanner?.startScan(this)
88 Log.v(TAG, "Bluetooth SCAN EXCEPTION...")
92 override fun onLeScan(device: BluetoothDevice, rssi: Int, scanRecord: ByteArray?)
96 Log.v(TAG, " onLeScan() ")
98 val btDeviceName = device.name
99 if (btDeviceName != null && btDeviceName.matches(Regex(targetDeviceName)))
102 foundBleDevice = true
103 scanResult.foundBluetoothDevice(device)
112 override fun onScanFailed(errorCode: Int)
114 Log.v(TAG, " onScanFailed : $errorCode")
117 override fun onScanResult(callbackType: Int, result: ScanResult?)
119 //super.onScanResult(callbackType, result)
120 val device = result?.device
121 Log.v(TAG, " onScanResult($callbackType, ${device?.name}) ")
122 val findDevice = (device?.name)?.contains(targetDeviceName)
123 if ((findDevice != null)&&(findDevice))
125 Log.v(TAG, " FIND DEVICE : $targetDeviceName")
126 scanResult.foundBluetoothDevice(device)
127 scanner?.stopScan(this)
131 override fun onBatchScanResults(results: MutableList<ScanResult>?)
133 //super.onBatchScanResults(results)
134 Log.v(TAG, " onBatchScanResults ")