android.bluetooth.BluetoothGattCharacteristic Java Examples

The following examples show how to use android.bluetooth.BluetoothGattCharacteristic. 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: AbstractHOGPServer.java    From DeviceConnect-Android with MIT License 6 votes vote down vote up
/**
 * Setup Battery Service
 *
 * @return the service
 */
private BluetoothGattService setUpBatteryService() {
    final BluetoothGattService service = new BluetoothGattService(SERVICE_BATTERY, BluetoothGattService.SERVICE_TYPE_PRIMARY);

    // Battery Level
    final BluetoothGattCharacteristic characteristic = new BluetoothGattCharacteristic(
            CHARACTERISTIC_BATTERY_LEVEL,
            BluetoothGattCharacteristic.PROPERTY_NOTIFY | BluetoothGattCharacteristic.PROPERTY_READ,
            BluetoothGattCharacteristic.PERMISSION_READ_ENCRYPTED);

    final BluetoothGattDescriptor clientCharacteristicConfigurationDescriptor = new BluetoothGattDescriptor(
            DESCRIPTOR_CLIENT_CHARACTERISTIC_CONFIGURATION,
            BluetoothGattDescriptor.PERMISSION_READ | BluetoothGattDescriptor.PERMISSION_WRITE);
    clientCharacteristicConfigurationDescriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
    characteristic.addDescriptor(clientCharacteristicConfigurationDescriptor);

    service.addCharacteristic(characteristic);

    return service;
}
 
Example #2
Source File: BleRequestImpl.java    From Android-BLE with Apache License 2.0 6 votes vote down vote up
@Override
public void onCharacteristicWrite(BluetoothGatt gatt,
                                  BluetoothGattCharacteristic characteristic, int status) {
    if (gatt == null || gatt.getDevice() == null)return;
    BleLog.d(TAG, gatt.getDevice().getAddress() + "-----write success----- status: " + status);
    synchronized (locker) {
        T bleDevice = getBleDeviceInternal(gatt.getDevice().getAddress());
        if (status == BluetoothGatt.GATT_SUCCESS) {
            if (null != writeWrapperCallback){
                writeWrapperCallback.onWriteSuccess(bleDevice, characteristic);
            }
            if (options.uuid_ota_write_cha.equals(characteristic.getUuid())) {
                if (otaListener != null) {
                    otaListener.onWrite();
                }
            }
        }else {
            if (null != writeWrapperCallback){
                writeWrapperCallback.onWriteFailed(bleDevice, status);
            }
        }
    }
}
 
