Java Code Examples for android.bluetooth.BluetoothGattCharacteristic#setWriteType()

The following examples show how to use android.bluetooth.BluetoothGattCharacteristic#setWriteType() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BluetoothLeService.java    From openvidonn with GNU General Public License v3.0 6 votes vote down vote up
public void writePersonalInformation(PersonalInfo pinfo) {
    if(mGattCharacteristics == null)
        return;
    BluetoothGattCharacteristic c = mGattCharacteristics.get(VidonnGattAttributes.VIDONN_SERVICE).get(VidonnGattAttributes.VIDONN_PERSONAL_INFO);
    if(c == null) {
        Log.e(TAG, "Could not access VIDONN_PERSONAL_INFO");
        Toast.makeText(getApplication(), R.string.error_writing_to_bracelet, Toast.LENGTH_SHORT).show();
        return;
    }
    Log.d(TAG, "write PersonalInfo = " + pinfo);
    byte packet[] = c.getValue();
    if(packet == null || packet.length < 5) {
        Log.e(TAG, "Invalid characteristic in VIDONN_PERSONAL_INFO ");
        Toast.makeText(getApplication(), R.string.error_writing_to_bracelet, Toast.LENGTH_SHORT).show();
        return;
    }
    packet[1] = (byte) pinfo.height;
    packet[2] = (byte) pinfo.weight;
    packet[3] = (byte) pinfo.getGender();
    packet[4] = (byte) pinfo.age;
    packet[packet.length-1] = calculateChecksum(packet);
    c.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT);
    c.setValue(packet);
    writeCharacteristic(c);
}
 
Example 2
Source File: DeviceServicesActivity.java    From EFRConnect-android with Apache License 2.0 6 votes vote down vote up
/**
 * WRITES BYTE TO OTA CONTROL CHARACTERISTIC
 *****************************************/
public boolean writeOtaControl(byte ctrl) {
    Log.d("writeOtaControl", "Called");

    if (bluetoothGatt.getService(ota_service) != null) {
        BluetoothGattCharacteristic charac = bluetoothGatt.getService(ota_service).getCharacteristic(ota_control);
        if (charac != null) {
            Log.d("Instance ID", "" + charac.getInstanceId());
            charac.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT);
            Log.d("charac_properties", "" + charac.getProperties());
            byte[] control = new byte[1];
            control[0] = ctrl;
            charac.setValue(control);
            bluetoothGatt.writeCharacteristic(charac);
            return true;
        } else {
            Log.d("characteristic", "null");
        }
    } else {
        Log.d("service", "null");
    }
    return false;
}
 
Example 3
Source File: OWDevice.java    From android-ponewheel with MIT License 6 votes vote down vote up
public void setLights(BluetoothUtil bluetoothUtil,int state) {

        lightMode.set(state);
        BluetoothGattCharacteristic lc = null;

        ByteBuffer v = ByteBuffer.allocate(2);
        lc = bluetoothUtil.getCharacteristic(OWDevice.OnewheelCharacteristicLightingMode);

        v.putShort((short) state);
        if (lc != null) {
            lc.setValue(v.array());
            lc.setWriteType(2);
            bluetoothUtil.writeCharacteristic(lc);
            EventBus.getDefault().post(new DeviceStatusEvent("LIGHTS SET TO STATE:" + state));
        }

    }
 
Example 4
Source File: BluetoothLeService.java    From openvidonn with GNU General Public License v3.0 6 votes vote down vote up
public void writeDateTime() {
    if(mGattCharacteristics == null)
        return;
    BluetoothGattCharacteristic c = mGattCharacteristics.get(VidonnGattAttributes.VIDONN_SERVICE).get(VidonnGattAttributes.VIDONN_DATETIME);

    Calendar today = Calendar.getInstance();

    byte packet[] = new byte[8];
    packet[0] = (byte) 0xF5;
    packet[1] = (byte) (today.get(Calendar.YEAR) - 2000);
    packet[2] = (byte) (today.get(Calendar.MONTH));
    packet[3] = (byte) (today.get(Calendar.DAY_OF_MONTH)-1);
    packet[4] = (byte) (today.get(Calendar.HOUR_OF_DAY));
    packet[5] = (byte) (today.get(Calendar.MINUTE));
    packet[6] = (byte) (today.get(Calendar.SECOND));
    packet[packet.length-1] = calculateChecksum(packet);
    c.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT);
    c.setValue(packet);
    writeCharacteristic(c);
}
 
