Using_J2ME_Bluetooth_API_For_Mobile_Games_en by arshad2011

VIEWS: 15 PAGES: 31

									         Using J2ME Bluetooth API For Mobile
                       Games


                      Jianmin Ding, Murali Gollapudi
                              Forum Nokia




www.forum.nokia.com
                                Goal
    •   The basic knowledge on Bluetooth technology
    •   JSR-82 Java APIs for Bluetooth
    •   how to develop Java Bluetooth multi -players games




                                         Get Connected
www.forum.nokia.com
                             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
www.forum.nokia.com
                                              Piconets
    •   An ad-hoc network of 1 master and up to 7 slaves



                                                              slave
    master                    slave

                                                 master                  master
  point-to-                                                               opens
   point                                                               connections
                                                 point-to-
                      slave                      multipoint
                                                               slave
                                      slave
                                                          Get Connected
www.forum.nokia.com
                                  Scatternets
    •   One device acts as both master & slave



                                                slave/master
                      slave                                         slave

                                      master
                                                typically not implemented
                                                     in today’s phones


                              slave
                                               Get Connected
www.forum.nokia.com
                                    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
www.forum.nokia.com
                               Service Discovery
    •   This is used to ask the remote device if it supports the
        service(s) you need, specify services by using their
        UUIDs
    •   A Bluetooth device keeps a database of registered
        services
           •   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
www.forum.nokia.com
                      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
www.forum.nokia.com
                             Bluetooth Protocol Stack

        OBEX               WAP
                           UDP
         TCP
                            IP                                   TCP
          IP
                           PPP                                    IP
                                                                                Audio
                 RFCOMM                  SDP         HID        BNEP      TCS

                      Logical Link Control & Adaptation Protocl (L2CAP)

                                   Host Controller Interface (HCI)


                                                            Get Connected
www.forum.nokia.com
                              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
www.forum.nokia.com
                           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-
        multipoint
    •   Use L2CAP packets or RFCOMM streams
                                                  Get Connected
www.forum.nokia.com
                          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
           •


www.forum.nokia.com
                      Example Game Screen Map

                                   hosting game
       Splash
                      Search for     Choose
                                                    Connect
                       players       players
   Host game /
                                                              Play
    Join game
                                     Wait for
                                    connection

                                   joining game


                                                  Get Connected
www.forum.nokia.com
                          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
               necessary
    •   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
        ends
                                                 Get Connected
www.forum.nokia.com
                      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
www.forum.nokia.com
       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
www.forum.nokia.com
                      Registering a Service: Sample Code
    String serviceUuidStr = "81D4852164FE4FF0A47F193BF803FABC";
    StreamConnection conn = null;
    StreamConnectionNotifier notifier = null;
    try {
      LocalDevice local = LocalDevice.getLocalDevice();
      local.setDiscoverable(DiscoveryAgent.LIAC);
      String url = "btspp://localhost:" +
                    serviceUuidStr + ";name=PaintballClient";
      notifier = (StreamConnectionNotifier)(Connector.open(url));
      conn = (StreamConnection)(notifier.acceptAndOpen());
    }
    catch (BluetoothStateException ex) {
      // handle error
    }
    catch (IOException ex) {
      // handle error
    }
                                           Get Connected
www.forum.nokia.com
                      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();
       local.setDiscoverable(DiscoveryAgent.NOT_DISCOVERABLE);
       DiscoveryAgent agent = local.getDiscoveryAgent();
       synchronized (this) {
         done = false;
         agent.startInquiry(DiscoveryAgent.LIAC, this);
         while (!done) {
         try {
           wait();
         } catch (InterruptedException ex) { /* ignore */ }
       }
     } catch (BluetoothStateException ex) { /* handle error */ }
   }
   ...                                    Get Connected
www.forum.nokia.com
                      Device Inquiry: Sample Code 2/2
...
  public void deviceDiscovered(RemoteDevice dev, DeviceClass cod) {
    if ((cod.getMajorDeviceClass() == 0x200) && // phone
        (cod.getMinorDeviceClass() == 0x04))    // cellular
      remoteDevices.addElement(dev);
  }

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




                                           Get Connected
www.forum.nokia.com
           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();
           local.setDiscoverable(DiscoveryAgent.NOT_DISCOVERABLE);
           DiscoveryAgent agent = local.getDiscoveryAgent();
           synchronized (this) {
                   done = false;
                   currentRemoteDevice = dev;
                   transactionId = agent.searchServices(null, uuids, dev, this);
                   while (!done) {
                     try {
                       wait();
                     } catch (InterruptedException ex) { /* ignore */ }
           }
                   }
                                               Get Connected
       } catch (BluetoothStateException ex) { /* handle error */ }
  }
www.forum.nokia.com
  ...
                      Service Discovery: Sample Code 2/2
    ...
     public void servicesDiscovered(int id, ServiceRecord[] recs) {
       devicesWithService.addElement(currentRemoteDevice);
       serviceRecords.put(currentRemoteDevice, recs[0]);
     }

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




                                            Get Connected
www.forum.nokia.com
                  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)(Connector.open(url));
       in = conn.openInputStream();
       out = conn.openOutputStream();
       // do something useful with the streams
       in.close();
       out.close();
       conn.close();
     } catch (IOException ex) { /* handle error */ }
   }

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




                                        Get Connected
www.forum.nokia.com
                      Demo Game




                              Get Connected
www.forum.nokia.com
                      Get Connected
www.forum.nokia.com
                      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
www.forum.nokia.com
                      Demo Game: Observations 2/2
    •   Device and service discovery sometimes fail
    •   Connection setup takes time
    •   Connections can drop anytime
    •   Latency
    •   Threading
    •   Testing!


                                        Get Connected
www.forum.nokia.com
                        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
www.forum.nokia.com
                      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
www.forum.nokia.com
                            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
www.forum.nokia.com
                               Web Resources
    •   Forum Nokia Java section
           •   http://www.forum.nokia.com/java
    •   Sun J2ME Wireless Toolkit 2.2 Beta
           •   http://java.sun.com/products/j2mewtoolkit/
    •   KVM-INTEREST mailing list
           •   http://archives.java.sun.com/kvm-interest.html
    •   Ben Hui’s Bluetooth pages
           •   http://www.benhui.net
                                                  Get Connected
www.forum.nokia.com

								
To top