/****************************************************************************
 * @source      : 
 * @description : 
 ****************************************************************************
 * DATE         AUTHOR    DESCRIPTION
 * --------------------------------------------------------------------------
 * 2016/07/24   정승호    최초작성
 *
 ****************************************************************************/
//---------------------------------------------------------------------------

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

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

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

    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;

    cxTabSheet2->TabVisible = false;
    cxTabSheet2->Visible = false;
    cxTabSheet1->TabVisible = false;
    cxTabSheet1->Visible = false;

    PgControl->ActivePageIndex = 0;

    FVmsIds = new TStringList();

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

    FCtrlTab = NULL;

    PgCam->Properties->HideTabs = true;

    PnlCamera->ParentColor = false;

    FInitPlayer = false;

    XnsSdkDevice1->Left = 1000;
    XnsSdkWindow1->Parent = PnlSamsung;
    XnsSdkWindow1->Align  = alClient;

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

    FCamUrl = "";
    fJSExec = NULL;
}
//---------------------------------------------------------------------------

bool __fastcall TVMS0500M::ExecScript(String AScript)
{
#if 0
    if (FHtmlCompleted == false) return false;

    try
    {
        if (fJSExec) ((TJSExec*)fJSExec)->RunJSFn(AScript);
    }
    catch(Exception &exception)
    {
        return false;
    }
#endif
    return true;
}
//---------------------------------------------------------------------------

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

        FInitPlayer = false;
        ReleaseWebCamera();

        //::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();

    //BtnNwkPing->Caption = "Network Ping Test";
    //BtnNwkPing->Hint = "VMS Controller and Web Camera Ping Test";
    //BtnNwkPingClear->Caption = "Initialize";
    //BtnNwkPingClear->Hint = "Ping List Initialize";
}
//---------------------------------------------------------------------------

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

    FInitPlayer = SetupWebCamera();

    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(String(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;

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

            cxDisplayTimeOff->EditValue = sPowerOffTime;
        }
        Se01->Value = FSelVmsObj->WSTATE.ScheduledMessageOperatingTime;/* 필수 계획된 메시지의 동작시간(초) */
        Se02->Value = FSelVmsObj->WSTATE.ModuleOperatingTemperature;   /* 필수 모듈 전원이 꺼지는 온도값(℃) */
        Se03->Value = FSelVmsObj->WSTATE.FanOperatingTemperature;      /* 필수 Fan 동작 기준 온도값(℃) */
        Se04->Value = FSelVmsObj->WSTATE.HeaterOperatingTemperature;   /* 필수 Heater 동작 기준 온도값(℃) */
        Se05->Value = FSelVmsObj->WSTATE.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;
#endif
    }
    catch(Exception &e)
    {
    }

    try
    {
        ShowVmsWebCam(String(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->WSTATE.Comm == vms_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_board_power_on;
        sMsg = cxLabel3->Caption + "\r\n" + cxLabel9->Caption;//"선택하신 VMS에 VMS 전광판 전원 ON 명령을 전송하시겠습니까?\r\n(통신상태에 따라 명령이 실행되지 않을 수 있습니다.)";
    }
    else
    if (RdbOff->Checked)
    {
        nCmdIdx = vms_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_board_power_on || nCmdIdx == vms_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.VmsId,   AnsiString(sVmsNmbr).c_str(), INT_VMS_MAX_ID);       /* VMS 제어기 번호 */
            memcpy(VmsPowerCtl.OperId,  AnsiString(sCmdUser).c_str(), INT_VMS_MAX_OPER_ID);  /* 운영자 ID */
            VmsPowerCtl.Command = (BYTE)nCmdIdx;                                            /* 제어 구분, 0:켜짐 1:꺼짐 */

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

            result = CComm_VmsPowerControlReq(&VmsPowerCtl, MsgSeq);
            if (VERR_NONE == result)
            {
                VmsManager->InsVmsControlHs(sCmdTime, sVmsNmbr, sOprCode, sCmdValue, "1", sCmdUser);
                nOkCnt++;
            }
            else
            {
                VmsManager->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.VmsId,   AnsiString(sVmsNmbr).c_str(), INT_VMS_MAX_ID);       /* VMS 제어기 번호 */
            memcpy(VmsReset.OperId,  AnsiString(sCmdUser).c_str(), INT_VMS_MAX_OPER_ID);  /* 운영자 ID */

            result = CComm_VmsResetReq(&VmsReset, MsgSeq);
            if (VERR_NONE == result)
            {
                VmsManager->InsVmsControlHs(sCmdTime, sVmsNmbr, "V03", "Reset", "1", sCmdUser);
                nOkCnt++;
            }
            else
            {
                VmsManager->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.VmsId,   AnsiString(sVmsNmbr).c_str(), INT_VMS_MAX_ID);       /* VMS 제어기 번호 */
            memcpy(VmsLuminance.OperId,  AnsiString(sCmdUser).c_str(), INT_VMS_MAX_OPER_ID);  /* 운영자 ID */
            VmsLuminance.Luminance = (BYTE)SeLuminance->Value;

            result = CComm_VmsLuminanceReq(&VmsLuminance, MsgSeq);
            if (VERR_NONE == result)
            {
                VmsManager->InsVmsControlHs(sCmdTime, sVmsNmbr, "V07", sCmdValue, "1", sCmdUser);
                nOkCnt++;
            }
            else
            {
                VmsManager->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 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)
        {
            VmsManager->InsVmsControlHs(sCmdTime, sVmsNmbr, "V04", sCmdValue, "1", sCmdUser);
            nOkCnt++;

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

            if (UpdateVmsParam(sVmsNmbr, (void*)&VmsPara))
            {
                TVmsCtlr *pObj = VmsManager->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->WSTATE.ScheduledMessageOperatingTime = pObj->VMS_PHSE_CHNG_CYCL;    /* 필수 계획된 메시지의 동작시간(초) */
                    pObj->WSTATE.ModuleOperatingTemperature    = pObj->VMS_CMNC_ERR_BASS_VAL; /* 필수 모듈 전원이 꺼지는 온도값(℃) */
                    pObj->WSTATE.FanOperatingTemperature       = pObj->FAN_MTNS_TMPR;         /* 필수 Fan 동작 기준 온도값(℃) */
                    pObj->WSTATE.HeaterOperatingTemperature    = pObj->HETR_MTNS_TMPR;        /* 필수 Heater 동작 기준 온도값(℃) */
                    pObj->WSTATE.ModuleBasicFailureRate        = pObj->VMS_MODL_ERR_RATE;     /* 선택 모듈 장애율 (한 개의 모듈을 장애로 처리하기 위한 픽셀의 백분율값) */
#endif
                }
            }
        }
        else
        {
            VmsManager->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);
}
//---------------------------------------------------------------------------

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;

    sQry = "UPDATE TB_VMS_CTLR                   \r\n"
           "   SET VMS_PHSE_CHNG_CYCL    = :p01, \r\n"
           "       VMS_CMNC_ERR_BASS_VAL = :p02, \r\n"
           "       FAN_MTNS_TMPR         = :p03, \r\n"
           "       HETR_MTNS_TMPR        = :p04, \r\n"
           "       VMS_MODL_ERR_RATE     = :p05  \r\n"
           " WHERE VMS_CTLR_NMBR = :p06          \r\n";
    try
    {
        try
        {
            pADO = new TADOQuery(NULL);
			pADO->Close();
            pADO->Connection = ITSDb_GetConnection();
			pADO->SQL->Clear();
			pADO->SQL->Text = sQry;
            pADO->Parameters->ParamByName("p01")->Value = pReq->SchMsgTime;
            pADO->Parameters->ParamByName("p02")->Value = pReq->ModuleTemp;
            pADO->Parameters->ParamByName("p03")->Value = pReq->FanTemp;
            pADO->Parameters->ParamByName("p04")->Value = pReq->HeaterTemp;
            pADO->Parameters->ParamByName("p05")->Value = pReq->ModuleFail;
            pADO->Parameters->ParamByName("p06")->Value = AVmsNmbr;
			nCnt = pADO->ExecSQL();
        }
        catch(EDatabaseError &E)
        {
            DBERRORLOG("VMS Parameter Save", String(E.ClassName()), E.Message, sQry);
            throw Exception(String(E.ClassName()) + E.Message);
        }
        catch(Exception &e)
        {
            DBERRORLOG("VMS Parameter Save", String(e.ClassName()), e.Message, sQry);
            throw Exception(String(e.ClassName()) + e.Message);
        }
    }
    __finally
    {
        if (pADO)
        {
            pADO->Close();
            delete pADO;
        }
    }

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

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   = :p01, \r\n"
           "       PANL_OFF_TIME  = :p02, \r\n"
           "       LAST_CRPR_NMBR = :p03, \r\n"
           "       LAST_CRCT_DT   = :p04  \r\n"
           " WHERE VMS_CTLR_NMBR  = :p05  \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 = PANL_ON_TIME;
                pADO->Parameters->ParamByName("p02")->Value = PANL_OFF_TIME;
                pADO->Parameters->ParamByName("p03")->Value = LAST_CRPR_NMBR;
                pADO->Parameters->ParamByName("p04")->Value = LAST_CRCT_DT;
                pADO->Parameters->ParamByName("p05")->Value = sVmsNmbr;
                pADO->ExecSQL();
                nOkCnt++;

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

    //sMsg = String(nSelCnt) + " 개의 선택 VMS 중에 " + String(nOkCnt) + " 개의 VMS로 전광판 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];

        VmsManager->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)
{
    //전광판ON/OFF시각설정
    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 = VmsManager->FLists.Find(sVmsNmbr);
                if (pObj)
                {
                    pObj->OPER_MODE = OPER_MODE;
                    if      (pObj->OPER_MODE == "A") pObj->WSTATE.OprMode = 'A';
                    else if (pObj->OPER_MODE == "B") pObj->WSTATE.OprMode = 'B';
                    else                             pObj->WSTATE.OprMode = 'F';
                }
                else continue;

                //memcpy(VmsMode.VmsId,   AnsiString("ALL").c_str(),          INT_VMS_MAX_ID);       /* VMS 제어기 번호 */
                memcpy(VmsMode.Unit[VmsMode.Count].VmsId, AnsiString(sVmsNmbr).c_str(), INT_VMS_MAX_ID);       /* 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_MAX_VMS_MODE)
                {
                    CComm_VmsModeReq(&VmsMode, MsgSeq);
                }
            }
            if (VmsMode.Count > 0)
            {
                CComm_VmsModeReq(&VmsMode, MsgSeq);
            }
        }
        catch(EDatabaseError &E)
        {
            DBERRORLOG("VMS Config Save", String(E.ClassName()), E.Message, sQry);
            throw Exception(String(E.ClassName()) + E.Message);
        }
        catch(Exception &e)
        {
            DBERRORLOG("VMS Config Save", String(e.ClassName()), e.Message, sQry);
            throw Exception(String(e.ClassName()) + e.Message);
        }
    }
    __finally
    {
        if (pADO)
        {
            pADO->Close();
            delete pADO;
        }
    }

    //sMsg = String(nSelCnt) + " 개의 선택 VMS 중에 " + String(nOkCnt) + " 개의 VMS 운영모드를 변경하였습니다.";
    sMsg = String(nSelCnt) + " " + cxLabel7->Caption + " " + String(nOkCnt) + " " + 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];

        VmsManager->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();
            ShellExecute(NULL, NULL, sUrl.c_str(), NULL, NULL, 0);
        }
    }
}
//---------------------------------------------------------------------------

void __fastcall TVMS0500M::OpenUrl(bool AOpen)
{
}
//---------------------------------------------------------------------------

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)
        {
            VmsManager->InsVmsControlHs(sCmdTime, sVmsNmbr, sCmd, sCmdValue, "1", sCmdUser);
            nOkCnt++;
        }
        else
        {
            VmsManager->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::controlCamera(int ACommand)
{
    if (FInitPlayer)
    {
        CameraControl(ACommand, PTZSpeed->Position);
    }
}
//---------------------------------------------------------------------------


void __fastcall TVMS0500M::BtnUpLeftMouseDown(TObject *Sender, TMouseButton Button,
          TShiftState Shift, int X, int Y)
{
    //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
    {
        TImageBtn *pBtn = (TImageBtn*)Sender;
        //	PTZ_FOCUS_NEAR	12		Focus near
        //	PTZ_FOCUS_FAR	13		Focus far
        //	PTZ_FOCUS_STOP	14		Stop focus moving
        if (pBtn->Tag == 0)
        {
        }
        else
        {
            controlCamera((int)pBtn->Tag);
        }
    }
    catch(...) {}
}
//---------------------------------------------------------------------------

void __fastcall TVMS0500M::BtnUpLeftMouseUp(TObject *Sender, TMouseButton Button,
          TShiftState Shift, int X, int Y)
{
    //PTZ Control Stop
    try
    {
        TImageBtn *pBtn = (TImageBtn*)Sender;
        //	PTZ_FOCUS_NEAR	12		Focus near
        //	PTZ_FOCUS_FAR	13		Focus far
        //	PTZ_FOCUS_STOP	14		Stop focus moving
        if (pBtn->Tag == PTZ_FOCUS_NEAR || pBtn->Tag == PTZ_FOCUS_FAR)
        {
            controlCamera(PTZ_FOCUS_STOP);
        }
        else if (pBtn->Tag == 0)
        {
        }
        else
        {
            controlCamera(PTZ_STOP);
        }
    }
    catch(...) {}
}
//---------------------------------------------------------------------------

void __fastcall TVMS0500M::ShowVmsWebCam(String AVmsNo)
{
    TVmsCtlr *pObj = VmsManager->FLists.Find(AVmsNo);
    if (!pObj) return;

    if (FInitPlayer)
    {
#if 0
        Play(pObj->VMS_CTLR_ID,
             pObj->VMS_NM,
             pObj->WEB_CMRA_IP,
             pObj->WEB_CMRA_PORT,
             pObj->WEB_CMRA_ID,
             pObj->WEB_CMRA_PWD,
             pObj->WEB_CMRA_CMPY,
             pObj->WEB_CMRA_MDL);
#endif
    }
}
//---------------------------------------------------------------------------

void __fastcall TVMS0500M::BtnParamSettingClick(TObject *Sender)
{
    //제어기함체환경설정
    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)
        {
            VmsManager->InsVmsControlHs(sCmdTime, sVmsNmbr, "V04", sCmdValue, "1", sCmdUser);
            nOkCnt++;

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

            if (UpdateVmsParam2(sVmsNmbr, (void*)&VmsPara))
            {
                TVmsCtlr *pObj = VmsManager->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->WSTATE.ScheduledMessageOperatingTime = pObj->DEF_PHSE_CHNG_CYCL;    /* 필수 계획된 메시지의 동작시간(초) */
                    //pObj->WSTATE.ModuleOperatingTemperature    = pObj->VMS_CMNC_ERR_BASS_VAL; /* 필수 모듈 전원이 꺼지는 온도값(℃) */
                    pObj->WSTATE.ModuleBasicFailureRate        = pObj->VMS_MODL_ERR_RATE;     /* 선택 모듈 장애율 (한 개의 모듈을 장애로 처리하기 위한 픽셀의 백분율값) */
#endif
                }
            }
        }
        else
        {
            VmsManager->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);
}
//---------------------------------------------------------------------------
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"
           "       DEF_PHSE_CHNG_CYCL    = :p09, \r\n"
           "       PANL_ON_TIME          = :p10, \r\n"
           "       PANL_OFF_TIME         = :p11  \r\n"
           " WHERE VMS_CTLR_NMBR = :p01          \r\n";

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

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

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

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

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 = VmsManager->FLists.Find(sVmsNmbr);
                if (pObj)
                {
                    //pObj->VMS_PHSE_CHNG_CYCL = VMS_PHSE_CHNG_CYCL;
                }
            }
        }
        catch(EDatabaseError &E)
        {
            DBERRORLOG("VMS Config Save", String(E.ClassName()), E.Message, sQry);
            throw Exception(String(E.ClassName()) + E.Message);
        }
        catch(Exception &e)
        {
            DBERRORLOG("VMS Config Save", String(e.ClassName()), e.Message, sQry);
            throw Exception(String(e.ClassName()) + e.Message);
        }
    }
    __finally
    {
        if (pADO)
        {
            pADO->Close();
            delete pADO;
        }
    }

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

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

        VmsManager->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_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)
    {
        //VmsManager->InsVmsControlHs(sCmdTime, sVmsNmbr, "V10", "Download", "1", sCmdUser);
    }
    else
    {
        //VmsManager->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, VmsManager->FLists)
    {
        String sVmsNmbr = String(pObj->VMS_CTLR_NMBR);

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

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

void __fastcall TVMS0500M::TmrCommandTimer(TObject *Sender)
{
    TmrCommand->Enabled = false;
    BtnMsgImmediateDownload->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;
    try
    {
        int nRow;
        TvPing->BeginUpdate();
        pGDC->BeginUpdate();

        VmsManager->FLists.Lock();

        FOR_STL(TVmsCtlr*, pObj, VmsManager->FLists)
        {
            if (pObj->DEL_YN == "Y") continue;

            nRow = pGDC->AppendRecord();

            if (pObj->WSTATE.Comm == vms_normal) pGDC->Values[nRow][ColumnSel->Index] = false;
            else                                 pGDC->Values[nRow][ColumnSel->Index] = true;

            pGDC->Values[nRow][Col01->Index] = String(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
    {
        VmsManager->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->WSTATE.Comm == vms_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::XnsSdkDevice1ConnectFailed(TObject *Sender, long nWidth,
          long nHeight)
{
    FCaption = FCaption + " - Connect Failed.";
    ErrorMsg(FCaption);
}
//---------------------------------------------------------------------------

void __fastcall TVMS0500M::XnsSdkDevice1DeviceStatusChanged(TObject *Sender, long nDeviceID,
          long nErrorCode, long nDeviceStatus, long nHddCondition)
{
	if (nErrorCode != ERR_SUCCESS || nDeviceStatus != 1)
	{
        //ErrorMsg("Device Status Change");
		return;
	}

    //if (nErrorCode == ERR_SUCCESS && nDeviceStatus == 1)
    {
        FCaption = FId + ": " + FLoc;

        String sId   = FId;
        String sName = FLoc;

#if 1
        XnsSdkWindow1->SetOSDOnOff(OSD_ALL, false);
        XnsSdkWindow1->SetOSDOnOff(OSD_TIME1|OSD_IPS, true);

        XnsSdkWindow1->SetCustomOSDOnOff(false);
        WideString sOsdText = sName;
        XnsSdkWindow1->SetCustomOSD(sOsdText.Detach(), 1, 1, 255,255,255);
        XnsSdkWindow1->SetCustomOSDOnOff(true);

        XnsSdkWindow1->SetOSDOnOff(OSD_TIME1|OSD_IPS, true);
#endif

        OpenWebCamera();
    }
}
//---------------------------------------------------------------------------

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();

    //Application->MessageBox(AErrMsg.c_str(), Caption.c_str(), MB_OK|MB_ICONERROR|MB_APPLMODAL);
}
//---------------------------------------------------------------------------

bool __fastcall TVMS0500M::SetupWebCamera()
{
    if (FInitPlayer)
        return true;

    String sErrMsg;
	long nRet = XnsSdkDevice1->Initialize();
	if (nRet != ERR_SUCCESS && nRet != ERR_ALREADY_INITIALIZE)
	{
    	sErrMsg.printf(L"Samsung XnsSdkDevice1 Initialize() failed.\r\nreturn=[%d](%s)\n", nRet, XnsSdkDevice1->GetErrorString(nRet));
        ErrorMsg(sErrMsg);
        return false;
	}

	nRet = XnsSdkWindow1->Initialize(NULL, NULL);
	if (nRet != ERR_SUCCESS && nRet != ERR_ALREADY_INITIALIZE)
	{
    	sErrMsg.printf(L"Samsung XnsSdkWindow1 Initialize() failed.\r\nreturn=[%d](%s)\n", nRet, XnsSdkDevice1->GetErrorString(nRet));
        ErrorMsg(sErrMsg);
        return false;
	}

	m_lDeviceId = XnsSdkDevice1->CreateDeviceEx();
	m_hDevice = XnsSdkDevice1->GetDeviceHandle(m_lDeviceId);
	if (m_hDevice == 0)
	{
		sErrMsg = "CreateDevice() failed.";
    	sErrMsg.printf(L"Samsung XnsSdkDevice1 GetDeviceHandle() failed.\r\nreturn=[%d](%s)\n", nRet, XnsSdkDevice1->GetErrorString(nRet));
        ErrorMsg(sErrMsg);
        return false;
	}

    FInitPlayer = true;
    return FInitPlayer;
}
//---------------------------------------------------------------------------

void __fastcall TVMS0500M::WebCamPlay()
{
    try
    {
        Caption = FId + ": " + FLoc;

        DisconnectWebCamera();
        ConnectWebCamera();
    }
    catch(...)
    {
    }
}
//---------------------------------------------------------------------------

void __fastcall TVMS0500M::WebCamStop()
{
    try {
        DisconnectWebCamera();
    } catch(...) {}
}
//---------------------------------------------------------------------------

void __fastcall TVMS0500M::ReleaseWebCamera()
{
	if (m_hDevice != 0)
    {
		if (m_hMediaSource)
		{
			XnsSdkWindow1->Stop();
			XnsSdkDevice1->CloseMedia(m_hDevice, m_hMediaSource);
		}
		if (XnsSdkDevice1->GetDeviceStatus(m_hDevice) == XDEVICE_STATUS_CONNECTED)
		{
			XnsSdkDevice1->Disconnect(m_hDevice);
		}
    	XnsSdkDevice1->ReleaseDevice(m_hDevice);
        m_hDevice = 0;
    }
}
//---------------------------------------------------------------------------

bool __fastcall TVMS0500M::ConnectWebCamera()
{
    bool bConnect = true;

	XnsSdkDevice1->SetConnectionInfo(
		m_hDevice,					            // [in] Device handle
		FDefModel.Detach(),				        // [in] Fixed as 'Samsung'
		FModelName.Detach(),				    // [in] Name of model to connect to. The maximum length allowed is 126-byte.
		XADDRESS_IP, FIpAddress.Detach(),	    // [in] Address type, actual address according to addresstype.
		FPort, 0,					            // [in] Port number, port number for web access
		FConnId.Detach(), FConnPass.Detach()    // [in] Login ID, password
		);

	long nRet = XnsSdkDevice1->ConnectNonBlock(
		m_hDevice,		// [in] Device handle
		false,			// [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 sErrMsg;
    	sErrMsg.printf(L"XnsSdkDevice1 ConnectNonBlock() failed.\r\nerrno=[%d](%s)\n", nRet, XnsSdkDevice1->GetErrorString(nRet));
        ErrorMsg(sErrMsg);
        bConnect = false;
	}

    return bConnect;
}
//---------------------------------------------------------------------------

bool __fastcall TVMS0500M::OpenWebCamera()
{
    XnsSdkDevice1->OpenMedia(m_hDevice, 3, MEDIA_TYPE_LIVE, 0, 0, &m_hMediaSource);
    XnsSdkWindow1->Start(m_hMediaSource);

    m_nControlId = 3;
    m_bIsMediaPlay = true;
    return true;
}
//---------------------------------------------------------------------------

void __fastcall TVMS0500M::DisconnectWebCamera()
{
    if (m_hDevice == 0) return;

	CloseWebCamera();

	// Disconnects from the device.
    if (XnsSdkDevice1->GetDeviceStatus(m_hDevice) == XDEVICE_STATUS_CONNECTED)
    {
        XnsSdkDevice1->Disconnect(m_hDevice);
    }

	m_bIsMediaPlay = false;
	m_hMediaSource = 0;
}
//---------------------------------------------------------------------------

void __fastcall TVMS0500M::CloseWebCamera()
{
	if (!m_hMediaSource)
	{
		return;
	}

	if (m_bIsMediaPlay)
	{
        XnsSdkWindow1->Stop();
        m_bIsMediaPlay = false;
	}

	XnsSdkDevice1->CloseMedia(m_hDevice, m_hMediaSource);

	m_hMediaSource = 0;
	m_nControlId   = 0;
}
//---------------------------------------------------------------------------

int __fastcall TVMS0500M::CameraControl(int ACommand, int ASpeed)
{
	long ret = -1;

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

    int nPtzSpeed = ASpeed;

// 	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.
			ACommand,		// [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, ACommand, 30);
    }

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

int __fastcall TVMS0500M::Play(String AId,
                               String ALoc,
                               String AIpAddress,
                               int    APort,
                               String AConnId,
                               String AConnPass,
                               String AComModel,
                               String ADevModel)
{
    FId        = AId;
    FLoc       = ALoc;

    FIpAddress = WideString(AIpAddress);
    FPort      = APort;
    FConnId    = WideString(AConnId);
    FConnPass  = WideString(AConnPass);

    FDefModel  = WideString(AComModel);
    FModelName = WideString(ADevModel);

    LblErrMsg->Visible = false;

    FCaption = FId + ": " + FLoc;

    WebCamPlay();
    return 0;
}
//---------------------------------------------------------------------------

