My favorites | Sign in
Logo
                
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
/**
* BlueCove - Java library for Bluetooth
* Copyright (C) 2006-2007 Vlad Skarzhevskyy
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*
* @author vlads
* @version $Id$
*/
package net.sf.bluecove.awt;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.bluetooth.L2CAPConnection;
import javax.bluetooth.LocalDevice;
import javax.bluetooth.RemoteDevice;
import javax.microedition.io.Connection;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;

import org.bluecove.tester.log.Logger;
import org.bluecove.tester.util.IOUtils;
import org.bluecove.tester.util.RuntimeDetect;
import org.bluecove.tester.util.StringUtils;
import org.bluecove.tester.util.TimeUtils;

import com.intel.bluetooth.RemoteDeviceHelper;

import net.sf.bluecove.ConnectionHolder;
import net.sf.bluecove.ConnectionHolderL2CAP;
import net.sf.bluecove.ConnectionHolderStream;
import net.sf.bluecove.util.BluetoothTypesInfo;

/**
*
*
*/
public class ClientConnectionThread extends Thread {

Object threadLocalBluetoothStack;

private static int connectionCount = 0;

private String serverURL;

private ConnectionHolder c;

private RemoteDevice remoteDevice;

private boolean stoped = false;

boolean isRunning = false;

boolean isConnecting = false;

long receivedCount = 0;

long reportedSize = 0;

long receivedPacketsCount = 0;

boolean rfcomm;

public static final int interpretDataChar = 0;

public static final int interpretDataCharArray = 1;

public static final int interpretDataStats = 2;

public static final int interpretDataStatsArray = 3;

public static final int interpretIgnore = 4;

int interpretData = interpretDataChar;

long reported = 0;

String logPrefix = "";

private StringBuffer dataBuf = new StringBuffer();

private boolean binaryData = false;

private FileOutputStream fileOut;

private boolean rssiEnabled;

ClientConnectionThread(String serverURL) {
super("ClientConnectionThread" + (++connectionCount));
this.serverURL = serverURL;
}

String getLocalBluetoothId() {
if (threadLocalBluetoothStack == null) {
return "";
} else {
return threadLocalBluetoothStack.toString();
}
}

public void run() {
try {
rfcomm = BluetoothTypesInfo.isRFCOMM(serverURL);
if (!rfcomm && !BluetoothTypesInfo.isL2CAP(serverURL)) {
Logger.error(logPrefix + "unsupported connection type " + serverURL);
return;
}
RuntimeDetect.cldcStub.setThreadLocalBluetoothStack(threadLocalBluetoothStack);
Connection conn = null;
try {
isConnecting = true;
Logger.debug(logPrefix + "Connecting:" + serverURL + " ...");
conn = Connector.open(serverURL);
remoteDevice = RemoteDevice.getRemoteDevice(conn);
} catch (IOException e) {
Logger.error(logPrefix + "Connection error", e);
return;
} finally {
isConnecting = false;
}
Logger.info(logPrefix + "Connected");
rssiEnabled = "true".equals(LocalDevice.getProperty("bluecove.feature.rssi"));
if (rfcomm) {
ConnectionHolderStream cs = new ConnectionHolderStream((StreamConnection) conn);
c = cs;
cs.is = cs.conn.openInputStream();
cs.os = cs.conn.openOutputStream();
isRunning = true;
while (!stoped) {
if (interpretData == interpretIgnore) {
Thread.sleep(777);
} else if ((interpretData == interpretDataCharArray) || (interpretData == interpretDataStatsArray)) {
byte b[] = new byte[0xFF];
int readLen = cs.is.read(b);
if (readLen == -1) {
Logger.debug(logPrefix + "EOF recived");
break;
}
receivedCount += readLen;
for (int k = 0; k < readLen; k++) {
printdataReceivedRFCOMM(b[k]);
}
} else {
int data = cs.is.read();
if (data == -1) {
Logger.debug(logPrefix + "EOF recived");
break;
}
receivedCount++;
printdataReceivedRFCOMM(data);
}
}
if (dataBuf.length() > 0) {
Logger.debug(logPrefix + "cc:" + StringUtils.toBinaryText(dataBuf));
}
} else { // l2cap
ConnectionHolderL2CAP lc = new ConnectionHolderL2CAP((L2CAPConnection) conn);
isRunning = true;
c = lc;
while (!stoped) {
if (interpretData == interpretIgnore) {
Thread.sleep(777);
} else {
// Tests if receive() will block
if ((interpretData != interpretDataCharArray) && (interpretData != interpretDataStatsArray)) {
while ((!lc.channel.ready()) && (!stoped)) {
Thread.sleep(100);
}
}
if (stoped) {
break;
}
int receiveMTU = lc.channel.getReceiveMTU();
byte[] data = new byte[receiveMTU];
int length = lc.channel.receive(data);
receivedCount += length;
receivedPacketsCount++;
printdataReceivedL2CAP(data, length);
}
}
}
} catch (IOException e) {
if (!stoped) {
Logger.error(logPrefix + "Communication error", e);
} else {
Logger.debug(logPrefix + "communication stopped", e);
}
} catch (Throwable e) {
Logger.error(logPrefix + "Error", e);
} finally {
isRunning = false;
if (c != null) {
c.shutdown();
}
closeFile();
}
}

private void printdataReceivedRFCOMM(int data) {
switch (interpretData) {
case interpretDataChar:
case interpretDataCharArray:
char c = (char) data;
if ((!binaryData) && (c < ' ')) {
binaryData = true;
}
dataBuf.append(c);
if (((!binaryData) && (c == '\n')) || (dataBuf.length() > 32)) {
Logger.debug("cc:" + StringUtils.toBinaryText(dataBuf));
dataBuf = new StringBuffer();
}
break;
case interpretDataStatsArray:
case interpretDataStats:
long now = System.currentTimeMillis();
if (now - reported > 5 * 1000) {
int size = (int) (receivedCount - reportedSize);
reportedSize = receivedCount;
String rssiInfo = "";
if (rssiEnabled) {
try {
rssiInfo = " RSSI:" + RemoteDeviceHelper.readRSSI(remoteDevice);
} catch (IOException ignore) {
}
}
Logger.debug(logPrefix + "Received " + receivedCount + " bytes " + TimeUtils.bps(size, reported) + rssiInfo);
reported = now;
}
break;
}
synchronized (this) {
if (fileOut != null) {
try {
fileOut.write((char) data);
} catch (IOException e) {
Logger.debug(logPrefix + "file write error", e);
closeFile();
}
}
}
}

private void printdataReceivedL2CAP(byte[] data, int length) {
switch (interpretData) {
case interpretDataCharArray:
case interpretDataChar:
int messageLength = length;
if ((length > 0) && (data[length - 1] == '\n')) {
messageLength = length - 1;
}
StringBuffer buf = new StringBuffer();
buf.append(logPrefix).append("cc:");
if (messageLength != 0) {
buf.append(StringUtils.toBinaryText(new StringBuffer(new String(data, 0, messageLength))));
}
buf.append(" (").append(length).append(")");
Logger.debug(buf.toString());
break;
case interpretDataStatsArray:
case interpretDataStats:
long now = System.currentTimeMillis();
if (now - reported > 5 * 1000) {
int size = (int) (receivedCount - reportedSize);
reportedSize = receivedCount;
Logger.debug(logPrefix + "Received " + receivedPacketsCount + " packet(s), " + receivedCount
+ " bytes " + TimeUtils.bps(size, reported));
reported = now;
}
break;
}
synchronized (this) {
if (fileOut != null) {
try {
fileOut.write(data, 0, length);
} catch (IOException e) {
Logger.debug(logPrefix + "file write error", e);
closeFile();
}
}
}
}

public void shutdown() {
stoped = true;
if (c != null) {
c.shutdown();
}
c = null;
closeFile();
}

private synchronized void closeFile() {
if (fileOut != null) {
try {
fileOut.flush();
} catch (IOException ignore) {
}
IOUtils.closeQuietly(fileOut);
fileOut = null;
}
}

public void updateDataReceiveType(int type, boolean saveToFile) {
interpretData = type;

if ((!saveToFile) && (fileOut != null)) {
closeFile();
} else if ((saveToFile) && (fileOut == null)) {
SimpleDateFormat fmt = new SimpleDateFormat("MM-dd_HH-mm-ss");
File file = new File("data-" + BluetoothTypesInfo.extractBluetoothAddress(serverURL)
+ fmt.format(new Date()) + ".bin");
try {
fileOut = new FileOutputStream(file);
Logger.info(logPrefix + "saving data to file " + file.getAbsolutePath());
} catch (IOException e) {
}
}
}

public void send(final byte data[]) {
Thread t = new Thread("ClientConnectionSendThread" + (++connectionCount)) {
public void run() {
try {
if (rfcomm) {
((ConnectionHolderStream) c).os.write(data);
} else {
((ConnectionHolderL2CAP) c).channel.send(data);
}
Logger.debug(logPrefix + "data " + data.length + " sent");
} catch (IOException e) {
Logger.error(logPrefix + "Communication error", e);
}
}
};
t.setDaemon(true);
t.start();
}
}
Show details Hide details

Change log

r2796 by skarzhevskyy on Feb 24, 2009   Diff
Testing L2CAP receive
Go to: 
Project members, sign in to write a code review

Older revisions

r2742 by skarzhevskyy on Feb 13, 2009   Diff
print RSSI info in stats
r2607 by skarzhevskyy on Dec 17, 2008   Diff
OBEX tests in J2ME
r2585 by skarzhevskyy on Dec 15, 2008   Diff
allow to interrupt connection
All revisions of this file

File info

Size: 9799 bytes, 357 lines

File properties

svn:mime-type
text/plain
svn:eol-style
native
svn:keywords
Date Author Id Revision
Hosted by Google Code