Пример #1
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;
          }
        }
Пример #2
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);
  }
 // 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!");
   }
 }
Пример #4
0
  public BluetoothGattService getSupportedGattService() {
    if (mBluetoothGatt == null) {
      LogUtil.info(TAG, "mBluetoothGatt is  null ,try reconnect!");
      boolean isconnectok = connect();
      if (!isconnectok) {
        connect();
      }
      return null;
    }
    String UUID_SERVICE;
    switch (DEVICE_TYPE) {
      case 1: // 脂肪秤
        UUID_SERVICE = BLEConstants.UUID_FATSCALE_SERVICE;
        break;
      case 2: // 血压计
        UUID_SERVICE = BLEConstants.UUID_BLOOD_PRESSURE_SERVICE;
        break;
      case 3: // 血糖仪
        UUID_SERVICE = BLEConstants.UUID_BLOODSUGAR_SERVICE;
        break;
      default:
        UUID_SERVICE = BLEConstants.UUID_FATSCALE_SERVICE;
        break;
    }

    LogUtil.info(TAG, "device type=" + DEVICE_TYPE);
    BluetoothGattService service = mBluetoothGatt.getService(UUID.fromString(UUID_SERVICE));
    return service;
  }
Пример #5
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);
        }
  public void removeNotify(
      UUID serviceUUID, UUID characteristicUUID, Callback success, Callback fail) {

    Log.d(LOG_TAG, "removeNotify");

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

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

    if (characteristic != null) {

      if (gatt.setCharacteristicNotification(characteristic, false)) {
        success.invoke();
      } else {
        // TODO we can probably ignore and return success anyway since we removed the notification
        // callback
        fail.invoke("Failed to stop notification for " + characteristicUUID);
      }

    } else {
      fail.invoke("Characteristic " + characteristicUUID + " not found");
    }
  }
Пример #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;
  }
Пример #8
0
 @Override
 public boolean isRequiredServiceSupported(final BluetoothGatt gatt) {
   final BluetoothGattService service = gatt.getService(UART_SERVICE_UUID);
   if (service != null) {
     mTXCharacteristic = service.getCharacteristic(UART_TX_CHARACTERISTIC_UUID);
     mRXCharacteristic = service.getCharacteristic(UART_RX_CHARACTERISTIC_UUID);
   }
   return mTXCharacteristic != null && mRXCharacteristic != null;
 }
 @Override
 public boolean isRequiredServiceSupported(final BluetoothGatt gatt) {
   final BluetoothGattService service =
       gatt.getService(CYCLING_SPEED_AND_CADENCE_SERVICE_UUID);
   if (service != null) {
     mCSCMeasurementCharacteristic =
         service.getCharacteristic(CSC_MEASUREMENT_CHARACTERISTIC_UUID);
   }
   return mCSCMeasurementCharacteristic != null;
 }
Пример #10
0
  public void writeLetter() {

    char letter = motEcrit.charAt(indiceMotEcrit);
    Log.i(tag, "         envoie  = " + letter);
    sendByte = new String(new char[] {letter}).getBytes();
    BluetoothGattCharacteristic characteristic =
        bluetoothGatt.getService(SERVICE).getCharacteristic(CHARACTERISTIC);
    characteristic.setValue(sendByte);
    bluetoothGatt.writeCharacteristic(characteristic);
  }
