B2G/Bluetooth/WebBluetooth-v2/BluetoothAdapter

From MozillaWiki
Jump to: navigation, search

Overview

BluetoothAdapter handles all the operations requested by bluetooth networks. A bluetooth adapter is the physical interface used to interact with local bluetooth device. BluetoothAdapter is the most important interface in the whole WebBluetooth API because it manages all the interactions between the local bluetooth device and remote bluetooth devices.

Interfaces

BluetoothAdapter

[CheckPermissions="bluetooth"]
interface BluetoothAdapter: EventTarget
{
  [AvailableIn=CertifiedApps] readonly attribute DOMString address;
  [AvailableIn=CertifiedApps] readonly attribute BluetoothPairingListener pairingReqs; 
  readonly attribute BluetoothAdapterState state;
  readonly attribute DOMString name;
  readonly attribute boolean discoverable;
  readonly attribute boolean discovering;
  readonly attribute BluetoothGattServer? gattServer;

           attribute EventHandler onattributechanged;
           attribute EventHandler ondevicepaired;
           attribute EventHandler ondeviceunpaired;
           attribute EventHandler onpairingaborted;

  [NewObject, AvailableIn=CertifiedApps] Promise<void> enable();
  [NewObject, AvailableIn=CertifiedApps] Promise<void> disable();
  [NewObject, AvailableIn=CertifiedApps] Promise<void> setName(DOMString name);
  [NewObject] Promise<void> setDiscoverable(boolean discoverable);
  [NewObject] Promise<BluetoothDiscoveryHandle> startDiscovery();
  [NewObject] Promise<void> stopDiscovery();
  [NewObject] Promise<void> pair(DOMString address);
  [NewObject] Promise<void> unpair(DOMString address);
  sequence<BluetoothDevice> getPairedDevices();

  // BLE methods
  [NewObject] Promise<BluetoothDiscoveryHandle> startLeScan(sequence<DOMString> aServiceUuids);
  [NewObject] Promise<void> stopLeScan(BluetoothDiscoveryHandle discoveryHandle);
  [NewObject] Promise<void> startAdvertising(optional BluetoothAdvertisingData advData);
  [NewObject] Promise<void> stopAdvertising();
};

BluetoothAdapterState

enum BluetoothAdapterState
{
  "disabled",
  "disabling",
  "enabled",
  "enabling"
}

BluetoothAdapterAttribute

enum BluetoothAdapterAttribute
{
  "unknown",
  "state",
  "address",
  "name",
  "discoverable",
  "discovering"
}

BluetoothAdvertisingData

dictionary BluetoothAdvertisingData
{
  unsigned short appearance = 0;
  boolean includeDevName = false;
  boolean includeTxPower = false;
  ArrayBuffer? manufacturerData = null;
  ArrayBuffer? serviceData = null;
  sequence<DOMString> serviceUuids = [];
};

Properties

state

Description
The state of the local bluetooth adapter.
Value type
BluetoothAdapterState
Default value
BluetoothAdapterState.disabled
Sample
var adapter = navigator.mozBluetooth.defaultAdapter;
if (adapter) {
  var state = adapter.state;
}

address

Description
The address of the device's adapter on the bluetooth micro-network.
Value type
DOMString
Default value
Empty string ("")
Sample
var adapter = navigator.mozBluetooth.defaultAdapter;
if (adapter) {
  var address = adapter.address;
}

name

Description
The human readable name of the device's adapter.
Value type
DOMString
Default value
Empty string ("")
Sample
var adapter = navigator.mozBluetooth.defaultAdapter;
if (adapter) {
  var name = adapter.name;
}

discoverable

Description
Indicates if the device is discoverable (true) or not (false) by other bluetooth devices.
Value type
boolean
Default value
false
Sample
var adapter = navigator.mozBluetooth.defaultAdapter;
if (adapter) {
  var discoverable = adapter.discoverable;
}

discovering

Description
Indicates if the device is in the process of discovering (true) or not (false) surrounding bluetooth devices.
Value type
boolean
Default value
false
Sample
var adapter = navigator.mozBluetooth.defaultAdapter;
if (adapter) {
  var discovering = adapter.discovering;
}

pairingReqs

Description
[AvailableIn=CertifiedApps]
The property wraps event handlers triggered for different pairing types. This BluetoothPairingListener object is created/destroyed as BluetoothAdapter is created/destroyed. The property is only available in certified applications to keep privileged applications from replying other applications' pairing requests.
Value type
BluetoothPairingListener
Default value
Null pointer
Sample
var adapter = navigator.mozBluetooth.defaultAdapter;

if (adapter && adapter.pairingReqs) {
  adapter.pairingReqs.ondisplaypasskeyreq = function onDisplayPasskeyReq(evt) {
    var device = evt.device;
    var passkey = evt.handle.passkey; // passkey to display

    console.log("Pairing request from", device.name, ": display passkey");
    // display passkey to user
  }

  adapter.pairingReqs.onenterpincodereq = function onEnterPinCodeReq(evt) {
    var device = evt.device;
    console.log("Pairing request from", device.name, ": enter pin code");
    // inform user to enter pin code

    var pinCode = UserEnteredPinCode;
    evt.handle.setPinCode(pinCode).then ( function onResolve() {
      console.log("Resolved setPinCode operation");
    }, function onReject(aReason) {
      console.log("Rejected with this reason: " + aReason);
    });
  }

  adapter.pairingReqs.onpairingconfirmationreq = function onPairingConfirmationReq(evt) {
    var device = evt.device;
    var passkey = evt.handle.passkey; // passkey for user to confirm
    console.log("Pairing request from", device.name, ": pairing confirmation");
    // display passkey for user confirm

    var confirm = UserConfirmedOrNot;
    evt.handle.setPairingConfirmation(confirm).then ( function onResolve() {
      console.log("Resolved setPairingConfirmation operation");
    }, function onReject(aReason) {
      console.log("Rejected with this reason: " + aReason);
    });
  }

  adapter.pairingReqs.onpairingconsentreq = function onPairingConsentReq(evt) {
    var device = evt.device;
    console.log("Pairing request from", device.name, ": pairing consent");
    // notify user of just-work pairing
  }
}

gattServer

Description
gattServer property is the object to conduct GATT server operations on local bluetooth adapter. This property will be a null pointer if the adapter is not enabled.
Value type
BluetoothGattServer
Default value
Null pointer
Sample
var adapter = navigator.mozBluetooth.defaultAdapter;
if (adapter) {
  var gattServer = adapter.gattServer;
}

Event Handlers

onattributechanged

Description
A handler to trigger when one of the local bluetooth adapter's properties has changed. Note access to the changed property in this event handler would get the updated value.
Paramter
aAttributeEvent
The event is a BluetoothAttributeEvent with property attrs that contains changed BluetoothAdapterAttributes.
Sample
var adapter = navigator.mozBluetooth.defaultAdapter;

adapter.onattributechanged = function onAdapterAttributeChanged(evt) {
  for (var i in evt.attrs) {
    switch (evt.attrs[i]) {
      case 'state':
        console.log("adapter state changed to", adapter.state);
        break
      case 'name':
        console.log("adapter name changed to", adapter.name);
        break;
      case 'discoverable':
        console.log("adapter discoverable changed to", adapter.discoverable);
        break;
      default:
        break;
    }
  }
};

ondevicepaired

Description
A handler to trigger when a remote device gets paired with local bluetooth adapter.
Parameter
aDeviceEvent
The event is a BluetoothDeviceEvent with property device as the paired remote bluetooth device.

ondeviceunpaired

Description
A handler to trigger when a remote device gets unpaired from local bluetooth adapter.
Parameter
aDeviceEvent
The event is a BluetoothDeviceEvent with property address as the unpaired remote bluetooth device's address.

onpairingaborted

Description
A handler to trigger when pairing fails due to one of following conditions:
- authentication fails
- remote device down (bluetooth ACL becomes disconnected)
- internal error happens

Methods


enable()

Description
The method turns on the local bluetooth adapter.
This is an asynchronous method and its result is returned via a Promise. Once the method is called, property state becomes enabling and a corresponding onattributechanged would be triggered. If the enable operation succeeds, several onattributechanged would be triggered before the Promise is resolved to indicate the address and name has been updated, and the last one must indicate property state becomes enabled. In other words, all adapter's properties except pairingReqs and event handlers must be updated value once property state becomes enabled.
Return
A Promise to indicate whether the operation is resolved or rejected. If the bluetooth adapter is not currently disabled, the Promise would be rejected.
Sample
var adapter = navigator.mozBluetooth.defaultAdapter;

adapter.enable().then ( function onResolve() {
  console.log("Resolved with void value");
}, function onReject(aReason) {
  console.log("Rejected with this reason: " + aReason);
});

disable()

Description
The method turns off the local bluetooth adapter.
This is an asynchronous method and its result is returned via a Promise. Once the method is called, property state becomes disabling and a corresponding onattributechanged would be triggered. If the disable operation succeeds, several onattributechanged would be triggered before the Promise is resolved to the indicate all properties (except state, pairingReqs, and event handlers) become default value, and the last one must indicate property state becomes disabled. In other words, all adapter's properties except pairingReqs and event handlers are reset to default value once property state becomes disabled.
Return
A Promise to indicate whether the operation is resolved or rejected. If the bluetooth adapter is not currently enabled, the Promise would be rejected.
Sample
var adapter = navigator.mozBluetooth.defaultAdapter;

adapter.disable().then ( function onResolve() {
  console.log("Resolved with void value");
}, function onReject(aReason) {
  console.log("Rejected with this reason: " + aReason);
});

setName(DOMString name)

Description
The method sets the human-readable name of the local bluetooth adapter. This name is visible to remote bluetooth devices.
This is an asynchronous method and its result is returned via a Promise. If the setName operation succeeds, an onattributechanged would be triggered before the Promise is resolved to indicate property name has changed.
Parameters
name
A DOMString representing the new name to set.
Return
A Promise to indicate whether the operation is resolved or rejected. If the bluetooth adapter is currently disabled or aName is identical to current name attribute, the Promise would be rejected.
Sample
var adapter = navigator.mozBluetooth.defaultAdapter;
var name = "The name of bluetooth adapter";

adapter.setName(name).then ( function onResolve() {
  console.log("Resolved with void value");
}, function onReject(aReason) {
  console.log("Rejected with this reason: " + aReason);
});

setDiscoverable(boolean discoverable)

Description
The method changes the value of the bluetooth adapter's discoverable property.
This is an asynchronous method and the result is returned via a Promise. If the setDiscoverable operation succeeds, an onattributechanged would be triggered before the Promise is resolved to indicate property discoverable has changed.
Parameters
discoverable
A boolean indicating if the device is discoverable (true) or not (false).
Return
A Promise to indicate whether the operation is resolved or rejected. If the bluetooth adapter is currently disabled or aDiscoverable is identical to current discoverable attribute, the Promise would be rejected.
Sample
var adapter = navigator.mozBluetooth.defaultAdapter;
 
adapter.setDiscoverable(true).then ( function onResolve() {
  console.log("Resolved with void value");
}, function onReject(aReason) {
  console.log("Rejected with this reason: " + aReason);
});

startDiscovery()

Description
The method makes the device's adapter start seeking for remote devices. The discovery process may be terminated after discovering a period of time. If the startDiscovery operation succeeds, an onattributechanged event would be triggered before the Promise is resolved to indicate property discovering becomes true.
Return
A Promise to indicate whether the operation is resolved or rejected. If the Promise is resolved, it returns a BluetoothDiscoveryHandle. The BluetoothDiscoveryHandle's event handler ondevicefound is fired each time a remote bluetooth device is discovered. If the bluetooth adapter is currently discovering or disabled, the Promise would be rejected.
Sample
var adapter = navigator.mozBluetooth.defaultAdapter;
var discoveryHandle;

adapter.startDiscovery().then ( function onResolve(handle) {
  console.log("Resolved with discoveryHandle");

  // Keep reference to handle in order to listen to ondevicefound event handler 
  discoveryHandle = handle;
  discoveryHandle.ondevicefound = function onDeviceFound(evt) {
    var device = evt.device;
    console.log("Discovered remote device. Address:", device.address);
  };
}, function onReject(aReason) {
  console.log("Rejected with this reason: " + aReason);
});

stopDiscovery()

Description
The method makes the device's adapter stop seeking for remote devices.
This is an asynchronous method and its result is returned via a Promise. If the stopDiscovery operation succeeds, an onattributechanged would be triggered before the Promise is resolved to indicate property discovering becomes false. Note adapter may still receive BluetoothDiscoveryHandle.ondevicefound event until the Promise is resolved.
Return
A Promise to indicate whether the operation is resolved or rejected. If the bluetooth adapter is currently disabled, the Promise would be rejected.
Sample
var adapter = navigator.mozBluetooth.defaultAdapter;

