#include <stdio.h>
#include <unistd.h>
#include "i8094_dll.h"

int main(void)
{
	short nRet, nInit, nTargetCnt;
	DWORD dwFixedPulse, dwSpeed;
	long nCmdCntX;
	WORD wActiveSts = 0;
	nTargetCnt = 60;
	dwFixedPulse = 5;
	dwSpeed = 60000;
	BYTE bCardID = 0; //bCardID=(bSlotNum-1), if the I-8094 plug-in Slot 2 of LinPAC, bCardID=2-1=1 

	nRet = i8094_open( bCardID );
	if(nRet == SUCCESS_NO_ERROR)
	{
				
		nRet = i8094_set_pls_cfg( bCardID, AXIS_X, PULSE_MODE_CW_CCW, PULSE_LOGIC_ACTIVE_HIGH, PARAMETER_IGNORED );
		if(nRet != SUCCESS_NO_ERROR) 
			printf(" [AXIS_X] i8094_set_pls_cfg returns = %d\n", nRet );
			
		nRet = i8094_set_enc_cfg( bCardID, AXIS_X, ENCODER_MODE_CW_CCW, 0 );
		if(nRet != SUCCESS_NO_ERROR)
			printf(" [AXIS_X] i8094_set_enc_cfg returns = %d\n", nRet );
		
		nRet = i8094_set_limit( bCardID, AXIS_X, LIMIT_LOGIC_ACTIVE_LOW, LIMIT_STOP_SUDDEN );
		if(nRet != SUCCESS_NO_ERROR)
			printf(" [AXIS_X] i8094_set_limit returns = %d\n", nRet );

		nRet = i8094_set_cmdcounter( bCardID, AXIS_X, 0);
		if(nRet != SUCCESS_NO_ERROR)
			printf(" [AXIS_X] i8094_set_position returns = %d\n", nRet );
		
		nRet = i8094_set_inp( bCardID, AXIS_X, INP_ENABLE_FEATURE, INP_LOGIC_ACTIVE_HIGH);
		if(nRet != SUCCESS_NO_ERROR)
			printf(" i8094_set_inp returns = %d\n", nRet );
		
		nRet = i8094_set_alarm( bCardID, AXIS_X, ALARM_ENABLE_FEATURE, ALARM_LOGIC_ACTIVE_LOW );
		if(nRet != SUCCESS_NO_ERROR)
			printf(" i8094_set_alarm returns = %d\n", nRet );
		
		nRet = i8094_servo_on(bCardID, AXIS_X, SERVO_ON, SERVO_AUTO_OFF);
		if(nRet != SUCCESS_NO_ERROR)
			printf("i8094_servo_on returns = %d\n", nRet);
		
		nRet = i8094_set_mpg(bCardID, AXIS_X, EXP_AB_PHASE_MPG, dwFixedPulse, dwSpeed, 5000);
		if(nRet != SUCCESS_NO_ERROR)
			printf("i8094_set_mpg returns = %d\n", nRet);
		
		// Loop in 30 secs
		for(nInit = 0; nInit < nTargetCnt; nInit++)
		{
			nRet = i8094_get_mdi_status( bCardID, AXIS_X, &wActiveSts );
			if( (wActiveSts & DI_STATUS_ACTIVE_ALARM ) == DI_STATUS_ACTIVE_ALARM )
			{
				printf(" DI_STATUS_ACTIVE_ALARM" );
				nRet = i8094_set_mpg(bCardID, AXIS_X, EXP_DISABLE_FEATURE, 0, 0, 5000);
				nRet = i8094_servo_on(bCardID, AXIS_X, SERVO_OFF, SERVO_AUTO_OFF);
				break;
			}
			
			i8094_get_cmdcounter( bCardID, AXIS_X, &nCmdCntX);
			printf(" [CmdCounter-X = %ld]\n", nCmdCntX);
			
			usleep( 500000 ); //sleep 500ms
	    }
			
		nRet = i8094_set_mpg(bCardID, AXIS_X, EXP_DISABLE_FEATURE, 0, 0, 5000);
		i8094_close( bCardID );
		
	}
	else
	{
		printf (" i8094_open() return %d !\n", nRet );
	}
	return 0;
}
