Created
August 10, 2015 12:20
-
-
Save janjongboom/78f6e45bc3b4133193ff to your computer and use it in GitHub Desktop.
Scan Uri Beacons with Web Bluetooth
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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