Пример #11
0
 @Override
 public void onServicesDiscovered(BluetoothGatt gatt, int status) {
   BluetoothGattService mOximeterMeasurement = gatt.getService(Service.OXIMETER);
   if (mOximeterMeasurement != null) {
     BluetoothGattCharacteristic characteristic =
         mOximeterMeasurement.getCharacteristic(Characteristic.OXIMETER);
     if (characteristic != null) {
       setCharacteristic(gatt, characteristic, BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
     }
   }
 }
  private void turnOnService(BluetoothGatt gatt, UUID serviceUUID, UUID configUUID) {

    BluetoothGattService humService = gatt.getService(serviceUUID);
    BluetoothGattCharacteristic config = humService.getCharacteristic(configUUID);
    config.setValue(
        new byte[] {
          1
        }); // 01 for Humidity; 01 for +-2g deviation//NB: the config value is different for the
            // Gyroscope
    gatt.writeCharacteristic(config);
  }
Пример #13
0
        private void disableSensors(BluetoothGatt gatt) {
          SICRunning = false;
          BluetoothGattCharacteristic characteristic;
          Log.d(TAG, "Disabling Sensors");
          characteristic = gatt.getService(MAIN_SERVICE).getCharacteristic(CONFIG_CHAR);
          byte finisher = 0x00;
          characteristic.setValue(new byte[] {finisher});

          gatt.writeCharacteristic(characteristic);
          sicAct.stillRunning = true;
        }
  private void enableNotifications(BluetoothGatt gatt, UUID serviceUuid, UUID dataUuid) {
    UUID CCC = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb");

    BluetoothGattService service = gatt.getService(serviceUuid);
    BluetoothGattCharacteristic dataCharacteristic = service.getCharacteristic(dataUuid);
    gatt.setCharacteristicNotification(dataCharacteristic, true); // Enabled locally

    BluetoothGattDescriptor config = dataCharacteristic.getDescriptor(CCC);
    config.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
    gatt.writeDescriptor(config); // Enabled remotely
  }
Пример #15
0
 @Override
 public void onServicesDiscovered(final BluetoothGatt gatt, final int status) {
   Log.i(tag, "onServicesDiscovered");
   BluetoothGattCharacteristic characteristic =
       gatt.getService(SERVICE).getCharacteristic(CHARACTERISTIC);
   if (characteristic != null) {
     gatt.setCharacteristicNotification(characteristic, true);
     bluetoothGatt = gatt;
     characFound = true;
   } else characFound = false;
   connected = true;
 }
Пример #16
0
        private void writeSecurity(BluetoothGatt gatt) {
          Log.wtf(TAG, "Security Written");
          BluetoothGattCharacteristic securityCharacteristic = null;
          byte[] packet = new byte[1];
          int i = 153;

          packet[0] = (byte) i;
          securityCharacteristic = gatt.getService(MAIN_SERVICE).getCharacteristic(SECURITY_KEY);
          securityCharacteristic.setValue(packet);
          Log.wtf(TAG, packet[0] + "");
          gatt.writeCharacteristic(securityCharacteristic);
        }
Пример #17
0
 @Override
 public void onServicesDiscovered(BluetoothGatt gatt, int status) {
   if (gatt != null && status == BluetoothGatt.GATT_SUCCESS) {
     bluetoothGattService = gatt.getService(bleGattService.getServiceUUID());
     if (bluetoothGattService != null
         && bleGattService.initializeCharacteristics(bluetoothGattService, gatt)) {
       callBack.onConnected();
       return;
     }
   }
   close();
 }
 @Override
 public boolean isRequiredServiceSupported(final BluetoothGatt gatt) {
   final BluetoothGattService service = gatt.getService(GLS_SERVICE_UUID);
   if (service != null) {
     mGlucoseMeasurementCharacteristic = service.getCharacteristic(GM_CHARACTERISTIC);
     mGlucoseMeasurementContextCharacteristic =
         service.getCharacteristic(GM_CONTEXT_CHARACTERISTIC);
     mRecordAccessControlPointCharacteristic =
         service.getCharacteristic(RACP_CHARACTERISTIC);
   }
   return mGlucoseMeasurementCharacteristic != null
       && mRecordAccessControlPointCharacteristic != null;
 }
 private boolean checkCloudWatchServiceSupported(BluetoothGatt gatt) {
   BluetoothGattService cloudWatchGattService =
       gatt.getService(UUID.fromString(BleUuid.SERVICE_DEVICE_INFORMATION));
   if (cloudWatchGattService == null) {
     LogTool.e(TAG, "Cloud Watch Service不支持");
   } else {
     BluetoothGattCharacteristic rfcommCharacteristic =
         cloudWatchGattService.getCharacteristic(
             UUID.fromString(BleUuid.CHAR_MANUFACTURER_NAME_STRING));
     if (rfcommCharacteristic == null) {
       LogTool.e(TAG, "RFCOMM BLUETOOTH COMMAND不支持");
     } else {
       gatt.setCharacteristicNotification(rfcommCharacteristic, true);
     }
     BluetoothGattCharacteristic heartbeatCharacteristic =
         cloudWatchGattService.getCharacteristic(
             UUID.fromString(BleUuid.CHAR_MODEL_NUMBER_STRING));
     if (heartbeatCharacteristic == null) {
       LogTool.e(TAG, "HEARTBEAT OR DISCONNECT COMMAND不支持");
     } else {
       gatt.setCharacteristicNotification(heartbeatCharacteristic, true);
     }
   }
   BluetoothGattService currentTimeGattService =
       gatt.getService(UUID.fromString(BleUuid.SERVICE_CURRENT_TIME));
   if (currentTimeGattService == null) {
     LogTool.e(TAG, "Current Time Service不支持");
   } else {
     BluetoothGattCharacteristic syncTimeCharacteristic =
         currentTimeGattService.getCharacteristic(UUID.fromString(BleUuid.CHAR_CURRENT_TIME));
     if (syncTimeCharacteristic == null) {
       LogTool.e(TAG, "SYNCTIME COMMAND不支持");
     } else {
       gatt.setCharacteristicNotification(syncTimeCharacteristic, true);
     }
   }
   return true;
 }
Пример #20
0
  /**
   * When the device is bonded and has the Generic Attribute service and the Service Changed
   * characteristic this method enables indications on this characteristic. In case one of the
   * requirements is not fulfilled this method returns <code>false</code>.
   *
   * @param gatt the gatt device with services discovered
   * @return <code>true</code> when the request has been sent, <code>false</code> when the device is
   *     not bonded, does not have the Generic Attribute service, the GA service does not have the
   *     Service Changed characteristic or this characteristic does not have the CCCD.
   */
  private boolean ensureServiceChangedEnabled(final BluetoothGatt gatt) {
    if (gatt == null) return false;

    // The Service Changed indications have sense only on bonded devices
    final BluetoothDevice device = gatt.getDevice();
    if (device.getBondState() != BluetoothDevice.BOND_BONDED) return false;

    final BluetoothGattService gaService = gatt.getService(GENERIC_ATTRIBUTE_SERVICE);
    if (gaService == null) return false;

    final BluetoothGattCharacteristic scCharacteristic =
        gaService.getCharacteristic(SERVICE_CHANGED_CHARACTERISTIC);
    if (scCharacteristic == null) return false;

    Logger.i(mLogSession, "Service Changed characteristic found on a bonded device");
    return enableIndications(scCharacteristic);
  }
Пример #21
0
  /**
   * This method tries to enable notifications on the Battery Level characteristic.
   *
   * @param enable <code>true</code> to enable battery notifications, false to disable
   * @return true if request has been sent
   */
  public boolean setBatteryNotifications(final boolean enable) {
    final BluetoothGatt gatt = mBluetoothGatt;
    if (gatt == null) {
      return false;
    }

    final BluetoothGattService batteryService = gatt.getService(BATTERY_SERVICE);
    if (batteryService == null) return false;

    final BluetoothGattCharacteristic batteryLevelCharacteristic =
        batteryService.getCharacteristic(BATTERY_LEVEL_CHARACTERISTIC);
    if (batteryLevelCharacteristic == null) return false;

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

    gatt.setCharacteristicNotification(batteryLevelCharacteristic, enable);
    final BluetoothGattDescriptor descriptor =
        batteryLevelCharacteristic.getDescriptor(CLIENT_CHARACTERISTIC_CONFIG_DESCRIPTOR_UUID);
    if (descriptor != null) {
      if (enable) {
        descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
        Logger.a(mLogSession, "Enabling battery level notifications...");
        Logger.v(mLogSession, "Enabling notifications for " + BATTERY_LEVEL_CHARACTERISTIC);
        Logger.d(
            mLogSession,
            "gatt.writeDescriptor("
                + CLIENT_CHARACTERISTIC_CONFIG_DESCRIPTOR_UUID
                + ", value=0x01-00)");
      } else {
        descriptor.setValue(BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE);
        Logger.a(mLogSession, "Disabling battery level notifications...");
        Logger.v(mLogSession, "Disabling notifications for " + BATTERY_LEVEL_CHARACTERISTIC);
        Logger.d(
            mLogSession,
            "gatt.writeDescriptor("
                + CLIENT_CHARACTERISTIC_CONFIG_DESCRIPTOR_UUID
                + ", value=0x00-00)");
      }
      return gatt.writeDescriptor(descriptor);
    }
    return false;
  }
Пример #22
0
  /**
   * Reads the battery level from the device.
   *
   * @return true if request has been sent
   */
  public final boolean readBatteryLevel() {
    final BluetoothGatt gatt = mBluetoothGatt;
    if (gatt == null) return false;

    final BluetoothGattService batteryService = gatt.getService(BATTERY_SERVICE);
    if (batteryService == null) return false;

    final BluetoothGattCharacteristic batteryLevelCharacteristic =
        batteryService.getCharacteristic(BATTERY_LEVEL_CHARACTERISTIC);
    if (batteryLevelCharacteristic == null) return false;

    // Check characteristic property
    final int properties = batteryLevelCharacteristic.getProperties();
    if ((properties & BluetoothGattCharacteristic.PROPERTY_READ) == 0) {
      return setBatteryNotifications(true);
    }

    Logger.a(mLogSession, "Reading battery level...");
    return readCharacteristic(batteryLevelCharacteristic);
  }
        /*
         * from Samsung HRPService.java
         */
        private void DummyReadForSecLevelCheck(BluetoothGatt btGatt) {
          if (btGatt == null) return;

          BluetoothGattService disService = btGatt.getService(DIS_UUID);
          if (disService == null) {
            reportConnectFailed("Dis service not found");
            return;
          }
          BluetoothGattCharacteristic firmwareIdCharc =
              disService.getCharacteristic(FIRMWARE_REVISON_UUID);
          if (firmwareIdCharc == null) {
            reportConnectFailed("firmware revison charateristic not found!");
            return;
          }

          if (btGatt.readCharacteristic(firmwareIdCharc) == false) {
            reportConnectFailed("firmware revison reading is failed!");
          }
          // continue in onCharacteristicRead
        }
Пример #24
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);
  }