Example 5
Source File: ConnectionImpl.java    From easyble-x with Apache License 2.0 6 votes vote down vote up
private boolean write(GenericRequest request, BluetoothGattCharacteristic characteristic, byte[] value) {
    characteristic.setValue(value);
    int writeType = request.writeOptions.writeType;
    if ((writeType == BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE ||
            writeType == BluetoothGattCharacteristic.WRITE_TYPE_SIGNED ||
            writeType == BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT)) {
        characteristic.setWriteType(writeType);
    }
    if (bluetoothGatt == null) {
        handleFailedCallback(request, REQUEST_FAIL_TYPE_GATT_IS_NULL, true);
        return false;
    }
    if (!bluetoothGatt.writeCharacteristic(characteristic)) {
        handleWriteFailed(request);
        return false;
    }
    return true;
}
 
Example 6
Source File: BLETransport.java    From esp-idf-provisioning-android with Apache License 2.0 5 votes vote down vote up
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {

    super.onServicesDiscovered(gatt, status);

    if (status != BluetoothGatt.GATT_SUCCESS) {
        Log.d(TAG, "Status not success");
        EventBus.getDefault().post(new DeviceConnectionEvent(ESPConstants.EVENT_DEVICE_CONNECTION_FAILED));
        return;
    }

    service = gatt.getService(UUID.fromString(serviceUuid));

    if (service == null) {
        Log.e(TAG, "Service not found!");
        EventBus.getDefault().post(new DeviceConnectionEvent(ESPConstants.EVENT_DEVICE_CONNECTION_FAILED));
        return;
    }

    for (BluetoothGattCharacteristic characteristic : service.getCharacteristics()) {

        if (characteristic == null) {
            Log.e(TAG, "Tx characteristic not found!");
            EventBus.getDefault().post(new DeviceConnectionEvent(ESPConstants.EVENT_DEVICE_CONNECTION_FAILED));
            return;
        }

        String uuid = characteristic.getUuid().toString();
        Log.d(TAG, "Characteristic UUID : " + uuid);
        charUuidList.add(uuid);

        characteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT);
    }

    readNextDescriptor();
}
 
Example 7
Source File: BleConnectWorker.java    From Android-BluetoothKit with Apache License 2.0 5 votes vote down vote up
@Override
    public boolean writeCharacteristicWithNoRsp(UUID service, UUID character, byte[] value) {
        BluetoothLog.v(String.format("writeCharacteristicWithNoRsp for %s: service = 0x%s, character = 0x%s, value = 0x%s",
                mBluetoothDevice.getAddress(), service, character, ByteUtils.byteToString(value)));

        checkRuntime();

        BluetoothGattCharacteristic characteristic = getCharacter(service, character);

        if (characteristic == null) {
            BluetoothLog.e(String.format("characteristic not exist!"));
            return false;
        }

//        if (!isCharacteristicNoRspWritable(characteristic)) {
//            BluetoothLog.e(String.format("characteristic not norsp writable!"));
//            return false;
//        }

        if (mBluetoothGatt == null) {
            BluetoothLog.e(String.format("ble gatt null"));
            return false;
        }

        characteristic.setValue(value != null ? value : ByteUtils.EMPTY_BYTES);
        characteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE);

        if (!mBluetoothGatt.writeCharacteristic(characteristic)) {
            BluetoothLog.e(String.format("writeCharacteristic failed"));
            return false;
        }

        return true;
    }
 
