Java Code Examples for android.bluetooth.BluetoothGattService

The following are top voted examples for showing how to use android.bluetooth.BluetoothGattService. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: Sense-Hub-Android-Things   File: MiFloraSensorEntity.java   Source Code and License 11 votes vote down vote up
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
    if(status == BluetoothGatt.GATT_SUCCESS){
        for(BluetoothGattService service : gatt.getServices()){
            Log.d(mTAG, "service: " + service.getUuid().toString());
        }
        //Log.d(mTAG, "mGattMiFloraService: " + UUID_MI_FLORA_SERVICE_ID.toString());
        mGattMiFloraService = gatt.getService(UUID_MI_FLORA_SERVICE_ID);
        if(mGattMiFloraService != null){
            boolean rs = gatt.readCharacteristic(mGattMiFloraService.getCharacteristic(UUID_MI_FLORA_FIRMWARE));
            if(!rs){
                Log.i(mTAG, "Can't read mGattMiFloraFwCharacteristic");
            }
        }
    }
    else{
        gatt.close();
        mIsConnecting = false;
    }
}
 
Example 2
Project: ITagAntiLost   File: BleService.java   Source Code and License 8 votes vote down vote up
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
  for (BluetoothGattService service : gatt.getServices()) {
    if (IMMEDIATE_ALERT_SERVICE.equals(service.getUuid())) {
      BlePair pair = bluetoothGatt.get(gatt.getDevice().getAddress());
      if (pair != null) {
        pair.alertCharacteristic = getCharacteristic(
            gatt,
            IMMEDIATE_ALERT_SERVICE,
            ALERT_LEVEL_CHARACTERISTIC
        );
        gatt.readCharacteristic(pair.alertCharacteristic);
      }
    }

    if (FIND_ME_SERVICE.equals(service.getUuid())) {
      if (!service.getCharacteristics().isEmpty()) {
        buttonCharacteristic = service.getCharacteristics().get(0);
        setCharacteristicNotification(gatt, buttonCharacteristic, true);
      }
    }
  }
}
 
Example 3
Project: DailyStudy   File: BleActivity.java   Source Code and License 7 votes vote down vote up
/**
 * Callback invoked when the list of remote services, characteristics and descriptors for the remote device have been updated, ie new services have been discovered.
 *
 * @param gatt 返回的是本次连接的gatt对象
 * @param status
 */
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
    Log.d(Tag, "onServicesDiscovered status" + status);
    mServiceList = gatt.getServices();
    if (mServiceList != null) {
        System.out.println(mServiceList);
        System.out.println("Services num:" + mServiceList.size());
    }

    for (BluetoothGattService service : mServiceList){
        List<BluetoothGattCharacteristic> characteristics = service.getCharacteristics();
        System.out.println("扫描到Service:" + service.getUuid());

        for (BluetoothGattCharacteristic characteristic : characteristics) {
            System.out.println("characteristic: " + characteristic.getUuid() );
        }
    }
}
 
Example 4
Project: mDL-ILP   File: GattClient.java   Source Code and License 6 votes vote down vote up
private synchronized void discoverServices() throws InterruptedException {
    if (VDBG) { Log.d(TAG, "discoverServices: [CMD]"); }
    while (lastMessage != MESSAGE_SERVICES_DISCOVERED) {
        mBtGatt.discoverServices();
        wait(1000);
    }
    if (VDBG) {
        Log.d(TAG, "discoverServices: [DONE] ");
        for (BluetoothGattService s : mBtGatt.getServices()) {
            Log.d(TAG, "discoverServices: found " + s.getUuid());
            for (BluetoothGattCharacteristic c : s.getCharacteristics()) {
                Log.d(TAG, "--> characteristic: " + c.getUuid() + ":" + String.format("%x", c.getInstanceId()));
            }
        }
    }
    lastMessage = -1;
}
 
Example 5
Project: mi-band-2   File: BLEMiBand2Helper.java   Source Code and License 6 votes vote down vote up
public void getNotifications(UUID service, UUID Characteristics) {
    if (!isConnectedToGatt || myGatBand == null) {
        Log.d(TAG, "Cant get notifications from BLE, not initialized.");
        return;
    }

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

        BluetoothGattCharacteristic myGatChar
                = myGatService.getCharacteristic(Characteristics/*Consts.UUID_BUTTON_TOUCH*/);
        if (myGatChar != null) {
            Log.d(TAG, "* Statring listening");

            // second parametes is for starting\stopping the listener.
            boolean status =  myGatBand.setCharacteristicNotification(myGatChar, true);
            Log.d(TAG, "* Set notification status :" + status);
        }
    }
}
 
Example 6
Project: Make-A-Pede-Android-App   File: BluetoothLeConnection.java   Source Code and License 6 votes vote down vote up
/**
 * Search for the desired GATT characteristics inside the provided list of GATT services.
 *
 * @param gattServices a {@code List<BluetoothGattService>} to search for the characteristics
 *                     within
 */
private void getGattCharacteristics(List<BluetoothGattService> gattServices) {
	if (gattServices == null) return;

	for (BluetoothGattService gattService : gattServices) {
		if(gattService.getCharacteristic(DRIVE_UUID_CURIE) != null) {
			driveCharacteristic = gattService.getCharacteristic(DRIVE_UUID_CURIE);
		} else if(gattService.getCharacteristic(DRIVE_UUID_HC08) != null) {
			driveCharacteristic = gattService.getCharacteristic(DRIVE_UUID_HC08);
		}

		if(gattService.getCharacteristic(HEADING_UUID_CURIE) != null) {
			headingCharacteristic = gattService.getCharacteristic(HEADING_UUID_CURIE);
			bluetoothLeService.setCharacteristicNotification(headingCharacteristic, true);
		}
	}

	if (driveCharacteristic == null) {
		Toast.makeText(context, "Incompatible Device", Toast.LENGTH_LONG).show();
		connectionEventListener.onBluetoothConnectionEvent(BluetoothLeService.ACTION_ERROR);
	}
}
 
Example 7
Project: microbit   File: BLEService.java   Source Code and License 6 votes vote down vote up
/**
 * Enables or disables micro:bit event by given event and enable/disable flag.
 *
 * @param eventService Bluetooth GATT service to be registered.
 * @param enable       Enable or disable.
 * @return True, if successful.
 */
private boolean registerMicroBitEvents(BluetoothGattService eventService, boolean enable) {
    // Read (or register for notify) on (1) to receive events generated by the micro:bit.
    BluetoothGattCharacteristic microbit_requirements = eventService.getCharacteristic(CharacteristicUUIDs
            .ES_MICROBIT_EVENT);
    if(microbit_requirements == null) {
        logi("register_eventsFromMicrobit() :: ES_MICROBIT_EVENT Not found");
        return false;
    }
    BluetoothGattDescriptor microbit_requirementsDescriptor = microbit_requirements.getDescriptor(UUIDs
            .CLIENT_DESCRIPTOR);
    if(microbit_requirementsDescriptor == null) {
        logi("register_eventsFromMicrobit() :: CLIENT_DESCRIPTOR Not found");
        return false;
    }

    enableCharacteristicNotification(microbit_requirements, microbit_requirementsDescriptor, enable);
    return true;
}
 