adapter.stopDiscovery().then ( function onResolve() {
  console.log("Resolved with void value");
}, function onReject(aReason) {
  console.log("Rejected with this reason: " + aReason);
});

pair(DOMString deviceAddress)

Description
The method starts pairing a remote device with the device's adapter.
Note on Bluedroid stack, discovery has to be stopped before pairing (i.e., call stopDiscovery() before pair()) otherwise stack callbacks with pairing failure.
Parameters
deviceAddress
A DOMString object representing the address of the device to pair with.
Return
A Promise to indicate whether the operation is resolved or rejected. Note event handler ondevicepaired would be triggered before the Promise is resolved.
Sample
var adapter = navigator.mozBluetooth.defaultAdapter;

adapter.pair('00:80:98:09:0B:5D').then ( function onResolve() {
  console.log("Resolved with void value");
}, function onReject(aReason) {
  console.log("Rejected with this reason: " + aReason);
});

unpair(DOMString deviceAddress)

Description
The method unpairs a remote device from the device's adapter.
Parameters
deviceAddress
A DOMString object representing the address of the device to unpair from.
Return
A Promise to indicate whether the operation is resolved or rejected. Note event handler ondeviceunpaired would be triggered before the Promise is resolved.

getPairedDevices()

Description
The method retrieves the list of all devices paired with the device's adapter.
Return
sequence<BluetoothDevice>
Sample
var adapter = navigator.mozBluetooth.defaultAdapter;
var pairedDevices = adapter.getPairedDevices();
for (var i = 0; i < pairedDevices.length; i++) {   
  console.log("address of paired device " + i + ":" + pairedDevices[i].address);
}

startLeScan(sequence<DOMString> serviceUuids)

Description
The method makes the device's adapter start seeking for remote LE devices advertising given services.
Parameters
serviceUuids
A DOMString array of service UUIDs to seek for. Standardized service UUIDs are listed in here. An empty array means to seek for devices advertising any service.
Return
A Promise to indicate whether the operation is resolved or rejected. If the Promise is resolved, it returns a BluetoothDiscoveryHandle. The BluetoothDiscoveryHandle's event handler ondevicefound is fired each time a remote bluetooth LE device is found. If the bluetooth adapter is currently disabled, the Promise would be rejected.
Sample
const HEART_RATE_SERVICE = "0000180d-0000-1000-8000-00805f9b34fb";
const BATTERY_SERVICE = "0000180f-0000-1000-8000-00805f9b34fb";

var adapter = navigator.mozBluetooth.defaultAdapter;
var serviceUuids = [HEART_RATE_SERVICE, BATTERY_SERVICE];
var discoveryHandle;

adapter.startLeScan(serviceUuids).then ( function onResolve(handle) {
  console.log("Resolved with discoveryHandle");

  // Keep reference to handle in order to listen to ondevicefound event handler 
  discoveryHandle = handle;
  discoveryHandle.ondevicefound = function onDeviceFound(evt) {
    var device = evt.device;
    var rssi = evt.rssi;
    var scanRecord = evt.scanRecord;
    console.log("Found remote LE device. Address:", device.address, "rssi:", rssi);
  };
}, function onReject(aReason) {
  console.log("Rejected with this reason: " + aReason);
});

stopLeScan(BluetoothDiscoveryHandle discoveryHandle)

Description
The method makes the device's adapter stop an ongoing scan of remote LE devices.
Parameters
discoveryHandle
The BluetoothDiscoveryHandle of the ongoing scan to stop.
Return
A Promise to indicate whether the operation is resolved or rejected. If the bluetooth adapter is currently disabled, the Promise would be rejected.
Sample
var adapter = navigator.mozBluetooth.defaultAdapter;
var discoveryHandle = discoveryHandle returned from startLeScan method

adapter.stopLeScan(discoveryHandle).then ( function onResolve() {
  console.log("Resolved with void value");
}, function onReject(aReason) {
  console.log("Rejected with this reason: " + aReason);
});

startAdvertising(optional BluetoothAdvertisingData advData)

Description
Start to broadcast advertisements with an optional custom advertisement data.
Parameters
advData
The custom advertisement data.
Return
A Promise to indicate whether the operation is resolved or rejected. If the bluetooth adapter is currently disabled, the Promise would be rejected.

stopAdvertising()

Description
Stop broadcasting advertisements.
Return
A Promise to indicate whether the operation is resolved or rejected. If the bluetooth adapter is currently disabled, the Promise would be rejected.

See also