BluetoothOppRfcommListener.java revision d288c0dac06748780916bf438b7c84482545672f
1/*
2 * Copyright (c) 2008-2009, Motorola, Inc.
3 *
4 * All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions are met:
8 *
9 * - Redistributions of source code must retain the above copyright notice,
10 * this list of conditions and the following disclaimer.
11 *
12 * - Redistributions in binary form must reproduce the above copyright notice,
13 * this list of conditions and the following disclaimer in the documentation
14 * and/or other materials provided with the distribution.
15 *
16 * - Neither the name of the Motorola, Inc. nor the names of its contributors
17 * may be used to endorse or promote products derived from this software
18 * without specific prior written permission.
19 *
20 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
24 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30 * POSSIBILITY OF SUCH DAMAGE.
31 */
32
33package com.android.bluetooth.opp;
34
35import java.io.IOException;
36import java.net.ServerSocket;
37import java.net.Socket;
38
39import android.bluetooth.BluetoothAdapter;
40import android.bluetooth.BluetoothServerSocket;
41import android.bluetooth.BluetoothSocket;
42import android.bluetooth.BluetoothUuid;
43import android.os.Handler;
44import android.os.Message;
45import android.util.Log;
46
47/**
48 * This class listens on OPUSH channel for incoming connection
49 */
50public class BluetoothOppRfcommListener {
51    private static final String TAG = "BtOppRfcommListener";
52
53    private static final boolean V = Constants.VERBOSE;
54
55    public static final int MSG_INCOMING_BTOPP_CONNECTION = 100;
56    private static final int JOIN_TIMEOUT_MS=2000;
57
58    private volatile boolean mInterrupted;
59    private volatile boolean mFinish;
60
61    private Thread mSocketAcceptThread;
62
63    private Handler mCallback;
64
65    private static final int CREATE_RETRY_TIME = 10;
66
67    private final BluetoothAdapter mAdapter;
68
69    private BluetoothServerSocket mBtServerSocket = null;
70
71    private ServerSocket mTcpServerSocket = null;
72
73    public BluetoothOppRfcommListener(BluetoothAdapter adapter) {
74        mAdapter = adapter;
75    }
76
77
78    public synchronized boolean start(Handler callback) {
79        if (mSocketAcceptThread == null) {
80            mCallback = callback;
81
82            mSocketAcceptThread = new Thread(TAG) {
83
84                public void run() {
85                    if (Constants.USE_TCP_DEBUG) {
86                        try {
87                            if (V) Log.v(TAG, "Create TCP ServerSocket");
88                            mTcpServerSocket = new ServerSocket(Constants.TCP_DEBUG_PORT, 1);
89                        } catch (IOException e) {
90                            Log.e(TAG, "Error listing on port" + Constants.TCP_DEBUG_PORT);
91                            mInterrupted = true;
92                        }
93                        while (!mInterrupted) {
94                            try {
95                                Socket clientSocket = mTcpServerSocket.accept();
96
97                                if (V) Log.v(TAG, "Socket connected!");
98                                TestTcpTransport transport = new TestTcpTransport(clientSocket);
99                                Message msg = Message.obtain();
100                                msg.setTarget(mCallback);
101                                msg.what = MSG_INCOMING_BTOPP_CONNECTION;
102                                msg.obj = transport;
103                                msg.sendToTarget();
104
105                            } catch (IOException e) {
106                                Log.e(TAG, "Error accept connection " + e);
107                            }
108                        }
109                        if (V) Log.v(TAG, "TCP listen thread finished");
110                    } else {
111                        boolean serverOK = true;
112
113                        /*
114                         * it's possible that create will fail in some cases.
115                         * retry for 10 times
116                         */
117                        for (int i = 0; i < CREATE_RETRY_TIME && !mInterrupted; i++) {
118                            try {
119                                if (V) Log.v(TAG, "Starting RFCOMM listener....");
120                                mBtServerSocket = mAdapter.listenUsingInsecureRfcommWithServiceRecord("OBEX Object Push", BluetoothUuid.ObexObjectPush.getUuid());
121                                if (V) Log.v(TAG, "Started RFCOMM listener....");
122                            } catch (IOException e1) {
123                                Log.e(TAG, "Error create RfcommServerSocket " + e1);
124                                serverOK = false;
125                            }
126                            if (!serverOK) {
127                                synchronized (this) {
128                                    try {
129                                        if (V) Log.v(TAG, "Wait 3 seconds");
130                                        Thread.sleep(3000);
131                                    } catch (InterruptedException e) {
132                                        Log.e(TAG, "socketAcceptThread thread was interrupted (3)");
133                                        mInterrupted = true;
134                                    }
135                                }
136                            } else {
137                                break;
138                            }
139                        }
140                        if (!serverOK) {
141                            Log.e(TAG, "Error start listening after " + CREATE_RETRY_TIME + " try");
142                            mInterrupted = true;
143                        }
144                        if (!mInterrupted) {
145                            Log.i(TAG, "Accept thread started.");
146                        }
147                        BluetoothSocket clientSocket;
148                        while (!mInterrupted) {
149                            try {
150                                if (V) Log.v(TAG, "Accepting connection...");
151                                if (mBtServerSocket == null) {
152
153                                }
154                                BluetoothServerSocket sSocket = mBtServerSocket;
155                                if (sSocket ==null) {
156                                    mInterrupted = true;
157
158                                } else {
159                                    clientSocket = mBtServerSocket.accept();
160                                    if (V) Log.v(TAG, "Accepted connection from "
161                                        + clientSocket.getRemoteDevice());
162                                    BluetoothOppRfcommTransport transport = new BluetoothOppRfcommTransport(
163                                        clientSocket);
164                                    Message msg = Message.obtain();
165                                    msg.setTarget(mCallback);
166                                    msg.what = MSG_INCOMING_BTOPP_CONNECTION;
167                                    msg.obj = transport;
168                                    msg.sendToTarget();
169                                }
170                            } catch (IOException e) {
171                                Log.e(TAG, "Error accept connection " + e);
172                            }
173                        }
174                        Log.i(TAG, "BluetoothSocket listen thread finished");
175                    }
176                }
177            };
178            mInterrupted = false;
179            if(!Constants.USE_TCP_SIMPLE_SERVER) {
180                mSocketAcceptThread.start();
181            }
182        }
183        return true;
184    }
185
186    public synchronized void stop() {
187        if (mSocketAcceptThread != null) {
188            Log.i(TAG, "stopping Accept Thread");
189
190            mInterrupted = true;
191             if (Constants.USE_TCP_DEBUG) {
192                if (V) Log.v(TAG, "close mTcpServerSocket");
193                if (mTcpServerSocket != null) {
194                    try {
195                        mTcpServerSocket.close();
196                        mTcpServerSocket = null;
197                    } catch (IOException e) {
198                        Log.e(TAG, "Error close mTcpServerSocket");
199                    }
200                }
201            } else {
202                if (V) Log.v(TAG, "close mBtServerSocket");
203
204                if (mBtServerSocket != null) {
205                    try {
206                        mBtServerSocket.close();
207                        mBtServerSocket = null;
208                    } catch (IOException e) {
209                        Log.e(TAG, "Error close mBtServerSocket");
210                    }
211                }
212            }
213            try {
214                mSocketAcceptThread.interrupt();
215                if (V) Log.v(TAG, "waiting for thread to terminate");
216                //mSocketAcceptThread.join(JOIN_TIMEOUT_MS);
217                mSocketAcceptThread.join();
218                if (V) Log.v(TAG, "done waiting for thread to terminate");
219                mSocketAcceptThread = null;
220                mCallback = null;
221            } catch (InterruptedException e) {
222                if (V) Log.v(TAG, "Interrupted waiting for Accept Thread to join");
223            }
224        }
225    }
226}
227