Search code examples
javascriptapibluetoothprogressive-web-appsweb-bluetooth

read tempreture from bluetooth device with web bluetooth


I am facing some problems with web Bluetooth API. the problem is that I have a temperature and humidity recorder Bluetooth device, which recorded temperature and humidity data through the sensor. I want to fetch that data in my web app by using web Bluetooth in javascript. so how can I perform this task?

I have tried web Bluetooth but I only get device name and battery level but I am not able to fetch temperature & humidity data.


Solution

  • If the Bluetooth device uses the GATT Environmental Sensing service (GATT Assigned Number 0x181A), you should be able to read and get notified of the Temperature (0x2A6E) and Humidity (0x2A6F) GATT characteristics.

    Here's some code that should* work.

    const serviceUuid = 0x181A;
    
    // Requesting Bluetooth Device assuming it advertises
    // the GATT Environmental Sensing Service...
    const device = await navigator.bluetooth.requestDevice({
        filters: [{services: [serviceUuid]}]});
    
    // Connecting to GATT Server...
    const server = await device.gatt.connect();
    
    // Getting Environmental Sensing Service...
    const service = await server.getPrimaryService(serviceUuid);
    
    // Getting Humidity Characteristic...
    const characteristic = await service.getCharacteristic(0x2A6F);
    
    // Reading Humidity...
    const value = await characteristic.readValue();
    console.log(value);
    

    The sample at https://googlechrome.github.io/samples/web-bluetooth/notifications.html?characteristic=humidity&service=environmental_sensing may also help you get started.