/************************************************************************
検査シーケンサ
 *************************************************************************/
#include <nn.h>
#include <nn/gx/CTR/gx_LcdPowerManager.h>
#include <nn/mcu.h>
#include "Coordinate.h"
#include "sys.h"
#include "../sys/sys_ClassMenu.h"
#include "../sys/sys_SoundPlayer.h"
#include "../sys/sys_GetPlatform.h"
#include "../sys/TesterCommunication/TesterCommunication.h"
#include "../eva/mcu/McuInitializer.h"
#include "config.h"
#include "Version.h"
#include "TestListManager.h"
#include "TestResult.h"
#include "TestSequencer.h"
#include "TesterLog/InspectLog.h"
#include "TesterLog/InspectLog_Viewer.h"
#include "TesterLog/InspectLog_TestFunc.h"
#include "TesterLog/ProductionLog.h"
#include "TesterLog/ProductionLogViewer.h"
#include "TesterLog/ProductionLogDummy.h"
#include "TesterLog/ProductionLogTestFunc.h"
#include "PortChecker.h"
#include "CommC2T.h"
#include "reception_board_interface.h"
#include "CommCamera.h"
#include "Reception_Camera.h"
#ifdef EVA_GYRO_M
#include "../eva/gyro/gyro_UdsMaster.h"
#endif
#include "../eva/wlaudio/TestWlAudioMenu.h"
#include "../eva/camera/TestCamAndIF.h"
#include "../eva/camera/TestCamera.h"
#include "../eva/procchk/ProcessCheck.h"
#include "../seq/Reception_board_interface.h"
#include "../eva/wireless/TestWirelessMenu.h"

using namespace uji::sys;
using namespace uji::seq;

static void SecondToString( char *Str, int Second );
static void ShowPicture( wchar_t *file );
static void ShowPicture( wchar_t *file, s32 renderWidth, s32 renderHeight );
static bool IsRetest(void);


TestResultManager *TestSequencer::m_TestResultManager=0;

/************************************************************************
内部で使用する定数類
 ************************************************************************/

//画面上に表示するメッセージの頂点座標
const Coordinate<int> TITLE_LOCATION            (  0, 0 );
const Coordinate<int> MODE_LOCATION             (  0, 1 );
const Coordinate<int> AGING_LOCATION            (  0, 2 );
const Coordinate<int> TIME_LOCATION             ( 40, 3 );
const Coordinate<int> PROGRESS_LOCATION         (  0, 3 );
const Coordinate<int> NAME_LOCATION             (  0, 4 );
const Coordinate<int> MESSAGE_LOCATION          (  0, 6 );
const Coordinate<int> RESULT_LOCATION           ( 22,14 );
const Coordinate<int> TOTAL_RESULT_LOCATION     ( 22,15 );


/************************************************************************
シーケンサを使用可能状態にする

現時点では本ルーチン内で実施すべきことがありません。
************************************************************************/
void TestSequencer::Initialize(){
}

/************************************************************************
メニュー表示
 ************************************************************************/
void TestSequencer::OpenMenu(){

    ConfigWindow *configWindow = new ConfigWindow( m_Config );
    ClassMenu   *m  = new ClassMenu( "Checker Menu" );

    m->Add<TestSequencer>     ( "Execute Current Sequence",   this,               &TestSequencer::Execute         );
    m->Add<TestResultManager> ( "Show Error Log",             m_TestResultManager,&TestResultManager::ShowRecords );
    m->Add<TestListManager>   ( "Change Current Sequence",    m_TestListManager,  &TestListManager::Change        );
    m->Add                    ( "-----------------------------" ,NULL);
    m->Add<TestSequencer>     ( "Communication(BOARD I/F, CAM)", this,            &TestSequencer::OpenCommMenu    );
    m->Add                    ( "-----------------------------" ,NULL);
    m->Add<TestSequencer>     ( "PortChecker" ,               this,               &TestSequencer::RunPortChecker     );
    m->Add<TestSequencer>     ( "InspectLog",                 this,               &TestSequencer::OpenInspectLogMenu );
    m->Add<TestSequencer>     ( "ProductionLog",              this,               &TestSequencer::OpenLogMenu );
    m->Add<ConfigWindow>      ( "Change  Configuration",      configWindow,       &ConfigWindow::Open             );
    m->Open();

    delete m;
    delete configWindow;
}

void TestSequencer::RunPortChecker(void)
{
    uji::seq::PortChecker * pc = new uji::seq::PortChecker;
    pc->Run();
    delete pc;
}

/************************************************************************
InspectLog用メニュー
************************************************************************/
void TestSequencer::OpenInspectLogMenu(void)
{
    ClassMenu *m = new ClassMenu( "InspectLog Menu" );

    m->Add   ( "InspectLogViewer", Run_InspectLog_Viewer);
#ifndef EVA_REPAIR
    m->Add   ( "----------------", NULL);
    m->Add   ( "Export Log (MAC)", this, &TestSequencer::Export_InspectLog);
    m->Add   ( "----------------" ,NULL);
    m->Add   ( "FS Menu",          InspectLog_TestFunc_Menu);
#endif
    m->Open();
    delete m;
}

/************************************************************************
ProductLog用メニュー
************************************************************************/
void TestSequencer::OpenLogMenu(void)
{
    ClassMenu *m = new ClassMenu( "ProductLog Menu" );

    m->Add   ( "LogViewer",        Run_ProductLog_Viewer);
#ifndef EVA_REPAIR
    m->Add   ( "----------------", NULL);
#if 0
    m->Add   ( "Export Log (SN)",  NULL);
#endif
    m->Add   ( "Export Log (MAC)", this, &TestSequencer::Export_ProductLog);
    m->Add   ( "Extract CpuBoard", this, &TestSequencer::ExtractCpuBoard);
    m->Add   ( "----------------" ,NULL);
    m->Add   ( "FS Menu",         ProductionLogTestFunc_Menu);
    m->Add   ( "Dummy Log 1/2",   ProductionLogDummy_Menu);
    m->Add   ( "Dummy Log 2/2",   ProductionLogDummy_Menu2);
#endif
    m->Open();
    delete m;
}

// inspect.logをSDカードに出力する
void TestSequencer::Export_InspectLog(void)
{
    InspectLog * il = new InspectLog;
    il->Initialize();
    il->Dump();
    il->ExportSD_MacAddress();
    il->Finalize();
    delete il;
}

// product.logをSDカードに出力する
void TestSequencer::Export_ProductLog(void)
{
    ProductionLog * pl = new ProductionLog;
    pl->Initialize();
    pl->ExportSD_MacAddress();
    pl->Finalize();
    delete pl;
}

// product.logから基板検査(CpuBoard)のみ抜き出し、他を削除。
void TestSequencer::ExtractCpuBoard(void)
{
    ProductionLog * pl = new ProductionLog;
    pl->Initialize();
    pl->LogTable_Extract_CpuBoard();
    pl->Finalize();
    delete pl;
}

