blob: 8029a1a25ce12b678ad83f8e85c9b118c4c816f9 [file] [log] [blame]
Nick Pelly0b6955a2009-05-26 19:13:43 -07001/*
Zhihai Xufa0fd392012-10-23 17:31:56 -07002 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
Nick Pelly0b6955a2009-05-26 19:13:43 -070015 */
16
17package android.bluetooth;
18
zzy3b147b72012-04-03 19:48:32 -070019import android.os.IBinder;
Nick Pelly16fb88a2009-10-07 07:44:03 +020020import android.os.ParcelUuid;
zzy3b147b72012-04-03 19:48:32 -070021import android.os.ParcelFileDescriptor;
Nick Pelly16fb88a2009-10-07 07:44:03 +020022import android.os.RemoteException;
zzy3b147b72012-04-03 19:48:32 -070023import android.os.ServiceManager;
Nick Pelly16fb88a2009-10-07 07:44:03 +020024import android.util.Log;
25
Nick Pelly0b6955a2009-05-26 19:13:43 -070026import java.io.Closeable;
zzy3b147b72012-04-03 19:48:32 -070027import java.io.FileDescriptor;
28import java.io.FileInputStream;
29import java.io.FileOutputStream;
Nick Pelly0b6955a2009-05-26 19:13:43 -070030import java.io.IOException;
31import java.io.InputStream;
32import java.io.OutputStream;
zzy3b147b72012-04-03 19:48:32 -070033import java.util.List;
zzyb49a8962012-10-11 14:52:43 -070034import java.util.UUID;
zzy3b147b72012-04-03 19:48:32 -070035import android.net.LocalSocket;
36import java.nio.ByteOrder;
37import java.nio.ByteBuffer;
Nick Pelly0b6955a2009-05-26 19:13:43 -070038/**
Nick Pelly45e27042009-08-19 11:00:00 -070039 * A connected or connecting Bluetooth socket.
Nick Pelly0b6955a2009-05-26 19:13:43 -070040 *
Nick Pelly45e27042009-08-19 11:00:00 -070041 * <p>The interface for Bluetooth Sockets is similar to that of TCP sockets:
42 * {@link java.net.Socket} and {@link java.net.ServerSocket}. On the server
43 * side, use a {@link BluetoothServerSocket} to create a listening server
Scott Main9fab0ae2009-11-03 18:17:59 -080044 * socket. When a connection is accepted by the {@link BluetoothServerSocket},
45 * it will return a new {@link BluetoothSocket} to manage the connection.
Jake Hambyf51eada2010-09-21 13:39:53 -070046 * On the client side, use a single {@link BluetoothSocket} to both initiate
Scott Main9fab0ae2009-11-03 18:17:59 -080047 * an outgoing connection and to manage the connection.
Nick Pelly0b6955a2009-05-26 19:13:43 -070048 *
Scott Main9fab0ae2009-11-03 18:17:59 -080049 * <p>The most common type of Bluetooth socket is RFCOMM, which is the type
50 * supported by the Android APIs. RFCOMM is a connection-oriented, streaming
51 * transport over Bluetooth. It is also known as the Serial Port Profile (SPP).
Nick Pelly0b6955a2009-05-26 19:13:43 -070052 *
Scott Main9fab0ae2009-11-03 18:17:59 -080053 * <p>To create a {@link BluetoothSocket} for connecting to a known device, use
54 * {@link BluetoothDevice#createRfcommSocketToServiceRecord
55 * BluetoothDevice.createRfcommSocketToServiceRecord()}.
56 * Then call {@link #connect()} to attempt a connection to the remote device.
57 * This call will block until a connection is established or the connection
58 * fails.
Nick Pelly45e27042009-08-19 11:00:00 -070059 *
Scott Main9fab0ae2009-11-03 18:17:59 -080060 * <p>To create a {@link BluetoothSocket} as a server (or "host"), see the
61 * {@link BluetoothServerSocket} documentation.
Nick Pelly45e27042009-08-19 11:00:00 -070062 *
Scott Main9fab0ae2009-11-03 18:17:59 -080063 * <p>Once the socket is connected, whether initiated as a client or accepted
64 * as a server, open the IO streams by calling {@link #getInputStream} and
65 * {@link #getOutputStream} in order to retrieve {@link java.io.InputStream}
66 * and {@link java.io.OutputStream} objects, respectively, which are
67 * automatically connected to the socket.
68 *
69 * <p>{@link BluetoothSocket} is thread
Nick Pelly45e27042009-08-19 11:00:00 -070070 * safe. In particular, {@link #close} will always immediately abort ongoing
71 * operations and close the socket.
Nick Pellycf440592009-09-08 10:12:06 -070072 *
Scott Main9fab0ae2009-11-03 18:17:59 -080073 * <p class="note"><strong>Note:</strong>
74 * Requires the {@link android.Manifest.permission#BLUETOOTH} permission.
75 *
Joe Fernandez3aef8e1d2011-12-20 10:38:34 -080076 * <div class="special reference">
77 * <h3>Developer Guides</h3>
78 * <p>For more information about using Bluetooth, read the
79 * <a href="{@docRoot}guide/topics/wireless/bluetooth.html">Bluetooth</a> developer guide.</p>
80 * </div>
81 *
Scott Main9fab0ae2009-11-03 18:17:59 -080082 * {@see BluetoothServerSocket}
83 * {@see java.io.InputStream}
84 * {@see java.io.OutputStream}
Nick Pelly0b6955a2009-05-26 19:13:43 -070085 */
86public final class BluetoothSocket implements Closeable {
Nick Pelly16fb88a2009-10-07 07:44:03 +020087 private static final String TAG = "BluetoothSocket";
Matthew Xie563e4142012-10-09 22:10:37 -070088 private static final boolean DBG = true;
89 private static final boolean VDBG = false;
Nick Pelly16fb88a2009-10-07 07:44:03 +020090
Nick Pelly24bb9b82009-10-02 20:34:18 -070091 /** @hide */
92 public static final int MAX_RFCOMM_CHANNEL = 30;
93
Nick Pelly45e27042009-08-19 11:00:00 -070094 /** Keep TYPE_ fields in sync with BluetoothSocket.cpp */
Nick Pelly6a669fa2009-06-02 15:57:18 -070095 /*package*/ static final int TYPE_RFCOMM = 1;
96 /*package*/ static final int TYPE_SCO = 2;
97 /*package*/ static final int TYPE_L2CAP = 3;
98
Nick Pelly24bb9b82009-10-02 20:34:18 -070099 /*package*/ static final int EBADFD = 77;
100 /*package*/ static final int EADDRINUSE = 98;
101
zzy3b147b72012-04-03 19:48:32 -0700102 /*package*/ static final int SEC_FLAG_ENCRYPT = 1;
103 /*package*/ static final int SEC_FLAG_AUTH = 1 << 1;
104
Nick Pelly6a669fa2009-06-02 15:57:18 -0700105 private final int mType; /* one of TYPE_RFCOMM etc */
zzy3b147b72012-04-03 19:48:32 -0700106 private BluetoothDevice mDevice; /* remote device */
107 private String mAddress; /* remote address */
Nick Pelly0b6955a2009-05-26 19:13:43 -0700108 private final boolean mAuth;
109 private final boolean mEncrypt;
110 private final BluetoothInputStream mInputStream;
111 private final BluetoothOutputStream mOutputStream;
zzy3b147b72012-04-03 19:48:32 -0700112 private final ParcelUuid mUuid;
113 private ParcelFileDescriptor mPfd;
114 private LocalSocket mSocket;
115 private InputStream mSocketIS;
116 private OutputStream mSocketOS;
Nick Pelly16fb88a2009-10-07 07:44:03 +0200117 private int mPort; /* RFCOMM channel or L2CAP psm */
zzy3b147b72012-04-03 19:48:32 -0700118 private int mFd;
119 private String mServiceName;
zzy3b147b72012-04-03 19:48:32 -0700120 private static int PROXY_CONNECTION_TIMEOUT = 5000;
121
122 private static int SOCK_SIGNAL_SIZE = 16;
Nick Pelly0b6955a2009-05-26 19:13:43 -0700123
Matthew Xieceb6c9f2011-05-03 19:50:20 -0700124 private enum SocketState {
125 INIT,
126 CONNECTED,
zzy3b147b72012-04-03 19:48:32 -0700127 LISTENING,
128 CLOSED,
Matthew Xieceb6c9f2011-05-03 19:50:20 -0700129 }
Nick Pelly71c3c782009-09-02 11:51:35 -0700130
Matthew Xieceb6c9f2011-05-03 19:50:20 -0700131 /** prevents all native calls after destroyNative() */
zzy3b147b72012-04-03 19:48:32 -0700132 private volatile SocketState mSocketState;
Matthew Xieceb6c9f2011-05-03 19:50:20 -0700133
134 /** protects mSocketState */
zzy3b147b72012-04-03 19:48:32 -0700135 //private final ReentrantReadWriteLock mLock;
Nick Pelly0b6955a2009-05-26 19:13:43 -0700136
137 /**
Nick Pellybd022f42009-08-14 18:33:38 -0700138 * Construct a BluetoothSocket.
Nick Pelly6a669fa2009-06-02 15:57:18 -0700139 * @param type type of socket
Nick Pelly0b6955a2009-05-26 19:13:43 -0700140 * @param fd fd to use for connected socket, or -1 for a new socket
141 * @param auth require the remote device to be authenticated
142 * @param encrypt require the connection to be encrypted
Nick Pellybd022f42009-08-14 18:33:38 -0700143 * @param device remote device that this socket can connect to
Nick Pelly0b6955a2009-05-26 19:13:43 -0700144 * @param port remote port
Nick Pelly16fb88a2009-10-07 07:44:03 +0200145 * @param uuid SDP uuid
Nick Pelly0b6955a2009-05-26 19:13:43 -0700146 * @throws IOException On error, for example Bluetooth not available, or
Jake Hambyf51eada2010-09-21 13:39:53 -0700147 * insufficient privileges
Nick Pelly0b6955a2009-05-26 19:13:43 -0700148 */
Nick Pellybd022f42009-08-14 18:33:38 -0700149 /*package*/ BluetoothSocket(int type, int fd, boolean auth, boolean encrypt,
Nick Pelly16fb88a2009-10-07 07:44:03 +0200150 BluetoothDevice device, int port, ParcelUuid uuid) throws IOException {
151 if (type == BluetoothSocket.TYPE_RFCOMM && uuid == null && fd == -1) {
Nick Pelly24bb9b82009-10-02 20:34:18 -0700152 if (port < 1 || port > MAX_RFCOMM_CHANNEL) {
153 throw new IOException("Invalid RFCOMM channel: " + port);
154 }
155 }
zzyb49a8962012-10-11 14:52:43 -0700156 if(uuid != null)
157 mUuid = uuid;
158 else mUuid = new ParcelUuid(new UUID(0, 0));
Nick Pelly6a669fa2009-06-02 15:57:18 -0700159 mType = type;
Nick Pelly0b6955a2009-05-26 19:13:43 -0700160 mAuth = auth;
161 mEncrypt = encrypt;
Nick Pellybd022f42009-08-14 18:33:38 -0700162 mDevice = device;
zzy3b147b72012-04-03 19:48:32 -0700163 mPort = port;
164 mFd = fd;
165
166 mSocketState = SocketState.INIT;
167
Nick Pellybd022f42009-08-14 18:33:38 -0700168 if (device == null) {
zzy3b147b72012-04-03 19:48:32 -0700169 // Server socket
170 mAddress = BluetoothAdapter.getDefaultAdapter().getAddress();
Nick Pellybd022f42009-08-14 18:33:38 -0700171 } else {
zzy3b147b72012-04-03 19:48:32 -0700172 // Remote socket
Nick Pellybd022f42009-08-14 18:33:38 -0700173 mAddress = device.getAddress();
174 }
Nick Pelly0b6955a2009-05-26 19:13:43 -0700175 mInputStream = new BluetoothInputStream(this);
176 mOutputStream = new BluetoothOutputStream(this);
zzy3b147b72012-04-03 19:48:32 -0700177 }
178 private BluetoothSocket(BluetoothSocket s) {
179 mUuid = s.mUuid;
180 mType = s.mType;
181 mAuth = s.mAuth;
182 mEncrypt = s.mEncrypt;
183 mPort = s.mPort;
184 mInputStream = new BluetoothInputStream(this);
185 mOutputStream = new BluetoothOutputStream(this);
186 mServiceName = s.mServiceName;
187 }
188 private BluetoothSocket acceptSocket(String RemoteAddr) throws IOException {
189 BluetoothSocket as = new BluetoothSocket(this);
190 as.mSocketState = SocketState.CONNECTED;
191 FileDescriptor[] fds = mSocket.getAncillaryFileDescriptors();
Matthew Xie563e4142012-10-09 22:10:37 -0700192 if (VDBG) Log.d(TAG, "socket fd passed by stack fds: " + fds);
zzy3b147b72012-04-03 19:48:32 -0700193 if(fds == null || fds.length != 1) {
194 Log.e(TAG, "socket fd passed from stack failed, fds: " + fds);
195 throw new IOException("bt socket acept failed");
196 }
197 as.mSocket = new LocalSocket(fds[0]);
198 as.mSocketIS = as.mSocket.getInputStream();
199 as.mSocketOS = as.mSocket.getOutputStream();
200 as.mAddress = RemoteAddr;
201 as.mDevice = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(RemoteAddr);
202 return as;
203 }
Nick Pellybd022f42009-08-14 18:33:38 -0700204 /**
Nick Pelly16fb88a2009-10-07 07:44:03 +0200205 * Construct a BluetoothSocket from address. Used by native code.
Nick Pellybd022f42009-08-14 18:33:38 -0700206 * @param type type of socket
207 * @param fd fd to use for connected socket, or -1 for a new socket
208 * @param auth require the remote device to be authenticated
209 * @param encrypt require the connection to be encrypted
210 * @param address remote device that this socket can connect to
211 * @param port remote port
212 * @throws IOException On error, for example Bluetooth not available, or
Jake Hambyf51eada2010-09-21 13:39:53 -0700213 * insufficient privileges
Nick Pellybd022f42009-08-14 18:33:38 -0700214 */
215 private BluetoothSocket(int type, int fd, boolean auth, boolean encrypt, String address,
216 int port) throws IOException {
Nick Pelly16fb88a2009-10-07 07:44:03 +0200217 this(type, fd, auth, encrypt, new BluetoothDevice(address), port, null);
Nick Pellybd022f42009-08-14 18:33:38 -0700218 }
219
Nick Pelly45e27042009-08-19 11:00:00 -0700220 /** @hide */
Nick Pelly0b6955a2009-05-26 19:13:43 -0700221 @Override
222 protected void finalize() throws Throwable {
223 try {
224 close();
225 } finally {
226 super.finalize();
227 }
228 }
zzy3b147b72012-04-03 19:48:32 -0700229 private int getSecurityFlags() {
230 int flags = 0;
231 if(mAuth)
232 flags |= SEC_FLAG_AUTH;
233 if(mEncrypt)
234 flags |= SEC_FLAG_ENCRYPT;
235 return flags;
Nick Pelly0b6955a2009-05-26 19:13:43 -0700236 }
237
238 /**
Nick Pelly45e27042009-08-19 11:00:00 -0700239 * Get the remote device this socket is connecting, or connected, to.
240 * @return remote device
Nick Pelly0b6955a2009-05-26 19:13:43 -0700241 */
Nick Pellybd022f42009-08-14 18:33:38 -0700242 public BluetoothDevice getRemoteDevice() {
243 return mDevice;
Nick Pelly0b6955a2009-05-26 19:13:43 -0700244 }
245
246 /**
247 * Get the input stream associated with this socket.
Nick Pelly45e27042009-08-19 11:00:00 -0700248 * <p>The input stream will be returned even if the socket is not yet
Nick Pelly0b6955a2009-05-26 19:13:43 -0700249 * connected, but operations on that stream will throw IOException until
250 * the associated socket is connected.
251 * @return InputStream
252 */
253 public InputStream getInputStream() throws IOException {
254 return mInputStream;
255 }
256
257 /**
258 * Get the output stream associated with this socket.
Nick Pelly45e27042009-08-19 11:00:00 -0700259 * <p>The output stream will be returned even if the socket is not yet
Nick Pelly0b6955a2009-05-26 19:13:43 -0700260 * connected, but operations on that stream will throw IOException until
261 * the associated socket is connected.
262 * @return OutputStream
263 */
264 public OutputStream getOutputStream() throws IOException {
265 return mOutputStream;
266 }
267
Nick Pelly24bb9b82009-10-02 20:34:18 -0700268 /**
Matthew Xieceb6c9f2011-05-03 19:50:20 -0700269 * Get the connection status of this socket, ie, whether there is an active connection with
270 * remote device.
271 * @return true if connected
272 * false if not connected
273 */
274 public boolean isConnected() {
zzy3b147b72012-04-03 19:48:32 -0700275 return mSocketState == SocketState.CONNECTED;
276 }
277
278 /*package*/ void setServiceName(String name) {
279 mServiceName = name;
280 }
281
282 /**
283 * Attempt to connect to a remote device.
284 * <p>This method will block until a connection is made or the connection
285 * fails. If this method returns without an exception then this socket
286 * is now connected.
287 * <p>Creating new connections to
288 * remote Bluetooth devices should not be attempted while device discovery
289 * is in progress. Device discovery is a heavyweight procedure on the
290 * Bluetooth adapter and will significantly slow a device connection.
291 * Use {@link BluetoothAdapter#cancelDiscovery()} to cancel an ongoing
292 * discovery. Discovery is not managed by the Activity,
293 * but is run as a system service, so an application should always call
294 * {@link BluetoothAdapter#cancelDiscovery()} even if it
295 * did not directly request a discovery, just to be sure.
296 * <p>{@link #close} can be used to abort this call from another thread.
297 * @throws IOException on error, for example connection failure
298 */
299 public void connect() throws IOException {
300 if (mDevice == null) throw new IOException("Connect is called on null device");
301
302 try {
zzy3b147b72012-04-03 19:48:32 -0700303 if (mSocketState == SocketState.CLOSED) throw new IOException("socket closed");
fredc903ac6f2012-04-24 03:59:57 -0700304 IBluetooth bluetoothProxy = BluetoothAdapter.getDefaultAdapter().getBluetoothService(null);
fredc0f420372012-04-12 00:02:00 -0700305 if (bluetoothProxy == null) throw new IOException("Bluetooth is off");
306 mPfd = bluetoothProxy.connectSocket(mDevice, mType,
zzy3b147b72012-04-03 19:48:32 -0700307 mUuid, mPort, getSecurityFlags());
308 synchronized(this)
309 {
Matthew Xie563e4142012-10-09 22:10:37 -0700310 if (DBG) Log.d(TAG, "connect(), SocketState: " + mSocketState + ", mPfd: " + mPfd);
zzy3b147b72012-04-03 19:48:32 -0700311 if (mSocketState == SocketState.CLOSED) throw new IOException("socket closed");
312 if (mPfd == null) throw new IOException("bt socket connect failed");
313 FileDescriptor fd = mPfd.getFileDescriptor();
314 mSocket = new LocalSocket(fd);
315 mSocketIS = mSocket.getInputStream();
316 mSocketOS = mSocket.getOutputStream();
317 }
318 int channel = readInt(mSocketIS);
319 if (channel <= 0)
320 throw new IOException("bt socket connect failed");
321 mPort = channel;
322 waitSocketSignal(mSocketIS);
323 synchronized(this)
324 {
325 if (mSocketState == SocketState.CLOSED)
326 throw new IOException("bt socket closed");
327 mSocketState = SocketState.CONNECTED;
328 }
329 } catch (RemoteException e) {
330 Log.e(TAG, Log.getStackTraceString(new Throwable()));
331 }
Matthew Xieceb6c9f2011-05-03 19:50:20 -0700332 }
333
334 /**
Nick Pelly24bb9b82009-10-02 20:34:18 -0700335 * Currently returns unix errno instead of throwing IOException,
336 * so that BluetoothAdapter can check the error code for EADDRINUSE
337 */
338 /*package*/ int bindListen() {
zzy3b147b72012-04-03 19:48:32 -0700339 int ret;
340 if (mSocketState == SocketState.CLOSED) return EBADFD;
fredc903ac6f2012-04-24 03:59:57 -0700341 IBluetooth bluetoothProxy = BluetoothAdapter.getDefaultAdapter().getBluetoothService(null);
fredc0f420372012-04-12 00:02:00 -0700342 if (bluetoothProxy == null) {
343 Log.e(TAG, "bindListen fail, reason: bluetooth is off");
344 return -1;
345 }
Nick Pelly71c3c782009-09-02 11:51:35 -0700346 try {
fredc0f420372012-04-12 00:02:00 -0700347 mPfd = bluetoothProxy.createSocketChannel(mType, mServiceName,
zzy3b147b72012-04-03 19:48:32 -0700348 mUuid, mPort, getSecurityFlags());
349 } catch (RemoteException e) {
350 Log.e(TAG, Log.getStackTraceString(new Throwable()));
zzy3b147b72012-04-03 19:48:32 -0700351 return -1;
352 }
353
354 // read out port number
355 try {
356 synchronized(this) {
Matthew Xie563e4142012-10-09 22:10:37 -0700357 if (VDBG) Log.d(TAG, "bindListen(), SocketState: " + mSocketState + ", mPfd: " +
358 mPfd);
zzy3b147b72012-04-03 19:48:32 -0700359 if(mSocketState != SocketState.INIT) return EBADFD;
360 if(mPfd == null) return -1;
361 FileDescriptor fd = mPfd.getFileDescriptor();
Matthew Xie563e4142012-10-09 22:10:37 -0700362 if (VDBG) Log.d(TAG, "bindListen(), new LocalSocket ");
zzy3b147b72012-04-03 19:48:32 -0700363 mSocket = new LocalSocket(fd);
Matthew Xie563e4142012-10-09 22:10:37 -0700364 if (VDBG) Log.d(TAG, "bindListen(), new LocalSocket.getInputStream() ");
zzy3b147b72012-04-03 19:48:32 -0700365 mSocketIS = mSocket.getInputStream();
366 mSocketOS = mSocket.getOutputStream();
367 }
Matthew Xie563e4142012-10-09 22:10:37 -0700368 if (VDBG) Log.d(TAG, "bindListen(), readInt mSocketIS: " + mSocketIS);
zzy3b147b72012-04-03 19:48:32 -0700369 int channel = readInt(mSocketIS);
370 synchronized(this) {
371 if(mSocketState == SocketState.INIT)
372 mSocketState = SocketState.LISTENING;
373 }
Matthew Xie563e4142012-10-09 22:10:37 -0700374 if (VDBG) Log.d(TAG, "channel: " + channel);
zzy3b147b72012-04-03 19:48:32 -0700375 if (mPort == -1) {
376 mPort = channel;
377 } // else ASSERT(mPort == channel)
378 ret = 0;
379 } catch (IOException e) {
380 Log.e(TAG, "bindListen, fail to get port number, exception: " + e);
381 return -1;
382 }
383 return ret;
Nick Pelly71c3c782009-09-02 11:51:35 -0700384 }
385
386 /*package*/ BluetoothSocket accept(int timeout) throws IOException {
zzy3b147b72012-04-03 19:48:32 -0700387 BluetoothSocket acceptedSocket;
388 if (mSocketState != SocketState.LISTENING) throw new IOException("bt socket is not in listen state");
zzy652678a2012-11-22 11:52:44 -0800389 if(timeout > 0) {
390 Log.d(TAG, "accept() set timeout (ms):" + timeout);
391 mSocket.setSoTimeout(timeout);
392 }
zzy3b147b72012-04-03 19:48:32 -0700393 String RemoteAddr = waitSocketSignal(mSocketIS);
zzy652678a2012-11-22 11:52:44 -0800394 if(timeout > 0)
395 mSocket.setSoTimeout(0);
zzy3b147b72012-04-03 19:48:32 -0700396 synchronized(this)
397 {
398 if (mSocketState != SocketState.LISTENING)
399 throw new IOException("bt socket is not in listen state");
400 acceptedSocket = acceptSocket(RemoteAddr);
401 //quick drop the reference of the file handle
Nick Pelly71c3c782009-09-02 11:51:35 -0700402 }
zzy3b147b72012-04-03 19:48:32 -0700403 return acceptedSocket;
Nick Pelly71c3c782009-09-02 11:51:35 -0700404 }
405
406 /*package*/ int available() throws IOException {
Matthew Xie563e4142012-10-09 22:10:37 -0700407 if (VDBG) Log.d(TAG, "available: " + mSocketIS);
zzy3b147b72012-04-03 19:48:32 -0700408 return mSocketIS.available();
Nick Pelly71c3c782009-09-02 11:51:35 -0700409 }
410
411 /*package*/ int read(byte[] b, int offset, int length) throws IOException {
zzy3b147b72012-04-03 19:48:32 -0700412
Matthew Xie563e4142012-10-09 22:10:37 -0700413 if (VDBG) Log.d(TAG, "read in: " + mSocketIS + " len: " + length);
zzy3b147b72012-04-03 19:48:32 -0700414 int ret = mSocketIS.read(b, offset, length);
415 if(ret < 0)
416 throw new IOException("bt socket closed, read return: " + ret);
Matthew Xie563e4142012-10-09 22:10:37 -0700417 if (VDBG) Log.d(TAG, "read out: " + mSocketIS + " ret: " + ret);
zzy3b147b72012-04-03 19:48:32 -0700418 return ret;
Nick Pelly71c3c782009-09-02 11:51:35 -0700419 }
420
421 /*package*/ int write(byte[] b, int offset, int length) throws IOException {
zzy3b147b72012-04-03 19:48:32 -0700422
Matthew Xie563e4142012-10-09 22:10:37 -0700423 if (VDBG) Log.d(TAG, "write: " + mSocketOS + " length: " + length);
zzy3b147b72012-04-03 19:48:32 -0700424 mSocketOS.write(b, offset, length);
425 // There is no good way to confirm since the entire process is asynchronous anyway
Matthew Xie563e4142012-10-09 22:10:37 -0700426 if (VDBG) Log.d(TAG, "write out: " + mSocketOS + " length: " + length);
zzy3b147b72012-04-03 19:48:32 -0700427 return length;
Nick Pelly71c3c782009-09-02 11:51:35 -0700428 }
429
zzy3b147b72012-04-03 19:48:32 -0700430 @Override
431 public void close() throws IOException {
Matthew Xied77982e2012-11-29 20:26:19 -0800432 if (VDBG) Log.d(TAG, "close() in, this: " + this + ", channel: " + mPort + ", state: " + mSocketState);
zzy3b147b72012-04-03 19:48:32 -0700433 if(mSocketState == SocketState.CLOSED)
434 return;
435 else
436 {
437 synchronized(this)
438 {
439 if(mSocketState == SocketState.CLOSED)
440 return;
441 mSocketState = SocketState.CLOSED;
Matthew Xie563e4142012-10-09 22:10:37 -0700442 if (VDBG) Log.d(TAG, "close() this: " + this + ", channel: " + mPort + ", mSocketIS: " + mSocketIS +
zzy3b147b72012-04-03 19:48:32 -0700443 ", mSocketOS: " + mSocketOS + "mSocket: " + mSocket);
444 if(mSocket != null) {
Matthew Xie563e4142012-10-09 22:10:37 -0700445 if (VDBG) Log.d(TAG, "Closing mSocket: " + mSocket);
zzy3b147b72012-04-03 19:48:32 -0700446 mSocket.shutdownInput();
447 mSocket.shutdownOutput();
448 mSocket.close();
449 mSocket = null;
450 }
451 if(mPfd != null)
452 mPfd.detachFd();
453 }
Nick Pelly16fb88a2009-10-07 07:44:03 +0200454 }
zzy3b147b72012-04-03 19:48:32 -0700455 }
Nick Pelly16fb88a2009-10-07 07:44:03 +0200456
zzy3b147b72012-04-03 19:48:32 -0700457 /*package */ void removeChannel() {
458 }
Nick Pelly16fb88a2009-10-07 07:44:03 +0200459
zzy3b147b72012-04-03 19:48:32 -0700460 /*package */ int getPort() {
461 return mPort;
462 }
463 private String convertAddr(final byte[] addr) {
464 return String.format("%02X:%02X:%02X:%02X:%02X:%02X",
465 addr[0] , addr[1], addr[2], addr[3] , addr[4], addr[5]);
466 }
467 private String waitSocketSignal(InputStream is) throws IOException {
468 byte [] sig = new byte[SOCK_SIGNAL_SIZE];
469 int ret = readAll(is, sig);
Matthew Xie563e4142012-10-09 22:10:37 -0700470 if (VDBG) Log.d(TAG, "waitSocketSignal read 16 bytes signal ret: " + ret);
zzy3b147b72012-04-03 19:48:32 -0700471 ByteBuffer bb = ByteBuffer.wrap(sig);
472 bb.order(ByteOrder.nativeOrder());
473 int size = bb.getShort();
zzy652678a2012-11-22 11:52:44 -0800474 if(size != SOCK_SIGNAL_SIZE)
475 throw new IOException("Connection failure, wrong signal size: " + size);
zzy3b147b72012-04-03 19:48:32 -0700476 byte [] addr = new byte[6];
477 bb.get(addr);
478 int channel = bb.getInt();
479 int status = bb.getInt();
480 String RemoteAddr = convertAddr(addr);
Matthew Xie563e4142012-10-09 22:10:37 -0700481 if (VDBG) Log.d(TAG, "waitSocketSignal: sig size: " + size + ", remote addr: "
zzy3b147b72012-04-03 19:48:32 -0700482 + RemoteAddr + ", channel: " + channel + ", status: " + status);
483 if(status != 0)
484 throw new IOException("Connection failure, status: " + status);
485 return RemoteAddr;
486 }
487 private int readAll(InputStream is, byte[] b) throws IOException {
488 int left = b.length;
489 while(left > 0) {
490 int ret = is.read(b, b.length - left, left);
fredcd6883532012-04-25 17:46:13 -0700491 if(ret <= 0)
zzy652678a2012-11-22 11:52:44 -0800492 throw new IOException("read failed, socket might closed or timeout, read ret: " + ret);
zzy3b147b72012-04-03 19:48:32 -0700493 left -= ret;
494 if(left != 0)
495 Log.w(TAG, "readAll() looping, read partial size: " + (b.length - left) +
496 ", expect size: " + b.length);
Nick Pelly16fb88a2009-10-07 07:44:03 +0200497 }
zzy3b147b72012-04-03 19:48:32 -0700498 return b.length;
499 }
500
501 private int readInt(InputStream is) throws IOException {
502 byte[] ibytes = new byte[4];
503 int ret = readAll(is, ibytes);
Matthew Xie563e4142012-10-09 22:10:37 -0700504 if (VDBG) Log.d(TAG, "inputStream.read ret: " + ret);
zzy3b147b72012-04-03 19:48:32 -0700505 ByteBuffer bb = ByteBuffer.wrap(ibytes);
506 bb.order(ByteOrder.nativeOrder());
507 return bb.getInt();
Nick Pelly16fb88a2009-10-07 07:44:03 +0200508 }
Nick Pelly0b6955a2009-05-26 19:13:43 -0700509}