【问题标题】:Using BLE - Read GATT characteristics使用 BLE - 读取 GATT 特征
【发布时间】:2016-07-26 12:20:27
【问题描述】:

我正在尝试从蓝牙 LE 设备(心率手环)读取 GATT 特征值。它的规格是:

Services

Characteristics

我还没有弄清楚如何“阅读”规范并将它们“翻译”成代码。

我需要在我的应用上显示设备检测到的心跳。读取 GATT 值的方法是什么?一个代码示例将不胜感激:)

按照我的实际源代码。


设置蓝牙连接

    private BluetoothAdapter mBluetoothAdapter;
    private BluetoothGatt mBluetoothGatt;
    private Handler mHandler;

    private static final int REQUEST_ENABLE_BT = 1;
    private static final long SCAN_PERIOD = 10000;

    // ...

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bluetooth);
        mHandler = new Handler();

        // BLE is supported?
        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            Toast.makeText(this, "Bluetooth Low Energy non supportato", Toast.LENGTH_SHORT).show();
            finish();
        }

        final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter = bluetoothManager.getAdapter();

        // Bluetooth is supported?
        if (mBluetoothAdapter == null) {
            Toast.makeText(this, "Bluetooth non supportato", Toast.LENGTH_SHORT).show();
            finish();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        // Bluetooth is enabled?
        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
        }

        scanLeDevice(true);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mBluetoothAdapter != null && mBluetoothAdapter.isEnabled()) {
            scanLeDevice(false);
        }
    }

发现 BLE 设备并连接心率监测器

    // Device scan callback.
    private BluetoothAdapter.LeScanCallback mLeScanCallback =
            new BluetoothAdapter.LeScanCallback() {
                @Override
                public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Log.i(TAG, "Name: " + device.getName() + " (" + device.getAddress() + ")");
                            String deviceAddress = device.getAddress();
                            if (deviceAddress.equals("C0:19:37:54:9F:30")) {
                                connectToDevice(device);
                            }
                        }
                    });
                }
            };

    public void connectToDevice(BluetoothDevice device) {
        if (mBluetoothGatt == null) {
            Log.i(TAG, "Attempting to connect to device " + device.getName() + " (" + device.getAddress() + ")");
            mBluetoothGatt = device.connectGatt(this, true, gattCallback);
            scanLeDevice(false);// will stop after first device detection
        }
    }

    private final BluetoothGattCallback gattCallback = new BluetoothGattCallback() {
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            Log.i(TAG, "Status: " + status);
            switch (newState) {
                case BluetoothProfile.STATE_CONNECTED:
                    Log.i(TAG, "STATE_CONNECTED");
                    //BluetoothDevice device = gatt.getDevice(); // Get device
                    gatt.discoverServices();
                    break;
                case BluetoothProfile.STATE_DISCONNECTED:
                    Log.e(TAG, "STATE_DISCONNECTED");
                    break;
                default:
                    Log.e(TAG, "STATE_OTHER");
            }
        }

        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            List<BluetoothGattService> services = gatt.getServices();
            Log.i(TAG, "Services: " + services.toString());

            BluetoothGattCharacteristic bpm = services.get(2).getCharacteristics().get(0);
            gatt.readCharacteristic(services.get(0).getCharacteristics().get(0));
        }

        @Override
        public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            // my attempt to read and print characteristics
            byte[] charValue = characteristic.getValue();
            byte flag = charValue[0];
            Log.i(TAG, "Characteristic: " + flag);
            //gatt.disconnect();
        }
    };

【问题讨论】:

    标签: android android-bluetooth bluetooth-lowenergy gatt android-ble


    【解决方案1】:

    gattCallback 里面试试这个:

            @Override
            public synchronized void onCharacteristicChanged(BluetoothGatt gatt,
                                                BluetoothGattCharacteristic characteristic) {
    
    
                final byte[] dataInput = characteristic.getValue();
    
    }
    

    编辑

    我认为你会收到一个带有听力数据的字节,使用这个函数来获取 int 值:

    public int unsignedByteToInt(byte b) {
        return b & 0xFF;
    }
    

    并在 onCharacteristicChanged() 内部调用它:

    final byte[] dataInput = characteristic.getValue();
    int hearRate = unsignedByteToInt(dataInput);
    

    编辑 2

    为心率创建通知监听器:

    public void setHeartRateNotification(boolean enable){
    
        String uuidHRCharacteristic = "YOUR CHARACTERISTIC";
    
        BluetoothGattService mBluetoothLeService = null;
        BluetoothGattCharacteristic mBluetoothGattCharacteristic = null;
    
        for (BluetoothGattService service : mBluetoothGatt.getServices()) {
            if ((service == null) || (service.getUuid() == null)) {
    
                continue;
            }
            if (uuidAccelService.equalsIgnoreCase(service.getUuid().toString())) {
    
                mBluetoothLeService = service;
            }
        }
    
        if(mBluetoothLeService!=null) {
            mBluetoothGattCharacteristic =
                    mBluetoothLeService.getCharacteristic(UUID.fromString(uuidHRCharacteristic));
        }
        else{
            Log.i("Test","mBluetoothLeService is null");
        }
    
        if(mBluetoothGattCharacteristic!=null) {
    
            setCharacteristicNotification(mBluetoothGattCharacteristic, enable);
    
            Log.i("Test","setCharacteristicNotification:"+true);
        }
        else{
            Log.i("Test","mBluetoothGattCharacteristic is null");
        }
    
    
    }
    

    并在 gattCallback 中设置 onServiceDiscover:

    @Override
    public void onServicesDiscovered(BluetoothGatt gatt, int status) {
    
        Log.i("Test", "onServicesDiscovered received: " + status);
    
        setHeartRateNotification(true);
    
    }
    

    【讨论】:

    • 我试过你的代码,但应用没有运行 onCharacteristicChanged()。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多