Example 8
Project: mi-band-2   File: BLEMiBand2Helper.java   Source Code and License 6 votes vote down vote up
public void writeData(UUID service, UUID Characteristics,byte[] data) {
    if (!isConnectedToGatt || myGatBand == null) {
        Log.d(TAG, "Cant read from BLE, not initialized.");
        return;
    }

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

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

            boolean status =  myGatBand.writeCharacteristic(myGatChar);
            Log.d(TAG, "* Writting trigger status :" + status);
        }
    }
}
 
Example 9
Project: UDOOBluLib-android   File: UdooBluManager.java   Source Code and License 6 votes vote down vote up
private void writeLed(String address, int color, byte func) {
    BluetoothGattService serv = null;
    BluetoothGattCharacteristic charac = null;
    serv = mUdooBluService.getService(address, UDOOBLE.UUID_LED_SERV);
    if (serv != null) {
        switch (color) {
            case Constant.GREEN_LED:
                charac = serv.getCharacteristic(UDOOBLE.UUID_LED_GREEN);
                break;
            case Constant.YELLOW_LED:
                charac = serv.getCharacteristic(UDOOBLE.UUID_LED_YELLOW);
                break;
            case Constant.RED_LED:
                charac = serv.getCharacteristic(UDOOBLE.UUID_LED_RED);
                break;
        }

        byte[] msg = new byte[2];
        msg[0] = func;
        msg[1] = (byte) 0x03;

        mUdooBluService.writeCharacteristic(address, charac, msg);
    }
}
 
Example 10
Project: react-native-blue-manager   File: Peripheral.java   Source Code and License 6 votes vote down vote up
public void read(UUID serviceUUID, UUID characteristicUUID, Callback callback) {

		if (gatt == null) {
			callback.invoke("BluetoothGatt is null", null);
			return;
		}

		BluetoothGattService service = gatt.getService(serviceUUID);
		BluetoothGattCharacteristic characteristic = findReadableCharacteristic(service, characteristicUUID);

		if (characteristic == null) {
			callback.invoke("Characteristic " + characteristicUUID + " not found.", null);
		} else {
			readCallback = callback;
			if (!gatt.readCharacteristic(characteristic)) {
				readCallback = null;
				callback.invoke("Read failed", null);
			}
		}
	}
 
Example 11
Project: UDOOBluLib-android   File: UdooBluManager.java   Source Code and License 6 votes vote down vote up
private void detectSensors(String address, IReaderListener<byte[]> readerListener) {
    if (isBluManagerReady) {
        UUID servUuid = UDOOBLE.UUID_SENSORS_SERV;
        UUID dataUuid = UDOOBLE.UUID_SENSOR_DATA;

        BluetoothGattService serv = mUdooBluService.getService(address, servUuid);

        if (serv != null) {
            BluetoothGattCharacteristic charac = serv.getCharacteristic(dataUuid);

            mUdooBluService.readCharacteristic(address, charac);
            mIReaderListenerMap.put(address + charac.getUuid().toString(), readerListener);
        } else {
            if (readerListener != null)
                readerListener.onError(new UdooBluException(UdooBluException.BLU_SENSOR_NOT_FOUND));
        }

    } else {
        if (BuildConfig.DEBUG)
            Log.i(TAG, "BluManager not ready");

        if (readerListener != null)
            readerListener.onError(new UdooBluException(UdooBluException.BLU_SERVICE_NOT_READY));
    }
}
 
Example 12
Project: microbit   File: BLEService.java   Source Code and License 6 votes vote down vote up
private void writeCharacteristic(String serviceGuid, String characteristic, int value, int type) {
    if(!isConnected()) {
        logi("writeCharacteristic() :: Not connected. Returning");
        return;
    }

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

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

    c.setValue(value, type, 0);
    int ret = writeCharacteristic(c);
    logi("writeCharacteristic() :: returns - " + ret);
}
 
Example 13
Project: UDOOBluLib-android   File: UdooBluManager.java   Source Code and License 6 votes vote down vote up
public void readFirmwareVersion(final String address, final IReaderListener<byte[]> readerListener) {
    addOperation(new Callable<Void>() {
        @Override
        public Void call() throws Exception {
            if (isBluManagerReady) {
                UUID servUuid = TIUUID.UUID_DEVINFO_SERV;
                UUID dataUuid = TIUUID.UUID_DEVINFO_FWREV;
                BluetoothGattService serv = mUdooBluService.getService(address, servUuid);

                if (serv != null) {
                    BluetoothGattCharacteristic charac = serv.getCharacteristic(dataUuid);
                    mUdooBluService.readCharacteristic(address, charac);
                    mIReaderListenerMap.put(address + charac.getUuid().toString(), readerListener);
                } else {
                    if (readerListener != null)
                        readerListener.onError(new UdooBluException(UdooBluException.BLU_GATT_SERVICE_NOT_FOUND));
                }
            }
            return null;
        }
    });
}
 
Example 14
Project: Android-DFU-App   File: UARTManager.java   Source Code and License 6 votes vote down vote up
@Override
public boolean isRequiredServiceSupported(final BluetoothGatt gatt) {
	final BluetoothGattService service = gatt.getService(UART_SERVICE_UUID);
	if (service != null) {
		mRXCharacteristic = service.getCharacteristic(UART_RX_CHARACTERISTIC_UUID);
		mTXCharacteristic = service.getCharacteristic(UART_TX_CHARACTERISTIC_UUID);
	}

	boolean writeRequest = false;
	boolean writeCommand = false;
	if (mRXCharacteristic != null) {
		final int rxProperties = mRXCharacteristic.getProperties();
		writeRequest = (rxProperties & BluetoothGattCharacteristic.PROPERTY_WRITE) > 0;
		writeCommand = (rxProperties & BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE) > 0;

		// Set the WRITE REQUEST type when the characteristic supports it. This will allow to send long write (also if the characteristic support it).
		// In case there is no WRITE REQUEST property, this manager will divide texts longer then 20 bytes into up to 20 bytes chunks.
		if (writeRequest)
			mRXCharacteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT);
	}

	return mRXCharacteristic != null && mTXCharacteristic != null && (writeRequest || writeCommand);
}
 
Example 15
Project: UDOOBluLib-android   File: UdooBluManager.java   Source Code and License 6 votes vote down vote up
private void setNotification(final String address, final UDOOBLESensor udoobleSensor, final INotificationListener<byte[]> iNotificationListener) {
    if (isBluManagerReady) {
        addOperation(new Callable<Void>() {
            @Override
            public Void call() throws Exception {
                UUID servUuid = udoobleSensor.getService();
                UUID dataUuid = udoobleSensor.getData();
                BluetoothGattService serv = mUdooBluService.getService(address, servUuid);

                if (serv != null) {
                    BluetoothGattCharacteristic charac = serv.getCharacteristic(dataUuid);
                    mINotificationListenerMap.put(address + charac.getUuid().toString(), iNotificationListener);
                    mUdooBluService.setCharacteristicNotification(address, charac, true);
                    Log.i(TAG, "setNotification: ");
                } else if (iNotificationListener != null)
                    iNotificationListener.onError(new UdooBluException(UdooBluException.BLU_GATT_SERVICE_NOT_FOUND));
                return null;
            }
        });
    } else if (BuildConfig.DEBUG)
        Log.i(TAG, "BluManager not ready");
}
 
