Total members 11890 |It is currently Thu Apr 25, 2024 5:57 pm Login / Join Codemiles

Java

C/C++

PHP

C#

HTML

CSS

ASP

Javascript

JQuery

AJAX

XSD

Python

Matlab

R Scripts

Weka



Go to page 1, 2, 3  Next


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 bluecove-2.0.2.jar and avetanaObex.jar .
Here is code from it
java code
package sift;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.LocalDevice;
import javax.bluetooth.UUID;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.io.StreamConnectionNotifier;
import javax.swing.ImageIcon;

/**
* A class that demonstrates Bluetooth communication between server mode PC and
* client mode device through serial port profile.
*
* @see sourceforge.net/projects/bluecove : BlueCove - JSR-82
* implementation</a>
*/
public class PCServerCOMM {

/*-
* ================
* Bluetooth Server
* ================
*
* This example application is a straighforward implementation of
* a bluetooth server.
*
*
* Usage
* =====
*
* Start the program. Events are logged by printing them out with standard
* output stream. Once the server is up and ready to accept connections,
* connect to server with client.
*
*
* How it Works
* ============
*
* The application starts a loop to wait for a new connection. After a new
* connection is reseived the connection is handled. In the handling
* operation few tokens and end token is written to connection stream.
* Each read token is logged to standard output. After handling session
* the loop continues by waiting for a new connection.
*
*/

/*-
*
* ---- Bluetooth attributes ----
*/

// serial port profile
protected String UUID = new UUID("1101", true).toString();
protected int discoveryMode = DiscoveryAgent.GIAC; // no paring needed

public static InputStream in;
public static OutputStream out;
private static boolean ServerRun = true;
Image aa;
MOBILEOR_GUI frame;
/*-
*
* ---- Connection handling attributes ----
*/
protected int endToken = 255;

public PCServerCOMM(MOBILEOR_GUI frame) {

this.frame = frame;
ServerRun = true;

try {
LocalDevice device = LocalDevice.getLocalDevice();
device.setDiscoverable(DiscoveryAgent.GIAC);

String url = "btspp://localhost:" + UUID + ";name=PCServerCOMM";

log("Create server by uri: " + url);
StreamConnectionNotifier notifier = (StreamConnectionNotifier) Connector.open(url);

serverLoop(notifier);

} catch (Throwable e) {
log(e);
}
}

private void serverLoop(final StreamConnectionNotifier notifier) {
Thread handler = new Thread() {

@Override
public void run() {
try {
while (ServerRun) { // infinite loop to accept connections.

log("Waiting for connection...");
handleConnection(notifier.acceptAndOpen());
}
} catch (Exception e) {
log(e);
}
try {
Thread.sleep(200);
} catch (InterruptedException ex) {
Logger.getLogger(PCServerCOMM.class.getName()).log(Level.SEVERE, null, ex);
}
}
};
handler.start();
}

private void handleConnection(StreamConnection conn) throws IOException {
out = conn.openOutputStream();
in = conn.openInputStream();
startReadThread(in);
log("Connection found...");
/*
try { // to write some tokens through the bluetooth link
int[] tokens = new int[] { 1, 3, 5, 7, endToken };
for (int i = 0; i < tokens.length; i++) {
out.write(tokens[i]);
out.flush();
log("write:" + tokens[i]);
// wait a sec before next write.
Thread.sleep(1 * 1000);
}
} catch (Exception e) {
log(e);
} finally {
log("Close connection.");
if (conn != null) {
try {
conn.close();
} catch (IOException e) {
}
}
}
* */
}

private void startReadThread(final InputStream in) {

Thread reader = new Thread() {

@Override
public void run() {
FileOutputStream f1 = null;
// System.out.println("Image data");
File directory = new File("C:/Image/");
String path = "image/image.png";
String image = "";


try {
f1 = new FileOutputStream(path,false);
} catch (FileNotFoundException ex) {
Logger.getLogger(PCServerCOMM.class.getName()).log(Level.SEVERE, null, ex);
}
byte[] s = new byte[512];
boolean falg = true;
log("Waiting for image data");
try {
while (true) {

int r = in.read(s);

if (r != -1) {
falg = false;

try {


//s=Base64.decode(new String(s).intern());
// image = image + new String(s,0,r);
f1.write(s, 0, r);
f1.flush();
} catch (IOException e) {
System.out.println("Problems creating the file");
}

}
if (!falg && (r < s.length)) {
// System.out.println("Frame !!!");
f1.flush();
f1.close();
aa = new ImageIcon(path).getImage();
new FrameImage(aa, 1);

SIFT sift = new SIFT(path, "scale2.jpg", "welcome");
frame.setImg(aa);
frame.repaint();
BufferedImage buff = new BufferedImage(aa.getWidth(null), aa.getHeight(null), BufferedImage.TYPE_INT_RGB);
// buff.createGraphics().drawImage(sift.oriented_Image(), 0, 0, null);
// OrientationForm orientionResult = new OrientationForm(buff);
// orientionResult.showOrientationResult();
MOBILEOR_GUI.AppendTostatus(sift.getATree().getMatchingInfo());
// setNearestImages(sift.getNearest_5_imgs());
// frame.createNearestWindow(sift.getNearest_5_imgs(), orientionResult);
// frame.getDisplayNearest().setSize(frame.getDesktopWidth(), 200);
// frame.getDisplayNearest().setLocation(0, orientionResult.getHeight() + 5);
// frame.getDesktop().add(frame.getDisplayNearest());

break;
}
}
} catch (Throwable e) {
log(e);

} finally {
if (in != null) {
try {
log("Image transfering done...");
in.close();

} catch (IOException e) {
}
}
}
}
};
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 -------
*/
}


About the mobile side you can make a midlet and install it on your mobile .Here is some codes :

java code
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Vector;

import javax.bluetooth.BluetoothStateException;
import javax.bluetooth.DeviceClass;
import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.DiscoveryListener;
import javax.bluetooth.LocalDevice;
import javax.bluetooth.RemoteDevice;
import javax.bluetooth.ServiceRecord;
import javax.bluetooth.UUID;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.List;
import javax.microedition.midlet.MIDlet;
import 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.
*
* 3) *Stream handling* communicates with the server through the bluetooth
* link. This example operates in echo loop until stop token is found.
*
*
* Special Debug Mode
* ==================
*
* There's a special debug mode which speeds up development by skipping the
* inquiry method to resolve the remote device. In the debug mode the device's
* bluetooth address is provided by the developer.
*/

