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