Example 8
Source File: BleManager.java    From Android-nRF-Toolbox with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * There was a bug in Android up to 6.0 where the descriptor was written using parent
 * characteristic's write type, instead of always Write With Response, as the spec says.
 * <p>
 *     See: <a href="https://android.googlesource.com/platform/frameworks/base/+/942aebc95924ab1e7ea1e92aaf4e7fc45f695a6c%5E%21/#F0">
 *         https://android.googlesource.com/platform/frameworks/base/+/942aebc95924ab1e7ea1e92aaf4e7fc45f695a6c%5E%21/#F0</a>
 * </p>
 * @param descriptor the descriptor to be written
 * @return the result of {@link BluetoothGatt#writeDescriptor(BluetoothGattDescriptor)}
 */
private boolean internalWriteDescriptorWorkaround(final BluetoothGattDescriptor descriptor) {
	final BluetoothGatt gatt = bluetoothGatt;
	if (gatt == null || descriptor == null)
		return false;

	final BluetoothGattCharacteristic parentCharacteristic = descriptor.getCharacteristic();
	final int originalWriteType = parentCharacteristic.getWriteType();
	parentCharacteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT);
	final boolean result = gatt.writeDescriptor(descriptor);
	parentCharacteristic.setWriteType(originalWriteType);
	return result;
}
 
Example 9
Source File: OWDevice.java    From android-ponewheel with MIT License 5 votes vote down vote up
public void setRideMode(BluetoothUtil bluetoothUtil, int ridemode) {
    Timber.d("setRideMode() called for gatt:" + ridemode);
    BluetoothGattCharacteristic lc = bluetoothUtil.getCharacteristic(OWDevice.OnewheelCharacteristicRidingMode);
    if (lc != null) {
        ByteBuffer var2 = ByteBuffer.allocate(2);
        var2.putShort((short) ridemode);
        lc.setValue(var2.array());
        lc.setWriteType(2);
        bluetoothUtil.writeCharacteristic(lc);
        //setDeviceCharacteristicDisplay("ride_mode","ridemode: " + ridemode);
    }
}
 
Example 10
Source File: BleManagerHandler.java    From Android-BLE-Library with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * There was a bug in Android up to 6.0 where the descriptor was written using parent
 * characteristic's write type, instead of always Write With Response, as the spec says.
 * <p>
 * See: <a href="https://android.googlesource.com/platform/frameworks/base/+/942aebc95924ab1e7ea1e92aaf4e7fc45f695a6c%5E%21/#F0">
 * https://android.googlesource.com/platform/frameworks/base/+/942aebc95924ab1e7ea1e92aaf4e7fc45f695a6c%5E%21/#F0</a>
 *
 * @param descriptor the descriptor to be written
 * @return the result of {@link BluetoothGatt#writeDescriptor(BluetoothGattDescriptor)}
 */
private boolean internalWriteDescriptorWorkaround(@Nullable final BluetoothGattDescriptor descriptor) {
	final BluetoothGatt gatt = bluetoothGatt;
	if (gatt == null || descriptor == null || !connected)
		return false;

	final BluetoothGattCharacteristic parentCharacteristic = descriptor.getCharacteristic();
	final int originalWriteType = parentCharacteristic.getWriteType();
	parentCharacteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT);
	final boolean result = gatt.writeDescriptor(descriptor);
	parentCharacteristic.setWriteType(originalWriteType);
	return result;
}
 
Example 11
Source File: SerialInterface_BLE.java    From PodEmu with GNU General Public License v3.0 5 votes vote down vote up
@TargetApi(21)
public int write(byte[] buffer, int numBytes)
{
    PodEmuLog.debug("SIBLE: starting GATT characteristic write");
    if(bleGATT==null)
    {
        PodEmuLog.debug("SIBLE: write attempt before GATT initialized");
        return -1;
    }

    byte[] tmpBuff = new byte[numBytes];
    System.arraycopy(buffer,0, tmpBuff, 0, numBytes);

    try
    {
        final BluetoothGattCharacteristic characteristic = bleGATT
                .getService(SERVICE_UUID)
                .getCharacteristic(CHARACTERISTIC_SERIAL_UUID);

        characteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT);
        characteristic.setValue(tmpBuff);

        acquireWriteLock();

        if (!bleGATT.writeCharacteristic(characteristic))
        {
            PodEmuLog.error("SIBLE: write() couldn't send data!");
            releaseWriteLock();
            numBytes = -1;
        }

        PodEmuLog.debug("SIBLE: written " + numBytes + " bytes to GATT characteristic");
    }
    catch(NullPointerException e)
    {
        PodEmuLog.debug("SIBLE: ERROR during write. Interface disconnected.");
    }

    return numBytes;
}
 
Example 12
Source File: DfuBaseService.java    From microbit with Apache License 2.0 5 votes vote down vote up
/**
 * <p>
 * Writes the Soft Device, Bootloader and Application image sizes to the characteristic. Soft Device and Bootloader update is supported since Soft Device s110 v7.0.0.
 * Sizes of SD, BL and App are uploaded as 3x UINT32 even though some of them may be 0s. F.e. if only App is being updated the data will be <0x00000000, 0x00000000, [App size]>
 * </p>
 * <p>
 * This method is SYNCHRONOUS and wait until the {@link android.bluetooth.BluetoothGattCallback#onCharacteristicWrite(android.bluetooth.BluetoothGatt, android.bluetooth.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.
 * </p>
 *
 * @param gatt                the GATT device
 * @param characteristic      the characteristic to write to. Should be the DFU PACKET
 * @param softDeviceImageSize the Soft Device image size in bytes
 * @param bootloaderImageSize the Bootloader image size in bytes
 * @param appImageSize        the Application image size in bytes
 * @throws DeviceDisconnectedException
 * @throws DfuException
 * @throws UploadAbortedException
 */
private void writeImageSize(final BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic, final int softDeviceImageSize,
                            final int bootloaderImageSize, final int appImageSize) throws DeviceDisconnectedException, DfuException, UploadAbortedException {

    mReceivedData = null;
    mError = 0;
    mImageSizeSent = false;

    characteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE);
    characteristic.setValue(new byte[12]);
    characteristic.setValue(softDeviceImageSize, BluetoothGattCharacteristic.FORMAT_UINT32, 0);
    characteristic.setValue(bootloaderImageSize, BluetoothGattCharacteristic.FORMAT_UINT32, 4);
    characteristic.setValue(appImageSize, BluetoothGattCharacteristic.FORMAT_UINT32, 8);
    sendLogBroadcast(LOG_LEVEL_VERBOSE, "Writing to characteristic " + characteristic.getUuid());
    sendLogBroadcast(LOG_LEVEL_DEBUG, "gatt.writeCharacteristic(" + characteristic.getUuid() + ")");
    gatt.writeCharacteristic(characteristic);

    // We have to wait for confirmation
    try {
        synchronized (mLock) {
            while ((!mImageSizeSent && mConnectionState == STATE_CONNECTED_AND_READY && mError == 0 && !mAborted) || mPaused)
                mLock.wait();
        }
    } catch (final InterruptedException e) {
        loge("Sleeping interrupted", e);
    }

    if (mAborted)
        throw new UploadAbortedException();

    if (mError != 0)
        throw new DfuException("Unable to write Image Sizes", mError);

    if (mConnectionState != STATE_CONNECTED_AND_READY)
        throw new DeviceDisconnectedException("Unable to write Image Sizes", mConnectionState);
}
 
Example 13
Source File: BluetoothLeService.java    From openvidonn with GNU General Public License v3.0 5 votes vote down vote up
public void writeAlarms(ArrayList<Alarm> alarms) {
    if(mGattCharacteristics == null)
        return;
    BluetoothGattCharacteristic c = mGattCharacteristics.get(VidonnGattAttributes.VIDONN_SERVICE).get(VidonnGattAttributes.VIDONN_ALARM);

    Log.e(TAG, "writeAlarms:");

    byte packet[] = new byte[19];
    packet[0] = (byte) 0xF5;

    int i = 0;
    for(Object a : alarms) {
        Alarm alarm = (Alarm) a;
        Log.e(TAG, alarm.toStringDebug());
        packet[1] = (i<4) ? (byte) 0x00 : (byte) 0x01;

        packet[2+(i%4)*4] = alarm.getLevel();
        packet[3+(i%4)*4] = alarm.getWeekdays();
        packet[3+(i%4)*4] = (byte) (packet[3+(i%4)*4] | (alarm.isEnabled() ? (byte) 0x80 : (byte) 0x00));
        packet[4+(i%4)*4] = (byte) alarm.getHour();
        packet[5+(i%4)*4] = (byte) alarm.getMinutes();

        i++;
        if(i%4==0) {
            packet[packet.length - 1] = calculateChecksum(packet);
            c.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT);
            c.setValue(packet);
            writeCharacteristic(c);
        }
    }

}
 
Example 14
Source File: BluetoothLeService.java    From WheelLogAndroid with GNU General Public License v3.0 4 votes vote down vote up
public boolean writeBluetoothGattCharacteristic(byte[] cmd) {
      if (this.mBluetoothGatt == null) {
          return false;
      }
StringBuilder stringBuilder = new StringBuilder(cmd.length);
      for (byte aData : cmd)
          stringBuilder.append(String.format(Locale.US, "%02X", aData));
      Timber.i("Transmitted: " + stringBuilder.toString());

      switch (WheelData.getInstance().getWheelType()) {
          case KINGSONG:
              BluetoothGattService ks_service = this.mBluetoothGatt.getService(UUID.fromString(Constants.KINGSONG_SERVICE_UUID));
              if (ks_service == null) {
                  Timber.i("writeBluetoothGattCharacteristic service == null");
                  return false;
              }
              BluetoothGattCharacteristic ks_characteristic = ks_service.getCharacteristic(UUID.fromString(Constants.KINGSONG_READ_CHARACTER_UUID));
              if (ks_characteristic == null) {
                  Timber.i("writeBluetoothGattCharacteristic characteristic == null");
                  return false;
              }
              ks_characteristic.setValue(cmd);
              Timber.i("writeBluetoothGattCharacteristic writeType = %d", ks_characteristic.getWriteType());
              ks_characteristic.setWriteType(1);
              return this.mBluetoothGatt.writeCharacteristic(ks_characteristic);
          case GOTWAY:
              BluetoothGattService gw_service = this.mBluetoothGatt.getService(UUID.fromString(Constants.GOTWAY_SERVICE_UUID));
              if (gw_service == null) {
                  Timber.i("writeBluetoothGattCharacteristic service == null");
                  return false;
              }
              BluetoothGattCharacteristic characteristic = gw_service.getCharacteristic(UUID.fromString(Constants.GOTWAY_READ_CHARACTER_UUID));
              if (characteristic == null) {
                  Timber.i("writeBluetoothGattCharacteristic characteristic == null");
                  return false;
              }
              characteristic.setValue(cmd);
              Timber.i("writeBluetoothGattCharacteristic writeType = %d", characteristic.getWriteType());
              return this.mBluetoothGatt.writeCharacteristic(characteristic);
          case NINEBOT_Z:
              BluetoothGattService nz_service = this.mBluetoothGatt.getService(UUID.fromString(Constants.NINEBOT_Z_SERVICE_UUID));
              if (nz_service == null) {
                  Timber.i("writeBluetoothGattCharacteristic service == null");
                  return false;
              }
              BluetoothGattCharacteristic nz_characteristic = nz_service.getCharacteristic(UUID.fromString(Constants.NINEBOT_Z_WRITE_CHARACTER_UUID));
              if (nz_characteristic == null) {
                  Timber.i("writeBluetoothGattCharacteristic characteristic == null");
                  return false;
              }
              nz_characteristic.setValue(cmd);
              Timber.i("writeBluetoothGattCharacteristic writeType = %d", nz_characteristic.getWriteType());
              return this.mBluetoothGatt.writeCharacteristic(nz_characteristic);
          case INMOTION:
              BluetoothGattService im_service = this.mBluetoothGatt.getService(UUID.fromString(Constants.INMOTION_WRITE_SERVICE_UUID));
              if (im_service == null) {
                  Timber.i("writeBluetoothGattCharacteristic service == null");
                  return false;
              }
              BluetoothGattCharacteristic im_characteristic = im_service.getCharacteristic(UUID.fromString(Constants.INMOTION_WRITE_CHARACTER_UUID));
              if (im_characteristic == null) {
                  Timber.i("writeBluetoothGattCharacteristic characteristic == null");
                  return false;
              }
              byte[] buf = new byte[20];
              int i2 = cmd.length / 20;
              int i3 = cmd.length - (i2 * 20);
              for (int i4 = 0; i4 < i2; i4++) {
                  System.arraycopy(cmd, i4 * 20, buf, 0, 20);
                  im_characteristic.setValue(buf);
                  if (!this.mBluetoothGatt.writeCharacteristic(im_characteristic)) return false;
                  try {
                      Thread.sleep(20);
                  } catch (InterruptedException e) {
                      e.printStackTrace();
                  }
              }
              if (i3 > 0) {
                  System.arraycopy(cmd, i2 * 20, buf, 0, i3);
                  im_characteristic.setValue(buf);
                  if(!this.mBluetoothGatt.writeCharacteristic(im_characteristic)) return false;
              }
              Timber.i("writeBluetoothGattCharacteristic writeType = %d", im_characteristic.getWriteType());
              return true;
      }
      return false;
  }
 
Example 15
Source File: P_Task_TestMtu.java    From SweetBlue with GNU General Public License v3.0 4 votes vote down vote up
@Override protected void executeReadOrWrite()
{
    if( false == write_earlyOut(m_data) )
    {
        final BluetoothGattCharacteristic char_native = getFilteredCharacteristic() != null ? getFilteredCharacteristic() : getDevice().getNativeCharacteristic(getServiceUuid(), getCharUuid());

        if( char_native == null )
        {
            fail(BleDevice.ReadWriteListener.Status.NO_MATCHING_TARGET, BleStatuses.GATT_STATUS_NOT_APPLICABLE, getDefaultTarget(), getCharUuid(), BleDevice.ReadWriteListener.ReadWriteEvent.NON_APPLICABLE_UUID);
        }
        else
        {
            // Set the write type now, if it is not null
            if (m_writeType != null)
            {
                if (m_writeType == BleDevice.ReadWriteListener.Type.WRITE_NO_RESPONSE)
                {
                    char_native.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE);
                }
                else if (m_writeType == BleDevice.ReadWriteListener.Type.WRITE_SIGNED)
                {
                    char_native.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_SIGNED);
                }
                else if (char_native.getWriteType() != BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT)
                {
                    char_native.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT);
                }
            }

            if( false == getDevice().layerManager().setCharValue(char_native, m_data) )
            {
                fail(BleDevice.ReadWriteListener.Status.FAILED_TO_SET_VALUE_ON_TARGET, BleStatuses.GATT_STATUS_NOT_APPLICABLE, getDefaultTarget(), getCharUuid(), BleDevice.ReadWriteListener.ReadWriteEvent.NON_APPLICABLE_UUID);
            }
            else
            {
                if( false == getDevice().layerManager().writeCharacteristic(char_native) )
                {
                    fail(BleDevice.ReadWriteListener.Status.FAILED_TO_SEND_OUT, BleStatuses.GATT_STATUS_NOT_APPLICABLE, getDefaultTarget(), getCharUuid(), BleDevice.ReadWriteListener.ReadWriteEvent.NON_APPLICABLE_UUID);
                }
                else
                {
                    // SUCCESS, for now...
                }
            }
        }
    }
}
 
