الاتصال بخادم GATT

الخطوة الأولى للتفاعل مع جهاز BLE هي الاتصال به. وبشكل أكثر تحديدًا، الاتصال بخادم GATT على الجهاز. للاتصال بخادم GATT على جهاز يتضمّن تكنولوجيا BLE، استخدِم طريقة connectGatt(). تتطلّب هذه الطريقة ثلاث مَعلمات: عنصر 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. تتولّى خدمة الربط معالجة عملية الاتصال هذه، وهي تتيح للنشاط الاتصال بـ 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، يُرجى الاطّلاع على مقالة إعداد البلوتوث. يُغلِّف المثال التالي رمز الإعداد هذا في دالة 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.

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

الإعلان عن استدعاء GATT

بعد أن يخبر النشاط الخدمة بالجهاز الذي يجب الاتصال به وتتصل الخدمة بالجهاز، تحتاج الخدمة إلى الاتصال بخادم GATT على جهاز BLE. يتطلّب هذا الاتصال BluetoothGattCallback لتلقّي إشعارات حول حالة الاتصال واكتشاف الخدمة وقراءات الخصائص وإشعارات الخصائص.

يركّز هذا المستند على إشعارات حالة الاتصال. لمعرفة كيفية اكتشاف الخدمات وقراءة الخصائص وطلب إشعارات الخصائص، يُرجى الاطّلاع على نقل بيانات BLE.

يتم تشغيل الدالة onConnectionStateChange() عند تغيير الاتصال بخادم GATT الخاص بالجهاز. في المثال التالي، يتم تحديد دالة الاستدعاء في فئة 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. في هذا المثال، يتصل التطبيق مباشرةً بجهاز يتضمّن بلوتوث منخفض الطاقة، لذا يتم تمرير 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

تتمثل إحدى الخطوات المهمة عند التعامل مع اتصالات البلوتوث في إغلاق الاتصال عند الانتهاء منه. لإجراء ذلك، استدعِ الدالة 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
        }
    }
}