@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);
          }
        }
        /** 收到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;
          }
        }
Exemplo n.º 3
0
  /**
   * Getting the Energy Expended
   *
   * @param characteristic
   * @return String
   */
  public static String getEnergyExpended(BluetoothGattCharacteristic characteristic) {
    int eeval = 0;

    if (isEEpresent(characteristic.getValue()[0])) {
      if (isHeartRateInUINT16(characteristic.getValue()[0])) {
        eeval = characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT16, 3);

      } else {
        eeval = characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT16, 2);
      }
    }
    return String.valueOf(eeval);
  }
Exemplo n.º 4
0
    @Override
    public void handleMessage(Message msg) {
      // process incoming messages here
      SICActivity activity = mTarget.get();

      BluetoothGattCharacteristic characteristic;

      switch (msg.what) {
        case MSG_HUMIDITY:
          characteristic = (BluetoothGattCharacteristic) msg.obj;
          if (characteristic.getValue() == null) {
            Log.w(TAG, "Error obtaining humidity value");
            return;
          }
          activity.updatePressureValue(characteristic);
          break;
        case MSG_PRESSURE:
          characteristic = (BluetoothGattCharacteristic) msg.obj;
          if (characteristic.getValue() == null) {
            Log.w(TAG, "Error obtaining pressure value");
            return;
          }
          activity.updatePressureValue(characteristic);
          break;
        case MSG_PRESSURE_CAL:
          characteristic = (BluetoothGattCharacteristic) msg.obj;
          if (characteristic.getValue() == null) {
            Log.w(TAG, "Error obtaining cal value");
            return;
          }
          break;
        case MSG_PROGRESS:
          activity.mProgress.setMessage((String) msg.obj);
          if (!activity.mProgress.isShowing()) {
            activity.mProgress.show();
          }
          break;
        case MSG_DISMISS:
          activity.mProgress.hide();
          View decorView = activity.getWindow().getDecorView();
          int uiOptions =
              View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                  | View.SYSTEM_UI_FLAG_FULLSCREEN
                  | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
          decorView.setSystemUiVisibility(uiOptions);

          break;
        case MSG_CLEAR:
          break;
      }
    }
Exemplo n.º 5
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);
 }
Exemplo n.º 6
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();
     }
   }
 }
Exemplo n.º 7
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);
   }
 }
  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 onCharacteristicChanged(
     BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
   if (DEBUG) Log.d(TAG, "onCharacteristicChanged: " + characteristic.toString());
   final byte[] data = characteristic.getValue();
   inTalkStream.write(data);
 }
Exemplo n.º 10
0
 @Override
 public void onCharacteristicRead(
     BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
   if (bleGattService.containsCharacteristic(characteristic.getUuid())) {
     callBack.onCharacteristicRead(characteristic.getUuid(), characteristic.getValue());
   }
 }
Exemplo n.º 11
0
  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);
  }
 private void calculateTempSensi(BluetoothGattCharacteristic chara, BluetoothGatt gatt) {
   byte[] data = chara.getValue();
   double fl = (double) ByteBuffer.wrap(data).order(ByteOrder.LITTLE_ENDIAN).getFloat();
   String address = gatt.getDevice().getAddress();
   temperature.put(address, fl);
   SensorData sd = getSensorData(gatt);
   setChanged();
   notifyObservers(sd);
 }
Exemplo n.º 13
0
 @Override
 public void onCharacteristicChanged(
     BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
   UUID characteristicUUID = characteristic.getUuid();
   if (MiBandService.UUID_CHARACTERISTIC_ACTIVITY_DATA.equals(characteristicUUID)) {
     handleActivityNotif(characteristic.getValue());
   } else {
     super.onCharacteristicChanged(gatt, characteristic);
   }
 }
