

#include "sys_GraphicsDrawing.h"
#include "TestCodec.h"
#include "../seq/Reception_board_interface.h"

using namespace uji::sys;
using namespace uji::seq;


static bool s_InitializeCodecHardwareCheck = false;
static nn::Handle s_Session;

namespace uji {
namespace eva {
namespace codec {


/*---------------------------------------------------------------------------
  Desc: Initialize

  Args: pSession        セッション
        group           ヘッダグループ

  Rtns: nn::Result      処理の結果
---------------------------------------------------------------------------*/
nn::Result TestCodec::InitializeCodecGroup(nn::Handle* pSession, u8 group)
{
    nn::Result result;
    switch(group)
    {
    case HID:       result = nn::codec::CTR::InitializeHID(pSession);
    case Mic:       result = nn::codec::CTR::InitializeMic(pSession);
    case Csnd:      result = nn::codec::CTR::InitializeCsnd(pSession);
    case Dsp:       result = nn::codec::CTR::InitializeDsp(pSession);
    case Lgy:       result = nn::codec::CTR::InitializeLgy(pSession);
    case Check:     result = nn::codec::CTR::InitializeCheck(pSession);
    }
    return result;
}

/*---------------------------------------------------------------------------
  Desc: Finalize

  Args: pSession        セッション
        group           ヘッダグループ

  Rtns: nn::Result      処理の結果
---------------------------------------------------------------------------*/
nn::Result TestCodec::FinalizeCodecGroup(nn::Handle* pSession, u8 group)
{
    nn::Result result;
    switch(group)
    {
    case HID:       result = nn::codec::CTR::FinalizeHID(pSession);
    case Mic:       result = nn::codec::CTR::FinalizeMic(pSession);
    case Csnd:      result = nn::codec::CTR::FinalizeCsnd(pSession);
    case Dsp:       result = nn::codec::CTR::FinalizeDsp(pSession);
    case Lgy:       result = nn::codec::CTR::FinalizeLgy(pSession);
    case Check:     result = nn::codec::CTR::FinalizeCheck(pSession);
    }
    return result;
}

/*---------------------------------------------------------------------------
  Desc: codec の HardwareCheck ポートを開放（イニシャライズ）
---------------------------------------------------------------------------*/
void TestCodec::TestInitializeCommon()
{
    nn::Result result;
    
    if( s_InitializeCodecHardwareCheck==false )
    {
        // 初期化
        result = InitializeCodecGroup(&s_Session, Check);
        if (result.IsFailure())
        {
            NN_LOG("* Error: Fail to Initialize Codec HWCheck!\n");
        }
        
        s_InitializeCodecHardwareCheck = true;
     }
}

/*---------------------------------------------------------------------------
  Desc: SPI1 を使用して CODEC の Vendor ID をリード
---------------------------------------------------------------------------*/
void TestCodec::TestReadMultiEx_SPI1_VendorId()
{
    nn::Result result;
    
    TestInitializeCommon();
    
    nn::codec::CTR::HardwareCheck hc(s_Session);
    
    // Vendor ID を read
    result = hc.ReadMultiEx_SPI1( 0, 2, &m_VendorId_SPI1,   1 );
    if (result.IsFailure())
    {
        NN_LOG("* Error: Fail to read Revision ID!\n");
    }
    
}

/*---------------------------------------------------------------------------
  Desc: SPI2 を使用して CODEC の Vendor ID をリード
---------------------------------------------------------------------------*/
void TestCodec::TestReadMultiEx_SPI2_VendorId()
{
    nn::Result result;
    
    TestInitializeCommon();
    
    nn::codec::CTR::HardwareCheck hc(s_Session);
    
    // Vendor ID を read
    result = hc.ReadMultiEx_SPI2( 0, 2, &m_VendorId_SPI2,   1 );
    if (result.IsFailure())
    {
        NN_LOG("* Error: Fail to read Revision ID!\n");
    }
    
}

/*---------------------------------------------------------------------------
  Desc: SPI1 を使用して CODEC の Revision ID をリード
---------------------------------------------------------------------------*/
void TestCodec::TestReadMultiEx_SPI1_RevisionId()
{
    nn::Result result;
    
    TestInitializeCommon();
    
    nn::codec::CTR::HardwareCheck hc(s_Session);
    
    // Revision ID を read
    result = hc.ReadMultiEx_SPI1( 0, 3, &m_RevisionId_SPI1, 1 );
    if (result.IsFailure())
    {
        NN_LOG("* Error: Fail to read Revision ID!\n");
    }
    
}

/*---------------------------------------------------------------------------
  Desc: SPI2 を使用して CODEC の Revision ID をリード
---------------------------------------------------------------------------*/
void TestCodec::TestReadMultiEx_SPI2_RevisionId()
{
    nn::Result result;
    
    TestInitializeCommon();
    
    nn::codec::CTR::HardwareCheck hc(s_Session);
    
    // Revision ID を read
    result = hc.ReadMultiEx_SPI2( 0, 3, &m_RevisionId_SPI2, 1 );
    if (result.IsFailure())
    {
        NN_LOG("* Error: Fail to read Revision ID!\n");
    }
    
}

/*---------------------------------------------------------------------------
  Desc: CODEC の MIC PGA Gain Calibration をリード
---------------------------------------------------------------------------*/
void TestCodec::TestReadMultiEx_SPI2_MicPgaGainCalibration()
{
    nn::Result result;
    
    TestInitializeCommon();
    
    nn::codec::CTR::HardwareCheck hc(s_Session);
    
    // Vendor ID を read
    result = hc.ReadMultiEx_SPI2( 101, 65, &m_MicPgaGainCalibration_SPI2,   1 );
    if (result.IsFailure())
    {
        NN_LOG("* Error: Fail to read MIC PGA Gain Calibration!\n");
    }
}

/*---------------------------------------------------------------------------
  Desc: CODEC の MIC PGA Gain Calibration をライト
---------------------------------------------------------------------------*/
void TestCodec::TestWriteMultiEx_SPI2_MicPgaGainCalibration(u8* setMicPgaGainCalibration)
{
    nn::Result result;
    
    TestInitializeCommon();
    
    nn::codec::CTR::HardwareCheck hc(s_Session);
    
    // Revision ID を write
    result = hc.WriteMultiEx_SPI2( 101, 65, setMicPgaGainCalibration, 1 );
    if (result.IsFailure())
    {
        NN_LOG("* Error: Fail to read MIC PGA Gain Calibration!\n");
    }
}

/*---------------------------------------------------------------------------
  Desc: CODEC の ボリューム優先設定 をライト
---------------------------------------------------------------------------*/
void TestCodec::TestSetVolumeSetting(u8* setVolumeSetting)
{
    nn::Result result;
    
    TestInitializeCommon();
    
    nn::codec::CTR::HardwareCheck hc(s_Session);
    
    // Revision ID を write
    result = hc.WriteMultiEx_SPI1( 0, 116, setVolumeSetting, 1 );
    if (result.IsFailure())
    {
        NN_LOG("* Error: Fail to write Volume setting!\n");
    }
}

/*---------------------------------------------------------------------------
  Desc: CODEC の 左ボリューム値 をライト
---------------------------------------------------------------------------*/
void TestCodec::TestSetLeftVolume(u8* setLeftVolume)
{
    nn::Result result;
    
    TestInitializeCommon();
    
    nn::codec::CTR::HardwareCheck hc(s_Session);
    
    // Revision ID を write
    result = hc.WriteMultiEx_SPI1( 0, 65, setLeftVolume, 1 );
    if (result.IsFailure())
    {
        NN_LOG("* Error: Fail to write Left volume!\n");
    }
}

/*---------------------------------------------------------------------------
  Desc: CODEC の 右ボリューム値 をライト
---------------------------------------------------------------------------*/
void TestCodec::TestSetRightVolume(u8* setRightVolume)
{
    nn::Result result;
    
    TestInitializeCommon();
    
    nn::codec::CTR::HardwareCheck hc(s_Session);
    
    // Revision ID を write
    result = hc.WriteMultiEx_SPI1( 0, 66, setRightVolume, 1 );
    if (result.IsFailure())
    {
        NN_LOG("* Error: Fail to write Right volume!\n");
    }
}

/*---------------------------------------------------------------------------
  Desc: CODEC PGAキャリブレ用ゲイン値をHex値からdB値に変換
---------------------------------------------------------------------------*/
f32 TestCodec::ConvCalibGainHexToF32(u8 hex_gain)
{
    // 0dB 〜 6.0dB
    if (0x0 <= hex_gain && hex_gain <= 0xC)
    {
        return (f32)hex_gain / 2;
    }
    // -0.5dB 〜 -15.0dB
    else if (0x22 <= hex_gain && hex_gain <= 0x3f)
    {
        return ((f32)hex_gain - 64) / 2;
    }
    // 変換可能範囲外
    else
    {
        return 999.0;   // ありえない数値
    }
}

/*---------------------------------------------------------------------------
  Desc: CODEC PGAキャリブレ用ゲイン値をdB値からHex値に変換
---------------------------------------------------------------------------*/
u8 TestCodec::ConvCalibGainF32ToHex(f32 f32_gain)
{
    // 0dB 〜 11.5dB
    if (0.0f <= f32_gain && f32_gain <= 6.0f)
    {
        return (u8)(f32_gain * 2);
    }
    // -0.5dB 〜 -15.0dB
    else if (-15.0f <= f32_gain && f32_gain <= -0.5f)
    {
        return  (u8)((f32_gain * 2) + 64);
    }
    // 変換可能範囲外
    else
    {
        return 0x47;   // ありえない数値
    }
}

/*---------------------------------------------------------------------------
  Desc: CODEC バージョン取得
---------------------------------------------------------------------------*/
bool TestGetCodecVer(uji::seq::TestResult &result)
{
    u8 codecVer[4];
    
    TestCodec* pTc = new TestCodec;
    
    pTc->TestReadMultiEx_SPI1_VendorId();
    pTc->TestReadMultiEx_SPI2_VendorId();
    pTc->TestReadMultiEx_SPI1_RevisionId();
    pTc->TestReadMultiEx_SPI2_RevisionId();
    
    if(pTc->m_VendorId_SPI1   != pTc->m_VendorId_SPI2 || 
       pTc->m_RevisionId_SPI1 != pTc->m_RevisionId_SPI2 )
    {
        result.m_Result = false;
        goto FINALLY;
    }
    
    pTc->m_VendorId   = pTc->m_VendorId_SPI1;
    pTc->m_RevisionId = pTc->m_RevisionId_SPI1;
    
    codecVer[0] = pTc->m_VendorId;
    codecVer[1] = 0x00;
    codecVer[2] = pTc->m_RevisionId;
    codecVer[3] = 0x00;
    
    g_CommC2T->WriteDpramBinary(codecVer, sizeof(codecVer));
    
    result.m_Result = true;
    
FINALLY:
    delete pTc;
    return result.m_Result;
}


/*---------------------------------------------------------------------------
  Desc: アナログキー検査
---------------------------------------------------------------------------*/
bool TestAnalogKey(uji::seq::TestResult &result)
{
    u8 analogStatus[4];
    
    nn::hid::AnalogStickCalibrator* pAsc = new nn::hid::AnalogStickCalibrator();
    nn::hid::AnalogStickStatus asStatus;
    
    // スライドパッドの生値を取得
    pAsc->ReadRaw(&asStatus);
    u16 Rx = asStatus.x;
    u16 Ry = 4096 - asStatus.y;
    
    delete pAsc;
    
    analogStatus[0] = Rx & 0xff;
    analogStatus[1] = Rx >> 8;
    analogStatus[2] = Ry & 0xff;
    analogStatus[3] = Ry >> 8;
    
    g_CommC2T->WriteDpramBinary(analogStatus, sizeof(analogStatus));
    
    result.m_Result = true;
    return result.m_Result;
}

bool TestTouchPanel( uji::seq::TestResult &result )
{
    nn::hid::CTR::TouchPanelCalibrator TPCal;
    nn::hid::TouchPanelStatus TPStatus;
    
    u16 tp_x = 0;
    u16 tp_y = 0;
    u16 counter = 0;

    while( true )
    {
        TPCal.ReadRaw( &TPStatus );
        if( TPStatus.touch )
        {
            tp_x = TPStatus.x;
            tp_y = TPStatus.y;
            break;
        }else
        {
            tp_x = 0xFFFF;
            tp_y = 0xFFFF;
        }
        nn::os::Thread::Sleep( nn::fnd::TimeSpan::FromMilliSeconds(10));
        if( ++counter > 100 )
        {
            break;
        }
    }
    

    
    
    //--------------------------------------------------------------------------
    // 基板検査機に検査結果を返す
    //--------------------------------------------------------------------------
    u8 tpDpramData[6];
    tpDpramData[0] = TPStatus.touch;
    tpDpramData[1] = 0x00;
    tpDpramData[2] = tp_x & 0xFF;
    tpDpramData[3] = tp_x >> 8;
    tpDpramData[4] = tp_y & 0xFF;
    tpDpramData[5] = tp_y >> 8;
    
    g_CommC2T->WriteDpramBinary( tpDpramData, sizeof( tpDpramData ));

    
    
    result.m_Result = true;
    return result.m_Result;
}


} // namespace codec
} // namespace eva
} // namespace uji

