// InitCardDlg.cpp : implementation file
//

#include "stdafx.h"
#include "InitCard.h"
#include "InitCardDlg.h"
#include ".\initcarddlg.h"
#include "RQProtected.h"
#include "PRXProtected.h"
#include "NDTSErrorInternal.h"

#include "Inc\PlxApi.h"
#include "Inc\Reg9056.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

// these are obsolete and so we just ignore them
#define RQ_HandlePciError(X,Y)
#define RQ_HandleRQError(X,Y)

static unsigned long rapidaqs_found;
static unsigned long prx_found;
static unsigned long uninit_found;
static unsigned long total_found;

// CAboutDlg dialog used for App About

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

// Dialog Data
	enum { IDD = IDD_ABOUTBOX };

	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support

// Implementation
protected:
	DECLARE_MESSAGE_MAP()
};

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

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

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
END_MESSAGE_MAP()


// CInitCardDlg dialog



CInitCardDlg::CInitCardDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CInitCardDlg::IDD, pParent)
{
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CInitCardDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	DDX_Control(pDX, IDC_EDIT1, m_resultCode);
	DDX_Control(pDX, IDC_LIST2, m_NEWList);
	DDX_Control(pDX, IDC_LIST3, m_RQList);
	DDX_Control(pDX, IDC_LIST4, m_PRXList);
	DDX_Control(pDX, IDC_EDIT2, m_RQserialNum);
	//DDX_Control(pDX, IDC_EDIT3, m_RQcalibrationFlags);
	DDX_Control(pDX, IDC_EDIT4, m_PRXserialNum);
}

BEGIN_MESSAGE_MAP(CInitCardDlg, CDialog)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	//}}AFX_MSG_MAP
	ON_BN_CLICKED(IDC_BUTTON1, OnBnClickedButton1)
	ON_BN_CLICKED(IDC_BUTTON2, OnBnClickedButton2)
	ON_BN_CLICKED(IDC_BUTTON3, OnBnClickedButton3)
	ON_BN_CLICKED(IDC_BUTTON4, OnBnClickedButton4)
	ON_BN_CLICKED(IDC_BUTTON5, OnBnClickedButton5)
	ON_BN_CLICKED(IDC_BUTTON6, OnBnClickedButton6)
	ON_BN_CLICKED(IDC_BUTTON7, OnBnClickedButton7)
	ON_BN_CLICKED(IDC_BUTTON8, OnBnClickedButton8)
END_MESSAGE_MAP()


// CInitCardDlg message handlers

BOOL CInitCardDlg::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

	m_resultCode.SetWindowText("Ready");
	OnBnClickedButton5(); // populate the card lists

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

void CInitCardDlg::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 CInitCardDlg::OnPaint() 
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, reinterpret_cast<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 function to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CInitCardDlg::OnQueryDragIcon()
{
	return static_cast<HCURSOR>(m_hIcon);
}

const unsigned long rapidaq_secondary_id = 0x52443851; // RDAQ
const unsigned long pulser_secondary_id = 0x504C5258; // PLRX

// These days we only assign unassigned cards.
// We can unassign PRX or RQ cards.
// However we only allow any of these operations when there can be no ambiguity.
// To be pedantic we insist that there's only one PLX card in the system
bool CInitCardDlg::assignCard(RQ_SecondaryIDs id)
{
	RETURN_CODE PciReturnCode ;
	DEVICE_LOCATION device;
	HANDLE hDevice;
	U32 d = (U32)0; // first matching device
	RETURN_CODE rc;

	// Grab the first PLX-chipped device we see
	device.BusNumber = (U8) -1 ; 
	device.SlotNumber = (U8) -1 ; 
	device.VendorId = (U16) 0x10b5 ; // pci Vendor ID ; 
	device.DeviceId = (U16) -1 ; 
	device.SerialNumber[0] = 0 ; 

	PciReturnCode = PlxPciDeviceFind(&device, &d) ;
	if (PciReturnCode != ApiSuccess)
	{
		AfxMessageBox("Couldn't find device", MB_OK);
		return false;
	}

	// Open the device and see what it is
	PciReturnCode = PlxPciDeviceOpen(&device, &hDevice) ;
	if (PciReturnCode != ApiSuccess)
	{
		AfxMessageBox("Couldn't open device", MB_OK);
		return false;
	}

	PlxSerialEepromPresent(hDevice, &rc);
	if (rc == ApiSuccess)
	{
		U32 secondaryId;
		const U16 secondary_id_offset_in_eeprom = 0x44;

		// FROG for development testing
		rc = PlxSerialEepromReadByOffset(hDevice, secondary_id_offset_in_eeprom, &secondaryId);

		rc = PlxSerialEepromWriteByOffset(hDevice, secondary_id_offset_in_eeprom, id);

		if (rc != ApiSuccess)
		{
			// Couldn't write secondary device ID
			AfxMessageBox("Couldn't set device type", MB_OK);
			PlxPciDeviceClose(hDevice) ;
			return false;
		}
	}
	else
	{
		AfxMessageBox("Couldn't access device identifier", MB_OK);
		PlxPciDeviceClose(hDevice) ;
		return false;
	}

	PlxPciDeviceClose(hDevice) ;

	// rebuild the list
	OnBnClickedButton5();

	AfxMessageBox("A device type has changed so you should restart Windows to re-detect it", MB_OK);

	return true;
}

// assign unassigned card as RQ
void CInitCardDlg::OnBnClickedButton1()
{
	// Only try to assign if there's exactly 1 card present
	if ((m_NEWList.GetCount() != 1) ||
		(m_RQList.GetCount() != 0) ||
		(m_PRXList.GetCount() != 0))
	{
		AfxMessageBox("Assigning cards is only allowed when there is exactly 1 card in the system", MB_OK);
		return;
	}

	m_resultCode.SetWindowText("Busy");

	int card;
	DWORD identifier = (DWORD)m_NEWList.GetItemData(0);
	card = (identifier & 0x0000ff00) >> 8;
	m_resultCode.SetWindowText(assignCard(RQ_SIDRapiDAQ) ? "Success" : "failed");

	OnBnClickedButton5(); // rebuild the card list
}

// assign unassigned card as PRX
void CInitCardDlg::OnBnClickedButton2()
{
	// Only try to assign if there's exactly 1 card present
	if ((m_NEWList.GetCount() != 1) ||
		(m_RQList.GetCount() != 0) ||
		(m_PRXList.GetCount() != 0))
	{
		AfxMessageBox("Assigning cards is only allowed when there is exactly 1 card in the system", MB_OK);
		return;
	}

	m_resultCode.SetWindowText("Busy");

	int card;
	DWORD identifier = (DWORD)m_NEWList.GetItemData(0);
	card = (identifier & 0x0000ff00) >> 8;
	m_resultCode.SetWindowText(assignCard(RQ_SIDPRX) ? "Success" : "failed");
	OnBnClickedButton5(); // rebuild the card list
}

// In RS1 we stored the calibration values in EEPROM:
// word 1 contains the magic number 0x55aa1234
// words 2 to 7 contain the zero offsets for input ranges 0 to 5
// words 8 to 13 contain the gain trim values for input ranges 0 to 5
// words 14 and 15 are unused in RS1
// In RS2 we used to store the magic number 0x123455aa at offset 14
// Now it's  0x1234aa55 (indicates that calibration flags are used differently
// word 15 contains the serial number for the card
// word 16 contains a bit mask which can be used with dodgy boards to prevent certain channels
// from being calibrated

// 'program card' button for RQ
void CInitCardDlg::OnBnClickedButton4()
{
	char userText[11];
	unsigned long serialNum;
	// Program the serial number into the card
	int card;

	if (m_RQList.GetCount() != 1)
	{
		AfxMessageBox("Programming RQ details is only permitted when there is exactly 1 RQ card present", MB_OK);
		return;
	}

	DWORD identifier = (DWORD)m_RQList.GetItemData(0);
	if (identifier & 0x00ff0000)
	{
		AfxMessageBox("Can't set a serial number for this card because it can't be initialised", MB_OK);
		return;
	}

	m_resultCode.SetWindowText("Busy");
	card = identifier & 0x000000ff;

	// Ooh my word
	// This reads the serial number into userText and null-terminates it
	userText[m_RQserialNum.GetLine(0, userText, 10)] = 0;
	sscanf(userText, "%uld", &serialNum);

	if (RQ_SetEEPROM(card, 14, 0x1234aa55) != NDTS_BTrue)
	{
		AfxMessageBox("Signature write failed", MB_OK);
		goto Exit;
	}

	if (RQ_SetEEPROM(card, 15, serialNum) != NDTS_BTrue)
	{
		AfxMessageBox("Serial number write failed", MB_OK);
		goto Exit;
	}

	// clear calibration flags
	//if (RQ_SetEEPROM(card, 16, calibrationFlags) != NDTS_BTrue)
	//{
	//	AfxMessageBox("Calibration flags write failed", MB_OK);
	//	goto Exit;
	//}

Exit:
	// Finally rebuild the card list
	OnBnClickedButton5();
	m_resultCode.SetWindowText("Ready");
}

