BluetoothOppRfcommListener.java revision 6769b59d715ea98bd72eafcfea9acd2714a887da
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;
38import java.net.SocketException;
39
40import android.bluetooth.BluetoothServerSocket;
41import android.bluetooth.BluetoothSocket;
42import android.os.Handler;
43import android.os.Message;
44import android.util.Log;
45
46/**
47 * This class listens on OPUSH channel for incoming connection
48 */
49public class BluetoothOppRfcommListener {
50    private static final String TAG = "BtOpp RfcommListener";
51
52    private volatile boolean mInterrupted;
53
54    private Thread mSocketAcceptThread;
55
56    private Handler mCallback;
57
58    private static final int ACCEPT_WAIT_TIMEOUT = 5000;
59
60    private static final int CREATE_RETRY_TIME = 10;
61
62    public static final int DEFAULT_OPP_CHANNEL = 12;
63
64    public static final int MSG_INCOMING_BTOPP_CONNECTION = 100;
65
66    private int mBtOppRfcommChannel = -1;
67
68    public BluetoothOppRfcommListener() {
69        this(DEFAULT_OPP_CHANNEL);
70    }
71
72    public BluetoothOppRfcommListener(int channel) {
73        mBtOppRfcommChannel = channel;
74    }
75
76    public synchronized boolean start(Handler callback) {
77        if (mSocketAcceptThread == null) {
78            mCallback = callback;
79            if (Constants.LOGV) {
80                Log.v(TAG, "create mSocketAcceptThread");
81            }
82            mSocketAcceptThread = new Thread(TAG) {
83
84                public void run() {
85                    if (Constants.LOGV) {
86                        Log.v(TAG, "BluetoothOppRfcommListener thread starting");
87                    }
88                    if (Constants.USE_TCP_DEBUG) {
89                        ServerSocket mServerSocket = null;
90                        try {
91                            if (Constants.LOGVV) {
92                                Log.v(TAG, "Create ServerSocket on port "
93                                        + Constants.TCP_DEBUG_PORT);
94                            }
95
96                            mServerSocket = new ServerSocket(Constants.TCP_DEBUG_PORT, 1);
97
98                        } catch (IOException e) {
99                            Log.e(TAG, "Error listing on port" + Constants.TCP_DEBUG_PORT);
100                            mInterrupted = true;
101                        }
102                        while (!mInterrupted) {
103                            try {
104                                mServerSocket.setSoTimeout(ACCEPT_WAIT_TIMEOUT);
105                                Socket clientSocket = mServerSocket.accept();
106
107                                if (clientSocket == null) {
108                                    if (Constants.LOGVV) {
109                                        Log.v(TAG, "incomming connection time out");
110                                    }
111                                } else {
112                                    if (Constants.LOGV) {
113                                        Log.v(TAG, "TCP Socket connected!");
114                                    }
115                                    Log.d(TAG, "remote addr is "
116                                            + clientSocket.getRemoteSocketAddress());
117                                    TestTcpTransport transport = new TestTcpTransport(clientSocket);
118                                    Message msg = Message.obtain();
119                                    msg.setTarget(mCallback);
120                                    msg.what = MSG_INCOMING_BTOPP_CONNECTION;
121                                    msg.obj = transport;
122                                    msg.sendToTarget();
123                                }
124                            } catch (SocketException e) {
125                                Log.e(TAG, "Error accept connection " + e);
126                            } catch (IOException e) {
127                                Log.e(TAG, "Error accept connection " + e);
128                            }
129                        }
130                        if (Constants.LOGV) {
131                            Log.v(TAG, "TCP listen thread finished");
132                        }
133                        try {
134                            mServerSocket.close();
135                        } catch (IOException e) {
136                            Log.e(TAG, "Error close mServerSocker " + e);
137                        }
138                    } else {
139                        BluetoothServerSocket mServerSocket = null;
140                        boolean serverOK = true;
141
142                        /*
143                         * it's possible that create will fail in some cases.
144                         * retry for 10 times
145                         */
146                        if (Constants.LOGVV) {
147                            Log.v(TAG, "Create BluetoothServerSocket on channel "
148                                    + mBtOppRfcommChannel);
149                        }
150                        for (int i = 0; i < CREATE_RETRY_TIME && !mInterrupted; i++) {
151                            try {
152                                mServerSocket = BluetoothServerSocket
153                                        .listenUsingInsecureRfcommOn(mBtOppRfcommChannel);
154                            } catch (IOException e1) {
155                                Log.d(TAG, "Error create RfcommServerSocket " + e1);
156                                serverOK = false;
157                            }
158                            if (!serverOK) {
159                                synchronized (this) {
160                                    try {
161                                        if (Constants.LOGVV) {
162                                            Log.v(TAG, "wait 3 seconds");
163                                        }
164                                        Thread.sleep(3000);
165                                    } catch (InterruptedException e) {
166                                        Log.e(TAG, "socketAcceptThread thread was interrupted (3)");
167                                        mInterrupted = true;
168                                    }
169                                }
170                            } else {
171                                break;
172                            }
173                        }
174                        if (!serverOK) {
175                            Log.e(TAG, "Error start listening after " + CREATE_RETRY_TIME + " try");
176                            mInterrupted = true;
177                        }
178
179                        BluetoothSocket clientSocket;
180                        while (!mInterrupted) {
181                            try {
182                                clientSocket = mServerSocket.accept(ACCEPT_WAIT_TIMEOUT);
183                                if (Constants.LOGVV) {
184                                    Log.v(TAG, "BluetoothSocket connected!");
185                                    Log.v(TAG, "remote addr is " + clientSocket.getAddress());
186                                }
187                                BluetoothOppRfcommTransport transport = new BluetoothOppRfcommTransport(
188                                        clientSocket);
189                                Message msg = Message.obtain();
190                                msg.setTarget(mCallback);
191                                msg.what = MSG_INCOMING_BTOPP_CONNECTION;
192                                msg.obj = transport;
193                                msg.sendToTarget();
194                            } catch (IOException e) {
195                                if (Constants.LOGVV) {
196                                    Log.v(TAG, "Error accept connection " + e);
197                                }
198                            }
199                        }
200                        try {
201                            if (mServerSocket != null) {
202                                if (Constants.LOGVV) {
203                                    Log.v(TAG, "close mServerSocket");
204                                }
205                                mServerSocket.close();
206                                //TODO
207                                //mServerSocket.destroy();
208                            }
209                        } catch (IOException e) {
210                            Log.e(TAG, "Errro close mServerSocket " + e);
211                        }
212                        if (Constants.LOGV) {
213                            Log.v(TAG, "BluetoothSocket listen thread finished");
214                        }
215                    }
216                }
217            };
218            mInterrupted = false;
219            mSocketAcceptThread.start();
220        }
221        return true;
222    }
223
224    public synchronized void stop() {
225        if (mSocketAcceptThread != null) {
226            if (Constants.LOGV) {
227                Log.v(TAG, "stopping Connect Thread");
228            }
229            mInterrupted = true;
230            try {
231                mSocketAcceptThread.interrupt();
232                if (Constants.LOGVV) {
233                    Log.v(TAG, "waiting for thread to terminate");
234                }
235                mSocketAcceptThread.join();
236                mSocketAcceptThread = null;
237                mCallback = null;
238            } catch (InterruptedException e) {
239                if (Constants.LOGVV) {
240                    Log.v(TAG, "Interrupted waiting for Accept Thread to join");
241                }
242            }
243        }
244    }
245}
246