Java Code Examples for android.bluetooth.BluetoothGattCharacteristic

The following are top voted examples for showing how to use android.bluetooth.BluetoothGattCharacteristic. 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: microbit   File: BLEService.java   Source Code and License 7 votes vote down vote up
private void handleCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
    String UUID = characteristic.getUuid().toString();

    Integer integerValue = characteristic.getIntValue(GattFormats.FORMAT_UINT32, 0);

    if(integerValue == null) {
        return;
    }
    int value = integerValue;
    int eventSrc = value & 0x0ffff;
    if(eventSrc < 1001) {
        return;
    }
    logi("Characteristic UUID = " + UUID);
    logi("Characteristic Value = " + value);
    logi("eventSrc = " + eventSrc);

    int event = (value >> 16) & 0x0ffff;
    logi("event = " + event);
    sendMessage(eventSrc, event);
}
 
Example 2
Project: ITagAntiLost   File: BleService.java   Source Code and License 6 votes vote down vote up
private void setCharacteristicNotification(
    @NonNull BluetoothGatt bluetoothgatt,
    @NonNull BluetoothGattCharacteristic bluetoothgattcharacteristic,
    boolean flag
) {
  bluetoothgatt.setCharacteristicNotification(bluetoothgattcharacteristic, flag);
  if (FIND_ME_CHARACTERISTIC.equals(bluetoothgattcharacteristic.getUuid())) {
    BluetoothGattDescriptor descriptor = bluetoothgattcharacteristic.getDescriptor(
        CLIENT_CHARACTERISTIC_CONFIG
    );
    if (descriptor != null) {
      descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
      bluetoothgatt.writeDescriptor(descriptor);
    }
  }
}
 
Example 3
Project: Android-DFU-App   File: BleManager.java   Source Code and License 6 votes vote down vote up
/**
 * Enables indications on given characteristic
 *
 * @return true is the request has been sent, false if one of the arguments was <code>null</code> or the characteristic does not have the CCCD.
 */
protected final boolean enableIndications(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_INDICATE) == 0)
		return false;

	Logger.d(mLogSession, "gatt.setCharacteristicNotification(" + characteristic.getUuid() + ", true)");
	gatt.setCharacteristicNotification(characteristic, true);
	final BluetoothGattDescriptor descriptor = characteristic.getDescriptor(CLIENT_CHARACTERISTIC_CONFIG_DESCRIPTOR_UUID);
	if (descriptor != null) {
		descriptor.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
		Logger.v(mLogSession, "Enabling indications for " + characteristic.getUuid());
		Logger.d(mLogSession, "gatt.writeDescriptor(" + CLIENT_CHARACTERISTIC_CONFIG_DESCRIPTOR_UUID + ", value=0x02-00)");
		return gatt.writeDescriptor(descriptor);
	}
	return false;
}
 
Example 4
Project: mi-band-2   File: BLEMiBand2Helper.java   Source Code and License 6 votes vote down vote up
public void writeData(UUID service, UUID Characteristics,byte[] data) {
    if (!isConnectedToGatt || myGatBand == null) {
        Log.d(TAG, "Cant read from BLE, not initialized.");
        return;
    }

    Log.d(TAG, "* Getting gatt service, UUID:" + service.toString());
    BluetoothGattService myGatService =
            myGatBand.getService(service /*Consts.UUID_SERVICE_HEARTBEAT*/);
    if (myGatService != null) {
        Log.d(TAG, "* Getting gatt Characteristic. UUID: " + Characteristics.toString());

        BluetoothGattCharacteristic myGatChar
                = myGatService.getCharacteristic(Characteristics /*Consts.UUID_START_HEARTRATE_CONTROL_POINT*/);
        if (myGatChar != null) {
            Log.d(TAG, "* Writing trigger");
            myGatChar.setValue(data /*Consts.BYTE_NEW_HEART_RATE_SCAN*/);

            boolean status =  myGatBand.writeCharacteristic(myGatChar);
            Log.d(TAG, "* Writting trigger status :" + status);
        }
    }
}
 
Example 5
Project: Android-DFU-App   File: BleManager.java   Source Code and License 6 votes vote down vote up
@Override
public final boolean enableIndications(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_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 gatt.writeDescriptor(descriptor);
	}
	return false;
}
 
Example 6
Project: BLE-PEPS   File: BleClientMainActivity.java   Source Code and License 6 votes vote down vote up
/**
 * 收到BLE终端写入数据回调
 */
@Override
public void onCharacteristicWrite(BluetoothGatt gatt,
                                  final BluetoothGattCharacteristic characteristic, int status)  {
    Log.e(TAG,"onCharWrite "+gatt.getDevice().getName()
            +" write "
            +characteristic.getUuid().toString()
            +" -> "
            +new String(characteristic.getValue()));


    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            int t = test[0];
            Integer.toString(t);
            ResponseContent.setText(Integer.toString(t));
        }
    });
}
 
