Java Examples for android.bluetooth.BluetoothGattCharacteristic

The following java examples will help you to understand the usage of android.bluetooth.BluetoothGattCharacteristic. These source code samples are taken from different open source projects.

Example 1
Project: BleSensorTag-master  File: DeviceServicesActivity.java View source code
@Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
    if (gattServiceAdapter == null) {
        return false;
    }
    final BluetoothGattCharacteristic characteristic = gattServiceAdapter.getChild(groupPosition, childPosition);
    final DeviceDef def = getBleManager().getDeviceDefCollection().get(getDeviceName(), getDeviceAddress());
    if (def == null) {
        return false;
    }
    final Sensor<?> sensor = (Sensor<?>) def.getSensor(characteristic.getService().getUuid().toString());
    if (sensor == null) {
        return true;
    }
    if (sensor == activeSensor) {
        return true;
    }
    final String address = getDeviceAddress();
    if (sensor instanceof BaseSensor) {
        final BaseSensor<?> baseSensor = (BaseSensor<?>) sensor;
        if (activeSensor != null) {
            activeSensor.setEnabled(false);
            getBleManager().update(address, activeSensor, activeSensor.getConfigUUID(), null);
        }
        activeSensor = baseSensor;
        baseSensor.setEnabled(true);
        getBleManager().update(address, sensor, baseSensor.getConfigUUID(), null);
        getBleManager().listen(address, sensor, baseSensor.getDataUUID());
    } else {
        getBleManager().read(address, sensor, characteristic.getUuid().toString());
    }
    return true;
}
Example 2
Project: BluetoothBacon-master  File: GattSerialTransportProfile.java View source code
@Override
public void onServicesDiscovered(GattClient client) {
    BluetoothGattService service = client.getService(BEAN_SERIAL_SERVICE_UUID);
    mSerialCharacteristic = service.getCharacteristic(BEAN_SERIAL_CHARACTERISTIC_UUID);
    if (mSerialCharacteristic == null) {
        Log.w(TAG, "Did not find bean serial on device, disconnecting");
        abort();
    } else {
        if (BuildConfig.DEBUG) {
            Log.i(TAG, "Connected");
        }
        client.setCharacteristicNotification(mSerialCharacteristic, true);
        for (BluetoothGattDescriptor descriptor : mSerialCharacteristic.getDescriptors()) {
            if ((descriptor.getUuid().getMostSignificantBits() >> 32) == 0x2902) {
                descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
                client.writeDescriptor(descriptor);
            }
        }
        service = client.getService(BEAN_SCRATCH_SERVICE_UUID);
        for (BluetoothGattCharacteristic characteristic : service.getCharacteristics()) {
            client.setCharacteristicNotification(characteristic, true);
            for (BluetoothGattDescriptor descriptor : characteristic.getDescriptors()) {
                if ((descriptor.getUuid().getMostSignificantBits() >> 32) == 0x2902) {
                    descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
                    client.writeDescriptor(descriptor);
                }
            }
        }
    }
}
Example 3
Project: Bletia-master  File: BletiaTest.java View source code
@Test
public void writeCharacteristicSuccessfully() throws Exception {
    mBletia.writeCharacteristic(mCharacteristic).then(new DoneCallback<BluetoothGattCharacteristic>() {

        @Override
        public void onDone(BluetoothGattCharacteristic result) {
            assertThat(result.getUuid()).isEqualTo(mCharacteristic.getUuid());
            mLatch.countDown();
        }
    }).fail(mNeverCalledFailCallback);
    Thread.sleep(300);
    mCallbackHandler.onCharacteristicWrite(mBluetoothGattWrapper, mCharacteristic, BluetoothGatt.GATT_SUCCESS);
    await();
}
Example 4
Project: FirstBuild-Mobile-Android-master  File: BleManager.java View source code
@Override
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
    super.onCharacteristicRead(gatt, characteristic, status);
    Log.d(TAG, "onCharacteristicRead IN");
    // Retrieves address
    String address = gatt.getDevice().getAddress();
    // Retrieves uuid and value
    String uuid = characteristic.getUuid().toString();
    Log.d(TAG, "Read Characteristic UUID: " + uuid);
    byte[] value = characteristic.getValue();
    if (value != null) {
        printGattValue(value);
    }
    sendUpdate("onCharacteristicRead", new Object[] { address, uuid, value, status });
    executeNextOperation();
}
Example 5
Project: puck-central-android-master  File: GattManager.java View source code
@Override
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
    super.onCharacteristicChanged(gatt, characteristic);
    L.e("Characteristic " + characteristic.getUuid() + "was changed, device: " + device.getAddress());
    if (mCharacteristicChangeListeners.containsKey(characteristic.getUuid())) {
        for (CharacteristicChangeListener listener : mCharacteristicChangeListeners.get(characteristic.getUuid())) {
            listener.onCharacteristicChanged(device.getAddress(), characteristic);
        }
    }
}
Example 6
Project: RxAndroidBle-master  File: RxBleConnectionMock.java View source code
@Override
public Observable<BluetoothGattCharacteristic> getCharacteristic(@NonNull final UUID characteristicUuid) {
    return discoverServices().flatMap(new Func1<RxBleDeviceServices, Observable<? extends BluetoothGattCharacteristic>>() {

        @Override
        public Observable<? extends BluetoothGattCharacteristic> call(RxBleDeviceServices rxBleDeviceServices) {
            return rxBleDeviceServices.getCharacteristic(characteristicUuid);
        }
    });
}
Example 7
Project: Bean-Android-SDK-master  File: OADProfile.java View source code
/**
     * Received a notification on Block characteristic
     *
     * A notification to this characteristic means the Bean has accepted the most recent
     * firmware file we have offered, which is stored as `this.currentImage`. It is now
     * time to start sending blocks of FW to the device.
     *
     * @param characteristic BLE characteristic with a value equal to the the block number
     */
private void onNotificationBlock(BluetoothGattCharacteristic characteristic) {
    int requestedBlock = Convert.twoBytesToInt(characteristic.getValue(), Constants.CC2540_BYTE_ORDER);
    // Check for First block
    if (requestedBlock == 0) {
        Log.i(TAG, String.format("Image accepted (Name: %s) (Size: %s bytes)", currentImage.name(), currentImage.sizeBytes()));
        blockTransferStarted = System.currentTimeMillis() / 1000L;
        setState(OADState.BLOCK_XFER);
        nextBlock = 0;
    }
    // Normal BLOCK XFER state logic
    while (oadState == OADState.BLOCK_XFER && nextBlock <= currentImage.blockCount() - 1 && nextBlock < (requestedBlock + MAX_IN_AIR_BLOCKS)) {
        // Write the block, tell the OAD Listener
        writeToCharacteristic(oadBlock, currentImage.block(nextBlock));
        oadListener.progress(UploadProgress.create(nextBlock + 1, currentImage.blockCount()));
        nextBlock++;
        watchdog.poke();
    }
    // Check for final block requested, for logging purposes only
    if (requestedBlock == currentImage.blockCount() - 1) {
        // Calculate throughput
        long secondsElapsed = System.currentTimeMillis() / 1000L - blockTransferStarted;
        double KBs = 0;
        if (secondsElapsed > 0) {
            KBs = (double) (currentImage.sizeBytes() / secondsElapsed) / 1000;
        }
        // Log some stats
        Log.i(TAG, String.format("Final OAD Block Requested: %s/%s", nextBlock, currentImage.blockCount()));
        Log.i(TAG, String.format("Sent %d blocks in %d seconds (%.2f KB/s)", currentImage.blockCount(), secondsElapsed, KBs));
    }
}
Example 8
Project: Bluebit-master  File: AospGattService.java View source code
@Override
public List<GattCharacteristic> getCharacteristics() {
    mList.clear();
    /* Always return current charactesristic, we do not hold any cache. */
    List<BluetoothGattCharacteristic> chrs = mSrv.getCharacteristics();
    for (BluetoothGattCharacteristic chr : chrs) {
        mList.add(new AospGattCharacteristic(chr));
    }
    return mList;
}
Example 9
Project: Bluetooth-LE-Library---Android-master  File: DeviceControlActivity.java View source code
@Override
public boolean onChildClick(final ExpandableListView parent, final View v, final int groupPosition, final int childPosition, final long id) {
    final GattDataAdapterFactory.GattDataAdapter adapter = (GattDataAdapterFactory.GattDataAdapter) parent.getExpandableListAdapter();
    final BluetoothGattCharacteristic characteristic = adapter.getBluetoothGattCharacteristic(groupPosition, childPosition);
    final int charaProp = characteristic.getProperties();
    if ((charaProp | BluetoothGattCharacteristic.PROPERTY_READ) > 0) {
        // it first so it doesn't update the data field on the user interface.
        if (mNotifyCharacteristic != null) {
            mBluetoothLeService.setCharacteristicNotification(mNotifyCharacteristic, false);
            mNotifyCharacteristic = null;
        }
        mBluetoothLeService.readCharacteristic(characteristic);
    }
    if ((charaProp | BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) {
        mNotifyCharacteristic = characteristic;
        mBluetoothLeService.setCharacteristicNotification(characteristic, true);
    }
    return true;
}
Example 10
Project: Bluetooth-Manager-for-Glass-master  File: BleCharacteristicCardScrollAdapter.java View source code
@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder holder;
    if (convertView == null) {
        convertView = View.inflate(context, R.layout.ble_chara_card, null);
        holder = new ViewHolder();
        holder.icon = (ImageView) convertView.findViewById(R.id.imageView);
        holder.name = (TextView) convertView.findViewById(R.id.name);
        holder.text = (TextView) convertView.findViewById(R.id.text);
        holder.raw = (TextView) convertView.findViewById(R.id.raw);
        convertView.setTag(holder);
    } else {
        holder = (ViewHolder) convertView.getTag();
    }
    BluetoothGattCharacteristic characteristic = getItem(position);
    holder.name.setText(Characteristic.lookup(characteristic.getUuid(), characteristic.getUuid().toString()));
    final byte[] data = characteristic.getValue();
    if (data != null && data.length > 0) {
        String text = characteristic.getStringValue(0);
        holder.text.setText(text);
        final StringBuilder stringBuilder = new StringBuilder(data.length);
        for (byte byteChar : data) stringBuilder.append(String.format("%02X ", byteChar));
        holder.raw.setText(stringBuilder.toString());
    }
    return convertView;
}
Example 11
Project: Gadgetbridge-master  File: MiBand2Support.java View source code
public MiBand2Support enableFurtherNotifications(TransactionBuilder builder, boolean enable) {
    builder.notify(getCharacteristic(MiBand2Service.UUID_CHARACTERISTIC_3_CONFIGURATION), enable);
    builder.notify(getCharacteristic(MiBand2Service.UUID_CHARACTERISTIC_6_BATTERY_INFO), enable);
    builder.notify(getCharacteristic(MiBand2Service.UUID_CHARACTERISTIC_10_BUTTON), enable);
    BluetoothGattCharacteristic heartrateCharacteristic = getCharacteristic(GattCharacteristic.UUID_CHARACTERISTIC_HEART_RATE_MEASUREMENT);
    if (heartrateCharacteristic != null) {
        builder.notify(heartrateCharacteristic, enable);
    }
    return this;
}
Example 12
Project: Aerlink-for-Android-master  File: NotificationServiceHandler.java View source code
@Override
public void handleCharacteristic(BluetoothGattCharacteristic characteristic) {
    // Get notification packet from iOS
    byte[] packet = characteristic.getValue();
    switch(characteristic.getUuid().toString().toLowerCase()) {
        case ANCSConstants.CHARACTERISTIC_DATA_SOURCE:
            if (mPacketProcessor == null && packet.length >= 5) {
                byte[] notificationUID = new byte[] { packet[1], packet[2], packet[3], packet[4] };
                int notificationIndex = -1;
                for (int i = 0; i < mPendingNotifications.size(); i++) {
                    NotificationData notificationData = mPendingNotifications.get(i);
                    if (notificationData.compareUID(notificationUID)) {
                        notificationIndex = i;
                        break;
                    }
                }
                if (notificationIndex != -1) {
                    mPacketProcessor = new NotificationPacketProcessor(mPendingNotifications.get(notificationIndex));
                    mPendingNotifications.remove(notificationIndex);
                }
            }
            if (mPacketProcessor != null) {
                // Only remove callback if we are getting useful data
                cancelClearOldNotificationsTask();
                mPacketProcessor.process(packet);
                if (mPacketProcessor.hasFinishedProcessing()) {
                    NotificationData notificationData = mPacketProcessor.getNotificationData();
                    if (notificationData != null) {
                        if (notificationData.isIncomingCall()) {
                            onIncomingCall(notificationData);
                        } else {
                            onNotificationReceived(notificationData);
                        }
                    }
                    mPacketProcessor = null;
                }
            }
            if (mPendingNotifications.size() > 0 || mPacketProcessor != null) {
                // Clear notifications in case data never arrives
                scheduleClearOldNotificationsTask();
            }
            break;
        case ANCSConstants.CHARACTERISTIC_NOTIFICATION_SOURCE:
            try {
                switch(packet[0]) {
                    case ANCSConstants.EventIDNotificationAdded:
                    case ANCSConstants.EventIDNotificationModified:
                        // Request attributes for the new notification
                        byte[] getAttributesPacket = new byte[] { ANCSConstants.CommandIDGetNotificationAttributes, // UID
                        packet[4], packet[5], packet[6], packet[7], // App Identifier - NotificationAttributeIDAppIdentifier
                        ANCSConstants.NotificationAttributeIDAppIdentifier, // Followed by a 2-bytes max length parameter
                        ANCSConstants.NotificationAttributeIDTitle, (byte) 0xff, (byte) 0xff, // Followed by a 2-bytes max length parameter
                        ANCSConstants.NotificationAttributeIDMessage, (byte) 0xff, (byte) 0xff };
                        NotificationData notificationData = new NotificationData(packet);
                        mPendingNotifications.add(notificationData);
                        if (notificationData.hasPositiveAction()) {
                            getAttributesPacket = NotificationPacketProcessor.concat(getAttributesPacket, new byte[] { // Positive Action Label - NotificationAttributeIDPositiveActionLabel
                            ANCSConstants.NotificationAttributeIDPositiveActionLabel });
                        }
                        if (notificationData.hasNegativeAction()) {
                            getAttributesPacket = NotificationPacketProcessor.concat(getAttributesPacket, new byte[] { // Negative Action Label - NotificationAttributeIDNegativeActionLabel
                            ANCSConstants.NotificationAttributeIDNegativeActionLabel });
                        }
                        Command getAttributesCommand = new Command(ANCSConstants.SERVICE_UUID, ANCSConstants.CHARACTERISTIC_CONTROL_POINT, getAttributesPacket);
                        mServiceUtils.addCommandToQueue(getAttributesCommand);
                        // Clear notifications in case data never arrives
                        scheduleClearOldNotificationsTask();
                        break;
                    case ANCSConstants.EventIDNotificationRemoved:
                        if (packet[2] == 1) {
                            // Call ended
                            onCallEnded();
                        } else {
                            // Cancel notification in watch
                            String notificationId = new String(Arrays.copyOfRange(packet, 4, 8));
                            onNotificationCanceled(notificationId);
                        }
                        break;
                }
            } catch (Exception e) {
                Log.d(LOG_TAG, "error");
                e.printStackTrace();
            }
            break;
    }
}
Example 13
Project: AndroidWearBLE-master  File: BluetoothLeService.java View source code
private void startMonitoring(BluetoothGatt gatt, boolean value) {
    if (gatt == null) {
        return;
    }
    BluetoothGattService service = gatt.getService(BleServices.SVC_HEART_RATE);
    BluetoothGattCharacteristic characteristic = null;
    if (service == null) {
        Log.i(TAG, "service is null, trying creating one and characteristic");
        service = new BluetoothGattService(BleServices.SVC_HEART_RATE, 0);
        characteristic = new BluetoothGattCharacteristic(BleCharacteristics.CHAR_HEART_RATE_MEASUREMENT, 16, 0);
        service.addCharacteristic(characteristic);
    } else {
        characteristic = service.getCharacteristic(BleCharacteristics.CHAR_HEART_RATE_MEASUREMENT);
        if (characteristic == null) {
            Log.i(TAG, "characteristic is null");
            return;
        }
    }
    setCharacteristicNotification(characteristic, value);
}
Example 14
Project: bleYan-master  File: BleDeviceActivity.java View source code
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    List<BluetoothGattDescriptor> descriptors = characteristic.getDescriptors();
    if (descriptors != null && descriptors.size() > 0) {
        for (BluetoothGattDescriptor descriptor : descriptors) {
            final int properties = characteristic.getProperties();
            if ((properties | BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) {
                mBleHelper.updateCharacteristicNotification(UUID.fromString(serviceUUID), UUID.fromString(characteristicUUID), descriptor.getUuid(), isChecked);
            }
        }
        if (isChecked) {
            sb = new StringBuffer();
        }
    }
    dialog.dismiss();
}
Example 15
Project: gilgamesh-master  File: BluetoothLEController.java View source code
@Override
public // Result of a characteristic read operation
void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
    if (status == BluetoothGatt.GATT_SUCCESS) {
        // 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));
        }
    }
}
Example 16
Project: MovisensGattSensorExample-master  File: BluetoothLeService.java View source code
@Override
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
    bleQueue.onCharacteristicWrite(gatt, characteristic, status);
    if (status == BluetoothGatt.GATT_SUCCESS) {
        Log.d(TAG, "Characteristic writing successful");
    } else if (status == BluetoothGatt.GATT_INSUFFICIENT_AUTHENTICATION) {
        if (gatt.getDevice().getBondState() == BluetoothDevice.BOND_NONE) {
            Log.e(TAG, "Bonding required!!!");
        } else {
            // this situation happens when you try to connect for the
            // second time to already bonded device
            // it should never happen, in my opinion
            Log.e(TAG, "The phone is trying to read from paired device without encryption. Android Bug?");
        // I don't know what to do here
        // This error was found on Nexus 7 with KRT16S build of
        // Andorid 4.4. It does not appear on Samsung S4 with
        // Andorid 4.3.
        }
    } else {
        Log.e(TAG, "Error writing characteristic, status: " + status);
    }
}
Example 17
Project: accessory-samples-master  File: MainActivity.java View source code
/*
         * Send an enable command to each sensor by writing a configuration
         * characteristic.  This is specific to the SensorTag to keep power
         * low by disabling sensors you aren't using.
         */
