android.bluetooth.BluetoothGattService Java Examples

The following examples show how to use android.bluetooth.BluetoothGattService. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GattClient.java    From blefun-androidthings with Apache License 2.0 8 votes vote down vote up
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
    if (status == BluetoothGatt.GATT_SUCCESS) {
        boolean connected = false;

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

                BluetoothGattDescriptor descriptor = characteristic.getDescriptor(DESCRIPTOR_CONFIG);
                if (descriptor != null) {
                    descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
                    connected = gatt.writeDescriptor(descriptor);
                }
            }
        }
        mListener.onConnected(connected);
    } else {
        Log.w(TAG, "onServicesDiscovered received: " + status);
    }
}
 
Example #2
Source File: OADProfile.java    From bean-sdk-android with MIT License 6 votes vote down vote up
/**
 * Setup BLOCK and IDENTIFY characteristics
 */
private void setupOAD() {
    BluetoothGattService oadService = mGattClient.getService(Constants.UUID_OAD_SERVICE);
    if (oadService == null) {
        fail(BeanError.MISSING_OAD_SERVICE);
        return;
    }

    oadIdentify = oadService.getCharacteristic(Constants.UUID_OAD_CHAR_IDENTIFY);
    if (oadIdentify == null) {
        fail(BeanError.MISSING_OAD_IDENTIFY);
        return;
    }

    oadBlock = oadService.getCharacteristic(Constants.UUID_OAD_CHAR_BLOCK);
    if (oadBlock == null) {
        fail(BeanError.MISSING_OAD_BLOCK);
        return;
    }
}
 
Example #3
Source File: GattConnection.java    From bitgatt with Mozilla Public License 2.0 6 votes vote down vote up
boolean connectedDeviceHostsService(UUID serviceUuid) {
    if (mockMode) {
        for (BluetoothGattService service : mockServices) {
            if (service.getUuid() != null && service.getUuid().equals(serviceUuid)) {
                return true;
            }
        }
        return false;
    } else {
        // if the device has not had discovery performed, we will not know that the connection
        // is hosting the service
        if (isConnected()) {
            return null != getGatt() && null != getGatt().getService(serviceUuid);
        } else {
            return false;
        }
    }
}
 
Example #4
Source File: BleManager.java    From AsteroidOSSync with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Returns a {@link BleServer} instance. This is now the preferred method to retrieve the server instance.
 */
public final BleServer getServer(final IncomingListener incomingListener, final GattDatabase gattDatabase, final BleServer.ServiceAddListener addServiceListener)
{
	if (m_server == null)
	{
		m_server = new BleServer(this, /*isNull*/false);
		if (gattDatabase != null)
		{
			for (BluetoothGattService service : gattDatabase.getServiceList())
			{
				m_server.addService(service, addServiceListener);
			}
		}
	}
	m_server.setListener_Incoming(incomingListener);
	return m_server;
}
 
Example #5
Source File: TimeProfile.java    From sample-bluetooth-le-gattserver with Apache License 2.0 6 votes vote down vote up
/**
 * Return a configured {@link BluetoothGattService} instance for the
 * Current Time Service.
 */
public static BluetoothGattService createTimeService() {
    BluetoothGattService service = new BluetoothGattService(TIME_SERVICE,
            BluetoothGattService.SERVICE_TYPE_PRIMARY);

    // Current Time characteristic
    BluetoothGattCharacteristic currentTime = new BluetoothGattCharacteristic(CURRENT_TIME,
            //Read-only characteristic, supports notifications
            BluetoothGattCharacteristic.PROPERTY_READ | BluetoothGattCharacteristic.PROPERTY_NOTIFY,
            BluetoothGattCharacteristic.PERMISSION_READ);
    BluetoothGattDescriptor configDescriptor = new BluetoothGattDescriptor(CLIENT_CONFIG,
            //Read/write descriptor
            BluetoothGattDescriptor.PERMISSION_READ | BluetoothGattDescriptor.PERMISSION_WRITE);
    currentTime.addDescriptor(configDescriptor);

    // Local Time Information characteristic
    BluetoothGattCharacteristic localTime = new BluetoothGattCharacteristic(LOCAL_TIME_INFO,
            //Read-only characteristic
            BluetoothGattCharacteristic.PROPERTY_READ,
            BluetoothGattCharacteristic.PERMISSION_READ);

    service.addCharacteristic(currentTime);
    service.addCharacteristic(localTime);

    return service;
}
 