Exemplo n.º 14
0
  private void updatePressureValue(BluetoothGattCharacteristic characteristic) {
    counter++;
    byte[] value = characteristic.getValue();

    int x = twoBytesToShort(value[0], value[1]);
    x = x >> 6;
    int y = twoBytesToShort(value[2], value[3]);
    y = y >> 6;
    int z = twoBytesToShort(value[4], value[5]);
    z = z >> 6;
    int ref = value[6];
    ref += 2048;
    int p1 = twoBytesToShort(value[7], value[8]);
    int p2 = twoBytesToShort(value[9], value[10]);
    int spi = (int) value[11];
    String s = ("0000000" + Integer.toBinaryString(0xFF & value[12])).replaceAll(".*(.{8})$", "$1");
    if (s.charAt(0) == '1') {
      fpc = true;
    }
    char[] chars = s.toCharArray();
    chars[0] = '0';
    s = String.valueOf(chars);
    byte b = Byte.parseByte(s, 2);

    int batt = b;
    battCharge = "" + batt;
    runOnUiThread(
        new Runnable() {
          public void run() {
            battLevel.setText(battCharge + "%");
          }
        });
    float mP1 = p1;
    float p1Value = (((float) .000733) * mP1);
    float mP2 = p2;
    float p2Value = (((float) .000733) * mP2);
    float mP3 = ref;
    float p3Value = (((float) .000733) * mP3);
    usl.setText((String.format("%.2f", round(p1Value, 2)) + " V"));
    lsl.setText((String.format("%.2f", round(p2Value, 2)) + " V"));
    vref.setText((String.format("%.2f", round(p3Value, 2)) + " V"));

    Integer[] values = {x, y, z, ref, p1, p2, spi, batt};
    xBar.setProgress(x + 512);
    yBar.setProgress(y + 512);
    zBar.setProgress(z + 512);
    if (logging) {
      DownloadWebPageTask task = new DownloadWebPageTask();
      task.execute(values);
    } else {
      p1Series.appendData(new DataPoint(counter, p1), true, 100);
      p2Series.appendData(new DataPoint(counter, p2), true, 100);
      vSeries.appendData(new DataPoint(counter, ref), true, 100);
    }
  }
 @Override
 public void didUpdateValueForCharacteristic(BluetoothGattCharacteristic c) {
   byte[] value = c.getValue();
   if (c.equals(this.dataC)) {
     Point3D v = Sensor.HUMIDITY.convert(value);
     if (this.tRow.config == false) this.tRow.value.setText(String.format("%.1f %%rH", v.x));
     this.tRow.sl1.maxVal = 100;
     this.tRow.sl1.minVal = 0;
     this.tRow.sl1.addValue((float) v.x);
   }
 }
Exemplo n.º 16
0
  /**
   * Getting the heart rate
   *
   * @param characteristic
   * @return String
   */
  public static String getHeartRate(BluetoothGattCharacteristic characteristic) {

    int format = -1;
    if (isHeartRateInUINT16(characteristic.getValue()[0])) {
      format = BluetoothGattCharacteristic.FORMAT_UINT16;
    } else {
      format = BluetoothGattCharacteristic.FORMAT_UINT8;
    }
    final int heartRate = characteristic.getIntValue(format, 1);
    return String.valueOf(heartRate);
  }
Exemplo n.º 17
0
 // broadcast for gatt characteristic read or notification, including device name, charateristic
 // uuid and value
 private void broadcastDataUpdate(
     final String action, String devName, BluetoothGattCharacteristic characteristic) {
   final Intent intent = new Intent(action);
   String UUID = characteristic.getUuid().toString();
   LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
   intent.putExtra(DEVICE_NAME, devName);
   intent.putExtra(CHAR_UUID, UUID);
   intent.putExtra(CHAR_VALUE, characteristic.getValue());
   Log.i("broadcast", action);
   Log.i("broadcast", devName);
   Log.i("broadcast", UUID);
 }
Exemplo n.º 18
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);
        }
 /** BLE终端数据被读的事件 */
 @Override
 public void onCharacteristicRead(
     BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
   if (status == BluetoothGatt.GATT_SUCCESS)
     Log.e(
         TAG,
         "onCharRead "
             + gatt.getDevice().getName()
             + " read "
             + characteristic.getUuid().toString()
             + " -> "
             + Utils.bytesToHexString(characteristic.getValue()));
 }
Exemplo n.º 20
0
  @Override
  public void onCharacteristicChanged(
      BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
    super.onCharacteristicChanged(gatt, characteristic);

    // Log.d(LOG_TAG, "onCharacteristicChanged " + characteristic);
    byte[] dataValue = characteristic.getValue();
    Log.d(LOG_TAG, "Letto:" + BleManager.bytesToHex(dataValue) + " da:" + device.getAddress());

    WritableMap map = Arguments.createMap();
    map.putString("peripheral", device.getAddress());
    map.putString("characteristic", characteristic.getUuid().toString());
    map.putString("value", BleManager.bytesToHex(dataValue));
    sendEvent("BleManagerDidUpdateValueForCharacteristic", map);
  }
Exemplo n.º 21
0
  public static void updateValueForNotification(
      BluetoothGatt bluetoothGatt, BluetoothGattCharacteristic characteristic) {
    if (bluetoothGatt == null || characteristic == null) {
      Log.e(TAG, "invalid arguments");
      return;
    }
    if (!NotifyEnabled) {
      Log.e(TAG, "The notifyCharacteristic not enabled");
      return;
    }
    String strUUIDForNotifyChar = characteristic.getUuid().toString();
    final byte[] qppData = characteristic.getValue();

    if (qppData != null && qppData.length > 0)
      iQppCallback.onQppReceiveData(bluetoothGatt, strUUIDForNotifyChar, qppData);
  }
