summaryrefslogtreecommitdiffstats
path: root/src/android/bluetooth/src/org/qtproject/qt5/android/bluetooth/QtBluetoothLEServer.java
blob: 2e3e32d550e80ac3b9a7df5f55e4a80b855d8a8b (plain)
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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
/****************************************************************************
 **
 ** Copyright (C) 2016 The Qt Company Ltd.
 ** Contact: https://www.qt.io/licensing/
 **
 ** This file is part of the QtBluetooth module of the Qt Toolkit.
 **
 ** $QT_BEGIN_LICENSE:LGPL$
 ** Commercial License Usage
 ** Licensees holding valid commercial Qt licenses may use this file in
 ** accordance with the commercial license agreement provided with the
 ** Software or, alternatively, in accordance with the terms contained in
 ** a written agreement between you and The Qt Company. For licensing terms
 ** and conditions see https://www.qt.io/terms-conditions. For further
 ** information use the contact form at https://www.qt.io/contact-us.
 **
 ** GNU Lesser General Public License Usage
 ** Alternatively, this file may be used under the terms of the GNU Lesser
 ** General Public License version 3 as published by the Free Software
 ** Foundation and appearing in the file LICENSE.LGPL3 included in the
 ** packaging of this file. Please review the following information to
 ** ensure the GNU Lesser General Public License version 3 requirements
 ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
 **
 ** GNU General Public License Usage
 ** Alternatively, this file may be used under the terms of the GNU
 ** General Public License version 2.0 or (at your option) the GNU General
 ** Public license version 3 or any later version approved by the KDE Free
 ** Qt Foundation. The licenses are as published by the Free Software
 ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
 ** included in the packaging of this file. Please review the following
 ** information to ensure the GNU General Public License requirements will
 ** be met: https://www.gnu.org/licenses/gpl-2.0.html and
 ** https://www.gnu.org/licenses/gpl-3.0.html.
 **
 ** $QT_END_LICENSE$
 **
 ****************************************************************************/

package org.qtproject.qt5.android.bluetooth;

import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.content.Context;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattServer;
import android.bluetooth.BluetoothGattServerCallback;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.le.AdvertiseCallback;
import android.bluetooth.le.AdvertiseData;
import android.bluetooth.le.AdvertiseData.Builder;
import android.bluetooth.le.AdvertiseSettings;
import android.bluetooth.le.BluetoothLeAdvertiser;
import android.os.ParcelUuid;
import android.util.Log;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.HashMap;
import java.util.UUID;

public class QtBluetoothLEServer {
    private static final String TAG = "QtBluetoothGattServer";

    /* Pointer to the Qt object that "owns" the Java object */
    @SuppressWarnings({"CanBeFinal", "WeakerAccess"})
    long qtObject = 0;
    @SuppressWarnings("WeakerAccess")

    private Context qtContext = null;

    // Bluetooth members
    private final BluetoothAdapter mBluetoothAdapter;
    private BluetoothGattServer mGattServer = null;
    private BluetoothLeAdvertiser mLeAdvertiser = null;

    private ArrayList<BluetoothGattService> mPendingServiceAdditions =
                      new ArrayList<BluetoothGattService>();

    private String mRemoteName = "";
    // This function is called from Qt thread
    public synchronized String remoteName() {
        return mRemoteName;
    }

    private String mRemoteAddress = "";
    // This function is called from Qt thread
    public synchronized String remoteAddress() {
        return mRemoteAddress;
    }

    /*
        As per Bluetooth specification each connected device can have individual and persistent
        Client characteristic configurations (see Bluetooth Spec 5.0 Vol 3 Part G 3.3.3.3)
        This class manages the existing configurrations.
     */
    private class ClientCharacteristicManager {
        private final HashMap<BluetoothGattCharacteristic, List<Entry>> notificationStore = new HashMap<BluetoothGattCharacteristic, List<Entry>>();

        private class Entry {
            BluetoothDevice device = null;
            byte[] value = null;
            boolean isConnected = false;
        }

