Java Code Examples for android.bluetooth.BluetoothGattCharacteristic

The following examples show how to use android.bluetooth.BluetoothGattCharacteristic. These examples are extracted from open source projects. 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 Project: xDrip   Author: NightscoutFoundation   File: G5CollectionService.java    License: 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 #2
Source Project: Android-nRF-Toolbox   Author: NordicSemiconductor   File: BleManager.java    License: 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 #3
Source Project: Mi-Band   Author: betomaluje   File: BTConnectionManager.java    License: 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 #4
Source Project: BleLib   Author: junkchen   File: MultipleBleService.java    License: 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 #5
Source Project: myolib   Author: d4rken   File: BaseMyo.java    License: 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 #6
Source Project: blessed-android   Author: weliem   File: BluetoothPeripheralTest.java    License: 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 #7
Source Project: sony-smartband-open-api   Author: fbarriga   File: BtBridge.java    License: 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 #8
Source Project: AsteroidOSSync   Author: AsteroidOS   File: PA_ServiceManager.java    License: 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 #9
Source Project: Android-nRF-UART   Author: NordicPlayground   File: UartService.java    License: 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 #10
Source Project: Android-BLE   Author: aicareles   File: BleRequestImpl.java    License: 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 #11
Source Project: PolarHeartRateApplication   Author: marcolivierarsenault   File: H7ConnectThread.java    License: 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 #12
Source Project: bitgatt   Author: Fitbit   File: GattClientCallback.java    License: 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 #13
Source Project: AndroidBleManager   Author: haodynasty   File: DeviceControlActivity.java    License: 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 #14
Source Project: EFRConnect-android   Author: SiliconLabs   File: BLEUtils.java    License: 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 #15
Source Project: DeviceConnect-Android   Author: DeviceConnect   File: AbstractHOGPServer.java    License: 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 #16
Source Project: ESeal   Author: agenthun   File: ACSUtilityService.java    License: 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 #17
public BTLECommandSetCharacteristicNotification(BTLEDeviceManager.BTDeviceInfo	deviceInfo,
												BluetoothGattCharacteristic 	characteristic,
												boolean							fEnable) {
	super(deviceInfo);
	mCharacteristic = characteristic;
	mfEnable = fEnable;
}
 
Example #18
Source Project: Mi-Band   Author: betomaluje   File: BTConnectionManager.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
    super.onCharacteristicRead(gatt, characteristic, status);
    if (BluetoothGatt.GATT_SUCCESS == status) {
        if (io != null)
            io.onSuccess(characteristic);
    } else {
        io.onFail(status, "onCharacteristicRead fail");
    }
}
 
Example #19
Source Project: xDrip-plus   Author: jamorham   File: G5CollectionService.java    License: GNU General Public License v3.0 5 votes vote down vote up
private synchronized void doDisconnectMessage(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
       Log.d(TAG, "doDisconnectMessage() start");
       gatt.setCharacteristicNotification(controlCharacteristic, false);
       final DisconnectTxMessage disconnectTx = new DisconnectTxMessage();
       characteristic.setValue(disconnectTx.byteSequence);
       gatt.writeCharacteristic(characteristic);
       gatt.disconnect();
       Log.d(TAG, "doDisconnectMessage() finished");
}
 
Example #20
Source Project: bleTester   Author: SouthAve   File: CharacterisiticActivity.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressLint({ "NewApi", "DefaultLocale" })
@Override
public void onServiceConnected(ComponentName arg0, IBinder service) {
	// TODO Auto-generated method stub
	bleService = ((BleService.LocalBinder) service).getService();
	gattService = bleService.mBluetoothGatt.getService(uuid);
	bleService.mBluetoothGatt.readRemoteRssi();
	final ArrayList<HashMap<String, String>> charNames = new ArrayList<HashMap<String, String>>();
	final List<BluetoothGattCharacteristic> gattchars = gattService
			.getCharacteristics();
	for (BluetoothGattCharacteristic c : gattchars) {
		HashMap<String, String> currentCharData = new HashMap<String, String>();
		String uuidStr = c.getUuid().toString();
		currentCharData.put("Name", Utils.attributes
				.containsKey(uuidStr) ? Utils.attributes.get(uuidStr)
				: "Unknown Characteristics");
		charNames.add(currentCharData);
	}
	runOnUiThread(new Runnable() {
		@Override
		public void run() {
			// TODO Auto-generated method stub
			charListAdapter.addCharNames(charNames);
			charListAdapter.addChars(gattchars);
			charListAdapter.notifyDataSetChanged();
		}
	});
}
 