Exemplo n.º 22
0
 /**
  * Getting the RR-Interval
  *
  * @param characteristic
  * @return ArrayList
  */
 public static ArrayList<Integer> getRRInterval(BluetoothGattCharacteristic characteristic) {
   ArrayList<Integer> rrinterval = new ArrayList<Integer>();
   int length = characteristic.getValue().length;
   if (isEEpresent(characteristic.getValue()[0])) {
     if (isHeartRateInUINT16(characteristic.getValue()[0])) {
       if (isRRintpresent(characteristic.getValue()[0])) {
         int startoffset = 5;
         for (int i = startoffset; i < length; i += 2) {
           rrinterval.add(
               characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT16, i));
         }
       }
     } else {
       if (isRRintpresent(characteristic.getValue()[0])) {
         int startoffset = 4;
         for (int i = startoffset; i < length; i += 2) {
           rrinterval.add(
               characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT16, i));
         }
       }
     }
   } else {
     if (isHeartRateInUINT16(characteristic.getValue()[0])) {
       if (isRRintpresent(characteristic.getValue()[0])) {
         int startoffset = 3;
         for (int i = startoffset; i < length; i += 2) {
           rrinterval.add(
               characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT16, i));
         }
       }
     } else {
       if (isRRintpresent(characteristic.getValue()[0])) {
         int startoffset = 2;
         for (int i = startoffset; i < length; i += 2) {
           rrinterval.add(
               characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT16, i));
         }
       }
     }
   }
   return rrinterval;
 }
  @Override
  public synchronized void onDataAvailable(BluetoothGattCharacteristic characteristic) {
    // UART RX
    if (characteristic.getService().getUuid().toString().equalsIgnoreCase(UUID_SERVICE)) {
      if (characteristic.getUuid().toString().equalsIgnoreCase(UUID_RX)) {
        final byte[] bytes = characteristic.getValue();
        final String data = new String(bytes, Charset.forName("UTF-8"));

        mReceivedBytes += bytes.length;

        final UartDataChunk dataChunk =
            new UartDataChunk(System.currentTimeMillis(), UartDataChunk.TRANSFERMODE_RX, data);
        mDataBuffer.add(dataChunk);
        final String formattedData = mShowDataInHexFormat ? asciiToHex(data) : data;

        runOnUiThread(
            new Runnable() {
              @Override
              public void run() {
                if (mIsTimestampDisplayMode) {
                  final String currentDateTimeString =
                      DateFormat.getTimeInstance().format(new Date(dataChunk.getTimestamp()));

                  mBufferListAdapter.add(
                      new TimestampData(
                          "[" + currentDateTimeString + "] TX: " + formattedData, mRxColor));
                  // mBufferListAdapter.add("[" + currentDateTimeString + "] RX: " + formattedData);
                  // mBufferListView.smoothScrollToPosition(mBufferListAdapter.getCount() - 1);
                  mBufferListView.setSelection(mBufferListAdapter.getCount());
                }
                updateUI();
              }
            });

        // MQTT publish to RX
        MqttSettings settings = MqttSettings.getInstance(UartActivity.this);
        if (settings.isPublishEnabled()) {
          String topic = settings.getPublishTopic(MqttUartSettingsActivity.kPublishFeed_RX);
          final int qos = settings.getPublishQos(MqttUartSettingsActivity.kPublishFeed_RX);
          mMqttManager.publish(topic, data, qos);
        }
      }
    }
  }
        @Override
        public void onCharacteristicNotified(
            final BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic) {
          if (mLogSession != null)
            Logger.a(mLogSession, CSCMeasurementParser.parse(characteristic));

          // Decode the new data
          int offset = 0;
          final int flags = characteristic.getValue()[offset]; // 1 byte
          offset += 1;

          final boolean wheelRevPresent = (flags & WHEEL_REVOLUTIONS_DATA_PRESENT) > 0;
          final boolean crankRevPreset = (flags & CRANK_REVOLUTION_DATA_PRESENT) > 0;

          if (wheelRevPresent) {
            final int wheelRevolutions =
                characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT32, offset);
            offset += 4;

            final int lastWheelEventTime =
                characteristic.getIntValue(
                    BluetoothGattCharacteristic.FORMAT_UINT16, offset); // 1/1024 s
            offset += 2;

            // Notify listener about the new measurement
            mCallbacks.onWheelMeasurementReceived(wheelRevolutions, lastWheelEventTime);
          }

          if (crankRevPreset) {
            final int crankRevolutions =
                characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT16, offset);
            offset += 2;

            final int lastCrankEventTime =
                characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT16, offset);
            // offset += 2;

            // Notify listener about the new measurement
            mCallbacks.onCrankMeasurementReceived(crankRevolutions, lastCrankEventTime);
          }
        }
