// VIGIL firmware outline: XIAO ESP32-S3 (Arduino core 3.x)
// A hand under the bud wakes it: the head turns toward the hand (stem stepper), the bud opens
// (PQ12-P linear actuator, closed loop on its potentiometer) and the light fades up. When the room
// is empty for a while it closes, dims and turns home.
//
// Libraries: SparkFun_VL53L5CX_Library, TMCStepper, FastAccelStepper
#include <Wire.h>
#include <SparkFun_VL53L5CX_Library.h>
#include <TMCStepper.h>
#include <FastAccelStepper.h>

// ---- pins (XIAO ESP32-S3) ----
const int PIN_POT   = D0;   // PQ12 wiper (ADC), pot ends on 3V3 / GND
const int PIN_STEP  = D1;
const int PIN_DIR   = D2;
const int PIN_EN    = D3;   // TMC2209 enable (active low)
// D4 SDA, D5 SCL -> VL53L5CX (Qwiic, 3V3), via the 10-core cable up the stem
const int PIN_TMC_TX = D6, PIN_TMC_RX = D7;  // TMC2209 single-wire UART (1k from TX to PDN_UART)
const int PIN_AIN1  = D8;   // DRV8833 -> PQ12 motor
const int PIN_AIN2  = D9;
const int PIN_LED   = D10;  // Mean Well LDD-700LS DIM input (PWM)

// ---- mechanics ----
const float STEPS_PER_DEG = 200.0f * 16 / 360.0f;  // 1.8 deg motor, 1/16 microstep, direct drive
const float YAW_LIMIT = 40.0f;                     // keeps the head inside the feet (tip-over margin 2.3x)
const int POT_CLOSED = 610, POT_OPEN = 3420;       // ADC counts at 0 and 12 mm of stroke (calibrate per lamp)

SparkFun_VL53L5CX tof;
VL53L5CX_ResultsData zones;
HardwareSerial TMCSerial(1);
TMC2209Stepper driver(&TMCSerial, 0.11f, 0b00);
FastAccelStepperEngine engine;
FastAccelStepper *yaw = nullptr;

enum State { SLEEP, WAKING, OPEN, CLOSING };
State state = SLEEP;
uint32_t lastSeen = 0, nearSince = 0;
float bloom = 0, bloomTarget = 0;   // 0 closed .. 1 open
float light = 0, lightTarget = 0;   // 0 .. 1
float yawTarget = 0;

// ---------- bloom actuator: PD loop on the PQ12 potentiometer ----------
void driveBloom(float target) {
  int pos = analogRead(PIN_POT);
  float want = POT_CLOSED + target * (POT_OPEN - POT_CLOSED);
  static float lastErr = 0;
  float err = want - pos, d = err - lastErr; lastErr = err;
  float u = constrain(0.25f * err + 0.8f * d, -255.0f, 255.0f);
  if (fabsf(err) < 12) u = 0;                 // dead band: quiet when holding (the spring carries the ribs)
  analogWrite(PIN_AIN1, u > 0 ? (int)u : 0);  // slow decay H-bridge drive
  analogWrite(PIN_AIN2, u < 0 ? (int)-u : 0);
}

// ---------- hand finding: 8x8 zones, the bud looks straight down ----------
// returns true and the hand's bearing (deg, + = counter-clockwise seen from above) if something is
// closer than 280 mm in at least 3 zones
bool findHand(float &bearing, float &dist) {
  if (!tof.isDataReady() || !tof.getRangingData(&zones)) return false;
  float sx = 0, sy = 0; int n = 0; float dmin = 9999;
  for (int i = 0; i < 64; i++) {
    int mm = zones.distance_mm[i];
    if (zones.target_status[i] != 5 || mm > 280 || mm < 30) continue;
    int r = i / 8, c = i % 8;
    sx += c - 3.5f; sy += 3.5f - r; n++; dmin = min(dmin, (float)mm);
  }
  if (n < 3) return false;
  bearing = degrees(atan2f(sy / n, sx / n)) * 0.35f;  // small nudge toward the hand, not a full swing
  dist = dmin;
  return true;
}

void homeYaw() {
  // sensorless homing: creep onto the -40 deg stop pin and watch StallGuard
  driver.SGTHRS(60);
  yaw->setSpeedInHz(400); yaw->runBackward();
  uint32_t t0 = millis();
  while (millis() - t0 < 6000 && driver.SG_RESULT() > 120) delay(5);
  yaw->forceStopAndNewPosition(-YAW_LIMIT * STEPS_PER_DEG);
  yaw->moveTo(0, true);
}

void setup() {
  analogReadResolution(12);
  pinMode(PIN_EN, OUTPUT); digitalWrite(PIN_EN, LOW);
  ledcAttach(PIN_LED, 2000, 12); ledcWrite(PIN_LED, 0);
  pinMode(PIN_AIN1, OUTPUT); pinMode(PIN_AIN2, OUTPUT);

  Wire.begin(D4, D5, 400000);
  tof.begin(); tof.setResolution(64); tof.setRangingFrequency(15); tof.startRanging();

  TMCSerial.begin(115200, SERIAL_8N1, PIN_TMC_RX, PIN_TMC_TX);
  driver.begin(); driver.toff(4); driver.rms_current(450); driver.microsteps(16);
  driver.en_spreadCycle(false); driver.pwm_autoscale(true);       // stealthChop: silent
  engine.init(); yaw = engine.stepperConnectToPin(PIN_STEP);
  yaw->setDirectionPin(PIN_DIR); yaw->setAcceleration(900);
  homeYaw();
}

void loop() {
  float bearing, dist;
  uint32_t now = millis();
  bool hand = findHand(bearing, dist);
  if (hand) { lastSeen = now; if (!nearSince) nearSince = now; } else nearSince = 0;

  switch (state) {
    case SLEEP:
      if (hand && now - nearSince > 250) state = WAKING;
      break;
    case WAKING:                                   // turn toward the hand, then open and light
      yawTarget = constrain(yawTarget + bearing, -YAW_LIMIT, YAW_LIMIT);
      bloomTarget = 1; lightTarget = 0.85;
      if (bloom > 0.97) state = OPEN;
      break;
    case OPEN:
      if (hand) {                                  // hand height sets brightness: lower hand, brighter
        lightTarget = constrain(map((long)dist, 60, 260, 100, 25) / 100.0f, 0.25f, 1.0f);
      }
      if (now - lastSeen > 20000) state = CLOSING; // 20 s with nobody under it
      break;
    case CLOSING:
      bloomTarget = 0; lightTarget = 0; yawTarget = 0;
      if (hand) state = WAKING;
      else if (bloom < 0.03 && light < 0.01) state = SLEEP;
      break;
  }

  // slow, even motion: 1.4 s to open, light fades over 1.5 s (gamma 2.2)
  bloom += constrain(bloomTarget - bloom, -0.012f, 0.012f);
  light += constrain(lightTarget - light, -0.011f, 0.011f);
  driveBloom(bloom);
  ledcWrite(PIN_LED, (uint32_t)(4095 * powf(light, 2.2f)));
  yaw->setSpeedInHz(900);
  yaw->moveTo((int32_t)(yawTarget * STEPS_PER_DEG));
  delay(16);
}
