// VCExampleDlg.cpp : implementation file
//

#include "stdafx.h"
#include "VCExample.h"
#include "VCExampleDlg.h"

#include "SetBasepara.h"

#define GT_PCI			//define your card, pci or isa
//#define GT_ISA

#define GT_SV				//define your card, sv,sg,sd or sp
//#define GT_SG
//#define GT_SP
//#define GT_SD

#ifdef GT_ISA
	#ifdef GT_SV
	#include "GTsvdll.h"
	#endif
	
	#ifdef GT_SG
	#include "GTsgdll.h"
	#endif

	#ifdef GT_SP
	#include "GTspdll.h"
	#endif

	#ifdef GT_SD
	#include "GTsddll.h"
	#endif
#else
	#ifdef GT_SV
	#include "GT400sv.h"
	#endif
	
	#ifdef GT_SG
	#include "GT400sg.h"
	#endif

	#ifdef GT_SP
	#include "GT400sp.h"
	#endif

	#ifdef GT_SD
	#include "GT400sd.h"
	#endif
#endif

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About

class CAboutDlg : public CDialog
{
public:
	CAboutDlg();

// Dialog Data
	//{{AFX_DATA(CAboutDlg)
	enum { IDD = IDD_ABOUTBOX };
	//}}AFX_DATA

	// ClassWizard generated virtual function overrides
	//{{AFX_VIRTUAL(CAboutDlg)
	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support
	//}}AFX_VIRTUAL

// Implementation
protected:
	//{{AFX_MSG(CAboutDlg)
	//}}AFX_MSG
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
	//{{AFX_DATA_INIT(CAboutDlg)
	//}}AFX_DATA_INIT
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CAboutDlg)
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
	//{{AFX_MSG_MAP(CAboutDlg)
		// No message handlers
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CVCExampleDlg dialog

CVCExampleDlg::CVCExampleDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CVCExampleDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CVCExampleDlg)
		// NOTE: the ClassWizard will add member initialization here
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CVCExampleDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CVCExampleDlg)
		// NOTE: the ClassWizard will add DDX and DDV calls here
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CVCExampleDlg, CDialog)
	//{{AFX_MSG_MAP(CVCExampleDlg)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDC_INITIALCARD, OnInitialcard)
	ON_WM_CREATE()
	ON_WM_DESTROY()
	ON_BN_CLICKED(IDC_AXIS_MOTION, OnAxisMotion)
	ON_WM_TIMER()
	ON_BN_CLICKED(IDC_INTER_TIMER, OnInterTimer)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CVCExampleDlg message handlers

BOOL CVCExampleDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	// Add "About..." menu item to system menu.

	// IDM_ABOUTBOX must be in the system command range.
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		CString strAboutMenu;
		strAboutMenu.LoadString(IDS_ABOUTBOX);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon
	
	// TODO: Add extra initialization here
	SetTimer(1, 100, NULL);
	MessageBox("VERY IMPORTANT!!\nI set motor parameter as follow:\nEncode Sense: 0\nLimit Sense:  0 \
		\nKp=320\nKd=20\nKi=0\nKvff=0\nKaff=0\nI-Limit=100\n If there aren't suit for your motor, change it in source code.");

    return TRUE;  // return TRUE  unless you set the focus to a control
}

void CVCExampleDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialog::OnSysCommand(nID, lParam);
	}
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CVCExampleDlg::OnPaint() 
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
}

// The system calls this to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CVCExampleDlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}

void CVCExampleDlg::OnInitialcard() 
{
	// Before initial the card, you must open the card in windows. I do it in the message of WM_CREATE
	MessageBox("I will set motor parameter as follow:\nEncode Sense: 0\nLimit Sense:  0 \
		\nKp=320\nKd=20\nKi=0\nKvff=0\nKaff=0\nI-Limit=100\n If there aren't suit for your motor,please power off your motor \
		before press OK button and change it in source code before you try again.");
	short rtn;
	rtn=GT_Reset();		err(rtn);
	rtn=GT_EncSns(0);	err(rtn);
	rtn=GT_LmtSns(0);	err(rtn);

	for(unsigned short i=1;i<5;i++) {
		rtn=GT_Axis(i);	err(rtn);
#ifdef GT_SV
		rtn=GT_SetKp(320);	err(rtn);
		rtn=GT_SetKd(20);	err(rtn);
		rtn=GT_SetKi(0);	err(rtn);
		rtn=GT_SetKvff(0);	err(rtn);
		rtn=GT_SetKaff(0);	err(rtn);
#endif
		rtn=GT_SetILmt(100);	err(rtn);
//GT_LmtsOff() and GT_LmtsOn() is work for a special axis, which is different with the function of GT_LmtSns();
//		rtn=GT_LmtOff();	err(rtn);
		rtn=GT_Update();	err(rtn);
		rtn=GT_AxisOn();		err(rtn);
	}
}

