GATT シナリオ: Bluetooth LE データの取得 (HTML)

Windows ストア アプリがフォアグラウンドで実行されている間に、Bluetooth LE デバイスからデータを取り込みます。

この例の Windows ストア アプリは、Bluetooth LE Health Thermometer Service を実装する Bluetooth LE デバイスから温度の測定値を取り込みます。新しい温度測定値が利用可能な状態になったときに通知を受け取るための指定は、アプリの初期化ルーチンで行います。"Thermometer Characteristic Value Changed" イベントのハンドラーを登録することにより、フォアグラウンドでの実行中、特性値が変化したときに、そのイベントの通知を受け取ります。

アプリが中断されているときは、デバイスのリソースをすべて解放し、再開された時点で再びデバイスの列挙処理と初期化処理を行う必要がある点に注意してください。

function convertTemperature(temperatureData)
{
    // Read temperature data in IEEE 11703 floating point format
    // temperatureData[0] contains flags about optional data - not used
    var mantissa = ((temperatureData[3] << 16) |
        (temperatureData[2] << 8) |
        (temperatureData[1] << 0));

    var exponent = temperatureData[4];

    return mantissa * Math.pow(10.0, exponent);
}

function initialize() {
    var Gatt = Windows.Devices.Bluetooth.GenericAttributeProfile;
        
    Windows.Devices.Enumeration.DeviceInformation.findAllAsync(
        Gatt.GattDeviceService.getDeviceSelectorFromUuid(
        Gatt.GattServiceUuids.healthThermometer),
        null).done(function (devices) {
            Gatt.GattDeviceService.fromIdAsync(devices[0].id)
            .done(function (firstThermometerService) {
                var thermometerCharacteristic = firstThermometerService
                    .getCharacteristics(
                            Gatt.GattCharacteristicUuids
                                .temperatureMeasurement)[0];

                thermometerCharacteristic.onvaluechanged =
                    function (args) {
                        var temperatureData = Uint8Array(
                            args.characteristicValue.length);

                        Windows.Storage.Streams.DataReader.fromBuffer(
                            args.characteristicValue)
                                .readBytes(temperatureData);

                        // Interpret the temperature value
                        var temperature = 
                            convertTemperature(temperatureData);

                        document.getElementById("outputDiv").innerText =
                            temperature.toString();
                    };

                thermometerCharacteristic
                    .writeClientCharacteristicConfigurationDescriptorAsync(
                    Gatt
                      .GattClientCharacteristicConfigurationDescriptorValue
                        .notify);
            });
        });
}