Example #6
Source File: BleManager.java    From Android-nRF-Toolbox with BSD 3-Clause "New" or "Revised" 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>.
 *
 * @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 = bluetoothGatt;
	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 internalEnableIndications(scCharacteristic);
}
 
Example #7
Source File: BTLEDeviceManager.java    From BLEService with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public boolean writeDescriptor(String	address,
  							   UUID		serviceUUID,
  							   UUID		characteristicUUID,
  							   UUID		descriptorUUID,
						   byte[]	value) throws DeviceManagerException, DeviceNameNotFoundException {
BTDeviceInfo deviceInfo = getDeviceInfo(address);
if (deviceInfo == null) {
	throw new DeviceNameNotFoundException(String.format("%s %s", mContext.getString(R.string.device_not_found), address));   		    		
}
BluetoothGattService service = deviceInfo.getGatt().getService(serviceUUID);
if (service == null) {
	throw new DeviceManagerException(String.format("%s %s %s", mContext.getString(R.string.service_not_found), address, serviceUUID));
}
BluetoothGattCharacteristic characteristic = service.getCharacteristic(characteristicUUID);
if (characteristic == null) {
	throw new DeviceManagerException(String.format("%s %s %s", mContext.getString(R.string.characteristic_not_found), address, characteristicUUID));
}
BluetoothGattDescriptor descriptor = characteristic.getDescriptor(descriptorUUID);
if (descriptor == null) {
	throw new DeviceManagerException(String.format("%s %s %s %s", mContext.getString(R.string.descriptor_not_found), address, characteristicUUID, descriptorUUID));
}
return writeDescriptor(deviceInfo, characteristic, descriptor, value);
  }
 
Example #8
Source File: BleService.java    From BleLib with Apache License 2.0 6 votes vote down vote up
/**
     * Reads the value for a given descriptor from the associated remote device.
     *
     * @param serviceUUID        remote device service uuid
     * @param characteristicUUID remote device characteristic uuid
     * @param descriptorUUID     remote device descriptor uuid
     * @return true, if the read operation was initiated successfully
     */
    public boolean readDescriptor(String serviceUUID, String characteristicUUID,
                                  String descriptorUUID) {
        if (mBluetoothGatt == null) {
            Log.w(TAG, "BluetoothGatt is null");
            return false;
        }
//        try {
        BluetoothGattService service =
                mBluetoothGatt.getService(UUID.fromString(serviceUUID));
        BluetoothGattCharacteristic characteristic =
                service.getCharacteristic(UUID.fromString(characteristicUUID));
        BluetoothGattDescriptor descriptor =
                characteristic.getDescriptor(UUID.fromString(descriptorUUID));
        return mBluetoothGatt.readDescriptor(descriptor);
//        } catch (Exception e) {
//            Log.e(TAG, "read descriptor exception", e);
//            return false;
//        }
    }
 
