/**
   * Enables or disables notification on a give characteristic.
   *
   * @param characteristic Characteristic to act on.
   * @param enabled If true, enable notification. False otherwise.
   */
  public void setCharacteristicNotification(
      BluetoothGattCharacteristic characteristic, boolean enabled) {
    if (mBluetoothAdapter == null || mBluetoothGatt == null) {
      Log.w(TAG, "BluetoothAdapter not initialized");
      return;
    }
    mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);

    // This is specific to Heart Rate Measurement.
    if (UUID_HEART_RATE_MEASUREMENT.equals(characteristic.getUuid())) {
      BluetoothGattDescriptor descriptor =
          characteristic.getDescriptor(
              UUID.fromString(SampleGattAttributes.CLIENT_CHARACTERISTIC_CONFIG));
      descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
      mBluetoothGatt.writeDescriptor(descriptor);
    }

    // specific for pm2.5
    if (UUID_FFE0.equals(characteristic.getUuid())) {
      BluetoothGattDescriptor descriptor =
          characteristic.getDescriptor(
              UUID.fromString(SampleGattAttributes.CLIENT_CHARACTERISTIC_CONFIG));
      descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
      mBluetoothGatt.writeDescriptor(descriptor);
    }
  }
 public void onCharacteristicWrite(
     Peripheral peripheral, BluetoothGattCharacteristic characteristic, int status) {
   if (characteristic.getUuid().equals(AN_DEVICE_DFU_DATA)) {
     if (status == BluetoothGatt.GATT_SUCCESS) {
       mSendedFileSize += characteristic.getValue().length;
       Log.e(TAG, "write: " + mSendedFileSize + " total: " + mDataBuf.length);
       if (mCallback != null) {
         mCallback.onSendAUnit(mSendedFileSize, mDataBuf.length);
       }
     }
     if (mSendedFileSize >= mDataBuf.length) {
       mOtaing = false;
       mSendedFileSize = 0;
       try {
         Thread.sleep(500);
       } catch (InterruptedException e) {
         e.printStackTrace();
       }
       otaValidFW();
     } else {
       try {
         Thread.sleep(mUpdateInterval);
       } catch (InterruptedException e) {
         e.printStackTrace();
       }
       sendData();
     }
   } else if (characteristic.getUuid().equals(AN_DEVICE_FIRMWARE_UPDATE_CHAR)) {
     if (mOtaing) {
       startSendData();
     }
   }
 }
    @Override
    public final void onCharacteristicChanged(
        final BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic) {
      final String data = ParserUtils.parse(characteristic);

      if (isBatteryLevelCharacteristic(characteristic)) {
        Logger.i(
            mLogSession,
            "Notification received from " + characteristic.getUuid() + ", value: " + data);
        final int batteryValue =
            characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8, 0);
        Logger.a(mLogSession, "Battery level received: " + batteryValue + "%");
        mCallbacks.onBatteryValueReceived(batteryValue);
      } else {
        final BluetoothGattDescriptor cccd =
            characteristic.getDescriptor(CLIENT_CHARACTERISTIC_CONFIG_DESCRIPTOR_UUID);
        final boolean notifications =
            cccd == null
                || cccd.getValue() == null
                || cccd.getValue().length != 2
                || cccd.getValue()[0] == 0x01;

        if (notifications) {
          Logger.i(
              mLogSession,
              "Notification received from " + characteristic.getUuid() + ", value: " + data);
          onCharacteristicNotified(gatt, characteristic);
        } else { // indications
          Logger.i(
              mLogSession,
              "Indication received from " + characteristic.getUuid() + ", value: " + data);
          onCharacteristicIndicated(gatt, characteristic);
        }
      }
    }
  public SensorTagHumidityProfile(
      Context con,
      BluetoothDevice device,
      BluetoothGattService service,
      BluetoothLeService controller) {
    super(con, device, service, controller);
    this.tRow = new GenericCharacteristicTableRow(con);

    List<BluetoothGattCharacteristic> characteristics = this.mBTService.getCharacteristics();

    for (BluetoothGattCharacteristic c : characteristics) {
      if (c.getUuid().toString().equals(SensorTagGatt.UUID_HUM_DATA.toString())) {
        this.dataC = c;
      }
      if (c.getUuid().toString().equals(SensorTagGatt.UUID_HUM_CONF.toString())) {
        this.configC = c;
      }
      if (c.getUuid().toString().equals(SensorTagGatt.UUID_HUM_PERI.toString())) {
        this.periodC = c;
      }
    }

    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.0%rH");
    this.tRow.periodBar.setProgress(100);
  }
