Samsung Electronics logo

Samsung Web API: Bluetooth


Introduction

This specification defines interfaces and methods to manage Bluetooth.

The following Bluetooth functionalities are provided:

  • Controls local Bluetooth device, that is, turn Bluetooth on/off, etc.
  • Sets visibility
  • Discovers nearby Bluetooth devices (Device discovery).
  • Gets bonded devices information.
  • Controls bonding.
  • Connects to a service on a remote device and exchanges data.
  • Registers a service (RFCOMM) on a local device, which can be consumed by remote devices to exchange data.

For more information on the Bluetooth features, see Bluetooth Guide.


Table of Contents


Summary of Interfaces and Methods

Interface Method
BluetoothManagerObject
BluetoothManager BluetoothAdapter getDefaultAdapter()
BluetoothAdapter void setName(DOMString name, SuccessCallback? successCallback, ErrorCallback? errorCallback)
void setPowered(boolean state, SuccessCallback? successCallback, ErrorCallback? errorCallback)
void setVisible(boolean mode, SuccessCallback? successCallback, ErrorCallback? errorCallback, unsigned short? timeout)
void setChangeListener(BluetoothAdapterChangeCallback listener)
void unsetChangeListener()
void discoverDevices(BluetoothDiscoverDevicesSuccessCallback successCallback, ErrorCallback? errorCallback)
void stopDiscovery(SuccessCallback? successCallback, ErrorCallback? errorCallback)
void getKnownDevices(BluetoothDeviceArraySuccessCallback successCallback, ErrorCallback? errorCallback)
void getDevice(BluetoothAddress address, BluetoothDeviceSuccessCallback successCallback, ErrorCallback? errorCallback)
void createBonding(BluetoothAddress address, BluetoothDeviceSuccessCallback successCallback, ErrorCallback? errorCallback)
void destroyBonding(BluetoothAddress address, SuccessCallback? successCallback, ErrorCallback? errorCallback)
void registerRFCOMMServiceByUUID(BluetoothUUID uuid, DOMString name, BluetoothServiceSuccessCallback successCallback, ErrorCallback? errorCallback)
BluetoothProfileHandler getBluetoothProfileHandler(BluetoothProfileType profileType)
BluetoothDevice void connectToServiceByUUID(BluetoothUUID uuid, BluetoothSocketSuccessCallback successCallback, ErrorCallback? errorCallback)
BluetoothSocket unsigned long writeData(byte[] data)
byte[] readData()
void close()
BluetoothClass boolean hasService(unsigned short service)
BluetoothClassDeviceMajor
BluetoothClassDeviceMinor
BluetoothClassDeviceService
BluetoothServiceHandler void unregister(SuccessCallback? successCallback, ErrorCallback? errorCallback)
BluetoothProfileHandler
BluetoothHealthProfileHandler void registerSinkApplication(unsigned short dataType, DOMString name, BluetoothHealthApplicationSuccessCallback successCallback, ErrorCallback? errorCallback)
void connectToSource(BluetoothDevice peer, BluetoothHealthApplication application, BluetoothHealthChannelSuccessCallback successCallback, ErrorCallback? errorCallback)
BluetoothHealthApplication void unregister(SuccessCallback? successCallback, ErrorCallback? errorCallback)
BluetoothHealthChannel void close()
unsigned long sendData(byte[] data)
void setListener(BluetoothHealthChannelChangeCallback listener)
void unsetListener()
BluetoothAdapterChangeCallback void onstatechanged(boolean powered)
void onnamechanged(DOMString name)
void onvisibilitychanged(boolean visible)
BluetoothDeviceSuccessCallback void onsuccess(BluetoothDevice device)
BluetoothDeviceArraySuccessCallback void onsuccess(BluetoothDevice[] devices)
BluetoothDiscoverDevicesSuccessCallback void onstarted()
void ondevicefound(BluetoothDevice device)
void ondevicedisappeared(BluetoothAddress address)
void onfinished(BluetoothDevice[] foundDevices)
BluetoothSocketSuccessCallback void onsuccess(BluetoothSocket socket)
BluetoothServiceSuccessCallback void onsuccess(BluetoothServiceHandler handler)
BluetoothHealthApplicationSuccessCallback void onsuccess(BluetoothHealthApplication application)
BluetoothHealthChannelSuccessCallback void onsuccess(BluetoothHealthChannel channel)
BluetoothHealthChannelChangeCallback void onmessage(byte[] data)
void onclose()

1. Type Definitions

1.1. BluetoothAddress

The address of a Bluetooth device.

    typedef DOMString BluetoothAddress;

1.2. BluetoothUUID

The UUID of a Bluetooth service.

    typedef DOMString BluetoothUUID;

1.3. BluetoothSocketState

The Bluetooth socket state.

    enum BluetoothSocketState { "CLOSED", "OPEN" };

1.4. BluetoothProfileType

The Bluetooth profile.

    enum BluetoothProfileType { "HEALTH" };

1.5. BluetoothHealthChannelType

The channel type of health device profile.

    enum BluetoothHealthChannelType { "RELIABLE", "STREAMING" };

2. Interfaces

2.1. BluetoothManagerObject

This interface defines what is instantiated by the WebAPIs object.

    [NoInterfaceObject] interface BluetoothManagerObject {
        readonly attribute BluetoothManager bluetooth;
    };
    WebAPIs implements BluetoothManagerObject;

There is a webapis.bluetooth object that allows access to the Bluetooth API.

2.2. BluetoothManager

This interface provides access to the BluetoothAdapter object.

    [NoInterfaceObject] interface BluetoothManager {
        readonly attribute BluetoothClassDeviceMajor deviceMajor;
        readonly attribute BluetoothClassDeviceMinor deviceMinor;
        readonly attribute BluetoothClassDeviceService deviceService;
        BluetoothAdapter getDefaultAdapter() raises(WebAPIException);
    };

ATTRIBUTES

readonly BluetoothClassDeviceMajor deviceMajor

An attribute to access to a major device class identifiers of Bluetooth class of device (CoD).

This attribute is read-only.

readonly BluetoothClassDeviceMinor deviceMinor

An attribute to access to a minor device class identifiers of Bluetooth class of device (CoD).

This attribute is read-only.

readonly BluetoothClassDeviceService deviceService

Accessor to major service class identifiers of Bluetooth class of device (CoD).

This attribute is read-only.

METHODS

getDefaultAdapter

Gets the default local Bluetooth adapter.

Signature
BluetoothAdapter getDefaultAdapter();
Return value
BluetoothAdapter The local BluetoothAdapter object.
Exceptions
  • WebAPIException:

    with error type UnknownError, if any other error occurs.

    with error type NotSupportedError, if this feature is not supported.

    with error type SecurityError, if the application does not have the privilege to call this method.

Code example
 try {
  var adapter = webapis.bluetooth.getDefaultAdapter() ;
 } catch (err) {
  console.log (err.name +": " + err.message);
 }
 

2.3. BluetoothAdapter

This interface provides access to control the device's Bluetooth adapter.

    [NoInterfaceObject] interface BluetoothAdapter {
        readonly attribute DOMString name;
        readonly attribute BluetoothAddress address;
        readonly attribute boolean powered; 
        readonly attribute boolean visible;

        void setName(DOMString name,
                     optional SuccessCallback? successCallback, 
                     optional ErrorCallback? errorCallback) raises(WebAPIException);
 
        void setPowered(boolean state,
                        optional SuccessCallback? successCallback, 
                        optional ErrorCallback? errorCallback) raises(WebAPIException);     
        
        void setVisible(boolean mode,
                        optional SuccessCallback? successCallback, 
                        optional ErrorCallback? errorCallback,
                        optional unsigned short? timeout) raises(WebAPIException);

        void setChangeListener(BluetoothAdapterChangeCallback listener) raises(WebAPIException);

        void unsetChangeListener() raises(WebAPIException);

        void discoverDevices(BluetoothDiscoverDevicesSuccessCallback successCallback, 
                             optional ErrorCallback? errorCallback) raises(WebAPIException);

        void stopDiscovery(optional SuccessCallback? successCallback, 
                           optional ErrorCallback? errorCallback) raises(WebAPIException);

        void getKnownDevices(BluetoothDeviceArraySuccessCallback successCallback, 
                             optional ErrorCallback? errorCallback) raises(WebAPIException);




        void getDevice(BluetoothAddress address,
                       BluetoothDeviceSuccessCallback successCallback, 
                       optional ErrorCallback? errorCallback) raises(WebAPIException);




        void createBonding(BluetoothAddress address,
                           BluetoothDeviceSuccessCallback successCallback, 
                           optional ErrorCallback? errorCallback) raises(WebAPIException);

        void destroyBonding(BluetoothAddress address,
                            optional SuccessCallback? successCallback, 
                            optional ErrorCallback? errorCallback) raises(WebAPIException);



        void registerRFCOMMServiceByUUID(BluetoothUUID uuid,
                                         DOMString name,
                                         BluetoothServiceSuccessCallback successCallback, 
                                         optional ErrorCallback? errorCallback) raises(WebAPIException);

        BluetoothProfileHandler getBluetoothProfileHandler(BluetoothProfileType profileType) raises(WebAPIException);

             };

This interface offers methods to control local Bluetooth behavior, such as:

  • Turning on/off Bluetooth radio
  • Changing device visibility
  • Scanning for remote devices
  • Accessing known devices
  • Registering a service in the device service database

ATTRIBUTES

readonly DOMString name

An attribute to store the readable name of the Bluetooth adapter.

This attribute is read-only.
Code example
 
 // Access adapter name
 var adapter = webapis.bluetooth.getDefaultAdapter();
 console.log ("Bluetooth adapter name: " + adapter.name);
 

readonly BluetoothAddress address

An attribute to store the unique hardware address of the Bluetooth adapter, also known as the MAC address.

This attribute is read-only.
Code example
 var adapter = webapis.bluetooth.getDefaultAdapter();
 console.log("Bluetooth device address: " + adapter.address);
 

readonly boolean powered

An attribute to indicate the current state of the Bluetooth adapter. This attribute holds one of the following 2 values:

  • true - If Bluetooth adapter is currently on
  • false - If Bluetooth adapter is currently off
This attribute is read-only.
Code example
 var adapter = webapis.bluetooth.getDefaultAdapter();
 console.log("Bluetooth state: " + (adapter.powered ? "On" : "Off"));
 

readonly boolean visible

An attribute to indicate the current visibility state of the Bluetooth adapter, that is, whether the local device is discoverable by remote devices or not.

This attribute is read-only.
Code example
 // Queries current visible state
 var adapter = webapis.bluetooth.getDefaultAdapter();
 console.log ("Bluetooth Visibility: " + (adapter.visible ? "On" : "Off"));
 

METHODS

setName

Sets the local Bluetooth adapter name.

Signature
void setName(DOMString name, optional SuccessCallback? successCallback, optional ErrorCallback? errorCallback);

Sends a request to Bluetooth hardware to change the name of the local Bluetooth adapter to name.

The ErrorCallback is launched with these error types:

  • InvalidValuesError: If any of the input parameters contain an invalid value.
  • ServiceNotAvailableError: If a Bluetooth device is turned off.
  • UnknownError: In any other error case.
Parameters
  • name
    • Optional: No.
    • Nullable: No.
    • Type: DOMString.
    • Description: The name to set.
  • successCallback
    • Optional: Yes.
    • Nullable: Yes.
    • Type: SuccessCallback.
    • Description: The method to invoke when the asynchronous call completes successfully.
  • errorCallback
    • Optional: Yes.
    • Nullable: Yes.
    • Type: ErrorCallback.
    • Description: The method to invoke when an error occurs.
Exceptions
  • WebAPIException:

    with error type NotSupportedError, if this feature is not supported.

    with error type SecurityError, if the application does not have the privilege to call this method.

    with error type TypeMismatchError, if any of the input parameter is not compatible with the expected type for that parameter.

Code example
 var adapter = webapis.bluetooth.getDefaultAdapter();
 
 function changeName(newName) 
 {  
      if(adapter.name != newName) {
           // initiate change name
           adapter.setName(newName, function() {
               console.log("Adapter name changed to " + adapter.name);
           },
           function(e) {
               console.log("Failed to change name: " + e.message);
           });
      }
 }

 changeName("myDevice");
 

setPowered

Sets the state of a Bluetooth adapter to on or off by sending a request to Bluetooth hardware to change the power state. For most Bluetooth actions, the Bluetooth adapter must be powered on.

Signature
void setPowered(boolean state, optional SuccessCallback? successCallback, optional ErrorCallback? errorCallback);

The ErrorCallback is launched with these error names:

  • ServiceNotAvailableError - If a Bluetooth device is busy.
  • UnknownError - If any other error occurs.
Parameters
  • state
    • Optional: No.
    • Nullable: No.
    • Type: boolean.
    • Description: The state to set: true to power on Bluetooth, false to power it off.
  • successCallback
    • Optional: Yes.
    • Nullable: Yes.
    • Type: SuccessCallback.
    • Description: The method to invoke on successful Bluetooth activation/deactivation.
  • errorCallback
    • Optional: Yes.
    • Nullable: Yes.
    • Type: ErrorCallback.
    • Description: The method to invoke on failure of a Bluetooth activation/deactivation.
Exceptions
  • WebAPIException:

    with error type NotSupportedError, if this feature is not supported.

    with error type SecurityError, if the application does not have the privilege to call this method.

    with error type TypeMismatchError, if any of the input parameter is not compatible with the expected type for that parameter.

Code example
 var adapter = webapis.bluetooth.getDefaultAdapter();
 
 function powerOn() 
 {
      // If adapter is not powered on 
      if(!adapter.powered) {
           // Initiates power on
           adapter.setPowered(true, function() {
               console.log("Bluetooth powered on success.");
           },
           function(e) {
               console.log("Failed to power on Bluetooth: " + e.message);
           });
      }
 }

 function powerOff()
 {
      // If powered on
      if(adapter.powered) {
           // Initiates power off
           adapter.setPowered(false, function() {
               console.log("Bluetooth powered off successfully.");
           },
           function(e) {
               console.log("Failed to power off Bluetooth: " + e.message);
           });
      }
 }
 

setVisible

Sets the local device visibility by sending a request to a Bluetooth hardware to change the device visible state to mode. If mode is true, then the device is visible to other devices, that is, it responds to inquiry calls from remote devices for time period defined (in seconds) by timeout. After the timeout, the device will become invisible.

Signature
void setVisible(boolean mode, optional SuccessCallback? successCallback, optional ErrorCallback? errorCallback, optional unsigned short? timeout);

If timeout is not passed or an invalid parameter is passed, the timeout defaults to 180 seconds (3 minutes). A timeout of 0 is considered unlimited.

The ErrorCallback is launched with these error types:

  • InvalidValuesError - If any of the input parameters contain an invalid value.
  • ServiceNotAvailableError - If a Bluetooth device is turned off.
  • UnknownError - If any other error case occurs.
Parameters
  • mode
    • Optional: No.
    • Nullable: No.
    • Type: boolean.
    • Description: The boolean value to set visibility. It can either be set to: true - to show the device or false - to hide the device.
  • successCallback
    • Optional: Yes.
    • Nullable: Yes.
    • Type: SuccessCallback.
    • Description: The method to invoke when an asynchronous call completes successfully.
  • errorCallback
    • Optional: Yes.
    • Nullable: Yes.
    • Type: ErrorCallback.
    • Description: The method to invoke when an error occurs.
  • timeout
    • Optional: Yes.
    • Nullable: Yes.
    • Type: unsigned short.
    • Description: The visible timeout in seconds, used only when mode is true.
Exceptions
  • WebAPIException:

    with error type NotSupportedError, if this feature is not supported.

    with error type SecurityError, if the application does not have the privilege to call this method.

    with error type TypeMismatchError, if any of the input parameter is not compatible with the expected type for that parameter.

Code example
 var adapter = webapis.bluetooth.getDefaultAdapter();
 
 function showMe()
 {
      if (adapter.visible == false) {
          //Shows device
          adapter.setVisible(true, 
                             function() { console.log ('Device is visible to other devices for 3 minutes.'); },
                             function(e) { console.log ('Error: ' + e.message + '(' + e.name + ')'); });
      }
      else {
           console.log("Device is already in discoverable mode.");
      }
 }

 function hideMe() 
 {
     if (adapter.visible) {
          // Hides device
          adapter.setVisible(false,
                             function() { console.log('Device is in-visible now.'); },
                             function(e) { console.log ('Error: ' + e.message + '(' + e.name + ')'); });
     }
     else {
          console.log("Device is already in invisible mode.");
     }
 }
 

setChangeListener

Sets the listener to receive notifications about changes of Bluetooth adapter.

Signature
void setChangeListener(BluetoothAdapterChangeCallback listener);
Parameters
  • listener
    • Optional: No.
    • Nullable: No.
    • Type: BluetoothAdapterChangeCallback.
    • Description: The Bluetooth Adapter event listener to set.
Exceptions
  • WebAPIException:

    with error type UnknownError, if any other error occurs.

    with error type SecurityError, if this functionality is not allowed.

    with error type TypeMismatchError, if the input parameter is not compatible with the expected type.

Code example
 var changeListener = {
      onstatechanged: function(powered) {
          console.log ("Power state is changed into: " + powered);
      },
      onnamechanged: function(name) {
          console.log("Name is changed to: " + name);
      },
      onvisibilitychanged: function(visible) {
          console.log("Visibility is changed into: " + visible);
      }
 };

 var adapter = webapis.bluetooth.getDefaultAdapter();
 adapter.setChangeListener(changeListener);
 

unsetChangeListener

Unsets the listener, so stop receiving notifications about changes of Bluetooth adapter.

Signature
void unsetChangeListener();
Exceptions
  • WebAPIException:

    with error type UnknownError, if any other error occurs.

    with error type SecurityError, if this functionality is not allowed.

Code example
 var adapter = webapis.bluetooth.getDefaultAdapter();

 var changeListener = {
      onstatechanged: function(powered) {
          console.log ("Power state is changed into: " + powered);
          if(!powered)
              adapter.unsetChangeListener();
      },
      onnamechanged: function(name) {
          console.log("Name is changed to: " + name);
      },
      onvisibilitychanged: function(visible) {
          console.log("Visibility is changed into: " + visible);
      }
 };

 adapter.setChangeListener(changeListener);
 

discoverDevices

Discovers nearby Bluetooth devices if any, that is, devices within proximity to the local device.

Signature
void discoverDevices(BluetoothDiscoverDevicesSuccessCallback successCallback, optional ErrorCallback? errorCallback);

This method initiates the device discovery process. Depending on the progress of this process the following methods are invoked:

  • BluetoothDiscoverDevicesSuccessCallback.onstarted() - when a discovery process starts successfully.
  • BluetoothDiscoverDevicesSuccessCallback.ondevicefound() - when any device is found in the process and this method is invoked with the device information. If no device is found, this method will never be invoked.
  • BluetoothDiscoverDevicesSuccessCallback.ondevicedisappeared() - when a device goes out of proximity and this method is invoked with the address of the device.
  • BluetoothDiscoverDevicesSuccessCallback.onfinished() - when a discovery process is completed.

A discovery process can be canceled anytime, by calling stopDiscovery() on the BluetoothAdapter.

The ErrorCallback is launched with these error types:

  • ServiceNotAvailableError - If a Bluetooth device is turned off.
  • UnknownError - If any other error occurs.
Parameters
  • successCallback
    • Optional: No.
    • Nullable: No.
    • Type: BluetoothDiscoverDevicesSuccessCallback.
    • Description: The method to invoke when an asynchronous call completes successfully.
  • errorCallback
    • Optional: Yes.
    • Nullable: Yes.
    • Type: ErrorCallback.
    • Description: The method to invoke when an error occurs.
Exceptions
  • WebAPIException:

    with error type NotSupportedError, if this feature is not supported.

    with error type SecurityError, if the application does not have the privilege to call this method.

    with error type TypeMismatchError, if any of the input parameter is not compatible with the expected type for that parameter.

Code example
 var adapter = webapis.bluetooth.getDefaultAdapter();
 
 function startDiscovery() {

  var discoverDevicesSuccessCallback = {
      onstarted: function() { 
          console.log ("Device discovery started...");
      },
      ondevicefound: function(device) { 
          console.log("Found device - name: " + device.name + ", Address: "+ device.address); 
      },
      ondevicedisappeared: function(address) { 
          console.log("Device disappeared: " + address); 
      },
      onfinished: function(devices) { 
          console.log("Found Devices");
          for (var i = 0; i < devices.length; i++) {
              console.log("Name: " + devices[i].name + ", Address: " + devices[i].address);
          }
          console.log("Total: " + devices.length);
      }
  };
 
  // Starts searching for nearby devices, for about 12 sec.
  adapter.discoverDevices(discoverDevicesSuccessCallback, function(e){
      console.log ("Failed to search devices: " + e.message + "(" + e.name + ")");
  });
 }

 function onSetPoweredError(e) {
     console.log ("Could not turn on device, reason: " + e.message + "(" + e.name + ")");
 }

 adapter.setPowered(true, startDiscovery, onSetPoweredError);
 

stopDiscovery

Stops an active device discovery session.

Signature
void stopDiscovery(optional SuccessCallback? successCallback, optional ErrorCallback? errorCallback);

Device discovery is a heavyweight procedure, hence we recommend stopping discovery as soon as required device is found. This method cancels an active discovery session.

The ErrorCallback is launched with these error types:

  • ServiceNotAvailableError - If a Bluetooth device is turned off.
  • UnknownError - If any other error occurs.
Parameters
  • successCallback
    • Optional: Yes.
    • Nullable: Yes.
    • Type: SuccessCallback.
    • Description: The method to invoke when an asynchronous call completes successfully.
  • errorCallback
    • Optional: Yes.
    • Nullable: Yes.
    • Type: ErrorCallback.
    • Description: The method to invoke when an error occurs.
Exceptions
  • WebAPIException:

    with error type NotSupportedError, if this feature is not supported.

    with error type SecurityError, if the application does not have the privilege to call this method.

    with error type TypeMismatchError, if any of the input parameter is not compatible with the expected type for that parameter.

Code example
 var adapter = webapis.bluetooth.getDefaultAdapter();
 
 // Calls this method whenever user finds one of the device
 function cancelDiscovery() {
    adapter.stopDiscovery(function() {
        console.log("Stop discovery success.");
    },
    function (e) {
        console.log("Error while stopDiscovery:" + e.message);
    });
 }

 function startDiscovery() {

  var discoverDevicesSuccessCallback = {
      onstarted: function() { 
          console.log ("Device discovery started...") ;
      },
      ondevicefound: function(device) {
          console.log("Found device - name: " + device.name + ", Address: "+ device.address);
          // Shows the device to user to check if this is the device user is looking for.
          // For example, add this to list view.

          cancelDiscovery();
      },
      ondevicedisappeared: function(address) { 
          console.log("Device disappeared: " + address);
          // Removes from list, as it is no longer valid.
      },
      onfinished: function(devices) { 
          console.log("Found Devices");
          for (var i = 0; i < devices.length; i++) {
              console.log("Name: " + devices[i].name + ", Address: " + devices[i].address);
          }
          console.log("Total: " + devices.length);
      }
  };
 
  // Starts searching for nearby devices, for about 12 sec.
  adapter.discoverDevices(discoverDevicesSuccessCallback, function(e){
      console.log ("Failed to search devices: " + e.message + "(" + e.name + ")");
  });
 }

 function onSetPoweredError(e) {
     console.log ("Could not turn on device, reason: " + e.message + "(" + e.name + ")");
 }

 adapter.setPowered(true, startDiscovery, onSetPoweredError);
 