Example #9
Source File: Peripheral.java    From react-native-ble-manager with Apache License 2.0 6 votes vote down vote up
public void read(UUID serviceUUID, UUID characteristicUUID, Callback callback) {

		if (!isConnected()) {
			callback.invoke("Device is not connected", null);
			return;
		}
		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 #10
Source File: PeripheralActivity.java    From BLEService with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void uiCharacteristicsDetails(final BluetoothGatt gatt,
		 					 final BluetoothDevice device,
							 final BluetoothGattService service,
							 final BluetoothGattCharacteristic characteristic)
 {
 	runOnUiThread(new Runnable() {
@Override
public void run() {
	mListType = ListType.GATT_CHARACTERISTIC_DETAILS;
	mListView.setAdapter(mCharDetailsAdapter);
   	mHeaderTitle.setText(BleNamesResolver.resolveCharacteristicName(characteristic.getUuid().toString().toLowerCase(Locale.getDefault())) + "\'s details:");
   	mHeaderBackButton.setVisibility(View.VISIBLE);
   	
   	mCharDetailsAdapter.setCharacteristic(characteristic);
   	mCharDetailsAdapter.notifyDataSetChanged();
}
 	});
 }
 
Example #11
Source File: PA_ServiceManager.java    From SweetBlue with GNU General Public License v3.0 6 votes vote down vote up
public BleDescriptorWrapper getDescriptor(final UUID serviceUuid_nullable, final UUID charUuid_nullable, final UUID descUuid)
{
    if (serviceUuid_nullable == null)
    {
        final List<BluetoothGattService> serviceList = getNativeServiceList_original();

        for (int i = 0; i < serviceList.size(); i++)
        {
            final BleServiceWrapper service_ith = new BleServiceWrapper(serviceList.get(i));
            final BleDescriptorWrapper descriptor = getDescriptor(service_ith, charUuid_nullable, descUuid);

            return descriptor;
        }
    }
    else
    {
        final BleServiceWrapper service = getServiceDirectlyFromNativeNode(serviceUuid_nullable);

        if (service.hasUhOh())
            return new BleDescriptorWrapper(service.getUhOh());
        else
            return getDescriptor(service, charUuid_nullable, descUuid);
    }

    return BleDescriptorWrapper.NULL;
}
 
Example #12
Source File: BleMeshManager.java    From Android-nRF-Mesh-Library with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public boolean isRequiredServiceSupported(@NonNull final BluetoothGatt gatt) {
    final BluetoothGattService meshProxyService = gatt.getService(MESH_PROXY_UUID);
    if (meshProxyService != null) {
        isProvisioningComplete = true;
        mMeshProxyDataInCharacteristic = meshProxyService.getCharacteristic(MESH_PROXY_DATA_IN);
        mMeshProxyDataOutCharacteristic = meshProxyService.getCharacteristic(MESH_PROXY_DATA_OUT);

        return mMeshProxyDataInCharacteristic != null &&
               mMeshProxyDataOutCharacteristic != null &&
               hasNotifyProperty(mMeshProxyDataOutCharacteristic) &&
               hasWriteNoResponseProperty(mMeshProxyDataInCharacteristic);
    }
    final BluetoothGattService meshProvisioningService = gatt.getService(MESH_PROVISIONING_UUID);
    if (meshProvisioningService != null) {
        isProvisioningComplete = false;
        mMeshProvisioningDataInCharacteristic = meshProvisioningService.getCharacteristic(MESH_PROVISIONING_DATA_IN);
        mMeshProvisioningDataOutCharacteristic = meshProvisioningService.getCharacteristic(MESH_PROVISIONING_DATA_OUT);

        return mMeshProvisioningDataInCharacteristic != null &&
               mMeshProvisioningDataOutCharacteristic != null &&
               hasNotifyProperty(mMeshProvisioningDataOutCharacteristic) &&
               hasWriteNoResponseProperty(mMeshProvisioningDataInCharacteristic);
    }
    return false;
}
 
Example #13
Source File: BluetoothPeripheral.java    From blessed-android with MIT License 6 votes vote down vote up
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
    if (status != GATT_SUCCESS) {
        Timber.e("service discovery failed due to internal error '%s', disconnecting", statusToString(status));
        disconnect();
        return;
    }

    final List<BluetoothGattService> services = gatt.getServices();
    Timber.i("discovered %d services for '%s'", services.size(), getName());

    if (listener != null) {
        listener.connected(BluetoothPeripheral.this);
    }

    callbackHandler.post(new Runnable() {
        @Override
        public void run() {
            peripheralCallback.onServicesDiscovered(BluetoothPeripheral.this);
        }
    });
}
 
