เชื่อมต่อกับเซิร์ฟเวอร์ GATT

ขั้นตอนแรกในการโต้ตอบกับอุปกรณ์ BLE คือการเชื่อมต่อกับอุปกรณ์ โดยเฉพาะอย่างยิ่ง การเชื่อมต่อกับเซิร์ฟเวอร์ GATT บนอุปกรณ์ หากต้องการเชื่อมต่อกับเซิร์ฟเวอร์ GATT บนอุปกรณ์ BLE ให้ใช้เมธอด connectGatt() เมธอดนี้ใช้พารามิเตอร์ 3 รายการ ได้แก่ ออบเจ็กต์ Context, autoConnect (บูลีนที่ระบุว่าจะเชื่อมต่อกับอุปกรณ์ BLE โดยอัตโนมัติทันทีที่พร้อมใช้งานหรือไม่) และการอ้างอิงถึง BluetoothGattCallback ดังนี้

var bluetoothGatt: BluetoothGatt? = null
// ...
bluetoothGatt = device.connectGatt(this, false, bluetoothGattCallback)

ซึ่งจะเชื่อมต่อกับเซิร์ฟเวอร์ GATT ที่โฮสต์โดยอุปกรณ์ BLE และแสดงผลอินสแตนซ์ BluetoothGatt ซึ่งคุณสามารถใช้เพื่อดำเนินการกับไคลเอ็นต์ GATT ได้ ผู้โทร (แอป Android) คือไคลเอ็นต์ GATT BluetoothGattCallback ใช้เพื่อส่งผลลัพธ์ไปยังไคลเอ็นต์ เช่น สถานะการเชื่อมต่อ รวมถึงการดำเนินการอื่นๆ ของไคลเอ็นต์ GATT

ตั้งค่าบริการที่มีผลผูกพัน

ในตัวอย่างต่อไปนี้ แอป BLE จะมีกิจกรรม (DeviceControlActivity) เพื่อเชื่อมต่อกับอุปกรณ์บลูทูธ แสดงข้อมูลอุปกรณ์ รวมถึงแสดงบริการและลักษณะ GATT ที่อุปกรณ์รองรับ กิจกรรมนี้จะสื่อสารกับ Service ที่ชื่อว่า BluetoothLeService ซึ่งจะโต้ตอบกับอุปกรณ์ BLE โดยใช้ BLE API ตามข้อมูลที่ผู้ใช้ป้อน บริการที่มีผลผูกพันซึ่งช่วยให้กิจกรรมเชื่อมต่อกับ BluetoothLeService และเรียกใช้ฟังก์ชันเพื่อเชื่อมต่อกับอุปกรณ์จะจัดการการสื่อสารนี้ BluetoothLeService ต้องใช้การติดตั้งใช้งาน Binder ที่ให้สิทธิ์เข้าถึงบริการสำหรับกิจกรรม

class BluetoothLeService : Service() {

    private val binder = LocalBinder()

    override fun onBind(intent: Intent): IBinder? {
        return binder
    }

    inner class LocalBinder : Binder() {
        fun getService(): BluetoothLeService {
            return this@BluetoothLeService
        }
    }
}

กิจกรรมสามารถเริ่มบริการได้โดยใช้ bindService() โดยส่ง Intent เพื่อเริ่มบริการ, การติดตั้งใช้งาน ServiceConnection เพื่อฟังเหตุการณ์การเชื่อมต่อและการยกเลิกการเชื่อมต่อ และ Flag เพื่อระบุตัวเลือกการเชื่อมต่อเพิ่มเติม

class DeviceControlActivity : AppCompatActivity() {

    private var bluetoothService: BluetoothLeService? = null
    // Code to manage Service lifecycle.
    private val serviceConnection: ServiceConnection = object : ServiceConnection {
        override fun onServiceConnected(
            componentName: ComponentName,
            service: IBinder
        ) {
            bluetoothService = (service as LocalBinder).getService()
            bluetoothService?.let { bluetooth ->
                // call functions on service to check connection and connect to devices
            }
        }

        override fun onServiceDisconnected(componentName: ComponentName) {
            bluetoothService = null
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.gatt_services_characteristics)

        val gattServiceIntent = Intent(this, BluetoothLeService::class.java)
        bindService(gattServiceIntent, serviceConnection, Context.BIND_AUTO_CREATE)
    }
}

ตั้งค่า BluetoothAdapter

