GATT Scenario: Retrieve Bluetooth LE Data (HTML)
A Windows Store App consumes data from a Bluetooth LE device while running in the foreground.
In this example, the Windows Store App consumes temperature measurements from a Bluetooth LE device that implements the Bluetooth LE Health Thermometer Service. In the App's initialization routine, the App specifies that it wants to be notified when a new temperature measurement is available. By registering an event handler for the "Thermometer Characteristic Value Changed" event, the App will receive characteristic value changed event notifications while it is running in the foreground.
Note that when the App is suspended, it must release all device resources and when it resumes, it must perform device enumeration and initialization once again.
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);
});
});
}