Simple Bluetooth Communication in J2ME

Simple Bluetooth Communication

In this article, I will try to explain the simple Bluetooth communication standards and show how you can create a simple wrapper class around Bluetooth technology. This article is for those peoples who want to write a J2ME Bluetooth application by understanding its API and protocols.

Wireless Technologies

The most famous wireless technologies are infraree, Bluetooth, WiFi, and Zigbee. Infrared is the technology that you can see in TV remote controls or air conditioner remotes where the communication should be pointed to the target device. WiFi technology is used for strong and wide area communication where wireless communication can be made. Zigbee is the most recent technology; it’s cheaper than all the other wireless media. Bluetooth technology is the most used temporary communication technology, especially inside mobile devices, palm tops, pocket PCs, and so forth. It can be used to exchange objects, packets, or a simple stream.

Bluetooth Communication Types

There are three types of communication protocols defined inside Bluetooth technology:

  • OBEX: The “Object Exchange” communication protocol is used to exchange physical data such as files, images, and so on in binary format.
  • L2CAP: The “Logical Link Control and Adaptation Protocol” used to send packets between host and client.
  • RFCOMM: The “Radio Frequency COMMunication” is very easy and uncomplicated; it is used to stream simple data.

Java Bluetooth API

Sun Java has introduced the Bluetooth JSR82 API package. The JSR82 API has capability to provide all three kinds of communications: either Obex, L2CAP, or RFCOMM. This article will focus on the simplest protocol, RFCOMM, and send only string data between the devices.

Client and Server

The technique to communicate any device will follow the good old-fashioned rule of Client and Server. You will open the Server and then wait for the client to connect; after that, the server and client both can communicate with each other easily. In Bluetooth, you have to do the same technique; the application must allow the user to select it as either the server or client.

Code and Explanation

1. Server

Every Bluetooth device contains the local Bluetooth object that helps communicate between devices. In JSR82, the LocalDevice.getLocalDevice(); function returns the object of the local Bluetooth device. The local device object should call the setDiscoverable(DiscoveryAgent.GIAC); function, in which the mode is set as GIAC. In simple words, by doing this you give permission to the current device to find other devices.

To open the Bluetooth connection, you have to build a Bluetooth URL string that will be called inside the Connector.open(URL) function; this function will return the StreamConnectionNotifier Object. The URL actually is the way to initialize the communication protocol for Bluetooth, just like on an Internet Explorer search box. You just type http://www.address.com, where http:// is the protocol and the rest is the address of the target place. In Bluetooth, you will do something like this:

URL = "btspp://localhost:" + UUID + ";name=rfcommtest;authorize=true";

Here, you have btspp:// just like the http:// protocol. The rest has an uniquely identified ID so that it will have its unique address.

After the StreamConnectionNotifier has been initialized, it has to call the final acceptAndOpen(); function that simply opens the communication and returns the StreamConnection object. But, unless no client connection is found, it will block the other processes and wait.

Now, you can use two functions by StreamConnectionb’ object: openOutputStream() or openInputStream(). Both are used as a way to send and receive data.

m_strUrl= "btspp://localhost:" + RFCOMM_UUID + ";
   name=rfcommtest;authorize=true";

// m_StrmConn = BTFACADE.waitForClient(SERVICE_NBR);

try
{
   m_LclDevice = LocalDevice.getLocalDevice();

   m_LclDevice.setDiscoverable(DiscoveryAgent.GIAC);

   m_StrmNotf = (StreamConnectionNotifier)Connector.open(m_strUrl);

   //Now it will start waiting for the client connection
   m_StrmConn = m_StrmNotf.acceptAndOpen();

   m_bInitServer = true;

   m_Output = m_StrmConn.openOutputStream();
   m_Input  = m_StrmConn.openInputStream();
}
catch (BluetoothStateException e)
{
   System.err.println( "BluetoothStateException: " + e.getMessage() );
}
catch (IOException ex)
{
   ex.printStackTrace();
}
catch(Exception e)
{
   System.err.println( "Exception: " + e.getMessage() );
}

2. Client

To create the client, the UPI has to follow some rules to obtain your goal, which is to implement the DiscoveryListener interface. It has four, pure-virtual functions:

  • void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod)
  • void servicesDiscovered(int transID, ServiceRecord[] records)
  • void serviceSearchCompleted(int transID, int respCode)
  • void inquiryCompleted(int discType)

At first, you have to search the available Bluetooth devices around you. You have to get the local device information and, through it, retrieve the DiscoveryAgent object to start enquiry about available devices.

public void SearchAvailDevices()
{
   try
   {
      //First, get the local device and obtain the discovery agent.
      m_LclDevice = LocalDevice.getLocalDevice();

      m_DscrAgent=  m_LclDevice.getDiscoveryAgent();

      m_DscrAgent.startInquiry(DiscoveryAgent.GIAC,this);
   }
   catch (BluetoothStateException ex)
   {
      System.out.println("Problem in searching the Bluetooth devices");
      ex.printStackTrace();
   }

}

For the client, these four methods of DiscoveryListener must to be override in the class. According to their name, they do work; for example, deviceDiscovered suddenly gets triggered when any Bluetooth device is found. After that, it is your responsibility to find the services of devices such as OBEX, RFCOMM, or L2CAP.

public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod)
{
   try
   {
      // Device information
      System.out.println("Major Device Class and information : " +
                         cod.getMajorDeviceClass() +
                         " Minor Device Class: " +
                         cod.getMinorDeviceClass());
      System.out.println("Bluetooth Address of the device: " +
                         btDevice.getBluetoothAddress());
      System.out.println("Friendly Name: " +
                         btDevice.getFriendlyName(true));

      // Now its our responsibility to search its services
      UUID uuidSet[] = new UUID[1];
      uuidSet[0]     = RFCOMM_UUID;
      int searchID  = m_DscrAgent.searchServices(null,uuidSet,
                                                 btDevice,this);
   }
   catch (Exception e)
   {
      System.out.println("Device Discovered Error: " + e);
   }

}

Here, m_DscrAgent is the DiscoveryAgent object that searches the available services of the first device you found.

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

   for (int i = 0; i < records.length; i++)
   {
      m_strUrl = records[i].getConnectionURL(ServiceRecord.
         AUTHENTICATE_ENCRYPT, false);

      System.out.println(m_strUrl);
   //we have found our service protocol
   if(m_strUrl.startsWith("btspp"))
   {
      m_bServerFound = true;
      m_bInitClient=true;
      break;
   }

}

The ServicesDiscovered function above is triggered when services of that device are found. Here, you stop the loop on the first protocol that you found as Bluetooth.

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read