HeadsetStateMachine.java 155 KB
Newer Older
1
/*
2 3 4 5 6 7 8 9 10 11 12 13 14
 * Copyright (C) 2012 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
 */

/**
 * Bluetooth Handset StateMachine
 *                      (Disconnected)
 *                           |    ^
 *                   CONNECT |    | DISCONNECTED
 *                           V    |
 *                         (Pending)
 *                           |    ^
 *                 CONNECTED |    | CONNECT
 *                           V    |
 *                        (Connected)
 *                           |    ^
 *             CONNECT_AUDIO |    | DISCONNECT_AUDIO
 *                           V    |
 *                         (AudioOn)
 */
package com.android.bluetooth.hfp;

import android.bluetooth.BluetoothAdapter;
36
import android.bluetooth.BluetoothAssignedNumbers;
37 38 39 40 41 42 43 44 45 46
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothHeadset;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.BluetoothUuid;
import android.bluetooth.IBluetooth;
import android.bluetooth.IBluetoothHeadsetPhone;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
47
import android.content.ActivityNotFoundException;
48 49 50 51 52 53 54
import android.media.AudioManager;
import android.net.Uri;
import android.os.IBinder;
import android.os.Message;
import android.os.ParcelUuid;
import android.os.RemoteException;
import android.os.ServiceManager;
55
import android.os.PowerManager;
56
import android.os.UserHandle;
57
import android.os.PowerManager.WakeLock;
58 59 60
import android.telephony.PhoneNumberUtils;
import android.util.Log;
import com.android.bluetooth.Utils;
61
import com.android.bluetooth.btservice.AdapterService;
62
import com.android.bluetooth.btservice.ProfileService;
63 64 65 66
import com.android.internal.util.IState;
import com.android.internal.util.State;
import com.android.internal.util.StateMachine;
import java.util.ArrayList;
67
import java.util.HashMap;
68
import java.util.List;
69
import java.util.Map;
70
import java.util.Set;
Nitin Srivastava's avatar
Nitin Srivastava committed
71
import android.os.SystemProperties;
72 73 74

final class HeadsetStateMachine extends StateMachine {
    private static final String TAG = "HeadsetStateMachine";
75
    private static final boolean DBG = false;
76 77
    //For Debugging only
    private static int sRefCount=0;
78

79 80
    private static final String HEADSET_NAME = "bt_headset_name";
    private static final String HEADSET_NREC = "bt_headset_nrec";
Matthew Xie's avatar
Matthew Xie committed
81
    private static final String HEADSET_WBS = "bt_wbs";
82

83 84 85 86 87 88 89 90 91 92 93 94 95 96
    static final int CONNECT = 1;
    static final int DISCONNECT = 2;
    static final int CONNECT_AUDIO = 3;
    static final int DISCONNECT_AUDIO = 4;
    static final int VOICE_RECOGNITION_START = 5;
    static final int VOICE_RECOGNITION_STOP = 6;

    // message.obj is an intent AudioManager.VOLUME_CHANGED_ACTION
    // EXTRA_VOLUME_STREAM_TYPE is STREAM_BLUETOOTH_SCO
    static final int INTENT_SCO_VOLUME_CHANGED = 7;
    static final int SET_MIC_VOLUME = 8;
    static final int CALL_STATE_CHANGED = 9;
    static final int INTENT_BATTERY_CHANGED = 10;
    static final int DEVICE_STATE_CHANGED = 11;
97
    static final int SEND_CCLC_RESPONSE = 12;
98
    static final int SEND_VENDOR_SPECIFIC_RESULT_CODE = 13;
99

100 101
    static final int VIRTUAL_CALL_START = 14;
    static final int VIRTUAL_CALL_STOP = 15;
Syed Ibrahim M's avatar
Syed Ibrahim M committed
102

103 104 105 106
    static final int ENABLE_WBS = 16;
    static final int DISABLE_WBS = 17;


107 108
    private static final int STACK_EVENT = 101;
    private static final int DIALING_OUT_TIMEOUT = 102;
109
    private static final int START_VR_TIMEOUT = 103;
Nitin Srivastava's avatar
Nitin Srivastava committed
110
    private static final int CLCC_RSP_TIMEOUT = 104;
111 112 113 114

    private static final int CONNECT_TIMEOUT = 201;

    private static final int DIALING_OUT_TIMEOUT_VALUE = 10000;
115
    private static final int START_VR_TIMEOUT_VALUE = 5000;
Nitin Srivastava's avatar
Nitin Srivastava committed
116 117 118
    private static final int CLCC_RSP_TIMEOUT_VALUE = 5000;

    // Max number of HF connections at any time
Nitin Arora's avatar
Nitin Arora committed
119
    private int max_hf_connections = 1;
120

121 122 123
    private static final int NBS_CODEC = 1;
    private static final int WBS_CODEC = 2;

124 125
    // Keys are AT commands, and values are the company IDs.
    private static final Map<String, Integer> VENDOR_SPECIFIC_AT_COMMAND_COMPANY_ID;
Nitin Srivastava's avatar
Nitin Srivastava committed
126 127 128 129 130 131
    // Hash for storing the Audio Parameters like NREC for connected headsets
    private HashMap<BluetoothDevice, HashMap> mHeadsetAudioParam =
                                          new HashMap<BluetoothDevice, HashMap>();
    // Hash for storing the Remotedevice BRSF
    private HashMap<BluetoothDevice, Integer> mHeadsetBrsf =
                                          new HashMap<BluetoothDevice, Integer>();
132

133 134 135 136 137 138 139 140 141
    private static final ParcelUuid[] HEADSET_UUIDS = {
        BluetoothUuid.HSP,
        BluetoothUuid.Handsfree,
    };

    private Disconnected mDisconnected;
    private Pending mPending;
    private Connected mConnected;
    private AudioOn mAudioOn;
Nitin Srivastava's avatar
Nitin Srivastava committed
142 143
    // Multi HFP: add new class object
    private MultiHFPending mMultiHFPending;
144

145
    private HeadsetService mService;
146
    private PowerManager mPowerManager;
Syed Ibrahim M's avatar
Syed Ibrahim M committed
147
    private boolean mVirtualCallStarted = false;
148
    private boolean mVoiceRecognitionStarted = false;
149 150 151
    private boolean mWaitingForVoiceRecognition = false;
    private WakeLock mStartVoiceRecognitionWakeLock;  // held while waiting for voice recognition

152 153 154 155
    private boolean mDialingOut = false;
    private AudioManager mAudioManager;
    private AtPhonebook mPhonebook;

156 157
    private static Intent sVoiceCommandIntent;

158 159 160 161
    private HeadsetPhoneState mPhoneState;
    private int mAudioState;
    private BluetoothAdapter mAdapter;
    private IBluetoothHeadsetPhone mPhoneProxy;
162
    private boolean mNativeAvailable;
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

    // mCurrentDevice is the device connected before the state changes
    // mTargetDevice is the device to be connected
    // mIncomingDevice is the device connecting to us, valid only in Pending state
    //                when mIncomingDevice is not null, both mCurrentDevice
    //                  and mTargetDevice are null
    //                when either mCurrentDevice or mTargetDevice is not null,
    //                  mIncomingDevice is null
    // Stable states
    //   No connection, Disconnected state
    //                  both mCurrentDevice and mTargetDevice are null
    //   Connected, Connected state
    //              mCurrentDevice is not null, mTargetDevice is null
    // Interim states
    //   Connecting to a device, Pending
    //                           mCurrentDevice is null, mTargetDevice is not null
    //   Disconnecting device, Connecting to new device
    //     Pending
    //     Both mCurrentDevice and mTargetDevice are not null
    //   Disconnecting device Pending
    //                        mCurrentDevice is not null, mTargetDevice is null
    //   Incoming connections Pending
    //                        Both mCurrentDevice and mTargetDevice are null
    private BluetoothDevice mCurrentDevice = null;
    private BluetoothDevice mTargetDevice = null;
    private BluetoothDevice mIncomingDevice = null;
Nitin Srivastava's avatar
Nitin Srivastava committed
189 190 191 192 193 194
    private BluetoothDevice mActiveScoDevice = null;
    private BluetoothDevice mMultiDisconnectDevice = null;

    // Multi HFP: Connected devices list holds all currently connected headsets
    private ArrayList<BluetoothDevice> mConnectedDevicesList =
                                             new ArrayList<BluetoothDevice>();
195 196 197

    static {
        classInitNative();
198 199 200 201

        VENDOR_SPECIFIC_AT_COMMAND_COMPANY_ID = new HashMap<String, Integer>();
        VENDOR_SPECIFIC_AT_COMMAND_COMPANY_ID.put("+XEVENT", BluetoothAssignedNumbers.PLANTRONICS);
        VENDOR_SPECIFIC_AT_COMMAND_COMPANY_ID.put("+ANDROID", BluetoothAssignedNumbers.GOOGLE);
202 203
    }

Wink Saville's avatar
Wink Saville committed
204
    private HeadsetStateMachine(HeadsetService context) {
205
        super(TAG);
206
        mService = context;
207
        mVoiceRecognitionStarted = false;
208 209 210 211 212 213 214
        mWaitingForVoiceRecognition = false;

        mPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        mStartVoiceRecognitionWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
                                                       TAG + ":VoiceRecognition");
        mStartVoiceRecognitionWakeLock.setReferenceCounted(false);

215 216
        mDialingOut = false;
        mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
217
        mPhonebook = new AtPhonebook(mService, this);
218 219 220
        mPhoneState = new HeadsetPhoneState(context, this);
        mAudioState = BluetoothHeadset.STATE_AUDIO_DISCONNECTED;
        mAdapter = BluetoothAdapter.getDefaultAdapter();
221 222 223
        Intent intent = new Intent(IBluetoothHeadsetPhone.class.getName());
        intent.setComponent(intent.resolveSystemService(context.getPackageManager(), 0));
        if (intent.getComponent() == null || !context.bindService(intent, mConnection, 0)) {
224 225 226
            Log.e(TAG, "Could not bind to Bluetooth Headset Phone Service");
        }

Nitin Srivastava's avatar
Nitin Srivastava committed
227 228 229 230 231
        String max_hfp_clients = SystemProperties.get("bt.max.hfpclient.connections");
        if (!max_hfp_clients.isEmpty() && (Integer.parseInt(max_hfp_clients) == 2))
            max_hf_connections = Integer.parseInt(max_hfp_clients);
        Log.d(TAG, "max_hf_connections = " + max_hf_connections);
        initializeNative(max_hf_connections);
232
        mNativeAvailable=true;
233 234 235 236 237

        mDisconnected = new Disconnected();
        mPending = new Pending();
        mConnected = new Connected();
        mAudioOn = new AudioOn();
Nitin Srivastava's avatar
Nitin Srivastava committed
238 239
        // Multi HFP: initialise new class variable
        mMultiHFPending = new MultiHFPending();
240

241 242 243 244 245
        if (sVoiceCommandIntent == null) {
            sVoiceCommandIntent = new Intent(Intent.ACTION_VOICE_COMMAND);
            sVoiceCommandIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }

246 247 248 249
        addState(mDisconnected);
        addState(mPending);
        addState(mConnected);
        addState(mAudioOn);
Nitin Srivastava's avatar
Nitin Srivastava committed
250 251
        // Multi HFP: add State
        addState(mMultiHFPending);
252 253 254 255

        setInitialState(mDisconnected);
    }

Wink Saville's avatar
Wink Saville committed
256 257 258 259 260 261 262
    static HeadsetStateMachine make(HeadsetService context) {
        Log.d(TAG, "make");
        HeadsetStateMachine hssm = new HeadsetStateMachine(context);
        hssm.start();
        return hssm;
    }

263 264 265 266 267

    public void doQuit() {
        quitNow();
    }

fredc's avatar
fredc committed
268 269 270 271 272 273
    public void cleanup() {
        if (mPhoneProxy != null) {
            if (DBG) Log.d(TAG,"Unbinding service...");
            synchronized (mConnection) {
                try {
                    mPhoneProxy = null;
274
                    mService.unbindService(mConnection);
fredc's avatar
fredc committed
275
                } catch (Exception re) {
276
                    Log.e(TAG,"Error unbinding from IBluetoothHeadsetPhone",re);
fredc's avatar
fredc committed
277
                }
278
            }
fredc's avatar
fredc committed
279
        }
280 281 282
        if (mPhoneState != null) {
            mPhoneState.listenForPhoneState(false);
            mPhoneState.cleanup();
fredc's avatar
fredc committed
283
        }
284 285 286
        if (mPhonebook != null) {
            mPhonebook.cleanup();
        }
Nitin Srivastava's avatar
Nitin Srivastava committed
287 288 289 290 291 292 293 294 295
        if (mHeadsetAudioParam != null) {
            mHeadsetAudioParam.clear();
        }
        if (mHeadsetBrsf != null) {
            mHeadsetBrsf.clear();
        }
        if (mConnectedDevicesList != null) {
            mConnectedDevicesList.clear();
        }
296 297 298 299
        if (mNativeAvailable) {
            cleanupNative();
            mNativeAvailable = false;
        }
fredc's avatar
fredc committed
300 301
    }

302 303 304 305 306 307 308 309 310 311 312 313 314 315
    public void dump(StringBuilder sb) {
        ProfileService.println(sb, "mCurrentDevice: " + mCurrentDevice);
        ProfileService.println(sb, "mTargetDevice: " + mTargetDevice);
        ProfileService.println(sb, "mIncomingDevice: " + mIncomingDevice);
        ProfileService.println(sb, "mActiveScoDevice: " + mActiveScoDevice);
        ProfileService.println(sb, "mMultiDisconnectDevice: " + mMultiDisconnectDevice);
        ProfileService.println(sb, "mVirtualCallStarted: " + mVirtualCallStarted);
        ProfileService.println(sb, "mVoiceRecognitionStarted: " + mVoiceRecognitionStarted);
        ProfileService.println(sb, "mWaitingForVoiceRecognition: " + mWaitingForVoiceRecognition);
        ProfileService.println(sb, "StateMachine: " + this.toString());
        ProfileService.println(sb, "mPhoneState: " + mPhoneState);
        ProfileService.println(sb, "mAudioState: " + mAudioState);
    }