// QRコードを画面上部に表示
static void ShowQRCode_UpperLCD(void)
{
using namespace uji::eva::procchk;

#define TYPE_UPPER_QR    3

    ProcessCheck * pc = new ProcessCheck();
    pc->GraphicsInit("QR Code");

    pc->CreateQRCode();

    uji::sys::Pad pad;
    do
    {
        pad.UpdatePad();

        pc->GraphicsUpdate(TYPE_UPPER_QR);
        nn::os::Thread::Sleep(nn::fnd::TimeSpan::FromMilliSeconds(5));

    } while(!pad.IsButtonDown(uji::sys::Pad::BUTTON_DOWN));

    pc->GraphicsFinalize(TYPE_UPPER_QR);

    delete pc;
}

/************************************************************************
シーケンサ本体
 ************************************************************************/
void TestSequencer::Execute(){

    bool judge;
    uji::sys::Pad pad;

    pad.UpdatePad();
    if( pad.IsButtonPress(Pad::BUTTON_START) ) return;  //スタートボタンが押していると抜ける

    SoundPlayer *sp = new SoundPlayer;


    const int FONT_SIZE = 14;
    m_Window = new TextWindow( GraphicsDrawing::DISPLAY0_WIDTH/(FONT_SIZE/2), GraphicsDrawing::DISPLAY0_HEIGHT/FONT_SIZE, FONT_SIZE );
    m_Window->SetTitle( "SEQUENCER" );
    uji::sys::GraphicsDrawing *gfx = uji::sys::GraphicsDrawing::GetInstance();
    Menu::m_WindowManager.CreateWindow(m_Window, NN_GX_DISPLAY0,0,0 );

// 複合アプリ時はここでカメラ用Heapメモリを確保する
#ifdef EVA_COMPOSITE
    uji::sys::SysApp *sysApp = uji::sys::SysApp::GetInstance();
    u32 bmpSize = (uji::eva::TestCamera::CAMERA_WIDTH * uji::eva::TestCamera::CAMERA_HEIGHT *3 );
    // BMPデータ用バッファをデバイスメモリから確保
    CAM_BUF = (u8*)sysApp->AllocateDeviceMemory( bmpSize*6 );
#endif

    //メニューループ
    //検査ループ
    do{
#ifdef EVA_COMPOSITE
        // お知らせランプの消灯
        uji::eva::mcu::NotifyLedWhiteOff();
        
        const s32 compositeApplicationListNum = sizeof(s_CompositeApplicationList)/sizeof(s_CompositeApplicationList[0]) - 1;
        
        // メニューから希望のテストリストを選択する
        m_Config->SetAlternative().TestList = ShowCompositeApplicationList(s_CompositeApplicationList, compositeApplicationListNum);
        
        // CamAndIfはNANDアプリ時専用の関数に飛ばす。カード起動時は別関数（引数無し版）
        if     ( m_Config->GetAlternative().TestList==TESTLIST_ID_CAM_AND_IF )   {  uji::eva::TestCamAndIF::ExecuteTestCamAndIF2( CAM_BUF );    }
        else if( m_Config->GetAlternative().TestList==TESTLIST_ID_PARALLAX )     {  Reception_Camera();  }
        else if( m_Config->GetAlternative().TestList==TESTLIST_ID_WL_AUDIO )     {  uji::eva::TestWlAudio::ExecuteTestWlAudio();    }
        else if( m_Config->GetAlternative().TestList==TESTLIST_ID_CAM_CAPTURE )
        {
            m_CamWindow = new TextWindow( GraphicsDrawing::DISPLAY0_WIDTH/(FONT_SIZE/2), GraphicsDrawing::DISPLAY0_HEIGHT/FONT_SIZE, FONT_SIZE );
            uji::eva::camera::CaptureToHeap( CAM_BUF, m_CamWindow );
            Menu::m_WindowManager.DestroyWindow(m_CamWindow);
            m_CamWindow->Destroy();
            delete m_CamWindow;
        }
        else if( m_Config->GetAlternative().TestList==TESTLIST_ID_INTERFACE )    {  uji::seq::Reception_BoardInterface();           }
        else if( m_Config->GetAlternative().TestList==TESTLIST_ID_WIRELESS )     {  uji::eva::TestWireless::ExecuteTestWireless();  }
        else if( m_Config->GetAlternative().TestList==TESTLIST_ID_OCAM )         {  uji::seq::Reception_Camera();                   }
        else
        {
#endif
        //コンフィグから対応のテストリストを規定する
        m_TestListManager->SetCurrentTestList( m_Config->GetAlternative().TestList );
        m_SequenceLength = CalcActiveSequenceLength();
        if( false==SpecialHandlingFlagOnReboot() ) ShowTesterStatus();
        
        m_StartTick = nn::os::Tick::GetSystemCurrent();

        m_AgingCount=0;
        do{
            judge = Execute1Sequence();
            m_AgingCount++;

            //インターバル
            if( m_Config->Get().AgingMode )
            {
                // 経過時間の算出
                int ElapsedTime = (int)(nn::os::Tick::GetSystemCurrent() - m_StartTick).ToTimeSpan().GetMinutes();

                // NG時のスリープ処理
                if (!judge)
                {
                    // 検査ログNGの書込み
                    // TODO:

                    if (m_Config->Get().AgingSleep)
                    {
                        // TODO:
                    }

                    break; // エージング終了
                }

                // エージング時間経過時のスリープ処理
                if (!m_Config->Get().AgingEndless && m_Config->Get().AgingTime <= ElapsedTime)
                {
                    if (m_Config->Get().AgingSleep)
                    {
                        // TODO:
                    }

                    // 検査ログOKの書込み
                    // TODO:

                    break; // エージング終了
                }

                nn::os::Thread::Sleep( nn::fnd::TimeSpan::FromMilliSeconds(m_Config->Get().AgingInterval) );
            }

            //パッド情報更新
            pad.UpdatePad();

            // 描画処理
            Draw();
            gfx->m_DrawFramework->WaitVsync(NN_GX_DISPLAY_BOTH);
        }while( m_Config->Get().AgingMode && judge && !pad.IsButtonPress(Pad::BUTTON_B) );

        //判定
        m_Window->Gotoxy( TOTAL_RESULT_LOCATION.x, TOTAL_RESULT_LOCATION.y );
        if(judge){
            m_Window->SetTextColor( ATTR_COLOR_GREEN );
            m_Window->Printf( "TOTAL:PASS" );
            m_Window->SetTextColor( ATTR_COLOR_WHITE );
            if( m_Config->GetAlternative().TpCalAutoMode == true )
            {
                uji::seq::drawer::DrawOK();
                gfx->m_DrawFramework->SwapBuffers();
                nn::os::Thread::Sleep( nn::fnd::TimeSpan::FromMilliSeconds( m_Config->Get().WaitTestEnd ) );
            }
            ShowPicture( L"rom:/jpeg/Pass.jpg" );
            sp->UjiSoundPlayer( "rom:/SoundPlayer/ok.wav", 1500 );
        }else{
            m_Window->SetTextColor( ATTR_COLOR_RED );
            m_Window->Printf( "TOTAL:FAIL[%02d-%03d-%03d]",
                m_TestListManager->GetCurrentTestList(m_CurrentTest)->m_Id.m_Major,
                m_TestListManager->GetCurrentTestList(m_CurrentTest)->m_Id.m_Minor,
                m_TestResultManager->GetLastRecord().m_Micro );
            m_Window->SetTextColor( ATTR_COLOR_WHITE );
            if( m_Config->GetAlternative().TpCalAutoMode == true )
            {
                uji::seq::drawer::DrawNG();
                gfx->m_DrawFramework->SwapBuffers();
                nn::os::Thread::Sleep( nn::fnd::TimeSpan::FromMilliSeconds( m_Config->Get().WaitTestEnd ) );
            }
            ShowPicture( L"rom:/jpeg/Fail.jpg" );
            sp->UjiSoundPlayer( "rom:/SoundPlayer/ng.wav", 1500 );
            if( m_IsNgLogEnable || m_Config->Get().EnableNgLog || m_Config->GetAlternative().TpCalAutoMode )
            {
                AddNgLog();
            }
        }

        /*検査結果出力*/
        if(m_Config->GetAlternative().OutputTestResult)
        {
            if( OutputTestResult(judge, m_Window) )
            {
                ShowPicture( L"rom:/jpeg/PassSmall.jpg", 100, 60 );
            }
            else
            {
                ShowPicture( L"rom:/jpeg/FailSmall.jpg", 100, 60 );
            }
            gfx->m_DrawFramework->SwapBuffers();
        }
        
        // 描画処理
        Draw();
        gfx->m_DrawFramework->WaitVsync(NN_GX_DISPLAY_BOTH);

#ifdef EVA_COMPOSITE
        }
#endif
    }while( IsRetest() ) ;

// 複合アプリ時はここでカメラ用Heapメモリを解放する
#ifdef EVA_COMPOSITE
    // BMPファイル用に確保していた領域を解放する
    sysApp->Free( CAM_BUF );
#endif

    Menu::m_WindowManager.DestroyWindow(m_Window);
    m_Window->Destroy();
    delete m_Window;
    delete sp;
}