Example 16
Project: Android-DFU-App   File: BleManager.java   Source Code and License 6 votes vote down vote up
/**
 * When the device is bonded and has the Generic Attribute service and the Service Changed characteristic this method enables indications on this characteristic.
 * In case one of the requirements is not fulfilled this method returns <code>false</code>.
 *
 * @param gatt the gatt device with services discovered
 * @return <code>true</code> when the request has been sent, <code>false</code> when the device is not bonded, does not have the Generic Attribute service, the GA service does not have
 * the Service Changed characteristic or this characteristic does not have the CCCD.
 */
private boolean ensureServiceChangedEnabled(final BluetoothGatt gatt) {
	if (gatt == null)
		return false;

	// The Service Changed indications have sense only on bonded devices
	final BluetoothDevice device = gatt.getDevice();
	if (device.getBondState() != BluetoothDevice.BOND_BONDED)
		return false;

	final BluetoothGattService gaService = gatt.getService(GENERIC_ATTRIBUTE_SERVICE);
	if (gaService == null)
		return false;

	final BluetoothGattCharacteristic scCharacteristic = gaService.getCharacteristic(SERVICE_CHANGED_CHARACTERISTIC);
	if (scCharacteristic == null)
		return false;

	return enableIndications(scCharacteristic);
}
 
Example 17
Project: Android-DFU-App   File: BleManager.java   Source Code and License 6 votes vote down vote up
/**
 * When the device is bonded and has the Generic Attribute service and the Service Changed characteristic this method enables indications on this characteristic.
 * In case one of the requirements is not fulfilled this method returns <code>false</code>.
 *
 * @param gatt the gatt device with services discovered
 * @return <code>true</code> when the request has been sent, <code>false</code> when the device is not bonded, does not have the Generic Attribute service, the GA service does not have
 * the Service Changed characteristic or this characteristic does not have the CCCD.
 */
private boolean ensureServiceChangedEnabled(final BluetoothGatt gatt) {
	if (gatt == null)
		return false;

	// The Service Changed indications have sense only on bonded devices
	final BluetoothDevice device = gatt.getDevice();
	if (device.getBondState() != BluetoothDevice.BOND_BONDED)
		return false;

	final BluetoothGattService gaService = gatt.getService(GENERIC_ATTRIBUTE_SERVICE);
	if (gaService == null)
		return false;

	final BluetoothGattCharacteristic scCharacteristic = gaService.getCharacteristic(SERVICE_CHANGED_CHARACTERISTIC);
	if (scCharacteristic == null)
		return false;

	Logger.i(mLogSession, "Service Changed characteristic found on a bonded device");
	return enableIndications(scCharacteristic);
}
 
Example 18
Project: Android-DFU-App   File: BleManager.java   Source Code and License 6 votes vote down vote up
/**
 * Reads the battery level from the device.
 *
 * @return true if request has been sent
 */
public final boolean readBatteryLevel() {
	final BluetoothGatt gatt = mBluetoothGatt;
	if (gatt == null)
		return false;

	final BluetoothGattService batteryService = gatt.getService(BATTERY_SERVICE);
	if (batteryService == null)
		return false;

	final BluetoothGattCharacteristic batteryLevelCharacteristic = batteryService.getCharacteristic(BATTERY_LEVEL_CHARACTERISTIC);
	if (batteryLevelCharacteristic == null)
		return false;

	// Check characteristic property
	final int properties = batteryLevelCharacteristic.getProperties();
	if ((properties & BluetoothGattCharacteristic.PROPERTY_READ) == 0) {
		return setBatteryNotifications(true);
	}

	Logger.a(mLogSession, "Reading battery level...");
	return readCharacteristic(batteryLevelCharacteristic);
}
 
Example 19
Project: mDL-ILP   File: GattService.java   Source Code and License 5 votes vote down vote up
public GattService(AbstractLicenseActivity activity, BluetoothManager bluetoothManager) throws RemoteConnectionException {
    Log.d(TAG, "Create " + this.toString() + " for activity " + activity.toString());
    this.activity = activity;

    gattServer = bluetoothManager.openGattServer(activity, this);
    if (gattServer == null) {
        throw new RemoteConnectionException("Could not create GattServer", false);
    }
    bluetoothGattService = new BluetoothGattService(
            Constants.SERVICE_UUID,
            BluetoothGattService.SERVICE_TYPE_PRIMARY
    );
    bluetoothGattService.addCharacteristic(apduCharacteristic);
}
 
Example 20
Project: neatle   File: ReadAllCommand.java   Source Code and License 5 votes vote down vote up
@Override
protected void start(Connection connection, BluetoothGatt gatt) {
    List<BluetoothGattService> services = gatt.getServices();
    for (BluetoothGattService service : services) {
        List<BluetoothGattCharacteristic> characteristics = service.getCharacteristics();
        for (BluetoothGattCharacteristic characteristic : characteristics) {
            int props = characteristic.getProperties();
            if ((props & BluetoothGattCharacteristic.PROPERTY_READ) != 0) {
                queue.add(characteristic);
            }
        }
    }

    readNext(gatt);
}
 
Example 21
Project: microbit   File: BLEService.java   Source Code and License 5 votes vote down vote up
/**
 * write repeatedly to (4) to register for the events your app wants to see from the micro:bit.
 * e.g. write <1,1> to register for a 'DOWN' event on ButtonA.
 * Any events matching this will then start to be delivered via the MicroBit Event characteristic.
 *
 * @param eventService Bluetooth GATT service.
 * @param enable       Enable or disable.
 */
private void register_AppRequirement(BluetoothGattService eventService, boolean enable) {
    if(!enable) {
        return;
    }

    BluetoothGattCharacteristic app_requirements = eventService.getCharacteristic(CharacteristicUUIDs.ES_CLIENT_REQUIREMENTS);
    if(app_requirements != null) {
        logi("register_AppRequirement() :: found Constants.ES_CLIENT_REQUIREMENTS ");
        /*
        Registering for everything at the moment
        <1,0> which means give me all the events from ButtonA.
        <2,0> which means give me all the events from ButtonB.
        <0,0> which means give me all the events from everything.
        writeCharacteristic(Constants.EVENT_SERVICE.toString(), Constants.ES_CLIENT_REQUIREMENTS.toString(), 0, BluetoothGattCharacteristic.FORMAT_UINT32);
        */
        writeCharacteristic(GattServiceUUIDs.EVENT_SERVICE.toString(), CharacteristicUUIDs.ES_CLIENT_REQUIREMENTS.toString(),
                EventCategories.SAMSUNG_REMOTE_CONTROL_ID, GattFormats.FORMAT_UINT32);
        writeCharacteristic(GattServiceUUIDs.EVENT_SERVICE.toString(), CharacteristicUUIDs.ES_CLIENT_REQUIREMENTS.toString(),
                EventCategories.SAMSUNG_CAMERA_ID, GattFormats.FORMAT_UINT32);
        writeCharacteristic(GattServiceUUIDs.EVENT_SERVICE.toString(), CharacteristicUUIDs.ES_CLIENT_REQUIREMENTS.toString(),
                EventCategories.SAMSUNG_ALERTS_ID, GattFormats.FORMAT_UINT32);
        writeCharacteristic(GattServiceUUIDs.EVENT_SERVICE.toString(), CharacteristicUUIDs.ES_CLIENT_REQUIREMENTS.toString(),
                EventCategories.SAMSUNG_SIGNAL_STRENGTH_ID, GattFormats.FORMAT_UINT32);
        writeCharacteristic(GattServiceUUIDs.EVENT_SERVICE.toString(), CharacteristicUUIDs.ES_CLIENT_REQUIREMENTS.toString(),
                EventCategories.SAMSUNG_DEVICE_INFO_ID, GattFormats.FORMAT_UINT32);
        //writeCharacteristic(GattServiceUUIDs.EVENT_SERVICE.toString(), CharacteristicUUIDs
        //        .ES_CLIENT_REQUIREMENTS.toString(), EventCategories.SAMSUNG_TELEPHONY_ID,
        //        GattFormats.FORMAT_UINT32);
    }
}
 
Example 22
Project: BLE-HID-Peripheral-for-Android   File: HidPeripheral.java   Source Code and License 5 votes vote down vote up
/**
 * Setup Battery Service
 *
 * @return the service
 */
private static BluetoothGattService setUpBatteryService() {
    final BluetoothGattService service = new BluetoothGattService(SERVICE_BATTERY, BluetoothGattService.SERVICE_TYPE_PRIMARY);

    // Battery Level
    final BluetoothGattCharacteristic characteristic = new BluetoothGattCharacteristic(
            CHARACTERISTIC_BATTERY_LEVEL,
            BluetoothGattCharacteristic.PROPERTY_NOTIFY | BluetoothGattCharacteristic.PROPERTY_READ,
            BluetoothGattCharacteristic.PERMISSION_READ_ENCRYPTED);

    final BluetoothGattDescriptor clientCharacteristicConfigurationDescriptor = new BluetoothGattDescriptor(
            DESCRIPTOR_CLIENT_CHARACTERISTIC_CONFIGURATION,
            BluetoothGattDescriptor.PERMISSION_READ | BluetoothGattDescriptor.PERMISSION_WRITE);
    clientCharacteristicConfigurationDescriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
    characteristic.addDescriptor(clientCharacteristicConfigurationDescriptor);

    while (!service.addCharacteristic(characteristic));

    return service;
}
 
Example 23
Project: ITagAntiLost   File: BleService.java   Source Code and License 5 votes vote down vote up
private BluetoothGattCharacteristic getCharacteristic(
    @NonNull BluetoothGatt bluetoothgatt,
    @NonNull UUID serviceUuid,
    @NonNull UUID characteristicUuid
) {
  BluetoothGattService service = bluetoothgatt.getService(serviceUuid);
  if (service != null)
    return service.getCharacteristic(characteristicUuid);
  return null;
}
 
Example 24
Project: bluewatcher   File: LogClientService.java   Source Code and License 5 votes vote down vote up
@Override
public void actionGattServicesDiscovered(Device device) {
	List<BluetoothGattService> services = bleService.getInternalBleService().getSupportedGattServices();
	for (BluetoothGattService service : services) {
		for (BluetoothGattCharacteristic gattCharacteristic : service.getCharacteristics()) {
			Log.i(TAG, "LogClientService - Discovered. Service: " + service.getUuid().toString() + " - Characteristic: " + gattCharacteristic.getUuid().toString());
		}
	}
}
 
Example 25
Project: microbit   File: BLEManager.java   Source Code and License 5 votes vote down vote up
@Nullable
public BluetoothGattService getService(UUID uuid) {
    if(gatt == null) {
        return null;
    }

    if((bleState & BLE_SERVICES_DISCOVERED) != 0) {
        return gatt.getService(uuid);
    }

    return null;
}
 
Example 26
Project: Bluetooth_BLE   File: LiteBleConnector.java   Source Code and License 5 votes vote down vote up
public LiteBleConnector(LiteBluetooth liteBluetooth, BluetoothGattService service,
                        BluetoothGattCharacteristic characteristic, BluetoothGattDescriptor descriptor) {
    this(liteBluetooth);
    this.service = service;
    this.characteristic = characteristic;
    this.descriptor = descriptor;
}
 
Example 27
Project: UDOOBluLib-android   File: UdooBluManager.java   Source Code and License 5 votes vote down vote up
public void setPinAnalogOrPwmIndex(final String address, final IOPin ioPin, final OnBluOperationResult<Boolean> onResultListener) {
    if (isBluManagerReady) {
        addOperation(new Callable<Void>() {
            @Override
            public Void call() throws Exception {
                UUID service, characteristic;
                byte[] msg;

                service = UDOOBLE.UUID_IOPIN_SERV;
                characteristic = UDOOBLE.UUID_IOPIN_PWM_ANALOG_INDEX;

                msg = new byte[1];
                msg[0] = ioPin.getIndexValue();

                BluetoothGattService serv = mUdooBluService.getService(address, service);
                if (serv != null) {
                    BluetoothGattCharacteristic charac = serv.getCharacteristic(characteristic);
                    mOnResultMap.put(address, onResultListener);

                    if (BuildConfig.DEBUG)
                        BitUtility.LogBinValue(msg, false);

                    mUdooBluService.writeCharacteristic(address, charac, msg);
                } else if (onResultListener != null)
                    onResultListener.onError(new UdooBluException(UdooBluException.BLU_GATT_SERVICE_NOT_FOUND));

                return null;
            }
        });
    } else if (onResultListener != null) {
        onResultListener.onError(new UdooBluException(UdooBluException.BLU_SERVICE_NOT_READY));
    }
}
 
Example 28
Project: bluewatcher   File: WatchCtrlService.java   Source Code and License 5 votes vote down vote up
@Override
public void actionGattServicesDiscovered(Device deviceName) {
	if (bleService.getInternalBleService() == null)
		return;
	connectedDevice = deviceName;
	if (!deviceName.isGBA400() && !connectedDevice.isSTB1000())
		return;
	List<BluetoothGattService> services = bleService.getInternalBleService().getSupportedGattServices();
	for (BluetoothGattService service : services) {
		if (service.getUuid().equals(WATCH_FEATURES_SERVICE_UUID)) {
			BluetoothGattCharacteristic characteristic = service.getCharacteristic(FUNCTION_SWITCH_CHARACTERISTIC);
			if (characteristic != null) {
				BluetoothGattDescriptor descriptor = characteristic.getDescriptor(CCC_DESCRIPTOR_UUID);
				descriptor.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
				bleService.getInternalBleService().writeDescriptor(descriptor);
				gattCharacteristic = characteristic;
				gattCharacteristic.setValue(READY_MESSAGE.getBytes());
				gattCharacteristic.setWriteType(2);
				bleService.getInternalBleService().writeCharacteristic(gattCharacteristic);
				clientAvailable = true;
				Log.i(TAG, "WatchCtrlService - Discovered!" + characteristic.getUuid().toString());
				reloadPhoneControlModes();
				break;
			}
		}
	}
}
 
Example 29
Project: Quick-Bluetooth-LE   File: MainActivity.java   Source Code and License 5 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
@Override
public void onServicesDiscovered(List<BluetoothGattService> services) {
	BluetoothGattService service = null;
	for(BluetoothGattService s : services){
		if(s.getUuid().equals(communicationServiceUuid))
			service = s;
	}
	BluetoothGattCharacteristic characteristic = service.getCharacteristic(sliderCharacteristicUuid);
	bleClient.receiveNotifications(characteristic, true);
}
 
Example 30
Project: UDOOBluLib-android   File: UdooBluManager.java   Source Code and License 5 votes vote down vote up
public void readDigital(final String address, final IReaderListener<byte[]> readerListener) {
    if (isBluManagerReady) {
        addOperation(new Callable<Void>() {
            @Override
            public Void call() throws Exception {
                UUID servUuid = UDOOBLE.UUID_IOPIN_SERV;
                UUID dataUuid = UDOOBLE.UUID_IOPIN_DIGITAL_DATA;
                BluetoothGattService serv = mUdooBluService.getService(address, servUuid);

                if (serv != null) {
                    BluetoothGattCharacteristic charac = serv.getCharacteristic(dataUuid);
                    mUdooBluService.readCharacteristic(address, charac);
                    mIReaderListenerMap.put(address + charac.getUuid().toString(), readerListener);
                } else {
                    if (readerListener != null)
                        readerListener.onError(new UdooBluException(UdooBluException.BLU_GATT_SERVICE_NOT_FOUND));
                }
                return null;
            }
        });
    } else {
        if (BuildConfig.DEBUG)
            Log.i(TAG, "BluManager not ready");

        if (readerListener != null)
            readerListener.onError(new UdooBluException(UdooBluException.BLU_SERVICE_NOT_READY));
    }
}
 
Example 31
Project: Quick-Bluetooth-LE   File: BLEServer.java   Source Code and License 5 votes vote down vote up
public boolean setCharacteristicValue(UUID serviceUuid, UUID characteristicUuid, byte[] value, boolean notify){
	BluetoothGattService service = gattServer.getService(serviceUuid);
	if(service == null)
		return false;
	BluetoothGattCharacteristic ch = service.getCharacteristic(characteristicUuid);
	if(ch == null)
		return false;
	boolean rtn = ch.setValue(value);
	if(rtn && notify){
		notifyDevices(ch);
	}
	return rtn;
}
 
Example 32
Project: UDOOBluLib-android   File: UdooBluService.java   Source Code and License 5 votes vote down vote up
/**
 * Retrieves a list of supported GATT services on the connected device with @address.
 * This should be invoked only after {@code BluetoothGatt#discoverServices()} completes
 * successfully.
 *
 * @return A {@code List} of supported services.
 */
public List<BluetoothGattService> getSupportedGattServices(String mac) {
    List<BluetoothGattService> list = new ArrayList<>();

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

    return list;
}
 
Example 33
Project: UDOOBluLib-android   File: UdooBluService.java   Source Code and License 5 votes vote down vote up
public BluetoothGattService getService(String mBleAddress, UUID uuidLedServ) {
    BluetoothGattService gattService = null;
    BluetoothGatt bluetoothGatt = checkAndGetGattItem(mBleAddress);
    if (bluetoothGatt != null) {
        gattService = bluetoothGatt.getService(uuidLedServ);
    }
    return gattService;
}
 
Example 34
Project: Quick-Bluetooth-LE   File: BLEServer.java   Source Code and License 5 votes vote down vote up
public byte[] getCharacteristicValue(UUID serviceUuid, UUID characteristicUuid){
	BluetoothGattService service = gattServer.getService(serviceUuid);
	if(service == null)
		return null;
	BluetoothGattCharacteristic ch = service.getCharacteristic(characteristicUuid);
	if(ch == null)
		return null;
	return ch.getValue();
}
 
Example 35
Project: UDOOBluLib-android   File: UdooBluManager.java   Source Code and License 5 votes vote down vote up
public void readSensor(final String address, final IReaderListener<byte[]> readerListener, final SENSORS sensor, final UDOOBLESensor udoobleSensor) {
    if (isBluManagerReady) {
        addOperation(new Callable<Void>() {
            @Override
            public Void call() throws Exception {

                UUID servUuid = udoobleSensor.getService();
                UUID dataUuid = udoobleSensor.getData();
                BluetoothGattService serv = mUdooBluService.getService(address, servUuid);

                if (serv != null) {
                    BluetoothGattCharacteristic charac = serv.getCharacteristic(dataUuid);
                    mUdooBluService.readCharacteristic(address, charac);
                    mIReaderListenerMap.put(address + charac.getUuid().toString(), readerListener);
                } else {
                    if (readerListener != null)
                        readerListener.onError(new UdooBluException(UdooBluException.BLU_GATT_SERVICE_NOT_FOUND));
                }
                return null;
            }
        });
    } else {
        if (BuildConfig.DEBUG)
            Log.i(TAG, "BluManager not ready");

        if (readerListener != null)
            readerListener.onError(new UdooBluException(UdooBluException.BLU_SERVICE_NOT_READY));
    }
}
 
Example 36
Project: Quick-Bluetooth-LE   File: BLEServer.java   Source Code and License 5 votes vote down vote up
public int getCharacteristicValueInt(UUID serviceUuid, UUID characteristicUuid, int format, int ofst){
	BluetoothGattService service = gattServer.getService(serviceUuid);
	if(service == null)
		return -1;
	BluetoothGattCharacteristic ch = service.getCharacteristic(characteristicUuid);
	if(ch == null)
		return -1;
	return ch.getIntValue(format, ofst);
}
 
Example 37
Project: Quick-Bluetooth-LE   File: BLEServer.java   Source Code and License 5 votes vote down vote up
public String getCharacteristicValueString(UUID serviceUuid, UUID characteristicUuid, int ofst){
	BluetoothGattService service = gattServer.getService(serviceUuid);
	if(service == null)
		return null;
	BluetoothGattCharacteristic ch = service.getCharacteristic(characteristicUuid);
	if(ch == null)
		return null;
	return ch.getStringValue(ofst);
}
 
Example 38
Project: Quick-Bluetooth-LE   File: BLEServer.java   Source Code and License 5 votes vote down vote up
public boolean setDescriptorValue(UUID serviceUuid, UUID characteristicUuid, UUID descriptorUuid, byte[] value){
	BluetoothGattService service = gattServer.getService(serviceUuid);
	if(service == null)
		return false;
	BluetoothGattCharacteristic characteristic = service.getCharacteristic(characteristicUuid);
	if(characteristic == null)
		return false;
	BluetoothGattDescriptor descriptor = characteristic.getDescriptor(descriptorUuid);
	if(descriptor == null)
		return false;
	return descriptor.setValue(value);
}
 
