Java Code Examples for android.bluetooth.BluetoothGatt

The following are top voted examples for showing how to use android.bluetooth.BluetoothGatt. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: neatle   File: ReadCommand.java   Source Code and License 8 votes vote down vote up
@Override
protected void start(Connection connection, BluetoothGatt gatt) {
    BluetoothGattService service = gatt.getService(serviceUUID);
    if (service != null) {
        BluetoothGattCharacteristic characteristic = service.getCharacteristic(characteristicUUID);
        if (characteristic != null) {
            NeatleLogger.d("Reading characteristics " + characteristicUUID);
            if (gatt.readCharacteristic(characteristic)) {
                return;
            }
            NeatleLogger.d("Read failed" + characteristicUUID);
        } else {
            NeatleLogger.e("Could not find characteristics " + characteristicUUID);
        }
    } else {
        NeatleLogger.e("Could not find service " + serviceUUID);
    }

    finish(CommandResult.createErrorResult(characteristicUUID, BluetoothGatt.GATT_FAILURE));
}
 
Example 2
Project: blefun-androidthings   File: GattClient.java   Source Code and License 7 votes vote down vote up
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
    if (status == BluetoothGatt.GATT_SUCCESS) {
        boolean connected = false;

        BluetoothGattService service = gatt.getService(SERVICE_UUID);
        if (service != null) {
            BluetoothGattCharacteristic characteristic = service.getCharacteristic(CHARACTERISTIC_COUNTER_UUID);
            if (characteristic != null) {
                gatt.setCharacteristicNotification(characteristic, true);

                BluetoothGattDescriptor descriptor = characteristic.getDescriptor(DESCRIPTOR_CONFIG);
                if (descriptor != null) {
                    descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
                    connected = gatt.writeDescriptor(descriptor);
                }
            }
        }
        mListener.onConnected(connected);
    } else {
        Log.w(TAG, "onServicesDiscovered received: " + status);
    }
}
 
Example 3
Project: Make-A-Pede-Android-App   File: BluetoothLeService.java   Source Code and License 6 votes vote down vote up
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
	String intentAction;
	if (newState == BluetoothProfile.STATE_CONNECTED) {
		intentAction = ACTION_CONNECTED;
		connectionState = STATE_CONNECTED;
		broadcastUpdate(intentAction);
		Log.i(TAG, "Connected to GATT server.");
		Log.i(TAG, "Attempting to start service discovery:" + bluetoothGatt.discoverServices());

	} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
		intentAction = ACTION_DISCONNECTED;
		connectionState = STATE_DISCONNECTED;
		Log.i(TAG, "Disconnected from GATT server.");
		broadcastUpdate(intentAction);
	}
}
 
Example 4
Project: boohee_v5.6   File: QNBleHelper.java   Source Code and License 6 votes vote down vote up
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
    if (this.mGatt != gatt) {
        this.mGatt = gatt;
    }
    if (newState == 2) {
        QNLog.log("连接设备成功");
        this.qnDecoder = null;
        this.mGatt.discoverServices();
    } else if (newState == 0) {
        this.mGatt.close();
        this.uiHandler.post(new 1 (this));
        this.qnDecoder = null;
    } else {
        gatt.disconnect();
        QNLog.error("连接状态异常:", Integer.valueOf(status));
        this.uiHandler.post(new 2 (this));
        if (this.bleCallback != null) {
            this.bleCallback.onCompete(5);
        }
    }
}
 
Example 5
Project: Bluetooth_BLE   File: BleGattCallback.java   Source Code and License 6 votes vote down vote up
/**
 * 相当于一个监听器, 当蓝牙设备有数据返回时执行
 *
 * @param gatt
 * @param characteristic
 */
@Override
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
    Log.e(TAG, "onCharacteristicChanged 返回数据: " + Arrays.toString(characteristic.getValue()));
    Message message = new Message();
    message.what = Constant.RESULT_DATA;
    message.obj = characteristic.getValue();
    handler.sendMessage(message);
    //回调
    onCharacteristicRefresh(gatt, characteristic);
}
 
Example 6
Project: react-native-blue-manager   File: Peripheral.java   Source Code and License 6 votes vote down vote up
@Override
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
	super.onCharacteristicWrite(gatt, characteristic, status);

	if (writeCallback != null) {

		if (writeQueue.size() > 0){
			byte[] data = writeQueue.get(0);
			writeQueue.remove(0);
			doWrite(characteristic, data);
		} else {

			if (status == BluetoothGatt.GATT_SUCCESS) {
				writeCallback.invoke();
			} else {
				Log.e(LOG_TAG, "Error onCharacteristicWrite:" + status);
				writeCallback.invoke("Error writing status: " + status);
			}

			writeCallback = null;
		}
	}else
		Log.e(LOG_TAG, "No callback on write");
}
 
Example 7
Project: TrainAppTFG   File: BluetoothLeService.java   Source Code and License 6 votes vote down vote up
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
    super.onConnectionStateChange(gatt, status, newState);

    Log.d("BLUETOOTH", "Estado de conexión bluetooth: " + (newState == BluetoothProfile.STATE_CONNECTED ? "Connected" : "Disconnected"));

    if(newState == BluetoothProfile.STATE_CONNECTED){
        //setState(State.CONNECTED);
        mBluetoothGatt.discoverServices();
    }
    else{
        //setState(State.IDDLE);
        //TODO Realizar todas las tareas necesarias cuando se desconecte la pulsera
        Log.d("BLUETOOTH", "Se ha desconectado el dispostivo bluetooth");
    }
}
 