Exemplo n.º 25
0
  private void activateLED(int led) {
    BluetoothGattCharacteristic characteristic;
    // new byte [] finisher = 0x01;

    characteristic = gatt2.getService(MAIN_SERVICE).getCharacteristic(FINISH);
    if (led == 1) {
      maintChar ^= 1 << 5;
    }
    if (led == 2) {
      maintChar ^= 1 << 4;
    }
    if (led == 3) {
      maintChar ^= 1 << 3;
    }
    if (led == 4) {
      maintChar ^= 1 << 2;
    }
    characteristic.setValue(new byte[] {maintChar});
    Log.wtf(TAG, "Value is: " + characteristic.getValue().toString());
    gatt2.writeCharacteristic(characteristic);
  }
  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_LUGGAGE_NTF.equals(characteristic.getUuid())) {
      final String recData = characteristic.getStringValue(0);
      Log.d(TAG, String.format("Received heart rate: %s", recData));
      intent.putExtra(EXTRA_DATA, recData);
    } 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);
  }
Exemplo n.º 27
0
 private void decodeData(BluetoothGattCharacteristic characteristic) {
   if (Characteristic.OXIMETER.equals(characteristic.getUuid())) {
     byte[] value = characteristic.getValue();
     String byteStr = Utils.bytesToHexString(value);
     int length = byteStr.length();
     if (length == 16 && byteStr.startsWith("fe0856")) {
       Log.d(TAG, "Wave:" + byteStr);
     }
     if (length > 16) {
       int index = byteStr.indexOf("fe0a55");
       if (length >= index + 20) {
         String result = byteStr.substring(index, index + 20);
         int pr = Integer.parseInt(result.substring(6, 10), 16);
         int spo2 = Integer.parseInt(result.substring(10, 12), 16);
         int pi = Integer.parseInt(result.substring(12, 16), 16) / 1000;
         if (pr < 301 && pr > 0) {
           int[] data = new int[] {pr, spo2, pi};
           postData(data);
         }
       }
     }
   }
 }
Exemplo n.º 28
0
  public static String getBodySensorLocation(BluetoothGattCharacteristic characteristic) {
    String body_sensor_location = "";
    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));
      int body_sensor = Integer.valueOf(stringBuilder.toString().trim());
      switch (body_sensor) {
        case 0:
          body_sensor_location = "Other";
          break;
        case 1:
          body_sensor_location = "Chest";
          break;
        case 2:
          body_sensor_location = "Wrist";
          break;
        case 3:
          body_sensor_location = "Finger";
          break;
        case 4:
          body_sensor_location = "Hand";
          break;
        case 5:
          body_sensor_location = "Ear Lobe";
          break;
        case 6:
          body_sensor_location = "Foot";
          break;

        default:
          body_sensor_location = "Reserved for future use";
          break;
      }
    }
    return body_sensor_location;
  }
Exemplo n.º 29
0
  @Override
  public void onCharacteristicRead(
      BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
    super.onCharacteristicRead(gatt, characteristic, status);
    Log.d(LOG_TAG, "onCharacteristicRead " + characteristic);

    if (readCallback != null) {

      if (status == BluetoothGatt.GATT_SUCCESS) {
        byte[] dataValue = characteristic.getValue();
        String value = BleManager.bytesToHex(dataValue);

        if (readCallback != null) {
          readCallback.invoke(value);
          readCallback = null;
        }
      } else {
        readFailCallback.invoke("Error reading " + characteristic.getUuid() + " status=" + status);
        readFailCallback = null;
      }

      readCallback = null;
    }
  }
Exemplo n.º 30
0
        @Override
        public void onCharacteristicChanged(
            BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic) {

          byte[] buffer = characteristic.getValue();
          // send the next letter of the word when the previous letter has been sent back
          if (buffer[0] == motEcrit.charAt(indiceMotEcrit) && buffer[0] != 13) {
            Log.i(tag, "         return = " + motEcrit.charAt(indiceMotEcrit));
            indiceMotEcrit++;
            writeLetter();
          } else if (buffer[0] == 13) {
            writeOccupied = false;
            Log.i(tag, "fin du mot");
          }

          try {
            String str = new String(buffer, "UTF-8");
            Log.i(tag, "recu = " + str);
            receivedWord = str;

          } catch (UnsupportedEncodingException e) {
            Log.e(tag, "e = " + e);
          }
        }