Bluetooth connection. Problem with sony ericsson.

Posted by Hugi on Stack Overflow See other posts from Stack Overflow or by Hugi
Published on 2010-03-23T20:06:31Z Indexed on 2010/03/23 20:13 UTC
Read the original article Hit count: 421

Filed under:
|
|

I have bt client and server. Then i use method Connector.open, client connects to the port, but passed so that my server does not see them. Nokia for all normal, but with sony ericsson i have this problem. On bt adapter open one port (com 5).

Listings Client

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

import java.util.Vector;

import javax.bluetooth.*;

import javax.microedition.midlet.*;

import javax.microedition.lcdui.*;

import javax.microedition.io.*;

import java.io.*;



/**
 * @author ?????????????
 */
public class Client extends MIDlet implements DiscoveryListener, CommandListener
{
    private static Object lock=new Object();

    private static Vector vecDevices=new Vector();

    private ServiceRecord[] servRec = new ServiceRecord[INQUIRY_COMPLETED];

    private Form form = new Form( "Search" );

    private List voteList = new List( "Vote list", List.IMPLICIT );
    private List vote = new List( "", List.EXCLUSIVE );

    private RemoteDevice remoteDevice;

    private String connectionURL = null;

    protected int stopToken = 255;

    private Command select = null;

    public void startApp()
    {
        //view form
        Display.getDisplay(this).setCurrent(form);

        try {
            //device search
            print("Starting device inquiry...");
            getAgent().startInquiry(DiscoveryAgent.GIAC, this);

            try {
                synchronized(lock){
                    lock.wait();
                }
            }catch (InterruptedException e) {
                e.printStackTrace();
            }

            //device count
            int deviceCount=vecDevices.size();

            if(deviceCount <= 0) {
                print("No Devices Found .");
            } else{
                    remoteDevice=(RemoteDevice)vecDevices.elementAt(0);

                    print( "Server found" );
                    //create uuid
                    UUID uuid = new UUID(0x1101);
                    UUID uuids[] = new UUID[] { uuid };

                    //search service
                    print( "Searching for service..." );
                    getAgent().searchServices(null,uuids,remoteDevice,this);                   
            }
        } catch( Exception e) {
            e.printStackTrace();
        }
    }

    //if deivce discovered add to vecDevices
    public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod) {
        //add the device to the vector
        try {
            if(!vecDevices.contains(btDevice) && btDevice.getFriendlyName(true).equals("serverHugi")){
                vecDevices.addElement(btDevice);
            }
        } catch( IOException e ) {
        }
    }

    public synchronized void servicesDiscovered(int transID, ServiceRecord[] servRecord) {
        //for each service create connection
        if( servRecord!=null && servRecord.length>0 ){
            print( "Service found" );
            connectionURL = servRecord[0].getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT,false);
            //connectionURL = servRecord[0].getConnectionURL(ServiceRecord.AUTHENTICATE_NOENCRYPT,false);
        }

         if ( connectionURL != null ) {
             showVoteList();
         }
    }

    public void serviceSearchCompleted(int transID, int respCode) {
        //print( "serviceSearchCompleted" );
        synchronized(lock){
            lock.notify();
        }
    }



    //This callback method will be called when the device discovery is completed.
    public void inquiryCompleted(int discType) {
        synchronized(lock){
            lock.notify();
        }

        switch (discType) {
            case DiscoveryListener.INQUIRY_COMPLETED :
                print("INQUIRY_COMPLETED");
                break;
            case DiscoveryListener.INQUIRY_TERMINATED :
                print("INQUIRY_TERMINATED");
                break;
            case DiscoveryListener.INQUIRY_ERROR :
                print("INQUIRY_ERROR");
                break;
            default :
                print("Unknown Response Code");
                break;
        }
    }

    //add message at form
    public void print( String msg ) {
        form.append( msg );
        form.append( "\n\n" );
    }

    public void pauseApp() {
    }

    public void destroyApp(boolean unconditional) {
    }

    //get agent :)))
    private DiscoveryAgent getAgent() {
        try {
            return LocalDevice.getLocalDevice().getDiscoveryAgent();
        } catch (BluetoothStateException e) {
            throw new Error(e.getMessage());
        }
    }

    private synchronized String getMessage( final String send ) {
                StreamConnection stream = null;
                DataInputStream in = null;
                DataOutputStream out = null;
                String r = null;

                try {
                    //open connection
                    stream = (StreamConnection) Connector.open(connectionURL);

                    in = stream.openDataInputStream();
                    out = stream.openDataOutputStream();

                    out.writeUTF( send );
                    out.flush();

                    r = in.readUTF();
                    print( r );

                    in.close();
                    out.close();
                    stream.close();
                    return r;
                } catch (IOException e) {
                } finally {
                    if (stream != null) {
                        try {
                            stream.close();
                        } catch (IOException e) {
                        }
                    }
                    return r;
                }   
    }


    private synchronized void showVoteList() {
       String votes = getMessage( "c_getVotes" );
       voteList.append( votes, null );

       select = new Command( "Select", Command.OK, 4 );

       voteList.addCommand( select );
       voteList.setCommandListener( this );
       Display.getDisplay(this).setCurrent(voteList);
    }

    private synchronized void showVote( int index ) {
       String title = getMessage( "c_getVote_"+index );

       vote.setTitle( title );
       vote.append( "Yes", null );
       vote.append( "No", null );
       vote.setCommandListener( this );
       Display.getDisplay(this).setCurrent(vote);
    }

    public void commandAction( Command c, Displayable d ) {
        if ( c == select && d == voteList ) {
            int index = voteList.getSelectedIndex();
            print( ""+index );
            showVote( index );
        }
    }
}

