summaryrefslogtreecommitdiff
path: root/src/android/bluetooth/client/map/BluetoothMasClient.java
blob: 7d50e5bcfc3d8abda13f27c4c6ff5fc15693bd69 (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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
/*
 * Copyright (C) 2014 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 android.bluetooth.client.map;

import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothMasInstance;
import android.bluetooth.BluetoothSocket;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import android.bluetooth.client.map.BluetoothMasRequestSetMessageStatus.StatusIndicator;
import android.bluetooth.client.map.utils.ObexTime;

import java.io.IOException;
import java.lang.ref.WeakReference;
import java.math.BigInteger;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;

import javax.obex.ObexTransport;

public class BluetoothMasClient {

    private final static String TAG = "BluetoothMasClient";

    private static final int SOCKET_CONNECTED = 10;

    private static final int SOCKET_ERROR = 11;

    /**
     * Callback message sent when connection state changes
     * <p>
     * <code>arg1</code> is set to {@link #STATUS_OK} when connection is
     * established successfully and {@link #STATUS_FAILED} when connection
     * either failed or was disconnected (depends on request from application)
     *
     * @see #connect()
     * @see #disconnect()
     */
    public static final int EVENT_CONNECT = 1;

    /**
     * Callback message sent when MSE accepted update inbox request
     *
     * @see #updateInbox()
     */
    public static final int EVENT_UPDATE_INBOX = 2;

    /**
     * Callback message sent when path is changed
     * <p>
     * <code>obj</code> is set to path currently set on MSE
     *
     * @see #setFolderRoot()
     * @see #setFolderUp()
     * @see #setFolderDown(String)
     */
    public static final int EVENT_SET_PATH = 3;

    /**
     * Callback message sent when folder listing is received
     * <p>
     * <code>obj</code> contains ArrayList of sub-folder names
     *
     * @see #getFolderListing()
     * @see #getFolderListing(int, int)
     */
    public static final int EVENT_GET_FOLDER_LISTING = 4;

    /**
     * Callback message sent when folder listing size is received
     * <p>
     * <code>obj</code> contains number of items in folder listing
     *
     * @see #getFolderListingSize()
     */
    public static final int EVENT_GET_FOLDER_LISTING_SIZE = 5;

    /**
     * Callback message sent when messages listing is received
     * <p>
     * <code>obj</code> contains ArrayList of {@link BluetoothMapBmessage}
     *
     * @see #getMessagesListing(String, int)
     * @see #getMessagesListing(String, int, MessagesFilter, int)
     * @see #getMessagesListing(String, int, MessagesFilter, int, int, int)
     */
    public static final int EVENT_GET_MESSAGES_LISTING = 6;

    /**
     * Callback message sent when message is received
     * <p>
     * <code>obj</code> contains {@link BluetoothMapBmessage}
     *
     * @see #getMessage(String, CharsetType, boolean)
     */
    public static final int EVENT_GET_MESSAGE = 7;

    /**
     * Callback message sent when message status is changed
     *
     * @see #setMessageDeletedStatus(String, boolean)
     * @see #setMessageReadStatus(String, boolean)
     */
    public static final int EVENT_SET_MESSAGE_STATUS = 8;

    /**
     * Callback message sent when message is pushed to MSE
     * <p>
     * <code>obj</code> contains handle of message as allocated by MSE
     *
     * @see #pushMessage(String, BluetoothMapBmessage, CharsetType)
     * @see #pushMessage(String, BluetoothMapBmessage, CharsetType, boolean,
     *      boolean)
     */
    public static final int EVENT_PUSH_MESSAGE = 9;

    /**
     * Callback message sent when notification status is changed
     * <p>
     * <code>obj</code> contains <code>1</code> if notifications are enabled and
     * <code>0</code> otherwise
     *
     * @see #setNotificationRegistration(boolean)
     */
    public static final int EVENT_SET_NOTIFICATION_REGISTRATION = 10;

    /**
     * Callback message sent when event report is received from MSE to MNS
     * <p>
     * <code>obj</code> contains {@link BluetoothMapEventReport}
     *
     * @see #setNotificationRegistration(boolean)
     */
    public static final int EVENT_EVENT_REPORT = 11;

    /**
     * Callback message sent when messages listing size is received
     * <p>
     * <code>obj</code> contains number of items in messages listing
     *
     * @see #getMessagesListingSize()
     */
    public static final int EVENT_GET_MESSAGES_LISTING_SIZE = 12;

    /**
     * Status for callback message when request is successful
     */
    public static final int STATUS_OK = 0;

    /**
     * Status for callback message when request is not successful
     */
    public static final int STATUS_FAILED = 1;

    /**
     * Constant corresponding to <code>ParameterMask</code> application
     * parameter value in MAP specification
     */
    public static final int PARAMETER_DEFAULT = 0x00000000;

    /**
     * Constant corresponding to <code>ParameterMask</code> application
     * parameter value in MAP specification
     */
    public static final int PARAMETER_SUBJECT = 0x00000001;

    /**
     * Constant corresponding to <code>ParameterMask</code> application
     * parameter value in MAP specification
     */
    public static final int PARAMETER_DATETIME = 0x00000002;

    /**
     * Constant corresponding to <code>ParameterMask</code> application
     * parameter value in MAP specification
     */
    public static final int PARAMETER_SENDER_NAME = 0x00000004;

    /**
     * Constant corresponding to <code>ParameterMask</code> application
     * parameter value in MAP specification
     */
    public static final int PARAMETER_SENDER_ADDRESSING = 0x00000008;

    /**
     * Constant corresponding to <code>ParameterMask</code> application
     * parameter value in MAP specification
     */
    public static final int PARAMETER_RECIPIENT_NAME = 0x00000010;

    /**
     * Constant corresponding to <code>ParameterMask</code> application
     * parameter value in MAP specification
     */
    public static final int PARAMETER_RECIPIENT_ADDRESSING = 0x00000020;

    /**
     * Constant corresponding to <code>ParameterMask</code> application
     * parameter value in MAP specification
     */
    public static final int PARAMETER_TYPE = 0x00000040;

    /**
     * Constant corresponding to <code>ParameterMask</code> application
     * parameter value in MAP specification
     */
    public static final int PARAMETER_SIZE = 0x00000080;

    /**
     * Constant corresponding to <code>ParameterMask</code> application
     * parameter value in MAP specification
     */
    public static final int PARAMETER_RECEPTION_STATUS = 0x00000100;

    /**
     * Constant corresponding to <code>ParameterMask</code> application
     * parameter value in MAP specification
     */
    public static final int PARAMETER_TEXT = 0x00000200;

    /**
     * Constant corresponding to <code>ParameterMask</code> application
     * parameter value in MAP specification
     */
    public static final int PARAMETER_ATTACHMENT_SIZE = 0x00000400;

    /**
     * Constant corresponding to <code>ParameterMask</code> application
     * parameter value in MAP specification
     */
    public static final int PARAMETER_PRIORITY = 0x00000800;

    /**
     * Constant corresponding to <code>ParameterMask</code> application
     * parameter value in MAP specification
     */
    public static final int PARAMETER_READ = 0x00001000;

    /**
     * Constant corresponding to <code>ParameterMask</code> application
     * parameter value in MAP specification
     */
    public static final int PARAMETER_SENT = 0x00002000;

    /**
     * Constant corresponding to <code>ParameterMask</code> application
     * parameter value in MAP specification
     */
    public static final int PARAMETER_PROTECTED = 0x00004000;

    /**
     * Constant corresponding to <code>ParameterMask</code> application
     * parameter value in MAP specification
     */
    public static final int PARAMETER_REPLYTO_ADDRESSING = 0x00008000;

    public enum ConnectionState {
        DISCONNECTED, CONNECTING, CONNECTED, DISCONNECTING;
    }

    public enum CharsetType {
        NATIVE, UTF_8;
    }

    /** device associated with client */
    private final BluetoothDevice mDevice;

    /** MAS instance associated with client */
    private final BluetoothMasInstance mMas;

    /** callback handler to application */
    private final Handler mCallback;

    private ConnectionState mConnectionState = ConnectionState.DISCONNECTED;

    private boolean mNotificationEnabled = false;

    private SocketConnectThread mConnectThread = null;

    private ObexTransport mObexTransport = null;

    private BluetoothMasObexClientSession mObexSession = null;

    private SessionHandler mSessionHandler = null;

    private BluetoothMnsService mMnsService = null;

    private ArrayDeque<String> mPath = null;

    private static class SessionHandler extends Handler {

        private final WeakReference<BluetoothMasClient> mClient;

        public SessionHandler(BluetoothMasClient client) {
            super();

            mClient = new WeakReference<BluetoothMasClient>(client);
        }

        @Override
        public void handleMessage(Message msg) {

            BluetoothMasClient client = mClient.get();
            if (client == null) {
                return;
            }
            Log.v(TAG, "handleMessage  "+msg.what);

            switch (msg.what) {
                case SOCKET_ERROR:
                    client.mConnectThread = null;
                    client.sendToClient(EVENT_CONNECT, false);
                    break;

                case SOCKET_CONNECTED:
                    client.mConnectThread = null;

                    client.mObexTransport = (ObexTransport) msg.obj;

                    client.mObexSession = new BluetoothMasObexClientSession(client.mObexTransport,
                            client.mSessionHandler);
                    client.mObexSession.start();
                    break;

                case BluetoothMasObexClientSession.MSG_OBEX_CONNECTED:
                    client.mPath.clear(); // we're in root after connected
                    client.mConnectionState = ConnectionState.CONNECTED;
                    client.sendToClient(EVENT_CONNECT, true);
                    break;

                case BluetoothMasObexClientSession.MSG_OBEX_DISCONNECTED:
                    client.mConnectionState = ConnectionState.DISCONNECTED;
                    client.mNotificationEnabled = false;
                    client.mObexSession = null;
                    client.sendToClient(EVENT_CONNECT, false);
                    break;

                case BluetoothMasObexClientSession.MSG_REQUEST_COMPLETED:
                    BluetoothMasRequest request = (BluetoothMasRequest) msg.obj;
                    int status = request.isSuccess() ? STATUS_OK : STATUS_FAILED;

                    Log.v(TAG, "MSG_REQUEST_COMPLETED (" + status + ") for "
                            + request.getClass().getName());

                    if (request instanceof BluetoothMasRequestUpdateInbox) {
                        client.sendToClient(EVENT_UPDATE_INBOX, request.isSuccess());

                    } else if (request instanceof BluetoothMasRequestSetPath) {
                        if (request.isSuccess()) {
                            BluetoothMasRequestSetPath req = (BluetoothMasRequestSetPath) request;
                            switch (req.mDir) {
                                case UP:
                                    if (client.mPath.size() > 0) {
                                        client.mPath.removeLast();
                                    }
                                    break;

                                case ROOT:
                                    client.mPath.clear();
                                    break;

                                case DOWN:
                                    client.mPath.addLast(req.mName);
                                    break;
                            }
                        }

                        client.sendToClient(EVENT_SET_PATH, request.isSuccess(),
                                client.getCurrentPath());

                    } else if (request instanceof BluetoothMasRequestGetFolderListing) {
                        BluetoothMasRequestGetFolderListing req = (BluetoothMasRequestGetFolderListing) request;
                        ArrayList<String> folders = req.getList();

                        client.sendToClient(EVENT_GET_FOLDER_LISTING, request.isSuccess(), folders);

                    } else if (request instanceof BluetoothMasRequestGetFolderListingSize) {
                        int size = ((BluetoothMasRequestGetFolderListingSize) request).getSize();

                        client.sendToClient(EVENT_GET_FOLDER_LISTING_SIZE, request.isSuccess(),
                                size);

                    } else if (request instanceof BluetoothMasRequestGetMessagesListing) {
                        BluetoothMasRequestGetMessagesListing req = (BluetoothMasRequestGetMessagesListing) request;
                        ArrayList<BluetoothMapMessage> msgs = req.getList();

                        client.sendToClient(EVENT_GET_MESSAGES_LISTING, request.isSuccess(), msgs);

                    } else if (request instanceof BluetoothMasRequestGetMessage) {
                        BluetoothMasRequestGetMessage req = (BluetoothMasRequestGetMessage) request;
                        BluetoothMapBmessage bmsg = req.getMessage();

                        client.sendToClient(EVENT_GET_MESSAGE, request.isSuccess(), bmsg);

                    } else if (request instanceof BluetoothMasRequestSetMessageStatus) {
                        client.sendToClient(EVENT_SET_MESSAGE_STATUS, request.isSuccess());

                    } else if (request instanceof BluetoothMasRequestPushMessage) {
                        BluetoothMasRequestPushMessage req = (BluetoothMasRequestPushMessage) request;
                        String handle = req.getMsgHandle();

                        client.sendToClient(EVENT_PUSH_MESSAGE, request.isSuccess(), handle);

                    } else if (request instanceof BluetoothMasRequestSetNotificationRegistration) {
                        BluetoothMasRequestSetNotificationRegistration req = (BluetoothMasRequestSetNotificationRegistration) request;

                        client.mNotificationEnabled = req.isSuccess() ? req.getStatus()
                                : client.mNotificationEnabled;

                        client.sendToClient(EVENT_SET_NOTIFICATION_REGISTRATION,
                                request.isSuccess(),
                                client.mNotificationEnabled ? 1 : 0);
                    } else if (request instanceof BluetoothMasRequestGetMessagesListingSize) {
                        int size = ((BluetoothMasRequestGetMessagesListingSize) request).getSize();
                        client.sendToClient(EVENT_GET_MESSAGES_LISTING_SIZE, request.isSuccess(),
                                size);
                    }
                    break;

                case BluetoothMnsService.EVENT_REPORT:
                    /* pass event report directly to app */
                    client.sendToClient(EVENT_EVENT_REPORT, true, msg.obj);
                    break;
            }
        }
    }

    private void sendToClient(int event, boolean success) {
        sendToClient(event, success, null);
    }

    private void sendToClient(int event, boolean success, int param) {
        sendToClient(event, success, Integer.valueOf(param));
    }

    private void sendToClient(int event, boolean success, Object param) {
        if (success) {
            mCallback.obtainMessage(event, STATUS_OK, mMas.getId(), param).sendToTarget();
        } else {
            mCallback.obtainMessage(event, STATUS_FAILED, mMas.getId(), null).sendToTarget();
        }
    }

    private class SocketConnectThread extends Thread {
        private BluetoothSocket socket = null;

        public SocketConnectThread() {
            super("SocketConnectThread");
        }

        @Override
        public void run() {
            try {
                socket = mDevice.createRfcommSocket(mMas.getChannel());
                socket.connect();

                BluetoothMapRfcommTransport transport;
                transport = new BluetoothMapRfcommTransport(socket);

                mSessionHandler.obtainMessage(SOCKET_CONNECTED, transport).sendToTarget();
            } catch (IOException e) {
                Log.e(TAG, "Error when creating/connecting socket", e);

                closeSocket();
                mSessionHandler.obtainMessage(SOCKET_ERROR).sendToTarget();
            }
        }

        @Override
        public void interrupt() {
            closeSocket();
        }

        private void closeSocket() {
            try {
                if (socket != null) {
                    socket.close();
                }
            } catch (IOException e) {
                Log.e(TAG, "Error when closing socket", e);
            }
        }
    }

    /**
     * Object representation of filters to be applied on message listing
     *
     * @see #getMessagesListing(String, int, MessagesFilter, int)
     * @see #getMessagesListing(String, int, MessagesFilter, int, int, int)
     */
    public static final class MessagesFilter {

        public final static byte MESSAGE_TYPE_ALL = 0x00;
        public final static byte MESSAGE_TYPE_SMS_GSM = 0x01;
        public final static byte MESSAGE_TYPE_SMS_CDMA = 0x02;
        public final static byte MESSAGE_TYPE_EMAIL = 0x04;
        public final static byte MESSAGE_TYPE_MMS = 0x08;

        public final static byte READ_STATUS_ANY = 0x00;
        public final static byte READ_STATUS_UNREAD = 0x01;
        public final static byte READ_STATUS_READ = 0x02;

        public final static byte PRIORITY_ANY = 0x00;
        public final static byte PRIORITY_HIGH = 0x01;
        public final static byte PRIORITY_NON_HIGH = 0x02;

        byte messageType = MESSAGE_TYPE_ALL;

        String periodBegin = null;

        String periodEnd = null;

        byte readStatus = READ_STATUS_ANY;

        String recipient = null;

        String originator = null;

        byte priority = PRIORITY_ANY;

        public MessagesFilter() {
        }

        public void setMessageType(byte filter) {
            messageType = filter;
        }

        public void setPeriod(Date filterBegin, Date filterEnd) {
            periodBegin = (new ObexTime(filterBegin)).toString();
            periodEnd = (new ObexTime(filterEnd)).toString();
        }

        public void setReadStatus(byte readfilter) {
            readStatus = readfilter;
        }

        public void setRecipient(String filter) {
            if ("".equals(filter)) {
                recipient = null;
            } else {
                recipient = filter;
            }
        }

        public void setOriginator(String filter) {
            if ("".equals(filter)) {
                originator = null;
            } else {
                originator = filter;
            }
        }

        public void setPriority(byte filter) {
            priority = filter;
        }
    }

    /**
     * Constructs client object to communicate with single MAS instance on MSE
     *
     * @param device {@link BluetoothDevice} corresponding to remote device
     *            acting as MSE
     * @param mas {@link BluetoothMasInstance} object describing MAS instance on
     *            remote device
     * @param callback {@link Handler} object to which callback messages will be
     *            sent Each message will have <code>arg1</code> set to either
     *            {@link #STATUS_OK} or {@link #STATUS_FAILED} and
     *            <code>arg2</code> to MAS instance ID. <code>obj</code> in
     *            message is event specific.
     */
    public BluetoothMasClient(BluetoothDevice device, BluetoothMasInstance mas,
            Handler callback) {
        mDevice = device;
        mMas = mas;
        mCallback = callback;

        mPath = new ArrayDeque<String>();
    }

    /**
     * Retrieves MAS instance data associated with client
     *
     * @return instance data object
     */
    public BluetoothMasInstance getInstanceData() {
        return mMas;
    }

    /**
     * Connects to MAS instance
     * <p>
     * Upon completion callback handler will receive {@link #EVENT_CONNECT}
     */
    public void connect() {
        if (mSessionHandler == null) {
            mSessionHandler = new SessionHandler(this);
        }

        if (mConnectThread == null && mObexSession == null) {
            mConnectionState = ConnectionState.CONNECTING;

            mConnectThread = new SocketConnectThread();
            mConnectThread.start();
        }
    }

    /**
     * Disconnects from MAS instance
     * <p>
     * Upon completion callback handler will receive {@link #EVENT_CONNECT}
     */
    public void disconnect() {
        if (mConnectThread == null && mObexSession == null) {
            return;
        }

        mConnectionState = ConnectionState.DISCONNECTING;

        if (mConnectThread != null) {
            mConnectThread.interrupt();
        }

        if (mObexSession != null) {
            mObexSession.stop();
        }
    }

    @Override
    public void finalize() {
        disconnect();
    }

    /**
     * Gets current connection state
     *
     * @return current connection state
     * @see ConnectionState
     */
    public ConnectionState getState() {
        return mConnectionState;
    }

    private boolean enableNotifications() {
        Log.v(TAG, "enableNotifications()");

        if (mMnsService == null) {
            mMnsService = new BluetoothMnsService();
        }

        mMnsService.registerCallback(mMas.getId(), mSessionHandler);

        BluetoothMasRequest request = new BluetoothMasRequestSetNotificationRegistration(true);
        return mObexSession.makeRequest(request);
    }

    private boolean disableNotifications() {
        Log.v(TAG, "enableNotifications()");

        if (mMnsService != null) {
            mMnsService.unregisterCallback(mMas.getId());
        }

        mMnsService = null;

        BluetoothMasRequest request = new BluetoothMasRequestSetNotificationRegistration(false);
        return mObexSession.makeRequest(request);
    }

    /**
     * Sets state of notifications for MAS instance
     * <p>
     * Once notifications are enabled, callback handler will receive
     * {@link #EVENT_EVENT_REPORT} when new notification is received
     * <p>
     * Upon completion callback handler will receive
     * {@link #EVENT_SET_NOTIFICATION_REGISTRATION}
     *
     * @param status <code>true</code> if notifications shall be enabled,
     *            <code>false</code> otherwise
     * @return <code>true</code> if request has been sent, <code>false</code>
     *         otherwise
     */
    public boolean setNotificationRegistration(boolean status) {
        if (mObexSession == null) {
            return false;
        }

        if (status) {
            return enableNotifications();
        } else {
            return disableNotifications();
        }
    }

    /**
     * Gets current state of notifications for MAS instance
     *
     * @return <code>true</code> if notifications are enabled,
     *         <code>false</code> otherwise
     */
    public boolean getNotificationRegistration() {
        return mNotificationEnabled;
    }

    /**
     * Goes back to root of folder hierarchy
     * <p>
     * Upon completion callback handler will receive {@link #EVENT_SET_PATH}
     *
     * @return <code>true</code> if request has been sent, <code>false</code>
     *         otherwise
     */
    public boolean setFolderRoot() {
        if (mObexSession == null) {
            return false;
        }

        BluetoothMasRequest request = new BluetoothMasRequestSetPath(true);
        return mObexSession.makeRequest(request);
    }

    /**
     * Goes back to parent folder in folder hierarchy
     * <p>
     * Upon completion callback handler will receive {@link #EVENT_SET_PATH}
     *
     * @return <code>true</code> if request has been sent, <code>false</code>
     *         otherwise
     */
    public boolean setFolderUp() {
        if (mObexSession == null) {
            return false;
        }

        BluetoothMasRequest request = new BluetoothMasRequestSetPath(false);
        return mObexSession.makeRequest(request);
    }

    /**
     * Goes down to specified sub-folder in folder hierarchy
     * <p>
     * Upon completion callback handler will receive {@link #EVENT_SET_PATH}
     *
     * @param name name of sub-folder
     * @return <code>true</code> if request has been sent, <code>false</code>
     *         otherwise
     */
    public boolean setFolderDown(String name) {
        if (mObexSession == null) {
            return false;
        }

        if (name == null || name.isEmpty() || name.contains("/")) {
            return false;
        }

        BluetoothMasRequest request = new BluetoothMasRequestSetPath(name);
        return mObexSession.makeRequest(request);
    }

    /**
     * Gets current path in folder hierarchy
     *
     * @return current path
     */
    public String getCurrentPath() {
        if (mPath.size() == 0) {
            return "";
        }

        Iterator<String> iter = mPath.iterator();

        StringBuilder sb = new StringBuilder(iter.next());

        while (iter.hasNext()) {
            sb.append("/").append(iter.next());
        }

        return sb.toString();
    }

    /**
     * Gets list of sub-folders in current folder
     * <p>
     * Upon completion callback handler will receive
     * {@link #EVENT_GET_FOLDER_LISTING}
     *
     * @return <code>true</code> if request has been sent, <code>false</code>
     *         otherwise
     */
    public boolean getFolderListing() {
        return getFolderListing((short) 0, (short) 0);
    }

    /**
     * Gets list of sub-folders in current folder
     * <p>
     * Upon completion callback handler will receive
     * {@link #EVENT_GET_FOLDER_LISTING}
     *
     * @param maxListCount maximum number of items returned or <code>0</code>
     *            for default value
     * @param listStartOffset index of first item returned or <code>0</code> for
     *            default value
     * @return <code>true</code> if request has been sent, <code>false</code>
     *         otherwise
     * @throws IllegalArgumentException if either maxListCount or
     *             listStartOffset are outside allowed range [0..65535]
     */
    public boolean getFolderListing(int maxListCount, int listStartOffset) {
        if (mObexSession == null) {
            return false;
        }

        BluetoothMasRequest request = new BluetoothMasRequestGetFolderListing(maxListCount,
                listStartOffset);
        return mObexSession.makeRequest(request);
    }

    /**
     * Gets number of sub-folders in current folder
     * <p>
     * Upon completion callback handler will receive
     * {@link #EVENT_GET_FOLDER_LISTING_SIZE}
     *
     * @return <code>true</code> if request has been sent, <code>false</code>
     *         otherwise
     */
    public boolean getFolderListingSize() {
        if (mObexSession == null) {
            return false;
        }

        BluetoothMasRequest request = new BluetoothMasRequestGetFolderListingSize();
        return mObexSession.makeRequest(request);
    }

    /**
     * Gets list of messages in specified sub-folder
     * <p>
     * Upon completion callback handler will receive
     * {@link #EVENT_GET_MESSAGES_LISTING}
     *
     * @param folder name of sub-folder or <code>null</code> for current folder
     * @param parameters bit-mask specifying requested parameters in listing or
     *            <code>0</code> for default value
     * @return <code>true</code> if request has been sent, <code>false</code>
     *         otherwise
     */
    public boolean getMessagesListing(String folder, int parameters) {
        return getMessagesListing(folder, parameters, null, (byte) 0, 0, 0);
    }

    /**
     * Gets list of messages in specified sub-folder
     * <p>
     * Upon completion callback handler will receive
     * {@link #EVENT_GET_MESSAGES_LISTING}
     *
     * @param folder name of sub-folder or <code>null</code> for current folder
     * @param parameters corresponds to <code>ParameterMask</code> application
     *            parameter in MAP specification
     * @param filter {@link MessagesFilter} object describing filters to be
     *            applied on listing by MSE
     * @param subjectLength maximum length of message subject in returned
     *            listing or <code>0</code> for default value
     * @return <code>true</code> if request has been sent, <code>false</code>
     *         otherwise
     * @throws IllegalArgumentException if subjectLength is outside allowed
     *             range [0..255]
     */
    public boolean getMessagesListing(String folder, int parameters, MessagesFilter filter,
            int subjectLength) {

        return getMessagesListing(folder, parameters, filter, subjectLength, 0, 0);
    }

    /**
     * Gets list of messages in specified sub-folder
     * <p>
     * Upon completion callback handler will receive
     * {@link #EVENT_GET_MESSAGES_LISTING}
     *
     * @param folder name of sub-folder or <code>null</code> for current folder
     * @param parameters corresponds to <code>ParameterMask</code> application
     *            parameter in MAP specification
     * @param filter {@link MessagesFilter} object describing filters to be
     *            applied on listing by MSE
     * @param subjectLength maximum length of message subject in returned
     *            listing or <code>0</code> for default value
     * @param maxListCount maximum number of items returned or <code>0</code>
     *            for default value
     * @param listStartOffset index of first item returned or <code>0</code> for
     *            default value
     * @return <code>true</code> if request has been sent, <code>false</code>
     *         otherwise
     * @throws IllegalArgumentException if subjectLength is outside allowed
     *             range [0..255] or either maxListCount or listStartOffset are
     *             outside allowed range [0..65535]
     */
    public boolean getMessagesListing(String folder, int parameters, MessagesFilter filter,
            int subjectLength, int maxListCount, int listStartOffset) {

        if (mObexSession == null) {
            return false;
        }

        BluetoothMasRequest request = new BluetoothMasRequestGetMessagesListing(folder,
                parameters, filter, subjectLength, maxListCount, listStartOffset);
        return mObexSession.makeRequest(request);
    }

    /**
     * Gets number of messages in current folder
     * <p>
     * Upon completion callback handler will receive
     * {@link #EVENT_GET_MESSAGES_LISTING_SIZE}
     *
     * @return <code>true</code> if request has been sent, <code>false</code>
     *         otherwise
     */
    public boolean getMessagesListingSize() {
        if (mObexSession == null) {
            return false;
        }

        BluetoothMasRequest request = new BluetoothMasRequestGetMessagesListingSize();
        return mObexSession.makeRequest(request);
    }

    /**
     * Retrieves message from MSE
     * <p>
     * Upon completion callback handler will receive {@link #EVENT_GET_MESSAGE}
     *
     * @param handle handle of message to retrieve
     * @param charset {@link CharsetType} object corresponding to
     *            <code>Charset</code> application parameter in MAP
     *            specification
     * @param attachment corresponds to <code>Attachment</code> application
     *            parameter in MAP specification
     * @return <code>true</code> if request has been sent, <code>false</code>
     *         otherwise
     */
    public boolean getMessage(String handle, CharsetType charset, boolean attachment) {
        if (mObexSession == null) {
            return false;
        }

        try {
            /* just to validate */
            new BigInteger(handle, 16);
        } catch (NumberFormatException e) {
            return false;
        }

        BluetoothMasRequest request = new BluetoothMasRequestGetMessage(handle, charset,
                attachment);
        return mObexSession.makeRequest(request);
    }

    /**
     * Sets read status of message on MSE
     * <p>
     * Upon completion callback handler will receive
     * {@link #EVENT_SET_MESSAGE_STATUS}
     *
     * @param handle handle of message
     * @param read <code>true</code> for "read", <code>false</code> for "unread"
     * @return <code>true</code> if request has been sent, <code>false</code>
     *         otherwise
     */
    public boolean setMessageReadStatus(String handle, boolean read) {
        if (mObexSession == null) {
            return false;
        }

        try {
            /* just to validate */
            new BigInteger(handle, 16);
        } catch (NumberFormatException e) {
            return false;
        }

        BluetoothMasRequest request = new BluetoothMasRequestSetMessageStatus(handle,
                StatusIndicator.READ, read);
        return mObexSession.makeRequest(request);
    }

    /**
     * Sets deleted status of message on MSE
     * <p>
     * Upon completion callback handler will receive
     * {@link #EVENT_SET_MESSAGE_STATUS}
     *
     * @param handle handle of message
     * @param deleted <code>true</code> for "deleted", <code>false</code> for
     *            "undeleted"
     * @return <code>true</code> if request has been sent, <code>false</code>
     *         otherwise
     */
    public boolean setMessageDeletedStatus(String handle, boolean deleted) {
        if (mObexSession == null) {
            return false;
        }

        try {
            /* just to validate */
            new BigInteger(handle, 16);
        } catch (NumberFormatException e) {
            return false;
        }

        BluetoothMasRequest request = new BluetoothMasRequestSetMessageStatus(handle,
                StatusIndicator.DELETED, deleted);
        return mObexSession.makeRequest(request);
    }

    /**
     * Pushes new message to MSE
     * <p>
     * Upon completion callback handler will receive {@link #EVENT_PUSH_MESSAGE}
     *
     * @param folder name of sub-folder to push to or <code>null</code> for
     *            current folder
     * @param charset {@link CharsetType} object corresponding to
     *            <code>Charset</code> application parameter in MAP
     *            specification
     * @return <code>true</code> if request has been sent, <code>false</code>
     *         otherwise
     */
    public boolean pushMessage(String folder, BluetoothMapBmessage bmsg, CharsetType charset) {
        return pushMessage(folder, bmsg, charset, false, false);
    }

    /**
     * Pushes new message to MSE
     * <p>
     * Upon completion callback handler will receive {@link #EVENT_PUSH_MESSAGE}
     *
     * @param folder name of sub-folder to push to or <code>null</code> for
     *            current folder
     * @param bmsg {@link BluetoothMapBmessage} object representing message to
     *            be pushed
     * @param charset {@link CharsetType} object corresponding to
     *            <code>Charset</code> application parameter in MAP
     *            specification
     * @param transparent corresponds to <code>Transparent</code> application
     *            parameter in MAP specification
     * @param retry corresponds to <code>Transparent</code> application
     *            parameter in MAP specification
     * @return <code>true</code> if request has been sent, <code>false</code>
     *         otherwise
     */
    public boolean pushMessage(String folder, BluetoothMapBmessage bmsg, CharsetType charset,
            boolean transparent, boolean retry) {
        if (mObexSession == null) {
            return false;
        }

        String bmsgString = BluetoothMapBmessageBuilder.createBmessage(bmsg);

        BluetoothMasRequest request =
                new BluetoothMasRequestPushMessage(folder, bmsgString, charset, transparent, retry);
        return mObexSession.makeRequest(request);
    }

    /**
     * Requests MSE to initiate ubdate of inbox
     * <p>
     * Upon completion callback handler will receive {@link #EVENT_UPDATE_INBOX}
     *
     * @return <code>true</code> if request has been sent, <code>false</code>
     *         otherwise
     */
    public boolean updateInbox() {
        if (mObexSession == null) {
            return false;
        }

        BluetoothMasRequest request = new BluetoothMasRequestUpdateInbox();
        return mObexSession.makeRequest(request);
    }
}