private void enableNextSensor(BluetoothGatt gatt) {
    BluetoothGattCharacteristic characteristic;
    switch(mState) {
        case 0:
            Log.d(TAG, "Enabling pressure cal");
            characteristic = gatt.getService(PRESSURE_SERVICE).getCharacteristic(PRESSURE_CONFIG_CHAR);
            characteristic.setValue(new byte[] { 0x02 });
            break;
        case 1:
            Log.d(TAG, "Enabling pressure");
            characteristic = gatt.getService(PRESSURE_SERVICE).getCharacteristic(PRESSURE_CONFIG_CHAR);
            characteristic.setValue(new byte[] { 0x01 });
            break;
        case 2:
            Log.d(TAG, "Enabling humidity");
            characteristic = gatt.getService(HUMIDITY_SERVICE).getCharacteristic(HUMIDITY_CONFIG_CHAR);
            characteristic.setValue(new byte[] { 0x01 });
            break;
        default:
            mHandler.sendEmptyMessage(MSG_DISMISS);
            Log.i(TAG, "All Sensors Enabled");
            return;
    }
    gatt.writeCharacteristic(characteristic);
}
Example 18
Project: BLE-MIDI-for-Android-master  File: BleMidiPeripheralProvider.java View source code
@Override
public void onCharacteristicReadRequest(BluetoothDevice device, int requestId, int offset, BluetoothGattCharacteristic characteristic) {
    super.onCharacteristicReadRequest(device, requestId, offset, characteristic);
    UUID characteristicUuid = characteristic.getUuid();
    if (BleUuidUtils.matches(CHARACTERISTIC_BLE_MIDI, characteristicUuid)) {
        // send empty
        gattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, 0, new byte[] {});
    } else {
        switch(BleUuidUtils.toShortValue(characteristicUuid)) {
            case MODEL_NUMBER:
                gattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, 0, deviceName.getBytes(StandardCharsets.UTF_8));
                break;
            case MANUFACTURER_NAME:
                gattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, 0, manufacturer.getBytes(StandardCharsets.UTF_8));
                break;
            default:
                // send empty
                gattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, 0, new byte[] {});
                break;
        }
    }
}
Example 19
Project: cordova-plugin-ble-central-master  File: BLECentralPlugin.java View source code
@Override
public boolean execute(String action, CordovaArgs args, CallbackContext callbackContext) throws JSONException {
    LOG.d(TAG, "action = " + action);
    if (bluetoothAdapter == null) {
        Activity activity = cordova.getActivity();
        boolean hardwareSupportsBLE = activity.getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE) && Build.VERSION.SDK_INT >= 18;
        if (!hardwareSupportsBLE) {
            LOG.w(TAG, "This hardware does not support Bluetooth Low Energy.");
            callbackContext.error("This hardware does not support Bluetooth Low Energy.");
            return false;
        }
        BluetoothManager bluetoothManager = (BluetoothManager) activity.getSystemService(Context.BLUETOOTH_SERVICE);
        bluetoothAdapter = bluetoothManager.getAdapter();
    }
    boolean validAction = true;
    if (action.equals(SCAN)) {
        UUID[] serviceUUIDs = parseServiceUUIDList(args.getJSONArray(0));
        int scanSeconds = args.getInt(1);
        resetScanOptions();
        findLowEnergyDevices(callbackContext, serviceUUIDs, scanSeconds);
    } else if (action.equals(START_SCAN)) {
        UUID[] serviceUUIDs = parseServiceUUIDList(args.getJSONArray(0));
        resetScanOptions();
        findLowEnergyDevices(callbackContext, serviceUUIDs, -1);
    } else if (action.equals(STOP_SCAN)) {
        bluetoothAdapter.stopLeScan(this);
        callbackContext.success();
    } else if (action.equals(LIST)) {
        listKnownDevices(callbackContext);
    } else if (action.equals(CONNECT)) {
        String macAddress = args.getString(0);
        connect(callbackContext, macAddress);
    } else if (action.equals(DISCONNECT)) {
        String macAddress = args.getString(0);
        disconnect(callbackContext, macAddress);
    } else if (action.equals(READ)) {
        String macAddress = args.getString(0);
        UUID serviceUUID = uuidFromString(args.getString(1));
        UUID characteristicUUID = uuidFromString(args.getString(2));
        read(callbackContext, macAddress, serviceUUID, characteristicUUID);
    } else if (action.equals(READ_RSSI)) {
        String macAddress = args.getString(0);
        readRSSI(callbackContext, macAddress);
    } else if (action.equals(WRITE)) {
        String macAddress = args.getString(0);
        UUID serviceUUID = uuidFromString(args.getString(1));
        UUID characteristicUUID = uuidFromString(args.getString(2));
        byte[] data = args.getArrayBuffer(3);
        int type = BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT;
        write(callbackContext, macAddress, serviceUUID, characteristicUUID, data, type);
    } else if (action.equals(WRITE_WITHOUT_RESPONSE)) {
        String macAddress = args.getString(0);
        UUID serviceUUID = uuidFromString(args.getString(1));
        UUID characteristicUUID = uuidFromString(args.getString(2));
        byte[] data = args.getArrayBuffer(3);
        int type = BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE;
        write(callbackContext, macAddress, serviceUUID, characteristicUUID, data, type);
    } else if (action.equals(START_NOTIFICATION)) {
        String macAddress = args.getString(0);
        UUID serviceUUID = uuidFromString(args.getString(1));
        UUID characteristicUUID = uuidFromString(args.getString(2));
        registerNotifyCallback(callbackContext, macAddress, serviceUUID, characteristicUUID);
    } else if (action.equals(STOP_NOTIFICATION)) {
        String macAddress = args.getString(0);
        UUID serviceUUID = uuidFromString(args.getString(1));
        UUID characteristicUUID = uuidFromString(args.getString(2));
        removeNotifyCallback(callbackContext, macAddress, serviceUUID, characteristicUUID);
    } else if (action.equals(IS_ENABLED)) {
        if (bluetoothAdapter.isEnabled()) {
            callbackContext.success();
        } else {
            callbackContext.error("Bluetooth is disabled.");
        }
    } else if (action.equals(IS_CONNECTED)) {
        String macAddress = args.getString(0);
        if (peripherals.containsKey(macAddress) && peripherals.get(macAddress).isConnected()) {
            callbackContext.success();
        } else {
            callbackContext.error("Not connected.");
        }
    } else if (action.equals(SETTINGS)) {
        Intent intent = new Intent(Settings.ACTION_BLUETOOTH_SETTINGS);
        cordova.getActivity().startActivity(intent);
        callbackContext.success();
    } else if (action.equals(ENABLE)) {
        enableBluetoothCallback = callbackContext;
        Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        cordova.startActivityForResult(this, intent, REQUEST_ENABLE_BLUETOOTH);
    } else if (action.equals(START_STATE_NOTIFICATIONS)) {
        if (this.stateCallback != null) {
            callbackContext.error("State callback already registered.");
        } else {
            this.stateCallback = callbackContext;
            addStateListener();
            sendBluetoothStateChange(bluetoothAdapter.getState());
        }
    } else if (action.equals(STOP_STATE_NOTIFICATIONS)) {
        if (this.stateCallback != null) {
            // Clear callback in JavaScript without actually calling it
            PluginResult result = new PluginResult(PluginResult.Status.NO_RESULT);
            result.setKeepCallback(false);
            this.stateCallback.sendPluginResult(result);
            this.stateCallback = null;
        }
        removeStateListener();
        callbackContext.success();
    } else if (action.equals(START_SCAN_WITH_OPTIONS)) {
        UUID[] serviceUUIDs = parseServiceUUIDList(args.getJSONArray(0));
        JSONObject options = args.getJSONObject(1);
        resetScanOptions();
        this.reportDuplicates = options.optBoolean("reportDuplicates", false);
        findLowEnergyDevices(callbackContext, serviceUUIDs, -1);
    } else {
        validAction = false;
    }
    return validAction;
}
Example 20
Project: konashi-android-sdk-master  File: KonashiManager.java View source code
///////////////////////////
// PWM
///////////////////////////
/**
     * PIO �指定�ピンを PWM ���使用�る/����を設定�る
     * @param pin PWMモード�設定を�るPIO�ピン番�。Konashi.PIO0 〜 Konashi.PIO7。
     * @param mode 設定�るPWM�モード。Konashi.PWM_DISABLE, Konashi.PWM_ENABLE, Konashi.PWM_ENABLE_LED_MODE ���れ�をセット�る。
     */
