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

#include <vcl.h>
#include "AppGlobalF.h"
#include "ITSSkinF.h"
#include "ITSUtilF.h"
#include "FrmVmsOprMainF.h"
#include "ITSLangTransF.h"
#include "XnsCommon.h"
#include "XnsDeviceInterface.h"
#pragma hdrstop

#include "VMS0500MF.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 "AcesTechXPlayer2Lib_OCX"
#pragma link "XNSSDKDEVICELib_OCX"
#pragma link "XNSSDKWINDOWLib_OCX"
#pragma resource "*.dfm"
TVMS0500M *VMS0500M = NULL;

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

#define FFPLAYER    0
#define ACES        1

//---------------------------------------------------------------------------
__fastcall TVMS0500M::TVMS0500M(TComponent* Owner)
    : TForm(Owner)
{
    //::CoInitialize(NULL);
    // control width 900
    LangTrans->Translate(this, ITSDb_GetConnection());
    ITSSkin_Load(this);
    LoadLocalSkin();

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

    FPalyerForm = NULL;
    FSelVmsObj  = NULL;

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

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

    TabPing->TabVisible = false;
    TabPing->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();
    FStrmHandle = 0;

#if FFPLAYER
    AcesTechXPlayer21->Visible = false;

    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
    }
#endif

#if ACES
    ChkFullScreen->Visible = false;
#endif


    // xns-activex - start
    //XnsSdkDevice1->Align = alClient;
    XnsSdkDevice1->Visible = false;
    XnsSdkWindow1->Align = alClient;
    XnsSdkWindow1->Visible = false;

	m_hDevice      = 0;     // Device handle
	m_hMediaSource = 0;     // Media stream ID
	m_nControlId   = 0;     // Control ID
	m_bIsMediaPlay = false;

    m_bXnsInitialize = InitializeXnsDevice();
    // xns-activex - end

    reMsg->Lines->Clear();
}
//---------------------------------------------------------------------------

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

        FStrmPlay = false;

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

void __fastcall TVMS0500M::FormShow(TObject *Sender)
{
    Refresh();
    FRAMEVmsStateList1->UpdateList();
    //FRAMEVmsStateList1->TvList->ApplyBestFit(NULL, true, false);

    FRAMEVmsStateList1->CxList->Enabled = false;

    UpdatePingList();


    TmrShow->Enabled = true;
}
//---------------------------------------------------------------------------

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

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

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

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

    FRAMEVmsStateList1->CxList->Enabled = true;
}
//---------------------------------------------------------------------------

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

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

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

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

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

void __fastcall TVMS0500M::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 TVMS0500M::ActivateForm(bool AActivate)
{
//TODO: 기존에는 아래가 주석으로 막혀 있었음. 왜그러지?
    if (AActivate) FRAMEVmsStateList1->RefreshStatus();
}
//---------------------------------------------------------------------------

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

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

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

    int nMemPtr = (int)pGDC->Values[nSelIdx][FRAMEVmsStateList1->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 = FSelVmsObj->STATE.ScheduledMessageOperatingTime;/* 필수 계획된 메시지의 동작시간(초) */
        Se02->Value = FSelVmsObj->STATE.ModuleOperatingTemperature;   /* 필수 모듈 전원이 꺼지는 온도값(℃) */
        Se03->Value = FSelVmsObj->STATE.FanOperatingTemperature;      /* 필수 Fan 동작 기준 온도값(℃) */
        Se04->Value = FSelVmsObj->STATE.HeaterOperatingTemperature;   /* 필수 Heater 동작 기준 온도값(℃) */
        Se05->Value = FSelVmsObj->STATE.ModuleBasicFailureRate;       /* 선택 모듈 장애율 (한 개의 모듈을 장애로 처리하기 위한 픽셀의 백분율값) */
        Se06->Value = 3;
        Se07->Value = 30;


        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;
#else
        SeCurrBrgh->Value = FSelVmsObj->BRGH_CURR_STEP;
        SeWeekBrgh->Value = FSelVmsObj->BRGH_WEEK_STEP;
        SeNghtBrgh->Value = FSelVmsObj->BRGH_NGHT_STEP;
#endif

        if (FSelVmsObj->OPER_MODE == "A")
        {
            RdbAuto->Checked = true;
        }
        else
        if (FSelVmsObj->OPER_MODE == "F")
        {
            RdbFix->Checked = true;
        }
        else
        if (FSelVmsObj->OPER_MODE == "B")
        {
            RdbBase->Checked = true;
        }
    }
    catch(Exception &e)
    {
    }

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

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

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

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

    ClearCheckList();

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

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

void __fastcall TVMS0500M::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 TVMS0500M::GetSelListItems(bool ACommCheck/*=true*/)
{
    TcxGridBandedTableView *TvList = FRAMEVmsStateList1->TvList;
    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[FRAMEVmsStateList1->Col99->Index];
            TVmsCtlr *pVms = (TVmsCtlr*)nMemPtr;
            if (!pVms) continue;

            bSelected = (bool)ARow->Values[FRAMEVmsStateList1->ColumnSel->Index];
            if (bSelected)
            {
                String sVmsNmbr = ARow->Values[FRAMEVmsStateList1->Col01->Index];    //VMS번호
                if (ACommCheck)
                {
                    if (pVms->STATE.Comm == vms_comm_normal)
                    {
                        FVmsIds->Add(sVmsNmbr);
                    }
                }
                else
                {
                    FVmsIds->Add(sVmsNmbr);
                }
            }
        }
    }
    __finally
    {
        TvList->EndUpdate();
    }

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

void __fastcall TVMS0500M::BtnControlClick(TObject *Sender)
{
    //전광판제어
    String sTitle = cxLabel1->Caption;//"전광판/제어기 제어";
    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);
        FRAMEVmsStateList1->CxList->SetFocus();
        return;
    }

    int nCmdIdx;
    if (RdbOn->Checked)
    {
        nCmdIdx = vms_req_board_power_on;
        sMsg = cxLabel3->Caption + "\r\n" + cxLabel9->Caption;//"선택하신 VMS에 VMS 전광판 전원 ON 명령을 전송하시겠습니까?\r\n(통신상태에 따라 명령이 실행되지 않을 수 있습니다.)";
    }
    else
    if (RdbOff->Checked)
    {
        nCmdIdx = 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_pLOGIN->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)
            {
                VmsCtlrManager->InsVmsControlHs(sCmdTime, sVmsNmbr, sOprCode, sCmdValue, "1", sCmdUser);
                nOkCnt++;
            }
            else
            {
                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)
            {
                VmsCtlrManager->InsVmsControlHs(sCmdTime, sVmsNmbr, "V03", "Reset", "1", sCmdUser);
                nOkCnt++;
            }
            else
            {
                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)
            {
                VmsCtlrManager->InsVmsControlHs(sCmdTime, sVmsNmbr, "V07", sCmdValue, "1", sCmdUser);
                nOkCnt++;
            }
            else
            {
                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);
}
//---------------------------------------------------------------------------