Example #3
Source File: H7ConnectThread.java    From PolarHeartRateApplication with MIT License 6 votes vote down vote up
@Override
  public void onServicesDiscovered(final BluetoothGatt gatt, final int status) {
  	BluetoothGattService service = gatt.getService(UUID.fromString(HRUUID)); // Return the HR service
//BluetoothGattCharacteristic characteristic = service.getCharacteristic(UUID.fromString("00002A37-0000-1000-8000-00805F9B34FB"));
List<BluetoothGattCharacteristic> characteristics = service.getCharacteristics(); //Get the hart rate value
for (BluetoothGattCharacteristic cc : characteristics)
	{
		for (BluetoothGattDescriptor descriptor : cc.getDescriptors()) {
		    //find descriptor UUID that matches Client Characteristic Configuration (0x2902)
		    // and then call setValue on that descriptor
			
			//Those two line set the value for the disconnection
			H7ConnectThread.descriptor=descriptor;
			H7ConnectThread.cc=cc;
									
			gatt.setCharacteristicNotification(cc,true);//Register to updates
			descriptor.setValue( BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
		    gatt.writeDescriptor(descriptor);
			Log.d("H7ConnectThread", "Connected and regisering to info");
		}
	}
  }
 
Example #4
Source File: BluetoothPeripheralTest.java    From blessed-android with MIT License 6 votes vote down vote up
@Test
public void setNotifyNotificationTest() throws Exception {
    BluetoothGattCallback callback = connectAndGetCallback();
    callback.onConnectionStateChange(gatt, GATT_SUCCESS, STATE_CONNECTED);

    BluetoothGattService service = new BluetoothGattService(SERVICE_UUID, 0);
    BluetoothGattCharacteristic characteristic = new BluetoothGattCharacteristic(UUID.fromString("00002A1C-0000-1000-8000-00805f9b34fb"),PROPERTY_NOTIFY,0);
    BluetoothGattDescriptor descriptor = new BluetoothGattDescriptor(UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"),0);
    service.addCharacteristic(characteristic);
    characteristic.addDescriptor(descriptor);

    when(gatt.getServices()).thenReturn(Arrays.asList(service));

    peripheral.setNotify(characteristic, true);
    verify(gatt).setCharacteristicNotification(characteristic, true);
    assertEquals(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE[0], descriptor.getValue()[0]);
    assertEquals(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE[1], descriptor.getValue()[1]);
    verify(gatt).writeDescriptor(descriptor);

    callback.onDescriptorWrite(gatt, descriptor, 0);
    verify(peripheralCallback).onNotificationStateUpdate(peripheral, characteristic, 0);
}
 
Example #5
Source File: GattClientCallback.java    From bitgatt with Mozilla Public License 2.0 6 votes vote down vote up
@Override
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
    super.onCharacteristicWrite(gatt, characteristic, status);
    if (FitbitGatt.getInstance().isSlowLoggingEnabled()) {
        Timber.v("[%s] onCharacteristicWrite: Gatt Response Status %s", getDeviceMacFromGatt(gatt), GattStatus.getStatusForCode(status));
        Timber.d("[%s][Threading] Originally called on thread : %s", getDeviceMacFromGatt(gatt), Thread.currentThread().getName());
    }
    ArrayList<GattClientListener> copy = new ArrayList<>(listeners.size());
    copy.addAll(listeners);
    final BluetoothGattCharacteristicCopy bluetoothGattCharacteristic = gattUtils.copyCharacteristic(characteristic);
    handler.post(() -> {
        for (GattClientListener listener : copy) {
            if (listener.getDevice() != null && listener.getDevice().equals(gatt.getDevice())) {
                listener.onCharacteristicWrite(gatt, bluetoothGattCharacteristic, status);
            }
        }
    });
}
 
Example #6
Source File: UartService.java    From Android-nRF-UART with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void writeRXCharacteristic(byte[] value)
{

	
	BluetoothGattService RxService = mBluetoothGatt.getService(RX_SERVICE_UUID);
	showMessage("mBluetoothGatt null"+ mBluetoothGatt);
	if (RxService == null) {
        showMessage("Rx service not found!");
        broadcastUpdate(DEVICE_DOES_NOT_SUPPORT_UART);
        return;
    }
	BluetoothGattCharacteristic RxChar = RxService.getCharacteristic(RX_CHAR_UUID);
    if (RxChar == null) {
        showMessage("Rx charateristic not found!");
        broadcastUpdate(DEVICE_DOES_NOT_SUPPORT_UART);
        return;
    }
    RxChar.setValue(value);
	boolean status = mBluetoothGatt.writeCharacteristic(RxChar);
	
    Log.d(TAG, "write TXchar - status=" + status);  
}
 
Example #7
Source File: BaseMyo.java    From myolib with Apache License 2.0 6 votes vote down vote up
@Override
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int gattStatus) {
    WriteMsg msg = (WriteMsg) mMsgCallbackMap.remove(MyoMsg.toIdentifier(characteristic));
    mWaitToken.release();

    msg.setGattStatus(gattStatus);
    if (gattStatus == BluetoothGatt.GATT_SUCCESS) {
        Logy.v(TAG, "rtt: " + (System.currentTimeMillis() - mDispatchTime) + "ms | SUCCESS | " + msg.toString());
        msg.setState(MyoMsg.State.SUCCESS);
        if (msg.getCallback() != null)
            msg.getCallback().onResult(msg);
    } else {
        Logy.w(TAG, "rtt: " + (System.currentTimeMillis() - mDispatchTime) + "ms | ERROR(" + gattStatus + ") | " + msg.toString());
        msg.setState(MyoMsg.State.ERROR);
        if (msg.getRetryCounter() == 0) {
            if (msg.getCallback() != null)
                msg.getCallback().onResult(msg);
        } else {
            msg.decreaseRetryCounter();
            submit(msg);
        }
    }
    super.onCharacteristicWrite(gatt, characteristic, gattStatus);
}
 