getKnownDevices

Gets all the known devices that have information stored in the local Bluetooth adapter.

Signature
void getKnownDevices(BluetoothDeviceArraySuccessCallback successCallback, optional ErrorCallback? errorCallback);

A known device is one of the following:

  • a bonded device
  • a device found in last inquiry process

On success, it returns the list of currently known devices through BluetoothDeviceArraySuccessCallback.

The ErrorCallback is launched with these error types:

  • ServiceNotAvailableError - If a Bluetooth device is turned off.
  • UnknownError - If any other error occurs.
Parameters
  • successCallback
    • Optional: No.
    • Nullable: No.
    • Type: BluetoothDeviceArraySuccessCallback.
    • Description: The method to invoke at retrieval of a list of Bluetooth devices that were bonded (paired) to the local Bluetooth adapter.
  • errorCallback
    • Optional: Yes.
    • Nullable: Yes.
    • Type: ErrorCallback.
    • Description: The method to invoke in case of failure in finding any bonded devices.
Exceptions
  • WebAPIException:

    with error type NotSupportedError, if this feature is not supported.

    with error type SecurityError, if the application does not have the privilege to call this method.

    with error type TypeMismatchError, if the input parameter is not compatible with the expected type for that parameter

Code example
 var adapter = webapis.bluetooth.getDefaultAdapter();
 
 function onGotDevices(devices) {
    console.log("Devices");
    for (var i = 0; i < devices.length; i++) {
        console.log(" Name: " + devices[i].name + ", Address: " + devices[i].address);
    }
    console.log("Total: " + devices.length);
 }

 function onError(e) {
   console.log ("Error: " + e.message);
 }

 function onBluetoothsetPowered() {
    adapter.getKnownDevices(onGotDevices, onError);
 }
 
 // Turns on Bluetooth
 adapter.setPowered(true, onBluetoothsetPowered);
 

getDevice

Gets the BluetoothDevice object for a given device hardware address.

Signature
void getDevice(BluetoothAddress address, BluetoothDeviceSuccessCallback successCallback, optional ErrorCallback? errorCallback);

This method returns device information stored in the local Bluetooth adapter for the specified device address through BluetoothDeviceSuccessCallback. A valid hardware address must be passed, such as "35:F4:59:D1:7A:03".

The ErrorCallback is launched with these error types:

  • NotFoundError - If there is no device with the given address.
  • ServiceNotAvailableError - If a Bluetooth device is turned off.
  • UnknownError - If any other error occurs.
Parameters
  • address
    • Optional: No.
    • Nullable: No.
    • Type: BluetoothAddress.
    • Description: The address of a remote Bluetooth device to get.
  • successCallback
    • Optional: No.
    • Nullable: No.
    • Type: BluetoothDeviceSuccessCallback.
    • Description: The method to invoke when an asynchronous call completes successfully.
  • errorCallback
    • Optional: Yes.
    • Nullable: Yes.
    • Type: ErrorCallback.
    • Description: The method to invoke when an error occurs.
Exceptions
  • WebAPIException:

    with error type NotSupportedError, if this feature is not supported.

    with error type SecurityError, if the application does not have the privilege to call this method.

    with error type TypeMismatchError, if the input parameter is not compatible with the expected type for that parameter

Code example
 function gotDeviceInfo(device) {
    console.log("Device Name: " + device.name);
    console.log("Device Address: " + device.address);
    console.log("Device Class: " + device.deviceClass.major);
    console.log("Is Bonded: " + (device.isBonded ? "Yes" : "No"));
 }

 function onError(e) {
    console.log ("Could not get device info:" + e.message);
 }

 var adapter = webapis.bluetooth.getDefaultAdapter();
 adapter.getDevice("35:F4:59:D1:7A:03", gotDeviceInfo, onError);
 

createBonding

Creates a bond with a remote device by initiating the bonding process with peer device, using the given MAC address. The remote device must be bonded with the local device in order to connect to services of the remote device and then exchange data with each other.

Signature
void createBonding(BluetoothAddress address, BluetoothDeviceSuccessCallback successCallback, optional ErrorCallback? errorCallback);

If the bonding process is successful, the device information is sent in successCallback.

The ErrorCallback is launched with these error types:

  • NotFoundError - If there is no device with the given address.
  • ServiceNotAvailableError - If a Bluetooth device is turned off.
  • UnknownError - If any other error occurs.
Parameters
  • address
    • Optional: No.
    • Nullable: No.
    • Type: BluetoothAddress.
    • Description: The MAC address of remote Bluetooth address to bond with.
  • successCallback
    • Optional: No.
    • Nullable: No.
    • Type: BluetoothDeviceSuccessCallback.
    • Description: The method to invoke when an asynchronous call completes successfully.
  • errorCallback
    • Optional: Yes.
    • Nullable: Yes.
    • Type: ErrorCallback.
    • Description: The method to invoke when an error occurs.
Exceptions
  • WebAPIException:

    with error type NotSupportedError, if this feature is not supported.

    with error type SecurityError, if the application does not have the privilege to call this method.

    with error type TypeMismatchError, if the input parameter is not compatible with the expected type for that parameter.

Code example
 function onBondingSuccess(device) {
    console.log("Device Name:" + device.name);
    console.log("Device Address:" + device.address);
    console.log("Device Service UUIDs:" + device.uuids.join("\n"));
 }

 function onError(e) {
    console.log ("Could not create bonding, reason:" + e.message);
 }

 var adapter = webapis.bluetooth.getDefaultAdapter();
 adapter.createBonding("35:F4:59:D1:7A:03", onBondingSuccess, onError);
 

destroyBonding

Destroys the bond with a remote device, that is, this method initiates the process of removing the specified address from the list of bonded devices.

Signature
void destroyBonding(BluetoothAddress address, optional SuccessCallback? successCallback, optional ErrorCallback? errorCallback);

The ErrorCallback is launched with these error types:

  • NotFoundError - If there is no device with the given address.
  • ServiceNotAvailableError - If a Bluetooth device is turned off.
  • UnknownError - If any other error occurs.
Parameters
  • address
    • Optional: No.
    • Nullable: No.
    • Type: BluetoothAddress.
    • Description: The address of a bonded device.
  • successCallback
    • Optional: Yes.
    • Nullable: Yes.
    • Type: SuccessCallback.
    • Description: The method to invoke when an asynchronous call completes successfully.
  • errorCallback
    • Optional: Yes.
    • Nullable: Yes.
    • Type: ErrorCallback.
    • Description: The method to invoke when an error occurs.
Exceptions
  • WebAPIException:

    with error type NotSupportedError, if this feature is not supported.

    with error type SecurityError, if the application does not have the privilege to call this method.

    with error type TypeMismatchError, if the input parameter is not compatible with the expected type for that parameter

Code example
 var adapter = webapis.bluetooth.getDefaultAdapter();
 
 function gotDevice(device) {
    if (device.isBonded) {
      // Initiates destroying bonding
      adapter.destroyBonding(device.address, function() { 
           console.log("Succeeded to destroy the bond success with:" + device.address);
       },
       function(e) { 
           console.log("Failed to destroy the bond with " + device.address + ", reason: " + e.message); 
       });
    }
 }

 var deviceAddress = "35:F4:59:D1:7A:03";
 adapter.getDevice(deviceAddress, gotDevice, function(e) { 
             console.log("Failed to get device info for " + deviceAddress + ", reason: " + e.message); 
 } );
 

registerRFCOMMServiceByUUID

Registers a service record in the device service record database with the specified uuid, name.

Signature
void registerRFCOMMServiceByUUID(BluetoothUUID uuid, DOMString name, BluetoothServiceSuccessCallback successCallback, optional ErrorCallback? errorCallback);

On success of the service registration, it returns a BluetoothServiceHandler object as the first parameter of successCallback, and listens for client connections. The service handler can be used to be notified on client connections or to unregister the service. User interaction is mandatory to connect to a registered service.

If any client(remote device) connects to this service, then BluetoothServiceHandler.onconnect() is invoked with BluetoothSocket object.

BluetoothServiceHandler.unregister() can be used to unregister the service record from the device service database and stop listening for client connections.

The ErrorCallback is launched with these error types:

  • InvalidValuesError - If any of the input parameters contain an invalid value.
  • ServiceNotAvailableError - If a Bluetooth device is turned off.
  • UnknownError - If any other error occurs.
Parameters
  • uuid
    • Optional: No.
    • Nullable: No.
    • Type: BluetoothUUID.
    • Description: The UUID of the service, to which clients connects.
  • name
    • Optional: No.
    • Nullable: No.
    • Type: DOMString.
    • Description: The Name of a service.
  • successCallback
    • Optional: No.
    • Nullable: No.
    • Type: BluetoothServiceSuccessCallback.
    • Description: The method to invoke on successful service registration.
  • errorCallback
    • Optional: Yes.
    • Nullable: Yes.
    • Type: ErrorCallback.
    • Description: The method to invoke when an error occurs.
Exceptions
  • WebAPIException:

    with error type NotSupportedError, if this feature is not supported.

    with error type SecurityError, if the application does not have the privilege to call this method.

    with error type TypeMismatchError, if the input parameter is not compatible with the expected type for that parameter.

Code example
 var adapter = webapis.bluetooth.getDefaultAdapter();
 // Holds currently registered service record
 var chatServiceHandler = null;
 // Holds currently open socket
 var serviceSocket = null;

 function chatServiceSuccessCb(recordHandler) {
    console.log("Chat service registration succeeds!");
    chatServiceHandler = recordHandler;
    recordHandler.onconnect = function(socket) {
        console.log("Client connected: " + socket.peer.name + "," + socket.peer.address);
        serviceSocket = socket;
        // Messages received from remote device
        socket.onmessage = function() {
             var data = socket.readData();
             // Handles message code goes here
             
        };
        
        socket.onclose = function() {
            console.log('The socket is closed.');
            serviceSocket = null;
        };
    };
 };

 function publishChatService()
 {
    var CHAT_SERVICE_UUID = "5BCE9431-6C75-32AB-AFE0-2EC108A30860";
    adapter.registerRFCOMMServiceByUUID(CHAT_SERVICE_UUID, "Chat service", chatServiceSuccessCb,
      // Error handler
      function(e) {
           console.log( "Could not register service record, Error: " + e.message);
      });
 }
 
 function unregisterChatService()
 {
      if (chatServiceHandler != null) {
          chatServiceHandler.unregister(function() {
               console.log("Chat service is unregistered");
               chatServiceHandler = null;
           }, function(e) {
               console.log("Failed to unregister service: " + e.message);
           });
      }
 }
 

getBluetoothProfileHandler

Gets the profile handler for the given type.

Signature
BluetoothProfileHandler getBluetoothProfileHandler(BluetoothProfileType profileType);
Parameters
  • profileType
    • Optional: No.
    • Nullable: No.
    • Type: BluetoothProfileType.
    • Description: The type of Bluetooth Profile.
Exceptions
  • WebAPIException:

    with error type UnknownError, if any other error occurs.

    with error type NotSupportedError, if this feature is not supported.

    with error type TypeMismatchError, if the input parameter is not compatible with the expected type for that parameter.

Code example
 var adapter = webapis.bluetooth.getDefaultAdapter();
 var healthProfileHandler = adapter.getBluetoothProfileHandler("HEALTH");
 

2.4. BluetoothDevice

This interface represents a remote Bluetooth device.

    [NoInterfaceObject] interface BluetoothDevice {
        readonly attribute DOMString name;
        readonly attribute BluetoothAddress address;
        readonly attribute BluetoothClass deviceClass;
        readonly attribute boolean isBonded;
        readonly attribute boolean isTrusted;
        readonly attribute boolean isConnected;
        readonly attribute BluetoothUUID[] uuids;

        void connectToServiceByUUID(BluetoothUUID uuid,
                                    BluetoothSocketSuccessCallback successCallback, 
                                    optional ErrorCallback? errorCallback) raises(WebAPIException);
    };

A BluetoothDevice object can be retrieved using one of the following APIs:

  • BluetoothAdapter.getDevice()
  • BluetoothAdapter.getKnownDevices()
  • BluetoothAdapter.discoverDevices()
  • BluetoothAdapter.createBonding()

ATTRIBUTES

readonly DOMString name

An attribute to store the readable name of this remote device.

This attribute is read-only.
Code example
 var adapter = webapis.bluetooth.getDefaultAdapter();
 adapter.getDevice("11:22:33:44:55:66", function(device) {
    console.log("Device Name: " + device.name);
 });
 

readonly BluetoothAddress address

An attribute to store the hardware address of this remote device.

This attribute is read-only.
Code example
 var adapter = webapis.bluetooth.getDefaultAdapter();
 adapter.getDevice("11:22:33:44:55:66", function(device) {
    console.log("Device Address: " + device.address);
 });
 

readonly BluetoothClass deviceClass

An attribute to indicate a device class, which represents the type of the device and the services it provides.

This attribute is read-only.
Code example
 var adapter = webapis.bluetooth.getDefaultAdapter();
 adapter.getDevice("11:22:33:44:55:66", function(device) {
    console.log("Device Major Class: " + device.deviceClass.major);
 });
 

readonly boolean isBonded

An attribute to check the bond state of this remote device with the local device.

This attribute is read-only.
Code example
 var adapter = webapis.bluetooth.getDefaultAdapter();
 adapter.getDevice("11:22:33:44:55:66", function(device) {
    console.log("Is bonded: " + (device.isBonded ? "Yes" : "No"));
 });
 

readonly boolean isTrusted

An attribute to check whether the local device recognizes this remote device as a trusted device or not.

This attribute is read-only.
Code example
 var adapter = webapis.bluetooth.getDefaultAdapter();
 adapter.getDevice("11:22:33:44:55:66", function(device) {
    console.log("Is trusted: " + (device.isTrusted ? "Yes" : "No"));
 });
 

readonly boolean isConnected

An attribute to check the connection state of this remote device with the local device.

This attribute is read-only.
Code example
 var adapter = webapis.bluetooth.getDefaultAdapter();
 adapter.getDevice("11:22:33:44:55:66", function(device) {
    console.log("Is connected: " + (device.isConnected ? "Yes" : "No"));
 });
 

readonly BluetoothUUID[] uuids

An attribute to store the list of 128 bit service UUIDs available on this remote device.

This attribute is read-only.
Code example
 var adapter = webapis.bluetooth.getDefaultAdapter();
 var CHAT_SERVICE_UUID = "5BCE9431-6C75-32AB-AFE0-2EC108A30860";
 adapter.getDevice("11:22:33:44:55:66", function(device) {
    var uuids = device.uuids;
    var services = "";
    for (var i = 0; i < uuids.length; i++) {
        services += uuids[i] + "\n";
    }
    console.log ("Services found: " + services);
    if (uuids.indexOf(CHAT_SERVICE_UUID) != -1) {
        // Connects to service
        device.connectToServiceByUUID(CHAT_SERVICE_UUID, function(socket) {
            //
            // Connected to service, handle socket
            //
        }, function (e) {
            console.log("Could not connect to chat service !!!. Error: " + e.message);
        });
    }
 });
 

METHODS

connectToServiceByUUID

Connects to a specified service identified by uuid on this remote device.

Signature
void connectToServiceByUUID(BluetoothUUID uuid, BluetoothSocketSuccessCallback successCallback, optional ErrorCallback? errorCallback);

If opening a connection is successful, then a BluetoothSocket object with open state is sent using successCallback, through which data can be exchanged by both devices.

The ErrorCallback is launched with these error types:

  • NotFoundError - If there is no service with the specified uuid.
  • InvalidValuesError - If any of the input parameters contain an invalid value.
  • UnknownError - If any other error occurs.
Parameters
  • uuid
    • Optional: No.
    • Nullable: No.
    • Type: BluetoothUUID.
    • Description: The 128 bit unique identifier, which represents the service record on the device.
  • successCallback
    • Optional: No.
    • Nullable: No.
    • Type: BluetoothSocketSuccessCallback.
    • Description: The method to invoke when an asynchronous call completes successfully.
  • errorCallback
    • Optional: Yes.
    • Nullable: Yes.
    • Type: ErrorCallback.
    • Description: The method to invoke when opening of a socket fails.
Exceptions
  • WebAPIException:

    with error type NotSupportedError, if this feature is not supported.

    with error type SecurityError, if the application does not have the privilege to call this method.

    with error type TypeMismatchError, if the input parameter is not compatible with the expected type for that parameter

Code example
 var adapter = webapis.bluetooth.getDefaultAdapter();
 var clientSocket = null;

 // Calls a method that is invoked when user wants to send a message to a remote device
 function sendMessage(msg) {
    // Validates socket state, if everything is ok.
    if (clientSocket != null && clientSocket.state == "OPEN") {
        // Sends the message
        clientSocket.writeData(msg);
    }
 }

 // Calls a method that is invoked when a socket is open
 function onSocketConnected(socket) {
    clientSocket = socket;
    console.log("Opening a socket successfully!!!");
    socket.onmessage = function () {
        var data = socket.readData();
        var recvmsg = "";
        for (var i = 0; i < data.length; i++)
        {
           recvmsg += String.fromCharCode(data[i]);
        }
        console.log("server msg >> " + recvmsg);
    };

    socket.onclose = function() {
        console.log("socket disconnected.");
    };
 }

 function onDeviceReady(device) {
    // Validates device and service uuid
    if (device.uuids.indexOf("5BCE9431-6C75-32AB-AFE0-2EC108A30860") != -1) {
       // Opens socket
       device.connectToServiceByUUID("5BCE9431-6C75-32AB-AFE0-2EC108A30860", onSocketConnected, function(e) {
           console.log ("Error connecting to service. Reason: " + e.message);
        });
    }
    else {
        console.log ("Chat service is not supported by this device");
    }
 }

 function onSetPowered() {
    // Gets the BluetoothDevice object
    adapter.getDevice("35:F4:59:D1:7A:03", onDeviceReady, function(e) { console.log("Error: " + e.message); });
 }

 adapter.setPowered(true, onSetPowered, function(e) {console.log ("Could not turn on Bluetooth adapter. reason: " + e.message); });
 

2.5. BluetoothSocket

This interface represents the Bluetooth socket.

    [NoInterfaceObject] interface BluetoothSocket {
        readonly attribute BluetoothUUID uuid;
        readonly attribute BluetoothSocketState state;
        readonly attribute BluetoothDevice peer;
        [TreatNonCallableAsNull] attribute SuccessCallback? onmessage;
        [TreatNonCallableAsNull] attribute SuccessCallback? onclose;
        unsigned long writeData(byte[] data) raises(WebAPIException);


        byte[] readData() raises(WebAPIException);


        void close() raises(WebAPIException);
    };

The socket object is created by BluetoothDevice.connectToServiceByUUID() or BluetoothAdapter.registerRFCOMMServiceByUUID().

ATTRIBUTES

readonly BluetoothUUID uuid

An attribute to store the service UUID to which this socket is connected.

This attribute is read-only.

readonly BluetoothSocketState state

An attribute to indicate the socket state.

This attribute is read-only.

readonly BluetoothDevice peer

The peer device to which this socket is connected.

This attribute is read-only.

SuccessCallback? onmessage

The success callback to be invoked when an incoming message is received from the peer. By default, this attribute is set to null.

SuccessCallback? onclose

The success callback to be invoked when the socket is closed. By default, this attribute is set to null.

METHODS

writeData

Writes data as a sequence of bytes onto the socket and returns the number of bytes actually written.

Signature
unsigned long writeData(byte[] data);
Parameters
  • data
    • Optional: No.
    • Nullable: No.
    • Type: array.
    • Description: The data to send.
Return value
unsigned long The number of bytes actually sent.
Exceptions
  • WebAPIException:

    with error type UnknownError, if any other error occurs.

    with error type NotSupportedError, if this feature is not supported.

    with error type SecurityError, if the application does not have the privilege to call this method.

    with error type TypeMismatchError, if any input parameters not compatible with the expected type for that parameter.

Code example
 
 var adapter = webapis.bluetooth.getDefaultAdapter();
 
 function onSocketConnected(socket) {
    console.log ("Opened connection to remote device");
    socket.onmessage = function () {
      console.log ("Message received: " + socket.readData());
    };

    socket.onclose = function() {
       console.log("Socket closed with " + socket.peer.name);
    };

    // Sends data to peer.
    var textmsg = "Test";
    var sendtextmsg = new Array();
    for (var i = 0; i < textmsg.length; i++)
    {
        sendtextmsg[i] = textmsg.charCodeAt(i);
    }
    socket.writeData (sendtextmsg);
 }

 function onSocketError(e) {
    console.log ("Error connecting to service. Reason: " + e.message);
 }

 function onDeviceReady(device) {
    // Validates device and service uuid
    if (device.uuids.indexOf("5BCE9431-6C75-32AB-AFE0-2EC108A30860") != -1) {
       // Opens socket
       device.connectToServiceByUUID("5BCE9431-6C75-32AB-AFE0-2EC108A30860", onSocketConnected, onSocketError );
    }
 }
 function onSetPowered() {
    // Gets the BluetoothDevice object
    adapter.getDevice("35:F4:59:D1:7A:03", onDeviceReady, function(e) { console.log("Error: " + e.message); });
 }

 adapter.setPowered(true, onSetPowered, function(e) {console.log ("Could not turn on Bluetooth adapter. reason: " + e.message); });
 

readData

Reads data from the socket.

Signature
byte[] readData();

This method should be called only in the BluetoothSocket.onmessage handler, that is, when data is ready on the socket.

Return value
byte[] The sequence of bytes successfully read.
Exceptions
  • WebAPIException:

    with error type UnknownError, if any other error occurs.

    with error type NotSupportedError, if this feature is not supported.

    with error type SecurityError, if the application does not have the privilege to call this method.

Code example
 var adapter = webapis.bluetooth.getDefaultAdapter();

 function onError(e) {
    console.log ("Error connecting to service. Reason: " + e.message);
 }

 function onSocketConnected(socket) {
    console.log ("Opening socket success!!!");

    socket.onmessage = function() {
      //  Has got a message from peer, reads it
      var data = socket.readData();

      //
      // Code to evaluate message goes here
      //
    };

    socket.onclose = function() {
       console.log("Socket closed with " + socket.peer.name);
    };
 }

 function onDeviceReady(device) {
    // Validates device and service uuid
    if (device.uuids.indexOf("5BCE9431-6C75-32AB-AFE0-2EC108A30860") != -1) {
       // Opens socket
       device.connectToServiceByUUID("5BCE9431-6C75-32AB-AFE0-2EC108A30860", onSocketConnected, onError);
    }
 }
 function onSetPowered() {
    // Gets the BluetoothDevice object
    adapter.getDevice("35:F4:59:D1:7A:03", onDeviceReady, function(e) { console.log("Error: " + e.message); });
 }

 adapter.setPowered(true, onSetPowered, function(e) {console.log ("Could not turn on Bluetooth adapter. reason: " + e.message); });
 

close

Closes the socket.

Signature
void close();

BluetoothSocket.state changes to CLOSED, and BluetoothSocket.onclose() is invoked on success.

Exceptions
  • WebAPIException:

    with error type UnknownError, if any other error occurs.

    with error type SecurityError, if the application does not have the privilege to call this method.

    with error type NotSupportedError, if this feature is not supported.

2.6. BluetoothClass

This interface represents Bluetooth Class of Device/Service(CoD).

    [NoInterfaceObject] interface BluetoothClass {
        readonly attribute octet major;
        
        readonly attribute octet minor;
        
        readonly attribute unsigned short [] services ;
        
        boolean hasService(unsigned short service) raises(WebAPIException);
    };

Bluetooth device class describes the characteristics and capabilities of a device.

Bluetooth CoD is a 24 bit integer created by the union of three components:

  • Exactly one Major Device Class(bits 8-12 of CoD) - This is the highest level of granularity for defining a Bluetooth Device.
  • Exactly one Minor Device Class(bits 2-7 of CoD) - This is to be interpreted only in the context of the Major Device Class. Thus, the meaning of these bits may change, depending on the value of 'Major Device Class'.
  • Zero or more Major Service Classes(bits 13-23) - Represents the services supported by the device.

The Major and Minor classes are intended to define a general family of devices with which any particular implementation wishes to be associated. No assumptions should be made about specific functionality or characteristics of any application, based solely on the assignment of a Major or minor device class.

ATTRIBUTES

readonly octet major

The major device class and it refers to the BluetoothClassDeviceMajor interface for the list of possible values.

This attribute is read-only.
Code example
 var adapter = webapis.bluetooth.getDefaultAdapter();
 
 function evaluateDevice(address) {
    adapter.getDevice(address, function(device) {
        if (device.deviceClass.major == webapis.bluetooth.deviceMajor.COMPUTER) {
            // Shows computer icon for this device
            console.log("Device is computer");
        } else if (device.deviceClass.major == webapis.bluetooth.deviceMajor.PHONE) {
            // Shows phone icon
            console.log("Device is a Phone");
        }
    }, function(e) {
        console.log("Couldn't get any device with the given address: " + e.message);
    });
 }

 evaluateDevice("11:22:33:44:55:66");

 

readonly octet minor

The minor device class and it refer to the BluetoothClassDeviceMinor interface for the list of possible values.

This attribute is read-only.

readonly unsigned short[] services

The services provided by this device and it refers to the BluetoothClassDeviceService interface for the list of possible values.

This attribute is read-only.

METHODS

hasService

Checks whether the given service exists in the services.

Signature
boolean hasService(unsigned short service);
Parameters
  • service
    • Optional: No.
    • Nullable: No.
    • Type: unsigned short.
    • Description: The service to check.
Exceptions
  • WebAPIException:

    with error type UnknownError, if any other error occurs.

    with error type SecurityError, if the application does not have the privilege to call this method.

    with error type NotSupportedError, if this feature is not supported.

    with error type InvalidValuesError, if any of the input parameters contain an invalid value.

Code example
 var adapter = webapis.bluetooth.getDefaultAdapter();
 adapter.getDevice("12:34:56:78:9A:BC", function(device) {
    if (device.deviceClass.hasService(webapis.bluetooth.deviceService.POSITIONING)) {
         console.log("Device supports Positioning service");
    }
 }, function(e) {
    console.log("Couldn't get device for given address: " + e.message);
 });
 

2.7. BluetoothClassDeviceMajor

This interface holds the identifiers for major device classes of Bluetooth CoD.

    [NoInterfaceObject] interface BluetoothClassDeviceMajor {

        const octet MISC = 0x00;
        const octet COMPUTER = 0x01;
        const octet PHONE = 0x02;
        const octet NETWORK = 0x03;
        const octet AUDIO_VIDEO = 0x04;
        const octet PERIPHERAL = 0x05;
        const octet IMAGING = 0x06;
        const octet WEARABLE = 0x07;
        const octet TOY = 0x08;
        const octet HEALTH = 0x09;
        const octet UNCATEGORIZED = 0x1F;
    };

2.8. BluetoothClassDeviceMinor

This interface holds the identifiers for minor device classes of Bluetooth CoD.

    [NoInterfaceObject] interface BluetoothClassDeviceMinor {
        const octet COMPUTER_UNCATEGORIZED = 0x00;
        const octet COMPUTER_DESKTOP = 0x01;
        const octet COMPUTER_SERVER = 0x02;
        const octet COMPUTER_LAPTOP = 0x03;
        const octet COMPUTER_HANDHELD_PC_OR_PDA = 0x04;
        const octet COMPUTER_PALM_PC_OR_PDA = 0x05;
        const octet COMPUTER_WEARABLE = 0x06;

        const octet PHONE_UNCATEGORIZED = 0x00;
        const octet PHONE_CELLULAR = 0x01;
        const octet PHONE_CORDLESS = 0x02;
        const octet PHONE_SMARTPHONE = 0x03;
        const octet PHONE_MODEM_OR_GATEWAY = 0x04;
        const octet PHONE_ISDN = 0x05;

        const octet AV_UNRECOGNIZED = 0x00;
        const octet AV_WEARABLE_HEADSET = 0x01;
        const octet AV_HANDSFREE = 0x02;
        const octet AV_MICROPHONE = 0x04;
        const octet AV_LOUDSPEAKER = 0x05;
        const octet AV_HEADPHONES = 0x06;
        const octet AV_PORTABLE_AUDIO = 0x07;
        const octet AV_CAR_AUDIO = 0x08;
        const octet AV_SETTOP_BOX = 0x09;
        const octet AV_HIFI = 0x0a;
        const octet AV_VCR = 0x0b;
        const octet AV_VIDEO_CAMERA = 0x0c;
        const octet AV_CAMCORDER = 0x0d;
        const octet AV_MONITOR = 0x0e;
        const octet AV_DISPLAY_AND_LOUDSPEAKER = 0x0f;
        const octet AV_VIDEO_CONFERENCING = 0x10;
        const octet AV_GAMING_TOY = 0x12;

        const octet PERIPHERAL_UNCATEGORIZED = 0;
        const octet PERIPHERAL_KEYBOARD = 0x10;
        const octet PERIPHERAL_POINTING_DEVICE = 0x20;
        const octet PERIPHERAL_KEYBOARD_AND_POINTING_DEVICE = 0x30;
        const octet PERIPHERAL_JOYSTICK = 0x01;
        const octet PERIPHERAL_GAMEPAD = 0x02;
        const octet PERIPHERAL_REMOTE_CONTROL = 0x03;
        const octet PERIPHERAL_SENSING_DEVICE = 0x04;
        const octet PERIPHERAL_DEGITIZER_TABLET = 0x05;
        const octet PERIPHERAL_CARD_READER = 0x06;
        const octet PERIPHERAL_DIGITAL_PEN = 0x07;
        const octet PERIPHERAL_HANDHELD_SCANNER = 0x08;
        const octet PERIPHERAL_HANDHELD_INPUT_DEVICE = 0x09;

        const octet IMAGING_UNCATEGORIZED = 0x00;
        const octet IMAGING_DISPLAY = 0x04;
        const octet IMAGING_CAMERA = 0x08;
        const octet IMAGING_SCANNER = 0x10;
        const octet IMAGING_PRINTER = 0x20;

        const octet WEARABLE_WRITST_WATCH = 0x01;
        const octet WEARABLE_PAGER = 0x02;
        const octet WEARABLE_JACKET = 0x03;
        const octet WEARABLE_HELMET = 0x04;
        const octet WEARABLE_GLASSES = 0x05;

        const octet TOY_ROBOT = 0x01;
        const octet TOY_VEHICLE = 0x02;
        const octet TOY_DOLL = 0x03;
        const octet TOY_CONTROLLER = 0x04;
        const octet TOY_GAME = 0x05;

        const octet HEALTH_UNDEFINED = 0x00;
        const octet HEALTH_BLOOD_PRESSURE_MONITOR = 0x01;
        const octet HEALTH_THERMOMETER = 0x02;
        const octet HEALTH_WEIGHING_SCALE = 0x03;
        const octet HEALTH_GLUCOSE_METER = 0x04;
        const octet HEALTH_PULSE_OXIMETER = 0x05;
        const octet HEALTH_PULSE_RATE_MONITOR = 0x06;
        const octet HEALTH_DATA_DISPLAY = 0x07;
        const octet HEALTH_STEP_COUNTER = 0x08;
        const octet HEALTH_BODY_COMPOSITION_ANALYZER = 0x09;
        const octet HEALTH_PEAK_FLOW_MONITOR = 0x0a;
        const octet HEALTH_MEDICATION_MONITOR = 0x0b;
        const octet HEALTH_KNEE_PROSTHESIS = 0x0c;
        const octet HEALTH_ANKLE_PROSTHESIS = 0x0d;
    };

2.9. BluetoothClassDeviceService

This interface holds identifiers for the major service classes of Bluetooth CoD.

    [NoInterfaceObject] interface BluetoothClassDeviceService {
        const unsigned short LIMITED_DISCOVERABILITY = 0x0001;
        const unsigned short POSITIONING = 0x0008; 
        const unsigned short NETWORKING = 0x0010; 
        const unsigned short RENDERING = 0x0020; 
        const unsigned short CAPTURING = 0x0040;
        const unsigned short OBJECT_TRANSFER = 0x0080; 
        const unsigned short AUDIO = 0x0100;
        const unsigned short TELEPHONY = 0x0200;
        const unsigned short INFORMATION = 0x0400;
    };

2.10. BluetoothServiceHandler

This interface provides methods to handle Bluetooth service.

    [NoInterfaceObject] interface BluetoothServiceHandler {
        readonly attribute BluetoothUUID uuid;
        readonly attribute DOMString name;
        readonly attribute boolean isConnected;
        [TreatNonCallableAsNull] attribute BluetoothSocketSuccessCallback? onconnect;

        void unregister(optional SuccessCallback? successCallback, optional ErrorCallback? errorCallback) raises(WebAPIException);
    };

ATTRIBUTES

readonly BluetoothUUID uuid

The UUID of the service.

This attribute is read-only.

readonly DOMString name

The name of the service.

This attribute is read-only.

readonly boolean isConnected

An attribute to check whether any remote devices is using this service or not.

This attribute is read-only.

BluetoothSocketSuccessCallback? onconnect

The success callback to be invoked when a remote device is connected to this service. By default, this attribute is set to null.

METHODS

unregister

Unregisters a service record from the Bluetooth services record database and stops listening for new connections to this service.

Signature
void unregister(optional SuccessCallback? successCallback, optional ErrorCallback? errorCallback);

The ErrorCallback is launched with these error types:

  • UnknownError - If any other error occurs.
Parameters
  • successCallback
    • Optional: Yes.
    • Nullable: Yes.
    • Type: SuccessCallback.
    • Description: The method to be invoked when the record is removed successfully from the service records database.
  • errorCallback
    • Optional: Yes.
    • Nullable: Yes.
    • Type: ErrorCallback.
    • Description: The method to be invoked in case of failure (to unregister).
Exceptions
  • WebAPIException:

    with error type NotSupportedError, if this feature is not supported.

    with error type SecurityError, if the application does not have the privilege to call this method.

    with error type TypeMismatchError, if the input parameter is not compatible with the expected type for that parameter.

