Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

183
Vistas
BLE keep connection alive (website / pwa) using javascript

Disclaimer: I'm a noob coder.

I'm trying to keep the connection alive until the session ends (the user closes the browser/navigates to something else)

the code here shows the modified sample by Chrome Samples

function readData() {
    console.log('Requesting Bluetooth Device...');

    navigator.bluetooth.requestDevice({
        filters: [{
            services: [serviceUuid]
        }]
    })
        .then(device => {
            return device.gatt.connect();
        })
        .then(server => {
            return server.getPrimaryService(serviceUuid);
        })
        .then(service => {
            return service.getCharacteristic(characterUuid);
        })
        .then(characteristic => characteristic.readValue())
        .then(result => decodeValues(result))
        .then(result => document.getElementById("output").innerHTML = result)
        .catch(error => {
            console.log('Argh! ' + error);
        });
}

but the issue here is, if I want to write to the same service of a different characteristic when the user clicks another button, I have to use navigator.bluetooth.requestDevice(...) again which will bring up the popup dialog to choose the device. This will become very unintuitive when using the site. Please help.

Thank You.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

So, it worked using async await .....

explanation for the below code ... I'm gonna call the readData first before writeData .... hence storing service in a global variable

let device, server, service;
let serviceUuid = '4fafc201-1fb5-459e-8fcc-c5c9c331914b';
let writeUuid = 'beb5483e-36e1-4688-b7f5-ea07361b26a8';
let readUuid = '9fde8759-ffd6-40d7-a50e-f0ffa74abd25';

async function readData() {
    device = await navigator.bluetooth.requestDevice({ filters: [{ services: [serviceUuid] }] })
        .catch(error => console.log(error));

    server = await device.gatt.connect().catch(error => console.log(error));
    service = await server.getPrimaryService(serviceUuid).catch(error => console.log(error));
    let characteristic = await service.getCharacteristics(readUuid).catch(error => console.log(error));
    let value = decodeValues(await characteristic[0].readValue().catch(error => console.log(error)));
    document.getElementById('time-left').innerHTML = value;
}


async function writeData() {
    let characteristic = await service.getCharacteristics(writeUuid).catch(error => console.log(error));
    characteristic[0].writeValue(encodeValues('5'));
}

function decodeValues(result) {
    let decoder = new TextDecoder('utf-8');
    return decoder.decode(result.buffer);
}

function encodeValues(stringValue) {
    let encoder = new TextEncoder('utf-8');
    return encoder.encode(stringValue);
}

hope this helps for anyone searching for the answer

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda