blob: f532f7ce30a2f57f8120f4699543f4299dea54da [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
Nick Pelly16fb88a2009-10-07 07:44:03 +020019import android.os.ParcelUuid;
zzy3b147b72012-04-03 19:48:32 -070020import android.os.ParcelFileDescriptor;
Nick Pelly16fb88a2009-10-07 07:44:03 +020021import android.os.RemoteException;
22import android.util.Log;
23
Nick Pelly0b6955a2009-05-26 19:13:43 -070024import java.io.Closeable;
zzy3b147b72012-04-03 19:48:32 -070025import java.io.FileDescriptor;
Nick Pelly0b6955a2009-05-26 19:13:43 -070026import java.io.IOException;
27import java.io.InputStream;
28import java.io.OutputStream;
Jeff Sharkeyfea17de2013-06-11 14:13:09 -070029import java.util.Locale;
zzyb49a8962012-10-11 14:52:43 -070030import java.util.UUID;
zzy3b147b72012-04-03 19:48:32 -070031import android.net.LocalSocket;
32import java.nio.ByteOrder;
33import java.nio.ByteBuffer;
Nick Pelly0b6955a2009-05-26 19:13:43 -070034/**
Nick Pelly45e27042009-08-19 11:00:00 -070035 * A connected or connecting Bluetooth socket.
Nick Pelly0b6955a2009-05-26 19:13:43 -070036 *
Nick Pelly45e27042009-08-19 11:00:00 -070037 * <p>The interface for Bluetooth Sockets is similar to that of TCP sockets:
38 * {@link java.net.Socket} and {@link java.net.ServerSocket}. On the server
39 * side, use a {@link BluetoothServerSocket} to create a listening server
Scott Main9fab0ae2009-11-03 18:17:59 -080040 * socket. When a connection is accepted by the {@link BluetoothServerSocket},
41 * it will return a new {@link BluetoothSocket} to manage the connection.
Jake Hambyf51eada2010-09-21 13:39:53 -070042 * On the client side, use a single {@link BluetoothSocket} to both initiate
Scott Main9fab0ae2009-11-03 18:17:59 -080043 * an outgoing connection and to manage the connection.
Nick Pelly0b6955a2009-05-26 19:13:43 -070044 *
Scott Main9fab0ae2009-11-03 18:17:59 -080045 * <p>The most common type of Bluetooth socket is RFCOMM, which is the type
46 * supported by the Android APIs. RFCOMM is a connection-oriented, streaming
47 * transport over Bluetooth. It is also known as the Serial Port Profile (SPP).
Nick Pelly0b6955a2009-05-26 19:13:43 -070048 *
Scott Main9fab0ae2009-11-03 18:17:59 -080049 * <p>To create a {@link BluetoothSocket} for connecting to a known device, use
50 * {@link BluetoothDevice#createRfcommSocketToServiceRecord
51 * BluetoothDevice.createRfcommSocketToServiceRecord()}.
52 * Then call {@link #connect()} to attempt a connection to the remote device.
53 * This call will block until a connection is established or the connection
54 * fails.
Nick Pelly45e27042009-08-19 11:00:00 -070055 *
Scott Main9fab0ae2009-11-03 18:17:59 -080056 * <p>To create a {@link BluetoothSocket} as a server (or "host"), see the
57 * {@link BluetoothServerSocket} documentation.
Nick Pelly45e27042009-08-19 11:00:00 -070058 *
Scott Main9fab0ae2009-11-03 18:17:59 -080059 * <p>Once the socket is connected, whether initiated as a client or accepted
60 * as a server, open the IO streams by calling {@link #getInputStream} and
61 * {@link #getOutputStream} in order to retrieve {@link java.io.InputStream}
62 * and {@link java.io.OutputStream} objects, respectively, which are
63 * automatically connected to the socket.
64 *
65 * <p>{@link BluetoothSocket} is thread
Nick Pelly45e27042009-08-19 11:00:00 -070066 * safe. In particular, {@link #close} will always immediately abort ongoing
67 * operations and close the socket.
Nick Pellycf440592009-09-08 10:12:06 -070068 *
Scott Main9fab0ae2009-11-03 18:17:59 -080069 * <p class="note"><strong>Note:</strong>
70 * Requires the {@link android.Manifest.permission#BLUETOOTH} permission.
71 *
Joe Fernandez3aef8e1d2011-12-20 10:38:34 -080072 * <div class="special reference">
73 * <h3>Developer Guides</h3>
74 * <p>For more information about using Bluetooth, read the
75 * <a href="{@docRoot}guide/topics/wireless/bluetooth.html">Bluetooth</a> developer guide.</p>
76 * </div>
77 *
Scott Main9fab0ae2009-11-03 18:17:59 -080078 * {@see BluetoothServerSocket}
79 * {@see java.io.InputStream}
80 * {@see java.io.OutputStream}
Nick Pelly0b6955a2009-05-26 19:13:43 -070081 */
82public final class BluetoothSocket implements Closeable {
Nick Pelly16fb88a2009-10-07 07:44:03 +020083 private static final String TAG = "BluetoothSocket";
Matthew Xie563e4142012-10-09 22:10:37 -070084 private static final boolean DBG = true;
85 private static final boolean VDBG = false;
Nick Pelly16fb88a2009-10-07 07:44:03 +020086
Nick Pelly24bb9b82009-10-02 20:34:18 -070087 /** @hide */
88 public static final int MAX_RFCOMM_CHANNEL = 30;
89
Nick Pelly45e27042009-08-19 11:00:00 -070090 /** Keep TYPE_ fields in sync with BluetoothSocket.cpp */
Nick Pelly6a669fa2009-06-02 15:57:18 -070091 /*package*/ static final int TYPE_RFCOMM = 1;
92 /*package*/ static final int TYPE_SCO = 2;
93 /*package*/ static final int TYPE_L2CAP = 3;
94
Nick Pelly24bb9b82009-10-02 20:34:18 -070095 /*package*/ static final int EBADFD = 77;
96 /*package*/ static final int EADDRINUSE = 98;
97
zzy3b147b72012-04-03 19:48:32 -070098 /*package*/ static final int SEC_FLAG_ENCRYPT = 1;
99 /*package*/ static final int SEC_FLAG_AUTH = 1 << 1;
100
Nick Pelly6a669fa2009-06-02 15:57:18 -0700101 private final int mType; /* one of TYPE_RFCOMM etc */
zzy3b147b72012-04-03 19:48:32 -0700102 private BluetoothDevice mDevice; /* remote device */
103 private String mAddress; /* remote address */
Nick Pelly0b6955a2009-05-26 19:13:43 -0700104 private final boolean mAuth;
105 private final boolean mEncrypt;
106 private final BluetoothInputStream mInputStream;
107 private final BluetoothOutputStream mOutputStream;
zzy3b147b72012-04-03 19:48:32 -0700108 private final ParcelUuid mUuid;
109 private ParcelFileDescriptor mPfd;
110 private LocalSocket mSocket;
111 private InputStream mSocketIS;
112 private OutputStream mSocketOS;
Mike Lockwood68c692d2013-10-02 07:56:46 -0700113 private int mPort; /* RFCOMM channel or L2CAP psm */
zzy3b147b72012-04-03 19:48:32 -0700114 private int mFd;
115 private String mServiceName;
zzy3b147b72012-04-03 19:48:32 -0700116 private static int PROXY_CONNECTION_TIMEOUT = 5000;
117
118 private static int SOCK_SIGNAL_SIZE = 16;
Nick Pelly0b6955a2009-05-26 19:13:43 -0700119
Matthew Xieceb6c9f2011-05-03 19:50:20 -0700120 private enum SocketState {
121 INIT,
122 CONNECTED,
zzy3b147b72012-04-03 19:48:32 -0700123 LISTENING,
124 CLOSED,
Matthew Xieceb6c9f2011-05-03 19:50:20 -0700125 }
Nick Pelly71c3c782009-09-02 11:51:35 -0700126
Matthew Xieceb6c9f2011-05-03 19:50:20 -0700127 /** prevents all native calls after destroyNative() */
zzy3b147b72012-04-03 19:48:32 -0700128 private volatile SocketState mSocketState;
Matthew Xieceb6c9f2011-05-03 19:50:20 -0700129
130 /** protects mSocketState */
zzy3b147b72012-04-03 19:48:32 -0700131 //private final ReentrantReadWriteLock mLock;
Nick Pelly0b6955a2009-05-26 19:13:43 -0700132
133 /**
Nick Pellybd022f42009-08-14 18:33:38 -0700134 * Construct a BluetoothSocket.
Nick Pelly6a669fa2009-06-02 15:57:18 -0700135 * @param type type of socket
Nick Pelly0b6955a2009-05-26 19:13:43 -0700136 * @param fd fd to use for connected socket, or -1 for a new socket
137 * @param auth require the remote device to be authenticated
138 * @param encrypt require the connection to be encrypted
Nick Pellybd022f42009-08-14 18:33:38 -0700139 * @param device remote device that this socket can connect to
Nick Pelly0b6955a2009-05-26 19:13:43 -0700140 * @param port remote port
Nick Pelly16fb88a2009-10-07 07:44:03 +0200141 * @param uuid SDP uuid
Nick Pelly0b6955a2009-05-26 19:13:43 -0700142 * @throws IOException On error, for example Bluetooth not available, or
Jake Hambyf51eada2010-09-21 13:39:53 -0700143 * insufficient privileges
Nick Pelly0b6955a2009-05-26 19:13:43 -0700144 */
Nick Pellybd022f42009-08-14 18:33:38 -0700145 /*package*/ BluetoothSocket(int type, int fd, boolean auth, boolean encrypt,
Nick Pelly16fb88a2009-10-07 07:44:03 +0200146 BluetoothDevice device, int port, ParcelUuid uuid) throws IOException {
147 if (type == BluetoothSocket.TYPE_RFCOMM && uuid == null && fd == -1) {
Nick Pelly24bb9b82009-10-02 20:34:18 -0700148 if (port < 1 || port > MAX_RFCOMM_CHANNEL) {
149 throw new IOException("Invalid RFCOMM channel: " + port);
150 }
151 }
zzyb49a8962012-10-11 14:52:43 -0700152 if(uuid != null)
153 mUuid = uuid;
154 else mUuid = new ParcelUuid(new UUID(0, 0));
Nick Pelly6a669fa2009-06-02 15:57:18 -0700155 mType = type;
Nick Pelly0b6955a2009-05-26 19:13:43 -0700156 mAuth = auth;
157 mEncrypt = encrypt;
Nick Pellybd022f42009-08-14 18:33:38 -0700158 mDevice = device;
zzy3b147b72012-04-03 19:48:32 -0700159 mPort = port;
160 mFd = fd;
161
162 mSocketState = SocketState.INIT;
163
Nick Pellybd022f42009-08-14 18:33:38 -0700164 if (device == null) {
zzy3b147b72012-04-03 19:48:32 -0700165 // Server socket
166 mAddress = BluetoothAdapter.getDefaultAdapter().getAddress();
Nick Pellybd022f42009-08-14 18:33:38 -0700167 } else {
zzy3b147b72012-04-03 19:48:32 -0700168 // Remote socket
Nick Pellybd022f42009-08-14 18:33:38 -0700169 mAddress = device.getAddress();
170 }
Nick Pelly0b6955a2009-05-26 19:13:43 -0700171 mInputStream = new BluetoothInputStream(this);
172 mOutputStream = new BluetoothOutputStream(this);
zzy3b147b72012-04-03 19:48:32 -0700173 }
174 private BluetoothSocket(BluetoothSocket s) {
175 mUuid = s.mUuid;
176 mType = s.mType;
177 mAuth = s.mAuth;
178 mEncrypt = s.mEncrypt;
179 mPort = s.mPort;
180 mInputStream = new BluetoothInputStream(this);
181 mOutputStream = new BluetoothOutputStream(this);
182 mServiceName = s.mServiceName;
183 }
184 private BluetoothSocket acceptSocket(String RemoteAddr) throws IOException {
185 BluetoothSocket as = new BluetoothSocket(this);
186 as.mSocketState = SocketState.CONNECTED;
187 FileDescriptor[] fds = mSocket.getAncillaryFileDescriptors();
Matthew Xie563e4142012-10-09 22:10:37 -0700188 if (VDBG) Log.d(TAG, "socket fd passed by stack fds: " + fds);
zzy3b147b72012-04-03 19:48:32 -0700189 if(fds == null || fds.length != 1) {
190 Log.e(TAG, "socket fd passed from stack failed, fds: " + fds);
zzy71bfafc2013-04-16 17:17:37 -0700191 as.close();
zzy3b147b72012-04-03 19:48:32 -0700192 throw new IOException("bt socket acept failed");
193 }
194 as.mSocket = new LocalSocket(fds[0]);
195 as.mSocketIS = as.mSocket.getInputStream();
196 as.mSocketOS = as.mSocket.getOutputStream();
197 as.mAddress = RemoteAddr;
198 as.mDevice = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(RemoteAddr);
199 return as;
200 }
Nick Pellybd022f42009-08-14 18:33:38 -0700201 /**
Nick Pelly16fb88a2009-10-07 07:44:03 +0200202 * Construct a BluetoothSocket from address. Used by native code.
Nick Pellybd022f42009-08-14 18:33:38 -0700203 * @param type type of socket
204 * @param fd fd to use for connected socket, or -1 for a new socket
205 * @param auth require the remote device to be authenticated
206 * @param encrypt require the connection to be encrypted
207 * @param address remote device that this socket can connect to
208 * @param port remote port
209 * @throws IOException On error, for example Bluetooth not available, or
Jake Hambyf51eada2010-09-21 13:39:53 -0700210 * insufficient privileges
Nick Pellybd022f42009-08-14 18:33:38 -0700211 */
212 private BluetoothSocket(int type, int fd, boolean auth, boolean encrypt, String address,
213 int port) throws IOException {
Nick Pelly16fb88a2009-10-07 07:44:03 +0200214 this(type, fd, auth, encrypt, new BluetoothDevice(address), port, null);
Nick Pellybd022f42009-08-14 18:33:38 -0700215 }
216
Nick Pelly45e27042009-08-19 11:00:00 -0700217 /** @hide */
Nick Pelly0b6955a2009-05-26 19:13:43 -0700218 @Override
219 protected void finalize() throws Throwable {
220 try {
221 close();
222 } finally {
223 super.finalize();
224 }
225 }
zzy3b147b72012-04-03 19:48:32 -0700226 private int getSecurityFlags() {
227 int flags = 0;
228 if(mAuth)
229 flags |= SEC_FLAG_AUTH;
230 if(mEncrypt)
231 flags |= SEC_FLAG_ENCRYPT;
232 return flags;
Nick Pelly0b6955a2009-05-26 19:13:43 -0700233 }
234
235 /**
Nick Pelly45e27042009-08-19 11:00:00 -0700236 * Get the remote device this socket is connecting, or connected, to.
237 * @return remote device
Nick Pelly0b6955a2009-05-26 19:13:43 -0700238 */
Nick Pellybd022f42009-08-14 18:33:38 -0700239 public BluetoothDevice getRemoteDevice() {
240 return mDevice;
Nick Pelly0b6955a2009-05-26 19:13:43 -0700241 }
242
243 /**
244 * Get the input stream associated with this socket.
Nick Pelly45e27042009-08-19 11:00:00 -0700245 * <p>The input stream will be returned even if the socket is not yet
Nick Pelly0b6955a2009-05-26 19:13:43 -0700246 * connected, but operations on that stream will throw IOException until
247 * the associated socket is connected.
248 * @return InputStream
249 */
250 public InputStream getInputStream() throws IOException {
251 return mInputStream;
252 }
253
254 /**
255 * Get the output stream associated with this socket.
Nick Pelly45e27042009-08-19 11:00:00 -0700256 * <p>The output stream will be returned even if the socket is not yet
Nick Pelly0b6955a2009-05-26 19:13:43 -0700257 * connected, but operations on that stream will throw IOException until
258 * the associated socket is connected.
259 * @return OutputStream
260 */
261 public OutputStream getOutputStream() throws IOException {
262 return mOutputStream;
263 }
264
Nick Pelly24bb9b82009-10-02 20:34:18 -0700265 /**
Matthew Xieceb6c9f2011-05-03 19:50:20 -0700266 * Get the connection status of this socket, ie, whether there is an active connection with
267 * remote device.
268 * @return true if connected
269 * false if not connected
270 */
271 public boolean isConnected() {
zzy3b147b72012-04-03 19:48:32 -0700272 return mSocketState == SocketState.CONNECTED;
273 }
274
275 /*package*/ void setServiceName(String name) {
276 mServiceName = name;
277 }
278
279 /**
280 * Attempt to connect to a remote device.
281 * <p>This method will block until a connection is made or the connection
282 * fails. If this method returns without an exception then this socket
283 * is now connected.
284 * <p>Creating new connections to
285 * remote Bluetooth devices should not be attempted while device discovery
286 * is in progress. Device discovery is a heavyweight procedure on the
287 * Bluetooth adapter and will significantly slow a device connection.
288 * Use {@link BluetoothAdapter#cancelDiscovery()} to cancel an ongoing
289 * discovery. Discovery is not managed by the Activity,
290 * but is run as a system service, so an application should always call
291 * {@link BluetoothAdapter#cancelDiscovery()} even if it
292 * did not directly request a discovery, just to be sure.
293 * <p>{@link #close} can be used to abort this call from another thread.
294 * @throws IOException on error, for example connection failure
295 */
296 public void connect() throws IOException {
297 if (mDevice == null) throw new IOException("Connect is called on null device");
298
299 try {
zzy3b147b72012-04-03 19:48:32 -0700300 if (mSocketState == SocketState.CLOSED) throw new IOException("socket closed");
fredc903ac6f2012-04-24 03:59:57 -0700301 IBluetooth bluetoothProxy = BluetoothAdapter.getDefaultAdapter().getBluetoothService(null);
fredc0f420372012-04-12 00:02:00 -0700302 if (bluetoothProxy == null) throw new IOException("Bluetooth is off");
303 mPfd = bluetoothProxy.connectSocket(mDevice, mType,
zzy3b147b72012-04-03 19:48:32 -0700304 mUuid, mPort, getSecurityFlags());
305 synchronized(this)
306 {
Matthew Xie563e4142012-10-09 22:10:37 -0700307 if (DBG) Log.d(TAG, "connect(), SocketState: " + mSocketState + ", mPfd: " + mPfd);
zzy3b147b72012-04-03 19:48:32 -0700308 if (mSocketState == SocketState.CLOSED) throw new IOException("socket closed");
309 if (mPfd == null) throw new IOException("bt socket connect failed");
310 FileDescriptor fd = mPfd.getFileDescriptor();
311 mSocket = new LocalSocket(fd);
312 mSocketIS = mSocket.getInputStream();
313 mSocketOS = mSocket.getOutputStream();
314 }
315 int channel = readInt(mSocketIS);
316 if (channel <= 0)
317 throw new IOException("bt socket connect failed");
318 mPort = channel;
319 waitSocketSignal(mSocketIS);
320 synchronized(this)
321 {
322 if (mSocketState == SocketState.CLOSED)
323 throw new IOException("bt socket closed");
324 mSocketState = SocketState.CONNECTED;
325 }
326 } catch (RemoteException e) {
327 Log.e(TAG, Log.getStackTraceString(new Throwable()));
328 }
Matthew Xieceb6c9f2011-05-03 19:50:20 -0700329 }
330
331 /**
Nick Pelly24bb9b82009-10-02 20:34:18 -0700332 * Currently returns unix errno instead of throwing IOException,
333 * so that BluetoothAdapter can check the error code for EADDRINUSE
334 */
335 /*package*/ int bindListen() {
zzy3b147b72012-04-03 19:48:32 -0700336 int ret;
337 if (mSocketState == SocketState.CLOSED) return EBADFD;
fredc903ac6f2012-04-24 03:59:57 -0700338 IBluetooth bluetoothProxy = BluetoothAdapter.getDefaultAdapter().getBluetoothService(null);
fredc0f420372012-04-12 00:02:00 -0700339 if (bluetoothProxy == null) {
340 Log.e(TAG, "bindListen fail, reason: bluetooth is off");
341 return -1;
342 }
Nick Pelly71c3c782009-09-02 11:51:35 -0700343 try {
fredc0f420372012-04-12 00:02:00 -0700344 mPfd = bluetoothProxy.createSocketChannel(mType, mServiceName,
zzy3b147b72012-04-03 19:48:32 -0700345 mUuid, mPort, getSecurityFlags());
346 } catch (RemoteException e) {
347 Log.e(TAG, Log.getStackTraceString(new Throwable()));
zzy3b147b72012-04-03 19:48:32 -0700348 return -1;
349 }
350
351 // read out port number
352 try {
353 synchronized(this) {
Matthew Xie563e4142012-10-09 22:10:37 -0700354 if (VDBG) Log.d(TAG, "bindListen(), SocketState: " + mSocketState + ", mPfd: " +
355 mPfd);
zzy3b147b72012-04-03 19:48:32 -0700356 if(mSocketState != SocketState.INIT) return EBADFD;
357 if(mPfd == null) return -1;
358 FileDescriptor fd = mPfd.getFileDescriptor();
Matthew Xie563e4142012-10-09 22:10:37 -0700359 if (VDBG) Log.d(TAG, "bindListen(), new LocalSocket ");
zzy3b147b72012-04-03 19:48:32 -0700360 mSocket = new LocalSocket(fd);
Matthew Xie563e4142012-10-09 22:10:37 -0700361 if (VDBG) Log.d(TAG, "bindListen(), new LocalSocket.getInputStream() ");
zzy3b147b72012-04-03 19:48:32 -0700362 mSocketIS = mSocket.getInputStream();
363 mSocketOS = mSocket.getOutputStream();
364 }
Matthew Xie563e4142012-10-09 22:10:37 -0700365 if (VDBG) Log.d(TAG, "bindListen(), readInt mSocketIS: " + mSocketIS);
zzy3b147b72012-04-03 19:48:32 -0700366 int channel = readInt(mSocketIS);
367 synchronized(this) {
368 if(mSocketState == SocketState.INIT)
369 mSocketState = SocketState.LISTENING;
370 }
Matthew Xie563e4142012-10-09 22:10:37 -0700371 if (VDBG) Log.d(TAG, "channel: " + channel);
zzy3b147b72012-04-03 19:48:32 -0700372 if (mPort == -1) {
373 mPort = channel;
374 } // else ASSERT(mPort == channel)
375 ret = 0;
376 } catch (IOException e) {
377 Log.e(TAG, "bindListen, fail to get port number, exception: " + e);
378 return -1;
379 }
380 return ret;
Nick Pelly71c3c782009-09-02 11:51:35 -0700381 }
382
383 /*package*/ BluetoothSocket accept(int timeout) throws IOException {
zzy3b147b72012-04-03 19:48:32 -0700384 BluetoothSocket acceptedSocket;
385 if (mSocketState != SocketState.LISTENING) throw new IOException("bt socket is not in listen state");
zzy652678a2012-11-22 11:52:44 -0800386 if(timeout > 0) {
387 Log.d(TAG, "accept() set timeout (ms):" + timeout);
388 mSocket.setSoTimeout(timeout);
389 }
zzy3b147b72012-04-03 19:48:32 -0700390 String RemoteAddr = waitSocketSignal(mSocketIS);
zzy652678a2012-11-22 11:52:44 -0800391 if(timeout > 0)
392 mSocket.setSoTimeout(0);
zzy3b147b72012-04-03 19:48:32 -0700393 synchronized(this)
394 {
395 if (mSocketState != SocketState.LISTENING)
396 throw new IOException("bt socket is not in listen state");
397 acceptedSocket = acceptSocket(RemoteAddr);
398 //quick drop the reference of the file handle
Nick Pelly71c3c782009-09-02 11:51:35 -0700399 }
zzy3b147b72012-04-03 19:48:32 -0700400 return acceptedSocket;
Nick Pelly71c3c782009-09-02 11:51:35 -0700401 }
402
403 /*package*/ int available() throws IOException {
Matthew Xie563e4142012-10-09 22:10:37 -0700404 if (VDBG) Log.d(TAG, "available: " + mSocketIS);
zzy3b147b72012-04-03 19:48:32 -0700405 return mSocketIS.available();
Nick Pelly71c3c782009-09-02 11:51:35 -0700406 }
zzy71bfafc2013-04-16 17:17:37 -0700407 /**
408 * Wait until the data in sending queue is emptied. A polling version
409 * for flush implementation. Used to ensure the writing data afterwards will
410 * be packed in new RFCOMM frame.
411 * @throws IOException
412 * if an i/o error occurs.
413 */
414 /*package*/ void flush() throws IOException {
Zhihai Xu610770d2013-12-17 11:39:20 -0800415 if (mSocketOS == null) throw new IOException("flush is called on null OutputStream");
zzy71bfafc2013-04-16 17:17:37 -0700416 if (VDBG) Log.d(TAG, "flush: " + mSocketOS);
417 mSocketOS.flush();
418 }
Nick Pelly71c3c782009-09-02 11:51:35 -0700419
420 /*package*/ int read(byte[] b, int offset, int length) throws IOException {
Zhihai Xu610770d2013-12-17 11:39:20 -0800421 if (mSocketIS == null) throw new IOException("read is called on null InputStream");
422 if (VDBG) Log.d(TAG, "read in: " + mSocketIS + " len: " + length);
423 int ret = mSocketIS.read(b, offset, length);
424 if(ret < 0)
425 throw new IOException("bt socket closed, read return: " + ret);
426 if (VDBG) Log.d(TAG, "read out: " + mSocketIS + " ret: " + ret);
427 return ret;
Nick Pelly71c3c782009-09-02 11:51:35 -0700428 }
429
430 /*package*/ int write(byte[] b, int offset, int length) throws IOException {
Zhihai Xu610770d2013-12-17 11:39:20 -0800431 if (mSocketOS == null) throw new IOException("write is called on null OutputStream");
432 if (VDBG) Log.d(TAG, "write: " + mSocketOS + " length: " + length);
433 mSocketOS.write(b, offset, length);
434 // There is no good way to confirm since the entire process is asynchronous anyway
435 if (VDBG) Log.d(TAG, "write out: " + mSocketOS + " length: " + length);
436 return length;
Nick Pelly71c3c782009-09-02 11:51:35 -0700437 }
438
zzy3b147b72012-04-03 19:48:32 -0700439 @Override
440 public void close() throws IOException {
Matthew Xied77982e2012-11-29 20:26:19 -0800441 if (VDBG) Log.d(TAG, "close() in, this: " + this + ", channel: " + mPort + ", state: " + mSocketState);
zzy3b147b72012-04-03 19:48:32 -0700442 if(mSocketState == SocketState.CLOSED)
443 return;
444 else
445 {
446 synchronized(this)
447 {
448 if(mSocketState == SocketState.CLOSED)
449 return;
450 mSocketState = SocketState.CLOSED;
Matthew Xie563e4142012-10-09 22:10:37 -0700451 if (VDBG) Log.d(TAG, "close() this: " + this + ", channel: " + mPort + ", mSocketIS: " + mSocketIS +
zzy3b147b72012-04-03 19:48:32 -0700452 ", mSocketOS: " + mSocketOS + "mSocket: " + mSocket);
453 if(mSocket != null) {
Matthew Xie563e4142012-10-09 22:10:37 -0700454 if (VDBG) Log.d(TAG, "Closing mSocket: " + mSocket);
zzy3b147b72012-04-03 19:48:32 -0700455 mSocket.shutdownInput();
456 mSocket.shutdownOutput();
457 mSocket.close();
458 mSocket = null;
459 }
Zhihai Xu01771022014-01-20 12:04:23 -0800460 if (mPfd != null) {
461 mPfd.close();
462 mPfd = null;
463 }
zzy3b147b72012-04-03 19:48:32 -0700464 }
Nick Pelly16fb88a2009-10-07 07:44:03 +0200465 }
zzy3b147b72012-04-03 19:48:32 -0700466 }
Nick Pelly16fb88a2009-10-07 07:44:03 +0200467
zzy3b147b72012-04-03 19:48:32 -0700468 /*package */ void removeChannel() {
469 }
Nick Pelly16fb88a2009-10-07 07:44:03 +0200470
zzy3b147b72012-04-03 19:48:32 -0700471 /*package */ int getPort() {
472 return mPort;
473 }
474 private String convertAddr(final byte[] addr) {
Jeff Sharkeyfea17de2013-06-11 14:13:09 -0700475 return String.format(Locale.US, "%02X:%02X:%02X:%02X:%02X:%02X",
zzy3b147b72012-04-03 19:48:32 -0700476 addr[0] , addr[1], addr[2], addr[3] , addr[4], addr[5]);
477 }
478 private String waitSocketSignal(InputStream is) throws IOException {
479 byte [] sig = new byte[SOCK_SIGNAL_SIZE];
480 int ret = readAll(is, sig);
Matthew Xie563e4142012-10-09 22:10:37 -0700481 if (VDBG) Log.d(TAG, "waitSocketSignal read 16 bytes signal ret: " + ret);
zzy3b147b72012-04-03 19:48:32 -0700482 ByteBuffer bb = ByteBuffer.wrap(sig);
483 bb.order(ByteOrder.nativeOrder());
484 int size = bb.getShort();
zzy652678a2012-11-22 11:52:44 -0800485 if(size != SOCK_SIGNAL_SIZE)
486 throw new IOException("Connection failure, wrong signal size: " + size);
zzy3b147b72012-04-03 19:48:32 -0700487 byte [] addr = new byte[6];
488 bb.get(addr);
489 int channel = bb.getInt();
490 int status = bb.getInt();
491 String RemoteAddr = convertAddr(addr);
Matthew Xie563e4142012-10-09 22:10:37 -0700492 if (VDBG) Log.d(TAG, "waitSocketSignal: sig size: " + size + ", remote addr: "
zzy3b147b72012-04-03 19:48:32 -0700493 + RemoteAddr + ", channel: " + channel + ", status: " + status);
494 if(status != 0)
495 throw new IOException("Connection failure, status: " + status);
496 return RemoteAddr;
497 }
498 private int readAll(InputStream is, byte[] b) throws IOException {
499 int left = b.length;
500 while(left > 0) {
501 int ret = is.read(b, b.length - left, left);
fredcd6883532012-04-25 17:46:13 -0700502 if(ret <= 0)
zzy652678a2012-11-22 11:52:44 -0800503 throw new IOException("read failed, socket might closed or timeout, read ret: " + ret);
zzy3b147b72012-04-03 19:48:32 -0700504 left -= ret;
505 if(left != 0)
506 Log.w(TAG, "readAll() looping, read partial size: " + (b.length - left) +
507 ", expect size: " + b.length);
Nick Pelly16fb88a2009-10-07 07:44:03 +0200508 }
zzy3b147b72012-04-03 19:48:32 -0700509 return b.length;
510 }
511
512 private int readInt(InputStream is) throws IOException {
513 byte[] ibytes = new byte[4];
514 int ret = readAll(is, ibytes);
Matthew Xie563e4142012-10-09 22:10:37 -0700515 if (VDBG) Log.d(TAG, "inputStream.read ret: " + ret);
zzy3b147b72012-04-03 19:48:32 -0700516 ByteBuffer bb = ByteBuffer.wrap(ibytes);
517 bb.order(ByteOrder.nativeOrder());
518 return bb.getInt();
Nick Pelly16fb88a2009-10-07 07:44:03 +0200519 }
Nick Pelly0b6955a2009-05-26 19:13:43 -0700520}