หลังจากกิจกรรมเชื่อมโยงกับบริการแล้ว บริการจะต้องเข้าถึง BluetoothAdapter โดยควรตรวจสอบว่าอะแดปเตอร์พร้อมใช้งานในอุปกรณ์หรือไม่ ดูข้อมูลเพิ่มเติมเกี่ยวกับ BluetoothAdapter ได้ที่หัวข้อตั้งค่าบลูทูธ ตัวอย่างต่อไปนี้รวมโค้ดการตั้งค่านี้ไว้ในฟังก์ชัน initialize() ที่แสดงผลค่า Boolean ซึ่งบ่งบอกถึงความสำเร็จ

private const val TAG = "BluetoothLeService"

class BluetoothLeService : Service() {

    private var bluetoothAdapter: BluetoothAdapter? = null

    fun initialize(): Boolean {
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
        if (bluetoothAdapter == null) {
            Log.e(TAG, "Unable to obtain a BluetoothAdapter.")
            return false
        }
        return true
    }

    // ...
}

กิจกรรมจะเรียกใช้ฟังก์ชันนี้ภายในเมธอด ServiceConnection การจัดการค่าที่แสดงผลเป็นเท็จจากฟังก์ชัน initialize() ขึ้นอยู่กับแอปพลิเคชันของคุณ คุณสามารถแสดงข้อความแสดงข้อผิดพลาดแก่ผู้ใช้เพื่อระบุว่าอุปกรณ์ปัจจุบันไม่รองรับการทำงานของบลูทูธ หรือปิดใช้ฟีเจอร์ที่ต้องใช้บลูทูธในการทำงาน ในตัวอย่างต่อไปนี้ กิจกรรมจะเรียกใช้ finish() เพื่อส่งผู้ใช้กลับไปยังหน้าจอก่อนหน้า

class DeviceControlActivity : AppCompatActivity() {

    // Code to manage Service lifecycle.
    private val serviceConnection: ServiceConnection = object : ServiceConnection {
        override fun onServiceConnected(
            componentName: ComponentName,
            service: IBinder
        ) {
            bluetoothService = (service as LocalBinder).getService()
            bluetoothService?.let { bluetooth ->
                if (!bluetooth.initialize()) {
                    Log.e(TAG, "Unable to initialize Bluetooth")
                    finish()
                }
                // perform device connection
            }
        }

        override fun onServiceDisconnected(componentName: ComponentName) {
            bluetoothService = null
        }
    }

    // ...
}

เชื่อมต่อกับอุปกรณ์

หลังจากอินสแตนซ์ BluetoothLeService เริ่มต้นแล้ว ก็จะเชื่อมต่อกับอุปกรณ์ BLE ได้ กิจกรรมต้องส่งที่อยู่อุปกรณ์ไปยังบริการเพื่อให้เริ่มการเชื่อมต่อได้ บริการจะเรียกใช้ getRemoteDevice() ใน BluetoothAdapter ก่อนเพื่อเข้าถึงอุปกรณ์ หากอะแดปเตอร์ไม่พบอุปกรณ์ที่มีที่อยู่ดังกล่าว getRemoteDevice() จะแสดง IllegalArgumentException

fun connect(address: String): Boolean {
    bluetoothAdapter?.let { adapter ->
        try {
            val device = adapter.getRemoteDevice(address)
        } catch (exception: IllegalArgumentException) {
            Log.w(TAG, "Device not found with provided address.")
            return false
        }
        // connect to the GATT server on the device
        return true
    } ?: run {
        Log.w(TAG, "BluetoothAdapter not initialized")
        return false
    }
}

DeviceControlActivity จะเรียกใช้ฟังก์ชัน connect() นี้หลังจาก เริ่มต้นบริการแล้ว กิจกรรมต้องส่งผ่านที่อยู่ของอุปกรณ์ BLE ในตัวอย่างต่อไปนี้ ระบบจะส่งที่อยู่อุปกรณ์ไปยังกิจกรรมเป็น Intent Extra

// Code to manage Service lifecycle.
private val serviceConnection: ServiceConnection = object : ServiceConnection {
    override fun onServiceConnected(
        componentName: ComponentName,
        service: IBinder
    ) {
        bluetoothService = (service as LocalBinder).getService()
        bluetoothService?.let { bluetooth ->
            if (!bluetooth.initialize()) {
                Log.e(TAG, "Unable to initialize Bluetooth")
                finish()
            }
            // perform device connection
            deviceAddress?.let { bluetooth.connect(it) }
        }
    }

    override fun onServiceDisconnected(componentName: ComponentName) {
        bluetoothService = null
    }
}

ประกาศ Callback ของ GATT

หลังจากกิจกรรมแจ้งบริการว่าต้องเชื่อมต่อกับอุปกรณ์ใดและบริการเชื่อมต่อกับอุปกรณ์แล้ว บริการจะต้องเชื่อมต่อกับเซิร์ฟเวอร์ GATT ในอุปกรณ์ BLE การเชื่อมต่อนี้ต้องใช้ BluetoothGattCallback เพื่อรับการแจ้งเตือนเกี่ยวกับสถานะการเชื่อมต่อ, Service Discovery, การอ่านลักษณะเฉพาะ และการแจ้งเตือนลักษณะเฉพาะ

เอกสารนี้จะเน้นที่การแจ้งเตือนสถานะการเชื่อมต่อ ดูวิธีค้นพบบริการ อ่านลักษณะ และขอการแจ้งเตือนลักษณะได้ที่โอนข้อมูล BLE

ฟังก์ชัน onConnectionStateChange() จะทำงานเมื่อการเชื่อมต่อกับเซิร์ฟเวอร์ GATT ของอุปกรณ์มีการเปลี่ยนแปลง ในตัวอย่างต่อไปนี้ มีการกำหนด Callback ในคลาส Service เพื่อให้ใช้กับ BluetoothDevice ได้หลังจากที่บริการเชื่อมต่อกับคลาสดังกล่าว

private val bluetoothGattCallback = object : BluetoothGattCallback() {
    override fun onConnectionStateChange(gatt: BluetoothGatt?, status: Int, newState: Int) {
        if (newState == BluetoothProfile.STATE_CONNECTED) {
            // successfully connected to the GATT Server
        } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
            // disconnected from the GATT Server
        }
    }
}

เชื่อมต่อกับบริการ GATT

หลังจากประกาศ BluetoothGattCallback แล้ว บริการจะใช้ออบเจ็กต์ BluetoothDevice จากฟังก์ชัน connect() เพื่อเชื่อมต่อกับบริการ GATT บนอุปกรณ์ได้

บริการจะเรียกใช้ฟังก์ชัน connectGatt() ซึ่งต้องใช้ออบเจ็กต์ Context, แฟล็กบูลีน autoConnect และ BluetoothGattCallback ในตัวอย่างนี้ แอปจะเชื่อมต่อกับอุปกรณ์ BLE โดยตรง ดังนั้นระบบจะส่ง false สำหรับ autoConnect

นอกจากนี้ บริการยังเพิ่มพร็อพเพอร์ตี้ BluetoothGatt เพื่อให้สามารถปิดการเชื่อมต่อเมื่อไม่จำเป็นต้องใช้แล้ว

class BluetoothLeService : Service() {

    // ...
    private var bluetoothGatt: BluetoothGatt? = null

    // ...
    fun connect(address: String): Boolean {
        bluetoothAdapter?.let { adapter ->
            try {
                val device = adapter.getRemoteDevice(address)
                // connect to the GATT server on the device
                bluetoothGatt = device.connectGatt(this, false, bluetoothGattCallback)
                return true
            } catch (exception: IllegalArgumentException) {
                Log.w(TAG, "Device not found with provided address.  Unable to connect.")
                return false
            }
        } ?: run {
            Log.w(TAG, "BluetoothAdapter not initialized")
            return false
        }
    }
}

อัปเดตการออกอากาศ

เมื่อบริการเชื่อมต่อหรือยกเลิกการเชื่อมต่อกับเซิร์ฟเวอร์ GATT บริการจะต้องแจ้งกิจกรรมเกี่ยวกับสถานะใหม่ ซึ่งทำได้หลายวิธี ตัวอย่างต่อไปนี้ใช้การออกอากาศเพื่อส่งข้อมูลจากบริการไปยังกิจกรรม

บริการจะประกาศฟังก์ชันเพื่อประกาศสถานะใหม่ ฟังก์ชันนี้จะรับสตริงการดำเนินการซึ่งส่งไปยังออบเจ็กต์ Intent ก่อนที่จะออกอากาศไปยังระบบ

private fun broadcastUpdate(action: String) {
    val intent = Intent(action)
    sendBroadcast(intent)
}