Code example
 var adapter = webapis.bluetooth.getDefaultAdapter();
 var chatServiceHandler = null;

 function chatServiceSuccessCb(handler) {
    console.log("Chat service registration was successful!");

    chatServiceHandler = handler;
    handler.onconnect = function(socket) {
       console.log("Client is connected: " + socket.peer.name + "," + socket.peer.address);
       socket.onmessage = function() {
           var data = socket.readData();
           // Handle message code goes here
           //....
       };

       // Expected close
       socket.onclose = function() {
           console.log('The socket is closed.');
       };
    };
 }

 function publishChatService()
 {
    var CHAT_SERVICE_UUID = "5BCE9431-6C75-32AB-AFE0-2EC108A30860";
    adapter.registerRFCOMMServiceByUUID(CHAT_SERVICE_UUID, "Chat service", chatServiceSuccessCb,
      // Error handler
      function(e) {
           console.log( "Could not register service record, Error: " + e.message);
      });
 }

 function unRegisterChatService()
 {
      if (chatServiceHandler != null) {
           chatServiceHandler.unregister(function() {
               chatServiceHandler = null;
               console.log("Chat service is unregistered.");
           },
           function(e) {
               console.log ("Error: " + e.message);
           });
      }
 }
 

2.11. BluetoothProfileHandler

This interface represents the Bluetooth profile handler.

    [NoInterfaceObject] interface BluetoothProfileHandler {
        
        readonly attribute BluetoothProfileType profileType;
                
    };

ATTRIBUTES

readonly BluetoothProfileType profileType

The type of Bluetooth profile.

This attribute is read-only.

2.12. BluetoothHealthProfileHandler

This interface represents the handler of Bluetooth health device profile. The BluetoothHealthProfileHandler object is created by BluetoothAdapter.getBluetoothProfileHandler().

    [NoInterfaceObject] interface BluetoothHealthProfileHandler : BluetoothProfileHandler {
        
        void registerSinkApplication(unsigned short dataType, DOMString name, BluetoothHealthApplicationSuccessCallback successCallback, optional ErrorCallback? errorCallback) raises(WebAPIException);

        void connectToSource(BluetoothDevice peer, BluetoothHealthApplication application, BluetoothHealthChannelSuccessCallback successCallback, optional ErrorCallback? errorCallback) raises(WebAPIException);

        };

METHODS

registerSinkApplication

Registers an application for the Sink role.

Signature
void registerSinkApplication(unsigned short dataType, DOMString name, BluetoothHealthApplicationSuccessCallback successCallback, optional ErrorCallback? errorCallback);

The ErrorCallback is launched with these error types:

  • ServiceNotAvailableError - If a Bluetooth device is turned off.
  • UnknownError - If any other error occurs.
Parameters
  • dataType
    • Optional: No.
    • Nullable: No.
    • Type: unsigned short.
    • Description: The MDEP data type used for communication, which is referenced in the ISO/IEEE 11073-20601 spec. For example, pulse oximeter is 4100 and blood pressure monitor is 4103.
  • name
    • Optional: No.
    • Nullable: No.
    • Type: DOMString.
    • Description: The friendly name associated with sink application.
  • successCallback
    • Optional: No.
    • Nullable: No.
    • Type: BluetoothHealthApplicationSuccessCallback.
    • Description: The method to invoke when a sink application is registered successfully.
  • errorCallback
    • Optional: Yes.
    • Nullable: Yes.
    • Type: ErrorCallback.
    • Description: The method to invoke when an error occurs.
Exceptions
  • WebAPIException:

    with error type NotSupportedError, if this feature is not supported.

    with error type TypeMismatchError, if any of the input parameter is not compatible with the expected type for that parameter.

    with error type SecurityError, if the application does not have the privilege to call this method.

Code example
 var adapter = webapis.bluetooth.getDefaultAdapter();
 var healthProfileHandler = adapter.getBluetoothProfileHandler("HEALTH");

 function healthRegisterSuccess(app) {
     console.log("Registered application: " + app.name);
 }

 function healthRegisterError(e) {
     console.log("Failed to register application: " + e.message);
 };

 healthProfileHandler.registerSinkApplication(4100, "testSinkApp", healthRegisterSuccess, healthRegisterError);
 

connectToSource

Connect to the health device which acts as the Source role.

Signature
void connectToSource(BluetoothDevice peer, BluetoothHealthApplication application, BluetoothHealthChannelSuccessCallback successCallback, optional ErrorCallback? errorCallback);

The ErrorCallback is launched with these error types:

  • ServiceNotAvailableError - If a Bluetooth device is turned off.
  • InvalidValuesError - If any of the input parameters contain an invalid value.
  • UnknownError - If any other error occurs.
Parameters
  • peer
    • Optional: No.
    • Nullable: No.
    • Type: BluetoothDevice.
    • Description: The remote device which acts as the Source role.
  • application
    • Optional: No.
    • Nullable: No.
    • Type: BluetoothHealthApplication.
    • Description: The registered application for the Sink role.
  • successCallback
    • Optional: No.
    • Nullable: No.
    • Type: BluetoothHealthChannelSuccessCallback.
    • Description: The method to invoke when a connection is established successfully.
  • errorCallback
    • Optional: Yes.
    • Nullable: Yes.
    • Type: ErrorCallback.
    • Description: The method to invoke when an error occurs.
Exceptions
  • WebAPIException:

    with error type NotSupportedError, if this feature is not supported.

    with error type TypeMismatchError, if any of the input parameter is not compatible with the expected type for that parameter.

    with error type SecurityError, if the application does not have the privilege to call this method.

Code example
 var adapter = webapis.bluetooth.getDefaultAdapter();
 var healthProfileHandler = adapter.getBluetoothProfileHandler("HEALTH");
 var registerHealthApp = null;

 function healthConnectSuccess(channel) {
     console.log("Health device is connected");
 }
 
 function healthConnectError(e) {
     console.log("Failed to connect to source: " + e.message);
 };
 
 function gotDeviceInfo(device) {
     healthProfileHandler.connectToSource(device, registerHealthApp, healthConnectSuccess, healthConnectError);
 }
 
 function healthRegisterSuccess(app) {
     console.log("Registered application: " + app.name);
     registerHealthApp = app;
     var peer = adapter.getDevice("35:F4:59:D1:7A:03", gotDeviceInfo);
 }

 function healthRegisterError(e) {
     console.log("Failed to register application: " + e.message);
 };

 healthProfileHandler.registerSinkApplication(4100, "testSinkApp", healthRegisterSuccess, healthRegisterError);
 

2.13. BluetoothHealthApplication

This interface represents the Bluetooth health application.

    [NoInterfaceObject] interface BluetoothHealthApplication {

        readonly attribute unsigned short dataType;
                
        readonly attribute DOMString name;

        [TreatNonCallableAsNull] attribute BluetoothHealthChannelSuccessCallback? onconnect;
                
        void unregister(optional SuccessCallback? successCallback, optional ErrorCallback? errorCallback)raises(WebAPIException);
    };

ATTRIBUTES

readonly unsigned short dataType

The MDEP data type used for communication, which is referenced in the ISO/IEEE 11073-20601 spec. For example, pulse oximeter is 4100 and blood pressure monitor is 4103.

This attribute is read-only.

readonly DOMString name

The friendly name associated with sink application.

This attribute is read-only.

BluetoothHealthChannelSuccessCallback? onconnect

The callback invoked when a health device is connected through this application. By default, this attribute is set to null.

METHODS

unregister

Unregisters this application.

Signature
void unregister(optional SuccessCallback? successCallback, optional ErrorCallback? errorCallback);

The ErrorCallback is launched with these error types:

  • ServiceNotAvailableError - If a Bluetooth device is turned off.
  • UnknownError - If any other error occurs.
Parameters
  • successCallback
    • Optional: Yes.
    • Nullable: Yes.
    • Type: SuccessCallback.
    • Description: The method to invoke when a sink application is registered successfully.
  • errorCallback
    • Optional: Yes.
    • Nullable: Yes.
    • Type: ErrorCallback.
    • Description: The method to invoke when an error occurs.
Exceptions
  • WebAPIException:

    with error type NotSupportedError, if this feature is not supported.

    with error type TypeMismatchError, if any of the input parameter is not compatible with the expected type for that parameter.

    with error type SecurityError, if the application does not have the privilege to call this method.

Code example
 var adapter = webapis.bluetooth.getDefaultAdapter();
 var healthProfileHandler = adapter.getBluetoothProfileHandler("HEALTH");
 var healthApp = null;

 function healthRegisterSuccess(app) {
     console.log("Registered application: " + app.name);
     healthApp = app;
     healthApp.onconnect = function(channel) {
         console.log("Connected!!");
     };
 }

 function healthRegisterError(e) {
     console.log("Failed to register application: " + e.message);
 };

 function startSink() {
     try {
         healthProfileHandler.registerSinkApplication(4100, "testSinkApp", healthRegisterSuccess, healthRegisterError);
     } catch(e) {
         console.log("Error: " + e.message);
     }
 }

 function stopSink() {
     try {
         if(healthApp != null) {
             healthApp.unregister(function() {
                 healthApp = null;
                 console.log("Health application is unregistered.");
             },
             function(e) {
                 console.log ("Error: " + e.message);
             });
         }
     } catch(err) {
         console.log("Error: " + err.message);
     }
 }
 

2.14. BluetoothHealthChannel

This interface represents the Bluetooth health channel.

    [NoInterfaceObject] interface BluetoothHealthChannel {

        readonly attribute BluetoothDevice peer;
                
        readonly attribute BluetoothHealthChannelType channelType;

        readonly attribute BluetoothHealthApplication application;
                
        readonly attribute boolean isConnected;

        void close() raises(WebAPIException);

        unsigned long sendData(byte[] data) raises(WebAPIException);

        void setListener(BluetoothHealthChannelChangeCallback listener) raises(WebAPIException); 
 
        void unsetListener() raises(WebAPIException);
                
    };

ATTRIBUTES

readonly BluetoothDevice peer

The remote device to which this channel is connected.

This attribute is read-only.

readonly BluetoothHealthChannelType channelType

The type of of this channel.

This attribute is read-only.

readonly BluetoothHealthApplication application

The health application which is used to communicate with the remote device.

This attribute is read-only.

readonly boolean isConnected

An attrbitue to check whether any remote device is connected or not.

This attribute is read-only.

METHODS

close

Close the connected channel. BluetoothHealthChannel.isConnected is changed to false and BluetoothHealthChannelChangeCallback.onclose is invoked when this channel is closed successfully.

Signature
void close();
Exceptions
  • WebAPIException:

    with error type NotSupportedError, if this feature is not supported.

    with error type UnknownError, if any other error occurs.

    with error type ServiceNotAvailableError - If a Bluetooth device is turned off.

    with error type SecurityError, if the application does not have the privilege to call this method.

Code example
 var adapter = webapis.bluetooth.getDefaultAdapter();
 var healthProfileHandler = adapter.getBluetoothProfileHandler("HEALTH");
 
 function healthRegisterSuccess(app) {
     console.log("Registered application: " + app.name);
     app.onconnect = function(channel) {;
         console.log("Health device is connected");
         channel.close();
     }
 }

 function healthRegisterError(e) {
     console.log("Failed to register application: " + e.message);
 };

 healthProfileHandler.registerSinkApplication(4100, "testSinkApp", healthRegisterSuccess, healthRegisterError);
 

sendData

Send data and returns the number of bytes actually written.

Signature
unsigned long sendData(byte[] data);
Parameters
  • data
    • Optional: No.
    • Nullable: No.
    • Type: array.
    • Description: The data to send.
Return value
unsigned long The number of bytes actually sent.
Exceptions
  • WebAPIException:

    with error type NotSupportedError, if this feature is not supported.

    with error type UnknownError, if any other error occurs.

    with error type TypeMismatchError, if any of the input parameter is not compatible with the expected type for that parameter.

    with error type ServiceNotAvailableError - If a Bluetooth device is turned off.

    with error type SecurityError, if the application does not have the privilege to call this method.

