Connecting to Dash or Dot

With that out of the way, let’s get back to Dash and Dot and the Bluetooth API. The steps we will take to connect to Dash or Dot are:

  1. Connect to the device.
  2. Connect to the GATT server on the device.
  3. Connect to the Dash and Dot service.
  4. Connect to the “command” characteristic.
  5. Read and write to the “command” characteristic.

Connect to the Device

The JavaScript command to request a connection to the Bluetooth device is navigator.bluetooth.requestDevice(), however this can only be run in response to a user interaction, such as a mouse click.

function connect() {
  navigator.bluetooth.requestDevice({
    acceptAllDevices: true
  });
}

addEventListener('click', connect);

We’ve set acceptAllDevices to true, which we will change in a moment. Run the code and you’ll be surprised by the number of Bluetooth around you. These could be phones, mice, keyboards, headphones, heart rate monitors, etc.

Each Bluetooth service has a unique ID. The UUID for the Dash and Dot service is “af237777-879d-6186-1f49-deca0e85d9c1”. We can update our code to only show devices offering this service.

var SERVICE_UUID = 'af237777-879d-6186-1f49-deca0e85d9c1';

function connect() {
  navigator.bluetooth.requestDevice({
    filters: [{ services: [SERVICE_UUID] }]
  });
}

addEventListener('click', connect);

The Command Characteristic

In the General Attribute (GATT) protocol that Bluetooth LE follows, each data point (sensor etc.) is referred to as a characteristic and also has a unique ID. The robots have a characteristic used to communicate commands.

After connecting to the device, we’ll connect to the GATT server, the service, and finally the specific characteristic used to send commands. We’ll use async and await to keep everything straight-forward and synchronous.

var SERVICE_UUID = 'af237777-879d-6186-1f49-deca0e85d9c1';
var COMMAND_UUID = 'af230002-879d-6186-1f49-deca0e85d9c1';

async function connect() {
  var device = await navigator.bluetooth.requestDevice({
    filters: [{ services: [SERVICE_UUID] }]
  });
  var server = await device.gatt.connect();
  var service = await server.getPrimaryService(SERVICE_UUID);
  var command = await service.getCharacteristic(COMMAND_UUID);
}

addEventListener('click', connect);

Keywords

  • Await 1
  • B-Splines 1
  • Bezier 1
  • Binary 1
  • Bluetooth 1
  • Canvas 1 2
  • Curves 1
  • Drupal 1
  • Gulp 1
  • JavaScript 1 2 3
  • PHP 1
  • Promises 1
  • Xdebug 1