private void broadcastUpdate(
      final String action, final BluetoothGattCharacteristic characteristic) {
    final Intent intent = new Intent(action);

    // This is special handling for the Heart Rate Measurement profile.  Data parsing is
    // carried out as per profile specifications:
    // http://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.heart_rate_measurement.xml
    if (UUID_HEART_RATE_MEASUREMENT.equals(characteristic.getUuid())) {
      int flag = characteristic.getProperties();
      int format = -1;
      if ((flag & 0x01) != 0) {
        format = BluetoothGattCharacteristic.FORMAT_UINT16;
        Log.d(TAG, "Heart rate format UINT16.");
      } else {
        format = BluetoothGattCharacteristic.FORMAT_UINT8;
        Log.d(TAG, "Heart rate format UINT8.");
      }
      final int heartRate = characteristic.getIntValue(format, 1);
      Log.d(TAG, String.format("Received heart rate: %d", heartRate));
      intent.putExtra(EXTRA_DATA, String.valueOf(heartRate));
    } else {
      // For all other profiles, writes the data formatted in HEX.
      final byte[] data = characteristic.getValue();
      if (data != null && data.length > 0) {
        final StringBuilder stringBuilder = new StringBuilder(data.length);
        for (byte byteChar : data) stringBuilder.append(String.format("%02X ", byteChar));
        intent.putExtra(EXTRA_DATA, new String(data) + "\n" + stringBuilder.toString());
      }
    }
    sendBroadcast(intent);
  }
  // Some peripherals re-use UUIDs for multiple characteristics so we need to check the properties
  // and UUID of all characteristics instead of using service.getCharacteristic(characteristicUUID)
  private BluetoothGattCharacteristic findWritableCharacteristic(
      BluetoothGattService service, UUID characteristicUUID, int writeType) {
    try {
      BluetoothGattCharacteristic characteristic = null;

      // get write property
      int writeProperty = BluetoothGattCharacteristic.PROPERTY_WRITE;
      if (writeType == BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE) {
        writeProperty = BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE;
      }

      List<BluetoothGattCharacteristic> characteristics = service.getCharacteristics();
      for (BluetoothGattCharacteristic c : characteristics) {
        if ((c.getProperties() & writeProperty) != 0 && characteristicUUID.equals(c.getUuid())) {
          characteristic = c;
          break;
        }
      }

      // As a last resort, try and find ANY characteristic with this UUID, even if it doesn't have
      // the correct properties
      if (characteristic == null) {
        characteristic = service.getCharacteristic(characteristicUUID);
      }

      return characteristic;
    } catch (Exception e) {
      Log.e(LOG_TAG, "Errore su findWritableCharacteristic", e);
      return null;
    }
  }
 private void broadcastUpdate(
     final String action, final BluetoothGattCharacteristic characteristic) {
   final Intent intent = new Intent(action);
   if (UUID_HEART_RATE_MEASUREMENT.equals(characteristic.getUuid())) {
     int flag = characteristic.getProperties();
     int format = -1;
     if ((flag & 0x01) != 0) {
       format = BluetoothGattCharacteristic.FORMAT_UINT16;
     } else {
       format = BluetoothGattCharacteristic.FORMAT_UINT8;
     }
     final int heartRate = characteristic.getIntValue(format, 1);
     LogUtil.info(TAG, "心率数据Received heart rate: %d" + heartRate);
     LogUtil.info(TAG, String.format("Received heart rate: %d", heartRate));
     intent.putExtra(EXTRA_DATA, receiveData);
   } else {
     // 脂肪秤和血糖仪设备数据返回
     final byte[] data = characteristic.getValue();
     if (data != null && data.length > 0) {
       String s = FatScaleDataUtil.byteToHexStringFormat(data);
       LogUtil.info(TAG, "原始数据:" + s);
       if (DEVICE_TYPE == 1) {
         intent.putExtra(EXTRA_DATA, s);
       } else {
         intent.putExtra(EXTRA_DATA, receiveData);
       }
     }
   }
   sendBroadcast(intent);
 }