316 317 318
    private class Disconnected extends State {
        @Override
        public void enter() {
Nitin Srivastava's avatar
Nitin Srivastava committed
319 320
            log("Enter Disconnected: " + getCurrentMessage().what +
                                ", size: " + mConnectedDevicesList.size());
Sreenidhi T's avatar
Sreenidhi T committed
321
            mPhonebook.resetAtState();
322
            mPhoneState.listenForPhoneState(false);
323 324
            mVoiceRecognitionStarted = false;
            mWaitingForVoiceRecognition = false;
325 326 327 328
        }

        @Override
        public boolean processMessage(Message message) {
Nitin Srivastava's avatar
Nitin Srivastava committed
329 330 331 332 333 334
            log("Disconnected process message: " + message.what +
                                ", size: " + mConnectedDevicesList.size());
            if (mConnectedDevicesList.size() != 0 || mTargetDevice != null ||
                                mIncomingDevice != null) {
                Log.e(TAG, "ERROR: mConnectedDevicesList is not empty," +
                       "target, or mIncomingDevice not null in Disconnected");
335
                return NOT_HANDLED;
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
            }

            boolean retValue = HANDLED;
            switch(message.what) {
                case CONNECT:
                    BluetoothDevice device = (BluetoothDevice) message.obj;
                    broadcastConnectionState(device, BluetoothProfile.STATE_CONNECTING,
                                   BluetoothProfile.STATE_DISCONNECTED);

                    if (!connectHfpNative(getByteAddress(device)) ) {
                        broadcastConnectionState(device, BluetoothProfile.STATE_DISCONNECTED,
                                       BluetoothProfile.STATE_CONNECTING);
                        break;
                    }

                    synchronized (HeadsetStateMachine.this) {
                        mTargetDevice = device;
                        transitionTo(mPending);
                    }
                    // TODO(BT) remove CONNECT_TIMEOUT when the stack
                    //          sends back events consistently
Nitin Srivastava's avatar
Nitin Srivastava committed
357 358 359
                    Message m = obtainMessage(CONNECT_TIMEOUT);
                    m.obj = device;
                    sendMessageDelayed(m, 30000);
360 361 362 363 364 365 366 367
                    break;
                case DISCONNECT:
                    // ignore
                    break;
                case INTENT_BATTERY_CHANGED:
                    processIntentBatteryChanged((Intent) message.obj);
                    break;
                case CALL_STATE_CHANGED:
Syed Ibrahim M's avatar
Syed Ibrahim M committed
368 369
                    processCallState((HeadsetCallState) message.obj,
                        ((message.arg1 == 1)?true:false));
370 371 372
                    break;
                case STACK_EVENT:
                    StackEvent event = (StackEvent) message.obj;
373 374 375
                    if (DBG) {
                        log("event type: " + event.type);
                    }
376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397
                    switch (event.type) {
                        case EVENT_TYPE_CONNECTION_STATE_CHANGED:
                            processConnectionEvent(event.valueInt, event.device);
                            break;
                        default:
                            Log.e(TAG, "Unexpected stack event: " + event.type);
                            break;
                    }
                    break;
                default:
                    return NOT_HANDLED;
            }
            return retValue;
        }

        @Override
        public void exit() {
            log("Exit Disconnected: " + getCurrentMessage().what);
        }

        // in Disconnected state
        private void processConnectionEvent(int state, BluetoothDevice device) {
Nitin Srivastava's avatar
Nitin Srivastava committed
398 399
            Log.d(TAG, "processConnectionEvent state = " + state +
                             ", device = " + device);
400 401 402 403 404
            switch (state) {
            case HeadsetHalConstants.CONNECTION_STATE_DISCONNECTED:
                Log.w(TAG, "Ignore HF DISCONNECTED event, device: " + device);
                break;
            case HeadsetHalConstants.CONNECTION_STATE_CONNECTING:
Nitin Srivastava's avatar
Nitin Srivastava committed
405
                if (okToConnect(device)) {
406 407 408 409 410 411 412 413
                    Log.i(TAG,"Incoming Hf accepted");
                    broadcastConnectionState(device, BluetoothProfile.STATE_CONNECTING,
                                             BluetoothProfile.STATE_DISCONNECTED);
                    synchronized (HeadsetStateMachine.this) {
                        mIncomingDevice = device;
                        transitionTo(mPending);
                    }
                } else {
414
                    Log.i(TAG,"Incoming Hf rejected. priority=" + mService.getPriority(device)+
415
                              " bondState=" + device.getBondState());
416 417
                    //reject the connection and stay in Disconnected state itself
                    disconnectHfpNative(getByteAddress(device));
418
                    // the other profile connection should be initiated
419
                    AdapterService adapterService = AdapterService.getAdapterService();
Nitin Srivastava's avatar
Nitin Srivastava committed
420
                    if (adapterService != null) {
421 422 423
                        adapterService.connectOtherProfile(device,
                                                           AdapterService.PROFILE_CONN_REJECTED);
                    }
424 425 426 427
                }
                break;
            case HeadsetHalConstants.CONNECTION_STATE_CONNECTED:
                Log.w(TAG, "HFP Connected from Disconnected state");
Nitin Srivastava's avatar
Nitin Srivastava committed
428
                if (okToConnect(device)) {
429 430 431 432
                    Log.i(TAG,"Incoming Hf accepted");
                    broadcastConnectionState(device, BluetoothProfile.STATE_CONNECTED,
                                             BluetoothProfile.STATE_DISCONNECTED);
                    synchronized (HeadsetStateMachine.this) {
Nitin Srivastava's avatar
Nitin Srivastava committed
433 434 435 436 437
                        if (!mConnectedDevicesList.contains(device)) {
                            mConnectedDevicesList.add(device);
                            Log.d(TAG, "device " + device.getAddress() +
                                          " is adding in Disconnected state");
                        }
438 439 440
                        mCurrentDevice = device;
                        transitionTo(mConnected);
                    }
Nitin Srivastava's avatar
Nitin Srivastava committed
441
                    configAudioParameters(device);
442 443
                } else {
                    //reject the connection and stay in Disconnected state itself
444
                    Log.i(TAG,"Incoming Hf rejected. priority=" + mService.getPriority(device) +
445
                              " bondState=" + device.getBondState());
446
                    disconnectHfpNative(getByteAddress(device));
447
                    // the other profile connection should be initiated
448
                    AdapterService adapterService = AdapterService.getAdapterService();
Nitin Srivastava's avatar
Nitin Srivastava committed
449
                    if (adapterService != null) {
450 451 452
                        adapterService.connectOtherProfile(device,
                                                           AdapterService.PROFILE_CONN_REJECTED);
                    }
453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472
                }
                break;
            case HeadsetHalConstants.CONNECTION_STATE_DISCONNECTING:
                Log.w(TAG, "Ignore HF DISCONNECTING event, device: " + device);
                break;
            default:
                Log.e(TAG, "Incorrect state: " + state);
                break;
            }
        }
    }

    private class Pending extends State {
        @Override
        public void enter() {
            log("Enter Pending: " + getCurrentMessage().what);
        }

        @Override
        public boolean processMessage(Message message) {
Nitin Srivastava's avatar
Nitin Srivastava committed
473 474
            log("Pending process message: " + message.what + ", size: "
                                        + mConnectedDevicesList.size());
475 476 477 478

            boolean retValue = HANDLED;
            switch(message.what) {
                case CONNECT:
479
                case CONNECT_AUDIO:
480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503
                    deferMessage(message);
                    break;
                case CONNECT_TIMEOUT:
                    onConnectionStateChanged(HeadsetHalConstants.CONNECTION_STATE_DISCONNECTED,
                                             getByteAddress(mTargetDevice));
                    break;
                case DISCONNECT:
                    BluetoothDevice device = (BluetoothDevice) message.obj;
                    if (mCurrentDevice != null && mTargetDevice != null &&
                        mTargetDevice.equals(device) ) {
                        // cancel connection to the mTargetDevice
                        broadcastConnectionState(device, BluetoothProfile.STATE_DISCONNECTED,
                                       BluetoothProfile.STATE_CONNECTING);
                        synchronized (HeadsetStateMachine.this) {
                            mTargetDevice = null;
                        }
                    } else {
                        deferMessage(message);
                    }
                    break;
                case INTENT_BATTERY_CHANGED:
                    processIntentBatteryChanged((Intent) message.obj);
                    break;
                case CALL_STATE_CHANGED:
Syed Ibrahim M's avatar
Syed Ibrahim M committed
504 505
                    processCallState((HeadsetCallState) message.obj,
                        ((message.arg1 == 1)?true:false));
506 507 508
                    break;
                case STACK_EVENT:
                    StackEvent event = (StackEvent) message.obj;
509 510 511
                    if (DBG) {
                        log("event type: " + event.type);
                    }
512 513
                    switch (event.type) {
                        case EVENT_TYPE_CONNECTION_STATE_CHANGED:
Nitin Srivastava's avatar
Nitin Srivastava committed
514 515 516 517 518
                            BluetoothDevice device1 = getDeviceForMessage(CONNECT_TIMEOUT);
                            if (device1 != null && device1.equals(event.device)) {
                                Log.d(TAG, "remove connect timeout for device = " + device1);
                                removeMessages(CONNECT_TIMEOUT);
                            }
519 520 521 522 523 524 525 526 527 528 529 530 531 532 533
                            processConnectionEvent(event.valueInt, event.device);
                            break;
                        default:
                            Log.e(TAG, "Unexpected event: " + event.type);
                            break;
                    }
                    break;
                default:
                    return NOT_HANDLED;
            }
            return retValue;
        }

        // in Pending state
        private void processConnectionEvent(int state, BluetoothDevice device) {
Nitin Srivastava's avatar
Nitin Srivastava committed
534 535
            Log.d(TAG, "processConnectionEvent state = " + state +
                                              ", device = " + device);
536 537
            switch (state) {
                case HeadsetHalConstants.CONNECTION_STATE_DISCONNECTED:
Nitin Srivastava's avatar
Nitin Srivastava committed
538 539 540 541 542 543 544 545 546 547 548
                    if (mConnectedDevicesList.contains(device)) {

                        synchronized (HeadsetStateMachine.this) {
                            mConnectedDevicesList.remove(device);
                            mHeadsetAudioParam.remove(device);
                            mHeadsetBrsf.remove(device);
                            Log.d(TAG, "device " + device.getAddress() +
                                             " is removed in Pending state");
                        }

                        broadcastConnectionState(device,
549 550 551 552 553 554
                                                 BluetoothProfile.STATE_DISCONNECTED,
                                                 BluetoothProfile.STATE_DISCONNECTING);
                        synchronized (HeadsetStateMachine.this) {
                            mCurrentDevice = null;
                        }

555 556
                        processWBSEvent(0, device); /* disable WBS audio parameters */

557 558 559 560 561 562 563 564 565 566 567 568 569
                        if (mTargetDevice != null) {
                            if (!connectHfpNative(getByteAddress(mTargetDevice))) {
                                broadcastConnectionState(mTargetDevice,
                                                         BluetoothProfile.STATE_DISCONNECTED,
                                                         BluetoothProfile.STATE_CONNECTING);
                                synchronized (HeadsetStateMachine.this) {
                                    mTargetDevice = null;
                                    transitionTo(mDisconnected);
                                }
                            }
                        } else {
                            synchronized (HeadsetStateMachine.this) {
                                mIncomingDevice = null;
Nitin Srivastava's avatar
Nitin Srivastava committed
570 571 572 573 574 575
                                if (mConnectedDevicesList.size() == 0) {
                                    transitionTo(mDisconnected);
                                }
                                else {
                                    processMultiHFConnected(device);
                                }
576 577 578 579 580 581 582 583
                            }
                        }
                    } else if (mTargetDevice != null && mTargetDevice.equals(device)) {
                        // outgoing connection failed
                        broadcastConnectionState(mTargetDevice, BluetoothProfile.STATE_DISCONNECTED,
                                                 BluetoothProfile.STATE_CONNECTING);
                        synchronized (HeadsetStateMachine.this) {
                            mTargetDevice = null;
Nitin Srivastava's avatar
Nitin Srivastava committed
584 585 586 587 588 589 590
                            if (mConnectedDevicesList.size() == 0) {
                                transitionTo(mDisconnected);
                            }
                            else {
                                transitionTo(mConnected);
                            }

591 592 593 594 595 596 597
                        }
                    } else if (mIncomingDevice != null && mIncomingDevice.equals(device)) {
                        broadcastConnectionState(mIncomingDevice,
                                                 BluetoothProfile.STATE_DISCONNECTED,
                                                 BluetoothProfile.STATE_CONNECTING);
                        synchronized (HeadsetStateMachine.this) {
                            mIncomingDevice = null;
Nitin Srivastava's avatar
Nitin Srivastava committed
598 599 600 601 602 603
                            if (mConnectedDevicesList.size() == 0) {
                                transitionTo(mDisconnected);
                            }
                            else {
                                transitionTo(mConnected);
                            }
604 605 606 607 608
                        }
                    } else {
                        Log.e(TAG, "Unknown device Disconnected: " + device);
                    }
                    break;
Nitin Srivastava's avatar
Nitin Srivastava committed
609 610 611 612
                case HeadsetHalConstants.CONNECTION_STATE_CONNECTED:
                    if (mConnectedDevicesList.contains(device)) {
                         // disconnection failed
                         broadcastConnectionState(device, BluetoothProfile.STATE_CONNECTED,
613
                                             BluetoothProfile.STATE_DISCONNECTING);
Nitin Srivastava's avatar
Nitin Srivastava committed
614 615 616
                        if (mTargetDevice != null) {
                            broadcastConnectionState(mTargetDevice,
                                                 BluetoothProfile.STATE_DISCONNECTED,
617
                                                 BluetoothProfile.STATE_CONNECTING);
Nitin Srivastava's avatar
Nitin Srivastava committed
618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633
                        }
                        synchronized (HeadsetStateMachine.this) {
                            mTargetDevice = null;
                            transitionTo(mConnected);
                        }
                    } else if (mTargetDevice != null && mTargetDevice.equals(device)) {

                        synchronized (HeadsetStateMachine.this) {
                            mCurrentDevice = device;
                            mConnectedDevicesList.add(device);
                            Log.d(TAG, "device " + device.getAddress() +
                                         " is added in Pending state");
                            mTargetDevice = null;
                            transitionTo(mConnected);
                        }
                        broadcastConnectionState(device, BluetoothProfile.STATE_CONNECTED,
634
                                             BluetoothProfile.STATE_CONNECTING);
Nitin Srivastava's avatar
Nitin Srivastava committed
635 636 637 638 639 640 641 642 643 644 645 646
                        configAudioParameters(device);
                    } else if (mIncomingDevice != null && mIncomingDevice.equals(device)) {

                        synchronized (HeadsetStateMachine.this) {
                            mCurrentDevice = device;
                            mConnectedDevicesList.add(device);
                            Log.d(TAG, "device " + device.getAddress() +
                                             " is added in Pending state");
                            mIncomingDevice = null;
                            transitionTo(mConnected);
                        }
                        broadcastConnectionState(device, BluetoothProfile.STATE_CONNECTED,
647
                                             BluetoothProfile.STATE_CONNECTING);
Nitin Srivastava's avatar
Nitin Srivastava committed
648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674
                        configAudioParameters(device);
                    } else {
                        Log.w(TAG, "Some other incoming HF connected in Pending state");
                        if (okToConnect(device)) {
                            Log.i(TAG,"Incoming Hf accepted");
                            broadcastConnectionState(device, BluetoothProfile.STATE_CONNECTED,
                                                     BluetoothProfile.STATE_DISCONNECTED);
                            synchronized (HeadsetStateMachine.this) {
                                mCurrentDevice = device;
                                mConnectedDevicesList.add(device);
                                Log.d(TAG, "device " + device.getAddress() +
                                             " is added in Pending state");
                            }
                            configAudioParameters(device);
                        } else {
                            //reject the connection and stay in Pending state itself
                            Log.i(TAG,"Incoming Hf rejected. priority=" +
                                mService.getPriority(device) + " bondState=" +
                                               device.getBondState());
                            disconnectHfpNative(getByteAddress(device));
                            // the other profile connection should be initiated
                            AdapterService adapterService = AdapterService.getAdapterService();
                            if (adapterService != null) {
                                adapterService.connectOtherProfile(device,
                                         AdapterService.PROFILE_CONN_REJECTED);
                            }
                        }
675
                    }
Nitin Srivastava's avatar
Nitin Srivastava committed
676 677 678 679 680 681 682 683 684 685 686 687
                    break;
                case HeadsetHalConstants.CONNECTION_STATE_CONNECTING:
                    if ((mCurrentDevice != null) && mCurrentDevice.equals(device)) {
                        log("current device tries to connect back");
                        // TODO(BT) ignore or reject
                    } else if (mTargetDevice != null && mTargetDevice.equals(device)) {
                        // The stack is connecting to target device or
                        // there is an incoming connection from the target device at the same time
                        // we already broadcasted the intent, doing nothing here
                        if (DBG) {
                            log("Stack and target device are connecting");
                        }
688
                    }
Nitin Srivastava's avatar
Nitin Srivastava committed
689 690 691 692 693 694
                    else if (mIncomingDevice != null && mIncomingDevice.equals(device)) {
                        Log.e(TAG, "Another connecting event on the incoming device");
                    } else {
                        // We get an incoming connecting request while Pending
                        // TODO(BT) is stack handing this case? let's ignore it for now
                        log("Incoming connection while pending, ignore");
695
                    }
Nitin Srivastava's avatar
Nitin Srivastava committed
696 697 698 699 700 701 702 703 704 705 706 707 708
                    break;
                case HeadsetHalConstants.CONNECTION_STATE_DISCONNECTING:
                    if ((mCurrentDevice != null) && mCurrentDevice.equals(device)) {
                        // we already broadcasted the intent, doing nothing here
                        if (DBG) {
                            log("stack is disconnecting mCurrentDevice");
                        }
                    } else if (mTargetDevice != null && mTargetDevice.equals(device)) {
                        Log.e(TAG, "TargetDevice is getting disconnected");
                    } else if (mIncomingDevice != null && mIncomingDevice.equals(device)) {
                        Log.e(TAG, "IncomingDevice is getting disconnected");
                    } else {
                        Log.e(TAG, "Disconnecting unknow device: " + device);
709
                    }
Nitin Srivastava's avatar
Nitin Srivastava committed
710 711 712 713
                    break;
                default:
                    Log.e(TAG, "Incorrect state: " + state);
                    break;
714 715 716
            }
        }

Nitin Srivastava's avatar
Nitin Srivastava committed
717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732
        private void processMultiHFConnected(BluetoothDevice device) {
            log("Pending state: processMultiHFConnected");
            /* Assign the current activedevice again if the disconnected
                         device equals to the current active device*/
            if (mCurrentDevice != null && mCurrentDevice.equals(device)) {
                transitionTo(mConnected);
                int deviceSize = mConnectedDevicesList.size();
                mCurrentDevice = mConnectedDevicesList.get(deviceSize-1);
            } else {
                // The disconnected device is not current active device
                if (mAudioState == BluetoothHeadset.STATE_AUDIO_CONNECTED)
                    transitionTo(mAudioOn);
                else transitionTo(mConnected);
            }
            log("processMultiHFConnected , the latest mCurrentDevice is:"
                                             + mCurrentDevice);
733 734 735 736
            log("Pending state: processMultiHFConnected ," +
                           "fake broadcasting for mCurrentDevice");
            broadcastConnectionState(mCurrentDevice, BluetoothProfile.STATE_CONNECTED,
                                         BluetoothProfile.STATE_DISCONNECTED);
Nitin Srivastava's avatar
Nitin Srivastava committed
737
        }
738 739 740 741 742
    }

    private class Connected extends State {
        @Override
        public void enter() {
Nitin Srivastava's avatar
Nitin Srivastava committed
743 744
            log("Enter Connected: " + getCurrentMessage().what +
                           ", size: " + mConnectedDevicesList.size());
745 746 747 748 749
            // start phone state listener here so that the CIND response as part of SLC can be
            // responded to, correctly.
            // we may enter Connected from Disconnected/Pending/AudioOn. listenForPhoneState
            // internally handles multiple calls to start listen
            mPhoneState.listenForPhoneState(true);
750 751 752 753
        }

        @Override
        public boolean processMessage(Message message) {
Nitin Srivastava's avatar
Nitin Srivastava committed
754 755
            log("Connected process message: " + message.what +
                          ", size: " + mConnectedDevicesList.size());
756
            if (DBG) {
Nitin Srivastava's avatar
Nitin Srivastava committed
757 758
                if (mConnectedDevicesList.size() == 0) {
                    log("ERROR: mConnectedDevicesList is empty in Connected");
759 760 761 762 763 764 765 766 767
                    return NOT_HANDLED;
                }
            }

            boolean retValue = HANDLED;
            switch(message.what) {
                case CONNECT:
                {
                    BluetoothDevice device = (BluetoothDevice) message.obj;
Nitin Srivastava's avatar
Nitin Srivastava committed
768
                    if (device == null) {
769 770 771
                        break;
                    }

Nitin Srivastava's avatar
Nitin Srivastava committed
772 773
                    if (mConnectedDevicesList.contains(device)) {
                        Log.e(TAG, "ERROR: Connect received for already connected device, Ignore");
774 775 776
                        break;
                    }

Nitin Srivastava's avatar
Nitin Srivastava committed
777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819
                   if (mConnectedDevicesList.size() >= max_hf_connections) {
                       BluetoothDevice DisconnectConnectedDevice = null;
                       IState CurrentAudioState = getCurrentState();
                       Log.d(TAG, "Reach to max size, disconnect one of them first");
                       /* TODO: Disconnect based on CoD */
                       DisconnectConnectedDevice = mConnectedDevicesList.get(0);

                       broadcastConnectionState(device, BluetoothProfile.STATE_CONNECTING,
                                   BluetoothProfile.STATE_DISCONNECTED);

                       if (!disconnectHfpNative(getByteAddress(DisconnectConnectedDevice))) {
                           broadcastConnectionState(device, BluetoothProfile.STATE_DISCONNECTED,
                                       BluetoothProfile.STATE_CONNECTING);
                           break;
                       } else {
                           broadcastConnectionState(DisconnectConnectedDevice,
                                       BluetoothProfile.STATE_DISCONNECTING,
                                       BluetoothProfile.STATE_CONNECTED);
                       }

                       synchronized (HeadsetStateMachine.this) {
                           mTargetDevice = device;
                           if (max_hf_connections == 1) {
                               transitionTo(mPending);
                           } else {
                               mMultiDisconnectDevice = DisconnectConnectedDevice;
                               transitionTo(mMultiHFPending);
                           }
                           DisconnectConnectedDevice = null;
                       }
                    }else if (mConnectedDevicesList.size() < max_hf_connections) {
                       broadcastConnectionState(device, BluetoothProfile.STATE_CONNECTING,
                         BluetoothProfile.STATE_DISCONNECTED);
                       if (!connectHfpNative(getByteAddress(device))) {
                           broadcastConnectionState(device, BluetoothProfile.STATE_DISCONNECTED,
                               BluetoothProfile.STATE_CONNECTING);
                           break;
                       }
                       synchronized (HeadsetStateMachine.this) {
                           mTargetDevice = device;
                           // Transtion to MultiHFPending state for Multi HF connection
                           transitionTo(mMultiHFPending);
                       }
820
                    }
Nitin Srivastava's avatar
Nitin Srivastava committed
821 822 823
                    Message m = obtainMessage(CONNECT_TIMEOUT);
                    m.obj = device;
                    sendMessageDelayed(m, 30000);
824 825 826 827 828
                }
                    break;
                case DISCONNECT:
                {
                    BluetoothDevice device = (BluetoothDevice) message.obj;
Nitin Srivastava's avatar
Nitin Srivastava committed
829
                    if (!mConnectedDevicesList.contains(device)) {
830 831 832 833 834 835 836 837 838
                        break;
                    }
                    broadcastConnectionState(device, BluetoothProfile.STATE_DISCONNECTING,
                                   BluetoothProfile.STATE_CONNECTED);
                    if (!disconnectHfpNative(getByteAddress(device))) {
                        broadcastConnectionState(device, BluetoothProfile.STATE_CONNECTED,
                                       BluetoothProfile.STATE_DISCONNECTED);
                        break;
                    }
Nitin Srivastava's avatar
Nitin Srivastava committed
839 840 841 842 843 844 845

                    if (mConnectedDevicesList.size() > 1) {
                        mMultiDisconnectDevice = device;
                        transitionTo(mMultiHFPending);
                    } else {
                        transitionTo(mPending);
                    }
846 847 848
                }
                    break;
                case CONNECT_AUDIO:
Nitin Srivastava's avatar
Nitin Srivastava committed
849 850
                {
                    BluetoothDevice device = mCurrentDevice;
851 852
                    // TODO(BT) when failure, broadcast audio connecting to disconnected intent
                    //          check if device matches mCurrentDevice
Nitin Srivastava's avatar
Nitin Srivastava committed
853 854 855 856 857 858 859
                    if (mActiveScoDevice != null) {
                        log("connectAudioNative in Connected; mActiveScoDevice is not null");
                        device = mActiveScoDevice;
                    }
                    log("connectAudioNative in Connected for device = " + device);
                    connectAudioNative(getByteAddress(device));
                }
860 861
                    break;
                case VOICE_RECOGNITION_START:
862 863 864 865
                    processLocalVrEvent(HeadsetHalConstants.VR_STATE_STARTED);
                    break;
                case VOICE_RECOGNITION_STOP:
                    processLocalVrEvent(HeadsetHalConstants.VR_STATE_STOPPED);
866 867
                    break;
                case CALL_STATE_CHANGED:
Syed Ibrahim M's avatar
Syed Ibrahim M committed
868
                    processCallState((HeadsetCallState) message.obj, ((message.arg1==1)?true:false));
869 870 871 872 873 874 875 876 877 878
                    break;
                case INTENT_BATTERY_CHANGED:
                    processIntentBatteryChanged((Intent) message.obj);
                    break;
                case DEVICE_STATE_CHANGED:
                    processDeviceStateChanged((HeadsetDeviceState) message.obj);
                    break;
                case SEND_CCLC_RESPONSE:
                    processSendClccResponse((HeadsetClccResponse) message.obj);
                    break;
Nitin Srivastava's avatar
Nitin Srivastava committed
879 880 881 882 883 884
                case CLCC_RSP_TIMEOUT:
                {
                    BluetoothDevice device = (BluetoothDevice) message.obj;
                    clccResponseNative(0, 0, 0, 0, false, "", 0, getByteAddress(device));
                }
                    break;
885 886 887 888
                case SEND_VENDOR_SPECIFIC_RESULT_CODE:
                    processSendVendorSpecificResultCode(
                            (HeadsetVendorSpecificResultCode) message.obj);
                    break;
889
                case DIALING_OUT_TIMEOUT:
Nitin Srivastava's avatar
Nitin Srivastava committed
890 891
                {
                    BluetoothDevice device = (BluetoothDevice) message.obj;
892 893
                    if (mDialingOut) {
                        mDialingOut= false;
Nitin Srivastava's avatar
Nitin Srivastava committed
894 895
                        atResponseCodeNative(HeadsetHalConstants.AT_RESPONSE_ERROR,
                                                   0, getByteAddress(device));
896
                    }
Nitin Srivastava's avatar
Nitin Srivastava committed
897
                }
898
                    break;
Syed Ibrahim M's avatar
Syed Ibrahim M committed
899 900 901 902 903 904
                case VIRTUAL_CALL_START:
                    initiateScoUsingVirtualVoiceCall();
                    break;
                case VIRTUAL_CALL_STOP:
                    terminateScoUsingVirtualVoiceCall();
                    break;
905 906 907 908 909 910 911 912 913 914 915 916
                case ENABLE_WBS:
                {
                    BluetoothDevice device = (BluetoothDevice) message.obj;
                    configureWBSNative(getByteAddress(device),WBS_CODEC);
                }
                    break;
                case DISABLE_WBS:
                {
                    BluetoothDevice device = (BluetoothDevice) message.obj;
                    configureWBSNative(getByteAddress(device),NBS_CODEC);
                }
                    break;
917
                case START_VR_TIMEOUT:
Nitin Srivastava's avatar
Nitin Srivastava committed
918 919
                {
                    BluetoothDevice device = (BluetoothDevice) message.obj;
920
                    if (mWaitingForVoiceRecognition) {
Nitin Srivastava's avatar
Nitin Srivastava committed
921
                        device = (BluetoothDevice) message.obj;
922 923
                        mWaitingForVoiceRecognition = false;
                        Log.e(TAG, "Timeout waiting for voice recognition to start");
Nitin Srivastava's avatar
Nitin Srivastava committed
924 925
                        atResponseCodeNative(HeadsetHalConstants.AT_RESPONSE_ERROR,
                                                   0, getByteAddress(device));
926
                    }
Nitin Srivastava's avatar
Nitin Srivastava committed
927
                }
928
                    break;
929 930
                case STACK_EVENT:
                    StackEvent event = (StackEvent) message.obj;
931
                    if (DBG) {
Nitin Srivastava's avatar
Nitin Srivastava committed
932 933
                        log("event type: " + event.type + "event device : "
                                                  + event.device);
934
                    }
935 936 937 938 939 940 941
                    switch (event.type) {
                        case EVENT_TYPE_CONNECTION_STATE_CHANGED:
                            processConnectionEvent(event.valueInt, event.device);
                            break;
                        case EVENT_TYPE_AUDIO_STATE_CHANGED:
                            processAudioEvent(event.valueInt, event.device);
                            break;
942
                        case EVENT_TYPE_VR_STATE_CHANGED:
Nitin Srivastava's avatar
Nitin Srivastava committed
943
                            processVrEvent(event.valueInt, event.device);
944
                            break;
945 946
                        case EVENT_TYPE_ANSWER_CALL:
                            // TODO(BT) could answer call happen on Connected state?
Nitin Srivastava's avatar
Nitin Srivastava committed
947
                            processAnswerCall(event.device);
948 949 950
                            break;
                        case EVENT_TYPE_HANGUP_CALL:
                            // TODO(BT) could hangup call happen on Connected state?
Nitin Srivastava's avatar
Nitin Srivastava committed
951
                            processHangupCall(event.device);
952 953
                            break;
                        case EVENT_TYPE_VOLUME_CHANGED:
Nitin Srivastava's avatar
Nitin Srivastava committed
954 955
                            processVolumeEvent(event.valueInt, event.valueInt2,
                                                        event.device);
956 957
                            break;
                        case EVENT_TYPE_DIAL_CALL:
Nitin Srivastava's avatar
Nitin Srivastava committed
958
                            processDialCall(event.valueString, event.device);
959 960
                            break;
                        case EVENT_TYPE_SEND_DTMF:
Nitin Srivastava's avatar
Nitin Srivastava committed
961
                            processSendDtmf(event.valueInt, event.device);
962
                            break;
963
                        case EVENT_TYPE_NOICE_REDUCTION:
Nitin Srivastava's avatar
Nitin Srivastava committed
964
                            processNoiceReductionEvent(event.valueInt, event.device);
965
                            break;
966 967 968 969
                        case EVENT_TYPE_WBS:
                            Log.d(TAG, "EVENT_TYPE_WBS codec is "+event.valueInt);
                            processWBSEvent(event.valueInt, event.device);
                            break;
970
                        case EVENT_TYPE_AT_CHLD:
Nitin Srivastava's avatar
Nitin Srivastava committed
971
                            processAtChld(event.valueInt, event.device);
972 973
                            break;
                        case EVENT_TYPE_SUBSCRIBER_NUMBER_REQUEST:
Nitin Srivastava's avatar
Nitin Srivastava committed
974
                            processSubscriberNumberRequest(event.device);
975 976
                            break;
                        case EVENT_TYPE_AT_CIND:
Nitin Srivastava's avatar
Nitin Srivastava committed
977
                            processAtCind(event.device);
978 979
                            break;
                        case EVENT_TYPE_AT_COPS:
Nitin Srivastava's avatar
Nitin Srivastava committed
980
                            processAtCops(event.device);
981 982
                            break;
                        case EVENT_TYPE_AT_CLCC:
Nitin Srivastava's avatar
Nitin Srivastava committed
983
                            processAtClcc(event.device);
984 985
                            break;
                        case EVENT_TYPE_UNKNOWN_AT:
Nitin Srivastava's avatar
Nitin Srivastava committed
986
                            processUnknownAt(event.valueString, event.device);
987 988
                            break;
                        case EVENT_TYPE_KEY_PRESSED:
Nitin Srivastava's avatar
Nitin Srivastava committed
989
                            processKeyPressed(event.device);
990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003
                            break;
                        default:
                            Log.e(TAG, "Unknown stack event: " + event.type);
                            break;
                    }
                    break;
                default:
                    return NOT_HANDLED;
            }
            return retValue;
        }

        // in Connected state
        private void processConnectionEvent(int state, BluetoothDevice device) {
Nitin Srivastava's avatar
Nitin Srivastava committed
1004 1005
        Log.d(TAG, "processConnectionEvent state = " + state + ", device = "
                                                           + device);
1006 1007
            switch (state) {
                case HeadsetHalConstants.CONNECTION_STATE_DISCONNECTED:
Nitin Srivastava's avatar
Nitin Srivastava committed
1008
                    if (mConnectedDevicesList.contains(device)) {
1009
                        processWBSEvent(0, device); /* disable WBS audio parameters */
1010
                        synchronized (HeadsetStateMachine.this) {
Nitin Srivastava's avatar
Nitin Srivastava committed
1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023
                            mConnectedDevicesList.remove(device);
                            mHeadsetAudioParam.remove(device);
                            mHeadsetBrsf.remove(device);
                            Log.d(TAG, "device " + device.getAddress() +
                                         " is removed in Connected state");

                            if (mConnectedDevicesList.size() == 0) {
                                mCurrentDevice = null;
                                transitionTo(mDisconnected);
                            }
                            else {
                                processMultiHFConnected(device);
                            }
1024
                        }
1025 1026
                        broadcastConnectionState(device, BluetoothProfile.STATE_DISCONNECTED,
                                                 BluetoothProfile.STATE_CONNECTED);
1027 1028 1029 1030
                    } else {
                        Log.e(TAG, "Disconnected from unknown device: " + device);
                    }
                    break;
1031 1032 1033
                case HeadsetHalConstants.CONNECTION_STATE_SLC_CONNECTED:
                    processSlcConnected();
                    break;
Nitin Srivastava's avatar
Nitin Srivastava committed
1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070
                case HeadsetHalConstants.CONNECTION_STATE_CONNECTED:
                    if (mConnectedDevicesList.contains(device)) {
                        mIncomingDevice = null;
                        mTargetDevice = null;
                        break;
                    }
                    Log.w(TAG, "HFP to be Connected in Connected state");
                    if (okToConnect(device) && (mConnectedDevicesList.size()
                                                       < max_hf_connections)) {
                        Log.i(TAG,"Incoming Hf accepted");
                        broadcastConnectionState(device, BluetoothProfile.STATE_CONNECTED,
                                          BluetoothProfile.STATE_DISCONNECTED);
                        synchronized (HeadsetStateMachine.this) {
                            if(!mConnectedDevicesList.contains(device)) {
                                mCurrentDevice = device;
                                mConnectedDevicesList.add(device);
                                Log.d(TAG, "device " + device.getAddress() +
                                             " is added in Connected state");
                            }
                            transitionTo(mConnected);
                        }
                        configAudioParameters(device);
                    } else {
                        // reject the connection and stay in Connected state itself
                        Log.i(TAG,"Incoming Hf rejected. priority=" +
                               mService.getPriority(device) + " bondState=" +
                                        device.getBondState());
                        disconnectHfpNative(getByteAddress(device));
                        // the other profile connection should be initiated
                        AdapterService adapterService = AdapterService.getAdapterService();
                        if (adapterService != null) {
                            adapterService.connectOtherProfile(device,
                                                        AdapterService.PROFILE_CONN_REJECTED);
                        }
                    }
                    break;
                default:
1071
                  Log.e(TAG, "Connection State Device: " + device + " bad state: " + state);
Nitin Srivastava's avatar
Nitin Srivastava committed
1072
                    break;
1073 1074 1075 1076 1077
            }
        }

        // in Connected state
        private void processAudioEvent(int state, BluetoothDevice device) {
Nitin Srivastava's avatar
Nitin Srivastava committed
1078
            if (!mConnectedDevicesList.contains(device)) {
1079 1080 1081 1082 1083 1084
                Log.e(TAG, "Audio changed on disconnected device: " + device);
                return;
            }

            switch (state) {
                case HeadsetHalConstants.AUDIO_STATE_CONNECTED:
1085 1086 1087 1088 1089 1090
                    if (!isScoAcceptable()) {
                        Log.e(TAG,"Audio Connected without any listener");
                        disconnectAudioNative(getByteAddress(device));
                        break;
                    }

1091 1092
                    // TODO(BT) should I save the state for next broadcast as the prevState?
                    mAudioState = BluetoothHeadset.STATE_AUDIO_CONNECTED;
Nitin Srivastava's avatar
Nitin Srivastava committed
1093
                    setAudioParameters(device); /*Set proper Audio Paramters.*/
1094 1095 1096
                    mAudioManager.setBluetoothScoOn(true);
                    broadcastAudioState(device, BluetoothHeadset.STATE_AUDIO_CONNECTED,
                                        BluetoothHeadset.STATE_AUDIO_CONNECTING);
Nitin Srivastava's avatar
Nitin Srivastava committed
1097
                    mActiveScoDevice = device;
1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110
                    transitionTo(mAudioOn);
                    break;
                case HeadsetHalConstants.AUDIO_STATE_CONNECTING:
                    mAudioState = BluetoothHeadset.STATE_AUDIO_CONNECTING;
                    broadcastAudioState(device, BluetoothHeadset.STATE_AUDIO_CONNECTING,
                                        BluetoothHeadset.STATE_AUDIO_DISCONNECTED);
                    break;
                    // TODO(BT) process other states
                default:
                    Log.e(TAG, "Audio State Device: " + device + " bad state: " + state);
                    break;
            }
        }
1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123

        private void processSlcConnected() {
            if (mPhoneProxy != null) {
                try {
                    mPhoneProxy.queryPhoneState();
                } catch (RemoteException e) {
                    Log.e(TAG, Log.getStackTraceString(new Throwable()));
                }
            } else {
                Log.e(TAG, "Handsfree phone proxy null for query phone state");
            }

        }
Nitin Srivastava's avatar
Nitin Srivastava committed
1124 1125 1126

        private void processMultiHFConnected(BluetoothDevice device) {
            log("Connect state: processMultiHFConnected");
1127 1128 1129 1130
            if (mActiveScoDevice != null && mActiveScoDevice.equals(device)) {
                log ("mActiveScoDevice is disconnected, setting it to null");
                mActiveScoDevice = null;
            }
Nitin Srivastava's avatar
Nitin Srivastava committed
1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142
            /* Assign the current activedevice again if the disconnected
                         device equals to the current active device */
            if (mCurrentDevice != null && mCurrentDevice.equals(device)) {
                transitionTo(mConnected);
                int deviceSize = mConnectedDevicesList.size();
                mCurrentDevice = mConnectedDevicesList.get(deviceSize-1);
            } else {
                // The disconnected device is not current active device
                transitionTo(mConnected);
            }
            log("processMultiHFConnected , the latest mCurrentDevice is:" +
                                     mCurrentDevice);
1143 1144 1145 1146
            log("Connect state: processMultiHFConnected ," +
                       "fake broadcasting for mCurrentDevice");
            broadcastConnectionState(mCurrentDevice, BluetoothProfile.STATE_CONNECTED,
                            BluetoothProfile.STATE_DISCONNECTED);
Nitin Srivastava's avatar
Nitin Srivastava committed
1147
        }
1148 1149 1150 1151 1152 1153
    }

    private class AudioOn extends State {

        @Override
        public void enter() {
Nitin Srivastava's avatar
Nitin Srivastava committed
1154 1155
            log("Enter AudioOn: " + getCurrentMessage().what + ", size: " +
                                  mConnectedDevicesList.size());
1156 1157 1158 1159
        }

        @Override
        public boolean processMessage(Message message) {
Nitin Srivastava's avatar
Nitin Srivastava committed
1160 1161
            log("AudioOn process message: " + message.what + ", size: " +
                                  mConnectedDevicesList.size());
1162
            if (DBG) {
Nitin Srivastava's avatar
Nitin Srivastava committed
1163 1164
                if (mConnectedDevicesList.size() == 0) {
                    log("ERROR: mConnectedDevicesList is empty in AudioOn");
1165 1166 1167 1168 1169 1170
                    return NOT_HANDLED;
                }
            }

            boolean retValue = HANDLED;
            switch(message.what) {
Nitin Srivastava's avatar
Nitin Srivastava committed
1171
                case CONNECT:
1172 1173
                {
                    BluetoothDevice device = (BluetoothDevice) message.obj;
Nitin Srivastava's avatar
Nitin Srivastava committed
1174
                    if (device == null) {
1175 1176
                        break;
                    }
Nitin Srivastava's avatar
Nitin Srivastava committed
1177 1178 1179 1180 1181

                    if (mConnectedDevicesList.contains(device)) {
                        break;
                    }

1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192
                    if (max_hf_connections == 1) {
                        deferMessage(obtainMessage(DISCONNECT, mCurrentDevice));
                        deferMessage(obtainMessage(CONNECT, device));
                        if (disconnectAudioNative(getByteAddress(mCurrentDevice))) {
                            Log.d(TAG, "Disconnecting SCO audio for device = " + mCurrentDevice);
                        } else {
                            Log.e(TAG, "disconnectAudioNative failed");
                        }
                        break;
                    }

Nitin Srivastava's avatar
Nitin Srivastava committed
1193 1194 1195 1196 1197 1198 1199
                    if (mConnectedDevicesList.size() >= max_hf_connections) {
                        BluetoothDevice DisconnectConnectedDevice = null;
                        IState CurrentAudioState = getCurrentState();
                        Log.d(TAG, "Reach to max size, disconnect " +
                                           "one of them first");
                        DisconnectConnectedDevice = mConnectedDevicesList.get(0);

1200
                        if (mActiveScoDevice.equals(DisconnectConnectedDevice)) {
Nitin Srivastava's avatar
Nitin Srivastava committed
1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218
                           DisconnectConnectedDevice = mConnectedDevicesList.get(1);
                        }

                        broadcastConnectionState(device, BluetoothProfile.STATE_CONNECTING,
                                   BluetoothProfile.STATE_DISCONNECTED);

                        if (!disconnectHfpNative(getByteAddress(DisconnectConnectedDevice))) {
                            broadcastConnectionState(device, BluetoothProfile.STATE_DISCONNECTED,
                                           BluetoothProfile.STATE_CONNECTING);
                            break;
                        } else {
                            broadcastConnectionState(DisconnectConnectedDevice,
                                       BluetoothProfile.STATE_DISCONNECTING,
                                       BluetoothProfile.STATE_CONNECTED);
                        }

                        synchronized (HeadsetStateMachine.this) {
                            mTargetDevice = device;
1219 1220
                            mMultiDisconnectDevice = DisconnectConnectedDevice;
                            transitionTo(mMultiHFPending);
Nitin Srivastava's avatar
Nitin Srivastava committed
1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284
                            DisconnectConnectedDevice = null;
                        }
                    } else if(mConnectedDevicesList.size() < max_hf_connections) {
                        broadcastConnectionState(device, BluetoothProfile.STATE_CONNECTING,
                        BluetoothProfile.STATE_DISCONNECTED);
                        if (!connectHfpNative(getByteAddress(device))) {
                            broadcastConnectionState(device, BluetoothProfile.STATE_DISCONNECTED,
                                BluetoothProfile.STATE_CONNECTING);
                            break;
                        }
                        synchronized (HeadsetStateMachine.this) {
                            mTargetDevice = device;
                            // Transtion to MultilHFPending state for Multi handsfree connection
                            transitionTo(mMultiHFPending);
                        }
                    }
                    Message m = obtainMessage(CONNECT_TIMEOUT);
                    m.obj = device;
                    sendMessageDelayed(m, 30000);
                }
                break;
                case CONNECT_TIMEOUT:
                    onConnectionStateChanged(HeadsetHalConstants.CONNECTION_STATE_DISCONNECTED,
                                             getByteAddress(mTargetDevice));
                break;
                case DISCONNECT:
                {
                    BluetoothDevice device = (BluetoothDevice)message.obj;
                    if (!mConnectedDevicesList.contains(device)) {
                        break;
                    }
                    if (mActiveScoDevice != null && mActiveScoDevice.equals(device)) {
                        // The disconnected device is active SCO device
                        Log.d(TAG, "AudioOn, the disconnected device" +
                                            "is active SCO device");
                        deferMessage(obtainMessage(DISCONNECT, message.obj));
                        // Disconnect BT SCO first
                        if (disconnectAudioNative(getByteAddress(mActiveScoDevice))) {
                            log("Disconnecting SCO audio");
                        } else {
                            // if disconnect BT SCO failed, transition to mConnected state
                            transitionTo(mConnected);
                        }
                    } else {
                        /* Do not disconnect BT SCO if the disconnected
                           device is not active SCO device */
                        Log.d(TAG, "AudioOn, the disconnected device" +
                                        "is not active SCO device");
                        broadcastConnectionState(device, BluetoothProfile.STATE_DISCONNECTING,
                                   BluetoothProfile.STATE_CONNECTED);
                        // Should be still in AudioOn state
                        if (!disconnectHfpNative(getByteAddress(device))) {
                            Log.w(TAG, "AudioOn, disconnect device failed");
                            broadcastConnectionState(device, BluetoothProfile.STATE_CONNECTED,
                                       BluetoothProfile.STATE_DISCONNECTING);
                            break;
                        }
                        /* Transtion to MultiHFPending state for Multi
                           handsfree connection */
                        if (mConnectedDevicesList.size() > 1) {
                            mMultiDisconnectDevice = device;
                            transitionTo(mMultiHFPending);
                        }
                    }
1285
                }
Nitin Srivastava's avatar
Nitin Srivastava committed
1286
                break;
1287
                case DISCONNECT_AUDIO:
Nitin Srivastava's avatar
Nitin Srivastava committed
1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304
                    if (mActiveScoDevice != null) {
                        if (disconnectAudioNative(getByteAddress(mActiveScoDevice))) {
                            log("Disconnecting SCO audio for device = " +
                                                 mActiveScoDevice);
                        } else {
                            Log.e(TAG, "disconnectAudioNative failed" +
                                      "for device = " + mActiveScoDevice);
                        }
                    }
                    break;
                case VOICE_RECOGNITION_START:
                    processLocalVrEvent(HeadsetHalConstants.VR_STATE_STARTED);
                    break;
                case VOICE_RECOGNITION_STOP:
                    processLocalVrEvent(HeadsetHalConstants.VR_STATE_STOPPED);
                    break;
                case INTENT_SCO_VOLUME_CHANGED:
1305 1306 1307
                    if (mActiveScoDevice != null) {
                        processIntentScoVolume((Intent) message.obj, mActiveScoDevice);
                    }
Nitin Srivastava's avatar
Nitin Srivastava committed
1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451
                    break;
                case CALL_STATE_CHANGED:
                    processCallState((HeadsetCallState) message.obj, ((message.arg1 == 1)?true:false));
                    break;
                case INTENT_BATTERY_CHANGED:
                    processIntentBatteryChanged((Intent) message.obj);
                    break;
                case DEVICE_STATE_CHANGED:
                    processDeviceStateChanged((HeadsetDeviceState) message.obj);
                    break;
                case SEND_CCLC_RESPONSE:
                    processSendClccResponse((HeadsetClccResponse) message.obj);
                    break;
                case CLCC_RSP_TIMEOUT:
                {
                    BluetoothDevice device = (BluetoothDevice) message.obj;
                    clccResponseNative(0, 0, 0, 0, false, "", 0, getByteAddress(device));
                }
                    break;
                case SEND_VENDOR_SPECIFIC_RESULT_CODE:
                    processSendVendorSpecificResultCode(
                            (HeadsetVendorSpecificResultCode) message.obj);
                    break;

                case VIRTUAL_CALL_START:
                    initiateScoUsingVirtualVoiceCall();
                    break;
                case VIRTUAL_CALL_STOP:
                    terminateScoUsingVirtualVoiceCall();
                    break;

                case DIALING_OUT_TIMEOUT:
                {
                    if (mDialingOut) {
                        BluetoothDevice device = (BluetoothDevice)message.obj;
                        mDialingOut= false;
                        atResponseCodeNative(HeadsetHalConstants.AT_RESPONSE_ERROR,
                                               0, getByteAddress(device));
                    }
                }
                    break;
                case START_VR_TIMEOUT:
                {
                    if (mWaitingForVoiceRecognition) {
                        BluetoothDevice device = (BluetoothDevice)message.obj;
                        mWaitingForVoiceRecognition = false;
                        Log.e(TAG, "Timeout waiting for voice recognition" +
                                                     "to start");
                        atResponseCodeNative(HeadsetHalConstants.AT_RESPONSE_ERROR,
                                               0, getByteAddress(device));
                    }
                }
                    break;
                case STACK_EVENT:
                    StackEvent event = (StackEvent) message.obj;
                    if (DBG) {
                        log("event type: " + event.type);
                    }
                    switch (event.type) {
                        case EVENT_TYPE_CONNECTION_STATE_CHANGED:
                            BluetoothDevice device1 = getDeviceForMessage(CONNECT_TIMEOUT);
                            if (device1 != null && device1.equals(event.device)) {
                                Log.d(TAG, "remove connect timeout for device = " + device1);
                                removeMessages(CONNECT_TIMEOUT);
                            }
                            processConnectionEvent(event.valueInt, event.device);
                            break;
                        case EVENT_TYPE_AUDIO_STATE_CHANGED:
                            processAudioEvent(event.valueInt, event.device);
                            break;
                        case EVENT_TYPE_VR_STATE_CHANGED:
                            processVrEvent(event.valueInt, event.device);
                            break;
                        case EVENT_TYPE_ANSWER_CALL:
                            processAnswerCall(event.device);
                            break;
                        case EVENT_TYPE_HANGUP_CALL:
                            processHangupCall(event.device);
                            break;
                        case EVENT_TYPE_VOLUME_CHANGED:
                            processVolumeEvent(event.valueInt, event.valueInt2,
                                                     event.device);
                            break;
                        case EVENT_TYPE_DIAL_CALL:
                            processDialCall(event.valueString, event.device);
                            break;
                        case EVENT_TYPE_SEND_DTMF:
                            processSendDtmf(event.valueInt, event.device);
                            break;
                        case EVENT_TYPE_NOICE_REDUCTION:
                            processNoiceReductionEvent(event.valueInt, event.device);
                            break;
                        case EVENT_TYPE_AT_CHLD:
                            processAtChld(event.valueInt, event.device);
                            break;
                        case EVENT_TYPE_SUBSCRIBER_NUMBER_REQUEST:
                            processSubscriberNumberRequest(event.device);
                            break;
                        case EVENT_TYPE_AT_CIND:
                            processAtCind(event.device);
                            break;
                        case EVENT_TYPE_AT_COPS:
                            processAtCops(event.device);
                            break;
                        case EVENT_TYPE_AT_CLCC:
                            processAtClcc(event.device);
                            break;
                        case EVENT_TYPE_UNKNOWN_AT:
                            processUnknownAt(event.valueString, event.device);
                            break;
                        case EVENT_TYPE_KEY_PRESSED:
                            processKeyPressed(event.device);
                            break;
                        default:
                            Log.e(TAG, "Unknown stack event: " + event.type);
                            break;
                    }
                    break;
                default:
                    return NOT_HANDLED;
            }
            return retValue;
        }

        // in AudioOn state. Some headsets disconnect RFCOMM prior to SCO down. Handle this
        private void processConnectionEvent(int state, BluetoothDevice device) {
        Log.d(TAG, "processConnectionEvent state = " + state + ", device = " +
                                                   device);
            switch (state) {
                case HeadsetHalConstants.CONNECTION_STATE_DISCONNECTED:
                    if (mConnectedDevicesList.contains(device)) {
                        if (mActiveScoDevice != null
                            && mActiveScoDevice.equals(device)&& mAudioState
                            != BluetoothHeadset.STATE_AUDIO_DISCONNECTED) {
                            processAudioEvent(
                                HeadsetHalConstants.AUDIO_STATE_DISCONNECTED, device);
                        }

                        synchronized (HeadsetStateMachine.this) {
                            mConnectedDevicesList.remove(device);
                            mHeadsetAudioParam.remove(device);
                            mHeadsetBrsf.remove(device);
                            Log.d(TAG, "device " + device.getAddress() +
                                           " is removed in AudioOn state");
1452 1453
                            broadcastConnectionState(device, BluetoothProfile.STATE_DISCONNECTED,
                                                     BluetoothProfile.STATE_CONNECTED);
1454
                            processWBSEvent(0, device); /* disable WBS audio parameters */
Nitin Srivastava's avatar
Nitin Srivastava committed
1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519
                            if (mConnectedDevicesList.size() == 0) {
                                transitionTo(mDisconnected);
                            }
                            else {
                                processMultiHFConnected(device);
                            }
                        }
                    } else {
                        Log.e(TAG, "Disconnected from unknown device: " + device);
                    }
                    break;
               case HeadsetHalConstants.CONNECTION_STATE_SLC_CONNECTED:
                    processSlcConnected();
                    break;
                case HeadsetHalConstants.CONNECTION_STATE_CONNECTED:
                    if (mConnectedDevicesList.contains(device)) {
                        mIncomingDevice = null;
                        mTargetDevice = null;
                        break;
                    }
                    Log.w(TAG, "HFP to be Connected in AudioOn state");
                    if (okToConnect(device) && (mConnectedDevicesList.size()
                                                      < max_hf_connections) ) {
                        Log.i(TAG,"Incoming Hf accepted");
                        broadcastConnectionState(device, BluetoothProfile.STATE_CONNECTED,
                                          BluetoothProfile.STATE_DISCONNECTED);
                        synchronized (HeadsetStateMachine.this) {
                            if (!mConnectedDevicesList.contains(device)) {
                                mCurrentDevice = device;
                                mConnectedDevicesList.add(device);
                                Log.d(TAG, "device " + device.getAddress() +
                                              " is added in AudioOn state");
                            }
                        }
                        configAudioParameters(device);
                     } else {
                         // reject the connection and stay in Connected state itself
                         Log.i(TAG,"Incoming Hf rejected. priority="
                                      + mService.getPriority(device) +
                                       " bondState=" + device.getBondState());
                         disconnectHfpNative(getByteAddress(device));
                         // the other profile connection should be initiated
                         AdapterService adapterService = AdapterService.getAdapterService();
                         if (adapterService != null) {
                             adapterService.connectOtherProfile(device,
                                             AdapterService.PROFILE_CONN_REJECTED);
                         }
                    }
                    break;
                default:
                    Log.e(TAG, "Connection State Device: " + device + " bad state: " + state);
                    break;
            }
        }

        // in AudioOn state
        private void processAudioEvent(int state, BluetoothDevice device) {
            if (!mConnectedDevicesList.contains(device)) {
                Log.e(TAG, "Audio changed on disconnected device: " + device);
                return;
            }

            switch (state) {
                case HeadsetHalConstants.AUDIO_STATE_DISCONNECTED:
                    if (mAudioState != BluetoothHeadset.STATE_AUDIO_DISCONNECTED) {
1520 1521
                        mAudioState = BluetoothHeadset.STATE_AUDIO_DISCONNECTED;
                        mAudioManager.setBluetoothScoOn(false);
Nitin Srivastava's avatar
Nitin Srivastava committed
1522
                        broadcastAudioState(device, BluetoothHeadset.STATE_AUDIO_DISCONNECTED,
1523 1524
                                            BluetoothHeadset.STATE_AUDIO_CONNECTED);
                    }
Nitin Srivastava's avatar
Nitin Srivastava committed
1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547
                    transitionTo(mConnected);
                    break;
                case HeadsetHalConstants.AUDIO_STATE_DISCONNECTING:
                    // TODO(BT) adding STATE_AUDIO_DISCONNECTING in BluetoothHeadset?
                    //broadcastAudioState(device, BluetoothHeadset.STATE_AUDIO_DISCONNECTING,
                    //                    BluetoothHeadset.STATE_AUDIO_CONNECTED);
                    break;
                default:
                    Log.e(TAG, "Audio State Device: " + device + " bad state: " + state);
                    break;
            }
        }

        private void processSlcConnected() {
            if (mPhoneProxy != null) {
                try {
                    mPhoneProxy.queryPhoneState();
                } catch (RemoteException e) {
                    Log.e(TAG, Log.getStackTraceString(new Throwable()));
                }
            } else {
                Log.e(TAG, "Handsfree phone proxy null for query phone state");
            }
1548
        }
Nitin Srivastava's avatar
Nitin Srivastava committed
1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571

        private void processIntentScoVolume(Intent intent, BluetoothDevice device) {
            int volumeValue = intent.getIntExtra(AudioManager.EXTRA_VOLUME_STREAM_VALUE, 0);
            if (mPhoneState.getSpeakerVolume() != volumeValue) {
                mPhoneState.setSpeakerVolume(volumeValue);
                setVolumeNative(HeadsetHalConstants.VOLUME_TYPE_SPK,
                                        volumeValue, getByteAddress(device));
            }
        }

        private void processMultiHFConnected(BluetoothDevice device) {
            log("AudioOn state: processMultiHFConnected");
            /* Assign the current activedevice again if the disconnected
                          device equals to the current active device */
            if (mCurrentDevice != null && mCurrentDevice.equals(device)) {
                int deviceSize = mConnectedDevicesList.size();
                mCurrentDevice = mConnectedDevicesList.get(deviceSize-1);
            }
            if (mAudioState != BluetoothHeadset.STATE_AUDIO_CONNECTED)
                transitionTo(mConnected);

            log("processMultiHFConnected , the latest mCurrentDevice is:"
                                      + mCurrentDevice);
1572 1573 1574 1575
            log("AudioOn state: processMultiHFConnected ," +
                       "fake broadcasting for mCurrentDevice");
            broadcastConnectionState(mCurrentDevice, BluetoothProfile.STATE_CONNECTED,
                            BluetoothProfile.STATE_DISCONNECTED);
Nitin Srivastava's avatar
Nitin Srivastava committed
1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633
        }
    }

    /* Add MultiHFPending state when atleast 1 HS is connected
            and disconnect/connect new HS */
    private class MultiHFPending extends State {
        @Override
        public void enter() {
            log("Enter MultiHFPending: " + getCurrentMessage().what +
                         ", size: " + mConnectedDevicesList.size());
        }

        @Override
        public boolean processMessage(Message message) {
            log("MultiHFPending process message: " + message.what +
                         ", size: " + mConnectedDevicesList.size());

            boolean retValue = HANDLED;
            switch(message.what) {
                case CONNECT:
                    deferMessage(message);
                    break;

                case CONNECT_AUDIO:
                    if (mCurrentDevice != null) {
                        connectAudioNative(getByteAddress(mCurrentDevice));
                    }
                    break;
                case CONNECT_TIMEOUT:
                    onConnectionStateChanged(HeadsetHalConstants.CONNECTION_STATE_DISCONNECTED,
                                             getByteAddress(mTargetDevice));
                    break;

                case DISCONNECT_AUDIO:
                    if (mActiveScoDevice != null) {
                        if (disconnectAudioNative(getByteAddress(mActiveScoDevice))) {
                            Log.d(TAG, "MultiHFPending, Disconnecting SCO audio for " +
                                                 mActiveScoDevice);
                        } else {
                            Log.e(TAG, "disconnectAudioNative failed" +
                                      "for device = " + mActiveScoDevice);
                        }
                    }
                    break;
                case DISCONNECT:
                    BluetoothDevice device = (BluetoothDevice) message.obj;
                    if (mConnectedDevicesList.contains(device) &&
                        mTargetDevice != null && mTargetDevice.equals(device)) {
                        // cancel connection to the mTargetDevice
                        broadcastConnectionState(device,
                                       BluetoothProfile.STATE_DISCONNECTED,
                                       BluetoothProfile.STATE_CONNECTING);
                        synchronized (HeadsetStateMachine.this) {
                            mTargetDevice = null;
                        }
                    } else {
                        deferMessage(message);
                    }
1634 1635
                    break;
                case VOICE_RECOGNITION_START:
Nitin Srivastava's avatar
Nitin Srivastava committed
1636 1637 1638 1639
                    device = (BluetoothDevice) message.obj;
                    if (mConnectedDevicesList.contains(device)) {
                        processLocalVrEvent(HeadsetHalConstants.VR_STATE_STARTED);
                    }
1640 1641
                    break;
                case VOICE_RECOGNITION_STOP:
Nitin Srivastava's avatar
Nitin Srivastava committed
1642 1643 1644 1645
                    device = (BluetoothDevice) message.obj;
                    if (mConnectedDevicesList.contains(device)) {
                        processLocalVrEvent(HeadsetHalConstants.VR_STATE_STOPPED);
                    }
1646
                    break;
1647 1648 1649 1650 1651
                case INTENT_SCO_VOLUME_CHANGED:
                    if (mActiveScoDevice != null) {
                        processIntentScoVolume((Intent) message.obj, mActiveScoDevice);
                    }
                    break;
1652 1653 1654
                case INTENT_BATTERY_CHANGED:
                    processIntentBatteryChanged((Intent) message.obj);
                    break;
Nitin Srivastava's avatar
Nitin Srivastava committed
1655 1656 1657 1658
                case CALL_STATE_CHANGED:
                    processCallState((HeadsetCallState) message.obj,
                                      ((message.arg1 == 1)?true:false));
                    break;
1659 1660 1661 1662 1663 1664
                case DEVICE_STATE_CHANGED:
                    processDeviceStateChanged((HeadsetDeviceState) message.obj);
                    break;
                case SEND_CCLC_RESPONSE:
                    processSendClccResponse((HeadsetClccResponse) message.obj);
                    break;
Nitin Srivastava's avatar
Nitin Srivastava committed
1665 1666 1667 1668 1669
                case CLCC_RSP_TIMEOUT:
                {
                    device = (BluetoothDevice) message.obj;
                    clccResponseNative(0, 0, 0, 0, false, "", 0, getByteAddress(device));
                }
Syed Ibrahim M's avatar
Syed Ibrahim M committed
1670
                    break;
1671 1672
                case DIALING_OUT_TIMEOUT:
                    if (mDialingOut) {
Nitin Srivastava's avatar
Nitin Srivastava committed
1673
                        device = (BluetoothDevice) message.obj;
1674
                        mDialingOut= false;
Nitin Srivastava's avatar
Nitin Srivastava committed
1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688
                        atResponseCodeNative(HeadsetHalConstants.AT_RESPONSE_ERROR,
                                             0, getByteAddress(device));
                    }
                    break;
                case VIRTUAL_CALL_START:
                    device = (BluetoothDevice) message.obj;
                    if(mConnectedDevicesList.contains(device)) {
                        initiateScoUsingVirtualVoiceCall();
                    }
                    break;
                case VIRTUAL_CALL_STOP:
                    device = (BluetoothDevice) message.obj;
                    if (mConnectedDevicesList.contains(device)) {
                        terminateScoUsingVirtualVoiceCall();
1689 1690
                    }
                    break;
1691 1692
                case START_VR_TIMEOUT:
                    if (mWaitingForVoiceRecognition) {
Nitin Srivastava's avatar
Nitin Srivastava committed
1693
                        device = (BluetoothDevice) message.obj;
1694
                        mWaitingForVoiceRecognition = false;
Nitin Srivastava's avatar
Nitin Srivastava committed
1695 1696 1697 1698
                        Log.e(TAG, "Timeout waiting for voice" +
                                             "recognition to start");
                        atResponseCodeNative(HeadsetHalConstants.AT_RESPONSE_ERROR,
                                               0, getByteAddress(device));
1699 1700
                    }
                    break;
1701 1702
                case STACK_EVENT:
                    StackEvent event = (StackEvent) message.obj;
1703 1704 1705
                    if (DBG) {
                        log("event type: " + event.type);
                    }
1706
                    switch (event.type) {
1707
                        case EVENT_TYPE_CONNECTION_STATE_CHANGED:
Nitin Srivastava's avatar
Nitin Srivastava committed
1708 1709 1710 1711 1712
                            BluetoothDevice device1 = getDeviceForMessage(CONNECT_TIMEOUT);
                            if (device1 != null && device1.equals(event.device)) {
                                Log.d(TAG, "remove connect timeout for device = " + device1);
                                removeMessages(CONNECT_TIMEOUT);
                            }
1713 1714
                            processConnectionEvent(event.valueInt, event.device);
                            break;
1715 1716 1717 1718
                        case EVENT_TYPE_AUDIO_STATE_CHANGED:
                            processAudioEvent(event.valueInt, event.device);
                            break;
                        case EVENT_TYPE_VR_STATE_CHANGED:
Nitin Srivastava's avatar
Nitin Srivastava committed
1719
                            processVrEvent(event.valueInt,event.device);
1720 1721
                            break;
                        case EVENT_TYPE_ANSWER_CALL:
Nitin Srivastava's avatar
Nitin Srivastava committed
1722 1723
                            //TODO(BT) could answer call happen on Connected state?
                            processAnswerCall(event.device);
1724 1725
                            break;
                        case EVENT_TYPE_HANGUP_CALL:
Nitin Srivastava's avatar
Nitin Srivastava committed
1726 1727
                            // TODO(BT) could hangup call happen on Connected state?
                            processHangupCall(event.device);
1728 1729
                            break;
                        case EVENT_TYPE_VOLUME_CHANGED:
Nitin Srivastava's avatar
Nitin Srivastava committed
1730 1731
                            processVolumeEvent(event.valueInt, event.valueInt2,
                                                    event.device);
1732 1733
                            break;
                        case EVENT_TYPE_DIAL_CALL:
Nitin Srivastava's avatar
Nitin Srivastava committed
1734
                            processDialCall(event.valueString, event.device);
1735 1736
                            break;
                        case EVENT_TYPE_SEND_DTMF:
Nitin Srivastava's avatar
Nitin Srivastava committed
1737
                            processSendDtmf(event.valueInt, event.device);
1738 1739
                            break;
                        case EVENT_TYPE_NOICE_REDUCTION:
Nitin Srivastava's avatar
Nitin Srivastava committed
1740
                            processNoiceReductionEvent(event.valueInt, event.device);
1741 1742
                            break;
                        case EVENT_TYPE_SUBSCRIBER_NUMBER_REQUEST:
Nitin Srivastava's avatar
Nitin Srivastava committed
1743
                            processSubscriberNumberRequest(event.device);
1744 1745
                            break;
                        case EVENT_TYPE_AT_CIND:
Nitin Srivastava's avatar
Nitin Srivastava committed
1746 1747 1748 1749
                            processAtCind(event.device);
                            break;
                        case EVENT_TYPE_AT_CHLD:
                            processAtChld(event.valueInt, event.device);
1750 1751
                            break;
                        case EVENT_TYPE_AT_COPS:
Nitin Srivastava's avatar
Nitin Srivastava committed
1752
                            processAtCops(event.device);
1753 1754
                            break;
                        case EVENT_TYPE_AT_CLCC:
Nitin Srivastava's avatar
Nitin Srivastava committed
1755
                            processAtClcc(event.device);
1756 1757
                            break;
                        case EVENT_TYPE_UNKNOWN_AT:
Nitin Srivastava's avatar
Nitin Srivastava committed
1758
                            processUnknownAt(event.valueString,event.device);
1759 1760
                            break;
                        case EVENT_TYPE_KEY_PRESSED:
Nitin Srivastava's avatar
Nitin Srivastava committed
1761
                            processKeyPressed(event.device);
1762 1763
                            break;
                        default:
Nitin Srivastava's avatar
Nitin Srivastava committed
1764
                            Log.e(TAG, "Unexpected event: " + event.type);
1765 1766 1767 1768 1769 1770 1771 1772 1773
                            break;
                    }
                    break;
                default:
                    return NOT_HANDLED;
            }
            return retValue;
        }

Nitin Srivastava's avatar
Nitin Srivastava committed
1774
        // in MultiHFPending state
1775
        private void processConnectionEvent(int state, BluetoothDevice device) {
Nitin Srivastava's avatar
Nitin Srivastava committed
1776 1777
            Log.d(TAG, "processConnectionEvent state = " + state +
                                     ", device = " + device);
1778 1779
            switch (state) {
                case HeadsetHalConstants.CONNECTION_STATE_DISCONNECTED:
Nitin Srivastava's avatar
Nitin Srivastava committed
1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790
                    if (mConnectedDevicesList.contains(device)) {
                        if (mMultiDisconnectDevice != null &&
                                mMultiDisconnectDevice.equals(device)) {
                            mMultiDisconnectDevice = null;

                          synchronized (HeadsetStateMachine.this) {
                              mConnectedDevicesList.remove(device);
                              mHeadsetAudioParam.remove(device);
                              mHeadsetBrsf.remove(device);
                              Log.d(TAG, "device " + device.getAddress() +
                                      " is removed in MultiHFPending state");
1791 1792 1793
                              broadcastConnectionState(device,
                                        BluetoothProfile.STATE_DISCONNECTED,
                                        BluetoothProfile.STATE_DISCONNECTING);
Nitin Srivastava's avatar
Nitin Srivastava committed
1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842
                          }

                          if (mTargetDevice != null) {
                              if (!connectHfpNative(getByteAddress(mTargetDevice))) {

                                broadcastConnectionState(mTargetDevice,
                                          BluetoothProfile.STATE_DISCONNECTED,
                                          BluetoothProfile.STATE_CONNECTING);
                                  synchronized (HeadsetStateMachine.this) {
                                      mTargetDevice = null;
                                      if (mConnectedDevicesList.size() == 0) {
                                          // Should be not in this state since it has at least
                                          // one HF connected in MultiHFPending state
                                          Log.d(TAG, "Should be not in this state, error handling");
                                          transitionTo(mDisconnected);
                                      }
                                      else {
                                          processMultiHFConnected(device);
                                      }
                                  }
                              }
                          } else {
                              synchronized (HeadsetStateMachine.this) {
                                  mIncomingDevice = null;
                                  if (mConnectedDevicesList.size() == 0) {
                                      transitionTo(mDisconnected);
                                  }
                                  else {
                                      processMultiHFConnected(device);
                                  }
                              }
                           }
                        } else {
                            /* Another HF disconnected when one HF is connecting */
                            synchronized (HeadsetStateMachine.this) {
                              mConnectedDevicesList.remove(device);
                              mHeadsetAudioParam.remove(device);
                              mHeadsetBrsf.remove(device);
                              Log.d(TAG, "device " + device.getAddress() +
                                           " is removed in MultiHFPending state");
                            }
                            broadcastConnectionState(device,
                                BluetoothProfile.STATE_DISCONNECTED,
                                BluetoothProfile.STATE_CONNECTED);
                        }
                    } else if (mTargetDevice != null && mTargetDevice.equals(device)) {

                        broadcastConnectionState(mTargetDevice, BluetoothProfile.STATE_DISCONNECTED,
                                                 BluetoothProfile.STATE_CONNECTING);
1843
                        synchronized (HeadsetStateMachine.this) {
Nitin Srivastava's avatar
Nitin Srivastava committed
1844 1845 1846 1847 1848 1849 1850 1851 1852 1853
                            mTargetDevice = null;
                            if (mConnectedDevicesList.size() == 0) {
                                transitionTo(mDisconnected);
                            }
                            else
                            {
                               if (mAudioState == BluetoothHeadset.STATE_AUDIO_CONNECTED)
                                   transitionTo(mAudioOn);
                               else transitionTo(mConnected);
                            }
1854 1855
                        }
                    } else {
Nitin Srivastava's avatar
Nitin Srivastava committed
1856
                        Log.e(TAG, "Unknown device Disconnected: " + device);
1857 1858
                    }
                    break;
Nitin Srivastava's avatar
Nitin Srivastava committed
1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922
            case HeadsetHalConstants.CONNECTION_STATE_CONNECTED:
                /* Outgoing disconnection for device failed */
                if (mConnectedDevicesList.contains(device)) {

                    broadcastConnectionState(device, BluetoothProfile.STATE_CONNECTED,
                                             BluetoothProfile.STATE_DISCONNECTING);
                    if (mTargetDevice != null) {
                        broadcastConnectionState(mTargetDevice, BluetoothProfile.STATE_DISCONNECTED,
                                                 BluetoothProfile.STATE_CONNECTING);
                    }
                    synchronized (HeadsetStateMachine.this) {
                        mTargetDevice = null;
                        if (mAudioState == BluetoothHeadset.STATE_AUDIO_CONNECTED)
                            transitionTo(mAudioOn);
                        else transitionTo(mConnected);
                    }
                } else if (mTargetDevice != null && mTargetDevice.equals(device)) {

                    synchronized (HeadsetStateMachine.this) {
                            mCurrentDevice = device;
                            mConnectedDevicesList.add(device);
                            Log.d(TAG, "device " + device.getAddress() +
                                      " is added in MultiHFPending state");
                            mTargetDevice = null;
                            if (mAudioState == BluetoothHeadset.STATE_AUDIO_CONNECTED)
                                transitionTo(mAudioOn);
                            else transitionTo(mConnected);
                    }

                    broadcastConnectionState(device, BluetoothProfile.STATE_CONNECTED,
                                             BluetoothProfile.STATE_CONNECTING);
                    configAudioParameters(device);
                } else {
                    Log.w(TAG, "Some other incoming HF connected" +
                                          "in Multi Pending state");
                    if (okToConnect(device) &&
                            (mConnectedDevicesList.size() < max_hf_connections)) {
                        Log.i(TAG,"Incoming Hf accepted");
                        broadcastConnectionState(device, BluetoothProfile.STATE_CONNECTED,
                                         BluetoothProfile.STATE_DISCONNECTED);
                        synchronized (HeadsetStateMachine.this) {
                            if (!mConnectedDevicesList.contains(device)) {
                                mCurrentDevice = device;
                                mConnectedDevicesList.add(device);
                                Log.d(TAG, "device " + device.getAddress() +
                                            " is added in MultiHFPending state");
                            }
                        }
                        configAudioParameters(device);
                    } else {
                        // reject the connection and stay in Pending state itself
                        Log.i(TAG,"Incoming Hf rejected. priority=" +
                                          mService.getPriority(device) +
                                  " bondState=" + device.getBondState());
                        disconnectHfpNative(getByteAddress(device));
                        // the other profile connection should be initiated
                        AdapterService adapterService = AdapterService.getAdapterService();
                        if (adapterService != null) {
                            adapterService.connectOtherProfile(device,
                                          AdapterService.PROFILE_CONN_REJECTED);
                        }
                    }
                }
                break;
1923 1924 1925
            case HeadsetHalConstants.CONNECTION_STATE_SLC_CONNECTED:
                processSlcConnected();
                break;
Nitin Srivastava's avatar
Nitin Srivastava committed
1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954
            case HeadsetHalConstants.CONNECTION_STATE_CONNECTING:
                if (mConnectedDevicesList.contains(device)) {
                    Log.e(TAG, "current device tries to connect back");
                } else if (mTargetDevice != null && mTargetDevice.equals(device)) {
                    if (DBG) {
                        log("Stack and target device are connecting");
                    }
                }
                else if (mIncomingDevice != null && mIncomingDevice.equals(device)) {
                    Log.e(TAG, "Another connecting event on" +
                                              "the incoming device");
                }
                break;
            case HeadsetHalConstants.CONNECTION_STATE_DISCONNECTING:
                if (mConnectedDevicesList.contains(device)) {
                    if (DBG) {
                        log("stack is disconnecting mCurrentDevice");
                    }
                } else if (mTargetDevice != null && mTargetDevice.equals(device)) {
                    Log.e(TAG, "TargetDevice is getting disconnected");
                } else if (mIncomingDevice != null && mIncomingDevice.equals(device)) {
                    Log.e(TAG, "IncomingDevice is getting disconnected");
                } else {
                    Log.e(TAG, "Disconnecting unknow device: " + device);
                }
                break;
            default:
                Log.e(TAG, "Incorrect state: " + state);
                break;
1955 1956 1957
            }
        }

1958
        private void processAudioEvent(int state, BluetoothDevice device) {
Nitin Srivastava's avatar
Nitin Srivastava committed
1959
            if (!mConnectedDevicesList.contains(device)) {
1960 1961 1962 1963 1964
                Log.e(TAG, "Audio changed on disconnected device: " + device);
                return;
            }

            switch (state) {
Nitin Srivastava's avatar
Nitin Srivastava committed
1965
                case HeadsetHalConstants.AUDIO_STATE_CONNECTED:
1966 1967 1968 1969 1970
                    if (!isScoAcceptable()) {
                        Log.e(TAG,"Audio Connected without any listener");
                        disconnectAudioNative(getByteAddress(device));
                        break;
                    }
Nitin Srivastava's avatar
Nitin Srivastava committed
1971 1972 1973 1974
                    mAudioState = BluetoothHeadset.STATE_AUDIO_CONNECTED;
                    setAudioParameters(device); /* Set proper Audio Parameters. */
                    mAudioManager.setBluetoothScoOn(true);
                    mActiveScoDevice = device;
1975 1976
                    broadcastAudioState(device, BluetoothHeadset.STATE_AUDIO_CONNECTED,
                            BluetoothHeadset.STATE_AUDIO_CONNECTING);
Nitin Srivastava's avatar
Nitin Srivastava committed
1977 1978 1979 1980 1981 1982 1983 1984 1985
                    /* The state should be still in MultiHFPending state when
                       audio connected since other device is still connecting/
                       disconnecting */
                    break;
                case HeadsetHalConstants.AUDIO_STATE_CONNECTING:
                    mAudioState = BluetoothHeadset.STATE_AUDIO_CONNECTING;
                    broadcastAudioState(device, BluetoothHeadset.STATE_AUDIO_CONNECTING,
                                        BluetoothHeadset.STATE_AUDIO_DISCONNECTED);
                    break;
1986
                case HeadsetHalConstants.AUDIO_STATE_DISCONNECTED:
1987 1988 1989 1990 1991 1992
                    if (mAudioState != BluetoothHeadset.STATE_AUDIO_DISCONNECTED) {
                        mAudioState = BluetoothHeadset.STATE_AUDIO_DISCONNECTED;
                        mAudioManager.setBluetoothScoOn(false);
                        broadcastAudioState(device, BluetoothHeadset.STATE_AUDIO_DISCONNECTED,
                                            BluetoothHeadset.STATE_AUDIO_CONNECTED);
                    }
Nitin Srivastava's avatar
Nitin Srivastava committed
1993 1994 1995
                    /* The state should be still in MultiHFPending state when audio
                       disconnected since other device is still connecting/
                       disconnecting */
1996
                    break;
Nitin Srivastava's avatar
Nitin Srivastava committed
1997

1998 1999 2000 2001 2002 2003
                default:
                    Log.e(TAG, "Audio State Device: " + device + " bad state: " + state);
                    break;
            }
        }

2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016
        private void processSlcConnected() {
            if (mPhoneProxy != null) {
                try {
                    mPhoneProxy.queryPhoneState();
                } catch (RemoteException e) {
                    Log.e(TAG, Log.getStackTraceString(new Throwable()));
                }
            } else {
                Log.e(TAG, "Handsfree phone proxy null for query phone state");
            }
        }


Nitin Srivastava's avatar
Nitin Srivastava committed
2017 2018
        private void processMultiHFConnected(BluetoothDevice device) {
            log("MultiHFPending state: processMultiHFConnected");
2019 2020 2021 2022
            if (mActiveScoDevice != null && mActiveScoDevice.equals(device)) {
                log ("mActiveScoDevice is disconnected, setting it to null");
                mActiveScoDevice = null;
            }
Nitin Srivastava's avatar
Nitin Srivastava committed
2023 2024 2025 2026 2027
            /* Assign the current activedevice again if the disconnected
               device equals to the current active device */
            if (mCurrentDevice != null && mCurrentDevice.equals(device)) {
                int deviceSize = mConnectedDevicesList.size();
                mCurrentDevice = mConnectedDevicesList.get(deviceSize-1);
2028
            }
2029 2030 2031 2032
            // The disconnected device is not current active device
            if (mAudioState == BluetoothHeadset.STATE_AUDIO_CONNECTED)
                transitionTo(mAudioOn);
            else transitionTo(mConnected);
Nitin Srivastava's avatar
Nitin Srivastava committed
2033 2034
            log("processMultiHFConnected , the latest mCurrentDevice is:"
                                            + mCurrentDevice);
2035 2036 2037 2038
            log("MultiHFPending state: processMultiHFConnected ," +
                         "fake broadcasting for mCurrentDevice");
            broadcastConnectionState(mCurrentDevice, BluetoothProfile.STATE_CONNECTED,
                            BluetoothProfile.STATE_DISCONNECTED);
2039
        }
Nitin Srivastava's avatar
Nitin Srivastava committed
2040

2041 2042 2043 2044 2045 2046 2047 2048
        private void processIntentScoVolume(Intent intent, BluetoothDevice device) {
            int volumeValue = intent.getIntExtra(AudioManager.EXTRA_VOLUME_STREAM_VALUE, 0);
            if (mPhoneState.getSpeakerVolume() != volumeValue) {
                mPhoneState.setSpeakerVolume(volumeValue);
                setVolumeNative(HeadsetHalConstants.VOLUME_TYPE_SPK,
                                    volumeValue, getByteAddress(device));
            }
        }
2049 2050
    }