/************************************************************************
テストを１セット実行する
 ************************************************************************/
bool TestSequencer::Execute1Sequence()
{
    bool        judge;
    bool        judgeTotal = true;
    TestResultString *str = new TestResultString;

    uji::sys::Pad pad;
    uji::sys::GraphicsDrawing *gfx = uji::sys::GraphicsDrawing::GetInstance();

    m_TestResultManager->ClearAllRecords();
    
    // 方法２
    //if( false==SpecialHandlingFlagOnReboot() )
    {
    m_CurrentTest = 0;
    }
    m_Progress=1;
    while( m_TestListManager->GetCurrentTestList(m_CurrentTest)->m_Name != NULL )
    {
        // 方法１
        if( SpecialHandlingFlagOnReboot() )
        {
            while( 0!=strcmp(m_TestListManager->GetCurrentTestList(m_CurrentTest)->m_Name, "REINITIALIZE") )
            {
                m_CurrentTest++;
            }
        }
        
        judge = true;
        if( m_TestListManager->GetCurrentTestList(m_CurrentTest)->m_Enable )
        {
            //検査情報表示
            ShowInformation();
            Draw();         //一旦描画


            if( m_TestListManager->GetCurrentTestList(m_CurrentTest)->m_Function )
            {
                //検査実行
                TestList *currentTest = m_TestListManager->GetCurrentTestList(m_CurrentTest);
                TestResult &testResult = m_TestResultManager->AllocateOneRecord();

                testResult.m_TestList = currentTest;
                judge = (currentTest->m_Function)( testResult );
                testResult.m_Result = judge;
                judgeTotal &= judge;

                //検査情報表示（検査関数内でクリアされている可能性があるため
                ShowInformation();
                m_Window->Gotoxy( RESULT_LOCATION.x, RESULT_LOCATION.y );
                m_Window->Printf( "RESULT:%s", judge?"PASS":"FAIL" );

                //メッセージ表示
                m_Window->Gotoxy( MESSAGE_LOCATION.x, MESSAGE_LOCATION.y );
                m_Window->Printf( "MESSAGE:\n" );
                str->Initialize( m_Window, testResult.m_String );
                str->ShowInitialLines();
                str->ShowArrow();

                // 描画処理
                Draw();
                gfx->m_DrawFramework->WaitVsync(NN_GX_DISPLAY_BOTH);

            }
            if( m_Config->Get().StepExecMode ) pad.WaitAnyKey();
            m_Progress++;
        }

        //ＮＧ時の処理
        if( !judge ){
            if( m_Config->Get().EvaluationMode )
            {
                pad.WaitAnyKey();
            }
            else
            {
                break;
            }
        }
        m_CurrentTest++;
    }

    return judgeTotal;
}

/************************************************************************
データ書込み時に
Lineモードの最終検査ログが "Reboot","START" の場合に使用する特殊処理用フラグ

 ************************************************************************/
bool TestSequencer::SpecialHandlingFlagOnReboot()
{
    // データ書込み工程であるか
    if( 0 != strcmp(m_TestListManager->GetCurrentTestListName(), "Import") )
    {
        return false;
    }
    
    uji::seq::ProductionLog* pdl = new uji::seq::ProductionLog();
    pdl->Initialize();
    int id = pdl->Get_LatestLogEntryIndex(uji::seq::pl::LINE); // Lineモードの最後のログ
    pdl->Finalize();
    delete pdl;
    
    // Lineモードの検査ログが書かれているか
    if( id<0 )
    {
        return false;
    }
    
    LogEntry le;
    le = pdl->Get_LogEntry(id);
    
    // Lineモードの最終検査ログが "Reboot","START" であるか
    if( (0 != strcmp(le.testerName, "Reboot")) || (0 != strcmp(le.state, "START")) )
    {
        return false;
    }
    else
    {
        return true;
    }
}

#define TESTLIST_ID(name)  m_Config->GetAlternative().TestList==TESTLIST_ID_##name
/************************************************************************
テスタのステータス表示。


 ************************************************************************/
