//---------------------------------------------------------------------------
#include <vcl.h>

#pragma hdrstop

#include "DataDownload.h"


//---------------------------------------------------------------------------

#pragma package(smart_init)

#define PCI_VID     0x1172
#define PCI_PID     0xE001

#define ALTERA_REG_DMACSR 0x00

__fastcall TDataDownload::TDataDownload():
    m_bFPGAReady(false),
    m_pData(NULL),
    m_dwDataSize(0)
{
    //TODO: Add your source code here
    if (!m_FPGA.IsDriverAvailable()){
        MessageDlg("Fail to load driver!",  mtError, TMsgDlgButtons() << mbOK, 0);
    }else if (!m_FPGA.Open(PCI_VID, PCI_PID)){
        MessageDlg("Fail to connect PCI board!",  mtError, TMsgDlgButtons() << mbOK, 0);
    }else{
        m_bFPGAReady = true;
    }
}

__fastcall TDataDownload::~TDataDownload()
{
    //TODO: Add your source code here
    if (m_pData)
        ::GlobalFree(m_pData);
    m_FPGA.Close();
}



bool __fastcall TDataDownload::SetData(BYTE * pData, DWORD dwDataSize)
{
    //TODO: Add your source code here

if (!pData)
     return false;
    memcpy(pData, m_pData, 640*480*16);  // m_pData ->  pData

    return true;
}

bool __fastcall TDataDownload::Download(void)
{

    //TODO: Add your source code here
    if (m_pData)
         ::GlobalFree(m_pData);
    m_dwDataSize = 640*480*16;
     m_pData = (BYTE *)::GlobalAlloc(GPTR, m_dwDataSize);
     //allocation success?
       if (!m_pData)
         return false;
    bool bSuccess;
    PCIE_LOCAL_FIFO_ID FifoId = 0;
    bSuccess = m_FPGA.DmaFifoRead(FifoId, m_pData, m_dwDataSize);  
    return bSuccess;
}

bool __fastcall TDataDownload::IsFull(void)
{
return false;
    //TODO: Add your source code here
    bool bFull = true;
    PCIE_BAR PciBar = PCIE_BAR1;
    PCIE_ADDRESS PciAddress = ALTERA_REG_DMACSR;
    DWORD dwData;
    if (m_FPGA.Read32(PciBar,PciAddress,&dwData)){
        if ((dwData & 0x04) == 0)
            bFull = false;
    }else{
        MessageDlg("Fail to read IsFull register!",  mtError, TMsgDlgButtons() << mbOK, 0);
    }
    return bFull;
}

bool TDataDownload::IsReady(void)
{
    //TODO: Add your source code here
    return m_bFPGAReady;
}  

DWORD __fastcall TDataDownload::DataSize(void){
    if (!m_pData)
        return 0;
    return m_dwDataSize;
}