void __fastcall TVMS0500M::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);
        FRAMEVmsStateList1->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;
    }

    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_pLOGIN->sUserId;
    String sCmdTime = Now().FormatString("yyyymmddhhnnss");
    String sCmdValue;

    sCmdValue.printf(L"%d.%d,%02d%02d,%02d%02d",
                        nVal03,
                        nVal04,
                        nStrTmHour,
                        nStrTmMin,
                        nEndTmHour,
                        nEndTmMin);
    int result;
    for (int ii = 0; ii < nSelCnt; ii++)
    {
        String sVmsNmbr = FVmsIds->Strings[ii];

        INT_VMS_PARA_SET_REQ VmsPara;
        BYTE MsgSeq;

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

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

        VmsPara.FanRunTmpr  = (BYTE)nVal03;
        VmsPara.HetrRunTmpr = (BYTE)nVal04;
        sprintf(VmsPara.DispStrTm, "%02d%02d", nStrTmHour, nStrTmMin);
        sprintf(VmsPara.DispEndTm, "%02d%02d", nEndTmHour, nEndTmMin);

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

            if (UpdateVmsParam(sVmsNmbr, (void*)&VmsPara))
            {
                TVmsCtlr *pObj = VmsCtlrManager->FLists.Find(sVmsNmbr);
                if (pObj)
                {
                    pObj->PANL_ON_TIME.printf(L"%02d%02d", nStrTmHour, nStrTmMin);           //	N	VARCHAR2(4)	    Y	'0400'	전광판 ON TIME
                    pObj->PANL_OFF_TIME.printf(L"%02d%02d", nEndTmHour, nEndTmMin);          //	N	VARCHAR2(4)	    Y	'0200'	전광판 OFF TIME
#if 0
                    pObj->VMS_PHSE_CHNG_CYCL    = VmsPara.SchMsgTime;  /* 필수 계획된 메시지의 동작시간(초) */
                    pObj->VMS_CMNC_ERR_BASS_VAL = VmsPara.ModuleTemp;  /* 필수 모듈 전원이 꺼지는 온도값(℃) */
                    pObj->FAN_MTNS_TMPR         = VmsPara.FanTemp;     /* 필수 Fan 동작 기준 온도값(℃) */
                    pObj->HETR_MTNS_TMPR        = VmsPara.HeaterTemp;  /* 필수 Heater 동작 기준 온도값(℃) */
                    pObj->VMS_MODL_ERR_RATE     = VmsPara.ModuleFail;  /* 선택 모듈 장애율 (한 개의 모듈을 장애로 처리하기 위한 픽셀의 백분율값) */

                    pObj->STATE.ScheduledMessageOperatingTime = pObj->VMS_PHSE_CHNG_CYCL;    /* 필수 계획된 메시지의 동작시간(초) */
                    pObj->STATE.ModuleOperatingTemperature    = pObj->VMS_CMNC_ERR_BASS_VAL; /* 필수 모듈 전원이 꺼지는 온도값(℃) */
                    pObj->STATE.FanOperatingTemperature       = pObj->FAN_MTNS_TMPR;         /* 필수 Fan 동작 기준 온도값(℃) */
                    pObj->STATE.HeaterOperatingTemperature    = pObj->HETR_MTNS_TMPR;        /* 필수 Heater 동작 기준 온도값(℃) */
                    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) + " " + cxLabel12->Caption;

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

#if 0
    //제어기함체환경설정
    int nVal01 = Se01->Value;
    int nVal02 = Se02->Value;
    int nVal03 = Se03->Value;
    int nVal04 = Se04->Value;
    int nVal05 = Se05->Value;
    int nVal06 = Se06->Value;
    int nVal07 = Se07->Value;

    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);
        FRAMEVmsStateList1->CxList->SetFocus();
        return;
    }

    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_pLOGIN->sUserId;
    String sCmdTime = Now().FormatString("yyyymmddhhnnss");
    String sCmdValue;

    sCmdValue.printf(L"%d.%d,%d,%d,%d,%d,%d",
                        nVal01,
                        nVal02,
                        nVal03,
                        nVal04,
                        nVal05,
                        nVal06,
                        nVal07);
    int result;
    for (int ii = 0; ii < nSelCnt; ii++)
    {
        String sVmsNmbr = FVmsIds->Strings[ii];

        INT_VMS_PARA_SET_REQ 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.SchMsgTime = (DWORD)nVal01;  /* 계획된 메시지 동작시간 */
        VmsPara.ModuleTemp = (BYTE)nVal02;   /* 모듈전원 OFF 온도 */
        VmsPara.FanTemp    = (BYTE)nVal03;   /* Fan동작 기준온도 */
        VmsPara.HeaterTemp = (BYTE)nVal04;   /* Heater동작 기준온도 */
        VmsPara.ModuleFail = (BYTE)nVal05;   /* 모듈장애 판단율 */
        VmsPara.RetryCount = (BYTE)nVal06;   /* 재시도 횟수 */
        VmsPara.TimeOut    = (DWORD)nVal07;   /* 최대응답대기시간 */

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

            //통신전송후 바이트오더링이 바뀐다
            VmsPara.SchMsgTime = (DWORD)nVal01;  /* 계획된 메시지 동작시간 */
            VmsPara.TimeOut    = (DWORD)nVal07;  /* 최대응답대기시간 */

            if (UpdateVmsParam(sVmsNmbr, (void*)&VmsPara))
            {
                TVmsCtlr *pObj = VmsCtlrManager->FLists.Find(sVmsNmbr);
                if (pObj)
                {
#if 0
                    pObj->VMS_PHSE_CHNG_CYCL    = VmsPara.SchMsgTime;  /* 필수 계획된 메시지의 동작시간(초) */
                    pObj->VMS_CMNC_ERR_BASS_VAL = VmsPara.ModuleTemp;  /* 필수 모듈 전원이 꺼지는 온도값(℃) */
                    pObj->FAN_MTNS_TMPR         = VmsPara.FanTemp;     /* 필수 Fan 동작 기준 온도값(℃) */
                    pObj->HETR_MTNS_TMPR        = VmsPara.HeaterTemp;  /* 필수 Heater 동작 기준 온도값(℃) */
                    pObj->VMS_MODL_ERR_RATE     = VmsPara.ModuleFail;  /* 선택 모듈 장애율 (한 개의 모듈을 장애로 처리하기 위한 픽셀의 백분율값) */

                    pObj->STATE.ScheduledMessageOperatingTime = pObj->VMS_PHSE_CHNG_CYCL;    /* 필수 계획된 메시지의 동작시간(초) */
                    pObj->STATE.ModuleOperatingTemperature    = pObj->VMS_CMNC_ERR_BASS_VAL; /* 필수 모듈 전원이 꺼지는 온도값(℃) */
                    pObj->STATE.FanOperatingTemperature       = pObj->FAN_MTNS_TMPR;         /* 필수 Fan 동작 기준 온도값(℃) */
                    pObj->STATE.HeaterOperatingTemperature    = pObj->HETR_MTNS_TMPR;        /* 필수 Heater 동작 기준 온도값(℃) */
                    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) + " " + cxLabel12->Caption;

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

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

    INT_VMS_PARA_SET_REQ *pReq = (INT_VMS_PARA_SET_REQ*)pData;

#if 0
    sQry = "UPDATE TB_VMS_CTLR            \r\n"
           "   SET FAN_MTNS_TMPR  = :p02, \r\n"
           "       HETR_MTNS_TMPR = :p03, \r\n"
           "       PANL_ON_TIME   = :p04, \r\n"
           "       PANL_OFF_TIME  = :p05  \r\n"
           " WHERE VMS_CTLR_NMBR  = :p01  \r\n";
#else
    sQry = "UPDATE TB_VMS_CTLR           \r\n"
           "   SET PANL_ON_TIME  = :p04, \r\n"
           "       PANL_OFF_TIME = :p05  \r\n"
           " WHERE VMS_CTLR_NMBR = :p01  \r\n";
#endif
    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;
#if 0
            pADO->Parameters->ParamByName("p02")->Value = sFanRunTmpr;
            pADO->Parameters->ParamByName("p03")->Value = sHetrRunTmpr;
#endif
            pADO->Parameters->ParamByName("p04")->Value = sDispStrTm;
            pADO->Parameters->ParamByName("p05")->Value = sDispEndTm;
			nCnt = pADO->ExecSQL();
        }
        catch(EDatabaseError &E)
        {
            DBERRORMSG("TVMS0500M::UpdateVmsParam", String(E.ClassName()), E.Message, sQry);
            throw Exception(String(E.ClassName()) + E.Message);
        }
        catch(Exception &e)
        {
            DBERRORMSG("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;
}
//---------------------------------------------------------------------------

void __fastcall TVMS0500M::BtnOnOffSetClick(TObject *Sender)
{
    //전광판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);
        FRAMEVmsStateList1->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_pLOGIN->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)
        {
            DBERRORMSG("TVMS0500M::BtnOnOffSetClick", String(E.ClassName()), E.Message, sQry);
            throw Exception(String(E.ClassName()) + E.Message);
        }
        catch(Exception &e)
        {
            DBERRORMSG("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);
    }
    //FRAMEVmsStateList1->RefreshStatus();
    FrmVmsOprMain->RefreshVmsMessage(WM_VMS_STATE_REFRESH);
}
//---------------------------------------------------------------------------

void __fastcall TVMS0500M::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);
        FRAMEVmsStateList1->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;
    if (RdbAuto->Checked)
    {
        OPER_MODE = "A";
    }
    else
    if (RdbFix->Checked)
    {
        OPER_MODE = "F";
    }
    else
    if (RdbBase->Checked)
    {
        OPER_MODE = "B";
    }

    String     sQry;
    TADOQuery *pADO = NULL;

    sQry = "UPDATE TB_VMS_CTLR            \r\n"
           "   SET OPER_MODE      = :p01  \r\n"
           " WHERE VMS_CTLR_NMBR  = :p05  \r\n";

    String LAST_CRPR_NMBR = g_pLOGIN->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;

            INT_VMS_MODE_REQ VmsMode;
            BYTE             MsgSeq;

            memset(&VmsMode, 0x00, sizeof(VmsMode));
            MsgSeq = (BYTE)0x50;
            memcpy(VmsMode.CmdTime, AnsiString(LAST_CRCT_DT).c_str(),   INT_VMS_MAX_DATETIME); /* 명령수행시각 */
            memcpy(VmsMode.OperId,  AnsiString(LAST_CRPR_NMBR).c_str(), INT_VMS_MAX_OPER_ID);  /* 운영자 ID */

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

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

                TVmsCtlr *pObj = VmsCtlrManager->FLists.Find(sVmsNmbr);
                if (pObj)
                {
                    pObj->OPER_MODE = OPER_MODE;
                    if      (pObj->OPER_MODE == "A") pObj->STATE.OprMode = 'A';
                    else if (pObj->OPER_MODE == "B") pObj->STATE.OprMode = 'B';
                    else                             pObj->STATE.OprMode = 'F';
                }
                else continue;

                VmsMode.Unit[VmsMode.Count].VMS_CTLR_NMBR = sVmsNmbr.ToIntDef(0);       /* VMS 제어기 번호 */
                if      (OPER_MODE == "A") VmsMode.Unit[VmsMode.Count].Mode = 'A';
                else if (OPER_MODE == "B") VmsMode.Unit[VmsMode.Count].Mode = 'B';
                else                       VmsMode.Unit[VmsMode.Count].Mode = 'F';

                VmsMode.Count++;
                if (VmsMode.Count >= INT_VMS_MAX_MODE)
                {
                    CComm_VmsModeReq(&VmsMode, MsgSeq);
                }
            }
            if (VmsMode.Count > 0)
            {
                CComm_VmsModeReq(&VmsMode, MsgSeq);
            }
        }
        catch(EDatabaseError &E)
        {
            DBERRORMSG("TVMS0500M::BtnModeControlClick", String(E.ClassName()), E.Message, sQry);
            throw Exception(String(E.ClassName()) + E.Message);
        }
        catch(Exception &e)
        {
            DBERRORMSG("TVMS0500M::BtnModeControlClick", 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) + " " + cxLabel19->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, "V06", OPER_MODE, "1", LAST_CRPR_NMBR);
    }
    //FRAMEVmsStateList1->RefreshStatus();
    FrmVmsOprMain->RefreshVmsMessage(WM_VMS_STATE_REFRESH);
}
//---------------------------------------------------------------------------

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