void TestSequencer::ShowTesterStatus(){

    int maxWaitTime = 0;
#if   defined( EVA_MIC_TESTER )
    maxWaitTime = ( TESTLIST_ID(MIC)                               ? 5 : 9999);
#elif EVA_SLIDEPAD_AUTO
    maxWaitTime = ( TESTLIST_ID(SLIDEPAD)||TESTLIST_ID(SP_AND_TP)  ? 1 : 9999);
#elif defined( EVA_TP_MODULE )
    maxWaitTime = ( TESTLIST_ID(TP)                                ? 0 : 9999);
#else
    maxWaitTime = 9999;  //自動実行は実質停止
#endif

#ifdef EVA_SLIDEPAD_AUTO
    // 上記フラグがtrueでもCTRの場合は自動機がないので待ち時間を強制的に9999秒にする
    if( uji::sys::GetPlatformType() == uji::sys::PLATFORM_CTR )
    {
        maxWaitTime = 9999;
    }
#endif

    nn::os::Tick::Tick  startTick;                //開始時のＴＩＣＫ

    uji::sys::Pad pad;
    uji::sys::GraphicsDrawing *gfx = uji::sys::GraphicsDrawing::GetInstance();

    //開始時に必要な処理
    m_Window->Printf( "\f" );
    m_Window->Printf( "[CTR Eva]\n" );
    m_Window->Printf( "\n" );
    m_Window->Printf( "\n" );
    m_Window->Printf( "Mode:%s\n", m_TestListManager->GetCurrentTestListName() );
    m_Window->Printf( "\n" );
    m_Window->Printf( "\n" );
    m_Window->Printf( "Version    :%s\n", VERSION_STRING    );
    m_Window->Printf( "Last Update:%s\n", VERSION_DATE      );
    m_Window->Printf( "\n" );
    m_Window->Printf( "Test Sequence check code %04d\n", m_TestListManager->GetCheckCode()  );
    m_Window->Printf( "Configuration check code %04d\n", m_Config->GetCheckCode()   );
    m_Window->Printf( "\n" );
    m_Window->Printf( "\n" );

    //終了待ち
    int second;

#if !defined(EVA_MIC_TESTER)
    m_Window->Printf( "- Push A Key -" );
#endif

    startTick = nn::os::Tick::GetSystemCurrent();

    //メニューループ
    do {
        second = (int)( nn::os::Tick::GetSystemCurrent()-startTick ).ToTimeSpan().GetSeconds();

        //パッド情報更新
        pad.UpdatePad();
        Draw();
#if    defined( EVA_COMPOSITE )
        TESTLIST_ID(MIC) ? ShowPicture( L"rom:/jpeg/MicOpening.jpg")
                         : ShowPicture( L"rom:/jpeg/Start.jpg");
#elif  defined( EVA_MIC_TESTER )
        ShowPicture( L"rom:/jpeg/MicOpening.jpg" );
#else
        ShowPicture( L"rom:/jpeg/Start.jpg" );
#endif
        gfx->m_DrawFramework->WaitVsync(NN_GX_DISPLAY_BOTH);
    }
#ifdef EVA_GYRO_M
    while( second<maxWaitTime && !pad.IsButtonRepeat(Pad::BUTTON_A) &&
           !eva::GyroUdsMaster::GetInstance()->GetController()->GetStatus().STA_BF );
#else
    while( second<maxWaitTime && !pad.IsButtonRepeat(Pad::BUTTON_A) );
#endif
    pad.WaitReleaseKey();


}
/************************************************************************
検査の全般的な情報を表示する。
 ************************************************************************/
void TestSequencer::ShowInformation(){

    //一度画面クリア
    m_Window->Printf( "\f" );

    //一般情報表示
    m_Window->Gotoxy( TITLE_LOCATION.x, TITLE_LOCATION.y );
    m_Window->Printf( "[TEST Ver.%s]", VERSION_STRING );
    m_Window->Gotoxy( MODE_LOCATION.x,  MODE_LOCATION.y );
    m_Window->Printf( m_TestListManager->GetCurrentTestListName() );

    //エージング情報表示
    if( m_Config->Get().AgingMode ){
        char tmpString[0x10];
        char AgingTimeString[0x10];
        std::sprintf(tmpString, "%d min", static_cast<int>(m_Config->Get().AgingTime));
        std::sprintf(AgingTimeString, "%s", m_Config->Get().AgingEndless ? "Endless" : tmpString);

        m_Window->Gotoxy( AGING_LOCATION.x, AGING_LOCATION.y );
        m_Window->Printf( "AGING[%d] [%s]", m_AgingCount, AgingTimeString);
    }

    //進行状況表示
    m_Window->Gotoxy( PROGRESS_LOCATION.x, PROGRESS_LOCATION.y );
    m_Window->Printf( "[%03d/%03d]", m_Progress, m_SequenceLength );

    //検査項目表示
    m_Window->Gotoxy( NAME_LOCATION.x, NAME_LOCATION.y );
    m_Window->Printf( "[%02d-%03d %-24s]",
                        m_TestListManager->GetCurrentTestList(m_CurrentTest)->m_Id.m_Major,
                        m_TestListManager->GetCurrentTestList(m_CurrentTest)->m_Id.m_Minor,
                        m_TestListManager->GetCurrentTestList(m_CurrentTest)->m_Name        );

    //経過時間表示
    int     Second = (int)( nn::os::Tick::GetSystemCurrent()-m_StartTick ).ToTimeSpan().GetSeconds();
    char    TimeString[0x10];
    SecondToString( TimeString, Second );
    m_Window->Gotoxy( TIME_LOCATION.x, TIME_LOCATION.y );
    m_Window->Printf( "TIME:%s", TimeString );

    //アイコン表示
    ShowPicture( L"rom:/jpeg/Wait.jpg" );

}


/************************************************************************
複合アプリケーションのUI表示関数
ShowCompositeApplicationList=SCAL に使用する静的定数／静的変数／関数
************************************************************************/

static const int    MAX_OUTPUT_1TIME   = 8;
static const int    LIMIT_OUTPUT_1TIME = 6;
static char         s_AppImportVer[LOG_VERSION_LEN+1] = "*.**";
static char         s_SeqCrc[5] = "Fail";
static char         s_CfgCrc[5] = "Fail";
static s32          s_SelectedRow;
static char*        s_RemainingBatteryLv;
static bool         s_IsTurnOnBl = true;

/************************************************************************
複合アプリケーション用：各検査ログを取得
************************************************************************/
void TestSequencer::SCAL_GetProductionLogInformation(CompositeApplicationList* list, const s32 listNum)
{
    using namespace uji::seq::pl;
    ProductionLog* pdl = new ProductionLog;
    pdl->Initialize();
    
    // 複合アプリケーションに含まれる検査の最終検査ログを取得
    for(int i=0; i<listNum; i++)
    {
        int   index = pdl->Get_LatestLogEntryIndex( std::string(list[i].name), LINE ); // 対象ログがなかったら-1を返す
        LogEntry le = pdl->Get_LogEntry( index ); // index=-1の場合は最初の行（CPU基板検査ログ）の要素を返す
        sprintf( list[i].result, ((index!=-1) ? le.state : "") );
    }
    
    // "App_I"のOKログに記録されている検査ソフト書込みプログラムのCRC値を取得
    {
        int   index = pdl->Get_LatestLogEntryIndex( "App_I", LINE, "OK" ); // 対象ログがなかったら-1を返す
        LogEntry le = pdl->Get_LogEntry( index ); // index=-1の場合は最初の行（CPU基板検査ログ）の要素を返す
        if( index!=-1 )
        {
            string strPdlMsg = le.message; // "Seq:%04d$Cfg:%04d"
            string strSeqCrc = strPdlMsg.substr(  4, 4 );
            string strCfgCrc = strPdlMsg.substr( 13, 4 );
            
            sprintf( s_SeqCrc, "%s", strSeqCrc.c_str() );
            sprintf( s_CfgCrc, "%s", strCfgCrc.c_str() );
            sprintf( s_AppImportVer, "%s", le.version );
        }
        // index==-1（つまり検査ソフト書込みOKログがない場合）はCRC画面表示がどちらも"Fail"になる。
        // しかし画面が表示された時点で複合アプリケーションプログラムは正常に起動しているので、検査ログの異常状態。
    }
    
    pdl->Finalize();
    delete pdl;
}

