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: 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 #3
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 #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: 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 #6
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 #7
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 #8
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 #9
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 #10
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 #11
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 #12
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 #13
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 #14
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 #15
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 #16
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 #17
Source File: JoH.java From xDrip-plus with GNU General Public License v3.0 | 5 votes |
public static boolean refreshDeviceCache(String thisTAG, BluetoothGatt gatt){ try { final Method method = gatt.getClass().getMethod("refresh", new Class[0]); if (method != null) { return (Boolean) method.invoke(gatt, new Object[0]); } } catch (Exception e) { Log.e(thisTAG, "An exception occured while refreshing gatt device cache: "+e); } return false; }
Example #18
Source File: BluetoothGattShadow.java From BlueSTSDK_Android with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Implementation public boolean connect(){ if(userCallBack!=null) { Robolectric.getBackgroundThreadScheduler().postDelayed(new Runnable() { @Override public void run() { userCallBack.onConnectionStateChange(bluetoothGatt, BluetoothGatt.GATT_SUCCESS, BluetoothProfile.STATE_CONNECTED); } },CALLBACK_DELAY_MS); return true; } return false; }
Example #19
Source File: WriteCommandTest.java From neatle with MIT License | 5 votes |
@Test(timeout = 1000) public void testOnCharacteristicWriteFinishedAsyncSource() throws IOException { when(gatt.getService(eq(serviceUUID))).thenReturn(gattService); when(gattService.getCharacteristic(characteristicUUID)).thenReturn(gattCharacteristic); when(gatt.writeCharacteristic(eq(gattCharacteristic))).thenReturn(true); AsyncInputSource inputSource = Mockito.mock(AsyncInputSource.class); when(inputSource.nextChunk()).thenReturn(new byte[]{12, 21}); writeCommand = new WriteCommand( serviceUUID, characteristicUUID, BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT, inputSource, commandObserver); writeCommand.execute(device, operationCommandObserver, gatt); when(inputSource.nextChunk()).thenReturn(null); writeCommand.onCharacteristicWrite(gatt, gattCharacteristic, BluetoothGatt.GATT_SUCCESS); while (writeCommand.readerThread.isAlive()) { Robolectric.getForegroundThreadScheduler().advanceBy(0, TimeUnit.MILLISECONDS); Thread.yield(); } Robolectric.getForegroundThreadScheduler().advanceBy(0, TimeUnit.MILLISECONDS); CommandResult result = CommandResult.createEmptySuccess(characteristicUUID); verify(commandObserver, only()).finished(eq(writeCommand), refEq(result, "timestamp")); verify(operationCommandObserver, only()).finished(eq(writeCommand), refEq(result, "timestamp")); verify(inputSource).close(); }
Example #20
Source File: P_PollManager.java From SweetBlue with GNU General Public License v3.0 | 5 votes |
final ReadWriteEvent newAlreadyEnabledEvent(BluetoothGattCharacteristic characteristic, final UUID serviceUuid, final UUID characteristicUuid, final DescriptorFilter descriptorFilter) { //--- DRK > Just being anal with the null check here. byte[] writeValue = characteristic != null ? P_Task_ToggleNotify.getWriteValue(characteristic, /*enable=*/true) : P_Const.EMPTY_BYTE_ARRAY; int gattStatus = BluetoothGatt.GATT_SUCCESS; ReadWriteEvent result = new ReadWriteEvent(m_device, serviceUuid, characteristicUuid, Uuids.CLIENT_CHARACTERISTIC_CONFIGURATION_DESCRIPTOR_UUID, descriptorFilter, Type.ENABLING_NOTIFICATION, Target.DESCRIPTOR, writeValue, Status.SUCCESS, gattStatus, 0.0, 0.0, /*solicited=*/true); return result; }
Example #21
Source File: ESenseManager.java From flutter-plugins with MIT License | 5 votes |
@Override public void onServicesDiscovered(BluetoothGatt gatt, int status) { for (BluetoothGattService s : gatt.getServices()) { for (BluetoothGattCharacteristic c : s.getCharacteristics()) { mCharacteristicMap.put(getKey(c), c); } } // Fire onConnected event after all the services have been discovered if(mConnectionListener != null) { mConnectionListener.onConnected(ESenseManager.this); } }
Example #22
Source File: BleUtils.java From thunderboard-android with Apache License 2.0 | 5 votes |
private static List<BluetoothGattCharacteristic> findCharacteristics(BluetoothGatt gatt, UUID serviceUuid, UUID characteristicUuid, int property) { if (serviceUuid == null) { return null; } if (characteristicUuid == null) { return null; } if (gatt == null) { return null; } BluetoothGattService service = gatt.getService(serviceUuid); if (service == null) { return null; } List<BluetoothGattCharacteristic> results = new ArrayList<>(); for (BluetoothGattCharacteristic c : service.getCharacteristics()) { int props = c.getProperties(); if (characteristicUuid.equals(c.getUuid()) && (property == (property & props))) { results.add(c); } } return results; }
Example #23
Source File: CommandResultTest.java From neatle with MIT License | 5 votes |
@Test public void testIntValues() { CommandResult commandResult = new CommandResult(Neatle.createUUID(1), new byte[]{22, 21}, BluetoothGatt.GATT_SUCCESS, 1); assertArrayEquals(new byte[]{22, 21}, commandResult.getValue()); CommandResult commandResult1 = new CommandResult(Neatle.createUUID(1), new byte[]{22}, BluetoothGatt.GATT_SUCCESS, 1); CommandResult commandResult2 = new CommandResult(Neatle.createUUID(1), new byte[]{22, 21}, BluetoothGatt.GATT_SUCCESS, 1); CommandResult commandResult3 = new CommandResult(Neatle.createUUID(1), new byte[]{22, 21, 20}, BluetoothGatt.GATT_SUCCESS, 1); CommandResult commandResult4 = new CommandResult(Neatle.createUUID(1), new byte[]{22, 21, 20, 19}, BluetoothGatt.GATT_SUCCESS, 1); assertEquals(22, commandResult1.getValueAsInt()); assertEquals(5653, commandResult2.getValueAsInt()); assertEquals(1447188, commandResult3.getValueAsInt()); assertEquals(370480147, commandResult4.getValueAsInt()); }
Example #24
Source File: GattClientCallback.java From bitgatt with Mozilla Public License 2.0 | 5 votes |
@Override public void onPhyRead(BluetoothGatt gatt, int txPhy, int rxPhy, int status) { super.onPhyRead(gatt, txPhy, rxPhy, status); Timber.v("[%s] onPhyRead: 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); for (GattClientListener listener : copy) { if(listener.getDevice() != null && gatt != null && listener.getDevice().equals(gatt.getDevice())) { handler.post(() -> listener.onPhyRead(gatt, txPhy, rxPhy, status)); } } }
Example #25
Source File: ReadAllCommand.java From neatle with MIT License | 5 votes |
@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 #26
Source File: BleManager.java From BLEChat with GNU General Public License v3.0 | 5 votes |
@Override // New services discovered public void onServicesDiscovered(BluetoothGatt gatt, int status) { if (status == BluetoothGatt.GATT_SUCCESS) { Logs.d(TAG, "# New GATT service discovered."); checkGattServices(gatt.getServices()); } else { Logs.d(TAG, "# onServicesDiscovered received: " + status); } }
Example #27
Source File: LoggerUtil.java From RxAndroidBle with Apache License 2.0 | 5 votes |
public static void logConnectionUpdateCallback(String callbackName, BluetoothGatt gatt, int status, int interval, int latency, int timeout) { if (!RxBleLog.isAtLeast(LogConstants.INFO)) { return; } String customValueMessage = ", interval=%d (%.2f ms), latency=%d, timeout=%d (%.0f ms)"; RxBleLog.i(commonMacMessage(gatt) + commonCallbackMessage() + commonStatusMessage() + customValueMessage, callbackName, status, interval, interval * 1.25f, latency, timeout, timeout * 10f); }
Example #28
Source File: DeviceMirror.java From BLE with Apache License 2.0 | 5 votes |
/** * 阅读设备信号值 * @param gatt GATT * @param rssi 设备当前信号 * @param status 当前状态 */ @Override public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) { ViseLog.i("onReadRemoteRssi status: " + status + ", rssi:" + rssi + " ,thread: " + Thread.currentThread()); if (status == BluetoothGatt.GATT_SUCCESS) { if (rssiCallback != null) { rssiCallback.onSuccess(rssi); } } else { if (rssiCallback != null) { rssiCallback.onFailure(new GattException(status)); } } }
Example #29
Source File: MainActivity.java From NewXmPluginSDK with Apache License 2.0 | 5 votes |
@Override public void onConnectionStateChange(BluetoothDevice device, int status, int newState) throws RemoteException { BluetoothLog.v(String.format("%s.onConnectionStateChange: status = %d, newState = %d", TAG, status, newState)); if (newState == BluetoothGatt.STATE_CONNECTED) { mHandler.sendEmptyMessageDelayed(0, NOTIFY_CYCLE); } else if (newState == BluetoothGatt.STATE_DISCONNECTED) { } }
Example #30
Source File: UartService.java From gsn with GNU General Public License v3.0 | 5 votes |
@Override public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { if (status == BluetoothGatt.GATT_SUCCESS) { broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic); } }