Example 8
Project: TrainAppTFG   File: BluetoothLeService.java   Source Code and License 6 votes vote down vote up
private boolean obtenerCaracteristicasDescriptoresAccelGyroCC2650(BluetoothGatt gatt){
    boolean todoCorrecto = false;

    BluetoothGattService acelerometroService = gatt.getService(UUID_MOVEMENT_SERVICE);
    if(acelerometroService != null){
        this.movementCharacteristic = acelerometroService.getCharacteristic(UUID_MOVEMENT_DATA);
        this.movementConf = acelerometroService.getCharacteristic(UUID_MOVEMENT_CONF);
        this.movementPeriod = acelerometroService.getCharacteristic(UUID_MOVEMENT_PERIOD);

        if(movementCharacteristic != null && movementConf != null){
            this.config = movementCharacteristic.getDescriptor(UUID_CCC);
            todoCorrecto = true;
        }
    }

    return todoCorrecto;
}
 
Example 9
Project: Bluetooth_BLE   File: LiteBluetooth.java   Source Code and License 6 votes vote down vote up
/**
  * Clears the device cache. After uploading new hello4 the DFU target will have other services than before.
  * 清除设备缓存。 在上传新的hello4之后,DFU目标将具有比以前更多的服务。
  */
 public boolean refreshDeviceCache() {
     /*
      * There is a refresh() method in BluetoothGatt class but for now it's hidden. We will call it using reflections.
      * 使用反射调用
*/
     try {
         final Method refresh = BluetoothGatt.class.getMethod("refresh");
         if (refresh != null) {
             final boolean success = (Boolean) refresh.invoke(getBluetoothGatt());
             Log.i(TAG, "Refreshing result: " + success);
             return success;
         }
     } catch (Exception e) {
         Log.e(TAG, "An exception occured while refreshing device", e);
     }
     return false;
 }
 
Example 10
Project: UDOOBluLib-android   File: UdooBluService.java   Source Code and License 6 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(final String mac, final BluetoothGattCharacteristic characteristic) {
    try {
        voidBlockingQueue.put(new Callable<Boolean>() {
            @Override
            public Boolean call() throws Exception {
                BluetoothGatt bluetoothGatt = checkAndGetGattItem(mac);
                boolean success = false;
                if (bluetoothGatt != null && characteristic != null) {
                    success = bluetoothGatt.readCharacteristic(characteristic);
                }
                return success;
            }
        });

    } catch (InterruptedException e) {
        if (BuildConfig.DEBUG)
            Log.e(TAG, "readCharacteristic: " + e.getMessage());
    }
}
 
Example 11
Project: Bluetooth_BLE   File: LiteBleConnector.java   Source Code and License 6 votes vote down vote up
/**
 * 处理向特征码写入数据的回调
 * @param bleCallback
 */
private void handleCharacteristicWriteCallback(final BleCharactCallback bleCallback) {
    if (bleCallback != null) {
        // 添加连接回调到LiteBluetooth的回调集合中
        listenAndTimer(bleCallback, MSG_WRIATE_CHA, new BluetoothGattCallback() {
            @Override
            public void onCharacteristicWrite(BluetoothGatt gatt,
                                              BluetoothGattCharacteristic characteristic, int status) {
                handler.removeMessages(MSG_WRIATE_CHA, this);
                if (status == BluetoothGatt.GATT_SUCCESS) {
                    bleCallback.onSuccess(characteristic);
                } else {
                    bleCallback.onFailure(new GattException(status));
                }
            }
        });
    }
}
 
Example 12
Project: UDOOBluLib-android   File: UdooBluService.java   Source Code and License 6 votes vote down vote up
/**
 * Disconnects an existing connection or cancel a pending connection. The disconnection result is reported asynchronously through the
 * {@code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)} callback.
 */
public void disconnect(String address) {
    if (mBtAdapter == null) {
        Log.w(TAG, "disconnect: BluetoothAdapter not initialized");
        return;
    }
    final BluetoothDevice device = mBtAdapter.getRemoteDevice(address);
    int connectionState = mBluetoothManager.getConnectionState(device, BluetoothProfile.GATT);
    BluetoothGatt bluetoothGatt = checkAndGetGattItem(address);
    if (bluetoothGatt != null) {
        Log.i(TAG, "disconnect");
        if (connectionState != BluetoothProfile.STATE_DISCONNECTED) {
            bluetoothGatt.disconnect();
        } else {
            Log.w(TAG, "Attempt to disconnect in state: " + connectionState);
        }
    }
}
 
Example 13
Project: Android-DFU-App   File: BleManager.java   Source Code and License 6 votes vote down vote up
@Override
public final void onCharacteristicChanged(final BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic) {
	final String data = ParserUtils.parse(characteristic);

	if (isBatteryLevelCharacteristic(characteristic)) {
		Logger.i(mLogSession, "Notification received from " + characteristic.getUuid() + ", value: " + data);
		final int batteryValue = characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8, 0);
		Logger.a(mLogSession, "Battery level received: " + batteryValue + "%");
		mCallbacks.onBatteryValueReceived(batteryValue);
	} else {
		final BluetoothGattDescriptor cccd = characteristic.getDescriptor(CLIENT_CHARACTERISTIC_CONFIG_DESCRIPTOR_UUID);
		final boolean notifications = cccd == null || cccd.getValue() == null || cccd.getValue().length != 2 || cccd.getValue()[0] == 0x01;

		if (notifications) {
			Logger.i(mLogSession, "Notification received from " + characteristic.getUuid() + ", value: " + data);
			onCharacteristicNotified(gatt, characteristic);
		} else { // indications
			Logger.i(mLogSession, "Indication received from " + characteristic.getUuid() + ", value: " + data);
			onCharacteristicIndicated(gatt, characteristic);
		}
	}
}
 
Example 14
Project: Android-DFU-App   File: TemplateManager.java   Source Code and License 6 votes vote down vote up
@Override
protected void onCharacteristicNotified(final BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic) {
	// TODO this method is called when a notification has been received
	// This method may be removed from this class if not required

	if (mLogSession != null)
		Logger.a(mLogSession, TemplateParser.parse(characteristic));

	int value;
	final int flags = characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8, 0);
	if ((flags & 0x01) > 0) {
		value = characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT16, 1);
	} else {
		value = characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8, 1);
	}
	//This will send callback to the Activity when new value is received from HR device
	mCallbacks.onSampleValueReceived(value);
}
 
Example 15
Project: AndroidMuseumBleManager   File: BluetoothConnectInterface.java   Source Code and License 6 votes vote down vote up
@Override
public void onServicesDiscovered(final BluetoothGatt gatt, int status) {
    Logger.i("onServicesDiscovered status=" + GattError.parseConnectionError(status));
    if (status == BluetoothGatt.GATT_SUCCESS) {
        //start subscribe data
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                onDiscoverServicesSuccess(gatt);
                if (gatt != null){
                    startSubscribe(gatt);
                }
            }
        });
    }else {
        Logger.e("onServicesDiscovered fail!");
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                onDiscoverServicesFail(gatt);
            }
        });
    }
    if (getBluetoothGattCallback() != null) getBluetoothGattCallback().onServicesDiscovered(gatt, status);
}
 
Example 16
Project: neatle   File: Device.java   Source Code and License 6 votes vote down vote up
private void discoverDevice() {
    boolean isScanning = false;

    do {
        if (adapter == null || adapter.getState() != BluetoothAdapter.STATE_ON) {
            isScanning = false;
            break;
        }

        //FIXME: Switch to non-deprecated method.
        if (!adapter.startLeScan(discoverCallback)) {
            isScanning = true;
            break;
        }
    } while (false);

    if (isScanning) {
        NeatleLogger.e("Failed to start device discovery. Failing connection attempt");
        connectionFailed(BluetoothGatt.GATT_FAILURE);
    } else {
        handler.postDelayed(discoverWatchdog, DISCOVER_DEVICE_TIMEOUT);
    }
}
 
Example 17
Project: neatle   File: WriteCommandTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testOnCharacteristicWriteNextChunk() 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()).thenReturn(new byte[]{12, 21});

    writeCommand = new WriteCommand(
            serviceUUID,
            characteristicUUID,
            BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT,
            inputSource,
            commandObserver);

    writeCommand.execute(device, operationCommandObserver, gatt);

    writeCommand.onCharacteristicWrite(gatt, gattCharacteristic, BluetoothGatt.GATT_SUCCESS);
    verify(commandObserver, times(0)).finished(any(Command.class), any(CommandResult.class));
    verify(operationCommandObserver, times(0)).finished(any(Command.class), any(CommandResult.class));
}
 
Example 18
Project: BLE-PEPS   File: BluetoothLeClass.java   Source Code and License 6 votes vote down vote up
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
    if (newState == BluetoothProfile.STATE_CONNECTED) {
        if(mOnConnectListener!=null)
            mOnConnectListener.onConnect(gatt);
        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) {
        if(mOnDisconnectListener!=null)
            mOnDisconnectListener.onDisconnect(gatt);
        Log.i(TAG, "Disconnected from GATT server.");
    }

    if(mOnConnectStatusChangedListener!=null)
        mOnConnectStatusChangedListener.onConnectStatusChanged(gatt,status,newState);
        Log.i(TAG, "Changed");

}
 
Example 19
Project: Android-DFU-App   File: GattError.java   Source Code and License 6 votes vote down vote up
/**
 * Converts the connection status given by the {@link android.bluetooth.BluetoothGattCallback#onConnectionStateChange(BluetoothGatt, int, int)} to error name.
 * @param error the status number
 * @return the error name as stated in the gatt_api.h file
 */
public static String parseConnectionError(final int error) {
	switch (error) {
		case BluetoothGatt.GATT_SUCCESS:
			return "SUCCESS";
		case 0x01:
			return "GATT CONN L2C FAILURE";
		case 0x08:
			return "GATT CONN TIMEOUT";
		case 0x13:
			return "GATT CONN TERMINATE PEER USER";
		case 0x16:
			return "GATT CONN TERMINATE LOCAL HOST";
		case 0x3E:
			return "GATT CONN FAIL ESTABLISH";
		case 0x22:
			return "GATT CONN LMP TIMEOUT";
		case 0x0100:
			return "GATT CONN CANCEL ";
		case 0x0085:
			return "GATT ERROR"; // Device not reachable
		default:
			return "UNKNOWN (" + error + ")";
	}
}
 
Example 20
Project: AndroidMuseumBleManager   File: ConnectRequestQueue.java   Source Code and License 5 votes vote down vote up
@Override
protected void onDeviceDisconnect(BluetoothGatt gatt, int errorState) {
    Logger.e( "Disconnected from GATT server address:" + gatt.getDevice().getAddress());
    //可以不关闭,以便重用,因为在连接connect的时候可以快速连接
    if (!mBluetoothUtils.isBluetoothIsEnable()){
        //关闭所有的设备
        closeAll();
    }else {
        close(gatt.getDevice().getAddress());//防止出现status 133
    }
}
 
