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