Question subject: Re: Connecting to PC from mobile using bluetooth in java
Posted: Mon Nov 16, 2009 10:08 pm
Joined: Mon Nov 16, 2009 9:23 pm Posts: 1 Has thanked: 1 time Have thanks: 0 time
msi_333 wrote:
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
/** * A class that demonstrates Bluetooth communication between server mode PC and * client mode device through serial port profile. * * @see <a href="http://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
} if (!falg && (r < s.length)) { // System.out.println("Frame !!!"); f1.flush(); f1.close(); aa = new ImageIcon(path).getImage(); new FrameImage(aa, 1);
/** * 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. */
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();
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
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 .
hi can you help me about the code snack?
kirit
Question subject: Re: Connecting to PC from mobile using bluetooth in java
Posted: Fri Mar 12, 2010 11:25 am
Joined: Fri Mar 12, 2010 11:17 am Posts: 3 Has thanked: 0 time Have thanks: 0 time
i need to your sift package to run your program.because i have lots of error without this package. pls.. send me...
i am student of B.E. IT. My final year project is control pc using mobile via bluetooth. I have problem to transfer file or image without press any key or command action .I send both the file server & client .
pls reply me quickly
Attachments:
File comment: Server side code: EchoServer.java [3.15 KiB]
Downloaded 209 times
File comment: client side code: EchoClient.txt [7.96 KiB]
Downloaded 189 times
kirit
Question subject: Re: Connecting to PC from mobile using bluetooth in java
Posted: Fri Mar 12, 2010 11:38 am
Joined: Fri Mar 12, 2010 11:17 am Posts: 3 Has thanked: 0 time Have thanks: 0 time
In our project we can not send string or charecter from client(mobile) to server(pc) without press button or without calling command action method.
If you have code in which we send data without press any button in mobile plss send me or give me link or another related information about this topic. thanks in advance...
our project topic is controling pc using mobile
server side code is
import java.io.*; import javax.bluetooth.*; import javax.microedition.io.*; import java.awt.Robot; import java.awt.event.InputEvent; public class EchoServer {
private int x1=450; private int y1=550;
int msg;
public final UUID uuid = new UUID( //the uid of the service, it has to be unique, "27012f0c68af4fbf8dbe6bbaf7aa432a", false); //it can be generated randomly public final String name = "Echo Server"; //the name of the service public final String url = "btspp://localhost:" + uuid //the service url + ";name=" + name + ";authenticate=false;encrypt=false;"; LocalDevice local = null; StreamConnectionNotifier server = null; StreamConnection conn = null;
public EchoServer() { try { System.out.println("Setting device to be discoverable..."); local = LocalDevice.getLocalDevice(); local.setDiscoverable(DiscoveryAgent.GIAC); System.out.println("Start advertising service..."); server = (StreamConnectionNotifier)Connector.open(url); System.out.println("Waiting for incoming connection..."); conn = server.acceptAndOpen(); System.out.println("Client Connected..."); DataInputStream din = new DataInputStream(conn.openInputStream());
public static void main (String args[]){ EchoServer echoserver = new EchoServer(); }
}
client side code:
import javax.microedition.midlet.*; import javax.microedition.lcdui.*; import javax.microedition.io.*; import javax.bluetooth.*; import java.io.*; public class EchoClient extends MIDlet implements CommandListener,DiscoveryListener { List main_list,dev_list; Command exit,ok; TextBox cmd; Display display; java.util.Vector devices,services; LocalDevice local; DiscoveryAgent agent; DataOutputStream dout; int currentDevice = 0; String key1; //used as an indicator to the device queried for //the echo server
public void startApp() { main_list = new List("Echo Server",Choice.IMPLICIT); //the main menu dev_list = new List("Select Device",Choice.IMPLICIT); //the list of devices // cmd = new TextBox("Text to echo","",120,TextField.ANY); exit = new Command("Exit",Command.EXIT,1); ok = new Command("Send",Command.OK,1); display = Display.getDisplay(this);
} public void commandAction(Command com, Displayable dis) { if (com == exit){ //exit triggered from the main form destroyApp(false); notifyDestroyed(); } if (com == List.SELECT_COMMAND){ if (dis == main_list){ //select triggered from the main from if (main_list.getSelectedIndex() >= 0){ //find devices FindDevices(); do_alert("Searching for devices...", Alert.FOREVER); } } if (dis == dev_list){ //select triggered from the device list StreamConnection conn = null; ServiceRecord service = (ServiceRecord) services.elementAt(dev_list.getSelectedIndex()); String url = service.getConnectionURL( ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false); try { conn = (StreamConnection) Connector.open(url); //establish the connection dout = new DataOutputStream(conn.openOutputStream());//Get the output stream display.setCurrent(cmd); //Show the textbox } catch (Exception e) {this.do_alert("Error Connecting" , 4000);}
} } if(com == ok){ //the user is sending a command try{
public void FindDevices(){ try{ devices = new java.util.Vector(); LocalDevice local = LocalDevice.getLocalDevice(); DiscoveryAgent agent = local.getDiscoveryAgent(); agent.startInquiry(DiscoveryAgent.GIAC,this); }catch(Exception e){this.do_alert("Erron in initiating search" , 4000);} }
public void FindServices(RemoteDevice device){ try{ UUID[] uuids = new UUID[1]; uuids[0] = new UUID("27012f0c68af4fbf8dbe6bbaf7aa432a",false); //The UUID of the ech service local = LocalDevice.getLocalDevice(); agent = local.getDiscoveryAgent(); agent.searchServices(null,uuids,device,this); }catch(Exception e){this.do_alert("Erron in initiating search" , 4000);} }
public void deviceDiscovered(RemoteDevice remoteDevice,DeviceClass deviceClass) { devices.addElement(remoteDevice); }
public void servicesDiscovered(int transID,ServiceRecord[] serviceRecord) { for (int x = 0; x < serviceRecord.length; x++ ) services.addElement(serviceRecord[x]); try{ dev_list.append(((RemoteDevice)devices.elementAt(currentDevice)). getFriendlyName(false),null); }catch(Exception e){this.do_alert("Erron in initiating search" , 4000);} } public void inquiryCompleted(int param){ switch (param) { case DiscoveryListener.INQUIRY_COMPLETED: //Inquiry completed normally if (devices.size() > 0){ //Atleast one device has been found services = new java.util.Vector(); this.FindServices((RemoteDevice) devices.elementAt(0)); //Check if the first device offers the service }else do_alert("No device found in range",4000); break; case DiscoveryListener.INQUIRY_ERROR: // Error during inquiry this.do_alert("Inqury error" , 4000); break; case DiscoveryListener.INQUIRY_TERMINATED: // Inquiry terminated by agent.cancelInquiry() this.do_alert("Inqury Canceled" , 4000); break; } }
public void serviceSearchCompleted(int transID, int respCode) { switch(respCode) { case DiscoveryListener.SERVICE_SEARCH_COMPLETED: if(currentDevice == devices.size() -1){ //all devices have been searched if(services.size() > 0){ display.setCurrent(dev_list); }else do_alert("The service was not found",4000); }else{ //search next device currentDevice++; this.FindServices((RemoteDevice)devices.elementAt(currentDevice)); } break; case DiscoveryListener.SERVICE_SEARCH_DEVICE_NOT_REACHABLE: this.do_alert("Device not Reachable" , 4000); break; case DiscoveryListener.SERVICE_SEARCH_ERROR: this.do_alert("Service serch error" , 4000); break; case DiscoveryListener.SERVICE_SEARCH_NO_RECORDS: this.do_alert("No records returned" , 4000); break; case DiscoveryListener.SERVICE_SEARCH_TERMINATED: this.do_alert("Inqury Cancled" , 4000); break; } }
public void do_alert(String msg,int time_out){ if (display.getCurrent() instanceof Alert ){ ((Alert)display.getCurrent()).setString(msg); ((Alert)display.getCurrent()).setTimeout(time_out); }else{ Alert alert = new Alert("Bluetooth"); alert.setString(msg); alert.setTimeout(time_out); display.setCurrent(alert); } }
Canvas canvas = new Canvas() { // anonymous class public void paint(Graphics g) { g.setColor(255, 255, 255); g.fillRect(0, 0, getWidth(), getHeight()); g.setColor(255, 0, 0); g.drawString(key1, 100, 100, Graphics.TOP|Graphics.LEFT);
Question subject: Re: Connecting to PC from mobile using bluetooth in java
Posted: Fri Mar 12, 2010 11:51 am
Joined: Fri Mar 12, 2010 11:17 am Posts: 3 Has thanked: 0 time Have thanks: 0 time
Hi i am kirit. pls give me your complete code to run.i want to know how it actualy work.. Our project on control pc using mobile via bluetooth. I have problem sending image or file without press button or any command action. pls send me your complete code.. i send u my code so u better understand....... Give me link or any other related information pls send me Email:kirit_dholakiya@yahoo.com
server side code:
Code:
import java.io.*; import javax.bluetooth.*; import javax.microedition.io.*; import java.awt.Robot; import java.awt.event.InputEvent; public class EchoServer {
private int x1=450; private int y1=550;
int msg;
public final UUID uuid = new UUID( //the uid of the service, it has to be unique, "27012f0c68af4fbf8dbe6bbaf7aa432a", false); //it can be generated randomly public final String name = "Echo Server"; //the name of the service public final String url = "btspp://localhost:" + uuid //the service url + ";name=" + name + ";authenticate=false;encrypt=false;"; LocalDevice local = null; StreamConnectionNotifier server = null; StreamConnection conn = null;
public EchoServer() { try { System.out.println("Setting device to be discoverable..."); local = LocalDevice.getLocalDevice(); local.setDiscoverable(DiscoveryAgent.GIAC); System.out.println("Start advertising service..."); server = (StreamConnectionNotifier)Connector.open(url); System.out.println("Waiting for incoming connection..."); conn = server.acceptAndOpen(); System.out.println("Client Connected..."); DataInputStream din = new DataInputStream(conn.openInputStream());
public static void main (String args[]){ EchoServer echoserver = new EchoServer(); }
}
client side code:
import javax.microedition.midlet.*; import javax.microedition.lcdui.*; import javax.microedition.io.*; import javax.bluetooth.*; import java.io.*; public class EchoClient extends MIDlet implements CommandListener,DiscoveryListener { List main_list,dev_list; Command exit,ok; TextBox cmd; Display display; java.util.Vector devices,services; LocalDevice local; DiscoveryAgent agent; DataOutputStream dout; int currentDevice = 0; String key1; //used as an indicator to the device queried for //the echo server
public void startApp() { main_list = new List("Echo Server",Choice.IMPLICIT); //the main menu dev_list = new List("Select Device",Choice.IMPLICIT); //the list of devices // cmd = new TextBox("Text to echo","",120,TextField.ANY); exit = new Command("Exit",Command.EXIT,1); ok = new Command("Send",Command.OK,1); display = Display.getDisplay(this);
} public void commandAction(Command com, Displayable dis) { if (com == exit){ //exit triggered from the main form destroyApp(false); notifyDestroyed(); } if (com == List.SELECT_COMMAND){ if (dis == main_list){ //select triggered from the main from if (main_list.getSelectedIndex() >= 0){ //find devices FindDevices(); do_alert("Searching for devices...", Alert.FOREVER); } } if (dis == dev_list){ //select triggered from the device list StreamConnection conn = null; ServiceRecord service = (ServiceRecord) services.elementAt(dev_list.getSelectedIndex()); String url = service.getConnectionURL( ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false); try { conn = (StreamConnection) Connector.open(url); //establish the connection dout = new DataOutputStream(conn.openOutputStream());//Get the output stream display.setCurrent(cmd); //Show the textbox } catch (Exception e) {this.do_alert("Error Connecting" , 4000);}
} } if(com == ok){ //the user is sending a command try{
public void FindDevices(){ try{ devices = new java.util.Vector(); LocalDevice local = LocalDevice.getLocalDevice(); DiscoveryAgent agent = local.getDiscoveryAgent(); agent.startInquiry(DiscoveryAgent.GIAC,this); }catch(Exception e){this.do_alert("Erron in initiating search" , 4000);} }
public void FindServices(RemoteDevice device){ try{ UUID[] uuids = new UUID[1]; uuids[0] = new UUID("27012f0c68af4fbf8dbe6bbaf7aa432a",false); //The UUID of the ech service local = LocalDevice.getLocalDevice(); agent = local.getDiscoveryAgent(); agent.searchServices(null,uuids,device,this); }catch(Exception e){this.do_alert("Erron in initiating search" , 4000);} }
public void deviceDiscovered(RemoteDevice remoteDevice,DeviceClass deviceClass) { devices.addElement(remoteDevice); }
public void servicesDiscovered(int transID,ServiceRecord[] serviceRecord) { for (int x = 0; x < serviceRecord.length; x++ ) services.addElement(serviceRecord[x]); try{ dev_list.append(((RemoteDevice)devices.elementAt(currentDevice)). getFriendlyName(false),null); }catch(Exception e){this.do_alert("Erron in initiating search" , 4000);} } public void inquiryCompleted(int param){ switch (param) { case DiscoveryListener.INQUIRY_COMPLETED: //Inquiry completed normally if (devices.size() > 0){ //Atleast one device has been found services = new java.util.Vector(); this.FindServices((RemoteDevice) devices.elementAt(0)); //Check if the first device offers the service }else do_alert("No device found in range",4000); break; case DiscoveryListener.INQUIRY_ERROR: // Error during inquiry this.do_alert("Inqury error" , 4000); break; case DiscoveryListener.INQUIRY_TERMINATED: // Inquiry terminated by agent.cancelInquiry() this.do_alert("Inqury Canceled" , 4000); break; } }
public void serviceSearchCompleted(int transID, int respCode) { switch(respCode) { case DiscoveryListener.SERVICE_SEARCH_COMPLETED: if(currentDevice == devices.size() -1){ //all devices have been searched if(services.size() > 0){ display.setCurrent(dev_list); }else do_alert("The service was not found",4000); }else{ //search next device currentDevice++; this.FindServices((RemoteDevice)devices.elementAt(currentDevice)); } break; case DiscoveryListener.SERVICE_SEARCH_DEVICE_NOT_REACHABLE: this.do_alert("Device not Reachable" , 4000); break; case DiscoveryListener.SERVICE_SEARCH_ERROR: this.do_alert("Service serch error" , 4000); break; case DiscoveryListener.SERVICE_SEARCH_NO_RECORDS: this.do_alert("No records returned" , 4000); break; case DiscoveryListener.SERVICE_SEARCH_TERMINATED: this.do_alert("Inqury Cancled" , 4000); break; } }
public void do_alert(String msg,int time_out){ if (display.getCurrent() instanceof Alert ){ ((Alert)display.getCurrent()).setString(msg); ((Alert)display.getCurrent()).setTimeout(time_out); }else{ Alert alert = new Alert("Bluetooth"); alert.setString(msg); alert.setTimeout(time_out); display.setCurrent(alert); } }
Canvas canvas = new Canvas() { // anonymous class public void paint(Graphics g) { g.setColor(255, 255, 255); g.fillRect(0, 0, getWidth(), getHeight()); g.setColor(255, 0, 0); g.drawString(key1, 100, 100, Graphics.TOP|Graphics.LEFT);
I was not able to correct the above error so I'm very thankful to you if you can give me some guides for over come this error.
Best Regards, Aruna.
ArunaR
Question subject: Re: Connecting to PC from mobile using bluetooth in java
Posted: Thu Dec 15, 2011 6:10 am
Joined: Tue Dec 06, 2011 6:58 am Posts: 6 Has thanked: 1 time Have thanks: 1 time
HIi msi_333,
I was able to correct the above error
Your Client program is still giving error! it says "MIDlet initialization failed". I still couldn't able to find a solution for this because I still didn't able to dig down the code.
Anybody have a clue regarding this?
Thanks, Aruna.
msi_333
Question subject: Re: Connecting to PC from mobile using bluetooth in java
Posted: Sun Dec 18, 2011 9:30 pm
Joined: Tue Mar 27, 2007 10:55 pm Posts: 2103 Location: Earth Has thanked: 39 time Have thanks: 57 time