หลังจากที่ฟังก์ชันการออกอากาศพร้อมใช้งานแล้ว บริการจะใช้ฟังก์ชันดังกล่าวภายใน BluetoothGattCallback เพื่อส่งข้อมูลเกี่ยวกับสถานะการเชื่อมต่อกับเซิร์ฟเวอร์ GATT บริการจะประกาศค่าคงที่ซึ่งแสดงถึงการดำเนินการ Intent และสถานะการเชื่อมต่อปัจจุบันของบริการ

class BluetoothLeService : Service() {

    private var connectionState = STATE_DISCONNECTED

    private val bluetoothGattCallback = object : BluetoothGattCallback() {
        override fun onConnectionStateChange(gatt: BluetoothGatt?, status: Int, newState: Int) {
            if (newState == BluetoothProfile.STATE_CONNECTED) {
                // successfully connected to the GATT Server
                connectionState = STATE_CONNECTED
                broadcastUpdate(ACTION_GATT_CONNECTED)
            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                // disconnected from the GATT Server
                connectionState = STATE_DISCONNECTED
                broadcastUpdate(ACTION_GATT_DISCONNECTED)
            }
        }
    }

    // ...
    companion object {
        const val ACTION_GATT_CONNECTED =
            "com.example.bluetooth.le.ACTION_GATT_CONNECTED"
        const val ACTION_GATT_DISCONNECTED =
            "com.example.bluetooth.le.ACTION_GATT_DISCONNECTED"

        private const val STATE_DISCONNECTED = 0
        private const val STATE_CONNECTED = 2
    }
}

ฟังข้อมูลอัปเดตเกี่ยวกับกิจกรรม

หลังจากบริการประกาศการอัปเดตการเชื่อมต่อแล้ว กิจกรรมจะต้องใช้ BroadcastReceiver ลงทะเบียน BroadcastReceiver นี้เมื่อตั้งค่ากิจกรรม และยกเลิกการลงทะเบียนเมื่อกิจกรรมออกจากหน้าจอ การฟังเหตุการณ์จากบริการช่วยให้กิจกรรมอัปเดตอินเทอร์เฟซผู้ใช้ตามสถานะการเชื่อมต่อปัจจุบันกับอุปกรณ์ BLE ได้

class DeviceControlActivity : AppCompatActivity() {

    private val gattUpdateReceiver: BroadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            when (intent.action) {
                BluetoothLeService.ACTION_GATT_CONNECTED -> {
                    connected = true
                    updateConnectionState(R.string.connected)
                }
                BluetoothLeService.ACTION_GATT_DISCONNECTED -> {
                    connected = false
                    updateConnectionState(R.string.disconnected)
                }
            }
        }
    }

    override fun onResume() {
        super.onResume()
        registerReceiver(gattUpdateReceiver, makeGattUpdateIntentFilter())
        bluetoothService?.let { service ->
            deviceAddress?.let { address ->
                val result = service.connect(address)
                Log.d(TAG, "Connect request result=$result")
            }
        }
    }

    override fun onPause() {
        super.onPause()
        unregisterReceiver(gattUpdateReceiver)
    }

    private fun makeGattUpdateIntentFilter(): IntentFilter {
        return IntentFilter().apply {
            addAction(BluetoothLeService.ACTION_GATT_CONNECTED)
            addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED)
        }
    }
}

ในการโอนข้อมูล BLE ระบบจะใช้ BroadcastReceiver เพื่อสื่อสาร Service Discovery และข้อมูลลักษณะเฉพาะจากอุปกรณ์ด้วย

ปิดการเชื่อมต่อ GATT

ขั้นตอนสำคัญอย่างหนึ่งเมื่อจัดการกับการเชื่อมต่อบลูทูธคือการปิดการเชื่อมต่อเมื่อใช้งานเสร็จแล้ว โดยเรียกใช้ฟังก์ชัน close() ในออบเจ็กต์ BluetoothGatt ในตัวอย่างต่อไปนี้ บริการจะเก็บข้อมูลอ้างอิงไปยัง BluetoothGatt เมื่อกิจกรรมเลิกเชื่อมโยงกับบริการ ระบบจะปิดการเชื่อมต่อเพื่อหลีกเลี่ยงการใช้แบตเตอรี่ของอุปกรณ์จนหมด

class BluetoothLeService : Service() {

    // ...
    override fun onUnbind(intent: Intent?): Boolean {
        close()
        return super.onUnbind(intent)
    }

    private fun close() {
        bluetoothGatt?.let { gatt ->
            gatt.close()
            bluetoothGatt = null
        }
    }
}