android.bluetooth.BluetoothGatt Java Examples
The following examples show how to use
android.bluetooth.BluetoothGatt.
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: BleManager.java From Android-nRF-Toolbox with BSD 3-Clause "New" or "Revised" License | 8 votes |
private boolean internalEnableIndications(final BluetoothGattCharacteristic characteristic) { final BluetoothGatt gatt = bluetoothGatt; if (gatt == null || characteristic == null) return false; // Check characteristic property final int properties = characteristic.getProperties(); if ((properties & BluetoothGattCharacteristic.PROPERTY_INDICATE) == 0) return false; gatt.setCharacteristicNotification(characteristic, true); final BluetoothGattDescriptor descriptor = characteristic.getDescriptor(CLIENT_CHARACTERISTIC_CONFIG_DESCRIPTOR_UUID); if (descriptor != null) { descriptor.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE); return internalWriteDescriptorWorkaround(descriptor); } return false; }
Example #2
Source File: EddystoneGattServer.java From beacons-android with Apache License 2.0 | 6 votes |
@Override public void onConnectionStateChange(BluetoothDevice device, int status, int newState) { super.onConnectionStateChange(device, status, newState); if (newState == BluetoothGatt.STATE_DISCONNECTED) { log(device + " has disconnected"); if (device.equals(mEddystoneGattService.getConnectedOwner())) { log("Owner disconnected, stopping GATT server"); mEddystoneGattService.onOwnerDisconnected(); close(); } } else if (newState == BluetoothGatt.STATE_CONNECTED) { log(device + " has connected"); if (mEddystoneGattService.getConnectedOwner() != null) { // don't allow a second client to connect at the same time log(device + " tried to connect, but owner is active. Disconnecting."); mGattServer.cancelConnection(device); } } }
Example #3
Source File: BleService.java From BLE-Heart-rate-variability-demo with MIT License | 6 votes |
@Override public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) { super.onConnectionStateChange(gatt, status, newState); String intentAction; if (newState == BluetoothProfile.STATE_CONNECTED) { intentAction = ACTION_GATT_CONNECTED; connectionState = STATE_CONNECTED; broadcastUpdate(intentAction); Log.i(TAG, "Connected to GATT server."); // Attempts to discover services after successful connection. Log.i(TAG, "Attempting to start service discovery:" + BleService.this.gatt.discoverServices()); } else if (newState == BluetoothProfile.STATE_DISCONNECTED) { intentAction = ACTION_GATT_DISCONNECTED; connectionState = STATE_DISCONNECTED; Log.i(TAG, "Disconnected from GATT server."); broadcastUpdate(intentAction); } }
Example #4
Source File: BluetoothLeService.java From WheelLogAndroid with GNU General Public License v3.0 | 6 votes |
@Override public void onServicesDiscovered(BluetoothGatt gatt, int status) { super.onServicesDiscovered(gatt, status); Timber.i("onServicesDiscovered called"); if (status == BluetoothGatt.GATT_SUCCESS) { Timber.i("onServicesDiscovered called, status == BluetoothGatt.GATT_SUCCESS"); boolean recognisedWheel = WheelData.getInstance().detectWheel(BluetoothLeService.this); if (recognisedWheel) { mConnectionState = STATE_CONNECTED; broadcastConnectionUpdate(mConnectionState); } else disconnect(); return; } Timber.i("onServicesDiscovered called, status == BluetoothGatt.GATT_FAILURE"); }
Example #5
Source File: BluetoothLeService.java From IoT-Firstep with GNU General Public License v3.0 | 6 votes |
@Override public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) { String intentAction; if (newState == BluetoothProfile.STATE_CONNECTED) { intentAction = ACTION_GATT_CONNECTED; broadcastUpdate(intentAction); Log.i(TAG, "Connected to GATT server."); // Attempts to discover services after successful connection. Log.i(TAG, "Attempting to start service discovery:" + mBluetoothGatt.discoverServices()); } else if (newState == BluetoothProfile.STATE_DISCONNECTED) { intentAction = ACTION_GATT_DISCONNECTED; Log.i(TAG, "Disconnected from GATT server."); broadcastUpdate(intentAction); } }
Example #6
Source File: BtBridge.java From sony-smartband-open-api with MIT License | 6 votes |
@Override // TODO: maybe here we should set status == CONNECTED public void onServicesDiscovered( BluetoothGatt gatt, int status ) { if( status != BluetoothGatt.GATT_SUCCESS ) { Log.e( CLASS, "onServicesDiscovered: Status != SUCCESS: status=" + status ); return; } mGatt = gatt; List<BluetoothGattService> services = gatt.getServices(); Log.d( CLASS, "onServicesDiscovered: services=" + services.size() ); for( BtBridgeListener listener : mListeners ) { listener.onServicesDiscovered( services ); } }
Example #7
Source File: MainActivity.java From easyble-x with Apache License 2.0 | 6 votes |
@Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); device = getIntent().getParcelableExtra("device"); setContentView(R.layout.activity_main); assignViews(); initViews(); //连接配置,举个例随意配置两项 ConnectionConfiguration config = new ConnectionConfiguration(); config.setConnectTimeoutMillis(10000); config.setRequestTimeoutMillis(1000); config.setAutoReconnect(false); // connection = EasyBLE.getInstance().connect(device, config, observer);//回调监听连接状态,设置此回调不影响观察者接收连接状态消息 connection = EasyBLE.getInstance().connect(device, config);//观察者监听连接状态 connection.setBluetoothGattCallback(new BluetoothGattCallback() { @Override public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { Log.d("EasyBLE", "原始写入数据:" + StringUtils.toHex(characteristic.getValue())); } }); }
Example #8
Source File: G5CollectionService.java From xDrip-plus with GNU General Public License v3.0 | 6 votes |
@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 #9
Source File: DfuBaseService.java From microbit with Apache License 2.0 | 6 votes |
private String readCharacteristicNoFailure(final BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic) { if (mConnectionState != STATE_CONNECTED_AND_READY) return "not_ready"; if (characteristic == null) return "unknown"; logi("readCharacteristicNoFailure"); gatt.readCharacteristic(characteristic); try { synchronized (mLock) { while ((!mRequestCompleted && mConnectionState == STATE_CONNECTED_AND_READY && mError == 0 && !mAborted) || mPaused) mLock.wait(); } } catch (final InterruptedException e) { loge("Sleeping interrupted", e); } if (mAborted) return "unknown"; if (mError != 0) return "unknown"; if (mConnectionState != STATE_CONNECTED_AND_READY) return "unknown"; return characteristic.getStringValue(0); }
Example #10
Source File: DexShareCollectionService.java From xDrip-Experimental with GNU General Public License v3.0 | 6 votes |
@Override public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { Log.d(TAG, "characteristic wrote " + status); if (status == BluetoothGatt.GATT_SUCCESS) { Log.d(TAG, "Wrote a characteristic successfully " + characteristic.getUuid()); if (mAuthenticationCharacteristic.getUuid().equals(characteristic.getUuid())) { state_authSucess = true; gatt.readCharacteristic(mHeartBeatCharacteristic); } } 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"); } } else { Log.e(TAG, "Unknown error writing Characteristic"); } }
Example #11
Source File: GattServerDisconnectTransaction.java From bitgatt with Mozilla Public License 2.0 | 6 votes |
@Override public void onServerConnectionStateChange(BluetoothDevice device, int status, int newState) { Timber.d("[%s] Gatt State %s, Disconnect Reason : %s", getDevice(), GattStatus.values()[status].name(), GattDisconnectReason.getReasonForCode(newState)); TransactionResult.Builder builder = new TransactionResult.Builder().transactionName(getName()); builder.responseStatus(GattDisconnectReason.getReasonForCode(status).ordinal()); if (status == BluetoothGatt.GATT_SUCCESS) { if (newState == BluetoothProfile.STATE_DISCONNECTED) { getGattServer().setState(GattState.DISCONNECTED); builder.gattState(getGattServer().getGattState()) .resultStatus(TransactionResult.TransactionResultStatus.SUCCESS); callCallbackWithTransactionResultAndRelease(callback, builder.build()); } else if (newState == BluetoothProfile.STATE_CONNECTED) { getGattServer().setState(GattState.CONNECTED); builder.gattState(getGattServer().getGattState()) .resultStatus(TransactionResult.TransactionResultStatus.FAILURE); callCallbackWithTransactionResultAndRelease(callback, builder.build()); } } else { builder.gattState(getGattServer().getGattState()) .resultStatus(TransactionResult.TransactionResultStatus.FAILURE); callCallbackWithTransactionResultAndRelease(callback, builder.build()); } }
Example #12
Source File: BluetoothLeService.java From android-BluetoothLeGatt with Apache License 2.0 | 6 votes |
@Override public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) { String intentAction; if (newState == BluetoothProfile.STATE_CONNECTED) { intentAction = ACTION_GATT_CONNECTED; mConnectionState = STATE_CONNECTED; broadcastUpdate(intentAction); Log.i(TAG, "Connected to GATT server."); // Attempts to discover services after successful connection. Log.i(TAG, "Attempting to start service discovery:" + mBluetoothGatt.discoverServices()); } else if (newState == BluetoothProfile.STATE_DISCONNECTED) { intentAction = ACTION_GATT_DISCONNECTED; mConnectionState = STATE_DISCONNECTED; Log.i(TAG, "Disconnected from GATT server."); broadcastUpdate(intentAction); } }
Example #13
Source File: BleManager.java From Bluefruit_LE_Connect_Android with MIT License | 6 votes |
/** * Call to private Android method 'refresh' * This method does actually clear the cache from a bluetooth device. But the problem is that we don't have access to it. But in java we have reflection, so we can access this method. * http://stackoverflow.com/questions/22596951/how-to-programmatically-force-bluetooth-low-energy-service-discovery-on-android */ public boolean refreshDeviceCache() { try { BluetoothGatt localBluetoothGatt = mGatt; Method localMethod = localBluetoothGatt.getClass().getMethod("refresh"); if (localMethod != null) { boolean result = (Boolean) localMethod.invoke(localBluetoothGatt); if (result) { Log.d(TAG, "Bluetooth refresh cache"); } return result; } } catch (Exception localException) { Log.e(TAG, "An exception occurred while refreshing device"); } return false; }
Example #14
Source File: BleGattImpl.java From EasyBle with Apache License 2.0 | 6 votes |
@Override public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { super.onCharacteristicWrite(gatt, characteristic, status); if (status == BluetoothGatt.GATT_SUCCESS) { String address = gatt.getDevice().getAddress(); String serviceUuid = characteristic.getService().getUuid().toString(); String characteristicUuid = characteristic.getUuid().toString(); OperationIdentify identify = getOperationIdentifyFromMap(mWriteCallbackMap, address, serviceUuid, characteristicUuid); if (identify == null) { return; } final BleWriteCallback callback = mWriteCallbackMap.get(identify); final BleDevice device = getBleDeviceFromMap(address, mConnectCallbackMap); final byte[] data = characteristic.getValue(); mHandler.post(new Runnable() { @Override public void run() { if (callback != null) { callback.onWriteSuccess(data, device); } } }); } }
Example #15
Source File: WriteCommandTest.java From neatle with MIT License | 6 votes |
@Test public void testInputSourceClosesOnError() throws IOException { when(gatt.getService(eq(serviceUUID))).thenReturn(gattService); when(gattService.getCharacteristic(characteristicUUID)).thenReturn(gattCharacteristic); when(gatt.writeCharacteristic(eq(gattCharacteristic))).thenReturn(true); InputSource inputSource = Mockito.mock(InputSource.class); when(inputSource.nextChunk()).thenThrow(new IOException()); writeCommand = new WriteCommand( serviceUUID, characteristicUUID, BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT, inputSource, commandObserver); writeCommand.execute(device, operationCommandObserver, gatt); writeCommand.onCharacteristicWrite(gatt, gattCharacteristic, BluetoothGatt.GATT_SUCCESS); verify(inputSource).close(); }
Example #16
Source File: MainActivity.java From SensorTag-CC2650 with Apache License 2.0 | 6 votes |
void onConnect() { if (mNumDevs > 0) { int connState = mBluetoothManager.getConnectionState(mBluetoothDevice, BluetoothGatt.GATT); switch (connState) { case BluetoothGatt.STATE_CONNECTED: mBluetoothLeService.disconnect(null); break; case BluetoothGatt.STATE_DISCONNECTED: boolean ok = mBluetoothLeService.connect(mBluetoothDevice.getAddress()); if (!ok) { setError("Connect failed"); } break; default: setError("Device busy (connecting/disconnecting)"); break; } } }
Example #17
Source File: H7ConnectThread.java From PolarHeartRateApplication with MIT License | 5 votes |
@Override public void onCharacteristicChanged(BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic) { byte[] data = characteristic.getValue(); int bmp = data[1] & 0xFF; // To unsign the value DataHandler.getInstance().cleanInput(bmp); Log.v("H7ConnectThread", "Data received from HR "+bmp); }
Example #18
Source File: UpdateFragment.java From Android-nRF-Beacon-for-Eddystone with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Override public void onServiceConnected(final ComponentName name, final IBinder service) { final UpdateService.ServiceBinder binder = mBinder = (UpdateService.ServiceBinder) service; final int state = binder.getState(); Log.v(TAG, "Connection state on rotation: " + state); switch (state) { case UpdateService.STATE_DISCONNECTED: binder.connect(); break; case UpdateService.STATE_CONNECTED: if (!hasOptionsMenu()) { setHasOptionsMenu(true); getActivity().invalidateOptionsMenu(); } mConnectButton.setText(R.string.action_disconnect); final Integer lockState = binder.getLockState(); if (lockState != null) { updateUiForBeacons(BluetoothGatt.STATE_CONNECTED, lockState); } switch(lockState){ case UNLOCKED: case UNLOCKED_AUTOMATIC_RELOCK_DISABLED: readCharacteristicsOnRotation(binder); break; } break; case UpdateService.STATE_CONNECTING: case UpdateService.STATE_DISCOVERING_SERVICES: if(mConnectionProgressDialog != null) { mConnectionProgressDialog.setTitle(getString(R.string.prog_dialog_connect_title)); mConnectionProgressDialog.setMessage(getString(R.string.prog_dialog_connect_message)); mConnectionProgressDialog.show(); } break; } }
Example #19
Source File: BluetoothPeripheral.java From blessed-android with MIT License | 5 votes |
@Override public void onConnectionStateChange(final BluetoothGatt gatt, final int status, final int newState) { long timePassed = SystemClock.elapsedRealtime() - connectTimestamp; cancelConnectionTimer(); final int previousState = state; state = newState; if (status == GATT_SUCCESS) { switch (newState) { case BluetoothProfile.STATE_CONNECTED: successfullyConnected(device.getBondState(), timePassed); break; case BluetoothProfile.STATE_DISCONNECTED: successfullyDisconnected(previousState); break; case BluetoothProfile.STATE_DISCONNECTING: Timber.i("peripheral is disconnecting"); break; case BluetoothProfile.STATE_CONNECTING: Timber.i("peripheral is connecting"); default: Timber.e("unknown state received"); break; } } else { connectionStateChangeUnsuccessful(status, previousState, newState, timePassed); } }
Example #20
Source File: P_Task_BatteryLevel.java From SweetBlue with GNU General Public License v3.0 | 5 votes |
public void onCharacteristicRead(BluetoothGatt gatt, UUID uuid, byte[] value, int gattStatus) { getManager().ASSERT(getDevice().layerManager().gattEquals(gatt)); if( false == this.isForCharacteristic(uuid) ) return; onCharacteristicOrDescriptorRead(gatt, uuid, value, gattStatus, BleDevice.ReadWriteListener.Type.READ); }
Example #21
Source File: SubscribeCommandTest.java From neatle with MIT License | 5 votes |
@Test public void testOnDescriptorWriteFail() { setupDescriptorSuccess(); subscribeCommand.execute(device, operationCommandObserver, gatt); subscribeCommand.onDescriptorWrite(gatt, gattDescriptor, BluetoothGatt.GATT_FAILURE); verifyCommandFail(subscribeCommand, BluetoothGatt.GATT_FAILURE); }
Example #22
Source File: BluetoothPeripheral.java From blessed-android with MIT License | 5 votes |
@Override public void onCharacteristicChanged(BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic) { final byte[] value = copyOf(characteristic.getValue()); callbackHandler.post(new Runnable() { @Override public void run() { peripheralCallback.onCharacteristicUpdate(BluetoothPeripheral.this, value, characteristic, GATT_SUCCESS); } }); }
Example #23
Source File: BluetoothPeripheral.java From blessed-android with MIT License | 5 votes |
@Override public void onReadRemoteRssi(BluetoothGatt gatt, final int rssi, final int status) { callbackHandler.post(new Runnable() { @Override public void run() { peripheralCallback.onReadRemoteRssi(BluetoothPeripheral.this, rssi, status); } }); completedCommand(); }
Example #24
Source File: ConnectOperation.java From RxAndroidBle with Apache License 2.0 | 5 votes |
private SingleTransformer<BluetoothGatt, BluetoothGatt> wrapWithTimeoutWhenNotAutoconnecting() { return new SingleTransformer<BluetoothGatt, BluetoothGatt>() { @Override public Single<BluetoothGatt> apply(Single<BluetoothGatt> bluetoothGattSingle) { return autoConnect ? bluetoothGattSingle : bluetoothGattSingle .timeout(connectTimeout.timeout, connectTimeout.timeoutTimeUnit, connectTimeout.timeoutScheduler, prepareConnectionTimeoutError()); } }; }
Example #25
Source File: P_ReliableWriteManager.java From SweetBlue with GNU General Public License v3.0 | 5 votes |
public void onReliableWriteCompleted_unsolicited(final BluetoothGatt gatt, final int gattStatus) { final BleDevice.ReadWriteListener listener = m_listener; m_listener = null; final BleDevice.ReadWriteListener.Status status = Utils.isSuccess(gattStatus) ? BleDevice.ReadWriteListener.Status.SUCCESS : BleDevice.ReadWriteListener.Status.REMOTE_GATT_FAILURE; final BleDevice.ReadWriteListener.ReadWriteEvent e = newEvent(status, gattStatus, /*solicited=*/false); m_device.invokeReadWriteCallback(listener, e); }
Example #26
Source File: BluetoothGattExecutor.java From BLE-Heart-rate-variability-demo with MIT License | 5 votes |
@Override public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { super.onCharacteristicWrite(gatt, characteristic, status); currentAction = null; execute(gatt); }
Example #27
Source File: PeripheralActivity.java From BLEService with BSD 3-Clause "New" or "Revised" License | 5 votes |
public void uiSuccessfulWrite(final BluetoothGatt gatt, final BluetoothDevice device, final BluetoothGattService service, final BluetoothGattCharacteristic ch, final String description) { runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(), "Writing to " + description + " was finished successfully!", Toast.LENGTH_LONG).show(); } }); }
Example #28
Source File: BaseBleService.java From bleYan with GNU General Public License v2.0 | 5 votes |
@Override public void onDescriptorRead(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) { final byte[] data = descriptor.getValue(); BleLog.i(TAG, "onCharacteristicRead: " + HexUtil.encodeHexStr(data)); UUID uuid = descriptor.getUuid(); sendBleMessage(BleConstants.MSG_BLE_ID_DESCRIPTOR_READ, status, data, uuid); onNextWrite(); }
Example #29
Source File: Device.java From neatle with MIT License | 5 votes |
@Override public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { NeatleLogger.d("createCharacteristicRead"); BluetoothGattCallback target; synchronized (lock) { target = currentCallback; } target.onCharacteristicRead(gatt, characteristic, status); }
Example #30
Source File: BLEManager.java From microbit with Apache License 2.0 | 5 votes |
@Override public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { super.onCharacteristicWrite(gatt, characteristic, status); synchronized(locker) { if(DEBUG) { logi("BluetoothGattCallback.onCharacteristicWrite() :: start : status = " + status); } if(inBleOp == OP_WRITE_CHARACTERISTIC) { if(DEBUG) { logi("BluetoothGattCallback.onCharacteristicWrite() :: inBleOp == OP_WRITE_CHARACTERISTIC"); } if(status == BluetoothGatt.GATT_SUCCESS) { error = BLE_ERROR_OK; } else { error = BLE_ERROR_FAIL; } lastCharacteristic = characteristic; callbackCompleted = true; locker.notify(); } if(DEBUG) { logi("BluetoothGattCallback.onCharacteristicWrite() :: end"); } } }