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

#include <vcl.h>
#include "AppGlobalF.h"
#include "ITSSkinF.h"
#include "ITSUtilF.h"
#pragma hdrstop

#include "FrmInitializeF.h"  // 프로그램 초기화화면
#include "FrmVmsControlF.h"

//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "cxContainer"
#pragma link "cxControls"
#pragma link "cxEdit"
#pragma link "cxGraphics"
#pragma link "cxGroupBox"
#pragma link "cxLabel"
#pragma link "cxLookAndFeelPainters"
#pragma link "cxLookAndFeels"
#pragma link "cxPC"
#pragma link "cxPCdxBarPopupMenu"
#pragma link "cxSplitter"
#pragma link "dxSkinBlack"
#pragma link "dxSkinBlue"
#pragma link "dxSkinCaramel"
#pragma link "dxSkinCoffee"
#pragma link "dxSkinDarkRoom"
#pragma link "dxSkinDarkSide"
#pragma link "dxSkinFoggy"
#pragma link "dxSkinGlassOceans"
#pragma link "dxSkiniMaginary"
#pragma link "dxSkinLilian"
#pragma link "dxSkinLiquidSky"
#pragma link "dxSkinLondonLiquidSky"
#pragma link "dxSkinMcSkin"
#pragma link "dxSkinMoneyTwins"
#pragma link "dxSkinOffice2007Black"
#pragma link "dxSkinOffice2007Blue"
#pragma link "dxSkinOffice2007Green"
#pragma link "dxSkinOffice2007Pink"
#pragma link "dxSkinOffice2007Silver"
#pragma link "dxSkinOffice2010Black"
#pragma link "dxSkinOffice2010Blue"
#pragma link "dxSkinOffice2010Silver"
#pragma link "dxSkinsCore"
#pragma link "dxSkinscxPCPainter"
#pragma link "dxSkinSeven"
#pragma link "dxSkinSharp"
#pragma link "dxSkinSilver"
#pragma link "dxSkinStardust"
#pragma link "cxClasses"
#pragma link "cxCustomData"
#pragma link "cxData"
#pragma link "cxDataStorage"
#pragma link "cxFilter"
#pragma link "cxGrid"
#pragma link "cxGridCustomTableView"
#pragma link "cxGridCustomView"
#pragma link "cxGridLevel"
#pragma link "cxGridTableView"
#pragma link "cxStyles"
#pragma link "cxTextEdit"
#pragma link "cxGridCardView"
#pragma link "cxGridCustomLayoutView"
#pragma link "cxCheckBox"
#pragma link "cxDropDownEdit"
#pragma link "cxImage"
#pragma link "cxButtons"
#pragma link "cxCalc"
#pragma link "cxGridBandedTableView"
#pragma link "FRAME_VmsStateF"
#pragma link "FRAME_VmsStateF"
#pragma link "FRAME_VmsMsgListF"
#pragma link "ImageBtn"
#pragma link "cxMaskEdit"
#pragma link "cxRadioGroup"
#pragma link "cxSpinEdit"
#pragma link "cxTimeEdit"
#pragma link "IdBaseComponent"
#pragma link "IdComponent"
#pragma link "IdIcmpClient"
#pragma link "IdRawBase"
#pragma link "IdRawClient"
#pragma link "FFBaseComponent"
#pragma link "FFBasePlay"
#pragma link "FFPlay"
#pragma link "IdHTTP"
#pragma link "IdTCPClient"
#pragma link "IdTCPConnection"
#pragma link "dxSkinsForm"
#pragma link "IdCoder"
#pragma link "IdCoder00E"
#pragma link "IdCoder3to4"
#pragma link "IdCoderMIME"
#pragma link "IdCoderUUE"
#pragma resource "*.dfm"
TFrmVmsControl *FrmVmsControl = NULL;

#define LICENSE_KEY "FSXXXXXX-XXXXXXXX-XXXXXXXX-XXXXXXXX-XXXXXXXX"