void __fastcall TVMS0500M::BtnDefaultMsgClick(TObject *Sender)
{
    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);
        FRAMEVmsStateList1->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_pLOGIN->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)
        {
            VmsCtlrManager->InsVmsControlHs(sCmdTime, sVmsNmbr, sCmd, sCmdValue, "1", sCmdUser);
            nOkCnt++;
        }
        else
        {
            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);
}
//---------------------------------------------------------------------------

void __fastcall TVMS0500M::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);
        FRAMEVmsStateList1->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);
        FRAMEVmsStateList1->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 TVMS0500M::UpdateVmsParam2(String AVmsNmbr, void *pData)
{
    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"
           "       VMS_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)
        {
            DBERRORMSG("VMS Parameter Save", String(E.ClassName()), E.Message, sQry);
            throw Exception(String(E.ClassName()) + E.Message);
        }
        catch(Exception &e)
        {
            DBERRORMSG("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;
}
//---------------------------------------------------------------------------

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

void __fastcall TVMS0500M::BtnDisplayTimeSetClick(TObject *Sender)
{
    //폼 표출주기 설정
    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);
        FRAMEVmsStateList1->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_pLOGIN->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)
        {
            DBERRORMSG("VMS Config Save", String(E.ClassName()), E.Message, sQry);
            throw Exception(String(E.ClassName()) + E.Message);
        }
        catch(Exception &e)
        {
            DBERRORMSG("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);
    }
    //FRAMEVmsStateList1->RefreshStatus();
    FrmVmsOprMain->RefreshVmsMessage(WM_VMS_STATE_REFRESH);
}
//---------------------------------------------------------------------------

void __fastcall TVMS0500M::BtnMsgImmediateDownloadClick(TObject *Sender)
{
    //폼 표출주기 설정
    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_pLOGIN->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);

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

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

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

void __fastcall TVMS0500M::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 TVMS0500M::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->STATE.Comm == vms_comm_normal) pGDC->Values[nRow][ColumnSel->Index] = false;
            else                                     pGDC->Values[nRow][ColumnSel->Index] = true;

            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] = VmsComm(pObj);               //통신상태

            pGDC->Values[nRow][Col05->Index] = pObj->VMS_CTLR_IP;
            pGDC->Values[nRow][Col06->Index] = "-";
            pGDC->Values[nRow][Col07->Index] = "-";
            pGDC->Values[nRow][Col08->Index] = "-";

            pGDC->Values[nRow][Col09->Index] = pObj->WEB_CMRA_IP;
            pGDC->Values[nRow][Col10->Index] = "-";
            pGDC->Values[nRow][Col11->Index] = "-";
            pGDC->Values[nRow][Col12->Index] = "-";

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

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