Пример #25
0
  public void readBatteryCharacteristic() {
    if (mBluetoothAdapter == null || mBluetoothGatt == null) {
      Log.w(TAG, "BluetoothAdapter not initialized");
      return;
    }
    BluetoothGattService alarmService = null;

    BluetoothGattCharacteristic batteryCharacter = null;

    if (mBluetoothGatt != null) {
      alarmService = mBluetoothGatt.getService(BATTERY_SERVICE_UUID);
    }

    if (alarmService != null) {
      batteryCharacter =
          alarmService.getCharacteristic(UUID.fromString("00002a19-0000-1000-8000-00805f9b34fb"));
    }

    if (batteryCharacter != null) {
      mBluetoothGatt.readCharacteristic(batteryCharacter);
    }
  }
  public void read(
      UUID serviceUUID, UUID characteristicUUID, Callback successCallback, Callback failCallback) {

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

    BluetoothGattService service = gatt.getService(serviceUUID);
    BluetoothGattCharacteristic characteristic =
        findReadableCharacteristic(service, characteristicUUID);

    if (characteristic == null) {
      failCallback.invoke("Characteristic " + characteristicUUID + " not found.");
    } else {
      readCallback = successCallback;
      readFailCallback = failCallback;
      if (!gatt.readCharacteristic(characteristic)) {
        readCallback = null;
        failCallback.invoke("Read failed");
      }
    }
  }
        private void startHR() {
          BluetoothGattService mHRP = btGatt.getService(HRP_SERVICE);
          if (mHRP == null) {
            reportConnectFailed("HRP service not found!");
            return;
          }

          BluetoothGattCharacteristic mHRMcharac =
              mHRP.getCharacteristic(HEART_RATE_MEASUREMENT_CHARAC);
          if (mHRMcharac == null) {
            reportConnectFailed("HEART RATE MEASUREMENT charateristic not found!");
            return;
          }
          BluetoothGattDescriptor mHRMccc = mHRMcharac.getDescriptor(CCC);
          if (mHRMccc == null) {
            reportConnectFailed("CCC for HEART RATE MEASUREMENT charateristic not found!");
            return;
          }
          if (btGatt.readDescriptor(mHRMccc) == false) {
            reportConnectFailed("readDescriptor() is failed");
            return;
          }
          // Continue in onDescriptorRead
        }
  @Override
  public void disconnect() {
    if (btGatt == null) return;

    if (btDevice == null) {
      return;
    }

    boolean isConnected = mIsConnected;
    if (mIsConnecting == false && mIsConnected == false) return;

    if (mIsDisconnecting == true) return;

    mIsConnected = false;
    mIsConnecting = false;
    mIsDisconnecting = true;

    do {
      BluetoothGattService mHRP = btGatt.getService(HRP_SERVICE);
      if (mHRP == null) {
        reportDisconnectFailed("HRP service not found!");
        break;
      }

      BluetoothGattCharacteristic mHRMcharac =
          mHRP.getCharacteristic(HEART_RATE_MEASUREMENT_CHARAC);
      if (mHRMcharac == null) {
        reportDisconnectFailed("HEART RATE MEASUREMENT charateristic not found!");
        break;
      }

      if (!enableNotification(false, mHRMcharac)) {
        reportDisconnectFailed("disableNotfication");
        break;
      }
    } while (false);

    btGatt.disconnect();

    if (isConnected) {
      System.out.println("close btGatt in onConnectionState");
      // close btGatt in onConnectionState
      synchronized (this) {
        long end = System.currentTimeMillis() + 2000; // wait max 2
        // seconds
        while (btGatt != null && System.currentTimeMillis() < end) {
          System.out.println("waiting for btGatt to become null");
          try {
            this.wait(500);
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
        }
        BluetoothGatt copy = btGatt;
        if (copy != null) {
          System.out.println("close btGatt in disconnect() after waiting 2 secs");
          copy.close();
          btGatt = null;
        }
      }
    } else {
      System.out.println("close btGatt here in disconnect()");
      btGatt.close();
      btGatt = null;
    }

    btDevice = null;
    mIsDisconnecting = false;
  }
  // This seems way too complicated
  public void registerNotify(
      UUID serviceUUID, UUID characteristicUUID, Callback success, Callback fail) {

    Log.d(LOG_TAG, "registerNotify");

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

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

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

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

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

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

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

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

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

    } else {
      fail.invoke("Characteristic " + characteristicUUID + " not found");
    }
  }
  public void write(
      UUID serviceUUID,
      UUID characteristicUUID,
      byte[] data,
      Callback successCallback,
      Callback failCallback,
      int writeType) {

    Log.d(LOG_TAG, "write interno peripheral");

    if (gatt == null) {
      failCallback.invoke("BluetoothGatt is null");

    } else {

      BluetoothGattService service = gatt.getService(serviceUUID);
      BluetoothGattCharacteristic characteristic =
          findWritableCharacteristic(service, characteristicUUID, writeType);
      characteristic.setWriteType(writeType);

      if (characteristic == null) {
        failCallback.invoke("Characteristic " + characteristicUUID + " not found.");
      } else {

        if (writeQueue.size() > 0) {
          failCallback.invoke("Scrittura con byte ancora in coda");
        }

        if (writeCallback != null) {
          failCallback.invoke("Altra scrittura in corso");
        }

        if (writeQueue.size() == 0 && writeCallback == null) {

          if (BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT == writeType) {
            writeCallback = successCallback;
            writeFailCallback = failCallback;
          } else successCallback.invoke();

          if (data.length > 20) {
            int dataLength = data.length;
            int count = 0;
            byte[] firstMessage = null;
            while (count < dataLength && (dataLength - count > 20)) {
              if (count == 0) {
                firstMessage = Arrays.copyOfRange(data, count, count + 20);
              } else {
                byte[] splitMessage = Arrays.copyOfRange(data, count, count + 20);
                writeQueue.add(splitMessage);
              }
              count += 20;
            }
            if (count < dataLength) {
              // Rimangono byte in coda
              byte[] splitMessage = Arrays.copyOfRange(data, count, data.length);
              Log.d(LOG_TAG, "Lunghezza ultimo messaggio: " + splitMessage.length);
              writeQueue.add(splitMessage);
            }

            Log.d(LOG_TAG, "Messaggi in coda: " + writeQueue.size());
            doWrite(characteristic, firstMessage);
          } else {
            characteristic.setValue(data);

            if (gatt.writeCharacteristic(characteristic)) {
              Log.d(LOG_TAG, "write completato");
            } else {
              writeCallback = null;
              failCallback.invoke("Write failed");
            }
          }
        }
      }
    }
  }