public Promise<BluetoothGattCharacteristic, BletiaException, Void> pwmMode(final int pin, int mode) {
    Promise<BluetoothGattCharacteristic, BletiaException, Void> promise = execute(new PwmPinModeAction(getKonashiService(), pin, mode, mPwmStore.getModes())).then(mPwmDispatcher);
    if (mode == Konashi.PWM_ENABLE_LED_MODE) {
        promise.then(new DonePipe<BluetoothGattCharacteristic, BluetoothGattCharacteristic, BletiaException, Void>() {

            @Override
            public Promise<BluetoothGattCharacteristic, BletiaException, Void> pipeDone(BluetoothGattCharacteristic result) {
                return pwmPeriod(pin, Konashi.PWM_LED_PERIOD).then(mPwmDispatcher);
            }
        }).then(new DonePipe<BluetoothGattCharacteristic, BluetoothGattCharacteristic, BletiaException, Void>() {

            @Override
            public Promise<BluetoothGattCharacteristic, BletiaException, Void> pipeDone(BluetoothGattCharacteristic result) {
                return pwmLedDrive(pin, 0.0f).then(mPwmDispatcher);
            }
        });
    }
    return promise;
}
Example 21
Project: neatle-master  File: WriteCommandTest.java View source code
@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 22
Project: nikeplus-fuelband-se-reversed-master  File: MainActivity.java View source code
private void dumpServices(BluetoothGatt gatt) {
    for (BluetoothGattService svc : gatt.getServices()) {
        String svc_uuid = svc.getUuid().toString(), svc_name = GATTAttributes.lookup(svc_uuid, "");
        Logger.d("SERVICE " + svc_name + " ( " + svc_uuid + " )");
        for (BluetoothGattCharacteristic chara : svc.getCharacteristics()) {
            String chr_uuid = chara.getUuid().toString(), chr_name = GATTAttributes.lookup(chr_uuid, "");
            int chr_props = chara.getProperties();
            String props = "";
            Iterator it = propsMap.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry pairs = (Map.Entry) it.next();
                if ((chr_props & (Integer) pairs.getKey()) != 0) {
                    props += pairs.getValue().toString() + " ";
                }
            }
            Logger.d("    " + chr_name + " ( " + chr_uuid + " ) [" + props + "] : " + Utils.bytesToHex(chara.getValue()));
            for (BluetoothGattDescriptor desc : chara.getDescriptors()) {
                Logger.d("      DESC: " + desc.getUuid());
            }
        }
    }
    Logger.d("---------------------------------------------------------------------------");
}
Example 23
Project: PokemonGo_Android_RE-master  File: SfidaService.java View source code
public boolean enableDeviceControlServiceNotify() {
    Log.d(TAG, "enableDeviceControlServiceNotify()");
    BluetoothGattCharacteristic findCharacteristic = findCharacteristic(SfidaMessage.UUID_DEVICE_CONTROL_SERVICE, SfidaMessage.UUID_BUTTON_NOTIF_CHAR);
    if (findCharacteristic != null) {
        boolean sendToEnableSfidaNotification = sendToEnableSfidaNotification(findCharacteristic, true, SfidaMessage.UUID_BUTTON_NOTIF_CHAR);
        Log.d(TAG, "enableDeviceControlServiceNotify() result : " + sendToEnableSfidaNotification);
        return sendToEnableSfidaNotification;
    }
    Log.e(TAG, "enableDeviceControlServiceNotify() BluetoothGattCharacteristic not found.");
    return false;
}
Example 24
Project: GizwitsBLE-master  File: AndroidBle.java View source code
@Override
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
    String address = gatt.getDevice().getAddress();
    Log.d(TAG, "onCharacteristicRead " + address + " status " + status);
    if (status != BluetoothGatt.GATT_SUCCESS) {
        mService.requestProcessed(address, RequestType.READ_CHARACTERISTIC, false);
        return;
    }
    // Log.d(TAG, "data " + characteristic.getStringValue(0));
    mService.bleCharacteristicRead(gatt.getDevice().getAddress(), characteristic.getUuid().toString(), status, characteristic.getValue());
}
Example 25
Project: DeviceConnect-Android-master  File: BleDeviceService.java View source code
@Override
public void onServicesDiscovered(final BluetoothGatt gatt, final int status) {
    if (status == BluetoothGatt.GATT_SUCCESS) {
        if (DEBUG_LOG) {
            Log.w(TAG, "mBluetoothGatt = " + mBluetoothGatt);
        }
        BluetoothGattCharacteristic txChar;
        BluetoothGattService rxService = mBluetoothGatt.getService(RX_SERVICE_UUID2);
        if (rxService == null) {
            showMessage("mBluetoothGatt null" + mBluetoothGatt);
            showMessage("Rx service not found!");
            broadcastUpdate(DEVICE_DOES_NOT_SUPPORT_UART);
            return;
        }
        txChar = rxService.getCharacteristic(TX_CHAR_UUID2);
        if (txChar == null) {
            showMessage("Rx charateristic not found!");
            broadcastUpdate(DEVICE_DOES_NOT_SUPPORT_UART);
            return;
        }
        if (DEBUG_LOG) {
            Log.w(TAG, "RxChar = " + TX_CHAR_UUID2.toString());
        }
        mBluetoothGatt.setCharacteristicNotification(txChar, true);
        BluetoothGattDescriptor descriptor = txChar.getDescriptor(CCCD);
        descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
        mBluetoothGatt.writeDescriptor(descriptor);
        broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED);
    } else {
        if (DEBUG_LOG) {
            Log.w(TAG, "onServicesDiscovered received: " + status);
        }
    }
}
Example 26
Project: ble-test-peripheral-android-master  File: Peripheral.java View source code
@Override
public void onCharacteristicReadRequest(BluetoothDevice device, int requestId, int offset, BluetoothGattCharacteristic characteristic) {
    super.onCharacteristicReadRequest(device, requestId, offset, characteristic);
    Log.d(TAG, "Device tried to read characteristic: " + characteristic.getUuid());
    Log.d(TAG, "Value: " + Arrays.toString(characteristic.getValue()));
    if (offset != 0) {
        mGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_INVALID_OFFSET, offset, /* value (optional) */
        null);
        return;
    }
    mGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, offset, characteristic.getValue());
}
Example 27
Project: BleDemo-master  File: LibTestActivity.java View source code
@Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
    if (mGattCharacteristics != null) {
        final BluetoothGattCharacteristic characteristic = mGattCharacteristics.get(groupPosition).get(childPosition);
        final int charaProp = characteristic.getProperties();
        if ((charaProp & BluetoothGattCharacteristic.PROPERTY_READ) > 0) {
            //如果当�有一个NOTIFY的特�正在活动,�先关闭NOTIFY特�,�去开�READ特�
            if (mNotifyCharacteristic != null) {
                //                                setCharacteristicNotification(mNotifyCharacteristic, false);
                mNotifyCharacteristic = null;
            }
            Toast.makeText(LibTestActivity.this, "这是一个READ特�,开�读特�", Toast.LENGTH_SHORT).show();
            //开�读特�
            mBleAdmin.processDeviceService(new BleDeviceService(mCurrentDeviceAddress, characteristic.getUuid(), BleDeviceService.OperateType.Read));
        //                            readCharacteristic(characteristic);
        }
        if ((charaProp & BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) {
            mNotifyCharacteristic = characteristic;
            Toast.makeText(LibTestActivity.this, "这是一个NOTIFY特�,开�读特�", Toast.LENGTH_SHORT).show();
            mBleAdmin.processDeviceService(new BleDeviceService(mCurrentDeviceAddress, characteristic.getUuid(), BleDeviceService.OperateType.Notify));
        }
        if ((characteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_WRITE) != 0 && (characteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE) != 0) {
            Toast.makeText(LibTestActivity.this, "这是一个WRITE特�", Toast.LENGTH_SHORT).show();
        }
        return true;
    }
    return false;
}
Example 28
Project: Bluefruit_LE_Connect_Android-master  File: MainActivity.java View source code
// endregion
private void launchComponentActivity() {
    // Enable generic attribute service
    final BluetoothGattService genericAttributeService = mBleManager.getGattService(kGenericAttributeService);
    if (genericAttributeService != null) {
        Log.d(TAG, "kGenericAttributeService found. Check if kServiceChangedCharacteristic exists");
        final UUID characteristicUuid = UUID.fromString(kServiceChangedCharacteristic);
        final BluetoothGattCharacteristic dataCharacteristic = genericAttributeService.getCharacteristic(characteristicUuid);
        if (dataCharacteristic != null) {
            Log.d(TAG, "kServiceChangedCharacteristic exists. Enable indication");
            mBleManager.enableIndication(genericAttributeService, kServiceChangedCharacteristic, true);
        } else {
            Log.d(TAG, "Skip enable indications for kServiceChangedCharacteristic. Characteristic not found");
        }
    } else {
        Log.d(TAG, "Skip enable indications for kServiceChangedCharacteristic. kGenericAttributeService not found");
    }
    // Launch activity
    showConnectionStatus(false);
    if (mComponentToStartWhenConnected != null) {
        Log.d(TAG, "Start component:" + mComponentToStartWhenConnected);
        Intent intent = new Intent(MainActivity.this, mComponentToStartWhenConnected);
        if (mComponentToStartWhenConnected == BeaconActivity.class && mSelectedDeviceData != null) {
            intent.putExtra("rssi", mSelectedDeviceData.rssi);
        }
        startActivityForResult(intent, kActivityRequestCode_ConnectedActivity);
    }
}
Example 29
Project: FastBle-master  File: BleConnector.java View source code
/***************************************main operation************************************************/
/**
     * notify
     */