Beispiel #5
0
 @Override
 public void onCharacteristicRead(
     BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
   if (bleGattService.containsCharacteristic(characteristic.getUuid())) {
     callBack.onCharacteristicRead(characteristic.getUuid(), characteristic.getValue());
   }
 }
  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());
    }
  }
Beispiel #7
0
        @Override
        public void onCharacteristicRead(
            BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
          Log.wtf("Read", characteristic.getUuid().toString());
          if (ERROR_CHAR.equals(characteristic.getUuid())) {
            Log.wtf("Something", "" + characteristic.getValue()[0]);

            advance();
            enableNextSensor(gatt);
          }
          super.onCharacteristicRead(gatt, characteristic, status);
        }
  /**
   * 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);
  }
  private void getGattServices(List<BluetoothGattService> gattServices) {
    if (gattServices == null) return;
    String uuid = null;
    mModelNumberCharacteristic = null;
    mSerialPortCharacteristic = null;
    mCommandCharacteristic = null;
    mGattCharacteristics = new ArrayList<ArrayList<BluetoothGattCharacteristic>>();

    // Loops through available GATT Services.
    for (BluetoothGattService gattService : gattServices) {
      uuid = gattService.getUuid().toString();
      System.out.println("displayGattServices + uuid=" + uuid);

      List<BluetoothGattCharacteristic> gattCharacteristics = gattService.getCharacteristics();
      ArrayList<BluetoothGattCharacteristic> charas = new ArrayList<BluetoothGattCharacteristic>();

      // Loops through available Characteristics.
      for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
        charas.add(gattCharacteristic);
        uuid = gattCharacteristic.getUuid().toString();
        if (uuid.equals(ModelNumberStringUUID)) {
          mModelNumberCharacteristic = gattCharacteristic;
          System.out.println(
              "mModelNumberCharacteristic  " + mModelNumberCharacteristic.getUuid().toString());
        } else if (uuid.equals(SerialPortUUID)) {
          mSerialPortCharacteristic = gattCharacteristic;
          System.out.println(
              "mSerialPortCharacteristic  " + mSerialPortCharacteristic.getUuid().toString());
          //                    updateConnectionState(R.string.comm_establish);
        } else if (uuid.equals(CommandUUID)) {
          mCommandCharacteristic = gattCharacteristic;
          System.out.println(
              "mSerialPortCharacteristic  " + mSerialPortCharacteristic.getUuid().toString());
          //                    updateConnectionState(R.string.comm_establish);
        }
      }
      mGattCharacteristics.add(charas);
    }

    if (mModelNumberCharacteristic == null
        || mSerialPortCharacteristic == null
        || mCommandCharacteristic == null) {
      Toast.makeText(mainContext, "Please select DFRobot devices", Toast.LENGTH_SHORT).show();
      mConnectionState = connectionStateEnum.isToScan;
      onConectionStateChange(mConnectionState);
    } else {
      mSCharacteristic = mModelNumberCharacteristic;
      mBluetoothLeService.setCharacteristicNotification(mSCharacteristic, true);
      mBluetoothLeService.readCharacteristic(mSCharacteristic);
    }
  }
  // Demonstrates how to iterate through the supported GATT Services/Characteristics.
  // In this sample, we populate the data structure that is bound to the ExpandableListView
  // on the UI.
  private void displayGattServices(List<BluetoothGattService> gattServices) {
    if (gattServices == null) return;
    String uuid = null;
    String unknownServiceString = getResources().getString(R.string.unknown_service);
    String unknownCharaString = getResources().getString(R.string.unknown_characteristic);
    ArrayList<HashMap<String, String>> gattServiceData = new ArrayList<HashMap<String, String>>();
    ArrayList<ArrayList<HashMap<String, String>>> gattCharacteristicData =
        new ArrayList<ArrayList<HashMap<String, String>>>();
    mGattCharacteristics = new ArrayList<ArrayList<BluetoothGattCharacteristic>>();

    // Loops through available GATT Services.
    for (BluetoothGattService gattService : gattServices) {
      HashMap<String, String> currentServiceData = new HashMap<String, String>();
      currentServiceData.put(
          LIST_NAME, Service.lookup(gattService.getUuid(), unknownServiceString));
      currentServiceData.put(LIST_UUID, uuid);
      gattServiceData.add(currentServiceData);

      ArrayList<HashMap<String, String>> gattCharacteristicGroupData =
          new ArrayList<HashMap<String, String>>();
      List<BluetoothGattCharacteristic> gattCharacteristics = gattService.getCharacteristics();
      ArrayList<BluetoothGattCharacteristic> charas = new ArrayList<BluetoothGattCharacteristic>();

      // Loops through available Characteristics.
      for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
        charas.add(gattCharacteristic);
        HashMap<String, String> currentCharaData = new HashMap<String, String>();
        uuid = gattCharacteristic.getUuid().toString();
        currentCharaData.put(
            LIST_NAME, Characteristic.lookup(gattCharacteristic.getUuid(), unknownCharaString));
        currentCharaData.put(LIST_UUID, uuid);
        gattCharacteristicGroupData.add(currentCharaData);
      }
      mGattCharacteristics.add(charas);
      gattCharacteristicData.add(gattCharacteristicGroupData);
    }

    SimpleExpandableListAdapter gattServiceAdapter =
        new SimpleExpandableListAdapter(
            this,
            gattServiceData,
            android.R.layout.simple_expandable_list_item_2,
            new String[] {LIST_NAME, LIST_UUID},
            new int[] {android.R.id.text1, android.R.id.text2},
            gattCharacteristicData,
            android.R.layout.simple_expandable_list_item_2,
            new String[] {LIST_NAME, LIST_UUID},
            new int[] {android.R.id.text1, android.R.id.text2});
    mGattServicesList.setAdapter(gattServiceAdapter);
  }
  /**
   * 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 displayData(final BluetoothGattCharacteristic characteristic, Characteristiques ch) {
   switch (characteristic.getUuid().toString()) {
     case FlowerPowerConstants.CHARACTERISTIC_UUID_TEMPERATURE:
       int temperature =
           valueMapper.mapTemperature(
               characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT16, 0));
       ch.setValue(temperature + "");
       System.err.println("Temp " + ch.getValue());
       break;
     case FlowerPowerConstants.CHARACTERISTIC_UUID_SUNLIGHT:
       double luminosite =
           valueMapper.mapSunlight(
               characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT16, 0));
       ch.setValue(luminosite + "");
       System.err.println("Display Sunlight" + ch.getValue());
       break;
     case FlowerPowerConstants.CHARACTERISTIC_UUID_SOIL_MOISTURE:
       double humidite =
           valueMapper.mapSoilMoisture(
               characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT16, 0));
       ch.setValue(humidite + "");
       System.err.println("Display Soil Moisture " + ch.getValue());
       break;
     default:
       break;
   }
   MainActivity.adapter.notifyDataSetChanged();
   myView.invalidate();
 }
 @Override
 public void onCharacteristicWrite(
     final BluetoothGatt gatt,
     final BluetoothGattCharacteristic characteristic,
     final int status) {
   if (status == BluetoothGatt.GATT_SUCCESS) {
     Logger.i(
         mLogSession,
         "Data written to "
             + characteristic.getUuid()
             + ", value: "
             + ParserUtils.parse(characteristic.getValue()));
     // The value has been written. Notify the manager and proceed with the initialization queue.
     onCharacteristicWrite(gatt, characteristic);
     nextRequest();
   } else if (status == BluetoothGatt.GATT_INSUFFICIENT_AUTHENTICATION) {
     if (gatt.getDevice().getBondState() != BluetoothDevice.BOND_NONE) {
       DebugLogger.w(TAG, ERROR_AUTH_ERROR_WHILE_BONDED);
       mCallbacks.onError(ERROR_AUTH_ERROR_WHILE_BONDED, status);
     }
   } else {
     DebugLogger.e(TAG, "onCharacteristicRead error " + status);
     onError(ERROR_READ_CHARACTERISTIC, status);
   }
 }
  // 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;
    }
  }
        @Override
        public void onReceive(Context context, Intent intent) {

          final String action = intent.getAction();
          Log.d(TAG, "action: " + action);

          if (BluetoothLeService.ACTION_DATA_NOTIFY.equals(action)) {
            byte[] value = intent.getByteArrayExtra(BluetoothLeService.EXTRA_DATA);
            String uuidStr = intent.getStringExtra(BluetoothLeService.EXTRA_UUID);
            if (uuidStr.equals(mCharIdentify.getUuid().toString())) {
              // Image info notification
              mTargImgHdr.ver = Conversion.buildUint16(value[1], value[0]);
              mTargImgHdr.imgType = ((mTargImgHdr.ver & 1) == 1) ? 'B' : 'A';
              mTargImgHdr.len = Conversion.buildUint16(value[3], value[2]);
              displayImageInfo(mTargImage, mTargImgHdr);
            }
          } else if (BluetoothLeService.ACTION_DATA_WRITE.equals(action)) {
            int status =
                intent.getIntExtra(BluetoothLeService.EXTRA_STATUS, BluetoothGatt.GATT_SUCCESS);
            if (status != BluetoothGatt.GATT_SUCCESS) {
              Log.e(TAG, "Write failed: " + status);
              Toast.makeText(context, "GATT error: status=" + status, Toast.LENGTH_SHORT).show();
            }
          }
        }
  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);
  }
        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
          System.out.println("onServicesDiscoverd(): " + gatt + ", status: " + status);

          if (gatt != btGatt) return;

          List<BluetoothGattService> list = btGatt.getServices();
          for (BluetoothGattService s : list) {
            System.err.println(
                "Found service: " + s.getType() + ", " + s.getInstanceId() + ", " + s.getUuid());
            for (BluetoothGattCharacteristic a : s.getCharacteristics()) {
              System.err.println("  char: " + a.getUuid());
            }
            for (BluetoothGattService a : s.getIncludedServices()) {
              System.err.println("  serv: " + a.getUuid());
            }
          }

          System.out.println(" => DummyRead");
          if (status == BluetoothGatt.GATT_SUCCESS) {
            DummyReadForSecLevelCheck(gatt);
            // continue in onCharacteristicRead
          } else {
            DummyReadForSecLevelCheck(gatt);
            // reportConnectFailed("onServicesDiscovered(" + gatt + ", " +
            // status + ")");
          }
        }
  private void getCharacteristics(List<BluetoothGattService> gattServices) {
    Boolean tx = false;
    Boolean rx = false;

    if (gattServices == null) return;

    List<BluetoothGattCharacteristic> gattCharacteristics =
        new ArrayList<BluetoothGattCharacteristic>();

    for (BluetoothGattService gattService : gattServices) {
      if (gattService.getUuid().equals(UART_UUID)) {
        gattCharacteristics = gattService.getCharacteristics();
        for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
          if (gattCharacteristic.getUuid().equals(TX_UUID)) {
            target_character = gattCharacteristic;
            // Sleep a bit
            try {
              Thread.sleep(200);
            } catch (InterruptedException e) {
              e.printStackTrace();
            }
            sendCurrentTime();
            sendClearToSend();
          }
        }
      }
    }
  }
 private String generateHashKey(UUID serviceUUID, BluetoothGattCharacteristic characteristic) {
   return String.valueOf(serviceUUID)
       + "|"
       + characteristic.getUuid()
       + "|"
       + characteristic.getInstanceId();
 }
 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);
 }
        /** 收到BLE终端写入数据回调 */
        @Override
        public void onCharacteristicWrite(
            BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
          Log.e(
              TAG,
              "onCharWrite "
                  + gatt.getDevice().getName()
                  + " write "
                  + characteristic.getUuid().toString()
                  + " -> "
                  + Utils.bytesToHexString(characteristic.getValue()));

          switch (characteristic.getValue()[0]) {
            case (byte) 0x55: // 实时体重数据
              appState.calcWeight(characteristic.getValue()); // 解析实时体重
              appState.dataArrive = true;
              break;
            case (byte) 0x5A: // 完整测量结果数据
              appState.calcAllWeight(characteristic.getValue()); // 解析实时体重
              appState.dataArrive = true;
              break;

            default:
              break;
          }
        }
 // broadcast for GATT on characteristic write
 private void broadcastWriteSuccess(
     final String action, String devName, BluetoothGattCharacteristic characteristic) {
   final Intent intent = new Intent(action);
   LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
   intent.putExtra(DEVICE_NAME, devName);
   intent.putExtra(CHAR_UUID, characteristic.getUuid().toString());
 }
        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic arg0) {
          if (gatt != btGatt) {
            return;
          }

          if (!arg0.getUuid().equals(HEART_RATE_MEASUREMENT_CHARAC)) {
            System.err.println("onCharacteristicChanged(" + arg0 + ") != HEART_RATE ??");
            return;
          }

          int length = arg0.getValue().length;
          if (length == 0) {
            System.err.println("length = 0");
            return;
          }

          if (isHeartRateInUINT16(arg0.getValue()[0])) {
            hrValue = arg0.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT16, 1);
          } else {
            hrValue = arg0.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8, 1);
          }
          hrTimestamp = System.currentTimeMillis();

          if (mIsConnecting) {
            reportConnected(true);
          }
        }
