API da ponte JavaScript
Web Bluetooth
O formato do navigator.bluetooth, respondido de forma nativa para que uma página escrita para o Chrome funcione sem alterações.
wbConnect ponte#
window.WebToApk.wbConnect(requestId: String, deviceId: String)
Transporte bruto do WebBluetoothPolyfill. Uma página nunca chama isso diretamente - ela chama navigator.bluetooth, exatamente como faria em um navegador.
Descrito por seu grupo, Web Bluetooth (navigator.bluetooth), e não separadamente.
Exemplo
Transporte interno por trás de device.gatt.connect(). As páginas usam navigator.bluetooth; não chame isto diretamente.
Retorna: (por meio de gatt.connect()) uma Promise do BluetoothRemoteGATTServer, depois que os serviços do dispositivo são descobertos. Requer: Bluetooth (ativado por um build de ZIP ou HTML quando seu código menciona navigator.bluetooth).
async function connectAndList(device) {
try {
var server = await device.gatt.connect();
var services = await server.getPrimaryServices();
services.forEach(function (s) { console.log('service', s.uuid); });
return server;
} catch (err) {
showStatus('Could not connect: ' + err.message); // NetworkError, NotFoundError
return null;
}
}Reconecte quando o dispositivo cair. Chamar connect() de novo no mesmo dispositivo funciona:
device.addEventListener('gattserverdisconnected', async function () {
showStatus('Reconnecting...');
try { await connectAndList(device); showStatus('Connected'); } catch (e) {}
});Conecte-se a dois sensores ao mesmo tempo, por exemplo uma cinta de frequência cardíaca e um medidor de potência:
async function connectBoth(hrDevice, powerDevice) {
var servers = await Promise.all([hrDevice.gatt.connect(), powerDevice.gatt.connect()]);
var hr = await servers[0].getPrimaryService('heart_rate');
var power = await servers[1].getPrimaryService('cycling_power');
return {
heartRate: await hr.getCharacteristic('heart_rate_measurement'),
power: await power.getCharacteristic('cycling_power_measurement')
};
}Observações: Assinatura bruta wbConnect(requestId, deviceId). Conectar a um dispositivo que já está conectado resolve de novo na hora. getPrimaryService(s) rejeita com NetworkError antes de connect() terminar. Vários dispositivos podem estar conectados ao mesmo tempo.
wbDisconnect ponte#
window.WebToApk.wbDisconnect(deviceId: String)
Transporte bruto do WebBluetoothPolyfill. Uma página nunca chama isso diretamente - ela chama navigator.bluetooth, exatamente como faria em um navegador.
Descrito por seu grupo, Web Bluetooth (navigator.bluetooth), e não separadamente.
Exemplo
Transporte interno por trás de device.gatt.disconnect() (e device.forget()). As páginas usam navigator.bluetooth; não chame isso diretamente.
Retorna: nada (disconnect() é síncrono, como no padrão da web). Depois o dispositivo dispara gattserverdisconnected. Requer: Bluetooth (ativado por uma build ZIP ou HTML quando seu código menciona navigator.bluetooth).
var device = null; // from navigator.bluetooth.requestDevice(...)
document.getElementById('stop').addEventListener('click', function () {
if (device && device.gatt.connected) device.gatt.disconnect();
});
// Fires for your own disconnect() and when the device goes away by itself.
function watch(dev) {
dev.addEventListener('gattserverdisconnected', function () {
showStatus('Disconnected from ' + (dev.name || dev.id));
});
}Diferencie o seu próprio Parar do sensor saindo do alcance e reconecte apenas no segundo caso:
var userStopped = false;
function stopSession(device) {
userStopped = true;
if (device.gatt.connected) device.gatt.disconnect();
}
function watchDrops(device) {
device.addEventListener('gattserverdisconnected', function () {
if (userStopped) { userStopped = false; showStatus('Session ended'); return; }
showStatus('Sensor out of range, reconnecting...');
device.gatt.connect()
.then(resubscribe) // your code: get the characteristics, startNotifications()
.catch(function () { showStatus('Could not reconnect'); });
});
}Um botão "Remover sensor": forget() desconecta e descarta o dispositivo, e nenhum gattserverdisconnected o segue:
var device = null; // from navigator.bluetooth.requestDevice(...)
document.getElementById('forget').addEventListener('click', async function () {
if (!device) return;
await device.forget();
device = null;
showStatus('Sensor removed. Tap Connect to pick one again.');
});Observações: Assinatura bruta wbDisconnect(deviceId). Depois de uma desconexão, os objetos antigos de serviço e característica deixam de receber notificações; depois do próximo connect(), obtenha-os de novo e chame startNotifications() outra vez. O app encerra todas as conexões quando fecha.
wbGetCharacteristics ponte#
window.WebToApk.wbGetCharacteristics(requestId: String, deviceId: String, service: String)
Transporte bruto do WebBluetoothPolyfill. Uma página nunca chama isso diretamente - ela chama navigator.bluetooth, exatamente como faria em um navegador.
Descrito por seu grupo, Web Bluetooth (navigator.bluetooth), e não separadamente.
Exemplo
Transporte interno por trás de service.getCharacteristic(uuid) e service.getCharacteristics(). As páginas usam navigator.bluetooth; não chame isto diretamente.
Retorna: (por meio do serviço) uma Promise de um BluetoothRemoteGATTCharacteristic, ou de um array deles, cada um com uuid e properties (read, write, writeWithoutResponse, notify, indicate, broadcast, authenticatedSignedWrites). Requer: Bluetooth (ativado por um build de ZIP ou HTML quando seu código menciona navigator.bluetooth).
async function describe(server) {
var service = await server.getPrimaryService('heart_rate');
// One characteristic, by standard name, 16-bit number or full UUID:
var measurement = await service.getCharacteristic('heart_rate_measurement'); // same as 0x2a37
// All of them:
var list = await service.getCharacteristics();
list.forEach(function (c) {
var p = c.properties;
console.log(c.uuid, p.read ? 'read' : '', p.write ? 'write' : '', p.notify ? 'notify' : '');
});
return measurement;
}Encontre as características de um serviço personalizado pelo que elas podem fazer, em vez de fixar os UUIDs no código:
async function findSerialPipes(server) {
var svc = await server.getPrimaryService('0000ffe0-0000-1000-8000-00805f9b34fb');
var list = await svc.getCharacteristics();
var incoming = list.find(function (c) { return c.properties.notify || c.properties.indicate; });
var outgoing = list.find(function (c) { return c.properties.write || c.properties.writeWithoutResponse; });
if (!incoming || !outgoing) throw new Error('This device does not look like a serial adapter');
return { incoming: incoming, outgoing: outgoing };
}Leia uma característica opcional e trate NotFoundError como "este dispositivo não tem isso":
var LOCATIONS = ['Other', 'Chest', 'Wrist', 'Finger', 'Hand', 'Ear lobe', 'Foot'];
async function sensorLocation(server) {
var hr = await server.getPrimaryService('heart_rate');
try {
var chr = await hr.getCharacteristic('body_sensor_location'); // 0x2a38, optional in the spec
var v = await chr.readValue();
return LOCATIONS[v.getUint8(0)] || 'Unknown';
} catch (err) {
if (err.name === 'NotFoundError') return null; // this strap does not report it
throw err;
}
}Observações: Assinatura bruta wbGetCharacteristics(requestId, deviceId, service). Um UUID que o serviço não tem é rejeitado com NotFoundError; um nome desconhecido lança TypeError (passe um UUID completo para características personalizadas). A lista é buscada uma vez por serviço e depois reutilizada.
wbIsAvailable ponte#
window.WebToApk.wbIsAvailable(): Boolean
getAvailability(): se o celular TEM Bluetooth (a resposta do Chrome), não se ele está ligado. requestDevice() pede ao usuário que o ligue; responder false quando ele estava apenas desligado fazia páginas que verificam antes ("if (!await getAvailability())") dizerem "Bluetooth não suportado" e nunca chegarem a esse prompt (relatório de fitness de 2026-10-03).
Exemplo
Transporte interno por trás de navigator.bluetooth.getAvailability(). As páginas usam navigator.bluetooth; não chame isto diretamente.
Retorna: (por meio de getAvailability()) uma Promise de true quando o build tem Bluetooth e o Bluetooth do celular está ligado, caso contrário false. Requer: Bluetooth (ativado por um build de ZIP ou HTML quando seu código menciona navigator.bluetooth).
async function updateBluetoothHint() {
var hint = document.getElementById('bt-hint');
if (!navigator.bluetooth) { hint.textContent = 'Bluetooth is not available in this app.'; return; }
var on = await navigator.bluetooth.getAvailability();
hint.textContent = on ? '' : 'Turn on Bluetooth to connect your sensor.';
}
document.addEventListener('visibilitychange', function () {
if (!document.hidden) updateBluetoothHint();
});Ative o botão Conectar somente enquanto o Bluetooth estiver ligado, verificando de novo sempre que o usuário voltar ao app:
async function refreshConnectButton() {
var btn = document.getElementById('connect');
if (!navigator.bluetooth) { btn.hidden = true; return; }
btn.disabled = !(await navigator.bluetooth.getAvailability());
}
window.addEventListener('load', refreshConnectButton);
document.addEventListener('visibilitychange', function () {
if (!document.hidden) refreshConnectButton();
});Dê uma mensagem clara de "Bluetooth desligado" antes de abrir o seletor, em vez de um NotFoundError depois:
document.getElementById('scan').addEventListener('click', async function () {
if (!navigator.bluetooth) { showStatus('Bluetooth is not available in this app.'); return; }
if (!(await navigator.bluetooth.getAvailability())) {
showStatus('Bluetooth is off. Turn it on, then tap Scan again.');
return;
}
try {
var device = await navigator.bluetooth.requestDevice({ acceptAllDevices: true });
showStatus('Picked ' + (device.name || device.id));
} catch (err) {
showStatus(err.name === 'NotFoundError' ? 'No device chosen.' : err.message);
}
});Observações: Assinatura bruta wbIsAvailable(): Boolean (síncrona). Verifica apenas o adaptador; não pede nenhuma permissão. O evento availabilitychanged do padrão web não é disparado, então verifique de novo quando a página ficar visível.
wbNotify ponte#
window.WebToApk.wbNotify(
Transporte bruto do WebBluetoothPolyfill. Uma página nunca chama isso diretamente - ela chama navigator.bluetooth, exatamente como faria em um navegador.
Descrito por seu grupo, Web Bluetooth (navigator.bluetooth), e não separadamente.
Exemplo
Transporte interno por trás de characteristic.startNotifications() e stopNotifications(). As páginas usam navigator.bluetooth; não chame isto diretamente.
Retorna: (por meio da característica) uma Promise da própria característica. Cada novo valor dispara characteristicvaluechanged nela, com o valor em event.target.value (um DataView). Requer: Bluetooth (ativado por um build de ZIP ou HTML quando seu código menciona navigator.bluetooth).
var cadenceChr = null;
async function startCadence(server) {
var svc = await server.getPrimaryService('running_speed_and_cadence');
cadenceChr = await svc.getCharacteristic('rsc_measurement');
cadenceChr.addEventListener('characteristicvaluechanged', onRsc);
await cadenceChr.startNotifications();
}
function onRsc(e) {
var v = e.target.value;
var kmh = v.getUint16(1, true) / 256 * 3.6;
var spm = v.getUint8(3);
show('run', kmh.toFixed(1) + ' km/h, ' + spm + ' steps/min');
}
async function stopCadence() {
if (!cadenceChr) return;
cadenceChr.removeEventListener('characteristicvaluechanged', onRsc);
try { await cadenceChr.stopNotifications(); } catch (e) {}
}Um termômetro cuja medição só aceita indicações é assinado do mesmo jeito, aqui pela propriedade oncharacteristicvaluechanged:
async function watchThermometer(server) {
var svc = await server.getPrimaryService('health_thermometer');
var chr = await svc.getCharacteristic('temperature_measurement');
chr.oncharacteristicvaluechanged = function (e) {
var v = e.target.value;
var mantissa = v.getUint32(1, true) & 0x00ffffff; // IEEE-11073 FLOAT
if (mantissa & 0x800000) mantissa -= 0x1000000;
var fahrenheit = v.getUint8(0) & 1;
show('temp', (mantissa * Math.pow(10, v.getInt8(4))).toFixed(1) + (fahrenheit ? ' °F' : ' °C'));
};
await chr.startNotifications();
}Receba linhas de texto de um dispositivo do tipo serial, juntando as notificações que dividem uma linha no meio:
async function listenForLines(server, onLine) {
var uart = await server.getPrimaryService('6e400001-b5a3-f393-e0a9-e50e24dcca9e');
var tx = await uart.getCharacteristic('6e400003-b5a3-f393-e0a9-e50e24dcca9e');
if (!tx.properties.notify && !tx.properties.indicate) throw new Error('This device does not stream data');
var decoder = new TextDecoder(), buffer = '';
tx.addEventListener('characteristicvaluechanged', function (e) {
buffer += decoder.decode(e.target.value, { stream: true });
var lines = buffer.split('\n');
buffer = lines.pop();
lines.forEach(onLine);
});
await tx.startNotifications();
return tx;
}Observações: Assinatura bruta wbNotify(requestId, deviceId, service, characteristic, enable). Uma característica que só suporta indicações é assinada automaticamente com indicações. Uma característica que não pode notificar rejeita com NotSupportedError. oncharacteristicvaluechanged = fn também funciona. Depois de uma desconexão, assine de novo.
wbRead ponte#
window.WebToApk.wbRead(requestId: String, deviceId: String, service: String, characteristic: String)
Transporte bruto do WebBluetoothPolyfill. Uma página nunca chama isso diretamente - ela chama navigator.bluetooth, exatamente como faria em um navegador.
Descrito por seu grupo, Web Bluetooth (navigator.bluetooth), e não separadamente.
Exemplo
Transporte interno por trás de characteristic.readValue(). As páginas usam navigator.bluetooth; não chame isto diretamente.
Retorna: (por meio de readValue()) uma Promise de um DataView; characteristic.value também é atualizado. Requer: Bluetooth (ativado por um build de ZIP ou HTML quando seu código menciona navigator.bluetooth).
async function readInfo(server) {
try {
var battery = await server.getPrimaryService('battery_service');
var level = await (await battery.getCharacteristic('battery_level')).readValue();
show('battery', level.getUint8(0) + '%');
var info = await server.getPrimaryService('device_information');
var maker = await (await info.getCharacteristic('manufacturer_name_string')).readValue();
show('maker', new TextDecoder().decode(maker));
} catch (err) {
// NotFoundError: the device has no such service/characteristic
// NotSupportedError: read rejected by the device NetworkError: not connected / read failed
show('info', err.message);
}
}Faça polling de um sensor que só pode ser lido, aqui a característica padrão Temperature (0x2a6e, em centésimos de grau):
var pollTimer = null;
async function startTemperaturePolling(server) {
var env = await server.getPrimaryService('environmental_sensing');
var temp = await env.getCharacteristic(0x2a6e);
pollTimer = setInterval(async function () {
try {
var v = await temp.readValue();
show('temp', (v.getInt16(0, true) / 100).toFixed(1) + ' °C');
} catch (err) {
clearInterval(pollTimer); // NetworkError once the sensor is gone
show('temp', err.message);
}
}, 5000);
}Preencha um painel "Sobre este dispositivo" iniciando várias leituras de uma vez; elas rodam uma após a outra para você:
async function readDeviceInfo(server) {
var info = await server.getPrimaryService('device_information');
var names = ['model_number_string', 'serial_number_string', 'firmware_revision_string'];
var decoder = new TextDecoder();
var results = await Promise.allSettled(names.map(async function (name) {
var chr = await info.getCharacteristic(name);
return decoder.decode(await chr.readValue());
}));
results.forEach(function (r, i) {
show(names[i], r.status === 'fulfilled' ? r.value : '-'); // missing ones reject with NotFoundError
});
}Observações: Assinatura bruta wbRead(requestId, deviceId, service, characteristic). Leituras, gravações e mudanças de notificação em um mesmo dispositivo rodam uma após a outra, na ordem em que você as chama, então você pode disparar várias sem esperar entre elas.
wbRequestDevice ponte#
window.WebToApk.wbRequestDevice(requestId: String, optionsJson: String)
Transporte bruto do WebBluetoothPolyfill. Uma página nunca chama isso diretamente - ela chama navigator.bluetooth, exatamente como faria em um navegador.
Descrito por seu grupo, Web Bluetooth (navigator.bluetooth), e não separadamente.
Exemplo
Transporte interno por trás de navigator.bluetooth.requestDevice(options): mostra o seletor de dispositivos do app. As páginas usam navigator.bluetooth.requestDevice; não chame isto diretamente.
Retorna: (por meio de requestDevice) uma Promise de um BluetoothDevice {id, name, gatt}. Requer: Bluetooth (ativado por um build de ZIP ou HTML quando seu código menciona navigator.bluetooth) e a permissão de Dispositivos por perto, solicitada no primeiro uso.
document.getElementById('pick').addEventListener('click', async function () {
if (!navigator.bluetooth) { showStatus('Bluetooth is not available in this app.'); return; }
try {
var device = await navigator.bluetooth.requestDevice({
filters: [{ services: ['cycling_power'] }, { namePrefix: 'KICKR' }],
optionalServices: ['battery_service']
});
showStatus('Picked ' + (device.name || device.id));
} catch (err) {
if (err.name === 'NotFoundError') showStatus('No device chosen.'); // also: Bluetooth off
else showStatus(err.name + ': ' + err.message); // SecurityError = permission
}
});Para listar todos os dispositivos próximos em vez de filtrar: requestDevice({ acceptAllDevices: true }).
Escolha um dispositivo personalizado pelo nome exato ou pelo prefixo do nome, listando o próprio serviço de 128 bits dele para poder usá-lo após conectar:
async function pickLamp() {
try {
return await navigator.bluetooth.requestDevice({
filters: [{ name: 'Desk Lamp' }, { namePrefix: 'LAMP-' }], // either one matches
optionalServices: ['0000ffe0-0000-1000-8000-00805f9b34fb']
});
} catch (err) {
if (err.name === 'SecurityError') showStatus('Allow Nearby devices to find your lamp.');
else if (err.name !== 'NotFoundError') showStatus(err.message); // NotFoundError = cancelled
return null;
}
}Peça o dispositivo uma vez por sessão e reutilize-o nos toques seguintes (getDevices() não está disponível, então guarde o objeto que você recebeu):
var scale = null;
document.getElementById('weigh').addEventListener('click', async function () {
if (!navigator.bluetooth) { showStatus('Bluetooth is not available in this app.'); return; }
try {
if (!scale) {
scale = await navigator.bluetooth.requestDevice({
filters: [{ services: ['weight_scale'], namePrefix: 'MI' }] // both keys must match
});
}
var server = await scale.gatt.connect();
var svc = await server.getPrimaryService('weight_scale');
var chr = await svc.getCharacteristic('weight_measurement');
chr.addEventListener('characteristicvaluechanged', onWeight);
await chr.startNotifications();
} catch (err) {
showStatus(err.name + ': ' + err.message);
}
});Observações: Assinatura bruta wbRequestDevice(requestId, optionsJson); a resposta volta para o polyfill, não para a página. Chame requestDevice a partir de um toque. Os filtros usam services (deve ser anunciado), name (exato) e namePrefix; um filtro corresponde quando todas as suas chaves correspondem, e o dispositivo corresponde quando qualquer filtro corresponde. Sem filters nem acceptAllDevices → TypeError. Cancelar o seletor rejeita com NotFoundError. O seletor busca por 30 segundos. device.id é o endereço Bluetooth do dispositivo.
wbWrite ponte#
window.WebToApk.wbWrite(
Transporte bruto do WebBluetoothPolyfill. Uma página nunca chama isso diretamente - ela chama navigator.bluetooth, exatamente como faria em um navegador.
Descrito por seu grupo, Web Bluetooth (navigator.bluetooth), e não separadamente.
Exemplo
Transporte interno por trás de characteristic.writeValue(), writeValueWithResponse() e writeValueWithoutResponse(). As páginas usam navigator.bluetooth; não chame isto diretamente.
Retorna: (pela característica) uma Promise de undefined. Requer: Bluetooth (ativado por uma build ZIP ou HTML quando seu código menciona navigator.bluetooth).
Com resposta (writeValue funciona do mesmo jeito): resolve quando o dispositivo confirma a gravação.
async function setTargetPower(server, watts) {
var ftms = await server.getPrimaryService('fitness_machine');
var cp = await ftms.getCharacteristic('00002ad9-0000-1000-8000-00805f9b34fb'); // FTMS control point
await cp.writeValueWithResponse(new Uint8Array([0x00])); // request control
var cmd = new DataView(new ArrayBuffer(3));
cmd.setUint8(0, 0x05); // set target power
cmd.setInt16(1, watts, true);
await cp.writeValueWithResponse(cmd);
}Sem resposta: mais rápido, para fluxos em que perder um pacote não importa.
async function sendText(characteristic, text) {
if (!characteristic.properties.writeWithoutResponse) throw new Error('This characteristic needs writeValue');
await characteristic.writeValueWithoutResponse(new TextEncoder().encode(text));
}Envie um comando de texto longo em pedaços de 20 bytes. O app não pede ao dispositivo um tamanho de pacote maior, então 20 bytes é o que cabe em uma gravação:
async function sendLine(rx, text) {
var bytes = new TextEncoder().encode(text + '\n');
for (var i = 0; i < bytes.length; i += 20) {
await rx.writeValueWithoutResponse(bytes.subarray(i, i + 20));
}
}
// sendLine(rxCharacteristic, 'SET COLOR 255 120 0 BRIGHTNESS 80');Observações: Assinatura bruta wbWrite(requestId, deviceId, service, characteristic, valueBase64, withResponse). O valor pode ser um ArrayBuffer, qualquer typed array, um DataView ou um array simples de bytes; qualquer outra coisa lança TypeError. Erros: NotSupportedError (gravação rejeitada), NetworkError (gravação falhou ou não está conectado), NotFoundError.