2014年6月24日火曜日

AndroidでiBeacon(2)

前回「AndroidでiBeacon(1)」の続きで、今回は検出したBeaconから情報を取得します
取得するのは

  • UUID
  • major
  • minor
  • 電波強度

の4つです

端末を検出したらコールバックされるBluetoothAdapter.LeScanCallbackのonLeScanを変更していきます

onLeScanには3つの引数があり、UUIDなどの情報は第3引数のbyte配列に入っています

その配列は次のようになっています

データ構造


01ブロック目のバイト数
1
フラグ
2
32ブロック目のバイト数
4AD Type
5
会社ID
0x00CがAPPLE
6
7データタイプ0x02がiBeacon
8iBeaconデータのバイト数
9
UUID
16バイト
~
24
25
major
4バイト
26
27
minor
4バイト
28
29電波強度距離計算する際の基準値として利用

データを取得

onLeScanの中身を変更しています


    private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
        @Override
        public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
            if (scanRecord.length > 30) {
                //このif文でiBeaconかどうかを判別
                if ((scanRecord[5] == (byte) 0x4c) && (scanRecord[6] == (byte) 0x00)
                        && (scanRecord[7] == (byte) 0x02) && (scanRecord[8] == (byte) 0x15)) {
                    String uuid = getScanData(9, 24, scanRecord);
                    String major = getScanData(25, 26, scanRecord);
                    String minor = getScanData(27, 28, scanRecord);
                    String strength = String.valueOf(scanRecord[29]);
                    Log.d("BeaconSample", "-----------------------------");
                    Log.d("BeaconSample", "uuid::" + uuid);
                    Log.d("BeaconSample", "major::" + major);
                    Log.d("BeaconSample", "minor::" + minor);
                    Log.d("BeaconSample", "strength::" + strength);
                    Log.d("BeaconSample", "rssi::" + rssi);
                }
            }
        }
    };

    public String getScanData(int start, int end, byte[] scanRecord) {
        StringBuilder result = new StringBuilder(end - start);
        for (int i = start; i <= end; i++) {
            result.append(convertHex(scanRecord[i] & 0xff));
        }
        return result.toString();
    }

    public String convertHex(int i) {
        char hexArray[] = {
                Character.forDigit((i >> 4) & 0x0f, 16), Character.forDigit(i & 0x0f, 16)
        };
        return new String(hexArray).toUpperCase();
    }

データの取得は以上です

配列の中にある電波強度は基準値なので変化しません
実際の電波強度は第2引数のrssiになります



次回は、Androidで使えるライブラリを探してライブラリを利用方法などを紹介したいと思います

0 コメント:

コメントを投稿