GATT Scenario: Control Presentation of Bluetooth LE Device Data (HTML)

A Windows Store App Bluetooth LE devices may expose a battery service that provides the current battery level to the user. The battery service includes an optional PresentationFormat descriptor which allows some flexibility in interpretation of the battery level data. This scenario provides example of an App that works with such a device and uses the PresentationFormats property to format a characteristic value, before presenting it to the user.

function initialize() {
    var Gatt = Windows.Devices.Bluetooth.GenericAttributeProfile;
    Windows.Devices.Enumeration.DeviceInformation.findAllAsync(
        Gatt.GattDeviceService.getDeviceSelectorFromUuid(
            Gatt.GattServiceUuids.battery),
        null).done(function (batteryServices) {
          Gatt.GattDeviceService.fromIdAsync(batteryServices[0].id)
            .done(function (firstBatteryService) {
              var batteryLevelCharacteristic = firstBatteryService
                    .getCharacteristics(
                        Gatt.GattCharacteristicUuids.batteryLevel)[0];

                batteryLevelCharacteristic.onvaluechanged =
                    function (args) {
                        var levelData = Windows.Storage.Streams.DataReader
                            .fromBuffer(args.characteristicValue)
                            .readByte();

                        // Retrieve the GattCharacteristic sender
                        var sender = args.target;

                        // if the sender Characteristic has a presentation
                        // format use that information to format the value
                        var levelValue;
                        if (args.target.presentationFormats.length > 0) {
                            levelValue = levelData *
                                Math.pow(
                                    10.0,
                                    args.target
                                        .presentationFormats[0].exponent);
                        } else {
                            levelValue = levelData;
                        }

                        outputDiv.innerText = levelValue.toString();
                    };

                batteryLevelCharacteristic
                    .writeClientCharacteristicConfigurationDescriptorAsync(
                    Gatt
                      .GattClientCharacteristicConfigurationDescriptorValue
                          .notify).done(function (status) {
                            if (Gatt.GattCommunicationStatus.unreachable ==
                                status) {
                              outputDiv.innerText =
                                  "Writing to the device failed !";
                            }
                          });
            });
        });
}