Sei sulla pagina 1di 24

Connecting to PC from mobile using bluetooth in java-Question

Question subject: Connecting to PC from mobile using bluetooth in java


Posted: Fri Jul 25, 2008 6:43 pm
I will talk about how to make data transfer from your mobile to your PC .The mobile side will
be a j2me application.The server side is J2se application .To make such communication using
bluetooth you need to open a virtual COM in your pc and assign this virtual COM to your paired
mobile .Paired devices means an same PIN Code entered in both sides (mobile and PC ) .In my
case i worked on bluecove external adapter .There is an application for bluecove device that
allow me to assign COMs to a specific mobile.In my system i was sending images from my
phone to PC server using bluetooth.
In server side :
You will need some packages to make the work done .in my case i used two packages bluecove2.0.2.jar and avetanaObex.jar .
Here is code from it
java code
?
1 package sift;
2
java.awt.Image;
3 import
import java.awt.image.BufferedImage;
4 import java.io.File;
5 import java.io.FileNotFoundException;
6 import java.io.FileOutputStream;
7 import java.io.IOException;
import java.io.InputStream;
8 import java.io.OutputStream;
9
10 import java.util.logging.Level;
11 import java.util.logging.Logger;
12 import javax.bluetooth.DiscoveryAgent;
13 import javax.bluetooth.LocalDevice;
import javax.bluetooth.UUID;
14 import javax.microedition.io.Connector;
15 import javax.microedition.io.StreamConnection;
16 import javax.microedition.io.StreamConnectionNotifier;
17 import javax.swing.ImageIcon;
18
19 /**
* A class that demonstrates Bluetooth communication between server mode PC
20 and
21 * client mode device through serial port profile.
22 *
23 * @see sourceforge.net/projects/bluecove : BlueCove - JSR-82
*
implementation</a>
24 */
25 public class PCServerCOMM {
26
27
/** ================
28

* Bluetooth Server
29
* ================
30
*
31
* This example application is a straighforward implementation of
32
* a bluetooth server.
*
33
*
34
* Usage
35
* =====
36
*
37
* Start the program. Events are logged by printing them out with
standard
38
* output stream. Once the server is up and ready to accept
39
connections,
40
* connect to server with client.
41
*
*
42
* How it Works
43
* ============
44
*
45
* The application starts a loop to wait for a new connection. After a
46 new
* connection is reseived the connection is handled. In the handling
47
* operation few tokens and end token is written to connection stream.
48
* Each read token is logged to standard output. After handling session
49
* the loop continues by waiting for a new connection.
50
*
51
*/
52
/*53
*
54
* ---- Bluetooth attributes ---55
*/
56
57
// serial port profile
protected String UUID = new UUID("1101", true).toString();
58
protected int discoveryMode = DiscoveryAgent.GIAC; // no paring needed
59
60
public static InputStream in;
61
public static OutputStream out;
62
private static boolean ServerRun = true;
63
Image aa;
MOBILEOR_GUI frame;
64
/*65
*
66
* ---- Connection handling attributes ---67
*/
protected int endToken = 255;
68
69
public PCServerCOMM(MOBILEOR_GUI frame) {
70
71
this.frame = frame;
72
ServerRun = true;
73
74
try {

LocalDevice device = LocalDevice.getLocalDevice();


75
device.setDiscoverable(DiscoveryAgent.GIAC);
76
77
String url = "btspp://localhost:" + UUID +
78 ";name=PCServerCOMM";
79
80
log("Create server by uri: " + url);
StreamConnectionNotifier notifier = (StreamConnectionNotifier)
81
Connector.open(url);
82
83
serverLoop(notifier);
84
85
} catch (Throwable e) {
86
log(e);
87
}
}
88
89
private void serverLoop(final StreamConnectionNotifier notifier) {
90
Thread handler = new Thread() {
91
92
@Override
93
public void run() {
try {
94
while (ServerRun) { // infinite loop to accept
95
connections.
96
97
log("Waiting for connection...");
98
handleConnection(notifier.acceptAndOpen());
99
}
} catch (Exception e) {
10
log(e);
0
}
10
try {
1
Thread.sleep(200);
10
} catch (InterruptedException ex) {
Logger.getLogger(PCServerCOMM.class.getName()).log(Leve
2
l.SEVERE,
null,
ex);
10
}
3
}
10
};
handler.start();
4
}
10
5
private void handleConnection(StreamConnection conn) throws IOException
10 {
6
out = conn.openOutputStream();
10
in = conn.openInputStream();
startReadThread(in);
7
log("Connection found...");
10
/*
8
try { // to write some tokens through the bluetooth link
10
int[] tokens = new int[] { 1, 3, 5, 7, endToken };
for (int i = 0; i < tokens.length; i++) {
9
out.write(tokens[i]);
11
out.flush();

log("write:" + tokens[i]);
0
// wait a sec before next write.
11
Thread.sleep(1 * 1000);
1
}
11
} catch (Exception e) {
log(e);
2
} finally {
11
log("Close connection.");
3
if (conn != null) {
11
try {
4
conn.close();
} catch (IOException e) {
11
}
5
}
11
}
6
* */
}
11
7
private void startReadThread(final InputStream in) {
11
8
Thread reader = new Thread() {
11
9
@Override
12
public void run() {
0
FileOutputStream f1 = null;
// System.out.println("Image data");
12
File directory = new File("C:/Image/");
1
String path = "image/image.png";
12
String image = "";
2
12
3
try {
12
f1 = new FileOutputStream(path,false);
} catch (FileNotFoundException ex) {
4
Logger.getLogger(PCServerCOMM.class.getName()).log(Leve
12
l.SEVERE, null, ex);
5
}
12
byte[] s = new byte[512];
boolean falg = true;
6
log("Waiting for image data");
12
try {
7
while (true) {
12
8
int r = in.read(s);
12
9
if (r != -1) {
falg = false;
13
0
try {
13
1
13
//s=Base64.decode(new String(s).intern());
2
//
image = image + new
13 String(s,0,r);

f1.write(s, 0, r);
3
f1.flush();
13
} catch (IOException e) {
4
System.out.println("Problems creating the
13 file");
}
5
13
}
6
if (!falg && (r < s.length)) {
13
//
System.out.println("Frame !!!");
7
f1.flush();
13
f1.close();
aa = new ImageIcon(path).getImage();
8
new FrameImage(aa, 1);
13
9
SIFT sift = new SIFT(path, "scale2.jpg",
14 "welcome");
0
frame.setImg(aa);
frame.repaint();
14
BufferedImage buff = new
1
BufferedImage(aa.getWidth(null), aa.getHeight(null),
14 BufferedImage.TYPE_INT_RGB);
2
//
14 buff.createGraphics().drawImage(sift.oriented_Image(), 0, 0, null);
//
OrientationForm orientionResult = new
3
OrientationForm(buff);
14
//
orientionResult.showOrientationResult();
4
MOBILEOR_GUI.AppendTostatus(sift.getATree().get
14 MatchingInfo());
5
//
setNearestImages(sift.getNearest_5_imgs());
14
//
6
frame.createNearestWindow(sift.getNearest_5_imgs(), orientionResult);
14
//
7 frame.getDisplayNearest().setSize(frame.getDesktopWidth(), 200);
//
frame.getDisplayNearest().setLocation(0,
14
8 orientionResult.getHeight() + 5);
//
14 frame.getDesktop().add(frame.getDisplayNearest());
9
15
break;
0
}
}
15
}
catch
(Throwable e) {
1
log(e);
15
2
} finally {
15
if (in != null) {
try {
3
log("Image transfering done...");
15
in.close();
4
15
} catch (IOException e) {
5
}
15
}

6
15
7
15
8
15
9
16
0
16
1
16
2
16
3
16
4
16
5
16
6
16
7
16
8
16
}
9
17
0
17
1
17
2
17
3
17
4
17
5
17
6
17
7
17
8
17

};
reader.start();
}
/**
------- Utility section ------*/
private void log(String msg) {
MOBILEOR_GUI.AppendTostatus(msg + "\n");
}
private void log(Throwable e) {
log(e.getMessage());
e.printStackTrace();
}
public Image getImage() {
return aa;
}
public static void StopServer() {
ServerRun = false;
}
/**
------- Bootstrap section, i.e., main method ------*/

9
18
0
18
1
18
2
18
3
18
4
18
5
18
6
18
7
18
8
18
9
19
0
19
1
19
2
19
3
19
4
19
5
19
6
19
7
19
8
19
9
20
0
20
1
20

2
20
3
20
4
20
5
20
6
20
7
20
8
20
9
21
0
21
1
21
2
21
3
21
4
21
5
21
6
21
7
21
8
21
9
22
0
22
1
22
2
22
3
22
4
22

5
22
6
22
7
22
8
22
9
23
0
23
1
23
2
23
3
23
4
23
5
23
6
23
7
23
8
23
9
24
0
24
1
24
2
24
3
24
4
24
5
24
6
24
7
24

8
24
9
25
0
25
1
25
2
25
3
25
4
25
5
25
6
25
7
25
8
25
9
26
0
About the mobile side you can make a midlet and install it on your mobile .Here is some codes :
java code
?
1 import java.io.IOException;
2 import java.io.InputStream;
import java.io.OutputStream;
3 import java.util.Vector;
4
5 import javax.bluetooth.BluetoothStateException;
6 import javax.bluetooth.DeviceClass;
7 import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.DiscoveryListener;
8 import javax.bluetooth.LocalDevice;
9 import javax.bluetooth.RemoteDevice;
10 import javax.bluetooth.ServiceRecord;
11 import javax.bluetooth.UUID;
12 import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
13 import javax.microedition.lcdui.Command;
14 import javax.microedition.lcdui.CommandListener;
15 import javax.microedition.lcdui.Display;

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

import
import
import
import
import

javax.microedition.lcdui.Displayable;
javax.microedition.lcdui.Form;
javax.microedition.lcdui.List;
javax.microedition.midlet.MIDlet;
javax.microedition.midlet.MIDletStateChangeException;

/**
* A class that demonstrates Bluetooth communication between client mode
device
* and server mode PC through serial port profile.
*/
public class DeviceClientCOMM implements DiscoveryListener, CommandListener
{
/** ================
* Bluetooth Client
* ================
*
* This example application is a straightforward implementation of
* making a connection throught bluetooth link and using it.
*
*
* Usage
* =====
*
* Once the system is started the information area is filled with
logging
* information. Wait until combo box is enabled (if there's any
bluetooth
* device around) and select a device from the combo box. A connection
* is constructed to selected device after selection.
*
* After connection is constructed succesfully the application
* operates as an echo client, i.e., everything that is read is
written
* back to the server. All information is also written into the
information
* area.
*
*
* How it Works
* ============
*
* The example consist of three different operations. Operations need
to
* be executed in the dependency order.
*
* 1) *Inquiry method* is used to search all available devices. The
combo
*
box's data model is filled with found bluetooth devices.
*
* 2) *Service search* is used to search serial port profile service
from the
*
selected device. The search is started after the user selects
the

*
device from the combo box.
62
*
63
* 3) *Stream handling* communicates with the server through the
64 bluetooth
65
*
link. This example operates in echo loop until stop token is
66 found.
*
67
*
68
* Special Debug Mode
69
* ==================
70
*
* There's a special debug mode which speeds up development by
71
skipping
the
72
* inquiry method to resolve the remote device. In the debug mode the
73 device's
74
* bluetooth address is provided by the developer.
*/
75
76
/*77
*
78
* ---- Debug attributes ---79
*/
80
static final boolean DEBUG = false;
static final String DEBUG_address = "0013FDC157C8"; // N6630
81
82
/*83
*
84
* ---- Bluetooth attributes ---85
*/
86
protected UUID uuid = new UUID(0x1101); // serial port profile
87
protected int inquiryMode = DiscoveryAgent.GIAC; // no pairing is
88
needed
89
90
protected int connectionOptions =
91 ServiceRecord.NOAUTHENTICATE_NOENCRYPT;
92
93
/**
94
* ---- Echo loop attributes ---95
*/
96
protected int stopToken = 255;
97
98
/*99
*
* ---- GUI attributes ---100
*/
101
private Command backCommand = new Command("Back", Command.BACK, 1);
102
protected Form infoArea = new Form("Bluetooth Client");
103
protected Vector deviceList = new Vector();
private CameraMIDlet mymidlet;
104
private byte[] imag;
105
106
public DeviceClientCOMM(CameraMIDlet m, byte[] imag) {
107
mymidlet = m;

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

this.imag = imag;
infoArea.setCommandListener(this);
infoArea.addCommand(backCommand);
try {
startApp();
} catch (MIDletStateChangeException ex) {
ex.printStackTrace();
}
}
protected void startApp() throws MIDletStateChangeException {
makeInformationAreaGUI();
if (DEBUG) // skip inquiry in debug mode
{
startServiceSearch(new RemoteDevice(DEBUG_address) {
});
} else {
try {
startDeviceInquiry();
} catch (Throwable t) {
log(t);
}
}
}
/**
------- Device inquiry section ------*/
private void startDeviceInquiry() {
try {
log("Start inquiry method - this will take few seconds...");
DiscoveryAgent agent = getAgent();
agent.startInquiry(inquiryMode, this);
} catch (Exception e) {
log(e);
}
}
public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod) {
log("A device discovered (" + getDeviceStr(btDevice) + ")");
deviceList.addElement(btDevice);
}
public void inquiryCompleted(int discType) {
log("Inquiry compeleted. Please select device from combo box.");
makeDeviceSelectionGUI();
}
/**
------- Service search section ------*/
private void startServiceSearch(RemoteDevice device) {

try {
154
log("Start search for Serial Port Profile service from " +
155
getDeviceStr(device));
156
UUID uuids[] = new UUID[]{uuid};
157
getAgent().searchServices(null, uuids, device, this);
} catch (Exception e) {
158
log(e);
159
}
160
}
161
162
/**
163
* This method is called when a service(s) are discovered.This method
164starts
* a thread that handles the data exchange with the server.
165
*/
166
public void servicesDiscovered(int transId, ServiceRecord[] records) {
167
log("Service discovered.");
for (int i = 0; i < records.length; i++) {
168
ServiceRecord rec = records[i];
169
String url = rec.getConnectionURL(connectionOptions, false);
170
handleConnection(url);
171
}
172
}
173
public void serviceSearchCompleted(int transID, int respCode) {
174
String msg = null;
175
switch (respCode) {
176
case SERVICE_SEARCH_COMPLETED:
177
msg = "the service search completed normally";
178
break;
case
SERVICE_SEARCH_TERMINATED:
179
msg
= "the service search request was cancelled by a call
180
to DiscoveryAgent.cancelServiceSearch()";
181
break;
182
case SERVICE_SEARCH_ERROR:
msg = "an error occurred while processing the request";
183
break;
184
case SERVICE_SEARCH_NO_RECORDS:
185
msg = "no records were found during the service search";
186
break;
187
case SERVICE_SEARCH_DEVICE_NOT_REACHABLE:
msg = "the device specified in the search request could
188
189not be reached or the local device could not establish a connection to the
remote device";
190
break;
191
}
log("Service search completed - " + msg);
192
}
193
194
/*195
*
------- The actual connection handling. ------196
*/
197
private void handleConnection(final String url) {
Thread echo = new Thread() {
198
199

public void run() {


200
StreamConnection stream = null;
201
InputStream in = null;
202
OutputStream out = null;
203
204
try {
log("Connecting to server by url: " + url);
205
stream = (StreamConnection) Connector.open(url);
206
207
log("Bluetooth stream open.");
208
//
InputStream in = stream.openInputStream();
209
out = stream.openOutputStream();
210
in = stream.openInputStream();
startReadThread(in);
211
// String stringImage = Base64.encode(imag);
212
log("Start echo loop.");
213
out.write(imag);
214
out.flush();
//
out.flush();
215
216
//
stream.close();
217
218
} catch (IOException e) {
219
log(e);
220
} finally {
221
log("Bluetooth stream closed.");
if (out != null) {
222
try {
223
224
out.close();
225
stream.close();
226
227
logSet("Image Transfer
228done\n----------------\n\nWaiting for results...");
} catch (IOException e) {
229
log(e);
230
}
231
}
232
}
}
233
};
234
echo.start();
235
}
236
237
private void startReadThread(final InputStream in) {
238
239
Thread reader = new Thread() {
240
public void run() {
241
242
byte[] s = new byte[512];
243
//boolean flag = true;
244
try {
245
while (true) {

int r = in.read(s);
246
247
if (r != -1) {
248
249
logSet(new String(s, 0, r));
250
} else {
251
break;
}
252
253
254
Thread.sleep(200);
255
}
256
} catch (Throwable e) {
257
log(e);
258
259
} finally {
if (in != null) {
260
try {
261
in.close();
262
} catch (IOException e) {
263
}
}
264
}
265
}
266
};
267
reader.start();
268
}
269
/*270
*
------- Graphic User Interface section ------271
*/
272
private void makeInformationAreaGUI() {
273
infoArea.deleteAll();
274
Display.getDisplay(mymidlet).setCurrent(infoArea);
}
275
276
private void makeDeviceSelectionGUI() {
277
final List devices = new List("Select a device", List.IMPLICIT);
278
for (int i = 0; i < deviceList.size(); i++) {
279
devices.append(
getDeviceStr((RemoteDevice) deviceList.elementAt(i)),
280
281null);
}
282
devices.setCommandListener(new
283
284
CommandListener(
) {
285
286
287
288
289
290
291

292
293
public void commandAction(Command arg0,
Displayable arg1)
294
{
295
makeInformationAreaGUI();
296
startServiceSearch((RemoteDevice)
297deviceList.elementAt(devices.getSelectedIndex()));
}
298
});
299
Display.getDisplay(mymidlet).setCurrent(devices);
300
}
301
302
synchronized private void log(String msg) {
303
infoArea.append(msg);
infoArea.append("\n\n");
304
}
305
306
synchronized private void logSet(String msg) {
307
infoArea.deleteAll();
308
infoArea.append(msg);
infoArea.append("\n\n");
309
310
}
311
312
private void log(Throwable e) {
313
log(e.getMessage());
314
}
315
316
/**
------- Utils section - contains utility functions ------317
*/
318
private DiscoveryAgent getAgent() {
319
try {
320
return LocalDevice.getLocalDevice().getDiscoveryAgent();
321
} catch (BluetoothStateException e) {
throw new Error(e.getMessage());
322
}
323
}
324
325
private String getDeviceStr(RemoteDevice btDevice) {
326
return getFriendlyName(btDevice) + " - 0x" +
327btDevice.getBluetoothAddress();
}
328
329
private String getFriendlyName(RemoteDevice btDevice) {
330
try {
331
return btDevice.getFriendlyName(false);
332
} catch (IOException e) {
return "no name available";
333
}
334
}
335
336
public void commandAction(Command arg0, Displayable arg1) {
337
mymidlet.DisplayMainList();

338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358}
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377

The mobile will start searching for the neighbor bluetooth turned on devices after that you will
choose your PC .

_________________
Please recommend my post if you found it helpful.
Posts: 2722
Have thanks: 70 time
For
this
mes
sag
e
the
auth
or
msi
_33
3
has
rece
ived
grat
itud
e:
Bhu
pen
dra

Question subject: Re: Connecting to PC from mobile using bluetooth in java


Posted: Tue Jan 27, 2009 10:14 pm
Hi msi_333, your Post is great! Very useful
But I cannot understand some things ...
I.E. :
What is the meaning of MOBILEOR_GUI ?
Quote:
MOBILEOR_GUI frame;
And what about this?
Quote:
new FrameImage(aa, 1);

SIFT sift = new SIFT(path, "scale2.jpg", "welcome");

I don't know where are these Classes (MOBILEOR_GUI, FrameImage, SIFT)


Sorry for my poor English
If you can send me the complete code of the Server I'll be grateful (eliasturbay@gmail.com)
Thanks in advance

Posts: 1
Have thanks: 0 time

Question subject: Re: Connecting to PC from mobile using bluetooth in java


Posted: Tue Jan 27, 2009 10:26 pm
Hi ,thank you for your reply
these lines of codes not related to the connection of bluetooth , it is related to my project
function , for example , SIFT is an object recognition algorithm .
_________________
Please recommend my post if you found it helpful.
Posts: 2722
Have thanks: 70 time

Question subject: Re: Connecting to PC from mobile using bluetooth in java


Posted: Sat Apr 18, 2009 8:59 pm
please help meeeeeeeee
im an a graduate student and part of my final project is to transfer a text file from a pc to mobile
if we went to transfer text file the uuid not mention and i not found it although i search a lot on it
please help me if you can and the reminder time is very little

Posts: 4
Have thanks: 0 time

Question subject: Re: Connecting to PC from mobile using bluetooth in java


Posted: Mon Apr 20, 2009 6:59 pm
hi thankx it is really working good in iphone.do you have any code for n96 nokia.
________________________
Medical wound Dressings
Heel Pain
Last edited by jack2008 on Thu May 14, 2009 2:39 pm, edited 1 time in total.
Posts: 3
Have thanks: 0 time

Question subject: Re: Connecting to PC from mobile using bluetooth in java


Posted: Mon Apr 27, 2009 8:34 am
hi msi_333 ,
Nice post !
I am facing an small problem with a similar code for just text transfer ,
I have a bluesoliel stack and bluecove library .
when i run the application the device gets discovered fromthe client and stack gets initialized
and the window pops up asking for permission to open up virtual com ports but the application
still ends in a loop waiting for connection , when i use hyperterminal instead of the app i get
read n write back in the client .
init:
deps-jar:
compile:
BlueCove version 2.0.2 on bluesoleil
Create server by uri: btspp://localhost:000011010000100080000 ... ServerCOMM
Waiting for connection...
wat could be the problem please help me out!
sriram

Posts: 1
Have thanks: 0 time

Question subject: Re: Connecting to PC from mobile using bluetooth in java


Posted: Mon Apr 27, 2009 5:28 pm
this gonna be helpful to me, thanks for sharing the code for java

Airtel :
To Transfer Balance In Airtel Just Dial *141# And Follow The Onscreen Instructions.
You Can Transfer From 5 To 30 Rupees Of Balance In Airtel.

Tata Docomo :
To Transfer Balance In Tata Docomo SMS as BT MobileNumber Amount And Send It To
54321.
E.g. BT 9876543210 30 To Transfer 30 Rupees Of Balance.

!dea :
To Transfer Balance In !dea Network Send SMS as GIVE MobileNumber Amount And
Send It To 55567.
E.g. GIVE 9876543210 30 To Transfer 30 Rupees.

Vodafone :
To Transfer Balance In Vodafone Dial *131*Amount*Mobile No#
E.g. *131*50*9876543210# To Transfer 50 Rupees Of Balance.

Uninor :
To Transfer Balance In Uninor Just Dial *202*MobileNumber*Amount#
E.g. *202*9876543210*30# To Transfer 30 Rupees.

Aircel :
To Transfer Balance In Aircel Just Dial *122*666# And Follow The Instructions.
You Can Transfer 10,20 Or 100 Rupees Of Balance.

BSNL :
To Transfer Balance In BSNL Just Send SMS GIFT MobileNumber Amount To 53733.
E.g. GIFT 9876543210 50 To Transfer 50 Rupees Of Balance.

Potrebbero piacerti anche