Example 7
Project: Android-DFU-App   File: ProximityManager.java   Source Code and License 6 votes vote down vote up
@Override
public void onCharacteristicReadRequest(final BluetoothDevice device, final int requestId, final int offset, final BluetoothGattCharacteristic characteristic) {
	Logger.d(mLogSession, "[Server callback] Read request for characteristic " + characteristic.getUuid() + " (requestId=" + requestId + ", offset=" + offset + ")");
	Logger.i(mLogSession, "[Server] READ request for characteristic " + characteristic.getUuid() + " received");

	byte[] value = characteristic.getValue();
	if (value != null && offset > 0) {
		byte[] offsetValue = new byte[value.length - offset];
		System.arraycopy(value, offset, offsetValue, 0, offsetValue.length);
		value = offsetValue;
	}
	if (value != null)
		Logger.d(mLogSession, "server.sendResponse(GATT_SUCCESS, value=" + ParserUtils.parse(value) + ")");
	else
		Logger.d(mLogSession, "server.sendResponse(GATT_SUCCESS, value=null)");
	mBluetoothGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, offset, value);
	Logger.v(mLogSession, "[Server] Response sent");
}
 
Example 8
Project: Android-DFU-App   File: GlucoseManager.java   Source Code and License 6 votes vote down vote up
/**
 * Writes given operation parameters to the characteristic
 * 
 * @param characteristic
 *            the characteristic to write. This must be the Record Access Control Point characteristic
 * @param opCode
 *            the operation code
 * @param operator
 *            the operator (see {@link #OPERATOR_NULL} and others
 * @param params
 *            optional parameters (one for >=, <=, two for the range, none for other operators)
 */
private void setOpCode(final BluetoothGattCharacteristic characteristic, final int opCode, final int operator, final Integer... params) {
	final int size = 2 + ((params.length > 0) ? 1 : 0) + params.length * 2; // 1 byte for opCode, 1 for operator, 1 for filter type (if parameters exists) and 2 for each parameter
	characteristic.setValue(new byte[size]);

	// write the operation code
	int offset = 0;
	characteristic.setValue(opCode, BluetoothGattCharacteristic.FORMAT_UINT8, offset);
	offset += 1;

	// write the operator. This is always present but may be equal to OPERATOR_NULL
	characteristic.setValue(operator, BluetoothGattCharacteristic.FORMAT_UINT8, offset);
	offset += 1;

	// if parameters exists, append them. Parameters should be sorted from minimum to maximum. Currently only one or two params are allowed
	if (params.length > 0) {
		// our implementation use only sequence number as a filer type
		characteristic.setValue(FILTER_TYPE_SEQUENCE_NUMBER, BluetoothGattCharacteristic.FORMAT_UINT8, offset);
		offset += 1;

		for (final Integer i : params) {
			characteristic.setValue(i, BluetoothGattCharacteristic.FORMAT_UINT16, offset);
			offset += 2;
		}
	}
}
 
Example 9
Project: Android-BLE-to-Arduino   File: BluetoothLeService.java   Source Code and License 6 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 10
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 11
Project: microbit   File: BLEService.java   Source Code and License 6 votes vote down vote up
private void writeCharacteristic(String serviceGuid, String characteristic, int value, int type) {
    if(!isConnected()) {
        logi("writeCharacteristic() :: Not connected. Returning");
        return;
    }

    BluetoothGattService s = getService(UUID.fromString(serviceGuid));
    if(s == null) {
        logi("writeCharacteristic() :: Service not found");
        return;
    }

    BluetoothGattCharacteristic c = s.getCharacteristic(UUID.fromString(characteristic));
    if(c == null) {
        logi("writeCharacteristic() :: characteristic not found");
        return;
    }

    c.setValue(value, type, 0);
    int ret = writeCharacteristic(c);
    logi("writeCharacteristic() :: returns - " + ret);
}
 
Example 12
Project: freeu2f-android   File: U2FService.java   Source Code and License 6 votes vote down vote up
@Override
public void onCharacteristicReadRequest(
        BluetoothDevice device,
        int requestId,
        int offset,
        BluetoothGattCharacteristic chr) {
    int status = BluetoothGatt.GATT_FAILURE;
    byte[] bytes = null;

    if (offset != 0) {
        status = BluetoothGatt.GATT_INVALID_OFFSET;
    } else if (chr.equals(U2FGattService.U2F_CONTROL_POINT_LENGTH)) {
        status = BluetoothGatt.GATT_SUCCESS;
        bytes = new byte[] { 0x02, 0x00 }; /* Length == 512, see U2F BT 6.1 */
    } else if (chr.equals(U2FGattService.U2F_SERVICE_REVISION_BITFIELD)) {
        status = BluetoothGatt.GATT_SUCCESS;
        bytes = new byte[] { 0x40 };       /* Version == 1.2, see U2F BT 6.1 */
    }

    Log.d(getClass().getCanonicalName(), Integer.valueOf(bytes.length).toString());
    mGattServer.sendResponse(device, requestId, status, 0, bytes);
}
 
Example 13
Project: mesh-core-on-android   File: JniCallbacks.java   Source Code and License 6 votes vote down vote up
@Override
public void onCharacteristicWriteRequest(BluetoothDevice device, int requestId, 
										BluetoothGattCharacteristic characteristic, boolean preparedWrite, 
										boolean responseNeeded, int offset, byte[] value) {
	super.onCharacteristicWriteRequest(device, requestId, characteristic, preparedWrite, responseNeeded, offset, value);
			
	mGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, offset, value);

	if (mProvClientDev.getPeerDevice().equals(device)) {
		if (characteristic.getUuid().compareTo(UUID.fromString(UUID_PB_CHAR_DATA_IN)) == 0)
		{
			String strAddr=device.getAddress();
			byte[] addr = stringToAddress(strAddr);
			
			provServerPduInNative(addr, value);
		}
	}
}
 