Example #14
Source File: ProximityServerManager.java    From Android-nRF-Toolbox with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@NonNull
@Override
protected List<BluetoothGattService> initializeServer() {
	final List<BluetoothGattService> services = new ArrayList<>();
	services.add(
			service(ProximityManager.IMMEDIATE_ALERT_SERVICE_UUID,
					characteristic(ProximityManager.ALERT_LEVEL_CHARACTERISTIC_UUID,
							BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE,
							BluetoothGattCharacteristic.PERMISSION_WRITE))
	);
	services.add(
			service(ProximityManager.LINK_LOSS_SERVICE_UUID,
					characteristic(ProximityManager.ALERT_LEVEL_CHARACTERISTIC_UUID,
							BluetoothGattCharacteristic.PROPERTY_WRITE | BluetoothGattCharacteristic.PROPERTY_READ,
							BluetoothGattCharacteristic.PERMISSION_WRITE | BluetoothGattCharacteristic.PERMISSION_READ,
							AlertLevelData.highAlert()))
	);
	return services;
}
 
Example #15
Source File: P_AndroidBleServer.java    From SweetBlue with GNU General Public License v3.0 5 votes vote down vote up
@Override
public final boolean addService(BluetoothGattService service)
{
    if (m_server != null)
    {
        return m_server.addService(service);
    }

    return false;
}
 
Example #16
Source File: DeviceDetails.java    From neatle with MIT License 5 votes vote down vote up
private void updateServices(Connection conn) {
    items.clear();
    for (BluetoothGattService service : conn.getServices()) {
        items.add(service);
        for (BluetoothGattCharacteristic characteristic : service.getCharacteristics()) {
            items.add(characteristic);
        }
    }
    notifyDataSetChanged();
}
 
Example #17
Source File: ServiceDiscoveryManager.java    From RxAndroidBle with Apache License 2.0 5 votes vote down vote up
@NonNull
private static Function<List<BluetoothGattService>, RxBleDeviceServices> wrapIntoRxBleDeviceServices() {
    return new Function<List<BluetoothGattService>, RxBleDeviceServices>() {
        @Override
        public RxBleDeviceServices apply(List<BluetoothGattService> bluetoothGattServices) {
            return new RxBleDeviceServices(bluetoothGattServices);
        }
    };
}
 
Example #18
Source File: CGMManager.java    From Android-nRF-Toolbox with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
protected boolean isRequiredServiceSupported(@NonNull final BluetoothGatt gatt) {
	final BluetoothGattService service = gatt.getService(CGMS_UUID);
	if (service != null) {
		cgmStatusCharacteristic = service.getCharacteristic(CGM_STATUS_UUID);
		cgmFeatureCharacteristic = service.getCharacteristic(CGM_FEATURE_UUID);
		cgmMeasurementCharacteristic = service.getCharacteristic(CGM_MEASUREMENT_UUID);
		cgmSpecificOpsControlPointCharacteristic = service.getCharacteristic(CGM_OPS_CONTROL_POINT_UUID);
		recordAccessControlPointCharacteristic = service.getCharacteristic(RACP_UUID);
	}
	return cgmMeasurementCharacteristic != null
                  && cgmSpecificOpsControlPointCharacteristic != null
                  && recordAccessControlPointCharacteristic != null;
}
 
Example #19
Source File: BPMManager.java    From Android-nRF-Toolbox with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
protected boolean isRequiredServiceSupported(@NonNull final BluetoothGatt gatt) {
	final BluetoothGattService service = gatt.getService(BP_SERVICE_UUID);
	if (service != null) {
		bpmCharacteristic = service.getCharacteristic(BPM_CHARACTERISTIC_UUID);
		icpCharacteristic = service.getCharacteristic(ICP_CHARACTERISTIC_UUID);
	}
	return bpmCharacteristic != null;
}
 
