Total members 11892 |It is currently Fri Sep 20, 2024 9:33 pm Login / Join Codemiles

Java

C/C++

PHP

C#

HTML

CSS

ASP

Javascript

JQuery

AJAX

XSD

Python

Matlab

R Scripts

Weka



Go to page Previous  1, 2, 3  Next


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
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 <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

    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 :

Code:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

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 .


hi can you help me about the code snack?




Author:
Newbie
User avatar Posts: 1
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 1167 times
File comment: client side code:
EchoClient.txt [7.96 KiB]
Downloaded 1159 times
Author:
Newbie
User avatar Posts: 3
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());

Robot robo=new Robot();


while(true){
// String cmd = "";
char c;
while (((c = din.readChar()) > 0) && (c!='\n') ){
// cmd = cmd + c;

/* System.out.println("Received " + cmd);
msg=Integer.parseInt(cmd);
System.out.println("Received " + cmd);*/

System.out.println("Received " + c);
// System.out.println("Rece " + msg);

if(c=='G')
{
robo.mouseMove(x1,y1);
x1=x1-10;
}
else if(c=='A')
{
robo.mouseMove(x1,y1);
y1=y1-10;
}
else if(c=='M')
{
robo.mouseMove(x1,y1);
x1=x1+10;
}
else if(c=='T')
{
robo.mouseMove(x1,y1);
y1=y1+10;
}
else if(c=='J')
{
robo.mousePress(InputEvent.BUTTON1_MASK);
robo.mousePress(InputEvent.BUTTON1_MASK);
// robo.mouseRelease(InputEvent.BUTTON1_MASK);
// robo.keyPress(KeyEvent.VK_ENTER);
// robo.keyRelease(KeyEvent.VK_ENTER);
robo.mouseRelease(InputEvent.BUTTON1_MASK);
// robo.mousePress(InputEvent.BUTTON1_MASK);
robo.mouseRelease(InputEvent.BUTTON1_MASK);


}






}


// System.out.println("Received " + cmd);
}

} catch (Exception e) {System.out.println("Exception Occured: " + e.toString());}
}

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);

main_list.addCommand(exit);
main_list.setCommandListener(this);
dev_list.addCommand(exit);
dev_list.setCommandListener(this);
// cmd.addCommand(ok);
// cmd.setCommandListener(this);



main_list.append("Find Echo Server",null);
display.setCurrent(main_list);


}
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{

dout.writeChars(key1);
//dout.writeChars(cmd.getString() + "\n");
dout.flush();
cmd.setString("");
} catch (Exception e) {this.do_alert("Error sending data" , 4000);}
}
}

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);

}
protected void keyPressed(int keyCode)
{

key1=Integer.toString(keyCode);
commandAction(ok, null);
}

/* protected void keyReleased(int keyCode)
{
if (keyCode > 0) {
System.out.println("keyReleased " + ((char) keyCode));
}
else {
System.out.println("keyReleased action " + getGameAction(keyCode));
}
}*/
};

display.setCurrent(canvas);


public void pauseApp() {}

public void destroyApp(boolean unconditional) {}

}


Author:
Newbie
User avatar Posts: 3
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:[email protected]

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());

            Robot robo=new Robot();


            while(true){
               // String cmd = "";
                char c;
                while (((c = din.readChar()) > 0) && (c!='\n') ){
                 //   cmd = cmd + c;
               
  /* System.out.println("Received " + cmd);
                msg=Integer.parseInt(cmd);
                   System.out.println("Received " + cmd);*/

                System.out.println("Received " + c);
           //   System.out.println("Rece " + msg);

             if(c=='G')
            {
                robo.mouseMove(x1,y1);
                x1=x1-10;
            }
            else if(c=='A')
            {
                robo.mouseMove(x1,y1);
                y1=y1-10;
            }
            else if(c=='M')
            {
                robo.mouseMove(x1,y1);
                x1=x1+10;
            }
            else if(c=='T')
            {
                robo.mouseMove(x1,y1);
                y1=y1+10;
            }
            else if(c=='J')
            {
                robo.mousePress(InputEvent.BUTTON1_MASK);
                robo.mousePress(InputEvent.BUTTON1_MASK);
               // robo.mouseRelease(InputEvent.BUTTON1_MASK);
              //  robo.keyPress(KeyEvent.VK_ENTER);
               // robo.keyRelease(KeyEvent.VK_ENTER);
                robo.mouseRelease(InputEvent.BUTTON1_MASK);
           //     robo.mousePress(InputEvent.BUTTON1_MASK);
               robo.mouseRelease(InputEvent.BUTTON1_MASK);


            }






                }


             //   System.out.println("Received " + cmd);
            }

        } catch (Exception  e) {System.out.println("Exception Occured: " + e.toString());}
    }

    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);

    main_list.addCommand(exit);
    main_list.setCommandListener(this);
    dev_list.addCommand(exit);
    dev_list.setCommandListener(this);
  //  cmd.addCommand(ok);
   // cmd.setCommandListener(this);



    main_list.append("Find Echo Server",null);
    display.setCurrent(main_list);


    }
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{

            dout.writeChars(key1);
            //dout.writeChars(cmd.getString() + "\n");
            dout.flush();
            cmd.setString("");
        } catch (Exception e) {this.do_alert("Error sending data" , 4000);}
    }
}

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);

                        }
                       protected void keyPressed(int keyCode)
                       {

                           key1=Integer.toString(keyCode);
                           commandAction(ok, null);
                       }

                     /* protected void keyReleased(int keyCode)
                      {
                      if (keyCode > 0) {
                        System.out.println("keyReleased " + ((char) keyCode));
                        }
                      else {
                           System.out.println("keyReleased action " + getGameAction(keyCode));
                           }
                      }*/
                   };

          display.setCurrent(canvas);


public void pauseApp() {}

public void destroyApp(boolean unconditional) {}

}

pls give me reply quick...
Thank you in advanced....


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

SIFT package is for object recognition and it will not help you brother .

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


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

thaaaaaaaanks msi

I did the second code for mobile

But I have problem in the last line ( mymidlet.DisplayMainList(); )

the output window show this:

Quote:
cannot find symbol
symbol : method DisplayMainList()
location: class CameraMIDlet
mymidlet.DisplayMainList();


can you help me to answer this problem

thanks in advanced and sorry for my poor english


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

Hi,

Thanks you very much for sharing above information with us.

I was able to compile the server code successfully but there was exception error when I try to run this code.

The exception occurs at:

LocalDevice device = LocalDevice.getLocalDevice();

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.


Author:
Newbie
User avatar Posts: 6
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.


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

Code:
www.codemiles.com/java/java-program-for-communicate-pc-and-mobile-t8417.html


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


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

it is a another error can you please post the exception trace.

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


Author:
Mastermind
User avatar Posts: 2715
Have thanks: 74 time
Post new topic Reply to topic  [ 21 posts ]  Go to page Previous  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     -  
 Mobile to PC connection using Bluetooth     -  
 sending sms from bluetooth mobile to pc     -  
 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 Networking, Java J2ME
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