Beispiel #24
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;
  }
  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);
  }
Beispiel #26
0
        @Override
        public void onCharacteristicWrite(
            BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
          // After writing the enable flag, next we read the initial
          Log.wtf(TAG, "Written to " + characteristic.getUuid().toString() + ":" + status);
          if (characteristic.getUuid().toString().equals(SECURITY_KEY.toString())) {
            Log.wtf(TAG, "Written to Security");
            //                    setNotifyNextSensor(gatt);
            setNotifyNextSensor(gatt);
          }

          if (characteristic.getUuid().toString().equals(CONFIG_CHAR.toString())) {
            Log.wtf(TAG, "Written to Config");
            advance();
            setNotifyNextSensor(gatt);
          }
        }
 protected void onHeartRateServiceFound(BluetoothGattService service) {
   Log.d();
   for (BluetoothGattCharacteristic characteristic : service.getCharacteristics()) {
     Log.d("characteristic=" + characteristic.getUuid());
     boolean found = false;
     if (getAssignedNumber(characteristic.getUuid())
         == GATT_CHARACTERISTIC_HEART_RATE_MEASUREMENT) {
       // Found heart read measurement characteristic
       onHeartRateMeasurementCharacteristicFound(characteristic);
       found = true;
       break;
     }
     if (!found) {
       onHeartRateMeasurementCharacteristicNotFound();
     }
   }
 }
  @Override
  public boolean onCharacteristicRead(BluetoothGattCharacteristic c) {
    super.onCharacteristicRead(c);

    if (!c.getUuid().toString().equals(UUID_PERIOD)) return false;

    period = TiSensorUtils.shortUnsignedAtOffset(c, 0);
    return true;
  }
