/**
 * ranging.h, Shared ultrasonic time-of-flight ranging
 *
 * getDistance() is identical across Node A (glasses), Node B (shoes),
 * and Node C (gloves), all three use a single HC-SR04-class sensor
 * read per call. Extracted here so the three nodes stay in sync.
 *
 * Round-trip formula: distance (cm) = pulseWidth (µs) / 58
 * (Speed of sound: ~343 m/s = 0.0343 cm/µs = 1 cm per 29 µs round-trip)
 */
#pragma once

// Sensor timeout (prevent infinite waits)
#define SENSOR_TIMEOUT 30000  // 30 ms in microseconds

/**
 * getDistance(), Measure distance using ultrasonic time-of-flight
 *
 * Returns distance in cm, or -1 on timeout / out-of-range reading
 * (valid range: 2 cm to 400 cm, per HC-SR04 datasheet).
 */
inline float getDistance(int trigPin, int echoPin) {
  // Send 10 µs trigger pulse
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  // Measure echo pulse width
  long pulseDuration = pulseIn(echoPin, HIGH, SENSOR_TIMEOUT);

  // Invalid measurement (sensor not responding or timeout)
  if (pulseDuration == 0) {
    return -1;  // Return negative to indicate error
  }

  // Convert pulse duration to distance
  float distance = pulseDuration / 58.0;

  // Clamp to reasonable range (2 cm to 400 cm)
  if (distance < 2 || distance > 400) {
    return -1;
  }

  return distance;
}
