#include "cpowermeterdriver_fp.h"
#include "cpowermeter.h"
#define COMPLIEPOWERMETER
int32_t CPowerMeterDriver_FP::init_driver()
{

#ifdef COMPLIEPOWERMETER
    int iSerialID= m_Variants.get_VData(Var_Base_SerialID_ID)->toInt();
    FT_STATUS status=FT_Open(iSerialID,&m_ftHandle);
    if (status)
    {
        MQT_THROW_STR(GetLastError(status));
    }
#endif
    return 0;
}

int32_t CPowerMeterDriver_FP::exit_driver()
{
    FT_Close(m_ftHandle);
    return 0;
}

CPowerMeterDriver_FP::CPowerMeterDriver_FP(const QString& name,int32_t id)
    :CPowerMeterDriver(name,id)
{

    lib = LoadLibraryA("ftd2xx.dll");
    FT_Open = reinterpret_cast<FP_FT_Open>(GetProcAddress(lib, "FT_Open"));
    FT_Close = reinterpret_cast<FP_FT_Close>(GetProcAddress(lib, "FT_Close"));
    FT_Read = reinterpret_cast<FP_FT_Read>(GetProcAddress(lib, "FT_Read"));
    FT_Write = reinterpret_cast<FP_FT_Write>(GetProcAddress(lib, "FT_Write"));

    FT_Purge= reinterpret_cast<FP_FT_Purge>(GetProcAddress(lib, "FT_Purge"));
    FT_GetQueueStatus= reinterpret_cast<FP_FT_GetQueueStatus>(GetProcAddress(lib, "FT_GetQueueStatus"));
    FT_GetStatus= reinterpret_cast<FP_FT_GetStatus>(GetProcAddress(lib, "FT_GetStatus"));

}

int32_t CPowerMeterDriver_FP::freshresult(int32_t chid)
{
    CPowerMeter* pHead=(CPowerMeter*)FindChannel(chid);
    char ch_response[RESPONSELENGTH]={0};
    SendCommand("OUTPM",ch_response);
    pHead->m_Variants.get_VData(Var_PowerMeter_MeasResult_ID)->setValue((double)atof(ch_response));
    return RTN_SUCCESS1;
}

int32_t CPowerMeterDriver_FP::SetZero(int32_t chid)
{
    UNUSED(chid);
    char ch_response[RESPONSELENGTH]={0};
    SendCommand("ZERO",ch_response);
    if (strcmp(ch_response,"ok"))
    {
        MQT_THROW_STR(QObject::trUtf8("Powermeter setZero err."));
    }
    return 0;
}

QString CPowerMeterDriver_FP::GetLastError(FT_STATUS status)
{

    switch(status)
    {
    case 0: return "FT_OK" ;
    case 1:  return "FT_INVALID_HANDLE"  ;
    case 2:  return "FT_DEVICE_NOT_FOUND"  ;
    case 3:  return "FT_DEVICE_NOT_OPENED"  ;
    case 4:  return "FT_IO_ERROR"  ;
    case 5:  return "FT_INSUFFICIENT_RESOURCES"  ;
    case 6:  return "FT_INVALID_PARAMETER"  ;
    case 7:  return "FT_INVALID_BAUD_RATE"  ;
    case 8:  return "FT_DEVICE_NOT_OPENED_FOR_ERASE" ;
    case 9:  return "FT_DEVICE_NOT_OPENED_FOR_WRITE" ;
    case 10:  return "FT_FAILED_TO_WRITE_DEVICE"  ;
    case 11:  return "FT_EEPROM_READ_FAILED" ;
    case 12:  return "FT_EEPROM_WRITE_FAILED"  ;
    case 13:  return "FT_EEPROM_ERASE_FAILED" ;
    case 14:  return "FT_EEPROM_NOT_PRESENT"  ;
    case 15:  return "FT_EEPROM_NOT_PROGRAMMED"  ;
    case 16:  return "FT_INVALID_ARGS"  ;
    default:Q_ASSERT(0);
    }
    return "";
}