        public void insertOrUpdate(BluetoothGattCharacteristic characteristic,
                              BluetoothDevice device, byte[] newValue)
        {
            if (notificationStore.containsKey(characteristic)) {

                List<Entry> entries = notificationStore.get(characteristic);
                for (int i = 0; i < entries.size(); i++) {
                    if (entries.get(i).device.equals(device)) {
                        Entry e = entries.get(i);
                        e.value = newValue;
                        entries.set(i, e);
                        return;
                    }
                }

                // not match so far -> add device to list
                Entry e = new Entry();
                e.device = device;
                e.value = newValue;
                e.isConnected = true;
                entries.add(e);
                return;
            }

            // new characteristic
            Entry e = new Entry();
            e.device = device;
            e.value = newValue;
            e.isConnected = true;
            List<Entry> list = new LinkedList<Entry>();
            list.add(e);
            notificationStore.put(characteristic, list);
        }

        /*
            Marks client characteristic configuration entries as (in)active based the associated
            devices general connectivity state.
            This function avoids that existing configurations are not acted
            upon when the associated device is not connected.
         */
        public void markDeviceConnectivity(BluetoothDevice device, boolean isConnected)
        {
            final Iterator<BluetoothGattCharacteristic> keys = notificationStore.keySet().iterator();
            while (keys.hasNext()) {
                final BluetoothGattCharacteristic characteristic = keys.next();
                final List<Entry> entries = notificationStore.get(characteristic);
                if (entries == null)
                    continue;

                ListIterator<Entry> charConfig = entries.listIterator();
                while (charConfig.hasNext()) {
                    Entry e = charConfig.next();
                    if (e.device.equals(device))
                        e.isConnected = isConnected;
                }
            }
        }

        // Returns list of all BluetoothDevices which require notification or indication.
        // No match returns an empty list.
        List<BluetoothDevice> getToBeUpdatedDevices(BluetoothGattCharacteristic characteristic)
        {
            ArrayList<BluetoothDevice> result = new ArrayList<BluetoothDevice>();
            if (!notificationStore.containsKey(characteristic))
                return result;

            final ListIterator<Entry> iter = notificationStore.get(characteristic).listIterator();
            while (iter.hasNext())
                result.add(iter.next().device);

            return result;
        }

        // Returns null if no match; otherwise the configured actual client characteristic
        // configuration value
        byte[] valueFor(BluetoothGattCharacteristic characteristic, BluetoothDevice device)
        {
            if (!notificationStore.containsKey(characteristic))
                return null;

            List<Entry> entries = notificationStore.get(characteristic);
            for (int i = 0; i < entries.size(); i++) {
                final Entry entry = entries.get(i);
                if (entry.device.equals(device) && entry.isConnected == true)
                    return entries.get(i).value;
            }

            return null;
        }
    }

    private static final UUID CLIENT_CHARACTERISTIC_CONFIGURATION_UUID = UUID
            .fromString("00002902-0000-1000-8000-00805f9b34fb");
    ClientCharacteristicManager clientCharacteristicManager = new ClientCharacteristicManager();

    public QtBluetoothLEServer(Context context)
    {
        qtContext = context;
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        if (mBluetoothAdapter == null || qtContext == null) {
            Log.w(TAG, "Missing Bluetooth adapter or Qt context. Peripheral role disabled.");
            return;
        }

        BluetoothManager manager = (BluetoothManager) qtContext.getSystemService(Context.BLUETOOTH_SERVICE);
        if (manager == null) {
            Log.w(TAG, "Bluetooth service not available.");
            return;
        }

        mLeAdvertiser = mBluetoothAdapter.getBluetoothLeAdvertiser();

        if (!mBluetoothAdapter.isMultipleAdvertisementSupported())
            Log.w(TAG, "Device does not support Bluetooth Low Energy advertisement.");
        else
            Log.w(TAG, "Let's do BTLE Peripheral.");
    }