Example #8
Source File: BtBridge.java    From sony-smartband-open-api with MIT License 6 votes vote down vote up
@Override
public void onDescriptorWrite( BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status ) {
    if( status != BluetoothGatt.GATT_SUCCESS ) {
        Log.e( CLASS, "onDescriptorWrite: Status != SUCCESS: status=" + status );
        return;
    }
    mGatt = gatt;

    if( descriptor == null ) {
        Log.e( CLASS, "onDescriptorWrite: null descriptor" );
        return;
    }

    BluetoothGattCharacteristic characteristic = descriptor.getCharacteristic();
    for( BtBridgeListener listener : mListeners ) {
        listener.onDescriptorWrite( characteristic, descriptor );
    }
}
 
Example #9
Source File: PA_ServiceManager.java    From AsteroidOSSync with GNU General Public License v3.0 6 votes vote down vote up
private BleDescriptorWrapper getDescriptor(final BleServiceWrapper service, final UUID charUuid_nullable, final UUID descUuid)
{
    if (!service.isNull())
    {
        final List<BluetoothGattCharacteristic> charList = getNativeCharacteristicList_original(service);

        for (int j = 0; j < charList.size(); j++)
        {
            final BleCharacteristicWrapper char_jth = new BleCharacteristicWrapper(charList.get(j));

            if (charUuid_nullable == null || !char_jth.isNull() && charUuid_nullable.equals(char_jth.getCharacteristic().getUuid()))
            {
                final BleDescriptorWrapper descriptor = getDescriptor(char_jth, descUuid);

                return descriptor;
            }
        }
    }

    return BleDescriptorWrapper.NULL;
}
 
Example #10
Source File: DeviceControlActivity.java    From AndroidBleManager with Apache License 2.0 6 votes vote down vote up
/**
 * get property,http://blog.csdn.net/chenxh515/article/details/45723299
 * @param property
 * @return
 */
