Write the "Central" App

The Central app

You could write the central as a mobile application, but for our purposes we're going to use the Web Bluetooth API. This will let us connect to our peripheral through some Javascript code.


Web Bluetooth API

A few lines of Javascript allow us to connect to our peripheral, and subscribe to notifications when the value of the characteristic has changed:

<script>
  window.BluetoothThermometer = class {
    connectBluetooth() {
        const serviceUUID        = '12634d89-d598-4874-8e86-7d042ee07ba7'
        const characteristicUUID = '4116f8d2-9f66-4f58-a53d-fc7440e7c14e'

        navigator.bluetooth.requestDevice({
            filters: [
                {name: 'RasberryPi-Bluetooth.com Thermometer'},
                {services: [serviceUUID]}
            ]
        })
        .then(device => device.gatt.connect())
        .then(server => server.getPrimaryService(serviceUUID))
        .then(service => service.getCharacteristic(characteristicUUID))
        .then(characteristic => characteristic.startNotifications())
        .then(characteristic => {
            characteristic.addEventListener('characteristicvaluechanged', this._update(this))
            console.log('Notifications have been started.');
        })
        .catch(error => { console.error(error); });
    }

    _update(event) {
        const temperatureReading = event.target.value.getFloat32();
        // Do something with the temperature reading.
    }
  }
</script>

The Web Bluetooth API requires a user interaction to trigger, so we'll set an on-click handler for the body.

<script >
  document.body.onclick = (new BluetoothThermometer).connectBluetooth;
</script>

I've included a sample page for you to see how this interaction works


Important Restrictions

  1. A user interaction (e.g., click or keystroke) is required for requestDevice() to run
  2. You won't be able to connect to Bluetooth devices if the webpage hosting the central code didn't use a secure transport (https) or wasn't running on localhost.
  3. You need to list all of the services you intend to connect to in RequestDevice({filters: {services: []}}). Without specifying the services, Web Bluetooth will allow you to connect to the peripheral, but it won't let you access unspecified services.

To debug the central application, open up the chrome://bluetooth-internals/ page. That will let you know if your browser can see the peripheral, and show you the services that are available.

💪That's the whole guide! I hope you enjoyed it and that it helps you develop some interested things with Bluetooth Low Energy!

-- Mark Lorenz