Using_J2ME_Bluetooth_API_For_Mobile_Games_en by arshad2011


									         Using J2ME Bluetooth API For Mobile

                      Jianmin Ding, Murali Gollapudi
                              Forum Nokia
    •   The basic knowledge on Bluetooth technology
    •   JSR-82 Java APIs for Bluetooth
    •   how to develop Java Bluetooth multi -players games

                                         Get Connected
                             What is Bluetooth?
    •   Low cost, low power and short range wireless
        communication technology
    •   Intended for e.g.:
           •   Cable replacement (e.g. Bluetooth headset)
           •   Wireless data transfer (e.g. phone ↔ PC, phone ↔ phone)
           •   Multi-player gaming (e.g. Nokia N-Gage™ game deck)
           •   Personal Ad Hoc Networks

                                                  Get Connected
    •   An ad-hoc network of 1 master and up to 7 slaves

    master                    slave

                                                 master                  master
  point-to-                                                               opens
   point                                                               connections
                      slave                      multipoint
                                                          Get Connected
    •   One device acts as both master & slave

                      slave                                         slave

                                                typically not implemented
                                                     in today’s phones

                                               Get Connected
                                    Device Inquiry
 •    Device broadcasts an inquiry; Other devices in range respond;
      Results are a list of device Bluetooth addresses and the devices’
      Class of Device (COD), e.g. printer, laptop
 •    Inquiries can use one of two inquiry codes:
        •   General Inquiry Access Code (GIAC)
        •   Limited Inquiry Access Code (LIAC)
 •    Devices will be in one of three modes:
        •   Undiscoverable: will not respond to device inquiries
        •   General: will respond to only GIAC device inquiries
        •   Limited: will respond to both LIAC and GIAC inquiries (a device only stays in
            this mode for a short time)

                                                          Get Connected
                               Service Discovery
    •   This is used to ask the remote device if it supports the
        service(s) you need, specify services by using their
    •   A Bluetooth device keeps a database of registered
           •   e.g. printing, or playing a particular game
    •   Each service is identified by a 16-byte Universally Unique
        Indentifier (UUID)
           •   e.g. A55665EE9F9146109085C2055C888B39
                                                    Get Connected
                      Connecting to a Device’s Service
  •    Once you have a list of reachable devices of the right
       class that support the service, the user can choose to
       which they want to connect
  •    The device which opens the connection is the master;
       the device it connects to is the slave

                                           Get Connected
                             Bluetooth Protocol Stack

        OBEX               WAP
                            IP                                   TCP
                           PPP                                    IP
                 RFCOMM                  SDP         HID        BNEP      TCS

                      Logical Link Control & Adaptation Protocl (L2CAP)

                                   Host Controller Interface (HCI)

                                                            Get Connected
                              Bluetooth ‘Profiles’
    •   Describe the implementation of Bluetooth protocol stack for
        typical applications, e.g.:
    •   generic access profile (everything depends on this)
    •   service discovery application profile
    •   serial port profile
    •   headset profile
    •   basic printing profile
    •   hands free profile
    •   ….
                                                Get Connected
                           Games Over Bluetooth
    •   Bluetooth is suitable for ‘proximity gaming’ – playing
        games with people around you
    •   The low latency makes it suitable for real-time games
           •   driving games, shooting games, …
           •   but also card games, etc.
    •   Up to 8 players, if master device supports point-to-
    •   Use L2CAP packets or RFCOMM streams
                                                  Get Connected
                          Game Update Strategies
    •   Frame-based: clients operate synchronously with
        server, displaying each frame as they receive its data
           •   needs latency < 40ms or so
    •   Dead reckoning: clients operate asynchronously from
        server, predicting action and correcting when the
        server sends updates
           •   OK for Internet-level latencies, 100-200ms
    •   Turn-based: clients take turn to act, when the server
        tells them it’s their turn
               OK even if latency is several seconds
                                                       Get Connected
                      Example Game Screen Map

                                   hosting game
                      Search for     Choose
                       players       players
   Host game /
    Join game
                                     Wait for

                                   joining game

                                                  Get Connected
                          Special Considerations
    •   Low-Power Mode: if a Nokia device gets no Bluetooth
        data for 15 seconds, it enters SNIFF mode, only
        checking for new data every 0.5 seconds
           •   avoid this by sending an empty message every few seconds if
    •   Link Loss: if the device receives no low-level Bluetooth
        packets for 20 seconds, the link will be dropped
    •   Disconnection: players will often leave a game before it
                                                 Get Connected
                      Java APIs for Bluetooth (JSR-82)
    •   Two J2ME Optional Packages:
           •   javax.bluetooth: Bluetooth API
           •   javax.obex: OBEX API
    •   Finalized by JCP on 22 March 2002, specification lead
        Motorola, expert group included Nokia
    •   Features: device inquiry; service registration &
        discovery; L2CAP and RFCOMM connections
    •   Provides a foundation for implementing other profiles
                                                Get Connected
       Nokia Phones Supporting JSR-82 (Not OBEX)
                                                      not all phones with MIDP
                                                    and Bluetooth support JSR-82
                                                       (e.g. 6310i, 7650, 3650)

          Nokia 6600    Nokia 6230   Nokia 7610

                                                                 Nokia 9500
           Nokia 6620                Nokia 6260   Nokia 6630    Communicator
                        Nokia 6255
                                                   Get Connected
                      Registering a Service: Sample Code
    String serviceUuidStr = "81D4852164FE4FF0A47F193BF803FABC";
    StreamConnection conn = null;
    StreamConnectionNotifier notifier = null;
    try {
      LocalDevice local = LocalDevice.getLocalDevice();
      String url = "btspp://localhost:" +
                    serviceUuidStr + ";name=PaintballClient";
      notifier = (StreamConnectionNotifier)(;
      conn = (StreamConnection)(notifier.acceptAndOpen());
    catch (BluetoothStateException ex) {
      // handle error
    catch (IOException ex) {
      // handle error
                                           Get Connected
                      Device Inquiry: Sample Code 1/2
class MyClass implements DiscoveryListener {
  private Vector remoteDevices = new Vector();
  private boolean done = false;
   void inquire() {
     try {
       LocalDevice local = LocalDevice.getLocalDevice();
       DiscoveryAgent agent = local.getDiscoveryAgent();
       synchronized (this) {
         done = false;
         agent.startInquiry(DiscoveryAgent.LIAC, this);
         while (!done) {
         try {
         } catch (InterruptedException ex) { /* ignore */ }
     } catch (BluetoothStateException ex) { /* handle error */ }
   ...                                    Get Connected
                      Device Inquiry: Sample Code 2/2
  public void deviceDiscovered(RemoteDevice dev, DeviceClass cod) {
    if ((cod.getMajorDeviceClass() == 0x200) && // phone
        (cod.getMinorDeviceClass() == 0x04))    // cellular

    public void inquiryCompleted(int discType) {
      done = true;
      synchronized (this) { notifyAll(); }

                                           Get Connected
           Service Discovery: Sample Code 1/2
class MyClass implements DiscoveryListener {
  private Vector devicesWithService = new Vector();
  private Hashtable serviceRecords = new Hashtable();
  private RemoteDevice currentRemoteDevice;
  private int transactionId;
  void search(RemoteDevice dev) {
       try {
           LocalDevice local = LocalDevice.getLocalDevice();
           DiscoveryAgent agent = local.getDiscoveryAgent();
           synchronized (this) {
                   done = false;
                   currentRemoteDevice = dev;
                   transactionId = agent.searchServices(null, uuids, dev, this);
                   while (!done) {
                     try {
                     } catch (InterruptedException ex) { /* ignore */ }
                                               Get Connected
       } catch (BluetoothStateException ex) { /* handle error */ }
                      Service Discovery: Sample Code 2/2
     public void servicesDiscovered(int id, ServiceRecord[] recs) {
       serviceRecords.put(currentRemoteDevice, recs[0]);

    public void serviceSearchCompleted(int iD, int code) {
      transactionId = -1;
      done = true;
      synchronized (this) { notifyAll(); }

                                            Get Connected
                  Opening a Connection: Sample Code
   void handleConnection(ServiceRecord rec) {
     StreamConnection conn = null;
     InputStream in = null;
     OutputStream out = null;
     String url = rec.getConnectionURL(
       ServiceRecord.NOAUTHENTICATE_NOENCRYPT, true); // be master
     // url-> btspp://00E003364338:81D4852164FE4FF0A47F193BF803FABC
     try {
       conn = (StreamConnection)(;
       in = conn.openInputStream();
       out = conn.openOutputStream();
       // do something useful with the streams
     } catch (IOException ex) { /* handle error */ }

                                          Get Connected
                      Demo Game: Paintball
                              •   Simple real-time ‘shooter’
                              •   Motion on a 16x16 grid
                              •   Master holds the game state

                                        Get Connected
                      Demo Game

                              Get Connected
                      Get Connected
                      Demo Game: Observations 1/2
    •   Master finds slaves and initiates connections
    •   There is always a way to restart discovery and
        connection setup
    •   Messaging: 2 bytes length, 2 bytes msg type, data
    •   Local player’s connection is an in-memory stream
    •   Master informs each slave of changes in the state

                                         Get Connected
                      Demo Game: Observations 2/2
    •   Device and service discovery sometimes fail
    •   Connection setup takes time
    •   Connections can drop anytime
    •   Latency
    •   Threading
    •   Testing!

                                        Get Connected
                        Developing Your Own Game
    •   Get a good book, especially Bluetooth Application Programming
        with the Java APIs by Kumar et al.
    •   Get Forum Nokia’s documents:
           •   Introduction to Developing Networked MIDlets Using Bluetooth
           •   Games Over Bluetooth: Recommendations to Game Developers
    •   Get a MIDP development environment, e.g. IDEs, Ant/Antenna
    •   Get at least 3 phones, and ideally varied models
    •   Get emulators…

                                                         Get Connected
                      Emulators Supporting JSR-82
    From Nokia:
    •   Series 60 MIDP Concept SDK Beta 0.3.1, Nokia Edition
    •   Nokia 6230 MIDP Concept SDK Beta 0.2
    •   Series 60 MIDP SDK 2.1 Beta for Symbian OS
    From Sun:
    •   Wireless Toolkit 2.2 Beta

                                         Get Connected
                            Hints & Tips
    •   Pay attention to threading issues
    •   Close connections on exit
    •   Ignore cached devices, since you can’t find out their
        Class of Device
    •   On Series 60, prefer RFCOMM to L2CAP
    •   Test with many devices, different devices, and with
        other Bluetooth devices (e.g. headsets) in proximity

                                            Get Connected
                               Web Resources
    •   Forum Nokia Java section
    •   Sun J2ME Wireless Toolkit 2.2 Beta
    •   KVM-INTEREST mailing list
    •   Ben Hui’s Bluetooth pages
                                                  Get Connected

To top