Example #20
Source File: SensorTagHumidityProfile.java    From SensorTag-CC2650 with Apache License 2.0 5 votes vote down vote up
public static boolean isCorrectService(BluetoothGattService service) {
	if ((service.getUuid().toString().compareTo(SensorTagGatt.UUID_HUM_SERV.toString())) == 0) {//service.getUuid().toString().compareTo(SensorTagGatt.UUID_HUM_DATA.toString())) {
		Log.d("Test", "Match !");
		return true;
	}
	else return false;
}
 
Example #21
Source File: P_AndroidBleServer.java    From SweetBlue with GNU General Public License v3.0 5 votes vote down vote up
@Override
public final boolean removeService(BluetoothGattService service)
{
    if (m_server != null)
    {
        return m_server.removeService(service);
    }
    return false;
}
 
Example #22
Source File: DexCollectionService.java    From xDrip with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onCreate() {

    if (scanMeister == null) {
        scanMeister = new ScanMeister()
                .applyKnownWorkarounds()
                .addCallBack(this, TAG);
    }

    foregroundServiceStarter = new ForegroundServiceStarter(getApplicationContext(), this);
    foregroundServiceStarter.start();
    //mContext = getApplicationContext();
    dexCollectionService = this;
    prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    listenForChangeInSettings();
    //bgToSpeech = BgToSpeech.setupTTS(mContext); //keep reference to not being garbage collected
    if (CollectionServiceStarter.isDexBridgeOrWifiandDexBridge()) {
        Log.i(TAG, "onCreate: resetting bridge_battery preference to 0");
        prefs.edit().putInt("bridge_battery", 0).apply();
        //if (Home.get_master()) GcmActivity.sendBridgeBattery(prefs.getInt("bridge_battery",-1));
    }

    cloner.dontClone(
            android.bluetooth.BluetoothDevice.class,
            android.bluetooth.BluetoothGattService.class
    );

    final IntentFilter pairingRequestFilter = new IntentFilter(BluetoothDevice.ACTION_PAIRING_REQUEST);
    pairingRequestFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY - 1);
    registerReceiver(mPairingRequestRecevier, pairingRequestFilter);
    Log.i(TAG, "onCreate: STARTING SERVICE: pin code: " + DEFAULT_BT_PIN);

    Blukon.unBondIfBlukonAtInit();

}
 
Example #23
Source File: BLEComm.java    From AndroidAPS with GNU Affero General Public License v3.0 5 votes vote down vote up
private List<BluetoothGattService> getSupportedGattServices() {
    if (L.isEnabled(L.PUMPBTCOMM))
        log.debug("getSupportedGattServices");
    if ((mBluetoothAdapter == null) || (mBluetoothGatt == null)) {
        log.error("BluetoothAdapter not initialized_ERROR");
        isConnecting = false;
        isConnected = false;
        return null;
    }

    return mBluetoothGatt.getServices();
}
 
Example #24
Source File: SensorTagBarometerProfile.java    From SensorTag-CC2650 with Apache License 2.0 5 votes vote down vote up
public SensorTagBarometerProfile(Context con,BluetoothDevice device,BluetoothGattService service,BluetoothLeService controller) {
	super(con,device,service,controller);
	this.tRow =  new SensorTagBarometerTableRow(con);
	
	List<BluetoothGattCharacteristic> characteristics = this.mBTService.getCharacteristics();
	
	for (BluetoothGattCharacteristic c : characteristics) {
		if (c.getUuid().toString().equals(SensorTagGatt.UUID_BAR_DATA.toString())) {
			this.dataC = c;
		}
		if (c.getUuid().toString().equals(SensorTagGatt.UUID_BAR_CONF.toString())) {
			this.configC = c;
		}
		if (c.getUuid().toString().equals(SensorTagGatt.UUID_BAR_PERI.toString())) {
			this.periodC = c;
		}
		if (c.getUuid().toString().equals(SensorTagGatt.UUID_BAR_CALI.toString())) {
			this.calibC = c;
		}
	}
	if (this.mBTDevice.getName().equals("CC2650 SensorTag")) {
		this.isCalibrated = true;
	}
	else {
		this.isCalibrated = false;
	}
	this.isHeightCalibrated = false;
	this.tRow.sl1.autoScale = true;
	this.tRow.sl1.autoScaleBounceBack = true;
	this.tRow.sl1.setColor(255, 0, 150, 125);
	this.tRow.setIcon(this.getIconPrefix(), this.dataC.getUuid().toString());
	
	this.tRow.title.setText(GattInfo.uuidToName(UUID.fromString(this.dataC.getUuid().toString())));
	this.tRow.uuidLabel.setText(this.dataC.getUuid().toString());
	this.tRow.value.setText("0.0mBar, 0.0m");
	this.tRow.periodBar.setProgress(100);
}
 