Nitin Srivastava's avatar
Nitin Srivastava committed
2051

2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067
    private ServiceConnection mConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder service) {
            if (DBG) Log.d(TAG, "Proxy object connected");
            mPhoneProxy = IBluetoothHeadsetPhone.Stub.asInterface(service);
        }

        public void onServiceDisconnected(ComponentName className) {
            if (DBG) Log.d(TAG, "Proxy object disconnected");
            mPhoneProxy = null;
        }
    };

    // HFP Connection state of the device could be changed by the state machine
    // in separate thread while this method is executing.
    int getConnectionState(BluetoothDevice device) {
        if (getCurrentState() == mDisconnected) {
Nitin Srivastava's avatar
Nitin Srivastava committed
2068
            if (DBG) Log.d(TAG, "currentState is Disconnected");
2069 2070 2071 2072 2073
            return BluetoothProfile.STATE_DISCONNECTED;
        }

        synchronized (this) {
            IState currentState = getCurrentState();
Nitin Srivastava's avatar
Nitin Srivastava committed
2074
            if (DBG) Log.d(TAG, "currentState = " + currentState);
2075 2076 2077 2078
            if (currentState == mPending) {
                if ((mTargetDevice != null) && mTargetDevice.equals(device)) {
                    return BluetoothProfile.STATE_CONNECTING;
                }
Nitin Srivastava's avatar
Nitin Srivastava committed
2079
                if (mConnectedDevicesList.contains(device)) {
2080 2081 2082 2083 2084 2085 2086 2087
                    return BluetoothProfile.STATE_DISCONNECTING;
                }
                if ((mIncomingDevice != null) && mIncomingDevice.equals(device)) {
                    return BluetoothProfile.STATE_CONNECTING; // incoming connection
                }
                return BluetoothProfile.STATE_DISCONNECTED;
            }

Nitin Srivastava's avatar
Nitin Srivastava committed
2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105
            if (currentState == mMultiHFPending) {
                if ((mTargetDevice != null) && mTargetDevice.equals(device)) {
                    return BluetoothProfile.STATE_CONNECTING;
                }
                if ((mIncomingDevice != null) && mIncomingDevice.equals(device)) {
                    return BluetoothProfile.STATE_CONNECTING; // incoming connection
                }
                if (mConnectedDevicesList.contains(device)) {
                    if ((mMultiDisconnectDevice != null) &&
                            (!mMultiDisconnectDevice.equals(device))) {
                        // The device is still connected
                        return BluetoothProfile.STATE_CONNECTED;
                    }
                    return BluetoothProfile.STATE_DISCONNECTING;
                }
                return BluetoothProfile.STATE_DISCONNECTED;
            }

2106
            if (currentState == mConnected || currentState == mAudioOn) {
2107
                if (mConnectedDevicesList.contains(device)) {
2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120
                    return BluetoothProfile.STATE_CONNECTED;
                }
                return BluetoothProfile.STATE_DISCONNECTED;
            } else {
                Log.e(TAG, "Bad currentState: " + currentState);
                return BluetoothProfile.STATE_DISCONNECTED;
            }
        }
    }

    List<BluetoothDevice> getConnectedDevices() {
        List<BluetoothDevice> devices = new ArrayList<BluetoothDevice>();
        synchronized(this) {
Nitin Srivastava's avatar
Nitin Srivastava committed
2121 2122
            for (int i = 0; i < mConnectedDevicesList.size(); i++)
                devices.add(mConnectedDevicesList.get(i));
2123
            }
Nitin Srivastava's avatar
Nitin Srivastava committed
2124

2125 2126 2127 2128 2129 2130 2131 2132 2133
        return devices;
    }

    boolean isAudioOn() {
        return (getCurrentState() == mAudioOn);
    }

    boolean isAudioConnected(BluetoothDevice device) {
        synchronized(this) {
2134 2135 2136 2137 2138 2139 2140 2141 2142

            /*  Additional check for audio state included for the case when PhoneApp queries
            Bluetooth Audio state, before we receive the close event from the stack for the
            sco disconnect issued in AudioOn state. This was causing a mismatch in the
            Incall screen UI. */

            if (getCurrentState() == mAudioOn && mCurrentDevice.equals(device)
                && mAudioState != BluetoothHeadset.STATE_AUDIO_DISCONNECTED)
            {
2143 2144 2145 2146 2147 2148 2149 2150
                return true;
            }
        }
        return false;
    }

    int getAudioState(BluetoothDevice device) {
        synchronized(this) {
Nitin Srivastava's avatar
Nitin Srivastava committed
2151
            if (mConnectedDevicesList.size() == 0) {
2152 2153 2154 2155 2156 2157
                return BluetoothHeadset.STATE_AUDIO_DISCONNECTED;
            }
        }
        return mAudioState;
    }