public boolean enableCharacteristicNotify(BleCharacterCallback bleCallback, String uuid_notify) {
    if (getCharacteristic() != null && (getCharacteristic().getProperties() | BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) {
        BleLog.w(TAG, "characteristic.getProperties():" + getCharacteristic().getProperties());
        handleCharacteristicNotificationCallback(bleCallback, uuid_notify);
        return setCharacteristicNotification(getBluetoothGatt(), getCharacteristic(), true);
    } else {
        if (bleCallback != null) {
            bleCallback.onFailure(new OtherException("this characteristic not support notify!"));
        }
        return false;
    }
}
Example 30
Project: android-BluetoothLeGatt-master  File: DeviceControlActivity.java View source code
@Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
    if (mGattCharacteristics != null) {
        final BluetoothGattCharacteristic characteristic = mGattCharacteristics.get(groupPosition).get(childPosition);
        final int charaProp = characteristic.getProperties();
        if ((charaProp | BluetoothGattCharacteristic.PROPERTY_READ) > 0) {
            // it first so it doesn't update the data field on the user interface.
            if (mNotifyCharacteristic != null) {
                mBluetoothLeService.setCharacteristicNotification(mNotifyCharacteristic, false);
                mNotifyCharacteristic = null;
            }
            mBluetoothLeService.readCharacteristic(characteristic);
        }
        if ((charaProp | BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) {
            mNotifyCharacteristic = characteristic;
            mBluetoothLeService.setCharacteristicNotification(characteristic, true);
        }
        return true;
    }
    return false;
}
Example 31
Project: BLEConnect-master  File: DeviceControlActivity.java View source code
// Demonstrates how to iterate through the supported GATT
// Services/Characteristics.
// In this sample, we populate the data structure that is bound to the
// ExpandableListView
// on the UI.
private void displayGattServices(List<BluetoothGattService> gattServices) {
    if (gattServices == null)
        return;
    String uuid = null;
    String unknownServiceString = getResources().getString(R.string.unknown_service);
    String unknownCharaString = getResources().getString(R.string.unknown_characteristic);
    ArrayList<HashMap<String, String>> gattServiceData = new ArrayList<HashMap<String, String>>();
    ArrayList<ArrayList<HashMap<String, String>>> gattCharacteristicData = new ArrayList<ArrayList<HashMap<String, String>>>();
    mGattCharacteristics = new ArrayList<ArrayList<BluetoothGattCharacteristic>>();
    // Loops through available GATT Services.
    for (BluetoothGattService gattService : gattServices) {
        HashMap<String, String> currentServiceData = new HashMap<String, String>();
        uuid = gattService.getUuid().toString();
        currentServiceData.put(LIST_NAME, SampleGattAttributes.lookup(uuid, unknownServiceString));
        currentServiceData.put(LIST_UUID, uuid);
        gattServiceData.add(currentServiceData);
        ArrayList<HashMap<String, String>> gattCharacteristicGroupData = new ArrayList<HashMap<String, String>>();
        List<BluetoothGattCharacteristic> gattCharacteristics = gattService.getCharacteristics();
        ArrayList<BluetoothGattCharacteristic> charas = new ArrayList<BluetoothGattCharacteristic>();
        // Loops through available Characteristics.
        for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
            if (UUID.fromString(SampleGattAttributes.HEART_RATE_MEASUREMENT).equals(gattCharacteristic.getUuid())) {
                Log.d(TAG, "Found heart rate");
                mNotifyCharacteristic = gattCharacteristic;
            }
            charas.add(gattCharacteristic);
            HashMap<String, String> currentCharaData = new HashMap<String, String>();
            uuid = gattCharacteristic.getUuid().toString();
            currentCharaData.put(LIST_NAME, SampleGattAttributes.lookup(uuid, unknownCharaString));
            currentCharaData.put(LIST_UUID, uuid);
            gattCharacteristicGroupData.add(currentCharaData);
        }
        mGattCharacteristics.add(charas);
        gattCharacteristicData.add(gattCharacteristicGroupData);
    }
}
Example 32
Project: TCC---DESENVOLVIMENTO---UNIVALI-master  File: DeviceControlActivity.java View source code
// Demonstrates how to iterate through the supported GATT
// Services/Characteristics.
// In this sample, we populate the data structure that is bound to the
// ExpandableListView
// on the UI.
private void displayGattServices(List<BluetoothGattService> gattServices) {
    if (gattServices == null)
        return;
    String uuid = null;
    String unknownServiceString = getResources().getString(R.string.unknown_service);
    String unknownCharaString = getResources().getString(R.string.unknown_characteristic);
    ArrayList<HashMap<String, String>> gattServiceData = new ArrayList<HashMap<String, String>>();
    ArrayList<ArrayList<HashMap<String, String>>> gattCharacteristicData = new ArrayList<ArrayList<HashMap<String, String>>>();
    mGattCharacteristics = new ArrayList<ArrayList<BluetoothGattCharacteristic>>();
    // Loops through available GATT Services.
    for (BluetoothGattService gattService : gattServices) {
        HashMap<String, String> currentServiceData = new HashMap<String, String>();
        uuid = gattService.getUuid().toString();
        currentServiceData.put(LIST_NAME, SampleGattAttributes.lookup(uuid, unknownServiceString));
        currentServiceData.put(LIST_UUID, uuid);
        gattServiceData.add(currentServiceData);
        ArrayList<HashMap<String, String>> gattCharacteristicGroupData = new ArrayList<HashMap<String, String>>();
        List<BluetoothGattCharacteristic> gattCharacteristics = gattService.getCharacteristics();
        ArrayList<BluetoothGattCharacteristic> charas = new ArrayList<BluetoothGattCharacteristic>();
        // Loops through available Characteristics.
        for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
            if (UUID.fromString(SampleGattAttributes.HEART_RATE_MEASUREMENT).equals(gattCharacteristic.getUuid())) {
                Log.d(TAG, "Freqüência cardíaca encontrada");
                mNotifyCharacteristic = gattCharacteristic;
            }
            charas.add(gattCharacteristic);
            HashMap<String, String> currentCharaData = new HashMap<String, String>();
            uuid = gattCharacteristic.getUuid().toString();
            currentCharaData.put(LIST_NAME, SampleGattAttributes.lookup(uuid, unknownCharaString));
            currentCharaData.put(LIST_UUID, uuid);
            gattCharacteristicGroupData.add(currentCharaData);
        }
        mGattCharacteristics.add(charas);
        gattCharacteristicData.add(gattCharacteristicGroupData);
    }
}
Example 33
Project: gsn-master  File: UartService.java View source code
private void broadcastUpdate(final String action, final BluetoothGattCharacteristic characteristic) {
    final Intent intent = new Intent(action);
    // This is handling for the notification on TX Character of NUS service
    if (TX_CHAR_UUID.equals(characteristic.getUuid())) {
        // Log.d(TAG, String.format("Received TX: %d",characteristic.getValue() ));
        intent.putExtra(EXTRA_DATA, characteristic.getValue());
    } else {
    }
    LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
Example 34
Project: iWish-master  File: ProgressActivity.java View source code
private void startHeart() {
    Log.e(TAG, "chiamato StartHeart");
    //nuovo if che sostituisce il bottone connect quindi connessione in automatico
    if (mDeviceAddress != null && mBluetoothLeService != null && mBluetoothLeService.getSupportedGattService() != null) {
        //ritorna il servizio Heart Rate
        BluetoothGattService mBluetoothGattService = mBluetoothLeService.getSupportedGattService();
        //richiede la characteristic Heart Rate Measurement caratteristica dei battiti cardiaci
        final BluetoothGattCharacteristic characteristic = mBluetoothGattService.getCharacteristic(BluetoothLeService.UUID_HEART_RATE_MEASUREMENT);
        final int charaProp = characteristic.getProperties();
        if ((charaProp | BluetoothGattCharacteristic.PROPERTY_READ) > 0) {
            // it first so it doesn't update the data field on the user interface.
            if (mNotifyCharacteristic != null) {
                mBluetoothLeService.setCharacteristicNotification(mNotifyCharacteristic, false);
                mNotifyCharacteristic = null;
            }
            mBluetoothLeService.readCharacteristic(characteristic);
        }
        if ((charaProp | BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) {
            mNotifyCharacteristic = characteristic;
            mBluetoothLeService.setCharacteristicNotification(characteristic, true);
        }
    } else {
        if (mDeviceAddress != null) {
            // Start heartRate.
            mHandler.postDelayed(new Runnable() {

                @Override
                public void run() {
                    startHeart();
                }
            }, START_HEART);
        }
    }
}
Example 35
Project: MultiFinder-master  File: BluetoothLeService.java View source code
private void broadcastUpdate(final String action, final BluetoothGattCharacteristic characteristic) {
    final Intent intent = new Intent(action);
    // 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 36
Project: RfTransceiver-master  File: BluetoothLeService.java View source code
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
    if (status == BluetoothGatt.GATT_SUCCESS) {
        if (writeCharacteristic == null) {
            BluetoothGattService writeServer = mBluetoothGatt.getService(UUID.fromString("0000ffe0-0000-1000-8000-00805f9b34fb"));
            writeCharacteristic = writeServer.getCharacteristic(UUID.fromString("0000ffe1-0000-1000-8000-00805f9b34fb"));
            final int charaProp = writeCharacteristic.getProperties();
            if ((charaProp | BluetoothGattCharacteristic.PROPERTY_READ) > 0) {
                // it first so it doesn't update the data field on the user interface.
                if (notifyCharacter != null) {
                    setCharacteristicNotification(notifyCharacter, false);
                    notifyCharacter = null;
                }
                readCharacteristic(writeCharacteristic);
            }
            if ((charaProp | BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) {
                notifyCharacter = writeCharacteristic;
                setCharacteristicNotification(writeCharacteristic, true);
            }
        }
        broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED);
    } else {
        Log.e(TAG, "onServicesDiscovered received: " + status);
    }
}
Example 37
Project: rtty_modem-master  File: BtScreen.java View source code
@Override
public void onReceive(Context context, Intent intent) {
    final String action = intent.getAction();
    if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {
        mConnected = true;
        updateConnectionState();
        scanLeDevice(false);
        lvValues.clear();
        lvAdapter.notifyDataSetChanged();
    //invalidateOptionsMenu();
    } else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {
        mConnected = false;
        updateConnectionState();
    //invalidateOptionsMenu();
    //clearUI();
    } else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {
        // Show all the supported services and characteristics on the
        // user interface.
        Log.i("BTLE", mBtService.getSupportedGattServices().toString());
        List<BluetoothGattService> l = mBtService.getSupportedGattServices();
        for (int i = 0; i < l.size(); i++) {
            Log.i("BTLE GATT", (l.get(i)).getUuid().toString());
            List<BluetoothGattCharacteristic> clist = l.get(i).getCharacteristics();
            for (int k = 0; k < clist.size(); k++) {
                String c = clist.get(k).getUuid().toString();
                //	 mBtService.setCharacteristicNotification( clist.get(k), true);
                if (LoraBsGattAttributes.UUID_TELEMETRY_STRING_ASCII.equals(clist.get(k).getUuid()))
                    mBtService.setCharacteristicNotification(clist.get(k), true);
                characteristic_list.add(c);
            }
        }
        displayGattServices(l);
    } else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
        Log.i("BTLE", intent.getStringExtra(BluetoothLeService.EXTRA_DATA));
    }
}
Example 38
Project: android-sdk-sources-for-api-level-23-master  File: BluetoothMidiDevice.java View source code
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
    if (status == BluetoothGatt.GATT_SUCCESS) {
        List<BluetoothGattService> services = mBluetoothGatt.getServices();
        for (BluetoothGattService service : services) {
            if (MIDI_SERVICE.equals(service.getUuid())) {
                Log.d(TAG, "found MIDI_SERVICE");
                List<BluetoothGattCharacteristic> characteristics = service.getCharacteristics();
                for (BluetoothGattCharacteristic characteristic : characteristics) {
                    if (MIDI_CHARACTERISTIC.equals(characteristic.getUuid())) {
                        Log.d(TAG, "found MIDI_CHARACTERISTIC");
                        mCharacteristic = characteristic;
                        // Specification says to read the characteristic first and then
                        // switch to receiving notifications
                        mBluetoothGatt.readCharacteristic(characteristic);
                        break;
                    }
                }
                break;
            }
        }
    } else {
        Log.e(TAG, "onServicesDiscovered received: " + status);
        close();
    }
}
Example 39
Project: android_frameworks_base-master  File: BluetoothMidiDevice.java View source code
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
    if (status == BluetoothGatt.GATT_SUCCESS) {
        List<BluetoothGattService> services = mBluetoothGatt.getServices();
        for (BluetoothGattService service : services) {
            if (MIDI_SERVICE.equals(service.getUuid())) {
                Log.d(TAG, "found MIDI_SERVICE");
                List<BluetoothGattCharacteristic> characteristics = service.getCharacteristics();
                for (BluetoothGattCharacteristic characteristic : characteristics) {
                    if (MIDI_CHARACTERISTIC.equals(characteristic.getUuid())) {
                        Log.d(TAG, "found MIDI_CHARACTERISTIC");
                        mCharacteristic = characteristic;
                        // Specification says to read the characteristic first and then
                        // switch to receiving notifications
                        mBluetoothGatt.readCharacteristic(characteristic);
                        break;
                    }
                }
                break;
            }
        }
    } else {
        Log.e(TAG, "onServicesDiscovered received: " + status);
        close();
    }
}
Example 40
Project: BetterBluetoothLE-master  File: AsyncBluetoothGattTest.java View source code
@Test
public void test_read_characteristic_immediate_failure_rejects_promise() throws Exception {
    AsyncBluetoothGatt gatt = connectedAsyncGatt();
    BluetoothGattService service = mockService(TEST_UUID1, 0);
    BluetoothGattCharacteristic ch = mockCharacteristic(TEST_UUID1, 0, service);
    when(gatt.getGatt().readCharacteristic(ch)).thenReturn(false);
    Promise<BluetoothGattCharacteristic, Integer, Void> readCh = gatt.readCharacteristic(ch);
    assertThat(readCh.isPending()).isFalse();
    assertThat(readCh.isRejected()).isTrue();
    assertThat(readCh.isResolved()).isFalse();
}
Example 41
Project: BGSEP-master  File: HIDoverGattProfile.java View source code
private BluetoothGattService createHIDService() {
    UUID uuid = createUUID(SIG_HID);
    Log.d(TAG, "HID UUID: " + uuid.toString());
    HIDService = new BluetoothGattService(uuid, BluetoothGattService.SERVICE_TYPE_PRIMARY);
    BluetoothGattCharacteristic reportMapCharacteristic = new BluetoothGattCharacteristic(createUUID(SIG_CHARA_REPORT_MAP), BluetoothGattCharacteristic.PROPERTY_READ, BluetoothGattCharacteristic.PERMISSION_READ);
    reportMapCharacteristic.setValue(GAMEPAD_VALUE);
    BluetoothGattCharacteristic HIDInformationCharacteristic = new BluetoothGattCharacteristic(createUUID(SIG_CHARA_HID_INFORMATION), BluetoothGattCharacteristic.PROPERTY_READ, BluetoothGattCharacteristic.PERMISSION_READ);
    // version,
    byte[] HIDInformationValue = { 0x01, 0x11, 26, 0x40 };
    // version,
    // sweden's
    // country code
    // in decimal,
    // flags 0100
    // 0000
    HIDInformationCharacteristic.setValue(HIDInformationValue);
    BluetoothGattCharacteristic HIDControlPointCharacteristic = new BluetoothGattCharacteristic(createUUID(SIG_CHARA_HID_CONTROL_POINT), BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE, BluetoothGattCharacteristic.PERMISSION_WRITE);
    HIDService.addCharacteristic(reportMapCharacteristic);
    HIDService.addCharacteristic(HIDInformationCharacteristic);
    HIDService.addCharacteristic(HIDControlPointCharacteristic);
    return HIDService;
}
Example 42
Project: bikey-master  File: HeartRateManagerJellyBeanMR2.java View source code
@Override
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
    Log.d("characteristic=" + characteristic.getUuid());
    int format;
    int flag = characteristic.getProperties();
    if ((flag & 0x01) != 0) {
        format = BluetoothGattCharacteristic.FORMAT_UINT16;
    } else {
        format = BluetoothGattCharacteristic.FORMAT_UINT8;
    }
    int previousValue = mLastValue;
    int value = characteristic.getIntValue(format, 1);
    if (value < 50) {
        // This is probably a false measurement, consider this as a disconnect
        if (mStatus == Status.CONNECTED) {
            // Disconnect
            onDisconnect();
        }
        return;
    }
    mLastValue = value;
    Log.d("heartRate=" + mLastValue);
    if (mStatus != Status.CONNECTED) {
        mStatus = Status.CONNECTED;
        // Inform listeners
        mListeners.dispatch(HeartRateListener::onConnected);
    }
    if (previousValue != mLastValue) {
        // Inform listeners
        mListeners.dispatch( listener -> listener.onHeartRateChange(mLastValue));
    }
}
Example 43
Project: MiBand-Notify-master  File: BLECommunicationManager.java View source code
public void run() {
    while (true) {
        BLEAction action = null;
        try {
            action = bleActions.take();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if (action instanceof WaitAction) {
            action.run();
        } else if (action instanceof WriteAction) {
            try {
                BluetoothGattCharacteristic characteristic = getCharacteristic(((WriteAction) action).getCharacteristic());
                characteristic.setValue(((WriteAction) action).getPayload());
                write(characteristic);
            } catch (MiBandConnectFailureException e) {
                Log.i(TAG, "Write failed");
            }
        }
    }
}
Example 44
Project: physical-web-master  File: FatBeaconBroadcastService.java View source code
@Override
public void onCharacteristicReadRequest(BluetoothDevice device, int requestId, int offset, BluetoothGattCharacteristic characteristic) {
    super.onCharacteristicReadRequest(device, requestId, offset, characteristic);
    Log.i(TAG, "onCharacteristicReadRequest " + characteristic.getUuid().toString());
    if (CHARACTERISTIC_WEBPAGE_UUID.equals(characteristic.getUuid())) {
        Log.d(TAG, "Data length:" + data.length + ", offset:" + queueOffset);
        if (queueOffset < data.length) {
            int end = queueOffset + transferSpeed >= data.length ? data.length : queueOffset + transferSpeed;
            Log.d(TAG, "Data length:" + data.length + ", offset:" + queueOffset + ", end:" + end);
            mGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, 0, Arrays.copyOfRange(data, queueOffset, end));
            queueOffset = end;
        } else if (queueOffset == data.length) {
            mGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, 0, new byte[] {});
            queueOffset++;
        }
    }
    /*
             * Unless the characteristic supports WRITE_NO_RESPONSE,
             * always send a response back for any request.
             */
    mGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_FAILURE, 0, null);
}
Example 45
Project: platform_frameworks_base-master  File: BluetoothMidiDevice.java View source code
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
    if (status == BluetoothGatt.GATT_SUCCESS) {
        List<BluetoothGattService> services = mBluetoothGatt.getServices();
        for (BluetoothGattService service : services) {
            if (MIDI_SERVICE.equals(service.getUuid())) {
                Log.d(TAG, "found MIDI_SERVICE");
                List<BluetoothGattCharacteristic> characteristics = service.getCharacteristics();
                for (BluetoothGattCharacteristic characteristic : characteristics) {
                    if (MIDI_CHARACTERISTIC.equals(characteristic.getUuid())) {
                        Log.d(TAG, "found MIDI_CHARACTERISTIC");
                        mCharacteristic = characteristic;
                        // Specification says to read the characteristic first and then
                        // switch to receiving notifications
                        mBluetoothGatt.readCharacteristic(characteristic);
                        break;
                    }
                }
                break;
            }
        }
    } else {
        Log.e(TAG, "onServicesDiscovered received: " + status);
        close();
    }
}
Example 46
Project: BlunoAccessoryShieldDemo-master  File: BlunoLibrary.java View source code
private void getGattServices(List<BluetoothGattService> gattServices) {
    if (gattServices == null)
        return;
    String uuid = null;
    mModelNumberCharacteristic = null;
    mSerialPortCharacteristic = null;
    mCommandCharacteristic = null;
    mGattCharacteristics = new ArrayList<ArrayList<BluetoothGattCharacteristic>>();
    // Loops through available GATT Services.
    for (BluetoothGattService gattService : gattServices) {
        uuid = gattService.getUuid().toString();
        System.out.println("displayGattServices + uuid=" + uuid);
        List<BluetoothGattCharacteristic> gattCharacteristics = gattService.getCharacteristics();
        ArrayList<BluetoothGattCharacteristic> charas = new ArrayList<BluetoothGattCharacteristic>();
        // Loops through available Characteristics.
        for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
            charas.add(gattCharacteristic);
            uuid = gattCharacteristic.getUuid().toString();
            if (uuid.equals(ModelNumberStringUUID)) {
                mModelNumberCharacteristic = gattCharacteristic;
                System.out.println("mModelNumberCharacteristic  " + mModelNumberCharacteristic.getUuid().toString());
            } else if (uuid.equals(SerialPortUUID)) {
                mSerialPortCharacteristic = gattCharacteristic;
                System.out.println("mSerialPortCharacteristic  " + mSerialPortCharacteristic.getUuid().toString());
            //                    updateConnectionState(R.string.comm_establish);
            } else if (uuid.equals(CommandUUID)) {
                mCommandCharacteristic = gattCharacteristic;
                System.out.println("mSerialPortCharacteristic  " + mSerialPortCharacteristic.getUuid().toString());
            //                    updateConnectionState(R.string.comm_establish);
            }
        }
        mGattCharacteristics.add(charas);
    }
    if (mModelNumberCharacteristic == null || mSerialPortCharacteristic == null || mCommandCharacteristic == null) {
        Toast.makeText(mainContext, "Please select DFRobot devices", Toast.LENGTH_SHORT).show();
        mConnectionState = connectionStateEnum.isToScan;
        onConectionStateChange(mConnectionState);
    } else {
        mSCharacteristic = mModelNumberCharacteristic;
        mBluetoothLeService.setCharacteristicNotification(mSCharacteristic, true);
        mBluetoothLeService.readCharacteristic(mSCharacteristic);
    }
}
Example 47
Project: hoit-master  File: DeviceActivity.java View source code
private void enableSensors(boolean f) {
    final boolean enable = f;
    for (Sensor sensor : mEnabledSensors) {
        UUID servUuid = sensor.getService();
        UUID confUuid = sensor.getConfig();
        // Skip keys
        if (confUuid == null)
            break;
        if (!mIsSensorTag2) {
            // Barometer calibration
            if (confUuid.equals(SensorTagGatt.UUID_BAR_CONF) && enable) {
                calibrateBarometer();
            }
        }
        BluetoothGattService serv = mBtGatt.getService(servUuid);
        if (serv != null) {
            BluetoothGattCharacteristic charac = serv.getCharacteristic(confUuid);
            byte value = enable ? sensor.getEnableSensorCode() : Sensor.DISABLE_SENSOR_CODE;
            if (mBtLeService.writeCharacteristic(charac, value)) {
                mBtLeService.waitIdle(GATT_TIMEOUT);
            } else {
                setError("Sensor config failed: " + serv.getUuid().toString());
                break;
            }
        }
    }
}
Example 48
Project: android-microduino-master  File: BluetoothLeService.java View source code
private void broadcastUpdate(final String action, final BluetoothGattCharacteristic characteristic) {
    final Intent intent = new Intent(action);
    // For all other profiles, writes the data formatted in HEX.
    final byte[] data = characteristic.getValue();
    Log.i(TAG, "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));
        Log.d(TAG, String.format("%s", new String(data)));
        // getting cut off when longer, need to push on new line, 0A
        intent.putExtra(EXTRA_DATA, String.format("%s", new String(data)));
    }
    sendBroadcast(intent);
}
Example 49
Project: intro-to-ble-master  File: BLEHandler.java View source code
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
    BluetoothDevice device = gatt.getDevice();
    String localName = device.getName();
    String macAddress = device.getAddress();
    if (status == BluetoothGatt.GATT_SUCCESS) {
        //Step 4 and 5: Services discovered.
        //Characteristics and descriptors are automatically discovered with services in Android so we can stop here.
        logDeviceMessage("Services discovered for", gatt.getDevice());
        //Find the relevant service by UUID
        BluetoothGattService customService = getCustomService();
        BluetoothGattCharacteristic buttonChar = customService.getCharacteristic(UUID_CHAR_BUTTON);
        //Apply to be notified so we can listen to changes in button characteristic
        gatt.setCharacteristicNotification(buttonChar, true);
        //Extra step for Android, write enable to CCCD
        BluetoothGattDescriptor descriptor = buttonChar.getDescriptor(UUID_CLIENT_CHARACTERISTIC_CONFIG_DESCRIPTOR);
        descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
        gatt.writeDescriptor(descriptor);
        bleHandlerCallback.servicesDiscoveredState(localName, macAddress, true);
    } else {
        logDeviceMessage("Services status " + status + " for", gatt.getDevice());
        bleHandlerCallback.servicesDiscoveredState(localName, macAddress, false);
    }
}
Example 50
Project: Mi-Band-master  File: MiBand.java View source code
@Override
public void onSuccess(Object data) {
    BluetoothGattCharacteristic characteristic = (BluetoothGattCharacteristic) data;
    //Log.d(TAG, "pair result " + Arrays.toString(characteristic.getValue()));
    if (characteristic.getValue().length == 1 && characteristic.getValue()[0] == 2) {
        Log.d(TAG, "Pairing success!");
        setUserInfo(UserInfo.getSavedUser(context));
        //setUserInfo(null);
        if (connectionCallback != null)
            connectionCallback.onSuccess(null);
    } else {
        if (connectionCallback != null)
            connectionCallback.onFail(-1, "failed to pair with Mi Band");
    }
}
Example 51
Project: OldLilliput-master  File: BluetoothService.java View source code
// It makes BluetoothLeService to read data of the characteristic and broadcast the data.
private boolean readCharacteristic(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
    if (null == characteristic)
        return false;
    final int charaProp = characteristic.getProperties();
    if ((charaProp | BluetoothGattCharacteristic.PROPERTY_READ) > 0) {
        // clear it first so it doesn't update the data field on the user interface.
        if (mNotifyCharacteristic != null) {
            bleService.setCharacteristicNotification(gatt, mNotifyCharacteristic, false);
            mNotifyCharacteristic = null;
        }
        //JS: if no data is displayed, immediately read data from the connected sensor.
        gatt.readCharacteristic(characteristic);
    }
    if ((charaProp | BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) {
        mNotifyCharacteristic = characteristic;
        bleService.setCharacteristicNotification(gatt, characteristic, true);
    }
    return true;
}
Example 52
Project: openScale-master  File: BluetoothSanitasSbf70.java View source code
/**
         * @brief configure the scale
         */
private void init(final BluetoothGatt gatt) {
    BluetoothGattCharacteristic characteristic;
    BluetoothGattDescriptor descriptor;
    characteristic = gatt.getService(CUSTOM_SERVICE_1).getCharacteristic(CUSTOM_CHARACTERISTIC_WEIGHT);
    gatt.setCharacteristicNotification(characteristic, true);
    descriptor = characteristic.getDescriptor(CLIENT_CHARACTERISTICS_CONFIGURATION);
    descriptor.setValue(new byte[] { (byte) 0x01, (byte) 0x00 });
    gatt.writeDescriptor(descriptor);
    msgQueue.add(new byte[] { (byte) 0xe6, (byte) 0x01 });
    canSend = false;
}
Example 53
Project: xDrip-master  File: DexShareCollectionService.java View source code
public void setCharacteristicNotification(BluetoothGattCharacteristic characteristic, boolean enabled) {
    Log.w(TAG, "Characteristic setting notification");
    mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);
    BluetoothGattDescriptor descriptor = characteristic.getDescriptor(UUID.fromString(HM10Attributes.CLIENT_CHARACTERISTIC_CONFIG));
    Log.w(TAG, "Descriptor found: " + descriptor.getUuid());
    descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
    mBluetoothGatt.writeDescriptor(descriptor);
}
Example 54
Project: android-bluetooth-demo-master  File: MainActivity.java View source code
/**
     * Writes a value (alternating 0 and 1) to the characteristics
     */