/************************************************************************
複合アプリケーション用：下画面描画
************************************************************************/
void TestSequencer::SCAL_DrawDisplay1(uji::sys::GraphicsDrawing *gfx)
{
    gfx->m_DrawFramework->SetRenderTarget( NN_GX_DISPLAY1 );
    gfx->m_DrawFramework->SetClearColor( NN_GX_DISPLAY1, 0.0f, 0.0f, 0.0f, 1.0f );
    gfx->m_DrawFramework->Clear();
    gfx->m_DrawFramework->SwapBuffers();
    ShowPicture( L"rom:/jpeg/CompositeApplication.jpg");
    gfx->m_DrawFramework->WaitVsync( NN_GX_DISPLAY_BOTH );
}

/************************************************************************
複合アプリケーション用：上画面描画
************************************************************************/
void TestSequencer::SCAL_DrawDisplay0(uji::sys::GraphicsDrawing *gfx, CompositeApplicationList* list, const s32 listNum)
{
    m_Window->SetTitle( "COMPOSITE APPLICATION" );
    m_Window->SetTextColor( ATTR_COLOR_WHITE );
    m_Window->Printf( "\f" );
    m_Window->Printf( "        Importer Program        |   Importee Program    \n" );
    m_Window->Printf( "----------+----------+----------+------------+----------\n" );
    m_Window->Printf( "  Ver%04s | Seq:%04s | Cfg:%04s | %-10s | Ver%04s  \n", s_AppImportVer, s_SeqCrc, s_CfgCrc, IMPORTEE_PRG_NAME, IMPORTEE_PRG_VER );
    m_Window->Printf( "----------+----------+----------+------------+----------\n" );
    m_Window->Printf( "\n" );
    m_Window->Printf( "\n" );
    m_Window->Printf( "\n" );
    m_Window->Printf( "\n" );
    m_Window->Printf( "\n" );
    m_Window->Printf( "\n" );
    m_Window->Printf( "\n" );
    m_Window->Printf( "\n" );
    m_Window->Printf( "\n" );
    m_Window->Printf( "\n" );
    m_Window->Printf( "-----------------------------------------+--------------\n" );
    m_Window->Printf( "  MoveCursor:UP/DOWN  StartTest:A_BUTTON | BATTERY:%3s  \n", s_RemainingBatteryLv );
    
    const u16 START_LINE = 5;
    m_Window->Gotoxy( 0, START_LINE );
    
    if( listNum <= MAX_OUTPUT_1TIME )
    {
        // 検査数が１ページに収まる（検査項目が８個以内）場合はそのまま表示
        for(int i=0; i<listNum; i++)
        {
            m_Window->SetTextColor( ATTR_COLOR_WHITE );
            m_Window->Printf( "   %-35s(%s) ", list[i].msg, list[i].version );
            m_Window->SetTextColor( strcmp(list[i].result, "OK")==0 ? ATTR_COLOR_GREEN : ATTR_COLOR_RED );
            m_Window->Printf( "%s\n", list[i].result ); 
        }
        m_Window->SetTextColor( ATTR_COLOR_WHITE );
        m_Window->Gotoxy( 1, s_SelectedRow + START_LINE );
        m_Window->Printf( "*" );
    }
    else
    {
        // 検査数が１ページに収まらない（検査項目が８個より多い）場合は１ページ辺りの表示数を６つに減らす
        int totalPageNum   = static_cast<int>((listNum-1)/LIMIT_OUTPUT_1TIME)+1;
        int presentPageNum = static_cast<int>(s_SelectedRow/LIMIT_OUTPUT_1TIME)+1;
        int loopNum = 0;
        int gainNum = 0;
        
        if( totalPageNum==presentPageNum ) // 最終ページ
        {
            loopNum = listNum%LIMIT_OUTPUT_1TIME;
            gainNum = (presentPageNum-1)*LIMIT_OUTPUT_1TIME;
        }
        else                               // 最終ページ以外
        {
            loopNum = LIMIT_OUTPUT_1TIME;
            gainNum = 0;
        }
        
        for(int i=0; i<loopNum; i++)
        {
            int j = gainNum + i;
            m_Window->SetTextColor( ATTR_COLOR_WHITE );
            m_Window->Printf( "   %-35s(%s) ", list[j].msg, list[j].version );
            m_Window->SetTextColor( strcmp(list[j].result, "OK")==0 ? ATTR_COLOR_GREEN : ATTR_COLOR_RED );
            m_Window->Printf( "%s\n", list[j].result ); 
        }
        m_Window->SetTextColor( ATTR_COLOR_WHITE );
        m_Window->Gotoxy( 3, 12 );
        m_Window->Printf( "Page %d/%d", presentPageNum, totalPageNum );
        m_Window->Gotoxy( 1, s_SelectedRow%LIMIT_OUTPUT_1TIME + START_LINE );
        m_Window->Printf( "*" );
    }
    
    Draw();
    gfx->m_DrawFramework->WaitVsync(NN_GX_DISPLAY_BOTH);
}

/************************************************************************
複合アプリケーション用：初期カーソル位置の設定
************************************************************************/
void TestSequencer::SCAL_SetCursor1stPos(CompositeApplicationList* list, const s32 listNum)
{
    for(int i=0; i<listNum; i++)
    {
        if(0==strcmp( "OK", list[i].result ))
        {
            s_SelectedRow++;
            if(s_SelectedRow>listNum-1) s_SelectedRow=0;
        }
        else
        {
            break;
        }
    }
}

/************************************************************************
複合アプリケーション用：バッテリー残量を取得
************************************************************************/
void TestSequencer::SCAL_GetRemainingBatteryLv()
{
    u8 btLevel = 0;
    nn::Result nnr = uji::eva::mcu::GetRemainingBatteryLv(&btLevel);
    if( nnr.IsFailure() ){  sprintf( s_RemainingBatteryLv, "ERR" );           }
    else                 {  sprintf( s_RemainingBatteryLv, "%3d", btLevel );  }
}

