private String generateHashKey(UUID serviceUUID, BluetoothGattCharacteristic characteristic) {
   return String.valueOf(serviceUUID)
       + "|"
       + characteristic.getUuid()
       + "|"
       + characteristic.getInstanceId();
 }
  // 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;
    }
  }
Пример #3
0
 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();
     }
   }
 }
  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);
  }
Пример #5
0
 public void enableNotification(int index, UUID service, UUID characteristic) {
   BluetoothGattService Service;
   BluetoothGattCharacteristic Characteristic;
   BluetoothGattDescriptor Descriptor;
   if (index < 0 || index > mBluetoothGatt.length) {
     Log.e(TAG, "Read char index out of bound");
     return;
   }
   if (mBluetoothGatt[index] == null) {
     Log.e(TAG, "GATT isn't connected");
     return;
   }
   if (service != null && characteristic != null) {
     Service = mBluetoothGatt[index].getService(service);
     if (Service == null) {
       Log.e(TAG, "Service not found");
       return;
     }
     Characteristic = Service.getCharacteristic(characteristic);
     if (Characteristic == null) {
       Log.e(TAG, "Characteristic not found");
       return;
     }
     mBluetoothGatt[index].setCharacteristicNotification(Characteristic, true);
     Descriptor = Characteristic.getDescriptor(CCCD);
     Descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
     mBluetoothGatt[index].writeDescriptor(Descriptor);
     Log.i(TAG, "CCCD set");
   }
 }
Пример #6
0
 @Override
 public void onCharacteristicRead(
     BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
   if (bleGattService.containsCharacteristic(characteristic.getUuid())) {
     callBack.onCharacteristicRead(characteristic.getUuid(), characteristic.getValue());
   }
 }
Пример #7
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 calculateAcceleration(
      BluetoothGattCharacteristic characteristic, BluetoothGatt gatt) {
    /*
     * The accelerometer has the range [-2g, 2g] with unit (1/64)g.
     *
     * To convert from unit (1/64)g to unit g we divide by 64.
     *
     * (g = 9.81 m/s^2)
     *
     * The z value is multiplied with -1 to coincide
     * with how we have arbitrarily defined the positive y direction.
     * (illustrated by the apps accelerometer image)
     *
     * -32 = -2g
     * -16 = -1g
     *  0 = 0g
     *  16 = 1g
     *  32 = 2g
     * */

    int accX = characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_SINT8, 0);
    int accY = characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_SINT8, 1);
    int accZ = characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_SINT8, 2) * -1;
    System.out.println("Acc X: " + accX + " Y: " + accY + " Z: " + accZ);
    Acceleration a = new Acceleration(accX, accY, accZ);
    acc.put(gatt.getDevice().getAddress(), a);
    setChanged();
    notifyObservers(getSensorData(gatt));
  }
        @SuppressLint("DefaultLocale")
        @Override
        public void onReceive(Context context, Intent intent) {
          final String action = intent.getAction();
          System.out.println("mGattUpdateReceiver->onReceive->action=" + action);
          if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {
            mConnected = true;
            mHandler.removeCallbacks(mConnectingOverTimeRunnable);

          } else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {
            mConnected = false;
            mConnectionState = connectionStateEnum.isToScan;
            onConectionStateChange(mConnectionState);
            mHandler.removeCallbacks(mDisonnectingOverTimeRunnable);
            mBluetoothLeService.close();
          } else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {
            // Show all the supported services and characteristics on the user interface.
            for (BluetoothGattService gattService :
                mBluetoothLeService.getSupportedGattServices()) {
              System.out.println(
                  "ACTION_GATT_SERVICES_DISCOVERED  " + gattService.getUuid().toString());
            }
            getGattServices(mBluetoothLeService.getSupportedGattServices());
          } else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
            if (mSCharacteristic == mModelNumberCharacteristic) {
              if (intent
                  .getStringExtra(BluetoothLeService.EXTRA_DATA)
                  .toUpperCase()
                  .startsWith("DF BLUNO")) {
                mBluetoothLeService.setCharacteristicNotification(mSCharacteristic, false);
                mSCharacteristic = mCommandCharacteristic;
                mSCharacteristic.setValue(mPassword);
                mBluetoothLeService.writeCharacteristic(mSCharacteristic);
                mSCharacteristic.setValue(mBaudrateBuffer);
                mBluetoothLeService.writeCharacteristic(mSCharacteristic);
                mSCharacteristic = mSerialPortCharacteristic;
                mBluetoothLeService.setCharacteristicNotification(mSCharacteristic, true);
                mConnectionState = connectionStateEnum.isConnected;
                onConectionStateChange(mConnectionState);

              } else {
                Toast.makeText(mainContext, "Please select DFRobot devices", Toast.LENGTH_SHORT)
                    .show();
                mConnectionState = connectionStateEnum.isToScan;
                onConectionStateChange(mConnectionState);
              }
            } else if (mSCharacteristic == mSerialPortCharacteristic) {
              onSerialReceived(intent.getStringExtra(BluetoothLeService.EXTRA_DATA));
            }

            System.out.println(
                "displayData " + intent.getStringExtra(BluetoothLeService.EXTRA_DATA));

            //
            //	mPlainProtocol.mReceivedframe.append(intent.getStringExtra(BluetoothLeService.EXTRA_DATA)) ;
            //            	System.out.print("mPlainProtocol.mReceivedframe:");
            //            	System.out.println(mPlainProtocol.mReceivedframe.toString());

          }
        }
Пример #10
0
 @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);
   }
 }
Пример #11
0
    @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);
        }
      }
    }
        @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);
          }
        }
        @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 + ")");
          }
        }
Пример #14
0
  /**
   * 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);
    }
  }
Пример #15
0
 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();
 }
Пример #16
0
 /** Function for writing value to characteristic */
 public void writeCharacteristic(int index, UUID service, UUID characteristic, byte[] value) {
   BluetoothGattService Service;
   BluetoothGattCharacteristic Characteristic;
   if (index < 0 || index > mBluetoothGatt.length) {
     Log.e(TAG, "Read char index out of bound");
     return;
   }
   if (mBluetoothGatt[index] == null) {
     Log.e(TAG, "GATT isn't connected");
     return;
   }
   if (service != null && characteristic != null) {
     Service = mBluetoothGatt[index].getService(service);
     if (Service == null) {
       Log.e(TAG, "Service not found");
       return;
     }
     Characteristic = Service.getCharacteristic(characteristic);
     if (Characteristic == null) {
       Log.e(TAG, "Characteristic not found");
       return;
     }
     Characteristic.setValue(value);
     // Characteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE);
     mBluetoothGatt[index].writeCharacteristic(Characteristic);
   }
 }
Пример #17
0
  public void writeCharacter(String address) {

    BluetoothGattService alarmService = null;

    BluetoothGattCharacteristic alarmCharacter = null;

    if (mBluetoothGatt != null) {
      alarmService = mBluetoothGatt.getService(SERVIE_UUID);
    }
    if (alarmService == null) {
      showMessage("link loss Alert service not found!");
      return;
    }
    alarmCharacter =
        alarmService.getCharacteristic(UUID.fromString("00002a06-0000-1000-8000-00805f9b34fb"));
    if (alarmCharacter == null) {
      connect(address);
      showMessage("link loss Alert Level charateristic not found!");
      return;
    }
    alarmCharacter.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE);
    byte[] value = {0x01};
    alarmCharacter.setValue(value);
    mBluetoothGatt.writeCharacteristic(alarmCharacter);
  }
  @Override
  public void onWriteToA007(byte[] data) {

    if ((data[3] == 0x72 || data[3] == 0x73) && isBtnFlag) {
      isBeginFlag = true;
      isBtnFlag = false;
    } else {
      isBeginFlag = false;
    }
    LogUtil.e(
        "send commond is:"
            + LogUtil.byte2HexString(data)
            + " ; isBtnFlag="
            + isBtnFlag
            + " ; isBeginFlag="
            + isBeginFlag);

    if (gattCharacteristics != null) {
      if (data != null && data.length > 0 && data[data.length - 1] != (byte) 0x00) {
        final BluetoothGattCharacteristic characteristic = gattCharacteristics.get(2);
        //                LogUtil.e("准备请求uuid:" + characteristic.getUuid());
        byte[] bytes = currentCmdPacket.getInputDataPacket();
        if (bytes != null) {
          characteristic.setValue(bytes);
        }
        bluetoothGatt.writeCharacteristic(characteristic);
      } else {
        final BluetoothGattCharacteristic characteristic = gattCharacteristics.get(0);
        //                LogUtil.e("准备请求uuid:" + characteristic.getUuid());
        bluetoothGatt.readCharacteristic(characteristic);
      }
    }
  }
Пример #19
0
 public synchronized void send(UUID uuid, byte[] value) {
   if (bluetoothGattService != null) {
     BluetoothGattCharacteristic characteristic = bluetoothGattService.getCharacteristic(uuid);
     characteristic.setValue(value);
     bluetoothGatt.writeCharacteristic(characteristic);
   }
 }