void __fastcall TVMS0500M::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][Col99->Index];
            TVmsCtlr *pObj = (TVmsCtlr*)nMemPtr;
            if (!pObj) continue;

            if (AInit == false && PgControl->Properties->ActivePage != TabPing)
            {
                if (pObj->STATE.Comm == vms_comm_normal) pGDC->Values[nRow][ColumnSel->Index] = false;
                else                                     pGDC->Values[nRow][ColumnSel->Index] = true;
            }

            if (AInit)
            {
                pGDC->Values[nRow][Col06->Index] = "-";
                pGDC->Values[nRow][Col07->Index] = "-";
                pGDC->Values[nRow][Col08->Index] = "-";

                pGDC->Values[nRow][Col10->Index] = "-";
                pGDC->Values[nRow][Col11->Index] = "-";
                pGDC->Values[nRow][Col12->Index] = "-";
            }

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

void __fastcall TVMS0500M::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 TVMS0500M::BtnNwkPingClick(TObject *Sender)
{
    TWaitCursor waitCrs;
	TcxDataController *pGDC = TvPing->DataController;
	int nRows  = pGDC->RecordCount;

    String sMsg;
    int nSelCnt = CMM_GetCheckCount(TvPing, ColumnSel->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][ColumnSel->Index];
        if (!bPing) continue;

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

        FPingType = 1;

        sSvrIp = pGDC->Values[ii][Col05->Index];
        if (sSvrIp == NULL || sSvrIp.IsEmpty())
        {
            continue;
        }
        pGDC->Values[ii][Col06->Index] = "?";
        pGDC->Values[ii][Col07->Index] = "?";
        pGDC->Values[ii][Col08->Index] = "?";

        nSvrPort = 0;

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

        Application->ProcessMessages();

        FPingType = 2;

        sSvrIp = pGDC->Values[ii][Col09->Index];
        if (sSvrIp == NULL || sSvrIp.IsEmpty())
        {
            continue;
        }
        pGDC->Values[ii][Col10->Index] = "?";
        pGDC->Values[ii][Col11->Index] = "?";
        pGDC->Values[ii][Col12->Index] = "?";

        nSvrPort = 0;

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

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

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

void __fastcall TVMS0500M::Col04CustomDrawCell(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 = 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(FrmLang->lblState1->Caption.Trim())) tColor = clRed;
        else if (sStatus.Pos(FrmLang->lblPOWER0->Caption.Trim())) tColor = clYellow;
        else if (sStatus.Pos(FrmLang->lblCDS1->Caption.Trim()))   tColor = clRed;
        else if (sStatus.Pos(FrmLang->lblFAN0->Caption.Trim()))   tColor = clYellow;
        //else if (sStatus.Pos(frmLang->lblHEAT0->Caption.Trim()))  tColor = clYellow;
        else                                                      tColor = clLime;
#endif

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

void __fastcall TVMS0500M::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][Col05->Index];
            else
                sSvrIp = pGDC->Values[ii][Col09->Index];

			int nSvrPort = 0;

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

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

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

                break;
            }

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

void __fastcall TVMS0500M::Col08CustomDrawCell(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 TVMS0500M::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 == Col05->Index ||
        ACellViewInfo->Item->Index == Col09->Index)
	{
        String sSvrIp = pGDC->Values[nRow][ACellViewInfo->Item->Index];
        ITSUtil_NetworkPing(sSvrIp);
    }
}
//---------------------------------------------------------------------------