Example 14
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 15
Project: Android-DFU-App   File: BleManager.java   Source Code and License 6 votes vote down vote up
/**
 * Sends the read request to the given characteristic.
 *
 * @param characteristic the characteristic to read
 * @return true if request has been sent
 */
protected final boolean readCharacteristic(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_READ) == 0)
		return false;

	Logger.v(mLogSession, "Reading characteristic " + characteristic.getUuid());
	Logger.d(mLogSession, "gatt.readCharacteristic(" + characteristic.getUuid() + ")");
	return gatt.readCharacteristic(characteristic);
}
 
Example 16
Project: Bluetooth_BLE   File: LiteBleConnector.java   Source Code and License 6 votes vote down vote up
/**
 * 读取特征码刷新数据
 * @param bleCallback
 */
private void handleCharacteristicNotificationCallback(final BleCharactCallback bleCallback) {
    if (bleCallback != null) {
        listenAndTimer(bleCallback, MSG_NOTIY_CHA, new BluetoothGattCallback() {
            AtomicBoolean msgRemoved = new AtomicBoolean(false);

            @Override
            public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
                if (!msgRemoved.getAndSet(true)) {
                    handler.removeMessages(MSG_NOTIY_CHA, this);
                }
                bleCallback.onSuccess(characteristic);
            }
        });
    }
}
 
Example 17
Project: mesh-core-on-android   File: JniCallbacks.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 (characteristic.getUuid().compareTo(UUID.fromString(UUID_PROXY_CHAR_DATA_IN)) == 0) {
		if (mProxyDev != null && mProxyDev.getConnectionState() == PeerDevice.STATE_CONNECTED) {
			mProxyDev.onDataOut();
		}
	} else if (characteristic.getUuid().compareTo(UUID.fromString(UUID_PB_CHAR_DATA_IN)) == 0) {
		if (mProvServerDev != null && mProvServerDev.getConnectionState() == PeerDevice.STATE_CONNECTED) {
			String strAddr=gatt.getDevice().getAddress();
			byte[] addr = stringToAddress(strAddr);
			provClientPduSentNative(addr);
			mProvServerDev.onDataOut();
		}
	}
}
 
Example 18
Project: Bluetooth_BLE   File: LiteBleConnector.java   Source Code and License 6 votes vote down vote up
/**
 * read data from specified characteristic
 */
public boolean readCharacteristic(BluetoothGattCharacteristic charact, BleCharactCallback bleCallback) {
    if ((characteristic.getProperties() | BluetoothGattCharacteristic.PROPERTY_READ) > 0) {
        // If there is an active notification on a characteristic, clear
        // it first so it doesn't update the data field on the user interface.
        setCharacteristicNotification(getBluetoothGatt(), charact, false);
        // 读取到的数据回调返回
        handleCharacteristicReadCallback(bleCallback);
        return handleAfterInitialed(getBluetoothGatt().readCharacteristic(charact), bleCallback);
    } else {
        if (bleCallback != null) {
            // 特征码不可读
            bleCallback.onFailure(new OtherException("Characteristic [is not] readable!"));
        }
        return false;
    }
}
 
Example 19
Project: neatle   File: WriteCommandTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testWriteFirstChunkFailed() throws IOException {
    InputSource inputSource = Mockito.mock(InputSource.class);
    doThrow(IOException.class).when(inputSource).open();

    when(gatt.getService(eq(serviceUUID))).thenReturn(gattService);
    when(gattService.getCharacteristic(characteristicUUID)).thenReturn(gattCharacteristic);

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

    writeCommand.execute(device, operationCommandObserver, gatt);
    CommandResult result = CommandResult.createErrorResult(characteristicUUID, BluetoothGatt.GATT_FAILURE);
    verify(commandObserver, times(1)).finished(eq(writeCommand), refEq(result, "timestamp"));
    verify(operationCommandObserver, times(1)).finished(eq(writeCommand), refEq(result, "timestamp"));
    Mockito.reset(commandObserver, operationCommandObserver, inputSource);

    when(inputSource.nextChunk()).thenThrow(IOException.class);
    writeCommand.execute(device, operationCommandObserver, gatt);
    verify(commandObserver, times(1)).finished(eq(writeCommand), refEq(result, "timestamp"));
    verify(operationCommandObserver, times(1)).finished(eq(writeCommand), refEq(result, "timestamp"));
}
 
Example 20
Project: mi-band-2   File: BLEMiBand2Helper.java   Source Code and License 5 votes vote down vote up
public void readData(UUID service, UUID Characteristics) {
    if (!isConnectedToGatt || myGatBand == null) {
        Log.d(TAG, "Cant read from BLE, not initialized.");
        return;
    }

    Log.d(TAG, "* Getting gatt service, UUID:" + service.toString());
    BluetoothGattService myGatService =
            myGatBand.getService(service /*Consts.UUID_SERVICE_GENERIC*/);
    if (myGatService != null) {
        Log.d(TAG, "* Getting gatt Characteristic. UUID: " + Characteristics.toString());

        BluetoothGattCharacteristic myGatChar
                = myGatService.getCharacteristic(Characteristics /*Consts.UUID_CHARACTERISTIC_DEVICE_NAME*/);
        if (myGatChar != null) {
            Log.d(TAG, "* Reading data");

            boolean status =  myGatBand.readCharacteristic(myGatChar);
            Log.d(TAG, "* Read status :" + status);
        }
    }
}
 
