FileDocCategorySizeDatePackage
BluetoothStack.javaAPI DocphoneME MR2 API (J2ME)21199Wed May 02 18:00:30 BST 2007com.sun.midp.jsr082.bluetooth

BluetoothStack

public abstract class BluetoothStack extends Object
Represents native Bluetooth stack provided by the system. Provides services such as device and service discovery.

Fields Summary
private static BluetoothStack
instance
Instance of BluetoothStack's subclass used in the current isolate.
private int
nativeInstance
Instance handle of the native porting layer class.
private javax.bluetooth.DiscoveryListener
discListener
Listener where discovery events are reported to.
private Hashtable
nameResults
Contains remote name request results.
private Hashtable
authenticateResults
Contains authentication request results.
private Hashtable
encryptResults
Contains set encryption request results.
private final long
ASK_FRIENDLY_NAME_TIMEOUT
Timeout value in milliseconds for friendly name retrieval.
private final long
AUTHENTICATE_TIMEOUT
Timeout value in milliseconds for authentication.
private final long
ENCRYPT_TIMEOUT
Timeout value in milliseconds for setting encryption.
int
pollRequests
Keeps the count of pending requests.
Vector
inquiryHistory
Contains results of ongoing inquiry to avoid reporting the same inquiry result twice.
Constructors Summary
protected BluetoothStack()
Class constructor.


           
      
        initialize();
    
Methods Summary
private native booleanaskFriendlyName(java.lang.String addr)
Passes remote device's friendly name acquisition request to the native porting layer.

param
addr Bluetooth address of the remote device
return
true if the operation was accepted, false otherwise

public java.lang.StringaskFriendlyNameSync(java.lang.String addr)
Retrieves friendly name from a remote device synchronously.

param
addr remote device address
return
friendly name of the remote device, or null if the name could not be retrieved

        if (!askFriendlyName(addr)) {
            return null;
        }
        nameResults.remove(addr);
        startPolling();
        return (String)waitResult(nameResults, addr,
                ASK_FRIENDLY_NAME_TIMEOUT);
    
private native booleanauthenticate(java.lang.String addr)
Passes remote device authentication request to the native porting layer.

param
addr Bluetooth address of the remote device
return
true if the operation was accepted, false otherwise

public booleanauthenticateSync(java.lang.String addr)
Performs remote device authentication synchronously.

param
addr remote device address
return
true if authentication was successful, false otherwise

        if (!authenticate(addr)) {
            return false;
        }
        int handle = getHandle(addr);
        authenticateResults.remove(new Integer(handle));
        startPolling();
        Boolean result = (Boolean)waitResult(authenticateResults,
                new Integer(handle), AUTHENTICATE_TIMEOUT);
        if (result == null) {
            return false;
        }
        return result.booleanValue();
    
public booleancancelInquiry(javax.bluetooth.DiscoveryListener listener)
Removes the device from inquiry mode.

param
listener the listener that is receiving inquiry events
return
true if the inquiry was canceled, false otherwise

        if (discListener != listener) {
            return false;
        }
        if (cancelInquiry()) {
            stopPolling();
            discListener = null;
            return true;
        }
        return false;
    
private native booleancancelInquiry()
Passes cancellation of device discovery request to the native porting layer.

return
true if the operation was accepted, false otherwise

private native booleancheckEvents()
Checks if Bluetooth events are available on the native porting layer.

return
true if there are pending events, false otherwise

public native booleanenable()
Enables Bluetooth radio.

return
true if Bluetooth is enabled, false otherwise

private native booleanencrypt(java.lang.String addr, boolean enable)
Passes connection encryption change request to the native porting layer.

param
addr Bluetooth address of the remote device
param
enable true if the encryption needs to be enabled, false otherwise
return
true if the operation was accepted, false otherwise

public booleanencryptSync(java.lang.String addr, boolean enable)
Sets encryption mode synchronously.

param
addr remote device address
param
enable true if the encryption needs to be enabled, false otherwise
return
true if authentication was successful, false otherwise

        if (!encrypt(addr, enable)) {
            return false;
        }
        int handle = getHandle(addr);
        encryptResults.remove(new Integer(handle));
        startPolling();
        Boolean result = (Boolean)waitResult(encryptResults,
                new Integer(handle), ENCRYPT_TIMEOUT);
        if (result == null) {
            return false;
        }
        return result.booleanValue();
    