Beispiel #29
0
 @Override
 public void onCharacteristicReadRequest(
     BluetoothDevice device,
     int requestId,
     int offset,
     BluetoothGattCharacteristic characteristic) {
   super.onCharacteristicReadRequest(device, requestId, offset, characteristic);
   System.out.println("onCharacteristicReadRequest " + characteristic.getUuid().toString());
 }
  public JSONObject asJSONObject(BluetoothGatt gatt) {

    JSONObject json = asJSONObject();

    try {
      JSONArray servicesArray = new JSONArray();
      JSONArray characteristicsArray = new JSONArray();
      json.put("services", servicesArray);
      json.put("characteristics", characteristicsArray);

      if (connected && gatt != null) {
        for (BluetoothGattService service : gatt.getServices()) {
          servicesArray.put(UUIDHelper.uuidToString(service.getUuid()));

          for (BluetoothGattCharacteristic characteristic : service.getCharacteristics()) {
            JSONObject characteristicsJSON = new JSONObject();
            characteristicsArray.put(characteristicsJSON);

            characteristicsJSON.put("service", UUIDHelper.uuidToString(service.getUuid()));
            characteristicsJSON.put(
                "characteristic", UUIDHelper.uuidToString(characteristic.getUuid()));
            // characteristicsJSON.put("instanceId", characteristic.getInstanceId());

            characteristicsJSON.put("properties", Helper.decodeProperties(characteristic));
            // characteristicsJSON.put("propertiesValue", characteristic.getProperties());

            if (characteristic.getPermissions() > 0) {
              characteristicsJSON.put("permissions", Helper.decodePermissions(characteristic));
              // characteristicsJSON.put("permissionsValue", characteristic.getPermissions());
            }

            JSONArray descriptorsArray = new JSONArray();

            for (BluetoothGattDescriptor descriptor : characteristic.getDescriptors()) {
              JSONObject descriptorJSON = new JSONObject();
              descriptorJSON.put("uuid", UUIDHelper.uuidToString(descriptor.getUuid()));
              descriptorJSON.put("value", descriptor.getValue()); // always blank

              if (descriptor.getPermissions() > 0) {
                descriptorJSON.put("permissions", Helper.decodePermissions(descriptor));
                // descriptorJSON.put("permissionsValue", descriptor.getPermissions());
              }
              descriptorsArray.put(descriptorJSON);
            }
            if (descriptorsArray.length() > 0) {
              characteristicsJSON.put("descriptors", descriptorsArray);
            }
          }
        }
      }
    } catch (JSONException e) { // TODO better error handling
      e.printStackTrace();
    }

    return json;
  }