summaryrefslogtreecommitdiffstats
path: root/device/bluetooth/android/java/src/org/chromium/device/bluetooth/Wrappers.java
blob: b61c7cdcf781b60fbe06a081d294db8f28c77047 (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
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.device.bluetooth;

import android.Manifest;
import android.annotation.TargetApi;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanFilter;
import android.bluetooth.le.ScanResult;
import android.bluetooth.le.ScanSettings;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.ParcelUuid;
import android.os.Process;

import org.chromium.base.Log;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.JNINamespace;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

/**
 * Wrapper classes around android.bluetooth.* classes that provide an
 * indirection layer enabling fake implementations when running tests.
 *
 * Each Wrapper base class accepts an Android API object and passes through
 * calls to it. When under test, Fake subclasses override all methods that
 * pass through to the Android object and instead provide fake implementations.
 */
@JNINamespace("device")
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
class Wrappers {
    private static final String TAG = "Bluetooth";

    public static final int DEVICE_CLASS_UNSPECIFIED = 0x1F00;

    /**
     * Wraps android.bluetooth.BluetoothAdapter.
     */
    static class BluetoothAdapterWrapper {
        private final BluetoothAdapter mAdapter;
        protected final ContextWrapper mContext;
        protected BluetoothLeScannerWrapper mScannerWrapper;

        /**
         * Creates a BluetoothAdapterWrapper using the default
         * android.bluetooth.BluetoothAdapter. May fail if the default adapter
         * is not available or if the application does not have sufficient
         * permissions.
         */
        @CalledByNative("BluetoothAdapterWrapper")
        public static BluetoothAdapterWrapper createWithDefaultAdapter(Context context) {
            final boolean hasMinAPI = Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP;
            if (!hasMinAPI) {
                Log.i(TAG, "BluetoothAdapterWrapper.create failed: SDK version (%d) too low.",
                        Build.VERSION.SDK_INT);
                return null;
            }

            final boolean hasPermissions =
                    context.checkCallingOrSelfPermission(Manifest.permission.BLUETOOTH)
                            == PackageManager.PERMISSION_GRANTED
                    && context.checkCallingOrSelfPermission(Manifest.permission.BLUETOOTH_ADMIN)
                            == PackageManager.PERMISSION_GRANTED;
            if (!hasPermissions) {
                Log.w(TAG, "BluetoothAdapterWrapper.create failed: Lacking Bluetooth permissions.");
                return null;
            }

            // Only Low Energy currently supported, see BluetoothAdapterAndroid class note.
            final boolean hasLowEnergyFeature =
                    Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2
                    && context.getPackageManager().hasSystemFeature(
                               PackageManager.FEATURE_BLUETOOTH_LE);
            if (!hasLowEnergyFeature) {
                Log.i(TAG, "BluetoothAdapterWrapper.create failed: No Low Energy support.");
                return null;
            }

            BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
            if (adapter == null) {
                Log.i(TAG, "BluetoothAdapterWrapper.create failed: Default adapter not found.");
                return null;
            } else {
                return new BluetoothAdapterWrapper(adapter, new ContextWrapper(context));
            }
        }

        public BluetoothAdapterWrapper(BluetoothAdapter adapter, ContextWrapper context) {
            mAdapter = adapter;
            mContext = context;
        }

        public boolean disable() {
            return mAdapter.disable();
        }

        public boolean enable() {
            return mAdapter.enable();
        }

        public String getAddress() {
            return mAdapter.getAddress();
        }

        public BluetoothLeScannerWrapper getBluetoothLeScanner() {
            BluetoothLeScanner scanner = mAdapter.getBluetoothLeScanner();
            if (scanner == null) {
                return null;
            }
            if (mScannerWrapper == null) {
                mScannerWrapper = new BluetoothLeScannerWrapper(scanner);
            }
            return mScannerWrapper;
        }

        public ContextWrapper getContext() {
            return mContext;
        }

        public String getName() {
            return mAdapter.getName();
        }

        public int getScanMode() {
            return mAdapter.getScanMode();
        }

        public boolean isDiscovering() {
            return mAdapter.isDiscovering();
        }

        public boolean isEnabled() {
            return mAdapter.isEnabled();
        }
    }

    /**
     * Wraps android.content.Context.
     */
    static class ContextWrapper {
        private final Context mContext;

        public ContextWrapper(Context context) {
            mContext = context;
        }

        public boolean checkPermission(String permission) {
            return mContext.checkPermission(permission, Process.myPid(), Process.myUid())
                    == PackageManager.PERMISSION_GRANTED;
        }

        public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter) {
            return mContext.registerReceiver(receiver, filter);
        }

        public void unregisterReceiver(BroadcastReceiver receiver) {
            mContext.unregisterReceiver(receiver);
        }
    }

    /**
     * Wraps android.bluetooth.BluetoothLeScanner.
     */
    static class BluetoothLeScannerWrapper {
        protected final BluetoothLeScanner mScanner;
        private final HashMap<ScanCallbackWrapper, ForwardScanCallbackToWrapper> mCallbacks;

        public BluetoothLeScannerWrapper(BluetoothLeScanner scanner) {
            mScanner = scanner;
            mCallbacks = new HashMap<ScanCallbackWrapper, ForwardScanCallbackToWrapper>();
        }

        public void startScan(
                List<ScanFilter> filters, int scanSettingsScanMode, ScanCallbackWrapper callback) {
            ScanSettings settings =
                    new ScanSettings.Builder().setScanMode(scanSettingsScanMode).build();

            ForwardScanCallbackToWrapper callbackForwarder =
                    new ForwardScanCallbackToWrapper(callback);
            mCallbacks.put(callback, callbackForwarder);

            mScanner.startScan(filters, settings, callbackForwarder);
        }

        public void stopScan(ScanCallbackWrapper callback) {
            ForwardScanCallbackToWrapper callbackForwarder = mCallbacks.remove(callback);
            mScanner.stopScan(callbackForwarder);
        }
    }

    /**
     * Implements android.bluetooth.le.ScanCallback and forwards calls through to a
     * provided ScanCallbackWrapper instance.
     *
     * This class is required so that Fakes can use ScanCallbackWrapper without
     * it extending from ScanCallback. Fakes must function even on Android
     * versions where ScanCallback class is not defined.
     */
    static class ForwardScanCallbackToWrapper extends ScanCallback {
        final ScanCallbackWrapper mWrapperCallback;

        ForwardScanCallbackToWrapper(ScanCallbackWrapper wrapperCallback) {
            mWrapperCallback = wrapperCallback;
        }

        @Override
        public void onBatchScanResults(List<ScanResult> results) {
            ArrayList<ScanResultWrapper> resultsWrapped =
                    new ArrayList<ScanResultWrapper>(results.size());
            for (ScanResult result : results) {
                resultsWrapped.add(new ScanResultWrapper(result));
            }
            mWrapperCallback.onBatchScanResult(resultsWrapped);
        }

        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            mWrapperCallback.onScanResult(callbackType, new ScanResultWrapper(result));
        }

        @Override
        public void onScanFailed(int errorCode) {
            mWrapperCallback.onScanFailed(errorCode);
        }
    }

    /**
     * Wraps android.bluetooth.le.ScanCallback, being called by ScanCallbackImpl.
     */
    abstract static class ScanCallbackWrapper {
        public abstract void onBatchScanResult(List<ScanResultWrapper> results);
        public abstract void onScanResult(int callbackType, ScanResultWrapper result);
        public abstract void onScanFailed(int errorCode);
    }

    /**
     * Wraps android.bluetooth.le.ScanResult.
     */
    static class ScanResultWrapper {
        private final ScanResult mScanResult;

        public ScanResultWrapper(ScanResult scanResult) {
            mScanResult = scanResult;
        }

        public BluetoothDeviceWrapper getDevice() {
            return new BluetoothDeviceWrapper(mScanResult.getDevice());
        }

        public List<ParcelUuid> getScanRecord_getServiceUuids() {
            return mScanResult.getScanRecord().getServiceUuids();
        }
    }

    /**
     * Wraps android.bluetooth.BluetoothDevice.
     */
    static class BluetoothDeviceWrapper {
        private final BluetoothDevice mDevice;
        private final HashMap<BluetoothGattCharacteristic, BluetoothGattCharacteristicWrapper>
                mCharacteristicsToWrappers;
        private final HashMap<BluetoothGattDescriptor, BluetoothGattDescriptorWrapper>
                mDescriptorsToWrappers;

        public BluetoothDeviceWrapper(BluetoothDevice device) {
            mDevice = device;
            mCharacteristicsToWrappers =
                    new HashMap<BluetoothGattCharacteristic, BluetoothGattCharacteristicWrapper>();
            mDescriptorsToWrappers =
                    new HashMap<BluetoothGattDescriptor, BluetoothGattDescriptorWrapper>();
        }

        public BluetoothGattWrapper connectGatt(
                Context context, boolean autoConnect, BluetoothGattCallbackWrapper callback) {
            return new BluetoothGattWrapper(
                    mDevice.connectGatt(context, autoConnect,
                            new ForwardBluetoothGattCallbackToWrapper(callback, this)),
                    this);
        }

        public String getAddress() {
            return mDevice.getAddress();
        }

        public int getBluetoothClass_getDeviceClass() {
            if (mDevice == null || mDevice.getBluetoothClass() == null) {
                // BluetoothDevice.getBluetoothClass() returns null if adapter has been powered off.
                // Return DEVICE_CLASS_UNSPECIFIED in these cases.
                return DEVICE_CLASS_UNSPECIFIED;
            }
            return mDevice.getBluetoothClass().getDeviceClass();
        }

        public int getBondState() {
            return mDevice.getBondState();
        }

        public String getName() {
            return mDevice.getName();
        }
    }

    /**
     * Wraps android.bluetooth.BluetoothGatt.
     */
    static class BluetoothGattWrapper {
        private final BluetoothGatt mGatt;
        private final BluetoothDeviceWrapper mDeviceWrapper;

        BluetoothGattWrapper(BluetoothGatt gatt, BluetoothDeviceWrapper deviceWrapper) {
            mGatt = gatt;
            mDeviceWrapper = deviceWrapper;
        }

        public void disconnect() {
            mGatt.disconnect();
        }

        public void close() {
            mGatt.close();
        }

        public void discoverServices() {
            mGatt.discoverServices();
        }

        public List<BluetoothGattServiceWrapper> getServices() {
            List<BluetoothGattService> services = mGatt.getServices();
            ArrayList<BluetoothGattServiceWrapper> servicesWrapped =
                    new ArrayList<BluetoothGattServiceWrapper>(services.size());
            for (BluetoothGattService service : services) {
                servicesWrapped.add(new BluetoothGattServiceWrapper(service, mDeviceWrapper));
            }
            return servicesWrapped;
        }

        boolean readCharacteristic(BluetoothGattCharacteristicWrapper characteristic) {
            return mGatt.readCharacteristic(characteristic.mCharacteristic);
        }

        boolean setCharacteristicNotification(
                BluetoothGattCharacteristicWrapper characteristic, boolean enable) {
            return mGatt.setCharacteristicNotification(characteristic.mCharacteristic, enable);
        }

        boolean writeCharacteristic(BluetoothGattCharacteristicWrapper characteristic) {
            return mGatt.writeCharacteristic(characteristic.mCharacteristic);
        }

        boolean readDescriptor(BluetoothGattDescriptorWrapper descriptor) {
            return mGatt.readDescriptor(descriptor.mDescriptor);
        }

        boolean writeDescriptor(BluetoothGattDescriptorWrapper descriptor) {
            return mGatt.writeDescriptor(descriptor.mDescriptor);
        }
    }

    /**
     * Implements android.bluetooth.BluetoothGattCallback and forwards calls through
     * to a provided BluetoothGattCallbackWrapper instance.
     *
     * This class is required so that Fakes can use BluetoothGattCallbackWrapper
     * without it extending from BluetoothGattCallback. Fakes must function even on
     * Android versions where BluetoothGattCallback class is not defined.
     */
    static class ForwardBluetoothGattCallbackToWrapper extends BluetoothGattCallback {
        final BluetoothGattCallbackWrapper mWrapperCallback;
        final BluetoothDeviceWrapper mDeviceWrapper;

        ForwardBluetoothGattCallbackToWrapper(BluetoothGattCallbackWrapper wrapperCallback,
                BluetoothDeviceWrapper deviceWrapper) {
            mWrapperCallback = wrapperCallback;
            mDeviceWrapper = deviceWrapper;
        }

        @Override
        public void onCharacteristicChanged(
                BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
            Log.i(TAG, "wrapper onCharacteristicChanged.");
            mWrapperCallback.onCharacteristicChanged(
                    mDeviceWrapper.mCharacteristicsToWrappers.get(characteristic));
        }

        @Override
        public void onCharacteristicRead(
                BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            mWrapperCallback.onCharacteristicRead(
                    mDeviceWrapper.mCharacteristicsToWrappers.get(characteristic), status);
        }

        @Override
        public void onCharacteristicWrite(
                BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            mWrapperCallback.onCharacteristicWrite(
                    mDeviceWrapper.mCharacteristicsToWrappers.get(characteristic), status);
        }

        @Override
        public void onDescriptorRead(
                BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
            mWrapperCallback.onDescriptorRead(
                    mDeviceWrapper.mDescriptorsToWrappers.get(descriptor), status);
        }

        @Override
        public void onDescriptorWrite(
                BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
            mWrapperCallback.onDescriptorWrite(
                    mDeviceWrapper.mDescriptorsToWrappers.get(descriptor), status);
        }

        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            mWrapperCallback.onConnectionStateChange(status, newState);
        }

        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            mWrapperCallback.onServicesDiscovered(status);
        }
    }

    /**
     * Wrapper alternative to android.bluetooth.BluetoothGattCallback allowing clients and Fakes to
     * work on older SDK versions without having a dependency on the class not defined there.
     *
     * BluetoothGatt gatt parameters are omitted from methods as each call would
     * need to look up the correct BluetoothGattWrapper instance.
     * Client code should cache the BluetoothGattWrapper provided if
     * necessary from the initial BluetoothDeviceWrapper.connectGatt
     * call.
     */
    abstract static class BluetoothGattCallbackWrapper {
        public abstract void onCharacteristicChanged(
                BluetoothGattCharacteristicWrapper characteristic);
        public abstract void onCharacteristicRead(
                BluetoothGattCharacteristicWrapper characteristic, int status);
        public abstract void onCharacteristicWrite(
                BluetoothGattCharacteristicWrapper characteristic, int status);
        public abstract void onDescriptorRead(
                BluetoothGattDescriptorWrapper descriptor, int status);
        public abstract void onDescriptorWrite(
                BluetoothGattDescriptorWrapper descriptor, int status);
        public abstract void onConnectionStateChange(int status, int newState);
        public abstract void onServicesDiscovered(int status);
    }

    /**
     * Wraps android.bluetooth.BluetoothGattService.
     */
    static class BluetoothGattServiceWrapper {
        private final BluetoothGattService mService;
        private final BluetoothDeviceWrapper mDeviceWrapper;

        public BluetoothGattServiceWrapper(
                BluetoothGattService service, BluetoothDeviceWrapper deviceWrapper) {
            mService = service;
            mDeviceWrapper = deviceWrapper;
        }

        public List<BluetoothGattCharacteristicWrapper> getCharacteristics() {
            List<BluetoothGattCharacteristic> characteristics = mService.getCharacteristics();
            ArrayList<BluetoothGattCharacteristicWrapper> characteristicsWrapped =
                    new ArrayList<BluetoothGattCharacteristicWrapper>(characteristics.size());
            for (BluetoothGattCharacteristic characteristic : characteristics) {
                BluetoothGattCharacteristicWrapper characteristicWrapper =
                        mDeviceWrapper.mCharacteristicsToWrappers.get(characteristic);
                if (characteristicWrapper == null) {
                    characteristicWrapper =
                            new BluetoothGattCharacteristicWrapper(characteristic, mDeviceWrapper);
                    mDeviceWrapper.mCharacteristicsToWrappers.put(
                            characteristic, characteristicWrapper);
                }
                characteristicsWrapped.add(characteristicWrapper);
            }
            return characteristicsWrapped;
        }

        public int getInstanceId() {
            return mService.getInstanceId();
        }

        public UUID getUuid() {
            return mService.getUuid();
        }
    }

    /**
     * Wraps android.bluetooth.BluetoothGattCharacteristic.
     */
    static class BluetoothGattCharacteristicWrapper {
        final BluetoothGattCharacteristic mCharacteristic;
        final BluetoothDeviceWrapper mDeviceWrapper;

        public BluetoothGattCharacteristicWrapper(
                BluetoothGattCharacteristic characteristic, BluetoothDeviceWrapper deviceWrapper) {
            mCharacteristic = characteristic;
            mDeviceWrapper = deviceWrapper;
        }

        public BluetoothGattDescriptorWrapper getDescriptor(UUID uuid) {
            BluetoothGattDescriptor descriptor = mCharacteristic.getDescriptor(uuid);
            if (descriptor == null) {
                return null;
            }

            BluetoothGattDescriptorWrapper descriptorWrapper =
                    mDeviceWrapper.mDescriptorsToWrappers.get(descriptor);

            if (descriptorWrapper == null) {
                descriptorWrapper = new BluetoothGattDescriptorWrapper(descriptor, mDeviceWrapper);
                mDeviceWrapper.mDescriptorsToWrappers.put(descriptor, descriptorWrapper);
            }
            return descriptorWrapper;
        }

        public List<BluetoothGattDescriptorWrapper> getDescriptors() {
            List<BluetoothGattDescriptor> descriptors = mCharacteristic.getDescriptors();

            ArrayList<BluetoothGattDescriptorWrapper> descriptorsWrapped =
                    new ArrayList<BluetoothGattDescriptorWrapper>(descriptors.size());

            for (BluetoothGattDescriptor descriptor : descriptors) {
                BluetoothGattDescriptorWrapper descriptorWrapper =
                        mDeviceWrapper.mDescriptorsToWrappers.get(descriptor);
                if (descriptorWrapper == null) {
                    descriptorWrapper =
                            new BluetoothGattDescriptorWrapper(descriptor, mDeviceWrapper);
                    mDeviceWrapper.mDescriptorsToWrappers.put(descriptor, descriptorWrapper);
                }
                descriptorsWrapped.add(descriptorWrapper);
            }
            return descriptorsWrapped;
        }

        public int getInstanceId() {
            return mCharacteristic.getInstanceId();
        }

        public int getProperties() {
            return mCharacteristic.getProperties();
        }

        public UUID getUuid() {
            return mCharacteristic.getUuid();
        }

        public byte[] getValue() {
            return mCharacteristic.getValue();
        }

        public boolean setValue(byte[] value) {
            return mCharacteristic.setValue(value);
        }
    }

    /**
     * Wraps android.bluetooth.BluetoothGattDescriptor.
     */
    static class BluetoothGattDescriptorWrapper {
        private final BluetoothGattDescriptor mDescriptor;
        final BluetoothDeviceWrapper mDeviceWrapper;

        public BluetoothGattDescriptorWrapper(
                BluetoothGattDescriptor descriptor, BluetoothDeviceWrapper deviceWrapper) {
            mDescriptor = descriptor;
            mDeviceWrapper = deviceWrapper;
        }

        public BluetoothGattCharacteristicWrapper getCharacteristic() {
            return mDeviceWrapper.mCharacteristicsToWrappers.get(mDescriptor.getCharacteristic());
        }

        public UUID getUuid() {
            return mDescriptor.getUuid();
        }

        public byte[] getValue() {
            return mDescriptor.getValue();
        }

        public boolean setValue(byte[] value) {
            return mDescriptor.setValue(value);
        }
    }
}