Example 21
Project: BLE-PEPS   File: BluetoothLeClass.java   Source Code and License 5 votes vote down vote up
@Override
public void onReadRemoteRssi(BluetoothGatt gatt,
                             int rssi,
                             int status) {
    if (mOnDataAvailableListener!=null)
        mOnDataAvailableListener.onReadRemoteRssi(gatt, rssi, status);
}
 
Example 22
Project: Android-DFU-App   File: ProximityManager.java   Source Code and License 5 votes vote down vote up
@Override
public void onCharacteristicWriteRequest(final BluetoothDevice device, final int requestId, final BluetoothGattCharacteristic characteristic, final boolean preparedWrite,
										 final boolean responseNeeded, final int offset, final byte[] value) {
	Logger.d(mLogSession, "[Server callback] Write request to characteristic " + characteristic.getUuid()
			+ " (requestId=" + requestId + ", prepareWrite=" + preparedWrite + ", responseNeeded=" + responseNeeded + ", offset=" + offset + ", value=" + ParserUtils.parse(value) + ")");
	final String writeType = !responseNeeded ? "WRITE NO RESPONSE" : "WRITE COMMAND";
	Logger.i(mLogSession, "[Server] " + writeType + " request for characteristic " + characteristic.getUuid() + " received, value: " + ParserUtils.parse(value));

	if (offset == 0) {
		characteristic.setValue(value);
	} else {
		final byte[] currentValue = characteristic.getValue();
		final byte[] newValue = new byte[currentValue.length + value.length];
		System.arraycopy(currentValue, 0, newValue, 0, currentValue.length);
		System.arraycopy(value, 0, newValue, offset, value.length);
		characteristic.setValue(newValue);
	}

	if (!preparedWrite && value != null && value.length == 1) { // small validation
		if (value[0] != NO_ALERT[0]) {
			Logger.a(mLogSession, "[Server] Immediate alarm request received: " + AlertLevelParser.parse(characteristic));
			mCallbacks.onAlarmTriggered();
		} else {
			Logger.a(mLogSession, "[Server] Immediate alarm request received: OFF");
			mCallbacks.onAlarmStopped();
		}
	}

	Logger.d(mLogSession, "server.sendResponse(GATT_SUCCESS, offset=" + offset + ", value=" + ParserUtils.parse(value) + ")");
	mBluetoothGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, offset, null);
	Logger.v(mLogSession, "[Server] Response sent");
}
 
Example 23
Project: Android-DFU-App   File: RSCManager.java   Source Code and License 5 votes vote down vote up
@Override
public boolean isRequiredServiceSupported(final BluetoothGatt gatt) {
	final BluetoothGattService service = gatt.getService(RUNNING_SPEED_AND_CADENCE_SERVICE_UUID);
	if (service != null) {
		mRSCMeasurementCharacteristic = service.getCharacteristic(RSC_MEASUREMENT_CHARACTERISTIC_UUID);
	}
	return mRSCMeasurementCharacteristic != null;
}
 
Example 24
Project: microbit   File: DfuBaseService.java   Source Code and License 5 votes vote down vote up
@Override
public void onServicesDiscovered(final BluetoothGatt gatt, final int status) {
    // Notify waiting thread
    logi("onServicesDiscovered() :: Start");
    if (status == BluetoothGatt.GATT_SUCCESS) {
        logi("onServicesDiscovered() :: Services discovered");
        mConnectionState = STATE_CONNECTED_AND_READY;
    } else {
        loge("onServicesDiscovered() :: Service discovery error: " + status);
        mError = ERROR_CONNECTION_MASK | status;
    }
    synchronized (mLock) {
        mLock.notifyAll();
    }
}
 
Example 25
Project: neatle   File: SubscribeCommandTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testOnError() {
    setupDescriptorSuccess();
    subscribeCommand.execute(device, operationCommandObserver, gatt);

    subscribeCommand.onError(BluetoothGatt.GATT_FAILURE);
    verifyCommandFail(subscribeCommand, BluetoothGatt.GATT_FAILURE);
}
 
Example 26
Project: blefun-androidthings   File: GattClient.java   Source Code and License 5 votes vote down vote up
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
    if (newState == BluetoothProfile.STATE_CONNECTED) {
        Log.i(TAG, "Connected to GATT client. Attempting to start service discovery");
        gatt.discoverServices();
    } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
        Log.i(TAG, "Disconnected from GATT client");
        mListener.onConnected(false);
    }
}
 
Example 27
Project: Android-DFU-App   File: ProximityManager.java   Source Code and License 5 votes vote down vote up
@Override
public void onExecuteWrite(final BluetoothDevice device, final int requestId, final boolean execute) {
	Logger.d(mLogSession, "[Server callback] Execute write request (requestId=" + requestId + ", execute=" + execute + ")");
	// This method is not supported
	Logger.w(mLogSession, "[Server] Operation not supported");
	Logger.d(mLogSession, "[Server] server.sendResponse(GATT_REQUEST_NOT_SUPPORTED)");
	mBluetoothGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_REQUEST_NOT_SUPPORTED, 0, null);
	Logger.v(mLogSession, "[Server] Response sent");
}
 
