Skip to main content



      Home
Home » Eclipse Projects » Kura » Not able to read data over bluethooth(Not able to read data over bluethooth)
Not able to read data over bluethooth [message #1765877] Wed, 14 June 2017 03:10 Go to next message
Eclipse UserFriend
Hello,

I am running a sample service on Kura which will just print the data by an arduino board over bluetooth through an HC05.

My code seems to work fine if I run it as a standalone java project. But it fails if I execute it through Kura.

The issue I face is, it is just stuck on read. [I'm using Bluecove 2.1.1] library.

Here is my code,

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.sql.SQLException;
import java.util.Map;

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 org.eclipse.kura.configuration.ConfigurableComponent;
import org.osgi.framework.BundleContext;
import org.osgi.service.component.ComponentContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class GatewayConfigurator implements ConfigurableComponent  {
	private static final Logger logger = LoggerFactory.getLogger(GatewayConfigurator.class);
	private static final String APP_ID = "com.x.gateway.GatewayConfigurator";
	private BundleContext context;
	public Object lock = new Object();
	RemoteDevice hc05device;
	String hc05Url;
	boolean inq;
	protected void activate(ComponentContext componentContext) {
		logger.info("Bundle " + APP_ID + " has started! <==================");
		activate(componentContext, null);
		
	}

	protected void activate(ComponentContext componentContext, Map<String, Object> properties) {
		logger.info("Bundle " + APP_ID + " has started! <==================");
		try {
			  inq = LocalDevice.getLocalDevice().getDiscoveryAgent().startInquiry(DiscoveryAgent.GIAC, new DiscoveryListener() {
				 
				
				 @Override
		            public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod) {
					  logger.debug("deviceDiscovered1.. started");
		                try {
		                    String name = btDevice.getFriendlyName(false);
		                    System.out.format("%s (%s)\n", name, btDevice.getBluetoothAddress());
		                    if (name.matches("HC.*")) {
		                        hc05device = btDevice;
		                        logger.info("got it!");
		                    }
		                } catch (IOException e) {
		                    e.printStackTrace();
		                }
		            }

		            @Override
		            public void inquiryCompleted(int discType) {
		            	logger.info("inquiryCompleted1.. started");
		                
		                try {
		        			synchronized (lock) {
		        				lock.notify();
		        			}
		        		} catch (Exception e) {
		        			// TODO Auto-generated catch block
		        			logger.info("Notify1 complete....");
		        		}
		            }

		            @Override
		            public void serviceSearchCompleted(int transID, int respCode) {
		            	logger.info("serviceSearchCompleted1.. started");
		            }

		            @Override
		            public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {
		            	logger.info("servicesDiscovered1.. started");
		            }
		        });
		} catch (BluetoothStateException e) {
			// TODO: handle exception
			
			logger.info("exception::" + e.getCause());
		}
		logger.info("Inquiry started: " + inq);
		try {
			synchronized (lock) {
				lock.wait();
			}
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			logger.info("Scan complete....");
		}
		 UUID uuid = new UUID(0x1101); //scan for btspp://... services (as HC-05 offers it)
	        UUID[] searchUuidSet = new UUID[]{uuid};
	        int[] attrIDs = new int[]{
	            0x0100 // service name
	        };
	        
	        try {
				LocalDevice.getLocalDevice().getDiscoveryAgent().searchServices(attrIDs, searchUuidSet,
				        hc05device, new DiscoveryListener() {
				            @Override
				            public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod) {
				            	logger.info("deviceDiscovered2.. started");
				            }

				            @Override
				            public void inquiryCompleted(int discType) {
				            	logger.info("inquiryCompleted2.. started");
				            }

				            @Override
				            public void serviceSearchCompleted(int transID, int respCode) {
				            	logger.info("serviceSearchCompleted2.. started");
				            	try {
				        			synchronized (lock) {
				        				lock.notify();
				        			}
				        		} catch (Exception e) {
				        			// TODO Auto-generated catch block
				        			logger.info("Notify1 complete....");
				        		}
				            }

				            @Override
				            public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {
				            	logger.info("servicesDiscovered2.. started");
				                for (int i = 0; i < servRecord.length; i++) {
				                    hc05Url = servRecord[i].getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
				                    if (hc05Url != null) {
				                        break; //take the first one
				                    }
				                }
				            }
				        });
			} catch (BluetoothStateException e) {
				// TODO Auto-generated catch block
				logger.info("exception::" + e.getCause());
			}
	        
	        try {
				synchronized (lock) {
					lock.wait();
				}
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				logger.info("Scan complete....");
			}
	        
	        System.out.println(hc05device.getBluetoothAddress());
	        System.out.println(hc05Url);
	        if(hc05Url == null) {
	        	hc05Url= "btspp://98D3321046B8:1;authenticate=false;encrypt=false;master=false";
	        }

	        try {
	        	//if you know your hc05Url this is all you need:
		        StreamConnection streamConnection = (StreamConnection) Connector.open(hc05Url);
		        OutputStream os = streamConnection.openOutputStream();
		        InputStream is = streamConnection.openInputStream();

		       // os.write("Hello Arduino".getBytes()); //just send '1' to the device
		        
		        BufferedReader br = new BufferedReader(new InputStreamReader(is));
		        int i = 0;
		        String line;
		     //   while (i++ <= 10000000) {
		        	logger.info("Starting read write process");
		        	//os.write("Hello Arduino".getBytes());
		        	//os.flush();
		        	line = new String(br.readLine());
		        	/*while(true) {
		        		logger.info("data:" + is.read());
		        	}*/
					//System.out.println(line);
			//	}
		        
		        //os.close();
		        //is.close();
		       // streamConnection.close();
			} catch (Exception e) {
				logger.info("exception::" + e.getCause());
			}
	}
	
	
	
	
	protected void deactivate(ComponentContext componentContext) {

	}
	
	public void updated(Map<String, Object> properties) {
		logger.info("Bundle " + APP_ID + " has been updated!");
		//handleInstruction(properties);
    }
	
	
	

}




This is my first post, kindly excuse if I have violated any rules.

Regards,
Vik
Re: Not able to read data over bluethooth [message #1765904 is a reply to message #1765877] Wed, 14 June 2017 08:52 Go to previous messageGo to next message
Eclipse UserFriend
Hello,

could you provide us more information about the error?
Can you run the discovery? Does it get the bluetooth device?

Best,
Pier
Re: Not able to read data over bluethooth [message #1766039 is a reply to message #1765904] Thu, 15 June 2017 01:34 Go to previous message
Eclipse UserFriend
Hi Peir,

I have it running now, I think the problem was my that my Arduino was also doing a read on bluetooth. I changed that to have my Arduino only write. No change was required in the above code.
Thanks.

Regards,
Vikrant
Previous Topic:Kura - Azure IoT Hub connectivity
Next Topic:Problem starting Kura on Karaf on Raspberry Pi
Goto Forum:
  


Current Time: Sat Jul 19 03:54:40 EDT 2025

Powered by FUDForum. Page generated in 0.25494 seconds
.:: Contact :: Home ::.

Powered by: FUDforum 3.0.2.
Copyright ©2001-2010 FUDforum Bulletin Board Software

Back to the top