private String getPropertyString(int property){
    StringBuilder sb = new StringBuilder("(");
    //Read
    if ((property & BluetoothGattCharacteristic.PROPERTY_READ) > 0) {
        sb.append("Read ");
    }
    //Write
    if ((property & BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE) > 0
            || (property & BluetoothGattCharacteristic.PROPERTY_WRITE) > 0) {
        sb.append("Write ");
    }
    //Notify
    if ((property & BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0
            || (property & BluetoothGattCharacteristic.PROPERTY_INDICATE) > 0) {
        sb.append("Notity Indicate ");
    }
    //Broadcast
    if ((property & BluetoothGattCharacteristic.PROPERTY_BROADCAST) > 0){
        sb.append("Broadcast ");
    }
    sb.deleteCharAt(sb.length() - 1);
    sb.append(")");
    return sb.toString();
}
 
Example #11
Source File: G5CollectionService.java    From xDrip with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onCharacteristicWrite(final BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic, final int status) {
    Log.e(TAG, "OnCharacteristic WRITE started: "
            + getUUIDName(characteristic.getUuid())
            + " status: " + getStatusName(status));
    //Log.e(TAG, "Write Status " + String.valueOf(status));
    //Log.e(TAG, "Characteristic " + String.valueOf(characteristic.getUuid()));

    if (enforceMainThread()) {
        Handler iHandler = new Handler(Looper.getMainLooper());
        iHandler.post(new Runnable() {
            @Override
            public void run() {
                processOnCharacteristicWrite(gatt, characteristic, status);
            }
        });
    } else {
        processOnCharacteristicWrite(gatt, characteristic, status);
    }


}
 
Example #12
Source File: BleManager.java    From Android-nRF-Toolbox with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public final void onCharacteristicWrite(final BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic, final int status) {
	if (status == BluetoothGatt.GATT_SUCCESS) {
		// The value has been written. Notify the profile and proceed with the initialization queue.
		profile.onCharacteristicWrite(gatt, characteristic);
		operationInProgress = false;
		nextRequest();
	} else if (status == BluetoothGatt.GATT_INSUFFICIENT_AUTHENTICATION) {
		if (gatt.getDevice().getBondState() != BluetoothDevice.BOND_NONE) {
			// This should never happen but it used to: http://stackoverflow.com/a/20093695/2115352
			DebugLogger.w(TAG, ERROR_AUTH_ERROR_WHILE_BONDED);
			onError(gatt.getDevice(), ERROR_AUTH_ERROR_WHILE_BONDED, status);
		}
	} else {
		DebugLogger.e(TAG, "onCharacteristicWrite error " + status);
		onError(gatt.getDevice(), ERROR_WRITE_CHARACTERISTIC, status);
	}
}
 
Example #13
Source File: BLEUtils.java    From EFRConnect-android with Apache License 2.0 6 votes vote down vote up
/**
 * Search for a specific characteristic given a BluetoothGattService
 *
 * @param service              the service to search through
 * @param targetService        the service that you're looking for
 * @param targetCharacteristic the characteristic you're looking for
 * @return the characteristic, if it's found - null otherwise
 */
public static BluetoothGattCharacteristic getCharacteristic(BluetoothGattService service, GattService targetService, GattCharacteristic targetCharacteristic) {
    if (service == null || targetService == null || targetCharacteristic == null) {
        return null;
    }
    GattService gattService = GattService.fromUuid(service.getUuid());
    if (gattService != null && gattService == targetService) {
        List<BluetoothGattCharacteristic> characteristics = service.getCharacteristics();
        if (characteristics != null && !characteristics.isEmpty()) {
            for (BluetoothGattCharacteristic characteristic : characteristics) {
                GattCharacteristic gattCharacteristic = GattCharacteristic.fromUuid(characteristic.getUuid());
                if (gattCharacteristic != null && gattCharacteristic == targetCharacteristic) {
                    return characteristic;
                }
            }
        }
    }
    return null;
}
 
Example #14
Source File: BTConnectionManager.java    From Mi-Band with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
    super.onCharacteristicWrite(gatt, characteristic, status);

    //if status is 0, success on sending and received
    //Log.i(TAG, "handleControlPoint got status:" + status);

    if (BluetoothGatt.GATT_SUCCESS == status) {
        io.onSuccess(characteristic);

        if (characteristic.getUuid().equals(Profile.UUID_CHAR_CONTROL_POINT)) {
            io.handleControlPointResult(characteristic.getValue());
        }

    } else {
        io.onFail(status, "onCharacteristicWrite fail");
    }

    if (onDataRead != null)
        onDataRead.OnDataRead();
}
 
Example #15
Source File: MultipleBleService.java    From BleLib with Apache License 2.0 6 votes vote down vote up
/**
 * Enables or disables notification on a give characteristic.
 *
 * @param address        The address.
 * @param characteristic Characteristic to act on.
 * @param enabled        If true, enable notification.  False otherwise.
 */
public void setCharacteristicNotification(String address,
                                          BluetoothGattCharacteristic characteristic,
                                          boolean enabled) {
    if (mBluetoothAdapter == null || mBluetoothGattMap.get(address) == null) {
        Log.w(TAG, "BluetoothAdapter not initialized");
        return;
    }
    mBluetoothGattMap.get(address).setCharacteristicNotification(characteristic, enabled);

    BluetoothGattDescriptor descriptor = characteristic.getDescriptor(
            UUID.fromString(GattAttributes.DESCRIPTOR_CLIENT_CHARACTERISTIC_CONFIGURATION));
    descriptor.setValue(enabled ? BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE :
            BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE);
    mBluetoothGattMap.get(address).writeDescriptor(descriptor);
}
 
Example #16
Source File: BaseBleService.java    From bleYan with GNU General Public License v2.0 5 votes vote down vote up
protected synchronized boolean writeToCharacteristic(UUID serviceUUID, UUID characteristicUUID, byte[] values) {
	BluetoothGattService gattService = mGatt == null ? null : mGatt.getService(serviceUUID);
	if(gattService != null) {
		BluetoothGattCharacteristic gattCharacteristic = gattService.getCharacteristic(characteristicUUID);
		if(gattCharacteristic != null) {
			gattCharacteristic.setValue(values);
			write(gattCharacteristic);
			return true;
		}
	}
	return false;
}
 