private native voidfinalize()
Releases native resources.

public native intgetAccessCode()
Retrieves the inquiry access code that the local Bluetooth device is scanning for during inquiry scans.

return
inquiry access code, or -1 if the information could not be retrieved

public native intgetDeviceClass()
Returns class of device including service classes.

return
class of device value, or -1 if the information could not be retrieved

public static synchronized com.sun.midp.jsr082.bluetooth.BluetoothStackgetEnabledInstance()
Returns a BluetoothStack object and guarantees that Bluetooth radio is on.

return
an instance of BluetoothStack subclass
throws
BluetoothStateException if BluetoothStack is off and cannot be turned on.

        getInstance();
        if (!instance.isEnabled() && !instance.enable()) {
            throw new BluetoothStateException("Failed turning Bluetooth on");
        }
        // intent here is launching EmulationPolling and SDPServer
        // in emulation mode
        com.sun.kvem.jsr082.bluetooth.SDDB.getInstance();
        return instance;
    
private native intgetHandle(java.lang.String addr)
Retrieves default ACL connection handle for the specified remote device.

param
addr the Bluetooth address of the remote device
return
ACL connection handle value

public static synchronized com.sun.midp.jsr082.bluetooth.BluetoothStackgetInstance()
Returns a BluetoothStack object.

return
an instance of BluetoothStack subclass

        if (instance == null) {
            // Note to porting engineer: please replace the class name with
            // the one you intend to use on the target platform.
            instance = new GenericBluetoothStack();
        }
        return instance;
    
public native java.lang.StringgetLocalAddress()
Returns Bluetooth address of the local device.

return
Bluetooth address of the local device, or null if the address could not be retrieved

public native java.lang.StringgetLocalName()
Returns user-friendly name for the local device.

return
User-friendly name for the local device, or null if the name could not be retrieved

private native voidinitialize()
Allocates native resources.

public native booleanisEnabled()
Checks if the Bluetooth radio is enabled.

return
true if Bluetooth is enabled, false otherwise

voidonAuthenticationComplete(int handle, boolean result)
Called when an authentication request is completed.

param
handle connection handle for an ACL connection
param
result indicates whether the operation was successful

        stopPolling();
        putResult(authenticateResults, new Integer(handle),
            new Boolean(result));
    
voidonEncryptionChange(int handle, boolean result)
Called when a set encryption request is completed.

param
handle connection handle for an ACL connection
param
result indicates whether the operation was successful

        stopPolling();
        putResult(encryptResults, new Integer(handle), new Boolean(result));
    
voidonInquiryComplete(boolean success)
Called when an inquiry request is completed.

param
success indicates whether inquiry completed successfully

        if (discListener == null) {
            return;
        }
        stopPolling();
        discListener = null;
        inquiryHistory.removeAllElements();
        int type = success ? DiscoveryListener.INQUIRY_COMPLETED :
                DiscoveryListener.INQUIRY_ERROR;
        DiscoveryAgentImpl.getInstance().inquiryCompleted(type);
    
voidonInquiryResult(InquiryResult result)
Called when an inquiry result is obtained.

param
result inquiry result object

        if (discListener == null) {
            return;
        }
        String addr = result.getAddress();
        Enumeration e = inquiryHistory.elements();
        while (e.hasMoreElements()) {
            InquiryResult oldResult = (InquiryResult)e.nextElement();
            if (oldResult.getAddress().equals(addr)) {
                // inquiry result is already in our possession
                return;
            }
        }
        inquiryHistory.addElement(result);
        RemoteDevice dev
            = DiscoveryAgentImpl.getInstance().getRemoteDevice(addr);
        DiscoveryAgentImpl.getInstance().addCachedDevice(addr);
        discListener.deviceDiscovered(dev, result.getDeviceClass());
    
voidonNameRetrieve(java.lang.String addr, java.lang.String name)
Called when a name retrieval request is completed.

