// integratorDlg.cpp : implementation file
//

#include "stdafx.h"
#include "integrator.h"
#include "integratorDlg.h"

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



CCyUSBDevice *USBDevice;

	CCyUSBEndPoint *OutEndpt;
	CCyUSBEndPoint *InEndpt;


/////////////////////////////////////////////////////////////////////////////
// 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()
};


    unsigned char bufer_rx[65535];
	long rx_length;

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()

/////////////////////////////////////////////////////////////////////////////
// CIntegratorDlg dialog

CIntegratorDlg::CIntegratorDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CIntegratorDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CIntegratorDlg)
	m_Status = _T("");
	m_Disp_Data = _T("");
	m_Out_Sel = -1;
	m_Delay = 0;
	m_Gate = 0;
	m_Samples = 0;
	m_Delay_Time = _T("");
	m_Gate_Time = _T("");
	m_Result = _T("");
	m_FileName = _T("");
	m_sample_acq = FALSE;
	m_ready = FALSE;
	m_idle = FALSE;
	m_int_empty = FALSE;
	m_int_full = FALSE;
	m_usb_empty = FALSE;
	m_usb_full = FALSE;
	m_delay_count = FALSE;
	m_ResetTime = _T("");
	m_ChSel = -1;
	m_SrcSel = -1;
	m_Looping = FALSE;
	m_ExtRstTime = 0;
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CIntegratorDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CIntegratorDlg)
	DDX_Text(pDX, IDC_STATUS, m_Status);
	DDV_MaxChars(pDX, m_Status, 20);
	DDX_CBString(pDX, IDC_Disp_Data, m_Disp_Data);
	DDV_MaxChars(pDX, m_Disp_Data, 30);
	DDX_Radio(pDX, IDC_MSB, m_Out_Sel);
	DDX_Text(pDX, IDC_Delay, m_Delay);
	DDX_Text(pDX, IDC_Gate, m_Gate);
	DDX_Text(pDX, IDC_Samples, m_Samples);
	DDX_Text(pDX, IDC_Deay_Time, m_Delay_Time);
	DDX_Text(pDX, IDC_Gate_Time, m_Gate_Time);
	DDX_Text(pDX, IDC_Result, m_Result);
	DDV_MaxChars(pDX, m_Result, 65535);
	DDX_Text(pDX, IDC_FileName, m_FileName);
	DDX_Check(pDX, IDC_CHECK1, m_sample_acq);
	DDX_Check(pDX, IDC_CHECK3, m_ready);
	DDX_Check(pDX, IDC_CHECK4, m_idle);
	DDX_Check(pDX, IDC_CHECK5, m_int_empty);
	DDX_Check(pDX, IDC_CHECK6, m_int_full);
	DDX_Check(pDX, IDC_CHECK7, m_usb_empty);
	DDX_Check(pDX, IDC_CHECK8, m_usb_full);
	DDX_Check(pDX, IDC_CHECK2, m_delay_count);
	DDX_Text(pDX, IDC_Reset_Time, m_ResetTime);
	DDX_Radio(pDX, IDC_CH1, m_ChSel);
	DDX_Radio(pDX, IDC_INT, m_SrcSel);
	DDX_Check(pDX, IDC_LOOP, m_Looping);
	DDX_Text(pDX, IDC_ResetTime, m_ExtRstTime);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CIntegratorDlg, CDialog)
	//{{AFX_MSG_MAP(CIntegratorDlg)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDC_READY, OnReady)
	ON_BN_CLICKED(IDC_STATUS_BTN, OnStatusBtn)
	ON_BN_CLICKED(IDC_Reset, OnReset)
	ON_BN_CLICKED(IDC_Res_Dev, OnResDev)
	ON_BN_CLICKED(IDC_Start_TX, OnStartTX)
	ON_EN_CHANGE(IDC_Gate, OnChangeGate)
	ON_BN_CLICKED(IDC_FileSave, OnFileSave)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CIntegratorDlg message handlers

BOOL CIntegratorDlg::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
	m_Status=("NO DEVICE");
	UpdateData(FALSE);
	
	//default file name
	//m_FileName = "C:\\result1.txt";	
	//Radio button and comboxes default settings
	m_Out_Sel = 0;
	m_ChSel=0;
	m_SrcSel=0;
	m_Looping=0;
	m_Delay = 20;
	m_Gate=255;
	m_Samples=20;
	m_ExtRstTime=20;
	UpdateData(FALSE);