Example 28
Project: UDOOBluLib-android   File: UdooBluService.java   Source Code and License 5 votes vote down vote up
public boolean isNotificationEnabled(String mac, BluetoothGattCharacteristic characteristic) {
    BluetoothGatt bluetoothGatt = checkAndGetGattItem(mac);
    boolean result = false;
    if (bluetoothGatt != null) {
        BluetoothGattDescriptor clientConfig = characteristic.getDescriptor(GattInfo.CLIENT_CHARACTERISTIC_CONFIG);
        if (clientConfig != null) {
            result = clientConfig.getValue() == BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE;
        }
    }
    return result;
}
 
Example 29
Project: Bluetooth_BLE   File: BluetoothUtil.java   Source Code and License 5 votes vote down vote up
/**
 * 关闭GATT连接
 * @param gatt
 */
public static void closeBluetoothGatt(BluetoothGatt gatt) {
    if (gatt != null) {
        gatt.disconnect();
        refreshDeviceCache(gatt);
        gatt.close();
    }
}
 
Example 30
Project: microbit   File: DfuBaseService.java   Source Code and License 5 votes vote down vote up
/**
 * <p>
 * Writes the Soft Device, Bootloader and Application image sizes to the characteristic. Soft Device and Bootloader update is supported since Soft Device s110 v7.0.0.
 * Sizes of SD, BL and App are uploaded as 3x UINT32 even though some of them may be 0s. F.e. if only App is being updated the data will be <0x00000000, 0x00000000, [App size]>
 * </p>
 * <p>
 * This method is SYNCHRONOUS and wait until the {@link android.bluetooth.BluetoothGattCallback#onCharacteristicWrite(android.bluetooth.BluetoothGatt, android.bluetooth.BluetoothGattCharacteristic, int)} will be called or the connection state will
 * change from {@link #STATE_CONNECTED_AND_READY}. If connection state will change, or an error will occur, an exception will be thrown.
 * </p>
 *
 * @param gatt                the GATT device
 * @param characteristic      the characteristic to write to. Should be the DFU PACKET
 * @param softDeviceImageSize the Soft Device image size in bytes
 * @param bootloaderImageSize the Bootloader image size in bytes
 * @param appImageSize        the Application image size in bytes
 * @throws DeviceDisconnectedException
 * @throws DfuException
 * @throws UploadAbortedException
 */
private void writeImageSize(final BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic, final int softDeviceImageSize,
                            final int bootloaderImageSize, final int appImageSize) throws DeviceDisconnectedException, DfuException, UploadAbortedException {

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

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

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

    if (mAborted)
        throw new UploadAbortedException();

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

    if (mConnectionState != STATE_CONNECTED_AND_READY)
        throw new DeviceDisconnectedException("Unable to write Image Sizes", mConnectionState);
}
 
Example 31
Project: Android-DFU-App   File: ProximityManager.java   Source Code and License 5 votes vote down vote up
@Override
public void onDescriptorWriteRequest(final BluetoothDevice device, final int requestId, final BluetoothGattDescriptor descriptor, final boolean preparedWrite,
									 final boolean responseNeeded, final int offset, final byte[] value) {
	Logger.d(mLogSession, "[Server callback] Write request to descriptor " + descriptor.getUuid()
			+ " (requestId=" + requestId + ", prepareWrite=" + preparedWrite + ", responseNeeded=" + responseNeeded + ", offset=" + offset + ", value=" + ParserUtils.parse(value) + ")");
	Logger.i(mLogSession, "[Server] READ request for descriptor " + descriptor.getUuid() + " received");
	// This method is not supported
	Logger.w(mLogSession, "[Server] Operation not supported");
	Logger.d(mLogSession, "[Server] server.sendResponse(GATT_REQUEST_NOT_SUPPORTED)");
	mBluetoothGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_REQUEST_NOT_SUPPORTED, offset, null);
	Logger.v(mLogSession, "[Server] Response sent");
}
 
Example 32
Project: microbit   File: DfuBaseService.java   Source Code and License 5 votes vote down vote up
private void gattConnect(final BluetoothGatt gatt) {
    try {
        if (gatt.connect()) {
            synchronized (mLock) {
                while (mConnectionState != STATE_CONNECTED_AND_READY && mError == 0) {
                    mLock.wait(30 * 1000); //Wait only 30 seconds. TODO Check this again
                }
            }
        }
    } catch (final InterruptedException e) {
        e.printStackTrace();
        loge("Sleeping interrupted", e);
    }

}
 
Example 33
Project: AndroidMuseumBleManager   File: BluetoothConnectInterface.java   Source Code and License 5 votes vote down vote up
/**
 * start subscribe data, add data to subscribe list before invoke this method
 * <p>You should invoke this method after onServicesDiscovered, otherwise can not find service<p/>
 * @param bluetoothGatt
 * @return boolean is success start read or write character
 */
public boolean startSubscribe(BluetoothGatt bluetoothGatt){
    if (bluetoothGatt == null){
        Logger.e("Fail to subscribe, BluetoothGatt is null");
        return false;
    }
    boolean isSuccess = subscribe(bluetoothGatt.getDevice().getAddress());
    mOpratorQueue.start(bluetoothGatt);
    return isSuccess;
}
 
Example 34
Project: microbit   File: BLEManager.java   Source Code and License 5 votes vote down vote up
@Override
public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
    super.onDescriptorWrite(gatt, descriptor, status);

    synchronized(locker) {
        if(DEBUG) {
            logi("BluetoothGattCallback.onDescriptorWrite() :: start : status = " + status);
        }

        if(inBleOp == OP_WRITE_DESCRIPTOR) {
            if(DEBUG) {
                logi("BluetoothGattCallback.onDescriptorWrite() :: inBleOp == OP_WRITE_DESCRIPTOR");
            }

            if(status == BluetoothGatt.GATT_SUCCESS) {
                error = BLE_ERROR_OK;
            } else {
                error = BLE_ERROR_FAIL;
            }

            lastDescriptor = descriptor;
            callbackCompleted = true;
            locker.notify();
        }

        if(DEBUG) {
            logi("BluetoothGattCallback.onDescriptorWrite() :: end");
        }
    }
}
 