Example #17
Source File: ACSUtilityService.java    From ESeal with Apache License 2.0 5 votes vote down vote up
private BluetoothGattCharacteristic getACSCharacteristic(UUID charaUUID) {
    if (mBluetoothAdapter == null || mBluetoothGatt == null) {
        Log.w(TAG, "BluetoothAdapter not initialized");
        return null;
    }
    BluetoothGattService service = mBluetoothGatt.getService(ACS_SERVICE_UUID);
    if (service == null) {
        Log.e(TAG, "Service is not found!");
        return null;
    }
    BluetoothGattCharacteristic chara = service.getCharacteristic(charaUUID);
    return chara;
}
 
Example #18
Source File: BlePeripheral.java    From Bluefruit_LE_Connect_Android_V2 with MIT License 5 votes vote down vote up
private static int getDescriptorPermissions(BluetoothGattService service, String characteristicUUIDString, String descriptorUUIDString) {
    final UUID characteristicUuid = UUID.fromString(characteristicUUIDString);
    BluetoothGattCharacteristic characteristic = service.getCharacteristic(characteristicUuid);

    int permissions = 0;
    if (characteristic != null) {
        final UUID descriptorUuid = UUID.fromString(descriptorUUIDString);
        BluetoothGattDescriptor descriptor = characteristic.getDescriptor(descriptorUuid);
        if (descriptor != null) {
            permissions = descriptor.getPermissions();
        }
    }

    return permissions;
}
 
Example #19
Source File: AbsGattCallback.java    From MiBandDecompiled with Apache License 2.0 5 votes vote down vote up
public final void onCharacteristicWrite(BluetoothGatt bluetoothgatt, final BluetoothGattCharacteristic characteristic, int i)
{
    boolean flag = true;
    Debug.TRACE();
    boolean flag1;
    if (i == 0)
    {
        flag1 = flag;
    } else
    {
        flag1 = false;
    }
    Debug.ASSERT_TRUE(flag1);
    if (m_Gatt != bluetoothgatt)
    {
        flag = false;
    }
    Debug.ASSERT_TRUE(flag);
    Debug.DEBUG((new StringBuilder()).append("Characteristic Write: ").append(Helper.bytesToHexString(characteristic.getValue())).toString());
    c_GattOperationLock.lock();
    c_ReturnValue = i;
    Debug.DEBUG_LOCK((new StringBuilder()).append("NOTIFY: onCharacteristicWrite(): ").append(c_ReturnValue).toString());
    c_isGattOperationLocking = false;
    c_condGattOperationComplete.signal();
    c_GattOperationLock.unlock();
    if (i == 0)
    {
        m_Executor.execute(new _cls10());
    }
    return;
    Exception exception;
    exception;
    c_GattOperationLock.unlock();
    throw exception;
}
 
Example #20
Source File: ReminderServiceHandler.java    From Aerlink-for-Android with MIT License 5 votes vote down vote up
@Override
public void handleCharacteristic(BluetoothGattCharacteristic characteristic) {
    byte[] packet = characteristic.getValue();

    if (mPacketProcessor == null) {
        mPacketProcessor = new PacketProcessor(packet);

        if (!mPacketProcessor.isFinished()) {
            switch (mPacketProcessor.getAction()) {
                case 0x01:
                    if (calendarsCallback != null) {
                        calendarsCallback.onDataTransferStarted();
                    }
                    break;
                case 0x02:
                    if (remindersCallback != null) {
                        remindersCallback.onDataTransferStarted();
                    }
                    break;
            }
        }
    }
    else {
        mPacketProcessor.process(packet);
    }

    if (mPacketProcessor == null || !mPacketProcessor.isFinished()) {
        return;
    }
    switch (mPacketProcessor.getAction()) {
        case 0x01:
            processCalendarsData(mPacketProcessor);
            break;
        case 0x02:
            processRemindersData(mPacketProcessor);
            break;
    }

    mPacketProcessor = null;
}
 
