התחברות לשרת GATT

השלב הראשון באינטראקציה עם מכשיר BLE הוא להתחבר אליו. באופן ספציפי יותר, החיבור לשרת ה-GATT במכשיר. כדי להתחבר לשרת GATT במכשיר BLE, משתמשים ב-method‏ connectGatt(). השיטה הזו מקבלת שלושה פרמטרים: אובייקט Context,‏ autoConnect (ערך בוליאני שמציין אם להתחבר אוטומטית למכשיר ה-BLE ברגע שהוא זמין) והפניה אל BluetoothGattCallback:

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

הפעולה הזו מתחברת לשרת ה-GATT שמתארח במכשיר ה-BLE, ומחזירה מכונה של BluetoothGatt, שבה אפשר להשתמש כדי לבצע פעולות של לקוח GATT. המתקשר (אפליקציית Android) הוא לקוח ה-GATT. ה-BluetoothGattCallback משמש להעברת תוצאות ללקוח, כמו סטטוס החיבור, וגם כל פעולה נוספת של לקוח GATT.

הגדרת שרת מאגד (bound service)

בדוגמה הבאה, אפליקציית ה-BLE מספקת פעילות (DeviceControlActivity) כדי להתחבר למכשירי Bluetooth, להציג את נתוני המכשיר ולהציג את שירותי ה-GATT והמאפיינים שנתמכים במכשיר. בהתאם לקלט של המשתמש, הפעילות הזו מתקשרת עם Service שנקרא BluetoothLeService, שמתקשר עם מכשיר ה-BLE באמצעות ה-API של BLE. שרת מאגד (bound service), שמאפשר לפעילות להתחבר אל 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 כדי להאזין לאירועי החיבור והניתוק, ודגל כדי לציין אפשרויות חיבור נוספות.

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 זמין במאמר הגדרת Bluetooth. בדוגמה הבאה, קוד ההגדרה הזה מוקף בפונקציה 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. הטיפול בערך החזרה False מהפונקציה initialize() תלוי באפליקציה. אפשר להציג למשתמש הודעת שגיאה שמציינת שהמכשיר הנוכחי לא תומך בפעולת Bluetooth, או להשבית את כל התכונות שדורשות Bluetooth כדי לפעול. בדוגמה הבאה, הפעילות קוראת ל-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.

// 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

אחרי שה-Activity אומרת לשירות לאיזה מכשיר להתחבר והשירות מתחבר למכשיר, השירות צריך להתחבר לשרת ה-GATT במכשיר ה-BLE. כדי לקבל התראות על מצב החיבור, זיהוי השירותים, קריאת המאפיינים והתראות על המאפיינים, החיבור הזה דורש BluetoothGattCallback.

המסמך הזה מתמקד בהתראות על מצב החיבור. במאמר העברת נתוני 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. צריך לרשום את המקלט הזה כשמגדירים את הפעילות, ולבטל את הרישום שלו כשהפעילות יוצאת מהמסך. האזנה לאירועים מהשירות מאפשרת לפעילות לעדכן את ממשק המשתמש על סמך מצב החיבור הנוכחי למכשיר ה-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 משמש גם כדי להעביר את זיהוי השירותים ואת נתוני המאפיינים מהמכשיר.

סגירת חיבור GATT

שלב חשוב כשעובדים עם חיבורי Bluetooth הוא לסגור את החיבור כשמסיימים להשתמש בו. כדי לעשות את זה, מפעילים את הפונקציה 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
        }
    }
}