void __fastcall TVMS0500M::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 TVMS0500M::WebCamPlay(String AVmsNo)
{
    if (LblErrMsg->Visible) LblErrMsg->Visible = false;
    reMsg->Lines->Clear();
    reMsg->Lines->Add("Try Connect...");

    WebCamStop();

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

    PnlSamsung->Caption = "Connecting...";
    PnlSamsung->Refresh();
    try
    {
        FStrmAddr = pObj->FULL_STRM_SESN_NM.Trim();
        if (FStrmAddr == "")
        {
            FStrmAddr = pObj->STRM_SESN_NM.Trim();
        }
        if (FStrmAddr == "")
        {
            String pswd = "";
            if (pObj->WEB_CMRA_ID != "" && pObj->WEB_CMRA_PWD != "")
            {
                pswd = pObj->WEB_CMRA_ID + ":" + pObj->WEB_CMRA_PWD + "@";
            }
            FStrmAddr = "rtsp://" + pswd + pObj->WEB_CMRA_IP + "/profile1/media.smp";
            //FStrmAddr = "rtsp://" + pswd + pObj->WEB_CMRA_IP + "/profile2/media.smp";
        }

        if (FStrmAddr != "" && pObj->WEB_CMRA_IP != "")
        {
#if FFPLAYER
            FFPlayer1->AspectRatio = ChkFullScreen->Checked ? -1 : 0;
            FFPlayer1->TryOpen(FStrmAddr, PnlSamsung->Handle);
#endif
#if ACES
            AcesTechXPlayer21->URL = FStrmAddr;
            FStrmHandle = AcesTechXPlayer21->ConnectAsync();
            if (FStrmHandle > 0)
            {
            }
#endif

            FStrmUser = pObj->WEB_CMRA_ID;
            FStrmPswd = pObj->WEB_CMRA_PWD;
            FStrmHttp = "http://" + pObj->WEB_CMRA_IP;

            FStrmPlay = true;

            if (pObj->WEB_CMRA_PROTOCOL == "1")
            {
                PTZSpeed->Min = 1;
                PTZSpeed->Max = 100;
                PnlPTZ->Enabled = false;
                ConnectXnsDevice(pObj);
            }
            else
            {
                PTZSpeed->Min = 1;
                PTZSpeed->Max = 100;
                PnlPTZ->Enabled = true;
            }
        }
        else
        {
            FStrmHttp = "";
        }
    }
    catch(Exception &e)
    {
    }
}
//---------------------------------------------------------------------------

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

    try
    {
#if FFPLAYER
        if (FFPlayer1->ScreenHandle != NULL)
        {
            FFPlayer1->Stop(true);
            PostMessage(FFPlayer1->ScreenHandle, CM_INVALIDATE, 0, 0);
            UpdateWindow(FFPlayer1->ScreenHandle);
            //FFPlayer1->ScreenHandle = NULL;
        }
#endif
#if ACES
        if (FStrmHandle > 0)
        {
            AcesTechXPlayer21->Close();
        }
#endif

        if (m_hMediaSource)
        {
            // [ XNS ACTIVEX HELP ]
            // -----------------------------------------------------------------------
            // Stops receiving the stream data from the media source handle.
            // -----------------------------------------------------------------------
            if (m_bIsMediaPlay)
            {
                XnsSdkWindow1->Stop();
            }

            // Terminates transferring media stream data from the device. The media
            // stream data will be separated by hMediaSource
            // (i.e., phMediaSource of OpenMedia()).

            XnsSdkDevice1->CloseMedia(m_hDevice, m_hMediaSource);
        }

        // Disconnects from the device.
        XnsSdkDevice1->Disconnect(m_hDevice);

        m_hMediaSource = 0;
    	m_nControlId   = 0;
    	m_bIsMediaPlay = false;

    }
    catch(Exception &e)
    {
    }
    PnlSamsung->Caption = "Disconnected";
    PnlSamsung->Refresh();
    FStrmPlay = false;
}
//---------------------------------------------------------------------------

void __fastcall TVMS0500M::BtnImdFromDnldClick(TObject *Sender)
{
    //폼 즉시 다운로드
    String sTitle = cxLabel30->Caption;//"폼 즉시 다운로드";
    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);
        FRAMEVmsStateList1->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_pLOGIN->sUserId;
    String sCmdTime = Now().FormatString("yyyymmddhhnnss");

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

    memcpy(directCmd.CmdTime, AnsiString(sCmdTime).c_str(), INT_VMS_MAX_DATETIME); /* 명령수행시각 */
    memcpy(directCmd.OperId,  AnsiString(sCmdUser).c_str(), INT_VMS_MAX_OPER_ID);  /* 운영자 ID */

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

        directCmd.VMS_CTLR_NMBR[ii] = sVmsNmbr.ToIntDef(0);
    }
    directCmd.Count = (BYTE)nSelCnt;

    int result = CComm_VmsImmediateScenarioDnldReq(&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 (int ii = 0; ii < nSelCnt; ii++)
    {
        String sVmsNmbr = FVmsIds->Strings[ii];

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

    BtnImdFromDnld->Enabled = false;
    TmrCommand->Enabled = true;
}
//---------------------------------------------------------------------------

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

    String sTitle = cxLabel1->Caption;//"전광판/제어기 제어";
    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);
        FRAMEVmsStateList1->CxList->SetFocus();
        return;
    }

    int nCmdIdx;
    if (pBtnControl->Tag == 1)
    {
        nCmdIdx = vms_req_board_power_on;
        sMsg = cxLabel3->Caption + "\r\n" + cxLabel9->Caption;//"선택하신 VMS에 VMS 전광판 전원 ON 명령을 전송하시겠습니까?\r\n(통신상태에 따라 명령이 실행되지 않을 수 있습니다.)";
    }
    else
    {
        nCmdIdx = vms_req_board_power_off;
        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_pLOGIN->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)
            {
                VmsCtlrManager->InsVmsControlHs(sCmdTime, sVmsNmbr, sOprCode, sCmdValue, "1", sCmdUser);
                nOkCnt++;
            }
            else
            {
                VmsCtlrManager->InsVmsControlHs(sCmdTime, sVmsNmbr, sOprCode, sCmdValue, "0", sCmdUser);
            }
        }

        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 TVMS0500M::BtnResetClick(TObject *Sender)
{
    TcxButton *pBtnControl = (TcxButton*)Sender;

    String sTitle = cxLabel1->Caption;//"전광판/제어기 제어";
    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);
        FRAMEVmsStateList1->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_pLOGIN->sUserId;
    String sCmdTime = Now().FormatString("yyyymmddhhnnss");

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

        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);
            VmsReset.Mode          = (BYTE)pBtnControl->Tag;

            result = CComm_VmsResetReq(&VmsReset, MsgSeq);
            if (VERR_NONE == result)
            {
                VmsCtlrManager->InsVmsControlHs(sCmdTime, sVmsNmbr, "V03", "Reset", "1", sCmdUser);
                nOkCnt++;
            }
            else
            {
                VmsCtlrManager->InsVmsControlHs(sCmdTime, sVmsNmbr, "V03", "Reset", "0", sCmdUser);
            }
        }

        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 TVMS0500M::BtnBrghControlClick(TObject *Sender)
{
    TcxButton *pBtnControl = (TcxButton*)Sender;

    String sTitle = cxLabel1->Caption;//"전광판/제어기 제어";
    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);
        FRAMEVmsStateList1->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_pLOGIN->sUserId;
    String sCmdTime = Now().FormatString("yyyymmddhhnnss");

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

        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);
            VmsLuminance.BrghMode      = (BYTE)pBtnControl->Tag;

            VmsLuminance.BrghCurrStep = (BYTE)SeCurrBrgh->Value;
            VmsLuminance.BrghWeekStep = (BYTE)SeWeekBrgh->Value;
            VmsLuminance.BrghNghtStep = (BYTE)SeNghtBrgh->Value;

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

        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 TVMS0500M::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 TVMS0500M::FFPlayer1OpenFailed(TObject *Sender)
{
    //ErrorMsg("웹카메라에 연결할 수 없습니다.");
    //WebCamStop();
}
//---------------------------------------------------------------------------

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

