1/*
2 * Copyright (C) 2013 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 android.bluetooth;
18
19import android.Manifest;
20import android.annotation.RequiresFeature;
21import android.annotation.RequiresPermission;
22import android.annotation.SystemService;
23import android.content.Context;
24import android.content.pm.PackageManager;
25import android.os.RemoteException;
26import android.util.Log;
27
28import java.util.ArrayList;
29import java.util.List;
30
31/**
32 * High level manager used to obtain an instance of an {@link BluetoothAdapter}
33 * and to conduct overall Bluetooth Management.
34 * <p>
35 * Use {@link android.content.Context#getSystemService(java.lang.String)}
36 * with {@link Context#BLUETOOTH_SERVICE} to create an {@link BluetoothManager},
37 * then call {@link #getAdapter} to obtain the {@link BluetoothAdapter}.
38 * </p>
39 * <div class="special reference">
40 * <h3>Developer Guides</h3>
41 * <p>
42 * For more information about using BLUETOOTH, read the <a href=
43 * "{@docRoot}guide/topics/connectivity/bluetooth.html">Bluetooth</a> developer
44 * guide.
45 * </p>
46 * </div>
47 *
48 * @see Context#getSystemService
49 * @see BluetoothAdapter#getDefaultAdapter()
50 */
51@SystemService(Context.BLUETOOTH_SERVICE)
52@RequiresFeature(PackageManager.FEATURE_BLUETOOTH)
53public final class BluetoothManager {
54    private static final String TAG = "BluetoothManager";
55    private static final boolean DBG = true;
56    private static final boolean VDBG = true;
57
58    private final BluetoothAdapter mAdapter;
59
60    /**
61     * @hide
62     */
63    public BluetoothManager(Context context) {
64        context = context.getApplicationContext();
65        if (context == null) {
66            throw new IllegalArgumentException(
67                    "context not associated with any application (using a mock context?)");
68        }
69        // Legacy api - getDefaultAdapter does not take in the context
70        mAdapter = BluetoothAdapter.getDefaultAdapter();
71    }
72
73    /**
74     * Get the default BLUETOOTH Adapter for this device.
75     *
76     * @return the default BLUETOOTH Adapter
77     */
78    public BluetoothAdapter getAdapter() {
79        return mAdapter;
80    }
81
82    /**
83     * Get the current connection state of the profile to the remote device.
84     *
85     * <p>This is not specific to any application configuration but represents
86     * the connection state of the local Bluetooth adapter for certain profile.
87     * This can be used by applications like status bar which would just like
88     * to know the state of Bluetooth.
89     *
90     * @param device Remote bluetooth device.
91     * @param profile GATT or GATT_SERVER
92     * @return State of the profile connection. One of {@link BluetoothProfile#STATE_CONNECTED},
93     * {@link BluetoothProfile#STATE_CONNECTING}, {@link BluetoothProfile#STATE_DISCONNECTED},
94     * {@link BluetoothProfile#STATE_DISCONNECTING}
95     */
96    @RequiresPermission(Manifest.permission.BLUETOOTH)
97    public int getConnectionState(BluetoothDevice device, int profile) {
98        if (DBG) Log.d(TAG, "getConnectionState()");
99
100        List<BluetoothDevice> connectedDevices = getConnectedDevices(profile);
101        for (BluetoothDevice connectedDevice : connectedDevices) {
102            if (device.equals(connectedDevice)) {
103                return BluetoothProfile.STATE_CONNECTED;
104            }
105        }
106
107        return BluetoothProfile.STATE_DISCONNECTED;
108    }
109
110    /**
111     * Get connected devices for the specified profile.
112     *
113     * <p> Return the set of devices which are in state {@link BluetoothProfile#STATE_CONNECTED}
114     *
115     * <p>This is not specific to any application configuration but represents
116     * the connection state of Bluetooth for this profile.
117     * This can be used by applications like status bar which would just like
118     * to know the state of Bluetooth.
119     *
120     * @param profile GATT or GATT_SERVER
121     * @return List of devices. The list will be empty on error.
122     */
123    @RequiresPermission(Manifest.permission.BLUETOOTH)
124    public List<BluetoothDevice> getConnectedDevices(int profile) {
125        if (DBG) Log.d(TAG, "getConnectedDevices");
126        if (profile != BluetoothProfile.GATT && profile != BluetoothProfile.GATT_SERVER) {
127            throw new IllegalArgumentException("Profile not supported: " + profile);
128        }
129
130        List<BluetoothDevice> connectedDevices = new ArrayList<BluetoothDevice>();
131
132        try {
133            IBluetoothManager managerService = mAdapter.getBluetoothManager();
134            IBluetoothGatt iGatt = managerService.getBluetoothGatt();
135            if (iGatt == null) return connectedDevices;
136
137            connectedDevices = iGatt.getDevicesMatchingConnectionStates(
138                    new int[]{BluetoothProfile.STATE_CONNECTED});
139        } catch (RemoteException e) {
140            Log.e(TAG, "", e);
141        }
142
143        return connectedDevices;
144    }
145
146    /**
147     * Get a list of devices that match any of the given connection
148     * states.
149     *
150     * <p> If none of the devices match any of the given states,
151     * an empty list will be returned.
152     *
153     * <p>This is not specific to any application configuration but represents
154     * the connection state of the local Bluetooth adapter for this profile.
155     * This can be used by applications like status bar which would just like
156     * to know the state of the local adapter.
157     *
158     * @param profile GATT or GATT_SERVER
159     * @param states Array of states. States can be one of {@link BluetoothProfile#STATE_CONNECTED},
160     * {@link BluetoothProfile#STATE_CONNECTING}, {@link BluetoothProfile#STATE_DISCONNECTED},
161     * {@link BluetoothProfile#STATE_DISCONNECTING},
162     * @return List of devices. The list will be empty on error.
163     */
164    @RequiresPermission(Manifest.permission.BLUETOOTH)
165    public List<BluetoothDevice> getDevicesMatchingConnectionStates(int profile, int[] states) {
166        if (DBG) Log.d(TAG, "getDevicesMatchingConnectionStates");
167
168        if (profile != BluetoothProfile.GATT && profile != BluetoothProfile.GATT_SERVER) {
169            throw new IllegalArgumentException("Profile not supported: " + profile);
170        }
171
172        List<BluetoothDevice> devices = new ArrayList<BluetoothDevice>();
173
174        try {
175            IBluetoothManager managerService = mAdapter.getBluetoothManager();
176            IBluetoothGatt iGatt = managerService.getBluetoothGatt();
177            if (iGatt == null) return devices;
178            devices = iGatt.getDevicesMatchingConnectionStates(states);
179        } catch (RemoteException e) {
180            Log.e(TAG, "", e);
181        }
182
183        return devices;
184    }
185
186    /**
187     * Open a GATT Server
188     * The callback is used to deliver results to Caller, such as connection status as well
189     * as the results of any other GATT server operations.
190     * The method returns a BluetoothGattServer instance. You can use BluetoothGattServer
191     * to conduct GATT server operations.
192     *
193     * @param context App context
194     * @param callback GATT server callback handler that will receive asynchronous callbacks.
195     * @return BluetoothGattServer instance
196     */
197    public BluetoothGattServer openGattServer(Context context,
198            BluetoothGattServerCallback callback) {
199
200        return (openGattServer(context, callback, BluetoothDevice.TRANSPORT_AUTO));
201    }
202
203    /**
204     * Open a GATT Server
205     * The callback is used to deliver results to Caller, such as connection status as well
206     * as the results of any other GATT server operations.
207     * The method returns a BluetoothGattServer instance. You can use BluetoothGattServer
208     * to conduct GATT server operations.
209     *
210     * @param context App context
211     * @param callback GATT server callback handler that will receive asynchronous callbacks.
212     * @param transport preferred transport for GATT connections to remote dual-mode devices {@link
213     * BluetoothDevice#TRANSPORT_AUTO} or {@link BluetoothDevice#TRANSPORT_BREDR} or {@link
214     * BluetoothDevice#TRANSPORT_LE}
215     * @return BluetoothGattServer instance
216     * @hide
217     */
218    public BluetoothGattServer openGattServer(Context context,
219            BluetoothGattServerCallback callback, int transport) {
220        if (context == null || callback == null) {
221            throw new IllegalArgumentException("null parameter: " + context + " " + callback);
222        }
223
224        // TODO(Bluetooth) check whether platform support BLE
225        //     Do the check here or in GattServer?
226
227        try {
228            IBluetoothManager managerService = mAdapter.getBluetoothManager();
229            IBluetoothGatt iGatt = managerService.getBluetoothGatt();
230            if (iGatt == null) {
231                Log.e(TAG, "Fail to get GATT Server connection");
232                return null;
233            }
234            BluetoothGattServer mGattServer = new BluetoothGattServer(iGatt, transport);
235            Boolean regStatus = mGattServer.registerCallback(callback);
236            return regStatus ? mGattServer : null;
237        } catch (RemoteException e) {
238            Log.e(TAG, "", e);
239            return null;
240        }
241    }
242}
243