Example 39
Project: Android-DFU-App   File: CSCManager.java   Source Code and License 5 votes vote down vote up
@Override
public boolean isRequiredServiceSupported(final BluetoothGatt gatt) {
	final BluetoothGattService service = gatt.getService(CYCLING_SPEED_AND_CADENCE_SERVICE_UUID);
	if (service != null) {
		mCSCMeasurementCharacteristic = service.getCharacteristic(CSC_MEASUREMENT_CHARACTERISTIC_UUID);
	}
	return mCSCMeasurementCharacteristic != null;
}
 
Example 40
Project: UDOOBluLib-android   File: UdooBluManager.java   Source Code and License 5 votes vote down vote up
private void unSubscribeNotification(final String address, final UDOOBLESensor udoobleSensor, final OnBluOperationResult<Boolean> operationResult) {
    if (isBluManagerReady) {
        addOperation(new Callable<Void>() {
            @Override
            public Void call() throws Exception {
                UUID servUuid = udoobleSensor.getService();
                UUID dataUuid = udoobleSensor.getData();
                BluetoothGattService serv = mUdooBluService.getService(address, servUuid);

                Log.i(TAG, "enableNotifications service " + servUuid.toString() + " is null: " + (serv == null));

                if (serv != null) {
                    BluetoothGattCharacteristic charac = serv.getCharacteristic(dataUuid);
                    String keySearch = address + charac.getUuid().toString();

                    if (mINotificationListenerMap.containsKey(keySearch))
                        mINotificationListenerMap.remove(keySearch);

                    mOnResultMap.put(address, operationResult);
                    mUdooBluService.setCharacteristicNotification(address, charac, false);
                } else if (operationResult != null)
                    operationResult.onError(new UdooBluException(UdooBluException.BLU_GATT_SERVICE_NOT_FOUND));
                return null;
            }
        });
    } else {
        if (BuildConfig.DEBUG)
            Log.i(TAG, "BluManager not ready");

        if (operationResult != null)
            operationResult.onError(new UdooBluException(UdooBluException.BLU_SERVICE_NOT_READY));
    }
}
 
Example 41
Project: mi-band-2   File: BLEMiBand2Helper.java   Source Code and License 5 votes vote down vote up
/**
 * Get notification but also set descriptor to Enable notification. You need to wait couple of
 *      seconds before you could use it (at least in the mi band 2)
 * @param service
 * @param Characteristics
 */
public void getNotificationsWithDescriptor(UUID service, UUID Characteristics, UUID Descriptor) {
    if (!isConnectedToGatt || myGatBand == null) {
        Log.d(TAG, "Cant get notifications from BLE, not initialized.");
        return;
    }

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

        BluetoothGattCharacteristic myGatChar
                = myGatService.getCharacteristic(Characteristics/*Consts.UUID_BUTTON_TOUCH*/);
        if (myGatChar != null) {
            Log.d(TAG, "* Statring listening");

            // second parametes is for starting\stopping the listener.
            boolean status = myGatBand.setCharacteristicNotification(myGatChar, true);
            Log.d(TAG, "* Set notification status :" + status);

            BluetoothGattDescriptor myDescriptor
                    = myGatChar.getDescriptor(Descriptor/*Consts.UUID_DESCRIPTOR_UPDATE_NOTIFICATION*/);
            if (myDescriptor != null) {
                Log.d(TAG, "Writing decriptor: " + Descriptor.toString());
                myDescriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
                status = myGatBand.writeDescriptor(myDescriptor);
                Log.d(TAG, "Writing decriptors result: " + status);
            }
        }
    }
}
 
Example 42
Project: Quick-Bluetooth-LE   File: BLEServer.java   Source Code and License 5 votes vote down vote up
public String getDescriptorValueString(UUID serviceUuid, UUID characteristicUuid, UUID descriptorUuid){
	BluetoothGattService service = gattServer.getService(serviceUuid);
	if(service == null)
		return null;
	BluetoothGattCharacteristic characteristic = service.getCharacteristic(characteristicUuid);
	if(characteristic == null)
		return null;
	BluetoothGattDescriptor descriptor = characteristic.getDescriptor(descriptorUuid);
	if(descriptor == null)
		return null;
	return new String(descriptor.getValue());
}
 
Example 43
Project: Android-DFU-App   File: TemplateManager.java   Source Code and License 5 votes vote down vote up
@Override
protected boolean isRequiredServiceSupported(final BluetoothGatt gatt) {
	final BluetoothGattService service = gatt.getService(SERVICE_UUID);
	if (service != null) {
		mCharacteristic = service.getCharacteristic(MEASUREMENT_CHARACTERISTIC_UUID);
	}
	return mCharacteristic != null;
}
 
Example 44
Project: Quick-Bluetooth-LE   File: BLEClient.java   Source Code and License 5 votes vote down vote up
public boolean setCharacteristicValue(UUID serviceUuid, UUID characteristicUuid, byte[] value){
	if(gattConnection == null)
		return false;
	BluetoothGattService service = gattConnection.getService(serviceUuid);
	if(service == null)
		return false;
	BluetoothGattCharacteristic ch = service.getCharacteristic(characteristicUuid);
	if(ch == null)
		return false;
	ch.setValue(value);
	return gattConnection.writeCharacteristic(ch);
}
 
Example 45
Project: Quick-Bluetooth-LE   File: BLEClient.java   Source Code and License 5 votes vote down vote up
public boolean setCharacteristicValue(UUID serviceUuid, UUID characteristicUuid, String value){
	if(gattConnection == null)
		return false;
	BluetoothGattService service = gattConnection.getService(serviceUuid);
	if(service == null)
		return false;
	BluetoothGattCharacteristic ch = service.getCharacteristic(characteristicUuid);
	if(ch == null)
		return false;
	ch.setValue(value);
	return gattConnection.writeCharacteristic(ch);
}
 
Example 46
Project: neatle   File: DeviceDetails.java   Source Code and License 5 votes vote down vote up
@Override
public void onBindViewHolder(DeviceDetailsAdapter.ViewHolder holder, int position) {
    Object item = items.get(position);
    if (item instanceof BluetoothGattService) {
        BluetoothGattService service = (BluetoothGattService) item;
        holder.setTitle(service.getUuid().toString());
        holder.setSubTitle("service");
    } else if (item instanceof  BluetoothGattCharacteristic) {
        BluetoothGattCharacteristic characteristic = (BluetoothGattCharacteristic) item;
        holder.setTitle(characteristic.getUuid().toString());
        holder.setSubTitle("Data: " + characteristic.getStringValue(0));
    } else {
        holder.setTitle("Unknown");
    }
}
 