void CInitCardDlg::OnBnClickedButton5()
{
	// list all cards with PLX chips

	RETURN_CODE PciReturnCode ;
	unsigned long devNum;
	DEVICE_LOCATION device;
	HANDLE hDevice;
	U32 d;
	RETURN_CODE rc;

	m_NEWList.ResetContent();
	m_RQList.ResetContent();
	m_PRXList.ResetContent();

	rapidaqs_found = 0;
	prx_found = 0;
	uninit_found = 0;
	total_found = 0;

	if (RQ_PCIEnumerate(&rapidaqs_found) != NDTS_BTrue)
	{
		AfxMessageBox("Fatal error: Couldn't enumerate RapiDAQ cards", MB_OK);
		return;
	}

	if (PRX_PCIEnumerate(&prx_found) != NDTS_BTrue)
	{
		AfxMessageBox("Fatal error: Couldn't enumerate PRX cards", MB_OK);
		return;
	}

	rapidaqs_found = 0;
	prx_found = 0;

	devNum = FIND_AMOUNT_MATCHED;
	
	device.BusNumber = (U8) -1 ; 
	device.SlotNumber = (U8) -1 ; 
	device.VendorId = (U16) 0x10b5 ; // pci Vendor ID ; 
	device.DeviceId = (U16) -1 ; 
	device.SerialNumber[0] = 0 ; 
	
	PciReturnCode = PlxPciDeviceFind(&device, &devNum) ;
	if (PciReturnCode != ApiSuccess)
	{
		m_NEWList.AddString("No cards found");
		return; // there's a problem so report no devices found
	}

	// Now attempt to open each device and see which are which
	for (d = 0; d < devNum; d++)
	{
		device.BusNumber = (U8) -1 ; 
		device.SlotNumber = (U8) -1 ; 
		device.VendorId = (U16) 0x10b5 ; // pci Vendor ID ; 
		device.DeviceId = (U16) -1 ; 
		device.SerialNumber[0] = 0 ; 
		PciReturnCode = PlxPciDeviceFind(&device, &d) ;
		if (PciReturnCode != ApiSuccess)
		{
			RQ_HandlePciError(0, PciReturnCode) ;
			RQ_HandleRQError(0, RQ_Initialise_FindPCIDeviceFail) ;
			continue;
		}

		// Open the device and see what it is
		PciReturnCode = PlxPciDeviceOpen(&device, &hDevice) ;
		if (PciReturnCode != ApiSuccess)
		{
			RQ_HandlePciError(0, PciReturnCode) ;
			RQ_HandleRQError(0, RQ_Initialise_PCIDeviceOpenFail) ;
			continue;
		}

		// Try to read the EEPROM
		PlxSerialEepromPresent(hDevice, &rc);
		if (rc == ApiSuccess)
		{
			U32 secondaryId;
			const U16 secondary_id_offset_in_eeprom = 0x44;
			unsigned long EEval;
			CString msg;

			rc = PlxSerialEepromReadByOffset(hDevice, secondary_id_offset_in_eeprom, &secondaryId);

			if(rc != ApiSuccess)
			{
				// Couldn't read secondary device ID
			}
			else
			{
				if (secondaryId == RQ_SIDRapiDAQ)
				{
					DWORD idMask = 0x80000000;

					msg.Format("RQ Card %d on bus %d in slot %d", 
							   rapidaqs_found, device.BusNumber, device.SlotNumber);

					RQ_Uninitialise(rapidaqs_found); // this will fail if the card isn't initialised but never mind

					// Don't try to calibrate the card at this stage
					//if (RQ_InitialiseProtected(rapidaqs_found, (RQ_SamplingFirmwareVersion)0x110, (RQ_PeripheralFirmwareVersion)0x00d, NDTS_BFalse) != NDTS_BTrue)
					if (RQ_InitialiseProtected(rapidaqs_found, NDTS_BFalse, NDTS_BTrue) != NDTS_BTrue)
					{
						msg.Append(" init failed");
						idMask |= 0x00800000;
						goto listAbortRQ;
					}

					if (RQ_GetEEPROM(rapidaqs_found, 14, &EEval) != NDTS_BTrue)
					{
						msg.Append(" couldn't read signature from EEPROM");
						// complain
						goto listAbortRQ;
					}
					if (EEval == 0x123455aa)
					{
						msg.Append(" (old signature)");
						goto listAbortRQ;
					}
					else if (EEval != 0x1234aa55)
					{
						msg.Append(" signature not found");
						goto listAbortRQ;
					}

					if (RQ_GetEEPROM(rapidaqs_found, 15, &EEval) != NDTS_BTrue)
					{
						msg.Append(" couldn't read serial number from EEPROM");
						goto listAbortRQ;
					}

					// output the serial number
					msg.AppendFormat(" serial no. %d", EEval);
					{
						CString ee;
						ee.Format("%d", EEval);
						m_RQserialNum.SetWindowText(ee);
					}

					if (RQ_GetEEPROM(rapidaqs_found, 16, &EEval) != NDTS_BTrue)
					{
						msg.Append(" couldn't read calibration mask from EEPROM");
						goto listAbortRQ;
					}

					msg.AppendFormat(" calib. mask is 0x%04x", EEval);

listAbortRQ:
					int pos = m_RQList.AddString(msg);
					m_RQList.SetItemData(pos, idMask + rapidaqs_found + (total_found << 8));
					total_found++;
					rapidaqs_found++;
				}
				else if (secondaryId == RQ_SIDPRX)
				{
					DWORD idMask = 0x40000000;

					msg.Format("PRX Card %d on bus %d in slot %d", 
							   prx_found, device.BusNumber, device.SlotNumber);

					PRX_Uninitialise(prx_found); // this will fail if the card isn't initialised but never mind

					if (PRX_Initialise(prx_found) != NDTS_BTrue)
					{
						msg.Append(" couldn't initialise card");
						idMask |= 0x00800000;
						goto listAbortPRX;
					}

					if (PRX_GetEEPROM(prx_found, 14, &EEval) != NDTS_BTrue)
					{
						msg.Append(" couldn't read signature from EEPROM");
						// complain
						goto listAbortPRX;
					}
					if (EEval == 0x123455aa)
					{
						msg.Append(" (old signature)");
						goto listAbortPRX;
					}
					if (EEval != 0x1234aa55)
					{
						msg.Append(" signature not found");
						goto listAbortPRX;
					}

					if (PRX_GetEEPROM(prx_found, 15, &EEval) != NDTS_BTrue)
					{
						msg.Append(" couldn't read serial number from EEPROM");
						goto listAbortPRX;
					}

					// output the serial number
					msg.AppendFormat(" serial no. %d", EEval);
					{
						CString ee;
						ee.Format("%d", EEval);
						m_PRXserialNum.SetWindowText(ee);
					}

listAbortPRX:
					int pos = m_PRXList.AddString(msg);
					m_PRXList.SetItemData(pos, idMask + prx_found + (total_found << 8));

					total_found++;
					prx_found++;
				}
				else
				{
					msg.Format("Uninitialised Card %d on bus %d in slot %d", 
							   uninit_found, device.BusNumber, device.SlotNumber);
					int pos = m_NEWList.AddString(msg);
					m_NEWList.SetItemData(pos, (total_found << 8));
					total_found++;
					uninit_found++;
				}
			}
		}

		PciReturnCode = PlxPciDeviceClose(hDevice) ;
	}
}