Use BlueCove in this program.

Server

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

package javaapplication4;

import java.io.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import javax.bluetooth.*;
import javax.microedition.io.*;
import javaapplication4.Connect;


/**
 *
 * @author ?????????????
 */
public class SampleSPPServer {
    protected static int endToken = 255;
    private static Lock lock=new ReentrantLock();
    private static StreamConnection conn = null;
    private static StreamConnectionNotifier streamConnNotifier = null;


    private void startServer() throws IOException{
         //Create a UUID for SPP
        UUID uuid = new UUID("1101", true);
        //Create the service url
        String connectionString = "btspp://localhost:" + uuid +";name=Sample SPP Server";
        //open server url
        StreamConnectionNotifier streamConnNotifier = (StreamConnectionNotifier)Connector.open( connectionString );

        while ( true )  {
            Connect ct = new Connect( streamConnNotifier.acceptAndOpen() );
            ct.getMessage();
        }
    }


    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        //display local device address and name
        try {
            LocalDevice localDevice = LocalDevice.getLocalDevice();
            localDevice.setDiscoverable(DiscoveryAgent.GIAC);
            System.out.println("Name: "+localDevice.getFriendlyName());
        } catch( Throwable e ) {
            e.printStackTrace();
        }

        SampleSPPServer sampleSPPServer=new SampleSPPServer();
        try {
            //start server
            sampleSPPServer.startServer();
        } catch( IOException e ) {
            e.printStackTrace();
        }
    }
}

Connect

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

package javaapplication4;

import java.io.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import javax.bluetooth.*;
import javax.microedition.io.*;
/**
 *
 * @author ?????????????
 */
public class Connect  {
    private static DataInputStream in = null;
    private static DataOutputStream out = null;
    private static StreamConnection connection = null;
    private static Lock lock=new ReentrantLock();

    public Connect( StreamConnection conn  ) {
        connection = conn;
    }


    public synchronized void getMessage( ) {
        Thread t = new Thread() {
                        public void run() {
                try {
                    in = connection.openDataInputStream();
                    out = connection.openDataOutputStream();

                    String r = in.readUTF();

                    System.out.println("read:" + r);

                    if ( r.equals( "c_getVotes" ) ) {
                        out.writeUTF( "vote1" );
                        out.flush();
                    }

                    if ( r.equals( "c_getVote_0" ) ) {
                        out.writeUTF( "Vote1" );
                        out.flush();
                    }

                    out.close();
                    in.close();
                } catch (Throwable e) {
                } finally {
                    if (in != null) {
                        try {
                            in.close();
                        } catch (IOException e) {
                        }
                    }
                    try {
                    connection.close();
                    } catch( IOException e ) {
                    }
                }
         }
         };
         t.start();
    }
}

© Stack Overflow or respective owner

Related posts about bluetooth

Related posts about java