Connecting BLE Nano over Bluetooth with PC (WITH JAVA)


#1

Hi,

what I want

First of all I want to tell what I want to do, I want to connect my Windows 10 PC or my Macbook with bluetooth and I want to write a JAVA programm to controll the BLE Nano over bluetooth. I don’t want to use UART connection, because I use the BLE Nano for things, where the user don’t have a opportunity to connect with a USB Cable on PC (and UART Over BLE I don’t and can’t use it, I tried it already with some tutorials… here I can’t get a COM-Port (ex. Com3) for my BLE Nano)

what i did

I read a lot of tutorials, I have running the Sample code “SimpleChat” from ReadBearLabs on my Arduino Nano (http://redbearlab.com/blenano). I can connect the BLE Nano with your iPhone application and I can chat. I connected it via PC so i Could recive and send messages in the chat on PC and on my iPhone.

I connect my BLE Nano with my PC over Bluetooth. I did the followin steps :

  1. Open in windows Settings “Bluetooth and other Devices”
  2. add Bluetooth or other device (by clicking on the + )
  3. select Bluetooth device, now Windows search after the devices, (make sure that your device is on), I added my BLE Nano device.

Thats how I connected the device with my laptop. Now I didn’t know how to check if it is working. RedBearLabs didn’t have an application for windows where I could check that…

So I searched in the internet for JAVA source code examples & tutorials and I found 3. I tried everyone of them. Not so many, because no one is doing that like this… or I don’t know why I just found 3. nvm.

I added the bluecove libary like in my Eclipse project like on this turorial https://www.youtube.com/watch?v=Z2yyTlJf_Ro

I add now the 3 source codes here, because If someone in the future search after that he can found it on google here and this isn’t working for me right now.
I run every one of this code and I get Nullpointer exceptions because he didn’t found my device or I don’t get any output, because there was no device found and thats why it wasn’t print out. I add my Macbook over bluetooth connected to check if it works the code and yes my Windows 10 Laptop printed all information about my Macbook out. But I can’t find my BLE NANO.

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

source code 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();
        }
    }

} 

source code 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");
    	    }
	
	}

}

need help

So I want to sum the problem together, my BLE Nano is connected over Bluetooth with my Laptop, but any of the source codes i added my BLE Nano can’t be found. All are correct. I use Eclipse and I have a BLE NANO v1.0.
Pleas help me by my problem.
Anyone have the same problem like me ?
In which language do you programm to communicate over bluetooth via LAPTOP <=> BLE NANO ?

I just want to get a it work with my current system.
If not I want get an tutorial to another programming language to communicate between LAPTOP and BLE NANO over Bluetooth.

@RedBearLab Technical Support pleas help me.


#2

No one have any answere / solution for me ?


#3

We are really sorry for that we do not support Windows BLE, since it does not provide standard APIs for it compare to iOS and Android.

Any other users here could help on Windows?