www.mikrocontroller.net

Forum: PC-Programmierung Bluetooth verbindung


Autor: Bob Hulu (Firma: hinter den 7 bergen) (bob128)
Datum:

Bewertung
0 lesenswert
nicht lesenswert
Hi ich bin gerade dabei eine Bluetooth Verbindung zwischen meinem 
Laptop(BlueSoleil USB Stick) und einem Free2Move F2M03GXA Bluetooth 
Modul herzustellen. Mit der mitgelieferten Software hat es geklappt eine 
Verbindung aufzubauen und Daten auszutauschen.
Jetzt will ich das ganze mit java realisieren. Was bisher sehr gut 
klappt ist die Erkennung des BlueSoleil USB Stick also Adresse, Name usw 
wird erkannt. Aber ich hänge fest bei der Suche nach anderen Modulen bzw 
meinem Free2Move Modul. hier mein bisheriger Code:
package bluesoleiltest;

import javax.bluetooth.*;
import com.intel.bluetooth.*;
import com.sun.org.apache.xpath.internal.FoundIndex;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.bluetooth.RemoteDevice;
import javax.bluetooth.ServiceRecord;
import javax.microedition.io.StreamConnection;
import javax.microedition.io.Connector;
import javax.microedition.io.*;
import java.io.*;
import java.util.Hashtable;
import java.util.Map;
import javax.bluetooth.UUID;

import java.lang.*;
import java.util.Vector;
import javax.microedition.midlet.MIDlet;
import javax.microedition.lcdui.CommandListener;
import java.util.List;
import javax.bluetooth.*;



public class Main
{

    /**
     * @param args the command line arguments
     */
    private static LocalDevice localdevice;  //local Bluetooth Manager
    private static DiscoveryAgent discoveryagent; //discovery agent for clients

          //Bluetooth Service UUID of interest
          private static final String myServiceUUID = "000BCE059FFF"; //Adresse von dem Free2Move Modul
          private static UUID MYSERVICEUUID_UUID = new UUID(myServiceUUID, true);
          //Define the client connecntion URL
          private static String connURL = "btspp://"+ MYSERVICEUUID_UUID.toString() + ":1" + ";master=false" + ";encrypt=false" + ";authenticate=false";
          private static UUID[] uuids = {MYSERVICEUUID_UUID};
          private static int[] attrSet = {0x0000,0x0001,0x0002,0x0003};

          private static final Object serviceSearchSemaphore = new Object();

    public static void main(String[] args)
    {
        Bluetooth bt = new Bluetooth();
        BtClient  btc = new BtClient();

        try
        {
          bt.btInit();
        }
         catch(Exception ex)
         {
            System.out.println("XXX");
         }
        btc.btinitiateDeviceSearch();
        btc.btInitiateServiceSearch();
        btc.btConnect2(MYSERVICEUUID_UUID);

        System.out.println("start");
        getBluetoothInfo();
        System.out.println(LocalDevice.getProperty("bluecove.stack"));

     }

    public static class Bluetooth 
    {
        public void btInit() throws BluetoothStateException
        {
        localdevice = null;
        discoveryagent = null;
        //Retrieve the local device to get to the Bluetooth Manager
            localdevice = LocalDevice.getLocalDevice();
        //Servers set the discoverable mode to GIAC
            localdevice.setDiscoverable(DiscoveryAgent.GIAC);
            discoveryagent = localdevice.getDiscoveryAgent();
            //discoveryagent.startInquiry(DiscoveryAgent.GIAC, this);
        }

        public void btServer()
        {
        try{
        //create a server connection ( a notifier)
        StreamConnectionNotifier scn = (StreamConnectionNotifier) Connector.open(connURL);
         //Accept a new client connection
        StreamConnection sc = scn.acceptAndOpen();
        //New client connection accepted; get a handle on it
        RemoteDevice rd = RemoteDevice.getRemoteDevice(sc);
        System.out.println("New Client connection...." + rd.getFriendlyName(false));
        //Read input message, in this example a String
        DataInputStream dataIn = sc.openDataInputStream();
        String s = dataIn.readUTF();
        //Pass received message to incoming message listener
        System.out.println(s);
        scn.close();
        } catch(IOException e)
          {
           System.out.println(e);
          }
        }
        
       /*
        public void btupdateServiceRecord()
        {
            try{
                //retrieve service record and set/update optional attributes
                //for example ServiceAvailability, indicating service is available
                sr = localdevice.getRecord(scn);
            }
        }*/

    }

    public static class BtClient implements DiscoveryListener
    {
        Map discoveredDevices = new Hashtable();
        Map remoteDevices = new Hashtable();

        //DiscoveryListener Callbacks
        /**
         * deviceDiscovered() is called by the DiscoverAgent when
         * it discovers a device during an inquiry
         */