Example #4
0
  public static boolean qppEnable(
      BluetoothGatt bluetoothGatt, String qppServiceUUID, String writeCharUUID) {
    resetQppField();
    if (qppServiceUUID != null) uuidQppService = qppServiceUUID;
    if (writeCharUUID != null) uuidQppCharWrite = writeCharUUID;
    if (bluetoothGatt == null || qppServiceUUID.isEmpty() || writeCharUUID.isEmpty()) {
      Log.e(TAG, "invalid arguments");
      return false;
    }

    BluetoothGattService qppService = bluetoothGatt.getService(UUID.fromString(qppServiceUUID));
    if (qppService == null) {
      Log.e(TAG, "Qpp service not found");
      return false;
    }

    List<BluetoothGattCharacteristic> gattCharacteristics = qppService.getCharacteristics();
    for (int j = 0; j < gattCharacteristics.size(); j++) {
      BluetoothGattCharacteristic chara = gattCharacteristics.get(j);
      if (chara.getUuid().toString().equals(writeCharUUID)) {
        // Log.i(TAG,"Wr char is "+chara.getUuid().toString());
        writeCharacteristic = chara;
      } else if (chara.getProperties() == BluetoothGattCharacteristic.PROPERTY_NOTIFY) {
        // Log.i(TAG,"NotiChar UUID is : "+chara.getUuid().toString());
        notifyCharacteristic = chara;
        arrayNtfCharList.add(chara);
      }
    }

    if (!setCharacteristicNotification(bluetoothGatt, arrayNtfCharList.get(0), true)) return false;

    notifyCharaIndex++;

    return true;
  }
  public void listenToCaliperMeasurements(final BluetoothGattCharacteristic characteristic) {
    if (characteristic == null) {
      Log.e(
          TAG,
          "Haven't discovered this feature yet, please wait until it has connected once, and or try disconnecting and reconnecting.");
      return;
    }

    Log.d(TAG, "Starting to listen to notifications from " + characteristic.getUuid());
    final int charaProp = characteristic.getProperties();
    if ((charaProp | BluetoothGattCharacteristic.PROPERTY_READ) > 0) {
      // If there is an active notification on a characteristic, clear
      // it first so it doesn't update the data field on the user interface.
      if (mNotifyCharacteristic != null) {
        mBluetoothLeService.setCharacteristicNotification(mNotifyCharacteristic, false);
        mNotifyCharacteristic = null;
      }
      mBluetoothLeService.readCharacteristic(characteristic);
    }
    if ((charaProp | BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) {
      mNotifyCharacteristic = characteristic;
      mBluetoothLeService.setCharacteristicNotification(characteristic, true);

      // Set descriptor to enable notifications
      BluetoothGattDescriptor descriptor =
          characteristic.getDescriptor(
              UUID.fromString(SCalEvoBluetoothSpecifications.CLIENT_CHARACTERISTIC_CONFIG));
      if (descriptor == null) {
        Log.e(
            TAG,
            "descriptor "
                + SCalEvoBluetoothSpecifications.CLIENT_CHARACTERISTIC_CONFIG
                + "was null, looking for others.");

        List<BluetoothGattDescriptor> descriptors = characteristic.getDescriptors();
        String uuid;
        for (BluetoothGattDescriptor aDescriptor : descriptors) {
          uuid = aDescriptor.getUuid().toString();
          Log.e(TAG, "BluetoothGattDescriptor " + uuid);
          descriptor = aDescriptor;
        }
        if (descriptor == null) {
          Log.e(
              TAG,
              "Couldn't find any descriptors for this characteristic, cant enable notifications");
          return;
        } else {
          Log.e(TAG, "Trying the last descriptor to enable notifications");
        }
      }
      descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
      mBluetoothLeService.writeDescriptor(descriptor);
      Toast.makeText(this, "Ready", Toast.LENGTH_SHORT).show();
      Log.e(TAG, "Ready to read from characteristic " + characteristic.getUuid());
    }
  }
  /**
   * Sends the read request to the given characteristic.
   *
   * @param characteristic the characteristic to read
   * @return true if request has been sent
   */
  protected final boolean readCharacteristic(final BluetoothGattCharacteristic characteristic) {
    final BluetoothGatt gatt = mBluetoothGatt;
    if (gatt == null || characteristic == null) return false;

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

    Logger.v(mLogSession, "Reading characteristic " + characteristic.getUuid());
    Logger.d(mLogSession, "gatt.readCharacteristic(" + characteristic.getUuid() + ")");
    return gatt.readCharacteristic(characteristic);
  }
        @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(
                new Dispatcher<HeartRateListener>() {
                  @Override
                  public void dispatch(HeartRateListener listener) {
                    listener.onConnected();
                  }
                });
          }

          if (previousValue != mLastValue) {
            // Inform listeners
            mListeners.dispatch(
                new Dispatcher<HeartRateListener>() {
                  @Override
                  public void dispatch(HeartRateListener listener) {
                    listener.onHeartRateChange(mLastValue);
                  }
                });
          }
        }
  public static JSONArray decodeProperties(BluetoothGattCharacteristic characteristic) {

    // NOTE: props strings need to be consistent across iOS and Android
    JSONArray props = new JSONArray();
    int properties = characteristic.getProperties();

    if ((properties & BluetoothGattCharacteristic.PROPERTY_BROADCAST) != 0x0) {
      props.put("Broadcast");
    }

    if ((properties & BluetoothGattCharacteristic.PROPERTY_READ) != 0x0) {
      props.put("Read");
    }

    if ((properties & BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE) != 0x0) {
      props.put("WriteWithoutResponse");
    }

    if ((properties & BluetoothGattCharacteristic.PROPERTY_WRITE) != 0x0) {
      props.put("Write");
    }

    if ((properties & BluetoothGattCharacteristic.PROPERTY_NOTIFY) != 0x0) {
      props.put("Notify");
    }

    if ((properties & BluetoothGattCharacteristic.PROPERTY_INDICATE) != 0x0) {
      props.put("Indicate");
    }

    if ((properties & BluetoothGattCharacteristic.PROPERTY_SIGNED_WRITE) != 0x0) {
      // Android calls this "write with signature", using iOS name for now
      props.put("AuthenticateSignedWrites");
    }

    if ((properties & BluetoothGattCharacteristic.PROPERTY_EXTENDED_PROPS) != 0x0) {
      props.put("ExtendedProperties");
    }

    //      iOS only?
    //
    //            if ((p & CBCharacteristicPropertyNotifyEncryptionRequired) != 0x0) {  // 0x100
    //                [props addObject:@"NotifyEncryptionRequired"];
    //            }
    //
    //            if ((p & CBCharacteristicPropertyIndicateEncryptionRequired) != 0x0) { // 0x200
    //                [props addObject:@"IndicateEncryptionRequired"];
    //            }

    return props;
  }
  // Some devices reuse UUIDs across characteristics, so we can't use
  // service.getCharacteristic(characteristicUUID)
  // instead check the UUID and properties for each characteristic in the service until we find the
  // best match
  // This function prefers Notify over Indicate
  private BluetoothGattCharacteristic findNotifyCharacteristic(
      BluetoothGattService service, UUID characteristicUUID) {
    BluetoothGattCharacteristic characteristic = null;

    try {
      // Check for Notify first
      List<BluetoothGattCharacteristic> characteristics = service.getCharacteristics();
      for (BluetoothGattCharacteristic c : characteristics) {
        if ((c.getProperties() & BluetoothGattCharacteristic.PROPERTY_NOTIFY) != 0
            && characteristicUUID.equals(c.getUuid())) {
          characteristic = c;
          break;
        }
      }

      if (characteristic != null) return characteristic;

      // If there wasn't Notify Characteristic, check for Indicate
      for (BluetoothGattCharacteristic c : characteristics) {
        if ((c.getProperties() & BluetoothGattCharacteristic.PROPERTY_INDICATE) != 0
            && characteristicUUID.equals(c.getUuid())) {
          characteristic = c;
          break;
        }
      }

      // As a last resort, try and find ANY characteristic with this UUID, even if it doesn't have
      // the correct properties
      if (characteristic == null) {
        characteristic = service.getCharacteristic(characteristicUUID);
      }

      return characteristic;
    } catch (Exception e) {
      Log.e(LOG_TAG, "Errore su caratteristica " + characteristicUUID, e);
      return null;
    }
  }
  /**
   * Writes the characteristic value to the given characteristic.
   *
   * @param characteristic the characteristic to write to
   * @return true if request has been sent
   */
  protected final boolean writeCharacteristic(final BluetoothGattCharacteristic characteristic) {
    final BluetoothGatt gatt = mBluetoothGatt;
    if (gatt == null || characteristic == null) return false;

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

    Logger.v(mLogSession, "Writing characteristic " + characteristic.getUuid());
    Logger.d(mLogSession, "gatt.writeCharacteristic(" + characteristic.getUuid() + ")");
    return gatt.writeCharacteristic(characteristic);
  }
  private void broadcastUpdate(
      final String action, final BluetoothGattCharacteristic characteristic, String device) {
    final Intent intent = new Intent(action);
    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);
      System.out.println("Received heart rate: %d" + heartRate);
      Log.d(TAG, String.format("Received heart rate: %d", heartRate));
      intent.putExtra(EXTRA_DATA, String.valueOf(heartRate));
    } else if (BATTERY_CHACTER_UUID.equals(characteristic.getUuid())) {
      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));

        Log.e(TAG, "############################broadcastUpdate : " + data[0]);
        intent.putExtra(BATTERY_DATA, data);
        intent.putExtra(BluetoothDevice.EXTRA_DEVICE, device);
      }
    } else {
      // For all other profiles, writes the data formatted in HEX.
      /*final byte[] data = characteristic.getValue();
      for (int i = 0; i < data.length; i++) {
      	Log.v("ww", "sa:" + data[i]);
      }
      if (data != null && data.length > 0) {
      	intent.putExtra(EXTRA_DATA, data);
      }*/

      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());
        intent.putExtra(BluetoothDevice.EXTRA_DEVICE, device);
      }
    }
    sendBroadcast(intent);
  }
  /**
   * 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;
  }
  /**
   * 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);
  }
  // Some peripherals re-use UUIDs for multiple characteristics so we need to check the properties
  // and UUID of all characteristics instead of using service.getCharacteristic(characteristicUUID)
  private BluetoothGattCharacteristic findReadableCharacteristic(
      BluetoothGattService service, UUID characteristicUUID) {
    BluetoothGattCharacteristic characteristic = null;

    int read = BluetoothGattCharacteristic.PROPERTY_READ;

    List<BluetoothGattCharacteristic> characteristics = service.getCharacteristics();
    for (BluetoothGattCharacteristic c : characteristics) {
      if ((c.getProperties() & read) != 0 && characteristicUUID.equals(c.getUuid())) {
        characteristic = c;
        break;
      }
    }

    // As a last resort, try and find ANY characteristic with this UUID, even if it doesn't have the
    // correct properties
    if (characteristic == null) {
      characteristic = service.getCharacteristic(characteristicUUID);
    }

    return characteristic;
  }
 @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) {
       // If there is an active notification on a characteristic, clear
       // 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) {
       listenToCaliperMeasurements(characteristic);
     }
     return true;
   }
   return false;
 }
  /**
   * Enables indications on given characteristic
   *
   * @return true is the request has been sent, false if one of the arguments was <code>null</code>
   *     or the characteristic does not have the CCCD.
   */
  protected final boolean enableIndications(final BluetoothGattCharacteristic characteristic) {
    final BluetoothGatt gatt = mBluetoothGatt;
    if (gatt == null || characteristic == null) return false;

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

    gatt.setCharacteristicNotification(characteristic, true);
    final BluetoothGattDescriptor descriptor =
        characteristic.getDescriptor(CLIENT_CHARACTERISTIC_CONFIG_DESCRIPTOR_UUID);
    if (descriptor != null) {
      descriptor.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
      Logger.v(mLogSession, "Enabling indications for " + characteristic.getUuid());
      Logger.d(
          mLogSession,
          "gatt.writeDescriptor("
              + CLIENT_CHARACTERISTIC_CONFIG_DESCRIPTOR_UUID
              + ", value=0x02-00)");
      return gatt.writeDescriptor(descriptor);
    }
    return false;
  }