Example 16
Source File: P_Task_TestMtu.java    From AsteroidOSSync with GNU General Public License v3.0 4 votes vote down vote up
@Override protected void executeReadOrWrite()
{
    if( false == write_earlyOut(m_data) )
    {
        final BluetoothGattCharacteristic char_native = getFilteredCharacteristic() != null ? getFilteredCharacteristic() : getDevice().getNativeCharacteristic(getServiceUuid(), getCharUuid());

        if( char_native == null )
        {
            fail(BleDevice.ReadWriteListener.Status.NO_MATCHING_TARGET, BleStatuses.GATT_STATUS_NOT_APPLICABLE, getDefaultTarget(), getCharUuid(), BleDevice.ReadWriteListener.ReadWriteEvent.NON_APPLICABLE_UUID);
        }
        else
        {
            // Set the write type now, if it is not null
            if (m_writeType != null)
            {
                if (m_writeType == BleDevice.ReadWriteListener.Type.WRITE_NO_RESPONSE)
                {
                    char_native.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE);
                }
                else if (m_writeType == BleDevice.ReadWriteListener.Type.WRITE_SIGNED)
                {
                    char_native.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_SIGNED);
                }
                else if (char_native.getWriteType() != BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT)
                {
                    char_native.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT);
                }
            }

            if( false == getDevice().layerManager().setCharValue(char_native, m_data) )
            {
                fail(BleDevice.ReadWriteListener.Status.FAILED_TO_SET_VALUE_ON_TARGET, BleStatuses.GATT_STATUS_NOT_APPLICABLE, getDefaultTarget(), getCharUuid(), BleDevice.ReadWriteListener.ReadWriteEvent.NON_APPLICABLE_UUID);
            }
            else
            {
                if( false == getDevice().layerManager().writeCharacteristic(char_native) )
                {
                    fail(BleDevice.ReadWriteListener.Status.FAILED_TO_SEND_OUT, BleStatuses.GATT_STATUS_NOT_APPLICABLE, getDefaultTarget(), getCharUuid(), BleDevice.ReadWriteListener.ReadWriteEvent.NON_APPLICABLE_UUID);
                }
                else
                {
                    // SUCCESS, for now...
                }
            }
        }
    }
}
 
Example 17
Source File: BleManager.java    From BLEChat with GNU General Public License v3.0 4 votes vote down vote up
public boolean write(BluetoothGattCharacteristic chr, byte[] data) {
	if (mBluetoothGatt == null) {
	    Logs.d(TAG, "# BluetoothGatt not initialized");
	    return false;
	}
	
	BluetoothGattCharacteristic writableChar = null;
	
	if(chr == null) {
		if(mDefaultChar == null) {
			for(BluetoothGattCharacteristic bgc : mWritableCharacteristics) {
				if(isWritableCharacteristic(bgc)) {
					writableChar = bgc;
				}
			}
			if(writableChar == null) {
				Logs.d(TAG, "# Write failed - No available characteristic");
				return false;
			}
		} else {
			if(isWritableCharacteristic(mDefaultChar)) {
				Logs.d("# Default GattCharacteristic is PROPERY_WRITE | PROPERTY_WRITE_NO_RESPONSE");
				writableChar = mDefaultChar;
			} else {
				Logs.d("# Default GattCharacteristic is not writable");
				mDefaultChar = null;
				return false;
			}
		}
	} else {
		if (isWritableCharacteristic(chr)) {
			Logs.d("# user GattCharacteristic is PROPERY_WRITE | PROPERTY_WRITE_NO_RESPONSE");
			writableChar = chr;
		} else {
			Logs.d("# user GattCharacteristic is not writable");
			return false;
		}
	}
	
	writableChar.setValue(data);
	writableChar.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE);
	mBluetoothGatt.writeCharacteristic(writableChar);
	mDefaultChar = writableChar;
	return true;
}
 
