public void disconnect() {
    if (mDeviceSocket != null) {
      try {
        mDeviceSocket.close();
        mDeviceSocket = null;
      } catch (IOException e) {
        Logger.BT("ERROR: close socket failed (" + e.getMessage() + ")");
      }
    }
    if (mOutputStream != null) {
      try {
        mOutputStream.close();
        mOutputStream = null;
      } catch (IOException e) {
        Logger.BT("ERROR: close output stream failed (" + e.getMessage() + ")");
      }
    }
    if (mInputStream != null) {
      try {
        mInputStream.close();
        mInputStream = null;
      } catch (IOException e) {
        Logger.BT("ERROR: close input stream failed (" + e.getMessage() + ")");
      }
    }

    mSelectedDevice = null;
    isConnected = false;
  }
  public boolean servo(int pin, int value) {
    try {
      Logger.BT("SERVO: pin=" + pin + " value=" + value);

      mOutputStream.write(2);
      mOutputStream.write(pin);
      mOutputStream.write(value);
    } catch (IOException e) {
      Logger.BT("ERROR: failed to servo (" + e.getMessage() + ")");
      return false;
    } catch (Exception e) {
      Logger.BT("ERROR: " + e.getMessage());
      return false;
    }
    return true;
  }
  /**
   * *****************************************************************************************
   * *****************************************************************************************
   */
  public int read(int pin) {
    int value = -1;
    try {
      mOutputStream.write(0);
      mOutputStream.write(pin);
      mOutputStream.write(0);
      value = mInputStream.read();
      Logger.BT("READ: pin=" + pin + " value=" + value);

    } catch (IOException e) {
      Logger.BT("ERROR: failed to read (" + e.getMessage() + ")");
      return value;
    } catch (Exception e) {
      Logger.BT("ERROR: " + e.getMessage());
      return value;
    }
    return value;
  }
  public boolean connect(Device device) {
    cancelDiscovery();

    mDevice = getAdapter().getRemoteDevice(device.getMAC());
    mSelectedDevice = device;

    try {
      mDeviceSocket = mDevice.createRfcommSocketToServiceRecord(SPP_UUID);
    } catch (IOException e) {
      Logger.BT("ERROR: socket create failed (" + e.getMessage() + ")");
      return false;
    }

    try {
      mDeviceSocket.connect();
    } catch (IOException e) {
      Logger.BT("ERROR: open socket failed (" + e.getMessage() + ")");
      try {
        mDeviceSocket.close();
      } catch (IOException e2) {
      }
      return false;
    }

    try {
      mOutputStream = mDeviceSocket.getOutputStream();
    } catch (IOException e) {
      Logger.BT("ERROR: get output stream failed (" + e.getMessage() + ")");
      return false;
    }

    try {
      mInputStream = mDeviceSocket.getInputStream();
    } catch (IOException e) {
      Logger.BT("ERROR: get input stream failed (" + e.getMessage() + ")");
      return false;
    }

    isConnected = true;
    return true;
  }