summaryrefslogtreecommitdiffstats
path: root/src/com/android/bluetooth/sap/SapServer.java
blob: 4a1998feb1c54957b174e2d7c2d0be8448be573e (plain)
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
package com.android.bluetooth.sap;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.concurrent.CountDownLatch;

import com.android.bluetooth.R;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SyncResult;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.os.Parcel;
import android.os.SystemClock;
import android.telephony.TelephonyManager;
import android.util.Log;
//import com.android.internal.telephony.RIL;
import com.google.protobuf.micro.CodedOutputStreamMicro;


/**
 * The SapServer uses two threads, one for reading messages from the RFCOMM socket and
 * one for writing the responses.
 * Incoming requests are decoded in the "main" SapServer, by the decoder build into SapMEssage.
 * The relevant RIL calls are made from the message handler thread through the rild-bt socket.
 * The RIL replies are read in the SapRilReceiver, and passed to the SapServer message handler
 * to be written to the RFCOMM socket.
 * All writes to the RFCOMM and rild-bt socket must be synchronized, hence to write e.g. an error
 * response, send a message to the Sap Handler thread. (There are helper functions to do this)
 * Communication to the RIL is through an intent, and a BroadcastReceiver.
 */
public class SapServer extends Thread implements Callback {
    private static final String TAG = "SapServer";
    private static final String TAG_HANDLER = "SapServerHandler";
    public static final boolean DEBUG = SapService.DEBUG;
    public static final boolean VERBOSE = SapService.VERBOSE;
    public static final boolean PTS_TEST = SapService.PTS_TEST;

    private enum SAP_STATE    {
        DISCONNECTED, CONNECTING, CONNECTING_CALL_ONGOING, CONNECTED,
        CONNECTED_BUSY, DISCONNECTING;
    }

    private SAP_STATE mState = SAP_STATE.DISCONNECTED;

    private Context mContext = null;
    /* RFCOMM socket I/O streams */
    private BufferedOutputStream mRfcommOut = null;
    private BufferedInputStream mRfcommIn = null;
    /* The RIL output stream - the input stream is owned by the SapRilReceiver object */
    private CodedOutputStreamMicro mRilBtOutStream = null;
    /* References to the SapRilReceiver object */
    private SapRilReceiver mRilBtReceiver = null;
    private Thread mRilBtReceiverThread = null;
    /* The message handler members */
    private Handler mSapHandler = null;
    private HandlerThread mHandlerThread = null;
    /* Reference to the SAP service - which created this instance of the SAP server */
    private Handler mSapServiceHandler = null;

    /* flag for when user forces disconnect of rfcomm */
    private boolean mIsLocalInitDisconnect = false;
    private CountDownLatch mDeinitSignal = new CountDownLatch(1);

    /* Message ID's handled by the message handler */
    public static final int SAP_MSG_RFC_REPLY =   0x00;
    public static final int SAP_MSG_RIL_CONNECT = 0x01;
    public static final int SAP_MSG_RIL_REQ =     0x02;
    public static final int SAP_MSG_RIL_IND =     0x04;

    public static final String SAP_DISCONNECT_ACTION = "com.android.bluetooth.sap.action.DISCONNECT_ACTION";
    public static final String SAP_DISCONNECT_TYPE_EXTRA = "com.android.bluetooth.sap.extra.DISCONNECT_TYPE";
    public static final int NOTIFICATION_ID = android.R.drawable.stat_sys_data_bluetooth;
    private static final int DISCONNECT_TIMEOUT_IMMEDIATE = 5000; /* ms */
    private static final int DISCONNECT_TIMEOUT_RFCOMM = 2000; /* ms */
    private PendingIntent pDiscIntent = null; // Holds a reference to disconnect timeout intents
    /* These are just used to evaluate the maxMessageSize which we are able to handle in the SAP profile.
     * The RIL may set other limits, but this will be handled by the SAP connect request send ti the RIL */
// TODO: REMOVE    private static final int MAX_MAX_MESSAGE_SIZE = SapRilReceiver.RIL_MAX_COMMAND_BYTES;
    /* We store the mMaxMessageSize, as we need a copy of it when the init. sequence completes */
    private int mMaxMsgSize = 0;
    /* keep track of the current RIL test mode */
    private int mTestMode = SapMessage.INVALID_VALUE; // used to set the RIL in test mode