int CVCExampleDlg::OnCreate(LPCREATESTRUCT lpCreateStruct) 
{
	if (CDialog::OnCreate(lpCreateStruct) == -1)
		return -1;
	
	// Open the card here and you must Close the card before you exit the program
	// I close the card when received the message WM_DESTORY
	short rtn;
#ifdef GT_ISA
	CSetBasepara dlg;
	dlg.m_iBase=0x300;
	dlg.m_iIRQ=0;
	int result = dlg.DoModal();
	if(dlg.m_iIRQ<10) dlg.m_iIRQ=0;
	rtn=GT_Open(dlg.m_iBase,dlg.m_iIRQ);	err(rtn);
#else
	rtn=GT_Open();	err(rtn);
	rtn=GT_Reset();
#endif

	return 0;
}

HANDLE hSyncEvent,hSubThread;
bool stopflag;

void CVCExampleDlg::OnDestroy() 
{
	CDialog::OnDestroy();
	
	// Close the servo and close the card
	short rtn;
	stopflag=true;
	if(hSyncEvent) SetEvent(hSyncEvent);		//唤醒中断线程
	if(hSubThread) CloseHandle(hSubThread);	//关闭中断线程

	for(unsigned short i=1;i<5;i++) {
		rtn=GT_Axis(i);	err(rtn);
		rtn=GT_AxisOff();	err(rtn);
	}
	rtn=GT_Close();	err(rtn);
	
   KillTimer(1);
}


void CVCExampleDlg::OnAxisMotion() 
{
	MessageBox("These routin illustrate how to make the axis run and how to respond\
		interrupt with background command.");

#define MAX_SIZE	500

	PBGCOMMANDSET pBgCmdSet;//定义一指针
	pBgCmdSet=new BGCOMMANDSET[MAX_SIZE];//分配内存
	if(pBgCmdSet==NULL)
	{
		MessageBox("Don't have enough memory,please review the source code and then test again!");
		return;
	}
	PBACKGROUND_COMMAND pBackCmd;
	PGENERAL_COMMAND pCmd;
	//指定要为多少种中断设置后台命令
	pBgCmdSet->Count=2;			 //要为两种中断设置后台命令
	//分别为每个中断设置命令数组，对同一个中断允许设多条命令
	pBackCmd=pBgCmdSet->BackgroundCommand;
	
	pBackCmd->InterruptMask=0x01;		//指定中断原因
	pBackCmd->CommandCount=2;		//产生本中断时要执行的命令数量
	//分别填充每一条命令
	//第一条命令
	pCmd=pBackCmd->GenCommand;
	pCmd->usCommand= Intr_GT_SetPos; 	//设定命令类型字
	pCmd->OutputLength=2;	//该命令执行时，需要向DSP输出多少个字长度的数据
	pCmd->InputLength=0;		//该命令执行时，需要从DSP输入多少个字长度的数据
	pCmd->in.lData=5000;		//输入数据
	pCmd->out.lData=0;		//输出数据
	//填充下一条命令
	pCmd=PGENERAL_COMMAND((char *)pCmd+sizeof(GENERAL_COMMAND));	//指向下一个内存单元
	pCmd->usCommand= Intr_GT_Update;	//设定命令类型字
	pCmd->OutputLength=0;	//该命令执行时，需要向DSP输出多少个字长度的数据
	pCmd->InputLength=0;		//该命令执行时，需要从DSP输入多少个字长度的数据
	pCmd->in.lData=0;			//输入数据
	pCmd->out.lData=0;		//输出数据

	//为另一中断设置命令数组
	pBackCmd= PBACKGROUND_COMMAND( (char *)pCmd+sizeof(GENERAL_COMMAND));//指向下一内存单元
	
	pBackCmd->InterruptMask=0x02;//指定中断原因
	pBackCmd->CommandCount=1;//产生本中断时要执行的命令数量
	//填充第一条命令
	pCmd=pBackCmd->GenCommand;
	pCmd->usCommand= Intr_GT_SetKp;	 //设定命令类型字
	pCmd->OutputLength=1;	//该命令执行时，需要向DSP输出多少个字长度的数据
	pCmd->InputLength=0;		//该命令执行时，需要从DSP输入多少个字长度的数据
	pCmd->in.lData=0;			//输入数据
	pCmd->out.lData=20;		//输出数据
	//将命令缓冲传给设备ISR
	short rtn=GT_SetBgCommandSet(pBgCmdSet,MAX_SIZE);   err(rtn);
//之后释放内存
	delete[]pBgCmdSet;

//使轴运动
	rtn=GT_Axis(1);  err(rtn);
	rtn=GT_ClrSts();  err(rtn);
	rtn=GT_SetPos(10000);  err(rtn);
	rtn=GT_SetVel(1);  err(rtn);
	rtn=GT_SetAcc(0.5);  err(rtn);
	rtn=GT_Update();	  err(rtn);
}

