AdapterProperties.java revision f19f1ac64a5fefb248ab15b918d009b926c99dde
1/*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.bluetooth.btservice;
18
19import android.bluetooth.BluetoothAdapter;
20import android.bluetooth.BluetoothDevice;
21import android.bluetooth.BluetoothProfile;
22import android.content.Context;
23import android.content.Intent;
24import android.os.ParcelUuid;
25import android.os.UserHandle;
26import android.util.Log;
27import android.util.Pair;
28
29import com.android.bluetooth.Utils;
30import com.android.bluetooth.btservice.RemoteDevices.DeviceProperties;
31
32import java.util.HashMap;
33import java.util.ArrayList;
34import java.util.concurrent.CopyOnWriteArrayList;
35
36class AdapterProperties {
37    private static final boolean DBG = true;
38    private static final boolean VDBG = false;
39    private static final String TAG = "BluetoothAdapterProperties";
40
41    private static final int BD_ADDR_LEN = 6; // 6 bytes
42    private String mName;
43    private byte[] mAddress;
44    private int mBluetoothClass;
45    private int mScanMode;
46    private int mDiscoverableTimeout;
47    private ParcelUuid[] mUuids;
48    private CopyOnWriteArrayList<BluetoothDevice> mBondedDevices = new CopyOnWriteArrayList<BluetoothDevice>();
49
50    private int mProfilesConnecting, mProfilesConnected, mProfilesDisconnecting;
51    private HashMap<Integer, Pair<Integer, Integer>> mProfileConnectionState;
52
53
54    private int mConnectionState = BluetoothAdapter.STATE_DISCONNECTED;
55    private int mState = BluetoothAdapter.STATE_OFF;
56
57    private AdapterService mService;
58    private boolean mDiscovering;
59    private RemoteDevices mRemoteDevices;
60    private BluetoothAdapter mAdapter;
61    //TODO - all hw capabilities to be exposed as a class
62    private int mNumOfAdvertisementInstancesSupported;
63    private boolean mRpaOffloadSupported;
64    private int mNumOfOffloadedIrkSupported;
65    private int mNumOfOffloadedScanFilterSupported;
66    private int mOffloadedScanResultStorageBytes;
67    private int mVersSupported;
68    private int mTotNumOfTrackableAdv;
69    private boolean mIsActivityAndEnergyReporting;
70
71    // Lock for all getters and setters.
72    // If finer grained locking is needer, more locks
73    // can be added here.
74    private Object mObject = new Object();
75
76    public AdapterProperties(AdapterService service) {
77        mService = service;
78        mAdapter = BluetoothAdapter.getDefaultAdapter();
79    }
80    public void init(RemoteDevices remoteDevices) {
81        if (mProfileConnectionState ==null) {
82            mProfileConnectionState = new HashMap<Integer, Pair<Integer, Integer>>();
83        } else {
84            mProfileConnectionState.clear();
85        }
86        mRemoteDevices = remoteDevices;
87    }
88
89    public void cleanup() {
90        mRemoteDevices = null;
91        if (mProfileConnectionState != null) {
92            mProfileConnectionState.clear();
93            mProfileConnectionState = null;
94        }
95        mService = null;
96        if (!mBondedDevices.isEmpty())
97            mBondedDevices.clear();
98    }
99
100    @Override
101    public Object clone() throws CloneNotSupportedException {
102        throw new CloneNotSupportedException();
103    }
104
105    /**
106     * @return the mName
107     */
108    String getName() {
109        synchronized (mObject) {
110            return mName;
111        }
112    }
113
114    /**
115     * Set the local adapter property - name
116     * @param name the name to set
117     */
118    boolean setName(String name) {
119        synchronized (mObject) {
120            return mService.setAdapterPropertyNative(
121                    AbstractionLayer.BT_PROPERTY_BDNAME, name.getBytes());
122        }
123    }
124
125    /**
126     * @return the mClass
127     */
128    int getBluetoothClass() {
129        synchronized (mObject) {
130            return mBluetoothClass;
131        }
132    }
133
134    /**
135     * @return the mScanMode
136     */
137    int getScanMode() {
138        synchronized (mObject) {
139            return mScanMode;
140        }
141    }
142
143    /**
144     * Set the local adapter property - scanMode
145     *
146     * @param scanMode the ScanMode to set
147     */
148    boolean setScanMode(int scanMode) {
149        synchronized (mObject) {
150            return mService.setAdapterPropertyNative(
151                    AbstractionLayer.BT_PROPERTY_ADAPTER_SCAN_MODE, Utils.intToByteArray(scanMode));
152        }
153    }
154
155    /**
156     * @return the mUuids
157     */
158    ParcelUuid[] getUuids() {
159        synchronized (mObject) {
160            return mUuids;
161        }
162    }
163
164    /**
165     * Set local adapter UUIDs.
166     *
167     * @param uuids the uuids to be set.
168     */
169    boolean setUuids(ParcelUuid[] uuids) {
170        synchronized (mObject) {
171            return mService.setAdapterPropertyNative(
172                    AbstractionLayer.BT_PROPERTY_UUIDS, Utils.uuidsToByteArray(uuids));
173        }
174    }
175
176    /**
177     * @return the mAddress
178     */
179    byte[] getAddress() {
180        synchronized (mObject) {
181            return mAddress;
182        }
183    }
184
185    /**
186     * @param mConnectionState the mConnectionState to set
187     */
188    void setConnectionState(int mConnectionState) {
189        synchronized (mObject) {
190            this.mConnectionState = mConnectionState;
191        }
192    }
193
194    /**
195     * @return the mConnectionState
196     */
197    int getConnectionState() {
198        synchronized (mObject) {
199            return mConnectionState;
200        }
201    }
202
203    /**
204     * @param mState the mState to set
205     */
206    void setState(int mState) {
207        synchronized (mObject) {
208            debugLog("Setting state to " + mState);
209            this.mState = mState;
210        }
211    }
212
213    /**
214     * @return the mState
215     */
216    int getState() {
217        /* remove the lock to work around a platform deadlock problem */
218        /* and also for read access, it is safe to remove the lock to save CPU power */
219        return mState;
220    }
221
222    /**
223     * @return the mNumOfAdvertisementInstancesSupported
224     */
225    int getNumOfAdvertisementInstancesSupported() {
226        return mNumOfAdvertisementInstancesSupported;
227    }
228
229    /**
230     * @return the mRpaOffloadSupported
231     */
232    boolean isRpaOffloadSupported() {
233        return mRpaOffloadSupported;
234    }
235
236    /**
237     * @return the mNumOfOffloadedIrkSupported
238     */
239    int getNumOfOffloadedIrkSupported() {
240        return mNumOfOffloadedIrkSupported;
241    }
242
243    /**
244     * @return the mNumOfOffloadedScanFilterSupported
245     */
246    int getNumOfOffloadedScanFilterSupported() {
247        return mNumOfOffloadedScanFilterSupported;
248    }
249
250    /**
251     * @return the mOffloadedScanResultStorageBytes
252     */
253    int getOffloadedScanResultStorage() {
254        return mOffloadedScanResultStorageBytes;
255    }
256
257    /**
258     * @return tx/rx/idle activity and energy info
259     */
260    boolean isActivityAndEnergyReportingSupported() {
261        return mIsActivityAndEnergyReporting;
262    }
263    /**
264     * @return the mBondedDevices
265     */
266    BluetoothDevice[] getBondedDevices() {
267        BluetoothDevice[] bondedDeviceList = new BluetoothDevice[0];
268        synchronized (mObject) {
269            if(mBondedDevices.isEmpty())
270                return (new BluetoothDevice[0]);
271
272            try {
273                bondedDeviceList = mBondedDevices.toArray(bondedDeviceList);
274                infoLog("getBondedDevices: length="+bondedDeviceList.length);
275                return bondedDeviceList;
276            } catch(ArrayStoreException ee) {
277                errorLog("Error retrieving bonded device array");
278                return (new BluetoothDevice[0]);
279            }
280        }
281    }
282    // This function shall be invoked from BondStateMachine whenever the bond
283    // state changes.
284    void onBondStateChanged(BluetoothDevice device, int state)
285    {
286        if(device == null)
287            return;
288        try {
289            byte[] addrByte = Utils.getByteAddress(device);
290            DeviceProperties prop = mRemoteDevices.getDeviceProperties(device);
291            if (prop == null)
292                prop = mRemoteDevices.addDeviceProperties(addrByte);
293            prop.setBondState(state);
294
295            if (state == BluetoothDevice.BOND_BONDED) {
296                // add if not already in list
297                if(!mBondedDevices.contains(device)) {
298                    debugLog("Adding bonded device:" +  device);
299                    mBondedDevices.add(device);
300                }
301            } else if (state == BluetoothDevice.BOND_NONE) {
302                // remove device from list
303                if (mBondedDevices.remove(device))
304                    debugLog("Removing bonded device:" +  device);
305                else
306                    debugLog("Failed to remove device: " + device);
307            }
308        }
309        catch(Exception ee) {
310            Log.e(TAG, "Exception in onBondStateChanged : ", ee);
311        }
312    }
313
314    int getDiscoverableTimeout() {
315        synchronized (mObject) {
316            return mDiscoverableTimeout;
317        }
318    }
319
320    boolean setDiscoverableTimeout(int timeout) {
321        synchronized (mObject) {
322            return mService.setAdapterPropertyNative(
323                    AbstractionLayer.BT_PROPERTY_ADAPTER_DISCOVERABLE_TIMEOUT,
324                    Utils.intToByteArray(timeout));
325        }
326    }
327
328    int getProfileConnectionState(int profile) {
329        synchronized (mObject) {
330            Pair<Integer, Integer> p = mProfileConnectionState.get(profile);
331            if (p != null) return p.first;
332            return BluetoothProfile.STATE_DISCONNECTED;
333        }
334    }
335
336    boolean isDiscovering() {
337        synchronized (mObject) {
338            return mDiscovering;
339        }
340    }
341
342    void sendConnectionStateChange(BluetoothDevice device, int profile, int state, int prevState) {
343        if (!validateProfileConnectionState(state) ||
344                !validateProfileConnectionState(prevState)) {
345            // Previously, an invalid state was broadcast anyway,
346            // with the invalid state converted to -1 in the intent.
347            // Better to log an error and not send an intent with
348            // invalid contents or set mAdapterConnectionState to -1.
349            errorLog("Error in sendConnectionStateChange: "
350                    + "prevState " + prevState + " state " + state);
351            return;
352        }
353
354        synchronized (mObject) {
355            updateProfileConnectionState(profile, state, prevState);
356
357            if (updateCountersAndCheckForConnectionStateChange(state, prevState)) {
358                setConnectionState(state);
359
360                Intent intent = new Intent(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED);
361                intent.putExtra(BluetoothDevice.EXTRA_DEVICE, device);
362                intent.putExtra(BluetoothAdapter.EXTRA_CONNECTION_STATE,
363                        convertToAdapterState(state));
364                intent.putExtra(BluetoothAdapter.EXTRA_PREVIOUS_CONNECTION_STATE,
365                        convertToAdapterState(prevState));
366                intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
367                mService.sendBroadcastAsUser(intent, UserHandle.ALL,
368                        mService.BLUETOOTH_PERM);
369                Log.d(TAG, "CONNECTION_STATE_CHANGE: " + device + ": "
370                        + prevState + " -> " + state);
371            }
372        }
373    }
374
375    private boolean validateProfileConnectionState(int state) {
376        return (state == BluetoothProfile.STATE_DISCONNECTED ||
377                state == BluetoothProfile.STATE_CONNECTING ||
378                state == BluetoothProfile.STATE_CONNECTED ||
379                state == BluetoothProfile.STATE_DISCONNECTING);
380    }
381
382
383    private int convertToAdapterState(int state) {
384        switch (state) {
385            case BluetoothProfile.STATE_DISCONNECTED:
386                return BluetoothAdapter.STATE_DISCONNECTED;
387            case BluetoothProfile.STATE_DISCONNECTING:
388                return BluetoothAdapter.STATE_DISCONNECTING;
389            case BluetoothProfile.STATE_CONNECTED:
390                return BluetoothAdapter.STATE_CONNECTED;
391            case BluetoothProfile.STATE_CONNECTING:
392                return BluetoothAdapter.STATE_CONNECTING;
393        }
394        Log.e(TAG, "Error in convertToAdapterState");
395        return -1;
396    }
397
398    private boolean updateCountersAndCheckForConnectionStateChange(int state, int prevState) {
399        switch (prevState) {
400            case BluetoothProfile.STATE_CONNECTING:
401                mProfilesConnecting--;
402                break;
403
404            case BluetoothProfile.STATE_CONNECTED:
405                mProfilesConnected--;
406                break;
407
408            case BluetoothProfile.STATE_DISCONNECTING:
409                mProfilesDisconnecting--;
410                break;
411        }
412
413        switch (state) {
414            case BluetoothProfile.STATE_CONNECTING:
415                mProfilesConnecting++;
416                return (mProfilesConnected == 0 && mProfilesConnecting == 1);
417
418            case BluetoothProfile.STATE_CONNECTED:
419                mProfilesConnected++;
420                return (mProfilesConnected == 1);
421
422            case BluetoothProfile.STATE_DISCONNECTING:
423                mProfilesDisconnecting++;
424                return (mProfilesConnected == 0 && mProfilesDisconnecting == 1);
425
426            case BluetoothProfile.STATE_DISCONNECTED:
427                return (mProfilesConnected == 0 && mProfilesConnecting == 0);
428
429            default:
430                return true;
431        }
432    }
433
434    private void updateProfileConnectionState(int profile, int newState, int oldState) {
435        // mProfileConnectionState is a hashmap -
436        // <Integer, Pair<Integer, Integer>>
437        // The key is the profile, the value is a pair. first element
438        // is the state and the second element is the number of devices
439        // in that state.
440        int numDev = 1;
441        int newHashState = newState;
442        boolean update = true;
443
444        // The following conditions are considered in this function:
445        // 1. If there is no record of profile and state - update
446        // 2. If a new device's state is current hash state - increment
447        //    number of devices in the state.
448        // 3. If a state change has happened to Connected or Connecting
449        //    (if current state is not connected), update.
450        // 4. If numDevices is 1 and that device state is being updated, update
451        // 5. If numDevices is > 1 and one of the devices is changing state,
452        //    decrement numDevices but maintain oldState if it is Connected or
453        //    Connecting
454        Pair<Integer, Integer> stateNumDev = mProfileConnectionState.get(profile);
455        if (stateNumDev != null) {
456            int currHashState = stateNumDev.first;
457            numDev = stateNumDev.second;
458
459            if (newState == currHashState) {
460                numDev ++;
461            } else if (newState == BluetoothProfile.STATE_CONNECTED ||
462                   (newState == BluetoothProfile.STATE_CONNECTING &&
463                    currHashState != BluetoothProfile.STATE_CONNECTED)) {
464                 numDev = 1;
465            } else if (numDev == 1 && oldState == currHashState) {
466                 update = true;
467            } else if (numDev > 1 && oldState == currHashState) {
468                 numDev --;
469
470                 if (currHashState == BluetoothProfile.STATE_CONNECTED ||
471                     currHashState == BluetoothProfile.STATE_CONNECTING) {
472                    newHashState = currHashState;
473                 }
474            } else {
475                 update = false;
476            }
477        }
478
479        if (update) {
480            mProfileConnectionState.put(profile, new Pair<Integer, Integer>(newHashState,
481                    numDev));
482        }
483    }
484
485    void adapterPropertyChangedCallback(int[] types, byte[][] values) {
486        Intent intent;
487        int type;
488        byte[] val;
489        for (int i = 0; i < types.length; i++) {
490            val = values[i];
491            type = types[i];
492            infoLog("adapterPropertyChangedCallback with type:" + type + " len:" + val.length);
493            synchronized (mObject) {
494                switch (type) {
495                    case AbstractionLayer.BT_PROPERTY_BDNAME:
496                        mName = new String(val);
497                        intent = new Intent(BluetoothAdapter.ACTION_LOCAL_NAME_CHANGED);
498                        intent.putExtra(BluetoothAdapter.EXTRA_LOCAL_NAME, mName);
499                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
500                        mService.sendBroadcastAsUser(intent, UserHandle.ALL,
501                                 mService.BLUETOOTH_PERM);
502                        debugLog("Name is: " + mName);
503                        break;
504                    case AbstractionLayer.BT_PROPERTY_BDADDR:
505                        mAddress = val;
506                        debugLog("Address is:" + Utils.getAddressStringFromByte(mAddress));
507                        break;
508                    case AbstractionLayer.BT_PROPERTY_CLASS_OF_DEVICE:
509                        mBluetoothClass = Utils.byteArrayToInt(val, 0);
510                        debugLog("BT Class:" + mBluetoothClass);
511                        break;
512                    case AbstractionLayer.BT_PROPERTY_ADAPTER_SCAN_MODE:
513                        int mode = Utils.byteArrayToInt(val, 0);
514                        mScanMode = mService.convertScanModeFromHal(mode);
515                        intent = new Intent(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
516                        intent.putExtra(BluetoothAdapter.EXTRA_SCAN_MODE, mScanMode);
517                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
518                        mService.sendBroadcast(intent, mService.BLUETOOTH_PERM);
519                        debugLog("Scan Mode:" + mScanMode);
520                        if (mBluetoothDisabling) {
521                            mBluetoothDisabling=false;
522                            mService.startBluetoothDisable();
523                        }
524                        break;
525                    case AbstractionLayer.BT_PROPERTY_UUIDS:
526                        mUuids = Utils.byteArrayToUuid(val);
527                        break;
528                    case AbstractionLayer.BT_PROPERTY_ADAPTER_BONDED_DEVICES:
529                        int number = val.length/BD_ADDR_LEN;
530                        byte[] addrByte = new byte[BD_ADDR_LEN];
531                        for (int j = 0; j < number; j++) {
532                            System.arraycopy(val, j * BD_ADDR_LEN, addrByte, 0, BD_ADDR_LEN);
533                            onBondStateChanged(mAdapter.getRemoteDevice(
534                                               Utils.getAddressStringFromByte(addrByte)),
535                                               BluetoothDevice.BOND_BONDED);
536                        }
537                        break;
538                    case AbstractionLayer.BT_PROPERTY_ADAPTER_DISCOVERABLE_TIMEOUT:
539                        mDiscoverableTimeout = Utils.byteArrayToInt(val, 0);
540                        debugLog("Discoverable Timeout:" + mDiscoverableTimeout);
541                        break;
542
543                    case AbstractionLayer.BT_PROPERTY_LOCAL_LE_FEATURES:
544                        updateFeatureSupport(val);
545                        break;
546
547                    default:
548                        errorLog("Property change not handled in Java land:" + type);
549                }
550            }
551        }
552    }
553
554    void updateFeatureSupport(byte[] val) {
555        mVersSupported = ((0xFF & ((int)val[1])) << 8)
556                            + (0xFF & ((int)val[0]));
557        mNumOfAdvertisementInstancesSupported = (0xFF & ((int)val[3]));
558        mRpaOffloadSupported = ((0xFF & ((int)val[4]))!= 0);
559        mNumOfOffloadedIrkSupported =  (0xFF & ((int)val[5]));
560        mNumOfOffloadedScanFilterSupported = (0xFF & ((int)val[6]));
561        mIsActivityAndEnergyReporting = ((0xFF & ((int)val[7])) != 0);
562        mOffloadedScanResultStorageBytes = ((0xFF & ((int)val[9])) << 8)
563                            + (0xFF & ((int)val[8]));
564        mTotNumOfTrackableAdv = ((0xFF & ((int)val[11])) << 8)
565                            + (0xFF & ((int)val[10]));
566
567        Log.d(TAG, "BT_PROPERTY_LOCAL_LE_FEATURES: update from BT controller"
568                + " mNumOfAdvertisementInstancesSupported = "
569                + mNumOfAdvertisementInstancesSupported
570                + " mRpaOffloadSupported = " + mRpaOffloadSupported
571                + " mNumOfOffloadedIrkSupported = "
572                + mNumOfOffloadedIrkSupported
573                + " mNumOfOffloadedScanFilterSupported = "
574                + mNumOfOffloadedScanFilterSupported
575                + " mOffloadedScanResultStorageBytes= "
576                + mOffloadedScanResultStorageBytes
577                + " mIsActivityAndEnergyReporting = "
578                + mIsActivityAndEnergyReporting
579                +" mVersSupported = "
580                + mVersSupported
581                + " mTotNumOfTrackableAdv = "
582                + mTotNumOfTrackableAdv);
583    }
584
585    void onBluetoothReady() {
586        Log.d(TAG, "ScanMode =  " + mScanMode );
587        Log.d(TAG, "State =  " + getState() );
588
589        // When BT is being turned on, all adapter properties will be sent in 1
590        // callback. At this stage, set the scan mode.
591        synchronized (mObject) {
592            if (getState() == BluetoothAdapter.STATE_TURNING_ON &&
593                    mScanMode == BluetoothAdapter.SCAN_MODE_NONE) {
594                    /* mDiscoverableTimeout is part of the
595                       adapterPropertyChangedCallback received before
596                       onBluetoothReady */
597                    if (mDiscoverableTimeout != 0)
598                      setScanMode(AbstractionLayer.BT_SCAN_MODE_CONNECTABLE);
599                    else /* if timeout == never (0) at startup */
600                      setScanMode(AbstractionLayer.BT_SCAN_MODE_CONNECTABLE_DISCOVERABLE);
601                    /* though not always required, this keeps NV up-to date on first-boot after flash */
602                    setDiscoverableTimeout(mDiscoverableTimeout);
603            }
604        }
605    }
606
607    private boolean mBluetoothDisabling = false;
608
609    void onBleDisable() {
610        // Sequence BLE_ON to STATE_OFF - that is _complete_ OFF state.
611        // When BT disable is invoked, set the scan_mode to NONE
612        // so no incoming connections are possible
613        debugLog("onBleDisable");
614        if (getState() == BluetoothAdapter.STATE_BLE_TURNING_OFF) {
615           setScanMode(AbstractionLayer.BT_SCAN_MODE_NONE);
616        }
617    }
618
619    void onBluetoothDisable() {
620        // From STATE_ON to BLE_ON
621        // When BT disable is invoked, set the scan_mode to NONE
622        // so no incoming connections are possible
623
624        //Set flag to indicate we are disabling. When property change of scan mode done
625        //continue with disable sequence
626        debugLog("onBluetoothDisable()");
627        mBluetoothDisabling = true;
628        if (getState() == BluetoothAdapter.STATE_TURNING_OFF) {
629            setScanMode(AbstractionLayer.BT_SCAN_MODE_NONE);
630        }
631    }
632
633    void discoveryStateChangeCallback(int state) {
634        infoLog("Callback:discoveryStateChangeCallback with state:" + state);
635        synchronized (mObject) {
636            Intent intent;
637            if (state == AbstractionLayer.BT_DISCOVERY_STOPPED) {
638                mDiscovering = false;
639                intent = new Intent(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
640                mService.sendBroadcast(intent, mService.BLUETOOTH_PERM);
641            } else if (state == AbstractionLayer.BT_DISCOVERY_STARTED) {
642                mDiscovering = true;
643                intent = new Intent(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
644                mService.sendBroadcast(intent, mService.BLUETOOTH_PERM);
645            }
646        }
647    }
648
649    private void infoLog(String msg) {
650        if (VDBG) Log.i(TAG, msg);
651    }
652
653    private void debugLog(String msg) {
654        if (DBG) Log.d(TAG, msg);
655    }
656
657    private void errorLog(String msg) {
658        Log.e(TAG, msg);
659    }
660}
661