param
addr Bluetooth address of a remote device
param
name friendly name of the device

        stopPolling();
        putResult(nameResults, addr, name);
    
public voidpollEvents()
Checks for Bluetooth events and processes them.

        while (checkEvents()) {
            BluetoothEvent event = retrieveEvent();
            if (event != null) {
                event.dispatch();
            }
        }
    
private voidputResult(java.util.Hashtable hashtable, java.lang.Object key, java.lang.Object value)
Puts result value into hastable and notifies threads waiting for the result to appear.

param
hashtable Hashtable object where the result will be stored
param
key key identifying the result
param
value value of the result

        synchronized (hashtable) {
            hashtable.put(key, value);
            hashtable.notify();
        }
    
protected native intreadData(byte[] data)
Reads binary event data from the native porting layer. This data can be interpreted differently by different subclasses of BluetoothStack.

param
data byte array to be filled with data
return
number of bytes read

protected abstract BluetoothEventretrieveEvent()
Retrieves Bluetooth event.

return
a Bluetooth event object

public native booleansetAccessCode(int accessCode)
Sets the inquiry access code that the local Bluetooth device is scanning for during inquiry scans.

param
accessCode inquiry access code to be set (valid values are in the range 0x9e8b00 to 0x9e8b3f), or 0 to take the device out of discoverable mode
return
true if the operation succeeded, false otherwise

public native booleansetServiceClasses(int classes)
Sets major service class bits of the device.

param
classes an integer whose binary representation indicates the major service class bits that should be set
return
true if the operation succeeded, false otherwise

public booleanstartInquiry(int accessCode, javax.bluetooth.DiscoveryListener listener)
Places the device into inquiry mode.

param
accessCode the type of inquiry
param
listener the event listener that will receive discovery events
return
true if the inquiry was started, false otherwise

        if (discListener != null || listener == null) {
            return false;
        }
        discListener = listener;
        if (startInquiry(accessCode)) {
            inquiryHistory.removeAllElements();
            startPolling();
            return true;
        }
        return false;
    
private native booleanstartInquiry(int accessCode)
Passes device discovery request to the native porting layer.

param
accessCode the type of inquiry
return
true if the operation was accepted, false otherwise

public synchronized voidstartPolling()
Starts a supplementary polling thread.

        pollRequests++;
        PollingThread.resume();
    
public synchronized voidstopPolling()
Cancels event polling for one request. Polling thread will continue to run unless there are no other pending requests.

        pollRequests--;
        if (pollRequests > 0) {
            return;
        }
        PollingThread.suspend();
    
protected static native java.lang.StringstringUTF8(byte[] buffer, int offset, int length)
Creates Java String object from UTF-8 encoded string.

param
buffer buffer containing the string in UTF-8 format
param
offset offset of the first character in the buffer
param
length length of the encoded string in bytes
return
Java String object containing the string in UTF-16 format

private java.lang.ObjectwaitResult(java.util.Hashtable hashtable, java.lang.Object key, long timeout)
Waits for the specified key to appear in the given hastable. If the key does not appear within the timeout specified, null value is returned.

param
hashtable Hashtable object where the key is expected
param
key the key expected to appear in the hastable
param
timeout timeout value in milliseconds
return
Object corresponding to the given key

        synchronized (hashtable) {
            if (timeout == 0) {
                // infinite timeout
                while (true) {
                    if (hashtable.containsKey(key)) {
                        return hashtable.remove(key);
                    }
                    try {
                        // wait for a new key-value pair to appear in hashtable
                        hashtable.wait();
                    } catch (InterruptedException e) {
                        return null;
                    }
                }
            }
            // endTime indicates time up to which the method is allowed to run
            long endTime = System.currentTimeMillis() + timeout;
            while (true) {
                if (hashtable.containsKey(key)) {
                    return hashtable.remove(key);
                }
                // update timeout value
                timeout = endTime - System.currentTimeMillis();
                if (timeout <= 0) {
                    return null;
                }
                try {
                    // wait for a new key-value pair to appear in hashtable
                    hashtable.wait(timeout);
                } catch (InterruptedException e) {
                    return null;
                }
            }
        }