Example 35
Project: Android-DFU-App   File: BleManager.java   Source Code and License 5 votes vote down vote up
/**
 * Writes the characteristic value to the given characteristic.
 *
 * @param characteristic the characteristic to write to
 * @return true if request has been sent
 */
protected final boolean writeCharacteristic(final BluetoothGattCharacteristic characteristic) {
	final BluetoothGatt gatt = mBluetoothGatt;
	if (gatt == null || characteristic == null)
		return false;

	// Check characteristic property
	final int properties = characteristic.getProperties();
	if ((properties & (BluetoothGattCharacteristic.PROPERTY_WRITE | BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE)) == 0)
		return false;

	Logger.v(mLogSession, "Writing characteristic " + characteristic.getUuid() + " (" + getWriteType(characteristic.getWriteType()) + ")");
	Logger.d(mLogSession, "gatt.writeCharacteristic(" + characteristic.getUuid() + ")");
	return gatt.writeCharacteristic(characteristic);
}
 
Example 36
Project: neatle   File: ReadAllCommand.java   Source Code and License 5 votes vote down vote up
@Override
protected void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
    super.onCharacteristicRead(gatt, characteristic, status);
    if (status != BluetoothGatt.GATT_SUCCESS) {
        finish(CommandResult.createErrorResult(null, status));
    } else {
        if (observer != null) {
            observer.characteristicRead(CommandResult.createCharacteristicRead(characteristic, status));
        }
        readNext(gatt);
    }
}
 
Example 37
Project: neatle   File: ReadCommand.java   Source Code and License 5 votes vote down vote up
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
    if (!characteristic.getUuid().equals(characteristicUUID)) {
        NeatleLogger.e("Got a read request for a unknown characteristic");
        return;
    }

    CommandResult result = CommandResult.createCharacteristicRead(characteristic, status);
    NeatleLogger.d("Read: " + result);
    finish(result);
}
 
Example 38
Project: Sense-Hub-Android-Things   File: TitagSensorEntity.java   Source Code and License 5 votes vote down vote up
@Override
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
    if(status == BluetoothGatt.GATT_SUCCESS){
        if(characteristic.getUuid().equals(UUID_TITAG_GET_BATTERY)){
            byte[] mValue = characteristic.getValue();
            int mBattery = new Byte(mValue[0]).intValue();
            setBattery(mBattery);
            byte[] mHumidityValue = {mValue[0]};
            mGattnTitagTempHumidityService.getCharacteristic(UUID_TITAG_ENABLE_AIR_TEMP_HUMIDITY).setValue(mHumidityValue);
            gatt.writeCharacteristic(mGattnTitagTempHumidityService.getCharacteristic(UUID_TITAG_ENABLE_AIR_TEMP_HUMIDITY));
        }
    }
}
 
Example 39
Project: mesh-core-on-android   File: JniCallbacks.java   Source Code and License 5 votes vote down vote up
@Override
public void onMtuChanged (BluetoothGatt gatt, int mtu, int status) {
	if (status == BluetoothGatt.GATT_SUCCESS) {
		mGattMtu = mtu;
		gatt.discoverServices();
	}
}
 
Example 40
Project: UDOOBluLib-android   File: UdooBluService.java   Source Code and License 5 votes vote down vote up
/**
 * Retrieves a list of supported GATT services on the connected device with @address.
 * This should be invoked only after {@code BluetoothGatt#discoverServices()} completes
 * successfully.
 *
 * @return A {@code List} of supported services.
 */
public List<BluetoothGattService> getSupportedGattServices(String mac) {
    List<BluetoothGattService> list = new ArrayList<>();

    if (mBluetoothGatts.containsKey(mac)) {
        BluetoothGatt bluetoothGatt = mBluetoothGatts.get(mac);
        if (bluetoothGatt != null)
            list = bluetoothGatt.getServices();
    }

    return list;
}
 
Example 41
Project: ITagAntiLost   File: BleService.java   Source Code and License 5 votes vote down vote up
private void onConnected(BluetoothGatt gatt) {
  gatt.discoverServices();
  bluetoothGatt.put(gatt.getDevice().getAddress(), new BlePair(gatt));
  sendBroadcast(
      new Intent(DEVICE_CONNECTED)
          .putExtra(DEVICE_ADDRESS, gatt.getDevice().getAddress())
  );
}
 
Example 42
Project: Bluetooth_BLE   File: BleGattCallback.java   Source Code and License 5 votes vote down vote up
/**
 * 获取RSSI值, 计算距离
 *
 * @param gatt
 * @param rssi
 * @param status
 */
@Override
public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {
    // 发送广播
    Intent mIntent = new Intent(ACTION_NAME_RSSI);
    mIntent.putExtra("RSSI", rssi);
    context.sendBroadcast(mIntent);
}
 
Example 43
Project: Android-BLE-to-Arduino   File: BluetoothLeService.java   Source Code and License 5 votes vote down vote up
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
    if (status == BluetoothGatt.GATT_SUCCESS) {
        broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED);
    } else {
        Log.w(TAG, "onServicesDiscovered received: " + status);
    }
}
 
Example 44
Project: neatle   File: WriteCommand.java   Source Code and License 5 votes vote down vote up
private void fail(Exception ex) {
    NeatleLogger.e("Failed to read", ex);
    try {
      buffer.close();
    } catch (IOException closeEx) {
        NeatleLogger.e("Failed to close input source", closeEx);
    } finally {
        finish(CommandResult.createErrorResult(characteristicUUID, BluetoothGatt.GATT_FAILURE));
    }
}
 
Example 45
Project: Bluetooth_BLE   File: LiteBleConnector.java   Source Code and License 5 votes vote down vote up
/**
 * Write the value of a given descriptor to the associated remote device.
 *
 * 是否允许刷新描述符
 *
 * <p>A {@link BluetoothGattCallback#onDescriptorWrite} callback is
 * triggered to report the result of the write operation.
 *
 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} permission.
 *
 * @return true, if the write operation was initiated successfully
 */
public boolean setDescriptorNotification(BluetoothGatt gatt,
                                         BluetoothGattDescriptor descriptor,
                                         boolean enable) {
    if (gatt != null && descriptor != null) {
        BleLog.i(TAG, "Descriptor set notification value: " + enable);
        if (enable) {
            descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
        } else {
            descriptor.setValue(BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE);
        }
        return gatt.writeDescriptor(descriptor);
    }
    return false;
}
 
Example 46
Project: arduator   File: ArduinoCommBle.java   Source Code and License 5 votes vote down vote up
@Override
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
    super.onCharacteristicWrite(gatt, characteristic, status);

    if (characteristic.equals(charSerial) && status == BluetoothGatt.GATT_SUCCESS) {
        messenger.obtainMessage(MessageConstants.ACTION, ActionCode.WriteNext).sendToTarget();
    } else {
        messenger.obtainMessage(MessageConstants.ERROR, ErrorCode.Send).sendToTarget();
    }
}
 
Example 47
Project: NaiveDemos   File: BleOperationService.java   Source Code and License 5 votes vote down vote up
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
    LogUtils.d(TAG, "onConnctionStateChange:" + Thread.currentThread().toString());
    if (BluetoothProfile.STATE_CONNECTED == newState) {
        //连接成功
        LogUtils.i(TAG, "onConnectionStateChange():连接成功,得到gatt,status = " + status);
        mState = State.STATE_CONNECTED;

        //发现服务
        boolean b = gatt.discoverServices();
        LogUtils.d(TAG, "试图查询 gatt 上的 services :" + b);

        //发送消息给 Activity
        sendMsgToClient(MsgClient.MSG_GATT_CONNECTED, null);


    } else if (BluetoothProfile.STATE_DISCONNECTED == newState) {
        //返回连接断开的消息
        sendMsgToClient(MsgClient.MSG_CONNECTED_DISMISS, null);

        //取消周期行读取 rssi 的操作
        cancelAllTasks();

        //清除当前 gatt
        refreshDeviceCache();
        gatt.disconnect();//不使用自带的重连功能
        closeGatt();

        //定时重连操作
        mScheduledThreadPool.schedule(task1, Attributes.RE_CONNECTING_TIME, TimeUnit.MILLISECONDS);

        LogUtils.i(TAG, "onConnectionStateChange():连接断开,status = " + status);
        mState = State.STATE_DISCONNECT;

    } else {
        LogUtils.i(TAG, "其它状态: status = " + status + ", newState = " + newState);
    }
}
 
Example 48
Project: neatle   File: SubscribeCommand.java   Source Code and License 5 votes vote down vote up
@Override
protected void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
    if (status != BluetoothGatt.GATT_SUCCESS) {
        finish(CommandResult.createErrorResult(characteristicUUID, status));
    } else {
        finish(CommandResult.createEmptySuccess(characteristicUUID));
    }
}
 
Example 49
Project: NaiveDemos   File: BleOperationService.java   Source Code and License 5 votes vote down vote up
@Override
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
    LogUtils.d(TAG, "onCharacteristicRead:" + Thread.currentThread().toString());

    Bundle bundle = new Bundle();
    bundle.putByteArray(Key.KEY_CHARACTER_READ, characteristic.getValue());
    sendMsgToClient(MsgClient.MSG_CHARACTER_READ, bundle);

}
 
Example 50
Project: mi-band-2   File: BLEMiBand2Helper.java   Source Code and License 5 votes vote down vote up
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status)
{
    if(status == BluetoothGatt.GATT_SUCCESS)
    {

    }
    Log.d(TAG, "Service discovered with status " + status);
}
 
Example 51
Project: mesh-core-on-android   File: JniCallbacks.java   Source Code and License 5 votes vote down vote up
PeerDevice(BluetoothGatt gatt) {
	mConnectionState = STATE_DISCONNECTED;
	mPeerRole = ROLE_SERVER;
	mGattClient = gatt;
	mSending = false;
	mSendList = new ArrayList<byte[]>();
}
 