/************************************************************************
複合アプリケーション用：キー入力
************************************************************************/
void TestSequencer::SCAL_InputKey(uji::sys::Pad& pad, const s32 listNum)
{
    // L+R+X 同時押しで上 LCD を ON/OFF 切り替え(CTRのみ)
    if(uji::sys::GetPlatformType() == uji::sys::PLATFORM_CTR)
    {
        do
        {
            // UpdatePad を複数回呼ぶと IsButtonRepeat/Down/Press の処理が
            // おかしくなるので注意！
            pad.UpdatePad();
            
            if(pad.IsButtonPress( Pad::BUTTON_L ) && 
               pad.IsButtonPress( Pad::BUTTON_R ) && 
               pad.IsButtonPress( Pad::BUTTON_X ))
            {
                if( s_IsTurnOnBl )
                {
                    nn::gx::CTR::LcdPowerManager::TurnOffBl( nn::gx::CTR::LCD_UPPER );
                    s_IsTurnOnBl = false;
                    ShowPicture( L"rom:/jpeg/LCDUpperBlTurnOff.jpg");
                }
                else
                {
                    nn::gx::CTR::LcdPowerManager::TurnOnBl( nn::gx::CTR::LCD_UPPER );
                    s_IsTurnOnBl = true;
                    ShowPicture( L"rom:/jpeg/CompositeApplication.jpg");
                }
                pad.WaitReleaseKey();
            }
        }
        while( !s_IsTurnOnBl );
    }
    else
    {
        // UpdatePad を複数回呼ぶと IsButtonRepeat/Down/Press の処理が
        // おかしくなるので注意！
        pad.UpdatePad();
    }
    
    // 上キー入力で一つ前に戻る。先頭のテスト選択時に押すと最後のテストに移動。
    if(pad.IsButtonRepeat( Pad::BUTTON_UP ))
    {
        s_SelectedRow--;
        if(s_SelectedRow<0) s_SelectedRow=listNum-1;
    }
    // 下キー入力で一つ先に移動。最後のテスト選択時に押すと先頭のテストに移動。
    if(pad.IsButtonRepeat( Pad::BUTTON_DOWN ))
    {
        s_SelectedRow++;
        if(s_SelectedRow>listNum-1) s_SelectedRow=0;
    }
    // MAX_OUTPUT_1TIME 以上の場合には複数ページ構成になるため左右でページ移動。
    if( listNum > MAX_OUTPUT_1TIME )
    {
        // 左キー入力で前のページに戻る。先頭ページで押しても移動しない。
        if(pad.IsButtonRepeat( Pad::BUTTON_LEFT ))
        {
            s_SelectedRow-=LIMIT_OUTPUT_1TIME;
            if(s_SelectedRow<0) s_SelectedRow=0;
        }
        // 右キー入力で次のページに移動。最終ページで押しても移動しない。
        if(pad.IsButtonRepeat( Pad::BUTTON_RIGHT ))
        {
            s_SelectedRow+=LIMIT_OUTPUT_1TIME;
            if(s_SelectedRow>listNum-1) s_SelectedRow=listNum-1;
        }
    }
}

/************************************************************************
複合アプリケーション用：検査項目を（手動）選択する画面表示（UI部）

************************************************************************/
u32 TestSequencer::ShowCompositeApplicationList(CompositeApplicationList* list, const s32 listNum)
{
    s_SelectedRow = 0;
    s_RemainingBatteryLv = reinterpret_cast<char*>(sys::Alloc(4*sizeof(char), 32));
    memset( s_RemainingBatteryLv, '\0', 4*sizeof(char) );
    
    uji::sys::Pad pad;
    uji::sys::GraphicsDrawing *gfx = uji::sys::GraphicsDrawing::GetInstance();
    
    SCAL_DrawDisplay1(gfx);                                 // 下画面描画
    SCAL_GetProductionLogInformation(list, listNum);        // 各検査ログを取得
    SCAL_SetCursor1stPos(list, listNum);                    // 初期カーソル位置
    
    // スリープ要求に対する返答を有効にします
    sys::SleepHandler::EnableSleep();
    
    // メニューループ
    do
    {
        if(sys::SleepHandler::IsSleepRequested())
        {
            sys::SleepHandler::SleepSystem();               // スリープモードに入る
            nn::gx::StartLcdDisplay();                      // 再開後の処理
        }
        
        SCAL_GetRemainingBatteryLv();                       // バッテリー残量を取得
        SCAL_InputKey(pad, listNum);                        // キー入力処理
        SCAL_DrawDisplay0(gfx, list, listNum);              // 上画面描画
        
        // -----------------------------------------------
        // ToDO: 自動化対応
        // 自動化の場合は画面だけ表示して（しなくても良いが）
        // 受信コマンドを受けて testListId を返す。
        // 通信方式は IRNOP を予定。
        // -----------------------------------------------
        
    }
    while( !pad.IsButtonRepeat(Pad::BUTTON_A) );
    pad.WaitReleaseKey();
    
    // スリープを無効に
    sys::SleepHandler::DisableSleep();
    
#ifdef EVA_COMPOSITE
    memcpy( VERSION_STRING, list[s_SelectedRow].version, sizeof(char) * (sizeof(VERSION_STRING)/sizeof(VERSION_STRING[0])) );
#endif
    
    return list[s_SelectedRow].testListId;
}



/************************************************************************
シーケンスリストの長さを算出する
 ************************************************************************/
int  TestSequencer::CalcActiveSequenceLength(void){
    int counter=0;
    int active=0;
    //ターミネータを検索
    while( m_TestListManager->GetCurrentTestList(counter)->m_Name != NULL ){
        if( m_TestListManager->GetCurrentTestList(counter)->m_Enable
            && m_TestListManager->GetCurrentTestList(counter)->m_Name[0]!='@' ) active++;
        counter++;
    }

    return active;
}
/************************************************************************
画面描画
************************************************************************/
void TestSequencer::Draw(void)
{
    uji::sys::GraphicsDrawing *gfx = uji::sys::GraphicsDrawing::GetInstance();

    //ウインドウ処理
    Menu::m_WindowManager.Update();

    // 上画面描画
    gfx->m_DrawFramework->SetRenderTarget(NN_GX_DISPLAY0);
    gfx->m_DrawFramework->Clear();
    Menu::m_WindowManager.DrawDisplay0();
    gfx->m_DrawFramework->SwapBuffers();
}

/************************************************************************
通信メニュー
 ************************************************************************/
void TestSequencer::OpenCommMenu(void)
{

    Menu *m = new Menu( "Communcation(BOARD I/F)" );
    m->Add( "[BOARD I/F]TEST COMM",     &CommC2T::TestComm );
    m->Add( "[BOARD I/F]TEST DPRAM",    &CommC2T::TestDpram );
    m->Add( "[BOARD I/F]RECEPTION",     &Reception_BoardInterface );
    m->Add( "---------------------",    NULL );
    m->Add( "[CAMERA]TEST FIFO",        &CommCamera::TestFifo );
    m->Add( "[CAMERA]TEST PACKET",      &CommPacketCamera::TestPacket );
    m->Add( "[CAMERA]RECEPTION",        &Reception_Camera );

    m->Open();
    delete m;
}

/************************************************************************
ＮＧメッセージをプロダクションログ用に整える

dst側はsrcと同じサイズか８０文字が格納できるバッファを用意してください。
 ************************************************************************/
static void FormToLogMessage( char *dst, const char *src )
{
    const int MAX_LENGTH = 80;

    //最大長にトリミング
    strncpy( dst, src, MAX_LENGTH );
    if( strlen(src) > MAX_LENGTH ) dst[MAX_LENGTH]='\0';

    //\nを$に変換、,をスペースに変換
    for( int i=0 ; dst[i]!='\0' ; i++ )
    {
        if( dst[i]=='\n' ) dst[i]='$';
        if( dst[i]==','  ) dst[i]=' ';
    }
}

/************************************************************************
通信メニュー
 ************************************************************************/
void TestSequencer::AddNgLog(void)
{

    uji::seq::Config  *c = new uji::seq::Config;
    uji::seq::ProductionLog* pdl = new uji::seq::ProductionLog();

    char errorCode[0x10];
    char errorMessage[0x80];

    sprintf( errorCode, "%02d-%03d-%03d",
             m_TestListManager->GetCurrentTestList(m_CurrentTest)->m_Id.m_Major,
             m_TestListManager->GetCurrentTestList(m_CurrentTest)->m_Id.m_Minor,
             (int)m_TestResultManager->GetLastRecord().m_Micro );
    FormToLogMessage( errorMessage, m_TestResultManager->GetLastRecord().m_String );

    pdl->Initialize();
    pdl->Add_1Line( c->Get().TestMode,
                    g_TestListSet[c->GetAlternative().TestList].m_Name,
                    errorCode,
                    VERSION_STRING,
                    "",
                    "",
                    "",
                    errorMessage        );
    delete pdl;
    delete c;
}