    /**
     * SapServer constructor
     * @param serviceHandler The handler to send a SapService.MSG_SERVERSESSION_CLOSE when closing
     * @param inStream The socket input stream
     * @param outStream The socket output stream
     */
    public SapServer(Handler serviceHandler, Context context, InputStream inStream, OutputStream outStream) {
        mContext = context;
        mSapServiceHandler = serviceHandler;

        /* Open in- and output streams */
        mRfcommIn = new BufferedInputStream(inStream);
        mRfcommOut = new BufferedOutputStream(outStream);

        /* Register for phone state change and the RIL cfm message */
        IntentFilter filter = new IntentFilter();
        filter.addAction(TelephonyManager.ACTION_PHONE_STATE_CHANGED);
        filter.addAction(SAP_DISCONNECT_ACTION);
        mContext.registerReceiver(mIntentReceiver, filter);
    }

    /**
     * This handles the response from RIL.
     */
    BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent.getAction().equals(TelephonyManager.ACTION_PHONE_STATE_CHANGED)) {
                if(VERBOSE) Log.i(TAG, "ACTION_PHONE_STATE_CHANGED intent received in state "
                                        + mState.name()
                                        + "PhoneState: "
                                        + intent.getStringExtra(TelephonyManager.EXTRA_STATE));
                if(mState == SAP_STATE.CONNECTING_CALL_ONGOING) {
                    String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
                    if(state != null) {
                        if(state.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
                            if(DEBUG) Log.i(TAG, "sending RIL.ACTION_RIL_RECONNECT_OFF_REQ intent");
                            // TODO: Send connect request to RIL
                            SapMessage fakeConReq = new SapMessage(SapMessage.ID_CONNECT_REQ);
                            fakeConReq.setMaxMsgSize(mMaxMsgSize);
                            onConnectRequest(fakeConReq);
                        }
                    }
                }
            } else if (intent.getAction().equals(SAP_DISCONNECT_ACTION)
                    && mState != SAP_STATE.DISCONNECTED
                    && mState != SAP_STATE.DISCONNECTING ) {

                int disconnectType = intent.getIntExtra(SapServer.SAP_DISCONNECT_TYPE_EXTRA,SapMessage.DISC_GRACEFULL);
                Log.v(TAG, " - Received SAP_DISCONNECT_ACTION type: " + disconnectType);
                sendDisconnectInd(disconnectType);

            } else {
                Log.w(TAG, "RIL-BT received unexpected Intent: " + intent.getAction());
            }
        }
    };

    /**
     * Set RIL driver in test mode - only possible if SapMessage is build with TEST == true
     * The value set by this function will take effect at the next connect request received
     * in DISCONNECTED state.
     * @param testMode Use SapMessage.TEST_MODE_XXX
     */
    public void setTestMode(int testMode) {
        if(SapMessage.TEST) {
            mTestMode = testMode;
        }
    }

    private void sendDisconnectInd(int discType) {
        if(VERBOSE) Log.v(TAG, "in sendDisconnectInd()");

        if(discType != SapMessage.DISC_FORCED){
            if(VERBOSE) Log.d(TAG, "Sending  disconnect ("+discType+") indication to client");
            /* Send disconnect to client */
            SapMessage discInd = new SapMessage(SapMessage.ID_DISCONNECT_IND);
            discInd.setDisconnectionType(discType);
            sendClientMessage(discInd);

            /* Handle local disconnect procedures */
            if (discType == SapMessage.DISC_GRACEFULL)
            {
                /* Update the notification to allow the user to initiate a force disconnect */
                setNotification(SapMessage.DISC_IMMEDIATE, PendingIntent.FLAG_CANCEL_CURRENT);

            } else if (discType == SapMessage.DISC_IMMEDIATE){
                /* Request an immediate disconnect, but start a timer to force disconnect if the client
                 * do not obey our request. */
                startDisconnectTimer(SapMessage.DISC_FORCED, DISCONNECT_TIMEOUT_IMMEDIATE);
            }

        } else {
            SapMessage msg = new SapMessage(SapMessage.ID_DISCONNECT_REQ);
            /* Force disconnect of RFCOMM - but first we need to clean up. */
            clearPendingRilResponses(msg);

            // We simply need to forward to RIL, but not change state to busy - hence send and set message to null.
            changeState(SAP_STATE.DISCONNECTING);
            sendRilThreadMessage(msg);
            mIsLocalInitDisconnect = true;
        }
    }


    void setNotification(int type, int flags)
    {
        String title, text, button, ticker;
        Notification notification;
        if(VERBOSE) Log.i(TAG, "setNotification type: " + type);
        /* put notification up for the user to be able to disconnect from the client*/
        Intent sapDisconnectIntent = new Intent(SapServer.SAP_DISCONNECT_ACTION);
        if(type == SapMessage.DISC_GRACEFULL){
            title = mContext.getString(R.string.bluetooth_sap_notif_title);
            button = mContext.getString(R.string.bluetooth_sap_notif_disconnect_button);
            text = mContext.getString(R.string.bluetooth_sap_notif_message);
            ticker = mContext.getString(R.string.bluetooth_sap_notif_ticker);
        }else{
            title = mContext.getString(R.string.bluetooth_sap_notif_title);
            button = mContext.getString(R.string.bluetooth_sap_notif_force_disconnect_button);
            text = mContext.getString(R.string.bluetooth_sap_notif_disconnecting);
            ticker = mContext.getString(R.string.bluetooth_sap_notif_ticker);
        }
        if(!PTS_TEST)
        {
            sapDisconnectIntent.putExtra(SapServer.SAP_DISCONNECT_TYPE_EXTRA, type);
            PendingIntent pIntentDisconnect = PendingIntent.getBroadcast(mContext, type, sapDisconnectIntent,flags);
            notification = new Notification.Builder(mContext).setOngoing(true)
                .addAction(android.R.drawable.stat_sys_data_bluetooth, button, pIntentDisconnect)
                .setContentTitle(title)
                .setTicker(ticker)
                .setContentText(text)
                .setSmallIcon(android.R.drawable.stat_sys_data_bluetooth)
                .setAutoCancel(false)
                .setPriority(Notification.PRIORITY_MAX)
                .setOnlyAlertOnce(true)
                .build();
        }else{

            sapDisconnectIntent.putExtra(SapServer.SAP_DISCONNECT_TYPE_EXTRA, SapMessage.DISC_GRACEFULL);
            Intent sapForceDisconnectIntent = new Intent(SapServer.SAP_DISCONNECT_ACTION);
            sapForceDisconnectIntent.putExtra(SapServer.SAP_DISCONNECT_TYPE_EXTRA, SapMessage.DISC_IMMEDIATE);
            PendingIntent pIntentDisconnect = PendingIntent.getBroadcast(mContext, SapMessage.DISC_GRACEFULL, sapDisconnectIntent,flags);
            PendingIntent pIntentForceDisconnect = PendingIntent.getBroadcast(mContext, SapMessage.DISC_IMMEDIATE, sapForceDisconnectIntent,flags);
            notification = new Notification.Builder(mContext).setOngoing(true)
                    .addAction(android.R.drawable.stat_sys_data_bluetooth, mContext.getString(R.string.bluetooth_sap_notif_disconnect_button), pIntentDisconnect)
                    .addAction(android.R.drawable.stat_sys_data_bluetooth, mContext.getString(R.string.bluetooth_sap_notif_force_disconnect_button), pIntentForceDisconnect)
                    .setContentTitle(title)
                    .setTicker(ticker)
                    .setContentText(text)
                    .setSmallIcon(android.R.drawable.stat_sys_data_bluetooth)
                    .setAutoCancel(false)
                    .setPriority(Notification.PRIORITY_MAX)
                    .setOnlyAlertOnce(true)
                    .build();
        }


        notification.flags |= Notification.FLAG_NO_CLEAR |Notification.FLAG_ONLY_ALERT_ONCE; /* cannot be set with the builder */

        NotificationManager notificationManager =
                (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(NOTIFICATION_ID, notification);
    }
    /**
     * The SapServer RFCOMM reader thread. Sets up the handler thread and handle
     * all read from the RFCOMM in-socket. This thread also handle writes to the RIL socket.
     */
    @Override
    public void run() {
        try {
            /* SAP is not time critical, hence lowering priority to ensure critical tasks are executed
             * in a timely manner. */
            android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);

            /* Start the SAP message handler thread */
            mHandlerThread = new HandlerThread("SapServerHandler", android.os.Process.THREAD_PRIORITY_BACKGROUND);
            mHandlerThread.start();
            Looper sapLooper = mHandlerThread.getLooper(); /* This will return when the looper is ready */
            mSapHandler = new Handler(sapLooper, this);

            mRilBtReceiver = new SapRilReceiver(mSapHandler);
            mRilBtReceiverThread = new Thread(mRilBtReceiver, "RilBtReceiver");
            setNotification(SapMessage.DISC_GRACEFULL,0);
            boolean done = false;
            while (!done) {
                if(VERBOSE) Log.i(TAG, "Waiting for incomming RFCOMM message...");
                int requestType = mRfcommIn.read();
                if(requestType == -1) {
                    done = true; // EOF reached
                } else {
                    SapMessage msg = SapMessage.readMessage(requestType, mRfcommIn);
                    if(msg != null && mState != SAP_STATE.DISCONNECTING)
                    {
                        switch (requestType) {
                        case SapMessage.ID_CONNECT_REQ:
                            if(VERBOSE) Log.d(TAG, "CONNECT_REQ - MaxMsgSize: " + msg.getMaxMsgSize());
                            onConnectRequest(msg);
                            msg = null; /* don't send ril connect yet */
                            break;
                        case SapMessage.ID_DISCONNECT_REQ: /* No params */
                            /*
                             * 1) send RIL_REQUEST_SIM_SAP_DISCONNECT (block for all incoming requests, as they are not
                             *                                         allowed, don't even send an error_resp)
                             * 2) on response disconnect ril socket.
                             * 3) when disconnected send RIL.ACTION_RIL_RECONNECT_OFF_REQ
                             * 4) on RIL.ACTION_RIL_RECONNECT_CFM send SAP_DISCONNECT_RESP to client.
                             * 5) Start RFCOMM disconnect timer
                             * 6.a) on rfcomm disconnect: cancel timer and initiate cleanup
                             * 6.b) on rfcomm disc. timeout: close socket-streams and initiate cleanup */
                            if(VERBOSE) Log.d(TAG, "DISCONNECT_REQ");

                            clearPendingRilResponses(msg);
                            // We simply need to forward to RIL, but not change state to busy - hence send and set message to null.
                            changeState(SAP_STATE.DISCONNECTING); /* do not enter disconnecting state for disconnect_ind
                                                                     - we need to obtain normal operation until disconnect is received. */
                            sendRilThreadMessage(msg);
                            msg = null; // don't send twice
                            /*cancel the timer for the hard-disconnect intent*/
                            stopDisconnectTimer();
                            break;
                        case SapMessage.ID_POWER_SIM_OFF_REQ: // Fall through
                        case SapMessage.ID_RESET_SIM_REQ:
                            /* Forward these to the RIL regardless of the state, and clear any pending resp */
                            clearPendingRilResponses(msg);
                            break;
                        default:
                            /* remaining cases just needs to be forwarded to the RIL unless we are in busy state. */
                            if(mState != SAP_STATE.CONNECTED) {
                                Log.w(TAG, "Message received in STATE != CONNECTED - state = " + mState.name());
                                /* We shall only handle one request at the time, hence return error */
                                SapMessage atrReply = new SapMessage(SapMessage.ID_ERROR_RESP);
                                sendClientMessage(atrReply);
                                msg = null;
                            }
                        }

                        if(msg != null && msg.getSendToRil() == true) {
                            changeState(SAP_STATE.CONNECTED_BUSY);
                            sendRilThreadMessage(msg);
                        }

                    } else { /* An unknown message or in disconnecting state - send error indication */
                        Log.e(TAG, "Unable to parse message.");
                        SapMessage atrReply = new SapMessage(SapMessage.ID_ERROR_RESP);
                        sendClientMessage(atrReply);
                    }
                }
            } // end while
        } catch (NullPointerException e) {
            Log.w(TAG, e);
        } catch (IOException e) {
            /* This is expected during shutdown */
            Log.i(TAG, "IOException received, this is probably a shutdown signal, cleaning up...");
        } catch (Exception e) {
            /* TODO: Change to the needed Exception types when done testing */
            Log.w(TAG, e);
        } finally {
            // Do cleanup even if an exception occurs
            stopDisconnectTimer();
            /* In case of e.g. a RFCOMM close while connected:
             *        - Initiate a FORCED shutdown
             *        - Wait for RIL deinit to complete
             */
            if(mState != SAP_STATE.DISCONNECTED) {
                if(mState != SAP_STATE.DISCONNECTING &&
                        mIsLocalInitDisconnect != true) {
                    sendDisconnectInd(SapMessage.DISC_FORCED);
                }
                if(DEBUG) Log.i(TAG, "Waiting for deinit to complete");
                try {
                    mDeinitSignal.await();
                } catch (InterruptedException e) {
                    Log.e(TAG, "Interrupt received while waitinf for de-init to complete", e);
                }
            }
            mContext.unregisterReceiver(mIntentReceiver);
            if(mHandlerThread != null) try {
                mHandlerThread.quit();
                mHandlerThread.join();
            } catch (InterruptedException e) {}
            if(mRilBtReceiverThread != null) try {
                mRilBtReceiverThread.join();
            } catch (InterruptedException e) {}

            if(mRfcommIn != null) try {
                if(VERBOSE) Log.i(TAG, "Closing mRfcommIn...");
                mRfcommIn.close();
            } catch (IOException e) {}

            if(mRfcommOut != null) try {
                if(VERBOSE) Log.i(TAG, "Closing mRfcommOut...");
                mRfcommOut.close();
            } catch (IOException e) {}

            if (mSapServiceHandler != null) {
                Message msg = Message.obtain(mSapServiceHandler);
                msg.what = SapService.MSG_SERVERSESSION_CLOSE;
                msg.sendToTarget();
                if (DEBUG) Log.d(TAG, "MSG_SERVERSESSION_CLOSE sent out.");
            }
            Log.i(TAG, "All done exiting thread...");
        }
    }


    /**
     * This function needs to determine:
     *  - if the maxMsgSize is acceptable - else reply CON_STATUS_ERROR_MAX_MSG_SIZE_UNSUPPORTED + new maxMsgSize if too big
     *  - connect to the RIL-BT socket
     *  - if a call is ongoing reply CON_STATUS_OK_ONGOING_CALL.
     *  - if all ok, just respond CON_STATUS_OK.
     *
     * @param msg the incoming SapMessage
     */
    private void onConnectRequest(SapMessage msg) {
        SapMessage reply = new SapMessage(SapMessage.ID_CONNECT_RESP);

        if(mState == SAP_STATE.CONNECTING) {
            /* A connect request might have been rejected because of maxMessageSize negotiation, and
             * this is a new connect request. Simply forward to RIL, and stay in connecting state.
             * */
            reply = null;
            sendRilMessage(msg);
            stopDisconnectTimer();

        } else if(mState != SAP_STATE.DISCONNECTED && mState != SAP_STATE.CONNECTING_CALL_ONGOING) {
            reply.setConnectionStatus(SapMessage.CON_STATUS_ERROR_CONNECTION);
        } else {
            // Store the MaxMsgSize for future use
            mMaxMsgSize = msg.getMaxMsgSize();
            /* All parameters OK, examine if a call is ongoing and start the RIL-BT listener thread. */
            if (isCallOngoing() == true) {
                /* If a call is ongoing we set the state, inform the SAP client and wait for a state change
                 * intent from the TelephonyManager with state IDLE. */
                changeState(SAP_STATE.CONNECTING_CALL_ONGOING);
                reply.setConnectionStatus(SapMessage.CON_STATUS_OK_ONGOING_CALL);
            } else {
                /* no call is ongoing, initiate the connect sequence:
                 *  1) Start the SapRilReceiver thread (open the rild-bt socket)
                 *  2) Send a RIL_SIM_SAP_CONNECT request to RILD
                 *  3) Send a RIL_SIM_RESET request and a connect confirm to the SAP client */
                changeState(SAP_STATE.CONNECTING);
                if(mRilBtReceiverThread != null) {
                     /* Open the RIL socket, and wait for the complete message: SAP_MSG_RIL_CONNECT */
                    mRilBtReceiverThread.start();
                    // Don't send reply yet
                    reply = null;
                } else {
                    reply = new SapMessage(SapMessage.ID_CONNECT_RESP);
                    reply.setConnectionStatus(SapMessage.CON_STATUS_ERROR_CONNECTION);
                    sendClientMessage(reply);
                }
            }
        }
        if(reply != null)
            sendClientMessage(reply);
    }

    private void clearPendingRilResponses(SapMessage msg) {
        if(mState == SAP_STATE.CONNECTED_BUSY) {
            msg.setClearRilQueue(true);
        }
    }
    /**
     * Send RFCOMM message to the Sap Server Handler Thread
     * @param sapMsg The message to send
     */
    private void sendClientMessage(SapMessage sapMsg) {
        Message newMsg = mSapHandler.obtainMessage(SAP_MSG_RFC_REPLY, sapMsg);
        mSapHandler.sendMessage(newMsg);
    }

    /**
     * Send a RIL message to the SapServer message handler thread
     * @param sapMsg
     */
    private void sendRilThreadMessage(SapMessage sapMsg) {
        Message newMsg = mSapHandler.obtainMessage(SAP_MSG_RIL_REQ, sapMsg);
        mSapHandler.sendMessage(newMsg);
    }

    /**
     * Examine if a call is ongoing, by asking the telephony manager
     * @return false if the phone is IDLE (can be used for SAP), true otherwise.
     */
    private boolean isCallOngoing() {
        TelephonyManager tManager =(TelephonyManager)mContext.getSystemService(Context.TELEPHONY_SERVICE);
        if(tManager.getCallState() == TelephonyManager.CALL_STATE_IDLE) {
            return false;
        }
        return true;
    }

    /**
     * Change the SAP Server state.
     * We add thread protection, as we access the state from two threads.
     * @param newState
     */
    private void changeState(SAP_STATE newState) {
        if(DEBUG) Log.i(TAG_HANDLER,"Changing state from " + mState.name() +
                                        " to " + newState.name());
        synchronized (this) {
            mState = newState;
        }
    }


    /*************************************************************************
     * SAP Server Message Handler Thread Functions
     *************************************************************************/

    /**
     * The SapServer message handler thread implements the SAP state machine.
     *  - Handle all outgoing communication to the out-socket. Either replies from the RIL or direct
     *    messages send from the SapServe (e.g. connect_resp).
     *  - Handle all outgoing communication to the RIL-BT socket.
     *  - Handle all replies from the RIL
     */
    @Override
    public boolean handleMessage(Message msg) {
        if(VERBOSE) Log.i(TAG_HANDLER,"Handling message (ID: " + msg.what + "): " + getMessageName(msg.what));

        SapMessage sapMsg = null;

        switch(msg.what) {
        case SAP_MSG_RFC_REPLY:
            sapMsg = (SapMessage) msg.obj;
            handleRfcommReply(sapMsg);
            break;
        case SAP_MSG_RIL_CONNECT:
            /* The connection to rild-bt have been established. Store the outStream handle
             * and send the connect request. */
            mRilBtOutStream = mRilBtReceiver.getRilBtOutStream();
            if(mTestMode != SapMessage.INVALID_VALUE) {
                SapMessage rilTestModeReq = new SapMessage(SapMessage.ID_RIL_SIM_ACCESS_TEST_REQ);
                rilTestModeReq.setTestMode(mTestMode);
                sendRilMessage(rilTestModeReq);
                mTestMode = SapMessage.INVALID_VALUE;
            }
            SapMessage rilSapConnect = new SapMessage(SapMessage.ID_CONNECT_REQ);
            rilSapConnect.setMaxMsgSize(mMaxMsgSize);
            sendRilMessage(rilSapConnect);
            break;
        case SAP_MSG_RIL_REQ:
            sapMsg = (SapMessage) msg.obj;
            if(sapMsg != null) {
                sendRilMessage(sapMsg);
            }
            break;
        case SAP_MSG_RIL_IND:
            sapMsg = (SapMessage) msg.obj;
            handleRilInd(sapMsg);
            break;
        default:
            /* Message not handled */
            return false;
        }
        return true; // Message handles
    }

    /**
     * Close the in/out rfcomm streams, to trigger a shutdown of the SapServer main thread.
     * Use this after completing the deinit sequence.
     */
    private void shutdown() {

        if(DEBUG) Log.i(TAG_HANDLER, "in Shutdown()");
        try {
            mRfcommOut.close();
        } catch (IOException e) {}
        try {
            mRfcommIn.close();

        } catch (IOException e) {}
        mRfcommIn = null;
        mRfcommOut = null;
        stopDisconnectTimer();
    }

    private void startDisconnectTimer(int discType, int timeMs) {

        stopDisconnectTimer();
        synchronized (this) {
            Intent sapDisconnectIntent = new Intent(SapServer.SAP_DISCONNECT_ACTION);
            sapDisconnectIntent.putExtra(SAP_DISCONNECT_TYPE_EXTRA, discType);
            AlarmManager alarmManager =
                    (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
            pDiscIntent = PendingIntent.getBroadcast(mContext,
                                                    discType,
                                                    sapDisconnectIntent, PendingIntent.FLAG_CANCEL_CURRENT);
            alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,  SystemClock.elapsedRealtime() + timeMs, pDiscIntent);

            if(VERBOSE) Log.d(TAG_HANDLER, "Setting alarm for " + timeMs +
                    " ms to activate disconnect type " + discType);
        }
    }

    private void stopDisconnectTimer() {
        synchronized (this) {
            if(pDiscIntent != null)
            {
                AlarmManager alarmManager =
                        (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
                alarmManager.cancel(pDiscIntent);
                pDiscIntent.cancel();
                if(VERBOSE) {
                    Log.d(TAG_HANDLER, "Canceling disconnect alarm");
                }
                pDiscIntent = null;
            }
        }
    }

    /**
     * Here we handle the replies to the SAP client, normally forwarded directly from the RIL.
     * We do need to handle some of the messages in the SAP profile, hence we look at the messages
     * here before they go to the client
     * @param sapMsg the message to send to the SAP client
     */
    private void handleRfcommReply(SapMessage sapMsg) {
        if(sapMsg != null) {

            if(DEBUG) Log.i(TAG_HANDLER, "handleRfcommReply() handling " + SapMessage.getMsgTypeName(sapMsg.getMsgType()));

            switch(sapMsg.getMsgType()) {

                case SapMessage.ID_CONNECT_RESP:
                    if (sapMsg.getConnectionStatus() == SapMessage.CON_STATUS_OK) {
                        // This is successful connect response from RIL/modem.
                        changeState(SAP_STATE.CONNECTED);
                    } else if(sapMsg.getConnectionStatus() == SapMessage.CON_STATUS_OK_ONGOING_CALL
                              && mState != SAP_STATE.CONNECTING_CALL_ONGOING) {
                        changeState(SAP_STATE.CONNECTING_CALL_ONGOING);
                    } else if(mState == SAP_STATE.CONNECTING_CALL_ONGOING) {
                        // Hold back the connect resp if a call was ongoing when the connect req was received.
                        if(VERBOSE) Log.i(TAG, "Hold back the connect resp, as a call was ongoing when the initial response were sent.");
                        sapMsg = null;
                    } else if(sapMsg.getConnectionStatus() != SapMessage.CON_STATUS_OK) {
                        /* Most likely the peer will try to connect again, hence we keep the connection to RIL open
                         * and stay in connecting state.
                         */
                        // Start timer to do shutdown if a new connect request is not received in time
                        startDisconnectTimer(SapMessage.DISC_FORCED, DISCONNECT_TIMEOUT_RFCOMM);
                    }
                    break;
                case SapMessage.ID_DISCONNECT_RESP:
                    if(mState == SAP_STATE.DISCONNECTING) {
                        /* Close the RIL-BT output Stream and signal to SapRilReceiver to close down the input stream. */
                        if(DEBUG) Log.i(TAG, "ID_DISCONNECT_RESP received in SAP_STATE.DISCONNECTING" +
                                             " - shutdown bt-ril ");
                        /* We need to close down the RilBtReceiverThread before signaling to RILJ
                         * that it can re-open the socket to RILC. */
                        mRilBtReceiver.shutdown();
                        mRilBtOutStream = null;
                        try {
                            mRilBtReceiverThread.join();
                        } catch (InterruptedException e) {
                            Log.e(TAG_HANDLER, "Exception occured while waiting for thread to exit.", e);
                        }
                        mRilBtReceiverThread = null;

                        // Wait for the thread to close, as we need the socket to be closed before signaling the RIL to reopen.
                        // Disconnecting
                        // Send the disconnect resp, and wait for the client to close the Rfcomm, but start a
                        // timeout timer, just to be sure. Use alarm, to ensure we wake the host to close the
                        // connection to minimize power consumption.
                        SapMessage disconnectResp = new SapMessage(SapMessage.ID_DISCONNECT_RESP);
                        changeState(SAP_STATE.DISCONNECTED);
                        sapMsg = disconnectResp;
                        //since we are disconnected we remove the notification
                        NotificationManager notificationManager =
                                (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
                        notificationManager.cancel(SapServer.NOTIFICATION_ID);
                    } else { /* DISCONNECTED */
                        mDeinitSignal.countDown(); /* Signal deinit complete */
                        if(mIsLocalInitDisconnect == true) {
                            if(VERBOSE) Log.i(TAG_HANDLER, "This is a FORCED disconnect.");
                            /* We needed to force the disconnect, hence no hope for the client to close
                             * the RFCOMM connection, hence we do it here. */
                            shutdown();
                            sapMsg = null;
                        } else {
                            /* The client must disconnect the RFCOMM, but in case it does not, we need to do it.
                             * We start an alarm, and if it triggers, we must send the MSG_SERVERSESSION_CLOSE */
                            if(VERBOSE) Log.i(TAG_HANDLER, "This is a NORMAL disconnect.");
                            startDisconnectTimer(SapMessage.DISC_RFCOMM, DISCONNECT_TIMEOUT_RFCOMM);
                        }
                    }
                    break;
                case SapMessage.ID_STATUS_IND:
                    /* Some car-kits only "likes" status indication when connected, hence discard
                     * any arriving outside this state */
                    if(mState == SAP_STATE.DISCONNECTED ||
                            mState == SAP_STATE.CONNECTING ||
                            mState == SAP_STATE.DISCONNECTING) {
                        sapMsg = null;
                    }
                    break;
                default:
                // Nothing special, just send the message
            }
        }

        /* Update state variable based on the number of pending commands. We are only able to
         * handle one request at the time, except from disconnect, sim off and sim reset.
         * Hence if one of these are received while in busy state, we might have a crossing
         * response, hence we must stay in BUSY state if we have an ongoing RIL request. */
        if(mState == SAP_STATE.CONNECTED_BUSY) {
            if(SapMessage.getNumPendingRilMessages() == 0) {
                changeState(SAP_STATE.CONNECTED);
            }
        }

        // This is the default case - just send the message to the SAP client.
        if(sapMsg != null)
            sendReply(sapMsg);
    }

    private void handleRilInd(SapMessage sapMsg) {
        if(sapMsg == null)
            return;

        switch(sapMsg.getMsgType()) {
        case SapMessage.ID_DISCONNECT_IND:
        {
            if(mState != SAP_STATE.DISCONNECTED && mState != SAP_STATE.DISCONNECTING){
                /* we only send disconnect indication to the client if we are actually connected*/
                SapMessage reply = new SapMessage(SapMessage.ID_DISCONNECT_IND);
                reply.setDisconnectionType(sapMsg.getDisconnectionType()) ;
                sendClientMessage(reply);
            } else {
                /* TODO: This was introduced to handle disconnect indication from RIL */
                sendDisconnectInd(sapMsg.getDisconnectionType());
            }
            break;
        }

        default:
            if(DEBUG) Log.w(TAG_HANDLER,"Unhandled message - type: " + SapMessage.getMsgTypeName(sapMsg.getMsgType()));
        }
    }

    /**
     * This is only to be called from the handlerThread, else use sendRilThreadMessage();
     * @param sapMsg
     */
    private void sendRilMessage(SapMessage sapMsg) {
        if(VERBOSE) Log.i(TAG_HANDLER, "sendRilMessage() - " + SapMessage.getMsgTypeName(sapMsg.getMsgType()));
        try {
            sapMsg.writeReqToStream(mRilBtOutStream);
        } catch (IOException e) {
            Log.e(TAG_HANDLER, "Unable to send message to RIL", e);
            SapMessage errorReply = new SapMessage(SapMessage.ID_ERROR_RESP);
            sendClientMessage(errorReply);
        }
    }

    /**
     * Only call this from the sapHandler thread.
     */
    private void sendReply(SapMessage msg) {
        if(VERBOSE) Log.i(TAG_HANDLER, "sendReply() RFCOMM - " + SapMessage.getMsgTypeName(msg.getMsgType()));
        try {
            msg.write(mRfcommOut);
            mRfcommOut.flush();
        } catch (IOException e) {
            Log.w(TAG_HANDLER, e);
        }
    }

    private static String getMessageName(int messageId) {
        switch (messageId) {
        case SAP_MSG_RFC_REPLY:
            return "SAP_MSG_REPLY";
        case SAP_MSG_RIL_CONNECT:
            return "SAP_MSG_RIL_CONNECT";
        case SAP_MSG_RIL_REQ:
            return "SAP_MSG_RIL_REQ";
        case SAP_MSG_RIL_IND:
            return "SAP_MSG_RIL_IND";
        default:
            return "Unknown message ID";
        }
    }

}