2015年8月21日金曜日

How to parse Eddystone packets (Android)

It's easy if you use nv-bluetooth library. onLeScan method would be implemented like the following.


public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord)
{
    // Parse the payload part of an advertisement packet.
    List<ADStructure> structures =
        ADPayloadParser.getInstance().parse(scanRecord);
 
    // For each AD structure contained in the packet.
    for (ADStructure structure : structures)
    {
        if (structure instanceof EddystoneUID)
        {
            // Eddystone UID
            EddystoneUID es = (EddystoneUID)structure;

            // Beacon ID (= Namespace ID + Instance ID)
            // byte[] beaconId = es.getBeaconId();
            String beaconId = es.getBeaconIdAsString();

            // Namespace ID
            // byte[] namespaceId = es.getNamespaceId();
            String namespaceId = es.getNamespaceIdAsString();

            // Instance ID
            // byte[] instanceId = es.getInstanceId();
            String instanceId = es.getInstanceIdAsString();

            // Tx Power
            int power = es.getTxPower();
        }
        else if (structure instanceof EddystoneURL)
        {
            // Eddystone URL
            EddystoneURL es = (EddystoneURL)structure;

            // URL
            URL url = es.getURL();

            // Tx Power
            int power = es.getTxPower();
        }
        else if (structure instanceof EddystoneTLM)
        {
            // Eddystone TLM
            EddystoneTLM es = (EddystoneTLM)structure;

            // TLM Version
            int version = es.getTLMVersion();

            // Battery Voltage
            int voltage = es.getBatteryVoltage();

            // Beacon Temperature
            float temperature = es.getBeaconTemperature();

            // The number of advertisement packets since power-on or reboot.
            long count = es.getAdvertisementCount();

            // The elapsed time since power-on or reboot.
            long time = es.getElapsedTime();
        }
        else if (structure instanceof IBeacon)
        {
            // In passing, iBeacon
            IBeacon iBeacon = (IBeacon)structure;

            // Major Number
            int major = iBeacon.getMajor();

            // Minor Number
            int minor = iBeacon.getMinor();

            // Proximity UUID
            UUID uuid = iBeacon.getUUID();

            // Tx Power
            int power = iBeacon.getPower();
        }
    }
}


All you need to do to use nv-bluetooth is to add one line shown below into dependencies block in build.gradle.

compile 'com.neovisionaries:nv-bluetooth:1.6'


Links