forked from darchstar/android_packages_apps_Phone
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathBluetoothHandsfree.java
executable file
·3070 lines (2747 loc) · 123 KB
/
BluetoothHandsfree.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.phone;
import android.bluetooth.AtCommandHandler;
import android.bluetooth.AtCommandResult;
import android.bluetooth.AtParser;
import android.bluetooth.BluetoothA2dp;
import android.bluetooth.BluetoothAssignedNumbers;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothHeadset;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.bluetooth.HeadsetBase;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.net.Uri;
import android.os.AsyncResult;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.os.SystemProperties;
import android.telephony.PhoneNumberUtils;
import android.telephony.ServiceState;
import android.telephony.SignalStrength;
import android.util.Log;
import com.android.internal.telephony.Call;
import com.android.internal.telephony.Connection;
import com.android.internal.telephony.Phone;
import com.android.internal.telephony.TelephonyIntents;
import com.android.internal.telephony.CallManager;
import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedList;
/**
* Bluetooth headset manager for the Phone app.
* @hide
*/
public class BluetoothHandsfree {
private static final String TAG = "Bluetooth HS/HF";
private static final boolean DBG = (PhoneApp.DBG_LEVEL >= 1)
&& (SystemProperties.getInt("ro.debuggable", 0) == 1);
private static final boolean VDBG = (PhoneApp.DBG_LEVEL >= 2); // even more logging
public static final int TYPE_UNKNOWN = 0;
public static final int TYPE_HEADSET = 1;
public static final int TYPE_HANDSFREE = 2;
/** The singleton instance. */
private static BluetoothHandsfree sInstance;
private final Context mContext;
private final BluetoothAdapter mAdapter;
private final CallManager mCM;
private BluetoothA2dp mA2dp;
private BluetoothDevice mA2dpDevice;
private int mA2dpState;
private boolean mPendingAudioState;
private int mAudioState;
private ServiceState mServiceState;
private HeadsetBase mHeadset;
private BluetoothHeadset mBluetoothHeadset;
private int mHeadsetType; // TYPE_UNKNOWN when not connected
private boolean mAudioPossible;
private BluetoothSocket mConnectedSco;
private IncomingScoAcceptThread mIncomingScoThread = null;
private ScoSocketConnectThread mConnectScoThread = null;
private SignalScoCloseThread mSignalScoCloseThread = null;
private AudioManager mAudioManager;
private PowerManager mPowerManager;
private boolean mPendingSco; // waiting for a2dp sink to suspend before establishing SCO
private boolean mA2dpSuspended;
private boolean mUserWantsAudio;
private WakeLock mStartCallWakeLock; // held while waiting for the intent to start call
private WakeLock mStartVoiceRecognitionWakeLock; // held while waiting for voice recognition
// AT command state
private static final int GSM_MAX_CONNECTIONS = 6; // Max connections allowed by GSM
private static final int CDMA_MAX_CONNECTIONS = 2; // Max connections allowed by CDMA
private long mBgndEarliestConnectionTime = 0;
private boolean mClip = false; // Calling Line Information Presentation
private boolean mIndicatorsEnabled = false;
private boolean mCmee = false; // Extended Error reporting
private long[] mClccTimestamps; // Timestamps associated with each clcc index
private boolean[] mClccUsed; // Is this clcc index in use
private boolean mWaitingForCallStart;
private boolean mWaitingForVoiceRecognition;
// do not connect audio until service connection is established
// for 3-way supported devices, this is after AT+CHLD
// for non-3-way supported devices, this is after AT+CMER (see spec)
private boolean mServiceConnectionEstablished;
private final BluetoothPhoneState mBluetoothPhoneState; // for CIND and CIEV updates
private final BluetoothAtPhonebook mPhonebook;
private Phone.State mPhoneState = Phone.State.IDLE;
CdmaPhoneCallState.PhoneCallState mCdmaThreeWayCallState =
CdmaPhoneCallState.PhoneCallState.IDLE;
private DebugThread mDebugThread;
private int mScoGain = Integer.MIN_VALUE;
private static Intent sVoiceCommandIntent;
// Audio parameters
private static final String HEADSET_NREC = "bt_headset_nrec";
private static final String HEADSET_NAME = "bt_headset_name";
private int mRemoteBrsf = 0;
private int mLocalBrsf = 0;
// CDMA specific flag used in context with BT devices having display capabilities
// to show which Caller is active. This state might not be always true as in CDMA
// networks if a caller drops off no update is provided to the Phone.
// This flag is just used as a toggle to provide a update to the BT device to specify
// which caller is active.
private boolean mCdmaIsSecondCallActive = false;
private boolean mCdmaCallsSwapped = false;
/* Constants from Bluetooth Specification Hands-Free profile version 1.5 */
private static final int BRSF_AG_THREE_WAY_CALLING = 1 << 0;
private static final int BRSF_AG_EC_NR = 1 << 1;
private static final int BRSF_AG_VOICE_RECOG = 1 << 2;
private static final int BRSF_AG_IN_BAND_RING = 1 << 3;
private static final int BRSF_AG_VOICE_TAG_NUMBE = 1 << 4;
private static final int BRSF_AG_REJECT_CALL = 1 << 5;
private static final int BRSF_AG_ENHANCED_CALL_STATUS = 1 << 6;
private static final int BRSF_AG_ENHANCED_CALL_CONTROL = 1 << 7;
private static final int BRSF_AG_ENHANCED_ERR_RESULT_CODES = 1 << 8;
private static final int BRSF_HF_EC_NR = 1 << 0;
private static final int BRSF_HF_CW_THREE_WAY_CALLING = 1 << 1;
private static final int BRSF_HF_CLIP = 1 << 2;
private static final int BRSF_HF_VOICE_REG_ACT = 1 << 3;
private static final int BRSF_HF_REMOTE_VOL_CONTROL = 1 << 4;
private static final int BRSF_HF_ENHANCED_CALL_STATUS = 1 << 5;
private static final int BRSF_HF_ENHANCED_CALL_CONTROL = 1 << 6;
// VirtualCall - true if Virtual Call is active, false otherwise
private boolean mVirtualCallStarted = false;
// Voice Recognition - true if Voice Recognition is active, false otherwise
private boolean mVoiceRecognitionStarted;
private HandsfreeMessageHandler mHandler;
public static String typeToString(int type) {
switch (type) {
case TYPE_UNKNOWN:
return "unknown";
case TYPE_HEADSET:
return "headset";
case TYPE_HANDSFREE:
return "handsfree";
}
return null;
}
/**
* Initialize the singleton BluetoothHandsfree instance.
* This is only done once, at startup, from PhoneApp.onCreate().
*/
/* package */ static BluetoothHandsfree init(Context context, CallManager cm) {
synchronized (BluetoothHandsfree.class) {
if (sInstance == null) {
sInstance = new BluetoothHandsfree(context, cm);
} else {
Log.wtf(TAG, "init() called multiple times! sInstance = " + sInstance);
}
return sInstance;
}
}
/** Private constructor; @see init() */
private BluetoothHandsfree(Context context, CallManager cm) {
mCM = cm;
mContext = context;
mAdapter = BluetoothAdapter.getDefaultAdapter();
boolean bluetoothCapable = (mAdapter != null);
mHeadset = null;
mHeadsetType = TYPE_UNKNOWN; // nothing connected yet
if (bluetoothCapable) {
mAdapter.getProfileProxy(mContext, mProfileListener,
BluetoothProfile.A2DP);
}
mA2dpState = BluetoothA2dp.STATE_DISCONNECTED;
mA2dpDevice = null;
mA2dpSuspended = false;
mPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
mStartCallWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
TAG + ":StartCall");
mStartCallWakeLock.setReferenceCounted(false);
mStartVoiceRecognitionWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
TAG + ":VoiceRecognition");
mStartVoiceRecognitionWakeLock.setReferenceCounted(false);
mLocalBrsf = BRSF_AG_THREE_WAY_CALLING |
BRSF_AG_EC_NR |
BRSF_AG_REJECT_CALL |
BRSF_AG_ENHANCED_CALL_STATUS;
if (sVoiceCommandIntent == null) {
sVoiceCommandIntent = new Intent(Intent.ACTION_VOICE_COMMAND);
sVoiceCommandIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
if (mContext.getPackageManager().resolveActivity(sVoiceCommandIntent, 0) != null &&
BluetoothHeadset.isBluetoothVoiceDialingEnabled(mContext)) {
mLocalBrsf |= BRSF_AG_VOICE_RECOG;
}
HandlerThread thread = new HandlerThread("BluetoothHandsfreeHandler");
thread.start();
Looper looper = thread.getLooper();
mHandler = new HandsfreeMessageHandler(looper);
mBluetoothPhoneState = new BluetoothPhoneState();
mUserWantsAudio = true;
mVirtualCallStarted = false;
mVoiceRecognitionStarted = false;
mPhonebook = new BluetoothAtPhonebook(mContext, this);
mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
cdmaSetSecondCallState(false);
if (bluetoothCapable) {
resetAtState();
}
}
/**
* A thread that runs in the background waiting for a Sco Server Socket to
* accept a connection. Even after a connection has been accepted, the Sco Server
* continues to listen for new connections.
*/
private class IncomingScoAcceptThread extends Thread{
private final BluetoothServerSocket mIncomingServerSocket;
private BluetoothSocket mIncomingSco;
private boolean stopped = false;
public IncomingScoAcceptThread() {
BluetoothServerSocket serverSocket = null;
try {
serverSocket = BluetoothAdapter.listenUsingScoOn();
} catch (IOException e) {
Log.e(TAG, "Could not create BluetoothServerSocket");
stopped = true;
}
mIncomingServerSocket = serverSocket;
}
@Override
public void run() {
while (!stopped) {
try {
mIncomingSco = mIncomingServerSocket.accept();
} catch (IOException e) {
Log.e(TAG, "BluetoothServerSocket could not accept connection");
}
if (mIncomingSco != null) {
connectSco();
}
}
}
private void connectSco() {
synchronized (BluetoothHandsfree.this) {
if (!Thread.interrupted() && isHeadsetConnected() &&
(mAudioPossible || allowAudioAnytime()) &&
mConnectedSco == null) {
Log.i(TAG, "Routing audio for incoming SCO connection");
mConnectedSco = mIncomingSco;
mAudioManager.setBluetoothScoOn(true);
setAudioState(BluetoothHeadset.STATE_AUDIO_CONNECTED,
mHeadset.getRemoteDevice());
if (mSignalScoCloseThread == null) {
mSignalScoCloseThread = new SignalScoCloseThread();
mSignalScoCloseThread.setName("SignalScoCloseThread");
mSignalScoCloseThread.start();
}
} else {
Log.i(TAG, "Rejecting incoming SCO connection");
try {
mIncomingSco.close();
}catch (IOException e) {
Log.e(TAG, "Error when closing incoming Sco socket");
}
mIncomingSco = null;
}
}
}
// must be called with BluetoothHandsfree locked
void shutdown() {
try {
mIncomingServerSocket.close();
} catch (IOException e) {
Log.w(TAG, "Error when closing server socket");
}
stopped = true;
interrupt();
}
}
/**
* A thread that runs in the background waiting for a Sco Socket to
* connect.Once the socket is connected, this thread shall be
* shutdown.
*/
private class ScoSocketConnectThread extends Thread{
private BluetoothSocket mOutgoingSco;
public ScoSocketConnectThread(BluetoothDevice device) {
try {
mOutgoingSco = device.createScoSocket();
} catch (IOException e) {
Log.w(TAG, "Could not create BluetoothSocket");
failedScoConnect();
}
}
@Override
public void run() {
try {
mOutgoingSco.connect();
}catch (IOException connectException) {
Log.e(TAG, "BluetoothSocket could not connect");
mOutgoingSco = null;
failedScoConnect();
}
if (mOutgoingSco != null) {
connectSco();
}
}
private void connectSco() {
synchronized (BluetoothHandsfree.this) {
if (!Thread.interrupted() && isHeadsetConnected() && mConnectedSco == null) {
if (VDBG) log("Routing audio for outgoing SCO conection");
mConnectedSco = mOutgoingSco;
mAudioManager.setBluetoothScoOn(true);
setAudioState(BluetoothHeadset.STATE_AUDIO_CONNECTED,
mHeadset.getRemoteDevice());
if (mSignalScoCloseThread == null) {
mSignalScoCloseThread = new SignalScoCloseThread();
mSignalScoCloseThread.setName("SignalScoCloseThread");
mSignalScoCloseThread.start();
}
} else {
if (VDBG) log("Rejecting new connected outgoing SCO socket");
try {
mOutgoingSco.close();
}catch (IOException e) {
Log.e(TAG, "Error when closing Sco socket");
}
mOutgoingSco = null;
failedScoConnect();
}
}
}
private void failedScoConnect() {
// Wait for couple of secs before sending AUDIO_STATE_DISCONNECTED,
// since an incoming SCO connection can happen immediately with
// certain headsets.
Message msg = Message.obtain(mHandler, SCO_AUDIO_STATE);
msg.obj = mHeadset.getRemoteDevice();
mHandler.sendMessageDelayed(msg, 2000);
// Sync with interrupt() statement of shutdown method
// This prevents resetting of a valid mConnectScoThread.
// If this thread has been interrupted, it has been shutdown and
// mConnectScoThread is/will be reset by the outer class.
// We do not want to do it here since mConnectScoThread could be
// assigned with a new object.
synchronized (ScoSocketConnectThread.this) {
if (!isInterrupted()) {
resetConnectScoThread();
}
}
}
// must be called with BluetoothHandsfree locked
void shutdown() {
closeConnectedSco();
// sync with isInterrupted() check in failedScoConnect method
// see explanation there
synchronized (ScoSocketConnectThread.this) {
interrupt();
}
}
}
/*
* Signals when a Sco connection has been closed
*/
private class SignalScoCloseThread extends Thread{
private boolean stopped = false;
@Override
public void run() {
while (!stopped) {
BluetoothSocket connectedSco = null;
synchronized (BluetoothHandsfree.this) {
connectedSco = mConnectedSco;
}
if (connectedSco != null) {
byte b[] = new byte[1];
InputStream inStream = null;
try {
inStream = connectedSco.getInputStream();
} catch (IOException e) {}
if (inStream != null) {
try {
// inStream.read is a blocking call that won't ever
// return anything, but will throw an exception if the
// connection is closed
int ret = inStream.read(b, 0, 1);
}catch (IOException connectException) {
// call a message to close this thread and turn off audio
// we can't call audioOff directly because then
// the thread would try to close itself
Message msg = Message.obtain(mHandler, SCO_CLOSED);
mHandler.sendMessage(msg);
break;
}
}
}
}
}
// must be called with BluetoothHandsfree locked
void shutdown() {
stopped = true;
closeConnectedSco();
interrupt();
}
}
private void connectScoThread(){
// Sync with setting mConnectScoThread to null to assure the validity of
// the condition
synchronized (ScoSocketConnectThread.class) {
if (mConnectScoThread == null) {
BluetoothDevice device = mHeadset.getRemoteDevice();
if (getAudioState(device) == BluetoothHeadset.STATE_AUDIO_DISCONNECTED) {
setAudioState(BluetoothHeadset.STATE_AUDIO_CONNECTING, device);
}
mConnectScoThread = new ScoSocketConnectThread(mHeadset.getRemoteDevice());
mConnectScoThread.setName("HandsfreeScoSocketConnectThread");
mConnectScoThread.start();
}
}
}
private void resetConnectScoThread() {
// Sync with if (mConnectScoThread == null) check
synchronized (ScoSocketConnectThread.class) {
mConnectScoThread = null;
}
}
// must be called with BluetoothHandsfree locked
private void closeConnectedSco() {
if (mConnectedSco != null) {
try {
mConnectedSco.close();
} catch (IOException e) {
Log.e(TAG, "Error when closing Sco socket");
}
BluetoothDevice device = null;
if (mHeadset != null) {
device = mHeadset.getRemoteDevice();
}
mAudioManager.setBluetoothScoOn(false);
setAudioState(BluetoothHeadset.STATE_AUDIO_DISCONNECTED, device);
mConnectedSco = null;
}
}
/* package */ synchronized void onBluetoothEnabled() {
/* Bluez has a bug where it will always accept and then orphan
* incoming SCO connections, regardless of whether we have a listening
* SCO socket. So the best thing to do is always run a listening socket
* while bluetooth is on so that at least we can disconnect it
* immediately when we don't want it.
*/
if (mIncomingScoThread == null) {
mIncomingScoThread = new IncomingScoAcceptThread();
mIncomingScoThread.setName("incomingScoAcceptThread");
mIncomingScoThread.start();
}
}
/* package */ synchronized void onBluetoothDisabled() {
// Close off the SCO sockets
audioOff();
if (mIncomingScoThread != null) {
mIncomingScoThread.shutdown();
mIncomingScoThread = null;
}
}
private boolean isHeadsetConnected() {
if (mHeadset == null || mHeadsetType == TYPE_UNKNOWN) {
return false;
}
return mHeadset.isConnected();
}
/* package */ synchronized void connectHeadset(HeadsetBase headset, int headsetType) {
mHeadset = headset;
mHeadsetType = headsetType;
if (mHeadsetType == TYPE_HEADSET) {
initializeHeadsetAtParser();
} else {
initializeHandsfreeAtParser();
}
// Headset vendor-specific commands
registerAllVendorSpecificCommands();
headset.startEventThread();
configAudioParameters();
if (inDebug()) {
startDebug();
}
if (isIncallAudio()) {
audioOn();
} else if ( mCM.getFirstActiveRingingCall().isRinging()) {
// need to update HS with RING when single ringing call exist
mBluetoothPhoneState.ring();
}
}
/* returns true if there is some kind of in-call audio we may wish to route
* bluetooth to */
private boolean isIncallAudio() {
Call.State state = mCM.getActiveFgCallState();
return (state == Call.State.ACTIVE || state == Call.State.ALERTING);
}
/* package */ synchronized void disconnectHeadset() {
audioOff();
// No need to check if isVirtualCallInProgress()
// terminateScoUsingVirtualVoiceCall() does the check
terminateScoUsingVirtualVoiceCall();
mHeadsetType = TYPE_UNKNOWN;
stopDebug();
resetAtState();
}
/* package */ synchronized void resetAtState() {
mClip = false;
mIndicatorsEnabled = false;
mServiceConnectionEstablished = false;
mCmee = false;
mClccTimestamps = new long[GSM_MAX_CONNECTIONS];
mClccUsed = new boolean[GSM_MAX_CONNECTIONS];
for (int i = 0; i < GSM_MAX_CONNECTIONS; i++) {
mClccUsed[i] = false;
}
mRemoteBrsf = 0;
mPhonebook.resetAtState();
}
/* package */ HeadsetBase getHeadset() {
return mHeadset;
}
private void configAudioParameters() {
String name = mHeadset.getRemoteDevice().getName();
if (name == null) {
name = "<unknown>";
}
mAudioManager.setParameters(HEADSET_NAME+"="+name+";"+HEADSET_NREC+"=on");
}
/** Represents the data that we send in a +CIND or +CIEV command to the HF
*/
private class BluetoothPhoneState {
// 0: no service
// 1: service
private int mService;
// 0: no active call
// 1: active call (where active means audio is routed - not held call)
private int mCall;
// 0: not in call setup
// 1: incoming call setup
// 2: outgoing call setup
// 3: remote party being alerted in an outgoing call setup
private int mCallsetup;
// 0: no calls held
// 1: held call and active call
// 2: held call only
private int mCallheld;
// cellular signal strength of AG: 0-5
private int mSignal;
// cellular signal strength in CSQ rssi scale
private int mRssi; // for CSQ
// 0: roaming not active (home)
// 1: roaming active
private int mRoam;
// battery charge of AG: 0-5
private int mBattchg;
// 0: not registered
// 1: registered, home network
// 5: registered, roaming
private int mStat; // for CREG
private String mRingingNumber; // Context for in-progress RING's
private int mRingingType;
private boolean mIgnoreRing = false;
private boolean mStopRing = false;
// current or last call start timestamp
private long mCallStartTime = 0;
// time window to reconnect remotely-disconnected SCO
// in mili-seconds
private static final int RETRY_SCO_TIME_WINDOW = 1000;
private static final int SERVICE_STATE_CHANGED = 1;
private static final int PRECISE_CALL_STATE_CHANGED = 2;
private static final int RING = 3;
private static final int PHONE_CDMA_CALL_WAITING = 4;
private Handler mStateChangeHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch(msg.what) {
case RING:
AtCommandResult result = ring();
if (result != null) {
sendURC(result.toString());
}
break;
case SERVICE_STATE_CHANGED:
ServiceState state = (ServiceState) ((AsyncResult) msg.obj).result;
updateServiceState(sendUpdate(), state);
break;
case PRECISE_CALL_STATE_CHANGED:
case PHONE_CDMA_CALL_WAITING:
Connection connection = null;
if (((AsyncResult) msg.obj).result instanceof Connection) {
connection = (Connection) ((AsyncResult) msg.obj).result;
}
handlePreciseCallStateChange(sendUpdate(), connection);
break;
}
}
};
private BluetoothPhoneState() {
// init members
// TODO May consider to repalce the default phone's state and signal
// by CallManagter's state and signal
updateServiceState(false, mCM.getDefaultPhone().getServiceState());
handlePreciseCallStateChange(false, null);
mBattchg = 5; // There is currently no API to get battery level
// on demand, so set to 5 and wait for an update
mSignal = asuToSignal(mCM.getDefaultPhone().getSignalStrength());
// register for updates
// Use the service state of default phone as BT service state to
// avoid situation such as no cell or wifi connection but still
// reporting in service (since SipPhone always reports in service).
mCM.getDefaultPhone().registerForServiceStateChanged(mStateChangeHandler,
SERVICE_STATE_CHANGED, null);
mCM.registerForPreciseCallStateChanged(mStateChangeHandler,
PRECISE_CALL_STATE_CHANGED, null);
mCM.registerForCallWaiting(mStateChangeHandler,
PHONE_CDMA_CALL_WAITING, null);
IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
filter.addAction(TelephonyIntents.ACTION_SIGNAL_STRENGTH_CHANGED);
filter.addAction(BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED);
filter.addAction(BluetoothDevice.ACTION_CONNECTION_ACCESS_REPLY);
mContext.registerReceiver(mStateReceiver, filter);
}
private void updateBtPhoneStateAfterRadioTechnologyChange() {
if(VDBG) Log.d(TAG, "updateBtPhoneStateAfterRadioTechnologyChange...");
//Unregister all events from the old obsolete phone
mCM.getDefaultPhone().unregisterForServiceStateChanged(mStateChangeHandler);
mCM.unregisterForPreciseCallStateChanged(mStateChangeHandler);
mCM.unregisterForCallWaiting(mStateChangeHandler);
//Register all events new to the new active phone
mCM.getDefaultPhone().registerForServiceStateChanged(mStateChangeHandler,
SERVICE_STATE_CHANGED, null);
mCM.registerForPreciseCallStateChanged(mStateChangeHandler,
PRECISE_CALL_STATE_CHANGED, null);
mCM.registerForCallWaiting(mStateChangeHandler,
PHONE_CDMA_CALL_WAITING, null);
}
private boolean sendUpdate() {
return isHeadsetConnected() && mHeadsetType == TYPE_HANDSFREE && mIndicatorsEnabled
&& mServiceConnectionEstablished;
}
private boolean sendClipUpdate() {
return isHeadsetConnected() && mHeadsetType == TYPE_HANDSFREE && mClip &&
mServiceConnectionEstablished;
}
private boolean sendRingUpdate() {
if (isHeadsetConnected() && !mIgnoreRing && !mStopRing &&
mCM.getFirstActiveRingingCall().isRinging()) {
if (mHeadsetType == TYPE_HANDSFREE) {
return mServiceConnectionEstablished ? true : false;
}
return true;
}
return false;
}
private void stopRing() {
mStopRing = true;
}
/* convert [0,31] ASU signal strength to the [0,5] expected by
* bluetooth devices. Scale is similar to status bar policy
*/
private int gsmAsuToSignal(SignalStrength signalStrength) {
int asu = signalStrength.getGsmSignalStrength();
if (asu >= 16) return 5;
else if (asu >= 8) return 4;
else if (asu >= 4) return 3;
else if (asu >= 2) return 2;
else if (asu >= 1) return 1;
else return 0;
}
/**
* Convert the cdma / evdo db levels to appropriate icon level.
* The scale is similar to the one used in status bar policy.
*
* @param signalStrength
* @return the icon level
*/
private int cdmaDbmEcioToSignal(SignalStrength signalStrength) {
int levelDbm = 0;
int levelEcio = 0;
int cdmaIconLevel = 0;
int evdoIconLevel = 0;
int cdmaDbm = signalStrength.getCdmaDbm();
int cdmaEcio = signalStrength.getCdmaEcio();
if (cdmaDbm >= -75) levelDbm = 4;
else if (cdmaDbm >= -85) levelDbm = 3;
else if (cdmaDbm >= -95) levelDbm = 2;
else if (cdmaDbm >= -100) levelDbm = 1;
else levelDbm = 0;
// Ec/Io are in dB*10
if (cdmaEcio >= -90) levelEcio = 4;
else if (cdmaEcio >= -110) levelEcio = 3;
else if (cdmaEcio >= -130) levelEcio = 2;
else if (cdmaEcio >= -150) levelEcio = 1;
else levelEcio = 0;
cdmaIconLevel = (levelDbm < levelEcio) ? levelDbm : levelEcio;
if (mServiceState != null &&
(mServiceState.getRadioTechnology() == ServiceState.RADIO_TECHNOLOGY_EVDO_0 ||
mServiceState.getRadioTechnology() == ServiceState.RADIO_TECHNOLOGY_EVDO_A)) {
int evdoEcio = signalStrength.getEvdoEcio();
int evdoSnr = signalStrength.getEvdoSnr();
int levelEvdoEcio = 0;
int levelEvdoSnr = 0;
// Ec/Io are in dB*10
if (evdoEcio >= -650) levelEvdoEcio = 4;
else if (evdoEcio >= -750) levelEvdoEcio = 3;
else if (evdoEcio >= -900) levelEvdoEcio = 2;
else if (evdoEcio >= -1050) levelEvdoEcio = 1;
else levelEvdoEcio = 0;
if (evdoSnr > 7) levelEvdoSnr = 4;
else if (evdoSnr > 5) levelEvdoSnr = 3;
else if (evdoSnr > 3) levelEvdoSnr = 2;
else if (evdoSnr > 1) levelEvdoSnr = 1;
else levelEvdoSnr = 0;
evdoIconLevel = (levelEvdoEcio < levelEvdoSnr) ? levelEvdoEcio : levelEvdoSnr;
}
// TODO(): There is a bug open regarding what should be sent.
return (cdmaIconLevel > evdoIconLevel) ? cdmaIconLevel : evdoIconLevel;
}
private int asuToSignal(SignalStrength signalStrength) {
if (signalStrength.isGsm()) {
return gsmAsuToSignal(signalStrength);
} else {
return cdmaDbmEcioToSignal(signalStrength);
}
}
/* convert [0,5] signal strength to a rssi signal strength for CSQ
* which is [0,31]. Despite the same scale, this is not the same value
* as ASU.
*/
private int signalToRssi(int signal) {
// using C4A suggested values
switch (signal) {
case 0: return 0;
case 1: return 4;
case 2: return 8;
case 3: return 13;
case 4: return 19;
case 5: return 31;
}
return 0;
}
private final BroadcastReceiver mStateReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_BATTERY_CHANGED)) {
Message msg = mHandler.obtainMessage(BATTERY_CHANGED, intent);
mHandler.sendMessage(msg);
} else if (intent.getAction().equals(
TelephonyIntents.ACTION_SIGNAL_STRENGTH_CHANGED)) {
Message msg = mHandler.obtainMessage(SIGNAL_STRENGTH_CHANGED,
intent);
mHandler.sendMessage(msg);
} else if (intent.getAction().equals(
BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED)) {
int state = intent.getIntExtra(BluetoothProfile.EXTRA_STATE,
BluetoothProfile.STATE_DISCONNECTED);
int oldState = intent.getIntExtra(BluetoothProfile.EXTRA_PREVIOUS_STATE,
BluetoothProfile.STATE_DISCONNECTED);
BluetoothDevice device =
intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// We are only concerned about Connected sinks to suspend and resume
// them. We can safely ignore SINK_STATE_CHANGE for other devices.
if (device == null || (mA2dpDevice != null && !device.equals(mA2dpDevice))) {
return;
}
synchronized (BluetoothHandsfree.this) {
mA2dpState = state;
if (state == BluetoothProfile.STATE_DISCONNECTED) {
mA2dpDevice = null;
} else {
mA2dpDevice = device;
}
if (oldState == BluetoothA2dp.STATE_PLAYING &&
mA2dpState == BluetoothProfile.STATE_CONNECTED) {
if (mA2dpSuspended) {
if (mPendingSco) {
mHandler.removeMessages(MESSAGE_CHECK_PENDING_SCO);
if (DBG) log("A2DP suspended, completing SCO");
connectScoThread();
mPendingSco = false;
}
}
}
}
} else if (intent.getAction().
equals(BluetoothDevice.ACTION_CONNECTION_ACCESS_REPLY)) {
mPhonebook.handleAccessPermissionResult(intent);
}
}
};
private synchronized void updateBatteryState(Intent intent) {
int batteryLevel = intent.getIntExtra("level", -1);
int scale = intent.getIntExtra("scale", -1);
if (batteryLevel == -1 || scale == -1) {
return; // ignore
}
batteryLevel = batteryLevel * 5 / scale;
if (mBattchg != batteryLevel) {
mBattchg = batteryLevel;
if (sendUpdate()) {
sendURC("+CIEV: 7," + mBattchg);
}
}
}
private synchronized void updateSignalState(Intent intent) {
// NOTE this function is called by the BroadcastReceiver mStateReceiver after intent
// ACTION_SIGNAL_STRENGTH_CHANGED and by the DebugThread mDebugThread
if (!isHeadsetConnected()) {
return;
}
SignalStrength signalStrength = SignalStrength.newFromBundle(intent.getExtras());
int signal;
if (signalStrength != null) {
signal = asuToSignal(signalStrength);
mRssi = signalToRssi(signal); // no unsolicited CSQ
if (signal != mSignal) {
mSignal = signal;
if (sendUpdate()) {
sendURC("+CIEV: 5," + mSignal);
}
}
} else {
Log.e(TAG, "Signal Strength null");
}
}
private synchronized void updateServiceState(boolean sendUpdate, ServiceState state) {
int service = state.getState() == ServiceState.STATE_IN_SERVICE ? 1 : 0;
int roam = state.getRoaming() ? 1 : 0;
int stat;
AtCommandResult result = new AtCommandResult(AtCommandResult.UNSOLICITED);
mServiceState = state;
if (service == 0) {
stat = 0;
} else {
stat = (roam == 1) ? 5 : 1;
}
if (service != mService) {
mService = service;
if (sendUpdate) {
result.addResponse("+CIEV: 1," + mService);
}
}
if (roam != mRoam) {
mRoam = roam;
if (sendUpdate) {
result.addResponse("+CIEV: 6," + mRoam);
}
}
if (stat != mStat) {
mStat = stat;
if (sendUpdate) {
result.addResponse(toCregString());
}