/************************************************************************
  検査結果をIRから出力
************************************************************************/
bool TestSequencer::OutputTestResult(bool judge, uji::sys::TextWindow* textWindow)
{
    using namespace TesterCommunication;
    char c_buf[128];

    //送信データ フォーマットID0x04で出力
    static int packetId = 0x00;
    int retryCount = 0x0;
    int targetId = TesterCommunication::GetTargetId();
    int testId = TesterCommunication::GetTestId();
    int testKindId = TesterCommunication::GetTestKindId();
    int testResult = TesterCommunication::GetTestResult(judge);

    if(judge)
    {
        strcpy(c_buf, "");
    }
    else
    {
        sprintf(c_buf, 
                "%02d-%03d-%03d",
                m_TestListManager->GetCurrentTestList(m_CurrentTest)->m_Id.m_Major,
                m_TestListManager->GetCurrentTestList(m_CurrentTest)->m_Id.m_Minor,
                (int)m_TestResultManager->GetLastRecord().m_Micro );
    }
    string errorCode = c_buf;
    
    string testerProgramVer = "";
    string testerSequenceCheckCode = "";
    string testerConfigurationCheckCode = "";
    string dutProgramVer = VERSION_STRING;

    sprintf(c_buf, "%04d", m_TestListManager->GetCheckCode());
    string dutSequenceCheckCode = c_buf;

    sprintf(c_buf, "%04d", m_Config->GetCheckCode());
    string dutConfigurationCheckCode = c_buf;

    string jigNo = "";
    
    uji::sys::GetSerialNumber(c_buf);
    string nclSerialNo = c_buf;

    string emsSerialNo = "";//TODO.
    int emsSerialNoSize= emsSerialNo.length();
    string extendedEntry = "";
    int extendedEntrySize = extendedEntry.length();

    /*----検査ステータスデータ部取得----*/
    TestTrace *testTrace = new TestTrace();
    Result dataResult = testTrace->SetEntry( packetId, retryCount,targetId, testId, testKindId, testResult, errorCode,
                                             testerProgramVer, testerSequenceCheckCode, testerConfigurationCheckCode,
                                             dutProgramVer, dutSequenceCheckCode, dutConfigurationCheckCode,
                                             jigNo, nclSerialNo, emsSerialNoSize, emsSerialNo, extendedEntrySize, extendedEntry );
    if( dataResult.GetErrorType() != Error::None )
    {
        return false;
    }
    /*----------------------------------*/

    /*----------送信パケット取得----------*/
    Packet *packet = new Packet();
    Result packetResult = packet->SetEntry( testTrace );//送信データ フォーマットID0x04の例
    if( packetResult.GetErrorType() != Error::None )
    {
        return false;
    }
    /*------------------------------------*/

    /*----IRからのパケット送信and返答受信----*/
    Ir ir;
    ir.Initialize();
    Result sendResult = ir.SendAndRecvReply( packet );
    ir.Finalize();
    if ( sendResult.GetErrorType() != Error::None )
    {
        textWindow->Printf("\nIr Result : %s", (sendResult.GetMsg() + "\n").c_str());
        return false;
    }
    /*---------------------------------------*/

    /*送信毎にPacketIdをインクリメント*/
    packetId++;

    return true;
}

/************************************************************************

 秒を時間の文字列に変換

引数：
    Second  秒数
    Str     文字列ポインタのアドレス（９バイトの容量が必要）
 ************************************************************************/
static void SecondToString( char *Str, int Second ){
    int h,m,s;

    h = (Second/3600)%99; //最高９９時まで保持
    m = (Second/60  )%60;
    s = Second       %60;

    *Str++ = (char)( '0'+(h/10) );
    *Str++ = (char)( '0'+(h%10) );
    *Str++ = ':';
    *Str++ = (char)( '0'+(m/10) );
    *Str++ = (char)( '0'+(m%10) );
    *Str++ = ':';
    *Str++ = (char)( '0'+(s/10) );
    *Str++ = (char)( '0'+(s%10) );
    *Str++ = '\0';
}


/************************************************************************
下画面に絵を表示

************************************************************************/
static void ShowPicture( wchar_t *file )
{
    GLuint s_TextureId;

    uji::sys::GraphicsDrawing *gfx = uji::sys::GraphicsDrawing::GetInstance();
    JpegTexture jt;

    jt.Open( file );

    gfx->m_DrawFramework->GenerateTexture(  GL_TEXTURE_2D,
                                            GL_RGB_NATIVE_DMP,
                                            jt.GetWidth(),
                                            jt.GetHeight(),
                                            GL_RGB_NATIVE_DMP,
                                            GL_UNSIGNED_SHORT_5_6_5,
                                            jt.GetTextureDataPointer(),
                                            s_TextureId );

    gfx->m_DrawFramework->SetRenderTarget( NN_GX_DISPLAY1 );
    gfx->SetScreenSize( GraphicsDrawing::DISPLAY1_WIDTH, GraphicsDrawing::DISPLAY1_HEIGHT );
    gfx->m_DrawFramework->FillTexturedRectangle(s_TextureId,
                                                0.0f, 0.0f,
                                                GraphicsDrawing::DISPLAY1_WIDTH, GraphicsDrawing::DISPLAY1_HEIGHT,
                                                GraphicsDrawing::DISPLAY1_WIDTH, GraphicsDrawing::DISPLAY1_HEIGHT,
                                                jt.GetWidth(), jt.GetHeight() );
    gfx->m_DrawFramework->SwapBuffers();
    gfx->m_DrawFramework->DeleteTexture(s_TextureId);
    jt.Close();

}

/************************************************************************
下画面に絵を表示

************************************************************************/
static void ShowPicture( wchar_t *file,  s32 renderWidth, s32 renderHeight)
{
    GLuint s_TextureId;

    uji::sys::GraphicsDrawing *gfx = uji::sys::GraphicsDrawing::GetInstance();
    JpegTexture jt;

    jt.Open( file );

    gfx->m_DrawFramework->GenerateTexture(  GL_TEXTURE_2D,
                                            GL_RGB_NATIVE_DMP,
                                            jt.GetWidth(),
                                            jt.GetHeight(),
                                            GL_RGB_NATIVE_DMP,
                                            GL_UNSIGNED_SHORT_5_6_5,
                                            jt.GetTextureDataPointer(),
                                            s_TextureId );

    gfx->m_DrawFramework->SetRenderTarget( NN_GX_DISPLAY1 );
    gfx->SetScreenSize( renderWidth, renderHeight );
    gfx->m_DrawFramework->FillTexturedRectangle(s_TextureId,
                                                0.0f, 0.0f,
                                                renderWidth, renderHeight,
                                                renderWidth, renderHeight,
                                                jt.GetWidth(), jt.GetHeight() );
    gfx->m_DrawFramework->SwapBuffers();
    gfx->m_DrawFramework->DeleteTexture(s_TextureId);
    jt.Close();

}

