Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

184
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda