#include "ramp_ctrl.h"

#define RAMP_INTVAL 5 //ms
static void ramp_timer_handler(timer_t *timer);

void ramp_ctrl_init(ramp_t *ramp, float start, float final, u32 duration_ms){
	ramp->start_point = start;
	ramp->target = start;
	ramp->final_point = final;
	ramp->duration_ms = duration_ms;
	ramp->steps = (final - start) / (duration_ms / RAMP_INTVAL);
	if (ramp->timer.handler != NULL) {
		timer_cancel(&ramp->timer);
	}
	ramp->timer.handler = NULL;
}

void ramp_clear(ramp_t *ramp) {
	ramp_ctrl_init(ramp, ramp->start_point, ramp->final_point, ramp->duration_ms);
}

void ramp_exc(ramp_t *ramp){
	if (ramp->timer.handler == NULL) {
		ramp->timer.handler = ramp_timer_handler;
		timer_post(&ramp->timer, RAMP_INTVAL);
	}
}

float ramp_get_target(ramp_t *ramp){
	return ramp->target;
}

bool ramp_complete(ramp_t *ramp) {
	return ramp->target == ramp->final_point;
}

static void ramp_timer_handler(timer_t *timer) {
	ramp_t *ramp = (ramp_t *)timer;
	float target = ramp->target + ramp->steps;
	if (target > ramp->final_point) {
		target = ramp->final_point;
	}
	ramp->target = target;
	if (target != ramp->final_point) {
		timer_post(&ramp->timer, RAMP_INTVAL);
	}
}

