#include "UltrasonicSensor.h"

#include <Arduino.h>

namespace RoboidControl {
namespace Arduino {

UltrasonicSensor::UltrasonicSensor(Participant* participant, unsigned char pinTrigger, unsigned char pinEcho)
    : TouchSensor(participant) {
  this->pinTrigger = pinTrigger;
  this->pinEcho = pinEcho;

  pinMode(pinTrigger, OUTPUT);  // configure the trigger pin to output mode
  pinMode(pinEcho, INPUT);      // configure the echo pin to input mode
}

float UltrasonicSensor::GetDistance() {
  // Start the ultrasonic 'ping'
  digitalWrite(pinTrigger, LOW);
  delayMicroseconds(5);
  digitalWrite(pinTrigger, HIGH);
  delayMicroseconds(10);
  digitalWrite(pinTrigger, LOW);

  // Measure the duration of the pulse on the echo pin
  float duration_us = pulseIn(pinEcho, HIGH, 100000);  // the result is in microseconds

  // Calculate the distance:
  // * Duration should be divided by 2, because the ping goes to the object
  // and back again. The distance to the object is therefore half the duration
  // of the pulse: duration_us /= 2;
  // * Then we need to convert from microseconds to seconds: duration_sec =
  // duration_us / 1000000;
  // * Now we calculate the distance based on the speed of sound (340 m/s):
  // distance = duration_sec * 340;
  // * The result calculation is therefore:
  this->distance = duration_us / 2 / 1000000 * 340;

  // Filter faulty measurements. The sensor can often give values > 30 m which
  // are not correct
  // if (distance > 30)
  //   distance = 0;

  this->touchedSomething = (this->distance <= this->touchDistance);

//   std::cout << "Ultrasonic " << this->distance << " " << this->touchedSomething << "\n";

  return distance;
}

void UltrasonicSensor::Update(unsigned long currentTimeMs) {
  GetDistance();
}

}  // namespace Arduino
}  // namespace RoboidControl