/************************************************************************
再検査するかどうか

Aボタン true
Bボタン false
それ以外　ボタン受付待ち

************************************************************************/
static bool IsRetest( void )
{
    uji::sys::Pad pad;
    bool isRetest;
    bool isEnd = false;

#ifdef EVA_GYRO_M
    while (eva::GyroUdsMaster::GetInstance()->GetController()->GetStatus().STA_BF)
    {
        nn::os::Thread::Sleep(nn::fnd::TimeSpan::FromMilliSeconds(16));
    }
#endif
    while( !isEnd )
    {
        pad.UpdatePad();
        if( pad.IsButtonDown(Pad::BUTTON_A) )
        {
            isRetest = true;
            isEnd = true;
        }
        if( pad.IsButtonDown(Pad::BUTTON_B) )
        {
            isRetest = false;
            isEnd = true;
        }
#ifdef EVA_GYRO_M
        if(eva::GyroUdsMaster::GetInstance()->GetController()->GetStatus().STA_BF)
        {
            return true;
        }
#endif

#ifdef EVA_PROCCHK
		if ( pad.IsButtonDown(Pad::BUTTON_UP) )
		{
        	ShowQRCode_UpperLCD();
			return true;
		}
#endif

        nn::os::Thread::Sleep(nn::fnd::TimeSpan::FromMilliSeconds(5));
    }

    pad.WaitReleaseKey();
    return isRetest;
}

void uji::seq::drawer::DrawOK()
{
    uji::sys::GraphicsDrawing *gfx = uji::sys::GraphicsDrawing::GetInstance();
    
    const int AREA_SIZE = 70;
    const int AREA_MARGINE = 0;
    
    nw::ut::FloatColor fColor_WH(nw::ut::Color8::WHITE);
    nw::ut::FloatColor fColor_BL(nw::ut::Color8::BLACK);
    
    gfx->m_DrawFramework->SetColor( fColor_WH.r, fColor_WH.g, fColor_WH.b );
    
    gfx->m_DrawFramework->SetRenderTarget( NN_GX_DISPLAY1 );

#if 0
    gfx->m_DrawFramework->FillSquare( GraphicsDrawing::DISPLAY1_WIDTH/2 - AREA_SIZE, AREA_MARGINE,
                                      GraphicsDrawing::DISPLAY1_WIDTH/2 - AREA_SIZE, AREA_MARGINE + AREA_SIZE + 1,
                                      GraphicsDrawing::DISPLAY1_WIDTH/2 + AREA_SIZE, AREA_MARGINE + AREA_SIZE + 1,
                                      GraphicsDrawing::DISPLAY1_WIDTH/2 + AREA_SIZE, AREA_MARGINE );
#endif
    gfx->m_DrawFramework->FillRectangle( 0, 0, gfx->DISPLAY1_WIDTH, gfx->DISPLAY1_HEIGHT );
    
    gfx->m_DrawFramework->SetColor( fColor_BL.r, fColor_BL.g, fColor_BL.b );
    {
        int x = 0;
        int y = 21/2+1;
        double d;
        d = -21*21 + 4*y*y -4*y +2;
        int dx, dy;
        dx = 4;
        dy = -8*y+8;
        int px = 159;
        int py = 28;

        for (x=0; x <= y ; x++)
        {
            if (d>0)
            {
                d += dy;
                dy += 8;
                y--;
            }
            gfx->m_DrawFramework->DrawPoint(  y + px, x + py );        // 0-45     度の間
            gfx->m_DrawFramework->DrawPoint(  x + px, y + py );        // 45-90    度の間

            gfx->m_DrawFramework->DrawPoint( -x + px + 1, y + py ); // 90-135   度の間
            gfx->m_DrawFramework->DrawPoint( -y + px + 1, x + py ); // 135-180  度の間

            gfx->m_DrawFramework->DrawPoint( -y + px + 1, -x + py + 1 );  // 180-225  度の間
            gfx->m_DrawFramework->DrawPoint( -x + px + 1, -y + py + 1 );  // 225-270  度の間

            gfx->m_DrawFramework->DrawPoint(  x + px, -y + py + 1 ); // 270-315  度の間
            gfx->m_DrawFramework->DrawPoint(  y + px, -x + py + 1 ); // 315-360  度の間

            d += dx;
            dx+=8;
        }
    }
        {
        int x = 0;
        int y = 23/2+1;
        double d;
        d = -23*23 + 4*y*y -4*y +2;
        int dx, dy;
        dx = 4;
        dy = -8*y+8;
        int px = 159;
        int py = 28;

        for (x=0; x <= y ; x++)
        {
            if (d>0)
            {
                d += dy;
                dy += 8;
                y--;
            }
            gfx->m_DrawFramework->DrawPoint(  y + px, x + py );        // 0-45     度の間
            gfx->m_DrawFramework->DrawPoint(  x + px, y + py );        // 45-90    度の間

            gfx->m_DrawFramework->DrawPoint( -x + px + 1, y + py ); // 90-135   度の間
            gfx->m_DrawFramework->DrawPoint( -y + px + 1, x + py ); // 135-180  度の間

            gfx->m_DrawFramework->DrawPoint( -y + px + 1, -x + py + 1 );  // 180-225  度の間
            gfx->m_DrawFramework->DrawPoint( -x + px + 1, -y + py + 1 );  // 225-270  度の間

            gfx->m_DrawFramework->DrawPoint(  x + px, -y + py + 1 ); // 270-315  度の間
            gfx->m_DrawFramework->DrawPoint(  y + px, -x + py + 1 ); // 315-360  度の間

            d += dx;
            dx+=8;
        }
    }
    
}

void uji::seq::drawer::DrawNG()
{
    uji::sys::GraphicsDrawing *gfx = uji::sys::GraphicsDrawing::GetInstance();
    
    const int AREA_SIZE = 70;
    const int AREA_MARGINE = 0;
    
    nw::ut::FloatColor fColor_WH(nw::ut::Color8::WHITE);
    nw::ut::FloatColor fColor_BL(nw::ut::Color8::BLACK);
    
    gfx->m_DrawFramework->SetColor( fColor_WH.r, fColor_WH.g, fColor_WH.b );
    
    gfx->m_DrawFramework->SetRenderTarget( NN_GX_DISPLAY1 );
    gfx->m_DrawFramework->FillRectangle( 0, 0, gfx->DISPLAY1_WIDTH, gfx->DISPLAY1_HEIGHT );
    
    gfx->m_DrawFramework->SetColor( fColor_BL.r, fColor_BL.g, fColor_BL.b );
    
    int px = 160;
    int py = 30;
    int size = 10;
    
    gfx->m_DrawFramework->DrawLine( px + size,     py + size,     px - size - 1, py - size - 1 );
    gfx->m_DrawFramework->DrawLine( px + size,     py - size - 1, px - size - 1, py + size );
    gfx->m_DrawFramework->DrawLine( px + size + 1, py + size,     px - size,     py - size - 1 );
    gfx->m_DrawFramework->DrawLine( px + size + 1, py - size - 1, px - size,     py + size );

}