    // The following functions are synchronized callback handlers. The callbacks
    // from Android are forwarded to these methods to synchronize member variable
    // access with other threads (the Qt thread's JNI calls in particular).
    //
    // We use a single lock object (this server) for simplicity because:
    // - Some variables may change and would thus not be suitable as locking objects but
    //   would require their own additional objects => overhead
    // - Many accesses to shared variables are infrequent and the code paths are fast and
    //   deterministic meaning that long "wait times" on a lock should not happen
    // - Typically several shared variables are accessed in a single code block.
    //   If each variable would be protected individually, the amount of (nested) locking
    //   would become quite unreasonable

    public synchronized void handleOnConnectionStateChange(BluetoothDevice device,
                                                           int status, int newState)
    {
        if (mGattServer == null) {
            Log.w(TAG, "Ignoring connection state event, server is disconnected");
            return;
        }

        int qtControllerState = 0;
        switch (newState) {
            case BluetoothProfile.STATE_DISCONNECTED:
                qtControllerState = 0; // QLowEnergyController::UnconnectedState
                clientCharacteristicManager.markDeviceConnectivity(device, false);
                mGattServer.close();
                mPendingServiceAdditions.clear();
                mGattServer = null;
                break;
            case BluetoothProfile.STATE_CONNECTED:
                clientCharacteristicManager.markDeviceConnectivity(device, true);
                qtControllerState = 2; // QLowEnergyController::ConnectedState
                break;
        }

        mRemoteName = device.getName();
        mRemoteAddress = device.getAddress();

        int qtErrorCode;
        switch (status) {
            case BluetoothGatt.GATT_SUCCESS:
                qtErrorCode = 0;
                break;
            default:
                Log.w(TAG, "Unhandled error code on peripheral connectionStateChanged: "
                           + status + " " + newState);
                qtErrorCode = status;
                break;
        }
        leServerConnectionStateChange(qtObject, qtErrorCode, qtControllerState);
    }

    public synchronized void handleOnServiceAdded(int status, BluetoothGattService service)
    {
        if (mGattServer == null) {
            Log.w(TAG, "Ignoring service addition event, server is disconnected");
            return;
        }

        Log.d(TAG, "Service " + service.getUuid().toString() + " addition result: " + status);

        // Remove the indicated service from the pending queue
        ListIterator<BluetoothGattService> iterator = mPendingServiceAdditions.listIterator();
        while (iterator.hasNext()) {
            if (iterator.next().getUuid().equals(service.getUuid())) {
                iterator.remove();
                break;
            }
        }

        // If there are more services in the queue, add the next whose add initiation succeeds
        iterator = mPendingServiceAdditions.listIterator();
        while (iterator.hasNext()) {
            BluetoothGattService nextService = iterator.next();
            if (mGattServer.addService(nextService)) {
                break;
            } else {
                Log.w(TAG, "Adding service " + nextService.getUuid().toString() + " failed");
                iterator.remove();
            }
        }
    }