//	CCyUSBDevice *USBDevice;


	USBDevice = new CCyUSBDevice(m_hWnd);   // Create an instance of CCyUSBDevice

	// Look for a device programmed for Bulk Loop (VID = 0547, PID = 1002)
	int devices = USBDevice->DeviceCount();
	int d = 0;
	do {
		USBDevice->Open(d);  // Open automatically calls Close( ) if necessary
		d++;		
	}  while ((d < devices ) && (USBDevice->VendorID != 0x04b4) && (USBDevice->ProductID != 0x8613));


	

    if ((USBDevice->VendorID == 0x04b4) && (USBDevice->ProductID == 0x8613)) {
	m_Status=("FOUND DEVICE");
	UpdateData(FALSE);
		//MessageBox("USB device found");

////MY CODE
		
	CCyControlEndPoint  *ept = USBDevice->ControlEndPt; 
    CCyInterruptEndPoint *InterruptInEndPt = NULL; 
    CCyInterruptEndPoint *InterruptOutEndPt = NULL; 
    CCyIsocEndPoint *IsocInEndPt = NULL; 


//	int lastIntfc = USBDevice->AltIntfcCount( ); 

    //  Select the last Alternate Interface 
    USBDevice->SetAltIntfc(3); 



	unsigned int buf_Adr[10];

      int eptCount =  USBDevice->EndPointCount(); 
      for (int i=1; i<eptCount; i++) 
	{ 
//      bool  bIn  = USBDevice->EndPoints[i]->Address  & 0x80; 
  //    bool  bInt = (USBDevice->EndPoints[i]->Attributes  == 1); 
	  buf_Adr[i] = USBDevice->EndPoints[i]->Address;

   //   if (bInt  && bIn) InterruptInEndPt = (CCyInterruptEndPoint *) USBDevice->EndPoints[i]; 
   //   if (bInt && !bIn) InterruptOutEndPt = (CCyInterruptEndPoint *) USBDevice->EndPoints[i]; 
	 } 


	  	CString display_data;
		display_data.Format("Edpts found: %X,%X,%X,%X,%X,%X",buf_Adr[1],buf_Adr[2],buf_Adr[3],buf_Adr[4],buf_Adr[5],buf_Adr[6]);

    	m_Disp_Data= display_data;
	    UpdateData(FALSE);


	  InterruptInEndPt = (CCyInterruptEndPoint *) USBDevice->EndPoints[2];
	  InterruptOutEndPt = (CCyInterruptEndPoint *) USBDevice->EndPoints[1];
	  IsocInEndPt = (CCyIsocEndPoint *) USBDevice->EndPoints[5];

	
   

	  
	ept->Target    = TGT_DEVICE;  
	ept->ReqType   = REQ_VENDOR;  
	ept->Direction = DIR_TO_DEVICE;   
	ept->ReqCode   = 0xa0;    
	ept->Value     = 0xe600;   //CPUCS
	ept->Index     = 0;  
	unsigned char buf[512];   
	ZeroMemory(buf, 512);  
	LONG buflen =  1;
	buf[0]=1;
	ept->XferData(buf,  buflen);     //RESET cpu
	buf[0] = 0;
	ept->XferData(buf,  buflen); 


	


	}



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

void CIntegratorDlg::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 CIntegratorDlg::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 CIntegratorDlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}



void CIntegratorDlg::OnReady() 
{
	// TODO: Add your control notification handler code here
	
     USBDevice->InterruptOutEndPt->TimeOut = 1000;  // 1 sec timeout 
    USBDevice->InterruptInEndPt->TimeOut = 1000;  // 1 sec timeout 
    
unsigned char buf[16]; 
  LONG length = 12; 
  CString text;
 buf[0] = 0x0b; //command
 buf[1] = 0;    // MSB of status
 
 buf[2] = 0;

 UpdateData(TRUE);
 if(m_Out_Sel == 0)
 {
	 buf[2] = buf[2] | 1;
 }
 else if (m_Out_Sel == 1)
 {
	 buf[2] = buf[2] & 254;
 }


 if(m_ChSel == 1)
 {
	 buf[2] = buf[2] | 2;
 }
 else if (m_ChSel == 0)
 {
	 buf[2] = buf[2] & 253;
 }

 if(m_SrcSel == 1)
 {
	 buf[2] = buf[2] | 4;
 }
 else if (m_SrcSel == 0)
 {
	 buf[2] = buf[2] & 251;
 }

 if(m_Looping == 1)
 {
	 buf[2] = buf[2] | 8;
 }
 else if (m_Looping == 0)
 {
	 buf[2] = buf[2] & 247;
 }




 if (m_Gate >4096 )	
 {
		MessageBox("Maximum Value for Gate is 4096");
		m_Gate=4096;
		UpdateData(FALSE);
		goto exit_error;
 }
 if (m_Delay >65535 ) 
{
		MessageBox("Maximum Value of Delay is 65535");
		m_Delay=65535;
		UpdateData(FALSE);
		goto exit_error;
 }
 if (m_Samples >4096 ) 
{
		MessageBox("Maximum Number of samples is 4096");
		m_Samples=4096;
		UpdateData(FALSE);
		goto exit_error;
 }

 if (m_ExtRstTime >65535 ) 
{
		MessageBox("Maximum Value for Reser is 65535");
		m_Samples=65535;
		UpdateData(FALSE);
		goto exit_error;
 }

 buf[3] = (m_Delay >> 8)/4 ;
 buf[4] = (m_Delay & 255)/4;

 text.Format("%.2f ns",((buf[3]*256+buf[4]) * 5.95*4));
 m_Delay_Time = text;

 buf[5] = (m_Gate >> 8)/4 ;
 buf[6] = (m_Gate & 255)/4;
 text.Format("%.2f ns",((buf[5]*256+buf[6]) * (5.95*4) ));
 m_Gate_Time = text;
 UpdateData(FALSE);

 buf[7] = (m_Samples >>8);
 buf[8] = (m_Samples & 255);

 buf[9] = (m_ExtRstTime >>8 );
 buf[10] = (m_ExtRstTime & 255 );
 text.Format("%.2f ns",((buf[9]*256+buf[10]) * (5.95*4) ));
 m_ResetTime = text;
 UpdateData(FALSE);
 
 
  
  USBDevice->InterruptOutEndPt->XferData(buf, length);




  length = 1; 
  buf[0] = 3;

    USBDevice->InterruptOutEndPt->XferData(buf, length); 

exit_error:
;
}

void CIntegratorDlg::OnStatusBtn() 
{
	// TODO: Add your control notification handler code here
	 unsigned char buf[1]; 
  LONG length = 1; 
  buf[0] = 0x0A;

    USBDevice->InterruptOutEndPt->XferData(buf, length); 

 	


    
    USBDevice->InterruptOutEndPt->TimeOut = 1000;  // 1 sec timeout 
    USBDevice->InterruptInEndPt->TimeOut = 1000;  // 1 sec timeout 
    
    LONG len = 4; 
	unsigned char buffer[5];
	ZeroMemory(buffer,5);

    USBDevice->InterruptInEndPt->XferData(buffer, len); 

	CString display_data;
	display_data.Format("STATUS:%X,%X,%X,%X",buffer[0],buffer[1],buffer[2],buffer[3]);
	m_Disp_Data= display_data;

	if (buffer[1] & 0x80) m_sample_acq = 1;     else m_sample_acq = 0;
	if (buffer[1] & 0x40) m_delay_count = 1;    else m_delay_count = 0;
	if (buffer[1] & 0x20) m_ready = 1;          else m_ready = 0;
	if (buffer[1] & 0x10) m_idle = 1;			else m_idle = 0;
	if (buffer[1] & 0x08) m_int_empty = 1;		else m_int_empty = 0;
	if (buffer[1] & 0x04) m_int_full = 1;		else m_int_full = 0;
	if (buffer[1] & 0x02) m_usb_full = 1;		else m_usb_full = 0;
	if (buffer[1] & 0x01) m_usb_empty = 1;		else m_usb_empty = 0;



	UpdateData(FALSE);


}

void CIntegratorDlg::OnReset() 
{
	 unsigned char buf[1]; 
  LONG length = 1; 
  buf[0] = 0x09;

    USBDevice->InterruptOutEndPt->XferData(buf, length); 

	
}

void CIntegratorDlg::OnCancel() 
{
	// TODO: Add extra cleanup here
	USBDevice->Close();
	CDialog::OnCancel();
}

void CIntegratorDlg::OnResDev() 
{
	// TODO: Add your control notification handler code here
			
	OnInitDialog();
	
}

void CIntegratorDlg::OnStartTX() 
{
	// TODO: Add your control notification handler code here

  	unsigned char buf[5]; 
    LONG length = 1; 
    buf[0] = 0x0A;

    USBDevice->InterruptOutEndPt->XferData(buf, length); 

    USBDevice->InterruptOutEndPt->TimeOut = 1000;  // 1 sec timeout 
    USBDevice->InterruptInEndPt->TimeOut = 1000;  // 1 sec timeout 
    
    LONG len = 4; 

    USBDevice->InterruptInEndPt->XferData(buf, len); 
	
   rx_length=(buf[3]+buf[2]*256);	
   rx_length=rx_length*2;
   length = 1;
   buf[0] = 8;
   USBDevice->InterruptOutEndPt->XferData(buf, length); 


 for (int m=0;m<1000;m++)
 {
	 for (int l=0;l<1000;l++) 
	 {
		 buf[0]=8;
	 }
 
 };




  ZeroMemory(bufer_rx,65535);
    length = rx_length;
  USBDevice->IsocInEndPt->XferData(bufer_rx,length); 



	CString display_data;
	display_data.Format("%X,%X,%X,%X,%X,%X",bufer_rx[0],bufer_rx[1],bufer_rx[2],bufer_rx[3],bufer_rx[4],bufer_rx[5]);

   	m_Result= display_data;
    UpdateData(FALSE);




}

void CIntegratorDlg::OnChangeGate() 
{
	// TODO: If this is a RICHEDIT control, the control will not
	// send this notification unless you override the CDialog::OnInitDialog()
	// function and call CRichEditCtrl().SetEventMask()
	// with the ENM_CHANGE flag ORed into the mask.

	// TODO: Add your control notification handler code here
	
}


void CIntegratorDlg::OnFileSave() 
{
	// TODO: Add your control notification handler code here
	FILE *plik;
	UpdateData(TRUE);
	plik=fopen(m_FileName,"a");
	fputs("NewData\n",plik);



	for(int i=0; i<rx_length-2;i++)
	{
	 fprintf(plik, "%d\n", ((bufer_rx[i+1]*256) + bufer_rx[i]) );
	i++;
	}

	fclose(plik);
	
}