private void write() {
    if (mWriteCharacteristic == null) {
        Log.e(TAG, "There's no characteristic to write to");
    }
    // Disable until write has finished to prevent sending faster than the connection can handle
    mBtWrite.setEnabled(false);
    if ((mWriteCharacteristic.getProperties() | BluetoothGattCharacteristic.PROPERTY_WRITE) > 0) {
        Log.i(TAG, "Writing data to bluetooth device...");
        mWriteCharacteristic.setValue(new byte[] { mWriteValue });
        mGatt.writeCharacteristic(mWriteCharacteristic);
    } else {
        Log.w(TAG, "Characteristic " + CHARACTERISTIC_A_WRITE + " not writable");
    }
}
Example 55
Project: android_wear_for_ios-master  File: BLEService.java View source code
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
    Log.d(TAG_LOG, "onServicesDiscovered received: " + status);
    if (status == BluetoothGatt.GATT_SUCCESS) {
        BluetoothGattService service = gatt.getService(UUID.fromString(service_ancs));
        if (service == null) {
            Log.d(TAG_LOG, "cant find service");
        } else {
            Log.d(TAG_LOG, "find service");
            Log.d(TAG_LOG, String.valueOf(bluetooth_gatt.getServices()));
            // subscribe data source characteristic
            BluetoothGattCharacteristic data_characteristic = service.getCharacteristic(UUID.fromString(characteristics_data_source));
            if (data_characteristic == null) {
                Log.d(TAG_LOG, "cant find data source chara");
            } else {
                Log.d(TAG_LOG, "find data source chara :: " + data_characteristic.getUuid());
                Log.d(TAG_LOG, "set notify:: " + data_characteristic.getUuid());
                bluetooth_gatt.setCharacteristicNotification(data_characteristic, true);
                BluetoothGattDescriptor descriptor = data_characteristic.getDescriptor(UUID.fromString(descriptor_config));
                if (descriptor == null) {
                    Log.d(TAG_LOG, " ** cant find desc :: " + descriptor.getUuid());
                } else {
                    Log.d(TAG_LOG, " ** find desc :: " + descriptor.getUuid());
                    descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
                    bluetooth_gatt.writeDescriptor(descriptor);
                    if (api_level >= 21) {
                        stop_le_scanner();
                    } else {
                        bluetooth_adapter.stopLeScan(le_scan_callback);
                    }
                }
            }
        }
    }
}
Example 56
Project: H-Ble-master  File: BleController.java View source code
//�务被�现了
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
    if (null != mBluetoothGatt && status == BluetoothGatt.GATT_SUCCESS) {
        List<BluetoothGattService> services = mBluetoothGatt.getServices();
        int serviceSize = services.size();
        for (int i = 0; i < serviceSize; i++) {
            HashMap<String, BluetoothGattCharacteristic> charMap = new HashMap<>();
            BluetoothGattService bluetoothGattService = services.get(i);
            String serviceUuid = bluetoothGattService.getUuid().toString();
            List<BluetoothGattCharacteristic> characteristics = bluetoothGattService.getCharacteristics();
            int characteristicSize = characteristics.size();
            for (int j = 0; j < characteristicSize; j++) {
                charMap.put(characteristics.get(j).getUuid().toString(), characteristics.get(j));
                if (characteristics.get(j).getUuid().toString().equals(BLUETOOTH_NOTIFY_C)) {
                    if (enableNotification(true, characteristics.get(j))) {
                        isConnectResponse = true;
                        connSuccess();
                    } else {
                        reConnect();
                    }
                }
            }
            servicesMap.put(serviceUuid, charMap);
        }
    // TODO 打��索到的�务
    //                printServices(mBluetoothGatt);
    }
}
Example 57
Project: nova-android-sdk-master  File: BluetoothLENovaLink.java View source code
// ------------------------------
// Establish connection to device
// ------------------------------
private void connect(BluetoothDevice device) {
    debug("connect() " + deviceDetails(device));
    // Connects to the discovered device
    activeDevice = device;
    // These callbacks are generated by an internal Bluetooth thread.
    // Before we do anything we need to thunk back to the main thread.
    activeGatt = device.connectGatt(activity, false, /* first connect false, subsequent true */
    new BluetoothGattCallback() {

        @Override
        public void onConnectionStateChange(final BluetoothGatt gatt, final int status, final int newState) {
            activity.runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    BluetoothLENovaLink.this.onConnectionStateChange(gatt, status, newState);
                }
            });
        }

        @Override
        public void onServicesDiscovered(final BluetoothGatt gatt, final int status) {
            activity.runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    BluetoothLENovaLink.this.onServicesDiscovered(gatt, status);
                }
            });
        }

        @Override
        public void onCharacteristicChanged(final BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic) {
            activity.runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    BluetoothLENovaLink.this.onCharacteristicChanged(gatt, characteristic);
                }
            });
        }

        @Override
        public void onCharacteristicWrite(final BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic, final int status) {
            activity.runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    BluetoothLENovaLink.this.onCharacteristicWrite(gatt, characteristic, status);
                }
            });
        }
    });
    setStatus(NovaLinkStatus.Connecting);
}
Example 58
Project: remotteSDK_Android-master  File: MainActivity.java View source code
//AFTER CONNECTED TO GATT, THIS FUNCTION IS CALLED TO SCAN FOR SERVICES AND CHARACTERISTICS
private void displayGattServices(List<BluetoothGattService> gattServices) {
    if (gattServices == null)
        return;
    chars = new ArrayList<BluetoothGattCharacteristic>();
    for (BluetoothGattService gattService : gattServices) {
        List<BluetoothGattCharacteristic> gattCharacteristics = gattService.getCharacteristics();
        for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
            chars.add(gattCharacteristic);
            if (//SEARCH AND STORE FOR THE CONFIGURATION CHARACTERISTIC
            gattCharacteristic.getUuid().toString().contains("aa62")) {
                mChar = gattCharacteristic;
            }
        }
    }
}
Example 59
Project: runner-master  File: AndroidBLEHRProvider.java View source code
@Override
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic arg0) {
    try {
        if (!checkBtGattOnlyLogError(gatt)) {
            return;
        }
        if (!arg0.getUuid().equals(HEART_RATE_MEASUREMENT_CHARAC)) {
            log("onCharacteristicChanged(" + arg0 + ") != HEART_RATE ??");
            return;
        }
        int length = arg0.getValue().length;
        if (length == 0) {
            log("onCharacteristicChanged length = 0");
            return;
        }
        if (isHeartRateInUINT16(arg0.getValue()[0])) {
            hrValue = arg0.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT16, 1);
        } else {
            hrValue = arg0.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8, 1);
        }
        if (hrValue == 0) {
            if (mIsConnecting) {
                reportConnectFailed("got hrValue = 0 => reportConnectFailed");
                return;
            }
            log("got hrValue == 0 => disconnecting");
            reportDisconnected();
            return;
        }
        hrTimestamp = System.currentTimeMillis();
        if (mIsConnecting) {
            reportConnected(true);
        }
    } catch (Exception e) {
        log("onCharacteristicChanged => " + e);
        if (mIsConnecting)
            reportConnectFailed("Exception in onCharacteristicChanged: " + e);
        else if (mIsConnected)
            reportDisconnected();
    }
}
Example 60
Project: runnerup-master  File: AndroidBLEHRProvider.java View source code
@Override
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic arg0) {
    try {
        if (!checkBtGattOnlyLogError(gatt)) {
            return;
        }
        if (!arg0.getUuid().equals(HEART_RATE_MEASUREMENT_CHARAC)) {
            log("onCharacteristicChanged(" + arg0 + ") != HEART_RATE ??");
            return;
        }
        int length = arg0.getValue().length;
        if (length == 0) {
            log("onCharacteristicChanged length = 0");
            return;
        }
        if (isHeartRateInUINT16(arg0.getValue()[0])) {
            hrValue = arg0.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT16, 1);
        } else {
            hrValue = arg0.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8, 1);
        }
        if (hrValue == 0) {
            if (mIsConnecting) {
                reportConnectFailed("got hrValue = 0 => reportConnectFailed");
                return;
            }
            log("got hrValue == 0 => disconnecting");
            reportDisconnected();
            return;
        }
        hrTimestamp = System.currentTimeMillis();
        if (mIsConnecting) {
            reportConnected(true);
        }
    } catch (Exception e) {
        log("onCharacteristicChanged => " + e);
        if (mIsConnecting)
            reportConnectFailed("Exception in onCharacteristicChanged: " + e);
        else if (mIsConnected)
            reportDisconnected();
    }
}
Example 61
Project: zcamp14-schild-master  File: CommunicationService.java View source code
private void writeNamesToConnectedPlate() {
    if (BTLE_WRITE_FLAG == BTLE_WRITE_OK) {
        if (namesToWrite.isEmpty()) {
            revisionNumberCharacteristic.setValue(doorPlateRevisionNumber, BluetoothGattCharacteristic.FORMAT_UINT32, 0);
            mBluetoothGatt.writeCharacteristic(revisionNumberCharacteristic);
        } else {
            String name = namesToWrite.pop();
            System.out.println("Write person " + name);
            try {
                personCharacteristic.setValue(name.getBytes("ASCII"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            mBluetoothGatt.writeCharacteristic(personCharacteristic);
        }
    } else {
        closeConnection();
    }
}
Example 62
Project: BLEFOTA-master  File: BflFwUploadService.java View source code
/**
         * Check BLE property.
         *
         * @param serviceIdx is the service index of the FOTA profile.
         * @param characteristicIdx is the characteristic index of the FOTA profile.
         * @return false, if mBflGattCharacteristics is not available.
         * @throws RemoteException
         */
@Override
public boolean checkProperty(int serviceIdx, int characteristicIdx) throws RemoteException {
    if (mBflGattCharacteristics != null) {
        final BluetoothGattCharacteristic characteristic = mBflGattCharacteristics.get(serviceIdx).get(characteristicIdx);
        final int characteristicProperty = characteristic.getProperties();
        if ((characteristicProperty | BluetoothGattCharacteristic.PROPERTY_READ) > 0) {
            // clear it first so it doesn't update the data field on the user interface.
            if (mNotifyCharacteristic != null) {
                setCharacteristicNotification(mNotifyCharacteristic, false);
                mNotifyCharacteristic = null;
                Log.i(BLE_FOTA_TAG, "READ Characteristic property: " + characteristicProperty);
            }
            writeBflCharacteristic(characteristic);
        }
        if ((characteristicProperty | BluetoothGattCharacteristic.PROPERTY_WRITE) > 0) {
            // clear it first so it doesn't update the data field on the user interface.
            if (mNotifyCharacteristic != null) {
                setCharacteristicNotification(mNotifyCharacteristic, false);
                mNotifyCharacteristic = null;
                Log.i(BLE_FOTA_TAG, "WRITE Characteristic property: " + characteristicProperty);
            }
            writeBflCharacteristic(characteristic);
        }
        if ((characteristicProperty | BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) {
            // NOTIFY property: 0X00000010
            mNotifyCharacteristic = characteristic;
            setCharacteristicNotification(characteristic, true);
            Log.i(BLE_FOTA_TAG, "NOTIFICATION Characteristic property: " + characteristicProperty);
        }
        return true;
    }
    return false;
}
Example 63
Project: BlueNinja_BLE_EXAMPLE_App4Android-master  File: MainActivity.java View source code
@Override
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
    Log.d(TAG, "onCharacteristicChanged");
    /* 加速度 */
    if (UUID_CHARACTERISTIC_ACCEL.equals(characteristic.getUuid().toString())) {
        byte[] read_data = characteristic.getValue();
        try {
            JSONObject json = new JSONObject(new String(read_data));
            mAccel[0] = json.getDouble("ax");
            mAccel[1] = json.getDouble("ay");
            mAccel[2] = json.getDouble("az");
            setStatus(AppState.BLE_DATA_UPDATE, ValueType.VT_ACCEL);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    /* 角速度 */
    if (UUID_CHARACTERISTIC_GYRO.equals(characteristic.getUuid().toString())) {
        byte[] read_data = characteristic.getValue();
        try {
            JSONObject json = new JSONObject(new String(read_data));
            mGyro[0] = json.getDouble("gx");
            mGyro[1] = json.getDouble("gy");
            mGyro[2] = json.getDouble("gz");
            setStatus(AppState.BLE_DATA_UPDATE, ValueType.VT_GYRO);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    /* 地�気 */
    if (UUID_CHARACTERISTIC_MAGM.equals(characteristic.getUuid().toString())) {
        byte[] read_data = characteristic.getValue();
        try {
            JSONObject json = new JSONObject(new String(read_data));
            mMagm[0] = json.getDouble("mx");
            mMagm[1] = json.getDouble("my");
            mMagm[2] = json.getDouble("mz");
            setStatus(AppState.BLE_DATA_UPDATE, ValueType.VT_MAGM);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    /* 気圧 */
    if (UUID_CHARACTERISTIC_AIRP.equals(characteristic.getUuid().toString())) {
        byte[] read_data = characteristic.getValue();
        try {
            JSONObject json = new JSONObject(new String(read_data));
            mAirp = json.getDouble("ap");
            setStatus(AppState.BLE_DATA_UPDATE, ValueType.VT_AIRP);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
Example 64
Project: focus-bluetooth-android-master  File: WorkableService.java View source code
@Override
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
    Debugger.d(TAG, "onCharacteristicChanged() >>>>  characteristic = characteristic");
    if (characteristic.getUuid().equals(ACTUAL_LEVEL)) {
        Debugger.d(TAG, "onCharacteristicChanged() >>>> Actual Level was changed");
        Bundle mBundle = new Bundle();
        Message msg = Message.obtain(mActivityHandler, CHARACTERISTIC_CHANGED);
        mBundle.putString(EXTRA_CHARACTERISTIC, characteristic.getUuid().toString());
        msg.setData(mBundle);
        msg.sendToTarget();
    }
    if (characteristic.getUuid().equals(BATTERY_LEVEL)) {
        Debugger.d(TAG, "onCharacteristicChanged() >>>> Battery Level was changed");
        Bundle mBundle = new Bundle();
        Message msg = Message.obtain(mActivityHandler, CHARACTERISTIC_CHANGED);
        mBundle.putString(EXTRA_CHARACTERISTIC, characteristic.getUuid().toString());
        msg.setData(mBundle);
        msg.sendToTarget();
    // readCharacteristic(characteristic);
    }
}
Example 65
Project: openvidonn-master  File: BluetoothLeService.java View source code
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
    if (status == BluetoothGatt.GATT_SUCCESS) {
        List<BluetoothGattService> gattServices = getSupportedGattServices();
        if (gattServices == null)
            return;
        mGattCharacteristics = new HashMap<String, HashMap<String, BluetoothGattCharacteristic>>();
        // Loops through available GATT Services.
        for (BluetoothGattService gattService : gattServices) {
            List<BluetoothGattCharacteristic> gattCharacteristics = gattService.getCharacteristics();
            HashMap<String, BluetoothGattCharacteristic> charas = new HashMap<String, BluetoothGattCharacteristic>();
            // Loops through available Characteristics.
            for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
                charas.put(gattCharacteristic.getUuid().toString(), gattCharacteristic);
            //Log.e(TAG, charas.toString() + " - Properties: " + gattCharacteristic.getProperties() + "Permissions: "+ gattCharacteristic.getPermissions());
            }
            mGattCharacteristics.put(gattService.getUuid().toString(), charas);
        }
        broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED);
    } else {
        Log.w(TAG, "onServicesDiscovered received: " + status);
    }
}
Example 66
Project: SensorTagAndroidProject-master  File: SensorTagService.java View source code
private void processService() {
    if (!mServiceToSubscribe.isEmpty()) {
        BluetoothGattService service = null;
        try {
            service = mServiceToSubscribe.take();
            UUID uuid = service.getUuid();
            if (uuid.equals(UUID_SERVICE_IR_TEMPERATURE)) {
                // This is the temperature service.
                BluetoothGattCharacteristic temperatureDataCharacteristic = service.getCharacteristic(UUID_CHAR_IR_TEMPERATURE_DATA);
                enableNotificationForService(true, mBluetoothGatt, temperatureDataCharacteristic);
            } else if (uuid.equals(UUID_SERVICE_HUMIDITY)) {
                BluetoothGattCharacteristic humidityDataCharacteristic = service.getCharacteristic(UUID_CHAR_HUMIDITY_DATA);
                enableNotificationForService(true, mBluetoothGatt, humidityDataCharacteristic);
            } else if (uuid.equals(UUID_SERVICE_ACCELEROMETER)) {
                BluetoothGattCharacteristic accelerometerDataCharacteristic = service.getCharacteristic(UUID_CHAR_ACCELEROMETER_DATA);
                enableNotificationForService(true, mBluetoothGatt, accelerometerDataCharacteristic);
            } else if (uuid.equals(UUID_SERVICE_MAGNETOMETER)) {
                BluetoothGattCharacteristic magnetometerDataCharacteristic = service.getCharacteristic(UUID_CHAR_MAGNETOMETER_DATA);
                enableNotificationForService(true, mBluetoothGatt, magnetometerDataCharacteristic);
            } else if (uuid.equals(UUID_SERVICE_GYROSCOPE)) {
                BluetoothGattCharacteristic gyroscopeDataCharacteristic = service.getCharacteristic(UUID_CHAR_GYROSCOPE_DATA);
                enableNotificationForService(true, mBluetoothGatt, gyroscopeDataCharacteristic);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
Example 67
Project: AIRS-master  File: HeartMonitorHandler.java View source code
@Override
public // New services discovered
void onServicesDiscovered(BluetoothGatt gatt, int status) {
    int i, j;
    List<BluetoothGattService> services;
    BluetoothGattService service;
    List<BluetoothGattCharacteristic> characteristics;
    BluetoothGattCharacteristic characteristic;
    if (status == BluetoothGatt.GATT_SUCCESS) {
        Log.e("AIRS", "Finished service discovery");
        // get services now
        services = mBluetoothGatt.getServices();
        // walk through all services
        for (i = 0; i < services.size(); i++) {
            // get current service
            service = services.get(i);
            // get the service characteristics
            characteristics = service.getCharacteristics();
            // go through all characteristics
            for (j = 0; j < characteristics.size(); j++) {
                // get current characteristic
                characteristic = characteristics.get(j);
                // heart rate measurement
                if (UUID_HEART_RATE_MEASUREMENT.equals(characteristic.getUuid())) {
                    // enable notification for heart rate measurements
                    mBluetoothGatt.setCharacteristicNotification(characteristic, true);
                    BluetoothGattDescriptor descriptor = characteristic.getDescriptor(CLIENT_CHARACTERISTIC_CONFIG);
                    descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
                    mBluetoothGatt.writeDescriptor(descriptor);
                    Log.e("AIRS", "Set notification for heart rate changes");
                }
                // battery level
                if (UUID_BATTERY_LEVEL.equals(characteristic.getUuid())) {
                    BluetoothGattService batteryService = mBluetoothGatt.getService(UUID_BATTERY_SERVICE);
                    if (batteryService != null) {
                        battery_characteristic = batteryService.getCharacteristic(UUID_BATTERY_LEVEL);
                        if (battery_characteristic != null)
                            Log.e("AIRS", "Found characteristic for battery_level");
                    }
                }
            }
        }
    }
}
Example 68
Project: bcfindme-master  File: Tools.java View source code
public static JSONArray decodeProperty(int property) {
    JSONArray properties = new JSONArray();
    String strProperty = null;
    if ((strProperty = lookup(property, BluetoothGattCharacteristic.PROPERTY_BROADCAST)) != null) {
        properties.put(strProperty);
    }
    if ((strProperty = lookup(property, BluetoothGattCharacteristic.PROPERTY_READ)) != null) {
        properties.put(strProperty);
    }
    if ((strProperty = lookup(property, BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE)) != null) {
        properties.put(strProperty);
    }
    if ((strProperty = lookup(property, BluetoothGattCharacteristic.PROPERTY_WRITE)) != null) {
        properties.put(strProperty);
    }
    if ((strProperty = lookup(property, BluetoothGattCharacteristic.PROPERTY_NOTIFY)) != null) {
        properties.put(strProperty);
    }
    if ((strProperty = lookup(property, BluetoothGattCharacteristic.PROPERTY_INDICATE)) != null) {
        properties.put(strProperty);
    }
    if ((strProperty = lookup(property, BluetoothGattCharacteristic.PROPERTY_SIGNED_WRITE)) != null) {
        properties.put(strProperty);
    }
    if ((strProperty = lookup(property, BluetoothGattCharacteristic.PROPERTY_EXTENDED_PROPS)) != null) {
        properties.put(strProperty);
    }
    return properties;
}
Example 69
Project: bcibeacon-master  File: Tools.java View source code
public static JSONArray decodeProperty(int property) {
    JSONArray properties = new JSONArray();
    String strProperty = null;
    if ((strProperty = lookup(property, BluetoothGattCharacteristic.PROPERTY_BROADCAST)) != null) {
        properties.put(strProperty);
    }
    if ((strProperty = lookup(property, BluetoothGattCharacteristic.PROPERTY_READ)) != null) {
        properties.put(strProperty);
    }
    if ((strProperty = lookup(property, BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE)) != null) {
        properties.put(strProperty);
    }
    if ((strProperty = lookup(property, BluetoothGattCharacteristic.PROPERTY_WRITE)) != null) {
        properties.put(strProperty);
    }
    if ((strProperty = lookup(property, BluetoothGattCharacteristic.PROPERTY_NOTIFY)) != null) {
        properties.put(strProperty);
    }
    if ((strProperty = lookup(property, BluetoothGattCharacteristic.PROPERTY_INDICATE)) != null) {
        properties.put(strProperty);
    }
    if ((strProperty = lookup(property, BluetoothGattCharacteristic.PROPERTY_SIGNED_WRITE)) != null) {
        properties.put(strProperty);
    }
    if ((strProperty = lookup(property, BluetoothGattCharacteristic.PROPERTY_EXTENDED_PROPS)) != null) {
        properties.put(strProperty);
    }
    return properties;
}
Example 70
Project: bcsocket-master  File: Tools.java View source code
public static JSONArray decodeProperty(int property) {
    JSONArray properties = new JSONArray();
    String strProperty = null;
    if ((strProperty = lookup(property, BluetoothGattCharacteristic.PROPERTY_BROADCAST)) != null) {
        properties.put(strProperty);
    }
    if ((strProperty = lookup(property, BluetoothGattCharacteristic.PROPERTY_READ)) != null) {
        properties.put(strProperty);
    }
    if ((strProperty = lookup(property, BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE)) != null) {
        properties.put(strProperty);
    }
    if ((strProperty = lookup(property, BluetoothGattCharacteristic.PROPERTY_WRITE)) != null) {
        properties.put(strProperty);
    }
    if ((strProperty = lookup(property, BluetoothGattCharacteristic.PROPERTY_NOTIFY)) != null) {
        properties.put(strProperty);
    }
    if ((strProperty = lookup(property, BluetoothGattCharacteristic.PROPERTY_INDICATE)) != null) {
        properties.put(strProperty);
    }
    if ((strProperty = lookup(property, BluetoothGattCharacteristic.PROPERTY_SIGNED_WRITE)) != null) {
        properties.put(strProperty);
    }
    if ((strProperty = lookup(property, BluetoothGattCharacteristic.PROPERTY_EXTENDED_PROPS)) != null) {
        properties.put(strProperty);
    }
    return properties;
}
Example 71
Project: bcsphere-core-dev-master  File: Tools.java View source code
public static JSONArray decodeProperty(int property) {
    JSONArray properties = new JSONArray();
    String strProperty = null;
    if ((strProperty = lookup(property, BluetoothGattCharacteristic.PROPERTY_BROADCAST)) != null) {
        properties.put(strProperty);
    }
    if ((strProperty = lookup(property, BluetoothGattCharacteristic.PROPERTY_READ)) != null) {
        properties.put(strProperty);
    }
    if ((strProperty = lookup(property, BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE)) != null) {
        properties.put(strProperty);
    }
    if ((strProperty = lookup(property, BluetoothGattCharacteristic.PROPERTY_WRITE)) != null) {
        properties.put(strProperty);
    }
    if ((strProperty = lookup(property, BluetoothGattCharacteristic.PROPERTY_NOTIFY)) != null) {
        properties.put(strProperty);
    }
    if ((strProperty = lookup(property, BluetoothGattCharacteristic.PROPERTY_INDICATE)) != null) {
        properties.put(strProperty);
    }
    if ((strProperty = lookup(property, BluetoothGattCharacteristic.PROPERTY_SIGNED_WRITE)) != null) {
        properties.put(strProperty);
    }
    if ((strProperty = lookup(property, BluetoothGattCharacteristic.PROPERTY_EXTENDED_PROPS)) != null) {
        properties.put(strProperty);
    }
    return properties;
}
Example 72
Project: bctakepicture-master  File: Tools.java View source code
public static JSONArray decodeProperty(int property) {
    JSONArray properties = new JSONArray();
    String strProperty = null;
    if ((strProperty = lookup(property, BluetoothGattCharacteristic.PROPERTY_BROADCAST)) != null) {
        properties.put(strProperty);
    }
    if ((strProperty = lookup(property, BluetoothGattCharacteristic.PROPERTY_READ)) != null) {
        properties.put(strProperty);
    }
    if ((strProperty = lookup(property, BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE)) != null) {
        properties.put(strProperty);
    }
    if ((strProperty = lookup(property, BluetoothGattCharacteristic.PROPERTY_WRITE)) != null) {
        properties.put(strProperty);
    }
    if ((strProperty = lookup(property, BluetoothGattCharacteristic.PROPERTY_NOTIFY)) != null) {
        properties.put(strProperty);
    }
    if ((strProperty = lookup(property, BluetoothGattCharacteristic.PROPERTY_INDICATE)) != null) {
        properties.put(strProperty);
    }
    if ((strProperty = lookup(property, BluetoothGattCharacteristic.PROPERTY_SIGNED_WRITE)) != null) {
        properties.put(strProperty);
    }
    if ((strProperty = lookup(property, BluetoothGattCharacteristic.PROPERTY_EXTENDED_PROPS)) != null) {
        properties.put(strProperty);
    }
    return properties;
}
Example 73
Project: nativeapps-master  File: Tools.java View source code
public static JSONArray decodeProperty(int property) {
    JSONArray properties = new JSONArray();
    String strProperty = null;
    if ((strProperty = lookup(property, BluetoothGattCharacteristic.PROPERTY_BROADCAST)) != null) {
        properties.put(strProperty);
    }
    if ((strProperty = lookup(property, BluetoothGattCharacteristic.PROPERTY_READ)) != null) {
        properties.put(strProperty);
    }
    if ((strProperty = lookup(property, BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE)) != null) {
        properties.put(strProperty);
    }
    if ((strProperty = lookup(property, BluetoothGattCharacteristic.PROPERTY_WRITE)) != null) {
        properties.put(strProperty);
    }
    if ((strProperty = lookup(property, BluetoothGattCharacteristic.PROPERTY_NOTIFY)) != null) {
        properties.put(strProperty);
    }
    if ((strProperty = lookup(property, BluetoothGattCharacteristic.PROPERTY_INDICATE)) != null) {
        properties.put(strProperty);
    }
    if ((strProperty = lookup(property, BluetoothGattCharacteristic.PROPERTY_SIGNED_WRITE)) != null) {
        properties.put(strProperty);
    }
    if ((strProperty = lookup(property, BluetoothGattCharacteristic.PROPERTY_EXTENDED_PROPS)) != null) {
        properties.put(strProperty);
    }
    return properties;
}
Example 74
Project: OpenFit-master  File: BluetoothLeService.java View source code
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
    Log.d(LOG_TAG, "onServicesDiscovered: " + status);
    if (status == BluetoothGatt.GATT_SUCCESS) {
        // loops through available GATT Services.
        for (BluetoothGattService gattService : gatt.getServices()) {
            String uuid = gattService.getUuid().toString();
            String type = gattServiceType[gattService.getType()];
            Log.d(LOG_TAG, "onServicesDiscovered type: " + type);
            Log.d(LOG_TAG, "onServicesDiscovered uuid: " + uuid);
            //Log.d(LOG_TAG, "onServicesDiscovered: getCharacteristic: "+mWriteCharacteristic);
            for (BluetoothGattCharacteristic gattCharacteristic : gattService.getCharacteristics()) {
                String cUuid = gattCharacteristic.getUuid().toString();
                int cInstanceId = gattCharacteristic.getInstanceId();
                int cPermissions = gattCharacteristic.getPermissions();
                int cProperties = gattCharacteristic.getProperties();
                byte[] cValue = gattCharacteristic.getValue();
                int cWriteType = gattCharacteristic.getWriteType();
                Log.d(LOG_TAG, "onServicesDiscovered cUuid: " + cUuid);
                Log.d(LOG_TAG, "onServicesDiscovered cInstanceId: " + cInstanceId);
                Log.d(LOG_TAG, "onServicesDiscovered cPermissions: " + cPermissions);
                Log.d(LOG_TAG, "onServicesDiscovered cProperties: " + cProperties);
                Log.d(LOG_TAG, "onServicesDiscovered cValue: " + cValue);
                Log.d(LOG_TAG, "onServicesDiscovered cWriteType: " + cWriteType);
            }
        }
        Log.d(LOG_TAG, "BluetoothLe Service discovered: " + status);
        broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED);
    } else {
        Log.d(LOG_TAG, "BluetoothLe onServicesDiscovered received: " + status);
    }
}
Example 75
Project: MariPoSa-master  File: DisplayMessageActivity.java View source code
/**
     * Add the initial base service to the gatt server (required to show up as advertisement)
     */
private void addServiceToGattServer() {
    serviceOneCharUuid = UUID.randomUUID().toString();
    BluetoothGattService firstService = new BluetoothGattService(UUID.fromString(SERVICE_UUID_1), BluetoothGattService.SERVICE_TYPE_PRIMARY);
    // alert level char.
    BluetoothGattCharacteristic firstServiceChar = new BluetoothGattCharacteristic(UUID.fromString(serviceOneCharUuid), BluetoothGattCharacteristic.PROPERTY_READ | BluetoothGattCharacteristic.PROPERTY_WRITE, BluetoothGattCharacteristic.PERMISSION_READ | BluetoothGattCharacteristic.PERMISSION_WRITE);
    firstService.addCharacteristic(firstServiceChar);
    ble.addService(firstService);
}
Example 76
Project: android_packages_apps_Bluetooth-master  File: GattService.java View source code
boolean permissionCheck(int connId, int handle) {
    List<BluetoothGattService> db = gattClientDatabases.get(connId);
    if (db == null)
        return true;
    for (BluetoothGattService service : db) {
        for (BluetoothGattCharacteristic characteristic : service.getCharacteristics()) {
            if (handle == characteristic.getInstanceId()) {
                if ((isRestrictedCharUuid(characteristic.getUuid()) || isRestrictedSrvcUuid(service.getUuid())) && (0 != checkCallingOrSelfPermission(BLUETOOTH_PRIVILEGED)))
                    return false;
                else
                    return true;
            }
            for (BluetoothGattDescriptor descriptor : characteristic.getDescriptors()) {
                if (handle == descriptor.getInstanceId()) {
                    if ((isRestrictedCharUuid(characteristic.getUuid()) || isRestrictedSrvcUuid(service.getUuid())) && (0 != checkCallingOrSelfPermission(BLUETOOTH_PRIVILEGED)))
                        return false;
                    else
                        return true;
                }
            }
        }
    }
    return true;
}
Example 77
Project: Android-BleEventAdapter-master  File: CharacteristicChangedEvent.java View source code
public BluetoothGattCharacteristic getCharacteristic() {
    return mCharacteristic;
}
Example 78
Project: arduino-android-blueprints-master  File: PulseActivity.java View source code
// Called when a remote characteristic changes (like the RX characteristic).
@Override
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
    super.onCharacteristicChanged(gatt, characteristic);
    writeSensorData(characteristic.getStringValue(0));
}
Example 79
Project: BTLETest-master  File: MainActivity.java View source code
// Called when a remote characteristic changes (like the RX characteristic).
@Override
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
    super.onCharacteristicChanged(gatt, characteristic);
    writeLine("Received: " + characteristic.getStringValue(0));
}
Example 80
Project: assertj-android-master  File: Assertions.java View source code
public static org.assertj.android.api.bluetooth.BluetoothGattCharacteristicAssert assertThat(android.bluetooth.BluetoothGattCharacteristic actual) {
    return new org.assertj.android.api.bluetooth.BluetoothGattCharacteristicAssert(actual);
}