Example #21
Source Project: Bluefruit_LE_Connect_Android_V2   Author: adafruit   File: BlePeripheralUart.java    License: MIT License 5 votes vote down vote up
private void uartSendPacket(@NonNull byte[] data, int offset, BluetoothGattCharacteristic uartTxCharacteristic, int withResponseEveryPacketCount, int numPacketsRemainingForDelay, BlePeripheral.ProgressHandler progressHandler, BlePeripheral.CompletionHandler completionHandler) {
    final int packetSize = Math.min(data.length - offset, mBlePeripheral.getMaxPacketLength());
    final byte[] packet = Arrays.copyOfRange(data, offset, offset + packetSize);
    final int writeStartingOffset = offset;
    final int uartTxCharacteristicWriteType = numPacketsRemainingForDelay <= 0 ? BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT : BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE;          // Send a packet WRITE_TYPE_DEFAULT to force wait until receive response and avoid dropping packets if the peripheral is not processing them fast enough

    mBlePeripheral.writeCharacteristic(uartTxCharacteristic, uartTxCharacteristicWriteType, packet, status -> {
        int writtenSize = writeStartingOffset;

        if (status != BluetoothGatt.GATT_SUCCESS) {
            Log.w(TAG, "Error " + status + " writing packet at offset" + writeStartingOffset + " Error: " + status);
        } else {
            Log.d(TAG, "uart tx " + (uartTxCharacteristicWriteType == BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE ? "withoutResponse" : "withResponse") + " offset " + writeStartingOffset + ": " + BleUtils.bytesToHex2(packet));

            writtenSize += packet.length;

            if (!mIsSendSequentiallyCancelled && writtenSize < data.length) {
                //int finalWrittenSize = writtenSize;
                //handler.postDelayed(() -> uartSendPacket(handler, data, finalWrittenSize, uartTxCharacteristic, uartTxCharacteristicWriteType, delayBetweenPackets, progressHandler, completionHandler), delayBetweenPackets);
                uartSendPacket(data, writtenSize, uartTxCharacteristic, withResponseEveryPacketCount, numPacketsRemainingForDelay <= 0 ? withResponseEveryPacketCount : numPacketsRemainingForDelay - 1, progressHandler, completionHandler);
            }
        }

        if (mIsSendSequentiallyCancelled) {
            completionHandler.completion(BluetoothGatt.GATT_SUCCESS);
        } else if (writtenSize >= data.length) {
            progressHandler.progress(1);
            completionHandler.completion(status);
        } else {
            progressHandler.progress(writtenSize / (float) data.length);
        }
    });
}
 
Example #22
Source Project: SweetBlue   Author: iDevicesInc   File: GattDatabase.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Builds the current {@link BluetoothGattService}, and returns the parent {@link GattDatabase}.
 */
public final GattDatabase build()
{
    m_service = new BluetoothGattService(m_serviceUuid, m_isPrimary ? BluetoothGattService.SERVICE_TYPE_PRIMARY : BluetoothGattService.SERVICE_TYPE_SECONDARY);
    for (BluetoothGattCharacteristic ch : m_characteristics)
    {
        m_service.addCharacteristic(ch);
    }
    m_database.addService(m_service);
    return m_database;
}
 
Example #23
Source Project: RxAndroidBle   Author: Polidea   File: NotificationAndIndicationManager.java    License: Apache License 2.0 5 votes vote down vote up
@NonNull
static Completable setCharacteristicNotification(final BluetoothGatt bluetoothGatt,
                                                 final BluetoothGattCharacteristic characteristic,
                                                 final boolean isNotificationEnabled) {
    return Completable.fromAction(new Action() {
        @Override
        public void run() {
            if (!bluetoothGatt.setCharacteristicNotification(characteristic, isNotificationEnabled)) {
                throw new BleCannotSetCharacteristicNotificationException(
                        characteristic, BleCannotSetCharacteristicNotificationException.CANNOT_SET_LOCAL_NOTIFICATION, null
                );
            }
        }
    });
}
 
Example #24
Source Project: thunderboard-android   Author: SiliconLabs   File: BleManager.java    License: Apache License 2.0 5 votes vote down vote up
public boolean resetRevolutions() {
    boolean submitted = BleUtils.writeCharacteristics(gatt, ThunderBoardUuids
            .UUID_SERVICE_ACCELERATION_ORIENTATION, ThunderBoardUuids
            .UUID_CHARACTERISTIC_CSC_CONTROL_POINT, 0x01, BluetoothGattCharacteristic
            .FORMAT_UINT8, 0);
    Timber.d("submitted: %s", submitted);
    return submitted;
}
 
