/*
   * Opens the bluetooth connection with the specified port name
   */
  public void open(String port) {
    synchronized (this.lock) {
      String error_message = null;
      try {
        BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
        adapter.cancelDiscovery();
        Set<BluetoothDevice> paired_devices = adapter.getBondedDevices();
        for (BluetoothDevice device : paired_devices) {
          String name = device.getName();
          if (name.equals(port)) {
            Log.i("BluetoothConnection", "trying " + name);

            ConnectThread ct = new ConnectThread(device);
            ct.start();
            ct.join(5000);
            error_message = ct.errorMessage;
            break;
          }
        }
        if (this.socket != null) {
          this.recv_stream = this.socket.getInputStream();
          this.send_stream = this.socket.getOutputStream();
          this.reader = new BufferedReader(new InputStreamReader(this.recv_stream, "UTF-8"));
          Log.i("BluetoothConnection", "Socket Ready");
        } else {
          error_message = "Could not detect device " + port + ": " + String.valueOf(error_message);
        }
      } catch (Exception e) {
        error_message = "Error opening Bluetooth socket: " + e.getMessage();
      }

      if (this.socket == null) {
        throw new RuntimeException(
            "Error opening Bluetooth port: " + String.valueOf(error_message));
      }
    }
  }