какой UUID следует использовать для чтения характеристик с определенного устройства Bluetooth?

какой UUID следует использовать для чтения характеристик с определенного устройства Bluetooth? Насколько я знаю, для этого не нужно сопряжение, я должен подключиться к устройству и получить данные

Мой код правильный?

Также mBluetoothGattService равно нулю!

Как я могу получить данные с конкретного устройства?

        if (action.equals(BluetoothDevice.ACTION_FOUND)) {
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            if (device.getName() != null && device.getName().equals(BluetoothName)) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                    Log.d(TAG, "onReceive: " + device.getName() + ": " + device.getAddress());
                    if (device.getUuids() != null) {
                        for (int i = 0; i <= device.getUuids().length; i++) {
                            Log.d(TAG, "onReceive: " + device.getUuids()[i].getUuid().toString());
                        }
                    }
                    BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
                    if (!mBluetoothAdapter.isEnabled()) {
                        return;
                    }
                    device.connectGatt(context, true, new BluetoothGattCallback() {
                        @Override
                        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
                            super.onServicesDiscovered(gatt, status);
                            if (status == BluetoothGatt.GATT_SUCCESS) {
                                BluetoothGattService mBluetoothGattService = mBluetoothGatt.getService(BTMODULEUUID);
                                if (mBluetoothGattService != null) {
                                    Log.i(TAG, "Service characteristic UUID found : " + mBluetoothGattService.getUuid().toString());
                                } else {
                                    Log.i(TAG, "Service characteristic not found for UUID : " + BTMODULEUUID);
                                }
                            }
                        }

                        @Override
                        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
                            if (newState == BluetoothGatt.STATE_CONNECTED) {
                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                                    gatt.requestMtu(512);
                                }
                            }
                            mBluetoothGatt = gatt;
                            Log.d(TAG, "discoverServices Size : " + mBluetoothGatt.getServices().size());
                            for (BluetoothGattService s : mBluetoothGatt.getServices()) {
                                Log.d(TAG, "discoverServices : found " + s.getUuid());
                                for (BluetoothGattCharacteristic c : s.getCharacteristics()) {
                                    Log.d(TAG, "--> characteristic : " + c.getUuid() + ":" + String.format("%x", c.getInstanceId()));
                                }
                            }

                            super.onConnectionStateChange(gatt, status, newState);
                            Log.d(TAG, "onReceive connectGatt.");
                            readCustomCharacteristic(mBluetoothAdapter);
                        }
                    });
                }
            }
        }

public void readCustomCharacteristic(BluetoothAdapter mBluetoothAdapter) {
    if (mBluetoothAdapter == null) {
        return;
    }
    if (mBluetoothGatt == null) {
        return;
    }
    // Is the service available on the device
    BluetoothGattService mCustomService = mBluetoothGatt.getService(convertUuidFromInteger(0x181D));// BTMODULEUUID not worked too
    if (mCustomService == null) {
        Log.w(TAG, "Custom BLE Service not found");
        return;
    }
    // Read the characteristic from the service
    BluetoothGattCharacteristic mReadCharacteristic = mCustomService.getCharacteristic(BTMODULEUUID);
    if (!mBluetoothGatt.readCharacteristic(mReadCharacteristic)) {
        Log.w(TAG, "Failed to read characteristic");
    }
}

LogCat показывает:

D: DiscoverServices Размер: 0

D: onReceive connectGatt.

W: Пользовательская служба BLE не найдена

Описание устройства


person Hossein Kurd    schedule 14.01.2019    source источник
comment
which UUID это то, что должна содержать документация specific Bluetooth device. Никто этого не знает.   -  person Vladyslav Matviienko    schedule 14.01.2019
comment
пожалуйста, взгляните на изображение   -  person Hossein Kurd    schedule 14.01.2019
comment
использовать полный UUID сервиса   -  person Vladyslav Matviienko    schedule 14.01.2019
comment
Что ты имеешь в виду? Unknown Service UUID не работает   -  person Hossein Kurd    schedule 14.01.2019
comment
правильно ли получить BluetoothGatt в onConnectionStateChange внутри BroadcastReceiver?   -  person Hossein Kurd    schedule 14.01.2019


Ответы (1)


наконец, я решил это.

Код такой:

final String action = intent.getAction();
            if (action == null || action.isEmpty()) {
                return;
            }
            // Log.d(TAG, "onReceive action : " + action);
            if (action.equals(BluetoothDevice.ACTION_FOUND)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                // Log.d(TAG, "onReceive : " + device.getName() + ": " + device.getAddress());
                if (DEVICE_NAME_FORCE_PLATE.equals(device.getName())) {
                    connectToForcePlate(context, device);

                }
            }

private void connectToForcePlate(Context context, BluetoothDevice device) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        Log.d(TAG, "connectToForcePlate Device Name : " + device.getName() + " Device address : " + device.getAddress());
        if (device.getUuids() != null) {
            for (int i = 0; i <= device.getUuids().length; i++) {
                Log.d(TAG, "connectToForcePlate Device UUID #" + i + " : " + device.getUuids()[i].getUuid().toString());
            }
        }
        BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (!mBluetoothAdapter.isEnabled()) {
            return;
        }
        device.connectGatt(context, false, new BluetoothGattCallback() {
            @Override
            public void onServicesDiscovered(BluetoothGatt gatt, int status) {
                super.onServicesDiscovered(gatt, status);
                Log.i(TAG, "onServicesDiscovered Status : " + status);
                if (status == BluetoothGatt.GATT_SUCCESS) {
                    BluetoothGattService mBluetoothGattService = mBluetoothGatt.getService(convertUuidFromInteger(0x181D));
                    if (mBluetoothGattService == null) {
                        Log.i(TAG, "onServicesDiscovered Service characteristic not found for UUID : " + SERVICE_UUID);
                        return;
                    }
                    Log.i(TAG, "onServicesDiscovered Service characteristic UUID found : " + mBluetoothGattService.getUuid().toString());
                    // streamBytes(device);
                    // read  the characteristic from the service
                    BluetoothGattCharacteristic mBluetoothGattCharacteristic = mBluetoothGattService.getCharacteristic(CHARACTERISTIC_UUID);
                    if (!mBluetoothGatt.readCharacteristic(mBluetoothGattCharacteristic)) {
                        Log.w(TAG, "onServicesDiscovered Failed to read characteristic");
                        return;
                    }
                    Log.i(TAG, "onServicesDiscovered Succeed to read characteristic");
                    // Log.i(TAG, "onServicesDiscovered Byte : " + mReadCharacteristic.getValue().length);

                }
            }

            @Override
            public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
                super.onCharacteristicRead(gatt, characteristic, status);
                Log.w(TAG, "onCharacteristicRead ******************************");
                if (!gatt.readCharacteristic(characteristic)) {
                    Log.w(TAG, "onCharacteristicRead Failed to read characteristic");
                    return;
                }
                Log.i(TAG, "onCharacteristicRead Succeed to read characteristic");
            }

            @Override
            public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
                if (newState == BluetoothGatt.STATE_CONNECTED) {
                    Log.d(TAG, "onConnectionStateChange CONNECTED.");
                    boolean isDiscoverable = gatt.discoverServices(); // Essential to declare right Here
                    Log.w(TAG, "onConnectionStateChange --> Discover Services : " + isDiscoverable);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        gatt.requestMtu(512);
                    }
                }
                mBluetoothGatt = gatt;
                Log.d(TAG, "onConnectionStateChange --> discoverServices Size : " + mBluetoothGatt.getServices().size());
                for (BluetoothGattService s : mBluetoothGatt.getServices()) {
                    Log.d(TAG, "onConnectionStateChange --> discoverServices : found " + s.getUuid());
                    for (BluetoothGattCharacteristic c : s.getCharacteristics()) {
                        Log.d(TAG, "--> characteristic : " + c.getUuid() + ":" + String.format("%x", c.getInstanceId()));
                    }
                }

                super.onConnectionStateChange(gatt, status, newState);
                Log.d(TAG, "onConnectionStateChange connectGatt.");
            }
        });
    }
}

Посмотрите: gatt.discoverServices()

Строка объявления важна

Не называйте это дважды

person Hossein Kurd    schedule 16.01.2019
comment
Идеальный. Я тоже работаю над тем же. Не могли бы вы указать название весов (модель, производитель), которые поддерживают сервис 0x181D Gatt? Или тот, с которым вы тестировали приведенный выше код? - person Muhammad Idris; 07.06.2020
comment
@MuhammadIdris, вам нужно использовать некоторые приложения, такие как nRF connect, чтобы найти UUID. - person Hossein Kurd; 07.06.2020
comment
У меня есть UUID службы (0x181D) и UUID персонажа (0x2A9D) для шкалы веса. Я хочу приобрести весы BLE, чтобы протестировать с их помощью свое приложение. какое устройство / модель я должен купить? – - person Muhammad Idris; 07.06.2020
comment
У меня нет доступа к деталям оборудования - person Hossein Kurd; 08.06.2020