component sim_spindle "Simulated spindle with index pulse";

pin in float    velocity-cmd    "Commanded speed";
pin out float   position-fb     "Feedback position, in revolutions";
pin io bit      index-enable    "Reset position-fb to 0 at next full rotation";
pin io float    scale = 1.0     "Factor applied to velocity-cmd.";

license "GPL";

function _;

;;
#include "rtapi_math.h"


FUNCTION(_) {
hal_float_t old_position = position_fb;
hal_float_t new_position = position_fb + velocity_cmd * fperiod * scale;

    if(index_enable && (rtapi_floor(old_position) != rtapi_floor(new_position)))
        {
       index_enable = false;
       if(velocity_cmd < 0)
            new_position = new_position - rtapi_ceil(new_position);
       else
            new_position = new_position - rtapi_floor(new_position);
        }
    position_fb = new_position;

   return 0;
}