Code example
 var adapter = webapis.bluetooth.getDefaultAdapter();
 var healthProfileHandler = adapter.getBluetoothProfileHandler("HEALTH");

 function healthRegisterSuccess(app) {
     console.log("Registered application: " + app.name);
     app.onconnect = function(channel) {
         console.log("Health device is connected");
         channel.sendData(dataToSend);
     }
 }

 function healthRegisterError(e) {
     console.log("Failed to register application: " + e.message);
 };

 healthProfileHandler.registerSinkApplication(4100, "testSinkApp", healthRegisterSuccess, healthRegisterError);
 

setListener

Sets the listener to receive notifications.

Signature
void setListener(BluetoothHealthChannelChangeCallback listener);
Parameters
  • listener
    • Optional: No.
    • Nullable: No.
    • Type: BluetoothHealthChannelChangeCallback.
    • Description: The event listener of Bluetooth health channel.
Exceptions
  • WebAPIException:

    with error type UnknownError, if any other error occurs.

    with error type SecurityError, if the application does not have the privilege to call this method.

    with error type TypeMismatchError, if the input parameter is not compatible with the expected type.

Code example
 var adapter = webapis.bluetooth.getDefaultAdapter();
 var healthProfileHandler = adapter.getBluetoothProfileHandler("HEALTH");

 var channelCallback = {
     onmessage: function(data) {
         console.log("data is received")
     },
     onclose: function() {
         console.log("channel is closed");
     }
 };

 function healthRegisterSuccess(app) {
     console.log("Registered application: " + app.name);
     app.onconnect = function(channel) {;
         console.log("Health device is connected");
         channel.setListener(channelCallback);
     }
 }

 function healthRegisterError(e) {
     console.log("Failed to register application: " + e.message);
 };

 healthProfileHandler.registerSinkApplication(4100, "testSinkApp", healthRegisterSuccess, healthRegisterError);
 

unsetListener

Unsets the listener, so stop receiving notifications.

Signature
void unsetListener();
Exceptions
  • WebAPIException:

    with error type UnknownError, if any other error occurs.

    with error type SecurityError, if the application does not have the privilege to call this method.

Code example
 var adapter = webapis.bluetooth.getDefaultAdapter();
 var healthProfileHandler = adapter.getBluetoothProfileHandler("HEALTH");
 var connectedChannel = null;

 var channelCallback = {
     onmessage: function(data) {
         console.log("data is received")
     },
     onclose: function() {
         console.log("channel is closed");
         connectedChannel.unsetListener();
     }
 };

 function healthRegisterSuccess(app) {
     console.log("Registered application: " + app.name);
     app.onconnect = function(channel) {;
         console.log("Health device is connected");
         connectedChannel = channel;
         connectedChannel.setListener(channelCallback);
     }
 }

 function healthRegisterError(e) {
     console.log("Failed to register application: " + e.message);
 };

 healthProfileHandler.registerSinkApplication(4100, "testSinkApp", healthRegisterSuccess, healthRegisterError);
 

2.15. BluetoothAdapterChangeCallback

This interface specifies a set of methods to be invoked when the changes of Bluetooth adapter occur.

    [Callback, NoInterfaceObject] interface BluetoothAdapterChangeCallback {
        void onstatechanged(boolean powered);
        void onnamechanged(DOMString name);
        void onvisibilitychanged(boolean visible);
    };

METHODS

onstatechanged

The method to be invoked when the power state is changed.

Signature
void onstatechanged(boolean powered);
Parameters
  • powered
    • Optional: No.
    • Nullable: No.
    • Type: boolean.
    • Description: The power state of local Bluetooth: true means power-on, false means power-off.

onnamechanged

The method to be invoked when the name is changed.

Signature
void onnamechanged(DOMString name);
Parameters
  • name
    • Optional: No.
    • Nullable: No.
    • Type: DOMString.
    • Description: The name of local Bluetooth.

onvisibilitychanged

The method to be invoked when the visibility is changed.

Signature
void onvisibilitychanged(boolean visible);
Parameters
  • visible
    • Optional: No.
    • Nullable: No.
    • Type: boolean.
    • Description: The visibility of local Bluetooth: true means that local Bluetooth is discoverable, false means that local Bluetooth is hidden from other devices.

2.16. BluetoothDeviceSuccessCallback

This interface implements the success callback BluetoothAdapter.getDevice() and BluetoothAdapter.createBonding().

    [Callback=FunctionOnly, NoInterfaceObject] interface BluetoothDeviceSuccessCallback {
        void onsuccess(BluetoothDevice device);
    };

METHODS

onsuccess

The method to be invoked on success.

Signature
void onsuccess(BluetoothDevice device);
Parameters
  • device
    • Optional: No.
    • Nullable: No.
    • Type: BluetoothDevice.
    • Description: The BluetoothDevice object.

2.17. BluetoothDeviceArraySuccessCallback

The success callback for BluetoothAdapter.getKnownDevices().

    [Callback=FunctionOnly, NoInterfaceObject] interface BluetoothDeviceArraySuccessCallback {
        void onsuccess(BluetoothDevice[] devices);
    };

METHODS

onsuccess

The method to be invoked when device information is ready.

Signature
void onsuccess(BluetoothDevice[] devices);
Parameters
  • devices
    • Optional: No.
    • Nullable: No.
    • Type: array.
    • Description: List of devices known to local Bluetooth adapter. Each element is a BluetoothDevice.

2.18. BluetoothDiscoverDevicesSuccessCallback

The success callback for BluetoothAdapter.discoverDevices().

    [Callback, NoInterfaceObject] interface BluetoothDiscoverDevicesSuccessCallback {
        void onstarted();
        void ondevicefound(BluetoothDevice device);
        void ondevicedisappeared(BluetoothAddress address);
        void onfinished(BluetoothDevice[] foundDevices);
    };

METHODS

onstarted

The method to be invoked at the beginning of a device discovery process for finding the nearby Bluetooth device.

Signature
void onstarted();

ondevicefound

The method to be invoked when a new device is discovered in the process of inquiry/discovery.

Signature
void ondevicefound(BluetoothDevice device);
Parameters
  • device
    • Optional: No.
    • Nullable: No.
    • Type: BluetoothDevice.
    • Description: The found device.

ondevicedisappeared

The method to be invoked when a device is lost from proximity. After that, this device is no longer visible.

Signature
void ondevicedisappeared(BluetoothAddress address);
Parameters
  • address
    • Optional: No.
    • Nullable: No.
    • Type: BluetoothAddress.
    • Description: The address of the device that is no longer in range or visible.

onfinished

The method to be invoked when the device discovery process has finished.

Signature
void onfinished(BluetoothDevice[] foundDevices);
Parameters
  • foundDevices
    • Optional: No.
    • Nullable: No.
    • Type: array.
    • Description: The array of devices found in this discovery session.

2.19. BluetoothSocketSuccessCallback

The success method for BluetoothDevice.connectToServiceByUUID().

    [Callback=FunctionOnly, NoInterfaceObject] interface BluetoothSocketSuccessCallback {
        void onsuccess(BluetoothSocket socket);
    };

METHODS

onsuccess

The method to be invoked when the connection to a service is ready.

Signature
void onsuccess(BluetoothSocket socket);
Parameters
  • socket
    • Optional: No.
    • Nullable: No.
    • Type: BluetoothSocket.
    • Description: The socket to connect to the specified service on a remote device.

2.20. BluetoothServiceSuccessCallback

This interface implements the success callback for BluetoothAdapter.registerRFCOMMServiceByUUID().

    [Callback=FunctionOnly, NoInterfaceObject] interface BluetoothServiceSuccessCallback {
        void onsuccess(BluetoothServiceHandler handler);
    };

METHODS

onsuccess

The method to be invoked when registering a service with the local device is successful.

Signature
void onsuccess(BluetoothServiceHandler handler);
Parameters
  • handler
    • Optional: No.
    • Nullable: No.
    • Type: BluetoothServiceHandler.
    • Description: Bluetooth service handler.

2.21. BluetoothHealthApplicationSuccessCallback

The success method for BluetoothHealthProfileHandler.registerSinkApplication().

    [Callback=FunctionOnly, NoInterfaceObject] interface BluetoothHealthApplicationSuccessCallback {
        void onsuccess(BluetoothHealthApplication application);
    };

METHODS

onsuccess

The method to be invoked when the application is registered successfully.

Signature
void onsuccess(BluetoothHealthApplication application);
Parameters
  • application
    • Optional: No.
    • Nullable: No.
    • Type: BluetoothHealthApplication.
    • Description: The registered health application.

2.22. BluetoothHealthChannelSuccessCallback

The success method for BluetoothHealthProfileHandler.connectToSource() and the event callback for BluetoothHealthApplication.onconnect.

    [Callback=FunctionOnly, NoInterfaceObject] interface BluetoothHealthChannelSuccessCallback {
        void onsuccess(BluetoothHealthChannel channel);
    };

METHODS

onsuccess

The method to be invoked when a connection is established.

Signature
void onsuccess(BluetoothHealthChannel channel);
Parameters
  • channel
    • Optional: No.
    • Nullable: No.
    • Type: BluetoothHealthChannel.
    • Description: The connected health channel.

2.23. BluetoothHealthChannelChangeCallback

This interface specifies a set of methods to be invoked when the changes of heath channel occur.

    [Callback, NoInterfaceObject] interface BluetoothHealthChannelChangeCallback {
        void onmessage(byte[] data);
                
        void onclose(); 
    };

METHODS

onmessage

The method to be invoked when the message is received.

Signature
void onmessage(byte[] data);
Parameters
  • data
    • Optional: No.
    • Nullable: No.
    • Type: array.
    • Description: The received data.

onclose

The method to be invoked when the health channel is closed.

Signature
void onclose();

3. Full WebIDL

module Bluetooth {
    typedef DOMString BluetoothAddress;
    
    typedef DOMString BluetoothUUID;
    
    enum BluetoothSocketState { "CLOSED", "OPEN" };

    enum BluetoothProfileType { "HEALTH" };
        
    enum BluetoothHealthChannelType { "RELIABLE", "STREAMING" };
    
    [NoInterfaceObject] interface BluetoothManagerObject {
        readonly attribute BluetoothManager bluetooth;
    };
    WebAPIs implements BluetoothManagerObject;

    [NoInterfaceObject] interface BluetoothManager {
        readonly attribute BluetoothClassDeviceMajor deviceMajor;
        readonly attribute BluetoothClassDeviceMinor deviceMinor;
        readonly attribute BluetoothClassDeviceService deviceService;
        BluetoothAdapter getDefaultAdapter() raises(WebAPIException);
    };


    [NoInterfaceObject] interface BluetoothAdapter {
        readonly attribute DOMString name;
        readonly attribute BluetoothAddress address;
        readonly attribute boolean powered; 
        readonly attribute boolean visible;

        void setName(DOMString name,
                     optional SuccessCallback? successCallback, 
                     optional ErrorCallback? errorCallback) raises(WebAPIException);
 
        void setPowered(boolean state,
                        optional SuccessCallback? successCallback, 
                        optional ErrorCallback? errorCallback) raises(WebAPIException);     
        
        void setVisible(boolean mode,
                        optional SuccessCallback? successCallback, 
                        optional ErrorCallback? errorCallback,
                        optional unsigned short? timeout) raises(WebAPIException);

        void setChangeListener(BluetoothAdapterChangeCallback listener) raises(WebAPIException);

        void unsetChangeListener() raises(WebAPIException);

        void discoverDevices(BluetoothDiscoverDevicesSuccessCallback successCallback, 
                             optional ErrorCallback? errorCallback) raises(WebAPIException);

        void stopDiscovery(optional SuccessCallback? successCallback, 
                           optional ErrorCallback? errorCallback) raises(WebAPIException);

        void getKnownDevices(BluetoothDeviceArraySuccessCallback successCallback, 
                             optional ErrorCallback? errorCallback) raises(WebAPIException);




        void getDevice(BluetoothAddress address,
                       BluetoothDeviceSuccessCallback successCallback, 
                       optional ErrorCallback? errorCallback) raises(WebAPIException);




        void createBonding(BluetoothAddress address,
                           BluetoothDeviceSuccessCallback successCallback, 
                           optional ErrorCallback? errorCallback) raises(WebAPIException);

        void destroyBonding(BluetoothAddress address,
                            optional SuccessCallback? successCallback, 
                            optional ErrorCallback? errorCallback) raises(WebAPIException);



        void registerRFCOMMServiceByUUID(BluetoothUUID uuid,
                                         DOMString name,
                                         BluetoothServiceSuccessCallback successCallback, 
                                         optional ErrorCallback? errorCallback) raises(WebAPIException);

        BluetoothProfileHandler getBluetoothProfileHandler(BluetoothProfileType profileType) raises(WebAPIException);

             };
    [NoInterfaceObject] interface BluetoothDevice {
        readonly attribute DOMString name;
        readonly attribute BluetoothAddress address;
        readonly attribute BluetoothClass deviceClass;
        readonly attribute boolean isBonded;
        readonly attribute boolean isTrusted;
        readonly attribute boolean isConnected;
        readonly attribute BluetoothUUID[] uuids;

        void connectToServiceByUUID(BluetoothUUID uuid,
                                    BluetoothSocketSuccessCallback successCallback, 
                                    optional ErrorCallback? errorCallback) raises(WebAPIException);
    };
    [NoInterfaceObject] interface BluetoothSocket {
        readonly attribute BluetoothUUID uuid;
        readonly attribute BluetoothSocketState state;
        readonly attribute BluetoothDevice peer;
        [TreatNonCallableAsNull] attribute SuccessCallback? onmessage;
        [TreatNonCallableAsNull] attribute SuccessCallback? onclose;
        unsigned long writeData(byte[] data) raises(WebAPIException);


        byte[] readData() raises(WebAPIException);


        void close() raises(WebAPIException);
    };

    [NoInterfaceObject] interface BluetoothClass {
        readonly attribute octet major;
        
        readonly attribute octet minor;
        
        readonly attribute unsigned short [] services ;
        
        boolean hasService(unsigned short service) raises(WebAPIException);
    };

    [NoInterfaceObject] interface BluetoothClassDeviceMajor {

        const octet MISC = 0x00;
        const octet COMPUTER = 0x01;
        const octet PHONE = 0x02;
        const octet NETWORK = 0x03;
        const octet AUDIO_VIDEO = 0x04;
        const octet PERIPHERAL = 0x05;
        const octet IMAGING = 0x06;
        const octet WEARABLE = 0x07;
        const octet TOY = 0x08;
        const octet HEALTH = 0x09;
        const octet UNCATEGORIZED = 0x1F;
    };

    [NoInterfaceObject] interface BluetoothClassDeviceMinor {
        const octet COMPUTER_UNCATEGORIZED = 0x00;
        const octet COMPUTER_DESKTOP = 0x01;
        const octet COMPUTER_SERVER = 0x02;
        const octet COMPUTER_LAPTOP = 0x03;
        const octet COMPUTER_HANDHELD_PC_OR_PDA = 0x04;
        const octet COMPUTER_PALM_PC_OR_PDA = 0x05;
        const octet COMPUTER_WEARABLE = 0x06;

        const octet PHONE_UNCATEGORIZED = 0x00;
        const octet PHONE_CELLULAR = 0x01;
        const octet PHONE_CORDLESS = 0x02;
        const octet PHONE_SMARTPHONE = 0x03;
        const octet PHONE_MODEM_OR_GATEWAY = 0x04;
        const octet PHONE_ISDN = 0x05;

        const octet AV_UNRECOGNIZED = 0x00;
        const octet AV_WEARABLE_HEADSET = 0x01;
        const octet AV_HANDSFREE = 0x02;
        const octet AV_MICROPHONE = 0x04;
        const octet AV_LOUDSPEAKER = 0x05;
        const octet AV_HEADPHONES = 0x06;
        const octet AV_PORTABLE_AUDIO = 0x07;
        const octet AV_CAR_AUDIO = 0x08;
        const octet AV_SETTOP_BOX = 0x09;
        const octet AV_HIFI = 0x0a;
        const octet AV_VCR = 0x0b;
        const octet AV_VIDEO_CAMERA = 0x0c;
        const octet AV_CAMCORDER = 0x0d;
        const octet AV_MONITOR = 0x0e;
        const octet AV_DISPLAY_AND_LOUDSPEAKER = 0x0f;
        const octet AV_VIDEO_CONFERENCING = 0x10;
        const octet AV_GAMING_TOY = 0x12;

        const octet PERIPHERAL_UNCATEGORIZED = 0;
        const octet PERIPHERAL_KEYBOARD = 0x10;
        const octet PERIPHERAL_POINTING_DEVICE = 0x20;
        const octet PERIPHERAL_KEYBOARD_AND_POINTING_DEVICE = 0x30;
        const octet PERIPHERAL_JOYSTICK = 0x01;
        const octet PERIPHERAL_GAMEPAD = 0x02;
        const octet PERIPHERAL_REMOTE_CONTROL = 0x03;
        const octet PERIPHERAL_SENSING_DEVICE = 0x04;
        const octet PERIPHERAL_DEGITIZER_TABLET = 0x05;
        const octet PERIPHERAL_CARD_READER = 0x06;
        const octet PERIPHERAL_DIGITAL_PEN = 0x07;
        const octet PERIPHERAL_HANDHELD_SCANNER = 0x08;
        const octet PERIPHERAL_HANDHELD_INPUT_DEVICE = 0x09;

        const octet IMAGING_UNCATEGORIZED = 0x00;
        const octet IMAGING_DISPLAY = 0x04;
        const octet IMAGING_CAMERA = 0x08;
        const octet IMAGING_SCANNER = 0x10;
        const octet IMAGING_PRINTER = 0x20;

        const octet WEARABLE_WRITST_WATCH = 0x01;
        const octet WEARABLE_PAGER = 0x02;
        const octet WEARABLE_JACKET = 0x03;
        const octet WEARABLE_HELMET = 0x04;
        const octet WEARABLE_GLASSES = 0x05;

        const octet TOY_ROBOT = 0x01;
        const octet TOY_VEHICLE = 0x02;
        const octet TOY_DOLL = 0x03;
        const octet TOY_CONTROLLER = 0x04;
        const octet TOY_GAME = 0x05;

        const octet HEALTH_UNDEFINED = 0x00;
        const octet HEALTH_BLOOD_PRESSURE_MONITOR = 0x01;
        const octet HEALTH_THERMOMETER = 0x02;
        const octet HEALTH_WEIGHING_SCALE = 0x03;
        const octet HEALTH_GLUCOSE_METER = 0x04;
        const octet HEALTH_PULSE_OXIMETER = 0x05;
        const octet HEALTH_PULSE_RATE_MONITOR = 0x06;
        const octet HEALTH_DATA_DISPLAY = 0x07;
        const octet HEALTH_STEP_COUNTER = 0x08;
        const octet HEALTH_BODY_COMPOSITION_ANALYZER = 0x09;
        const octet HEALTH_PEAK_FLOW_MONITOR = 0x0a;
        const octet HEALTH_MEDICATION_MONITOR = 0x0b;
        const octet HEALTH_KNEE_PROSTHESIS = 0x0c;
        const octet HEALTH_ANKLE_PROSTHESIS = 0x0d;
    };

    [NoInterfaceObject] interface BluetoothClassDeviceService {
        const unsigned short LIMITED_DISCOVERABILITY = 0x0001;
        const unsigned short POSITIONING = 0x0008; 
        const unsigned short NETWORKING = 0x0010; 
        const unsigned short RENDERING = 0x0020; 
        const unsigned short CAPTURING = 0x0040;
        const unsigned short OBJECT_TRANSFER = 0x0080; 
        const unsigned short AUDIO = 0x0100;
        const unsigned short TELEPHONY = 0x0200;
        const unsigned short INFORMATION = 0x0400;
    };

    [NoInterfaceObject] interface BluetoothServiceHandler {
        readonly attribute BluetoothUUID uuid;
        readonly attribute DOMString name;
        readonly attribute boolean isConnected;
        [TreatNonCallableAsNull] attribute BluetoothSocketSuccessCallback? onconnect;

        void unregister(optional SuccessCallback? successCallback, optional ErrorCallback? errorCallback) raises(WebAPIException);
    };

    [NoInterfaceObject] interface BluetoothProfileHandler {
        
        readonly attribute BluetoothProfileType profileType;
                
    };
                

    [NoInterfaceObject] interface BluetoothHealthProfileHandler : BluetoothProfileHandler {
        
        void registerSinkApplication(unsigned short dataType, DOMString name, BluetoothHealthApplicationSuccessCallback successCallback, optional ErrorCallback? errorCallback) raises(WebAPIException);

        void connectToSource(BluetoothDevice peer, BluetoothHealthApplication application, BluetoothHealthChannelSuccessCallback successCallback, optional ErrorCallback? errorCallback) raises(WebAPIException);

        };              


    [NoInterfaceObject] interface BluetoothHealthApplication {

        readonly attribute unsigned short dataType;
                
        readonly attribute DOMString name;

        [TreatNonCallableAsNull] attribute BluetoothHealthChannelSuccessCallback? onconnect;
                
        void unregister(optional SuccessCallback? successCallback, optional ErrorCallback? errorCallback)raises(WebAPIException);
    };          
        
        
    [NoInterfaceObject] interface BluetoothHealthChannel {

        readonly attribute BluetoothDevice peer;
                
        readonly attribute BluetoothHealthChannelType channelType;

        readonly attribute BluetoothHealthApplication application;
                
        readonly attribute boolean isConnected;

        void close() raises(WebAPIException);

        unsigned long sendData(byte[] data) raises(WebAPIException);

        void setListener(BluetoothHealthChannelChangeCallback listener) raises(WebAPIException); 
 
        void unsetListener() raises(WebAPIException);
                
    };
        

    [Callback, NoInterfaceObject] interface BluetoothAdapterChangeCallback {
        void onstatechanged(boolean powered);
        void onnamechanged(DOMString name);
        void onvisibilitychanged(boolean visible);
    };

    [Callback=FunctionOnly, NoInterfaceObject] interface BluetoothDeviceSuccessCallback {
        void onsuccess(BluetoothDevice device);
    };

    [Callback=FunctionOnly, NoInterfaceObject] interface BluetoothDeviceArraySuccessCallback {
        void onsuccess(BluetoothDevice[] devices);
    };

    [Callback, NoInterfaceObject] interface BluetoothDiscoverDevicesSuccessCallback {
        void onstarted();
        void ondevicefound(BluetoothDevice device);
        void ondevicedisappeared(BluetoothAddress address);
        void onfinished(BluetoothDevice[] foundDevices);
    };

    [Callback=FunctionOnly, NoInterfaceObject] interface BluetoothSocketSuccessCallback {
        void onsuccess(BluetoothSocket socket);
    };

    [Callback=FunctionOnly, NoInterfaceObject] interface BluetoothServiceSuccessCallback {
        void onsuccess(BluetoothServiceHandler handler);
    };

    [Callback=FunctionOnly, NoInterfaceObject] interface BluetoothHealthApplicationSuccessCallback {
        void onsuccess(BluetoothHealthApplication application);
    };

        
    [Callback=FunctionOnly, NoInterfaceObject] interface BluetoothHealthChannelSuccessCallback {
        void onsuccess(BluetoothHealthChannel channel);
    };

    [Callback, NoInterfaceObject] interface BluetoothHealthChannelChangeCallback {
        void onmessage(byte[] data);
                
        void onclose(); 
    };

};