Example 21
Project: AndroidMuseumBleManager   File: BluetoothConnectInterface.java   Source Code and License 5 votes vote down vote up
@Override
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
    super.onCharacteristicRead(gatt, characteristic, status);
    Logger.i("onCharacteristicRead data status:" + GattError.parseConnectionError(status) + " " + characteristic.getUuid().toString());
    mOpratorQueue.nextOperator();
    if (getBluetoothGattCallback() != null) getBluetoothGattCallback().onCharacteristicRead(gatt, characteristic, status);
}
 
Example 22
Project: mDL-ILP   File: GattClient.java   Source Code and License 5 votes vote down vote up
private synchronized void readCharacteristic(BluetoothGattCharacteristic characteristic) throws InterruptedException, GattException {
    if (VDBG) { Log.d(TAG, "readCharacteristic: [CMD]"); }
    if (!mBtGatt.readCharacteristic(characteristic)) {
        throw new GattException("Could not read characteristic.");
    };
    while (lastMessage != MESSAGE_READ) {
        wait();
    }
    if (VDBG) { Log.d(TAG, "readCharacteristic: [DONE] " + HexStrings.toHexString(characteristic.getValue())); }
    lastMessage = -1;
}
 
Example 23
Project: neatle   File: WriteCommand.java   Source Code and License 5 votes vote down vote up
@Override
protected void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
    if (status != BluetoothGatt.GATT_SUCCESS) {
        NeatleLogger.i("Write on " + characteristic.getUuid() + " failed with status " + status);
        finish(CommandResult.createErrorResult(characteristicUUID, status));
        return;
    }

    if (asyncMode) {
        synchronized (bufferReadLock) {
            bufferReadLock.notify();
        }
    } else {
        byte[] chunk;
        try {
            chunk = buffer.nextChunk();
        } catch (IOException ex) {
            NeatleLogger.e("Failed to get the first chunk", ex);
            finish(CommandResult.createErrorResult(characteristicUUID, BluetoothGatt.GATT_FAILURE));
            return;
        }
        if (chunk == null) {
            finish(CommandResult.createEmptySuccess(characteristicUUID));
            return;
        }
        nextChunkReady(chunk);
    }
}
 
Example 24
Project: Quick-Bluetooth-LE   File: BLEServer.java   Source Code and License 5 votes vote down vote up
public boolean setCharacteristicValue(UUID serviceUuid, UUID characteristicUuid, String value, boolean notify){
	BluetoothGattService service = gattServer.getService(serviceUuid);
	if(service == null)
		return false;
	BluetoothGattCharacteristic ch = service.getCharacteristic(characteristicUuid);
	if(ch == null)
		return false;
	boolean rtn = ch.setValue(value);
	if(rtn && notify){
		notifyDevices(ch);
	}
	return rtn;
}
 
Example 25
Project: Make-A-Pede-Android-App   File: BluetoothLeService.java   Source Code and License 5 votes vote down vote up
@Override
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
	if(status == BluetoothGatt.GATT_SUCCESS) {
		broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
	} else {
		Log.w(TAG, "onCharacteristicWrite received: " + status);
	}

	writeNextCharacteristic();
}
 
Example 26
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 27
Project: Make-A-Pede-Android-App   File: BluetoothLeService.java   Source Code and License 5 votes vote down vote up
public void setCharacteristicNotification(BluetoothGattCharacteristic characteristic, boolean enabled) {
	if (bluetoothAdapter == null || bluetoothGatt == null) {
		Log.w(TAG, "BluetoothAdapter not initialized");
		return;
	}

	bluetoothGatt.setCharacteristicNotification(characteristic, enabled);

	for (BluetoothGattDescriptor descriptor : characteristic.getDescriptors()) {
		descriptor.setValue(
				enabled ? BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE : new byte[] {0x00, 0x00});
		bluetoothGatt.writeDescriptor(descriptor);
	}
}
 
Example 28
Project: hackmelock-android   File: BluetoothLeService.java   Source Code and License 5 votes vote down vote up
/**
 * Request a read on a given {@code BluetoothGattCharacteristic}. The read result is reported
 * asynchronously through the {@code BluetoothGattCallback#onCharacteristicRead(android.bluetooth.BluetoothGatt, android.bluetooth.BluetoothGattCharacteristic, int)}
 * callback.
 *
 * @param characteristic The characteristic to read from.
 */
public void readCharacteristic(BluetoothGattCharacteristic characteristic) {
    if (mBluetoothAdapter == null || mBluetoothGatt == null) {
        Log.w(TAG, "BluetoothAdapter not initialized");
        return;
    }
    mBluetoothGatt.readCharacteristic(characteristic);
}
 
Example 29
Project: BLE-PEPS   File: BluetoothLeClass.java   Source Code and License 5 votes vote down vote up
@Override
public void onCharacteristicWrite(BluetoothGatt gatt,
                                 BluetoothGattCharacteristic characteristic,
                                 int status) {
    if (mOnDataAvailableListener!=null)
        mOnDataAvailableListener.onCharacteristicWrite(gatt, characteristic, status);
}
 
Example 30
Project: Quick-Bluetooth-LE   File: BLEClient.java   Source Code and License 5 votes vote down vote up
public boolean setCharacteristicValue(UUID serviceUuid, UUID characteristicUuid, byte[] value){
	if(gattConnection == null)
		return false;
	BluetoothGattService service = gattConnection.getService(serviceUuid);
	if(service == null)
		return false;
	BluetoothGattCharacteristic ch = service.getCharacteristic(characteristicUuid);
	if(ch == null)
		return false;
	ch.setValue(value);
	return gattConnection.writeCharacteristic(ch);
}
 