void __fastcall TVMS0500M::BtnWebCamControlMouseDown(TObject *Sender, TMouseButton Button,
          TShiftState Shift, int X, int Y)
{
    TImageBtn *pBtn = (TImageBtn*)Sender;

    if (FSelVmsObj->WEB_CMRA_PROTOCOL == "1")
    {
        PtzControlSamsung_iPoliceMouseDown(pBtn->Tag);
    }
    else
    if (FSelVmsObj->WEB_CMRA_PROTOCOL == "2")
    {
        PtzControlHanwha_WisenetMouseDown(pBtn->Tag);
    }
}
//---------------------------------------------------------------------------

void __fastcall TVMS0500M::BtnWebCamControlMouseUp(TObject *Sender, TMouseButton Button,
          TShiftState Shift, int X, int Y)
{
    TImageBtn *pBtn = (TImageBtn*)Sender;

    if (FSelVmsObj->WEB_CMRA_PROTOCOL == "1")
    {
        PtzControlSamsung_iPoliceMouseUp(pBtn->Tag);
    }
    else
    if (FSelVmsObj->WEB_CMRA_PROTOCOL == "2")
    {
        PtzControlHanwha_WisenetMouseUp(pBtn->Tag);
    }
}
//---------------------------------------------------------------------------

bool __fastcall TVMS0500M::InitializeXnsDevice()
{
    String sLog;
	long nRet = XnsSdkDevice1->Initialize();
	if (nRet != ERR_SUCCESS && nRet != ERR_ALREADY_INITIALIZE)
	{
    	sLog.printf(L"Samsung XnsSdkDevice Initialize() fail: return=[%d](%s)\n", nRet, XnsSdkDevice1->GetErrorString(nRet));
        reMsg->Lines->Add(sLog.Trim());
        ShowMessage(sLog);
        return false;
	}

	nRet = XnsSdkWindow1->Initialize(NULL, NULL);
	if (nRet != ERR_SUCCESS && nRet != ERR_ALREADY_INITIALIZE)
	{
    	sLog.printf(L"Samsung XnsSdkWindow Initialize() fail: return=[%d](%s)\n", nRet, XnsSdkDevice1->GetErrorString(nRet));
        reMsg->Lines->Add(sLog.Trim());
        ShowMessage(sLog);
        return false;
	}

	long device_id = XnsSdkDevice1->CreateDeviceEx();
	m_hDevice = XnsSdkDevice1->GetDeviceHandle(device_id);
	if (m_hDevice == 0)
	{
		sLog = "CreateDevice() fail";
        reMsg->Lines->Add(sLog.Trim());
    	ShowMessage(sLog);
        return false;
	}

    return true;
}
//---------------------------------------------------------------------------
void __fastcall TVMS0500M::DestroyXnsDevice()
{
    try {
        if (m_hDevice)
        {
            // [ XNS ACTIVEX HELP ]
            // -----------------------------------------------------------------------
            // Stops receiving the stream data from the media source handle.
            // -----------------------------------------------------------------------
            if (m_hMediaSource)
            {
                XnsSdkWindow1->Stop();

                // Terminates transferring media stream data from the device.
                // The media stream data will be separated by hMediaSource
                // (i.e., phMediaSource of OpenMedia()).
                XnsSdkDevice1->CloseMedia(m_hDevice, m_hMediaSource);
            }

            // [ XNS ACTIVEX HELP ]
            // -----------------------------------------------------------------------
            // Returns the connection status of the device.
            // -----------------------------------------------------------------------
            if (XnsSdkDevice1->GetDeviceStatus(m_hDevice) == XDEVICE_STATUS_CONNECTED)
            {
                XnsSdkDevice1->Disconnect(m_hDevice);
            }

            // Cancels the memory space assigned for the device information by
            // CreateDevice(). The device should be disconnected from the application
            // before this function is called.
            XnsSdkDevice1->ReleaseDevice(m_hDevice);
        }
    }
    catch(Exception &e)
    {
    }
}
//---------------------------------------------------------------------------
bool __fastcall TVMS0500M::ConnectXnsDevice(TVmsCtlr *AObj)
{
    WideString sVendorName = (AObj->WEB_CMRA_CMPY == "") ? WideString("Samsung")    : WideString(AObj->WEB_CMRA_CMPY);
    WideString sModelName  = (AObj->WEB_CMRA_MDL  == "") ? WideString("SNP-3120VH") : WideString(AObj->WEB_CMRA_MDL);
    WideString sID         = (AObj->WEB_CMRA_ID   == "") ? WideString("admin")      : WideString(AObj->WEB_CMRA_ID);
    WideString sPass       = (AObj->WEB_CMRA_PWD  == "") ? WideString("4321")       : WideString(AObj->WEB_CMRA_PWD);
    WideString sIpAddress  = WideString(AObj->WEB_CMRA_IP);
    int        nPort       = 4520;

	XnsSdkDevice1->SetConnectionInfo(
		m_hDevice,					        // [in] Device handle
		sVendorName.Copy(),				    // [in] Fixed as 'Samsung'
		sModelName.Copy(),				    // [in] Name of model to connect to. The maximum length allowed is 126-byte.
		XADDRESS_IP, sIpAddress.Copy(),	    // [in] Address type, actual address according to addresstype.
		nPort, 0,					        // [in] Port number, port number for web access
		sID.Copy(), sPass.Copy()		    // [in] Login ID, password
		);

	long nRet = XnsSdkDevice1->ConnectNonBlock(
		m_hDevice,		// [in] Device handle
		true,			// [in] Flag to decide where to forcibly log in or not.
		false			// [in] If this value is 1, try to connect again.
		);
	if (nRet != ERR_SUCCESS)
	{
        String sLog;
    	sLog.printf(L"ConnectNonBlock() fail: errno=[%d](%s)\n", nRet, XnsSdkDevice1->GetErrorString(nRet));
        ShowMessage(sLog);
        return false;
	}

    return true;
}
//---------------------------------------------------------------------------
void __fastcall TVMS0500M::PtzControlXnsDevice(int nCommand)
{
	long ret;

    if (m_hDevice == 0 || m_nControlId == 0) return;

    int nPtzSpeed = PTZSpeed->Position;

	//WLOGD(_T("MoveCamera, command=[%d], speed=%d\n"), nCommand, m_nPtzSpeed);

// 	if( nCommand != XPTZ_STOP)
// 		m_ctrlXnsDevice.ControlPtz(m_hDevice, m_nControlId, XPTZ_STOP, 30);

	// Returns the capabilities of the control module.
	long bIsCap = XnsSdkDevice1->GetControlCapability(m_hDevice, m_nControlId, XCTL_CAP_PTZ_SPEED);

	// [ XNS ACTIVEX HELP ]
	// -----------------------------------------------------------------------
	// Moves the camera to the predefined PTZ position. This function is
	// valid as long as the application is receiving media stream from the
	// camera.
	// -----------------------------------------------------------------------
	//	Command			Value	Description
	// -----------------------------------------------------------------------
	//	XPTZ_UP			1		Tilt up
	//	XPTZ_DOWN		2		Tilt down
	//	XPTZ_LEFT		3		Pan left
	//	XPTZ_RIGHT		4		Pan right
	//	XPTZ_UPLEFT		5		Tilt up and pan left
	//	XPTZ_UPRIGHT	6		Tilt up and pan right
	//	XPTZ_DOWNLEFT	7		Tilt down and pan left
	//	XPTZ_DOWNRIGHT	8		Tilt down and pan right
	//	XPTZ_ZOOMIN		9		Zoom in
	//	XPTZ_ZOOMOUT	10		Zoom out
	//	XPTZ_STOP		11		Stop the PTZ moving
	//	XPTZ_FOCUS_NEAR	12		Focus near
	//	XPTZ_FOCUS_FAR	13		Focus far
	//	XPTZ_FOCUS_STOP	14		Stop focus moving
	//	XPTZ_IRIS_OPEN	15		Open iris
	//	XPTZ_IRIS_CLOSE	16		Close iris
	// -----------------------------------------------------------------------
	if (bIsCap)
	{
		ret = XnsSdkDevice1->ControlPtz(
			m_hDevice,		// [in] Device handle. This value is returned from CreateDevice().
			m_nControlId,	// [in] Control ID.
			nCommand,		// [in] PTZ command
			nPtzSpeed		// [in] If nPtzCommand is a speed-related command,
							// this value indicates the PTZ operation speed.
							// (1~100) This value is valid only if the camera
							// supports the XCTL_CAP_PTZ_SPEED capability.
			);
	}
	else
    {
		ret = XnsSdkDevice1->ControlPtz(m_hDevice, m_nControlId, nCommand, 30);
    }

	if (ret != ERR_SUCCESS)
	{
        String sErr;
		sErr.printf(L"ControlPtz() fail:: error=[%d](%s)", ret, XnsSdkDevice1->GetErrorString(ret));
        reMsg->Lines->Add(sErr);
	}
}
//---------------------------------------------------------------------------

