BluetoothHandsfree.java revision f9f946bc1e3ba287f0fa8f47a662e42f20892526
1/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.phone;
18
19import android.bluetooth.AtCommandHandler;
20import android.bluetooth.AtCommandResult;
21import android.bluetooth.AtParser;
22import android.bluetooth.BluetoothA2dp;
23import android.bluetooth.BluetoothAdapter;
24import android.bluetooth.BluetoothDevice;
25import android.bluetooth.BluetoothHeadset;
26import android.bluetooth.HeadsetBase;
27import android.bluetooth.ScoSocket;
28import android.content.ActivityNotFoundException;
29import android.content.BroadcastReceiver;
30import android.content.Context;
31import android.content.Intent;
32import android.content.IntentFilter;
33import android.media.AudioManager;
34import android.net.Uri;
35import android.os.AsyncResult;
36import android.os.Bundle;
37import android.os.Handler;
38import android.os.Message;
39import android.os.PowerManager;
40import android.os.PowerManager.WakeLock;
41import android.os.SystemProperties;
42import android.telephony.PhoneNumberUtils;
43import android.telephony.ServiceState;
44import android.telephony.SignalStrength;
45import android.util.Log;
46
47import com.android.internal.telephony.Call;
48import com.android.internal.telephony.Connection;
49import com.android.internal.telephony.Phone;
50import com.android.internal.telephony.TelephonyIntents;
51
52import java.util.LinkedList;
53
54/**
55 * Bluetooth headset manager for the Phone app.
56 * @hide
57 */
58public class BluetoothHandsfree {
59    private static final String TAG = "BT HS/HF";
60    private static final boolean DBG = (PhoneApp.DBG_LEVEL >= 1)
61            && (SystemProperties.getInt("ro.debuggable", 0) == 1);
62    private static final boolean VDBG = (PhoneApp.DBG_LEVEL >= 2);  // even more logging
63
64    public static final int TYPE_UNKNOWN           = 0;
65    public static final int TYPE_HEADSET           = 1;
66    public static final int TYPE_HANDSFREE         = 2;
67
68    private final Context mContext;
69    private final Phone mPhone;
70    private final BluetoothA2dp mA2dp;
71
72    private BluetoothDevice mA2dpDevice;
73    private int mA2dpState;
74
75    private ServiceState mServiceState;
76    private HeadsetBase mHeadset;  // null when not connected
77    private int mHeadsetType;
78    private boolean mAudioPossible;
79    private ScoSocket mIncomingSco;
80    private ScoSocket mOutgoingSco;
81    private ScoSocket mConnectedSco;
82
83    private Call mForegroundCall;
84    private Call mBackgroundCall;
85    private Call mRingingCall;
86
87    private AudioManager mAudioManager;
88    private PowerManager mPowerManager;
89
90    private boolean mPendingSco;  // waiting for a2dp sink to suspend before establishing SCO
91    private boolean mUserWantsAudio;
92    private WakeLock mStartCallWakeLock;  // held while waiting for the intent to start call
93    private WakeLock mStartVoiceRecognitionWakeLock;  // held while waiting for voice recognition
94
95    // AT command state
96    private static final int GSM_MAX_CONNECTIONS = 6;  // Max connections allowed by GSM
97    private static final int CDMA_MAX_CONNECTIONS = 2;  // Max connections allowed by CDMA
98
99    private long mBgndEarliestConnectionTime = 0;
100    private boolean mClip = false;  // Calling Line Information Presentation
101    private boolean mIndicatorsEnabled = false;
102    private boolean mCmee = false;  // Extended Error reporting
103    private long[] mClccTimestamps; // Timestamps associated with each clcc index
104    private boolean[] mClccUsed;     // Is this clcc index in use
105    private boolean mWaitingForCallStart;
106    private boolean mWaitingForVoiceRecognition;
107    // do not connect audio until service connection is established
108    // for 3-way supported devices, this is after AT+CHLD
109    // for non-3-way supported devices, this is after AT+CMER (see spec)
110    private boolean mServiceConnectionEstablished;
111
112    private final BluetoothPhoneState mBluetoothPhoneState;  // for CIND and CIEV updates
113    private final BluetoothAtPhonebook mPhonebook;
114    private Phone.State mPhoneState = Phone.State.IDLE;
115    CdmaPhoneCallState.PhoneCallState mCdmaThreeWayCallState =
116                                            CdmaPhoneCallState.PhoneCallState.IDLE;
117
118    private DebugThread mDebugThread;
119    private int mScoGain = Integer.MIN_VALUE;
120
121    private static Intent sVoiceCommandIntent;
122
123    // Audio parameters
124    private static final String HEADSET_NREC = "bt_headset_nrec";
125    private static final String HEADSET_NAME = "bt_headset_name";
126
127    private int mRemoteBrsf = 0;
128    private int mLocalBrsf = 0;
129
130    // CDMA specific flag used in context with BT devices having display capabilities
131    // to show which Caller is active. This state might not be always true as in CDMA
132    // networks if a caller drops off no update is provided to the Phone.
133    // This flag is just used as a toggle to provide a update to the BT device to specify
134    // which caller is active.
135    private boolean mCdmaIsSecondCallActive = false;
136
137    /* Constants from Bluetooth Specification Hands-Free profile version 1.5 */
138    private static final int BRSF_AG_THREE_WAY_CALLING = 1 << 0;
139    private static final int BRSF_AG_EC_NR = 1 << 1;
140    private static final int BRSF_AG_VOICE_RECOG = 1 << 2;
141    private static final int BRSF_AG_IN_BAND_RING = 1 << 3;
142    private static final int BRSF_AG_VOICE_TAG_NUMBE = 1 << 4;
143    private static final int BRSF_AG_REJECT_CALL = 1 << 5;
144    private static final int BRSF_AG_ENHANCED_CALL_STATUS = 1 <<  6;
145    private static final int BRSF_AG_ENHANCED_CALL_CONTROL = 1 << 7;
146    private static final int BRSF_AG_ENHANCED_ERR_RESULT_CODES = 1 << 8;
147
148    private static final int BRSF_HF_EC_NR = 1 << 0;
149    private static final int BRSF_HF_CW_THREE_WAY_CALLING = 1 << 1;
150    private static final int BRSF_HF_CLIP = 1 << 2;
151    private static final int BRSF_HF_VOICE_REG_ACT = 1 << 3;
152    private static final int BRSF_HF_REMOTE_VOL_CONTROL = 1 << 4;
153    private static final int BRSF_HF_ENHANCED_CALL_STATUS = 1 <<  5;
154    private static final int BRSF_HF_ENHANCED_CALL_CONTROL = 1 << 6;
155
156    public static String typeToString(int type) {
157        switch (type) {
158        case TYPE_UNKNOWN:
159            return "unknown";
160        case TYPE_HEADSET:
161            return "headset";
162        case TYPE_HANDSFREE:
163            return "handsfree";
164        }
165        return null;
166    }
167
168    public BluetoothHandsfree(Context context, Phone phone) {
169        mPhone = phone;
170        mContext = context;
171        BluetoothAdapter adapter =
172                (BluetoothAdapter) context.getSystemService(Context.BLUETOOTH_SERVICE);
173        boolean bluetoothCapable = (adapter != null);
174        mHeadset = null;  // nothing connected yet
175        mA2dp = new BluetoothA2dp(mContext);
176        mA2dpState = BluetoothA2dp.STATE_DISCONNECTED;
177        mA2dpDevice = null;
178
179        mPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
180        mStartCallWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
181                                                       TAG + ":StartCall");
182        mStartCallWakeLock.setReferenceCounted(false);
183        mStartVoiceRecognitionWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
184                                                       TAG + ":VoiceRecognition");
185        mStartVoiceRecognitionWakeLock.setReferenceCounted(false);
186
187        mLocalBrsf = BRSF_AG_THREE_WAY_CALLING |
188                     BRSF_AG_EC_NR |
189                     BRSF_AG_REJECT_CALL |
190                     BRSF_AG_ENHANCED_CALL_STATUS;
191
192        if (sVoiceCommandIntent == null) {
193            sVoiceCommandIntent = new Intent(Intent.ACTION_VOICE_COMMAND);
194            sVoiceCommandIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
195        }
196        if (mContext.getPackageManager().resolveActivity(sVoiceCommandIntent, 0) != null &&
197                !BluetoothHeadset.DISABLE_BT_VOICE_DIALING) {
198            mLocalBrsf |= BRSF_AG_VOICE_RECOG;
199        }
200
201        if (bluetoothCapable) {
202            resetAtState();
203        }
204
205        mRingingCall = mPhone.getRingingCall();
206        mForegroundCall = mPhone.getForegroundCall();
207        mBackgroundCall = mPhone.getBackgroundCall();
208        mBluetoothPhoneState = new BluetoothPhoneState();
209        mUserWantsAudio = true;
210        mPhonebook = new BluetoothAtPhonebook(mContext, this);
211        mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
212        cdmaSetSecondCallState(false);
213    }
214
215    /* package */ synchronized void onBluetoothEnabled() {
216        /* Bluez has a bug where it will always accept and then orphan
217         * incoming SCO connections, regardless of whether we have a listening
218         * SCO socket. So the best thing to do is always run a listening socket
219         * while bluetooth is on so that at least we can diconnect it
220         * immediately when we don't want it.
221         */
222        if (mIncomingSco == null) {
223            mIncomingSco = createScoSocket();
224            mIncomingSco.accept();
225        }
226    }
227
228    /* package */ synchronized void onBluetoothDisabled() {
229        if (mConnectedSco != null) {
230            mAudioManager.setBluetoothScoOn(false);
231            broadcastAudioStateIntent(BluetoothHeadset.AUDIO_STATE_DISCONNECTED,
232                    mHeadset.getRemoteDevice());
233            mConnectedSco.close();
234            mConnectedSco = null;
235        }
236        if (mOutgoingSco != null) {
237            mOutgoingSco.close();
238            mOutgoingSco = null;
239        }
240        if (mIncomingSco != null) {
241            mIncomingSco.close();
242            mIncomingSco = null;
243        }
244    }
245
246    private boolean isHeadsetConnected() {
247        if (mHeadset == null) {
248            return false;
249        }
250        return mHeadset.isConnected();
251    }
252
253    /* package */ void connectHeadset(HeadsetBase headset, int headsetType) {
254        mHeadset = headset;
255        mHeadsetType = headsetType;
256        if (mHeadsetType == TYPE_HEADSET) {
257            initializeHeadsetAtParser();
258        } else {
259            initializeHandsfreeAtParser();
260        }
261        headset.startEventThread();
262        configAudioParameters();
263
264        if (inDebug()) {
265            startDebug();
266        }
267
268        if (isIncallAudio()) {
269            audioOn();
270        }
271    }
272
273    /* returns true if there is some kind of in-call audio we may wish to route
274     * bluetooth to */
275    private boolean isIncallAudio() {
276        Call.State state = mForegroundCall.getState();
277
278        return (state == Call.State.ACTIVE || state == Call.State.ALERTING);
279    }
280
281    /* package */ void disconnectHeadset() {
282        mHeadset = null;
283        stopDebug();
284        resetAtState();
285    }
286
287    private void resetAtState() {
288        mClip = false;
289        mIndicatorsEnabled = false;
290        mServiceConnectionEstablished = false;
291        mCmee = false;
292        mClccTimestamps = new long[GSM_MAX_CONNECTIONS];
293        mClccUsed = new boolean[GSM_MAX_CONNECTIONS];
294        for (int i = 0; i < GSM_MAX_CONNECTIONS; i++) {
295            mClccUsed[i] = false;
296        }
297        mRemoteBrsf = 0;
298    }
299
300    private void configAudioParameters() {
301        String name = mHeadset.getRemoteDevice().getName();
302        if (name == null) {
303            name = "<unknown>";
304        }
305        mAudioManager.setParameters(HEADSET_NAME+"="+name+";"+HEADSET_NREC+"=on");
306    }
307
308
309    /** Represents the data that we send in a +CIND or +CIEV command to the HF
310     */
311    private class BluetoothPhoneState {
312        // 0: no service
313        // 1: service
314        private int mService;
315
316        // 0: no active call
317        // 1: active call (where active means audio is routed - not held call)
318        private int mCall;
319
320        // 0: not in call setup
321        // 1: incoming call setup
322        // 2: outgoing call setup
323        // 3: remote party being alerted in an outgoing call setup
324        private int mCallsetup;
325
326        // 0: no calls held
327        // 1: held call and active call
328        // 2: held call only
329        private int mCallheld;
330
331        // cellular signal strength of AG: 0-5
332        private int mSignal;
333
334        // cellular signal strength in CSQ rssi scale
335        private int mRssi;  // for CSQ
336
337        // 0: roaming not active (home)
338        // 1: roaming active
339        private int mRoam;
340
341        // battery charge of AG: 0-5
342        private int mBattchg;
343
344        // 0: not registered
345        // 1: registered, home network
346        // 5: registered, roaming
347        private int mStat;  // for CREG
348
349        private String mRingingNumber;  // Context for in-progress RING's
350        private int    mRingingType;
351        private boolean mIgnoreRing = false;
352
353        private static final int SERVICE_STATE_CHANGED = 1;
354        private static final int PRECISE_CALL_STATE_CHANGED = 2;
355        private static final int RING = 3;
356        private static final int PHONE_CDMA_CALL_WAITING = 4;
357
358        private Handler mStateChangeHandler = new Handler() {
359            @Override
360            public void handleMessage(Message msg) {
361                switch(msg.what) {
362                case RING:
363                    AtCommandResult result = ring();
364                    if (result != null) {
365                        sendURC(result.toString());
366                    }
367                    break;
368                case SERVICE_STATE_CHANGED:
369                    ServiceState state = (ServiceState) ((AsyncResult) msg.obj).result;
370                    updateServiceState(sendUpdate(), state);
371                    break;
372                case PRECISE_CALL_STATE_CHANGED:
373                case PHONE_CDMA_CALL_WAITING:
374                    Connection connection = null;
375                    if (((AsyncResult) msg.obj).result instanceof Connection) {
376                        connection = (Connection) ((AsyncResult) msg.obj).result;
377                    }
378                    handlePreciseCallStateChange(sendUpdate(), connection);
379                    break;
380                }
381            }
382        };
383
384        private BluetoothPhoneState() {
385            // init members
386            updateServiceState(false, mPhone.getServiceState());
387            handlePreciseCallStateChange(false, null);
388            mBattchg = 5;  // There is currently no API to get battery level
389                           // on demand, so set to 5 and wait for an update
390            mSignal = asuToSignal(mPhone.getSignalStrength());
391
392            // register for updates
393            mPhone.registerForServiceStateChanged(mStateChangeHandler,
394                                                  SERVICE_STATE_CHANGED, null);
395            mPhone.registerForPreciseCallStateChanged(mStateChangeHandler,
396                    PRECISE_CALL_STATE_CHANGED, null);
397            if (mPhone.getPhoneType() == Phone.PHONE_TYPE_CDMA) {
398                mPhone.registerForCallWaiting(mStateChangeHandler,
399                                              PHONE_CDMA_CALL_WAITING, null);
400            }
401            IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
402            filter.addAction(TelephonyIntents.ACTION_SIGNAL_STRENGTH_CHANGED);
403            filter.addAction(BluetoothA2dp.ACTION_SINK_STATE_CHANGED);
404            mContext.registerReceiver(mStateReceiver, filter);
405        }
406
407        private void updateBtPhoneStateAfterRadioTechnologyChange() {
408            if(VDBG) Log.d(TAG, "updateBtPhoneStateAfterRadioTechnologyChange...");
409
410            //Unregister all events from the old obsolete phone
411            mPhone.unregisterForServiceStateChanged(mStateChangeHandler);
412            mPhone.unregisterForPreciseCallStateChanged(mStateChangeHandler);
413            mPhone.unregisterForCallWaiting(mStateChangeHandler);
414
415            //Register all events new to the new active phone
416            mPhone.registerForServiceStateChanged(mStateChangeHandler,
417                                                  SERVICE_STATE_CHANGED, null);
418            mPhone.registerForPreciseCallStateChanged(mStateChangeHandler,
419                    PRECISE_CALL_STATE_CHANGED, null);
420            if (mPhone.getPhoneType() == Phone.PHONE_TYPE_CDMA) {
421                mPhone.registerForCallWaiting(mStateChangeHandler,
422                                              PHONE_CDMA_CALL_WAITING, null);
423            }
424        }
425
426        private boolean sendUpdate() {
427            return isHeadsetConnected() && mHeadsetType == TYPE_HANDSFREE && mIndicatorsEnabled;
428        }
429
430        private boolean sendClipUpdate() {
431            return isHeadsetConnected() && mHeadsetType == TYPE_HANDSFREE && mClip;
432        }
433
434        /* convert [0,31] ASU signal strength to the [0,5] expected by
435         * bluetooth devices. Scale is similar to status bar policy
436         */
437        private int gsmAsuToSignal(SignalStrength signalStrength) {
438            int asu = signalStrength.getGsmSignalStrength();
439            if      (asu >= 16) return 5;
440            else if (asu >= 8)  return 4;
441            else if (asu >= 4)  return 3;
442            else if (asu >= 2)  return 2;
443            else if (asu >= 1)  return 1;
444            else                return 0;
445        }
446
447        /**
448         * Convert the cdma / evdo db levels to appropriate icon level.
449         * The scale is similar to the one used in status bar policy.
450         *
451         * @param signalStrength
452         * @return the icon level
453         */
454        private int cdmaDbmEcioToSignal(SignalStrength signalStrength) {
455            int levelDbm = 0;
456            int levelEcio = 0;
457            int cdmaIconLevel = 0;
458            int evdoIconLevel = 0;
459            int cdmaDbm = signalStrength.getCdmaDbm();
460            int cdmaEcio = signalStrength.getCdmaEcio();
461
462            if (cdmaDbm >= -75) levelDbm = 4;
463            else if (cdmaDbm >= -85) levelDbm = 3;
464            else if (cdmaDbm >= -95) levelDbm = 2;
465            else if (cdmaDbm >= -100) levelDbm = 1;
466            else levelDbm = 0;
467
468            // Ec/Io are in dB*10
469            if (cdmaEcio >= -90) levelEcio = 4;
470            else if (cdmaEcio >= -110) levelEcio = 3;
471            else if (cdmaEcio >= -130) levelEcio = 2;
472            else if (cdmaEcio >= -150) levelEcio = 1;
473            else levelEcio = 0;
474
475            cdmaIconLevel = (levelDbm < levelEcio) ? levelDbm : levelEcio;
476
477            if (mServiceState != null &&
478                  (mServiceState.getRadioTechnology() == ServiceState.RADIO_TECHNOLOGY_EVDO_0 ||
479                   mServiceState.getRadioTechnology() == ServiceState.RADIO_TECHNOLOGY_EVDO_A)) {
480                  int evdoEcio = signalStrength.getEvdoEcio();
481                  int evdoSnr = signalStrength.getEvdoSnr();
482                  int levelEvdoEcio = 0;
483                  int levelEvdoSnr = 0;
484
485                  // Ec/Io are in dB*10
486                  if (evdoEcio >= -650) levelEvdoEcio = 4;
487                  else if (evdoEcio >= -750) levelEvdoEcio = 3;
488                  else if (evdoEcio >= -900) levelEvdoEcio = 2;
489                  else if (evdoEcio >= -1050) levelEvdoEcio = 1;
490                  else levelEvdoEcio = 0;
491
492                  if (evdoSnr > 7) levelEvdoSnr = 4;
493                  else if (evdoSnr > 5) levelEvdoSnr = 3;
494                  else if (evdoSnr > 3) levelEvdoSnr = 2;
495                  else if (evdoSnr > 1) levelEvdoSnr = 1;
496                  else levelEvdoSnr = 0;
497
498                  evdoIconLevel = (levelEvdoEcio < levelEvdoSnr) ? levelEvdoEcio : levelEvdoSnr;
499            }
500            // TODO(): There is a bug open regarding what should be sent.
501            return (cdmaIconLevel > evdoIconLevel) ?  cdmaIconLevel : evdoIconLevel;
502
503        }
504
505
506        private int asuToSignal(SignalStrength signalStrength) {
507            if (signalStrength.isGsm()) {
508                return gsmAsuToSignal(signalStrength);
509            } else {
510                return cdmaDbmEcioToSignal(signalStrength);
511            }
512        }
513
514
515        /* convert [0,5] signal strength to a rssi signal strength for CSQ
516         * which is [0,31]. Despite the same scale, this is not the same value
517         * as ASU.
518         */
519        private int signalToRssi(int signal) {
520            // using C4A suggested values
521            switch (signal) {
522            case 0: return 0;
523            case 1: return 4;
524            case 2: return 8;
525            case 3: return 13;
526            case 4: return 19;
527            case 5: return 31;
528            }
529            return 0;
530        }
531
532
533        private final BroadcastReceiver mStateReceiver = new BroadcastReceiver() {
534            @Override
535            public void onReceive(Context context, Intent intent) {
536                if (intent.getAction().equals(Intent.ACTION_BATTERY_CHANGED)) {
537                    updateBatteryState(intent);
538                } else if (intent.getAction().equals(
539                            TelephonyIntents.ACTION_SIGNAL_STRENGTH_CHANGED)) {
540                    updateSignalState(intent);
541                } else if (intent.getAction().equals(BluetoothA2dp.ACTION_SINK_STATE_CHANGED)) {
542                    int state = intent.getIntExtra(BluetoothA2dp.EXTRA_SINK_STATE,
543                            BluetoothA2dp.STATE_DISCONNECTED);
544                    int oldState = intent.getIntExtra(BluetoothA2dp.EXTRA_PREVIOUS_SINK_STATE,
545                            BluetoothA2dp.STATE_DISCONNECTED);
546                    BluetoothDevice device =
547                            intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
548                    synchronized (BluetoothHandsfree.this) {
549                        mA2dpState = state;
550                        mA2dpDevice = device;
551                        if (isA2dpMultiProfile() && mPendingSco) {
552                            mHandler.removeMessages(MESSAGE_CHECK_PENDING_SCO);
553                            if (mA2dpState == BluetoothA2dp.STATE_CONNECTED) {
554                                if (DBG) log("A2DP suspended, completing SCO");
555                                mOutgoingSco = createScoSocket();
556                                if (!mOutgoingSco.connect(
557                                        mHeadset.getRemoteDevice().getAddress())) {
558                                    mOutgoingSco = null;
559                                }
560                            }
561                        }
562                        mPendingSco = false;
563                    }
564                }
565            }
566        };
567
568        private synchronized void updateBatteryState(Intent intent) {
569            int batteryLevel = intent.getIntExtra("level", -1);
570            int scale = intent.getIntExtra("scale", -1);
571            if (batteryLevel == -1 || scale == -1) {
572                return;  // ignore
573            }
574            batteryLevel = batteryLevel * 5 / scale;
575            if (mBattchg != batteryLevel) {
576                mBattchg = batteryLevel;
577                if (sendUpdate()) {
578                    sendURC("+CIEV: 7," + mBattchg);
579                }
580            }
581        }
582
583        private synchronized void updateSignalState(Intent intent) {
584            // NOTE this function is called by the BroadcastReceiver mStateReceiver after intent
585            // ACTION_SIGNAL_STRENGTH_CHANGED and by the DebugThread mDebugThread
586            SignalStrength signalStrength = SignalStrength.newFromBundle(intent.getExtras());
587            int signal;
588
589            if (signalStrength != null) {
590                signal = asuToSignal(signalStrength);
591                mRssi = signalToRssi(signal);  // no unsolicited CSQ
592                if (signal != mSignal) {
593                    mSignal = signal;
594                    if (sendUpdate()) {
595                        sendURC("+CIEV: 5," + mSignal);
596                    }
597                }
598            } else {
599                Log.e(TAG, "Signal Strength null");
600            }
601        }
602
603        private synchronized void updateServiceState(boolean sendUpdate, ServiceState state) {
604            int service = state.getState() == ServiceState.STATE_IN_SERVICE ? 1 : 0;
605            int roam = state.getRoaming() ? 1 : 0;
606            int stat;
607            AtCommandResult result = new AtCommandResult(AtCommandResult.UNSOLICITED);
608            mServiceState = state;
609            if (service == 0) {
610                stat = 0;
611            } else {
612                stat = (roam == 1) ? 5 : 1;
613            }
614
615            if (service != mService) {
616                mService = service;
617                if (sendUpdate) {
618                    result.addResponse("+CIEV: 1," + mService);
619                }
620            }
621            if (roam != mRoam) {
622                mRoam = roam;
623                if (sendUpdate) {
624                    result.addResponse("+CIEV: 6," + mRoam);
625                }
626            }
627            if (stat != mStat) {
628                mStat = stat;
629                if (sendUpdate) {
630                    result.addResponse(toCregString());
631                }
632            }
633
634            sendURC(result.toString());
635        }
636
637        private synchronized void handlePreciseCallStateChange(boolean sendUpdate,
638                Connection connection) {
639            int call = 0;
640            int callsetup = 0;
641            int callheld = 0;
642            int prevCallsetup = mCallsetup;
643            AtCommandResult result = new AtCommandResult(AtCommandResult.UNSOLICITED);
644
645            if (VDBG) log("updatePhoneState()");
646
647            // This function will get called when the Precise Call State
648            // {@link Call.State} changes. Hence, we might get this update
649            // even if the {@link Phone.state} is same as before.
650            // Check for the same.
651
652            Phone.State newState = mPhone.getState();
653            if (newState != mPhoneState) {
654                mPhoneState = newState;
655                switch (mPhoneState) {
656                case IDLE:
657                    mUserWantsAudio = true;  // out of call - reset state
658                    audioOff();
659                    break;
660                default:
661                    callStarted();
662                }
663            }
664
665            switch(mForegroundCall.getState()) {
666            case ACTIVE:
667                call = 1;
668                mAudioPossible = true;
669                break;
670            case DIALING:
671                callsetup = 2;
672                mAudioPossible = false;
673                break;
674            case ALERTING:
675                callsetup = 3;
676                // Open the SCO channel for the outgoing call.
677                audioOn();
678                mAudioPossible = true;
679                break;
680            default:
681                mAudioPossible = false;
682            }
683
684            switch(mRingingCall.getState()) {
685            case INCOMING:
686            case WAITING:
687                callsetup = 1;
688                break;
689            }
690
691            switch(mBackgroundCall.getState()) {
692            case HOLDING:
693                if (call == 1) {
694                    callheld = 1;
695                } else {
696                    call = 1;
697                    callheld = 2;
698                }
699                break;
700            }
701
702            if (mCall != call) {
703                if (call == 1) {
704                    // This means that a call has transitioned from NOT ACTIVE to ACTIVE.
705                    // Switch on audio.
706                    audioOn();
707                }
708                mCall = call;
709                if (sendUpdate) {
710                    result.addResponse("+CIEV: 2," + mCall);
711                }
712            }
713            if (mCallsetup != callsetup) {
714                mCallsetup = callsetup;
715                if (sendUpdate) {
716                    // If mCall = 0, send CIEV
717                    // mCall = 1, mCallsetup = 0, send CIEV
718                    // mCall = 1, mCallsetup = 1, send CIEV after CCWA,
719                    // if 3 way supported.
720                    // mCall = 1, mCallsetup = 2 / 3 -> send CIEV,
721                    // if 3 way is supported
722                    if (mCall != 1 || mCallsetup == 0 ||
723                        mCallsetup != 1 && (mRemoteBrsf & BRSF_HF_CW_THREE_WAY_CALLING) != 0x0) {
724                        result.addResponse("+CIEV: 3," + mCallsetup);
725                    }
726                }
727            }
728
729            if (mPhone.getPhoneType() == Phone.PHONE_TYPE_CDMA) {
730                PhoneApp app = PhoneApp.getInstance();
731                if (app.cdmaPhoneCallState != null) {
732                    CdmaPhoneCallState.PhoneCallState currCdmaThreeWayCallState =
733                            app.cdmaPhoneCallState.getCurrentCallState();
734                    CdmaPhoneCallState.PhoneCallState prevCdmaThreeWayCallState =
735                        app.cdmaPhoneCallState.getPreviousCallState();
736
737                    callheld = getCdmaCallHeldStatus(currCdmaThreeWayCallState,
738                                                     prevCdmaThreeWayCallState);
739
740                    if (mCdmaThreeWayCallState != currCdmaThreeWayCallState) {
741                        // In CDMA, the network does not provide any feedback
742                        // to the phone when the 2nd MO call goes through the
743                        // stages of DIALING > ALERTING -> ACTIVE we fake the
744                        // sequence
745                        if ((currCdmaThreeWayCallState ==
746                                CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE)
747                                    && app.cdmaPhoneCallState.IsThreeWayCallOrigStateDialing()) {
748                            mAudioPossible = true;
749                            if (sendUpdate) {
750                                if ((mRemoteBrsf & BRSF_HF_CW_THREE_WAY_CALLING) != 0x0) {
751                                    result.addResponse("+CIEV: 3,2");
752                                    result.addResponse("+CIEV: 3,3");
753                                    result.addResponse("+CIEV: 3,0");
754                                }
755                            }
756                            // We also need to send a Call started indication
757                            // for cases where the 2nd MO was initiated was
758                            // from a *BT hands free* and is waiting for a
759                            // +BLND: OK response
760                            callStarted();
761                        }
762
763                        // In CDMA, the network does not provide any feedback to
764                        // the phone when a user merges a 3way call or swaps
765                        // between two calls we need to send a CIEV response
766                        // indicating that a call state got changed which should
767                        // trigger a CLCC update request from the BT client.
768                        if (currCdmaThreeWayCallState ==
769                                CdmaPhoneCallState.PhoneCallState.CONF_CALL) {
770                            mAudioPossible = true;
771                            if (sendUpdate) {
772                                if ((mRemoteBrsf & BRSF_HF_CW_THREE_WAY_CALLING) != 0x0) {
773                                    result.addResponse("+CIEV: 2,1");
774                                    result.addResponse("+CIEV: 3,0");
775                                }
776                            }
777                        }
778                    }
779                    mCdmaThreeWayCallState = currCdmaThreeWayCallState;
780                }
781            }
782
783            boolean callsSwitched =
784                (callheld == 1 && ! (mBackgroundCall.getEarliestConnectTime() ==
785                    mBgndEarliestConnectionTime));
786
787            mBgndEarliestConnectionTime = mBackgroundCall.getEarliestConnectTime();
788
789            if (mCallheld != callheld || callsSwitched) {
790                mCallheld = callheld;
791                if (sendUpdate) {
792                    result.addResponse("+CIEV: 4," + mCallheld);
793                }
794            }
795
796            if (callsetup == 1 && callsetup != prevCallsetup) {
797                // new incoming call
798                String number = null;
799                int type = 128;
800                // find incoming phone number and type
801                if (connection == null) {
802                    connection = mRingingCall.getEarliestConnection();
803                    if (connection == null) {
804                        Log.e(TAG, "Could not get a handle on Connection object for new " +
805                              "incoming call");
806                    }
807                }
808                if (connection != null) {
809                    number = connection.getAddress();
810                    if (number != null) {
811                        type = PhoneNumberUtils.toaFromString(number);
812                    }
813                }
814                if (number == null) {
815                    number = "";
816                }
817                if ((call != 0 || callheld != 0) && sendUpdate) {
818                    // call waiting
819                    if ((mRemoteBrsf & BRSF_HF_CW_THREE_WAY_CALLING) != 0x0) {
820                        result.addResponse("+CCWA: \"" + number + "\"," + type);
821                        result.addResponse("+CIEV: 3," + callsetup);
822                    }
823                } else {
824                    // regular new incoming call
825                    mRingingNumber = number;
826                    mRingingType = type;
827                    mIgnoreRing = false;
828
829                    // Set up SCO channel immediately, regardless of in-band
830                    // ringtone support. SCO can take up to 2s to set up so
831                    // do it now before the call is answered
832                    audioOn();
833
834                    result.addResult(ring());
835                }
836            }
837            sendURC(result.toString());
838        }
839
840        private int getCdmaCallHeldStatus(CdmaPhoneCallState.PhoneCallState currState,
841                                  CdmaPhoneCallState.PhoneCallState prevState) {
842            int callheld;
843            // Update the Call held information
844            if (currState == CdmaPhoneCallState.PhoneCallState.CONF_CALL) {
845                if (prevState == CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE) {
846                    callheld = 0; //0: no calls held, as now *both* the caller are active
847                } else {
848                    callheld = 1; //1: held call and active call, as on answering a
849                            // Call Waiting, one of the caller *is* put on hold
850                }
851            } else if (currState == CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE) {
852                callheld = 1; //1: held call and active call, as on make a 3 Way Call
853                        // the first caller *is* put on hold
854            } else {
855                callheld = 0; //0: no calls held as this is a SINGLE_ACTIVE call
856            }
857            return callheld;
858        }
859
860
861        private AtCommandResult ring() {
862            if (!mIgnoreRing && mRingingCall.isRinging()) {
863                AtCommandResult result = new AtCommandResult(AtCommandResult.UNSOLICITED);
864                result.addResponse("RING");
865                if (sendClipUpdate()) {
866                    result.addResponse("+CLIP: \"" + mRingingNumber + "\"," + mRingingType);
867                }
868
869                Message msg = mStateChangeHandler.obtainMessage(RING);
870                mStateChangeHandler.sendMessageDelayed(msg, 3000);
871                return result;
872            }
873            return null;
874        }
875
876        private synchronized String toCregString() {
877            return new String("+CREG: 1," + mStat);
878        }
879
880        private synchronized AtCommandResult toCindResult() {
881            AtCommandResult result = new AtCommandResult(AtCommandResult.OK);
882            String status = "+CIND: " + mService + "," + mCall + "," + mCallsetup + "," +
883                            mCallheld + "," + mSignal + "," + mRoam + "," + mBattchg;
884            result.addResponse(status);
885            return result;
886        }
887
888        private synchronized AtCommandResult toCsqResult() {
889            AtCommandResult result = new AtCommandResult(AtCommandResult.OK);
890            String status = "+CSQ: " + mRssi + ",99";
891            result.addResponse(status);
892            return result;
893        }
894
895
896        private synchronized AtCommandResult getCindTestResult() {
897            return new AtCommandResult("+CIND: (\"service\",(0-1))," + "(\"call\",(0-1))," +
898                        "(\"callsetup\",(0-3)),(\"callheld\",(0-2)),(\"signal\",(0-5))," +
899                        "(\"roam\",(0-1)),(\"battchg\",(0-5))");
900        }
901
902        private synchronized void ignoreRing() {
903            mCallsetup = 0;
904            mIgnoreRing = true;
905            if (sendUpdate()) {
906                sendURC("+CIEV: 3," + mCallsetup);
907            }
908        }
909
910    };
911
912    private static final int SCO_ACCEPTED = 1;
913    private static final int SCO_CONNECTED = 2;
914    private static final int SCO_CLOSED = 3;
915    private static final int CHECK_CALL_STARTED = 4;
916    private static final int CHECK_VOICE_RECOGNITION_STARTED = 5;
917    private static final int MESSAGE_CHECK_PENDING_SCO = 6;
918
919    private final Handler mHandler = new Handler() {
920        @Override
921        public void handleMessage(Message msg) {
922            synchronized (BluetoothHandsfree.this) {
923                switch (msg.what) {
924                case SCO_ACCEPTED:
925                    if (msg.arg1 == ScoSocket.STATE_CONNECTED) {
926                        if (isHeadsetConnected() && (mAudioPossible || allowAudioAnytime()) &&
927                                mConnectedSco == null) {
928                            Log.i(TAG, "Routing audio for incoming SCO connection");
929                            mConnectedSco = (ScoSocket)msg.obj;
930                            mAudioManager.setBluetoothScoOn(true);
931                            broadcastAudioStateIntent(BluetoothHeadset.AUDIO_STATE_CONNECTED,
932                                    mHeadset.getRemoteDevice());
933                        } else {
934                            Log.i(TAG, "Rejecting incoming SCO connection");
935                            ((ScoSocket)msg.obj).close();
936                        }
937                    } // else error trying to accept, try again
938                    mIncomingSco = createScoSocket();
939                    mIncomingSco.accept();
940                    break;
941                case SCO_CONNECTED:
942                    if (msg.arg1 == ScoSocket.STATE_CONNECTED && isHeadsetConnected() &&
943                            mConnectedSco == null) {
944                        if (VDBG) log("Routing audio for outgoing SCO conection");
945                        mConnectedSco = (ScoSocket)msg.obj;
946                        mAudioManager.setBluetoothScoOn(true);
947                        broadcastAudioStateIntent(BluetoothHeadset.AUDIO_STATE_CONNECTED,
948                                mHeadset.getRemoteDevice());
949                    } else if (msg.arg1 == ScoSocket.STATE_CONNECTED) {
950                        if (VDBG) log("Rejecting new connected outgoing SCO socket");
951                        ((ScoSocket)msg.obj).close();
952                        mOutgoingSco.close();
953                    }
954                    mOutgoingSco = null;
955                    break;
956                case SCO_CLOSED:
957                    if (mConnectedSco == (ScoSocket)msg.obj) {
958                        mConnectedSco = null;
959                        mAudioManager.setBluetoothScoOn(false);
960                        broadcastAudioStateIntent(BluetoothHeadset.AUDIO_STATE_DISCONNECTED,
961                                mHeadset.getRemoteDevice());
962                    } else if (mOutgoingSco == (ScoSocket)msg.obj) {
963                        mOutgoingSco = null;
964                    } else if (mIncomingSco == (ScoSocket)msg.obj) {
965                        mIncomingSco = null;
966                    }
967                    break;
968                case CHECK_CALL_STARTED:
969                    if (mWaitingForCallStart) {
970                        mWaitingForCallStart = false;
971                        Log.e(TAG, "Timeout waiting for call to start");
972                        sendURC("ERROR");
973                        if (mStartCallWakeLock.isHeld()) {
974                            mStartCallWakeLock.release();
975                        }
976                    }
977                    break;
978                case CHECK_VOICE_RECOGNITION_STARTED:
979                    if (mWaitingForVoiceRecognition) {
980                        mWaitingForVoiceRecognition = false;
981                        Log.e(TAG, "Timeout waiting for voice recognition to start");
982                        sendURC("ERROR");
983                    }
984                    break;
985                case MESSAGE_CHECK_PENDING_SCO:
986                    if (mPendingSco && isA2dpMultiProfile()) {
987                        Log.w(TAG, "Timeout suspending A2DP for SCO (mA2dpState = " +
988                                mA2dpState + "). Starting SCO anyway");
989                        mOutgoingSco = createScoSocket();
990                        if (!mOutgoingSco.connect(mHeadset.getRemoteDevice().getAddress())) {
991                            mOutgoingSco = null;
992                        }
993                        mPendingSco = false;
994                    }
995                    break;
996                }
997            }
998        }
999    };
1000
1001    private ScoSocket createScoSocket() {
1002        return new ScoSocket(mPowerManager, mHandler, SCO_ACCEPTED, SCO_CONNECTED, SCO_CLOSED);
1003    }
1004
1005    private void broadcastAudioStateIntent(int state, BluetoothDevice device) {
1006        if (VDBG) log("broadcastAudioStateIntent(" + state + ")");
1007        Intent intent = new Intent(BluetoothHeadset.ACTION_AUDIO_STATE_CHANGED);
1008        intent.putExtra(BluetoothHeadset.EXTRA_AUDIO_STATE, state);
1009        intent.putExtra(BluetoothDevice.EXTRA_DEVICE, device);
1010        mContext.sendBroadcast(intent, android.Manifest.permission.BLUETOOTH);
1011    }
1012
1013    void updateBtHandsfreeAfterRadioTechnologyChange() {
1014        if(VDBG) Log.d(TAG, "updateBtHandsfreeAfterRadioTechnologyChange...");
1015
1016        //Get the Call references from the new active phone again
1017        mRingingCall = mPhone.getRingingCall();
1018        mForegroundCall = mPhone.getForegroundCall();
1019        mBackgroundCall = mPhone.getBackgroundCall();
1020
1021        mBluetoothPhoneState.updateBtPhoneStateAfterRadioTechnologyChange();
1022    }
1023
1024    /** Request to establish SCO (audio) connection to bluetooth
1025     * headset/handsfree, if one is connected. Does not block.
1026     * Returns false if the user has requested audio off, or if there
1027     * is some other immediate problem that will prevent BT audio.
1028     */
1029    /* package */ synchronized boolean audioOn() {
1030        if (VDBG) log("audioOn()");
1031        if (!isHeadsetConnected()) {
1032            if (DBG) log("audioOn(): headset is not connected!");
1033            return false;
1034        }
1035        if (mHeadsetType == TYPE_HANDSFREE && !mServiceConnectionEstablished) {
1036            if (DBG) log("audioOn(): service connection not yet established!");
1037            return false;
1038        }
1039
1040        if (mConnectedSco != null) {
1041            if (DBG) log("audioOn(): audio is already connected");
1042            return true;
1043        }
1044
1045        if (!mUserWantsAudio) {
1046            if (DBG) log("audioOn(): user requested no audio, ignoring");
1047            return false;
1048        }
1049
1050        if (mOutgoingSco != null) {
1051            if (DBG) log("audioOn(): outgoing SCO already in progress");
1052            return true;
1053        }
1054
1055        if (mPendingSco) {
1056            if (DBG) log("audioOn(): SCO already pending");
1057            return true;
1058        }
1059
1060        if (isA2dpMultiProfile() && mA2dpState == BluetoothA2dp.STATE_PLAYING) {
1061            if (DBG) log("suspending A2DP stream for SCO");
1062            mPendingSco = mA2dp.suspendSink(mA2dpDevice);
1063            if (mPendingSco) {
1064                Message msg = mHandler.obtainMessage(MESSAGE_CHECK_PENDING_SCO);
1065                mHandler.sendMessageDelayed(msg, 2000);
1066            } else {
1067                Log.w(TAG, "Could not suspend A2DP stream for SCO, going ahead with SCO");
1068                mOutgoingSco = createScoSocket();
1069                if (!mOutgoingSco.connect(mHeadset.getRemoteDevice().getAddress())) {
1070                    mOutgoingSco = null;
1071                }
1072            }
1073        }
1074
1075        return true;
1076    }
1077
1078    /** Used to indicate the user requested BT audio on.
1079     *  This will establish SCO (BT audio), even if the user requested it off
1080     *  previously on this call.
1081     */
1082    /* package */ synchronized void userWantsAudioOn() {
1083        mUserWantsAudio = true;
1084        audioOn();
1085    }
1086    /** Used to indicate the user requested BT audio off.
1087     *  This will prevent us from establishing BT audio again during this call
1088     *  if audioOn() is called.
1089     */
1090    /* package */ synchronized void userWantsAudioOff() {
1091        mUserWantsAudio = false;
1092        audioOff();
1093    }
1094
1095    /** Request to disconnect SCO (audio) connection to bluetooth
1096     * headset/handsfree, if one is connected. Does not block.
1097     */
1098    /* package */ synchronized void audioOff() {
1099        if (VDBG) log("audioOff()");
1100
1101        if (mConnectedSco != null) {
1102            mAudioManager.setBluetoothScoOn(false);
1103            broadcastAudioStateIntent(BluetoothHeadset.AUDIO_STATE_DISCONNECTED,
1104                    mHeadset.getRemoteDevice());
1105            mConnectedSco.close();
1106            mConnectedSco = null;
1107        }
1108        if (mOutgoingSco != null) {
1109            mOutgoingSco.close();
1110            mOutgoingSco = null;
1111        }
1112
1113        mPendingSco = false;
1114        if (isA2dpMultiProfile() && mA2dpState == BluetoothA2dp.STATE_CONNECTED) {
1115            if (DBG) log("resuming A2DP stream after SCO");
1116            mA2dp.resumeSink(mA2dpDevice);
1117        }
1118    }
1119
1120    /* package */ boolean isAudioOn() {
1121        return (mConnectedSco != null);
1122    }
1123
1124    private boolean isA2dpMultiProfile() {
1125        return mA2dp != null && mHeadset != null && mA2dpDevice != null &&
1126                mA2dpDevice.equals(mHeadset.getRemoteDevice());
1127    }
1128
1129    /* package */ void ignoreRing() {
1130        mBluetoothPhoneState.ignoreRing();
1131    }
1132
1133    private void sendURC(String urc) {
1134        if (isHeadsetConnected()) {
1135            mHeadset.sendURC(urc);
1136        }
1137    }
1138
1139    /** helper to redial last dialled number */
1140    private AtCommandResult redial() {
1141        String number = mPhonebook.getLastDialledNumber();
1142        if (number == null) {
1143            // spec seems to suggest sending ERROR if we dont have a
1144            // number to redial
1145            if (VDBG) log("Bluetooth redial requested (+BLDN), but no previous " +
1146                  "outgoing calls found. Ignoring");
1147            return new AtCommandResult(AtCommandResult.ERROR);
1148        }
1149        Intent intent = new Intent(Intent.ACTION_CALL_PRIVILEGED,
1150                Uri.fromParts("tel", number, null));
1151        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1152        mContext.startActivity(intent);
1153
1154        // We do not immediately respond OK, wait until we get a phone state
1155        // update. If we return OK now and the handsfree immeidately requests
1156        // our phone state it will say we are not in call yet which confuses
1157        // some devices
1158        expectCallStart();
1159        return new AtCommandResult(AtCommandResult.UNSOLICITED);  // send nothing
1160    }
1161
1162    /** Build the +CLCC result
1163     *  The complexity arises from the fact that we need to maintain the same
1164     *  CLCC index even as a call moves between states. */
1165    private synchronized AtCommandResult gsmGetClccResult() {
1166        // Collect all known connections
1167        Connection[] clccConnections = new Connection[GSM_MAX_CONNECTIONS];  // indexed by CLCC index
1168        LinkedList<Connection> newConnections = new LinkedList<Connection>();
1169        LinkedList<Connection> connections = new LinkedList<Connection>();
1170        if (mRingingCall.getState().isAlive()) {
1171            connections.addAll(mRingingCall.getConnections());
1172        }
1173        if (mForegroundCall.getState().isAlive()) {
1174            connections.addAll(mForegroundCall.getConnections());
1175        }
1176        if (mBackgroundCall.getState().isAlive()) {
1177            connections.addAll(mBackgroundCall.getConnections());
1178        }
1179
1180        // Mark connections that we already known about
1181        boolean clccUsed[] = new boolean[GSM_MAX_CONNECTIONS];
1182        for (int i = 0; i < GSM_MAX_CONNECTIONS; i++) {
1183            clccUsed[i] = mClccUsed[i];
1184            mClccUsed[i] = false;
1185        }
1186        for (Connection c : connections) {
1187            boolean found = false;
1188            long timestamp = c.getCreateTime();
1189            for (int i = 0; i < GSM_MAX_CONNECTIONS; i++) {
1190                if (clccUsed[i] && timestamp == mClccTimestamps[i]) {
1191                    mClccUsed[i] = true;
1192                    found = true;
1193                    clccConnections[i] = c;
1194                    break;
1195                }
1196            }
1197            if (!found) {
1198                newConnections.add(c);
1199            }
1200        }
1201
1202        // Find a CLCC index for new connections
1203        while (!newConnections.isEmpty()) {
1204            // Find lowest empty index
1205            int i = 0;
1206            while (mClccUsed[i]) i++;
1207            // Find earliest connection
1208            long earliestTimestamp = newConnections.get(0).getCreateTime();
1209            Connection earliestConnection = newConnections.get(0);
1210            for (int j = 0; j < newConnections.size(); j++) {
1211                long timestamp = newConnections.get(j).getCreateTime();
1212                if (timestamp < earliestTimestamp) {
1213                    earliestTimestamp = timestamp;
1214                    earliestConnection = newConnections.get(j);
1215                }
1216            }
1217
1218            // update
1219            mClccUsed[i] = true;
1220            mClccTimestamps[i] = earliestTimestamp;
1221            clccConnections[i] = earliestConnection;
1222            newConnections.remove(earliestConnection);
1223        }
1224
1225        // Build CLCC
1226        AtCommandResult result = new AtCommandResult(AtCommandResult.OK);
1227        for (int i = 0; i < clccConnections.length; i++) {
1228            if (mClccUsed[i]) {
1229                String clccEntry = connectionToClccEntry(i, clccConnections[i]);
1230                if (clccEntry != null) {
1231                    result.addResponse(clccEntry);
1232                }
1233            }
1234        }
1235
1236        return result;
1237    }
1238
1239    /** Convert a Connection object into a single +CLCC result */
1240    private String connectionToClccEntry(int index, Connection c) {
1241        int state;
1242        switch (c.getState()) {
1243        case ACTIVE:
1244            state = 0;
1245            break;
1246        case HOLDING:
1247            state = 1;
1248            break;
1249        case DIALING:
1250            state = 2;
1251            break;
1252        case ALERTING:
1253            state = 3;
1254            break;
1255        case INCOMING:
1256            state = 4;
1257            break;
1258        case WAITING:
1259            state = 5;
1260            break;
1261        default:
1262            return null;  // bad state
1263        }
1264
1265        int mpty = 0;
1266        Call call = c.getCall();
1267        if (call != null) {
1268            mpty = call.isMultiparty() ? 1 : 0;
1269        }
1270
1271        int direction = c.isIncoming() ? 1 : 0;
1272
1273        String number = c.getAddress();
1274        int type = -1;
1275        if (number != null) {
1276            type = PhoneNumberUtils.toaFromString(number);
1277        }
1278
1279        String result = "+CLCC: " + (index + 1) + "," + direction + "," + state + ",0," + mpty;
1280        if (number != null) {
1281            result += ",\"" + number + "\"," + type;
1282        }
1283        return result;
1284    }
1285
1286    /** Build the +CLCC result for CDMA
1287     *  The complexity arises from the fact that we need to maintain the same
1288     *  CLCC index even as a call moves between states. */
1289    private synchronized AtCommandResult cdmaGetClccResult() {
1290        // In CDMA at one time a user can have only two live/active connections
1291        Connection[] clccConnections = new Connection[CDMA_MAX_CONNECTIONS];// indexed by CLCC index
1292
1293        Call.State ringingCallState = mRingingCall.getState();
1294        // If the Ringing Call state is INCOMING, that means this is the very first call
1295        // hence there should not be any Foreground Call
1296        if (ringingCallState == Call.State.INCOMING) {
1297            if (VDBG) log("Filling clccConnections[0] for INCOMING state");
1298            clccConnections[0] = mRingingCall.getLatestConnection();
1299        } else if (mForegroundCall.getState().isAlive()) {
1300            // Getting Foreground Call connection based on Call state
1301            if (mRingingCall.isRinging()) {
1302                if (VDBG) log("Filling clccConnections[0] & [1] for CALL WAITING state");
1303                clccConnections[0] = mForegroundCall.getEarliestConnection();
1304                clccConnections[1] = mRingingCall.getLatestConnection();
1305            } else {
1306                if (mForegroundCall.getConnections().size() <= 1) {
1307                    // Single call scenario
1308                    if (VDBG) log("Filling clccConnections[0] with ForgroundCall latest connection");
1309                    clccConnections[0] = mForegroundCall.getLatestConnection();
1310                } else {
1311                    // Multiple Call scenario. This would be true for both
1312                    // CONF_CALL and THRWAY_ACTIVE state
1313                    if (VDBG) log("Filling clccConnections[0] & [1] with ForgroundCall connections");
1314                    clccConnections[0] = mForegroundCall.getEarliestConnection();
1315                    clccConnections[1] = mForegroundCall.getLatestConnection();
1316                }
1317            }
1318        }
1319
1320        // Update the mCdmaIsSecondCallActive flag based on the Phone call state
1321        if (PhoneApp.getInstance().cdmaPhoneCallState.getCurrentCallState()
1322                == CdmaPhoneCallState.PhoneCallState.SINGLE_ACTIVE) {
1323            cdmaSetSecondCallState(false);
1324        } else if (PhoneApp.getInstance().cdmaPhoneCallState.getCurrentCallState()
1325                == CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE) {
1326            cdmaSetSecondCallState(true);
1327        }
1328
1329        // Build CLCC
1330        AtCommandResult result = new AtCommandResult(AtCommandResult.OK);
1331        for (int i = 0; (i < clccConnections.length) && (clccConnections[i] != null); i++) {
1332            String clccEntry = cdmaConnectionToClccEntry(i, clccConnections[i]);
1333            if (clccEntry != null) {
1334                result.addResponse(clccEntry);
1335            }
1336        }
1337
1338        return result;
1339    }
1340
1341    /** Convert a Connection object into a single +CLCC result for CDMA phones */
1342    private String cdmaConnectionToClccEntry(int index, Connection c) {
1343        int state;
1344        PhoneApp app = PhoneApp.getInstance();
1345        CdmaPhoneCallState.PhoneCallState currCdmaCallState =
1346                app.cdmaPhoneCallState.getCurrentCallState();
1347        CdmaPhoneCallState.PhoneCallState prevCdmaCallState =
1348                app.cdmaPhoneCallState.getPreviousCallState();
1349
1350        if ((prevCdmaCallState == CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE)
1351                && (currCdmaCallState == CdmaPhoneCallState.PhoneCallState.CONF_CALL)) {
1352            // If the current state is reached after merging two calls
1353            // we set the state of all the connections as ACTIVE
1354            state = 0;
1355        } else {
1356            switch (c.getState()) {
1357            case ACTIVE:
1358                // For CDMA since both the connections are set as active by FW after accepting
1359                // a Call waiting or making a 3 way call, we need to set the state specifically
1360                // to ACTIVE/HOLDING based on the mCdmaIsSecondCallActive flag. This way the
1361                // CLCC result will allow BT devices to enable the swap or merge options
1362                if (index == 0) { // For the 1st active connection
1363                    state = mCdmaIsSecondCallActive ? 1 : 0;
1364                } else { // for the 2nd active connection
1365                    state = mCdmaIsSecondCallActive ? 0 : 1;
1366                }
1367                break;
1368            case HOLDING:
1369                state = 1;
1370                break;
1371            case DIALING:
1372                state = 2;
1373                break;
1374            case ALERTING:
1375                state = 3;
1376                break;
1377            case INCOMING:
1378                state = 4;
1379                break;
1380            case WAITING:
1381                state = 5;
1382                break;
1383            default:
1384                return null;  // bad state
1385            }
1386        }
1387
1388        int mpty = 0;
1389        if (currCdmaCallState == CdmaPhoneCallState.PhoneCallState.SINGLE_ACTIVE) {
1390            mpty = 0;
1391        } else {
1392            mpty = 1;
1393        }
1394
1395        int direction = c.isIncoming() ? 1 : 0;
1396
1397        String number = c.getAddress();
1398        int type = -1;
1399        if (number != null) {
1400            type = PhoneNumberUtils.toaFromString(number);
1401        }
1402
1403        String result = "+CLCC: " + (index + 1) + "," + direction + "," + state + ",0," + mpty;
1404        if (number != null) {
1405            result += ",\"" + number + "\"," + type;
1406        }
1407        return result;
1408    }
1409
1410    /**
1411     * Register AT Command handlers to implement the Headset profile
1412     */
1413    private void initializeHeadsetAtParser() {
1414        if (VDBG) log("Registering Headset AT commands");
1415        AtParser parser = mHeadset.getAtParser();
1416        // Headset's usually only have one button, which is meant to cause the
1417        // HS to send us AT+CKPD=200 or AT+CKPD.
1418        parser.register("+CKPD", new AtCommandHandler() {
1419            private AtCommandResult headsetButtonPress() {
1420                if (mRingingCall.isRinging()) {
1421                    // Answer the call
1422                    PhoneUtils.answerCall(mPhone);
1423                    // SCO might already be up, but just make sure
1424                    audioOn();
1425                } else if (mForegroundCall.getState().isAlive()) {
1426                    if (!isAudioOn()) {
1427                        // Transfer audio from AG to HS
1428                        audioOn();
1429                    } else {
1430                        if (mHeadset.getDirection() == HeadsetBase.DIRECTION_INCOMING &&
1431                          (System.currentTimeMillis() - mHeadset.getConnectTimestamp()) < 5000) {
1432                            // Headset made a recent ACL connection to us - and
1433                            // made a mandatory AT+CKPD request to connect
1434                            // audio which races with our automatic audio
1435                            // setup.  ignore
1436                        } else {
1437                            // Hang up the call
1438                            audioOff();
1439                            PhoneUtils.hangup(mPhone);
1440                        }
1441                    }
1442                } else {
1443                    // No current call - redial last number
1444                    return redial();
1445                }
1446                return new AtCommandResult(AtCommandResult.OK);
1447            }
1448            @Override
1449            public AtCommandResult handleActionCommand() {
1450                return headsetButtonPress();
1451            }
1452            @Override
1453            public AtCommandResult handleSetCommand(Object[] args) {
1454                return headsetButtonPress();
1455            }
1456        });
1457    }
1458
1459    /**
1460     * Register AT Command handlers to implement the Handsfree profile
1461     */
1462    private void initializeHandsfreeAtParser() {
1463        if (VDBG) log("Registering Handsfree AT commands");
1464        AtParser parser = mHeadset.getAtParser();
1465
1466        // Answer
1467        parser.register('A', new AtCommandHandler() {
1468            @Override
1469            public AtCommandResult handleBasicCommand(String args) {
1470                PhoneUtils.answerCall(mPhone);
1471                return new AtCommandResult(AtCommandResult.OK);
1472            }
1473        });
1474        parser.register('D', new AtCommandHandler() {
1475            @Override
1476            public AtCommandResult handleBasicCommand(String args) {
1477                if (args.length() > 0) {
1478                    if (args.charAt(0) == '>') {
1479                        // Yuck - memory dialling requested.
1480                        // Just dial last number for now
1481                        if (args.startsWith(">9999")) {   // for PTS test
1482                            return new AtCommandResult(AtCommandResult.ERROR);
1483                        }
1484                        return redial();
1485                    } else {
1486                        // Remove trailing ';'
1487                        if (args.charAt(args.length() - 1) == ';') {
1488                            args = args.substring(0, args.length() - 1);
1489                        }
1490                        Intent intent = new Intent(Intent.ACTION_CALL_PRIVILEGED,
1491                                Uri.fromParts("tel", args, null));
1492                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1493                        mContext.startActivity(intent);
1494
1495                        expectCallStart();
1496                        return new AtCommandResult(AtCommandResult.UNSOLICITED);  // send nothing
1497                    }
1498                }
1499                return new AtCommandResult(AtCommandResult.ERROR);
1500            }
1501        });
1502
1503        // Hang-up command
1504        parser.register("+CHUP", new AtCommandHandler() {
1505            @Override
1506            public AtCommandResult handleActionCommand() {
1507                sendURC("OK");
1508                if (!mRingingCall.isIdle()) {
1509                    PhoneUtils.hangupRingingCall(mPhone);
1510                } else if (!mForegroundCall.isIdle()) {
1511                    PhoneUtils.hangupActiveCall(mPhone);
1512                } else if (!mBackgroundCall.isIdle()) {
1513                    PhoneUtils.hangupHoldingCall(mPhone);
1514                }
1515                return new AtCommandResult(AtCommandResult.UNSOLICITED);
1516            }
1517        });
1518
1519        // Bluetooth Retrieve Supported Features command
1520        parser.register("+BRSF", new AtCommandHandler() {
1521            private AtCommandResult sendBRSF() {
1522                return new AtCommandResult("+BRSF: " + mLocalBrsf);
1523            }
1524            @Override
1525            public AtCommandResult handleSetCommand(Object[] args) {
1526                // AT+BRSF=<handsfree supported features bitmap>
1527                // Handsfree is telling us which features it supports. We
1528                // send the features we support
1529                if (args.length == 1 && (args[0] instanceof Integer)) {
1530                    mRemoteBrsf = (Integer) args[0];
1531                } else {
1532                    Log.w(TAG, "HF didn't sent BRSF assuming 0");
1533                }
1534                return sendBRSF();
1535            }
1536            @Override
1537            public AtCommandResult handleActionCommand() {
1538                // This seems to be out of spec, but lets do the nice thing
1539                return sendBRSF();
1540            }
1541            @Override
1542            public AtCommandResult handleReadCommand() {
1543                // This seems to be out of spec, but lets do the nice thing
1544                return sendBRSF();
1545            }
1546        });
1547
1548        // Call waiting notification on/off
1549        parser.register("+CCWA", new AtCommandHandler() {
1550            @Override
1551            public AtCommandResult handleActionCommand() {
1552                // Seems to be out of spec, but lets return nicely
1553                return new AtCommandResult(AtCommandResult.OK);
1554            }
1555            @Override
1556            public AtCommandResult handleReadCommand() {
1557                // Call waiting is always on
1558                return new AtCommandResult("+CCWA: 1");
1559            }
1560            @Override
1561            public AtCommandResult handleSetCommand(Object[] args) {
1562                // AT+CCWA=<n>
1563                // Handsfree is trying to enable/disable call waiting. We
1564                // cannot disable in the current implementation.
1565                return new AtCommandResult(AtCommandResult.OK);
1566            }
1567            @Override
1568            public AtCommandResult handleTestCommand() {
1569                // Request for range of supported CCWA paramters
1570                return new AtCommandResult("+CCWA: (\"n\",(1))");
1571            }
1572        });
1573
1574        // Mobile Equipment Event Reporting enable/disable command
1575        // Of the full 3GPP syntax paramters (mode, keyp, disp, ind, bfr) we
1576        // only support paramter ind (disable/enable evert reporting using
1577        // +CDEV)
1578        parser.register("+CMER", new AtCommandHandler() {
1579            @Override
1580            public AtCommandResult handleReadCommand() {
1581                return new AtCommandResult(
1582                        "+CMER: 3,0,0," + (mIndicatorsEnabled ? "1" : "0"));
1583            }
1584            @Override
1585            public AtCommandResult handleSetCommand(Object[] args) {
1586                if (args.length < 4) {
1587                    // This is a syntax error
1588                    return new AtCommandResult(AtCommandResult.ERROR);
1589                } else if (args[0].equals(3) && args[1].equals(0) &&
1590                           args[2].equals(0)) {
1591                    boolean valid = false;
1592                    if (args[3].equals(0)) {
1593                        mIndicatorsEnabled = false;
1594                        valid = true;
1595                    } else if (args[3].equals(1)) {
1596                        mIndicatorsEnabled = true;
1597                        valid = true;
1598                    }
1599                    if (valid) {
1600                        if ((mRemoteBrsf & BRSF_HF_CW_THREE_WAY_CALLING) == 0x0) {
1601                            mServiceConnectionEstablished = true;
1602                            sendURC("OK");  // send immediately, then initiate audio
1603                            if (isIncallAudio()) {
1604                                audioOn();
1605                            }
1606                            // only send OK once
1607                            return new AtCommandResult(AtCommandResult.UNSOLICITED);
1608                        } else {
1609                            return new AtCommandResult(AtCommandResult.OK);
1610                        }
1611                    }
1612                }
1613                return reportCmeError(BluetoothCmeError.OPERATION_NOT_SUPPORTED);
1614            }
1615            @Override
1616            public AtCommandResult handleTestCommand() {
1617                return new AtCommandResult("+CMER: (3),(0),(0),(0-1)");
1618            }
1619        });
1620
1621        // Mobile Equipment Error Reporting enable/disable
1622        parser.register("+CMEE", new AtCommandHandler() {
1623            @Override
1624            public AtCommandResult handleActionCommand() {
1625                // out of spec, assume they want to enable
1626                mCmee = true;
1627                return new AtCommandResult(AtCommandResult.OK);
1628            }
1629            @Override
1630            public AtCommandResult handleReadCommand() {
1631                return new AtCommandResult("+CMEE: " + (mCmee ? "1" : "0"));
1632            }
1633            @Override
1634            public AtCommandResult handleSetCommand(Object[] args) {
1635                // AT+CMEE=<n>
1636                if (args.length == 0) {
1637                    // <n> ommitted - default to 0
1638                    mCmee = false;
1639                    return new AtCommandResult(AtCommandResult.OK);
1640                } else if (!(args[0] instanceof Integer)) {
1641                    // Syntax error
1642                    return new AtCommandResult(AtCommandResult.ERROR);
1643                } else {
1644                    mCmee = ((Integer)args[0] == 1);
1645                    return new AtCommandResult(AtCommandResult.OK);
1646                }
1647            }
1648            @Override
1649            public AtCommandResult handleTestCommand() {
1650                // Probably not required but spec, but no harm done
1651                return new AtCommandResult("+CMEE: (0-1)");
1652            }
1653        });
1654
1655        // Bluetooth Last Dialled Number
1656        parser.register("+BLDN", new AtCommandHandler() {
1657            @Override
1658            public AtCommandResult handleActionCommand() {
1659                return redial();
1660            }
1661        });
1662
1663        // Indicator Update command
1664        parser.register("+CIND", new AtCommandHandler() {
1665            @Override
1666            public AtCommandResult handleReadCommand() {
1667                return mBluetoothPhoneState.toCindResult();
1668            }
1669            @Override
1670            public AtCommandResult handleTestCommand() {
1671                return mBluetoothPhoneState.getCindTestResult();
1672            }
1673        });
1674
1675        // Query Signal Quality (legacy)
1676        parser.register("+CSQ", new AtCommandHandler() {
1677            @Override
1678            public AtCommandResult handleActionCommand() {
1679                return mBluetoothPhoneState.toCsqResult();
1680            }
1681        });
1682
1683        // Query network registration state
1684        parser.register("+CREG", new AtCommandHandler() {
1685            @Override
1686            public AtCommandResult handleReadCommand() {
1687                return new AtCommandResult(mBluetoothPhoneState.toCregString());
1688            }
1689        });
1690
1691        // Send DTMF. I don't know if we are also expected to play the DTMF tone
1692        // locally, right now we don't
1693        parser.register("+VTS", new AtCommandHandler() {
1694            @Override
1695            public AtCommandResult handleSetCommand(Object[] args) {
1696                if (args.length >= 1) {
1697                    char c;
1698                    if (args[0] instanceof Integer) {
1699                        c = ((Integer) args[0]).toString().charAt(0);
1700                    } else {
1701                        c = ((String) args[0]).charAt(0);
1702                    }
1703                    if (isValidDtmf(c)) {
1704                        mPhone.sendDtmf(c);
1705                        return new AtCommandResult(AtCommandResult.OK);
1706                    }
1707                }
1708                return new AtCommandResult(AtCommandResult.ERROR);
1709            }
1710            private boolean isValidDtmf(char c) {
1711                switch (c) {
1712                case '#':
1713                case '*':
1714                    return true;
1715                default:
1716                    if (Character.digit(c, 14) != -1) {
1717                        return true;  // 0-9 and A-D
1718                    }
1719                    return false;
1720                }
1721            }
1722        });
1723
1724        // List calls
1725        parser.register("+CLCC", new AtCommandHandler() {
1726            @Override
1727            public AtCommandResult handleActionCommand() {
1728                int phoneType = mPhone.getPhoneType();
1729                if (phoneType == Phone.PHONE_TYPE_CDMA) {
1730                    return cdmaGetClccResult();
1731                } else if (phoneType == Phone.PHONE_TYPE_GSM) {
1732                    return gsmGetClccResult();
1733                } else {
1734                    throw new IllegalStateException("Unexpected phone type: " + phoneType);
1735                }
1736            }
1737        });
1738
1739        // Call Hold and Multiparty Handling command
1740        parser.register("+CHLD", new AtCommandHandler() {
1741            @Override
1742            public AtCommandResult handleSetCommand(Object[] args) {
1743                int phoneType = mPhone.getPhoneType();
1744                if (args.length >= 1) {
1745                    if (args[0].equals(0)) {
1746                        boolean result;
1747                        if (mRingingCall.isRinging()) {
1748                            result = PhoneUtils.hangupRingingCall(mPhone);
1749                        } else {
1750                            result = PhoneUtils.hangupHoldingCall(mPhone);
1751                        }
1752                        if (result) {
1753                            return new AtCommandResult(AtCommandResult.OK);
1754                        } else {
1755                            return new AtCommandResult(AtCommandResult.ERROR);
1756                        }
1757                    } else if (args[0].equals(1)) {
1758                        if (phoneType == Phone.PHONE_TYPE_CDMA) {
1759                            if (mRingingCall.isRinging()) {
1760                                // If there is Call waiting then answer the call and
1761                                // put the first call on hold.
1762                                if (VDBG) log("CHLD:1 Callwaiting Answer call");
1763                                PhoneUtils.answerCall(mPhone);
1764                                PhoneUtils.setMute(mPhone, false);
1765                                // Setting the second callers state flag to TRUE (i.e. active)
1766                                cdmaSetSecondCallState(true);
1767                            } else {
1768                                // If there is no Call waiting then just hangup
1769                                // the active call. In CDMA this mean that the complete
1770                                // call session would be ended
1771                                if (VDBG) log("CHLD:1 Hangup Call");
1772                                PhoneUtils.hangup(mPhone);
1773                            }
1774                            return new AtCommandResult(AtCommandResult.OK);
1775                        } else if (phoneType == Phone.PHONE_TYPE_GSM) {
1776                            // Hangup active call, answer held call
1777                            if (PhoneUtils.answerAndEndActive(mPhone)) {
1778                                return new AtCommandResult(AtCommandResult.OK);
1779                            } else {
1780                                return new AtCommandResult(AtCommandResult.ERROR);
1781                            }
1782                        } else {
1783                            throw new IllegalStateException("Unexpected phone type: " + phoneType);
1784                        }
1785                    } else if (args[0].equals(2)) {
1786                        if (phoneType == Phone.PHONE_TYPE_CDMA) {
1787                            // For CDMA, the way we switch to a new incoming call is by
1788                            // calling PhoneUtils.answerCall(). switchAndHoldActive() won't
1789                            // properly update the call state within telephony.
1790                            // If the Phone state is already in CONF_CALL then we simply send
1791                            // a flash cmd by calling switchHoldingAndActive()
1792                            if (mRingingCall.isRinging()) {
1793                                if (VDBG) log("CHLD:2 Callwaiting Answer call");
1794                                PhoneUtils.answerCall(mPhone);
1795                                PhoneUtils.setMute(mPhone, false);
1796                                // Setting the second callers state flag to TRUE (i.e. active)
1797                                cdmaSetSecondCallState(true);
1798                            } else if (PhoneApp.getInstance().cdmaPhoneCallState
1799                                    .getCurrentCallState()
1800                                    == CdmaPhoneCallState.PhoneCallState.CONF_CALL) {
1801                                if (VDBG) log("CHLD:2 Swap Calls");
1802                                PhoneUtils.switchHoldingAndActive(mPhone);
1803                                // Toggle the second callers active state flag
1804                                cdmaSwapSecondCallState();
1805                            }
1806                        } else if (phoneType == Phone.PHONE_TYPE_GSM) {
1807                            PhoneUtils.switchHoldingAndActive(mPhone);
1808                        } else {
1809                            throw new IllegalStateException("Unexpected phone type: " + phoneType);
1810                        }
1811                        return new AtCommandResult(AtCommandResult.OK);
1812                    } else if (args[0].equals(3)) {
1813                        if (phoneType == Phone.PHONE_TYPE_CDMA) {
1814                            // For CDMA, we need to check if the call is in THRWAY_ACTIVE state
1815                            if (PhoneApp.getInstance().cdmaPhoneCallState.getCurrentCallState()
1816                                    == CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE) {
1817                                if (VDBG) log("CHLD:3 Merge Calls");
1818                                PhoneUtils.mergeCalls(mPhone);
1819                            }
1820                        } else if (phoneType == Phone.PHONE_TYPE_GSM) {
1821                            if (mForegroundCall.getState().isAlive() &&
1822                                    mBackgroundCall.getState().isAlive()) {
1823                                PhoneUtils.mergeCalls(mPhone);
1824                            }
1825                        } else {
1826                            throw new IllegalStateException("Unexpected phone type: " + phoneType);
1827                        }
1828                        return new AtCommandResult(AtCommandResult.OK);
1829                    }
1830                }
1831                return new AtCommandResult(AtCommandResult.ERROR);
1832            }
1833            @Override
1834            public AtCommandResult handleTestCommand() {
1835                mServiceConnectionEstablished = true;
1836                sendURC("+CHLD: (0,1,2,3)");
1837                sendURC("OK");  // send reply first, then connect audio
1838                if (isIncallAudio()) {
1839                    audioOn();
1840                }
1841                // already replied
1842                return new AtCommandResult(AtCommandResult.UNSOLICITED);
1843            }
1844        });
1845
1846        // Get Network operator name
1847        parser.register("+COPS", new AtCommandHandler() {
1848            @Override
1849            public AtCommandResult handleReadCommand() {
1850                String operatorName = mPhone.getServiceState().getOperatorAlphaLong();
1851                if (operatorName != null) {
1852                    if (operatorName.length() > 16) {
1853                        operatorName = operatorName.substring(0, 16);
1854                    }
1855                    return new AtCommandResult(
1856                            "+COPS: 0,0,\"" + operatorName + "\"");
1857                } else {
1858                    return new AtCommandResult(
1859                            "+COPS: 0,0,\"UNKNOWN\",0");
1860                }
1861            }
1862            @Override
1863            public AtCommandResult handleSetCommand(Object[] args) {
1864                // Handsfree only supports AT+COPS=3,0
1865                if (args.length != 2 || !(args[0] instanceof Integer)
1866                    || !(args[1] instanceof Integer)) {
1867                    // syntax error
1868                    return new AtCommandResult(AtCommandResult.ERROR);
1869                } else if ((Integer)args[0] != 3 || (Integer)args[1] != 0) {
1870                    return reportCmeError(BluetoothCmeError.OPERATION_NOT_SUPPORTED);
1871                } else {
1872                    return new AtCommandResult(AtCommandResult.OK);
1873                }
1874            }
1875            @Override
1876            public AtCommandResult handleTestCommand() {
1877                // Out of spec, but lets be friendly
1878                return new AtCommandResult("+COPS: (3),(0)");
1879            }
1880        });
1881
1882        // Mobile PIN
1883        // AT+CPIN is not in the handsfree spec (although it is in 3GPP)
1884        parser.register("+CPIN", new AtCommandHandler() {
1885            @Override
1886            public AtCommandResult handleReadCommand() {
1887                return new AtCommandResult("+CPIN: READY");
1888            }
1889        });
1890
1891        // Bluetooth Response and Hold
1892        // Only supported on PDC (Japan) and CDMA networks.
1893        parser.register("+BTRH", new AtCommandHandler() {
1894            @Override
1895            public AtCommandResult handleReadCommand() {
1896                // Replying with just OK indicates no response and hold
1897                // features in use now
1898                return new AtCommandResult(AtCommandResult.OK);
1899            }
1900            @Override
1901            public AtCommandResult handleSetCommand(Object[] args) {
1902                // Neeed PDC or CDMA
1903                return new AtCommandResult(AtCommandResult.ERROR);
1904            }
1905        });
1906
1907        // Request International Mobile Subscriber Identity (IMSI)
1908        // Not in bluetooth handset spec
1909        parser.register("+CIMI", new AtCommandHandler() {
1910            @Override
1911            public AtCommandResult handleActionCommand() {
1912                // AT+CIMI
1913                String imsi = mPhone.getSubscriberId();
1914                if (imsi == null || imsi.length() == 0) {
1915                    return reportCmeError(BluetoothCmeError.SIM_FAILURE);
1916                } else {
1917                    return new AtCommandResult(imsi);
1918                }
1919            }
1920        });
1921
1922        // Calling Line Identification Presentation
1923        parser.register("+CLIP", new AtCommandHandler() {
1924            @Override
1925            public AtCommandResult handleReadCommand() {
1926                // Currently assumes the network is provisioned for CLIP
1927                return new AtCommandResult("+CLIP: " + (mClip ? "1" : "0") + ",1");
1928            }
1929            @Override
1930            public AtCommandResult handleSetCommand(Object[] args) {
1931                // AT+CLIP=<n>
1932                if (args.length >= 1 && (args[0].equals(0) || args[0].equals(1))) {
1933                    mClip = args[0].equals(1);
1934                    return new AtCommandResult(AtCommandResult.OK);
1935                } else {
1936                    return new AtCommandResult(AtCommandResult.ERROR);
1937                }
1938            }
1939            @Override
1940            public AtCommandResult handleTestCommand() {
1941                return new AtCommandResult("+CLIP: (0-1)");
1942            }
1943        });
1944
1945        // AT+CGSN - Returns the device IMEI number.
1946        parser.register("+CGSN", new AtCommandHandler() {
1947            @Override
1948            public AtCommandResult handleActionCommand() {
1949                // Get the IMEI of the device.
1950                // mPhone will not be NULL at this point.
1951                return new AtCommandResult("+CGSN: " + mPhone.getDeviceId());
1952            }
1953        });
1954
1955        // AT+CGMM - Query Model Information
1956        parser.register("+CGMM", new AtCommandHandler() {
1957            @Override
1958            public AtCommandResult handleActionCommand() {
1959                // Return the Model Information.
1960                String model = SystemProperties.get("ro.product.model");
1961                if (model != null) {
1962                    return new AtCommandResult("+CGMM: " + model);
1963                } else {
1964                    return new AtCommandResult(AtCommandResult.ERROR);
1965                }
1966            }
1967        });
1968
1969        // AT+CGMI - Query Manufacturer Information
1970        parser.register("+CGMI", new AtCommandHandler() {
1971            @Override
1972            public AtCommandResult handleActionCommand() {
1973                // Return the Model Information.
1974                String manuf = SystemProperties.get("ro.product.manufacturer");
1975                if (manuf != null) {
1976                    return new AtCommandResult("+CGMI: " + manuf);
1977                } else {
1978                    return new AtCommandResult(AtCommandResult.ERROR);
1979                }
1980            }
1981        });
1982
1983        // Noise Reduction and Echo Cancellation control
1984        parser.register("+NREC", new AtCommandHandler() {
1985            @Override
1986            public AtCommandResult handleSetCommand(Object[] args) {
1987                if (args[0].equals(0)) {
1988                    mAudioManager.setParameters(HEADSET_NREC+"=off");
1989                    return new AtCommandResult(AtCommandResult.OK);
1990                } else if (args[0].equals(1)) {
1991                    mAudioManager.setParameters(HEADSET_NREC+"=on");
1992                    return new AtCommandResult(AtCommandResult.OK);
1993                }
1994                return new AtCommandResult(AtCommandResult.ERROR);
1995            }
1996        });
1997
1998        // Voice recognition (dialing)
1999        parser.register("+BVRA", new AtCommandHandler() {
2000            @Override
2001            public AtCommandResult handleSetCommand(Object[] args) {
2002                if (BluetoothHeadset.DISABLE_BT_VOICE_DIALING) {
2003                    return new AtCommandResult(AtCommandResult.ERROR);
2004                }
2005                if (args.length >= 1 && args[0].equals(1)) {
2006                    synchronized (BluetoothHandsfree.this) {
2007                        if (!mWaitingForVoiceRecognition) {
2008                            try {
2009                                mContext.startActivity(sVoiceCommandIntent);
2010                            } catch (ActivityNotFoundException e) {
2011                                return new AtCommandResult(AtCommandResult.ERROR);
2012                            }
2013                            expectVoiceRecognition();
2014                        }
2015                    }
2016                    return new AtCommandResult(AtCommandResult.UNSOLICITED);  // send nothing yet
2017                } else if (args.length >= 1 && args[0].equals(0)) {
2018                    audioOff();
2019                    return new AtCommandResult(AtCommandResult.OK);
2020                }
2021                return new AtCommandResult(AtCommandResult.ERROR);
2022            }
2023            @Override
2024            public AtCommandResult handleTestCommand() {
2025                return new AtCommandResult("+BVRA: (0-1)");
2026            }
2027        });
2028
2029        // Retrieve Subscriber Number
2030        parser.register("+CNUM", new AtCommandHandler() {
2031            @Override
2032            public AtCommandResult handleActionCommand() {
2033                String number = mPhone.getLine1Number();
2034                if (number == null) {
2035                    return new AtCommandResult(AtCommandResult.OK);
2036                }
2037                return new AtCommandResult("+CNUM: ,\"" + number + "\"," +
2038                        PhoneNumberUtils.toaFromString(number) + ",,4");
2039            }
2040        });
2041
2042        // Microphone Gain
2043        parser.register("+VGM", new AtCommandHandler() {
2044            @Override
2045            public AtCommandResult handleSetCommand(Object[] args) {
2046                // AT+VGM=<gain>    in range [0,15]
2047                // Headset/Handsfree is reporting its current gain setting
2048                return new AtCommandResult(AtCommandResult.OK);
2049            }
2050        });
2051
2052        // Speaker Gain
2053        parser.register("+VGS", new AtCommandHandler() {
2054            @Override
2055            public AtCommandResult handleSetCommand(Object[] args) {
2056                // AT+VGS=<gain>    in range [0,15]
2057                if (args.length != 1 || !(args[0] instanceof Integer)) {
2058                    return new AtCommandResult(AtCommandResult.ERROR);
2059                }
2060                mScoGain = (Integer) args[0];
2061                int flag =  mAudioManager.isBluetoothScoOn() ? AudioManager.FLAG_SHOW_UI:0;
2062
2063                mAudioManager.setStreamVolume(AudioManager.STREAM_BLUETOOTH_SCO, mScoGain, flag);
2064                return new AtCommandResult(AtCommandResult.OK);
2065            }
2066        });
2067
2068        // Phone activity status
2069        parser.register("+CPAS", new AtCommandHandler() {
2070            @Override
2071            public AtCommandResult handleActionCommand() {
2072                int status = 0;
2073                switch (mPhone.getState()) {
2074                case IDLE:
2075                    status = 0;
2076                    break;
2077                case RINGING:
2078                    status = 3;
2079                    break;
2080                case OFFHOOK:
2081                    status = 4;
2082                    break;
2083                }
2084                return new AtCommandResult("+CPAS: " + status);
2085            }
2086        });
2087        mPhonebook.register(parser);
2088    }
2089
2090    public void sendScoGainUpdate(int gain) {
2091        if (mScoGain != gain && (mRemoteBrsf & BRSF_HF_REMOTE_VOL_CONTROL) != 0x0) {
2092            sendURC("+VGS:" + gain);
2093            mScoGain = gain;
2094        }
2095    }
2096
2097    public AtCommandResult reportCmeError(int error) {
2098        if (mCmee) {
2099            AtCommandResult result = new AtCommandResult(AtCommandResult.UNSOLICITED);
2100            result.addResponse("+CME ERROR: " + error);
2101            return result;
2102        } else {
2103            return new AtCommandResult(AtCommandResult.ERROR);
2104        }
2105    }
2106
2107    private static final int START_CALL_TIMEOUT = 10000;  // ms
2108
2109    private synchronized void expectCallStart() {
2110        mWaitingForCallStart = true;
2111        Message msg = Message.obtain(mHandler, CHECK_CALL_STARTED);
2112        mHandler.sendMessageDelayed(msg, START_CALL_TIMEOUT);
2113        if (!mStartCallWakeLock.isHeld()) {
2114            mStartCallWakeLock.acquire(START_CALL_TIMEOUT);
2115        }
2116    }
2117
2118    private synchronized void callStarted() {
2119        if (mWaitingForCallStart) {
2120            mWaitingForCallStart = false;
2121            sendURC("OK");
2122            if (mStartCallWakeLock.isHeld()) {
2123                mStartCallWakeLock.release();
2124            }
2125        }
2126    }
2127
2128    private static final int START_VOICE_RECOGNITION_TIMEOUT = 5000;  // ms
2129
2130    private synchronized void expectVoiceRecognition() {
2131        mWaitingForVoiceRecognition = true;
2132        Message msg = Message.obtain(mHandler, CHECK_VOICE_RECOGNITION_STARTED);
2133        mHandler.sendMessageDelayed(msg, START_VOICE_RECOGNITION_TIMEOUT);
2134        if (!mStartVoiceRecognitionWakeLock.isHeld()) {
2135            mStartVoiceRecognitionWakeLock.acquire(START_VOICE_RECOGNITION_TIMEOUT);
2136        }
2137    }
2138
2139    /* package */ synchronized boolean startVoiceRecognition() {
2140        if (mWaitingForVoiceRecognition) {
2141            // HF initiated
2142            mWaitingForVoiceRecognition = false;
2143            sendURC("OK");
2144        } else {
2145            // AG initiated
2146            sendURC("+BVRA: 1");
2147        }
2148        boolean ret = audioOn();
2149        if (mStartVoiceRecognitionWakeLock.isHeld()) {
2150            mStartVoiceRecognitionWakeLock.release();
2151        }
2152        return ret;
2153    }
2154
2155    /* package */ synchronized boolean stopVoiceRecognition() {
2156        sendURC("+BVRA: 0");
2157        audioOff();
2158        return true;
2159    }
2160
2161    private boolean inDebug() {
2162        return DBG && SystemProperties.getBoolean(DebugThread.DEBUG_HANDSFREE, false);
2163    }
2164
2165    private boolean allowAudioAnytime() {
2166        return inDebug() && SystemProperties.getBoolean(DebugThread.DEBUG_HANDSFREE_AUDIO_ANYTIME,
2167                false);
2168    }
2169
2170    private void startDebug() {
2171        if (DBG && mDebugThread == null) {
2172            mDebugThread = new DebugThread();
2173            mDebugThread.start();
2174        }
2175    }
2176
2177    private void stopDebug() {
2178        if (mDebugThread != null) {
2179            mDebugThread.interrupt();
2180            mDebugThread = null;
2181        }
2182    }
2183
2184    /** Debug thread to read debug properties - runs when debug.bt.hfp is true
2185     *  at the time a bluetooth handsfree device is connected. Debug properties
2186     *  are polled and mock updates sent every 1 second */
2187    private class DebugThread extends Thread {
2188        /** Turns on/off handsfree profile debugging mode */
2189        private static final String DEBUG_HANDSFREE = "debug.bt.hfp";
2190
2191        /** Mock battery level change - use 0 to 5 */
2192        private static final String DEBUG_HANDSFREE_BATTERY = "debug.bt.hfp.battery";
2193
2194        /** Mock no cellular service when false */
2195        private static final String DEBUG_HANDSFREE_SERVICE = "debug.bt.hfp.service";
2196
2197        /** Mock cellular roaming when true */
2198        private static final String DEBUG_HANDSFREE_ROAM = "debug.bt.hfp.roam";
2199
2200        /** false to true transition will force an audio (SCO) connection to
2201         *  be established. true to false will force audio to be disconnected
2202         */
2203        private static final String DEBUG_HANDSFREE_AUDIO = "debug.bt.hfp.audio";
2204
2205        /** true allows incoming SCO connection out of call.
2206         */
2207        private static final String DEBUG_HANDSFREE_AUDIO_ANYTIME = "debug.bt.hfp.audio_anytime";
2208
2209        /** Mock signal strength change in ASU - use 0 to 31 */
2210        private static final String DEBUG_HANDSFREE_SIGNAL = "debug.bt.hfp.signal";
2211
2212        /** Debug AT+CLCC: print +CLCC result */
2213        private static final String DEBUG_HANDSFREE_CLCC = "debug.bt.hfp.clcc";
2214
2215        /** Debug AT+BSIR - Send In Band Ringtones Unsolicited AT command.
2216         * debug.bt.unsol.inband = 0 => AT+BSIR = 0 sent by the AG
2217         * debug.bt.unsol.inband = 1 => AT+BSIR = 0 sent by the AG
2218         * Other values are ignored.
2219         */
2220
2221        private static final String DEBUG_UNSOL_INBAND_RINGTONE =
2222            "debug.bt.unsol.inband";
2223
2224        @Override
2225        public void run() {
2226            boolean oldService = true;
2227            boolean oldRoam = false;
2228            boolean oldAudio = false;
2229
2230            while (!isInterrupted() && inDebug()) {
2231                int batteryLevel = SystemProperties.getInt(DEBUG_HANDSFREE_BATTERY, -1);
2232                if (batteryLevel >= 0 && batteryLevel <= 5) {
2233                    Intent intent = new Intent();
2234                    intent.putExtra("level", batteryLevel);
2235                    intent.putExtra("scale", 5);
2236                    mBluetoothPhoneState.updateBatteryState(intent);
2237                }
2238
2239                boolean serviceStateChanged = false;
2240                if (SystemProperties.getBoolean(DEBUG_HANDSFREE_SERVICE, true) != oldService) {
2241                    oldService = !oldService;
2242                    serviceStateChanged = true;
2243                }
2244                if (SystemProperties.getBoolean(DEBUG_HANDSFREE_ROAM, false) != oldRoam) {
2245                    oldRoam = !oldRoam;
2246                    serviceStateChanged = true;
2247                }
2248                if (serviceStateChanged) {
2249                    Bundle b = new Bundle();
2250                    b.putInt("state", oldService ? 0 : 1);
2251                    b.putBoolean("roaming", oldRoam);
2252                    mBluetoothPhoneState.updateServiceState(true, ServiceState.newFromBundle(b));
2253                }
2254
2255                if (SystemProperties.getBoolean(DEBUG_HANDSFREE_AUDIO, false) != oldAudio) {
2256                    oldAudio = !oldAudio;
2257                    if (oldAudio) {
2258                        audioOn();
2259                    } else {
2260                        audioOff();
2261                    }
2262                }
2263
2264                int signalLevel = SystemProperties.getInt(DEBUG_HANDSFREE_SIGNAL, -1);
2265                if (signalLevel >= 0 && signalLevel <= 31) {
2266                    SignalStrength signalStrength = new SignalStrength(signalLevel, -1, -1, -1,
2267                            -1, -1, -1, true);
2268                    Intent intent = new Intent();
2269                    Bundle data = new Bundle();
2270                    signalStrength.fillInNotifierBundle(data);
2271                    intent.putExtras(data);
2272                    mBluetoothPhoneState.updateSignalState(intent);
2273                }
2274
2275                if (SystemProperties.getBoolean(DEBUG_HANDSFREE_CLCC, false)) {
2276                    log(gsmGetClccResult().toString());
2277                }
2278                try {
2279                    sleep(1000);  // 1 second
2280                } catch (InterruptedException e) {
2281                    break;
2282                }
2283
2284                int inBandRing =
2285                    SystemProperties.getInt(DEBUG_UNSOL_INBAND_RINGTONE, -1);
2286                if (inBandRing == 0 || inBandRing == 1) {
2287                    AtCommandResult result =
2288                        new AtCommandResult(AtCommandResult.UNSOLICITED);
2289                    result.addResponse("+BSIR: " + inBandRing);
2290                    sendURC(result.toString());
2291                }
2292            }
2293        }
2294    }
2295
2296    public void cdmaSwapSecondCallState() {
2297        if (VDBG) log("cdmaSetSecondCallState: Toggling mCdmaIsSecondCallActive");
2298        mCdmaIsSecondCallActive = !mCdmaIsSecondCallActive;
2299    }
2300
2301    public void cdmaSetSecondCallState(boolean state) {
2302        if (VDBG) log("cdmaSetSecondCallState: Setting mCdmaIsSecondCallActive to " + state);
2303        mCdmaIsSecondCallActive = state;
2304    }
2305
2306    private static void log(String msg) {
2307        Log.d(TAG, msg);
2308    }
2309}
2310