Example 31
Project: Quick-Bluetooth-LE   File: BLEClient.java   Source Code and License 5 votes vote down vote up
public void receiveNotifications(UUID serviceUuid, UUID characteristicUuid, UUID descriptorUuid, boolean receive){
	BluetoothGattCharacteristic characteristic = getCharacteristic(serviceUuid, characteristicUuid);
	gattConnection.setCharacteristicNotification(characteristic, receive);
	BluetoothGattDescriptor descriptor = characteristic.getDescriptor(UUID.fromString(SampleGattAttributes.CLIENT_CHARACTERISTIC_CONFIG));
	descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
	gattConnection.writeDescriptor(descriptor);
}
 
Example 32
Project: blefun-androidthings   File: GattServer.java   Source Code and License 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 33
Project: Bluetooth_BLE   File: BleManager.java   Source Code and License 5 votes vote down vote up
/**
 * 刷新返回的数据
 *
 * @return
 */
public void setCharacteristicNotification(BluetoothGattCharacteristic characteristic, boolean enable) {
    BluetoothGattDescriptor descriptor = characteristic.getDescriptor(UUIDCons.d);
    if (enable) {
        Log.i(TAG, "Enable Notification");
        mGatt.setCharacteristicNotification(characteristic, true);
        descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
        mGatt.writeDescriptor(descriptor);
    } else {
        Log.i(TAG, "Disable Notification");
        mGatt.setCharacteristicNotification(characteristic, false);
        descriptor.setValue(BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE);
        mGatt.writeDescriptor(descriptor);
    }
}
 
Example 34
Project: android-ponewheel   File: OWDevice.java   Source Code and License 5 votes vote down vote up
public void setCharacteristicValue(BluetoothGattService gattService, BluetoothGatt gatt, String k, int v) {
    DeviceCharacteristic dc = getDeviceCharacteristicByKey(k);
    if (dc != null) {
        BluetoothGattCharacteristic lc = null;
        lc = gattService.getCharacteristic(UUID.fromString(dc.uuid.get()));
        if (lc != null) {
            ByteBuffer var2 = ByteBuffer.allocate(2);
            var2.putShort((short) v);
            lc.setValue(var2.array());
            lc.setWriteType(2);
            gatt.writeCharacteristic(lc);
            EventBus.getDefault().post(new DeviceStatusEvent("SET " + k + " TO " + v));
        }
    }
}
 
Example 35
Project: bluewatcher   File: BluetoothServerService.java   Source Code and License 5 votes vote down vote up
@Override
public void onCharacteristicWriteRequest(BluetoothDevice device, int requestId, BluetoothGattCharacteristic characteristic,
		boolean preparedWrite, boolean responseNeeded, int offset, byte[] value) {
	super.onCharacteristicWriteRequest(device, requestId, characteristic, preparedWrite, responseNeeded, offset, value);
	Log.i("BLEMainActivity:BluetoothGattServerCallback:onCharacteristicWriteRequest", "device : " + device.getAddress()
			+ " characteristic : " + characteristic.getUuid() + "Value = " + value.toString());
	for (ServerService service : serverServices) {
		if (service.knowsCharacteristic(characteristic)) {
			service.processWriteRequest(characteristic, offset, value);
		}
	}
}
 
Example 36
Project: bluewatcher   File: BluetoothClientService.java   Source Code and License 5 votes vote down vote up
@Override
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
	Log.i(TAG, "onCharacteristicRead called...");
	if (status == BluetoothGatt.GATT_SUCCESS) {
		broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
	}
}
 
Example 37
Project: Android-DFU-App   File: BPMManager.java   Source Code and License 5 votes vote down vote up
@Override
protected void onCharacteristicNotified(final BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic) {
	// Intermediate Cuff Pressure characteristic read
	if (mLogSession != null)
		Logger.a(mLogSession, IntermediateCuffPressureParser.parse(characteristic));

	parseBPMValue(characteristic);
}
 
Example 38
Project: Quick-Bluetooth-LE   File: MainActivity.java   Source Code and License 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.activity_main);

	deviceCount = (TextView) findViewById(R.id.lbl_device_count);
	slider = (SeekBar) findViewById(R.id.seekBar);
	listView = (ListView) findViewById(R.id.lst_main_options);
	deviceList = new ArrayList<>();
	deviceAddresses = new ArrayList<>();
	deviceNames = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1);
	devices = (ListView) findViewById(R.id.lst_discovered_devices);
	devices.setAdapter(deviceNames);
	listView.setOnItemClickListener(this);

	if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
		bleServer = new BLEServer(MainActivity.this, this);
		sliderCharacteristic = bleServer.buildCharacteristic(sliderCharacteristicUuid, new BluetoothGattDescriptor[0],
				BLEServer.CharProperties.Read | BLEServer.CharProperties.Write | BLEServer.CharProperties.Notify,
				BLEServer.CharPermissions.Read | BLEServer.CharPermissions.Write);
		comService = bleServer.buildService(communicationServiceUuid,
				BLEServer.ServiceType.Primary, new BluetoothGattCharacteristic[]{sliderCharacteristic});
		bleServer.addService(comService);
	}

	if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2){
		bleClient = new BLEClient(MainActivity.this, this);
		bleClient.setUseNewMethod(false); //This requires more work with permissions than the old method

	}

}
 