Example #21
Source File: BluetoothHandler.java    From blessed-android with MIT License 5 votes vote down vote up
@Override
public void onNotificationStateUpdate(BluetoothPeripheral peripheral, BluetoothGattCharacteristic characteristic, int status) {
    if( status == GATT_SUCCESS) {
        if(peripheral.isNotifying(characteristic)) {
            Timber.i("SUCCESS: Notify set to 'on' for %s", characteristic.getUuid());
        } else {
            Timber.i("SUCCESS: Notify set to 'off' for %s", characteristic.getUuid());
        }
    } else {
        Timber.e("ERROR: Changing notification state failed for %s", characteristic.getUuid());
    }
}
 
Example #22
Source File: BleWrapper.java    From BLEService with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void getCharacteristicsForService(final BluetoothGattService service) {
	if(service == null) return;
	List<BluetoothGattCharacteristic> chars = null;
	
	chars = service.getCharacteristics();   	
	mUiCallback.uiCharacteristicForService(mBluetoothGatt, mBluetoothDevice, service, chars);
	// keep reference to the last selected service
	mBluetoothSelectedService = service;
}
 
Example #23
Source File: P_AndroidGatt.java    From SweetBlue with GNU General Public License v3.0 5 votes vote down vote up
@Override
public final boolean setCharacteristicNotification(BluetoothGattCharacteristic characteristic, boolean enable)
{
    if (m_gatt != null && characteristic != null)
    {
        return m_gatt.setCharacteristicNotification(characteristic, enable);
    }
    return false;
}
 
Example #24
Source File: DexShareCollectionService.java    From xDrip with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
    if (status == BluetoothGatt.GATT_SUCCESS) {
        BluetoothGattCharacteristic characteristic = descriptor.getCharacteristic();
        Log.d(TAG, "Characteristic onDescriptorWrite ch " + characteristic.getUuid());
        if(mHeartBeatCharacteristic.getUuid().equals(characteristic.getUuid())) {
            state_notifSetupSucess = true;
            setCharacteristicIndication(mReceiveDataCharacteristic);
        }
        if(mReceiveDataCharacteristic.getUuid().equals(characteristic.getUuid())) {
            setCharacteristicIndication(mResponseCharacteristic);
        }
        if(mResponseCharacteristic.getUuid().equals(characteristic.getUuid())) {
            attemptRead();
        }
    } else if ((status & BluetoothGatt.GATT_INSUFFICIENT_AUTHENTICATION) != 0 || (status & BluetoothGatt.GATT_INSUFFICIENT_ENCRYPTION) != 0) {
        if (gatt.getDevice().getBondState() == BluetoothDevice.BOND_NONE) {
            device = gatt.getDevice();
            state_authInProgress = true;
            bondDevice();
        } else {
            Log.e(TAG, "The phone is trying to read from paired device without encryption. Android Bug? Have the dexcom forget whatever device it was previously paired to: ondescriptorwrite code: "+status+ "bond: "+gatt.getDevice().getBondState());
        }
    } else {
        Log.e(TAG, "Unknown error writing descriptor");
    }
}
 
Example #25
Source File: CharacteristicWriteOperation.java    From RxAndroidBle with Apache License 2.0 5 votes vote down vote up
CharacteristicWriteOperation(RxBleGattCallback rxBleGattCallback, BluetoothGatt bluetoothGatt,
                             @Named(ConnectionModule.OPERATION_TIMEOUT) TimeoutConfiguration timeoutConfiguration,
                             BluetoothGattCharacteristic bluetoothGattCharacteristic,
                             byte[] data) {
    super(bluetoothGatt, rxBleGattCallback, BleGattOperationType.CHARACTERISTIC_WRITE, timeoutConfiguration);
    this.bluetoothGattCharacteristic = bluetoothGattCharacteristic;
    this.data = data;
}
 
Example #26
Source File: BluetoothLEGatt.java    From EFRConnect-android with Apache License 2.0 5 votes vote down vote up
/**
 * Instructs the gatt to request the remote device to send a value of the given characteristic.
 * It waits until the gatt's callback calls {@link #onRead(int, Object, boolean)} containing the value.
 * It will not wait longer than 1000 milliseconds. If it takes longer, the current value stored in memory
 * will be returned.
 *
 * @param characteristicID ID of the characteristic whose remote value is requested.
 * @return The value of the characteristic.
 */