Example #25
Source File: BleWrapperUiCallbacks.java    From BLEService with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void uiNewValueForCharacteristic(final BluetoothGatt gatt,
final BluetoothDevice device,
final BluetoothGattService service,
final BluetoothGattCharacteristic ch,
final String strValue,
final int intValue,
final byte[] rawValue,
final String timestamp);
 
Example #26
Source File: DeviceControlActivity.java    From IoT-Firstep with GNU General Public License v3.0 5 votes vote down vote up
/**
   * 获取BLE的特征值
   * @param gattServices
   */
  private void getCharacteristic(List<BluetoothGattService> gattServices) {
      if (gattServices == null) return;
      String uuid = null;

      // Loops through available GATT Services.
      for (BluetoothGattService gattService : gattServices) {
          uuid = gattService.getUuid().toString();
          
          //找uuid为0000ffe0-0000-1000-8000-00805f9b34fb的服务
          if (uuid.equals(C.SERVICE_UUID)) {
          	List<BluetoothGattCharacteristic> gattCharacteristics =
                      gattService.getCharacteristics();
              //找uuid为0000ffe1-0000-1000-8000-00805f9b34fb的特征值
              for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
                  uuid = gattCharacteristic.getUuid().toString();
                  if(uuid.equals(C.CHAR_UUID)){
                  	mCharacteristic = gattCharacteristic;
                  	final int charaProp = gattCharacteristic.getProperties();
              		//开启该特征值的数据的监听
              		if ((charaProp | BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) {
                          mBluetoothLeService.setCharacteristicNotification(
                                  mCharacteristic, true);
                      }
                  	System.out.println("uuid----->" + uuid);
                  }
              }
	}
      }
      
      //如果没找到指定的特征值,直接返回
      if (mCharacteristic == null) {
      	Toast.makeText(DeviceControlActivity.this, "未找到指定特征值", 
      			Toast.LENGTH_LONG).show();
	finish();
}

  }
 
Example #27
Source File: DeviceInfoAdapter.java    From Android-BLE with Apache License 2.0 5 votes vote down vote up
@Override
public void onBindViewHolder(@NonNull ViewHolder viewHolder, int position) {
    BluetoothGattService gattService = gattServices.get(position);
    String uuid = gattService.getUuid().toString();
    viewHolder.tvServiceUuid.setText(Utils.getUuid(uuid));
    viewHolder.tvServiceType.setText(gattService.getType()==BluetoothGattService.SERVICE_TYPE_PRIMARY?"PRIMARY SERVICE":"UNKNOWN SERVICE");

    if (position == opened){
        viewHolder.recyclerView.setVisibility(View.VISIBLE);
    } else {
        viewHolder.recyclerView.setVisibility(View.GONE);
    }

    viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(opened == viewHolder.getAdapterPosition()) {
                //当点击的item已经被展开了, 就关闭.
                opened = -1;
                notifyItemChanged(viewHolder.getAdapterPosition());
            }else {
                int oldOpened = opened;
                opened = viewHolder.getAdapterPosition();
                notifyItemChanged(oldOpened);
                notifyItemChanged(opened);
            }
        }
    });

    ChildAdapter adapter = new ChildAdapter(context, gattService.getCharacteristics());
    viewHolder.recyclerView.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false));
    viewHolder.recyclerView.setAdapter(adapter);

}
 
