summaryrefslogtreecommitdiffstats
path: root/core/java/android/bluetooth/BluetoothLeAdvertiser.java
blob: 30c90c4deabb124ee008c13db96f9c6275d5f29f (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
/*
 * Copyright (C) 2014 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package android.bluetooth;

import android.bluetooth.BluetoothLeAdvertiseScanData.AdvertisementData;
import android.os.Handler;
import android.os.Looper;
import android.os.Parcel;
import android.os.ParcelUuid;
import android.os.Parcelable;
import android.os.RemoteException;
import android.util.Log;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * This class provides a way to perform Bluetooth LE advertise operations, such as start and stop
 * advertising. An advertiser can broadcast up to 31 bytes of advertisement data represented by
 * {@link BluetoothLeAdvertiseScanData.AdvertisementData}.
 * <p>
 * To get an instance of {@link BluetoothLeAdvertiser}, call the
 * {@link BluetoothAdapter#getBluetoothLeAdvertiser()} method.
 * <p>
 * Note most of the methods here require {@link android.Manifest.permission#BLUETOOTH_ADMIN}
 * permission.
 *
 * @see BluetoothLeAdvertiseScanData.AdvertisementData
 */
public class BluetoothLeAdvertiser {

    private static final String TAG = "BluetoothLeAdvertiser";

    /**
     * The {@link Settings} provide a way to adjust advertising preferences for each individual
     * advertisement. Use {@link Settings.Builder} to create a {@link Settings} instance.
     */
    public static final class Settings implements Parcelable {
        /**
         * Perform Bluetooth LE advertising in low power mode. This is the default and preferred
         * advertising mode as it consumes the least power.
         */
        public static final int ADVERTISE_MODE_LOW_POWER = 0;
        /**
         * Perform Bluetooth LE advertising in balanced power mode. This is balanced between
         * advertising frequency and power consumption.
         */
        public static final int ADVERTISE_MODE_BALANCED = 1;
        /**
         * Perform Bluetooth LE advertising in low latency, high power mode. This has the highest
         * power consumption and should not be used for background continuous advertising.
         */
        public static final int ADVERTISE_MODE_LOW_LATENCY = 2;

        /**
         * Advertise using the lowest transmission(tx) power level. An app can use low transmission
         * power to restrict the visibility range of its advertising packet.
         */
        public static final int ADVERTISE_TX_POWER_ULTRA_LOW = 0;
        /**
         * Advertise using low tx power level.
         */
        public static final int ADVERTISE_TX_POWER_LOW = 1;
        /**
         * Advertise using medium tx power level.
         */
        public static final int ADVERTISE_TX_POWER_MEDIUM = 2;
        /**
         * Advertise using high tx power level. This is corresponding to largest visibility range of
         * the advertising packet.
         */
        public static final int ADVERTISE_TX_POWER_HIGH = 3;

        /**
         * Non-connectable undirected advertising event, as defined in Bluetooth Specification V4.0
         * vol6, part B, section 4.4.2 - Advertising state.
         */
        public static final int ADVERTISE_TYPE_NON_CONNECTABLE = 0;
        /**
         * Scannable undirected advertise type, as defined in same spec mentioned above. This event
         * type allows a scanner to send a scan request asking additional information about the
         * advertiser.
         */
        public static final int ADVERTISE_TYPE_SCANNABLE = 1;
        /**
         * Connectable undirected advertising type, as defined in same spec mentioned above. This
         * event type allows a scanner to send scan request asking additional information about the
         * advertiser. It also allows an initiator to send a connect request for connection.
         */
        public static final int ADVERTISE_TYPE_CONNECTABLE = 2;

        private final int mAdvertiseMode;
        private final int mAdvertiseTxPowerLevel;
        private final int mAdvertiseEventType;

        private Settings(int advertiseMode, int advertiseTxPowerLevel,
                int advertiseEventType) {
            mAdvertiseMode = advertiseMode;
            mAdvertiseTxPowerLevel = advertiseTxPowerLevel;
            mAdvertiseEventType = advertiseEventType;
        }

        private Settings(Parcel in) {
            mAdvertiseMode = in.readInt();
            mAdvertiseTxPowerLevel = in.readInt();
            mAdvertiseEventType = in.readInt();
        }

        /**
         * Creates a {@link Builder} to construct a {@link Settings} object.
         */
        public static Builder newBuilder() {
            return new Builder();
        }

        /**
         * Returns the advertise mode.
         */
        public int getMode() {
            return mAdvertiseMode;
        }

        /**
         * Returns the tx power level for advertising.
         */
        public int getTxPowerLevel() {
            return mAdvertiseTxPowerLevel;
        }

        /**
         * Returns the advertise event type.
         */
        public int getType() {
            return mAdvertiseEventType;
        }

        @Override
        public String toString() {
            return "Settings [mAdvertiseMode=" + mAdvertiseMode + ", mAdvertiseTxPowerLevel="
                    + mAdvertiseTxPowerLevel + ", mAdvertiseEventType=" + mAdvertiseEventType + "]";
        }

        @Override
        public int describeContents() {
            return 0;
        }

        @Override
        public void writeToParcel(Parcel dest, int flags) {
            dest.writeInt(mAdvertiseMode);
            dest.writeInt(mAdvertiseTxPowerLevel);
            dest.writeInt(mAdvertiseEventType);
        }

        public static final Parcelable.Creator<Settings> CREATOR =
                new Creator<BluetoothLeAdvertiser.Settings>() {
                @Override
                    public Settings[] newArray(int size) {
                        return new Settings[size];
                    }

                @Override
                    public Settings createFromParcel(Parcel in) {
                        return new Settings(in);
                    }
                };

        /**
         * Builder class for {@link BluetoothLeAdvertiser.Settings}. Caller should use
         * {@link Settings#newBuilder()} to get an instance of the builder.
         */
        public static final class Builder {
            private int mMode = ADVERTISE_MODE_LOW_POWER;
            private int mTxPowerLevel = ADVERTISE_TX_POWER_MEDIUM;
            private int mType = ADVERTISE_TYPE_NON_CONNECTABLE;

            // Private constructor, use Settings.newBuilder() get an instance of BUILDER.
            private Builder() {
            }

            /**
             * Set advertise mode to control the advertising power and latency.
             *
             * @param advertiseMode Bluetooth LE Advertising mode, can only be one of
             *            {@link Settings#ADVERTISE_MODE_LOW_POWER},
             *            {@link Settings#ADVERTISE_MODE_BALANCED}, or
             *            {@link Settings#ADVERTISE_MODE_LOW_LATENCY}.
             * @throws IllegalArgumentException If the advertiseMode is invalid.
             */
            public Builder advertiseMode(int advertiseMode) {
                if (advertiseMode < ADVERTISE_MODE_LOW_POWER
                        || advertiseMode > ADVERTISE_MODE_LOW_LATENCY) {
                    throw new IllegalArgumentException("unknown mode " + advertiseMode);
                }
                mMode = advertiseMode;
                return this;
            }

            /**
             * Set advertise tx power level to control the transmission power level for the
             * advertising.
             *
             * @param txPowerLevel Transmission power of Bluetooth LE Advertising, can only be one
             *            of {@link Settings#ADVERTISE_TX_POWER_ULTRA_LOW},
             *            {@link Settings#ADVERTISE_TX_POWER_LOW},
             *            {@link Settings#ADVERTISE_TX_POWER_MEDIUM} or
             *            {@link Settings#ADVERTISE_TX_POWER_HIGH}.
             * @throws IllegalArgumentException If the {@code txPowerLevel} is invalid.
             */
            public Builder txPowerLevel(int txPowerLevel) {
                if (txPowerLevel < ADVERTISE_TX_POWER_ULTRA_LOW
                        || txPowerLevel > ADVERTISE_TX_POWER_HIGH) {
                    throw new IllegalArgumentException("unknown tx power level " + txPowerLevel);
                }
                mTxPowerLevel = txPowerLevel;
                return this;
            }

            /**
             * Set advertise type to control the event type of advertising.
             *
             * @param type Bluetooth LE Advertising type, can be either
             *            {@link Settings#ADVERTISE_TYPE_NON_CONNECTABLE},
             *            {@link Settings#ADVERTISE_TYPE_SCANNABLE} or
             *            {@link Settings#ADVERTISE_TYPE_CONNECTABLE}.
             * @throws IllegalArgumentException If the {@code type} is invalid.
             */
            public Builder type(int type) {
                if (type < ADVERTISE_TYPE_NON_CONNECTABLE
                        || type > ADVERTISE_TYPE_CONNECTABLE) {
                    throw new IllegalArgumentException("unknown advertise type " + type);
                }
                mType = type;
                return this;
            }

            /**
             * Build the {@link Settings} object.
             */
            public Settings build() {
                return new Settings(mMode, mTxPowerLevel, mType);
            }
        }
    }

    /**
     * Callback of Bluetooth LE advertising, which is used to deliver operation status for start and
     * stop advertising.
     */
    public interface AdvertiseCallback {

        /**
         * The operation is success.
         *
         * @hide
         */
        public static final int SUCCESS = 0;
        /**
         * Fails to start advertising as the advertisement data contains services that are not added
         * to the local bluetooth Gatt server.
         */
        public static final int ADVERTISING_SERVICE_UNKNOWN = 1;
        /**
         * Fails to start advertising as system runs out of quota for advertisers.
         */
        public static final int TOO_MANY_ADVERTISERS = 2;

        /**
         * Fails to start advertising as the advertising is already started.
         */
        public static final int ADVERTISING_ALREADY_STARTED = 3;
        /**
         * Fails to stop advertising as the advertising is not started.
         */
        public static final int ADVERISING_NOT_STARTED = 4;

        /**
         * Operation fails due to bluetooth controller failure.
         */
        public static final int CONTROLLER_FAILURE = 5;

        /**
         * Callback when advertising operation succeeds.
         *
         * @param settingsInEffect The actual settings used for advertising, which may be different
         *            from what the app asks.
         */
        public void onSuccess(Settings settingsInEffect);

        /**
         * Callback when advertising operation fails.
         *
         * @param errorCode Error code for failures.
         */
        public void onFailure(int errorCode);
    }

    private final IBluetoothGatt mBluetoothGatt;
    private final Handler mHandler;
    private final Map<Settings, AdvertiseCallbackWrapper>
            mLeAdvertisers = new HashMap<Settings, AdvertiseCallbackWrapper>();

    // Package private constructor, use BluetoothAdapter.getLeAdvertiser() instead.
    BluetoothLeAdvertiser(IBluetoothGatt bluetoothGatt) {
        mBluetoothGatt = bluetoothGatt;
        mHandler = new Handler(Looper.getMainLooper());
    }

    /**
     * Bluetooth GATT interface callbacks for advertising.
     */
    private static class AdvertiseCallbackWrapper extends IBluetoothGattCallback.Stub {
        private static final int LE_CALLBACK_TIMEOUT_MILLIS = 2000;
        private final AdvertiseCallback mAdvertiseCallback;
        private final AdvertisementData mAdvertisement;
        private final AdvertisementData mScanResponse;
        private final Settings mSettings;
        private final IBluetoothGatt mBluetoothGatt;

        // mLeHandle 0: not registered
        // -1: scan stopped
        // >0: registered and scan started
        private int mLeHandle;
        private boolean isAdvertising = false;

        public AdvertiseCallbackWrapper(AdvertiseCallback advertiseCallback,
                AdvertisementData advertiseData, AdvertisementData scanResponse, Settings settings,
                IBluetoothGatt bluetoothGatt) {
            mAdvertiseCallback = advertiseCallback;
            mAdvertisement = advertiseData;
            mScanResponse = scanResponse;
            mSettings = settings;
            mBluetoothGatt = bluetoothGatt;
            mLeHandle = 0;
        }

        public boolean advertiseStarted() {
            boolean started = false;
            synchronized (this) {
                if (mLeHandle == -1) {
                    return false;
                }
                try {
                    wait(LE_CALLBACK_TIMEOUT_MILLIS);
                } catch (InterruptedException e) {
                    Log.e(TAG, "Callback reg wait interrupted: " + e);
                }
                started = (mLeHandle > 0 && isAdvertising);
            }
            return started;
        }

        public boolean advertiseStopped() {
            synchronized (this) {
                try {
                    wait(LE_CALLBACK_TIMEOUT_MILLIS);
                } catch (InterruptedException e) {
                    Log.e(TAG, "Callback reg wait interrupted: " + e);
                }
                return !isAdvertising;
            }
        }

        /**
         * Application interface registered - app is ready to go
         */
        @Override
        public void onClientRegistered(int status, int clientIf) {
            Log.d(TAG, "onClientRegistered() - status=" + status + " clientIf=" + clientIf);
            synchronized (this) {
                if (status == BluetoothGatt.GATT_SUCCESS) {
                    mLeHandle = clientIf;
                    try {
                        mBluetoothGatt.startMultiAdvertising(mLeHandle, mAdvertisement,
                                mScanResponse, mSettings);
                    } catch (RemoteException e) {
                        Log.e(TAG, "fail to start le advertise: " + e);
                        mLeHandle = -1;
                        notifyAll();
                    } catch (Exception e) {
                        Log.e(TAG, "fail to start advertise: " + e.getStackTrace());
                    }
                } else {
                    // registration failed
                    mLeHandle = -1;
                    notifyAll();
                }
            }
        }

        @Override
        public void onClientConnectionState(int status, int clientIf,
                boolean connected, String address) {
            // no op
        }

        @Override
        public void onScanResult(String address, int rssi, byte[] advData) {
            // no op
        }

        @Override
        public void onGetService(String address, int srvcType,
                int srvcInstId, ParcelUuid srvcUuid) {
            // no op
        }

        @Override
        public void onGetIncludedService(String address, int srvcType,
                int srvcInstId, ParcelUuid srvcUuid,
                int inclSrvcType, int inclSrvcInstId,
                ParcelUuid inclSrvcUuid) {
            // no op
        }

        @Override
        public void onGetCharacteristic(String address, int srvcType,
                int srvcInstId, ParcelUuid srvcUuid,
                int charInstId, ParcelUuid charUuid,
                int charProps) {
            // no op
        }

        @Override
        public void onGetDescriptor(String address, int srvcType,
                int srvcInstId, ParcelUuid srvcUuid,
                int charInstId, ParcelUuid charUuid,
                int descInstId, ParcelUuid descUuid) {
            // no op
        }

        @Override
        public void onSearchComplete(String address, int status) {
            // no op
        }

        @Override
        public void onCharacteristicRead(String address, int status, int srvcType,
                int srvcInstId, ParcelUuid srvcUuid,
                int charInstId, ParcelUuid charUuid, byte[] value) {
            // no op
        }

        @Override
        public void onCharacteristicWrite(String address, int status, int srvcType,
                int srvcInstId, ParcelUuid srvcUuid,
                int charInstId, ParcelUuid charUuid) {
            // no op
        }

        @Override
        public void onNotify(String address, int srvcType,
                int srvcInstId, ParcelUuid srvcUuid,
                int charInstId, ParcelUuid charUuid,
                byte[] value) {
            // no op
        }

        @Override
        public void onDescriptorRead(String address, int status, int srvcType,
                int srvcInstId, ParcelUuid srvcUuid,
                int charInstId, ParcelUuid charUuid,
                int descInstId, ParcelUuid descrUuid, byte[] value) {
            // no op
        }

        @Override
        public void onDescriptorWrite(String address, int status, int srvcType,
                int srvcInstId, ParcelUuid srvcUuid,
                int charInstId, ParcelUuid charUuid,
                int descInstId, ParcelUuid descrUuid) {
            // no op
        }

        @Override
        public void onExecuteWrite(String address, int status) {
            // no op
        }

        @Override
        public void onReadRemoteRssi(String address, int rssi, int status) {
            // no op
        }

        @Override
        public void onAdvertiseStateChange(int advertiseState, int status) {
            // no op
        }

        @Override
        public void onMultiAdvertiseCallback(int status) {
            synchronized (this) {
                if (status == 0) {
                    isAdvertising = !isAdvertising;
                    if (!isAdvertising) {
                        try {
                            mBluetoothGatt.unregisterClient(mLeHandle);
                            mLeHandle = -1;
                        } catch (RemoteException e) {
                            Log.e(TAG, "remote exception when unregistering", e);
                        }
                    }
                    mAdvertiseCallback.onSuccess(null);
                } else {
                    mAdvertiseCallback.onFailure(status);
                }
                notifyAll();
            }

        }

        /**
         * Callback reporting LE ATT MTU.
         *
         * @hide
         */
        public void onConfigureMTU(String address, int mtu, int status) {
            // no op
        }
    }

    /**
     * Start Bluetooth LE Advertising.
     *
     * @param settings {@link Settings} for Bluetooth LE advertising.
     * @param advertiseData {@link AdvertisementData} to be advertised.
     * @param callback {@link AdvertiseCallback} for advertising status.
     */
    public void startAdvertising(Settings settings,
            AdvertisementData advertiseData, final AdvertiseCallback callback) {
        startAdvertising(settings, advertiseData, null, callback);
    }

    /**
     * Start Bluetooth LE Advertising.
     * @param settings {@link Settings} for Bluetooth LE advertising.
     * @param advertiseData {@link AdvertisementData} to be advertised in advertisement packet.
     * @param scanResponse {@link AdvertisementData} for scan response.
     * @param callback {@link AdvertiseCallback} for advertising status.
     */
    public void startAdvertising(Settings settings,
            AdvertisementData advertiseData, AdvertisementData scanResponse,
            final AdvertiseCallback callback) {
        if (callback == null) {
            throw new IllegalArgumentException("callback cannot be null");
        }
        if (mLeAdvertisers.containsKey(settings)) {
            postCallbackFailure(callback, AdvertiseCallback.ADVERTISING_ALREADY_STARTED);
            return;
        }
        AdvertiseCallbackWrapper wrapper = new AdvertiseCallbackWrapper(callback, advertiseData,
                scanResponse, settings, mBluetoothGatt);
        UUID uuid = UUID.randomUUID();
        try {
            mBluetoothGatt.registerClient(new ParcelUuid(uuid), wrapper);
            if (wrapper.advertiseStarted()) {
                mLeAdvertisers.put(settings, wrapper);
            }
        } catch (RemoteException e) {
            Log.e(TAG, "failed to stop advertising", e);
        }
    }

    /**
     * Stop Bluetooth LE advertising. Returns immediately, the operation status will be delivered
     * through the {@code callback}.
     * <p>
     * Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN}
     *
     * @param settings {@link Settings} used to start Bluetooth LE advertising.
     * @param callback {@link AdvertiseCallback} for delivering stopping advertising status.
     */
    public void stopAdvertising(final Settings settings, final AdvertiseCallback callback) {
        if (callback == null) {
            throw new IllegalArgumentException("callback cannot be null");
        }
        AdvertiseCallbackWrapper wrapper = mLeAdvertisers.get(settings);
        if (wrapper == null) {
            postCallbackFailure(callback, AdvertiseCallback.ADVERISING_NOT_STARTED);
            return;
        }
        try {
            mBluetoothGatt.stopMultiAdvertising(wrapper.mLeHandle);
            if (wrapper.advertiseStopped()) {
                mLeAdvertisers.remove(settings);
            }
        } catch (RemoteException e) {
            Log.e(TAG, "failed to stop advertising", e);
        }
    }

    private void postCallbackFailure(final AdvertiseCallback callback, final int error) {
        mHandler.post(new Runnable() {
                @Override
            public void run() {
                callback.onFailure(error);
            }
        });
    }
}