Пример #20
0
        /*
         * Enable notification of changes on the data characteristic for each sensor
         * by writing the ENABLE_NOTIFICATION_VALUE flag to that characteristic's
         * configuration descriptor.
         */
        private void setNotifyNextSensor(BluetoothGatt gatt) {
          BluetoothGattCharacteristic characteristic;
          switch (mState) {
            case 0:
              Log.d(TAG, "Set notify on Data characteristic");
              characteristic = gatt.getService(MAIN_SERVICE).getCharacteristic(DATA_CHAR);
              break;

            default:
              // mHandler.sendEmptyMessage(MSG_DISMISS);
              Log.i(TAG, "All Sensors Enabled");
              reset();
              return;
          }

          bytesp1 = new ArrayList<>();
          bytesp2 = new ArrayList<>();
          bytesv = new ArrayList<>();

          // Enable local notifications
          gatt.setCharacteristicNotification(characteristic, true);
          // Enabled remote notifications
          BluetoothGattDescriptor desc = characteristic.getDescriptor(CONFIG_DESCRIPTOR);
          desc.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
          gatt.writeDescriptor(desc);
        }
Пример #21
0
  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();
          }
        }
      }
    }
  }
Пример #22
0
        /*
         * Send an enable command to each sensor by writing a configuration
         * characteristic.  This is specific to the SensorTag to keep power
         * low by disabling sensors you aren't using.
         */
        private void enableNextSensor(BluetoothGatt gatt) {
          BluetoothGattCharacteristic characteristic;
          gatt2 = gatt;
          Log.wtf("mState is", mState + "");
          switch (mState) {
            case 0:
              Log.wtf(TAG, "Renaming");
              characteristic = gatt.getService(MAIN_SERVICE).getCharacteristic(ERROR_CHAR);

              gatt.readCharacteristic(characteristic);
              break;

            case 1:
              Log.d(TAG, "Enabling pressure cal");
              characteristic = gatt.getService(MAIN_SERVICE).getCharacteristic(CONFIG_CHAR);
              characteristic.setValue(new byte[] {0x01});
              gatt.writeCharacteristic(characteristic);
              break;

            default:
              mHandler.sendEmptyMessage(MSG_DISMISS);
              Log.i(TAG, "All Sensors Enabled");
              return;
          }
        }
Пример #23
0
 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;
          }
        }
  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);
  }
 // Called when services have been discovered on the remote device.
 // It seems to be necessary to wait for this discovery to occur before
 // manipulating any services or characteristics.
 @Override
 public void onServicesDiscovered(BluetoothGatt gatt, int status) {
   super.onServicesDiscovered(gatt, status);
   if (status == BluetoothGatt.GATT_SUCCESS) {
     // writeLine("Service discovery completed!");
   } else {
     // writeLine("Service discovery failed with status: " + status);
   }
   // Save reference to each characteristic.
   tx = gatt.getService(UART_UUID).getCharacteristic(TX_UUID);
   rx = gatt.getService(UART_UUID).getCharacteristic(RX_UUID);
   // Setup notifications on RX characteristic changes (i.e. data received).
   // First call setCharacteristicNotification to enable notification.
   if (!gatt.setCharacteristicNotification(rx, true)) {
     // writeLine("Couldn't set notifications for RX characteristic!");
   }
   // Next update the RX characteristic's client descriptor to enable notifications.
   if (rx.getDescriptor(CLIENT_UUID) != null) {
     BluetoothGattDescriptor desc = rx.getDescriptor(CLIENT_UUID);
     desc.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
     if (!gatt.writeDescriptor(desc)) {
       // writeLine("Couldn't write RX client descriptor value!");
     }
   } else {
     // writeLine("Couldn't get RX client descriptor!");
   }
 }
 @Override
 public void onCharacteristicChanged(
     BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
   if (DEBUG) Log.d(TAG, "onCharacteristicChanged: " + characteristic.toString());
   final byte[] data = characteristic.getValue();
   inTalkStream.write(data);
 }
Пример #28
0
 /**
  * sendMessage will send a message represented as a String, over the BLE if server was
  * successfully started and client has connected.
  *
  * @param msg message to be sent
  */
 public void sendMessage(String msg) {
   if (mConnectedDevice != null) {
     BluetoothGattCharacteristic characteristic =
         ServiceFactory.generateService()
             .getCharacteristic(UUID.fromString(Constants.CHAT_CHARACTERISTIC_UUID));
     characteristic.setValue(msg);
     mGattserver.notifyCharacteristicChanged(mConnectedDevice, characteristic, false);
   }
 }
  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;
  }
  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());
    }
  }