void __fastcall TVMS0500M::PtzControlSamsung_iPoliceMouseDown(int ATag)
{
    int nCmd = ATag;

    if (ATag == 13) nCmd = PTZ_FOCUS_NEAR;
    if (ATag == 12) nCmd = PTZ_FOCUS_FAR;

    if (ATag == 3) nCmd = XPTZ_RIGHT;
    if (ATag == 4) nCmd = XPTZ_LEFT;

    //PTZ Control
	//	XPTZ_UP			1		Tilt up
	//	XPTZ_DOWN		2		Tilt down
	//	XPTZ_LEFT		3		Pan left
	//	XPTZ_RIGHT		4		Pan right
	//	XPTZ_UPLEFT		5		Tilt up and pan left
	//	XPTZ_UPRIGHT	6		Tilt up and pan right
	//	XPTZ_DOWNLEFT	7		Tilt down and pan left
	//	XPTZ_DOWNRIGHT	8		Tilt down and pan right
	//	XPTZ_ZOOMIN		9		Zoom in
	//	XPTZ_ZOOMOUT	10		Zoom out
	//	XPTZ_STOP		11		Stop the PTZ moving
	//	XPTZ_FOCUS_NEAR	12		Focus near
	//	XPTZ_FOCUS_FAR	13		Focus far
	//	XPTZ_FOCUS_STOP	14		Stop focus moving
	//	XPTZ_IRIS_OPEN	15		Open iris
	//	XPTZ_IRIS_CLOSE	16		Close iris

    try
    {
        //	PTZ_FOCUS_NEAR	12		Focus near
        //	PTZ_FOCUS_FAR	13		Focus far
        //	PTZ_FOCUS_STOP	14		Stop focus moving
        if (nCmd == 0)
        {
        }
        else
        {
            PtzControlXnsDevice(nCmd);
        }
    }
    catch(...) {}
}
//---------------------------------------------------------------------------
void __fastcall TVMS0500M::PtzControlSamsung_iPoliceMouseUp(int ATag)
{
    int nCmd = ATag;

    //	PTZ_FOCUS_NEAR	12		Focus near
    //	PTZ_FOCUS_FAR	13		Focus far
    //	PTZ_FOCUS_STOP	14		Stop focus moving

    if (ATag == 13) nCmd = PTZ_FOCUS_NEAR;
    if (ATag == 12) nCmd = PTZ_FOCUS_FAR;

    if (nCmd == PTZ_FOCUS_NEAR || nCmd == PTZ_FOCUS_FAR)
    {
        PtzControlXnsDevice(PTZ_FOCUS_STOP);
    }
    else if (nCmd == 0)
    {
    }
    else
    {
        PtzControlXnsDevice(PTZ_STOP);
    }
}
//---------------------------------------------------------------------------