// 'program card' button for PRX
void CInitCardDlg::OnBnClickedButton6()
{
	char userText[11];
	unsigned long serialNum;
	unsigned long calibrationFlags;
	// Program the serial number into the card
	int card;

	if (m_PRXList.GetCount() != 1)
	{
		AfxMessageBox("Programming PRX details is only permitted when there is exactly 1 RQ card present", MB_OK);
		return;
	}

	DWORD identifier = (DWORD)m_PRXList.GetItemData(0);
	if (identifier & 0x00ff0000)
	{
		AfxMessageBox("Can't set a serial number for this card because it can't be initialised", MB_OK);
		return;
	}

	m_resultCode.SetWindowText("Busy");
	card = identifier & 0x000000ff;

	m_PRXserialNum.GetLine(0, userText, 10);
	sscanf(userText, "%uld", &serialNum);

	calibrationFlags = 0;

	if (PRX_SetEEPROM(card, 14, 0x1234aa55) != NDTS_BTrue)
	{
		AfxMessageBox("Signature write failed", MB_OK);
		goto Exit;
	}

	if (PRX_SetEEPROM(card, 15, serialNum) != NDTS_BTrue)
	{
		AfxMessageBox("Serial number write failed", MB_OK);
		goto Exit;
	}

	if (PRX_SetEEPROM(card, 16, calibrationFlags) != NDTS_BTrue)
	{
		AfxMessageBox("Calibration flags write failed", MB_OK);
		goto Exit;
	}

Exit:
	// Rebuild the card list
	OnBnClickedButton5();
	m_resultCode.SetWindowText("Ready");
}

