private void decideDirection(ArrayList<String> matches) {
    int position = -1;

    for (String phrase : matches) {

      position = commands.indexOf(phrase.toLowerCase());
      if (position != -1) {
        break;
      }
    }

    if (position != -1) {
      Utilities.setDirectionImage(commands.get(position).toUpperCase(), ivDirection, bt);
      textToSpeech.speak(
          "EXECUTING COMMAND " + commands.get(position).toUpperCase(),
          TextToSpeech.QUEUE_FLUSH,
          null);
      ((TextView) findViewById(R.id.tvResults)).setText(commands.get(position).toUpperCase());
      command = commands.get(position).toUpperCase();
    } else {
      Utilities.setDirectionImage("STOP", ivDirection, bt);
      textToSpeech.speak("NO COMMAND DETECTED STOPPING", TextToSpeech.QUEUE_FLUSH, null);
      ((TextView) findViewById(R.id.tvResults)).setText("STOP");
      command = "STOP";
    }
  }
  public void clearRouteClicked(View view) {
    mMap.clear();
    tvDistance.setText("---m");
    if (running) running = Utilities.playStopButtonHandler(route, running, ivPlayStop, this);

    route.clearRoute();

    Utilities.setDirectionImage("STOP", ivDirection, bt);
  }
            @Override
            public boolean handleMessage(Message msg) {
              switch (msg.what) {
                case Bluetooth.MESSAGE_STATE_CHANGE:
                  Log.d(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);
                  break;
                case Bluetooth.MESSAGE_WRITE:
                  Log.d(TAG, "MESSAGE_WRITE ");
                  break;
                case Bluetooth.MESSAGE_READ:
                  byte[] readBuf = (byte[]) msg.obj;
                  String strIncom = new String(readBuf, 0, msg.arg1);
                  sb.append(strIncom);
                  int endOfLineIndex = sb.indexOf("\r\n"); // determine the end-of-line
                  if (endOfLineIndex > 0) { // if end-of-line,
                    String sbprint = sb.substring(0, endOfLineIndex); // extract string
                    sb.delete(0, sb.length()); // and clear

                    Log.d("READ_FROM_ARDUINO", sbprint + "");
                    try {

                      distanceToObstacle =
                          Utilities.normalizeReadingsFromDistanceSensor(
                              Integer.parseInt(sbprint), distanceToObstacle);

                      Log.d("READ_FROM_ARDUINO_NORM", distanceToObstacle + "");
                      tvDistance.setText(distanceToObstacle + "cm");
                      if (distanceToObstacle < 40 && !(command.equals("STOP"))) {
                        Utilities.setDirectionImage("STOP", ivDirection, bt);
                        textToSpeech.speak(
                            "YOU ARE ABOUT TO HIT AN OBSTACLE STOPPING",
                            TextToSpeech.QUEUE_FLUSH,
                            null);
                        ((TextView) findViewById(R.id.tvResults)).setText("STOP");
                        command = "STOP";
                      }
                      // distanceToObstacle = Integer.parseInt(sbprint);
                    } catch (Exception e) {
                      e.printStackTrace();
                      Log.e(TAG, "handleMessage: CRASH CONVERSION");
                    }
                  }
                  break;
                case Bluetooth.MESSAGE_DEVICE_NAME:
                  Log.d(TAG, "MESSAGE_DEVICE_NAME " + msg);
                  break;
                case Bluetooth.MESSAGE_TOAST:
                  Log.d(TAG, "MESSAGE_TOAST " + msg);
                  break;
              }
              return false;
            }
  @Override
  public void onBackPressed() {
    super.onBackPressed();

    Utilities.setDirectionImage("STOP", ivDirection, bt);
    bt.stop();
  }
 @Override
 public void onMapReady(GoogleMap googleMap) {
   mMap = googleMap;
   mMap.setMapType(Utilities.getMapType(this));
   mMap.getUiSettings().setZoomControlsEnabled(true);
   mMap.setOnMapClickListener(this);
 }
  public void onDestroy() {
    super.onDestroy();

    Utilities.setDirectionImage("STOP", ivDirection, bt);
    bt.stop();

    recognizer.cancel();
    recognizer.shutdown();
  }
 public void showMyLocationClicked(View view) {
   robotMarker =
       MapUtilities.placeRobotMarkerOnMap(
           robotMarker,
           mMap,
           Utilities.convertLocationToLatLng(robotLocation),
           true,
           getResources(),
           getApplicationContext());
 }
  @Override
  public void onSensorChanged(SensorEvent event) {
    if (robotLocation != null && (!route.isEmpty()) && running && textToSpeech != null) {

      // Legacy compass sensor code
      // compassBearingDegrees = Utilities.correctCompassBearing(Math.round(event.values[0]),
      // robotLocation);

      float azimuth = 0;

      azimuth = Utilities.landscapeModeCompassCalibration(event);
      compassBearingDegrees = Utilities.correctCompassBearing(azimuth, robotLocation);

      currentDegree =
          Utilities.compassAnimationHandler(ivCompass, compassBearingDegrees, currentDegree);
      currentDegreeNorth =
          Utilities.compassNorthIconHandler(
              ivCompassNorth, compassBearingDegrees, currentDegreeNorth);
    }
  }
 @Override
 public void onLocationChanged(Location location) {
   robotLocation = location;
   robotMarker =
       MapUtilities.placeRobotMarkerOnMap(
           robotMarker,
           mMap,
           Utilities.convertLocationToLatLng(robotLocation),
           false,
           getResources(),
           getApplicationContext());
 }
 @Override
 public void onMapClick(LatLng latLng) {
   route.addPoint(new Point(latLng, "Point " + route.getPointsNumber(), false));
   MapUtilities.drawPathOnMap(mMap, route, getResources());
   robotMarker =
       MapUtilities.placeRobotMarkerOnMap(
           robotMarker,
           mMap,
           Utilities.convertLocationToLatLng(robotLocation),
           true,
           getResources(),
           getApplicationContext());
 }
  @Override
  protected void onPause() {
    super.onPause();
    if (textToSpeech != null) {
      textToSpeech.stop();
      textToSpeech.shutdown();
    }
    Utilities.setDirectionImage("STOP", ivDirection, bt);
    bt.stop();
    recognizer.cancel();
    // finish();

    if (speech != null) {
      speech.destroy();
    }
  }
 public void addMyLocationToRoute(View view) {
   if (!running) {
     route.addPoint(
         new Point(
             new LatLng(robotLocation.getLatitude(), robotLocation.getLongitude()),
             "Point " + route.getPointsNumber(),
             false));
     MapUtilities.drawPathOnMap(mMap, route, getResources());
     robotMarker =
         MapUtilities.placeRobotMarkerOnMap(
             robotMarker,
             mMap,
             Utilities.convertLocationToLatLng(robotLocation),
             true,
             getResources(),
             getApplicationContext());
   }
 }
 public void playButtonClicked(View view) {
   running = Utilities.playStopButtonHandler(route, running, ivPlayStop, this);
 }
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_face_recognition);

    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

    initializeGraphicComponents();

    route = new Route();

    SupportMapFragment mapFragment =
        (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.fragmentMap);
    mapFragment.getMapAsync(this);

    mLocationRequest = Utilities.createLocationRequest(getResources());

    // ATTENTION: This "addApi(AppIndex.API)"was auto-generated to implement the App Indexing API.
    // See https://g.co/AppIndexing/AndroidStudio for more information.
    if (mGoogleApiClient == null) {
      mGoogleApiClient =
          new GoogleApiClient.Builder(this)
              .addApi(LocationServices.API)
              .addConnectionCallbacks(this)
              .addOnConnectionFailedListener(this)
              .addApi(AppIndex.API)
              .build();
    }
    mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);

    gSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);

    textToSpeech =
        new TextToSpeech(
            getApplicationContext(),
            new TextToSpeech.OnInitListener() {
              @Override
              public void onInit(int status) {
                if (status != TextToSpeech.ERROR) {
                  textToSpeech.setLanguage(Locale.ENGLISH);
                }
              }
            });

    bt = new Bluetooth(this, mHandler);
    connectService();

    ivAddToRoute.setOnLongClickListener(this);

    openCvCameraView = (CameraBridgeViewBase) findViewById(R.id.jcvFaceDetection);
    openCvCameraView.setCvCameraViewListener(this);

    /*handler1.postDelayed(*/
    runnable =
        new Runnable() {
          public void run() {
            try {
              int listSize = facesInASecond.size();
              int trues = Collections.frequency(facesInASecond, true);
              // int falses = Collections.frequency(facesInASecond, false);

              final double faceRatio = ((double) trues / (double) listSize) * (double) 100;

              if (faceRatio > 65) {
                faceDetected = true;
                if (!textToSpeech.isSpeaking())
                  textToSpeech.speak("Please get out the way", TextToSpeech.QUEUE_FLUSH, null);

              } else {
                faceDetected = false;
              }

              runOnUiThread(
                  new Runnable() // start actions in UI thread
                  {

                    @Override
                    public void run() {
                      if (faceDetected)
                        if (!command.equals("STOP")) {
                          Utilities.setDirectionImage("STOP", ivDirection, bt);
                          command = "STOP";
                        }
                      if (!(faceRatio == Double.NaN))
                        tvFaceRatio.setText(
                            "Face ratio: " + String.format("%.02f", faceRatio) + "%");
                      else tvFaceRatio.setText("Face ratio: " + 0 + "%");
                    }
                  });

              Log.d("RATIO", "" + faceRatio);
              Log.d("face state", " " + faceDetected);
              facesInASecond.clear();
            } catch (Exception e) {
              //  Log.e("ERROR", e.printStackTrace() + "");
              e.printStackTrace();
            }
            handler1.postDelayed(this, 1000); // 1 second
          }
        };

    handler1.postDelayed(runnable, 1000);

    /// lathos topothetisi den kerdizw kati apo to thread
    directionThread =
        new Thread(
            new Runnable() {

              @Override
              public void run() {
                while (!Thread.interrupted())
                  try {
                    Thread.sleep(
                        Preferences.loadPrefsInt(
                            "COMMUNICATION_LOOP_REPEAT_TIME", 300, getApplicationContext()));
                    runOnUiThread(
                        new Runnable() // start actions in UI thread
                        {

                          @Override
                          public void run() {
                            if (robotLocation != null
                                && (!route.isEmpty())
                                && running
                                && textToSpeech != null) {

                              if (!faceDetected)
                                command =
                                    Utilities.giveDirection(
                                        compassBearingDegrees,
                                        ivDirection,
                                        ivCompass,
                                        route,
                                        robotLocation,
                                        getApplicationContext(),
                                        command,
                                        mMap,
                                        getResources(),
                                        tvDistance,
                                        textToSpeech,
                                        bt,
                                        false);

                              // END OF PATH REACHED - FINISH PROGRAM
                              if (command.equals("FINISH")) {
                                mMap.clear();
                                tvDistance.setText("---m");
                                if (running)
                                  running =
                                      Utilities.playStopButtonHandler(
                                          route, running, ivPlayStop, getApplicationContext());

                                route.clearRoute();

                                Utilities.setDirectionImage("STOP", ivDirection, bt);
                              }
                            }
                          }
                        });
                  } catch (InterruptedException e) {
                    e.printStackTrace();
                    Log.e(TAG, "run: Direction Thread interrupted");
                    break;
                  }
              }
            });

    directionThread.start();
  }