Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Scan Uri Beacons with Web Bluetooth
navigator.mozBluetooth.defaultAdapter.startLeScan([]).then(handle => {
console.log('Start scanning', handle);
handle.ondevicefound = e=> {
var uri = parseUriBeacon(e.scanRecord);
if (uri) {
return console.log('Found UriBeacon', uri);
}
}
setTimeout(() => {
console.log('Stop scanning');
navigator.mozBluetooth.defaultAdapter.stopLeScan(handle)
}, 5000);
}, err => console.error(err))
function parseUriBeacon(scanRecord) {
var data = new Uint8Array(scanRecord);
for (var b = 0; b < 8; b++) {
if (data[b] === 0x03 && data[b + 1] === 0x03 &&
data[b + 2] === 0xd8 && data[b + 3] === 0xfe) {
break;
}
}
if (b === 8) {
return false;
}
var schemes = [
'http://www.',
'https://www.',
'http://',
'https://',
'urn:uuid:'
];
var expansions = [
'.com/',
'.org/',
'.edu/',
'.net/',
'.info/',
'.biz/',
'.gov/',
'.com',
'.org',
'.edu',
'.net',
'.info',
'.biz',
'.gov',
];
b += 4;
var adLength = data[b++];
var adType = data[b++];
b += 2; // skip Service UUID
var flags = data[b++];
var txPower = data[b++];
var scheme = data[b++];
var text = schemes[scheme];
// it has been 0x06 bytes since we read adLength, so take that into account
for (var i = b, c = data[i]; i < b + adLength - 0x06; c = data[++i]) {
if (c < expansions.length) {
text += expansions[c];
}
else {
text += String.fromCharCode(c);
}
}
return text;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment