Подтвердить что ты не робот

Работа с BLE Android 4.3 Как написать характеристики?

Я работаю над проектом BLE (приложение для Android) с использованием Android 4.3 API, я использовал образец приложения BLE, это только характеристики чтения в DeviceControlActivity.activity, но я хочу писать характеристики и отправлять их на чип BLE при нажатии кнопки кнопка. Как я могу написать данные на чипе cc2540.. В принципе, я не знаю пошаговой процедуры записи характеристик.

write Я могу видеть только имя и идентификатор устройства со следующим фрагментом кода в DeviceControlActivity

 private final ExpandableListView.OnChildClickListener servicesListClickListner =
        new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView parent, View v, int groupPosition,
                                        int childPosition, long id) {
                if (mGattCharacteristics != null) {
                    final BluetoothGattCharacteristic characteristic =
                            mGattCharacteristics.get(groupPosition).get(childPosition);
                    final int charaProp = characteristic.getProperties();
                    if ((charaProp | BluetoothGattCharacteristic.PROPERTY_READ) > 0) {
                        // If there is an active notification on a characteristic, clear
                        // it first so it doesn't update the data field on the user interface.
                        if (mNotifyCharacteristic != null) {
                            mBluetoothLeService.setCharacteristicNotification(
                                    mNotifyCharacteristic, false);
                            mNotifyCharacteristic = null;
                        }
                        mBluetoothLeService.readCharacteristic(characteristic);
                        showDialog("reading");
                    }

                    if ((charaProp | BluetoothGattCharacteristic.PROPERTY_WRITE) > 0) {
                        // If there is an active notification on a characteristic, clear
                        // it first so it doesn't update the data field on the user interface.
                        if (mNotifyCharacteristic != null) {
                            mBluetoothLeService.setCharacteristicNotification(
                                    mNotifyCharacteristic, false);
                            mNotifyCharacteristic = null;
                        }
                        mBluetoothLeService.writeCharacteristic(characteristic);
                        showDialog("writing");
                        //characteristic.setValue(bytes);
                        //characteristic.setValue("testing");
                        //characteristic.setWriteType(BluetoothGattCharacteristic.PERMISSION_WRITE);
                    }
                    if ((charaProp | BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) {
                        mNotifyCharacteristic = characteristic;
                        mBluetoothLeService.setCharacteristicNotification(
                                characteristic, true);
                    }

                    byte[] value = {0x00, (byte) (0xB9) , 0x0D, (byte) (0x90), 0x2F};
                    if(!characteristic.setValue(value)) 
                    {
                        Log.w(TAG, "Couldn't set characteristic local value"); 
                        //return;
                    }

                    characteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE);
                    /*if(!writeCharacteristic.writeCharacteristic(characteristic))
                    { 
                        Log.w(TAG, "Couldn't write characteristic");
                    }*/

                    return true;
                }
                return false;
            }
};
4b9b3361

Ответ 1

Следующий код представляет собой запись с использованием данных byte[]:

    public boolean writeCharacteristic(){

    //check mBluetoothGatt is available
    if (mBluetoothGatt == null) {
        Log.e(TAG, "lost connection");
        return false;
    }
    BluetoothGattService Service = mBluetoothGatt.getService(your Services);
    if (Service == null) {
        Log.e(TAG, "service not found!");
        return false;
    }
    BluetoothGattCharacteristic charac = Service
            .getCharacteristic(your characteristic);
    if (charac == null) {
        Log.e(TAG, "char not found!");
        return false;
    }

    byte[] value = new byte[1];
    value[0] = (byte) (21 & 0xFF);
    charac.setValue(value);
    boolean status = mBluetoothGatt.writeCharacteristic(charac);
    return status;
}

Ответ 2

Обратите внимание, что логика ИЛИ в:
if ((charaProp | BluetoothGattCharacteristic.PROPERTY_READ) > 0) "в исходном сообщении должно быть логическое И для проверки разрешений на работу. То же самое для второго сравнения charaProp. В противном случае утверждения bot истинны независимо от фактического разрешения.

Ответ 3

Следующий код представляет собой запись с использованием данных string в формате utf-8:

public void writeCharacteristic(BluetoothGattCharacteristic characteristic,
            String data) {
        if (mBluetoothAdapter == null || mBluetoothGatt == null) {
            Log.w(TAG, "BluetoothAdapter not initialized");
            return;
        }

        Log.i(TAG, "characteristic " + characteristic.toString());
        try {
            Log.i(TAG, "data " + URLEncoder.encode(data, "utf-8"));

            characteristic.setValue(URLEncoder.encode(data, "utf-8"));

            // TODO
            mBluetoothGatt.writeCharacteristic(characteristic);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

Надеюсь, что это поможет!

Ответ 4

public boolean writeCharacteristic(byte value[],int type){
    //check mBluetoothGatt is available
    if (mBluetoothGatt == null) {
        Log.e(TAG, "lost connection");
        return false;
    }
    BluetoothGattService Service = mBluetoothGatt.getService(UUID_SIMPLESERVICE);
    if (Service == null) {
        Log.e(TAG, "service not found!");
        //////////NO service found...........
         return false;
    }
    BluetoothGattCharacteristic charac1 = null;
    boolean status1 = false;

    if(type==1) {
        charac1 = Service.getCharacteristic(UUID_PORT1);
        charac1.setValue(value);
        status1 = mBluetoothGatt.writeCharacteristic(charac1);
        Log.v("________BLESERVICE____", "___WRITE CHARATERISTICS STATUS:_________"+status1);
        onReliableWriteCompleted(status1);
    }
    if (charac1 == null) {
        Log.e(TAG, "char not found!");
        return false;
    }

    Log.v("___TYPE___","______________________"+type);
    return status1;
}