Example 47
Project: UDOOBluLib-android   File: UdooBluManager.java   Source Code and License 5 votes vote down vote up
public void enableSensor(final String address, final UDOOBLESensor sensor, final boolean enable,final OnBluOperationResult<Boolean> operationResult) {
    if (isBluManagerReady) {
        addOperation(new Callable<Void>() {
            @Override
            public Void call() throws Exception {
                if (sensor != null) {
                    UUID servUuid = sensor.getService();
                    UUID confUuid = sensor.getConfig();
                    BluetoothGattService serv = null;
                    BluetoothGattCharacteristic charac = null;

                    byte[] value = new byte[1];
                    try {
                        serv = mUdooBluService.getService(address, servUuid);
                        charac = serv.getCharacteristic(confUuid);
                        value[0] = enable ? sensor.getEnableSensorCode()
                                : UDOOBLESensor.DISABLE_SENSOR_CODE;
                        mOnResultMap.put(address, operationResult);
                        mUdooBluService.writeCharacteristic(address, charac, value);
                    } catch (Exception e) {
                        if (operationResult != null)
                            operationResult.onError(new UdooBluException(UdooBluException.BLU_GATT_SERVICE_NOT_FOUND));
                        if (BuildConfig.DEBUG)
                            Log.e(TAG, "error enableSensor(), service uuid: " + servUuid.toString());
                    }
                }
                return null;
            }
        });
    } else if (BuildConfig.DEBUG)
        Log.i(TAG, "BluManager not ready");
}
 
Example 48
Project: Quick-Bluetooth-LE   File: BLEClient.java   Source Code and License 5 votes vote down vote up
public byte[] getCharacteristicValue(UUID serviceUuid, UUID characteristicUuid){
	BluetoothGattService service = gattConnection.getService(serviceUuid);
	if(service == null)
		return null;
	BluetoothGattCharacteristic ch = service.getCharacteristic(characteristicUuid);
	if(ch == null)
		return null;
	return ch.getValue();
}
 
Example 49
Project: Quick-Bluetooth-LE   File: BLEClient.java   Source Code and License 5 votes vote down vote up
public boolean setDescriptorValue(UUID serviceUuid, UUID characteristicUuid, UUID descriptorUuid, byte[] value){
	if(gattConnection == null)
		return false;
	BluetoothGattService service = gattConnection.getService(serviceUuid);
	if(service == null)
		return false;
	BluetoothGattCharacteristic characteristic = service.getCharacteristic(characteristicUuid);
	if(characteristic == null)
		return false;
	BluetoothGattDescriptor descriptor = characteristic.getDescriptor(descriptorUuid);
	if(descriptor == null)
		return false;
	descriptor.setValue(value);
	return gattConnection.writeDescriptor(descriptor);
}
 
Example 50
Project: bluewatcher   File: WatchCtrlService.java   Source Code and License 5 votes vote down vote up
@Override
public BluetoothGattService createService() {
	BluetoothGattService bluetoothgattservice = new BluetoothGattService(WATCH_CTRL_SERVICE_UUID, 0);
	BluetoothGattCharacteristic bluetoothgattcharacteristic = new BluetoothGattCharacteristic(KEY_CONTAINER_CHARACTERISTIC_UUID, 4, 16);
	bluetoothgattcharacteristic.setValue(new byte[0]);
	BluetoothGattCharacteristic bluetoothgattcharacteristic1 = new BluetoothGattCharacteristic(NAME_OF_APP_CHARACTERISTIC_UUID, 2, 3);
	bluetoothgattcharacteristic1.setValue(READY_MESSAGE.getBytes());
	BluetoothGattDescriptor bluetoothgattdescriptor = new BluetoothGattDescriptor(CCC_DESCRIPTOR_UUID, 17);
	bluetoothgattdescriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
	bluetoothgattcharacteristic1.addDescriptor(bluetoothgattdescriptor);
	bluetoothgattservice.addCharacteristic(bluetoothgattcharacteristic);
	bluetoothgattservice.addCharacteristic(bluetoothgattcharacteristic1);
	return bluetoothgattservice;
}
 
Example 51
Project: Quick-Bluetooth-LE   File: BLEClient.java   Source Code and License 5 votes vote down vote up
public BluetoothGattCharacteristic getCharacteristic(UUID serviceUuid, UUID characteristicUuid){
	if(gattConnection == null)
		return null;
	BluetoothGattService service = gattConnection.getService(serviceUuid);
	if(service == null)
		return null;
	return service.getCharacteristic(characteristicUuid);
}
 
Example 52
Project: Quick-Bluetooth-LE   File: BLEClient.java   Source Code and License 5 votes vote down vote up
public BluetoothGattDescriptor getDescriptor(UUID serviceUuid, UUID characteristicUuid, UUID descriptorUuid){
	if(gattConnection == null)
		return null;
	BluetoothGattService service = gattConnection.getService(serviceUuid);
	if(service == null)
		return null;
	BluetoothGattCharacteristic characteristic = service.getCharacteristic(characteristicUuid);
	if(characteristic == null)
		return null;
	return characteristic.getDescriptor(descriptorUuid);
}
 
Example 53
Project: sdc-1-quickstart-android   File: MainActivity.java   Source Code and License 5 votes vote down vote up
/**
 * Callback invoked when the list of remote services, characteristics and descriptors
 * for the remote device have been updated, ie new services have been discovered.
 *
 * @param gatt   GATT client invoked {@link BluetoothGatt#discoverServices}
 * @param status {@link BluetoothGatt#GATT_SUCCESS} if the remote device
 */
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
    super.onServicesDiscovered(gatt, status);

    // boolean indicating whether or not the next step is successful, default is false
    boolean success = false;

    // Check if Service discovery was successful and set the LED color to red if it was
    if (status == BluetoothGatt.GATT_SUCCESS) {
        // Check if the SPIN Service is found
        final BluetoothGattService spinService = gatt.getService(SPIN_SERVICE_UUID);
        if (spinService != null) {
            // Check if the Command Characteristic is found, write the new value and store
            // the result
            final BluetoothGattCharacteristic commandCharacteristic
                    = spinService.getCharacteristic(COMMAND_CHARACTERISTIC_UUID);
            if (commandCharacteristic != null) {
                // Set the value to 0x09FF0000
                commandCharacteristic.setValue(
                        new byte[]{
                                (byte) 0x09,    // commandId = set LED color (9)
                                (byte) 0xFF,    // red      = 0x00 - 0xFF (0 - 255)
                                (byte) 0x00,    // blue     = 0x00 - 0xFF (0 - 255)
                                (byte) 0x00     // green    = 0x00 - 0xFF (0 - 255)
                        }
                );

                success = gatt.writeCharacteristic(commandCharacteristic);
            }
        }
    }

    onStep(gatt, success);
}
 
Example 54
Project: sdc-1-quickstart-android   File: MainActivity.java   Source Code and License 5 votes vote down vote up
/**
 * Callback indicating the result of a descriptor write operation.
 *
 * @param gatt       GATT client invoked {@link BluetoothGatt#writeDescriptor}
 * @param descriptor Descriptor that was writte to the associated
 *                   remote device.
 * @param status     The result of the write operation
 *                   {@link BluetoothGatt#GATT_SUCCESS} if the operation succeeds.
 */