// Deassign RQ
void CInitCardDlg::OnBnClickedButton7()
{
	// Only try to assign if there's exactly 1 unassigned card
	if ((m_RQList.GetCount() != 1) ||
		(m_PRXList.GetCount() != 0) ||
		(m_NEWList.GetCount() != 0))
	{
		AfxMessageBox("Deassigning a card is only allowed when this is the only card in the system", MB_OK);
		return;
	}

	if (!makeAbsolutelyCertain())
	{
		AfxMessageBox("Deassignment aborted", MB_OK);
		return;
	}

	int card;
	DWORD identifier = (DWORD)m_NEWList.GetItemData(0);
	card = (identifier & 0x0000ff00) >> 8;
	m_resultCode.SetWindowText("Busy");

	if(assignCard((RQ_SecondaryIDs)0))
	{
		AfxMessageBox("Deassign complete.", MB_OK);
	}
	else
	{
		AfxMessageBox("Deassign card failed", MB_OK);
	}
	//m_resultCode.SetWindowText(assignCard((RQ_SecondaryIDs)0) ? "Success" : "failed");
	OnBnClickedButton5(); // rebuild the card list
	m_resultCode.SetWindowText("Ready");
}

// Deassign PRX
void CInitCardDlg::OnBnClickedButton8()
{
	// Only try to assign if there's exactly 1 unassigned card
	if ((m_PRXList.GetCount() != 1) ||
		(m_RQList.GetCount() != 0) ||
		(m_NEWList.GetCount() != 0))
	{
		AfxMessageBox("Deassigning a card is only allowed when this is the only card in the system", MB_OK);
		return;
	}

	if (!makeAbsolutelyCertain())
	{
		AfxMessageBox("Deassignment aborted", MB_OK);
		return;
	}

	int card;
	DWORD identifier = (DWORD)m_NEWList.GetItemData(0);
	card = (identifier & 0x0000ff00) >> 8;
	m_resultCode.SetWindowText("Busy");

	if(assignCard((RQ_SecondaryIDs)0))
	{
		AfxMessageBox("Deassign complete.", MB_OK);
	}
	else
	{
		AfxMessageBox("Deassign card failed", MB_OK);
	}
	//m_resultCode.SetWindowText(assignCard((RQ_SecondaryIDs)0) ? "Success" : "failed");
	OnBnClickedButton5(); // rebuild the card list
	m_resultCode.SetWindowText("Ready");
}

bool CInitCardDlg::makeAbsolutelyCertain()
{
	if (AfxMessageBox("Are you sure?", MB_YESNO) != IDYES) return false;
	if (AfxMessageBox("You won't be able to use the card again until it is reassigned.  Would you like to reconsider?", MB_YESNO) != IDNO) return false;

	return true;
}

// 'clear calibration' button for RQ
void CInitCardDlg::OnBnClickedButton3()
{
	int card;

	if (m_RQList.GetCount() != 1)
	{
		AfxMessageBox("Programming RQ details is only permitted when there is exactly 1 RQ card present", MB_OK);
		return;
	}

	DWORD identifier = (DWORD)m_RQList.GetItemData(0);
	if (identifier & 0x00ff0000)
	{
		AfxMessageBox("Can't program this card because it can't be initialised", MB_OK);
		return;
	}

	m_resultCode.SetWindowText("Busy");
	card = identifier & 0x000000ff;

	// clear calibration flags
	if (RQ_SetEEPROM(card, 16, 0) != NDTS_BTrue)
	{
		AfxMessageBox("Calibration flags write failed", MB_OK);
		goto Exit;
	}

Exit:
	// Finally rebuild the card list
	OnBnClickedButton5();
	m_resultCode.SetWindowText("Ready");
}