Example #25
Source Project: PHONK   Author: victordiaz   File: PBluetoothLEClient.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onCharacteristicWrite(BluetoothPeripheral peripheral, byte[] value, BluetoothGattCharacteristic characteristic, int status) {
    MLog.d(TAG, "onCharWrite");

    /*
    if( status == GATT_SUCCESS) {
        MLog.d(TAG, "SUCCESS: Writing <%s> to <%s>", bytes2String(value), characteristic.getUuid().toString());
    } else {
        MLog.d(TAG, "ERROR: Failed writing <%s> to <%s>", bytes2String(value), characteristic.getUuid().toString());
    }
     */
}
 
Example #26
Source Project: trigger   Author: mwarning   File: NukiPairingCallback.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void onConnected(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
    if (!this.setup.shared_key.isEmpty()) {
        this.listener.onTaskResult(setup_id, ReplyCode.LOCAL_ERROR, "Already paired to some device!");
        closeConnection(gatt);
        return;
    }

    NukiCommand.NukiRequest nr = new NukiCommand.NukiRequest(0x03);
    characteristic.setValue(NukiRequestHandler.crc_calc_and_add(nr.generate()));
    boolean ok = gatt.writeCharacteristic(characteristic);
    if (!ok) {
        Log.e(TAG, "writeCharacteristic failed for NukiRequest");
        closeConnection(gatt);
    }
}
 
Example #27
Source Project: Makeblock-App-For-Android   Author: Makeblock-official   File: BluetoothLE.java    License: MIT License 5 votes vote down vote up
/** 
 * BLE�ն����ݱ������¼� 
 */  
@Override  
public void onCharacteristicRead(BluetoothGatt gatt,  
        BluetoothGattCharacteristic characteristic, int status) {  
    if (status == BluetoothGatt.GATT_SUCCESS)   
        Log.d("mb","onCharRead "+gatt.getDevice().getName()  
                +" read "  
                +characteristic.getUuid().toString()  
                +" -> "  
                +Utils.bytesToHexString(characteristic.getValue()));  
}
 
Example #28
Source Project: blefun-androidthings   Author: Nilhcem   File: GattServer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void onCharacteristicReadRequest(BluetoothDevice device, int requestId, int offset, BluetoothGattCharacteristic characteristic) {
    if (CHARACTERISTIC_COUNTER_UUID.equals(characteristic.getUuid())) {
        Log.i(TAG, "Read counter");
        byte[] value = mListener.onCounterRead();
        mBluetoothGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, 0, value);
    } else {
        // Invalid characteristic
        Log.w(TAG, "Invalid Characteristic Read: " + characteristic.getUuid());
        mBluetoothGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_FAILURE, 0, null);
    }
}
 
Example #29
Source Project: android-BluetoothLeGatt   Author: googlearchive   File: BluetoothLeService.java    License: Apache License 2.0 5 votes vote down vote up
private void broadcastUpdate(final String action,
                             final BluetoothGattCharacteristic characteristic) {
    final Intent intent = new Intent(action);

    // This is special handling for the Heart Rate Measurement profile.  Data parsing is
    // carried out as per profile specifications:
    // http://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.heart_rate_measurement.xml
    if (UUID_HEART_RATE_MEASUREMENT.equals(characteristic.getUuid())) {
        int flag = characteristic.getProperties();
        int format = -1;
        if ((flag & 0x01) != 0) {
            format = BluetoothGattCharacteristic.FORMAT_UINT16;
            Log.d(TAG, "Heart rate format UINT16.");
        } else {
            format = BluetoothGattCharacteristic.FORMAT_UINT8;
            Log.d(TAG, "Heart rate format UINT8.");
        }
        final int heartRate = characteristic.getIntValue(format, 1);
        Log.d(TAG, String.format("Received heart rate: %d", heartRate));
        intent.putExtra(EXTRA_DATA, String.valueOf(heartRate));
    } else {
        // For all other profiles, writes the data formatted in HEX.
        final byte[] data = characteristic.getValue();
        if (data != null && data.length > 0) {
            final StringBuilder stringBuilder = new StringBuilder(data.length);
            for(byte byteChar : data)
                stringBuilder.append(String.format("%02X ", byteChar));
            intent.putExtra(EXTRA_DATA, new String(data) + "\n" + stringBuilder.toString());
        }
    }
    sendBroadcast(intent);
}
 
Example #30
Source Project: SweetBlue   Author: iDevicesInc   File: P_AndroidGatt.java    License: 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;
}