#ifndef MOTOR_H
#define MOTOR_H

bool motorInit();
void motorTask();
void motorMove(uint16_t position);

void motorStart(uint8_t motor); // 1 - Master, 2 - Slave, 3 - Both
void motorStop();
uint8_t motorCycle(uint16_t cycles, uint16_t cycle_delay);

void motorSetSpeed(uint8_t motor, uint8_t duty);
uint8_t motorGetSetSpeed(uint8_t motor);
uint8_t motorGetActualSpeed(uint8_t motor);

void motorSetPosition(uint8_t motor, uint16_t position);
uint16_t motorGetPosition(uint8_t motor);

void motorSetCurrentLimit(uint8_t motor, uint16_t limit);
uint16_t motorGetCurrent(uint8_t motor);

uint8_t motorGetFlags(uint8_t motor, uint8_t flag);

void motorJog(uint8_t motor, uint8_t state, uint16_t position);

#define MASTER 0
#define SLAVE 1

enum
{
	MOTOR_ERROR_NONE = 0,
	MOTOR_ERROR_TIMEOUT,	  // 1
	MOTOR_ERROR_MAX_DELTA,	  // 2
	MOTOR_ERROR_M1_FATAL,	  // 3
	MOTOR_ERROR_M2_FATAL,	  // 4
	MOTOR_ERROR_M1_CURRENT,	  // 5
	MOTOR_ERROR_M2_CURRENT,	  // 6
	MOTOR_ERROR_M1_SAT,		  // 7
	MOTOR_ERROR_M2_SAT,		  // 8
	MOTOR_ERROR_M1_VOLTS,	  // 9
	MOTOR_ERROR_M2_VOLTS,	  // 10
	MOTOR_ERROR_M1_TEMP,	  // 11
	MOTOR_ERROR_M2_TEMP,	  // 12
	MOTOR_ERROR_M1_BKDRV,	  // 13
	MOTOR_ERROR_M2_BKDRV,	  // 14
	MOTOR_ERROR_M1_PARM,	  // 15
	MOTOR_ERROR_M2_PARM,	  // 16
	MOTOR_ERROR_START_TIMEOUT // 17

} motorError_t;

uint16_t motorError;

enum
{
	MOTOR_IDLE = 0,
	MOTOR_START = 1,
	MOTOR_RAMP = 10,
	MOTOR_RUN = 50,
	MOTOR_END = 100,
	MOTOR_SEAL = 110,
	MOTOR_STOP = 200,
	MOTOR_CYCLE_DELAY = 1000
} motorState_t;

extern int motorState;

enum
{
	MOTOR_FLAG_VOLTAGE_ERROR = 0,
	MOTOR_FLAG_TEMP_ERROR,
	MOTOR_FLAG_MOTION,
	MOTOR_FLAG_OVERLOAD,
	MOTOR_FLAG_BACKDRIVE,
	MOTOR_FLAG_PARAMETER,
	MOTOR_FLAG_SATURATION,
	MOTOR_FLAG_FATAL_ERROR
};

bool motorDir; // 0 = extend, 1 = retract
#define EXTEND 1
#define RETRACT 0

int8_t currentDir; // actual running direction
				   //
#define RUN_IDLE 0
#define RUN_RETRACT -1
#define RUN_EXTEND 1

uint16_t masterSpeed;
// extern uint16_t masterSpeed;

extern bool bSyncEnable;
bool jogMotor;

// the following values to be suppled by
//  end application
// extern int32_t	parm[100];
#define P_MOTOR_ADJ_INTERVAL 41
#define P_MOTOR_ADJ_I 42
#define P_MOTOR_ADJ_P 43
#define P_MAX_DELTA 44
#define P_MAX_CURRENT 45
#define P_MOTOR_SPEED 46
#define P_EXTEND_LIMIT 47
#define P_SLAVE_OFFSET 48
#define P_MAX 49

const int32_t defParms[P_MAX] =
	{
		0,
		5,
		100,
		50,
		200,
		250,
		50,
		3000,
		0};

#endif // MOTOR_H