@Override
public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
    super.onDescriptorWrite(gatt, descriptor, status);

    // boolean indicating whether or not the next step is successful, default is false
    boolean success = false;

    // Check if writing descriptor was successful and force the action notification if it
    // was
    if (status == BluetoothGatt.GATT_SUCCESS) {
        // Check if the SPIN Service is found
        final BluetoothGattService spinService = gatt.getService(SPIN_SERVICE_UUID);
        if (spinService != null) {
            // Check if the Command Characteristic is found, write the new value and store
            // the result
            final BluetoothGattCharacteristic commandCharacteristic
                    = spinService.getCharacteristic(COMMAND_CHARACTERISTIC_UUID);
            if (commandCharacteristic != null) {
                // Set the value to 0x0801
                commandCharacteristic.setValue(
                        new byte[]{
                                (byte) 0x08,    // commandId = force action notification (8)
                                (byte) 0x01     // enable = false (0) or true (1)
                        }
                );

                success = gatt.writeCharacteristic(commandCharacteristic);
            }
        }
    }

    onStep(gatt, success);
}
 
Example 55
Project: mi-band-2   File: BLEMiBand2Helper.java   Source Code and License 5 votes vote down vote up
public void readData(UUID service, UUID Characteristics) {
    if (!isConnectedToGatt || myGatBand == null) {
        Log.d(TAG, "Cant read from BLE, not initialized.");
        return;
    }

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

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

            boolean status =  myGatBand.readCharacteristic(myGatChar);
            Log.d(TAG, "* Read status :" + status);
        }
    }
}
 
Example 56
Project: BLE-HID-Peripheral-for-Android   File: HidPeripheral.java   Source Code and License 5 votes vote down vote up
@Override
public void onServiceAdded(final int status, final BluetoothGattService service) {
    super.onServiceAdded(status, service);
    Log.d(TAG, "onServiceAdded status: " + status + ", service: " + service.getUuid());

    if (status != 0) {
        Log.d(TAG, "onServiceAdded Adding Service failed..");
    }
}
 
Example 57
Project: BLE-HID-Peripheral-for-Android   File: HidPeripheral.java   Source Code and License 5 votes vote down vote up
/**
 * Add GATT service to gattServer
 *
 * @param service the service
 */
private void addService(final BluetoothGattService service) {
    assert gattServer != null;
    boolean serviceAdded = false;
    while (!serviceAdded) {
        try {
            serviceAdded = gattServer.addService(service);
        } catch (final Exception e) {
            Log.d(TAG, "Adding Service failed", e);
        }
    }
    Log.d(TAG, "Service: " + service.getUuid() + " added.");
}
 
Example 58
Project: MagicLight-Controller   File: BluetoothLeService.java   Source Code and License 5 votes vote down vote up
/**
 * get Gatt services and save as arrayList
 * @param gattServices
 */
private ArrayList<ArrayList<BluetoothGattCharacteristic>> getGattServices(List<BluetoothGattService> gattServices) {
    // check Gatt service
    if (gattServices == null) return null;

    ArrayList<HashMap<String, String>> gattServiceData = new ArrayList<>();
    ArrayList<ArrayList<HashMap<String, String>>> gattCharacteristicData = new ArrayList<>();
    mGattCharacteristics = new ArrayList<>();

    // loops through available GATT services
    for (BluetoothGattService gattService : gattServices) {
        HashMap<String, String> currentServiceData = new HashMap<>();
        String uuid = gattService.getUuid().toString();
        currentServiceData.put("LIST_NAME", BluetoothGattAttributes.lookup(uuid, getString(R.string.unknown_service)));
        currentServiceData.put("LIST_UUID", uuid);
        gattServiceData.add(currentServiceData);
        ArrayList<HashMap<String, String>> gattCharacteristicGroupData = new ArrayList<>();
        List<BluetoothGattCharacteristic> gattCharacteristics = gattService.getCharacteristics();
        ArrayList<BluetoothGattCharacteristic> charas = new ArrayList<>();

        // loops through available characteristics
        for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
            charas.add(gattCharacteristic);
            HashMap<String, String> currentCharaData = new HashMap<>();
            uuid = gattCharacteristic.getUuid().toString();
            currentCharaData.put("LIST_NAME", BluetoothGattAttributes.lookup(uuid, getString(R.string.unknown_characteristic)));
            currentCharaData.put("LIST_UUID", uuid);
            gattCharacteristicGroupData.add(currentCharaData);
            Log.e(TAG, "LIST_NAME : " + BluetoothGattAttributes.lookup(uuid, getString(R.string.unknown_characteristic)) + ", LIST_UUID : " + uuid);
        }

        mGattCharacteristics.add(charas);
        gattCharacteristicData.add(gattCharacteristicGroupData);
    }
    return mGattCharacteristics;
}
 
Example 59
Project: Android-DFU-App   File: RSCManager.java   Source Code and License 5 votes vote down vote up
@Override
public boolean isRequiredServiceSupported(final BluetoothGatt gatt) {
	final BluetoothGattService service = gatt.getService(RUNNING_SPEED_AND_CADENCE_SERVICE_UUID);
	if (service != null) {
		mRSCMeasurementCharacteristic = service.getCharacteristic(RSC_MEASUREMENT_CHARACTERISTIC_UUID);
	}
	return mRSCMeasurementCharacteristic != null;
}
 
Example 60
Project: Android-DFU-App   File: BleManager.java   Source Code and License 5 votes vote down vote up
/**
 * This method tries to enable notifications on the Battery Level characteristic.
 *
 * @param enable <code>true</code> to enable battery notifications, false to disable
 * @return true if request has been sent
 */
public boolean setBatteryNotifications(final boolean enable) {
	final BluetoothGatt gatt = mBluetoothGatt;
	if (gatt == null) {
		return false;
	}

	final BluetoothGattService batteryService = gatt.getService(BATTERY_SERVICE);
	if (batteryService == null)
		return false;

	final BluetoothGattCharacteristic batteryLevelCharacteristic = batteryService.getCharacteristic(BATTERY_LEVEL_CHARACTERISTIC);
	if (batteryLevelCharacteristic == null)
		return false;

	// Check characteristic property
	final int properties = batteryLevelCharacteristic.getProperties();
	if ((properties & BluetoothGattCharacteristic.PROPERTY_NOTIFY) == 0)
		return false;

	gatt.setCharacteristicNotification(batteryLevelCharacteristic, enable);
	final BluetoothGattDescriptor descriptor = batteryLevelCharacteristic.getDescriptor(CLIENT_CHARACTERISTIC_CONFIG_DESCRIPTOR_UUID);
	if (descriptor != null) {
		if (enable) {
			descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
			Logger.a(mLogSession, "Enabling battery level notifications...");
			Logger.v(mLogSession, "Enabling notifications for " + BATTERY_LEVEL_CHARACTERISTIC);
			Logger.d(mLogSession, "gatt.writeDescriptor(" + CLIENT_CHARACTERISTIC_CONFIG_DESCRIPTOR_UUID + ", value=0x01-00)");
		} else {
			descriptor.setValue(BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE);
			Logger.a(mLogSession, "Disabling battery level notifications...");
			Logger.v(mLogSession, "Disabling notifications for " + BATTERY_LEVEL_CHARACTERISTIC);
			Logger.d(mLogSession, "gatt.writeDescriptor(" + CLIENT_CHARACTERISTIC_CONFIG_DESCRIPTOR_UUID + ", value=0x00-00)");
		}
		return gatt.writeDescriptor(descriptor);
	}
	return false;
}