//---------------------------------------------------------------------------
__fastcall TFrmVmsControl::TFrmVmsControl(TComponent* Owner)
    : TForm(Owner)
{
    //::CoInitialize(NULL);

    Caption = g_AppCfg.sTitle + " - Active";

    ITSSkin_Initialize(Application);

    CMM_SetFormPosition(g_AppCfg.bSaveForm);

    String sCaption = "0";
    ReadConfigInfo(g_AppCfg.sConfigFile, "APPLICATION", "CAPTION", sCaption);
    ITSSkin_Caption(sCaption == "1" ? true : false);

    ITSSkin_Load(this);
    LoadLocalSkin();

    FTitle = Caption;//"VMS 폼관리";

    //if (FormStyle != fsMDIChild) CMM_LoadForm(g_sFormsDir, this);

    FPalyerForm = NULL;
    FSelVmsObj  = NULL;

    TvList->OptionsView->Footer = false;
    Col04->Visible = false;
    Col05->Visible = false;
    Col06->Visible = true;
    ColumnSel->Visible = true;

    cxTabSheet5->TabVisible = false;
    cxTabSheet5->Visible = false;
    cxTabSheet1->TabVisible = false;
    cxTabSheet1->Visible = false;
    cxTabSheet6->TabVisible = false;
    cxTabSheet6->Visible = false;

    PgControl->ActivePageIndex = 0;

    FVmsIds = new TStringList();

    FTitle = Caption;//"VMS 제어";

    FCtrlTab = NULL;

    PgCam->Properties->HideTabs = true;

    PnlCamera->ParentColor = false;

    FStrmPlay = false;

    reMsg->Lines->Clear();

    String sAVILibDir = g_sAppDir + "LibAV";
    FFPlayer1->SetLicenseKey(LICENSE_KEY);
    FFPlayer1->DisableFPUExceptions();
    if (!FFPlayer1->LoadAVLib(sAVILibDir))
    {
        reMsg->Lines->Add("영상표출 라이브러리 초기화 실패.");
#if 0
        if (g_AppCfg.sLang != "kr") Application->MessageBox(L"Stream display library load failed.", L"Stream display fail", MB_OK|MB_ICONERROR|MB_APPLMODAL);
        else                        Application->MessageBox(L"영상표출 라이브러리를 로드하지 못하였습니다.", L"영상표출 오류", MB_OK|MB_ICONERROR|MB_APPLMODAL);
#endif
    }
    reMsg->Lines->Clear();

    SetColorScheme(g_AppCfg.sSkinName);

}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsControl::SetColorScheme(String ASkinName)
{
    dxSkinController1->SkinName = ASkinName;
    dxSkinController1->Refresh();
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsControl::CommClose()
{
    try
    {
        WebCamStop();
        SAFE_DELETE(FVmsIds);
        //if (FormStyle != fsMDIChild) CMM_SaveForm(g_sFormsDir, this);

        FStrmPlay = false;

        //::CoUninitialize();
    }
    catch(...)
    {
    }
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsControl::FormShow(TObject *Sender)
{
    TmrShow->Enabled = true;
    Refresh();
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsControl::FormActivate(TObject *Sender)
{
    ActivateForm(true);
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsControl::FormDeactivate(TObject *Sender)
{
    ActivateForm(false);
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsControl::LoadLocalSkin()
{
    PnlVmsCam->ParentColor = false;
    PnlVmsCam->Color = clBlack;
    PnlSamsung->ParentColor = false;
    PnlSamsung->Color = clBlack;
    Refresh();
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsControl::TmrShowTimer(TObject *Sender)
{
    TmrShow->Enabled = false;

    TFrmInitialize *FrmInitialize = new TFrmInitialize(this);
    FrmInitialize->FThreadId = g_AppCfg.thr.dwThreadId;
    FrmInitialize->ShowModal();

    UpdateList();
    CxList->Enabled = false;
    UpdatePingList();
    CxList->Enabled = true;
    TmrRefreshStatus->Enabled = true;
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsControl::FormClose(TObject *Sender, TCloseAction &Action)
{
    try {
        CommClose();

        FrmVmsControl = NULL;
        Action = caFree;
    } catch(...) {}
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsControl::OnMainFormMessage(TMessage &Msg)
{
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsControl::OnVmsStateRefreshMessage(TMessage &Msg)
{
    RefreshStatus();
    RefreshPingList();
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsControl::OnVmsFormRefreshMessage(TMessage &Msg)
{
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsControl::OnVmsSelectMessage(TMessage &Msg)
{
#if 0
    try {
        FSelVmsObj = (TVmsCtlr*)Msg.WParam;
        FRAMEVmsState1->SelVmsObj = FSelVmsObj;

        if (!FSelVmsObj) return;

        TVMSWCAM0 *pSelForm = (TVMSWCAM0*)Msg.LParam;
        if (pSelForm == FSelForm) return;

        if (FSelForm) FSelForm->SelectForm(false);

        FSelForm = pSelForm;
        if (FSelForm) FSelForm->SelectForm(true);

        //VMS정보제공구간 소통정보 업데이트
        LoadVmsMsgScenario((FSelVmsObj->VMS_CTLR_NMBR));
    } catch(...) {};
#endif
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsControl::ActivateForm(bool AActivate)
{
//TODO: 기존에는 아래가 주석으로 막혀 있었음. 왜그러지?
    if (AActivate) RefreshStatus();
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsControl::DisplayInfo()
{
    FSelVmsObj = NULL;
    PnlVms->Caption = " " + lblSelVms->Caption + " -";//" Select VMS: -";

    TcxDataController *pGDC = TvList->DataController;
    int nSelIdx = CMM_GetRecordIndex(TvList);
	if (nSelIdx < 0) return;

    String sVmsNmbr = VarToStr(pGDC->Values[nSelIdx][Col01->Index]);

    int nMemPtr = (int)pGDC->Values[nSelIdx][Col99->Index];
    FSelVmsObj = (TVmsCtlr*)nMemPtr;
    if (!FSelVmsObj) return;

    PnlVms->Caption = " " + lblSelVms->Caption + " [" + FSelVmsObj->VMS_CTLR_ID + "] " + FSelVmsObj->VMS_NM;
    try
    {
        if (FSelVmsObj->PANL_ON_TIME.Length() == 4)     // 전팡관ON시각
        {
            String sPowerOnTime  = FSelVmsObj->PANL_ON_TIME;
            sPowerOnTime.Insert(":", 3);
            cxTimeOn->EditValue = sPowerOnTime;
            cxDispStrTm->EditValue = sPowerOnTime;

            cxDisplayTimeOn->EditValue = sPowerOnTime;
        }
        if (FSelVmsObj->PANL_OFF_TIME.Length() == 4)    // 전광판OFF시각
        {
            String sPowerOffTime = FSelVmsObj->PANL_OFF_TIME;
            sPowerOffTime.Insert(":", 3);
            cxTimeOff->EditValue = sPowerOffTime;
            cxDispEndTm->EditValue = sPowerOffTime;

            cxDisplayTimeOff->EditValue = sPowerOffTime;
        }
        Se01->Value = 0;//FSelVmsObj->STATE.ScheduledMessageOperatingTime;/* 필수 계획된 메시지의 동작시간(초) */
        Se02->Value = 0;//FSelVmsObj->STATE.ModuleOperatingTemperature;   /* 필수 모듈 전원이 꺼지는 온도값(℃) */
        Se03->Value = FSelVmsObj->FAN_RUN_TMPR.ToIntDef(0);     /* 필수 Fan 동작 기준 온도값(℃) */
        Se04->Value = FSelVmsObj->HETR_RUN_TMPR.ToIntDef(0);    /* 필수 Heater 동작 기준 온도값(℃) */
        Se05->Value = FSelVmsObj->MODL_ERR_RATE.ToIntDef(0);    /* 선택 모듈 장애율 (한 개의 모듈을 장애로 처리하기 위한 픽셀의 백분율값) */
        Se06->Value = 3;
        Se07->Value = 30;

        SeCurrBrgh->Value = FSelVmsObj->BRGH_CURR_STEP.ToIntDef(0); //휘도 현재 단계(0~100)
        SeWeekBrgh->Value = FSelVmsObj->BRGH_WEEK_STEP.ToIntDef(0); //휘도 주간 단계(0~100)
        SeNghtBrgh->Value = FSelVmsObj->BRGH_NGHT_STEP.ToIntDef(0); //휘도 야간 단계(0~100)


        SeCommErrTime->Value  = 60;  //FSelVmsObj->VMS_CMNC_ERR_BASS_VAL;   //통신장애 기본값(Default=60초)
        SeSlotCommErr->Value  = 0;   //FSelVmsObj->CMNCFAIL_SLOT_NMBR  = (int)pReq->SlotCommErr;     // NUMBER(4)    Y    0        통신장애 SLOT 번호
        SeSlotPowerErr->Value = 0;   //FSelVmsObj->PWER_FAIL_SLOT_NMBR = (int)pReq->SlotPowerErr;    // NUMBER(4)    Y    0        전원 장애 SLOT 번호
#if 0
        SeLumNight->Value     = FSelVmsObj->VMS_NGHT_BRGH_STEP;
        SeLumDay->Value       = FSelVmsObj->VMS_WEEK_BRGH_STEP;
        SeModRate->Value      = FSelVmsObj->VMS_MODL_ERR_RATE;
        SeModCycle->Value     = FSelVmsObj->VMS_MODL_CHK_CYCL;
        SeMsgTime->Value      = FSelVmsObj->DEF_PHSE_CHNG_CYCL;

        SeFormCycleTime->Value = FSelVmsObj->VMS_PHSE_CHNG_CYCL;
#endif
    }
    catch(Exception &e)
    {
    }

    try
    {
        reMsg->Lines->Clear();
        WebCamPlay((FSelVmsObj->VMS_CTLR_NMBR));
    }
    catch(Exception &e)
    {
    }
    BtnWebCamUrl->Enabled = true;
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsControl::BtnAllSelectClick(TObject *Sender)
{
    TcxButton *pBtn = (TcxButton*)Sender;
    if (PgControl->Properties->ActivePage != TabPing)
        CMM_CheckAllListItem(TvList, ColumnSel->Index, pBtn->Tag);
    else
        CMM_CheckAllListItem(TvPing, PColumnSel->Index, pBtn->Tag);
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsControl::ClearCheckList()
{
    TcxDataController *pGDC = TvList->DataController;
    try
    {
        TvList->BeginUpdate();
        pGDC->BeginUpdate();
        int nRows = pGDC->RecordCount;
        for (int ii = 0; ii < nRows; ii++)
        {
            pGDC->Values[ii][ColumnSel->Index] = false;
        }
    }
    __finally
    {
        pGDC->EndUpdate();
        TvList->EndUpdate();
    }
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsControl::Se01PropertiesChange(TObject *Sender)
{
#if 1
    if (((TcxSpinEdit*)Sender)->Value < ((TcxSpinEdit*)Sender)->Properties->MinValue)
        ((TcxSpinEdit*)Sender)->Value = ((TcxSpinEdit*)Sender)->Properties->MinValue;
    else if(((TcxSpinEdit*)Sender)->Value > ((TcxSpinEdit*)Sender)->Properties->MaxValue &&
        ((TcxSpinEdit*)Sender)->Properties->MaxValue)
        ((TcxSpinEdit*)Sender)->Value = ((TcxSpinEdit*)Sender)->Properties->MaxValue;
#endif
}
//---------------------------------------------------------------------------

int __fastcall TFrmVmsControl::GetSelListItems(bool ACommCheck/*=true*/)
{
    TcxDataController *pGDC = TvList->DataController;

    FVmsIds->Clear();
    try
    {
        bool bSelected;

        int nRows = TvList->ViewData->RecordCount;
        TvList->BeginUpdate();

        for (int ii = 0; ii < nRows; ii++)
        {
            TcxCustomGridRow* ARow = TvList->ViewData->Rows[ii];
            int nMemPtr = (int)ARow->Values[Col99->Index];
            TVmsCtlr *pVms = (TVmsCtlr*)nMemPtr;
            if (!pVms) continue;

            bSelected = (bool)ARow->Values[ColumnSel->Index];
            if (bSelected)
            {
                String sVmsNmbr = ARow->Values[Col01->Index];    //VMS번호
                if (ACommCheck)
                {
                    if (pVms->STTS->CMNC_STTS_CD == "CMS0")
                    {
                        FVmsIds->Add(sVmsNmbr);
                    }
                }
                else
                {
                    FVmsIds->Add(sVmsNmbr);
                }
            }
        }
    }
    __finally
    {
        TvList->EndUpdate();
    }

    return FVmsIds->Count;
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsControl::BtnControlClick(TObject *Sender)
{
#if 0
    //전광판제어
    String sTitle = cxLabel1->Caption;//"전광판/제어기 제어";
    String sMsg   = "";

    int nOkCnt  = 0;
    int nSelCnt = GetSelListItems(false);
    if (0 == nSelCnt)
    {
        sMsg = cxLabel2->Caption + "\r\n" + cxLabel9->Caption;//"VMS가 선택되지 않았습니다.\r\nVMS 목록에서 VMS를 선택하십시요.\r\n현재 통신이 비정상인 VMS는 선택하실 수 없습니다.";
        Application->MessageBox(sMsg.c_str(), sTitle.c_str(), MB_OK|MB_ICONERROR|MB_APPLMODAL);
        CxList->SetFocus();
        return;
    }

    int nCmdIdx;
    if (RdbOn->Checked)
    {
        nCmdIdx = 1;//vms_req_board_power_on;
        sMsg = cxLabel3->Caption + "\r\n" + cxLabel9->Caption;//"선택하신 VMS에 VMS 전광판 전원 ON 명령을 전송하시겠습니까?\r\n(통신상태에 따라 명령이 실행되지 않을 수 있습니다.)";
    }
    else
    if (RdbOff->Checked)
    {
        nCmdIdx = 0;//vms_req_board_power_off;
        sMsg = cxLabel4->Caption + "\r\n" + cxLabel9->Caption;//"선택하신 VMS에 VMS 전광판 전원 OFF 명령을 전송하시겠습니까?\r\n(통신상태에 따라 명령이 실행되지 않을 수 있습니다.)";
    }
    else
    if (RdbReset->Checked)
    {
        nCmdIdx = 2;
        sMsg = cxLabel5->Caption + "\r\n" + cxLabel9->Caption;//"선택하신 VMS에 VMS 제어기 리셋 명령을 전송하시겠습니까?\r\n(통신상태에 따라 명령이 실행되지 않을 수 있습니다.)";
    }
    else
    if (RdbLuminance->Checked)
    {
        nCmdIdx = 3;
        sMsg = cxLabel6->Caption + "\r\n" + cxLabel9->Caption;//"선택하신 VMS에 VMS 휘도값 제어 명령을 전송하시겠습니까?\r\n(통신상태에 따라 명령이 실행되지 않을 수 있습니다.)";
    }
    if (Application->MessageBox(sMsg.c_str(), sTitle.c_str(), MB_YESNO|MB_ICONWARNING|MB_APPLMODAL) != IDYES) return;

    String sCmdUser = g_AppCfg.sUserId;
    String sCmdTime = Now().FormatString("yyyymmddhhnnss");

    int result;
    for (int ii = 0; ii < nSelCnt; ii++)
    {
        String sVmsNmbr = FVmsIds->Strings[ii];

        if (nCmdIdx == vms_req_board_power_on || nCmdIdx == vms_req_board_power_off)
        {
            // 전광판 On(=0)/Off(=1)
            INT_VMS_POWER_CTL_REQ VmsPowerCtl;
            BYTE                  MsgSeq;

            memset(&VmsPowerCtl, 0x00, sizeof(VmsPowerCtl));

            MsgSeq = (BYTE)0x10;                                                            // 제어명령 일련번호-결과값을 받아서 처리할때 필요함

            memcpy(VmsPowerCtl.CmdTime, AnsiString(sCmdTime).c_str(), INT_VMS_MAX_DATETIME); /* 명령수행시각 */
            memcpy(VmsPowerCtl.OperId,  AnsiString(sCmdUser).c_str(), INT_VMS_MAX_OPER_ID);  /* 운영자 ID */
            VmsPowerCtl.VMS_CTLR_NMBR = sVmsNmbr.ToIntDef(0);
            VmsPowerCtl.Command = (BYTE)nCmdIdx;    /* 제어 구분, 1:켜짐 2:꺼짐 */

            String sOprCode  = (nCmdIdx == vms_req_board_power_on) ? "V01" : "V02";
            String sCmdValue = (nCmdIdx == vms_req_board_power_on) ? "On"  : "Off";

            result = CComm_VmsPowerControlReq(&VmsPowerCtl, MsgSeq);
            if (VERR_NONE == result)
            {
                //TODO VmsCtlrManager->InsVmsControlHs(sCmdTime, sVmsNmbr, sOprCode, sCmdValue, "1", sCmdUser);
                nOkCnt++;
            }
            else
            {
                //TODO VmsCtlrManager->InsVmsControlHs(sCmdTime, sVmsNmbr, sOprCode, sCmdValue, "0", sCmdUser);
            }
        }
        else
        if (nCmdIdx == 2)
        {
            // 제어기 리셋
            INT_VMS_RESET_REQ VmsReset;
            BYTE              MsgSeq;

            memset(&VmsReset, 0x00, sizeof(VmsReset));

            MsgSeq = (BYTE)0x20;
            memcpy(VmsReset.CmdTime, AnsiString(sCmdTime).c_str(), INT_VMS_MAX_DATETIME); /* 명령수행시각 */
            memcpy(VmsReset.OperId,  AnsiString(sCmdUser).c_str(), INT_VMS_MAX_OPER_ID);  /* 운영자 ID */
            VmsReset.VMS_CTLR_NMBR = sVmsNmbr.ToIntDef(0);

            result = CComm_VmsResetReq(&VmsReset, MsgSeq);
            if (VERR_NONE == result)
            {
                //TODO VmsCtlrManager->InsVmsControlHs(sCmdTime, sVmsNmbr, "V03", "Reset", "1", sCmdUser);
                nOkCnt++;
            }
            else
            {
                //TODO VmsCtlrManager->InsVmsControlHs(sCmdTime, sVmsNmbr, "V03", "Reset", "0", sCmdUser);
            }
        }
        else
        if (nCmdIdx == 3)
        {
            // 휘도제어
            INT_VMS_LUMINANCE_REQ VmsLuminance;
            BYTE                  MsgSeq;

            String sCmdValue = SeLuminance->Value;
            memset(&VmsLuminance, 0x00, sizeof(VmsLuminance));

            MsgSeq = (BYTE)0x30;
            memcpy(VmsLuminance.CmdTime, AnsiString(sCmdTime).c_str(), INT_VMS_MAX_DATETIME); /* 명령수행시각 */
            memcpy(VmsLuminance.OperId,  AnsiString(sCmdUser).c_str(), INT_VMS_MAX_OPER_ID);  /* 운영자 ID */
            VmsLuminance.VMS_CTLR_NMBR = sVmsNmbr.ToIntDef(0);
            switch(CbBrghMode->ItemIndex)
            {
            case 0: VmsLuminance.BrghMode = 0x00; break;
            case 1: VmsLuminance.BrghMode = 0x01; break;
            case 2: VmsLuminance.BrghMode = 0x02; break;
            case 3: VmsLuminance.BrghMode = 0x09; break;
            }
            VmsLuminance.BrghCurrStep = (BYTE)SeCurrBrgh->Value;
            VmsLuminance.BrghWeekStep = (BYTE)SeWeekBrgh->Value;
            VmsLuminance.BrghNghtStep = (BYTE)SeNghtBrgh->Value;

            result = CComm_VmsLuminanceReq(&VmsLuminance, MsgSeq);
            if (VERR_NONE == result)
            {
                //TODO VmsCtlrManager->InsVmsControlHs(sCmdTime, sVmsNmbr, "V07", sCmdValue, "1", sCmdUser);
                nOkCnt++;
            }
            else
            {
                //TODO VmsCtlrManager->InsVmsControlHs(sCmdTime, sVmsNmbr, "V07", sCmdValue, "0", sCmdUser);
            }
        }
        Sleep(100);
        Application->ProcessMessages();
    }

    //sMsg = String(nSelCnt) + " 개의 선택 VMS 중에 " + String(nOkCnt) + " 개의 VMS로 전광판/제어기 제어 명령을 요청하였습니다.";
    sMsg = String(nSelCnt) + " " + cxLabel7->Caption + " " + String(nOkCnt) + " " + cxLabel8->Caption;

    Application->MessageBox(sMsg.c_str(), sTitle.c_str(), MB_OK|MB_ICONINFORMATION|MB_APPLMODAL);
#endif
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsControl::BtnConfigClick(TObject *Sender)
{
    //제어기함체환경설정
    int nVal03 = Se03->Value;
    int nVal04 = Se04->Value;
    int nStrTmHour = cxDispStrTm->Time.FormatString("HH").ToIntDef(0);
    int nStrTmMin  = cxDispStrTm->Time.FormatString("NN").ToIntDef(0);
    int nEndTmHour = cxDispEndTm->Time.FormatString("HH").ToIntDef(0);
    int nEndTmMin  = cxDispEndTm->Time.FormatString("NN").ToIntDef(0);

    String sTitle = cxLabel10->Caption;//"VMS 함체환경 설정";
    String sMsg   = "";

    int nOkCnt  = 0;
    int nSelCnt = GetSelListItems(false);
    if (0 == nSelCnt)
    {
        sMsg = cxLabel2->Caption;//"VMS가 선택되지 않았습니다.\r\nVMS 목록에서 VMS를 선택하십시요.\r\n현재 통신이 비정상인 VMS는 선택하실 수 없습니다.";
        Application->MessageBox(sMsg.c_str(), sTitle.c_str(), MB_OK|MB_ICONERROR|MB_APPLMODAL);
        CxList->SetFocus();
        return;
    }

    if ((nStrTmHour*60 + nStrTmMin) > (nEndTmHour*60 + nEndTmMin))
    {
        sMsg = "전광판 가동종료시각이 전광판 가동시작시각보다 클 수 없습니다.\r\n전광판 가동시각을 확인하세요.";
        Application->MessageBox(sMsg.c_str(), sTitle.c_str(), MB_OK|MB_ICONERROR|MB_APPLMODAL);
        return;
    }

    String sDispStrTm;
    String sDispEndTm;
    sDispStrTm.printf(L"%02d%02d", nStrTmHour, nStrTmMin);
    sDispEndTm.printf(L"%02d%02d", nEndTmHour, nEndTmMin);

    int nCmdIdx = 0;
    sMsg = cxLabel11->Caption + "\r\n" + cxLabel9->Caption;//"선택하신 VMS에 함체환경 설정 명령을 전송하시겠습니까?\r\n(통신상태에 따라 명령이 실행되지 않을 수 있습니다.)";
    if (Application->MessageBox(sMsg.c_str(), sTitle.c_str(), MB_YESNO|MB_ICONWARNING|MB_APPLMODAL) != IDYES) return;

    String sCmdUser = g_AppCfg.sUserId;
    for (int ii = 0; ii < nSelCnt; ii++)
    {
        String sVmsNmbr = FVmsIds->Strings[ii];

        bool result = VmsCtlrManager->ParamSet(sCmdUser, sVmsNmbr, nVal03, nVal04, sDispStrTm, sDispEndTm);
        if (result)
        {
            TVmsCtlr *pObj = VmsCtlrManager->FLists.Find(sVmsNmbr);
            if (pObj)
            {
                pObj->FAN_RUN_TMPR = String(nVal03);
                pObj->HETR_RUN_TMPR = String(nVal04);
                pObj->PANL_ON_TIME = sDispStrTm;
                pObj->PANL_OFF_TIME = sDispEndTm;
            }
            nOkCnt++;
        }
        Sleep(100);
        Application->ProcessMessages();
    }

    //sMsg = String(nSelCnt) + " 개의 선택 VMS 중에 " + String(nOkCnt) + " 개의 VMS 함체환경 설정 명령을 요청하였습니다.";
    sMsg = String(nSelCnt) + " " + cxLabel7->Caption + " " + String(nOkCnt) + " " + cxLabel12->Caption;
    Application->MessageBox(sMsg.c_str(), sTitle.c_str(), MB_OK|MB_ICONINFORMATION|MB_APPLMODAL);
    RefreshStatus();
}
//---------------------------------------------------------------------------

bool __fastcall TFrmVmsControl::UpdateVmsParam(String AVmsNmbr, void *pData)
{
#if 0
    String     sQry;
    TADOQuery *pADO = NULL;
    int        nCnt = 0;

    INT_VMS_PARA_SET_REQ *pReq = (INT_VMS_PARA_SET_REQ*)pData;

    sQry = "UPDATE TB_VMS_CTLR           \r\n"
           "   SET FAN_RUN_TMPR  = :p02, \r\n"
           "       HETR_RUN_TMPR = :p03, \r\n"
           "       PANL_ON_TIME  = :p04, \r\n"
           "       PANL_OFF_TIME = :p05  \r\n"
           " WHERE VMS_CTLR_NMBR = :p01  \r\n";
    try
    {
        try
        {
            String sFanRunTmpr;
            String sHetrRunTmpr;
            String sDispStrTm;
            String sDispEndTm;
            char szTemp[20];

            sFanRunTmpr.printf(L"%d", pReq->FanRunTmpr);
            sHetrRunTmpr.printf(L"%d", pReq->HetrRunTmpr);

            memset(szTemp, 0x00, sizeof(szTemp));
            sprintf(szTemp, "%4.4s", (char*)pReq->DispStrTm);
            sDispStrTm = String(szTemp);

            memset(szTemp, 0x00, sizeof(szTemp));
            sprintf(szTemp, "%4.4s", (char*)pReq->DispEndTm);
            sDispEndTm = String(szTemp);

            pADO = new TADOQuery(NULL);
			pADO->Close();
            pADO->Connection = ITSDb_GetConnection();
			pADO->SQL->Clear();
			pADO->SQL->Text = sQry;
            pADO->Parameters->ParamByName("p01")->Value = AVmsNmbr;
            pADO->Parameters->ParamByName("p02")->Value = sFanRunTmpr;
            pADO->Parameters->ParamByName("p03")->Value = sHetrRunTmpr;
            pADO->Parameters->ParamByName("p04")->Value = sDispStrTm;
            pADO->Parameters->ParamByName("p05")->Value = sDispEndTm;
			nCnt = pADO->ExecSQL();
        }
        catch(EDatabaseError &E)
        {
            DBERRORLOG("TVMS0500M::UpdateVmsParam", String(E.ClassName()), E.Message, sQry);
            throw Exception(String(E.ClassName()) + E.Message);
        }
        catch(Exception &e)
        {
            DBERRORLOG("TVMS0500M::UpdateVmsParam", String(e.ClassName()), e.Message, sQry);
            throw Exception(String(e.ClassName()) + e.Message);
        }
    }
    __finally
    {
        if (pADO)
        {
            pADO->Close();
            delete pADO;
        }
    }

    return nCnt > 0 ? true : false;
#endif
return false;
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsControl::BtnOnOffSetClick(TObject *Sender)
{
#if 0
    //전광판ON/OFF시각설정
    String sTitle = cxLabel13->Caption;//"전광판 ON/OFF 시각 설정";
    String sMsg   = "";

    int nOkCnt  = 0;
    int nSelCnt = GetSelListItems(false);
    if (0 == nSelCnt)
    {
        sMsg = cxLabel14->Caption;//"VMS가 선택되지 않았습니다.\r\nVMS 목록에서 VMS를 선택하십시요.";
        Application->MessageBox(sMsg.c_str(), sTitle.c_str(), MB_OK|MB_ICONERROR|MB_APPLMODAL);
        CxList->SetFocus();
        return;
    }

    int nCmdIdx = 0;
    sMsg = cxLabel15->Caption;//"선택하신 VMS의 전광판 ON/OFF 시각을 설정 하시겠습니까?";
    if (Application->MessageBox(sMsg.c_str(), sTitle.c_str(), MB_YESNO|MB_ICONWARNING|MB_APPLMODAL) != IDYES) return;

    String     sQry;
    TADOQuery *pADO = NULL;

    sQry = "UPDATE TB_VMS_CTLR            \r\n"
           "   SET PANL_ON_TIME   = :p02, \r\n"
           "       PANL_OFF_TIME  = :p03  \r\n"
           " WHERE VMS_CTLR_NMBR  = :p01  \r\n";


    String PANL_ON_TIME   = cxTimeOn->Time.FormatString("HHNN");
    String PANL_OFF_TIME  = cxTimeOff->Time.FormatString("HHNN");
    String LAST_CRPR_NMBR = g_AppCfg.sUserId;
    String LAST_CRCT_DT	  = Now().FormatString("yyyymmddhhnnss");

    try
    {
        try
        {
            pADO = new TADOQuery(NULL);
			pADO->Close();
            pADO->Connection = ITSDb_GetConnection();
			pADO->SQL->Clear();
			pADO->SQL->Text = sQry;

            for (int ii = 0; ii < nSelCnt; ii++)
            {
                String sVmsNmbr = FVmsIds->Strings[ii];

                pADO->Parameters->ParamByName("p01")->Value = sVmsNmbr;
                pADO->Parameters->ParamByName("p02")->Value = PANL_ON_TIME;
                pADO->Parameters->ParamByName("p03")->Value = PANL_OFF_TIME;
                pADO->ExecSQL();
                nOkCnt++;

                TVmsCtlr *pObj = VmsCtlrManager->FLists.Find(sVmsNmbr);
                if (pObj)
                {
                    pObj->PANL_ON_TIME  = PANL_ON_TIME;
                    pObj->PANL_OFF_TIME = PANL_OFF_TIME;
                }
            }
        }
        catch(EDatabaseError &E)
        {
            DBERRORLOG("TVMS0500M::BtnOnOffSetClick", String(E.ClassName()), E.Message, sQry);
            throw Exception(String(E.ClassName()) + E.Message);
        }
        catch(Exception &e)
        {
            DBERRORLOG("TVMS0500M::BtnOnOffSetClick", String(e.ClassName()), e.Message, sQry);
            throw Exception(String(e.ClassName()) + e.Message);
        }
    }
    __finally
    {
        if (pADO)
        {
            pADO->Close();
            delete pADO;
        }
    }

    //sMsg = String(nSelCnt) + " 개의 선택 VMS 중에 " + String(nOkCnt) + " 개의 VMS로 전광판 ON/OFF 시각 설정을 요청하였습니다.";
    sMsg = String(nSelCnt) + " " + cxLabel7->Caption + " " + String(nOkCnt) + " " + cxLabel16->Caption;
    Application->MessageBox(sMsg.c_str(), sTitle.c_str(), MB_OK|MB_ICONINFORMATION|MB_APPLMODAL);

    for (int ii = 0; ii < nSelCnt; ii++)
    {
        String sVmsNmbr = FVmsIds->Strings[ii];

        VmsCtlrManager->InsVmsControlHs(LAST_CRCT_DT, sVmsNmbr, "V05", PANL_ON_TIME+" "+PANL_OFF_TIME, "1", LAST_CRPR_NMBR);
    }
    //RefreshStatus();
    //FrmVmsOprMain->RefreshVmsMessage(WM_VMS_STATE_REFRESH);
#endif
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsControl::BtnModeControlClick(TObject *Sender)
{
    //VMS 운영모드 변경
    String sTitle = cxLabel17->Caption;//"VMS 운영모드 변경";
    String sMsg   = "";

    int nOkCnt  = 0;
    int nSelCnt = GetSelListItems(false);
    if (0 == nSelCnt)
    {
        sMsg = cxLabel14->Caption;//"VMS가 선택되지 않았습니다.\r\nVMS 목록에서 VMS를 선택하십시요.";
        Application->MessageBox(sMsg.c_str(), sTitle.c_str(), MB_OK|MB_ICONERROR|MB_APPLMODAL);
        CxList->SetFocus();
        return;
    }

    int nCmdIdx = 0;
    sMsg = cxLabel18->Caption;//"선택하신 VMS의 운영모드를 변경 하시겠습니까?";
    if (Application->MessageBox(sMsg.c_str(), sTitle.c_str(), MB_YESNO|MB_ICONWARNING|MB_APPLMODAL) != IDYES) return;

    String OPER_MODE;
    String OPER_MODE_DESC;
    if (RdbAuto->Checked)
    {
        OPER_MODE = "A";
        OPER_MODE_DESC = "자동";
    }
    else
    if (RdbFix->Checked)
    {
        OPER_MODE = "F";
        OPER_MODE_DESC = "고정";
    }
    else
    if (RdbBase->Checked)
    {
        OPER_MODE = "B";
        OPER_MODE_DESC = "기본";
    }

    String sCmdUser = g_AppCfg.sUserId;
    for (int ii = 0; ii < nSelCnt; ii++)
    {
        String sVmsNmbr = FVmsIds->Strings[ii];
        bool result = VmsCtlrManager->OperModeSet(sCmdUser, sVmsNmbr, OPER_MODE);
        if (result) {
            TVmsCtlr *pObj = VmsCtlrManager->FLists.Find(sVmsNmbr);
            if (pObj)
            {
                pObj->OPER_MODE = OPER_MODE;
                pObj->OPER_MODE_DESC = OPER_MODE_DESC;
            }
            nOkCnt++;
        }

        Sleep(100);
        Application->ProcessMessages();
    }

    //sMsg = String(nSelCnt) + " 개의 선택 VMS 중에 " + String(nOkCnt) + " 개의 VMS 운영모드를 변경하였습니다.";
    sMsg = String(nSelCnt) + " " + cxLabel7->Caption + " " + String(nOkCnt) + " " + cxLabel19->Caption;//;
    Application->MessageBox(sMsg.c_str(), sTitle.c_str(), MB_OK|MB_ICONINFORMATION|MB_APPLMODAL);

    //TmrRefreshStatus->Enabled = false;
    //TmrRefreshStatus->Interval = 5000;
    //TmrRefreshStatus->Enabled = true;
    RefreshStatus();
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsControl::BtnWebCamUrlClick(TObject *Sender)
{
    if (FSelVmsObj)
    {
        if (FSelVmsObj->WEB_CMRA_IP.Trim() != "")
        {
            String sUrl = "http://" + FSelVmsObj->WEB_CMRA_IP.Trim();
            if (FSelVmsObj->WEB_CMRA_PORT != "")
            {
                sUrl = sUrl + ":" + FSelVmsObj->WEB_CMRA_PORT;
            }
            ShellExecute(NULL, NULL, sUrl.c_str(), NULL, NULL, 0);
        }
    }
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsControl::BtnDefaultMsgClick(TObject *Sender)
{
#if 0
    TcxButton *pBtn = (TcxButton*)Sender;

    String sTitle = pBtn->Caption.Trim();
    String sMsg   = "";
    String sCmd   = "";
    String sCmdValue;
    BYTE   ucCommand;

    int nOkCnt  = 0;
    int nSelCnt = GetSelListItems(true);
    if (0 == nSelCnt)
    {
        sMsg = cxLabel2->Caption + "\r\n" + cxLabel9->Caption;//"VMS가 선택되지 않았습니다.\r\nVMS 목록에서 VMS를 선택하십시요.\r\n현재 통신이 비정상인 VMS는 선택하실 수 없습니다.";
        Application->MessageBox(sMsg.c_str(), sTitle.c_str(), MB_OK|MB_ICONERROR|MB_APPLMODAL);
        CxList->SetFocus();
        return;
    }

    if (pBtn->Tag == 0)
    {
        // Default Msg Display
        sMsg = cxLabel20->Caption + "\r\n" + cxLabel9->Caption;//"선택하신 VMS에 기본메시지 표출 명령을 전송하시겠습니까?\r\n(통신상태에 따라 명령이 실행되지 않을 수 있습니다.)";
        sCmd = "V11";
        sCmdValue = "D";
        ucCommand = 0x55;
    }
    else
    {
        // Blank Display
        sMsg = cxLabel21->Caption + "\r\n" + cxLabel9->Caption;//"선택하신 VMS에 Blank 표출 명령을 전송하시겠습니까?\r\n(통신상태에 따라 명령이 실행되지 않을 수 있습니다.)";
        sCmd = "V12";
        sCmdValue = "B";
        ucCommand = 0x54;
    }

    if (Application->MessageBox(sMsg.c_str(), sTitle.c_str(), MB_YESNO|MB_ICONWARNING|MB_APPLMODAL) != IDYES) return;

    String sCmdUser = g_AppCfg.sUserId;
    String sCmdTime = Now().FormatString("yyyymmddhhnnss");

    int result;
    for (int ii = 0; ii < nSelCnt; ii++)
    {
        String sVmsNmbr = FVmsIds->Strings[ii];

        INT_VMS_DIRECT_CTL_REQ directCmd;
        BYTE MsgSeq;

        memset(&directCmd, 0x00, sizeof(directCmd));
        MsgSeq = (BYTE)0x60;

        memcpy(directCmd.CmdTime, AnsiString(sCmdTime).c_str(), INT_VMS_MAX_DATETIME); /* 명령수행시각 */
        memcpy(directCmd.VmsId,   AnsiString(sVmsNmbr).c_str(), INT_VMS_MAX_ID);       /* VMS 제어기 번호 */
        memcpy(directCmd.OperId,  AnsiString(sCmdUser).c_str(), INT_VMS_MAX_OPER_ID);  /* 운영자 ID */

        directCmd.Command = ucCommand;

        result = CComm_VmsDirectCmdReq(&directCmd, MsgSeq);
        if (VERR_NONE == result)
        {
            //TODO VmsCtlrManager->InsVmsControlHs(sCmdTime, sVmsNmbr, sCmd, sCmdValue, "1", sCmdUser);
            nOkCnt++;
        }
        else
        {
            //TODO VmsCtlrManager->InsVmsControlHs(sCmdTime, sVmsNmbr, sCmd, sCmdValue, "0", sCmdUser);
        }
        Sleep(100);
        Application->ProcessMessages();
    }

    //sMsg = String(nSelCnt) + " 개의 선택 VMS 중에 " + String(nOkCnt) + " 개의 VMS에 명령을 요청하였습니다.";
    sMsg = String(nSelCnt) + " " + cxLabel7->Caption + " " + String(nOkCnt) + " " + cxLabel22->Caption;
    Application->MessageBox(sMsg.c_str(), sTitle.c_str(), MB_OK|MB_ICONINFORMATION|MB_APPLMODAL);
#endif
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsControl::BtnParamSettingClick(TObject *Sender)
{
#if 0
    //제어기함체환경설정
    int nCommErrTime  = SeCommErrTime->Value;//   = 60;  //통신장애 기본값(Default=60초)
    int nSlotCommErr  = SeSlotCommErr->Value;//   = 0;   //FSelVmsObj->CMNCFAIL_SLOT_NMBR  = (int)pReq->SlotCommErr;     // NUMBER(4)    Y    0        통신장애 SLOT 번호
    int nSlotPowerErr = SeSlotPowerErr->Value;//  = 0;   //FSelVmsObj->PWER_FAIL_SLOT_NMBR = (int)pReq->SlotPowerErr;    // NUMBER(4)    Y    0        전원 장애 SLOT 번호
    int nLumNight     = SeLumNight->Value;//      = FSelVmsObj->VMS_NGHT_BRGH_STEP;
    int nLumDay       = SeLumDay->Value;//        = FSelVmsObj->VMS_WEEK_BRGH_STEP;
    int nModErrRate   = SeModRate->Value;//       = FSelVmsObj->VMS_MODL_ERR_RATE;
    int nModChkCycle  = SeModCycle->Value;//      = FSelVmsObj->VMS_MODL_CHK_CYCL;
    int nPhaseCycle   = SeMsgTime->Value;//      = FSelVmsObj->DEF_PHSE_CHNG_CYCL;

    String sTitle = cxLabel23->Caption;//"VMS 함체환경 설정";
    String sMsg   = "";

    int nOkCnt  = 0;
    int nSelCnt = GetSelListItems(true);
    if (0 == nSelCnt)
    {
        sMsg = cxLabel2->Caption + "\r\n" + cxLabel9->Caption;//"VMS가 선택되지 않았습니다.\r\nVMS 목록에서 VMS를 선택하십시요.\r\n현재 통신이 비정상인 VMS는 선택하실 수 없습니다.";
        Application->MessageBox(sMsg.c_str(), sTitle.c_str(), MB_OK|MB_ICONERROR|MB_APPLMODAL);
        CxList->SetFocus();
        return;
    }

    int nCmdIdx = 0;
    sMsg = cxLabel24->Caption + "\r\n" + cxLabel9->Caption;//"선택하신 VMS에 함체환경 설정 명령을 전송하시겠습니까?\r\n(통신상태에 따라 명령이 실행되지 않을 수 있습니다.)";
    if (Application->MessageBox(sMsg.c_str(), sTitle.c_str(), MB_YESNO|MB_ICONWARNING|MB_APPLMODAL) != IDYES) return;

    String sCmdUser = g_pLOGIN->sUserId;
    String sCmdTime = Now().FormatString("yyyymmddhhnnss");
    String sCmdValue;

    sCmdValue.printf(L"%d.%d,%d,%d,%d,%d,%d",
                        nLumNight,
                        nLumDay,
                        nModErrRate,
                        nModChkCycle,
                        nPhaseCycle,
                        nCommErrTime,
                        nSlotCommErr);
    int result;
    for (int ii = 0; ii < nSelCnt; ii++)
    {
        String sVmsNmbr = FVmsIds->Strings[ii];

        INT_VMS_PARA_SET_REQ2 VmsPara;
        BYTE MsgSeq;

        memset(&VmsPara, 0x00, sizeof(VmsPara));
        MsgSeq = (BYTE)0x40;

        memcpy(VmsPara.CmdTime, AnsiString(sCmdTime).c_str(), INT_VMS_MAX_DATETIME); /* 명령수행시각 */
        memcpy(VmsPara.VmsId,   AnsiString(sVmsNmbr).c_str(), INT_VMS_MAX_ID);       /* VMS 제어기 번호 */
        memcpy(VmsPara.OperId,  AnsiString(sCmdUser).c_str(), INT_VMS_MAX_OPER_ID);  /* 운영자 ID */

        VmsPara.DefCommErr      = (BYTE)nCommErrTime;                           // 통신장애 기본값, 제어기가 Host로부터 Poll 또는 명령을 받지 않고 경과할 수 있는 최대시간 (default ; 60초)
        VmsPara.SlotCommErr     = (short)nSlotCommErr;                          // 통신장애 slot번호, 통신 fail 시 표시할 메시지 번호(default 0번)
        VmsPara.SlotPowerErr    = (short)nSlotPowerErr;                         // 전원장애 slot번호, 전원장애 시 표시할 메시지 번호(default 0번)
        VmsPara.NightLuminance  = (BYTE)nLumNight;                       // 야간 휘도 값, 0x30 ~ 0x3F
        VmsPara.DayLuminance    = (BYTE)nLumDay;                         // 주간 휘도 값, 0x40 ~ 0x4F
        VmsPara.PhaseCycleTime  = (BYTE)nPhaseCycle;                       // phase시간주기, 장애시 phase주기 (default : 3초, 범위 : 0 ~ 10초)
        VmsPara.ModuleFailRate  = (BYTE)nModErrRate;                       // 모듈장애율, 한개의 module을 장애로 처리하기 위한 장애 pixel백분율 (default 10%)
        VmsPara.ModuleCheckTime = (BYTE)nModChkCycle;                      // 모듈감시 주기, 0 ~ 255 (단위:초)
        VmsPara.BoardOnHour     = (BYTE)cxDisplayTimeOn->Time.FormatString("HH").ToIntDef(0);                          // 전광판 On time(시), 0시 ~ 23시
        VmsPara.BoardOnMin      = (BYTE)cxDisplayTimeOn->Time.FormatString("NN").ToIntDef(0);                           // 전광판 On time(분), 0시 ~ 23시
        VmsPara.BoardOffHour    = (BYTE)cxDisplayTimeOff->Time.FormatString("HH").ToIntDef(0);                         // 전광판 Off time(시), 0시 ~ 23시
        VmsPara.BoardOffMin     = (BYTE)cxDisplayTimeOff->Time.FormatString("NN").ToIntDef(0);                          // 전광판 Off time(분), 0시 ~ 23시

        result = CComm_VmsParaSetReq2(&VmsPara, MsgSeq);
        if (VERR_NONE == result)
        {
            VmsCtlrManager->InsVmsControlHs(sCmdTime, sVmsNmbr, "V04", sCmdValue, "1", sCmdUser);
            nOkCnt++;

            //통신전송후 바이트오더링이 바뀐다
            VmsPara.SlotCommErr  = (short)nSlotCommErr;
            VmsPara.SlotPowerErr = (short)nSlotPowerErr;

            if (UpdateVmsParam2(sVmsNmbr, (void*)&VmsPara))
            {
                TVmsCtlr *pObj = VmsCtlrManager->FLists.Find(sVmsNmbr);
                if (pObj)
                {
#if 0
                    pObj->VMS_CMNC_ERR_BASS_VAL  = (int)VmsPara.DefCommErr;
                    pObj->CMNCFAIL_SLOT_NMBR     = (int)VmsPara.SlotCommErr;     // NUMBER(4)    Y    0        통신장애 SLOT 번호
                    pObj->PWER_FAIL_SLOT_NMBR    = (int)VmsPara.SlotPowerErr;    // NUMBER(4)    Y    0        전원 장애 SLOT 번호
                    pObj->VMS_NGHT_BRGH_STEP     = (int)VmsPara.NightLuminance;
                    pObj->VMS_WEEK_BRGH_STEP     = (int)VmsPara.DayLuminance;
                    pObj->DEF_PHSE_CHNG_CYCL     = (int)VmsPara.PhaseCycleTime;
                    pObj->VMS_MODL_ERR_RATE      = (int)VmsPara.ModuleFailRate;
                    pObj->VMS_MODL_CHK_CYCL      = (int)VmsPara.ModuleCheckTime;

                    pObj->PANL_ON_TIME.printf(L"%02d%02d", (int)VmsPara.BoardOnHour, (int)VmsPara.BoardOnMin);
                    pObj->PANL_OFF_TIME.printf(L"%02d%02d", (int)VmsPara.BoardOffHour, (int)VmsPara.BoardOffMin);

                    pObj->DEF_PHSE_CHNG_CYCL = nPhaseCycle;
                    pObj->STATE.ScheduledMessageOperatingTime = pObj->DEF_PHSE_CHNG_CYCL;    /* 필수 계획된 메시지의 동작시간(초) */
                    //pObj->STATE.ModuleOperatingTemperature    = pObj->VMS_CMNC_ERR_BASS_VAL; /* 필수 모듈 전원이 꺼지는 온도값(℃) */
                    pObj->STATE.ModuleBasicFailureRate        = pObj->VMS_MODL_ERR_RATE;     /* 선택 모듈 장애율 (한 개의 모듈을 장애로 처리하기 위한 픽셀의 백분율값) */
#endif
                }
            }
        }
        else
        {
            VmsCtlrManager->InsVmsControlHs(sCmdTime, sVmsNmbr, "V04", sCmdValue, "0", sCmdUser);
        }
        Sleep(100);
        Application->ProcessMessages();
    }

    //sMsg = String(nSelCnt) + " 개의 선택 VMS 중에 " + String(nOkCnt) + " 개의 VMS 함체환경 설정 명령을 요청하였습니다.";
    sMsg = String(nSelCnt) + " " + cxLabel7->Caption + " " + String(nOkCnt) + " " + cxLabel25->Caption;
    Application->MessageBox(sMsg.c_str(), sTitle.c_str(), MB_OK|MB_ICONINFORMATION|MB_APPLMODAL);

#if 0
    //제어기함체환경설정
    int nCommErrTime  = SeCommErrTime->Value;//   = 60;  //통신장애 기본값(Default=60초)
    int nSlotCommErr  = SeSlotCommErr->Value;//   = 0;   //FSelVmsObj->CMNCFAIL_SLOT_NMBR  = (int)pReq->SlotCommErr;     // NUMBER(4)    Y    0        통신장애 SLOT 번호
    int nSlotPowerErr = SeSlotPowerErr->Value;//  = 0;   //FSelVmsObj->PWER_FAIL_SLOT_NMBR = (int)pReq->SlotPowerErr;    // NUMBER(4)    Y    0        전원 장애 SLOT 번호
    int nLumNight     = SeLumNight->Value;//      = FSelVmsObj->VMS_NGHT_BRGH_STEP;
    int nLumDay       = SeLumDay->Value;//        = FSelVmsObj->VMS_WEEK_BRGH_STEP;
    int nModErrRate   = SeModRate->Value;//       = FSelVmsObj->VMS_MODL_ERR_RATE;
    int nModChkCycle  = SeModCycle->Value;//      = FSelVmsObj->VMS_MODL_CHK_CYCL;
    int nPhaseCycle   = SeMsgTime->Value;//      = FSelVmsObj->DEF_PHSE_CHNG_CYCL;

    String sTitle = cxLabel23->Caption;//"VMS 함체환경 설정";
    String sMsg   = "";

    int nOkCnt  = 0;
    int nSelCnt = GetSelListItems(true);
    if (0 == nSelCnt)
    {
        sMsg = cxLabel2->Caption + "\r\n" + cxLabel9->Caption;//"VMS가 선택되지 않았습니다.\r\nVMS 목록에서 VMS를 선택하십시요.\r\n현재 통신이 비정상인 VMS는 선택하실 수 없습니다.";
        Application->MessageBox(sMsg.c_str(), sTitle.c_str(), MB_OK|MB_ICONERROR|MB_APPLMODAL);
        CxList->SetFocus();
        return;
    }

    int nCmdIdx = 0;
    sMsg = cxLabel24->Caption + "\r\n" + cxLabel9->Caption;//"선택하신 VMS에 함체환경 설정 명령을 전송하시겠습니까?\r\n(통신상태에 따라 명령이 실행되지 않을 수 있습니다.)";
    if (Application->MessageBox(sMsg.c_str(), sTitle.c_str(), MB_YESNO|MB_ICONWARNING|MB_APPLMODAL) != IDYES) return;

    String sCmdUser = g_pLOGIN->sUserId;
    String sCmdTime = Now().FormatString("yyyymmddhhnnss");
    String sCmdValue;

    sCmdValue.printf(L"%d.%d,%d,%d,%d,%d,%d",
                        nLumNight,
                        nLumDay,
                        nModErrRate,
                        nModChkCycle,
                        nPhaseCycle,
                        nCommErrTime,
                        nSlotCommErr);
    int result;
    for (int ii = 0; ii < nSelCnt; ii++)
    {
        String sVmsNmbr = FVmsIds->Strings[ii];

        INT_VMS_PARA_SET_REQ2 VmsPara;
        BYTE MsgSeq;

        memset(&VmsPara, 0x00, sizeof(VmsPara));
        MsgSeq = (BYTE)0x40;

        memcpy(VmsPara.CmdTime, AnsiString(sCmdTime).c_str(), INT_VMS_MAX_DATETIME); /* 명령수행시각 */
        memcpy(VmsPara.VmsId,   AnsiString(sVmsNmbr).c_str(), INT_VMS_MAX_ID);       /* VMS 제어기 번호 */
        memcpy(VmsPara.OperId,  AnsiString(sCmdUser).c_str(), INT_VMS_MAX_OPER_ID);  /* 운영자 ID */

        VmsPara.DefCommErr      = (BYTE)nCommErrTime;                           // 통신장애 기본값, 제어기가 Host로부터 Poll 또는 명령을 받지 않고 경과할 수 있는 최대시간 (default ; 60초)
        VmsPara.SlotCommErr     = (short)nSlotCommErr;                          // 통신장애 slot번호, 통신 fail 시 표시할 메시지 번호(default 0번)
        VmsPara.SlotPowerErr    = (short)nSlotPowerErr;                         // 전원장애 slot번호, 전원장애 시 표시할 메시지 번호(default 0번)
        VmsPara.NightLuminance  = (BYTE)nLumNight;                       // 야간 휘도 값, 0x30 ~ 0x3F
        VmsPara.DayLuminance    = (BYTE)nLumDay;                         // 주간 휘도 값, 0x40 ~ 0x4F
        VmsPara.PhaseCycleTime  = (BYTE)nPhaseCycle;                       // phase시간주기, 장애시 phase주기 (default : 3초, 범위 : 0 ~ 10초)
        VmsPara.ModuleFailRate  = (BYTE)nModErrRate;                       // 모듈장애율, 한개의 module을 장애로 처리하기 위한 장애 pixel백분율 (default 10%)
        VmsPara.ModuleCheckTime = (BYTE)nModChkCycle;                      // 모듈감시 주기, 0 ~ 255 (단위:초)
        VmsPara.BoardOnHour     = (BYTE)cxDisplayTimeOn->Time.FormatString("HH").ToIntDef(0);                          // 전광판 On time(시), 0시 ~ 23시
        VmsPara.BoardOnMin      = (BYTE)cxDisplayTimeOn->Time.FormatString("NN").ToIntDef(0);                           // 전광판 On time(분), 0시 ~ 23시
        VmsPara.BoardOffHour    = (BYTE)cxDisplayTimeOff->Time.FormatString("HH").ToIntDef(0);                         // 전광판 Off time(시), 0시 ~ 23시
        VmsPara.BoardOffMin     = (BYTE)cxDisplayTimeOff->Time.FormatString("NN").ToIntDef(0);                          // 전광판 Off time(분), 0시 ~ 23시

        result = CComm_VmsParaSetReq2(&VmsPara, MsgSeq);
        if (VERR_NONE == result)
        {
            VmsCtlrManager->InsVmsControlHs(sCmdTime, sVmsNmbr, "V04", sCmdValue, "1", sCmdUser);
            nOkCnt++;

            //통신전송후 바이트오더링이 바뀐다
            VmsPara.SlotCommErr  = (short)nSlotCommErr;
            VmsPara.SlotPowerErr = (short)nSlotPowerErr;

            if (UpdateVmsParam2(sVmsNmbr, (void*)&VmsPara))
            {
                TVmsCtlr *pObj = VmsCtlrManager->FLists.Find(sVmsNmbr);
                if (pObj)
                {
#if 0
                    pObj->VMS_CMNC_ERR_BASS_VAL  = (int)VmsPara.DefCommErr;
                    pObj->CMNCFAIL_SLOT_NMBR     = (int)VmsPara.SlotCommErr;     // NUMBER(4)    Y    0        통신장애 SLOT 번호
                    pObj->PWER_FAIL_SLOT_NMBR    = (int)VmsPara.SlotPowerErr;    // NUMBER(4)    Y    0        전원 장애 SLOT 번호
                    pObj->VMS_NGHT_BRGH_STEP     = (int)VmsPara.NightLuminance;
                    pObj->VMS_WEEK_BRGH_STEP     = (int)VmsPara.DayLuminance;
                    pObj->DEF_PHSE_CHNG_CYCL     = (int)VmsPara.PhaseCycleTime;
                    pObj->VMS_MODL_ERR_RATE      = (int)VmsPara.ModuleFailRate;
                    pObj->VMS_MODL_CHK_CYCL      = (int)VmsPara.ModuleCheckTime;

                    pObj->PANL_ON_TIME.printf(L"%02d%02d", (int)VmsPara.BoardOnHour, (int)VmsPara.BoardOnMin);
                    pObj->PANL_OFF_TIME.printf(L"%02d%02d", (int)VmsPara.BoardOffHour, (int)VmsPara.BoardOffMin);

                    pObj->DEF_PHSE_CHNG_CYCL = nPhaseCycle;
                    pObj->STATE.ScheduledMessageOperatingTime = pObj->DEF_PHSE_CHNG_CYCL;    /* 필수 계획된 메시지의 동작시간(초) */
                    //pObj->STATE.ModuleOperatingTemperature    = pObj->VMS_CMNC_ERR_BASS_VAL; /* 필수 모듈 전원이 꺼지는 온도값(℃) */
                    pObj->STATE.ModuleBasicFailureRate        = pObj->VMS_MODL_ERR_RATE;     /* 선택 모듈 장애율 (한 개의 모듈을 장애로 처리하기 위한 픽셀의 백분율값) */
#endif
                }
            }
        }
        else
        {
            VmsCtlrManager->InsVmsControlHs(sCmdTime, sVmsNmbr, "V04", sCmdValue, "0", sCmdUser);
        }
        Sleep(100);
        Application->ProcessMessages();
    }

    //sMsg = String(nSelCnt) + " 개의 선택 VMS 중에 " + String(nOkCnt) + " 개의 VMS 함체환경 설정 명령을 요청하였습니다.";
    sMsg = String(nSelCnt) + " " + cxLabel7->Caption + " " + String(nOkCnt) + " " + cxLabel25->Caption;
    Application->MessageBox(sMsg.c_str(), sTitle.c_str(), MB_OK|MB_ICONINFORMATION|MB_APPLMODAL);
#endif
#endif
}
//---------------------------------------------------------------------------
bool __fastcall TFrmVmsControl::UpdateVmsParam2(String AVmsNmbr, void *pData)
{
#if 0
    String     sQry;
    TADOQuery *pADO = NULL;
    int        nCnt = 0;

    INT_VMS_PARA_SET_REQ2 *pReq = (INT_VMS_PARA_SET_REQ2*)pData;

    sQry = "UPDATE TB_VMS_CTLR                   \r\n"
           "   SET VMS_CMNC_ERR_BASS_VAL = :p02, \r\n"
           "       CMNCFAIL_SLOT_NMBR    = :p03, \r\n"
           "       PWER_FAIL_SLOT_NMBR   = :p04, \r\n"
           "       VMS_NGHT_BRGH_STEP    = :p05, \r\n"
           "       VMS_WEEK_BRGH_STEP    = :p06, \r\n"
           "       VMS_MODL_ERR_RATE     = :p07, \r\n"
           "       VMS_MODL_CHK_CYCL     = :p08, \r\n"
           "       DEF_PHSE_CHNG_CYCL    = :p09, \r\n"
           "       PANL_ON_TIME          = :p10, \r\n"
           "       PANL_OFF_TIME         = :p11  \r\n"
           " WHERE VMS_CTLR_NMBR = :p01          \r\n";

    try
    {
        try
        {
            pADO = new TADOQuery(NULL);
			pADO->Close();
            pADO->Connection = ITSDb_GetConnection();
			pADO->SQL->Clear();
			pADO->SQL->Text = sQry;

            String sOn, sOff;
            sOn.printf(L"%02d%02d", (int)pReq->BoardOnHour, (int)pReq->BoardOnMin);
            sOff.printf(L"%02d%02d", (int)pReq->BoardOffHour, (int)pReq->BoardOffMin);

            pADO->Parameters->ParamByName("p01")->Value = AVmsNmbr;
            pADO->Parameters->ParamByName("p02")->Value = (int)pReq->DefCommErr;
            pADO->Parameters->ParamByName("p03")->Value = (int)pReq->SlotCommErr;
            pADO->Parameters->ParamByName("p04")->Value = (int)pReq->SlotPowerErr;
            pADO->Parameters->ParamByName("p05")->Value = (int)pReq->NightLuminance;
            pADO->Parameters->ParamByName("p06")->Value = (int)pReq->DayLuminance;
            pADO->Parameters->ParamByName("p07")->Value = (int)pReq->ModuleFailRate;
            pADO->Parameters->ParamByName("p08")->Value = (int)pReq->ModuleCheckTime;
            pADO->Parameters->ParamByName("p09")->Value = (int)pReq->PhaseCycleTime;
            pADO->Parameters->ParamByName("p10")->Value = sOn;
            pADO->Parameters->ParamByName("p11")->Value = sOff;
			nCnt = pADO->ExecSQL();
        }
        catch(EDatabaseError &E)
        {
            DBERRORLOG("VMS Parameter Save", String(E.ClassName()), E.Message, sQry);
            throw Exception(String(E.ClassName()) + E.Message);
        }
        catch(Exception &e)
        {
            DBERRORLOG("VMS Parameter Save", String(e.ClassName()), e.Message, sQry);
            throw Exception(String(e.ClassName()) + e.Message);
        }
    }
    __finally
    {
        if (pADO)
        {
            pADO->Close();
            delete pADO;
        }
    }

    return nCnt > 0 ? true : false;
#endif
return false;
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsControl::BtnDefMsgDownloadClick(TObject *Sender)
{
//
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsControl::BtnDisplayTimeSetClick(TObject *Sender)
{
#if 0
    //폼 표출주기 설정
    String sTitle = cxLabel26->Caption;//"폼 표출주기 설정";
    String sMsg   = "";

    int nOkCnt  = 0;
    int nSelCnt = GetSelListItems(false);
    if (0 == nSelCnt)
    {
        sMsg = cxLabel14->Caption;//"VMS가 선택되지 않았습니다.\r\nVMS 목록에서 VMS를 선택하십시요.";
        Application->MessageBox(sMsg.c_str(), sTitle.c_str(), MB_OK|MB_ICONERROR|MB_APPLMODAL);
        CxList->SetFocus();
        return;
    }

    int nCmdIdx = 0;
    sMsg = cxLabel27->Caption;//"선택하신 VMS의 폼 표출 주기를 설정 하시겠습니까?";
    if (Application->MessageBox(sMsg.c_str(), sTitle.c_str(), MB_YESNO|MB_ICONWARNING|MB_APPLMODAL) != IDYES) return;

    String     sQry;
    TADOQuery *pADO = NULL;

    sQry = "UPDATE TB_VMS_CTLR                \r\n"
           "   SET VMS_PHSE_CHNG_CYCL = :p02  \r\n"
           " WHERE VMS_CTLR_NMBR = :p01       \r\n";


    String LAST_CRPR_NMBR = g_AppCfg.sUserId;
    String LAST_CRCT_DT	  = Now().FormatString("yyyymmddhhnnss");

    int VMS_PHSE_CHNG_CYCL   = SeFormCycleTime->Value;

    try
    {
        try
        {
            pADO = new TADOQuery(NULL);
			pADO->Close();
            pADO->Connection = ITSDb_GetConnection();
			pADO->SQL->Clear();
			pADO->SQL->Text = sQry;

            for (int ii = 0; ii < nSelCnt; ii++)
            {
                String sVmsNmbr = FVmsIds->Strings[ii];

                pADO->Parameters->ParamByName("p01")->Value = sVmsNmbr;
                pADO->Parameters->ParamByName("p02")->Value = VMS_PHSE_CHNG_CYCL;
                pADO->ExecSQL();
                nOkCnt++;

                TVmsCtlr *pObj = VmsCtlrManager->FLists.Find(sVmsNmbr);
                if (pObj)
                {
                    //pObj->VMS_PHSE_CHNG_CYCL = VMS_PHSE_CHNG_CYCL;
                }
            }
        }
        catch(EDatabaseError &E)
        {
            DBERRORLOG("VMS Config Save", String(E.ClassName()), E.Message, sQry);
            throw Exception(String(E.ClassName()) + E.Message);
        }
        catch(Exception &e)
        {
            DBERRORLOG("VMS Config Save", String(e.ClassName()), e.Message, sQry);
            throw Exception(String(e.ClassName()) + e.Message);
        }
    }
    __finally
    {
        if (pADO)
        {
            pADO->Close();
            delete pADO;
        }
    }

    //sMsg = String(nSelCnt) + " 개의 선택 VMS 중에 " + String(nOkCnt) + " 개의 VMS의 폼 표출주기를 설정하였습니다.";
    sMsg = String(nSelCnt) + " " + cxLabel7->Caption + " " + String(nOkCnt) + " " + cxLabel28->Caption;
    Application->MessageBox(sMsg.c_str(), sTitle.c_str(), MB_OK|MB_ICONINFORMATION|MB_APPLMODAL);

    for (int ii = 0; ii < nSelCnt; ii++)
    {
        String sVmsNmbr = FVmsIds->Strings[ii];

        VmsCtlrManager->InsVmsControlHs(LAST_CRCT_DT, sVmsNmbr, "V09", String(VMS_PHSE_CHNG_CYCL), "1", LAST_CRPR_NMBR);
    }
    //RefreshStatus();
    //FrmVmsOprMain->RefreshVmsMessage(WM_VMS_STATE_REFRESH);
#endif
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsControl::BtnMsgImmediateDownloadClick(TObject *Sender)
{
#if 0
    //폼 표출주기 설정
    String sTitle = cxLabel30->Caption;//"폼 즉시 다운로드";
    String sMsg   = "";

    sMsg = cxLabel31->Caption;//"폼 메시지를 지금 즉시 제어기로 다운로드 하시겠습니까?";
    if (Application->MessageBox(sMsg.c_str(), sTitle.c_str(), MB_YESNO|MB_ICONWARNING|MB_APPLMODAL) != IDYES) return;

    String sCmdUser = g_AppCfg.sUserId;
    String sCmdTime = Now().FormatString("yyyymmddhhnnss");

#if 0
    INT_VMS_STATE_REQ Req;
    memset((char*)&Req, 0x00, sizeof(Req));
    Req.Count = 0;
    Req.Type  = vms_req_state_all;
    CComm_VmsStateReq(&Req);
#endif

    BYTE MsgSeq;
    INT_VMS_COMMON_REQ directCmd;
    memset(&directCmd, 0x00, sizeof(directCmd));
    MsgSeq = (BYTE)0x80;

    memcpy(directCmd.CmdTime, AnsiString(sCmdTime).c_str(), INT_VMS_MAX_DATETIME); /* 명령수행시각 */
    memcpy(directCmd.VmsId,   AnsiString("10001").c_str(), INT_VMS_MAX_ID);        /* VMS 제어기 번호 */
    memcpy(directCmd.OperId,  AnsiString(sCmdUser).c_str(), INT_VMS_MAX_OPER_ID);  /* 운영자 ID */

    directCmd.Command = 0x01;

    int result = CComm_VmsCommonReq(&directCmd, MsgSeq);
    if (VERR_NONE == result)
    {
        //VmsCtlrManager->InsVmsControlHs(sCmdTime, sVmsNmbr, "V10", "Download", "1", sCmdUser);
    }
    else
    {
        //VmsCtlrManager->InsVmsControlHs(sCmdTime, sVmsNmbr, "V10", "Download", "0", sCmdUser);
    }
    Sleep(100);
    Application->ProcessMessages();

    sMsg = cxLabel32->Caption;//"VMS 폼 메시지 즉시 전송을 요청하였습니다.";
    Application->MessageBox(sMsg.c_str(), sTitle.c_str(), MB_OK|MB_ICONINFORMATION|MB_APPLMODAL);

    FOR_STL(TVmsCtlr*, pObj, VmsCtlrManager->FLists)
    {
        String sVmsNmbr = (pObj->VMS_CTLR_NMBR);

        //TODO VmsCtlrManager->InsVmsControlHs(sCmdTime, sVmsNmbr, "V10", "Immediately Download", "1", sCmdUser);
    }

    BtnMsgImmediateDownload->Enabled = false;
    TmrCommand->Enabled = true;
#endif
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsControl::TmrCommandTimer(TObject *Sender)
{
    TmrCommand->Enabled = false;
    BtnImdFromDnld->Enabled = true;
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsControl::PgControlPageChanging(TObject *Sender, TcxTabSheet *NewPage,
          bool &AllowChange)
{
    if (NewPage == TabPing)
    {
        BtnAllSelect->Visible = false;
        BtnAllClear->Visible = false;
        BtnReverse->Visible = false;
    }
    else
    {
        if (BtnAllSelect->Visible == false) BtnAllSelect->Visible = true;;
        if (BtnAllClear->Visible  == false) BtnAllClear->Visible = true;;
        if (BtnReverse->Visible   == false) BtnReverse->Visible = true;;
    }
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsControl::UpdatePingList()
{
    CMM_ClearGridTableView(TvPing);

    int ii, jj;
    int nCols = 0;

    TcxDataController *pGDC = TvPing->DataController;

    TvPing->BeginUpdate();
    pGDC->BeginUpdate();

    VmsCtlrManager->FLists.Lock();
    try
    {
        int nRow;
        FOR_STL(TVmsCtlr*, pObj, VmsCtlrManager->FLists)
        {
            if (pObj->DEL_YN == "Y") continue;

            nRow = pGDC->AppendRecord();

            if (pObj->STTS->CMNC_STTS_CD == "CMS0") pGDC->Values[nRow][PColumnSel->Index] = false;
            else                                    pGDC->Values[nRow][PColumnSel->Index] = true;

            pGDC->Values[nRow][PCol01->Index] = (pObj->VMS_CTLR_NMBR);
            pGDC->Values[nRow][PCol02->Index] = pObj->VMS_CTLR_ID;
            pGDC->Values[nRow][PCol03->Index] = pObj->VMS_NM;

            pGDC->Values[nRow][PCol04->Index] = pObj->STTS->CMNC_STTS_DESC;               //통신상태

            pGDC->Values[nRow][PCol05->Index] = pObj->VMS_CTLR_IP;
            pGDC->Values[nRow][PCol06->Index] = "-";
            pGDC->Values[nRow][PCol07->Index] = "-";
            pGDC->Values[nRow][PCol08->Index] = "-";

            pGDC->Values[nRow][PCol09->Index] = pObj->WEB_CMRA_IP;
            pGDC->Values[nRow][PCol10->Index] = "-";
            pGDC->Values[nRow][PCol11->Index] = "-";
            pGDC->Values[nRow][PCol12->Index] = "-";

            pGDC->Values[nRow][PCol99->Index] = (int)pObj;
        }
    }
    __finally
    {
        VmsCtlrManager->FLists.UnLock();

        pGDC->EndUpdate();
        TvPing->EndUpdate();
    }
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsControl::RefreshPingList(bool AInit/*=false*/)
{
    TcxDataController *pGDC = TvPing->DataController;
    try
    {
        TvPing->BeginUpdate();
        pGDC->BeginUpdate();

        int nRows = pGDC->RecordCount;
        for(int nRow = 0; nRow < nRows; nRow++)
        {
            int nMemPtr = TvPing->DataController->Values[nRow][PCol99->Index];
            TVmsCtlr *pObj = (TVmsCtlr*)nMemPtr;
            if (!pObj) continue;

            if (AInit == false && PgControl->Properties->ActivePage != TabPing)
            {
                if (pObj->STTS->CMNC_STTS_CD == "CMS0") pGDC->Values[nRow][PColumnSel->Index] = false;
                else                                    pGDC->Values[nRow][PColumnSel->Index] = true;
            }

            if (AInit)
            {
                pGDC->Values[nRow][PCol06->Index] = "-";
                pGDC->Values[nRow][PCol07->Index] = "-";
                pGDC->Values[nRow][PCol08->Index] = "-";

                pGDC->Values[nRow][PCol10->Index] = "-";
                pGDC->Values[nRow][PCol11->Index] = "-";
                pGDC->Values[nRow][PCol12->Index] = "-";
            }

            pGDC->Values[nRow][PCol04->Index] = pObj->STTS->CMNC_STTS_DESC;               //통신상태
        }
    }
    __finally
    {
        pGDC->EndUpdate();
        TvPing->EndUpdate();
    }
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsControl::PingNetwork(String AIp, int APort)
{
    try
    {
        IdIcmpClient1->Host = AIp;
        IdIcmpClient1->Port = EdPingPort->Value/*512*/;
        IdIcmpClient1->ReceiveTimeout = EdPingTimeout->Value;
        IdIcmpClient1->Ping(IdIcmpClient1->Host, IdIcmpClient1->Port);
    }
	catch (Exception &e)
	{
		Application->ShowException(&e);
	}
    catch(...)
    {
        ShowMessage("Ping error[Unknown]");
    }
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsControl::BtnNwkPingClick(TObject *Sender)
{
    TWaitCursor waitCrs;
	TcxDataController *pGDC = TvPing->DataController;
	int nRows  = pGDC->RecordCount;

    String sMsg;
    int nSelCnt = CMM_GetCheckCount(TvPing, PColumnSel->Index);
    if (0 == nSelCnt)
    {
        sMsg = cxLabel14->Caption;//"VMS가 선택되지 않았습니다.\r\nVMS 목록에서 VMS를 선택하십시요.";
        Application->MessageBox(sMsg.c_str(), L"VMS Network Ping Test", MB_OK|MB_ICONERROR|MB_APPLMODAL);
        CxPing->SetFocus();
        return;
    }

    RefreshPingList(true);

    PnlPing->Enabled = false;

    String sSvrIp;
    int    nSvrPort;
    bool   bPing;

    for (int ii = 0; ii < nRows; ii++)
    {
        bPing = pGDC->Values[ii][PColumnSel->Index];
        if (!bPing) continue;

        //pGDC->Values[ii][PColPingMon->Index] = Now().FormatString("yyyy-mm-dd hh:mm:ss");

        FPingType = 1;

        sSvrIp = pGDC->Values[ii][PCol05->Index];
        if (sSvrIp == NULL || sSvrIp.IsEmpty())
        {
            continue;
        }
        pGDC->Values[ii][PCol06->Index] = "?";
        pGDC->Values[ii][PCol07->Index] = "?";
        pGDC->Values[ii][PCol08->Index] = "?";

        nSvrPort = 0;

        FPingTimeout = false;
        PingNetwork(sSvrIp.Trim(), nSvrPort);
        if (FPingTimeout)
        {
            pGDC->Values[ii][PCol08->Index] = "Time out";
        }

        Application->ProcessMessages();

        FPingType = 2;

        sSvrIp = pGDC->Values[ii][PCol09->Index];
        if (sSvrIp == NULL || sSvrIp.IsEmpty())
        {
            continue;
        }
        pGDC->Values[ii][PCol10->Index] = "?";
        pGDC->Values[ii][PCol11->Index] = "?";
        pGDC->Values[ii][PCol12->Index] = "?";

        nSvrPort = 0;

        FPingTimeout = false;
        PingNetwork(sSvrIp.Trim(), nSvrPort);
        if (FPingTimeout)
        {
            pGDC->Values[ii][PCol12->Index] = "Time out";
        }

        Application->ProcessMessages();
    }
    PnlPing->Enabled = true;
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsControl::BtnNwkPingClearClick(TObject *Sender)
{
    RefreshPingList(true);
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsControl::PCol04CustomDrawCell(TcxCustomGridTableView *Sender, TcxCanvas *ACanvas,
          TcxGridTableDataCellViewInfo *AViewInfo, bool &ADone)
{
    try
    {
        TColor tColor;
        String sStatus = AViewInfo->GridRecord->DisplayTexts[AViewInfo->Item->Index];
        tColor = ACanvas->Brush->Color;

        if      (sStatus.Pos("-"))    tColor = clGray;
        if      (sStatus.Pos("?"))    tColor = clGray;
        else if (sStatus.Pos("장애")) tColor = clRed;
        else if (sStatus.Pos("켜짐")) tColor = clYellow;
        else if (sStatus.Pos("열림")) tColor = clRed;
        else if (sStatus.Pos("동작")) tColor = clYellow;
        else if (sStatus.Pos("가동")) tColor = clYellow;
        else                          tColor = clLime;

        ACanvas->SetBrushColor(tColor);
        ACanvas->Font->Color  = clBlack;
        /*if (AViewInfo->GridRecord->Selected)
        {
            ACanvas->Font->Color  = clBlack;
        }*/
    }
    catch(Exception &e)
    {
    }
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsControl::IdIcmpClient1Reply(TComponent *ASender, const TReplyStatus *AReplyStatus)
{
    try
	{
        String sRcvIp = AReplyStatus->FromIpAddress;
        int    nRcvPort= IdIcmpClient1->Port;
        if (rsTimeOut == AReplyStatus->ReplyStatusType || sRcvIp == "0.0.0.0")
        {
            FPingTimeout = true;
            return;
        }

        TcxDataController *pGDC = TvPing->DataController;
        int nRows  = pGDC->RecordCount;

        String sSvrIp;
		for (int ii = 0; ii < nRows; ii++)
        {
			if (FPingType == 1)
                sSvrIp = pGDC->Values[ii][PCol05->Index];
            else
                sSvrIp = pGDC->Values[ii][PCol09->Index];

			int nSvrPort = 0;

            if (sSvrIp.Trim() == sRcvIp && nRcvPort == nSvrPort)
            {
                if (FPingType == 1)
                {
                    if (AReplyStatus->MsRoundTripTime > 100)
                    {
                        pGDC->Values[ii][PCol08->Index] = "Delayed";
                    }
                    else
                    {
                        pGDC->Values[ii][PCol08->Index] = "Normal";
                    }

                    pGDC->Values[ii][PCol06->Index] = String(AReplyStatus->MsRoundTripTime) + " ";
                    pGDC->Values[ii][PCol07->Index] = String(AReplyStatus->TimeToLive) + " ";
                }
                else
                {
                    if (AReplyStatus->MsRoundTripTime > 100)
                    {
                        pGDC->Values[ii][PCol12->Index] = "Delayed";
                    }
                    else
                    {
                        pGDC->Values[ii][PCol12->Index] = "Normal";
                    }

                    pGDC->Values[ii][PCol10->Index] = String(AReplyStatus->MsRoundTripTime) + " ";
                    pGDC->Values[ii][PCol11->Index] = String(AReplyStatus->TimeToLive) + " ";
                }

                break;
            }

        }
	}
	catch(Exception &e)
    {
	}
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsControl::PCol08CustomDrawCell(TcxCustomGridTableView *Sender, TcxCanvas *ACanvas,
          TcxGridTableDataCellViewInfo *AViewInfo, bool &ADone)
{
    try
    {
        int iIndex = AViewInfo->Item->Index;

        ACanvas->Canvas->Brush->Style = bsSolid;
        String val  = AViewInfo->GridRecord->DisplayTexts[iIndex];

        ACanvas->Canvas->Font->Color = clBlack;
        if (val == "Normal")        ACanvas->Canvas->Brush->Color = clLime;
        else if (val == "Delayed")  ACanvas->Canvas->Brush->Color = clRed;
        else if (val == "Time out") ACanvas->Canvas->Brush->Color = clRed;
        else                        ACanvas->Canvas->Brush->Color = clSilver;

    } catch(...) {}
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsControl::TvPingCellDblClick(TcxCustomGridTableView *Sender, TcxGridTableDataCellViewInfo *ACellViewInfo,
          TMouseButton AButton, TShiftState AShift,
          bool &AHandled)
{
	if (!ACellViewInfo) return;

	TcxGridDataController *pGDC = TvPing->DataController;
	int nRow = pGDC->FocusedRecordIndex;
	if( nRow <= -1 )
		return;

    if (ACellViewInfo->Item->Index == PCol05->Index ||
        ACellViewInfo->Item->Index == PCol09->Index)
	{
        String sSvrIp = pGDC->Values[nRow][ACellViewInfo->Item->Index];
        ITSUtil_NetworkPing(sSvrIp);
    }
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsControl::ErrorMsg(String AErrMsg)
{
    LblErrMsg->Caption = AErrMsg;
    LblErrMsg->BringToFront();
    LblErrMsg->Transparent = true;
    LblErrMsg->Style->Font->Color = clWhite;
    LblErrMsg->Style->TextColor = clWhite;
    LblErrMsg->Visible = true;
    LblErrMsg->Refresh();
    LblErrMsg->BringToFront();
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsControl::WebCamPlay(String AVmsNo)
{
    if (LblErrMsg->Visible) LblErrMsg->Visible = false;
    reMsg->Lines->Clear();
    reMsg->Lines->Add("Connect...");

    WebCamStop();

    TVmsCtlr *pObj = VmsCtlrManager->FLists.Find(AVmsNo);
    if (!pObj) return;

    PnlSamsung->Caption = "Connecting...";
    PnlSamsung->Refresh();
    try
    {
        //FStrmAddr = pObj->STRM_SESN_NM.Trim();
        FStrmAddr = pObj->STRM_RTSP_ADDR.Trim();
        if (FStrmAddr != "")
        {
            FFPlayer1->AspectRatio = ChkFullScreen->Checked ? -1 : 0;
            FFPlayer1->TryOpen(FStrmAddr, PnlSamsung->Handle);

            FStrmUser = pObj->WEB_CMRA_ID;
            FStrmPswd = pObj->WEB_CMRA_PWD;
            FStrmHttp = "http://" + pObj->WEB_CMRA_IP;
            if (pObj->WEB_CMRA_PORT.ToIntDef(0) != 0)
            {
                FStrmHttp = FStrmHttp + ":" + pObj->WEB_CMRA_PORT;
            }

            FStrmPlay = true;
        }
    }
    catch(Exception &e)
    {
    }
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsControl::WebCamStop()
{
    if (!FStrmPlay) return;

    try
    {
        if (FFPlayer1->ScreenHandle != NULL)
        {
            FFPlayer1->Stop(true);
            PostMessage(FFPlayer1->ScreenHandle, CM_INVALIDATE, 0, 0);
            UpdateWindow(FFPlayer1->ScreenHandle);
            //FFPlayer1->ScreenHandle = NULL;
        }
    }
    catch(Exception &e)
    {
    }
    PnlSamsung->Caption = "Disconnected";
    PnlSamsung->Refresh();
    FStrmPlay = false;
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsControl::BtnImdFromDnldClick(TObject *Sender)
{
    //폼 즉시 다운로드
    String sTitle = cxLabel30->Caption;//"폼 즉시 다운로드";
    String sMsg   = "";

    int nOkCnt  = 0;
    int nSelCnt = GetSelListItems(false);
    if (0 == nSelCnt)
    {
        sMsg = cxLabel2->Caption + "\r\n" + cxLabel9->Caption;//"VMS가 선택되지 않았습니다.\r\nVMS 목록에서 VMS를 선택하십시요.\r\n현재 통신이 비정상인 VMS는 선택하실 수 없습니다.";
        Application->MessageBox(sMsg.c_str(), sTitle.c_str(), MB_OK|MB_ICONERROR|MB_APPLMODAL);
        CxList->SetFocus();
        return;
    }

    sMsg = cxLabel31->Caption;//"폼 메시지를 지금 즉시 제어기로 다운로드 하시겠습니까?";
    if (Application->MessageBox(sMsg.c_str(), sTitle.c_str(), MB_YESNO|MB_ICONWARNING|MB_APPLMODAL) != IDYES) return;

    String sCmdUser = g_AppCfg.sUserId;
    for (int ii = 0; ii < nSelCnt; ii++)
    {
        String sVmsNmbr = FVmsIds->Strings[ii];
        bool result = VmsCtlrManager->ImmediatelyScnrDnld(sCmdUser, sVmsNmbr);
        if (result) {
            nOkCnt++;
        }

        Sleep(100);
        Application->ProcessMessages();
    }

    //sMsg = String(nSelCnt) + " 개의 선택 VMS 중에 " + String(nOkCnt) + " 개의 VMS 폼 메시지 즉시 전송을 요청하였습니다.";
    sMsg = String(nSelCnt) + " " + cxLabel7->Caption + " " + String(nOkCnt) + " " + cxLabel19->Caption;//;
    Application->MessageBox(sMsg.c_str(), sTitle.c_str(), MB_OK|MB_ICONINFORMATION|MB_APPLMODAL);
    BtnImdFromDnld->Enabled = false;
    TmrCommand->Enabled = true;
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsControl::BtnModuleControlClick(TObject *Sender)
{
    TcxButton *pBtnControl = (TcxButton*)Sender;

    String sTitle = cxLabel1->Caption;//"전광판/제어기 제어";
    String sMsg   = "";

    int nOkCnt  = 0;
    int nSelCnt = GetSelListItems(false);
    if (0 == nSelCnt)
    {
        sMsg = cxLabel2->Caption + "\r\n" + cxLabel9->Caption;//"VMS가 선택되지 않았습니다.\r\nVMS 목록에서 VMS를 선택하십시요.\r\n현재 통신이 비정상인 VMS는 선택하실 수 없습니다.";
        Application->MessageBox(sMsg.c_str(), sTitle.c_str(), MB_OK|MB_ICONERROR|MB_APPLMODAL);
        CxList->SetFocus();
        return;
    }

    int nCmdIdx;
    if (pBtnControl->Tag == 1)
    {
        nCmdIdx = 1;
        sMsg = cxLabel3->Caption + "\r\n" + cxLabel9->Caption;//"선택하신 VMS에 VMS 전광판 전원 ON 명령을 전송하시겠습니까?\r\n(통신상태에 따라 명령이 실행되지 않을 수 있습니다.)";
    }
    else
    {
        nCmdIdx = 0;
        sMsg = cxLabel4->Caption + "\r\n" + cxLabel9->Caption;//"선택하신 VMS에 VMS 전광판 전원 OFF 명령을 전송하시겠습니까?\r\n(통신상태에 따라 명령이 실행되지 않을 수 있습니다.)";
    }

    if (Application->MessageBox(sMsg.c_str(), sTitle.c_str(), MB_YESNO|MB_ICONWARNING|MB_APPLMODAL) != IDYES) return;

    String sCmdUser = g_AppCfg.sUserId;
    for (int ii = 0; ii < nSelCnt; ii++)
    {
        String sVmsNmbr = FVmsIds->Strings[ii];

        if (nCmdIdx == 1 || nCmdIdx == 0)
        {
            // 전광판 On(=0)/Off(=1)
            bool result = VmsCtlrManager->PowerOnOff(sCmdUser, sVmsNmbr, nCmdIdx);
            if (result)
            {
                nOkCnt++;
            }
        }

        Sleep(100);
        Application->ProcessMessages();
    }

    sMsg = String(nSelCnt) + " " + cxLabel7->Caption + " " + String(nOkCnt) + " " + cxLabel8->Caption;
    Application->MessageBox(sMsg.c_str(), sTitle.c_str(), MB_OK|MB_ICONINFORMATION|MB_APPLMODAL);
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsControl::BtnResetClick(TObject *Sender)
{
    TcxButton *pBtnControl = (TcxButton*)Sender;

    String sTitle = cxLabel1->Caption;//"전광판/제어기 제어";
    String sMsg   = "";

    int nOkCnt  = 0;
    int nSelCnt = GetSelListItems(false);
    if (0 == nSelCnt)
    {
        sMsg = cxLabel2->Caption + "\r\n" + cxLabel9->Caption;//"VMS가 선택되지 않았습니다.\r\nVMS 목록에서 VMS를 선택하십시요.\r\n현재 통신이 비정상인 VMS는 선택하실 수 없습니다.";
        Application->MessageBox(sMsg.c_str(), sTitle.c_str(), MB_OK|MB_ICONERROR|MB_APPLMODAL);
        CxList->SetFocus();
        return;
    }

    int nCmdIdx;
    {
        nCmdIdx = 2;
        sMsg = cxLabel5->Caption + "\r\n" + cxLabel9->Caption;//"선택하신 VMS에 VMS 제어기 리셋 명령을 전송하시겠습니까?\r\n(통신상태에 따라 명령이 실행되지 않을 수 있습니다.)";
    }

    if (Application->MessageBox(sMsg.c_str(), sTitle.c_str(), MB_YESNO|MB_ICONWARNING|MB_APPLMODAL) != IDYES) return;

    String sCmdUser = g_AppCfg.sUserId;
    for (int ii = 0; ii < nSelCnt; ii++)
    {
        String sVmsNmbr = FVmsIds->Strings[ii];

        if (nCmdIdx == 2)
        {
            // 제어기 리셋
            bool result = VmsCtlrManager->Reset(sCmdUser, sVmsNmbr, pBtnControl->Tag);
            if (result)
            {
                nOkCnt++;
            }
        }

        Sleep(100);
        Application->ProcessMessages();
    }

    sMsg = String(nSelCnt) + " " + cxLabel7->Caption + " " + String(nOkCnt) + " " + cxLabel8->Caption;
    Application->MessageBox(sMsg.c_str(), sTitle.c_str(), MB_OK|MB_ICONINFORMATION|MB_APPLMODAL);
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsControl::BtnBrghControlClick(TObject *Sender)
{
    TcxButton *pBtnControl = (TcxButton*)Sender;

    String sTitle = cxLabel1->Caption;//"전광판/제어기 제어";
    String sMsg   = "";

    int nOkCnt  = 0;
    int nSelCnt = GetSelListItems(false);
    if (0 == nSelCnt)
    {
        sMsg = cxLabel2->Caption + "\r\n" + cxLabel9->Caption;//"VMS가 선택되지 않았습니다.\r\nVMS 목록에서 VMS를 선택하십시요.\r\n현재 통신이 비정상인 VMS는 선택하실 수 없습니다.";
        Application->MessageBox(sMsg.c_str(), sTitle.c_str(), MB_OK|MB_ICONERROR|MB_APPLMODAL);
        CxList->SetFocus();
        return;
    }

    int nCmdIdx;
    {
        nCmdIdx = 3;
        sMsg = cxLabel6->Caption + "\r\n" + cxLabel9->Caption;//"선택하신 VMS에 VMS 휘도값 제어 명령을 전송하시겠습니까?\r\n(통신상태에 따라 명령이 실행되지 않을 수 있습니다.)";
    }

    if (Application->MessageBox(sMsg.c_str(), sTitle.c_str(), MB_YESNO|MB_ICONWARNING|MB_APPLMODAL) != IDYES) return;

    String sCmdUser = g_AppCfg.sUserId;
    for (int ii = 0; ii < nSelCnt; ii++)
    {
        String sVmsNmbr = FVmsIds->Strings[ii];
        if (nCmdIdx == 3)
        {
            // 휘도제어
            bool result = VmsCtlrManager->LuminanceSet(sCmdUser, sVmsNmbr, pBtnControl->Tag, SeCurrBrgh->Value, SeWeekBrgh->Value, SeNghtBrgh->Value);
            if (result)
            {
                nOkCnt++;
            }
        }

        Sleep(100);
        Application->ProcessMessages();
    }

    sMsg = String(nSelCnt) + " " + cxLabel7->Caption + " " + String(nOkCnt) + " " + cxLabel8->Caption;
    Application->MessageBox(sMsg.c_str(), sTitle.c_str(), MB_OK|MB_ICONINFORMATION|MB_APPLMODAL);
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsControl::FFPlayer1State(TObject *Sender, TPlayState APlayState)
{
    switch(APlayState)
    {
    case Ffbasecomponent::psPlay:   reMsg->Lines->Add("Play..."); break;
    case Ffbasecomponent::psResume: reMsg->Lines->Add("Resume."); break;
    case Ffbasecomponent::psPause:  reMsg->Lines->Add("Pause.."); break;
    case Ffbasecomponent::psStep:   reMsg->Lines->Add("Step..."); break;
    case Ffbasecomponent::psStop:
        if (FFPlayer1->ScreenHandle != NULL)
        {
            PostMessage(FFPlayer1->ScreenHandle, CM_INVALIDATE, 0, 0);
            UpdateWindow(FFPlayer1->ScreenHandle);
            //FFPlayer1->ScreenHandle = NULL;
        }
        reMsg->Lines->Add("Stop...");
        break;
    case Ffbasecomponent::psEnd:
        {
            FFPlayer1->Stop(true);
            PostMessage(FFPlayer1->ScreenHandle, CM_INVALIDATE, 0, 0);
            UpdateWindow(FFPlayer1->ScreenHandle);
            //FFPlayer1->ScreenHandle = NULL;
        }
        reMsg->Lines->Add("End...");
        break;
    }
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsControl::FFPlayer1OpenFailed(TObject *Sender)
{
    //ErrorMsg("웹카메라에 연결할 수 없습니다.");
    //WebCamStop();
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsControl::ChkFullScreenClick(TObject *Sender)
{
    FFPlayer1->AspectRatio = ChkFullScreen->Checked ? -1 : 0;
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsControl::IdHTTP1Authorization(TObject *Sender, TIdAuthentication *Authentication, bool &Handled)
{
#if 1
    IdHTTP1->Request->Username = FStrmUser;
    IdHTTP1->Request->Password = FStrmPswd;
#endif

    Authentication->Username = FStrmUser;
    Authentication->Password = FStrmPswd;

    TIdDigestAuthentication *pAuth1 = (TIdDigestAuthentication*)IdHTTP1->Request->Authentication;
    TIdDigestAuthentication *pAuth2 = (TIdDigestAuthentication*)Authentication;
    pAuth1->Uri = IdHTTP1->Request->URL;
    pAuth2->Method = "GET";

    Handled = true;
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsControl::BtnWebCamControlMouseDown(TObject *Sender, TMouseButton Button,
          TShiftState Shift, int X, int Y)
{
    // PANControl
    if (!FStrmPlay) return;

    try
    {
        String sCmdHtml;
        TImageBtn *pBtn = (TImageBtn*)Sender;
        switch(pBtn->Tag)
        {
        case  1: sCmdHtml.printf(L"%s/stw-cgi/ptzcontrol.cgi?msubmenu=continuous&action=control&Tilt=5&Duration=1",  FStrmHttp.c_str()); break;  // Tilt Up
        case  2: sCmdHtml.printf(L"%s/stw-cgi/ptzcontrol.cgi?msubmenu=continuous&action=control&Tilt=-5&Duration=1", FStrmHttp.c_str()); break;  // Tilt Down
        case  3: sCmdHtml.printf(L"%s/stw-cgi/ptzcontrol.cgi?msubmenu=continuous&action=control&Pan=5",              FStrmHttp.c_str()); break;  // Pan left
        case  4: sCmdHtml.printf(L"%s/stw-cgi/ptzcontrol.cgi?msubmenu=continuous&action=control&Pan=-5",             FStrmHttp.c_str()); break;  // Pan right
        case  9: sCmdHtml.printf(L"%s/stw-cgi/ptzcontrol.cgi?msubmenu=continuous&action=control&Zoom=3",             FStrmHttp.c_str()); break;  // Zoom In
        case 10: sCmdHtml.printf(L"%s/stw-cgi/ptzcontrol.cgi?msubmenu=continuous&action=control&Zoom=-3",            FStrmHttp.c_str()); break;  // Zoom Out
        case 12: sCmdHtml.printf(L"%s/stw-cgi/ptzcontrol.cgi?msubmenu=continuous&action=control&Focus=Near",         FStrmHttp.c_str()); break;  // Focus In
        case 13: sCmdHtml.printf(L"%s/stw-cgi/ptzcontrol.cgi?msubmenu=continuous&action=control&Focus=Far",          FStrmHttp.c_str()); break;  // Focus Out
        default: return;
        }

        IdHTTP1->HTTPOptions = IdHTTP1->HTTPOptions >> hoInProcessAuth;
        IdHTTP1->HTTPOptions = IdHTTP1->HTTPOptions << hoInProcessAuth;
        String sResult = IdHTTP1->Get(sCmdHtml);
        reMsg->Lines->Add(sResult);
        IdHTTP1->Disconnect();
    }
    catch(...) {}
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsControl::BtnWebCamControlMouseUp(TObject *Sender, TMouseButton Button,
          TShiftState Shift, int X, int Y)
{
    // PANControl Stop
    if (!FStrmPlay) return;

    try
    {
        String sCmdHtml;
        TImageBtn *pBtn = (TImageBtn*)Sender;
        switch(pBtn->Tag)
        {
        case 1: // Tilt Up
        case 2: // Tilt Down
            sCmdHtml.printf(L"%s/stw-cgi/ptzcontrol.cgi?msubmenu=continuous&action=control&Tilt=0&Duration=1", FStrmHttp.c_str());
            break;
        case 3: // Pan left
        case 4: // Pan right
            sCmdHtml.printf(L"%s/stw-cgi/ptzcontrol.cgi?msubmenu=continuous&action=control&Pan=0", FStrmHttp.c_str());
            break;
        case  9: // Zoom In
        case 10: // Zoom Out
            sCmdHtml.printf(L"%s/stw-cgi/ptzcontrol.cgi?msubmenu=continuous&action=control&Zoom=0", FStrmHttp.c_str());
            break;
        case 12: // Focus In
        case 13: // Focus Out
            sCmdHtml.printf(L"%s/stw-cgi/ptzcontrol.cgi?msubmenu=continuous&action=control&Focus=Stop", FStrmHttp.c_str());
            break;
        default: return;
        }

        IdHTTP1->HTTPOptions = IdHTTP1->HTTPOptions >> hoInProcessAuth;
        IdHTTP1->HTTPOptions = IdHTTP1->HTTPOptions << hoInProcessAuth;
        String sResult = IdHTTP1->Get(sCmdHtml);
        reMsg->Lines->Add(sResult);
        IdHTTP1->Disconnect();
    }
    catch(...) {}
}
//---------------------------------------------------------------------------


void __fastcall TFrmVmsControl::TvListCellDblClick(TcxCustomGridTableView *Sender, TcxGridTableDataCellViewInfo *ACellViewInfo,
          TMouseButton AButton, TShiftState AShift, bool &AHandled)
{
	if (!ACellViewInfo) return;

    ClearCheckList();

    TcxDataController *pGDC = TvList->DataController;
    int nSelIdx = CMM_GetRecordIndex(TvList);
	if (nSelIdx < 0) return;
    pGDC->Values[nSelIdx][ColumnSel->Index] = true;

    DisplayInfo();
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsControl::UpdateList()
{
    CMM_ClearGridTableView(TvList);

    int ii, jj;
    int nCols = 0;

    TcxDataController *pGDC = TvList->DataController;

    TvList->BeginUpdate();
    pGDC->BeginUpdate();

    VmsCtlrManager->FLists.Lock();
    try
    {
        int nRow;
        FOR_STL(TVmsCtlr*, pObj, VmsCtlrManager->FLists)
        {
            if (pObj->DEL_YN == "Y") continue;

            nRow = pGDC->AppendRecord();

            pGDC->Values[nRow][ColumnSel->Index] = false;

            RefreshVmsStatus(pGDC, nRow, pObj);

            pGDC->Values[nRow][Col99->Index] = (int)pObj;
        }
    }
    __finally
    {
        VmsCtlrManager->FLists.UnLock();

        pGDC->EndUpdate();
        TvList->EndUpdate();
        //RefreshStatus();
    }
}
//---------------------------------------------------------------------------
void __fastcall TFrmVmsControl::RefreshVmsStatus(TcxDataController *AGDC, int ARow, void *AMemObj)
{
    TcxDataController *pGDC = AGDC;
    int nRow = ARow;
    TVmsCtlr *pObj = (TVmsCtlr*)AMemObj;
    try {
        pGDC->Values[nRow][Col01->Index] = pObj->VMS_CTLR_NMBR;
        pGDC->Values[nRow][Col02->Index] = pObj->VMS_CTLR_ID;
        pGDC->Values[nRow][Col03->Index] = pObj->VMS_NM;
        pGDC->Values[nRow][Col04->Index] = pObj->VMS_TYPE_DESC;

        pGDC->Values[nRow][Col05->Index] = pObj->VMS_TYPE_DESC;

        pGDC->Values[nRow][Col06->Index] = pObj->OPER_MODE_DESC;
        //pGDC->Values[nRow][Col33->Index] = pObj->VMS_PHSE_CHNG_CYCL;

        pGDC->Values[nRow][Col07->Index] = ITSUtil_FormatStr(pObj->STTS->UPDT_DT, STR_DATETIME);
        pGDC->Values[nRow][Col08->Index] = String(pObj->STTS->PROVIDE_CNT);
        pGDC->Values[nRow][Col09->Index] = pObj->STTS->PROVIDE_RESULT;

        pGDC->Values[nRow][Col10->Index] = pObj->STTS->CMNC_STTS_DESC;               //통신상태

        pGDC->Values[nRow][Col11->Index] = pObj->STTS->MODL_STTS_DESC;        //모듈상태
        pGDC->Values[nRow][Col12->Index] = pObj->STTS->PWER_STTS_DESC;        //전원상태
        pGDC->Values[nRow][Col13->Index] = pObj->STTS->BRGH_VAL;    //휘도

        pGDC->Values[nRow][Col14->Index] = pObj->STTS->CBOX_DOOR_STTS_DESC;     //도어
        pGDC->Values[nRow][Col15->Index] = pObj->STTS->FAN_STTS_DESC;      //팬
        pGDC->Values[nRow][Col16->Index] = pObj->STTS->HETR_STTS_DESC;   //히터
        pGDC->Values[nRow][Col17->Index] = pObj->STTS->CBOX_TMPR;     //온도

#if 0
        pGDC->Values[nRow][Col18->Index] = String(pObj->STATE.ModuleOperatingTemperature);      //모듈정지온도
        pGDC->Values[nRow][Col19->Index] = String(pObj->STATE.FanOperatingTemperature);         //팬동작온도
        pGDC->Values[nRow][Col20->Index] = String(pObj->STATE.HeaterOperatingTemperature);      //히터동작온도
        pGDC->Values[nRow][Col21->Index] = String(pObj->STATE.ModuleBasicFailureRate);          //모듈장애율
        pGDC->Values[nRow][Col28->Index] = String(pObj->STATE.ScheduledMessageOperatingTime);   //계획된 메시지의 동작시간(초)
#endif

        pGDC->Values[nRow][Col29->Index] = pObj->PANL_ON_TIME;   //전광판 ON
        pGDC->Values[nRow][Col30->Index] = pObj->PANL_OFF_TIME;  //전광판 OFF
    } catch(Exception &e) {
    }
}
//---------------------------------------------------------------------------
void __fastcall TFrmVmsControl::RefreshStatus()
{
    TcxDataController *pGDC = TvList->DataController;
    try
    {
        TvList->BeginUpdate();
        pGDC->BeginUpdate();

        int nRows = pGDC->RecordCount;
        for(int nRow = 0; nRow < nRows; nRow++)
        {
            int nMemPtr = TvList->DataController->Values[nRow][Col99->Index];
            TVmsCtlr *pObj = (TVmsCtlr*)nMemPtr;
            if (!pObj) continue;

            RefreshVmsStatus(pGDC, nRow, pObj);
        }
    }
    __finally
    {
        pGDC->EndUpdate();
        TvList->EndUpdate();
        //CxList->LayoutChanged();
    }
}
//---------------------------------------------------------------------------

int  __fastcall TFrmVmsControl::GetSelIds(String &ALinkIds)
{
    ALinkIds = "";

    TcxDataController *pGDC = TvList->DataController;
    if (TvList->ViewData->RecordCount <= 0) return 0;
	int nIndex = pGDC->FocusedRecordIndex;
	if( nIndex < 0 )
		return 0;

    String sLinkId = VarToStr(pGDC->Values[nIndex][Col01->Index]);
    ALinkIds = sLinkId;
    return 1;
}
//---------------------------------------------------------------------------

int  __fastcall TFrmVmsControl::GetSelIds(TStringList *AStringList)
{
    int nSelCnt = 0;
    try
    {
        TvList->BeginUpdate();

        int nRowCnt = TvList->ViewData->RecordCount;

        for (int ii = 0; ii < nRowCnt; ii++)
        {
            TcxCustomGridRow* ARow = TvList->ViewData->Rows[ii];
            if (((bool)ARow->Values[ColumnSel->Index]))
            {
                AStringList->Add(ARow->Values[Col01->Index]);
                nSelCnt++;
            }
        }
    }
    __finally
    {
        TvList->EndUpdate();
    }
    return nSelCnt;
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsControl::Col06CustomDrawCell(TcxCustomGridTableView *Sender, TcxCanvas *ACanvas, TcxGridTableDataCellViewInfo *AViewInfo,
          bool &ADone)
{
    try
    {
        TColor tColor;
        String sVmsMode = AViewInfo->GridRecord->DisplayTexts[AViewInfo->Item->Index];
        tColor = ACanvas->Brush->Color;
        if      (sVmsMode == "자동") tColor = clLime;
        else if (sVmsMode == "고정") tColor = clFuchsia;
        else                         tColor = clYellow;

        ACanvas->SetBrushColor(tColor);
        ACanvas->Font->Color  = clBlack;
    }
    catch(Exception &e)
    {
    }
#if 0
    int nRecordIdx = AViewInfo->GridRecord->RecordIndex;
    if (nRecordIdx >= 0)
    {
        int nIdx = AViewInfo->Item->Index;
        String sVmsMode = AViewInfo->GridRecord->DisplayTexts[nIdx];
        if (sVmsMode == "고정") ACanvas->Canvas->Brush->Color = clLime;
    }
#endif
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsControl::Col07CustomDrawCell(TcxCustomGridTableView *Sender, TcxCanvas *ACanvas, TcxGridTableDataCellViewInfo *AViewInfo,
          bool &ADone)
{
    try
    {
        if (AViewInfo->GridRecord->RecordIndex < 0) return;
        String sResult = AViewInfo->GridRecord->DisplayTexts[Col09->Index];
        if (sResult == "N")
        {
            ACanvas->Canvas->Brush->Color = clRed;
        }
    }
    catch(Exception &e)
    {
    }
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsControl::Col10CustomDrawCell(TcxCustomGridTableView *Sender, TcxCanvas *ACanvas, TcxGridTableDataCellViewInfo *AViewInfo,
          bool &ADone)
{
    try
    {
        TColor tColor;
        String sStatus = AViewInfo->GridRecord->DisplayTexts[AViewInfo->Item->Index];
        tColor = ACanvas->Brush->Color;

        if      (sStatus.Pos("-"))    tColor = clGray;
        else if (sStatus.Pos("?"))    tColor = clGray;
        else if (sStatus.Pos("장애")) tColor = clRed;
        else if (sStatus.Pos("두절")) tColor = clRed;
        else if (sStatus.Pos("켜짐")) tColor = clYellow;
        else if (sStatus.Pos("열림")) tColor = clRed;
        else if (sStatus.Pos("동작")) tColor = clYellow;
        else if (sStatus.Pos("가동")) Color = clYellow;
        else                          tColor = clLime;

        ACanvas->SetBrushColor(tColor);
        ACanvas->Font->Color  = clBlack;
        /*if (AViewInfo->GridRecord->Selected)
        {
            ACanvas->Font->Color  = clBlack;
        }*/
    }
    catch(Exception &e)
    {
    }
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsControl::Col12CustomDrawCell(TcxCustomGridTableView *Sender, TcxCanvas *ACanvas, TcxGridTableDataCellViewInfo *AViewInfo,
          bool &ADone)
{
    try
    {
        TColor tColor;
        String sStatus = AViewInfo->GridRecord->DisplayTexts[AViewInfo->Item->Index];
        tColor = ACanvas->Brush->Color;

#if 0
        if      (sStatus.Pos("-"))    tColor = clGray;
        else if (sStatus.Pos("장애")) tColor = clRed;
        else if (sStatus.Pos("두절")) tColor = clRed;
        else if (sStatus.Pos("켜짐")) tColor = clYellow;
        else if (sStatus.Pos("열림")) tColor = clRed;
        else if (sStatus.Pos("동작")) tColor = clYellow;
        else if (sStatus.Pos("가동")) tColor = clYellow;
        else                          tColor = clLime;
#else
        if      (sStatus.Pos("-"))    tColor = clGray;
        else if (sStatus.Pos("장애")) tColor = clRed;
        else if (sStatus.Pos("두절")) tColor = clRed;
        else if (sStatus.Pos("꺼짐")) tColor = clRed;
        else                          tColor = clLime;
#endif

        ACanvas->SetBrushColor(tColor);
        ACanvas->Font->Color  = clBlack;
        /*if (AViewInfo->GridRecord->Selected)
        {
            ACanvas->Font->Color  = clBlack;
        }*/
    }
    catch(Exception &e)
    {
    }
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsControl::TmrRefreshStatusTimer(TObject *Sender)
{
    RefreshStatusRequest();
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsControl::BtnSearchClick(TObject *Sender)
{
    RefreshStatusRequest();
}
//---------------------------------------------------------------------------
void __fastcall TFrmVmsControl::RefreshStatusRequest()
{
    BtnSearch->Enabled = false;
    TmrRefreshStatus->Enabled = false;
    VmsCtlrManager->LoadStts();
    RefreshStatus();
    TmrRefreshStatus->Interval = 30000;
    TmrRefreshStatus->Enabled = true;
    BtnSearch->Enabled = true;
    EdFocus->SetFocus();
}
//---------------------------------------------------------------------------

