CachedBluetoothDeviceManager.java revision 5f23cb39a1bd9c319383108c209fca7f0256894b
1/*
2 * Copyright (C) 2008 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.settings.bluetooth;
18
19import android.bluetooth.BluetoothAdapter;
20import android.bluetooth.BluetoothClass;
21import android.bluetooth.BluetoothDevice;
22import android.util.Log;
23
24import com.android.settings.R;
25import com.android.settings.bluetooth.LocalBluetoothManager.Callback;
26import com.android.settings.bluetooth.LocalBluetoothProfileManager.Profile;
27
28import java.util.ArrayList;
29import java.util.List;
30import java.util.Set;
31
32/**
33 * CachedBluetoothDeviceManager manages the set of remote Bluetooth devices.
34 */
35public class CachedBluetoothDeviceManager {
36    private static final String TAG = "CachedBluetoothDeviceManager";
37
38    final LocalBluetoothManager mLocalManager;
39    final List<Callback> mCallbacks;
40
41    final List<CachedBluetoothDevice> mCachedDevices = new ArrayList<CachedBluetoothDevice>();
42
43    public CachedBluetoothDeviceManager(LocalBluetoothManager localManager) {
44        mLocalManager = localManager;
45        mCallbacks = localManager.getCallbacks();
46        readPairedDevices();
47    }
48
49    private synchronized boolean readPairedDevices() {
50        BluetoothAdapter adapter = mLocalManager.getBluetoothAdapter();
51        Set<BluetoothDevice> bondedDevices = adapter.getBondedDevices();
52        if (bondedDevices == null) return false;
53
54        boolean deviceAdded = false;
55        for (BluetoothDevice device : bondedDevices) {
56            CachedBluetoothDevice cachedDevice = findDevice(device);
57            if (cachedDevice == null) {
58                cachedDevice = new CachedBluetoothDevice(mLocalManager.getContext(), device);
59                mCachedDevices.add(cachedDevice);
60                dispatchDeviceAdded(cachedDevice);
61                deviceAdded = true;
62            }
63        }
64
65        return deviceAdded;
66    }
67
68    public synchronized List<CachedBluetoothDevice> getCachedDevicesCopy() {
69        return new ArrayList<CachedBluetoothDevice>(mCachedDevices);
70    }
71
72    void onBluetoothStateChanged(boolean enabled) {
73        if (enabled) {
74            readPairedDevices();
75        }
76    }
77
78    public synchronized void onDeviceAppeared(BluetoothDevice device, short rssi,
79            BluetoothClass btClass, String name) {
80        boolean deviceAdded = false;
81
82        CachedBluetoothDevice cachedDevice = findDevice(device);
83        if (cachedDevice == null) {
84            cachedDevice = new CachedBluetoothDevice(mLocalManager.getContext(), device);
85            mCachedDevices.add(cachedDevice);
86            deviceAdded = true;
87        }
88        cachedDevice.setRssi(rssi);
89        cachedDevice.setBtClass(btClass);
90        cachedDevice.setName(name);
91        cachedDevice.setVisible(true);
92
93        if (deviceAdded) {
94            dispatchDeviceAdded(cachedDevice);
95        }
96    }
97
98    public synchronized void onDeviceDisappeared(BluetoothDevice device) {
99        CachedBluetoothDevice cachedDevice = findDevice(device);
100        if (cachedDevice == null) return;
101
102        cachedDevice.setVisible(false);
103        checkForDeviceRemoval(cachedDevice);
104    }
105
106    private void checkForDeviceRemoval(CachedBluetoothDevice cachedDevice) {
107        if (cachedDevice.getBondState() == BluetoothDevice.BOND_NONE &&
108                !cachedDevice.isVisible()) {
109            // If device isn't paired, remove it altogether
110            mCachedDevices.remove(cachedDevice);
111            dispatchDeviceDeleted(cachedDevice);
112        }
113    }
114
115    public synchronized void onDeviceNameUpdated(BluetoothDevice device) {
116        CachedBluetoothDevice cachedDevice = findDevice(device);
117        if (cachedDevice != null) {
118            cachedDevice.refreshName();
119        }
120    }
121
122    public synchronized CachedBluetoothDevice findDevice(BluetoothDevice device) {
123
124        for (int i = mCachedDevices.size() - 1; i >= 0; i--) {
125            CachedBluetoothDevice cachedDevice = mCachedDevices.get(i);
126
127            if (cachedDevice.getDevice().equals(device)) {
128                return cachedDevice;
129            }
130        }
131
132        return null;
133    }
134
135    /**
136     * Attempts to get the name of a remote device, otherwise returns the address.
137     *
138     * @param device The remote device.
139     * @return The name, or if unavailable, the address.
140     */
141    public String getName(BluetoothDevice device) {
142        CachedBluetoothDevice cachedDevice = findDevice(device);
143        return cachedDevice != null ? cachedDevice.getName() : device.getAddress();
144    }
145
146    private void dispatchDeviceAdded(CachedBluetoothDevice cachedDevice) {
147        synchronized (mCallbacks) {
148            for (Callback callback : mCallbacks) {
149                callback.onDeviceAdded(cachedDevice);
150            }
151        }
152
153        // TODO: divider between prev paired/connected and scanned
154    }
155
156    private void dispatchDeviceDeleted(CachedBluetoothDevice cachedDevice) {
157        synchronized (mCallbacks) {
158            for (Callback callback : mCallbacks) {
159                callback.onDeviceDeleted(cachedDevice);
160            }
161        }
162    }
163
164    public synchronized void onBondingStateChanged(BluetoothDevice device, int bondState) {
165        CachedBluetoothDevice cachedDevice = findDevice(device);
166        if (cachedDevice == null) {
167            if (!readPairedDevices()) {
168                Log.e(TAG, "Got bonding state changed for " + device +
169                        ", but we have no record of that device.");
170            }
171            return;
172        }
173
174        cachedDevice.refresh();
175
176        if (bondState == BluetoothDevice.BOND_BONDED) {
177            // Auto-connect after pairing
178            cachedDevice.connect();
179        }
180    }
181
182    /**
183     * Called when there is a bonding error.
184     *
185     * @param device The remote device.
186     * @param reason The reason, one of the error reasons from
187     *            BluetoothDevice.UNBOND_REASON_*
188     */
189    public synchronized void onBondingError(BluetoothDevice device, int reason) {
190        int errorMsg;
191
192        switch(reason) {
193        case BluetoothDevice.UNBOND_REASON_AUTH_FAILED:
194            errorMsg = R.string.bluetooth_pairing_pin_error_message;
195            mLocalManager.showError(device, R.string.bluetooth_error_title, errorMsg);
196            break;
197        case BluetoothDevice.UNBOND_REASON_AUTH_REJECTED:
198            errorMsg = R.string.bluetooth_pairing_rejected_error_message;
199            mLocalManager.showError(device, R.string.bluetooth_error_title, errorMsg);
200            break;
201        case BluetoothDevice.UNBOND_REASON_REMOTE_DEVICE_DOWN:
202            errorMsg = R.string.bluetooth_pairing_device_down_error_message;
203            mLocalManager.showError(device, R.string.bluetooth_error_title, errorMsg);
204            break;
205        case BluetoothDevice.UNBOND_REASON_DISCOVERY_IN_PROGRESS:
206        case BluetoothDevice.UNBOND_REASON_AUTH_TIMEOUT:
207        case BluetoothDevice.UNBOND_REASON_REPEATED_ATTEMPTS:
208            errorMsg = R.string.bluetooth_pairing_error_message;
209            mLocalManager.showError(device, R.string.bluetooth_error_title, errorMsg);
210            break;
211        default:
212            Log.w(TAG, "onBondingError: Not displaying any error message for reason:" + reason);
213            break;
214        }
215    }
216
217    public synchronized void onProfileStateChanged(BluetoothDevice device, Profile profile,
218            int newProfileState) {
219        CachedBluetoothDevice cachedDevice = findDevice(device);
220        if (cachedDevice == null) return;
221
222        cachedDevice.onProfileStateChanged(profile, newProfileState);
223        cachedDevice.refresh();
224    }
225
226    public synchronized void onConnectingError(BluetoothDevice device) {
227        CachedBluetoothDevice cachedDevice = findDevice(device);
228        if (cachedDevice == null) return;
229
230        /*
231         * Go through the device's delegate so we don't spam the user with
232         * errors connecting to different profiles, and instead make sure the
233         * user sees a single error for his single 'connect' action.
234         */
235        cachedDevice.showConnectingError();
236    }
237
238    public synchronized void onScanningStateChanged(boolean started) {
239        if (!started) return;
240
241        // If starting a new scan, clear old visibility
242        for (int i = mCachedDevices.size() - 1; i >= 0; i--) {
243            CachedBluetoothDevice cachedDevice = mCachedDevices.get(i);
244            cachedDevice.setVisible(false);
245            checkForDeviceRemoval(cachedDevice);
246        }
247    }
248
249    public synchronized void onBtClassChanged(BluetoothDevice device) {
250        CachedBluetoothDevice cachedDevice = findDevice(device);
251        if (cachedDevice != null) {
252            cachedDevice.refreshBtClass();
253        }
254    }
255}
256