Example #28
Source File: ACSUtilityService.java    From ESeal with Apache License 2.0 5 votes vote down vote up
private BluetoothGattCharacteristic getACSCharacteristic(UUID charaUUID) {
    if (mBluetoothAdapter == null || mBluetoothGatt == null) {
        Log.w(TAG, "BluetoothAdapter not initialized");
        return null;
    }
    BluetoothGattService service = mBluetoothGatt.getService(ACS_SERVICE_UUID);
    if (service == null) {
        Log.e(TAG, "Service is not found!");
        return null;
    }
    BluetoothGattCharacteristic chara = service.getCharacteristic(charaUUID);
    return chara;
}
 
Example #29
Source File: DeviceControlActivity.java    From IoT-Firstep with GNU General Public License v3.0 5 votes vote down vote up
/**
   * 获取BLE的特征值
   * @param gattServices
   */
  private void getCharacteristic(List<BluetoothGattService> gattServices) {
      if (gattServices == null) return;
      String uuid = null;

      // Loops through available GATT Services.
      for (BluetoothGattService gattService : gattServices) {
          uuid = gattService.getUuid().toString();
          
          //找uuid为0xffe0的服务
          if (uuid.equals(C.SERVICE_UUID)) {
          	List<BluetoothGattCharacteristic> gattCharacteristics =
                      gattService.getCharacteristics();
              //找uuid为0xffe1的特征值
              for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
                  uuid = gattCharacteristic.getUuid().toString();
                  if(uuid.equals(C.CHAR_UUID)){
                  	mCharacteristic = gattCharacteristic;
                  	final int charaProp = gattCharacteristic.getProperties();
              		//开启该特征值的数据的监听
              		if ((charaProp | BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) {
                          mBluetoothLeService.setCharacteristicNotification(
                                  mCharacteristic, true);
                      }
                  	System.out.println("uuid----->" + uuid);
                  }
              }
	}
      }
      
      //如果没找到指定的特征值,直接返回
      if (mCharacteristic == null) {
      	Toast.makeText(DeviceControlActivity.this, "未找到指定特征值", 
      			Toast.LENGTH_LONG).show();
	finish();
}

  }
 
Example #30
Source File: PA_ServiceManager.java    From AsteroidOSSync with GNU General Public License v3.0 5 votes vote down vote up
private List<BluetoothGattDescriptor> collectAllNativeDescriptors(
        final UUID serviceUuid_nullable, final UUID charUuid_nullable, final Object forEach_nullable)
{
    final ArrayList<BluetoothGattDescriptor> toReturn = forEach_nullable == null ? new ArrayList<BluetoothGattDescriptor>() : null;
    final List<BluetoothGattService> serviceList_native = getNativeServiceList_original();

    for (int i = 0; i < serviceList_native.size(); i++)
    {
        final BleServiceWrapper service_ith = new BleServiceWrapper(serviceList_native.get(i));

        if (serviceUuid_nullable == null || !service_ith.isNull() && serviceUuid_nullable.equals(service_ith.getService().getUuid()))
        {
            final List<BluetoothGattCharacteristic> charList_native = getNativeCharacteristicList_original(service_ith);

            for (int j = 0; j < charList_native.size(); j++)
            {
                final BleCharacteristicWrapper char_jth = new BleCharacteristicWrapper(charList_native.get(j));

                if (charUuid_nullable == null || !char_jth.isNull() && charUuid_nullable.equals(char_jth.getCharacteristic().getUuid()))
                {
                    final List<BluetoothGattDescriptor> descriptors = getNativeDescriptorList_original(char_jth);

                    if (forEach_nullable != null)
                    {
                        if (Utils.doForEach_break(forEach_nullable, descriptors))
                        {
                            return P_Const.EMPTY_DESCRIPTOR_LIST;
                        }
                    }
                    else
                    {
                        toReturn.addAll(descriptors);
                    }
                }
            }
        }
    }

    return toReturn;
}