Example 52
Project: Android-DFU-App   File: BleManager.java   Source Code and License 5 votes vote down vote up
@Override
public final void onServicesDiscovered(final BluetoothGatt gatt, final int status) {
	if (status == BluetoothGatt.GATT_SUCCESS) {
		Logger.i(mLogSession, "Services Discovered");
		if (isRequiredServiceSupported(gatt)) {
			Logger.v(mLogSession, "Primary service found");
			final boolean optionalServicesFound = isOptionalServiceSupported(gatt);
			if (optionalServicesFound)
				Logger.v(mLogSession, "Secondary service found");

			// Notify the parent activity
			mCallbacks.onServicesDiscovered(optionalServicesFound);

			// Obtain the queue of initialization requests
			mInitInProgress = true;
			mInitQueue = initGatt(gatt);

			// When the device is bonded and has Service Changed characteristic, the indications must be enabled first.
			// In case this method returns true we have to continue in the onDescriptorWrite callback
			if (ensureServiceChangedEnabled(gatt))
				return;

			// We have discovered services, let's start by reading the battery level value. If the characteristic is not readable, try to enable notifications.
			// If there is no Battery service, proceed with the initialization queue.
			if (!readBatteryLevel())
				nextRequest();
		} else {
			Logger.w(mLogSession, "Device is not supported");
			mCallbacks.onDeviceNotSupported();
			disconnect();
		}
	} else {
		DebugLogger.e(TAG, "onServicesDiscovered error " + status);
		onError(ERROR_DISCOVERY_SERVICE, status);
	}
}
 
Example 53
Project: neatle   File: Device.java   Source Code and License 5 votes vote down vote up
private void deviceDiscovered() {
    stopDiscovery();

    int state = getState();
    if (state == BluetoothGatt.STATE_CONNECTING) {
        NeatleLogger.i("Device discovered. Continuing with connecting");
        connectWithGatt();
    } else {
        NeatleLogger.e("Device discovered but no longer connecting");
    }
}
 
Example 54
Project: neatle   File: SubscribeCommandTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testCharacteristicNotificationFail() {
    when(gatt.getService(eq(serviceUUID))).thenReturn(gattService);
    when(gattService.getCharacteristic(characteristicUUID)).thenReturn(gattCharacteristic);
    when(gattCharacteristic.getDescriptor(eq(clientCharacteristicConfig))).thenReturn(gattDescriptor);
    when(gatt.setCharacteristicNotification(Mockito.eq(gattCharacteristic), Mockito.anyBoolean())).thenReturn(false);

    subscribeCommand.execute(device, operationCommandObserver, gatt);
    verifyCommandFail(subscribeCommand, BluetoothGatt.GATT_FAILURE);
}
 
Example 55
Project: AndroidMuseumBleManager   File: ConnectRequestQueue.java   Source Code and License 5 votes vote down vote up
public ConnectRequestQueue(Context context){
    super(context);
    macMap = new ConcurrentHashMap<String, ConnectState>();//if not consider concurrent, should use ArrayMap
    gattMap = new ConcurrentHashMap<String, BluetoothGatt>();
    reconnectMap = new ConcurrentHashMap<String, ReconnectParamsBean>();
    deviceQueue = new ConcurrentLinkedQueue<>();
    mBluetoothUtils = BluetoothUtils.getInstance(context);
    connectStateListeners = new ArrayList<>();
}
 
Example 56
Project: AndroidMuseumBleManager   File: BluetoothConnectManager.java   Source Code and License 5 votes vote down vote up
/**
 * 断开蓝牙连接,不会释放BluetoothGatt持有的所有资源,可以调用mBluetoothGatt.connect()很快重新连接上
 * 如果不及时释放资源,可能出现133错误,http://www.loverobots.cn/android-ble-connection-solution-bluetoothgatt-status-133.html
 * @param address
 */
public void disconnect(String address){
    if (!isEmpty(address) && gattMap.containsKey(address)){
        reconnectParamsBean = new ReconnectParamsBean(address);
        reconnectParamsBean.setNumber(1000);
        Logger.w("disconnect gatt server " + address);
        BluetoothGatt mBluetoothGatt = gattMap.get(address);
        mBluetoothGatt.disconnect();
        updateConnectStateListener(address, ConnectState.NORMAL);
    }
}
 
Example 57
Project: Bluetooth_BLE   File: LiteBluetooth.java   Source Code and License 5 votes vote down vote up
/**
 * 设备连接后, 调用gatt.discoverServices(); 如果发现了service, 执行此方法
 * @param gatt
 * @param status
 */
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
    connectionState = STATE_SERVICES_DISCOVERED;
    for (BluetoothGattCallback call : callbackList) {
        call.onServicesDiscovered(gatt, status);
    }
}
 
Example 58
Project: Snach-Android   File: BLEManager.java   Source Code and License 5 votes vote down vote up
@Override
public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
    resetConnectionTimeoutChecker();

    if (status == BluetoothGatt.GATT_SUCCESS) {
        Log.d("BLE", "Callback: Wrote GATT Descriptor successfully.");

    } else {
        Log.d("BLE", "Callback: Error writing GATT Descriptor: "+ status);
    }
    hasFinishedWriting = true;
}
 
Example 59
Project: mi-band-2   File: BLEMiBand2Helper.java   Source Code and License 5 votes vote down vote up
@Override
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status)
{
    Log.d(TAG, "Write successful: " + Arrays.toString(characteristic.getValue()));
    raiseonWrite(gatt,characteristic,status);
    super.onCharacteristicWrite(gatt,characteristic,status);
}
 
Example 60
Project: microbit   File: BLEManager.java   Source Code and License 5 votes vote down vote up
@Override
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
    if(DEBUG) {
        logi("BluetoothGattCallback.onCharacteristicChanged() :: start");
    }

    super.onCharacteristicChanged(gatt, characteristic);
    characteristicChangeListener.onCharacteristicChanged(gatt, characteristic);

    if(DEBUG) {
        logi("BluetoothGattCallback.onCharacteristicChanged() :: end");
    }
}