inline CVCExampleDlg::err(short rtn)
{
 if(rtn) MessageBox("Some function return a error!");
}

static unsigned long count=0;

DWORD WINAPI CVCExampleDlg::intproc(LPVOID param)
{
	unsigned short Status;
	short rtn;
	ResetEvent(hSyncEvent);
	while(1)
	{
		//waiting for interrupt happen
		WaitForSingleObject(hSyncEvent,INFINITE);
		if(stopflag)		break;
		//add your code for handling intrerrupt event here
/*very important!!!!!!!
		if you will change current action axis,which means you will issue command
		GT_Axis(x) in your own sub-thread, you must assure it will not disturb your
		main thread. In short,you must take care of sync problem.
*very important!!!!!!!!*/
		//.....
		rtn=GT_GetIntr(&Status);	 if(rtn) AfxMessageBox("Some function return a error!");
//		rtn=GT_Axis((unsigned short)(count%4)+1);	 if(rtn) AfxMessageBox("Some function return a error!");
		rtn=GT_ExOpt((unsigned short)count);	 if(rtn) AfxMessageBox("Some function return a error!");
		count++;
		//reset event state
		ResetEvent(hSyncEvent);
	}
	
	rtn=GT_SetIntSyncEvent(NULL);	 if(rtn) AfxMessageBox("Some function return a error!");
	//close Synchronize Event Handle 
	CloseHandle(hSyncEvent);
	ExitThread(0);
	return 0;
}

void CVCExampleDlg::OnTimer(UINT nIDEvent) 
{
		CEdit* interNum=(CEdit*)GetDlgItem(IDC_INTER_NUM);
		CString str;
		str.Format("%ld",count);
		interNum->SetWindowText(str);

		if(count>10000) {
			/*you must assure to close the sub-thread at pudding time*/
			stopflag=true;
			SetEvent(hSyncEvent);		//唤醒中断线程
			CloseHandle(hSubThread);	//关闭中断线程
		}
	
	CDialog::OnTimer(nIDEvent);
}

void CVCExampleDlg::OnInterTimer() 
{
	MessageBox("These routine is just for test time interrupt.");
	//Create Sync event

	hSyncEvent=CreateEvent(NULL,true,false,NULL);
	if(hSyncEvent==INVALID_HANDLE_VALUE)
	{
		MessageBox("Create Synchnorize Event fail\n");
		return ;
	}
	short rtn;
	//将应用程序的事件与底层中断相关连
	rtn=GT_SetIntSyncEvent(hSyncEvent);		err(rtn);
	//设置中断时间
	rtn=GT_SetIntrTm(2000);		err(rtn);
	//中断模式设为时间中断
	rtn=GT_TmrIntr();		err(rtn);
	//开设中断服务线程
	stopflag=false;
	DWORD idSubThread;

	hSubThread=CreateThread(NULL,
						0,
						(LPTHREAD_START_ROUTINE)CVCExampleDlg::intproc, // the route handling interrupt
						NULL,//the parameter of intproc
						0,
						&idSubThread);

	//.......wait for interrupt----I do it in timer
	
}