        /**
         * btInitiateDeviceSearch() kicks off the device discovery
         *
         */
        public void btinitiateDeviceSearch()
        {
            System.out.println("BTMIDLET.btinitiateDeviceSearch");
            int i,s;
            boolean inquiryStarted;

            remoteDevices.clear();
            discoveredDevices.clear();

            RemoteDevice[] cachedDevices = discoveryagent.retrieveDevices(DiscoveryAgent.CACHED);
            if(cachedDevices != null)
            {
                s = cachedDevices.length;
                for(i=0; i<s ; i++)
                {
                    remoteDevices.put(cachedDevices[i].getBluetoothAddress(), cachedDevices[i]);
                }
            }
            RemoteDevice[] preknownDevices = discoveryagent.retrieveDevices(DiscoveryAgent.PREKNOWN);
            if(preknownDevices != null)
            {
                s = preknownDevices.length;
                for(i=0; i<s ; i++)
                {
                    remoteDevices.put(preknownDevices[i].getBluetoothAddress(), preknownDevices[i]);
                }
            }
            try{
                inquiryStarted = discoveryagent.startInquiry(DiscoveryAgent.GIAC, this);
            } catch(BluetoothStateException bse){
                System.out.println("Inquiry Failed " + bse);
                return;
            }
            if(inquiryStarted)
            {
                //Display progress message
                System.out.println("Inquiry in Progress");
            } else {
                //Display error message
                System.out.println("Inquiry Failed");
            }
        }

        /**
         * btInitiateServiceSearch() kicks off the service discovery
         */
        public void btInitiateServiceSearch()
        {
            System.out.println("BTMIDlet.btInitiateServiceSearch");
            int transID,s;

            discoveredDevices.clear();

            //Initiate the service search in the remote device
            s = remoteDevices.size();
            if(s == 0)
            {
                System.out.println("No devices to search...");
            } else
            {
                for(Object obj : remoteDevices.values())
                {
                    RemoteDevice rd = (RemoteDevice) obj;
                    try
                    {
                        transID = discoveryagent.searchServices(attrSet, uuids, rd, this);
                        //Display progress message
                        System.out.println("Service Search in Progress ("+transID+")");
                        synchronized (serviceSearchSemaphore){
                            serviceSearchSemaphore.wait();
                        }
                    } catch(InterruptedException ie)
                    {
                        System.out.println(ie);
                    } catch(BluetoothStateException bse)
                    {
                        System.out.println("Service Search Failed " + bse);
                        return;
                    }
                }
            }
        }

        public void btConnect(final ServiceRecord sr)
        {
            final String test = "World";
            Thread th = new Thread()
            {
                public void run()
                {
                    System.out.println("BTMIDlet.btConnect.run()");
                    RemoteDevice rd = sr.getHostDevice();
                    String connectionURL = sr.getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
                    try
                    {
                        System.out.println("Connecting to " + rd.getFriendlyName(false));
                        System.out.println("Connecting to " + rd.getFriendlyName(false) + ", " + connectionURL);
                        StreamConnection streamconnection = (StreamConnection)Connector.open(connectionURL);
                        DataOutputStream dataout = streamconnection.openDataOutputStream();
                        dataout.writeUTF(test);
                        System.out.println("Closing");
                        streamconnection.close();
                    } catch(IOException ioe)
                    {
                        System.out.println("BTMIDlet.btConnect, exception & " + ioe);
                    }
                }
            };
            th.start();
        }

