Example usage for android.bluetooth BluetoothGatt writeCharacteristic

List of usage examples for android.bluetooth BluetoothGatt writeCharacteristic

Introduction

In this page you can find the example usage for android.bluetooth BluetoothGatt writeCharacteristic.

Prototype

public boolean writeCharacteristic(BluetoothGattCharacteristic characteristic) 

Source Link

Document

Writes a given characteristic and its values to the associated remote device.

Usage

From source file:ble.AndroidBle.java

@Override
public boolean writeCharacteristic(String address, BleGattCharacteristic characteristic) {
    BluetoothGatt gatt = mBluetoothGatts.get(address);
    if (gatt == null) {
        return false;
    }//from   w  w  w.j  a  va 2 s . c o m

    Log.d("blelib", new String(Hex.encodeHex(characteristic.getGattCharacteristicA().getValue())));
    return gatt.writeCharacteristic(characteristic.getGattCharacteristicA());
}

From source file:com.google.android.apps.forscience.ble.MyBleService.java

void writeValue(String address, BluetoothGattCharacteristic theCharacteristic, byte[] value) {
    BluetoothGatt bluetoothGatt = addressToGattClient.get(address);
    if (bluetoothGatt == null) {
        Log.w(TAG, "No connection found for: " + address);
        sendGattBroadcast(address, BleEvents.WRITE_CHAR_FAIL, null);
        return;//from w w  w.j  av  a2s.c o  m
    }
    theCharacteristic.setValue(value);
    bluetoothGatt.writeCharacteristic(theCharacteristic);
}

From source file:com.umundus.service.NCallServiceOld.java

public void writePacket(final BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic,
        final byte[] buffer, final int size) {
    byte[] locBuffer = buffer;
    if (buffer.length != size) {
        locBuffer = new byte[size];
        System.arraycopy(buffer, 0, locBuffer, 0, size);
    }/*from   w  w w  .  j  ava 2s  .  c o m*/
    characteristic.setValue(locBuffer);
    gatt.writeCharacteristic(characteristic);
    Log.i(TAG, "writePacket " + characteristic.getUuid());
}

From source file:no.nordicsemi.android.nrftoolbox.dfu.DfuService.java

/**
 * Writes the operation code to the characteristic. This method is SYNCHRONOUS and wait until the
 * {@link BluetoothGattCallback#onCharacteristicWrite(BluetoothGatt, BluetoothGattCharacteristic, int)} will be called or the connection state will change from {@link #STATE_CONNECTED_AND_READY}.
 * If connection state will change, or an error will occur, an exception will be thrown.
 * /* w ww .  j a  va 2  s. co m*/
 * @param gatt
 *            the GATT device
 * @param characteristic
 *            the characteristic to write to. Should be the DFU CONTROL POINT
 * @param value
 *            the value to write to the characteristic
 * @throws DeviceDisconnectedException
 * @throws DfuException
 * @throws UploadAbortedException
 */
private void writeOpCode(final BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic,
        final byte[] value) throws DeviceDisconnectedException, DfuException, UploadAbortedException {
    mReceivedData = null;
    mErrorState = 0;
    mRequestCompleted = false;

    characteristic.setValue(value);
    gatt.writeCharacteristic(characteristic);

    // We have to wait for confirmation
    try {
        synchronized (mLock) {
            while ((mRequestCompleted == false && mConnectionState == STATE_CONNECTED_AND_READY
                    && mErrorState == 0 && !mAborted) || mPaused)
                mLock.wait();
        }
    } catch (final InterruptedException e) {
        loge("Sleeping interrupted", e);
    }
    if (mAborted)
        throw new UploadAbortedException();
    if (mErrorState != 0)
        throw new DfuException("Unable to write Op Code " + value[0], mErrorState);
    if (mConnectionState != STATE_CONNECTED_AND_READY)
        throw new DeviceDisconnectedException("Unable to write Op Code " + value[0], mConnectionState);
}

From source file:no.nordicsemi.android.nrftoolbox.dfu.DfuService.java

/**
 * Writes the buffer to the characteristic. The maximum size of the buffer is 20 bytes. This method is ASYNCHRONOUS and returns immediately after adding the data to TX queue.
 * //from w w  w  .  j  a  va2 s .  c  o  m
 * @param gatt
 *            the GATT device
 * @param characteristic
 *            the characteristic to write to. Should be the DFU PACKET
 * @param buffer
 *            the buffer with 1-20 bytes
 * @param size
 *            the number of bytes from the buffer to send
 */
private void writePacket(final BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic,
        final byte[] buffer, final int size) {
    byte[] locBuffer = buffer;
    if (buffer.length != size) {
        locBuffer = new byte[size];
        System.arraycopy(buffer, 0, locBuffer, 0, size);
    }
    characteristic.setValue(locBuffer);
    gatt.writeCharacteristic(characteristic);
    // FIXME BLE buffer overflow
    // after writing to the device with WRITE_NO_RESPONSE property the onCharacteristicWrite callback is received immediately after writing data to a buffer.
    // The real sending is much slower than adding to the buffer. This method does not return false if writing didn't succeed.. just the callback is not invoked.
    // 
    // More info: this works fine on Nexus 5 (Andorid 4.4) (4.3 seconds) and on Samsung S4 (Android 4.3) (20 seconds) so this is a driver issue.
    // Nexus 4 and 7 uses Qualcomm chip, Nexus 5 and Samsung uses Broadcom chips.
}

From source file:no.nordicsemi.android.nrftoolbox.dfu.DfuService.java

/**
 * Writes the image size to the characteristic. This method is SYNCHRONOUS and wait until the {@link BluetoothGattCallback#onCharacteristicWrite(BluetoothGatt, BluetoothGattCharacteristic, int)}
 * will be called or the connection state will change from {@link #STATE_CONNECTED_AND_READY}. If connection state will change, or an error will occur, an exception will be thrown.
 * //from ww w.j a  va2 s. c  o m
 * @param gatt
 *            the GATT device
 * @param characteristic
 *            the characteristic to write to. Should be the DFU PACKET
 * @param imageSize
 *            the image size in bytes
 * @throws DeviceDisconnectedException
 * @throws DfuException
 * @throws UploadAbortedException
 */
private void writeImageSize(final BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic,
        final int imageSize) throws DeviceDisconnectedException, DfuException, UploadAbortedException {
    mReceivedData = null;
    mErrorState = 0;
    mImageSizeSent = false;

    characteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE);
    characteristic.setValue(imageSize, BluetoothGattCharacteristic.FORMAT_UINT32, 0);
    gatt.writeCharacteristic(characteristic);

    // We have to wait for confirmation
    try {
        synchronized (mLock) {
            while ((mImageSizeSent == false && mConnectionState == STATE_CONNECTED_AND_READY && mErrorState == 0
                    && !mAborted) || mPaused)
                mLock.wait();
        }
    } catch (final InterruptedException e) {
        loge("Sleeping interrupted", e);
    }
    if (mAborted)
        throw new UploadAbortedException();
    if (mErrorState != 0)
        throw new DfuException("Unable to write Image Size", mErrorState);
    if (mConnectionState != STATE_CONNECTED_AND_READY)
        throw new DeviceDisconnectedException("Unable to write Image Size", mConnectionState);
}

From source file:com.nbplus.iotapp.bluetooth.BluetoothLeService.java

public boolean writeRemoteCharacteristic(String address, String serviceUuid, String characteristicUuid,
        byte[] value) {
    Log.d(TAG, "writeRemoteCharacteristic add = " + address + ", svc = " + serviceUuid + ", char = "
            + characteristicUuid);//from  w  w  w .  j  a  va2s .c  o  m
    if (StringUtils.isEmptyString(address) || StringUtils.isEmptyString(serviceUuid)
            || StringUtils.isEmptyString(characteristicUuid)) {
        Log.w(TAG, "Unknown parameter");
        return false;
    }
    if (value == null) {
        Log.w(TAG, "value is empty");
        return false;
    }
    BluetoothGatt bluetoothGatt = mConnectedBluetoothGattMap.get(address);

    if (mBluetoothAdapter == null || bluetoothGatt == null) {
        Log.w(TAG, "BluetoothAdapter not initialized");
        return false;
    }
    BluetoothGattService service = bluetoothGatt.getService(UUID.fromString(serviceUuid));
    if (service == null) {
        Log.w(TAG, "Service not found.");
        return false;
    }
    BluetoothGattCharacteristic characteristic = service.getCharacteristic(UUID.fromString(characteristicUuid));
    if (characteristic == null) {
        Log.w(TAG, "characteristic not found.");
        return false;
    }

    characteristic.setValue(value);
    boolean result = bluetoothGatt.writeCharacteristic(characteristic);
    Log.d(TAG, "Write charac uuid = " + characteristic.getUuid().toString() + ", result = " + result);

    return result;
}

From source file:com.wolkabout.hexiwear.service.BluetoothService.java

private void createGATT(final BluetoothDevice device) {
    bluetoothGatt = device.connectGatt(this, true, new BluetoothGattCallback() {
        @Override//from   ww  w.j  av a 2  s.co m
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            isConnected = BluetoothProfile.STATE_CONNECTED == newState;
            if (isConnected) {
                Log.i(TAG, "GATT connected.");
                startForeground(442, getNotification(device));
                gatt.discoverServices();
            } else {
                Log.i(TAG, "GATT disconnected.");
                NotificationService_.intent(BluetoothService.this).stop();
                notificationManager.notify(442, getNotification(device));
                gatt.connect();
            }

            final Intent connectionStateChanged = new Intent(CONNECTION_STATE_CHANGED);
            connectionStateChanged.putExtra(CONNECTION_STATE, isConnected);
            sendBroadcast(connectionStateChanged);
        }

        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            Log.i(TAG, "Services discovered.");
            if (status == BluetoothGatt.GATT_INSUFFICIENT_AUTHENTICATION) {
                handleAuthenticationError(gatt);
                return;
            }

            discoverCharacteristics(gatt);
        }

        @Override
        public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic,
                int status) {
            Log.i(TAG, "Characteristic written: " + status);

            if (status == BluetoothGatt.GATT_INSUFFICIENT_AUTHENTICATION) {
                handleAuthenticationError(gatt);
                return;
            }

            final byte command = characteristic.getValue()[0];
            switch (command) {
            case WRITE_TIME:
                Log.i(TAG, "Time written.");
                final BluetoothGattCharacteristic batteryCharacteristic = readableCharacteristics
                        .get(Characteristic.BATTERY.getUuid());
                gatt.setCharacteristicNotification(batteryCharacteristic, true);
                for (BluetoothGattDescriptor descriptor : batteryCharacteristic.getDescriptors()) {
                    if (descriptor.getUuid().toString().startsWith("00002904")) {
                        descriptor.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
                        gatt.writeDescriptor(descriptor);
                    }
                }
                break;
            case WRITE_NOTIFICATION:
                Log.i(TAG, "Notification sent.");
                if (notificationsQueue.isEmpty()) {
                    Log.i(TAG, "Reading characteristics...");
                    readNextCharacteristics(gatt);
                } else {
                    Log.i(TAG, "writing next notification...");
                    alertIn.setValue(notificationsQueue.poll());
                    gatt.writeCharacteristic(alertIn);
                }
                break;
            default:
                Log.w(TAG, "No such ALERT IN command: " + command);
                break;
            }
        }

        @Override
        public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
            readCharacteristic(gatt, Characteristic.MANUFACTURER);
        }

        @Override
        public void onCharacteristicRead(BluetoothGatt gatt,
                final BluetoothGattCharacteristic gattCharacteristic, int status) {
            if (status == BluetoothGatt.GATT_INSUFFICIENT_AUTHENTICATION) {
                handleAuthenticationError(gatt);
                return;
            }

            final String characteristicUuid = gattCharacteristic.getUuid().toString();
            final Characteristic characteristic = Characteristic.byUuid(characteristicUuid);
            switch (characteristic) {
            case MANUFACTURER:
                manufacturerInfo.manufacturer = gattCharacteristic.getStringValue(0);
                readCharacteristic(gatt, Characteristic.FW_REVISION);
                break;
            case FW_REVISION:
                manufacturerInfo.firmwareRevision = gattCharacteristic.getStringValue(0);
                readCharacteristic(gatt, Characteristic.MODE);
                break;
            default:
                Log.v(TAG, "Characteristic read: " + characteristic.name());
                if (characteristic == Characteristic.MODE) {
                    final Mode newMode = Mode.bySymbol(gattCharacteristic.getValue()[0]);
                    if (mode != newMode) {
                        onModeChanged(newMode);
                    }
                } else {
                    onBluetoothDataReceived(characteristic, gattCharacteristic.getValue());
                }

                if (notificationsQueue.isEmpty()) {
                    readNextCharacteristics(gatt);
                } else {
                    alertIn.setValue(notificationsQueue.poll());
                    gatt.writeCharacteristic(alertIn);
                }

                break;
            }
        }

        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt,
                BluetoothGattCharacteristic gattCharacteristic) {
            final String characteristicUuid = gattCharacteristic.getUuid().toString();
            final Characteristic characteristic = Characteristic.byUuid(characteristicUuid);
            Log.d(TAG, "Characteristic changed: " + characteristic);

            if (characteristic == Characteristic.BATTERY) {
                onBluetoothDataReceived(Characteristic.BATTERY, gattCharacteristic.getValue());
            }
        }
    });
}