Example 18
Source File: P_Task_Write.java    From SweetBlue with GNU General Public License v3.0 4 votes vote down vote up
@Override protected void executeReadOrWrite()
{
	m_data = m_futureData.getData();

	if( false == write_earlyOut(m_data) )
	{
		final BluetoothGattCharacteristic char_native = getFilteredCharacteristic() != null ? getFilteredCharacteristic() : getDevice().getNativeCharacteristic(getServiceUuid(), getCharUuid());

		if( char_native == null )
		{
			fail(Status.NO_MATCHING_TARGET, BleStatuses.GATT_STATUS_NOT_APPLICABLE, getDefaultTarget(), getCharUuid(), ReadWriteEvent.NON_APPLICABLE_UUID);
		}
		else
		{
			// Set the write type now, if it is not null
			if (m_writeType != null)
			{
				if (m_writeType == Type.WRITE_NO_RESPONSE)
				{
					char_native.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE);
				}
				else if (m_writeType == Type.WRITE_SIGNED)
				{
					char_native.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_SIGNED);
				}
				else if (char_native.getWriteType() != BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT)
				{
					char_native.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT);
				}
			}

			if( false == getDevice().layerManager().setCharValue(char_native, m_data) )
			{
				fail(Status.FAILED_TO_SET_VALUE_ON_TARGET, BleStatuses.GATT_STATUS_NOT_APPLICABLE, getDefaultTarget(), getCharUuid(), ReadWriteEvent.NON_APPLICABLE_UUID);
			}
			else
			{
				if( false == getDevice().layerManager().writeCharacteristic(char_native) )
				{
					fail(Status.FAILED_TO_SEND_OUT, BleStatuses.GATT_STATUS_NOT_APPLICABLE, getDefaultTarget(), getCharUuid(), ReadWriteEvent.NON_APPLICABLE_UUID);
				}
				else
				{
					// SUCCESS, for now...
				}
			}
		}
	}
}
 
Example 19
Source File: CorePeripheral.java    From RxCentralBle with Apache License 2.0 4 votes vote down vote up
@Nullable
private PeripheralError setCharacteristicNotification(
    BluetoothGatt bluetoothGatt, BluetoothGattCharacteristic characteristic, boolean enable) {

  BluetoothGattDescriptor cccd = characteristic.getDescriptor(CCCD_UUID);
  if (cccd == null) {
    return new PeripheralError(PeripheralError.Code.SET_CHARACTERISTIC_NOTIFICATION_CCCD_MISSING);
  }

  if (!bluetoothGatt.setCharacteristicNotification(characteristic, enable)) {
    return new PeripheralError(PeripheralError.Code.SET_CHARACTERISTIC_NOTIFICATION_FAILED);
  }

  int properties = characteristic.getProperties();
  byte[] value;

  if (enable) {
    if ((properties & BluetoothGattCharacteristic.PROPERTY_NOTIFY)
        == BluetoothGattCharacteristic.PROPERTY_NOTIFY) {
      value = BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE;
    } else if ((properties & BluetoothGattCharacteristic.PROPERTY_INDICATE)
        == BluetoothGattCharacteristic.PROPERTY_INDICATE) {
      value = BluetoothGattDescriptor.ENABLE_INDICATION_VALUE;
    } else {
      return new PeripheralError(PeripheralError.Code.SET_CHARACTERISTIC_NOTIFICATION_MISSING_PROPERTY);
    }
  } else {
    value = BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE;
  }

  characteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT);

  if (!cccd.setValue(value)) {
    return new PeripheralError(CHARACTERISTIC_SET_VALUE_FAILED);
  }

  if (!bluetoothGatt.writeDescriptor(cccd)) {
    return new PeripheralError(PeripheralError.Code.WRITE_DESCRIPTOR_FAILED, ERROR_STATUS_CALL_FAILED);
  }

  return null;
}
 
Example 20
Source File: DeviceServicesActivity.java    From EFRConnect-android with Apache License 2.0 3 votes vote down vote up
/**
 * WRITES BYTE ARRAY TO A GENERIC CHARACTERISTIC
 *****************************************/
public boolean writeGenericCharacteristic(UUID service, UUID characteristic, byte[] value) {

    if (bluetoothGatt != null) {

        BluetoothGattCharacteristic bluetoothGattCharacteristic = bluetoothGatt.getService(service).getCharacteristic(characteristic);
        Log.d("characteristic", "exists");

        if (bluetoothGattCharacteristic != null) {

            bluetoothGattCharacteristic.setValue(value);
            bluetoothGattCharacteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT);
            bluetoothGatt.writeCharacteristic(bluetoothGattCharacteristic);
            Log.d("characteristic", "written");

        } else {

            Log.d("characteristic", "null");
            return false;
        }

    } else {

        Log.d("bluetoothGatt", "null");
        return false;

    }

    return true;

}