         public void btConnect2(final UUID uuid)
        {
            final String test = "World";
            Thread th = new Thread()
            {
                public void run()
                {
                    System.out.println("BTMIDlet.btConnect2.run()");
                    try
                    {
                        //Select the Service. indicate no authentication or encryption is required
                        String connectionURL = discoveryagent.selectService(uuid, ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
                        System.out.println("Connecting to " + uuid.toString());
                        StreamConnection streamconnection = (StreamConnection)Connector.open(connectionURL);
                        System.out.println("Sending message out");
                        DataOutputStream dataout = streamconnection.openDataOutputStream();
                        dataout.writeUTF(test);
                        System.out.println("Closing");
                        streamconnection.close();
                    } catch(IOException ioe)
                    {
                        System.out.println("BTMIDlet.btConnect2, exception & " + ioe);
                    }
                }
            };
            th.start();
            try { th.join(); } catch (InterruptedException ex) { ex.printStackTrace(); }
        }

        public void inquiryCompleted(int type)
        {
            int s;

            //After each inquiry is completed, update thee screen
            //now that the inquiry has been completed move newly discovered
            //devices into remoteDevices Map
            s = discoveredDevices.size();
            if(s > 0)
            {
                System.out.println(s + " device(s) found ");
                for(Object obj : discoveredDevices.values())
                {
                    RemoteDevice rd = (RemoteDevice) obj;
                    //add device only if not already knwon or cached
                    RemoteDevice rd2 =(RemoteDevice)remoteDevices.get(rd.getBluetoothAddress());
                    if(rd2==null)
                    {
                        remoteDevices.put(rd.getBluetoothAddress(), rd);
                    }
                }
            }
            else
            {
                System.out.println("No devices found");
            }
            //Show remote devices
            String friendlyName;
            s = remoteDevices.size();
            if( s > 0)
            {
                System.out.println(s + " device(s) found ");
                for(Object obj : remoteDevices.values())
                {
                    RemoteDevice rd = (RemoteDevice) obj;
                    try
                    {
                        friendlyName = rd.getFriendlyName(false);
                    } catch(IOException ioe)
                    {
                        friendlyName = null;
                    }
                    if(friendlyName == null)
                    {
                        System.out.println(rd.getBluetoothAddress());
                    } else
                    {
                        System.out.println(friendlyName);
                    }
                }
            }
        }

        public void servicesDiscovered(int transID,ServiceRecord[] record){
        }

        public void serviceSearchCompleted(int transID,int type){
        }

        public void deviceDiscovered(RemoteDevice device, DeviceClass cod)
        {
            try{
                String friendlyName = device.getFriendlyName(true);
                System.out.println("Device Discovered: " + friendlyName);
                discoveredDevices.put(device.getBluetoothAddress(), device);
            }
            catch(IOException e)
            {
               System.out.println(e);
            }

        }
    }
    private static void getBluetoothInfo()
    {
        StringBuilder f = new StringBuilder();
        
        LocalDevice local = null;
        try
        {
            local = LocalDevice.getLocalDevice();
        }
        catch (BluetoothStateException e)
        {
            System.out.println(e.toString());
            return;
        }

        
        f.append("Adresse: " + local.getBluetoothAddress() + "\n");
        String name = local.getFriendlyName();
        if (name == null)
            f.append("Kein Name vorhanden\n");
        else
            f.append("Name: " + name + "\n");

        int mode = local.getDiscoverable();
        StringBuffer text = new StringBuffer("Modus: ");

        switch (mode)
        {
            case DiscoveryAgent.NOT_DISCOVERABLE:
                    text.append("Nicht aufsuchbar");
                    break;
            case DiscoveryAgent.GIAC:
                    text.append("General");
                    break;
            case DiscoveryAgent.LIAC:
                    text.append("Limited");
                    break;
            default:
                    text.append("0x" + Integer.toString(mode,16));
        }

        f.append(text.toString() + "\n");

        System.out.print(f.toString());
         
    }
}

Ich erhalte folgende Ausgabe:
run:
BlueCove version 2.1.0 on bluesoleil
BTMIDlet.btInitiateDeviceSearch
Inquiry in Progress
BTMIDlet.btInitiateServiceSearch
No devices to search...
BTMIDlet.btConnect2.run()
BTMIDlet.btConnect2, exception & 
javax.bluetooth.BluetoothStateException: Another inquiry already running
start
Adresse: 00158335A6DC  //Adresse von dem Bluesoleil stick
Name: .... // Name von meinem laptop
Modus: General
bluesoleil
java.io.IoExecption: Can't query remote device
java.io.IoExecption: Can't query remote device
java.io.IoExecption: Can't query remote device
java.io.IoExecption: Can't query remote device
No devices found

Also vielleicht übergebe ich die UUID falsch aber ich weiß echt nicht 
mehr weiter kein Gerät wird erkannt woran kann das liegen? Das 
mitgelieferte Programm für den BlueSoleil USB stick findet alle und kann 
auch verbindungen herstellen hoffe jemand hat sowas ähnliches schonmal 
gemacht und kann mir weiterhelfen.

Antwort schreiben

Die Angabe einer E-Mail-Adresse ist freiwillig. Wenn Sie automatisch per E-Mail über Antworten auf Ihren Beitrag informiert werden möchten, melden Sie sich bitte an.

Wichtige Regeln - erst lesen, dann posten!

  • Groß- und Kleinschreibung verwenden
  • Längeren Sourcecode nicht im Text einfügen, sondern als Dateianhang

Formatierung (mehr Informationen...)

  • [c]C-Code[/c]
  • [avrasm]AVR-Assembler-Code[/avrasm]
  • [code]Code in anderen Sprachen, ASCII-Zeichnungen[/code]
  • [math]Formel in LaTeX-Syntax[/math]
  • [[Titel]] - Link zu Artikel
  • Verweis auf anderen Beitrag einfügen: Rechtsklick auf Beitragstitel,
    "Adresse kopieren", und in den Text einfügen




Bild automatisch verkleinern, falls nötig
Bitte das JPG-Format nur für Fotos und Scans verwenden!
Zeichnungen und Screenshots im PNG- oder
GIF-Format hochladen. Siehe Bildformate.
Hinweis: der ursprüngliche Beitrag ist mehr als 6 Monate alt.
Bitte hier nur auf die ursprüngliche Frage antworten,
für neue Fragen einen neuen Beitrag erstellen.

Mit dem Abschicken bestätigst du, die Nutzungsbedingungen anzuerkennen.