void __fastcall TVMS0500M::PtzControlHanwha_WisenetMouseDown(int ATag)
{
    // PANControl
    if (!FStrmPlay) return;
    if (!FSelVmsObj) return;
    if (FSelVmsObj->WEB_CMRA_IP.Trim() == "") return;

    FStrmUser = FSelVmsObj->WEB_CMRA_ID;
    FStrmPswd = FSelVmsObj->WEB_CMRA_PWD;
    FStrmHttp = "http://" + FSelVmsObj->WEB_CMRA_IP;

    String sPTZSpeed = String(PTZSpeed->Position);
    try
    {
        String sCmdHtml = "";

        switch(ATag)
        {
        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;
        }

        if (sCmdHtml == "") return;

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

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

void __fastcall TVMS0500M::PtzControlHanwha_WisenetMouseUp(int ATag)
{
    // PANControl Stop
    if (!FStrmPlay) return;
    if (!FSelVmsObj) return;
    if (FSelVmsObj->WEB_CMRA_IP.Trim() == "") return;

    FStrmUser = FSelVmsObj->WEB_CMRA_ID;
    FStrmPswd = FSelVmsObj->WEB_CMRA_PWD;
    FStrmHttp = "http://" + FSelVmsObj->WEB_CMRA_IP;

    String sPTZSpeed = String(PTZSpeed->Position);
    try
    {
        String sCmdHtml = "";

        switch(ATag)
        {
            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;
        }

        if (sCmdHtml == "") return;

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

void __fastcall TVMS0500M::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 TVMS0500M::XnsSdkDevice1ConnectFailed(TObject *Sender, long nDeviceID, long nControlID)
{
    String sDeviceID  = String(nDeviceID);
    String sControlID = String(nControlID);
    String sLog = "Connect Failed: " + sDeviceID + "  " + sControlID;

    reMsg->Lines->Add(sLog);
}
//---------------------------------------------------------------------------

void __fastcall TVMS0500M::XnsSdkDevice1DeviceStatusChanged(TObject *Sender, long nDeviceID, long nErrorCode, long nDeviceStatus,
          long nHddCondition)
{
    String sDeviceID     = String(nDeviceID);
    String sDeviceStatus = String(nDeviceStatus);
    String sErrorCode    = String(nErrorCode);
    String sErrorDesc;

    sErrorDesc.printf(L"%s", XnsSdkDevice1->GetErrorString(nErrorCode));

    reMsg->Lines->Add("Event: " + sDeviceID + "  " + sDeviceStatus + "  " + sErrorDesc);

	if (nErrorCode != ERR_SUCCESS || nDeviceStatus != 1)
	{
		return;
	}

	if (m_hMediaSource)
	{
		reMsg->Lines->Add("Media stream was already opend\n");
		return;
	}

    int xret = XnsSdkDevice1->GetControlType(m_hDevice, 1);
    reMsg->Lines->Add("Open media stream: " + String(xret));

    if (nErrorCode == ERR_SUCCESS && nDeviceStatus == 1)
    {
        reMsg->Lines->Add("Connected...");

    	bool bIsPtzSupport = XnsSdkDevice1->GetControlCapability(m_hDevice, 2, XCTL_CAP_PTZ_PAN);
        PnlPTZ->Enabled = OpenXnsDevice();
    }
    else if (nErrorCode == ERR_SUCCESS && nDeviceStatus == 0)
    {
        reMsg->Lines->Add("DisConnected...");
    }
}
//---------------------------------------------------------------------------
bool __fastcall TVMS0500M::OpenXnsDevice()
{
	// [ XNS ACTIVEX HELP ]
	// -----------------------------------------------------------------------
	// Returns the type of control module corresponding to the control ID.
	//
	// < DVR control module structure >
	// +------------------------------------------------------------
	// Control Module(Device, 1) ----------------- Control ID : 1
	// |---- Control Module(Camera, 1) ----------- Control ID : 2
	// |---- Control Module(Camera, 2) ----------- Control ID : 3
	// |---- Control Module(Camera, 3) ----------- Control ID : 4
	// |---- ....
	// |---- Control Module(Camera,16) ----------- Control ID : 17
	// |---- Control Module(Sensor-in, 1) -------- Control ID : 18
	// |---- ...
	// |---- Control Module(Sensor-in, 16) ------- Control ID : 34
	// |---- Control Module(Digital-out, 1) ------ Control ID : 35
	// |---- ...
	// |---- Control Module(Digital-out, 4) ------ Control ID : 38
	// +------------------------------------------------------------
	//
	// < Network Camera control module structure >
	// +------------------------------------------------------------
	// Control Module(Device, 1) ----------------- Control ID : 1
	// |---- Control Module(Camera, 1) ----------- Control ID : 2
	//       |--- Control Module(Video, 1) ------- Control ID : 3
	//       |--- Control Module(Video, 2) ------- Control ID : 4
	//       |--- ...
	//       |--- Control Module(Video, 10) ------ Control ID : 12
	//       |--- Control Module(Sensor-in, 1) --- Control ID : 13
	//       |--- Control Module(Digital-out, 1) - Control ID : 14
	// +------------------------------------------------------------
	// -----------------------------------------------------------------------

	if (XnsSdkDevice1->GetControlType(m_hDevice, 1) & XCTL_DVR)
	{
		// Returns the number of control modules. The application can get
		// the number of a specific type of control modules, and can get
		// also the whole number of video recorders or cameras.
		// DVR control id is start with 2
		int nCount = XnsSdkDevice1->GetControlCount(m_hDevice, XCTL_CAMERA);
		for(int i=0; i<nCount ; i++)
		{
			// Returns the capabilities of the control module.
			if (XnsSdkDevice1->GetControlCapability(m_hDevice, i+2, XCTL_CAP_LIVE) &&
				// Gets the status of the control module.
				// DVR control id is start with 2
				XnsSdkDevice1->GetControlStatus(m_hDevice, i+2, 1))
			{
				// When called, it will start getting media streams from the
				// device. The receiving media streams will, then, be
				// forwarded to the XnsSdkWindow component that will play
				// the streams after decoding. phMediaSource is needed to
				// link the stream data with XnsSdkWindow.
				// The value can be obtained from a parameter (out-parameter)
				// of OpenMedia(). When XnsSdkWindow receives this value,
				// it can get stream data from the device.
				// phMediaSource is also used for controlling playback of
				// multimedia files. As a result, the application should keep this value at all times.
                XnsSdkDevice1->OpenMedia(
					m_hDevice,			// [in] Device handle. This value is returned from CreateDevice().
					i+2,				// [in] Control ID of video control module.
					MEDIA_TYPE_LIVE,	// [in] Media type.
					0,					// [in] Play start time. Format: 4-byte time_t.
					0,					// [in] Play end time. Format: 4-byte time_t.
					&m_hMediaSource		// [out] Media stream ID. This is needed for controlling
										//       the media stream and also used as a parameter
										//       of XnsSdkWindow::Start().
					);

				// Adds the media source handle to XnsSdkWindow.
				// The media source handle is created by XnsSdkDevice.
				// If the application calls XnsSdkDevice::OpenMedia(),
				// it will receive media stream from the device and return the MediaSource
				// handle. The application uses uses Start() to forward the mediasource
				// handle to XnsSdkWindow so that XnsSdkWindow can obtain stream data.
				XnsSdkWindow1->Start(m_hMediaSource);

				m_nControlId = i+2;
                m_bIsMediaPlay = true;
				//WLOGD(_T("DVR TYPE,  control id = %d\n"), m_nControlId);
				return true;
			}
		}
	}
	else if (XnsSdkDevice1->GetControlType(m_hDevice, 1) & (XCTL_NETCAM |XCTL_ENCODER))
	{
		int nCount = XnsSdkDevice1->GetControlCount(m_hDevice, XCTL_VIDEO);
		if (nCount == 0)
		{
        	nCount = XnsSdkDevice1->GetControlCount(m_hDevice, XCTL_CAMERA);
        }

		for(int i=0; i<nCount ; i++)
		{
			// Network camera and encoder control id is start with 3
			if (XnsSdkDevice1->GetControlCapability(m_hDevice, i+3, XCTL_CAP_LIVE) &&
				XnsSdkDevice1->GetControlStatus(m_hDevice, i+3, 1))
			{
				XnsSdkDevice1->OpenMedia(m_hDevice, i+3, MEDIA_TYPE_LIVE, 0, 0, &m_hMediaSource);
				XnsSdkWindow1->Start(m_hMediaSource);

				m_nControlId = i+3;
                m_bIsMediaPlay = true;
				//WLOGD(_T("NETCAM or ENCODER TYPE,  control id = %d\n"), m_nControlId);
				return true;
			}
		}
	}
	//WLOGD(_T("No valid device.."));

    return false;
}
//---------------------------------------------------------------------------