Nitin Srivastava's avatar
Nitin Srivastava committed
2158 2159 2160 2161 2162 2163
    private void processVrEvent(int state, BluetoothDevice device) {

        if(device == null) {
            Log.w(TAG, "processVrEvent device is null");
            return;
        }
2164 2165 2166 2167
        Log.d(TAG, "processVrEvent: state=" + state + " mVoiceRecognitionStarted: " +
            mVoiceRecognitionStarted + " mWaitingforVoiceRecognition: " + mWaitingForVoiceRecognition +
            " isInCall: " + isInCall());
        if (state == HeadsetHalConstants.VR_STATE_STARTED) {
2168
            if (!isVirtualCallInProgress() &&
2169 2170 2171
                !isInCall())
            {
                try {
2172
                    mService.startActivity(sVoiceCommandIntent);
2173
                } catch (ActivityNotFoundException e) {
Nitin Srivastava's avatar
Nitin Srivastava committed
2174 2175
                    atResponseCodeNative(HeadsetHalConstants.AT_RESPONSE_ERROR,
                                        0, getByteAddress(device));
2176 2177
                    return;
                }
Nitin Srivastava's avatar
Nitin Srivastava committed
2178
                expectVoiceRecognition(device);
2179 2180 2181 2182
            }
        } else if (state == HeadsetHalConstants.VR_STATE_STOPPED) {
            if (mVoiceRecognitionStarted || mWaitingForVoiceRecognition)
            {
Nitin Srivastava's avatar
Nitin Srivastava committed
2183 2184
                atResponseCodeNative(HeadsetHalConstants.AT_RESPONSE_OK,
                                         0, getByteAddress(device));
2185 2186
                mVoiceRecognitionStarted = false;
                mWaitingForVoiceRecognition = false;
Nitin Srivastava's avatar
Nitin Srivastava committed
2187 2188
                if (!isInCall() && (mActiveScoDevice != null)) {
                    disconnectAudioNative(getByteAddress(mActiveScoDevice));
2189 2190
                    mAudioManager.setParameters("A2dpSuspended=false");
                }
2191 2192 2193
            }
            else
            {
Nitin Srivastava's avatar
Nitin Srivastava committed
2194 2195
                atResponseCodeNative(HeadsetHalConstants.AT_RESPONSE_ERROR,
                                        0, getByteAddress(device));
2196 2197 2198 2199 2200 2201 2202 2203
            }
        } else {
            Log.e(TAG, "Bad Voice Recognition state: " + state);
        }
    }

    private void processLocalVrEvent(int state)
    {
Nitin Srivastava's avatar
Nitin Srivastava committed
2204
        BluetoothDevice device = null;
2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217
        if (state == HeadsetHalConstants.VR_STATE_STARTED)
        {
            boolean needAudio = true;
            if (mVoiceRecognitionStarted || isInCall())
            {
                Log.e(TAG, "Voice recognition started when call is active. isInCall:" + isInCall() + 
                    " mVoiceRecognitionStarted: " + mVoiceRecognitionStarted);
                return;
            }
            mVoiceRecognitionStarted = true;

            if (mWaitingForVoiceRecognition)
            {
Nitin Srivastava's avatar
Nitin Srivastava committed
2218 2219 2220 2221
                device = getDeviceForMessage(START_VR_TIMEOUT);
                if (device == null)
                    return;

2222 2223
                Log.d(TAG, "Voice recognition started successfully");
                mWaitingForVoiceRecognition = false;
Nitin Srivastava's avatar
Nitin Srivastava committed
2224 2225
                atResponseCodeNative(HeadsetHalConstants.AT_RESPONSE_OK,
                                        0, getByteAddress(device));
2226 2227 2228 2229 2230
                removeMessages(START_VR_TIMEOUT);
            }
            else
            {
                Log.d(TAG, "Voice recognition started locally");
Nitin Srivastava's avatar
Nitin Srivastava committed
2231 2232 2233
                needAudio = startVoiceRecognitionNative(getByteAddress(mCurrentDevice));
                if (mCurrentDevice != null)
                    device = mCurrentDevice;
2234 2235 2236 2237 2238
            }

            if (needAudio && !isAudioOn())
            {
                Log.d(TAG, "Initiating audio connection for Voice Recognition");
2239 2240 2241 2242 2243 2244 2245 2246 2247
                // At this stage, we need to be sure that AVDTP is not streaming. This is needed
                // to be compliant with the AV+HFP Whitepaper as we cannot have A2DP in
                // streaming state while a SCO connection is established.
                // This is needed for VoiceDial scenario alone and not for
                // incoming call/outgoing call scenarios as the phone enters MODE_RINGTONE
                // or MODE_IN_CALL which shall automatically suspend the AVDTP stream if needed.
                // Whereas for VoiceDial we want to activate the SCO connection but we are still
                // in MODE_NORMAL and hence the need to explicitly suspend the A2DP stream
                mAudioManager.setParameters("A2dpSuspended=true");
Mallikarjuna GB's avatar
Mallikarjuna GB committed
2248 2249 2250 2251 2252
                if (device != null) {
                    connectAudioNative(getByteAddress(device));
                } else {
                    Log.e(TAG, "device not found for VR");
                }
2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267
            }

            if (mStartVoiceRecognitionWakeLock.isHeld()) {
                mStartVoiceRecognitionWakeLock.release();
            }
        }
        else
        {
            Log.d(TAG, "Voice Recognition stopped. mVoiceRecognitionStarted: " + mVoiceRecognitionStarted +
                " mWaitingForVoiceRecognition: " + mWaitingForVoiceRecognition);
            if (mVoiceRecognitionStarted || mWaitingForVoiceRecognition)
            {
                mVoiceRecognitionStarted = false;
                mWaitingForVoiceRecognition = false;

Nitin Srivastava's avatar
Nitin Srivastava committed
2268 2269 2270
                if (stopVoiceRecognitionNative(getByteAddress(mCurrentDevice))
                                && !isInCall() && mActiveScoDevice != null) {
                    disconnectAudioNative(getByteAddress(mActiveScoDevice));
2271 2272
                    mAudioManager.setParameters("A2dpSuspended=false");
                }
2273 2274 2275 2276
            }
        }
    }

