Java蓝牙无法找到BLE Nano设备

时间:2017-11-12 11:55:17

标签: java windows bluetooth arduino

我想要什么

首先,我想告诉我想要做什么,我想将我的Windows 10 PC或Macbook与蓝牙连接,我想编写一个JAVA程序来控制BLE Nano蓝牙。我不想使用UART连接,因为我使用BLE Nano进行操作,用户没有机会在PC上连接USB电缆(而且UART Over BLE我不喜欢'并且无法使用它,我已经尝试了一些教程......在这里我无法为我的BLE Nano获得COM-Port(例如Com3)

我做了什么

我阅读了很多教程,我已经运行了示例代码" SimpleChat"来自我的Arduino Nano上的ReadBearLabs(http://redbearlab.com/blenano)。我可以将BLE Nano连接到你的iPhone应用程序,我可以聊天。我通过PC连接它,所以我可以在PC和iPhone上聊天并发送消息。

我通过蓝牙连接我的BLE Nano和我的电脑。我做了以下步骤:

  1. 在Windows设置"蓝牙和其他设备"
  2. 中打开
  3. 添加蓝牙或其他设备(通过点击+)
  4. 选择蓝牙设备,现在Windows搜索设备后,(确保您的设备已开启),我添加了我的BLE Nano设备。
  5. 这就是我如何将设备与笔记本电脑连接。现在我还不知道如何检查它是否正常工作。 RedBearLabs没有Windows应用程序,我可以检查......

    所以我在互联网上搜索了JAVA源代码示例&教程和我发现3.我尝试了所有人。没有那么多,因为没有人这样做......或者我不知道为什么我才发现3. nvm。

    我在我的Eclipse项目中添加了bluecove libary,就像在这个turorial https://www.youtube.com/watch?v=Z2yyTlJf_Ro

    上一样

    我现在在这里添加3个源代码,因为如果将来有人搜索,他可以在谷歌这里找到它,这对我现在不起作用。 我运行这些代码的每一个,我得到Nullpointer异常,因为他没有找到我的设备或者我没有得到任何输出,因为没有找到设备,这就是为什么它没有打印出来。我通过连接的蓝牙添加我的Macbook以检查代码是否正常工作,是的,我的Windows 10笔记本电脑打印出关于我的Macbook的所有信息。但我无法找到我的BLE NANO。

    源代码1

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.util.Vector;
    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;
    
    /**
    * Class that discovers all bluetooth devices in the neighbourhood,
    * Connects to the chosen device and checks for the presence of OBEX push service in it.
    * and displays their name and bluetooth address.
    */
    public class BluetoothServiceDiscovery implements DiscoveryListener{
    
    //object used for waiting
    private static Object lock=new Object();
    
    //vector containing the devices discovered
    private static Vector vecDevices=new Vector();
    
    private static String connectionURL=null;
    
    
    /**
     * Entry point.
     */
    public static void main(String[] args) throws IOException {
    
        BluetoothServiceDiscovery bluetoothServiceDiscovery=new BluetoothServiceDiscovery();
    
        //display local device address and name
        LocalDevice localDevice = LocalDevice.getLocalDevice();
        System.out.println("Address: "+localDevice.getBluetoothAddress());
        System.out.println("Name: "+localDevice.getFriendlyName());
    
        //find devices
        DiscoveryAgent agent = localDevice.getDiscoveryAgent();
    
        System.out.println("Starting device inquiry...");
        agent.startInquiry(DiscoveryAgent.GIAC, bluetoothServiceDiscovery);
    
        try {
            synchronized(lock){
                lock.wait();
            }
        }
        catch (InterruptedException e) {
            e.printStackTrace();
        }
    
    
        System.out.println("Device Inquiry Completed. ");
    
        //print all devices in vecDevices
        int deviceCount=vecDevices.size();
    
        if(deviceCount <= 0){
            System.out.println("No Devices Found .");
        }
        else{
            //print bluetooth device addresses and names in the format [ No. address (name) ]
            System.out.println("Bluetooth Devices: ");
            for (int i = 0; i <deviceCount; i++) {
                RemoteDevice remoteDevice=(RemoteDevice)vecDevices.elementAt(i);
                System.out.println((i+1)+". "+remoteDevice.getBluetoothAddress()+" ("+remoteDevice.getFriendlyName(true)+")");
            }
        }
    
        System.out.print("Choose the device to search for Obex Push service : ");
        BufferedReader bReader=new BufferedReader(new InputStreamReader(System.in));
    
        String chosenIndex=bReader.readLine();
        int index=Integer.parseInt(chosenIndex.trim());
    
        //check for obex service
        RemoteDevice remoteDevice=(RemoteDevice)vecDevices.elementAt(index-1);
        UUID[] uuidSet = new UUID[1];
        uuidSet[0]=new UUID("1105",true);
    
        System.out.println("\nSearching for service...");
        agent.searchServices(null,uuidSet,remoteDevice,bluetoothServiceDiscovery);
    
        try {
            synchronized(lock){
                lock.wait();
            }
        }
        catch (InterruptedException e) {
            e.printStackTrace();
        }
    
        if(connectionURL==null){
            System.out.println("Device does not support Object Push.");
        }
        else{
            System.out.println("Device supports Object Push.");
        }
    } 
    
    
    /**
     * Called when a bluetooth device is discovered.
     * Used for device search.
     */
    public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod) {
        //add the device to the vector
        if(!vecDevices.contains(btDevice)){
            vecDevices.addElement(btDevice);
        }
    }
    
    
    /**
     * Called when a bluetooth service is discovered.
     * Used for service search.
     */
    public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {
        if(servRecord!=null && servRecord.length>0){
            connectionURL=servRecord[0].getConnectionURL(0,false);
        }
        synchronized(lock){
            lock.notify();
        }
    }
    
    
    /**
     * Called when the service search is over.
     */
    public void serviceSearchCompleted(int transID, int respCode) {
        synchronized(lock){
            lock.notify();
        }
    }
    
    
    /**
     * Called when the device search is over.
     */
    public void inquiryCompleted(int discType) {
        synchronized(lock){
            lock.notify();
        }
    
    }//end method
    
    
    }//end class
    

    源代码2

    import java.io.OutputStream;
    import java.util.ArrayList;
    import javax.bluetooth.DataElement;
    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.obex.ClientSession;
    import javax.obex.HeaderSet;
    import javax.obex.Operation;
    import javax.obex.ResponseCodes;
    
        public class MyDiscoveryListener implements DiscoveryListener{
    
            private static Object lock=new Object();
            public ArrayList<RemoteDevice> devices;
    
            public MyDiscoveryListener() {
                devices = new ArrayList<RemoteDevice>();
            }
    
          public static void main(String[] args) {
    
            MyDiscoveryListener listener =  new MyDiscoveryListener();
    
            try{
                LocalDevice localDevice = LocalDevice.getLocalDevice();
                DiscoveryAgent agent = localDevice.getDiscoveryAgent();
                agent.startInquiry(DiscoveryAgent.GIAC, listener);
    
                try {
                    synchronized(lock){
                        lock.wait();
                    }
                }
                catch (InterruptedException e) {
                    e.printStackTrace();
                    return;
                }
    
    
                System.out.println("Device Inquiry Completed. ");
    
    
                UUID[] uuidSet = new UUID[1];
                uuidSet[0]=new UUID(0x1105); //OBEX Object Push service
    
                int[] attrIDs =  new int[] {
                        0x0100 // Service name
                };
    
                for (RemoteDevice device : listener.devices) {
                    agent.searchServices(
                            attrIDs,uuidSet,device,listener);
    
                    try {
                        synchronized(lock){
                            lock.wait();
                        }
                    }
                    catch (InterruptedException e) {
                        e.printStackTrace();
                        return;
                    }
                    System.out.println("Service search finished.");
                }
    
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
    
    
        @Override
        public void deviceDiscovered(RemoteDevice btDevice, DeviceClass arg1) {
            String name;
            try {
                name = btDevice.getFriendlyName(false);
            } catch (Exception e) {
                name = btDevice.getBluetoothAddress();
            }
    
            devices.add(btDevice);
            System.out.println("device found: " + name);
    
        }
    
        @Override
        public void inquiryCompleted(int arg0) {
            synchronized(lock){
                lock.notify();
            }
        }
    
        @Override
        public void serviceSearchCompleted(int arg0, int arg1) {
            synchronized (lock) {
                lock.notify();
            }
        }
    
        @Override
        public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {
            for (int i = 0; i < servRecord.length; i++) {
                String url = servRecord[i].getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
                if (url == null) {
                    continue;
                }
                DataElement serviceName = servRecord[i].getAttributeValue(0x0100);
                if (serviceName != null) {
                    System.out.println("service " + serviceName.getValue() + " found " + url);
    
                    if(serviceName.getValue().equals("OBEX Object Push")){
                        sendMessageToDevice(url);                
                    }
                } else {
                    System.out.println("service found " + url);
                }
    
    
            }
        }
    
        private static void sendMessageToDevice(String serverURL){
            try{
                System.out.println("Connecting to " + serverURL);
    
                ClientSession clientSession = (ClientSession) Connector.open(serverURL);
                HeaderSet hsConnectReply = clientSession.connect(null);
                if (hsConnectReply.getResponseCode() != ResponseCodes.OBEX_HTTP_OK) {
                    System.out.println("Failed to connect");
                    return;
                }
    
                HeaderSet hsOperation = clientSession.createHeaderSet();
                hsOperation.setHeader(HeaderSet.NAME, "Hello.txt");
                hsOperation.setHeader(HeaderSet.TYPE, "text");
    
                //Create PUT Operation
                Operation putOperation = clientSession.put(hsOperation);
    
                // Send some text to server
                byte data[] = "Hello World !!!".getBytes("iso-8859-1");
                OutputStream os = putOperation.openOutputStream();
                os.write(data);
                os.close();
    
                putOperation.close();
    
                clientSession.disconnect(null);
    
                clientSession.close();
            }
            catch (Exception e) {
                e.printStackTrace();
            }
        }
    
    } 
    

    源代码3

    import java.io.IOException;
    import javax.bluetooth.DiscoveryAgent;
    import javax.bluetooth.LocalDevice;
    import javax.bluetooth.RemoteDevice;
    
    public class PairDevice {
    
        public static void main(String args[]) throws IOException
        {
            LocalDevice device = LocalDevice.getLocalDevice();
    
            RemoteDevice[] remotedevice = device.getDiscoveryAgent().retrieveDevices(DiscoveryAgent.PREKNOWN);
    
            for(RemoteDevice d : remotedevice)
            {
                System.out.println("Device Name : "+d.getFriendlyName(false));
                System.out.println("Bluetooth Address : "+d.getBluetoothAddress()+"\n");
                }
    
        }
    
    }
    

    需要帮助

    所以我想把这个问题加在一起,我的BLE Nano通过蓝牙连接我的笔记本电脑,但我添加了BLE Nano的任何源代码都找不到。全部正确。我使用Eclipse,我有一个BLE NANO v1.0。 请帮我解决问题。 有人像我一样有同样的问题吗? 您使用哪种语言编程通过LAPTOP&lt; =&gt;进行蓝牙通信BLE NANO?

    我只是希望能够使用我当前的系统。 如果不是,我想获得另一种编程语言的教程,以通过蓝牙在LAPTOP和BLE NANO之间进行通信。

0 个答案:

没有答案