Skip to content

Instantly share code, notes, and snippets.

@sole
Forked from janjongboom/ibeacon.js
Last active August 29, 2015 14:21

Revisions

  1. @janjongboom janjongboom revised this gist May 18, 2015. 1 changed file with 3 additions and 3 deletions.
    6 changes: 3 additions & 3 deletions ibeacon.js
    Original file line number Diff line number Diff line change
    @@ -1,14 +1,14 @@
    navigator.mozBluetooth.defaultAdapter.startLeScan([]).then(handle => {
    console.log('got handle yo', handle);
    console.log('Start scanning', handle);
    handle.ondevicefound = e=> {
    var record = parseScanRecord(e.scanRecord);
    if (record) {
    console.log('Found it yo!', record.uuid, record.major, record.minor, e.rssi);
    console.log('Found an iBeacon', record.uuid, record.major, record.minor, e.rssi);
    }
    }

    setTimeout(() => {
    console.log('stop scan');
    console.log('Stop scanning');
    navigator.mozBluetooth.defaultAdapter.stopLeScan(handle)
    }, 5000);

  2. @janjongboom janjongboom created this gist May 18, 2015.
    55 changes: 55 additions & 0 deletions ibeacon.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,55 @@
    navigator.mozBluetooth.defaultAdapter.startLeScan([]).then(handle => {
    console.log('got handle yo', handle);
    handle.ondevicefound = e=> {
    var record = parseScanRecord(e.scanRecord);
    if (record) {
    console.log('Found it yo!', record.uuid, record.major, record.minor, e.rssi);
    }
    }

    setTimeout(() => {
    console.log('stop scan');
    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('');
    }