Nitin Srivastava's avatar
Nitin Srivastava committed
2277
    private synchronized void expectVoiceRecognition(BluetoothDevice device) {
2278
        mWaitingForVoiceRecognition = true;
Nitin Srivastava's avatar
Nitin Srivastava committed
2279 2280 2281 2282
        Message m = obtainMessage(START_VR_TIMEOUT);
        m.obj = getMatchingDevice(device);
        sendMessageDelayed(m, START_VR_TIMEOUT_VALUE);

2283 2284 2285 2286 2287
        if (!mStartVoiceRecognitionWakeLock.isHeld()) {
            mStartVoiceRecognitionWakeLock.acquire(START_VR_TIMEOUT_VALUE);
        }
    }

2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308
    List<BluetoothDevice> getDevicesMatchingConnectionStates(int[] states) {
        List<BluetoothDevice> deviceList = new ArrayList<BluetoothDevice>();
        Set<BluetoothDevice> bondedDevices = mAdapter.getBondedDevices();
        int connectionState;
        synchronized (this) {
            for (BluetoothDevice device : bondedDevices) {
                ParcelUuid[] featureUuids = device.getUuids();
                if (!BluetoothUuid.containsAnyUuid(featureUuids, HEADSET_UUIDS)) {
                    continue;
                }
                connectionState = getConnectionState(device);
                for(int i = 0; i < states.length; i++) {
                    if (connectionState == states[i]) {
                        deviceList.add(device);
                    }
                }
            }
        }
        return deviceList;
    }

Nitin Srivastava's avatar
Nitin Srivastava committed
2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342
    private BluetoothDevice getDeviceForMessage(int what)
    {
        if (what == CONNECT_TIMEOUT) {
            log("getDeviceForMessage: returning mTargetDevice for what=" + what);
            return mTargetDevice;
        }
        if (mConnectedDevicesList.size() == 0) {
            log("getDeviceForMessage: No connected device. what=" + what);
            return null;
        }
        for (BluetoothDevice device : mConnectedDevicesList)
        {
            if (getHandler().hasMessages(what, device))
            {
                log("getDeviceForMessage: returning " + device);
                return device;
            }
        }
        log("getDeviceForMessage: No matching device for " + what + ". Returning null");
        return null;
    }

    private BluetoothDevice getMatchingDevice(BluetoothDevice device)
    {
        for (BluetoothDevice matchingDevice : mConnectedDevicesList)
        {
            if (matchingDevice.equals(device))
            {
                return matchingDevice;
            }
        }
        return null;
    }

2343 2344
    // This method does not check for error conditon (newState == prevState)
    private void broadcastConnectionState(BluetoothDevice device, int newState, int prevState) {
2345
        log("Connection state " + device + ": " + prevState + "->" + newState);
Syed Ibrahim M's avatar
Syed Ibrahim M committed
2346 2347 2348 2349 2350
        if(prevState == BluetoothProfile.STATE_CONNECTED) {
            // Headset is disconnecting, stop Virtual call if active.
            terminateScoUsingVirtualVoiceCall();
        }

2351 2352 2353 2354 2355
        /* Notifying the connection state change of the profile before sending the intent for
           connection state change, as it was causing a race condition, with the UI not being
           updated with the correct connection state. */
        mService.notifyProfileConnectionStateChanged(device, BluetoothProfile.HEADSET,
                                                     newState, prevState);
2356 2357 2358 2359
        Intent intent = new Intent(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED);
        intent.putExtra(BluetoothProfile.EXTRA_PREVIOUS_STATE, prevState);
        intent.putExtra(BluetoothProfile.EXTRA_STATE, newState);
        intent.putExtra(BluetoothDevice.EXTRA_DEVICE, device);
2360 2361
        mService.sendBroadcastAsUser(intent, UserHandle.ALL,
                HeadsetService.BLUETOOTH_PERM);
2362 2363 2364
    }

    private void broadcastAudioState(BluetoothDevice device, int newState, int prevState) {
Syed Ibrahim M's avatar
Syed Ibrahim M committed
2365 2366 2367 2368 2369
        if(prevState == BluetoothHeadset.STATE_AUDIO_CONNECTED) {
            // When SCO gets disconnected during call transfer, Virtual call
            //needs to be cleaned up.So call terminateScoUsingVirtualVoiceCall.
            terminateScoUsingVirtualVoiceCall();
        }
2370 2371 2372 2373
        Intent intent = new Intent(BluetoothHeadset.ACTION_AUDIO_STATE_CHANGED);
        intent.putExtra(BluetoothProfile.EXTRA_PREVIOUS_STATE, prevState);
        intent.putExtra(BluetoothProfile.EXTRA_STATE, newState);
        intent.putExtra(BluetoothDevice.EXTRA_DEVICE, device);
2374 2375
        mService.sendBroadcastAsUser(intent, UserHandle.ALL,
                HeadsetService.BLUETOOTH_PERM);
2376
        log("Audio state " + device + ": " + prevState + "->" + newState);
2377 2378
    }

2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399
    /*
     * Put the AT command, company ID, arguments, and device in an Intent and broadcast it.
     */
    private void broadcastVendorSpecificEventIntent(String command,
                                                    int companyId,
                                                    int commandType,
                                                    Object[] arguments,
                                                    BluetoothDevice device) {
        log("broadcastVendorSpecificEventIntent(" + command + ")");
        Intent intent =
                new Intent(BluetoothHeadset.ACTION_VENDOR_SPECIFIC_HEADSET_EVENT);
        intent.putExtra(BluetoothHeadset.EXTRA_VENDOR_SPECIFIC_HEADSET_EVENT_CMD, command);
        intent.putExtra(BluetoothHeadset.EXTRA_VENDOR_SPECIFIC_HEADSET_EVENT_CMD_TYPE,
                        commandType);
        // assert: all elements of args are Serializable
        intent.putExtra(BluetoothHeadset.EXTRA_VENDOR_SPECIFIC_HEADSET_EVENT_ARGS, arguments);
        intent.putExtra(BluetoothDevice.EXTRA_DEVICE, device);

        intent.addCategory(BluetoothHeadset.VENDOR_SPECIFIC_HEADSET_EVENT_COMPANY_ID_CATEGORY
            + "." + Integer.toString(companyId));

2400 2401
        mService.sendBroadcastAsUser(intent, UserHandle.ALL,
                HeadsetService.BLUETOOTH_PERM);
2402 2403
    }

Nitin Srivastava's avatar
Nitin Srivastava committed
2404
    private void configAudioParameters(BluetoothDevice device)
2405 2406
    {
        // Reset NREC on connect event. Headset will override later
Nitin Srivastava's avatar
Nitin Srivastava committed
2407 2408 2409 2410
        HashMap<String, Integer> AudioParamConfig = new HashMap<String, Integer>();
        AudioParamConfig.put("NREC", 1);
        mHeadsetAudioParam.put(device, AudioParamConfig);
        mAudioManager.setParameters(HEADSET_NAME + "=" + getCurrentDeviceName(device) + ";" +
2411
                                    HEADSET_NREC + "=on");
Nitin Srivastava's avatar
Nitin Srivastava committed
2412 2413 2414 2415 2416 2417 2418 2419
        Log.d(TAG, "configAudioParameters for device:" + device + " are: nrec = " +
                      AudioParamConfig.get("NREC"));
    }

    private void setAudioParameters(BluetoothDevice device)
    {
        // 1. update nrec value
        // 2. update headset name
Mallikarjuna GB's avatar
Mallikarjuna GB committed
2420
        int mNrec = 0;
Nitin Srivastava's avatar
Nitin Srivastava committed
2421
        HashMap<String, Integer> AudioParam = mHeadsetAudioParam.get(device);
Mallikarjuna GB's avatar
Mallikarjuna GB committed
2422 2423 2424 2425 2426
        if (AudioParam != null && !AudioParam.isEmpty()) {
            mNrec = AudioParam.get("NREC");
        } else {
            Log.e(TAG,"setAudioParameters: AudioParam not found");
        }
Nitin Srivastava's avatar
Nitin Srivastava committed
2427 2428 2429 2430 2431 2432 2433 2434 2435

        if (mNrec == 1) {
            Log.d(TAG, "Set NREC: 1 for device:" + device);
            mAudioManager.setParameters(HEADSET_NREC + "=on");
        } else {
            Log.d(TAG, "Set NREC: 0 for device:" + device);
            mAudioManager.setParameters(HEADSET_NREC + "=off");
        }
        mAudioManager.setParameters(HEADSET_NAME + "=" + getCurrentDeviceName(device));
2436 2437
    }

Sreenidhi T's avatar
Sreenidhi T committed
2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481
    private String parseUnknownAt(String atString)
    {
        StringBuilder atCommand = new StringBuilder(atString.length());
        String result = null;

        for (int i = 0; i < atString.length(); i++) {
            char c = atString.charAt(i);
            if (c == '"') {
                int j = atString.indexOf('"', i + 1 );  // search for closing "
                if (j == -1) {  // unmatched ", insert one.
                    atCommand.append(atString.substring(i, atString.length()));
                    atCommand.append('"');
                    break;
                }
                atCommand.append(atString.substring(i, j + 1));
                i = j;
            } else if (c != ' ') {
                atCommand.append(Character.toUpperCase(c));
            }
        }
        result = atCommand.toString();
        return result;
    }

    private int getAtCommandType(String atCommand)
    {
        int commandType = mPhonebook.TYPE_UNKNOWN;
        String atString = null;
        atCommand = atCommand.trim();
        if (atCommand.length() > 5)
        {
            atString = atCommand.substring(5);
            if (atString.startsWith("?"))     // Read
                commandType = mPhonebook.TYPE_READ;
            else if (atString.startsWith("=?"))   // Test
                commandType = mPhonebook.TYPE_TEST;
            else if (atString.startsWith("="))   // Set
                commandType = mPhonebook.TYPE_SET;
            else
                commandType = mPhonebook.TYPE_UNKNOWN;
        }
        return commandType;
    }

Syed Ibrahim M's avatar
Syed Ibrahim M committed
2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532
    /* Method to check if Virtual Call in Progress */
    private boolean isVirtualCallInProgress() {
        return mVirtualCallStarted;
    }

    void setVirtualCallInProgress(boolean state) {
        mVirtualCallStarted = state;
    }

    /* NOTE: Currently the VirtualCall API does not support handling of
    call transfers. If it is initiated from the handsfree device,
    HeadsetStateMachine will end the virtual call by calling
    terminateScoUsingVirtualVoiceCall() in broadcastAudioState() */
    synchronized boolean initiateScoUsingVirtualVoiceCall() {
        if (DBG) log("initiateScoUsingVirtualVoiceCall: Received");
        // 1. Check if the SCO state is idle
        if (isInCall() || mVoiceRecognitionStarted) {
            Log.e(TAG, "initiateScoUsingVirtualVoiceCall: Call in progress.");
            return false;
        }

        // 2. Send virtual phone state changed to initialize SCO
        processCallState(new HeadsetCallState(0, 0,
            HeadsetHalConstants.CALL_STATE_DIALING, "", 0), true);
        processCallState(new HeadsetCallState(0, 0,
            HeadsetHalConstants.CALL_STATE_ALERTING, "", 0), true);
        processCallState(new HeadsetCallState(1, 0,
            HeadsetHalConstants.CALL_STATE_IDLE, "", 0), true);
        setVirtualCallInProgress(true);
        // Done
        if (DBG) log("initiateScoUsingVirtualVoiceCall: Done");
        return true;
    }

    synchronized boolean terminateScoUsingVirtualVoiceCall() {
        if (DBG) log("terminateScoUsingVirtualVoiceCall: Received");

        if (!isVirtualCallInProgress()) {
            Log.e(TAG, "terminateScoUsingVirtualVoiceCall:"+
                "No present call to terminate");
            return false;
        }

        // 2. Send virtual phone state changed to close SCO
        processCallState(new HeadsetCallState(0, 0,
            HeadsetHalConstants.CALL_STATE_IDLE, "", 0), true);
        setVirtualCallInProgress(false);
        // Done
        if (DBG) log("terminateScoUsingVirtualVoiceCall: Done");
        return true;
    }
Sreenidhi T's avatar
Sreenidhi T committed
2533

Nitin Srivastava's avatar
Nitin Srivastava committed
2534 2535 2536 2537 2538 2539
    private void processAnswerCall(BluetoothDevice device) {
        if(device == null) {
            Log.w(TAG, "processAnswerCall device is null");
            return;
        }

2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550
        if (mPhoneProxy != null) {
            try {
                mPhoneProxy.answerCall();
            } catch (RemoteException e) {
                Log.e(TAG, Log.getStackTraceString(new Throwable()));
            }
        } else {
            Log.e(TAG, "Handsfree phone proxy null for answering call");
        }
    }

Nitin Srivastava's avatar
Nitin Srivastava committed
2551 2552 2553 2554 2555
    private void processHangupCall(BluetoothDevice device) {
        if(device == null) {
            Log.w(TAG, "processHangupCall device is null");
            return;
        }
Syed Ibrahim M's avatar
Syed Ibrahim M committed
2556 2557 2558 2559
        // Close the virtual call if active. Virtual call should be
        // terminated for CHUP callback event
        if (isVirtualCallInProgress()) {
            terminateScoUsingVirtualVoiceCall();
2560
        } else {
Syed Ibrahim M's avatar
Syed Ibrahim M committed
2561 2562 2563 2564 2565 2566 2567 2568 2569
            if (mPhoneProxy != null) {
                try {
                    mPhoneProxy.hangupCall();
                } catch (RemoteException e) {
                    Log.e(TAG, Log.getStackTraceString(new Throwable()));
                }
            } else {
                Log.e(TAG, "Handsfree phone proxy null for hanging up call");
            }
2570 2571 2572
        }
    }

Nitin Srivastava's avatar
Nitin Srivastava committed
2573 2574 2575 2576 2577 2578
    private void processDialCall(String number, BluetoothDevice device) {
        if(device == null) {
            Log.w(TAG, "processDialCall device is null");
            return;
        }

2579
        String dialNumber;
2580 2581 2582 2583 2584 2585
        if (mDialingOut) {
            if (DBG) log("processDialCall, already dialling");
            atResponseCodeNative(HeadsetHalConstants.AT_RESPONSE_ERROR, 0,
                                       getByteAddress(device));
            return;
        }
2586
        if ((number == null) || (number.length() == 0)) {
2587 2588 2589
            dialNumber = mPhonebook.getLastDialledNumber();
            if (dialNumber == null) {
                if (DBG) log("processDialCall, last dial number null");
Nitin Srivastava's avatar
Nitin Srivastava committed
2590 2591
                atResponseCodeNative(HeadsetHalConstants.AT_RESPONSE_ERROR, 0,
                                       getByteAddress(device));
2592 2593 2594 2595 2596 2597
                return;
            }
        } else if (number.charAt(0) == '>') {
            // Yuck - memory dialling requested.
            // Just dial last number for now
            if (number.startsWith(">9999")) {   // for PTS test
Nitin Srivastava's avatar
Nitin Srivastava committed
2598 2599
                atResponseCodeNative(HeadsetHalConstants.AT_RESPONSE_ERROR, 0,
                                       getByteAddress(device));
2600 2601
                return;
            }
2602
            if (DBG) log("processDialCall, memory dial do last dial for now");
2603
            dialNumber = mPhonebook.getLastDialledNumber();
2604 2605
            if (dialNumber == null) {
                if (DBG) log("processDialCall, last dial number null");
Nitin Srivastava's avatar
Nitin Srivastava committed
2606 2607
                atResponseCodeNative(HeadsetHalConstants.AT_RESPONSE_ERROR, 0,
                                       getByteAddress(device));
2608 2609
                return;
            }
2610
        } else {
2611 2612 2613 2614 2615
            // Remove trailing ';'
            if (number.charAt(number.length() - 1) == ';') {
                number = number.substring(0, number.length() - 1);
            }

2616 2617
            dialNumber = PhoneNumberUtils.convertPreDial(number);
        }
Syed Ibrahim M's avatar
Syed Ibrahim M committed
2618 2619 2620
        // Check for virtual call to terminate before sending Call Intent
        terminateScoUsingVirtualVoiceCall();

2621 2622 2623
        Intent intent = new Intent(Intent.ACTION_CALL_PRIVILEGED,
                                   Uri.fromParts(SCHEME_TEL, dialNumber, null));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2624
        mService.startActivity(intent);
2625 2626 2627 2628
        // TODO(BT) continue send OK reults code after call starts
        //          hold wait lock, start a timer, set wait call flag
        //          Get call started indication from bluetooth phone
        mDialingOut = true;
Nitin Srivastava's avatar
Nitin Srivastava committed
2629
        Message m = obtainMessage(DIALING_OUT_TIMEOUT);
2630
        m.obj = getMatchingDevice(device);
Nitin Srivastava's avatar
Nitin Srivastava committed
2631
        sendMessageDelayed(m, DIALING_OUT_TIMEOUT_VALUE);
2632 2633
    }

