BondStateMachine.java revision fc9bed1b79edf77082f5baa21aa68d791a102ea4
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.BluetoothClass;
21import android.bluetooth.BluetoothProfile;
22import android.bluetooth.BluetoothDevice;
23import com.android.bluetooth.a2dp.A2dpService;
24import com.android.bluetooth.hid.HidService;
25import com.android.bluetooth.hfp.HeadsetService;
26import android.content.Context;
27import android.content.Intent;
28import android.os.Message;
29import android.os.UserHandle;
30import android.util.Log;
31
32import com.android.bluetooth.Utils;
33import com.android.bluetooth.btservice.RemoteDevices.DeviceProperties;
34import com.android.internal.util.State;
35import com.android.internal.util.StateMachine;
36
37import java.util.ArrayList;
38
39/**
40 * This state machine handles Bluetooth Adapter State.
41 * States:
42 *      {@link StableState} :  No device is in bonding / unbonding state.
43 *      {@link PendingCommandState} : Some device is in bonding / unbonding state.
44 * TODO(BT) This class can be removed and this logic moved to the stack.
45 */
46
47final class BondStateMachine extends StateMachine {
48    private static final boolean DBG = false;
49    private static final String TAG = "BluetoothBondStateMachine";
50
51    static final int CREATE_BOND = 1;
52    static final int CANCEL_BOND = 2;
53    static final int REMOVE_BOND = 3;
54    static final int BONDING_STATE_CHANGE = 4;
55    static final int SSP_REQUEST = 5;
56    static final int PIN_REQUEST = 6;
57    static final int BOND_STATE_NONE = 0;
58    static final int BOND_STATE_BONDING = 1;
59    static final int BOND_STATE_BONDED = 2;
60
61    private AdapterService mAdapterService;
62    private AdapterProperties mAdapterProperties;
63    private RemoteDevices mRemoteDevices;
64    private BluetoothAdapter mAdapter;
65
66    private PendingCommandState mPendingCommandState = new PendingCommandState();
67    private StableState mStableState = new StableState();
68
69    private BondStateMachine(AdapterService service,
70            AdapterProperties prop, RemoteDevices remoteDevices) {
71        super("BondStateMachine:");
72        addState(mStableState);
73        addState(mPendingCommandState);
74        mRemoteDevices = remoteDevices;
75        mAdapterService = service;
76        mAdapterProperties = prop;
77        mAdapter = BluetoothAdapter.getDefaultAdapter();
78        setInitialState(mStableState);
79    }
80
81    public static BondStateMachine make(AdapterService service,
82            AdapterProperties prop, RemoteDevices remoteDevices) {
83        Log.d(TAG, "make");
84        BondStateMachine bsm = new BondStateMachine(service, prop, remoteDevices);
85        bsm.start();
86        return bsm;
87    }
88
89    public void doQuit() {
90        quitNow();
91    }
92
93    public void cleanup() {
94        mAdapterService = null;
95        mRemoteDevices = null;
96        mAdapterProperties = null;
97    }
98
99    private class StableState extends State {
100        @Override
101        public void enter() {
102            infoLog("StableState(): Entering Off State");
103        }
104
105        @Override
106        public boolean processMessage(Message msg) {
107
108            BluetoothDevice dev = (BluetoothDevice)msg.obj;
109
110            switch(msg.what) {
111
112              case CREATE_BOND:
113                  createBond(dev, msg.arg1, true);
114                  break;
115              case REMOVE_BOND:
116                  removeBond(dev, true);
117                  break;
118              case BONDING_STATE_CHANGE:
119                int newState = msg.arg1;
120                /* if incoming pairing, transition to pending state */
121                if (newState == BluetoothDevice.BOND_BONDING)
122                {
123                    sendIntent(dev, newState, 0);
124                    transitionTo(mPendingCommandState);
125                }
126                else
127                {
128                    Log.e(TAG, "In stable state, received invalid newState: " + newState);
129                }
130                break;
131
132              case CANCEL_BOND:
133              default:
134                   Log.e(TAG, "Received unhandled state: " + msg.what);
135                   return false;
136            }
137            return true;
138        }
139    }
140
141
142    private class PendingCommandState extends State {
143        private final ArrayList<BluetoothDevice> mDevices =
144            new ArrayList<BluetoothDevice>();
145
146        @Override
147        public void enter() {
148            infoLog("Entering PendingCommandState State");
149            BluetoothDevice dev = (BluetoothDevice)getCurrentMessage().obj;
150        }
151
152        @Override
153        public boolean processMessage(Message msg) {
154
155            BluetoothDevice dev = (BluetoothDevice)msg.obj;
156            DeviceProperties devProp = mRemoteDevices.getDeviceProperties(dev);
157            boolean result = false;
158             if (mDevices.contains(dev) && msg.what != CANCEL_BOND &&
159                   msg.what != BONDING_STATE_CHANGE && msg.what != SSP_REQUEST &&
160                   msg.what != PIN_REQUEST) {
161                 deferMessage(msg);
162                 return true;
163             }
164
165            Intent intent = new Intent(BluetoothDevice.ACTION_PAIRING_REQUEST);
166
167            switch (msg.what) {
168                case CREATE_BOND:
169                    result = createBond(dev, msg.arg1, false);
170                    break;
171                case REMOVE_BOND:
172                    result = removeBond(dev, false);
173                    break;
174                case CANCEL_BOND:
175                    result = cancelBond(dev);
176                    break;
177                case BONDING_STATE_CHANGE:
178                    int newState = msg.arg1;
179                    int reason = getUnbondReasonFromHALCode(msg.arg2);
180                    sendIntent(dev, newState, reason);
181                    if(newState != BluetoothDevice.BOND_BONDING )
182                    {
183                        /* this is either none/bonded, remove and transition */
184                        result = !mDevices.remove(dev);
185                        if (mDevices.isEmpty()) {
186                            // Whenever mDevices is empty, then we need to
187                            // set result=false. Else, we will end up adding
188                            // the device to the list again. This prevents us
189                            // from pairing with a device that we just unpaired
190                            result = false;
191                            transitionTo(mStableState);
192                        }
193                        if (newState == BluetoothDevice.BOND_NONE)
194                        {
195                            mAdapterService.setPhonebookAccessPermission(dev,
196                                    BluetoothDevice.ACCESS_UNKNOWN);
197                            mAdapterService.setMessageAccessPermission(dev,
198                                    BluetoothDevice.ACCESS_UNKNOWN);
199                            // Set the profile Priorities to undefined
200                            clearProfilePriorty(dev);
201                        }
202                        else if (newState == BluetoothDevice.BOND_BONDED)
203                        {
204                           // Do not set profile priority
205                           // Profile priority should be set after SDP completion
206
207                           // Restore the profile priorty settings
208                           //setProfilePriorty(dev);
209                        }
210                    }
211                    else if(!mDevices.contains(dev))
212                        result=true;
213                    break;
214                case SSP_REQUEST:
215                    int passkey = msg.arg1;
216                    int variant = msg.arg2;
217                    sendDisplayPinIntent(devProp.getAddress(), passkey, variant);
218                    break;
219                case PIN_REQUEST:
220                    BluetoothClass btClass = dev.getBluetoothClass();
221                    int btDeviceClass = btClass.getDeviceClass();
222                    if (btDeviceClass == BluetoothClass.Device.PERIPHERAL_KEYBOARD ||
223                         btDeviceClass == BluetoothClass.Device.PERIPHERAL_KEYBOARD_POINTING) {
224                        // Its a keyboard. Follow the HID spec recommendation of creating the
225                        // passkey and displaying it to the user. If the keyboard doesn't follow
226                        // the spec recommendation, check if the keyboard has a fixed PIN zero
227                        // and pair.
228                        //TODO: Maintain list of devices that have fixed pin
229                        // Generate a variable 6-digit PIN in range of 100000-999999
230                        // This is not truly random but good enough.
231                        int pin = 100000 + (int)Math.floor((Math.random() * (999999 - 100000)));
232                        sendDisplayPinIntent(devProp.getAddress(), pin,
233                                 BluetoothDevice.PAIRING_VARIANT_DISPLAY_PIN);
234                        break;
235                    }
236                    //In PIN_REQUEST, there is no passkey to display.So do not send the
237                    //EXTRA_PAIRING_KEY type in the intent( 0 in SendDisplayPinIntent() )
238                    sendDisplayPinIntent(devProp.getAddress(), 0,
239                                          BluetoothDevice.PAIRING_VARIANT_PIN);
240
241                    break;
242                default:
243                    Log.e(TAG, "Received unhandled event:" + msg.what);
244                    return false;
245            }
246            if (result) mDevices.add(dev);
247
248            return true;
249        }
250    }
251
252    private boolean cancelBond(BluetoothDevice dev) {
253        if (dev.getBondState() == BluetoothDevice.BOND_BONDING) {
254            byte[] addr = Utils.getBytesFromAddress(dev.getAddress());
255            if (!mAdapterService.cancelBondNative(addr)) {
256               Log.e(TAG, "Unexpected error while cancelling bond:");
257            } else {
258                return true;
259            }
260        }
261        return false;
262    }
263
264    private boolean removeBond(BluetoothDevice dev, boolean transition) {
265        if (dev.getBondState() == BluetoothDevice.BOND_BONDED) {
266            byte[] addr = Utils.getBytesFromAddress(dev.getAddress());
267            if (!mAdapterService.removeBondNative(addr)) {
268               Log.e(TAG, "Unexpected error while removing bond:");
269            } else {
270                if (transition) transitionTo(mPendingCommandState);
271                return true;
272            }
273
274        }
275        return false;
276    }
277
278    private boolean createBond(BluetoothDevice dev, int transport, boolean transition) {
279        if (dev.getBondState() == BluetoothDevice.BOND_NONE) {
280            infoLog("Bond address is:" + dev);
281            byte[] addr = Utils.getBytesFromAddress(dev.getAddress());
282            if (!mAdapterService.createBondNative(addr, transport)) {
283                sendIntent(dev, BluetoothDevice.BOND_NONE,
284                           BluetoothDevice.UNBOND_REASON_REMOVED);
285                return false;
286            } else if (transition) {
287                transitionTo(mPendingCommandState);
288            }
289            return true;
290        }
291        return false;
292    }
293
294    private void sendDisplayPinIntent(byte[] address, int pin, int variant) {
295        Intent intent = new Intent(BluetoothDevice.ACTION_PAIRING_REQUEST);
296        intent.putExtra(BluetoothDevice.EXTRA_DEVICE, mRemoteDevices.getDevice(address));
297        if (pin != 0) {
298            intent.putExtra(BluetoothDevice.EXTRA_PAIRING_KEY, pin);
299        }
300        intent.putExtra(BluetoothDevice.EXTRA_PAIRING_VARIANT, variant);
301        mAdapterService.sendOrderedBroadcast(intent, mAdapterService.BLUETOOTH_ADMIN_PERM);
302    }
303
304    private void sendIntent(BluetoothDevice device, int newState, int reason) {
305        DeviceProperties devProp = mRemoteDevices.getDeviceProperties(device);
306        int oldState = BluetoothDevice.BOND_NONE;
307        if (devProp != null) {
308            oldState = devProp.getBondState();
309        }
310        if (oldState == newState) return;
311        mAdapterProperties.onBondStateChanged(device, newState);
312
313        Intent intent = new Intent(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
314        intent.putExtra(BluetoothDevice.EXTRA_DEVICE, device);
315        intent.putExtra(BluetoothDevice.EXTRA_BOND_STATE, newState);
316        intent.putExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, oldState);
317        if (newState == BluetoothDevice.BOND_NONE)
318            intent.putExtra(BluetoothDevice.EXTRA_REASON, reason);
319        mAdapterService.sendBroadcastAsUser(intent, UserHandle.ALL,
320                AdapterService.BLUETOOTH_PERM);
321        infoLog("Bond State Change Intent:" + device + " OldState: " + oldState
322                + " NewState: " + newState);
323    }
324
325    void bondStateChangeCallback(int status, byte[] address, int newState) {
326        BluetoothDevice device = mRemoteDevices.getDevice(address);
327
328        if (device == null) {
329            infoLog("No record of the device:" + device);
330            // This device will be added as part of the BONDING_STATE_CHANGE intent processing
331            // in sendIntent above
332            device = mAdapter.getRemoteDevice(Utils.getAddressStringFromByte(address));
333        }
334
335        infoLog("bondStateChangeCallback: Status: " + status + " Address: " + device
336                + " newState: " + newState);
337
338        Message msg = obtainMessage(BONDING_STATE_CHANGE);
339        msg.obj = device;
340
341        if (newState == BOND_STATE_BONDED)
342            msg.arg1 = BluetoothDevice.BOND_BONDED;
343        else if (newState == BOND_STATE_BONDING)
344            msg.arg1 = BluetoothDevice.BOND_BONDING;
345        else
346            msg.arg1 = BluetoothDevice.BOND_NONE;
347        msg.arg2 = status;
348
349        sendMessage(msg);
350    }
351
352    void sspRequestCallback(byte[] address, byte[] name, int cod, int pairingVariant,
353            int passkey) {
354        //TODO(BT): Get wakelock and update name and cod
355        BluetoothDevice bdDevice = mRemoteDevices.getDevice(address);
356        if (bdDevice == null) {
357            mRemoteDevices.addDeviceProperties(address);
358        }
359        infoLog("sspRequestCallback: " + address + " name: " + name + " cod: " +
360                cod + " pairingVariant " + pairingVariant + " passkey: " + passkey);
361        int variant;
362        boolean displayPasskey = false;
363        switch(pairingVariant) {
364
365            case AbstractionLayer.BT_SSP_VARIANT_PASSKEY_CONFIRMATION :
366                variant = BluetoothDevice.PAIRING_VARIANT_PASSKEY_CONFIRMATION;
367                displayPasskey = true;
368            break;
369
370            case AbstractionLayer.BT_SSP_VARIANT_CONSENT :
371                variant = BluetoothDevice.PAIRING_VARIANT_CONSENT;
372            break;
373
374            case AbstractionLayer.BT_SSP_VARIANT_PASSKEY_ENTRY :
375                variant = BluetoothDevice.PAIRING_VARIANT_PASSKEY;
376            break;
377
378            case AbstractionLayer.BT_SSP_VARIANT_PASSKEY_NOTIFICATION :
379                variant = BluetoothDevice.PAIRING_VARIANT_DISPLAY_PASSKEY;
380                displayPasskey = true;
381            break;
382
383            default:
384                errorLog("SSP Pairing variant not present");
385                return;
386        }
387        BluetoothDevice device = mRemoteDevices.getDevice(address);
388        if (device == null) {
389           warnLog("Device is not known for:" + Utils.getAddressStringFromByte(address));
390           mRemoteDevices.addDeviceProperties(address);
391           device = mRemoteDevices.getDevice(address);
392        }
393
394        Message msg = obtainMessage(SSP_REQUEST);
395        msg.obj = device;
396        if(displayPasskey)
397            msg.arg1 = passkey;
398        msg.arg2 = variant;
399        sendMessage(msg);
400    }
401
402    void pinRequestCallback(byte[] address, byte[] name, int cod) {
403        //TODO(BT): Get wakelock and update name and cod
404        BluetoothDevice bdDevice = mRemoteDevices.getDevice(address);
405        if (bdDevice == null) {
406            mRemoteDevices.addDeviceProperties(address);
407        }
408        infoLog("pinRequestCallback: " + address + " name:" + name + " cod:" +
409                cod);
410
411        Message msg = obtainMessage(PIN_REQUEST);
412        msg.obj = bdDevice;
413
414        sendMessage(msg);
415    }
416
417    private void setProfilePriorty (BluetoothDevice device){
418        HidService hidService = HidService.getHidService();
419        A2dpService a2dpService = A2dpService.getA2dpService();
420        HeadsetService headsetService = HeadsetService.getHeadsetService();
421
422        if ((hidService != null) &&
423            (hidService.getPriority(device) == BluetoothProfile.PRIORITY_UNDEFINED)){
424            hidService.setPriority(device,BluetoothProfile.PRIORITY_ON);
425        }
426
427        if ((a2dpService != null) &&
428            (a2dpService.getPriority(device) == BluetoothProfile.PRIORITY_UNDEFINED)){
429            a2dpService.setPriority(device,BluetoothProfile.PRIORITY_ON);
430        }
431
432        if ((headsetService != null) &&
433            (headsetService.getPriority(device) == BluetoothProfile.PRIORITY_UNDEFINED)){
434            headsetService.setPriority(device,BluetoothProfile.PRIORITY_ON);
435        }
436    }
437
438    private void clearProfilePriorty (BluetoothDevice device){
439        HidService hidService = HidService.getHidService();
440        A2dpService a2dpService = A2dpService.getA2dpService();
441        HeadsetService headsetService = HeadsetService.getHeadsetService();
442
443        if (hidService != null)
444            hidService.setPriority(device,BluetoothProfile.PRIORITY_UNDEFINED);
445        if(a2dpService != null)
446            a2dpService.setPriority(device,BluetoothProfile.PRIORITY_UNDEFINED);
447        if(headsetService != null)
448            headsetService.setPriority(device,BluetoothProfile.PRIORITY_UNDEFINED);
449    }
450
451    private void infoLog(String msg) {
452        Log.i(TAG, msg);
453    }
454
455    private void errorLog(String msg) {
456        Log.e(TAG, msg);
457    }
458
459    private void warnLog(String msg) {
460        Log.w(TAG, msg);
461    }
462
463    private int getUnbondReasonFromHALCode (int reason) {
464        if (reason == AbstractionLayer.BT_STATUS_SUCCESS)
465            return BluetoothDevice.BOND_SUCCESS;
466        else if (reason == AbstractionLayer.BT_STATUS_RMT_DEV_DOWN)
467            return BluetoothDevice.UNBOND_REASON_REMOTE_DEVICE_DOWN;
468        else if (reason == AbstractionLayer.BT_STATUS_AUTH_FAILURE)
469            return BluetoothDevice.UNBOND_REASON_AUTH_FAILED;
470        else if (reason == AbstractionLayer.BT_STATUS_AUTH_REJECTED)
471            return BluetoothDevice.UNBOND_REASON_AUTH_REJECTED;
472        else if (reason == AbstractionLayer.BT_STATUS_AUTH_TIMEOUT)
473            return BluetoothDevice.UNBOND_REASON_AUTH_TIMEOUT;
474
475        /* default */
476        return BluetoothDevice.UNBOND_REASON_REMOVED;
477    }
478}
479