/*-
*
* ---- Debug attributes ----
*/
static final boolean DEBUG = false;
static final String DEBUG_address = "0013FDC157C8"; // N6630

/*-
*
* ---- Bluetooth attributes ----
*/
protected UUID uuid = new UUID(0x1101); // serial port profile

protected int inquiryMode = DiscoveryAgent.GIAC; // no pairing is needed

protected int connectionOptions = ServiceRecord.NOAUTHENTICATE_NOENCRYPT;

/*-
*
* ---- Echo loop attributes ----
*/
protected int stopToken = 255;

/*-
*
* ---- GUI attributes ----
*/
private Command backCommand = new Command("Back", Command.BACK, 1);
protected Form infoArea = new Form("Bluetooth Client");
protected Vector deviceList = new Vector();
private CameraMIDlet mymidlet;
private byte[] imag;

public DeviceClientCOMM(CameraMIDlet m, byte[] imag) {
mymidlet = m;
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 {
log("Start search for Serial Port Profile service from " + getDeviceStr(device));
UUID uuids[] = new UUID[]{uuid};
getAgent().searchServices(null, uuids, device, this);
} catch (Exception e) {
log(e);
}
}

/**
* This method is called when a service(s) are discovered.This method starts
* a thread that handles the data exchange with the server.
*/
public void servicesDiscovered(int transId, ServiceRecord[] records) {
log("Service discovered.");
for (int i = 0; i < records.length; i++) {
ServiceRecord rec = records[i];
String url = rec.getConnectionURL(connectionOptions, false);
handleConnection(url);
}
}

public void serviceSearchCompleted(int transID, int respCode) {
String msg = null;
switch (respCode) {
case SERVICE_SEARCH_COMPLETED:
msg = "the service search completed normally";
break;
case SERVICE_SEARCH_TERMINATED:
msg = "the service search request was cancelled by a call to DiscoveryAgent.cancelServiceSearch()";
break;
case SERVICE_SEARCH_ERROR:
msg = "an error occurred while processing the request";
break;
case SERVICE_SEARCH_NO_RECORDS:
msg = "no records were found during the service search";
break;
case SERVICE_SEARCH_DEVICE_NOT_REACHABLE:
msg = "the device specified in the search request could not be reached or the local device could not establish a connection to the remote device";
break;
}
log("Service search completed - " + msg);
}

/*-
* ------- The actual connection handling. -------
*/
private void handleConnection(final String url) {
Thread echo = new Thread() {

public void run() {
StreamConnection stream = null;
InputStream in = null;
OutputStream out = null;

try {
log("Connecting to server by url: " + url);
stream = (StreamConnection) Connector.open(url);

log("Bluetooth stream open.");
// InputStream in = stream.openInputStream();
out = stream.openOutputStream();
in = stream.openInputStream();
startReadThread(in);
// String stringImage = Base64.encode(imag);
log("Start echo loop.");
out.write(imag);
out.flush();
// out.flush();

// stream.close();

} catch (IOException e) {
log(e);
} finally {
log("Bluetooth stream closed.");
if (out != null) {
try {

out.close();
stream.close();

logSet("Image Transfer done\n----------------\n\nWaiting for results...");
} catch (IOException e) {
log(e);
}
}
}
}
};
echo.start();
}

