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