#include <UFP.h>
#include "motionStateMachine.h"
#include "stepperDriver.h"
#include "machineClock.h"

// no-transport-layer stepper motor
// using the RP2040 at 200MHz
// using https://modular-things.github.io/modular-things/things/stepper-hbridge-xiao/
//
// Host communication is UFP (ufp/docs.md) over USB serial: every function
// below is registered in setup() and discovered by the host at connect time
// (see host/motor.py). All units on this side are full steps.
// Needs the UFP Arduino library: ufp/arduino/UFP (copy or link it into your
// Arduino libraries folder).

#define PIN_LIMIT 26

// change this for each
#define MOTOR_ID 1

// 256 B fits a queue_blocks call with 12 blocks (the host sends 10)
UFPDevice<256> ufp("simple_stepper");


uint8_t getId(){
  return MOTOR_ID;
}


void setTargetVelocity(float velocity, float maxAccel){
  motion_setVelocityTarget(velocity, maxAccel);
}


void setTargetPosition(float position, float maxVel, float maxAccel){
  motion_setPositionTarget(position, maxVel, maxAccel);
}


void setPosition(float position){
  // should do maxAccel, maxVel, and (optionally) setPosition
  // upstream should've though of this, so,
  motion_setPosition(position);
}


void setCurrent(float cscale){
  // we get that as a floating p, 0-1,
  // driver wants integers 0-1024:
  if(cscale < 0.0F) cscale = 0.0F;
  if(cscale > 1.0F) cscale = 1.0F;
  stepper_setAmplitude((uint16_t)(cscale * 1024));
}


boolean lastButtonState = false;

void getStates(float& pos, float& vel, float& accel, bool& isMoving, bool& limit, uint64_t& timeNs){
  motionState_t state;
  motion_getCurrentStates(&state);
  pos = state.pos;
  vel = state.vel;
  accel = state.accel;
  isMoving = state.is_moving;
  limit = lastButtonState;
  // machine time (ns) at which the above was computed
  timeNs = state.time_ns;
}


// ------------------------------------ timed block queue

// one block per array index: duration (ns), end position (16.16 fixed point
// full steps), start and end velocity (steps/s). Blocks that don't fit are not
// accepted: the host re-sends from the first unaccepted one.
void queueBlocks(UFPSpan<uint32_t> durationNs, UFPSpan<int64_t> pEnd, UFPSpan<float> vStart,
                 UFPSpan<float> vEnd, uint8_t& accepted, uint16_t& nfree){
  uint16_t count = durationNs.size();
  if(pEnd.size() != count || vStart.size() != count || vEnd.size() != count){
    ufp.fail(UFP_ERR_EXEC_FAILED, "block arrays differ in length");
    return;
  }
  accepted = 0;
  for(uint16_t i = 0; i < count && accepted < 255; i ++){
    if(!motion_queueBlock(durationNs[i], pEnd[i], vStart[i], vEnd[i])) break;
    accepted ++;
  }
  nfree = motion_queueFree();
}

// begin playback at machine time tNs; haltAccel is used to stop on underrun.
// returns a QSTART_ code (motionStateMachine.h)
uint8_t startAt(uint64_t tNs, float haltAccel){
  return motion_queueStartAt(tNs, haltAccel);
}

void halt(float decel){
  motion_halt(decel);
}

void getQueue(uint8_t& state, uint16_t& nfree, uint32_t& blocksDone, uint64_t& nowNs, uint16_t& isrMaxUs){
  motionQueueState_t q;
  motion_getQueueState(&q);
  state = q.state;
  nfree = q.free;
  blocksDone = q.blocks_done;
  nowNs = q.now_ns;
  isrMaxUs = q.isr_max_us;
}


// ------------------------------------ machine clock (see machineClock.h)

void getTime(uint64_t& nowUs, uint16_t& sofRaw, uint32_t& sofCount, uint64_t& sofEdgeUs,
             uint32_t& sofSkips, uint32_t& maxPollGapUs, uint64_t& machineNs, bool& ok,
             float& trimPpm, float& phaseErrNs, uint32_t& relocks, uint32_t& rejected){
  clockStatus_t c;
  clock_getStatus(&c);
  nowUs = c.now_us;
  sofRaw = c.sof_raw;
  sofCount = c.sof_count;
  sofEdgeUs = c.sof_edge_us;
  sofSkips = c.sof_skips;
  maxPollGapUs = c.max_poll_gap_us;
  machineNs = c.machine_ns;
  ok = c.ok;
  trimPpm = c.trim_ppm;
  phaseErrNs = c.phase_err_ns;
  relocks = c.relocks;
  rejected = c.rejected;
}


void setup() {
  // startup the stepper hardware
  stepper_init();
  // setup motion, pick an integration interval (us)
  motion_init(64);
  // and our limit pin, is wired (to spec)
  // to a normally-closed switch, from SIG to GND,
  // meaning that when the switch is "clicked" - it will open,
  // and the pullup will win, we will have logic high
  pinMode(PIN_LIMIT, INPUT_PULLUP);
  // and our comms: names are "name:unit:description"
  ufp.add("get_id", getId, "", "id", "Motor ID set at compile time");
  ufp.add("set_target_velocity", setTargetVelocity,
          "velocity:steps/s, max_accel:steps/s^2", "", "Ramp to a velocity");
  ufp.add("set_target_position", setTargetPosition,
          "position:steps, max_vel:steps/s, max_accel:steps/s^2", "", "Move to a position");
  ufp.add("set_position", setPosition, "position:steps", "", "Redefine the current position");
  ufp.add("set_current", setCurrent, "current::0-1 of full scale", "", "Set the motor current");
  ufp.add("get_states", getStates, "",
          "position:steps, velocity:steps/s, acceleration:steps/s^2, is_moving, limit,"
          "time_ns:ns:machine time at which the states were computed",
          "Motion state and limit switch");
  ufp.add("queue_blocks", queueBlocks,
          "duration:ns, p_end:steps/65536:16.16 fixed point, v_start:steps/s, v_end:steps/s",
          "accepted, free", "Append timed blocks to the queue (arrays of equal length)");
  ufp.add("start_at", startAt, "t:ns:machine time, halt_accel:steps/s^2:used on underrun",
          "status::0 ok 1 empty 2 past 3 busy 4 moved 5 noclock", "Start playing the queue");
  ufp.add("halt", halt, "decel:steps/s^2", "", "Clear the queue and decelerate to a stop");
  ufp.add("get_queue", getQueue, "",
          "state::0 idle 1 armed 2 running 3 underrun 4 halted, free, blocks_done,"
          "now_ns:ns:machine time, isr_max_us:us:worst integrator ISR since last call",
          "Queue state");
  ufp.add("get_time", getTime, "",
          "now_us:us, sof_raw, sof_count, sof_edge_us:us, sof_skips, max_poll_gap_us:us,"
          "machine_ns:ns, clock_ok, trim_ppm:ppm, phase_err_ns:ns, relocks, rejected",
          "Device clock and USB start-of-frame snapshot");
  Serial.begin(115200);
  ufp.begin(Serial);
}


uint32_t debounceDelay = 1;
uint32_t lastButtonCheck = 0;


void loop() {
  // track USB frames, discipline machine time (keep this cheap & frequent)
  clock_poll();
  // run comms: handles requests and replies, never blocks
  ufp.loop();
  // debounce and set button states,
  if(lastButtonCheck + debounceDelay < millis()){
    lastButtonCheck = millis();
    boolean newState = digitalRead(PIN_LIMIT);
    if(newState != lastButtonState){
      lastButtonState = newState;
    }
  }
}