    public synchronized void handleOnCharacteristicReadRequest(BluetoothDevice device,
                                                   int requestId, int offset,
                                                   BluetoothGattCharacteristic characteristic)
    {
        if (mGattServer == null) {
            Log.w(TAG, "Ignoring characteristic read, server is disconnected");
            return;
        }
        byte[] dataArray;
        try {
            dataArray = Arrays.copyOfRange(characteristic.getValue(),
                                           offset, characteristic.getValue().length);
            mGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS,
                                     offset, dataArray);
        } catch (Exception ex) {
            Log.w(TAG, "onCharacteristicReadRequest: " + requestId + " "
                        + offset + " " + characteristic.getValue().length);
            ex.printStackTrace();
            mGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_FAILURE, offset, null);
        }
    }

    public synchronized void handleOnCharacteristicWriteRequest(BluetoothDevice device,
                                                   int requestId,
                                                   BluetoothGattCharacteristic characteristic,
                                                   boolean preparedWrite, boolean responseNeeded,
                                                   int offset, byte[] value)
    {
        if (mGattServer == null) {
            Log.w(TAG, "Ignoring characteristic write, server is disconnected");
            return;
        }
        Log.w(TAG, "onCharacteristicWriteRequest");
        int resultStatus = BluetoothGatt.GATT_SUCCESS;
        boolean sendNotificationOrIndication = false;
        if (!preparedWrite) { // regular write
            if (offset == 0) {
                characteristic.setValue(value);
                leServerCharacteristicChanged(qtObject, characteristic, value);
                sendNotificationOrIndication = true;
            } else {
                // This should not really happen as per Bluetooth spec
                Log.w(TAG, "onCharacteristicWriteRequest: !preparedWrite, offset "
                            + offset + ", Not supported");
                resultStatus = BluetoothGatt.GATT_REQUEST_NOT_SUPPORTED;
            }
        } else {
            Log.w(TAG, "onCharacteristicWriteRequest: preparedWrite, offset "
                        + offset + ", Not supported");
            resultStatus = BluetoothGatt.GATT_REQUEST_NOT_SUPPORTED;

            // TODO we need to record all requests and execute them in one go once onExecuteWrite() is received
            // we use a queue to remember the pending requests
            // TODO we are ignoring the device identificator for now -> Bluetooth spec requires a queue per device
        }


        if (responseNeeded)
            mGattServer.sendResponse(device, requestId, resultStatus, offset, value);
        if (sendNotificationOrIndication)
            sendNotificationsOrIndications(characteristic);
    }

    public synchronized void handleOnDescriptorReadRequest(BluetoothDevice device, int requestId,
                                              int offset, BluetoothGattDescriptor descriptor)
    {
        if (mGattServer == null) {
            Log.w(TAG, "Ignoring descriptor read, server is disconnected");
            return;
        }

        byte[] dataArray = descriptor.getValue();
        try {
            if (descriptor.getUuid().equals(CLIENT_CHARACTERISTIC_CONFIGURATION_UUID)) {
                dataArray = clientCharacteristicManager.valueFor(
                            descriptor.getCharacteristic(), device);
                if (dataArray == null)
                    dataArray = descriptor.getValue();
            }

            dataArray = Arrays.copyOfRange(dataArray, offset, dataArray.length);
            mGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS,
                                     offset, dataArray);
        } catch (Exception ex) {
            Log.w(TAG, "onDescriptorReadRequest: " + requestId + " "
                                                   + offset + " " + dataArray.length);
            ex.printStackTrace();
            mGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_FAILURE,
                                     offset, null);
        }
    }

    public synchronized void handleOnDescriptorWriteRequest(BluetoothDevice device, int requestId,
                                     BluetoothGattDescriptor descriptor, boolean preparedWrite,
                                     boolean responseNeeded, int offset, byte[] value)
    {
        if (mGattServer == null) {
            Log.w(TAG, "Ignoring descriptor write, server is disconnected");
            return;
        }
        int resultStatus = BluetoothGatt.GATT_SUCCESS;
        if (!preparedWrite) { // regular write
            if (offset == 0) {
                descriptor.setValue(value);

                if (descriptor.getUuid().equals(CLIENT_CHARACTERISTIC_CONFIGURATION_UUID)) {
                    clientCharacteristicManager.insertOrUpdate(descriptor.getCharacteristic(),
                                                               device, value);
                }

                leServerDescriptorWritten(qtObject, descriptor, value);
            } else {
                // This should not really happen as per Bluetooth spec
                Log.w(TAG, "onDescriptorWriteRequest: !preparedWrite, offset "
                            + offset + ", Not supported");
                resultStatus = BluetoothGatt.GATT_REQUEST_NOT_SUPPORTED;
            }

        } else {
            Log.w(TAG, "onDescriptorWriteRequest: preparedWrite, offset "
                        + offset + ", Not supported");
            resultStatus = BluetoothGatt.GATT_REQUEST_NOT_SUPPORTED;
            // TODO we need to record all requests and execute them in one go once onExecuteWrite() is received
            // we use a queue to remember the pending requests
            // TODO we are ignoring the device identificator for now -> Bluetooth spec requires a queue per device
        }

        if (responseNeeded)
            mGattServer.sendResponse(device, requestId, resultStatus, offset, value);
    }

    public synchronized void handleOnExecuteWrite(BluetoothDevice device,
                                            int requestId, boolean execute)
    {
        if (mGattServer == null) {
            Log.w(TAG, "Ignoring execute write, server is disconnected");
            return;
        }
        // TODO not yet implemented -> return proper GATT error for it
        mGattServer.sendResponse(device, requestId,
                                 BluetoothGatt.GATT_REQUEST_NOT_SUPPORTED, 0, null);
    }

     /*
      * Call back handler for the Gatt Server.
      */
    private BluetoothGattServerCallback mGattServerListener = new BluetoothGattServerCallback()
    {
        @Override
        public void onConnectionStateChange(BluetoothDevice device, int status, int newState) {
            super.onConnectionStateChange(device, status, newState);
            handleOnConnectionStateChange(device, status, newState);
        }

        @Override
        public void onServiceAdded(int status, BluetoothGattService service) {
            super.onServiceAdded(status, service);
            handleOnServiceAdded(status, service);
        }

        @Override
        public void onCharacteristicReadRequest(BluetoothDevice device,
                                                int requestId, int offset,
                                                BluetoothGattCharacteristic characteristic)
        {
            super.onCharacteristicReadRequest(device, requestId, offset, characteristic);
            handleOnCharacteristicReadRequest(device, requestId, offset, characteristic);
        }

        @Override
        public void onCharacteristicWriteRequest(BluetoothDevice device, int requestId,
                                                 BluetoothGattCharacteristic characteristic,
                                                 boolean preparedWrite, boolean responseNeeded,
                                                 int offset, byte[] value)
        {
            super.onCharacteristicWriteRequest(device, requestId, characteristic,
                                               preparedWrite, responseNeeded, offset, value);
            handleOnCharacteristicWriteRequest(device, requestId, characteristic,
                                               preparedWrite, responseNeeded, offset, value);
        }

        @Override
        public void onDescriptorReadRequest(BluetoothDevice device, int requestId,
                                            int offset, BluetoothGattDescriptor descriptor)
        {
            super.onDescriptorReadRequest(device, requestId, offset, descriptor);
            handleOnDescriptorReadRequest(device, requestId, offset, descriptor);
        }

        @Override
        public void onDescriptorWriteRequest(BluetoothDevice device, int requestId,
                                             BluetoothGattDescriptor descriptor,
                                             boolean preparedWrite, boolean responseNeeded,
                                             int offset, byte[] value)
        {
            super.onDescriptorWriteRequest(device, requestId, descriptor, preparedWrite,
                                           responseNeeded, offset, value);
            handleOnDescriptorWriteRequest(device, requestId, descriptor, preparedWrite,
                                           responseNeeded, offset, value);
        }

        @Override
        public void onExecuteWrite(BluetoothDevice device, int requestId, boolean execute)
        {
            super.onExecuteWrite(device, requestId, execute);
            handleOnExecuteWrite(device, requestId, execute);
        }

        @Override
        public void onNotificationSent(BluetoothDevice device, int status) {
            super.onNotificationSent(device, status);
            Log.w(TAG, "onNotificationSent" + device + " " + status);
        }

//        MTU change disabled since it requires API level 22. Right now we only enforce lvl 21
//        @Override
//        public void onMtuChanged(BluetoothDevice device, int mtu) {
//            super.onMtuChanged(device, mtu);
//        }
    };

    // This function is called from Qt thread
    public synchronized boolean connectServer()
    {
        if (mGattServer != null)
            return true;

        BluetoothManager manager = (BluetoothManager) qtContext.getSystemService(Context.BLUETOOTH_SERVICE);
        if (manager == null) {
            Log.w(TAG, "Bluetooth service not available.");
            return false;
        }

        mGattServer = manager.openGattServer(qtContext, mGattServerListener);

        return (mGattServer != null);
    }

    // This function is called from Qt thread
    public synchronized void disconnectServer()
    {
        if (mGattServer == null)
            return;

        mPendingServiceAdditions.clear();
        mGattServer.close();
        mGattServer = null;

        mRemoteName = mRemoteAddress = "";
        leServerConnectionStateChange(qtObject, 0 /*NoError*/, 0 /*QLowEnergyController::UnconnectedState*/);
    }

    // This function is called from Qt thread
    public boolean startAdvertising(AdvertiseData advertiseData,
                                    AdvertiseData scanResponse,
                                    AdvertiseSettings settings)
    {
        if (mLeAdvertiser == null)
            return false;

        if (!connectServer()) {
            Log.w(TAG, "Server::startAdvertising: Cannot open GATT server");
            return false;
        }

        Log.w(TAG, "Starting to advertise.");
        mLeAdvertiser.startAdvertising(settings, advertiseData, scanResponse, mAdvertiseListener);

        return true;
    }

    // This function is called from Qt thread
    public void stopAdvertising()
    {
        if (mLeAdvertiser == null)
            return;

        mLeAdvertiser.stopAdvertising(mAdvertiseListener);
        Log.w(TAG, "Advertisement stopped.");
    }

    // This function is called from Qt thread
    public synchronized void addService(BluetoothGattService service)
    {
        if (!connectServer()) {
            Log.w(TAG, "Server::addService: Cannot open GATT server");
            return;
        }

        // When we add a service, we must wait for onServiceAdded callback before adding the
        // next one. If the pending service queue is empty it means that there are no ongoing
        // service additions => add the service to the server. If there are services in the
        // queue it means there is an initiated addition ongoing, and we only add to the queue.
        if (mPendingServiceAdditions.isEmpty()) {
            if (mGattServer.addService(service))
                mPendingServiceAdditions.add(service);
            else
                Log.w(TAG, "Adding service " + service.getUuid().toString() + " failed.");
        } else {
            mPendingServiceAdditions.add(service);
        }
    }

    /*
        Check the client characteristics configuration for the given characteristic
        and sends notifications or indications as per required.

        This function is called from Qt and Java threads and calls must be protected
     */
    private void sendNotificationsOrIndications(BluetoothGattCharacteristic characteristic)
    {
        final ListIterator<BluetoothDevice> iter =
                clientCharacteristicManager.getToBeUpdatedDevices(characteristic).listIterator();

        // TODO This quick loop over multiple devices should be synced with onNotificationSent().
        //      The next notifyCharacteristicChanged() call must wait until onNotificationSent()
        //      was received. At this becomes an issue when the server accepts multiple remote
        //      devices at the same time.
        while (iter.hasNext()) {
            final BluetoothDevice device = iter.next();
            final byte[] clientCharacteristicConfig = clientCharacteristicManager.valueFor(characteristic, device);
            if (clientCharacteristicConfig != null) {
                if (Arrays.equals(clientCharacteristicConfig, BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE)) {
                    mGattServer.notifyCharacteristicChanged(device, characteristic, false);
                } else if (Arrays.equals(clientCharacteristicConfig, BluetoothGattDescriptor.ENABLE_INDICATION_VALUE)) {
                    mGattServer.notifyCharacteristicChanged(device, characteristic, true);
                }
            }
        }
    }

    /*
        Updates the local database value for the given characteristic with \a charUuid and
        \a newValue. If notifications for this task are enabled an approproiate notification will
        be send to the remote client.

        This function is called from the Qt thread.
     */
    public boolean writeCharacteristic(BluetoothGattService service, UUID charUuid, byte[] newValue)
    {
        BluetoothGattCharacteristic foundChar = null;
        List<BluetoothGattCharacteristic> charList = service.getCharacteristics();
        for (BluetoothGattCharacteristic iter: charList) {
            if (iter.getUuid().equals(charUuid) && foundChar == null) {
                foundChar = iter;
                // don't break here since we want to check next condition below on next iteration
            } else if (iter.getUuid().equals(charUuid)) {
                Log.w(TAG, "Found second char with same UUID. Wrong char may have been selected.");
                break;
            }
        }

        if (foundChar == null) {
            Log.w(TAG, "writeCharacteristic: update for unknown characteristic failed");
            return false;
        }

        synchronized (this) // a value update might be in progress
        {
            foundChar.setValue(newValue);
            // Value is updated even if server is not connected, but notifying is not possible
            if (mGattServer != null)
                sendNotificationsOrIndications(foundChar);
        }
        return true;
    }

    /*
        Updates the local database value for the given \a descUuid to \a newValue.

        This function is called from the Qt thread.
     */
    public boolean writeDescriptor(BluetoothGattService service, UUID charUuid, UUID descUuid,
                                   byte[] newValue)
    {
        BluetoothGattDescriptor foundDesc = null;
        BluetoothGattCharacteristic foundChar = null;
        final List<BluetoothGattCharacteristic> charList = service.getCharacteristics();
        for (BluetoothGattCharacteristic iter: charList) {
            if (!iter.getUuid().equals(charUuid))
                continue;

            if (foundChar == null) {
                foundChar = iter;
            } else {
                Log.w(TAG, "Found second char with same UUID. Wrong char may have been selected.");
                break;
            }
        }

        if (foundChar != null)
            foundDesc = foundChar.getDescriptor(descUuid);

        if (foundChar == null || foundDesc == null) {
            Log.w(TAG, "writeDescriptor: update for unknown char or desc failed (" + foundChar + ")");
            return false;
        }

        // we even write CLIENT_CHARACTERISTIC_CONFIGURATION_UUID this way as we choose
        // to interpret the server's call as a change of the default value.
        synchronized (this) // a value update might be in progress
        {
            foundDesc.setValue(newValue);
        }
        return true;
    }

    /*
     * Call back handler for Advertisement requests.
     */
    private AdvertiseCallback mAdvertiseListener = new AdvertiseCallback()
    {
        @Override
        public void onStartSuccess(AdvertiseSettings settingsInEffect) {
            super.onStartSuccess(settingsInEffect);
        }

        @Override
        public void onStartFailure(int errorCode) {
            Log.e(TAG, "Advertising failure: " + errorCode);
            super.onStartFailure(errorCode);

            // changing errorCode here implies changes to errorCode handling on Qt side
            int qtErrorCode = 0;
            switch (errorCode) {
                case AdvertiseCallback.ADVERTISE_FAILED_ALREADY_STARTED:
                    return; // ignore -> noop
                case AdvertiseCallback.ADVERTISE_FAILED_DATA_TOO_LARGE:
                    qtErrorCode = 1;
                    break;
                case AdvertiseCallback.ADVERTISE_FAILED_FEATURE_UNSUPPORTED:
                    qtErrorCode = 2;
                    break;
                default: // default maps to internal error
                case AdvertiseCallback.ADVERTISE_FAILED_INTERNAL_ERROR:
                    qtErrorCode = 3;
                    break;
                case AdvertiseCallback.ADVERTISE_FAILED_TOO_MANY_ADVERTISERS:
                    qtErrorCode = 4;
                    break;
            }

            if (qtErrorCode > 0)
                leServerAdvertisementError(qtObject, qtErrorCode);
        }
    };

    public native void leServerConnectionStateChange(long qtObject, int errorCode, int newState);
    public native void leServerAdvertisementError(long qtObject, int status);
    public native void leServerCharacteristicChanged(long qtObject,
                                                     BluetoothGattCharacteristic characteristic,
                                                     byte[] newValue);
    public native void leServerDescriptorWritten(long qtObject,
                                                 BluetoothGattDescriptor descriptor,
                                                 byte[] newValue);
}