Example 39
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 40
Project: BLE-PEPS   File: BluetoothLeClass.java   Source Code and License 5 votes vote down vote up
public void readCharacteristic(BluetoothGattCharacteristic characteristic) {
    if (mBluetoothAdapter == null || mBluetoothGatt == null) {
        Log.w(TAG, "BluetoothAdapter not initialized");
        return;
    }
    mBluetoothGatt.readCharacteristic(characteristic);
}
 
Example 41
Project: Quick-Bluetooth-LE   File: MainActivity.java   Source Code and License 5 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
@Override
public void onServicesDiscovered(List<BluetoothGattService> services) {
	BluetoothGattService service = null;
	for(BluetoothGattService s : services){
		if(s.getUuid().equals(communicationServiceUuid))
			service = s;
	}
	BluetoothGattCharacteristic characteristic = service.getCharacteristic(sliderCharacteristicUuid);
	bleClient.receiveNotifications(characteristic, true);
}
 
Example 42
Project: Android-DFU-App   File: TemperatureMeasurementParser.java   Source Code and License 5 votes vote down vote up
public static String parse(final BluetoothGattCharacteristic characteristic) {
	int offset = 0;
	final int flags = characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8, offset++);

	/*
	 * false 	Temperature is in Celsius degrees 
	 * true 	Temperature is in Fahrenheit degrees 
	 */
	final boolean fahrenheit = (flags & TEMPERATURE_UNIT_FLAG) > 0;

	/*
	 * false 	No Timestamp in the packet
	 * true 	There is a timestamp information
	 */
	final boolean timestampIncluded = (flags & TIMESTAMP_FLAG) > 0;

	/*
	 * false 	Temperature type is not included
	 * true 	Temperature type included in the packet
	 */
	final boolean temperatureTypeIncluded = (flags & TEMPERATURE_TYPE_FLAG) > 0;

	final float tempValue = characteristic.getFloatValue(BluetoothGattCharacteristic.FORMAT_FLOAT, offset);
	offset += 4;

	String dateTime = null;
	if (timestampIncluded) {
		dateTime = DateTimeParser.parse(characteristic, offset);
		offset += 7;
	}

	String type = null;
	if (temperatureTypeIncluded) {
		type = TemperatureTypeParser.parse(characteristic, offset);
		// offset++;
	}

	final StringBuilder builder = new StringBuilder();
	builder.append(String.format("%.02f", tempValue));

	if (fahrenheit)
		builder.append("°F");
	else
		builder.append("°C");

	if (timestampIncluded)
		builder.append("\nTime: ").append(dateTime);
	if (temperatureTypeIncluded)
		builder.append("\nType: ").append(type);
	return builder.toString();
}
 
Example 43
Project: blefun-androidthings   File: GattClient.java   Source Code and License 5 votes vote down vote up
private void readCounterCharacteristic(BluetoothGattCharacteristic characteristic) {
    if (CHARACTERISTIC_COUNTER_UUID.equals(characteristic.getUuid())) {
        byte[] data = characteristic.getValue();
        int value = Ints.fromByteArray(data);
        mListener.onCounterRead(value);
    }
}
 
Example 44
Project: AndroidSDK2.0   File: BTLEAdt.java   Source Code and License 5 votes vote down vote up
@Override
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
    super.onCharacteristicChanged(gatt, characteristic);

    NLog.d("call onCharacteristicChanged");
    mConnectionThread.read(characteristic.getValue());
}
 
Example 45
Project: BLE-PEPS   File: BleClientMainActivity.java   Source Code and License 5 votes vote down vote up
@Override
public void onCharacteristicChanged(BluetoothGatt gatt,
                                  final BluetoothGattCharacteristic characteristic)  {
    Log.e(TAG,"onCharChanged "+gatt.getDevice().getName()
            +" changed "
            +characteristic.getUuid().toString()
            +" -> "
            +new String(characteristic.getValue()));
}
 
Example 46
Project: react-native-blue-manager   File: Helper.java   Source Code and License 5 votes vote down vote up
public static WritableMap decodePermissions(BluetoothGattCharacteristic characteristic) {

		// NOTE: props strings need to be consistent across iOS and Android
		WritableMap props = Arguments.createMap();
		int permissions = characteristic.getPermissions();

		if ((permissions & BluetoothGattCharacteristic.PERMISSION_READ) != 0x0 ) {
			props.putString("Read", "Read");
		}

		if ((permissions & BluetoothGattCharacteristic.PERMISSION_WRITE) != 0x0 ) {
			props.putString("Write", "Write");
		}

		if ((permissions & BluetoothGattCharacteristic.PERMISSION_READ_ENCRYPTED) != 0x0 ) {
			props.putString("ReadEncrypted", "ReadEncrypted");
		}

		if ((permissions & BluetoothGattCharacteristic.PERMISSION_WRITE_ENCRYPTED) != 0x0 ) {
			props.putString("WriteEncrypted", "WriteEncrypted");
		}

		if ((permissions & BluetoothGattCharacteristic.PERMISSION_READ_ENCRYPTED_MITM) != 0x0 ) {
			props.putString("ReadEncryptedMITM", "ReadEncryptedMITM");
		}

		if ((permissions & BluetoothGattCharacteristic.PERMISSION_WRITE_ENCRYPTED_MITM) != 0x0 ) {
			props.putString("WriteEncryptedMITM", "WriteEncryptedMITM");
		}

		if ((permissions & BluetoothGattCharacteristic.PERMISSION_WRITE_SIGNED) != 0x0 ) {
			props.putString("WriteSigned", "WriteSigned");
		}

		if ((permissions & BluetoothGattCharacteristic.PERMISSION_WRITE_SIGNED_MITM) != 0x0 ) {
			props.putString("WriteSignedMITM", "WriteSignedMITM");
		}

		return props;
	}
 
Example 47
Project: BLE-PEPS   File: BleClientMainActivity.java   Source Code and License 5 votes vote down vote up
@Override
public void onCharacteristicChanged(BluetoothGatt gatt,
                                  final BluetoothGattCharacteristic characteristic)  {
    Log.e(TAG,"onCharChanged "+gatt.getDevice().getName()
            +" changed "
            +characteristic.getUuid().toString()
            +" -> "
            +new String(characteristic.getValue()));
}
 
Example 48
Project: neatle   File: DeviceDetails.java   Source Code and License 5 votes vote down vote up
@Override
public void onBindViewHolder(DeviceDetailsAdapter.ViewHolder holder, int position) {
    Object item = items.get(position);
    if (item instanceof BluetoothGattService) {
        BluetoothGattService service = (BluetoothGattService) item;
        holder.setTitle(service.getUuid().toString());
        holder.setSubTitle("service");
    } else if (item instanceof  BluetoothGattCharacteristic) {
        BluetoothGattCharacteristic characteristic = (BluetoothGattCharacteristic) item;
        holder.setTitle(characteristic.getUuid().toString());
        holder.setSubTitle("Data: " + characteristic.getStringValue(0));
    } else {
        holder.setTitle("Unknown");
    }
}
 
Example 49
Project: UDOOBluLib-android   File: UdooBluManager.java   Source Code and License 5 votes vote down vote up
public void enableSensor(final String address, final UDOOBLESensor sensor, final boolean enable,final OnBluOperationResult<Boolean> operationResult) {
    if (isBluManagerReady) {
        addOperation(new Callable<Void>() {
            @Override
            public Void call() throws Exception {
                if (sensor != null) {
                    UUID servUuid = sensor.getService();
                    UUID confUuid = sensor.getConfig();
                    BluetoothGattService serv = null;
                    BluetoothGattCharacteristic charac = null;

                    byte[] value = new byte[1];
                    try {
                        serv = mUdooBluService.getService(address, servUuid);
                        charac = serv.getCharacteristic(confUuid);
                        value[0] = enable ? sensor.getEnableSensorCode()
                                : UDOOBLESensor.DISABLE_SENSOR_CODE;
                        mOnResultMap.put(address, operationResult);
                        mUdooBluService.writeCharacteristic(address, charac, value);
                    } catch (Exception e) {
                        if (operationResult != null)
                            operationResult.onError(new UdooBluException(UdooBluException.BLU_GATT_SERVICE_NOT_FOUND));
                        if (BuildConfig.DEBUG)
                            Log.e(TAG, "error enableSensor(), service uuid: " + servUuid.toString());
                    }
                }
                return null;
            }
        });
    } else if (BuildConfig.DEBUG)
        Log.i(TAG, "BluManager not ready");
}
 
Example 50
Project: ITagAntiLost   File: BleService.java   Source Code and License 5 votes vote down vote up
private BluetoothGattCharacteristic getCharacteristic(
    @NonNull BluetoothGatt bluetoothgatt,
    @NonNull UUID serviceUuid,
    @NonNull UUID characteristicUuid
) {
  BluetoothGattService service = bluetoothgatt.getService(serviceUuid);
  if (service != null)
    return service.getCharacteristic(characteristicUuid);
  return null;
}
 
Example 51
Project: Quick-Bluetooth-LE   File: ServerTest.java   Source Code and License 5 votes vote down vote up
@Override
public void onCharacteristicChangedServer(final BluetoothGattCharacteristic characteristic) {
	runOnUiThread(new Runnable() {
		@Override
		public void run() {
			outText.setText("Characteristic\nValue: " + server.getCharacteristicValueString(serviceUuid, charUuid, 0));
		}
	});
}
 
Example 52
Project: blefun-androidthings   File: GattServer.java   Source Code and License 5 votes vote down vote up
@Override
public void onCharacteristicWriteRequest(BluetoothDevice device, int requestId, BluetoothGattCharacteristic characteristic, boolean preparedWrite, boolean responseNeeded, int offset, byte[] value) {
    if (CHARACTERISTIC_INTERACTOR_UUID.equals(characteristic.getUuid())) {
        Log.i(TAG, "Write interactor");

        if (mListener != null) {
            mListener.onInteractorWritten();
        }
        notifyRegisteredDevices();
    } else {
        // Invalid characteristic
        Log.w(TAG, "Invalid Characteristic Write: " + characteristic.getUuid());
        mBluetoothGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_FAILURE, 0, null);
    }
}
 
Example 53
Project: TrainAppTFG   File: BluetoothLeService.java   Source Code and License 5 votes vote down vote up
private synchronized void doWrite(Object o){
    if(o instanceof BluetoothGattCharacteristic){
        sIsWritting = true;
        mBluetoothGatt.writeCharacteristic((BluetoothGattCharacteristic)o);
    }
    else if(o instanceof BluetoothGattDescriptor){
        sIsWritting = true;
        mBluetoothGatt.writeDescriptor((BluetoothGattDescriptor)o);
    }
    else{
        nextWrite();
    }
}
 
Example 54
Project: Android-DFU-App   File: GlucoseManager.java   Source Code and License 5 votes vote down vote up
/**
 * Sends the request to obtain all records from glucose device. Initially we want to notify him/her about the number of the records so the {@link #OP_CODE_REPORT_NUMBER_OF_RECORDS} is send. The
 * data will be returned to Glucose Measurement characteristic as a notification followed by Record Access Control Point indication with status code ({@link #RESPONSE_SUCCESS} or other in case of
 * error.
 */
public void getAllRecords() {
	if (mRecordAccessControlPointCharacteristic == null)
		return;

	clear();
	mCallbacks.onOperationStarted();

	final BluetoothGattCharacteristic characteristic = mRecordAccessControlPointCharacteristic;
	setOpCode(characteristic, OP_CODE_REPORT_NUMBER_OF_RECORDS, OPERATOR_ALL_RECORDS);
	writeCharacteristic(characteristic);
}
 
Example 55
Project: Quick-Bluetooth-LE   File: BLEClient.java   Source Code and License 5 votes vote down vote up
public boolean setDescriptorValue(UUID serviceUuid, UUID characteristicUuid, UUID descriptorUuid, String value){
	if(gattConnection == null)
		return false;
	BluetoothGattService service = gattConnection.getService(serviceUuid);
	if(service == null)
		return false;
	BluetoothGattCharacteristic characteristic = service.getCharacteristic(characteristicUuid);
	if(characteristic == null)
		return false;
	BluetoothGattDescriptor descriptor = characteristic.getDescriptor(descriptorUuid);
	if(descriptor == null)
		return false;
	descriptor.setValue(value.getBytes());
	return gattConnection.writeDescriptor(descriptor);
}
 
Example 56
Project: BLE-HID-Peripheral-for-Android   File: HidPeripheral.java   Source Code and License 5 votes vote down vote up
/**
 * Setup Battery Service
 *
 * @return the service
 */
private static 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);

    while (!service.addCharacteristic(characteristic));

    return service;
}
 
Example 57
Project: NaiveDemos   File: BleOperationService.java   Source Code and License 5 votes vote down vote up
/**
 * 操作2:通知
 * 操作结果返回到 GattCallback 中 onCharacteristicChanged()回调方法当中
 *
 * @param characteristic 需要操作的特征
 * @param enable         若为 true 表示要开启notify,若为 false 表示要停止 notify
 * @return 若为 true 表示设置 notify 状态成功
 */
private boolean notifyCharacteristic(BluetoothGattCharacteristic characteristic,
                                     boolean enable) {
    if (mBluetoothAdapter == null || mBluetoothGatt == null) {
        LogUtils.w(TAG, "蓝牙适配器为 null:notify");
        return false;
    }
    if (mState != State.STATE_CONNECTED) {
        LogUtils.w(TAG, "notify(): 当前状态为非连接状态");
        return false;
    }
    if ((characteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_NOTIFY) == 0) {
        LogUtils.w(TAG, "characteristic不能被notify");
        return false;
    }

    boolean suc = mBluetoothGatt.setCharacteristicNotification(characteristic, enable);
    if (!suc) {
        //notify 操作失败
        LogUtils.w(TAG, "set notify 操作失败");
        return false;
    }
    //特殊操作,注意三元表达式
    BluetoothGattDescriptor descriptor =
            characteristic.getDescriptor(Attributes.UUID_CLIENT_CHARACTERISTIC_CONFIG_DESCRIPTOR);

    if (null != descriptor) {
        descriptor.setValue(enable ?
                BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE :
                BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE);
        return mBluetoothGatt.writeDescriptor(descriptor);
    }

    return false;

}
 
Example 58
Project: BluetoothCtrl   File: BluetoothLeService.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) {
        ULog.i("onCharacteristicRead()");
        broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
    }
}
 
Example 59
Project: Bluetooth_BLE   File: BleManager.java   Source Code and License 5 votes vote down vote up
/**
 * 请求BLE设备获取数据
 * mGatt.setCharacteristicNotification(characteristic, true) 设置允许接收BLE设备返回的数据
 *
 * @param service 服务码
 * @param chara 特征码
 * @param desc
 * @param enable
 */
public void setCharacteristicNotification(UUID service, UUID chara, UUID desc, boolean enable) {
    BluetoothGattCharacteristic characteristic = mGatt.getService(service).getCharacteristic(chara);
    BluetoothGattDescriptor descriptor = characteristic.getDescriptor(desc);
    if (enable) {
        mGatt.setCharacteristicNotification(characteristic, true);
        descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
        mGatt.writeDescriptor(descriptor);
    } else {
        mGatt.setCharacteristicNotification(characteristic, false);
        descriptor.setValue(BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE);
        mGatt.writeDescriptor(descriptor);
    }
}
 
Example 60
Project: UDOOBluLib-android   File: UdooBluManager.java   Source Code and License 5 votes vote down vote up
public void subscribeNotification(String address, BluetoothGattCharacteristic characteristic, INotificationListener<byte[]> notificationListener) {
    if (characteristic != null) {
        mINotificationListenerMap.put(address + characteristic.getUuid().toString(), notificationListener);
        mUdooBluService.setCharacteristicNotification(address, characteristic, true);
        Log.i(TAG, "setNotification: ");
    }
}