Example #17
0
  // ----------------------------------------------------------------------------------------------------------------
  // Write to a given characteristic. The completion of the write is reported asynchronously through
  // the
  // BluetoothGattCallback onCharacteristicWrire callback method.
  public void writeCharacteristic(BluetoothGattCharacteristic characteristic) {
    if (mBluetoothAdapter == null
        || mBluetoothGatt == null) { // Check that we have access to a Bluetooth radio
      Log.w(TAG, "BluetoothAdapter not initialized");
      return;
    }
    int test = characteristic.getProperties(); // Get the properties of the characteristic
    if ((test & BluetoothGattCharacteristic.PROPERTY_WRITE) == 0
        && (test & BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE)
            == 0) { // Check that the property is writable
      return;
    }

    if (mBluetoothGatt.writeCharacteristic(
        characteristic)) { // Request the BluetoothGatt to do the Write
      Log.d(
          TAG,
          "writeCharacteristic successful"); // The request was accepted, this does not mean the
                                             // write completed
    } else {
      Log.d(
          TAG, "writeCharacteristic failed"); // Write request was not accepted by the BluetoothGatt
    }
  }
  private void displayGattServices(List<BluetoothGattService> gattServices) {
    if (gattServices == null) return;

    for (BluetoothGattService gattService : gattServices) {
      // -----Service的字段信息-----//
      int type = gattService.getType();
      Log.e(TAG, "-->service type:" + Utils.getServiceType(type));
      Log.e(TAG, "-->includedServices size:" + gattService.getIncludedServices().size());
      Log.e(TAG, "-->service uuid:" + gattService.getUuid());

      // -----Characteristics的字段信息-----//
      List<BluetoothGattCharacteristic> gattCharacteristics = gattService.getCharacteristics();
      for (final BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
        Log.e(TAG, "---->char uuid:" + gattCharacteristic.getUuid());

        int permission = gattCharacteristic.getPermissions();
        Log.e(TAG, "---->char permission:" + Utils.getCharPermission(permission));

        int property = gattCharacteristic.getProperties();
        Log.e(TAG, "---->char property:" + Utils.getCharPropertie(property));

        byte[] data = gattCharacteristic.getValue();
        if (data != null && data.length > 0) {
          Log.e(TAG, "---->char value:" + Utils.bytesToHexString(data));
        }

        if (gattService.getUuid().toString().equals(UUID_KEY_SERVICE)) { // 如果是温度计的service
          // UUID_KEY_DATA是可以跟蓝牙模块串口通信的Characteristic
          if (gattCharacteristic.getUuid().toString().equals(UUID_KEY_DATA_RECIV)) {
            // 测试读取当前Characteristic数据,会触发mOnDataAvailable.onCharacteristicRead()
            mHandler.postDelayed(
                new Runnable() {
                  @Override
                  public void run() {
                    mBLE_reciv.readCharacteristic(gattCharacteristic);
                  }
                },
                500);

            // 接受Characteristic被写的通知,收到蓝牙模块的数据后会触发mOnDataAvailable.onCharacteristicWrite()
            mBLE_reciv.setCharacteristicNotification(gattCharacteristic, true);
            BluetoothGattDescriptor localBluetoothGattDescriptor =
                gattCharacteristic.getDescriptor(UUID.fromString(CCC));
            localBluetoothGattDescriptor.setValue(
                BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
            mBluetoothGatt.writeDescriptor(localBluetoothGattDescriptor);
            appState.gattCharacteristic_reciv_dianzichen = gattCharacteristic;
            // 设置数据内容
            //            			gattCharacteristic.setValue("0");
            // 往蓝牙模块写入数据
            //            			appState.mBLE_reciv_dianzichen.writeCharacteristic(gattCharacteristic);
          }

          // UUID_KEY_DATA是可以跟蓝牙模块串口通信的Characteristic
          if (gattCharacteristic.getUuid().toString().equals(UUID_KEY_DATA_SEND)) {
            // 测试读取当前Characteristic数据,会触发mOnDataAvailable.onCharacteristicRead()
            mHandler.postDelayed(
                new Runnable() {
                  @Override
                  public void run() {
                    mBLE_send.readCharacteristic(gattCharacteristic);
                    // Log.i("info", "appState.mBLE_send_dianzichen 尝试读数据");
                  }
                },
                500);

            // 接受Characteristic被写的通知,收到蓝牙模块的数据后会触发mOnDataAvailable.onCharacteristicWrite()
            mBLE_send.setCharacteristicNotification(gattCharacteristic, true);
            // 设置数据内容
            // gattCharacteristic.setValue("send data->");
            // 往蓝牙模块写入数据
            // mBLE_send.writeCharacteristic(gattCharacteristic);

            if (!appState.firstActivityRunning) {
              appState.gattCharacteristic_send_dianzichen = gattCharacteristic;

              appState.file.write2SDFromInput("inurse/", "Dianzichen.txt", appState.deviceAddress);

              Intent it = new Intent(this, DianzichenActivity.class);
              startActivityForResult(it, 0); // 配合onActivityResult,当FirstActivity退出时获得一个0值,然后自己也退出
              //            				moveTaskToBack(true); //这一句是整个程序返回桌面
              appState.firstActivityRunning = true;
            }
          }
        } // 结束 if ( gattService.getUuid().toString().equals(UUID_KEY_SERVICE) )

        // -----Descriptors的字段信息-----//
        List<BluetoothGattDescriptor> gattDescriptors = gattCharacteristic.getDescriptors();
        for (BluetoothGattDescriptor gattDescriptor : gattDescriptors) {
          Log.e(TAG, "-------->desc uuid:" + gattDescriptor.getUuid());
          int descPermission = gattDescriptor.getPermissions();
          Log.e(TAG, "-------->desc permission:" + Utils.getDescPermission(descPermission));

          byte[] desData = gattDescriptor.getValue();
          if (desData != null && desData.length > 0) {
            Log.e(TAG, "-------->desc value:" + Utils.bytesToHexString(data));
          }

          // soloman 接收的uuid要设置CCC通知enable,并回写到BluetoothGatt
          //					if (gattDescriptor.getUuid().toString().equals(CCC)){
          //						gattDescriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
          //						mBluetoothGatt.writeDescriptor(gattDescriptor);
          //					}
        }
      }
    } //
  }
Example #19
0
  private void broadcastUpdate(
      final String action, final BluetoothGattCharacteristic characteristic) {
    final Intent intent = new Intent(action);

    // This is special handling for the Heart Rate Measurement profile.  Data parsing is
    // carried out as per profile specifications:
    // http://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.heart_rate_measurement.xml
    if (UUID_HEART_RATE_MEASUREMENT.equals(characteristic.getUuid())) {
      int flag = characteristic.getProperties();
      int format = -1;
      if ((flag & 0x01) != 0) {
        format = BluetoothGattCharacteristic.FORMAT_UINT16;
        Log.d(TAG, "Heart rate format UINT16.");
      } else {
        format = BluetoothGattCharacteristic.FORMAT_UINT8;
        Log.d(TAG, "Heart rate format UINT8.");
      }
      final int heartRate = characteristic.getIntValue(format, 1);
      Log.d(TAG, String.format("Received heart rate: %d", heartRate));
      intent.putExtra(EXTRA_DATA, String.valueOf(heartRate));
    } else {
      // For all other profiles, writes the data formatted in HEX.
      final byte[] data = characteristic.getValue();
      if (data != null && data.length > 0) {
        final StringBuilder stringBuilder = new StringBuilder(data.length);
        for (byte byteChar : data) stringBuilder.append(String.format("%02X ", byteChar));
        intent.putExtra(EXTRA_DATA, new String(data) + "\n" + stringBuilder.toString());
        if (characteristic.getUuid().toString().equals(SampleGattAttributes.DEBUG_PACKET_CHAR)) {
          log28.append("\n" + new String(data) + "\n" + stringBuilder.toString() + "\n");
        } else if (characteristic
            .getUuid()
            .toString()
            .equals(SampleGattAttributes.QUAT_PACKET_CHAR)) {
          log26.append("\n" + new String(data) + "\n" + stringBuilder.toString() + "\n");
        } else if (characteristic
            .getUuid()
            .toString()
            .equals(SampleGattAttributes.DATA_PACKET_CHAR)) {
          log27.append("\n" + new String(data) + "\n" + stringBuilder.toString() + "\n");
          String dataType = stringBuilder.substring(3, 5);
          Log.d(TAG, "String Subset: " + dataType);
          switch (dataType) {
            case "00": // a
              log27_a.append("\n" + new String(data) + "\n" + stringBuilder.toString() + "\n");
              break;
            case "01": // g
              log27_g.append("\n" + new String(data) + "\n" + stringBuilder.toString() + "\n");
              break;
            case "03": // q
              log27_q.append("\n" + new String(data) + "\n" + stringBuilder.toString() + "\n");
              break;
            case "04": // e
              log27_e.append("\n" + new String(data) + "\n" + stringBuilder.toString() + "\n");
              break;
            case "06": // h
              log27_h.append("\n" + new String(data) + "\n" + stringBuilder.toString() + "\n");
              break;
          }
        }
      }
    }
    sendBroadcast(intent);
  }
 @Override
 @Properties
 public int getProperties() {
   final @Properties int properties = wrappedCharacteristic.getProperties();
   return properties;
 }
  // This seems way too complicated
  public void registerNotify(
      UUID serviceUUID, UUID characteristicUUID, Callback success, Callback fail) {

    Log.d(LOG_TAG, "registerNotify");

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

    BluetoothGattService service = gatt.getService(serviceUUID);
    BluetoothGattCharacteristic characteristic =
        findNotifyCharacteristic(service, characteristicUUID);
    // String key = generateHashKey(serviceUUID, characteristic);

    if (characteristic != null) {
      Log.d(LOG_TAG, "characteristic ok");

      if (gatt.setCharacteristicNotification(characteristic, true)) {

        BluetoothGattDescriptor descriptor =
            characteristic.getDescriptor(UUID.fromString(CHARACTERISTIC_NOTIFICATION_CONFIG));
        if (descriptor != null) {
          Log.d(LOG_TAG, "trovato descriptor");

          // prefer notify over indicate
          if ((characteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_NOTIFY) != 0) {
            Log.d(LOG_TAG, "Characteristic " + characteristicUUID + " set NOTIFY");
            descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
          } else if ((characteristic.getProperties()
                  & BluetoothGattCharacteristic.PROPERTY_INDICATE)
              != 0) {
            Log.d(LOG_TAG, "Characteristic " + characteristicUUID + " set INDICATE");
            descriptor.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
          } else {
            Log.d(
                LOG_TAG,
                "Characteristic "
                    + characteristicUUID
                    + " does not have NOTIFY or INDICATE property set");
          }

          if (gatt.writeDescriptor(descriptor)) {
            // Tutto ok
            Log.d(LOG_TAG, "registerNotify completato");
            success.invoke();
          } else {
            fail.invoke(
                "Failed to set client characteristic notification for " + characteristicUUID);
          }

        } else {
          fail.invoke("Set notification failed for " + characteristicUUID);
        }

      } else {
        fail.invoke("Failed to register notification for " + characteristicUUID);
      }

    } else {
      fail.invoke("Characteristic " + characteristicUUID + " not found");
    }
  }