Nitin Srivastava's avatar
Nitin Srivastava committed
2634 2635 2636 2637 2638 2639
    private void processVolumeEvent(int volumeType, int volume, BluetoothDevice device) {
        if(device != null && !device.equals(mActiveScoDevice) && mPhoneState.isInCall()) {
            Log.w(TAG, "ignore processVolumeEvent");
            return;
        }

2640
        if (volumeType == HeadsetHalConstants.VOLUME_TYPE_SPK) {
2641
            mPhoneState.setSpeakerVolume(volume);
2642 2643
            int flag = (getCurrentState() == mAudioOn) ? AudioManager.FLAG_SHOW_UI : 0;
            mAudioManager.setStreamVolume(AudioManager.STREAM_BLUETOOTH_SCO, volume, flag);
2644 2645 2646 2647 2648
        } else if (volumeType == HeadsetHalConstants.VOLUME_TYPE_MIC) {
            mPhoneState.setMicVolume(volume);
        } else {
            Log.e(TAG, "Bad voluem type: " + volumeType);
        }
2649 2650
    }

Nitin Srivastava's avatar
Nitin Srivastava committed
2651 2652 2653 2654 2655 2656
    private void processSendDtmf(int dtmf, BluetoothDevice device) {
        if(device == null) {
            Log.w(TAG, "processSendDtmf device is null");
            return;
        }

2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668
        if (mPhoneProxy != null) {
            try {
                mPhoneProxy.sendDtmf(dtmf);
            } catch (RemoteException e) {
                Log.e(TAG, Log.getStackTraceString(new Throwable()));
            }
        } else {
            Log.e(TAG, "Handsfree phone proxy null for sending DTMF");
        }
    }

    private void processCallState(HeadsetCallState callState) {
Syed Ibrahim M's avatar
Syed Ibrahim M committed
2669 2670 2671 2672 2673
        processCallState(callState, false);
    }

    private void processCallState(HeadsetCallState callState,
        boolean isVirtualCall) {
2674 2675 2676
        mPhoneState.setNumActiveCall(callState.mNumActive);
        mPhoneState.setNumHeldCall(callState.mNumHeld);
        mPhoneState.setCallState(callState.mCallState);
Nitin Srivastava's avatar
Nitin Srivastava committed
2677 2678 2679 2680
        if (mDialingOut) {
            if (callState.mCallState ==
                HeadsetHalConstants.CALL_STATE_DIALING) {
                BluetoothDevice device = getDeviceForMessage(DIALING_OUT_TIMEOUT);
2681 2682 2683
                if (device == null) {
                    return;
                }
Nitin Srivastava's avatar
Nitin Srivastava committed
2684 2685
                atResponseCodeNative(HeadsetHalConstants.AT_RESPONSE_OK,
                                                       0, getByteAddress(device));
2686
                removeMessages(DIALING_OUT_TIMEOUT);
Nitin Srivastava's avatar
Nitin Srivastava committed
2687 2688 2689
            } else if (callState.mCallState ==
                HeadsetHalConstants.CALL_STATE_ACTIVE || callState.mCallState
                == HeadsetHalConstants.CALL_STATE_IDLE) {				
2690
                mDialingOut = false;
Nitin Srivastava's avatar
Nitin Srivastava committed
2691
            } 
2692
        }
Nitin Srivastava's avatar
Nitin Srivastava committed
2693 2694 2695 2696 2697 2698

        /* Set ActiveScoDevice to null when call ends */
        if ((mActiveScoDevice != null) && !isInCall() &&
                callState.mCallState == HeadsetHalConstants.CALL_STATE_IDLE)
            mActiveScoDevice = null;

Syed Ibrahim M's avatar
Syed Ibrahim M committed
2699 2700
        log("mNumActive: " + callState.mNumActive + " mNumHeld: " +
            callState.mNumHeld +" mCallState: " + callState.mCallState);
2701
        log("mNumber: " + callState.mNumber + " mType: " + callState.mType);
2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715

        if (isVirtualCall) {
            // virtual call state update
            if (getCurrentState() != mDisconnected) {
                phoneStateChangeNative(callState.mNumActive, callState.mNumHeld,
                    callState.mCallState, callState.mNumber, callState.mType);
            }
        } else {
            // circuit-switch voice call update
            // stop virtual voice call if there is a CSV call ongoing
            if (callState.mNumActive > 0 || callState.mNumHeld > 0
                    || callState.mCallState != HeadsetHalConstants.CALL_STATE_IDLE) {
                terminateScoUsingVirtualVoiceCall();
            }
2716 2717 2718 2719 2720 2721 2722 2723 2724 2725

            // Specific handling for case of starting MO/MT call while VOIP
            // ongoing, terminateScoUsingVirtualVoiceCall() resets callState
            // INCOMING/DIALING to IDLE. Some HS send AT+CIND? to read call
            // and get wrong value of callsetup. This case is hit only
            // SCO for VOIP call is not terminated via SDK API call.
            if (mPhoneState.getCallState() != callState.mCallState) {
                mPhoneState.setCallState(callState.mCallState);
            }

2726 2727 2728 2729 2730 2731 2732 2733
            // at this step: if there is virtual call ongoing, it means there is no CSV call
            // let virtual call continue and skip phone state update
            if (!isVirtualCallInProgress()) {
                if (getCurrentState() != mDisconnected) {
                    phoneStateChangeNative(callState.mNumActive, callState.mNumHeld,
                        callState.mCallState, callState.mNumber, callState.mType);
                }
            }
2734
        }
2735 2736
    }

Nitin Srivastava's avatar
Nitin Srivastava committed
2737 2738 2739 2740
    // 1 enable noice reduction
    // 0 disable noice reduction
    private void processNoiceReductionEvent(int enable, BluetoothDevice device) {
        HashMap<String, Integer> AudioParamNrec = mHeadsetAudioParam.get(device);
Mallikarjuna GB's avatar
Mallikarjuna GB committed
2741 2742 2743 2744 2745 2746 2747 2748 2749 2750
        if (AudioParamNrec != null && !AudioParamNrec.isEmpty()) {
            if (enable == 1)
                AudioParamNrec.put("NREC", 1);
            else
                AudioParamNrec.put("NREC", 0);
            log("NREC value for device :" + device + " is: " +
                    AudioParamNrec.get("NREC"));
        } else {
            Log.e(TAG,"processNoiceReductionEvent: AudioParamNrec is null ");
        }
2751 2752
    }

2753 2754 2755 2756
    // 2 - WBS on
    // 1 - NBS on
    private void processWBSEvent(int enable, BluetoothDevice device) {
        if (enable == 2) {
Matthew Xie's avatar
Matthew Xie committed
2757
            Log.d(TAG, "AudioManager.setParameters bt_wbs=on for " +
2758 2759 2760
                        device.getName() + " - " + device.getAddress());
            mAudioManager.setParameters(HEADSET_WBS + "=on");
        } else {
Matthew Xie's avatar
Matthew Xie committed
2761
            Log.d(TAG, "AudioManager.setParameters bt_wbs=off for " +
2762 2763 2764 2765 2766
                        device.getName() + " - " + device.getAddress());
            mAudioManager.setParameters(HEADSET_WBS + "=off");
        }
    }

Nitin Srivastava's avatar
Nitin Srivastava committed
2767 2768 2769 2770 2771 2772
    private void processAtChld(int chld, BluetoothDevice device) {
        if(device == null) {
            Log.w(TAG, "processAtChld device is null");
            return;
        }

2773 2774 2775
        if (mPhoneProxy != null) {
            try {
                if (mPhoneProxy.processChld(chld)) {
Nitin Srivastava's avatar
Nitin Srivastava committed
2776 2777
                    atResponseCodeNative(HeadsetHalConstants.AT_RESPONSE_OK,
                                               0, getByteAddress(device));
2778
                } else {
Nitin Srivastava's avatar
Nitin Srivastava committed
2779 2780
                    atResponseCodeNative(HeadsetHalConstants.AT_RESPONSE_ERROR,
                                               0, getByteAddress(device));
2781 2782 2783
                }
            } catch (RemoteException e) {
                Log.e(TAG, Log.getStackTraceString(new Throwable()));
Nitin Srivastava's avatar
Nitin Srivastava committed
2784 2785
                atResponseCodeNative(HeadsetHalConstants.AT_RESPONSE_ERROR,
                                               0, getByteAddress(device));
2786 2787 2788
            }
        } else {
            Log.e(TAG, "Handsfree phone proxy null for At+Chld");
Nitin Srivastava's avatar
Nitin Srivastava committed
2789 2790
            atResponseCodeNative(HeadsetHalConstants.AT_RESPONSE_ERROR,
                                               0, getByteAddress(device));
2791 2792 2793
        }
    }

Nitin Srivastava's avatar
Nitin Srivastava committed
2794 2795 2796 2797 2798 2799
    private void processSubscriberNumberRequest(BluetoothDevice device) {
        if(device == null) {
            Log.w(TAG, "processSubscriberNumberRequest device is null");
            return;
        }

2800 2801 2802 2803 2804
        if (mPhoneProxy != null) {
            try {
                String number = mPhoneProxy.getSubscriberNumber();
                if (number != null) {
                    atResponseStringNative("+CNUM: ,\"" + number + "\"," +
2805 2806
                                                PhoneNumberUtils.toaFromString(number) +
                                                ",,4", getByteAddress(device));
Nitin Srivastava's avatar
Nitin Srivastava committed
2807
                    atResponseCodeNative(HeadsetHalConstants.AT_RESPONSE_OK,
2808 2809 2810 2811 2812
                                                0, getByteAddress(device));
                } else {
                    Log.e(TAG, "getSubscriberNumber returns null");
                    atResponseCodeNative(HeadsetHalConstants.AT_RESPONSE_ERROR,
                                                0, getByteAddress(device));
2813 2814 2815
                }
            } catch (RemoteException e) {
                Log.e(TAG, Log.getStackTraceString(new Throwable()));
Nitin Srivastava's avatar
Nitin Srivastava committed
2816 2817
                atResponseCodeNative(HeadsetHalConstants.AT_RESPONSE_ERROR,
                                                 0, getByteAddress(device));
2818 2819 2820 2821 2822 2823
            }
        } else {
            Log.e(TAG, "Handsfree phone proxy null for At+CNUM");
        }
    }

Nitin Srivastava's avatar
Nitin Srivastava committed
2824
    private void processAtCind(BluetoothDevice device) {
Syed Ibrahim M's avatar
Syed Ibrahim M committed
2825 2826
        int call, call_setup;

Nitin Srivastava's avatar
Nitin Srivastava committed
2827 2828 2829 2830 2831
        if(device == null) {
            Log.w(TAG, "processAtCind device is null");
            return;
        }

Syed Ibrahim M's avatar
Syed Ibrahim M committed
2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845
        /* Handsfree carkits expect that +CIND is properly responded to
         Hence we ensure that a proper response is sent
         for the virtual call too.*/
        if (isVirtualCallInProgress()) {
            call = 1;
            call_setup = 0;
        } else {
            // regular phone call
            call = mPhoneState.getNumActiveCall();
            call_setup = mPhoneState.getNumHeldCall();
        }

        cindResponseNative(mPhoneState.getService(), call,
                           call_setup, mPhoneState.getCallState(),
2846
                           mPhoneState.getSignal(), mPhoneState.getRoam(),
Nitin Srivastava's avatar
Nitin Srivastava committed
2847
                           mPhoneState.getBatteryCharge(), getByteAddress(device));
2848 2849
    }

Nitin Srivastava's avatar
Nitin Srivastava committed
2850 2851 2852 2853 2854 2855
    private void processAtCops(BluetoothDevice device) {
        if(device == null) {
            Log.w(TAG, "processAtCops device is null");
            return;
        }

2856 2857 2858 2859 2860 2861
        if (mPhoneProxy != null) {
            try {
                String operatorName = mPhoneProxy.getNetworkOperator();
                if (operatorName == null) {
                    operatorName = "";
                } 
Nitin Srivastava's avatar
Nitin Srivastava committed
2862
                copsResponseNative(operatorName, getByteAddress(device));
2863 2864
            } catch (RemoteException e) {
                Log.e(TAG, Log.getStackTraceString(new Throwable()));
Nitin Srivastava's avatar
Nitin Srivastava committed
2865
                copsResponseNative("", getByteAddress(device));
2866 2867 2868
            }
        } else {
            Log.e(TAG, "Handsfree phone proxy null for At+COPS");
Nitin Srivastava's avatar
Nitin Srivastava committed
2869
            copsResponseNative("", getByteAddress(device));
2870 2871 2872
        }
    }

Nitin Srivastava's avatar
Nitin Srivastava committed
2873 2874 2875 2876 2877 2878
    private void processAtClcc(BluetoothDevice device) {
        if(device == null) {
            Log.w(TAG, "processAtClcc device is null");
            return;
        }

2879 2880
        if (mPhoneProxy != null) {
            try {
Syed Ibrahim M's avatar
Syed Ibrahim M committed
2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891
                if(isVirtualCallInProgress()) {
                    String phoneNumber = "";
                    int type = PhoneNumberUtils.TOA_Unknown;
                    try {
                        phoneNumber = mPhoneProxy.getSubscriberNumber();
                        type = PhoneNumberUtils.toaFromString(phoneNumber);
                    } catch (RemoteException ee) {
                        Log.e(TAG, "Unable to retrieve phone number"+
                            "using IBluetoothHeadsetPhone proxy");
                        phoneNumber = "";
                    }
Nitin Srivastava's avatar
Nitin Srivastava committed
2892 2893
                    clccResponseNative(1, 0, 0, 0, false, phoneNumber, type,
                                                       getByteAddress(device));
2894
                    clccResponseNative(0, 0, 0, 0, false, "", 0, getByteAddress(device));
Syed Ibrahim M's avatar
Syed Ibrahim M committed
2895 2896
                }
                else if (!mPhoneProxy.listCurrentCalls()) {
Nitin Srivastava's avatar
Nitin Srivastava committed
2897 2898 2899 2900 2901 2902 2903 2904 2905 2906
                    clccResponseNative(0, 0, 0, 0, false, "", 0,
                                                       getByteAddress(device));
                }
                else
                {
                    Log.d(TAG, "Starting CLCC response timeout for device: "
                                                                     + device);
                    Message m = obtainMessage(CLCC_RSP_TIMEOUT);
                    m.obj = getMatchingDevice(device);
                    sendMessageDelayed(m, CLCC_RSP_TIMEOUT_VALUE);
2907 2908 2909
                }
            } catch (RemoteException e) {
                Log.e(TAG, Log.getStackTraceString(new Throwable()));
Nitin Srivastava's avatar
Nitin Srivastava committed
2910
                clccResponseNative(0, 0, 0, 0, false, "", 0, getByteAddress(device));
2911 2912 2913
            }
        } else {
            Log.e(TAG, "Handsfree phone proxy null for At+CLCC");
Nitin Srivastava's avatar
Nitin Srivastava committed
2914
            clccResponseNative(0, 0, 0, 0, false, "", 0, getByteAddress(device));
2915 2916 2917
        }
    }

Nitin Srivastava's avatar
Nitin Srivastava committed
2918
    private void processAtCscs(String atString, int type, BluetoothDevice device) {
Sreenidhi T's avatar
Sreenidhi T committed
2919 2920
        log("processAtCscs - atString = "+ atString);
        if(mPhonebook != null) {
Nitin Srivastava's avatar
Nitin Srivastava committed
2921
            mPhonebook.handleCscsCommand(atString, type, device);
Sreenidhi T's avatar
Sreenidhi T committed
2922 2923 2924
        }
        else {
            Log.e(TAG, "Phonebook handle null for At+CSCS");
Nitin Srivastava's avatar
Nitin Srivastava committed
2925
            atResponseCodeNative(HeadsetHalConstants.AT_RESPONSE_ERROR, 0, getByteAddress(device));
Sreenidhi T's avatar
Sreenidhi T committed
2926 2927 2928
        }
    }

Nitin Srivastava's avatar
Nitin Srivastava committed
2929
    private void processAtCpbs(String atString, int type, BluetoothDevice device) {
Sreenidhi T's avatar
Sreenidhi T committed
2930 2931
        log("processAtCpbs - atString = "+ atString);
        if(mPhonebook != null) {
Nitin Srivastava's avatar
Nitin Srivastava committed
2932
            mPhonebook.handleCpbsCommand(atString, type, device);
Sreenidhi T's avatar
Sreenidhi T committed
2933 2934 2935
        }
        else {
            Log.e(TAG, "Phonebook handle null for At+CPBS");
Nitin Srivastava's avatar
Nitin Srivastava committed
2936
            atResponseCodeNative(HeadsetHalConstants.AT_RESPONSE_ERROR, 0, getByteAddress(device));
Sreenidhi T's avatar
Sreenidhi T committed
2937 2938 2939
        }
    }

Nitin Srivastava's avatar
Nitin Srivastava committed
2940
    private void processAtCpbr(String atString, int type, BluetoothDevice device) {
Sreenidhi T's avatar
Sreenidhi T committed
2941 2942
        log("processAtCpbr - atString = "+ atString);
        if(mPhonebook != null) {
Nitin Srivastava's avatar
Nitin Srivastava committed
2943
            mPhonebook.handleCpbrCommand(atString, type, device);
Sreenidhi T's avatar
Sreenidhi T committed
2944 2945 2946
        }
        else {
            Log.e(TAG, "Phonebook handle null for At+CPBR");
Nitin Srivastava's avatar
Nitin Srivastava committed
2947
            atResponseCodeNative(HeadsetHalConstants.AT_RESPONSE_ERROR, 0, getByteAddress(device));
Sreenidhi T's avatar
Sreenidhi T committed
2948 2949 2950
        }
    }

2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993
    /**
     * Find a character ch, ignoring quoted sections.
     * Return input.length() if not found.
     */
    static private int findChar(char ch, String input, int fromIndex) {
        for (int i = fromIndex; i < input.length(); i++) {
            char c = input.charAt(i);
            if (c == '"') {
                i = input.indexOf('"', i + 1);
                if (i == -1) {
                    return input.length();
                }
            } else if (c == ch) {
                return i;
            }
        }
        return input.length();
    }

    /**
     * Break an argument string into individual arguments (comma delimited).
     * Integer arguments are turned into Integer objects. Otherwise a String
     * object is used.
     */
    static private Object[] generateArgs(String input) {
        int i = 0;
        int j;
        ArrayList<Object> out = new ArrayList<Object>();
        while (i <= input.length()) {
            j = findChar(',', input, i);

            String arg = input.substring(i, j);
            try {
                out.add(new Integer(arg));
            } catch (NumberFormatException e) {
                out.add(arg);
            }

            i = j + 1; // move past comma
        }
        return out.toArray();
    }

2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004
    /**
     * @return {@code true} if the given string is a valid vendor-specific AT command.
     */
    private boolean processVendorSpecificAt(String atString) {
        log("processVendorSpecificAt - atString = " + atString);

        // Currently we accept only SET type commands.
        int indexOfEqual = atString.indexOf("=");
        if (indexOfEqual == -1) {
            Log.e(TAG, "processVendorSpecificAt: command type error in " + atString);
            return false;
3005
        }
3006 3007 3008 3009 3010 3011

        String command = atString.substring(0, indexOfEqual);
        Integer companyId = VENDOR_SPECIFIC_AT_COMMAND_COMPANY_ID.get(command);
        if (companyId == null) {
            Log.e(TAG, "processVendorSpecificAt: unsupported command: " + atString);
            return false;
3012
        }
3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025

        String arg = atString.substring(indexOfEqual + 1);
        if (arg.startsWith("?")) {
            Log.e(TAG, "processVendorSpecificAt: command type error in " + atString);
            return false;
        }

        Object[] args = generateArgs(arg);
        broadcastVendorSpecificEventIntent(command,
                                           companyId,
                                           BluetoothHeadset.AT_CMD_TYPE_SET,
                                           args,
                                           mCurrentDevice);
Nitin Srivastava's avatar
Nitin Srivastava committed
3026
        atResponseCodeNative(HeadsetHalConstants.AT_RESPONSE_OK, 0, getByteAddress(mCurrentDevice));
3027
        return true;
3028 3029
    }

Nitin Srivastava's avatar
Nitin Srivastava committed
3030 3031 3032 3033 3034 3035
    private void processUnknownAt(String atString, BluetoothDevice device) {
        if(device == null) {
            Log.w(TAG, "processUnknownAt device is null");
            return;
        }

3036
        // TODO (BT)
Sreenidhi T's avatar
Sreenidhi T committed
3037 3038 3039 3040
        log("processUnknownAt - atString = "+ atString);
        String atCommand = parseUnknownAt(atString);
        int commandType = getAtCommandType(atCommand);
        if (atCommand.startsWith("+CSCS"))
Nitin Srivastava's avatar
Nitin Srivastava committed
3041
            processAtCscs(atCommand.substring(5), commandType, device);
Sreenidhi T's avatar
Sreenidhi T committed
3042
        else if (atCommand.startsWith("+CPBS"))
Nitin Srivastava's avatar
Nitin Srivastava committed
3043
            processAtCpbs(atCommand.substring(5), commandType, device);
Sreenidhi T's avatar
Sreenidhi T committed
3044
        else if (atCommand.startsWith("+CPBR"))
Nitin Srivastava's avatar
Nitin Srivastava committed
3045
            processAtCpbr(atCommand.substring(5), commandType, device);
3046
        else if (!processVendorSpecificAt(atCommand))
Nitin Srivastava's avatar
Nitin Srivastava committed
3047
            atResponseCodeNative(HeadsetHalConstants.AT_RESPONSE_ERROR, 0, getByteAddress(device));
3048 3049
    }

Nitin Srivastava's avatar
Nitin Srivastava committed
3050 3051 3052 3053 3054 3055
    private void processKeyPressed(BluetoothDevice device) {
        if(device == null) {
            Log.w(TAG, "processKeyPressed device is null");
            return;
        }

3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066
        if (mPhoneState.getCallState() == HeadsetHalConstants.CALL_STATE_INCOMING) {
            if (mPhoneProxy != null) {
                try {
                    mPhoneProxy.answerCall();
                } catch (RemoteException e) {
                    Log.e(TAG, Log.getStackTraceString(new Throwable()));
                }
            } else {
                Log.e(TAG, "Handsfree phone proxy null for answering call");
            }
        } else if (mPhoneState.getNumActiveCall() > 0) {
3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080
            if (!isAudioOn())
            {
                connectAudioNative(getByteAddress(mCurrentDevice));
            }
            else
            {
                if (mPhoneProxy != null) {
                    try {
                        mPhoneProxy.hangupCall();
                    } catch (RemoteException e) {
                        Log.e(TAG, Log.getStackTraceString(new Throwable()));
                    }
                } else {
                    Log.e(TAG, "Handsfree phone proxy null for hangup call");
3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091
                }
            }
        } else {
            String dialNumber = mPhonebook.getLastDialledNumber();
            if (dialNumber == null) {
                if (DBG) log("processKeyPressed, last dial number null");
                return;
            }
            Intent intent = new Intent(Intent.ACTION_CALL_PRIVILEGED,
                                       Uri.fromParts(SCHEME_TEL, dialNumber, null));
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3092
            mService.startActivity(intent);
3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109
        }
    }

    private void onConnectionStateChanged(int state, byte[] address) {
        StackEvent event = new StackEvent(EVENT_TYPE_CONNECTION_STATE_CHANGED);
        event.valueInt = state;
        event.device = getDevice(address);
        sendMessage(STACK_EVENT, event);
    }

    private void onAudioStateChanged(int state, byte[] address) {
        StackEvent event = new StackEvent(EVENT_TYPE_AUDIO_STATE_CHANGED);
        event.valueInt = state;
        event.device = getDevice(address);
        sendMessage(STACK_EVENT, event);
    }

Nitin Srivastava's avatar
Nitin Srivastava committed
3110
    private void onVrStateChanged(int state, byte[] address) {
3111 3112
        StackEvent event = new StackEvent(EVENT_TYPE_VR_STATE_CHANGED);
        event.valueInt = state;
Nitin Srivastava's avatar
Nitin Srivastava committed
3113
        event.device = getDevice(address);
3114 3115 3116
        sendMessage(STACK_EVENT, event);
    }

Nitin Srivastava's avatar
Nitin Srivastava committed
3117
    private void onAnswerCall(byte[] address) {
3118
        StackEvent event = new StackEvent(EVENT_TYPE_ANSWER_CALL);
Nitin Srivastava's avatar
Nitin Srivastava committed
3119
        event.device = getDevice(address);
3120 3121 3122
        sendMessage(STACK_EVENT, event);
    }

Nitin Srivastava's avatar
Nitin Srivastava committed
3123
    private void onHangupCall(byte[] address) {
3124
        StackEvent event = new StackEvent(EVENT_TYPE_HANGUP_CALL);
Nitin Srivastava's avatar
Nitin Srivastava committed
3125
        event.device = getDevice(address);
3126 3127 3128
        sendMessage(STACK_EVENT, event);
    }

Nitin Srivastava's avatar
Nitin Srivastava committed
3129
    private void onVolumeChanged(int type, int volume, byte[] address) {
3130 3131 3132
        StackEvent event = new StackEvent(EVENT_TYPE_VOLUME_CHANGED);
        event.valueInt = type;
        event.valueInt2 = volume;
Nitin Srivastava's avatar
Nitin Srivastava committed
3133
        event.device = getDevice(address);
3134 3135 3136
        sendMessage(STACK_EVENT, event);
    }

Nitin Srivastava's avatar
Nitin Srivastava committed
3137
    private void onDialCall(String number, byte[] address) {
3138 3139
        StackEvent event = new StackEvent(EVENT_TYPE_DIAL_CALL);
        event.valueString = number;
Nitin Srivastava's avatar
Nitin Srivastava committed
3140
        event.device = getDevice(address);
3141 3142 3143
        sendMessage(STACK_EVENT, event);
    }

Nitin Srivastava's avatar
Nitin Srivastava committed
3144
    private void onSendDtmf(int dtmf, byte[] address) {
3145 3146
        StackEvent event = new StackEvent(EVENT_TYPE_SEND_DTMF);
        event.valueInt = dtmf;
Nitin Srivastava's avatar
Nitin Srivastava committed
3147
        event.device = getDevice(address);
3148 3149 3150
        sendMessage(STACK_EVENT, event);
    }

Nitin Srivastava's avatar
Nitin Srivastava committed
3151
    private void onNoiceReductionEnable(boolean enable,  byte[] address) {
3152 3153
        StackEvent event = new StackEvent(EVENT_TYPE_NOICE_REDUCTION);
        event.valueInt = enable ? 1 : 0;
Nitin Srivastava's avatar
Nitin Srivastava committed
3154
        event.device = getDevice(address);
3155 3156 3157
        sendMessage(STACK_EVENT, event);
    }

3158 3159 3160 3161 3162 3163 3164
    private void onWBS(int codec, byte[] address) {
        StackEvent event = new StackEvent(EVENT_TYPE_WBS);
        event.valueInt = codec;
        event.device = getDevice(address);
        sendMessage(STACK_EVENT, event);
    }

Nitin Srivastava's avatar
Nitin Srivastava committed
3165
    private void onAtChld(int chld, byte[] address) {
3166 3167
        StackEvent event = new StackEvent(EVENT_TYPE_AT_CHLD);
        event.valueInt = chld;
Nitin Srivastava's avatar
Nitin Srivastava committed
3168
        event.device = getDevice(address);
3169 3170 3171
        sendMessage(STACK_EVENT, event);
    }

Nitin Srivastava's avatar
Nitin Srivastava committed
3172
    private void onAtCnum(byte[] address) {
3173
        StackEvent event = new StackEvent(EVENT_TYPE_SUBSCRIBER_NUMBER_REQUEST);
Nitin Srivastava's avatar
Nitin Srivastava committed
3174
        event.device = getDevice(address);
3175 3176 3177
        sendMessage(STACK_EVENT, event);
    }

Nitin Srivastava's avatar
Nitin Srivastava committed
3178
    private void onAtCind(byte[] address) {
3179
        StackEvent event = new StackEvent(EVENT_TYPE_AT_CIND);
Nitin Srivastava's avatar
Nitin Srivastava committed
3180
        event.device = getDevice(address);
3181 3182 3183
        sendMessage(STACK_EVENT, event);
    }

Nitin Srivastava's avatar
Nitin Srivastava committed
3184
    private void onAtCops(byte[] address) {
3185
        StackEvent event = new StackEvent(EVENT_TYPE_AT_COPS);
Nitin Srivastava's avatar
Nitin Srivastava committed
3186
        event.device = getDevice(address);
3187 3188 3189
        sendMessage(STACK_EVENT, event);
    }

Nitin Srivastava's avatar
Nitin Srivastava committed
3190
    private void onAtClcc(byte[] address) {
3191
        StackEvent event = new StackEvent(EVENT_TYPE_AT_CLCC);
Nitin Srivastava's avatar
Nitin Srivastava committed
3192
        event.device = getDevice(address);
3193 3194 3195
        sendMessage(STACK_EVENT, event);
    }

Nitin Srivastava's avatar
Nitin Srivastava committed
3196
    private void onUnknownAt(String atString, byte[] address) {
3197 3198
        StackEvent event = new StackEvent(EVENT_TYPE_UNKNOWN_AT);
        event.valueString = atString;
Nitin Srivastava's avatar
Nitin Srivastava committed
3199
        event.device = getDevice(address);
3200 3201 3202
        sendMessage(STACK_EVENT, event);
    }

Nitin Srivastava's avatar
Nitin Srivastava committed
3203
    private void onKeyPressed(byte[] address) {
3204
        StackEvent event = new StackEvent(EVENT_TYPE_KEY_PRESSED);
Nitin Srivastava's avatar
Nitin Srivastava committed
3205
        event.device = getDevice(address);
3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225
        sendMessage(STACK_EVENT, event);
    }

    private void processIntentBatteryChanged(Intent intent) {
        int batteryLevel = intent.getIntExtra("level", -1);
        int scale = intent.getIntExtra("scale", -1);
        if (batteryLevel == -1 || scale == -1 || scale == 0) {
            Log.e(TAG, "Bad Battery Changed intent: " + batteryLevel + "," + scale);
            return;
        }
        batteryLevel = batteryLevel * 5 / scale;
        mPhoneState.setBatteryCharge(batteryLevel);
    }

    private void processDeviceStateChanged(HeadsetDeviceState deviceState) {
        notifyDeviceStatusNative(deviceState.mService, deviceState.mRoam, deviceState.mSignal,
                                 deviceState.mBatteryCharge);
    }

    private void processSendClccResponse(HeadsetClccResponse clcc) {
Nitin Srivastava's avatar
Nitin Srivastava committed
3226
        BluetoothDevice device = getDeviceForMessage(CLCC_RSP_TIMEOUT);
3227 3228 3229
        if (device == null) {
            return;
        }
Nitin Srivastava's avatar
Nitin Srivastava committed
3230 3231 3232
        if (clcc.mIndex == 0) {
            removeMessages(CLCC_RSP_TIMEOUT);
        }
3233
        clccResponseNative(clcc.mIndex, clcc.mDirection, clcc.mStatus, clcc.mMode, clcc.mMpty,
Nitin Srivastava's avatar
Nitin Srivastava committed
3234
                           clcc.mNumber, clcc.mType, getByteAddress(device));
3235 3236
    }

3237 3238 3239 3240 3241
    private void processSendVendorSpecificResultCode(HeadsetVendorSpecificResultCode resultCode) {
        String stringToSend = resultCode.mCommand + ": ";
        if (resultCode.mArg != null) {
            stringToSend += resultCode.mArg;
        }
Nitin Srivastava's avatar
Nitin Srivastava committed
3242
        atResponseStringNative(stringToSend, getByteAddress(resultCode.mDevice));
3243 3244
    }

Nitin Srivastava's avatar
Nitin Srivastava committed
3245
    private String getCurrentDeviceName(BluetoothDevice device) {
3246
        String defaultName = "<unknown>";
Nitin Srivastava's avatar
Nitin Srivastava committed
3247 3248

        if(device == null) {
3249 3250
            return defaultName;
        }
Nitin Srivastava's avatar
Nitin Srivastava committed
3251 3252

        String deviceName = device.getName();
3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267
        if (deviceName == null) {
            return defaultName;
        }
        return deviceName;
    }

    private byte[] getByteAddress(BluetoothDevice device) {
        return Utils.getBytesFromAddress(device.getAddress());
    }

    private BluetoothDevice getDevice(byte[] address) {
        return mAdapter.getRemoteDevice(Utils.getAddressStringFromByte(address));
    }

    private boolean isInCall() {
3268 3269
        return ((mPhoneState.getNumActiveCall() > 0) || (mPhoneState.getNumHeldCall() > 0) ||
                (mPhoneState.getCallState() != HeadsetHalConstants.CALL_STATE_IDLE));
3270 3271
    }

3272 3273 3274 3275 3276 3277
    // Accept incoming SCO only when there is active call, VR activated,
    // active VOIP call
    private boolean isScoAcceptable() {
        return (mVoiceRecognitionStarted || isInCall());
    }

3278 3279 3280 3281 3282
    boolean isConnected() {
        IState currentState = getCurrentState();
        return (currentState == mConnected || currentState == mAudioOn);
    }

3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303
    boolean okToConnect(BluetoothDevice device) {
        AdapterService adapterService = AdapterService.getAdapterService();
        int priority = mService.getPriority(device);
        boolean ret = false;
        //check if this is an incoming connection in Quiet mode.
        if((adapterService == null) ||
           ((adapterService.isQuietModeEnabled() == true) &&
           (mTargetDevice == null))){
            ret = false;
        }
        // check priority and accept or reject the connection. if priority is undefined
        // it is likely that our SDP has not completed and peer is initiating the
        // connection. Allow this connection, provided the device is bonded
        else if((BluetoothProfile.PRIORITY_OFF < priority) ||
                ((BluetoothProfile.PRIORITY_UNDEFINED == priority) &&
                (device.getBondState() != BluetoothDevice.BOND_NONE))){
            ret= true;
        }
        return ret;
    }

3304 3305
    @Override
    protected void log(String msg) {
3306
        if (DBG) {
3307
            super.log(msg);
3308 3309 3310
        }
    }

Sreenidhi T's avatar
Sreenidhi T committed
3311 3312
    public void handleAccessPermissionResult(Intent intent) {
        log("handleAccessPermissionResult");
Nitin Srivastava's avatar
Nitin Srivastava committed
3313
        BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
3314
        if (mPhonebook != null) {
Sreenidhi T's avatar
Sreenidhi T committed
3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325
            if (!mPhonebook.getCheckingAccessPermission()) {
                return;
            }
            int atCommandResult = 0;
            int atCommandErrorCode = 0;
            //HeadsetBase headset = mHandsfree.getHeadset();
            // ASSERT: (headset != null) && headSet.isConnected()
            // REASON: mCheckingAccessPermission is true, otherwise resetAtState
            // has set mCheckingAccessPermission to false
            if (intent.getAction().equals(BluetoothDevice.ACTION_CONNECTION_ACCESS_REPLY)) {
                if (intent.getIntExtra(BluetoothDevice.EXTRA_CONNECTION_ACCESS_RESULT,
3326 3327
                                       BluetoothDevice.CONNECTION_ACCESS_NO)
                        == BluetoothDevice.CONNECTION_ACCESS_YES) {
Sreenidhi T's avatar
Sreenidhi T committed
3328
                    if (intent.getBooleanExtra(BluetoothDevice.EXTRA_ALWAYS_ALLOWED, false)) {
3329
                        mCurrentDevice.setPhonebookAccessPermission(BluetoothDevice.ACCESS_ALLOWED);
Sreenidhi T's avatar
Sreenidhi T committed
3330
                    }
Nitin Srivastava's avatar
Nitin Srivastava committed
3331
                    atCommandResult = mPhonebook.processCpbrCommand(device);
3332 3333 3334 3335 3336
                } else {
                    if (intent.getBooleanExtra(BluetoothDevice.EXTRA_ALWAYS_ALLOWED, false)) {
                        mCurrentDevice.setPhonebookAccessPermission(
                                BluetoothDevice.ACCESS_REJECTED);
                    }
Sreenidhi T's avatar
Sreenidhi T committed
3337 3338 3339 3340 3341 3342
                }
            }
            mPhonebook.setCpbrIndex(-1);
            mPhonebook.setCheckingAccessPermission(false);

            if (atCommandResult >= 0) {
Nitin Srivastava's avatar
Nitin Srivastava committed
3343
                atResponseCodeNative(atCommandResult, atCommandErrorCode, getByteAddress(device));
3344
            } else {
Sreenidhi T's avatar
Sreenidhi T committed
3345
                log("handleAccessPermissionResult - RESULT_NONE");
3346 3347
            }
        } else {
Sreenidhi T's avatar
Sreenidhi T committed
3348
            Log.e(TAG, "Phonebook handle null");
3349
            if (device != null) {
Nitin Srivastava's avatar
Nitin Srivastava committed
3350 3351 3352
                atResponseCodeNative(HeadsetHalConstants.AT_RESPONSE_ERROR, 0,
                                     getByteAddress(device));
            }
Sreenidhi T's avatar
Sreenidhi T committed
3353 3354 3355
        }
    }

3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375
    private static final String SCHEME_TEL = "tel";

    // Event types for STACK_EVENT message
    final private static int EVENT_TYPE_NONE = 0;
    final private static int EVENT_TYPE_CONNECTION_STATE_CHANGED = 1;
    final private static int EVENT_TYPE_AUDIO_STATE_CHANGED = 2;
    final private static int EVENT_TYPE_VR_STATE_CHANGED = 3;
    final private static int EVENT_TYPE_ANSWER_CALL = 4;
    final private static int EVENT_TYPE_HANGUP_CALL = 5;
    final private static int EVENT_TYPE_VOLUME_CHANGED = 6;
    final private static int EVENT_TYPE_DIAL_CALL = 7;
    final private static int EVENT_TYPE_SEND_DTMF = 8;
    final private static int EVENT_TYPE_NOICE_REDUCTION = 9;
    final private static int EVENT_TYPE_AT_CHLD = 10;
    final private static int EVENT_TYPE_SUBSCRIBER_NUMBER_REQUEST = 11;
    final private static int EVENT_TYPE_AT_CIND = 12;
    final private static int EVENT_TYPE_AT_COPS = 13;
    final private static int EVENT_TYPE_AT_CLCC = 14;
    final private static int EVENT_TYPE_UNKNOWN_AT = 15;
    final private static int EVENT_TYPE_KEY_PRESSED = 16;
3376
    final private static int EVENT_TYPE_WBS = 17;
3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389

    private class StackEvent {
        int type = EVENT_TYPE_NONE;
        int valueInt = 0;
        int valueInt2 = 0;
        String valueString = null;
        BluetoothDevice device = null;

        private StackEvent(int type) {
            this.type = type;
        }
    }

Nitin Srivastava's avatar
Nitin Srivastava committed
3390 3391 3392
    /*package*/native boolean atResponseCodeNative(int responseCode, int errorCode,
                                                                          byte[] address);
    /*package*/ native boolean atResponseStringNative(String responseString, byte[] address);
Sreenidhi T's avatar
Sreenidhi T committed
3393

3394
    private native static void classInitNative();
Nitin Srivastava's avatar
Nitin Srivastava committed
3395
    private native void initializeNative(int max_hf_clients);
fredc's avatar
fredc committed
3396
    private native void cleanupNative();
3397 3398 3399 3400
    private native boolean connectHfpNative(byte[] address);
    private native boolean disconnectHfpNative(byte[] address);
    private native boolean connectAudioNative(byte[] address);
    private native boolean disconnectAudioNative(byte[] address);
Nitin Srivastava's avatar
Nitin Srivastava committed
3401 3402 3403
    private native boolean startVoiceRecognitionNative(byte[] address);
    private native boolean stopVoiceRecognitionNative(byte[] address);
    private native boolean setVolumeNative(int volumeType, int volume, byte[] address);
3404 3405
    private native boolean cindResponseNative(int service, int numActive, int numHeld,
                                              int callState, int signal, int roam,
Nitin Srivastava's avatar
Nitin Srivastava committed
3406
                                              int batteryCharge, byte[] address);
3407 3408
    private native boolean notifyDeviceStatusNative(int networkState, int serviceType, int signal,
                                                    int batteryCharge);
Sreenidhi T's avatar
Sreenidhi T committed
3409

3410
    private native boolean clccResponseNative(int index, int dir, int status, int mode,
Nitin Srivastava's avatar
Nitin Srivastava committed
3411 3412 3413
                                              boolean mpty, String number, int type,
                                                                           byte[] address);
    private native boolean copsResponseNative(String operatorName, byte[] address);
Sreenidhi T's avatar
Sreenidhi T committed
3414

3415 3416
    private native boolean phoneStateChangeNative(int numActive, int numHeld, int callState,
                                                  String number, int type);
3417
    private native boolean configureWBSNative(byte[] address,int condec_config);
3418
}