private void startReadThread(final InputStream in) {

Thread reader = new Thread() {

public void run() {

byte[] s = new byte[512];
//boolean flag = true;
try {
while (true) {
int r = in.read(s);

if (r != -1) {

logSet(new String(s, 0, r));
} else {
break;
}


Thread.sleep(200);
}
} catch (Throwable e) {
log(e);

} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
}
}
}
}
};
reader.start();
}

/*-
* ------- Graphic User Interface section -------
*/
private void makeInformationAreaGUI() {
infoArea.deleteAll();
Display.getDisplay(mymidlet).setCurrent(infoArea);
}

private void makeDeviceSelectionGUI() {
final List devices = new List("Select a device", List.IMPLICIT);
for (int i = 0; i < deviceList.size(); i++) {
devices.append(
getDeviceStr((RemoteDevice) deviceList.elementAt(i)), null);
}
devices.setCommandListener(new

CommandListener( ) {








public void commandAction(Command arg0,
Displayable arg1)
{
makeInformationAreaGUI();
startServiceSearch((RemoteDevice) deviceList.elementAt(devices.getSelectedIndex()));
}
});
Display.getDisplay(mymidlet).setCurrent(devices);
}

synchronized private void log(String msg) {
infoArea.append(msg);
infoArea.append("\n\n");
}

synchronized private void logSet(String msg) {
infoArea.deleteAll();
infoArea.append(msg);
infoArea.append("\n\n");

}

private void log(Throwable e) {
log(e.getMessage());
}

/*-
* ------- Utils section - contains utility functions -------
*/
private DiscoveryAgent getAgent() {
try {
return LocalDevice.getLocalDevice().getDiscoveryAgent();
} catch (BluetoothStateException e) {
throw new Error(e.getMessage());
}
}

private String getDeviceStr(RemoteDevice btDevice) {
return getFriendlyName(btDevice) + " - 0x" + btDevice.getBluetoothAddress();
}

private String getFriendlyName(RemoteDevice btDevice) {
try {
return btDevice.getFriendlyName(false);
} catch (IOException e) {
return "no name available";
}
}

public void commandAction(Command arg0, Displayable arg1) {
mymidlet.DisplayMainList();
}
}


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



_________________
M. S. Rakha, Ph.D.
Queen's University
Canada


Author:
Mastermind
User avatar Posts: 2715
Have thanks: 74 time

For this message the author DrRakha has received gratitude : Bhupendra

Hi msi_333, your Post is great! Very useful :gOOd:

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) :read:

Sorry for my poor English

If you can send me the complete code of the Server I'll be grateful ([email protected])

Thanks in advance


Author:
Newbie
User avatar Posts: 1
Have thanks: 0 time

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 .

_________________
M. S. Rakha, Ph.D.
Queen's University
Canada


Author:
Mastermind
User avatar Posts: 2715
Have thanks: 74 time

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


Author:
Newbie
User avatar Posts: 4
Have thanks: 0 time

hi thankx it is really working good in iphone.do you have any code for n96 nokia.


Last edited by jack2008 on Thu May 14, 2009 2:39 pm, edited 1 time in total.

Author:
Newbie
User avatar Posts: 3
Have thanks: 0 time

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


Author:
Newbie
User avatar Posts: 1
Have thanks: 0 time

this gonna be helpful to me, thanks for sharing the code for java


Author:
Newbie
User avatar Posts: 1
Have thanks: 0 time

hi friend can u pls send me the code of ur MOBILEOR_GUI? hope u will grant my wish...[[email protected]]


Author:
Newbie
User avatar Posts: 2
Have thanks: 0 time

hi friend.....can u pls send me the whole program? hope u will grant my wish....i am a student willing to learn the know-hows of bluetooth. [[email protected]]


Author:
Newbie
User avatar Posts: 2
Have thanks: 0 time

HI
Msi_33

plz you send code of whole program .i am student .i am very much interested in computer program to know some good good
program so that my knowlegage became good in computer


so plz you send me this complete code and some of brief description to my email id :
[email protected]


Author:
Newbie
User avatar Posts: 3
Have thanks: 0 time
Post new topic Reply to topic  [ 21 posts ]  Go to page 1, 2, 3  Next

  Related Posts  to : Connecting to PC from mobile using bluetooth in java
 connecting to pc from mobile using bluetooth in java     -  
 connecting PC with mobile using bluetooth code in java     -  
 mobile to pc in bluetooth in java     -  
 sending sms from bluetooth mobile to pc     -  
 Mobile to PC connection using Bluetooth     -  
 i want code for connecting mobile and pc can u send me code     -  
 bluetooth communication in java     -  
 Connecting Java Application to C++ Application from Code     -  
 java mobile apps     -  
 Java Program for communicate PC and Mobile     -  



Topic Tags

Java J2ME, Java Networking
cron





Powered by phpBB © 2000, 2002, 2005, 2007 phpBB Group
All copyrights reserved to codemiles.com 2007-2011
mileX v1.0 designed by codemiles team
Codemiles.com is a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for sites to earn advertising fees by advertising and linking to Amazon.com