Object read(int characteristicID) {
    final BluetoothGatt gatt = getGatt();
    if (gatt == null) {
        return null;
    }

    final BluetoothGattCharacteristic gattCharacteristic = gattCharacteristics.get(characteristicID);
    if (gattCharacteristic == null) {
        return null;
    }

    int properties = gattCharacteristic.getProperties();
    if ((properties & BluetoothGattCharacteristic.PROPERTY_READ) == 0) {
        return null;
    }

    //noinspection SynchronizationOnLocalVariableOrMethodParameter
    synchronized (gattCharacteristic) {
        final boolean didRead = gatt.readCharacteristic(gattCharacteristic);
        if (didRead) {
            try {
                gattCharacteristic.wait(GATT_READ_TIMEOUT);
            } catch (InterruptedException ignored) {
            }
        }

        return values.get(characteristicID);
    }
}
 
Example #27
Source File: BluetoothLeService.java    From BlunoAccessoryShieldDemo with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Request a read on a given {@code BluetoothGattCharacteristic}. The read result is reported
 * asynchronously through the {@code BluetoothGattCallback#onCharacteristicRead(android.bluetooth.BluetoothGatt, android.bluetooth.BluetoothGattCharacteristic, int)}
 * callback.
 *
 * @param characteristic The characteristic to read from.
 */
public void readCharacteristic(BluetoothGattCharacteristic characteristic) {
    if (mBluetoothAdapter == null || mBluetoothGatt == null) {
        Log.w(TAG, "BluetoothAdapter not initialized");
        return;
    }
    mBluetoothGatt.readCharacteristic(characteristic);
}
 
Example #28
Source File: DexCollectionService.java    From xDrip with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onCharacteristicChanged(BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic) {

    final PowerManager.WakeLock wakeLock1 = JoH.getWakeLock("DexCollectionService", 60000);
    try {
        final byte[] data = characteristic.getValue();

        if (data != null && data.length > 0) {
            setSerialDataToTransmitterRawData(data, data.length);

            final String hexdump = HexDump.dumpHexString(data);
            //if (!hexdump.contains("0x00000000 00      ")) {
            if (data.length > 1 || data[0] != 0x00) {
                static_last_hexdump = hexdump;
            }
            if (d) Log.i(TAG, "onCharacteristicChanged entered " + hexdump);

        }
        lastdata = data;

        Inevitable.task("dex-set-failover", 1000, () -> {
            setFailoverTimer(); // restart the countdown
            // intentionally left hanging wakelock for 5 seconds after we receive something
            final PowerManager.WakeLock wakeLock2 = JoH.getWakeLock("DexCollectionLinger", 5000);
        });

    } finally {
       /* if (Pref.getBoolean("bluetooth_frequent_reset", false)) {
            Log.e(TAG, "Resetting bluetooth due to constant reset option being set!");
            JoH.restartBluetooth(getApplicationContext(), 5000);
        }*/
        JoH.releaseWakeLock(wakeLock1);
    }
}
 
Example #29
Source File: ReadAllCommand.java    From neatle with MIT License 5 votes vote down vote up
@Override
protected void start(Connection connection, BluetoothGatt gatt) {
    List<BluetoothGattService> services = gatt.getServices();
    for (BluetoothGattService service : services) {
        List<BluetoothGattCharacteristic> characteristics = service.getCharacteristics();
        for (BluetoothGattCharacteristic characteristic : characteristics) {
            int props = characteristic.getProperties();
            if ((props & BluetoothGattCharacteristic.PROPERTY_READ) != 0) {
                queue.add(characteristic);
            }
        }
    }

    readNext(gatt);
}
 
Example #30
Source File: P_BleServer_Listeners.java    From SweetBlue with GNU General Public License v3.0 5 votes vote down vote up
@Override public void onCharacteristicReadRequest(final BluetoothDevice device, final int requestId, final int offset, final BluetoothGattCharacteristic characteristic)
{
	m_server.getManager().getPostManager().runOrPostToUpdateThread(new Runnable()
	{
		@Override public void run()
		{
			onReadRequest_updateThread(device, requestId, offset, characteristic.getService().getUuid(), characteristic.getUuid(), /*descUuid=*/null);
		}
	});
   }