Created
May 18, 2015 12:42
-
-
Save janjongboom/55da4fdaf186e50c9677 to your computer and use it in GitHub Desktop.
iBeacon scanning Firefox OS
This file contains 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 record = parseScanRecord(e.scanRecord); | |
if (record) { | |
console.log('Found an iBeacon', record.uuid, record.major, record.minor, e.rssi); | |
} | |
} | |
setTimeout(() => { | |
console.log('Stop scanning'); | |
navigator.mozBluetooth.defaultAdapter.stopLeScan(handle) | |
}, 5000); | |
}, err => console.error(err)) | |
function parseScanRecord(scanRecord) { | |
var view = new Uint8Array(scanRecord); | |
// Company ID does not have fixed length, so find out where to start by | |
// finding 0x02, 0x15 in byes 4..8 | |
for (var start = 4; start < 8; start++) { | |
if (view[start] === 0x02 && view[start + 1] === 0x15) { | |
break; | |
} | |
} | |
if (start === 8) { | |
return; | |
} | |
// Now UUID is the next 16 bytes right after 0x15 | |
start += 2; | |
var uuid = bytesToHex(view.slice(start, start + 16)); | |
// major / minor are two bytes each | |
start += 16; | |
var major = (view[start] & 0xff) * 0x100 + (view[start + 1] & 0xff); | |
start += 2; | |
var minor = (view[start] & 0xff) * 0x100 + (view[start + 1] & 0xff); | |
return { uuid: uuid, major: major, minor: minor }; | |
} | |
var hexArray = '0123456789ABCDEF'.split(''); | |
function bytesToHex(bytes) { | |
var hex = []; | |
for (var j = 0; j < bytes.length; j++) { | |
var v = bytes[j] & 0xff; | |
hex[j * 2] = hexArray[v >>> 4]; | |
hex[j * 2 + 1] = hexArray[v & 0x0f]; | |
} | |
return hex.join(''); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment