GsmCallTracker.java revision 368e873b65e60268521b3c74110a9b2abe8086ac
1/*
2 * Copyright (C) 2006 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.internal.telephony.gsm;
18
19import android.os.AsyncResult;
20import android.os.Handler;
21import android.os.Message;
22import android.os.Registrant;
23import android.os.RegistrantList;
24import android.os.SystemProperties;
25import android.telephony.PhoneNumberUtils;
26import android.telephony.ServiceState;
27import android.telephony.TelephonyManager;
28import android.telephony.gsm.GsmCellLocation;
29import android.util.EventLog;
30import android.telephony.Rlog;
31
32import com.android.internal.telephony.CallStateException;
33import com.android.internal.telephony.CallTracker;
34import com.android.internal.telephony.CommandsInterface;
35import com.android.internal.telephony.Connection;
36import com.android.internal.telephony.DriverCall;
37import com.android.internal.telephony.EventLogTags;
38import com.android.internal.telephony.Phone;
39import com.android.internal.telephony.PhoneConstants;
40import com.android.internal.telephony.TelephonyProperties;
41import com.android.internal.telephony.UUSInfo;
42import com.android.internal.telephony.gsm.CallFailCause;
43import com.android.internal.telephony.gsm.GSMPhone;
44import com.android.internal.telephony.gsm.GsmCall;
45import com.android.internal.telephony.gsm.GsmConnection;
46
47import java.io.FileDescriptor;
48import java.io.PrintWriter;
49import java.util.List;
50import java.util.ArrayList;
51
52/**
53 * {@hide}
54 */
55public final class GsmCallTracker extends CallTracker {
56    static final String LOG_TAG = "GsmCallTracker";
57    private static final boolean REPEAT_POLLING = false;
58
59    private static final boolean DBG_POLL = false;
60
61    //***** Constants
62
63    static final int MAX_CONNECTIONS = 7;   // only 7 connections allowed in GSM
64    static final int MAX_CONNECTIONS_PER_CALL = 5; // only 5 connections allowed per call
65
66    //***** Instance Variables
67    GsmConnection mConnections[] = new GsmConnection[MAX_CONNECTIONS];
68    RegistrantList mVoiceCallEndedRegistrants = new RegistrantList();
69    RegistrantList mVoiceCallStartedRegistrants = new RegistrantList();
70
71
72    // connections dropped during last poll
73    ArrayList<GsmConnection> mDroppedDuringPoll
74        = new ArrayList<GsmConnection>(MAX_CONNECTIONS);
75
76    GsmCall mRingingCall = new GsmCall(this);
77            // A call that is ringing or (call) waiting
78    GsmCall mForegroundCall = new GsmCall(this);
79    GsmCall mBackgroundCall = new GsmCall(this);
80
81    GsmConnection pendingMO;
82    boolean mHangupPendingMO;
83
84    GSMPhone mPhone;
85
86    boolean mDesiredMute = false;    // false = mute off
87
88    PhoneConstants.State mState = PhoneConstants.State.IDLE;
89
90
91
92    //***** Events
93
94
95    //***** Constructors
96
97    GsmCallTracker (GSMPhone phone) {
98        this.mPhone = phone;
99        mCi = phone.mCi;
100
101        mCi.registerForCallStateChanged(this, EVENT_CALL_STATE_CHANGE, null);
102
103        mCi.registerForOn(this, EVENT_RADIO_AVAILABLE, null);
104        mCi.registerForNotAvailable(this, EVENT_RADIO_NOT_AVAILABLE, null);
105    }
106
107    public void dispose() {
108        //Unregister for all events
109        mCi.unregisterForCallStateChanged(this);
110        mCi.unregisterForOn(this);
111        mCi.unregisterForNotAvailable(this);
112
113        for(GsmConnection c : mConnections) {
114            try {
115                if(c != null) hangup(c);
116            } catch (CallStateException ex) {
117                Rlog.e(LOG_TAG, "unexpected error on hangup during dispose");
118            }
119        }
120
121        try {
122            if(pendingMO != null) hangup(pendingMO);
123        } catch (CallStateException ex) {
124            Rlog.e(LOG_TAG, "unexpected error on hangup during dispose");
125        }
126
127        clearDisconnected();
128    }
129
130    @Override
131    protected void finalize() {
132        Rlog.d(LOG_TAG, "GsmCallTracker finalized");
133    }
134
135    //***** Instance Methods
136
137    //***** Public Methods
138    @Override
139    public void registerForVoiceCallStarted(Handler h, int what, Object obj) {
140        Registrant r = new Registrant(h, what, obj);
141        mVoiceCallStartedRegistrants.add(r);
142    }
143
144    @Override
145    public void unregisterForVoiceCallStarted(Handler h) {
146        mVoiceCallStartedRegistrants.remove(h);
147    }
148
149    @Override
150    public void registerForVoiceCallEnded(Handler h, int what, Object obj) {
151        Registrant r = new Registrant(h, what, obj);
152        mVoiceCallEndedRegistrants.add(r);
153    }
154
155    @Override
156    public void unregisterForVoiceCallEnded(Handler h) {
157        mVoiceCallEndedRegistrants.remove(h);
158    }
159
160    private void
161    fakeHoldForegroundBeforeDial() {
162        List<Connection> connCopy;
163
164        // We need to make a copy here, since fakeHoldBeforeDial()
165        // modifies the lists, and we don't want to reverse the order
166        connCopy = (List<Connection>) mForegroundCall.mConnections.clone();
167
168        for (int i = 0, s = connCopy.size() ; i < s ; i++) {
169            GsmConnection conn = (GsmConnection)connCopy.get(i);
170
171            conn.fakeHoldBeforeDial();
172        }
173    }
174
175    /**
176     * clirMode is one of the CLIR_ constants
177     */
178    synchronized Connection
179    dial (String dialString, int clirMode, UUSInfo uusInfo) throws CallStateException {
180        // note that this triggers call state changed notif
181        clearDisconnected();
182
183        if (!canDial()) {
184            throw new CallStateException("cannot dial in current state");
185        }
186
187        // The new call must be assigned to the foreground call.
188        // That call must be idle, so place anything that's
189        // there on hold
190        if (mForegroundCall.getState() == GsmCall.State.ACTIVE) {
191            // this will probably be done by the radio anyway
192            // but the dial might fail before this happens
193            // and we need to make sure the foreground call is clear
194            // for the newly dialed connection
195            switchWaitingOrHoldingAndActive();
196
197            // Fake local state so that
198            // a) foregroundCall is empty for the newly dialed connection
199            // b) hasNonHangupStateChanged remains false in the
200            // next poll, so that we don't clear a failed dialing call
201            fakeHoldForegroundBeforeDial();
202        }
203
204        if (mForegroundCall.getState() != GsmCall.State.IDLE) {
205            //we should have failed in !canDial() above before we get here
206            throw new CallStateException("cannot dial in current state");
207        }
208
209        pendingMO = new GsmConnection(mPhone.getContext(), checkForTestEmergencyNumber(dialString),
210                this, mForegroundCall);
211        mHangupPendingMO = false;
212
213        if (pendingMO.mAddress == null || pendingMO.mAddress.length() == 0
214            || pendingMO.mAddress.indexOf(PhoneNumberUtils.WILD) >= 0
215        ) {
216            // Phone number is invalid
217            pendingMO.mCause = Connection.DisconnectCause.INVALID_NUMBER;
218
219            // handlePollCalls() will notice this call not present
220            // and will mark it as dropped.
221            pollCallsWhenSafe();
222        } else {
223            // Always unmute when initiating a new call
224            setMute(false);
225
226            mCi.dial(pendingMO.mAddress, clirMode, uusInfo, obtainCompleteMessage());
227        }
228
229        updatePhoneState();
230        mPhone.notifyPreciseCallStateChanged();
231
232        return pendingMO;
233    }
234
235    Connection
236    dial(String dialString) throws CallStateException {
237        return dial(dialString, CommandsInterface.CLIR_DEFAULT, null);
238    }
239
240    Connection
241    dial(String dialString, UUSInfo uusInfo) throws CallStateException {
242        return dial(dialString, CommandsInterface.CLIR_DEFAULT, uusInfo);
243    }
244
245    Connection
246    dial(String dialString, int clirMode) throws CallStateException {
247        return dial(dialString, clirMode, null);
248    }
249
250    void
251    acceptCall () throws CallStateException {
252        // FIXME if SWITCH fails, should retry with ANSWER
253        // in case the active/holding call disappeared and this
254        // is no longer call waiting
255
256        if (mRingingCall.getState() == GsmCall.State.INCOMING) {
257            Rlog.i("phone", "acceptCall: incoming...");
258            // Always unmute when answering a new call
259            setMute(false);
260            mCi.acceptCall(obtainCompleteMessage());
261        } else if (mRingingCall.getState() == GsmCall.State.WAITING) {
262            setMute(false);
263            switchWaitingOrHoldingAndActive();
264        } else {
265            throw new CallStateException("phone not ringing");
266        }
267    }
268
269    void
270    rejectCall () throws CallStateException {
271        // AT+CHLD=0 means "release held or UDUB"
272        // so if the phone isn't ringing, this could hang up held
273        if (mRingingCall.getState().isRinging()) {
274            mCi.rejectCall(obtainCompleteMessage());
275        } else {
276            throw new CallStateException("phone not ringing");
277        }
278    }
279
280    void
281    switchWaitingOrHoldingAndActive() throws CallStateException {
282        // Should we bother with this check?
283        if (mRingingCall.getState() == GsmCall.State.INCOMING) {
284            throw new CallStateException("cannot be in the incoming state");
285        } else {
286            mCi.switchWaitingOrHoldingAndActive(
287                    obtainCompleteMessage(EVENT_SWITCH_RESULT));
288        }
289    }
290
291    void
292    conference() {
293        mCi.conference(obtainCompleteMessage(EVENT_CONFERENCE_RESULT));
294    }
295
296    void
297    explicitCallTransfer() {
298        mCi.explicitCallTransfer(obtainCompleteMessage(EVENT_ECT_RESULT));
299    }
300
301    void
302    clearDisconnected() {
303        internalClearDisconnected();
304
305        updatePhoneState();
306        mPhone.notifyPreciseCallStateChanged();
307    }
308
309    boolean
310    canConference() {
311        return mForegroundCall.getState() == GsmCall.State.ACTIVE
312                && mBackgroundCall.getState() == GsmCall.State.HOLDING
313                && !mBackgroundCall.isFull()
314                && !mForegroundCall.isFull();
315    }
316
317    boolean
318    canDial() {
319        boolean ret;
320        int serviceState = mPhone.getServiceState().getState();
321        String disableCall = SystemProperties.get(
322                TelephonyProperties.PROPERTY_DISABLE_CALL, "false");
323
324        ret = (serviceState != ServiceState.STATE_POWER_OFF)
325                && pendingMO == null
326                && !mRingingCall.isRinging()
327                && !disableCall.equals("true")
328                && (!mForegroundCall.getState().isAlive()
329                    || !mBackgroundCall.getState().isAlive());
330
331        return ret;
332    }
333
334    boolean
335    canTransfer() {
336        return mForegroundCall.getState() == GsmCall.State.ACTIVE
337                && mBackgroundCall.getState() == GsmCall.State.HOLDING;
338    }
339
340    //***** Private Instance Methods
341
342    private void
343    internalClearDisconnected() {
344        mRingingCall.clearDisconnected();
345        mForegroundCall.clearDisconnected();
346        mBackgroundCall.clearDisconnected();
347    }
348
349    /**
350     * Obtain a message to use for signalling "invoke getCurrentCalls() when
351     * this operation and all other pending operations are complete
352     */
353    private Message
354    obtainCompleteMessage() {
355        return obtainCompleteMessage(EVENT_OPERATION_COMPLETE);
356    }
357
358    /**
359     * Obtain a message to use for signalling "invoke getCurrentCalls() when
360     * this operation and all other pending operations are complete
361     */
362    private Message
363    obtainCompleteMessage(int what) {
364        mPendingOperations++;
365        mLastRelevantPoll = null;
366        mNeedsPoll = true;
367
368        if (DBG_POLL) log("obtainCompleteMessage: pendingOperations=" +
369                mPendingOperations + ", needsPoll=" + mNeedsPoll);
370
371        return obtainMessage(what);
372    }
373
374    private void
375    operationComplete() {
376        mPendingOperations--;
377
378        if (DBG_POLL) log("operationComplete: pendingOperations=" +
379                mPendingOperations + ", needsPoll=" + mNeedsPoll);
380
381        if (mPendingOperations == 0 && mNeedsPoll) {
382            mLastRelevantPoll = obtainMessage(EVENT_POLL_CALLS_RESULT);
383            mCi.getCurrentCalls(mLastRelevantPoll);
384        } else if (mPendingOperations < 0) {
385            // this should never happen
386            Rlog.e(LOG_TAG,"GsmCallTracker.pendingOperations < 0");
387            mPendingOperations = 0;
388        }
389    }
390
391    private void
392    updatePhoneState() {
393        PhoneConstants.State oldState = mState;
394
395        if (mRingingCall.isRinging()) {
396            mState = PhoneConstants.State.RINGING;
397        } else if (pendingMO != null ||
398                !(mForegroundCall.isIdle() && mBackgroundCall.isIdle())) {
399            mState = PhoneConstants.State.OFFHOOK;
400        } else {
401            mState = PhoneConstants.State.IDLE;
402        }
403
404        if (mState == PhoneConstants.State.IDLE && oldState != mState) {
405            mVoiceCallEndedRegistrants.notifyRegistrants(
406                new AsyncResult(null, null, null));
407        } else if (oldState == PhoneConstants.State.IDLE && oldState != mState) {
408            mVoiceCallStartedRegistrants.notifyRegistrants (
409                    new AsyncResult(null, null, null));
410        }
411
412        if (mState != oldState) {
413            mPhone.notifyPhoneStateChanged();
414        }
415    }
416
417    @Override
418    protected synchronized void
419    handlePollCalls(AsyncResult ar) {
420        List polledCalls;
421
422        if (ar.exception == null) {
423            polledCalls = (List)ar.result;
424        } else if (isCommandExceptionRadioNotAvailable(ar.exception)) {
425            // just a dummy empty ArrayList to cause the loop
426            // to hang up all the calls
427            polledCalls = new ArrayList();
428        } else {
429            // Radio probably wasn't ready--try again in a bit
430            // But don't keep polling if the channel is closed
431            pollCallsAfterDelay();
432            return;
433        }
434
435        Connection newRinging = null; //or waiting
436        boolean hasNonHangupStateChanged = false;   // Any change besides
437                                                    // a dropped connection
438        boolean hasAnyCallDisconnected = false;
439        boolean needsPollDelay = false;
440        boolean unknownConnectionAppeared = false;
441
442        for (int i = 0, curDC = 0, dcSize = polledCalls.size()
443                ; i < mConnections.length; i++) {
444            GsmConnection conn = mConnections[i];
445            DriverCall dc = null;
446
447            // polledCall list is sparse
448            if (curDC < dcSize) {
449                dc = (DriverCall) polledCalls.get(curDC);
450
451                if (dc.index == i+1) {
452                    curDC++;
453                } else {
454                    dc = null;
455                }
456            }
457
458            if (DBG_POLL) log("poll: conn[i=" + i + "]=" +
459                    conn+", dc=" + dc);
460
461            if (conn == null && dc != null) {
462                // Connection appeared in CLCC response that we don't know about
463                if (pendingMO != null && pendingMO.compareTo(dc)) {
464
465                    if (DBG_POLL) log("poll: pendingMO=" + pendingMO);
466
467                    // It's our pending mobile originating call
468                    mConnections[i] = pendingMO;
469                    pendingMO.mIndex = i;
470                    pendingMO.update(dc);
471                    pendingMO = null;
472
473                    // Someone has already asked to hangup this call
474                    if (mHangupPendingMO) {
475                        mHangupPendingMO = false;
476                        try {
477                            if (Phone.DEBUG_PHONE) log(
478                                    "poll: hangupPendingMO, hangup conn " + i);
479                            hangup(mConnections[i]);
480                        } catch (CallStateException ex) {
481                            Rlog.e(LOG_TAG, "unexpected error on hangup");
482                        }
483
484                        // Do not continue processing this poll
485                        // Wait for hangup and repoll
486                        return;
487                    }
488                } else {
489                    mConnections[i] = new GsmConnection(mPhone.getContext(), dc, this, i);
490
491                    // it's a ringing call
492                    if (mConnections[i].getCall() == mRingingCall) {
493                        newRinging = mConnections[i];
494                    } else {
495                        // Something strange happened: a call appeared
496                        // which is neither a ringing call or one we created.
497                        // Either we've crashed and re-attached to an existing
498                        // call, or something else (eg, SIM) initiated the call.
499
500                        Rlog.i(LOG_TAG,"Phantom call appeared " + dc);
501
502                        // If it's a connected call, set the connect time so that
503                        // it's non-zero.  It may not be accurate, but at least
504                        // it won't appear as a Missed Call.
505                        if (dc.state != DriverCall.State.ALERTING
506                                && dc.state != DriverCall.State.DIALING) {
507                            mConnections[i].onConnectedInOrOut();
508                            if (dc.state == DriverCall.State.HOLDING) {
509                                // We've transitioned into HOLDING
510                                mConnections[i].onStartedHolding();
511                            }
512                        }
513
514                        unknownConnectionAppeared = true;
515                    }
516                }
517                hasNonHangupStateChanged = true;
518            } else if (conn != null && dc == null) {
519                // Connection missing in CLCC response that we were
520                // tracking.
521                mDroppedDuringPoll.add(conn);
522                // Dropped connections are removed from the CallTracker
523                // list but kept in the GsmCall list
524                mConnections[i] = null;
525            } else if (conn != null && dc != null && !conn.compareTo(dc)) {
526                // Connection in CLCC response does not match what
527                // we were tracking. Assume dropped call and new call
528
529                mDroppedDuringPoll.add(conn);
530                mConnections[i] = new GsmConnection (mPhone.getContext(), dc, this, i);
531
532                if (mConnections[i].getCall() == mRingingCall) {
533                    newRinging = mConnections[i];
534                } // else something strange happened
535                hasNonHangupStateChanged = true;
536            } else if (conn != null && dc != null) { /* implicit conn.compareTo(dc) */
537                boolean changed;
538                changed = conn.update(dc);
539                hasNonHangupStateChanged = hasNonHangupStateChanged || changed;
540            }
541
542            if (REPEAT_POLLING) {
543                if (dc != null) {
544                    // FIXME with RIL, we should not need this anymore
545                    if ((dc.state == DriverCall.State.DIALING
546                            /*&& cm.getOption(cm.OPTION_POLL_DIALING)*/)
547                        || (dc.state == DriverCall.State.ALERTING
548                            /*&& cm.getOption(cm.OPTION_POLL_ALERTING)*/)
549                        || (dc.state == DriverCall.State.INCOMING
550                            /*&& cm.getOption(cm.OPTION_POLL_INCOMING)*/)
551                        || (dc.state == DriverCall.State.WAITING
552                            /*&& cm.getOption(cm.OPTION_POLL_WAITING)*/)
553                    ) {
554                        // Sometimes there's no unsolicited notification
555                        // for state transitions
556                        needsPollDelay = true;
557                    }
558                }
559            }
560        }
561
562        // This is the first poll after an ATD.
563        // We expect the pending call to appear in the list
564        // If it does not, we land here
565        if (pendingMO != null) {
566            Rlog.d(LOG_TAG,"Pending MO dropped before poll fg state:"
567                            + mForegroundCall.getState());
568
569            mDroppedDuringPoll.add(pendingMO);
570            pendingMO = null;
571            mHangupPendingMO = false;
572        }
573
574        if (newRinging != null) {
575            mPhone.notifyNewRingingConnection(newRinging);
576        }
577
578        // clear the "local hangup" and "missed/rejected call"
579        // cases from the "dropped during poll" list
580        // These cases need no "last call fail" reason
581        for (int i = mDroppedDuringPoll.size() - 1; i >= 0 ; i--) {
582            GsmConnection conn = mDroppedDuringPoll.get(i);
583
584            if (conn.isIncoming() && conn.getConnectTime() == 0) {
585                // Missed or rejected call
586                Connection.DisconnectCause cause;
587                if (conn.mCause == Connection.DisconnectCause.LOCAL) {
588                    cause = Connection.DisconnectCause.INCOMING_REJECTED;
589                } else {
590                    cause = Connection.DisconnectCause.INCOMING_MISSED;
591                }
592
593                if (Phone.DEBUG_PHONE) {
594                    log("missed/rejected call, conn.cause=" + conn.mCause);
595                    log("setting cause to " + cause);
596                }
597                mDroppedDuringPoll.remove(i);
598                hasAnyCallDisconnected |= conn.onDisconnect(cause);
599            } else if (conn.mCause == Connection.DisconnectCause.LOCAL
600                    || conn.mCause == Connection.DisconnectCause.INVALID_NUMBER) {
601                mDroppedDuringPoll.remove(i);
602                hasAnyCallDisconnected |= conn.onDisconnect(conn.mCause);
603            }
604        }
605
606        // Any non-local disconnects: determine cause
607        if (mDroppedDuringPoll.size() > 0) {
608            mCi.getLastCallFailCause(
609                obtainNoPollCompleteMessage(EVENT_GET_LAST_CALL_FAIL_CAUSE));
610        }
611
612        if (needsPollDelay) {
613            pollCallsAfterDelay();
614        }
615
616        // Cases when we can no longer keep disconnected Connection's
617        // with their previous calls
618        // 1) the phone has started to ring
619        // 2) A Call/Connection object has changed state...
620        //    we may have switched or held or answered (but not hung up)
621        if (newRinging != null || hasNonHangupStateChanged || hasAnyCallDisconnected) {
622            internalClearDisconnected();
623        }
624
625        updatePhoneState();
626
627        if (unknownConnectionAppeared) {
628            mPhone.notifyUnknownConnection();
629        }
630
631        if (hasNonHangupStateChanged || newRinging != null || hasAnyCallDisconnected) {
632            mPhone.notifyPreciseCallStateChanged();
633        }
634
635        //dumpState();
636    }
637
638    private void
639    handleRadioNotAvailable() {
640        // handlePollCalls will clear out its
641        // call list when it gets the CommandException
642        // error result from this
643        pollCallsWhenSafe();
644    }
645
646    private void
647    dumpState() {
648        List l;
649
650        Rlog.i(LOG_TAG,"Phone State:" + mState);
651
652        Rlog.i(LOG_TAG,"Ringing call: " + mRingingCall.toString());
653
654        l = mRingingCall.getConnections();
655        for (int i = 0, s = l.size(); i < s; i++) {
656            Rlog.i(LOG_TAG,l.get(i).toString());
657        }
658
659        Rlog.i(LOG_TAG,"Foreground call: " + mForegroundCall.toString());
660
661        l = mForegroundCall.getConnections();
662        for (int i = 0, s = l.size(); i < s; i++) {
663            Rlog.i(LOG_TAG,l.get(i).toString());
664        }
665
666        Rlog.i(LOG_TAG,"Background call: " + mBackgroundCall.toString());
667
668        l = mBackgroundCall.getConnections();
669        for (int i = 0, s = l.size(); i < s; i++) {
670            Rlog.i(LOG_TAG,l.get(i).toString());
671        }
672
673    }
674
675    //***** Called from GsmConnection
676
677    /*package*/ void
678    hangup (GsmConnection conn) throws CallStateException {
679        if (conn.mOwner != this) {
680            throw new CallStateException ("GsmConnection " + conn
681                                    + "does not belong to GsmCallTracker " + this);
682        }
683
684        if (conn == pendingMO) {
685            // We're hanging up an outgoing call that doesn't have it's
686            // GSM index assigned yet
687
688            if (Phone.DEBUG_PHONE) log("hangup: set hangupPendingMO to true");
689            mHangupPendingMO = true;
690        } else {
691            try {
692                mCi.hangupConnection (conn.getGSMIndex(), obtainCompleteMessage());
693            } catch (CallStateException ex) {
694                // Ignore "connection not found"
695                // Call may have hung up already
696                Rlog.w(LOG_TAG,"GsmCallTracker WARN: hangup() on absent connection "
697                                + conn);
698            }
699        }
700
701        conn.onHangupLocal();
702    }
703
704    /*package*/ void
705    separate (GsmConnection conn) throws CallStateException {
706        if (conn.mOwner != this) {
707            throw new CallStateException ("GsmConnection " + conn
708                                    + "does not belong to GsmCallTracker " + this);
709        }
710        try {
711            mCi.separateConnection (conn.getGSMIndex(),
712                obtainCompleteMessage(EVENT_SEPARATE_RESULT));
713        } catch (CallStateException ex) {
714            // Ignore "connection not found"
715            // Call may have hung up already
716            Rlog.w(LOG_TAG,"GsmCallTracker WARN: separate() on absent connection "
717                          + conn);
718        }
719    }
720
721    //***** Called from GSMPhone
722
723    /*package*/ void
724    setMute(boolean mute) {
725        mDesiredMute = mute;
726        mCi.setMute(mDesiredMute, null);
727    }
728
729    /*package*/ boolean
730    getMute() {
731        return mDesiredMute;
732    }
733
734
735    //***** Called from GsmCall
736
737    /* package */ void
738    hangup (GsmCall call) throws CallStateException {
739        if (call.getConnections().size() == 0) {
740            throw new CallStateException("no connections in call");
741        }
742
743        if (call == mRingingCall) {
744            if (Phone.DEBUG_PHONE) log("(ringing) hangup waiting or background");
745            mCi.hangupWaitingOrBackground(obtainCompleteMessage());
746        } else if (call == mForegroundCall) {
747            if (call.isDialingOrAlerting()) {
748                if (Phone.DEBUG_PHONE) {
749                    log("(foregnd) hangup dialing or alerting...");
750                }
751                hangup((GsmConnection)(call.getConnections().get(0)));
752            } else {
753                hangupForegroundResumeBackground();
754            }
755        } else if (call == mBackgroundCall) {
756            if (mRingingCall.isRinging()) {
757                if (Phone.DEBUG_PHONE) {
758                    log("hangup all conns in background call");
759                }
760                hangupAllConnections(call);
761            } else {
762                hangupWaitingOrBackground();
763            }
764        } else {
765            throw new RuntimeException ("GsmCall " + call +
766                    "does not belong to GsmCallTracker " + this);
767        }
768
769        call.onHangupLocal();
770        mPhone.notifyPreciseCallStateChanged();
771    }
772
773    /* package */
774    void hangupWaitingOrBackground() {
775        if (Phone.DEBUG_PHONE) log("hangupWaitingOrBackground");
776        mCi.hangupWaitingOrBackground(obtainCompleteMessage());
777    }
778
779    /* package */
780    void hangupForegroundResumeBackground() {
781        if (Phone.DEBUG_PHONE) log("hangupForegroundResumeBackground");
782        mCi.hangupForegroundResumeBackground(obtainCompleteMessage());
783    }
784
785    void hangupConnectionByIndex(GsmCall call, int index)
786            throws CallStateException {
787        int count = call.mConnections.size();
788        for (int i = 0; i < count; i++) {
789            GsmConnection cn = (GsmConnection)call.mConnections.get(i);
790            if (cn.getGSMIndex() == index) {
791                mCi.hangupConnection(index, obtainCompleteMessage());
792                return;
793            }
794        }
795
796        throw new CallStateException("no gsm index found");
797    }
798
799    void hangupAllConnections(GsmCall call) {
800        try {
801            int count = call.mConnections.size();
802            for (int i = 0; i < count; i++) {
803                GsmConnection cn = (GsmConnection)call.mConnections.get(i);
804                mCi.hangupConnection(cn.getGSMIndex(), obtainCompleteMessage());
805            }
806        } catch (CallStateException ex) {
807            Rlog.e(LOG_TAG, "hangupConnectionByIndex caught " + ex);
808        }
809    }
810
811    /* package */
812    GsmConnection getConnectionByIndex(GsmCall call, int index)
813            throws CallStateException {
814        int count = call.mConnections.size();
815        for (int i = 0; i < count; i++) {
816            GsmConnection cn = (GsmConnection)call.mConnections.get(i);
817            if (cn.getGSMIndex() == index) {
818                return cn;
819            }
820        }
821
822        return null;
823    }
824
825    private Phone.SuppService getFailedService(int what) {
826        switch (what) {
827            case EVENT_SWITCH_RESULT:
828                return Phone.SuppService.SWITCH;
829            case EVENT_CONFERENCE_RESULT:
830                return Phone.SuppService.CONFERENCE;
831            case EVENT_SEPARATE_RESULT:
832                return Phone.SuppService.SEPARATE;
833            case EVENT_ECT_RESULT:
834                return Phone.SuppService.TRANSFER;
835        }
836        return Phone.SuppService.UNKNOWN;
837    }
838
839    //****** Overridden from Handler
840
841    @Override
842    public void
843    handleMessage (Message msg) {
844        AsyncResult ar;
845
846        switch (msg.what) {
847            case EVENT_POLL_CALLS_RESULT:
848                ar = (AsyncResult)msg.obj;
849
850                if (msg == mLastRelevantPoll) {
851                    if (DBG_POLL) log(
852                            "handle EVENT_POLL_CALL_RESULT: set needsPoll=F");
853                    mNeedsPoll = false;
854                    mLastRelevantPoll = null;
855                    handlePollCalls((AsyncResult)msg.obj);
856                }
857            break;
858
859            case EVENT_OPERATION_COMPLETE:
860                ar = (AsyncResult)msg.obj;
861                operationComplete();
862            break;
863
864            case EVENT_SWITCH_RESULT:
865            case EVENT_CONFERENCE_RESULT:
866            case EVENT_SEPARATE_RESULT:
867            case EVENT_ECT_RESULT:
868                ar = (AsyncResult)msg.obj;
869                if (ar.exception != null) {
870                    mPhone.notifySuppServiceFailed(getFailedService(msg.what));
871                }
872                operationComplete();
873            break;
874
875            case EVENT_GET_LAST_CALL_FAIL_CAUSE:
876                int causeCode;
877                ar = (AsyncResult)msg.obj;
878
879                operationComplete();
880
881                if (ar.exception != null) {
882                    // An exception occurred...just treat the disconnect
883                    // cause as "normal"
884                    causeCode = CallFailCause.NORMAL_CLEARING;
885                    Rlog.i(LOG_TAG,
886                            "Exception during getLastCallFailCause, assuming normal disconnect");
887                } else {
888                    causeCode = ((int[])ar.result)[0];
889                }
890                // Log the causeCode if its not normal
891                if (causeCode == CallFailCause.NO_CIRCUIT_AVAIL ||
892                    causeCode == CallFailCause.TEMPORARY_FAILURE ||
893                    causeCode == CallFailCause.SWITCHING_CONGESTION ||
894                    causeCode == CallFailCause.CHANNEL_NOT_AVAIL ||
895                    causeCode == CallFailCause.QOS_NOT_AVAIL ||
896                    causeCode == CallFailCause.BEARER_NOT_AVAIL ||
897                    causeCode == CallFailCause.ERROR_UNSPECIFIED) {
898                    GsmCellLocation loc = ((GsmCellLocation)mPhone.getCellLocation());
899                    EventLog.writeEvent(EventLogTags.CALL_DROP,
900                            causeCode, loc != null ? loc.getCid() : -1,
901                            TelephonyManager.getDefault().getNetworkType());
902                }
903
904                for (int i = 0, s =  mDroppedDuringPoll.size()
905                        ; i < s ; i++
906                ) {
907                    GsmConnection conn = mDroppedDuringPoll.get(i);
908
909                    conn.onRemoteDisconnect(causeCode);
910                }
911
912                updatePhoneState();
913
914                mPhone.notifyPreciseCallStateChanged();
915                mDroppedDuringPoll.clear();
916            break;
917
918            case EVENT_REPOLL_AFTER_DELAY:
919            case EVENT_CALL_STATE_CHANGE:
920                pollCallsWhenSafe();
921            break;
922
923            case EVENT_RADIO_AVAILABLE:
924                handleRadioAvailable();
925            break;
926
927            case EVENT_RADIO_NOT_AVAILABLE:
928                handleRadioNotAvailable();
929            break;
930        }
931    }
932
933    @Override
934    protected void log(String msg) {
935        Rlog.d(LOG_TAG, "[GsmCallTracker] " + msg);
936    }
937
938    @Override
939    public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
940        pw.println("GsmCallTracker extends:");
941        super.dump(fd, pw, args);
942        pw.println("mConnections: length=" + mConnections.length);
943        for(int i=0; i < mConnections.length; i++) {
944            pw.printf("  mConnections[%d]=%s\n", i, mConnections[i]);
945        }
946        pw.println(" mVoiceCallEndedRegistrants=" + mVoiceCallEndedRegistrants);
947        pw.println(" mVoiceCallStartedRegistrants=" + mVoiceCallStartedRegistrants);
948        pw.println(" mDroppedDuringPoll: size=" + mDroppedDuringPoll.size());
949        for(int i = 0; i < mDroppedDuringPoll.size(); i++) {
950            pw.printf( "  mDroppedDuringPoll[%d]=%s\n", i, mDroppedDuringPoll.get(i));
951        }
952        pw.println(" mRingingCall=" + mRingingCall);
953        pw.println(" mForegroundCall=" + mForegroundCall);
954        pw.println(" mBackgroundCall=" + mBackgroundCall);
955        pw.println(" mPendingMO=" + pendingMO);
956        pw.println(" mHangupPendingMO=" + mHangupPendingMO);
957        pw.println(" mPhone=" + mPhone);
958        pw.println(" mDesiredMute=" + mDesiredMute);
959        pw.println(" mState=" + mState);
960    }
961}
962