/*
 * CodeProven — R09: Force-Limited Parallel Gripper
 * Generated starter firmware scaffold
 *
 * Status: generated starter scaffold — hardware validation required.
 * Hardware scope: MCU + two actuators + force sensors.
 * Acceptance tests: force calibration, grip repeatability, soft-object test, sensor-fault release.
 * Safety: Low-force only; include a physical release.
 *
 * This file is intentionally conservative: it boots, reports sensor state,
 * holds actuators in a safe low-energy state, and provides a place to add
 * the project-specific control law after the exact board and pinout are
 * verified. It is not a claim that the complete physical build has been
 * validated.
 */
#include <Arduino.h>

namespace Config {
constexpr uint32_t SERIAL_BAUD = 115200;
constexpr uint32_t CONTROL_INTERVAL_MS = 50;
constexpr uint8_t STATUS_LED_PIN = LED_BUILTIN;
constexpr uint8_t SENSOR_PIN = A0;
constexpr uint8_t ACTUATOR_PIN = 9;
constexpr uint8_t SAFETY_INPUT_PIN = 7;
constexpr bool ACTIVE_LOW_SAFETY = true;
}

uint32_t lastControlMs = 0;
uint32_t loopCount = 0;

bool safetyIsClear() {
  const int value = digitalRead(Config::SAFETY_INPUT_PIN);
  return Config::ACTIVE_LOW_SAFETY ? value == HIGH : value == LOW;
}

void safeStop() {
  analogWrite(Config::ACTUATOR_PIN, 0);
  digitalWrite(Config::STATUS_LED_PIN, LOW);
}

void printStatus(int sensorValue, bool fault) {
  Serial.print("PROJECT=R09;MODE=SAFE_STARTER;LOOPS=");
  Serial.print(loopCount);
  Serial.print(";SENSOR_RAW=");
  Serial.print(sensorValue);
  Serial.print(";FAULT=");
  Serial.println(fault ? 1 : 0);
}

void setup() {
  pinMode(Config::STATUS_LED_PIN, OUTPUT);
  pinMode(Config::ACTUATOR_PIN, OUTPUT);
  pinMode(Config::SAFETY_INPUT_PIN, INPUT_PULLUP);
  Serial.begin(Config::SERIAL_BAUD);
  delay(50);
  safeStop();
  Serial.println("CODEPROVEN_BOOT;FIRMWARE=0.1.0;STATUS=STARTER_SCAFFOLD");
}

void loop() {
  const uint32_t now = millis();
  if (now - lastControlMs < Config::CONTROL_INTERVAL_MS) return;
  lastControlMs = now;
  loopCount++;
  const int sensorValue = analogRead(Config::SENSOR_PIN);
  const bool fault = !safetyIsClear();
  if (fault) {
    safeStop();
  } else {
    // Conservative bench behavior: keep the actuator off until the exact
    // project-specific mapping, limits, and calibration are verified.
    analogWrite(Config::ACTUATOR_PIN, 0);
    digitalWrite(Config::STATUS_LED_PIN, (loopCount % 20) < 10 ? HIGH : LOW);
  }
  printStatus(sensorValue, fault);
}
