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

#pragma hdrstop

#include <DateUtils.hpp>
#include "PacketHandllingF.h"
#include "ClientSessionF.h"
#include "VMSCommLibF.h"
#include "CenterCommF.h"
//---------------------------------------------------------------------------
#define TERROR(args...)     ASession->SysLogWrite(eLOG_ERROR, ##args)
#define TDEBUG(args...)     ASession->LogWrite(eLOG_DEBUG, ##args)
#define TINFO(args...)      ASession->LogWrite(eLOG_INFO, ##args)

#pragma package(smart_init)

extern const unsigned short g_crc16_table[256] =
{
	0x0000, 0xC0C1, 0xC181, 0x0140, 0xC301, 0x03C0, 0x0280, 0xC241,
	0xC601, 0x06C0, 0x0780, 0xC741, 0x0500, 0xC5C1, 0xC481, 0x0440,
	0xCC01, 0x0CC0, 0x0D80, 0xCD41, 0x0F00, 0xCFC1, 0xCE81, 0x0E40,
	0x0A00, 0xCAC1, 0xCB81, 0x0B40, 0xC901, 0x09C0, 0x0880, 0xC841,
	0xD801, 0x18C0, 0x1980, 0xD941, 0x1B00, 0xDBC1, 0xDA81, 0x1A40,
	0x1E00, 0xDEC1, 0xDF81, 0x1F40, 0xDD01, 0x1DC0, 0x1C80, 0xDC41,
	0x1400, 0xD4C1, 0xD581, 0x1540, 0xD701, 0x17C0, 0x1680, 0xD641,
	0xD201, 0x12C0, 0x1380, 0xD341, 0x1100, 0xD1C1, 0xD081, 0x1040,
	0xF001, 0x30C0, 0x3180, 0xF141, 0x3300, 0xF3C1, 0xF281, 0x3240,
	0x3600, 0xF6C1, 0xF781, 0x3740, 0xF501, 0x35C0, 0x3480, 0xF441,
	0x3C00, 0xFCC1, 0xFD81, 0x3D40, 0xFF01, 0x3FC0, 0x3E80, 0xFE41,
	0xFA01, 0x3AC0, 0x3B80, 0xFB41, 0x3900, 0xF9C1, 0xF881, 0x3840,
	0x2800, 0xE8C1, 0xE981, 0x2940, 0xEB01, 0x2BC0, 0x2A80, 0xEA41,
	0xEE01, 0x2EC0, 0x2F80, 0xEF41, 0x2D00, 0xEDC1, 0xEC81, 0x2C40,
	0xE401, 0x24C0, 0x2580, 0xE541, 0x2700, 0xE7C1, 0xE681, 0x2640,
	0x2200, 0xE2C1, 0xE381, 0x2340, 0xE101, 0x21C0, 0x2080, 0xE041,
	0xA001, 0x60C0, 0x6180, 0xA141, 0x6300, 0xA3C1, 0xA281, 0x6240,
	0x6600, 0xA6C1, 0xA781, 0x6740, 0xA501, 0x65C0, 0x6480, 0xA441,
	0x6C00, 0xACC1, 0xAD81, 0x6D40, 0xAF01, 0x6FC0, 0x6E80, 0xAE41,
	0xAA01, 0x6AC0, 0x6B80, 0xAB41, 0x6900, 0xA9C1, 0xA881, 0x6840,
	0x7800, 0xB8C1, 0xB981, 0x7940, 0xBB01, 0x7BC0, 0x7A80, 0xBA41,
	0xBE01, 0x7EC0, 0x7F80, 0xBF41, 0x7D00, 0xBDC1, 0xBC81, 0x7C40,
	0xB401, 0x74C0, 0x7580, 0xB541, 0x7700, 0xB7C1, 0xB681, 0x7640,
	0x7200, 0xB2C1, 0xB381, 0x7340, 0xB101, 0x71C0, 0x7080, 0xB041,
	0x5000, 0x90C1, 0x9181, 0x5140, 0x9301, 0x53C0, 0x5280, 0x9241,
	0x9601, 0x56C0, 0x5780, 0x9741, 0x5500, 0x95C1, 0x9481, 0x5440,
	0x9C01, 0x5CC0, 0x5D80, 0x9D41, 0x5F00, 0x9FC1, 0x9E81, 0x5E40,
	0x5A00, 0x9AC1, 0x9B81, 0x5B40, 0x9901, 0x59C0, 0x5880, 0x9841,
	0x8801, 0x48C0, 0x4980, 0x8941, 0x4B00, 0x8BC1, 0x8A81, 0x4A40,
	0x4E00, 0x8EC1, 0x8F81, 0x4F40, 0x8D01, 0x4DC0, 0x4C80, 0x8C41,
	0x4400, 0x84C1, 0x8581, 0x4540, 0x8701, 0x47C0, 0x4680, 0x8641,
	0x8201, 0x42C0, 0x4380, 0x8341, 0x4100, 0x81C1, 0x8081, 0x4040
};
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
static WORD GETCRC16(char *AData, int ALen)
{
	WORD crc = 0;

	for (int ii = 0; ii < ALen; ii++)
	{
		crc = ( (crc >> 8) ^ g_crc16_table[(crc ^ AData[ii]) & 0x0ff] );
	}

	return crc;
}
//---------------------------------------------------------------------------


//---------------------------------------------------------------------------
typedef int (*RecvPktHandlerFunc)(TClientSession *ASession, BYTE *AData, int APktLen);
//---------------------------------------------------------------------------

static int UnknownPktHandler(TClientSession *ASession, BYTE *AData, int APktLen)
{
    if (ASession->CDSLogCtlr)
    {
        TERROR("+CLI Invalid packet handler: %s. will be closed.", ASession->IpAddress.c_str());
    }

    VMS_HEAD *pHd = (VMS_HEAD*)AData;
    if (!pHd) return -1;

    MERROR("+CLI Invalid packet handler: %s. 0x%02X, will be closed.", ASession->IpAddress.c_str(), pHd->OpCode);

    ASession->LogData("RECV", (BYTE*)ASession->GetRecvBuff(), APktLen);
	ASession->Disconnect();
    return -1;
}
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
static RecvPktHandlerFunc G_FuncPktHandler[e_vms_MAX] = {NULL};
//---------------------------------------------------------------------------

struct _init_pkt_handler
{
    //정적 패킷핸들러 함수 초기화
	_init_pkt_handler()
	{
		for (int ii = 0; ii < e_vms_MAX; ii++)
		{
        	G_FuncPktHandler[ii] = UnknownPktHandler;
        }
	}
};
static _init_pkt_handler init_pkt_handler;
//---------------------------------------------------------------------------

struct RegisterHandler
{
	RegisterHandler(BYTE AOpCode, RecvPktHandlerFunc AFuncHandler)
	{
		G_FuncPktHandler[(int)AOpCode] = AFuncHandler;
	}
};
//---------------------------------------------------------------------------

#define REGISTER_HANDLER(PKT_TYPE)	\
	static int Handler_##PKT_TYPE(TClientSession* ASession, BYTE *AData, int APktLen); \
	static RegisterHandler _register_##PKT_TYPE(PKT_TYPE, Handler_##PKT_TYPE); \
	static int Handler_##PKT_TYPE(TClientSession* ASession, BYTE *AData, int APktLen)

void CALLBACK RecvCompletion(DWORD dwError, DWORD cbTransferred, LPWSAOVERLAPPED lpOverlapped, DWORD dwFlags)
{
    TClientSession *pSession = static_cast<OverlappedIO*>(lpOverlapped)->FSession;

    if (!pSession->IsConnected)
    {
        MERROR("+SVR RecvCompletion(IsConnected false): %s[%d]", pSession->IpAddress.c_str(), pSession->Socket);
        return;
    }

    /// 에러 발생시 해당 세션 종료
    if (dwError || cbTransferred == 0)
    {
        MERROR("+SVR RecvCompletion(dwError || cbTransferred==0): %s[%d], will be closed", pSession->IpAddress.c_str(), pSession->Socket);
        pSession->Disconnect();
        return;
    }

    /// 받은 데이터 처리
    pSession->OnRead(cbTransferred);
}
//---------------------------------------------------------------------------

#if 0
void CALLBACK SendCompletion(DWORD dwError, DWORD cbTransferred, LPWSAOVERLAPPED lpOverlapped, DWORD dwFlags)
{
    TClientSession *pSession = static_cast<OverlappedIO*>(lpOverlapped)->FSession;

    if (!pSession->IsConnected)
    {
        MERROR("+SVR SendCompletion(IsConnected false): %s[%d]", pSession->IpAddress.c_str(), pSession->Socket);
        return;
    }

    /// 에러 발생시 해당 세션 종료
    if (dwError || cbTransferred == 0)
    {
        MERROR("+SVR SendCompletion(dwError || cbTransferred==0): %s[%d], will be closed", pSession->IpAddress.c_str(), pSession->Socket);
        pSession->Disconnect();
        return;
    }

    pSession->OnWriteComplete(cbTransferred, cbTransferred);
}
//---------------------------------------------------------------------------
#endif

static TCDSCtlr* FindControllerByIpAddr(AnsiString AIpAddress)
{
    CtlrItr it;
    for(it=CDSCtlrManager->FLists.FObjects.begin(); it != CDSCtlrManager->FLists.FObjects.end(); ++it)
    {
        TCDSCtlr *pObj = (TCDSCtlr*)it->second;

        if (!pObj->Used) continue;

        if (pObj->CTLR_IP.AnsiCompare(AIpAddress) == 0)
        {
            return pObj;
        }
    }

    return NULL;
}
//---------------------------------------------------------------------------
static TCDSCtlr* FindControllerById(AnsiString ACtrlNmbrId)
{
    CtlrItr it;
    for(it=CDSCtlrManager->FLists.FObjects.begin(); it != CDSCtlrManager->FLists.FObjects.end(); ++it)
    {
        TCDSCtlr *pObj = (TCDSCtlr*)it->second;

        if (!pObj->Used) continue;

        if (pObj->CTLR_NMBR_ID.AnsiCompare(ACtrlNmbrId) == 0)
        {
            return pObj;
        }
    }

    return NULL;
}
//---------------------------------------------------------------------------
static int RequestJob(TClientSession *ASession, int AJob, char *AData, int ALen)
{
    IPC_JOB_MESSAGE *pMsg = g_jobBuff.GetBuff();
    pMsg->Type   = AJob;
    pMsg->ObjPtr = (DWORD)ASession;
    if (ALen > 0)
    {
        memcpy(pMsg->Buff, AData, ALen);
    }
    pMsg->Len = ALen;
    g_jobQ.PushBlocking((DWORD)pMsg);
    return 0;
}
//---------------------------------------------------------------------------

bool TClientSession::SendPacketDleStuffing(char *AData, int ADataLen)
{
    int nSendLen;
    int nLen;
    WORD crc;
    BYTE c;
    BYTE *msgPrt;
    BYTE *pData;

    msgPrt = FMsgBuff;
    pData  = AData;

    nLen = ADataLen;
    crc  = GETCRC16(pData, nLen);

    *msgPrt++ = VMS_DLE;
    *msgPrt++ = VMS_STX;

    // DLE Stuffing
    for (int ii = 0; ii < ADataLen; ii++)
    {
        *msgPrt++ = AData[ii];

        if (pData[ii] == VMS_DLE)
        {
            *msgPrt++ = VMS_DLE;
        }
    }

    *msgPrt++ = VMS_DLE;
    *msgPrt++ = VMS_ETX;

    *msgPrt++ = HIBYTE(crc);
    *msgPrt++ = LOBYTE(crc);

    nSendLen = msgPrt - FMsgBuff;

    if (!SendRequest((char*)FMsgBuff, nSendLen))
    {
        SERROR("+CLI SendPacketDleStuffing send request faild: %s, 0x%02X will be closed.", FIpAddress.c_str(), AData[4]);
        MERROR("+CLI SendPacketDleStuffing send request faild: %s, 0x%02X will be closed.", FIpAddress.c_str(), AData[4]);
        Disconnect();
        return false;
    }

    return SendFlushComplete();
}
//---------------------------------------------------------------------------

bool TClientSession::SendPacketDLE(char *AData, int ADataLen)
{
    int nSendLen;
    int nLen;
    BYTE c;
    BYTE *msgPrt;
    BYTE *pData;

    IPC_JOB_MESSAGE *pMsg = g_jobBuff.GetBuff();

    msgPrt = (BYTE*)pMsg->Buff;
    pData  = AData;

    *msgPrt++ = AData[0];
    *msgPrt++ = AData[1];

    // DLE Stuffing
    for (int ii = 2; ii < ADataLen-4; ii++)
    {
        *msgPrt++ = AData[ii];

        if (pData[ii] == VMS_DLE)
        {
            *msgPrt++ = VMS_DLE;
        }
    }

    *msgPrt++ = AData[ADataLen-4];  // DLE
    *msgPrt++ = AData[ADataLen-3];  // ETX
    *msgPrt++ = AData[ADataLen-2];  // CRC
    *msgPrt++ = AData[ADataLen-1];  // CRC

    nSendLen = msgPrt - (BYTE*)pMsg->Buff;

    pMsg->Type   = eVmsSendPacket;
    pMsg->ObjPtr = (DWORD)this;
    pMsg->Len    = nSendLen;
    g_jobQ.PushBlocking((DWORD)pMsg);

    Sleep(20);
    return true;
}
//---------------------------------------------------------------------------

bool TClientSession::SendPacket(char *AData, int ADataLen)
{
    int nSendLen;
    int nLen;
    WORD crc;
    BYTE c;
    BYTE *msgPtr;
    BYTE *pData;

    msgPtr = FMsgBuff;
    pData  = AData;

    nLen = ADataLen;
    crc  = GETCRC16(pData, nLen);

    *msgPtr++ = VMS_DLE;
    *msgPtr++ = VMS_STX;

    // DLE Stuffing
    for (int ii = 0; ii < ADataLen; ii++)
    {
        *msgPtr++ = AData[ii];

        if (pData[ii] == VMS_DLE)
        {
            *msgPtr++ = VMS_DLE;
        }
    }

    *msgPtr++ = VMS_DLE;
    *msgPtr++ = VMS_ETX;
    *msgPtr++ = HIBYTE(crc);
    *msgPtr++ = LOBYTE(crc);

    nSendLen = msgPtr - FMsgBuff;

    if (!SendRequest((char*)FMsgBuff, nSendLen))
    {
        SERROR("+CLI SendPacket send request faild: %s, 0x%02X will be closed.", FIpAddress.c_str(), AData[4]);
        MERROR("+CLI SendPacket send request faild: %s, 0x%02X will be closed.", FIpAddress.c_str(), AData[4]);
        Disconnect();
        return false;
    }
    return true;
#if 0
    int nSendLen;
    int nLen;
    WORD crc;
    BYTE c;
    BYTE *msgPtr;
    BYTE *pData;

    msgPtr = FMsgBuff;
    pData  = AData;

    nLen = ADataLen;
    crc  = GETCRC16(pData, nLen);

    msgPtr[0] = VMS_DLE;
    msgPtr[1] = VMS_STX;

    if (ADataLen > 0)
    {
        memcpy(&msgPtr[2], AData, ADataLen);
    }
    msgPtr[ADataLen+2] = VMS_DLE;
    msgPtr[ADataLen+3] = VMS_ETX;
    msgPtr[ADataLen+4] = HIBYTE(crc);
    msgPtr[ADataLen+5] = LOBYTE(crc);

#if 0
    for (int ii = 0; ii < ADataLen; ii++)
    {
        *msgPrt++ = AData[ii];
#if 0
        if (pData[ii] == VMS_DLE)
        {
            *msgPrt++ = VMS_DLE;
        }
#endif
    }
#endif

    nSendLen = ADataLen + 6;

    if (!SendRequest((char*)msgPtr, nSendLen))
    {
        SERROR("+CLI SendPacket send request faild: %s, 0x%02X will be closed.", FIpAddress.c_str(), AData[4]);
        MERROR("+CLI SendPacket send request faild: %s, 0x%02X will be closed.", FIpAddress.c_str(), AData[4]);
        Disconnect();
        return false;
    }
    return true;
#endif
}
//---------------------------------------------------------------------------

bool TClientSession::CheckLoginClient()
{
    TCDSCtlr *pCDSCtlr = FindControllerByIpAddr(FIpAddress);
    if (!pCDSCtlr)
    {
        MERROR("+CLI Unknown client address: %s. will be closed.", FIpAddress.c_str());
        return false;
    }

    //이전 접속정보가 있는지 확인한다.
    if (FCDSCtlr)
    {
        TClientSession *pSession = FCDSCtlr->FSession;
        if (pSession)
        {
            //이전 접속을 종료하고 현재 접속을 새로운 VMS 제어기 통신으로 사용한다.
            MERROR("+CLI Client allready connect: %s. old connection will be closed.", FIpAddress.c_str());
            pSession->Disconnect();
        }
    }

    FState      = eSS_LoginReq;     //최초접속후 폼을 다운로드 하기위해 사용할 플래그(기존에는 로그인체크용으로 사용)
    FCDSCtlr    = pCDSCtlr;
    FCDSLogCtlr = pCDSCtlr;
    FCDSCtlr->FSession = this;
    FCDSCtlr->LOGIN_IPADDR     = FIpAddress;      //연결된 IP주소 설정
    FCDSCtlr->Server.commState = comm_open;
    FCDSCtlr->Server.ConnectTm = Now().FormatString("yyyy-MM-dd hh:nn:ss");
    FCtlrId.printf("%10.010d", FCDSCtlr->CTLR_NMBR.ToIntDef(0));
    POST_MSG(MAINHANDLE, WM_TCP_THREAD, WM_TCP_SERVER_STTS, (int)pCDSCtlr);
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    // 최초에 폼정보를 모두 다운로드 해버리자.(TODO: 메모리 할당이 위에서 끝난다음에 초기화해야함)
    FCDSCtlr->InitDownloadFileInfo();

    //최초에 상태정보를 요청하고 상태정보요청 응답이 완료되면 시나리오를 다운로드 하자.
    RequestJob(this, eVmsStatusReq, NULL, 0);

    return true;
}
//---------------------------------------------------------------------------

bool TClientSession::OnDisconnected()
{
    if (FCDSCtlr)
    {
        FCDSCtlr->Server.DisconnectTm = Now().FormatString("yyyy-MM-dd hh:nn:ss");
        FCDSCtlr->Server.commState    = comm_close;
        FCDSCtlr->FSession            = NULL;
        //FCDSCtlr->LOGIN_IPADDR        = "";

        LERROR("VMS %s disconnected.", CtlrId.c_str());
        MERROR("%s.%d, VMS %s disconnected.", FIpAddress.c_str(), FSocket, CtlrId.c_str());

        TCDSCtlr* pCDSCtlr = FCDSCtlr;
        POST_MSG(MAINHANDLE, WM_TCP_THREAD, WM_TCP_SERVER_STTS, (int)pCDSCtlr);
    }
    else
    {
        MERROR("%s.%d, disconnected.", FIpAddress.c_str(), FSocket);
    }

    FState = eSS_Disconnect;
    return true;
}
//---------------------------------------------------------------------------

/*
* 1개의 패킷을 모두 전송한 후 호출됨
*/
void TClientSession::OnWrite(char *APktPtr, int ASendLen)
{
    VMS_HEAD *pHd = (VMS_HEAD*)APktPtr;
    if (!pHd) return;

    if (ASendLen > 0)
    {
        LINFO("SEND: %d Bytes", ASendLen);
        LogData("SEND", APktPtr, ASendLen);
    }
    InfoPacket(pHd->OpCode, ASendLen, true, 0);

#if 0
    switch(pHd->OpCode)
    {
    case VMS_ID_REQ:            // 0xFF        // server -> client
    case DNLD_SCENARIO_REQ:     // 0x02        // server -> client
    case CTRL_RESET_REQ:        // 0x03        // server -> client
    case DNLD_FILE_REQ:         // 0x04        // server -> client
    case PARAMETER_REQ:         // 0x05        // server -> client
    case CTRL_LED_POWER_REQ:    // 0x06        // server -> client
    case CTRL_FAN_POWER_REQ:    // 0x07        // server -> client
    case CTRL_BRGH_REQ:         // 0x08        // server -> client
    case CTRL_CONFIG_REQ:       // 0x09        // server -> client
    case CTRL_TIME_REQ:         // 0x10        // server -> client
        FTmrSend = Now();
        if (FChkRecvTO == false)
        {
            FTmrRecv = Now();
        }
        FChkRecvTO = true;
        break;
    default:
        FChkRecvTO = false;     // 0x01        // server -> client
        break;
    }
#endif
}
//---------------------------------------------------------------------------

/*
*  프로토콜에 따른 처리
*/
void TClientSession::OnRead(int ALen)
{
    int  readIdx;
    int  stuffing;
    int  dleEtx;
    int  msgSize;
    BYTE msgBuff[SESSION_SEND_BUFFER];
    BYTE data;
    WORD crc;

    VMS_RES_HEAD *pHead;

    FRecvIdx += ALen;

    if (FRecvIdx > 0)
    {
        LINFO("RECV: %d Bytes", FRecvIdx);
        LogData("RECV", (char*)FRecvBuff, FRecvIdx);
    }

	while(true)
	{
        if (FRecvIdx < (int)sizeof(VMS_HEAD))
        {
            break;
        }

        if (FRecvBuff[0] != VMS_DLE && FRecvBuff[1] != VMS_STX)
        {
            MERROR("+CLI Packet parsing data start command error: %s, 0x%02X, 0x%02X. will be closed.", FIpAddress.c_str(), FRecvBuff[0], FRecvBuff[1]);
            Disconnect();
            return;
        }

        readIdx    = 0;
        stuffing   = 0; // 연속된 DLE 데이터 체크, 1 이면 DLE Stuffing
        dleEtx     = 0; // DLE_ETX, ETX를 체크하기 위함, 1 이고 ETX 데이터를 읽었으면 패킷의 마지막(DLE_ETX, ETX 데이터 임)
        msgSize    = 0; // 순수 데이터 사이즈

        while (readIdx < FRecvIdx && msgSize < (int)sizeof(msgBuff))
        {
            data = FRecvBuff[readIdx++];
            if (data == VMS_DLE)
            {
                if (stuffing)
                {
                    stuffing = 0;
                    dleEtx   = 0;   // TODO
                }
                else
                {
                    msgBuff[msgSize++] = data;
                    stuffing = 1;
                    dleEtx   = 1;
                }
            }
            else
            if (data == VMS_ETX)
            {
                msgBuff[msgSize++] = data;
                if (dleEtx)
                {
                    // 이전데이터가 DLE이고 현재 데이터가 ETX이면 패킷의 끝임.
                    // 다음 2바이트는 CRC 데이터임, 남아 있는 데이터가 CRC 2바이트를 포함한 크기보다 작으면
                    // 하나의 패킷을 완전히 수신하지 못한 것임
                    if ((readIdx + 2) > FRecvIdx)
                    {
                        // 하나의 패킷을 읽지 못함
                        return;
                    }
                    msgBuff[msgSize++] = FRecvBuff[readIdx++];  // CRC1
                    msgBuff[msgSize++] = FRecvBuff[readIdx++];  // CRC2

                    // 하나의 패킷을 완전히 읽었음.
                    ResetPacket(readIdx);   // 메모리에서 수신 인덱스 초기화

#if 0
                    // dle, stx 제외, dle,etx,crc(2) 제외
                    crc = GETCRC16(&msgBuff[2], msgSize-2-sizeof(VMS_TAIL));
                    if (msgBuff[readIdx-2] != HIBYTE(crc) || msgBuff[readIdx-1] != LOBYTE(crc))
                    {
                        MERROR("+CLI Packet parsing data crc error: %s, 0x%02X, 0x%02X, 0x%02X, 0x%02X. will be closed.",
                                FIpAddress.c_str(), msgBuff[readIdx-2], msgBuff[readIdx-1], HIBYTE(crc), LOBYTE(crc));
                        Disconnect();
                        return;
                    }
#endif

                    pHead = (VMS_RES_HEAD*)msgBuff;
                    if (pHead->Length != msgSize-sizeof(VMS_RES_HEAD)-sizeof(VMS_TAIL))
                    {
                        MERROR("+CLI Packet parsing data length error: %s, %d, %d. will be closed.",
                                FIpAddress.c_str(), pHead->Length, msgSize-sizeof(VMS_RES_HEAD)-sizeof(VMS_TAIL));
                        Disconnect();
                        return;
                    }

                    InfoPacket(pHead->OpCode, msgSize, false, 0);
                    if (G_FuncPktHandler[pHead->OpCode](this, msgBuff, msgSize) < 0)
                    {
                        Disconnect();
                        return;
                    }
                    SendFlush();
                    break;
                }
                else
                {
                    dleEtx = 0;
                }
            }
            else
            {
                // 순수 데이터를 읽음
                msgBuff[msgSize++] = data;
                stuffing = 0;
                dleEtx   = 0;
            }
        }

        if (readIdx >= FRecvIdx)
        {
            break;
        }
    }
}
//---------------------------------------------------------------------------

template <class PKT_TYPE>
bool TClientSession::ParsePacket(PKT_TYPE& pkt, int APktLen)
{
    if (APktLen > FRecvIdx)
    {
        MERROR("+CLI ParsePacket Error: %s, PktLen: %d, RecvIdx: %d", FIpAddress.c_str(), APktLen, FRecvIdx);
        return false;
    }

    memcpy((char*)&pkt, FRecvBuff, APktLen);
    FRecvIdx -= APktLen;
    if (FRecvIdx > 0)
    {
        memmove(FRecvBuff, FRecvBuff+APktLen, FRecvIdx);
    }
    return true;
}
//---------------------------------------------------------------------------

bool TClientSession::InfoPacket(BYTE AOpCode, int ALen, bool ASend, int AResult/*=0*/)
{
    TCDSCtlr* pCDSCtlr = FCDSLogCtlr;

    if (!pCDSCtlr) return -1;
    //if (!pCDSCtlr->FDispLog) return -1;
    //if (!g_LogCfg.Debug) return -1;
    if (!g_LogCfg.Info) return -1;

    AnsiString sCmd;

    switch(AOpCode)
    {
    case e_txt_disp_immediate_text://        = 0x02, //  Display Immediate Text                Opcode = 2  [0x02]  ⇔ Opcode = 72 [0x48]
        sCmd = "txt_disp_immediate_text";
        break;
    case e_txt_disp_immediate_graphic://     = 0x04, //  Display Immediate graphics            Opcode = 4  [0x04]  ⇔ Opcode = 72 [0x48]
        sCmd = "txt_disp_immediate_graphic";
        break;
    case e_txt_disp_lib_message://           = 0x06, //  Display Library Message               Opcode = 6  [0x06]  ⇔ Opcode = 72 [0x48]
        sCmd = "txt_disp_lib_message";
        break;
    case e_txt_download_message_lib://       = 0x08, //  Download  A Message Library           Opcode = 8  [0x08]  ⇔ Opcode = 72 [0x48]
        sCmd = "txt_download_message_lib";
        break;
    case e_txt_download_full_graphic_lib://  = 0x0A, //  Download Graphics Library             Opcode = 10 [0x0A]  ⇔ Opcode = 72 [0x48]
        sCmd = "txt_download_full_graphic_lib";
        break;
    case e_txt_download_graphic_symb_lib://  = 0x0C, //  Download Graphic Symbol Library       Opcode = 12 [0x0C]  ⇔ Opcode = 72 [0x48]
        sCmd = "txt_download_graphic_symb_lib";
        break;
    case e_txt_display_schedule_msg://       = 0x0E, //  Display Schedule Message              Opcode = 14 [0x0E]  ⇔ Opcode = 72 [0x48]
        sCmd = "txt_display_schedule_msg";
        break;
    case e_txt_initialize://                 = 0x12, //  Initailize                            Opcode = 18 [0x12]  ⇔ Opcode = 72 [0x48]
        sCmd = "txt_initialize";
        break;
    case e_txt_disp_test_pattern://          = 0x14, //  Display Test Pattern                  Opcode = 20 [0x14]  ⇔ Opcode = 72 [0x48]
        sCmd = "txt_disp_test_pattern";
        break;
    case e_txt_blank://                      = 0x16, //  Blank                                 Opcode = 22 [0x16]  ⇔ Opcode = 72 [0x48]
        sCmd = "txt_blank";
        break;

    case e_txt_download_parameter://         = 0x1C, //  Download Parameter                    Opcode = 28 [0x1C]  ⇔ Opcode = 72 [0x48]
        sCmd = "txt_download_parameter";
        break;
    case e_txt_display_default_msg://        = 0x1E, //  Display Default Message               Opcode = 30 [0x1E]  ⇔ Opcode = 72 [0x48]
        sCmd = "txt_display_default_msg";
        break;
    case e_txt_set_luminance_level://        = 0x20, //  Set Luminance Level                   Opcode = 32 [0x20]  ⇔ Opcode = 72 [0x48]
        sCmd = "txt_set_luminance_level";
        break;
    case e_txt_signboard_control://          = 0x24, //  Signboard Power Control               Opcode = 36 [0x24]  ⇔ Opcode = 72 [0x48]
        sCmd = "txt_signboard_control";
        break;
    case e_txt_signboard_alarm_control://    = 0x2A, //  Signboard Alarm Control               Opcode = 42 [0x2A]  ⇔ Opcode = 72 [0x48]
        sCmd = "txt_signboard_alarm_control";
        break;
    case e_txt_pan_hetr_temp_control://      = 0x31, //  함체 PAN/HEATER 온도 설정             Opcode = 49 [0x31]  ⇔ Opcode = 72 [0x48]
        sCmd = "txt_pan_hetr_temp_control";
        break;

    case e_txt_status_req://                 = 0x18, //  Status Request                        Opcode = 24 [0x18]  ⇔ Opcode = 64 [0x40]
        sCmd = "txt_status_req";
        break;
    case e_txt_status_res://                 = 0x40, //  Status Response                       Opcode = 24 [0x18]  ⇔ Opcode = 64 [0x40]
        sCmd = "txt_status_res";
        break;

    case e_txt_upload_modl_status_req://     = 0x28, //  Upload Module Status                  Opcode = 40 [0x28]  ⇔ Opcode = 74 [0x4A]
        sCmd = "txt_upload_modl_status_req";
        break;
    case e_txt_upload_modl_status_res://     = 0x4A, //  Upload Module Status                  Opcode = 40 [0x28]  ⇔ Opcode = 74 [0x4A]
        sCmd = "txt_upload_modl_status_res";
        break;

    case e_txt_pan_hetr_temp_req://          = 0x32, //  함체 PAN/HEATER 온도 요청    	      Opcode = 50 [0x32]  ⇔ Opcode = 66 [0x42]
        sCmd = "txt_pan_hetr_temp_req";
        break;
    //case e_txt_pan_hetr_temp_res://          = 0x42, //  함체 PAN/HEATER 온도 요청    	      Opcode = 50 [0x32]  ⇔ Opcode = 66 [0x42]
    //    sCmd = "txt_pan_hetr_temp_res";
    //    break;

    case e_txt_failed_elem_data_req://       = 0x1A, //  Failed Element Data Request           Opcode = 26 [0x1A]  ⇔ Opcode = 66 [0x42]
        sCmd = "txt_failed_elem_data_req";
        break;
    case e_txt_failed_elem_data_res://       = 0x42, //  Failed Element Data Response          Opcode = 26 [0x1A]  ⇔ Opcode = 66 [0x42]
        sCmd = "txt_failed_elem_data_res";
        break;

    case e_txt_upload_msg_req://             = 0x22, //  Upload A Message                      Opcode = 34 [0x22]  ⇔ Opcode = 68 [0x44]
        sCmd = "txt_upload_msg_req";
        break;
    case e_txt_upload_msg_res://             = 0x44, //  Upload A Message  Response            Opcode = 34 [0x22]  ⇔ Opcode = 68 [0x44]
        sCmd = "txt_upload_msg_res";
        break;

    case e_txt_upload_schedule_msg_req://    = 0x23, //  Upload Schedule Message               Opcode = 35 [0x23]  ⇔ Opcode = 69 [0x45]
        sCmd = "txt_upload_schedule_msg_req";
        break;
    case e_txt_upload_schedule_msg_res://    = 0x45, //  Upload Schedule Message               Opcode = 35 [0x23]  ⇔ Opcode = 69 [0x45]
        sCmd = "txt_upload_schedule_msg_res";
        break;

    case e_txt_msg_echo_back_req://          = 0x26, //  Message Echo Back                     Opcode = 38 [0x26]  ⇔ Opcode = 70 [0x46]
        sCmd = "txt_msg_echo_back_req";
        break;
    case e_txt_msg_echo_back_res://          = 0x46, //  Message Echo Back                     Opcode = 38 [0x26]  ⇔ Opcode = 70 [0x46]
        sCmd = "txt_msg_echo_back_res";
        break;

    case e_txt_image_req://                  = 0x2C, //  영상이미지 요청 Status                Opcode = 44 [0x2C]  ⇔ Opcode = 76 [0x4C]
        sCmd = "txt_image_req";
        break;
    case e_txt_image_res://                  = 0x4C, //  영상이미지 요청 Status                Opcode = 44 [0x2C]  ⇔ Opcode = 76 [0x4C]
        sCmd = "txt_image_res";
        break;

    //case e_txt_ftp_download://               = 0x2C, //  동영상 파일 FTP 다운로드              Opcode = 44 [0x2C]  ⇔ Opcode = 72 [0x48]
    //    sCmd = "txt_ftp_download";
    //    break;
    case e_txt_ftp_download_completed://     = 0x2E, //  동영상 파일 FTP 다운로드 완료         Opcode = 46 [0x2E]
        sCmd = "txt_ftp_download_completed";
        break;

    case e_txt_response://                   = 0x48, //  제어기 응답(ACK/NAK)
        sCmd = "txt_response";
        break;

    case e_vms_form_display://          = 0x80,//    폼 데이터 표출                          송신    표출할 폼 데이터 송신                       센터 → VMS
        sCmd = "vms_form_display";
        break;
    case e_vms_file_download://         = 0x82,//    데이터 다운로드                         송신    INI, CFG , Bitmap , Data파일송신            센터 → VMS
        sCmd = "vms_file_download";
        break;
    case e_vms_data_upload://           = 0x84,//    데이터 업로드                           송신    INI, CFG , Bitmap , Data파일 업로드 요구    센터 → VMS
        sCmd = "vms_data_upload";
        break;
    case e_vms_status_control://        = 0x86,//    VMS 상태제어                            송신    VMS 제어정보 송신                           센터 → VMS
        sCmd = "vms_status_control";
        break;
    case e_vms_status://                = 0x88,//    VMS Status 요구                         송신    VMS 상태정보 요구 송신                      센터 → VMS
        sCmd = "vms_status";
        break;
    case e_vms_parameter://             = 0x8A,//    VMS 파라미터 요구                       송신    VMS 로컬 상태 요구 송신                     센터 → VMS
        sCmd = "vms_parameter";
        break;
    case e_vms_power_module_status://   = 0x8C,//    전원 모듈 상태 요구                     송신    전원 모듈 상태를 검사 결과를 요청한다       센터 → VMS
        sCmd = "vms_power_module_status";
        break;
    case e_vms_display_module_status:// = 0x8E,//    표출 모듈 상태 요구                     송신    표출 모듈 상태를 검사 결과를 요청한다       센터 → VMS
        sCmd = "vms_display_module_status";
        break;
    case e_vms_pixel_image://           = 0x92,//    VMS Pixel Image 요구                    송신    VMS LED Pixel 상태요구 송신                 센터 → VMS
        sCmd = "vms_pixel_image";
        break;
    case e_vms_current_display_form://  = 0x94,//    현재표출폼 Upload                       송신    Local에서 표출 중인 폼  Upload요구          센터 → VMS
        sCmd = "vms_current_display_form";
        break;
    case e_vms_download_schedule_form:// = 0x96,//    Display Schedule Form                   송신    계획된 Form 표출 요구                       센터 → VMS
        sCmd = "vms_download_schedule_form";
        break;
    case e_vms_display_default_form://  = 0x98,//    Display Default Form                    송신    디폴트 From표출 요구                        센터 → VMS
        sCmd = "vms_display_default_form";
        break;
    case e_vms_download_form://         = 0x9A,//    Download Form                           송신    Form download                               센터 → VMS
        sCmd = "vms_download_form";
        break;
    case e_vms_upload_schedule_form://  = 0x9C,//    Upload Schedule Form                    송신    스케줄 메시지 업로드 요구                   센터 → VMS
        sCmd = "vms_upload_schedule_form";
        break;
    case e_vms_blank://                 = 0x9E,//    Blank                                   송신    schedule 표출                               센터 → VMS
        sCmd = "vms_blank";
        break;
    case e_vms_display_form_id://       = 0xA0,//    Display Form ID                         송신    Form ID에 해당하는 Form 표출                센터 → VMS
        sCmd = "vms_display_form_id";
        break;
    default:
        sCmd.printf("UNKNOWN Packet: %02X", AOpCode);
        return false;
    }

    if (ASend)
    {
        if (AResult == 0)
            LINFO("SEND: %s, %d Bytes, [DLE Stuffing]", sCmd.c_str(), ALen);
        else
            LERROR("SEND FAIL: %s, %d Bytes, [DLE Stuffing]", sCmd.c_str(), ALen);
    }
    else
    {
        LINFO("RECV: %s, %d Bytes, [DLE Stuffing]", sCmd.c_str(), ALen);
    }
    return true;
}
//---------------------------------------------------------------------------

void TClientSession::DisplayResponseError(BYTE *AData)
{
    BYTE *pData = &AData[sizeof(VMS_RES_HEAD)];
    if (pData[0] != VMS_NAK)
    {
        return;
    }

    AnsiString sErr = "";
    switch(pData[1])
    {
    case 0x30: sErr = "Data Length가 2,047 Byte 보다 크면 보고되는 오류";                   break;
    case 0x31: sErr = "Data Length 이후의 데이터가 Data Length + 5Byte가 되지 않는 오류";   break;
    case 0x32: sErr = "데이터 크기 불일치";                                                 break;
    case 0x33: sErr = "작업이전 작업 진행중 작업요구";                                      break;
    case 0x34: sErr = "파라미터 범위 초과";                                                 break;
    case 0x35: sErr = "저장되지 않은 폼데이터 요구";                                        break;
    case 0x36: sErr = "업무처리 해당사항 없음";                                             break;
    case 0x37: sErr = "STN Address 틀림";                                                   break;
    default  : sErr.printf("NAK, Unknown Result Code 0x%02X", (int)pData[1]);               break;
    }
    LERROR(sErr.c_str());
}
//---------------------------------------------------------------------------

/////////////////////////////////////////////////////////
REGISTER_HANDLER(e_txt_response)
{
    int nLength = APktLen-sizeof(VMS_RES_HEAD)-sizeof(VMS_TAIL);
#if 0
	if (nLength < 1)    // ACK or NAK
	{
        TERROR("%s.%d, e_txt_response Data Length error(%d). will be closed.", ASession->IpAddress.c_str(), ASession->Socket, nLength);
        MERROR("%s.%d, e_txt_response Data Length error(%d). will be closed.", ASession->IpAddress.c_str(), ASession->Socket, nLength);
		return -1;
	}
#endif
    TDEBUG("e_txt_response Length: %d", nLength);

    TDownloadForm *pInfo = NULL;
    VMS_RES_HEAD *pRes = (VMS_RES_HEAD*)AData;
    TCDSCtlr *AObj = ASession->CDSCtlr;
    if (AObj)
    {
        if (pRes->Ctlr != (BYTE)AObj->CTLR_LOCAL_NO)
        {
            TERROR("%s.%d, e_txt_response Controller No Error: %d, %d.", ASession->IpAddress.c_str(), ASession->Socket, AObj->CTLR_LOCAL_NO, (int)pRes->Ctlr);
            MERROR("%s.%d, e_txt_response Controller No Error: %d, %d.", ASession->IpAddress.c_str(), ASession->Socket, AObj->CTLR_LOCAL_NO, (int)pRes->Ctlr);
            return -3;
        }

        if (AObj->FTxtOpCode == e_txt_download_full_graphic_lib)
        {
            //라이브러리폼을 계속 다운로드
            TCDSCtlr *AObj = ASession->CDSCtlr;
            if (AObj)
            {
                pInfo = AObj->FDownloadLists.Find(AObj->DownloadFormId);
                if (pInfo)
                {
                    pInfo->AlreadyDownload = true;
                    pInfo->DownloadTm      = Now();
                }
            }
            ASession->download_lib_form_0x0A();
        }
        else
        if (AObj->FTxtOpCode == e_txt_display_schedule_msg)
        {
            //스케쥴다운로드가 완료됐으므로 blank 명령 전송
            ASession->download_blank_0x16();
        }
        else
        if (AObj->FTxtOpCode == e_txt_blank)
        {
            //Blank 명령 전송 완료 수신하면 OpCode 초기화
            AObj->FTxtOpCode == 0x00;

            // 폼 스케쥴 정보 다운로드 완료 메시지 처리
            ASession->download_form_schedule_complete();
        }

    }
    if (nLength == 1 && AData[sizeof(VMS_RES_HEAD)] == VMS_ACK)
    {
        TINFO("e_txt_response : ACK...");
    }
    else
    if (nLength == 2 && AData[sizeof(VMS_RES_HEAD)] == VMS_NAK)
    {
        if (AObj && pInfo)
        {
            pInfo->AlreadyDownload = false;
        }
        VMS_RESULT *pRes = (VMS_RESULT*)&AData[sizeof(VMS_RES_HEAD)];
        TERROR("%s.%d, e_txt_response Result Error. Error: 0x%02X.", ASession->IpAddress.c_str(), ASession->Socket, pRes->Error);
        MERROR("%s.%d, e_txt_response Result Error. Error: 0x%02X.", ASession->IpAddress.c_str(), ASession->Socket, pRes->Error);
        ASession->DisplayResponseError(AData);
        return -2;

     }
    else
    {
        TINFO("e_txt_response : OK...");
    }
    return 0;
}
//---------------------------------------------------------------------------

/////////////////////////////////////////////////////////
REGISTER_HANDLER(e_txt_status_res)
{
    TCDSCtlr *AObj = ASession->CDSCtlr;
    if (!AObj)
    {
        TERROR("%s.%d, e_txt_status_res Controller NULL. will be closed.", ASession->IpAddress.c_str(), ASession->Socket);
        MERROR("%s.%d, e_txt_status_res Controller NULL. will be closed.", ASession->IpAddress.c_str(), ASession->Socket);
        return -5;
    }
    if (ASession->State == eSS_LoginReq)
    {
        VMS_RES_HEAD *pRes = (VMS_RES_HEAD*)AData;

        if (pRes->Ctlr != (BYTE)AObj->CTLR_LOCAL_NO)
        {
            TERROR("%s.%d, e_txt_status_res Controller No Error: %d, %d.", ASession->IpAddress.c_str(), ASession->Socket, AObj->CTLR_LOCAL_NO, (int)pRes->Ctlr);
            MERROR("%s.%d, e_txt_status_res Controller No Error: %d, %d.", ASession->IpAddress.c_str(), ASession->Socket, AObj->CTLR_LOCAL_NO, (int)pRes->Ctlr);
            return -4;
        }
    }

    int nLength = APktLen-sizeof(VMS_RES_HEAD)-sizeof(VMS_TAIL);
	if (nLength < 2)
	{
        TERROR("%s.%d, e_txt_status_res Data Length error(%d). will be closed.", ASession->IpAddress.c_str(), ASession->Socket, nLength);
        MERROR("%s.%d, e_txt_status_res Data Length error(%d). will be closed.", ASession->IpAddress.c_str(), ASession->Socket, nLength);
		return -1;
	}
    TDEBUG("e_txt_status_res Length: %d", nLength);

    int nReqSize =  sizeof(VMS_TXT_STATUS);
	if (nLength != nReqSize)
	{
        TERROR("%s.%d, e_txt_status_res Data Size error(%d, %d). will be closed.", ASession->IpAddress.c_str(), ASession->Socket, nLength, nReqSize);
        MERROR("%s.%d, e_txt_status_res Data Size error(%d, %d). will be closed.", ASession->IpAddress.c_str(), ASession->Socket, nLength, nReqSize);
        if (nLength == 2)
        {
             ASession->DisplayResponseError(AData);
        }
		return -2;
	}

    VMS_TXT_STATUS *pStatus = (VMS_TXT_STATUS*)&AData[sizeof(VMS_RES_HEAD)];

    TDEBUG("VMS_TXT_STATUS: Door(%02X), Power(%02X), Fan(%02X), Heater(%02X), Reset(%02X), Temp(%02X,%d)",
            pStatus->DOOR,
            pStatus->POWER,
            pStatus->FAN,
            pStatus->HEATER,
            pStatus->RESET,
            pStatus->CBOX_TEMP,
            pStatus->CBOX_TEMP
            );

    INT_VMS_STATE *FStts = &AObj->RSTATE;

#if 0
    BYTE    DOOR;	    // Door Open/Close 상태	0x00 : Open, 0x01 : Close, 0x09 : Unknown
    BYTE    POWER;      // 전원의 ON/OFF 상태	0x00 : On, 0x01 : Off (Sign Board)
    BYTE    FAN;		// VMS Fan 동작상태		0x00 : On, 0x01 : Off, 0x09: Unknown
						// 함체 Fan 동작상태	0x00 : On, 0x10 : Off, 0x90: Unknown
    BYTE    HEATER;		// VMS Heater 동작상태	0x00 : On, 0x01 : Off, 0x09: Unknown
						// 함체 Heater 동작상태	0x00 : On, 0x10 : Off, 0x90: Unknown
    WORD    FORM_NUM;	// 표출 폼 번호	0x00 : 통신 폼, 0x01 : 디폴트 폼
    BYTE    REBOOT_YN;	// 재실행 여부	0x00 : 정상, 0x01 : 재실행
    char    CBOX_TEMP;	// 함체온도	127 ~ -127 -128 : Unknown
    BYTE    BRIGHT[4];	// 화면의 밝기	최대를 100으로 했을 때의 백분율 값 및 기준휘도
                        // 0: 현재  휘도(00:주간,01:야간,02:자동)
                        // 1: 야간휘도설정값
                        // 2: 주간휘도설정값
                        // 3: 현재휘도값(이건 나의 추측)
    char    DP_TEMP;	// 표출부온도	127 ~ -127 -128 : Unknown
    BYTE    DP_HUM;		// 표출부습도	0~100%, 포항UTIS부터 추가함
#endif

    if      (pStatus->POWER == 0x00) FStts->ModulePowerStatus = vms_module_power_off;
    else if (pStatus->POWER == 0x01) FStts->ModulePowerStatus = vms_module_power_on;
    else                             FStts->ModulePowerStatus = vms_module_power_unknown;

    if      (pStatus->DOOR == 0x00) FStts->DoorStatus = vms_door_close;
    else if (pStatus->DOOR == 0x01) FStts->DoorStatus = vms_door_open;
    else                            FStts->DoorStatus = vms_door_unknown;

    if      (pStatus->FAN == 0x00) FStts->FanStatus = vms_fan_off;
    else if (pStatus->FAN == 0x01) FStts->FanStatus = vms_fan_on;
    else                           FStts->FanStatus = vms_fan_unknown;

    if      (pStatus->HEATER == 0x00) FStts->HeaterStatus = vms_heater_off;
    else if (pStatus->HEATER == 0x01) FStts->HeaterStatus = vms_heater_on;
    else                              FStts->HeaterStatus = vms_heater_unknown;

    FStts->PowerCtrlStatus = FStts->ModulePowerStatus;  // 문자식은 받아오는게 없으니까 모듈전원상태와 동일한것으로 하자

    FStts->BodyTemp        = (short)pStatus->CBOX_TEMP;                             /* 함체온도값(℃), 범위(-128~127) */
    //FStts->LuminanceStatus = (BYTE)pStatus->BRIGHT[3];                                 /* 화면의 밝기값 (최대 휘도값을 100으로 했을 때의 백분율 값), 범위(0~100) */
    FStts->Wcomm           = vms_comm_normal;// : vms_comm_error;   /* 무선통신상태, 0:정상 1:장애 */
    //AObj->BRGH_WEEK_STEP   = pStatus->BRIGHT[2];
    //AObj->BRGH_NGHT_STEP   = pStatus->BRIGHT[1];

    RequestJob(ASession, eVmsDisplayModuleStatusReq, NULL, 0);
    return 0;
}
//---------------------------------------------------------------------------

/////////////////////////////////////////////////////////
REGISTER_HANDLER(e_txt_failed_elem_data_res)
{
    int nLength = APktLen-sizeof(VMS_RES_HEAD)-sizeof(VMS_TAIL);
	if (nLength < (int)sizeof(VMS_TXT_MODL_STATUE))    // module count 2 byte
	{
        TERROR("%s.%d, e_txt_failed_elem_data_res Data Length error(%d). will be closed.", ASession->IpAddress.c_str(), ASession->Socket, nLength);
        MERROR("%s.%d, e_txt_failed_elem_data_res Data Length error(%d). will be closed.", ASession->IpAddress.c_str(), ASession->Socket, nLength);
		return -1;
	}
    TDEBUG("e_txt_failed_elem_data_res Length: %d", nLength);

    VMS_TXT_MODL_STATUE *pData = (VMS_TXT_MODL_STATUE*)&AData[sizeof(VMS_RES_HEAD)];

    int idx = 0;
    int xCnt = 0;
    int yCnt = 0;
    TCDSCtlr *AObj = ASession->CDSCtlr;
    if (AObj)
    {
        INT_VMS_STATE *FStts = &AObj->RSTATE;

        yCnt = AObj->ROW_NUM;
        xCnt = AObj->COL_NUM;
        FStts->ModuleHorizontal = xCnt;                             /* 가로 모듈수 */
        FStts->ModuleVertical   = yCnt;                             /* 세로 모듈수 */

        idx = 0;
        for (int ii = 0; ii < yCnt && ii < MAX_TXT_MODL_ROWS; ii++)
        {
            for (int jj = 0; jj < xCnt && jj < MAX_TXT_MODL_COLS; jj++)
            {
                CComm_SetBitValue(FStts->ModuleStatus, idx, pData->Modl[ii][jj] == 0 ? 1 : 0);
                idx++;
            }
        }
    }

    TDEBUG("VMS_DISPLAY_MODULE : X(%d) Y(%d)", xCnt, yCnt);
    AnsiString sModSts = "";
    AnsiString sTmp;

    idx = 0;
    for (int ii = 0; ii < yCnt && ii < MAX_TXT_MODL_ROWS; ii++)
    {
        sModSts = "";
        for (int jj = 0; jj < xCnt && jj < MAX_TXT_MODL_COLS; jj++)
        {
            sTmp.printf("%d", pData->Modl[ii][jj]);    //0x00 : Off, 0x01 : On, 0x02 : Unknown,
            sModSts += sTmp;
            idx++;
        }
        TDEBUG("VMS_DISPLAY_MODULE: %02d, %s", ii+1, sModSts.c_str());
    }
    POST_MSG(MAINHANDLE, WM_TCP_THREAD, WM_CTLR_STATE_STTS, (int)ASession->CDSCtlr);    // 상태정보 업데이트

#if 0
    // 설정온도 요청하면 응답으로 모듈상태정보가 올라와서 사용할 수 없음.
    RequestJob(ASession, eVmsParamReq, NULL, 0);
#else
    if (ASession->State == eSS_LoginReq)
    {
        ASession->State = eSS_Connected;

        // 제어기가 최초 접속했을 때 마지막으로 시나리오를 전송한 시각과 다음 전송할 시각을 계산해서
        // 1분 이상 차이가 있을때에 시나리오를 전송하도록 한다.
        RequestJob(ASession, eVmsScenarioDownload, NULL, 0);
    }
#endif
    return 0;
}
//---------------------------------------------------------------------------

#if 0
//TODO: 이거 사용하면 OpCode가 중복이 되어 모듈상태정보 처리를 하지 못한다.
/////////////////////////////////////////////////////////
REGISTER_HANDLER(e_txt_pan_hetr_temp_res)
{
    int nLength = APktLen-sizeof(VMS_RES_HEAD)-sizeof(VMS_TAIL);
	if (nLength < (int)sizeof(VMS_TXT_PARAMETER))    // module count 2 byte
	{
        TERROR("%s.%d, e_txt_pan_hetr_temp_res Data Length error(%d). will be closed.", ASession->IpAddress.c_str(), ASession->Socket, nLength);
        MERROR("%s.%d, e_txt_pan_hetr_temp_res Data Length error(%d). will be closed.", ASession->IpAddress.c_str(), ASession->Socket, nLength);
		return -1;
	}
    TDEBUG("e_txt_pan_hetr_temp_res Length: %d", nLength);

    VMS_TXT_PARAMETER *pParam = (VMS_TXT_PARAMETER*)&AData[sizeof(VMS_RES_HEAD)];

    int nReqSize =  sizeof(VMS_TXT_PARAMETER);
	if (nLength != nReqSize)    // module count 2 byte
	{
        TERROR("%s.%d, e_txt_pan_hetr_temp_res Data Size error(%d, %d). will be closed.", ASession->IpAddress.c_str(), ASession->Socket, nLength, nReqSize);
        MERROR("%s.%d, e_txt_pan_hetr_temp_res Data Size error(%d, %d). will be closed.", ASession->IpAddress.c_str(), ASession->Socket, nLength, nReqSize);
        if (nLength == 2)
        {
             ASession->DisplayResponseError(AData);
        }
		return -2;
	}

    TCDSCtlr *AObj = ASession->CDSCtlr;
    if (AObj)
    {
        AObj->FAN_RUN_TMPR   = pParam->FanRunTemp;      // Fan의 동작개시온도           1 Byte  온도( 0x00 ~0x03f )
        AObj->HETR_RUN_TMPR  = pParam->HeaterRunTemp;   // Heater 의 동작개시온도       1 Byte  온도(0x00 ~ 0x3f )

        TDEBUG("VMS_TXT_PARAMETER: ");
        TDEBUG("                 FAN_RUN_TMPR: %d",   AObj->FAN_RUN_TMPR);
        TDEBUG("                HETR_RUN_TMPR: %02X", AObj->HETR_RUN_TMPR);

        CTLR_STTS stts;
        stts.Type = 2;
        stts.ObjPtr = (void*)AObj;

        INT_VMS_STATE  *FStts = &ASession->CDSCtlr->RSTATE;

        if (AObj->MODULE.IsOnOff)
        {
            if (AObj->MODULE.OnOff != AObj->PANL_PWER_MODE)
            {
                IPC_JOB_MESSAGE *pMsg = g_jobBuff.GetBuff();
                pMsg->Type    = eVmsStatusControl;
                pMsg->ObjPtr  = (DWORD)ASession;
                pMsg->Buff[0] = 0x01;
                pMsg->Buff[1] = ASession->CDSCtlr->MODULE.OnOff;// == vms_module_power_off ? 0x00 : 0x01;
                pMsg->Len     = 2;
                g_jobQ.PushBlocking((DWORD)pMsg);
            }
            else
            {
                AObj->MODULE.IsOnOff = false;
            }
        }
        //1분마다 주기적으로 상태정보를 업데이트 하니까 실시간으로 업데이트 할 필요가 없다.
        //운영단말로 실시간으로 데이터만 보내도록 하자
        APP_PostDbThreadWriteMessage(dbm_param_res, sizeof(stts), &stts);                        // 파라미터 저장
        POST_MSG(MAINHANDLE, WM_TCP_THREAD, WM_CTLR_STATE_STTS, (int)ASession->CDSCtlr);    // 상태정보 업데이트
    }

    if (ASession->State == eSS_LoginReq)
    {
        ASession->State = eSS_Connected;

        // 제어기가 최초 접속했을 때 마지막으로 시나리오를 전송한 시각과 다음 전송할 시각을 계산해서
        // 1분 이상 차이가 있을때에 시나리오를 전송하도록 한다.
        RequestJob(ASession, eVmsScenarioDownload, NULL, 0);
    }
    return 0;
}
//---------------------------------------------------------------------------
#endif

/////////////////////////////////////////////////////////
REGISTER_HANDLER(e_vms_status)
{
    TCDSCtlr *AObj = ASession->CDSCtlr;
    if (!AObj)
    {
        TERROR("%s.%d, e_vms_status Controller NULL. will be closed.", ASession->IpAddress.c_str(), ASession->Socket);
        MERROR("%s.%d, e_vms_status Controller NULL. will be closed.", ASession->IpAddress.c_str(), ASession->Socket);
        return -5;
    }
    if (ASession->State == eSS_LoginReq)
    {
        VMS_RES_HEAD *pRes = (VMS_RES_HEAD*)AData;

        if (pRes->Ctlr != (BYTE)AObj->CTLR_LOCAL_NO)
        {
            TERROR("%s.%d, e_vms_status Controller No Error: %d, %d.", ASession->IpAddress.c_str(), ASession->Socket, AObj->CTLR_LOCAL_NO, (int)pRes->Ctlr);
            MERROR("%s.%d, e_vms_status Controller No Error: %d, %d.", ASession->IpAddress.c_str(), ASession->Socket, AObj->CTLR_LOCAL_NO, (int)pRes->Ctlr);
            return -4;
        }
    }

    int nLength = APktLen-sizeof(VMS_RES_HEAD)-sizeof(VMS_TAIL);
	if (nLength < 2)
	{
        TERROR("%s.%d, e_vms_status Data Length error(%d). will be closed.", ASession->IpAddress.c_str(), ASession->Socket, nLength);
        MERROR("%s.%d, e_vms_status Data Length error(%d). will be closed.", ASession->IpAddress.c_str(), ASession->Socket, nLength);
		return -1;
	}
    TDEBUG("e_vms_status Length: %d", nLength);

    int nReqSize =  sizeof(VMS_STATUS);
	if (nLength != nReqSize)
	{
        TERROR("%s.%d, e_vms_status Data Size error(%d, %d). will be closed.", ASession->IpAddress.c_str(), ASession->Socket, nLength, nReqSize);
        MERROR("%s.%d, e_vms_status Data Size error(%d, %d). will be closed.", ASession->IpAddress.c_str(), ASession->Socket, nLength, nReqSize);
        if (nLength == 2)
        {
             ASession->DisplayResponseError(AData);
        }
		return -2;
	}

    VMS_STATUS *pStatus = (VMS_STATUS*)&AData[sizeof(VMS_RES_HEAD)];

    pStatus->FORM_NO = htons(pStatus->FORM_NO);
    //pStatus->BRIGHT  = htonl(pStatus->BRIGHT);

    TDEBUG("VMS_STATUS: Door(%02X), Power(%02X), Fan(%02X), Heater(%02X), FormNo(%d), Reboot(%02X), Temp(%02X,%d), Bright(%02X,%02X,%02X,%02X), ExtTemp(%02X,%d), ExtHum(%02X,%d)",
            pStatus->DOOR,
            pStatus->POWER,
            pStatus->FAN,
            pStatus->HEATER,
            pStatus->FORM_NO,
            pStatus->REBOOT_YN,
            pStatus->CBOX_TEMP,
            pStatus->CBOX_TEMP,
            pStatus->BRIGHT[0],
            pStatus->BRIGHT[1],
            pStatus->BRIGHT[2],
            pStatus->BRIGHT[3],
            pStatus->DP_TEMP,
            pStatus->DP_TEMP,
            pStatus->DP_HUM,
            pStatus->DP_HUM
            );

    INT_VMS_STATE *FStts = &AObj->RSTATE;

#if 0
    BYTE    DOOR;	    // Door Open/Close 상태	0x00 : Open, 0x01 : Close, 0x09 : Unknown
    BYTE    POWER;      // 전원의 ON/OFF 상태	0x00 : On, 0x01 : Off (Sign Board)
    BYTE    FAN;		// VMS Fan 동작상태		0x00 : On, 0x01 : Off, 0x09: Unknown
						// 함체 Fan 동작상태	0x00 : On, 0x10 : Off, 0x90: Unknown
    BYTE    HEATER;		// VMS Heater 동작상태	0x00 : On, 0x01 : Off, 0x09: Unknown
						// 함체 Heater 동작상태	x00 : On, 0x10 : Off, 0x90: Unknown
    WORD    FORM_NUM;	// 표출 폼 번호	0x00 : 통신 폼, 0x01 : 디폴트 폼
    BYTE    REBOOT_YN;	// 재실행 여부	0x00 : 정상, 0x01 : 재실행
    char    CBOX_TEMP;	// 함체온도	127 ~ -127 -128 : Unknown
    BYTE    BRIGHT[4];	// 화면의 밝기	최대를 100으로 했을 때의 백분율 값 및 기준휘도
                        // 0: 현재  휘도(00:주간,01:야간,02:자동)
                        // 1: 야간휘도설정값
                        // 2: 주간휘도설정값
                        // 3: 현재휘도값(이건 나의 추측)
    char    DP_TEMP;	// 표출부온도	127 ~ -127 -128 : Unknown
    BYTE    DP_HUM;		// 표출부습도	0~100%, 포항UTIS부터 추가함
#endif

    if      (pStatus->POWER == 0x01) FStts->ModulePowerStatus = vms_module_power_off;
    else if (pStatus->POWER == 0x00) FStts->ModulePowerStatus = vms_module_power_on;
    else                             FStts->ModulePowerStatus = vms_module_power_unknown;

    if      (pStatus->DOOR == 0x01) FStts->DoorStatus = vms_door_close;
    else if (pStatus->DOOR == 0x00) FStts->DoorStatus = vms_door_open;
    else                            FStts->DoorStatus = vms_door_unknown;

    // 2021.03.25 신규 추가 VMS
    // 랩에서 테스트시 장비가 연결되어 있지 않아서 9로 올라옴. ==> 현장에서는 정상적으로 올라올거라함.

    int S1, S2;

    // 둘다 꺼져 있으면 OFF, 하나라도 켜져 있으면 ON
    S1 = (pStatus->FAN & 0x0F);
    S2 = (pStatus->FAN & 0xF0) >> 4;
    if (S1 != 0 && S1 != 1) S1 = 1;
    if (S2 != 0 && S2 != 1) S2 = 1;
    if (S1 == 1 && S2 == 1)
        pStatus->FAN = 0x01;
    else
        pStatus->FAN = 0x00;

    //VMS : 0x00 : On, 0x01 : Off, 0x09: Unknown
    //함체: 0x00 : On, 0x10 : Off, 0x90: Unknown
    if      (pStatus->FAN == 0x00) FStts->FanStatus = vms_fan_on;
    else if (pStatus->FAN == 0x01) FStts->FanStatus = vms_fan_off;
    else if (pStatus->FAN == 0x10) FStts->FanStatus = vms_fan_off;
    else if (pStatus->FAN == 0x11) FStts->FanStatus = vms_fan_off;           // ??? 실제 현장 상황에 맞게
    else                           FStts->FanStatus = vms_fan_unknown;

    // 둘다 꺼져 있으면 OFF, 하나라도 켜져 있으면 ON
    S1 = (pStatus->HEATER & 0x0F);
    S2 = (pStatus->HEATER & 0xF0) >> 4;
    if (S1 != 0 && S1 != 1) S1 = 1;
    if (S2 != 0 && S2 != 1) S2 = 1;
    if (S1 == 1 && S2 == 1)
        pStatus->HEATER = 0x01;
    else
        pStatus->HEATER = 0x00;
    //VMS : 0x00 : On, 0x01 : Off, 0x09: Unknown
    //함체: 0x00 : On, 0x10 : Off, 0x90: Unknown
    if      (pStatus->HEATER == 0x00) FStts->HeaterStatus = vms_heater_on;
    else if (pStatus->HEATER == 0x01) FStts->HeaterStatus = vms_heater_off;
    else if (pStatus->HEATER == 0x10) FStts->HeaterStatus = vms_heater_off;
    else if (pStatus->HEATER == 0x11) FStts->HeaterStatus = vms_heater_off;     // // ??? 실제 현장 상황에 맞게
    else                              FStts->HeaterStatus = vms_heater_unknown;

    FStts->BodyTemp        = (short)pStatus->CBOX_TEMP;                             /* 함체온도값(℃), 범위(-128~127) */
    FStts->LuminanceStatus = (BYTE)pStatus->BRIGHT[3];                                 /* 화면의 밝기값 (최대 휘도값을 100으로 했을 때의 백분율 값), 범위(0~100) */
    FStts->Wcomm           = vms_comm_normal;// : vms_comm_error;   /* 무선통신상태, 0:정상 1:장애 */
    AObj->BRGH_WEEK_STEP   = pStatus->BRIGHT[2];
    AObj->BRGH_NGHT_STEP   = pStatus->BRIGHT[1];

    RequestJob(ASession, eVmsPowerModuleStautsReq, NULL, 0);
    return 0;
}
//---------------------------------------------------------------------------

/////////////////////////////////////////////////////////
REGISTER_HANDLER(e_vms_power_module_status)
{
    int nLength = APktLen-sizeof(VMS_RES_HEAD)-sizeof(VMS_TAIL);
	if (nLength < 1)    // module count 1 byte
	{
        TERROR("%s.%d, e_vms_power_module_status Data Length error(%d). will be closed.", ASession->IpAddress.c_str(), ASession->Socket, nLength);
        MERROR("%s.%d, e_vms_power_module_status Data Length error(%d). will be closed.", ASession->IpAddress.c_str(), ASession->Socket, nLength);
		return -1;
	}
    TDEBUG("e_vms_power_module_status Length: %d", nLength);

    BYTE *pData = &AData[sizeof(VMS_RES_HEAD)];
    int nModCnt = pData[0];
    // pData[0] ==> Reserved area

    int nReqSize =  (nModCnt+2);
	if (nLength != nReqSize)
	{
        TERROR("%s.%d, e_vms_power_module_status Data Size error(%d, %d). will be closed.", ASession->IpAddress.c_str(), ASession->Socket, nLength, nReqSize);
        MERROR("%s.%d, e_vms_power_module_status Data Size error(%d, %d). will be closed.", ASession->IpAddress.c_str(), ASession->Socket, nLength, nReqSize);
        if (nLength == 2)
        {
             ASession->DisplayResponseError(AData);
        }
		return -2;
	}

    TCDSCtlr *AObj = ASession->CDSCtlr;
    if (AObj)
    {
        INT_VMS_STATE *FStts = &ASession->CDSCtlr->RSTATE;
        FStts->PowerCount = nModCnt;
        for (int ii = 0; ii < nModCnt; ii++)
        {
            CComm_SetBitValue(FStts->PowerStatus, ii, pData[2+ii]);
        }
    }

    TDEBUG("VMS_POWER_MODULE COUNT: %d", nModCnt);
    AnsiString sModSts = "";
    AnsiString sTmp;
    for (int ii = 0; ii < nModCnt; ii++)
    {
        sTmp.printf("%d", pData[2+ii]);    //0x00 : Off, 0x01 : On, 0x02 : Unknown,
        sModSts += sTmp;
    }
    TDEBUG("VMS_POWER_MODULE STATUS: %s", sModSts.c_str());

    RequestJob(ASession, eVmsDisplayModuleStatusReq, NULL, 0);
    return 0;
}
//---------------------------------------------------------------------------

/////////////////////////////////////////////////////////
REGISTER_HANDLER(e_vms_display_module_status)
{
    int nLength = APktLen-sizeof(VMS_RES_HEAD)-sizeof(VMS_TAIL);
	if (nLength < 2)    // module count 2 byte
	{
        TERROR("%s.%d, e_vms_display_module_status Data Length error(%d). will be closed.", ASession->IpAddress.c_str(), ASession->Socket, nLength);
        MERROR("%s.%d, e_vms_display_module_status Data Length error(%d). will be closed.", ASession->IpAddress.c_str(), ASession->Socket, nLength);
		return -1;
	}
    TDEBUG("e_vms_display_module_status Length: %d", nLength);

    BYTE *pData = (BYTE*)&AData[sizeof(VMS_RES_HEAD)];
    int xCnt = pData[0];    // 1 Byte(X축) VMS 모듈수 //가로
    int yCnt = pData[1];    // 1 Byte(Y축) VMS 모듈수 //세로
    // 예)VMS 모듈수 : 2단 5열일 경우 모듈개수 (5(x), 2(y))를 표지한다.

    int nReqSize =  (xCnt*yCnt+2);
	if (nLength < nReqSize)    // module count 2 byte
	{
        TERROR("%s.%d, e_vms_display_module_status Data Size error(%d, %d). will be closed.", ASession->IpAddress.c_str(), ASession->Socket, nLength, nReqSize);
        MERROR("%s.%d, e_vms_display_module_status Data Size error(%d, %d). will be closed.", ASession->IpAddress.c_str(), ASession->Socket, nLength, nReqSize);
        if (nLength == 2)
        {
             ASession->DisplayResponseError(AData);
        }
		return -2;
	}

    int idx = 0;
    TCDSCtlr *AObj = ASession->CDSCtlr;
    if (AObj)
    {
        INT_VMS_STATE *FStts = &AObj->RSTATE;
        FStts->ModuleHorizontal = xCnt;                             /* 가로 모듈수 */
        FStts->ModuleVertical   = yCnt;                             /* 세로 모듈수 */

        idx = 0;
        for (int ii = 0; ii < yCnt; ii++)
        {
            for (int jj = 0; jj < xCnt; jj++)
            {
                //CComm_SetBitValue(FStts->ModuleStatus, idx, pData[2+idx]);
                CComm_SetBitValue(FStts->ModuleStatus, idx, pData[2+idx] == 0 ? 1 : 0);
                idx++;
            }
        }
    }

    TDEBUG("VMS_DISPLAY_MODULE : X(%d) Y(%d)", xCnt, yCnt);
    AnsiString sModSts = "";
    AnsiString sTmp;

    idx = 0;
    for (int ii = 0; ii < yCnt; ii++)
    {
        sModSts = "";
        for (int jj = 0; jj < xCnt; jj++)
        {
            sTmp.printf("%d", pData[2+idx]);    //0x00 : Off, 0x01 : On, 0x02 : Unknown,
            sModSts += sTmp;
            idx++;
        }
        TDEBUG("VMS_DISPLAY_MODULE: %02d, %s", ii+1, sModSts.c_str());
    }
    //백분율 컬럼 없음(프로토콜 문서에는 있는데 제어기에서 올리지 않음)
    //TDEBUG("VMS_DISPLAY_MODULE: Error Rate: 0x%02X, 0x%02X", pData[2+(xCnt*yCnt)], pData[2+(xCnt*yCnt)+1];

    RequestJob(ASession, eVmsParamReq, NULL, 0);
    return 0;
}
//---------------------------------------------------------------------------

/////////////////////////////////////////////////////////
REGISTER_HANDLER(e_vms_parameter)
{
    int nLength = APktLen-sizeof(VMS_RES_HEAD)-sizeof(VMS_TAIL);
	if (nLength < (int)sizeof(VMS_PARAMETER))    // module count 2 byte
	{
        TERROR("%s.%d, e_vms_parameter Data Length error(%d). will be closed.", ASession->IpAddress.c_str(), ASession->Socket, nLength);
        MERROR("%s.%d, e_vms_parameter Data Length error(%d). will be closed.", ASession->IpAddress.c_str(), ASession->Socket, nLength);
		return -1;
	}
    TDEBUG("e_vms_parameter Length: %d", nLength);

    VMS_PARAMETER *pParam = (VMS_PARAMETER*)&AData[sizeof(VMS_RES_HEAD)];

    int nReqSize =  sizeof(VMS_PARAMETER);
	if (nLength != nReqSize)    // module count 2 byte
	{
        TERROR("%s.%d, e_vms_parameter Data Size error(%d, %d). will be closed.", ASession->IpAddress.c_str(), ASession->Socket, nLength, nReqSize);
        MERROR("%s.%d, e_vms_parameter Data Size error(%d, %d). will be closed.", ASession->IpAddress.c_str(), ASession->Socket, nLength, nReqSize);
        if (nLength == 2)
        {
             ASession->DisplayResponseError(AData);
        }
		return -2;
	}

    TCDSCtlr *AObj = ASession->CDSCtlr;
    if (AObj)
    {
        AObj->PANL_PWER_MODE = pParam->PowerCtrlMode;   // 전원제어 모드                1 Byte  0x00 : 꺼짐, 0x01 : 켜짐,
        AObj->FAN_MODE       = pParam->FanRunMode;      // Fan 동작모드                 1 Byte  0x00 : 꺼짐, 0x01 : 켜짐, 0x02 : 자동, 0x09: Unknown
        AObj->FAN_RUN_TMPR   = pParam->FanRunTemp;      // Fan의 동작개시온도           1 Byte  온도( 0x00 ~0x03f )
        AObj->HETR_MODE      = pParam->HeaterRunMode;   // Heater의 동작모드            1 Byte  0x00 : 꺼짐, 0x01 : 켜짐, 0x02 : 자동, 0x09: Unknown
        AObj->HETR_RUN_TMPR  = pParam->HeaterRunTemp;   // Heater 의 동작개시온도       1 Byte  온도(0x00 ~ 0x3f )
        AObj->BRGH_MODE      = pParam->BrightMode;      // 밝기 모드                    2 Byte  0x0 : 수동, 0x1 : 자동, 비율 : 0-100
        AObj->BRGH_CURR_STEP = pParam->BrightRate;      // 밝기 모드                    2 Byte  0x0 : 수동, 0x1 : 자동, 비율 : 0-100
        //AObj->BRGH_WEEK_STEP = 0x00;                    // res.para.brghDay;     //	N	NUMBER(3)	Y	64		휘도 주간 단계(0~100)
        //AObj->BRGH_NGHT_STEP = 0x00;                    // res.para.brghNight;     //	N	NUMBER(3)	Y	48		휘도 야간 단계(0~100)
        AObj->ParamResTime.printf("%04d%02d%02d%02d%02d%02d",
                                  pParam->Year+2000,    // 년       1 Byte  0x00 ~ 0x32
                                  pParam->Mon,          // 월       1 Byte  0x01 ~ 0x0c
                                  pParam->Day,          // 일       1 Byte  0x01 ~ 0x1f
                                  pParam->Hour,         // 시       1 Byte  0x00 ~ 0x17
                                  pParam->Min,          // 분       1 Byte  0x00 ~ 0x3b
                                  pParam->Sec           // 초       1 Byte  0x00 ~ 0x3b
                                 );
#if 0
        pParam->BlinkTime;      // 깜빡이는 시간주기            1 Byte  문자 비트맵의 깜빡이는 시간주기 0x00 ~ 0x1e( 0.1 ~3.0 )
        pParam->ScnTurnTime;    // 디폴트 시나리오로 전환시간   2 Byte  디폴트 시나리오로 전환될 때까지 기다리는 시간, 단위 : 초
        pParam->Reserved;       // 기타                         1 Byte
#endif

        TDEBUG("VMS_PARAMETER: PANL_PWER_MODE: 0x%02X",     AObj->PANL_PWER_MODE);
        TDEBUG("                     FAN_MODE: 0x%02X",     AObj->FAN_MODE);
        TDEBUG("                 FAN_RUN_TMPR: 0x%02X, %d", AObj->FAN_RUN_TMPR, AObj->FAN_RUN_TMPR);
        TDEBUG("                    HETR_MODE: 0x%02X",     AObj->HETR_MODE);
        TDEBUG("                HETR_RUN_TMPR: 0x%02X, %d", AObj->HETR_RUN_TMPR, AObj->HETR_RUN_TMPR);
        TDEBUG("                    BRGH_MODE: 0x%02X",     AObj->BRGH_MODE);
        TDEBUG("               BRGH_CURR_STEP: 0x%02X, %d", AObj->BRGH_CURR_STEP, AObj->BRGH_CURR_STEP);
        TDEBUG("                   LOCAL_TIME: %s",         AObj->ParamResTime.c_str());

        CTLR_STTS stts;
        stts.Type = 2;
        stts.ObjPtr = (void*)AObj;

        // AObj->PANL_PWER_MODE 여기 정보가 모듈전원이 On/Off 된 것을 저장하고 있다.
        INT_VMS_STATE  *FStts = &ASession->CDSCtlr->RSTATE;
        //FStts->PowerCtrlStatus = pParam->PowerCtrlMode; // 전원제어 모드                1 Byte  0x00 : 꺼짐, 0x01 : 켜짐,
        if      (pParam->PowerCtrlMode == 0x00) FStts->PowerCtrlStatus = vms_module_power_off;
        else if (pParam->PowerCtrlMode == 0x01) FStts->PowerCtrlStatus = vms_module_power_on;
        else                                    FStts->PowerCtrlStatus = vms_module_power_unknown;

        memcpy(FStts->ControllerCurrentTime, AObj->ParamResTime.c_str(), INT_VMS_MAX_DATETIME);

        if (AObj->MODULE.IsOnOff)
        {
            if (AObj->MODULE.OnOff != AObj->PANL_PWER_MODE)
            {
                IPC_JOB_MESSAGE *pMsg = g_jobBuff.GetBuff();
                pMsg->Type    = eVmsStatusControl;
                pMsg->ObjPtr  = (DWORD)ASession;
                pMsg->Buff[0] = 0x01;
                pMsg->Buff[1] = ASession->CDSCtlr->MODULE.OnOff;// == vms_module_power_off ? 0x00 : 0x01;
                pMsg->Len     = 2;
                g_jobQ.PushBlocking((DWORD)pMsg);
            }
            else
            {
                AObj->MODULE.IsOnOff = false;
            }
        }
        //1분마다 주기적으로 상태정보를 업데이트 하니까 실시간으로 업데이트 할 필요가 없다.
        //운영단말로 실시간으로 데이터만 보내도록 하자
        if (AObj->OLD_PANL_PWER_MODE != AObj->PANL_PWER_MODE
         || AObj->OLD_FAN_MODE       != AObj->FAN_MODE
         || AObj->OLD_FAN_RUN_TMPR   != AObj->FAN_RUN_TMPR
         || AObj->OLD_HETR_MODE      != AObj->HETR_MODE
         || AObj->OLD_HETR_RUN_TMPR  != AObj->HETR_RUN_TMPR
         || AObj->OLD_BRGH_MODE      != AObj->BRGH_MODE
         || AObj->OLD_BRGH_CURR_STEP != AObj->BRGH_CURR_STEP
         || AObj->OLD_BRGH_WEEK_STEP != AObj->BRGH_WEEK_STEP
         || AObj->OLD_BRGH_NGHT_STEP != AObj->BRGH_NGHT_STEP)
        {
            AObj->OLD_PANL_PWER_MODE = AObj->PANL_PWER_MODE;
            AObj->OLD_FAN_MODE       = AObj->FAN_MODE;
            AObj->OLD_FAN_RUN_TMPR   = AObj->FAN_RUN_TMPR;
            AObj->OLD_HETR_MODE      = AObj->HETR_MODE;
            AObj->OLD_HETR_RUN_TMPR  = AObj->HETR_RUN_TMPR;
            AObj->OLD_BRGH_MODE      = AObj->BRGH_MODE;
            AObj->OLD_BRGH_CURR_STEP = AObj->BRGH_CURR_STEP;
            AObj->OLD_BRGH_WEEK_STEP = AObj->BRGH_WEEK_STEP;
            AObj->OLD_BRGH_NGHT_STEP = AObj->BRGH_NGHT_STEP;

            APP_PostDbThreadWriteMessage(dbm_param_res, sizeof(stts), &stts);                        // 파라미터 저장
        }
        POST_MSG(MAINHANDLE, WM_TCP_THREAD, WM_CTLR_STATE_STTS, (int)ASession->CDSCtlr);    // 상태정보 업데이트
    }

    if (ASession->State == eSS_LoginReq)
    {
        ASession->State = eSS_Connected;

        // 제어기가 최초 접속했을 때 마지막으로 시나리오를 전송한 시각과 다음 전송할 시각을 계산해서
        // 1분 이상 차이가 있을때에 시나리오를 전송하도록 한다.
        RequestJob(ASession, eVmsScenarioDownload, NULL, 0);
    }
    return 0;
}
//---------------------------------------------------------------------------

/////////////////////////////////////////////////////////
REGISTER_HANDLER(e_vms_pixel_image)
{
    // 요거는 제어기에서 응답을 하지 않음.
    int nLength = APktLen-sizeof(VMS_RES_HEAD)-sizeof(VMS_TAIL);
	if (nLength < (int)sizeof(VMS_PARAMETER))    // module count 2 byte
	{
        TERROR("%s.%d, e_vms_parameter Data Length error(%d). will be closed.", ASession->IpAddress.c_str(), ASession->Socket, nLength);
        MERROR("%s.%d, e_vms_parameter Data Length error(%d). will be closed.", ASession->IpAddress.c_str(), ASession->Socket, nLength);
		return -1;
	}
    TDEBUG("e_vms_parameter Length: %d", nLength);

    VMS_PARAMETER *pParam = (VMS_PARAMETER*)&AData[sizeof(VMS_RES_HEAD)];

    int nReqSize =  sizeof(VMS_PARAMETER);
	if (nLength != nReqSize)    // module count 2 byte
	{
        TERROR("%s.%d, e_vms_parameter Data Size error(%d, %d). will be closed.", ASession->IpAddress.c_str(), ASession->Socket, nLength, nReqSize);
        MERROR("%s.%d, e_vms_parameter Data Size error(%d, %d). will be closed.", ASession->IpAddress.c_str(), ASession->Socket, nLength, nReqSize);
        if (nLength == 2)
        {
             ASession->DisplayResponseError(AData);
        }
		return -2;
	}
    return 0;
}
//---------------------------------------------------------------------------

/////////////////////////////////////////////////////////
REGISTER_HANDLER(e_vms_current_display_form)
{
    int nLength = APktLen-sizeof(VMS_RES_HEAD)-sizeof(VMS_TAIL);
	if (nLength < (int)sizeof(VMS_PARAMETER))    // module count 2 byte
	{
        TERROR("%s.%d, e_vms_current_display_form Data Length error(%d). will be closed.", ASession->IpAddress.c_str(), ASession->Socket, nLength);
        MERROR("%s.%d, e_vms_current_display_form Data Length error(%d). will be closed.", ASession->IpAddress.c_str(), ASession->Socket, nLength);
		return -1;
	}
    TDEBUG("e_vms_current_display_form Length: %d", nLength);
    return 0;
}
//---------------------------------------------------------------------------

/////////////////////////////////////////////////////////
REGISTER_HANDLER(e_vms_display_default_form)
{
    int nLength = APktLen-sizeof(VMS_RES_HEAD)-sizeof(VMS_TAIL);
#if 0
	if (nLength < 1)    // ACK or NAK
	{
        TERROR("%s.%d, e_vms_display_default_form Data Length error(%d). will be closed.", ASession->IpAddress.c_str(), ASession->Socket, nLength);
        MERROR("%s.%d, e_vms_display_default_form Data Length error(%d). will be closed.", ASession->IpAddress.c_str(), ASession->Socket, nLength);
		return -1;
	}
#endif
    TDEBUG("e_vms_display_default_form Length: %d", nLength);

    VMS_RESULT *pRes = (VMS_RESULT*)&AData[sizeof(VMS_RES_HEAD)];
    if (pRes->Result != VMS_ACK)
    {
        TERROR("%s.%d, e_vms_display_default_form Result Error. Error: 0x%02X.", ASession->IpAddress.c_str(), ASession->Socket, pRes->Error);
        MERROR("%s.%d, e_vms_display_default_form Result Error. Error: 0x%02X.", ASession->IpAddress.c_str(), ASession->Socket, pRes->Error);
        ASession->DisplayResponseError(AData);
        return -2;
    }
    else
    {
        TINFO("e_vms_display_default_form : OK...");
    }
    return 0;
}
//---------------------------------------------------------------------------

/////////////////////////////////////////////////////////
REGISTER_HANDLER(e_vms_upload_schedule_form)
{
    int nLength = APktLen-sizeof(VMS_RES_HEAD)-sizeof(VMS_TAIL);
#if 0
	if (nLength < 1)    // ACK or NAK
	{
        TERROR("%s.%d, e_vms_upload_schedule_form Data Length error(%d). will be closed.", ASession->IpAddress.c_str(), ASession->Socket, nLength);
        MERROR("%s.%d, e_vms_upload_schedule_form Data Length error(%d). will be closed.", ASession->IpAddress.c_str(), ASession->Socket, nLength);
		return -1;
	}
#endif
    TDEBUG("e_vms_upload_schedule_form Length: %d", nLength);

    VMS_SCHEDULE_FORM *pRes = (VMS_SCHEDULE_FORM*)&AData[sizeof(VMS_RES_HEAD)];

    int nReqSize =  sizeof(VMS_SCHEDULE_FORM);
	if (nLength < nReqSize)
	{
        TERROR("%s.%d, e_vms_upload_schedule_form Data Size error(%d, %d). will be closed.", ASession->IpAddress.c_str(), ASession->Socket, nLength, nReqSize);
        MERROR("%s.%d, e_vms_upload_schedule_form Data Size error(%d, %d). will be closed.", ASession->IpAddress.c_str(), ASession->Socket, nLength, nReqSize);
        if (nLength == 2)
        {
             ASession->DisplayResponseError(AData);
        }
		return -2;
	}

    for (int ii = 0; ii < MAX_VMS_SCENARIO_FORM; ii++)
    {
        TDEBUG("e_vms_upload_schedule_form %02d: FormNo: %d, Display Second: %d", ii+1, ntohs(pRes->Form[ii].FormNo), pRes->Form[ii].DispSec);
    }
    return 0;
}
//---------------------------------------------------------------------------

/////////////////////////////////////////////////////////
REGISTER_HANDLER(e_vms_display_form_id)
{
    //프로토콜에는 있으나 제어기에서 반응을 하지 않음
    int nLength = APktLen-sizeof(VMS_RES_HEAD)-sizeof(VMS_TAIL);
#if 0
	if (nLength < 1)    // ACK or NAK
	{
        TERROR("%s.%d, e_vms_display_form_id Data Length error(%d). will be closed.", ASession->IpAddress.c_str(), ASession->Socket, nLength);
        MERROR("%s.%d, e_vms_display_form_id Data Length error(%d). will be closed.", ASession->IpAddress.c_str(), ASession->Socket, nLength);
		return -1;
	}
#endif
    TDEBUG("e_vms_display_form_id Length: %d", nLength);

    VMS_RESULT *pRes = (VMS_RESULT*)&AData[sizeof(VMS_RES_HEAD)];
    if (pRes->Result != VMS_ACK)
    {
        TERROR("%s.%d, e_vms_display_form_id Result Error. Error: 0x%02X.", ASession->IpAddress.c_str(), ASession->Socket, pRes->Error);
        MERROR("%s.%d, e_vms_display_form_id Result Error. Error: 0x%02X.", ASession->IpAddress.c_str(), ASession->Socket, pRes->Error);
        ASession->DisplayResponseError(AData);
        return -2;
    }
    else
    {
        TINFO("e_vms_display_form_id : OK...");
    }
    return 0;
}
//---------------------------------------------------------------------------

/////////////////////////////////////////////////////////
REGISTER_HANDLER(e_vms_status_control)
{
    //프로토콜에는 있으나 제어기에서 반응을 하지 않음
    int nLength = APktLen-sizeof(VMS_RES_HEAD)-sizeof(VMS_TAIL);
#if 0
	if (nLength < 1)    // ACK or NAK
	{
        TERROR("%s.%d, e_vms_status_control Data Length error(%d). will be closed.", ASession->IpAddress.c_str(), ASession->Socket, nLength);
        MERROR("%s.%d, e_vms_status_control Data Length error(%d). will be closed.", ASession->IpAddress.c_str(), ASession->Socket, nLength);
		return -1;
	}
#endif
    TDEBUG("e_vms_status_control Length: %d", nLength);

    VMS_RESULT *pRes = (VMS_RESULT*)&AData[sizeof(VMS_RES_HEAD)];
    if (pRes->Result != VMS_ACK)
    {
        TERROR("%s.%d, e_vms_status_control Result Error. Error: 0x%02X.", ASession->IpAddress.c_str(), ASession->Socket, pRes->Error);
        MERROR("%s.%d, e_vms_status_control Result Error. Error: 0x%02X.", ASession->IpAddress.c_str(), ASession->Socket, pRes->Error);
        ASession->DisplayResponseError(AData);
        return -2;
    }
    else
    {
        TINFO("e_vms_status_control : OK...");
    }

    RequestJob(ASession, eVmsStatusReq, NULL, 0);

    return 0;
}
//---------------------------------------------------------------------------

/////////////////////////////////////////////////////////
REGISTER_HANDLER(e_vms_download_form)
{
    int nLength = APktLen-sizeof(VMS_RES_HEAD)-sizeof(VMS_TAIL);
#if 0
	if (nLength < 1)    // ACK or NAK
	{
        TERROR("%s.%d, e_vms_download_form Data Length error(%d). will be closed.", ASession->IpAddress.c_str(), ASession->Socket, nLength);
        MERROR("%s.%d, e_vms_download_form Data Length error(%d). will be closed.", ASession->IpAddress.c_str(), ASession->Socket, nLength);
		return -1;
	}
#endif
    TDEBUG("e_vms_download_form Length: %d", nLength);

    VMS_RESULT *pRes = (VMS_RESULT*)&AData[sizeof(VMS_RES_HEAD)];
    if (pRes->Result != VMS_ACK)
    {
        TERROR("%s.%d, e_vms_download_form Result Error. Error: 0x%02X.", ASession->IpAddress.c_str(), ASession->Socket, pRes->Error);
        MERROR("%s.%d, e_vms_download_form Result Error. Error: 0x%02X.", ASession->IpAddress.c_str(), ASession->Socket, pRes->Error);
        ASession->DisplayResponseError(AData);
        return -2;
    }
    else
    {
        TINFO("e_vms_download_form : OK...");
    }

    // 폼정보를 계속해서 다운로드 한다.
    // 스케쥴 모드가 기본모드인 경우에는 폼정보가 하나만 내려가기때문에
    // 폼파일을 다운로드 해야 하고
    // 일반모드(자동, 고정) 인경우에는 폼정보를 계속해서 다운로드 해야 한다.
    if (ASession->CDSCtlr->FormDownload.IsDefault)
    {
        ASession->download_file_0x82();
    }
    else
    {
        ASession->download_form_0x9A();
    }

    return 0;
}
//---------------------------------------------------------------------------

/////////////////////////////////////////////////////////
REGISTER_HANDLER(e_vms_form_display)
{
    int nLength = APktLen-sizeof(VMS_RES_HEAD)-sizeof(VMS_TAIL);
#if 0
	if (nLength < 1)    // ACK or NAK
	{
        TERROR("%s.%d, e_vms_form_display Data Length error(%d). will be closed.", ASession->IpAddress.c_str(), ASession->Socket, nLength);
        MERROR("%s.%d, e_vms_form_display Data Length error(%d). will be closed.", ASession->IpAddress.c_str(), ASession->Socket, nLength);
		return -1;
	}
#endif
    TDEBUG("e_vms_form_display Length: %d", nLength);

    VMS_RESULT *pRes = (VMS_RESULT*)&AData[sizeof(VMS_RES_HEAD)];
    if (pRes->Result != VMS_ACK)
    {
        TERROR("%s.%d, e_vms_form_display Result Error. Error: 0x%02X.", ASession->IpAddress.c_str(), ASession->Socket, pRes->Error);
        MERROR("%s.%d, e_vms_form_display Result Error. Error: 0x%02X.", ASession->IpAddress.c_str(), ASession->Socket, pRes->Error);
        ASession->DisplayResponseError(AData);
        return -2;
    }
    else
    {
        TINFO("e_vms_form_display : OK...");
    }
    return 0;
}
//---------------------------------------------------------------------------

/////////////////////////////////////////////////////////
REGISTER_HANDLER(e_vms_download_schedule_form)
{
    //프로토콜에는 있으나 제어기에서 반응을 하지 않음
    int nLength = APktLen-sizeof(VMS_RES_HEAD)-sizeof(VMS_TAIL);
#if 0
	if (nLength < 1)    // ACK or NAK
	{
        TERROR("%s.%d, e_vms_download_schedule_form Data Length error(%d). will be closed.", ASession->IpAddress.c_str(), ASession->Socket, nLength);
        MERROR("%s.%d, e_vms_download_schedule_form Data Length error(%d). will be closed.", ASession->IpAddress.c_str(), ASession->Socket, nLength);
		return -1;
	}
#endif
    TDEBUG("e_vms_download_schedule_form Length: %d", nLength);

    VMS_RESULT *pRes = (VMS_RESULT*)&AData[sizeof(VMS_RES_HEAD)];
    if (pRes->Result != VMS_ACK)
    {
        TERROR("%s.%d, e_vms_download_schedule_form Result Error. Error: 0x%02X.", ASession->IpAddress.c_str(), ASession->Socket, pRes->Error);
        MERROR("%s.%d, e_vms_download_schedule_form Result Error. Error: 0x%02X.", ASession->IpAddress.c_str(), ASession->Socket, pRes->Error);
        ASession->DisplayResponseError(AData);
        return -2;
    }
    else
    {
        TINFO("e_vms_download_schedule_form : OK...");
    }

    // 스케쥴 표출 마지막 데이터 전송
    ASession->download_blank_0x9E();

    return 0;
}
//---------------------------------------------------------------------------

/////////////////////////////////////////////////////////
REGISTER_HANDLER(e_vms_file_download)
{
    //프로토콜에는 있으나 제어기에서 반응을 하지 않음
    int nLength = APktLen-sizeof(VMS_RES_HEAD)-sizeof(VMS_TAIL);
#if 0
	if (nLength < 1)    // ACK or NAK
	{
        TERROR("%s.%d, e_vms_file_download Data Length error(%d). will be closed.", ASession->IpAddress.c_str(), ASession->Socket, nLength);
        MERROR("%s.%d, e_vms_file_download Data Length error(%d). will be closed.", ASession->IpAddress.c_str(), ASession->Socket, nLength);
		return -1;
	}
#endif
    TDEBUG("e_vms_file_download Length: %d", nLength);

    TDownloadForm *pInfo = NULL;
    TCDSCtlr *AObj = ASession->CDSCtlr;
    if (AObj)
    {
        pInfo = AObj->FDownloadLists.Find(AObj->DownloadFormId);
    }

    VMS_RESULT *pRes = (VMS_RESULT*)&AData[sizeof(VMS_RES_HEAD)];
    if (pRes->Result != VMS_ACK)
    {
        if (pInfo)
        {
            pInfo->AlreadyDownload = false;
        }
        TERROR("%s.%d, e_vms_file_download Result Error. Error: 0x%02X.", ASession->IpAddress.c_str(), ASession->Socket, pRes->Error);
        MERROR("%s.%d, e_vms_file_download Result Error. Error: 0x%02X.", ASession->IpAddress.c_str(), ASession->Socket, pRes->Error);
        ASession->DisplayResponseError(AData);
        return -2;
    }
    else
    {
        if (pInfo)
        {
            pInfo->AlreadyDownload = true;
            pInfo->DownloadTm      = Now();
        }
        TINFO("e_vms_file_download : OK...");
    }

    // 폼이미지를 계속해서 다운로드 한다.
    ASession->download_file_0x82();
    return 0;
}
//---------------------------------------------------------------------------

/////////////////////////////////////////////////////////
REGISTER_HANDLER(e_vms_blank)
{
    int nLength = APktLen-sizeof(VMS_RES_HEAD)-sizeof(VMS_TAIL);
#if 0
	if (nLength < 1)    // ACK or NAK
	{
        TERROR("%s.%d, e_vms_blank Data Length error(%d). will be closed.", ASession->IpAddress.c_str(), ASession->Socket, nLength);
        MERROR("%s.%d, e_vms_blank Data Length error(%d). will be closed.", ASession->IpAddress.c_str(), ASession->Socket, nLength);
		return -1;
	}
#endif
    TDEBUG("e_vms_blank Length: %d", nLength);

    VMS_RESULT *pRes = (VMS_RESULT*)&AData[sizeof(VMS_RES_HEAD)];
    if (pRes->Result != VMS_ACK)
    {
        TERROR("%s.%d, e_vms_blank Result Error. Error: 0x%02X.", ASession->IpAddress.c_str(), ASession->Socket, pRes->Error);
        MERROR("%s.%d, e_vms_blank Result Error. Error: 0x%02X.", ASession->IpAddress.c_str(), ASession->Socket, pRes->Error);
        ASession->DisplayResponseError(AData);
        return -2;
    }
    else
    {
        TINFO("e_vms_blank : OK...");
    }

    if (ASession->CDSCtlr && ASession->CDSCtlr->FormDownload.IsDefault)
    {
        // 기본스케쥴인 경우에는 BLANK 명령을 내려보내지 말아야 한다.
        //ASession->ReqDisplayDefaultForm();
        //return download_form_schedule_complete();
    }

    // 폼 스케쥴 정보 다운로드 완료 메시지 처리
    ASession->download_form_schedule_complete();
    return 0;
}
//---------------------------------------------------------------------------

int TClientSession::ReqStauts()
{
    TCDSCtlr *AObj = FCDSCtlr;
    if (!AObj) return -1;

    VMS_REQ_DATA req;

    req.OpCode = (AObj->PROTOCOL_VER == 1) ? e_txt_status_req : e_vms_status;
    req.Group  = AObj->GROUP_NO;
    req.Ctlr   = AObj->CTLR_LOCAL_NO;

    if (!SendPacket((char*)&req, sizeof(VMS_REQ_DATA)))
    {
        SERROR("+CLI ReqStauts send request faild: %s will be closed.", FIpAddress.c_str());
        MERROR("+CLI ReqStauts send request faild: %s will be closed.", FIpAddress.c_str());
        Disconnect();
        return -1;
    }
    return 1;
}
//---------------------------------------------------------------------------

int TClientSession::ReqPowerModuleStatus()
{
    TCDSCtlr *AObj = FCDSCtlr;
    if (!AObj) return -1;

    VMS_REQ_DATA req;

    req.OpCode = e_vms_power_module_status;
    req.Group  = AObj->GROUP_NO;
    req.Ctlr   = AObj->CTLR_LOCAL_NO;

    if (!SendPacket((char*)&req, sizeof(VMS_REQ_DATA)))
    {
        SERROR("+CLI ReqPowerModuleStatus send request faild: %s will be closed.", FIpAddress.c_str());
        MERROR("+CLI ReqPowerModuleStatus send request faild: %s will be closed.", FIpAddress.c_str());
        Disconnect();
        return -1;
    }
    return 1;
}
//---------------------------------------------------------------------------

int TClientSession::ReqDisplayModuelStatus()
{
    TCDSCtlr *AObj = FCDSCtlr;
    if (!AObj) return -1;

    VMS_REQ_DATA req;

    req.OpCode = (AObj->PROTOCOL_VER == 1) ? e_txt_failed_elem_data_req : e_vms_display_module_status;
    req.Group  = AObj->GROUP_NO;
    req.Ctlr   = AObj->CTLR_LOCAL_NO;

    if (!SendPacket((char*)&req, sizeof(VMS_REQ_DATA)))
    {
        SERROR("+CLI ReqDisplayModuelStatus send request faild: %s will be closed.", FIpAddress.c_str());
        MERROR("+CLI ReqDisplayModuelStatus send request faild: %s will be closed.", FIpAddress.c_str());
        Disconnect();
        return -1;
    }
    return 1;
}
//---------------------------------------------------------------------------


int TClientSession::ReqParameter()
{
    TCDSCtlr *AObj = FCDSCtlr;
    if (!AObj) return -1;

    VMS_REQ_DATA req;

#if 0
    // 설정온도 요청하면 모듈상태정보가 응답으로 올라온다
    // 프로토콜의 OpCode도 동일하다.
    req.OpCode = (AObj->PROTOCOL_VER == 1) ? e_txt_pan_hetr_temp_req : e_vms_parameter;
#else
    req.OpCode = e_vms_parameter;
#endif
    req.Group  = AObj->GROUP_NO;
    req.Ctlr   = AObj->CTLR_LOCAL_NO;

    if (!SendPacket((char*)&req, sizeof(VMS_REQ_DATA)))
    {
        SERROR("+CLI ReqParameter send request faild: %s will be closed.", FIpAddress.c_str());
        MERROR("+CLI ReqParameter send request faild: %s will be closed.", FIpAddress.c_str());
        Disconnect();
        return -1;
    }
    return 1;
}
//---------------------------------------------------------------------------

int TClientSession::ReqPixelImage(char *ACmd)
{
    TCDSCtlr *AObj = FCDSCtlr;
    if (!AObj) return -1;

    VMS_REQ_INFO_DATA req;

    req.OpCode = e_vms_pixel_image;
    req.Group  = AObj->GROUP_NO;
    req.Ctlr   = AObj->CTLR_LOCAL_NO;
    req.Data[0] = ACmd[0];
    req.Length  = 1;

    if (!SendPacket((char*)&req, sizeof(VMS_REQ_DATA)+1))
    {
        SERROR("+CLI ReqPixelImage send request faild: %s will be closed.", FIpAddress.c_str());
        MERROR("+CLI ReqPixelImage send request faild: %s will be closed.", FIpAddress.c_str());
        Disconnect();
        return -1;
    }
    return 1;
}
//---------------------------------------------------------------------------

int TClientSession::ReqUploadCurrentForm()
{
    TCDSCtlr *AObj = FCDSCtlr;
    if (!AObj) return -1;

    VMS_REQ_DATA req;

    req.OpCode = e_vms_current_display_form;
    req.Group  = AObj->GROUP_NO;
    req.Ctlr   = AObj->CTLR_LOCAL_NO;

    if (!SendPacket((char*)&req, sizeof(VMS_REQ_DATA)))
    {
        SERROR("+CLI ReqUploadCurrentForm send request faild: %s will be closed.", FIpAddress.c_str());
        MERROR("+CLI ReqUploadCurrentForm send request faild: %s will be closed.", FIpAddress.c_str());
        Disconnect();
        return -1;
    }
    return 1;
}
//---------------------------------------------------------------------------

int TClientSession::ReqDisplayDefaultForm()
{
    TCDSCtlr *AObj = FCDSCtlr;
    if (!AObj) return -1;

    VMS_REQ_DATA req;

    req.OpCode = e_vms_display_default_form;
    req.Group  = AObj->GROUP_NO;
    req.Ctlr   = AObj->CTLR_LOCAL_NO;

    if (!SendPacket((char*)&req, sizeof(VMS_REQ_DATA)))
    {
        SERROR("+CLI ReqDisplayDefaultForm send request faild: %s will be closed.", FIpAddress.c_str());
        MERROR("+CLI ReqDisplayDefaultForm send request faild: %s will be closed.", FIpAddress.c_str());
        Disconnect();
        return -1;
    }
    return 1;
}
//---------------------------------------------------------------------------

int TClientSession::ReqUploadScheduleForm()
{
    TCDSCtlr *AObj = FCDSCtlr;
    if (!AObj) return -1;

    VMS_REQ_DATA req;

    req.OpCode = e_vms_upload_schedule_form;
    req.Group  = AObj->GROUP_NO;
    req.Ctlr   = AObj->CTLR_LOCAL_NO;

    if (!SendPacket((char*)&req, sizeof(VMS_REQ_DATA)))
    {
        SERROR("+CLI ReqUploadScheduleForm send request faild: %s will be closed.", FIpAddress.c_str());
        MERROR("+CLI ReqUploadScheduleForm send request faild: %s will be closed.", FIpAddress.c_str());
        Disconnect();
        return -1;
    }
    return 1;
}
//---------------------------------------------------------------------------

int TClientSession::ReqDisplayFormId(char *ACmd)
{
    TCDSCtlr *AObj = FCDSCtlr;
    if (!AObj) return -1;

    VMS_REQ_INFO_DATA req;

    req.OpCode = e_vms_display_form_id;
    req.Group  = AObj->GROUP_NO;
    req.Ctlr   = AObj->CTLR_LOCAL_NO;
    req.Data[0] = 0;//ACmd[0];
    req.Data[1] = 0;//ACmd[2];
    req.Length  = 2;

    if (!SendPacket((char*)&req, sizeof(VMS_REQ_DATA)+2))
    {
        SERROR("+CLI ReqDisplayFormId send request faild: %s will be closed.", FIpAddress.c_str());
        MERROR("+CLI ReqDisplayFormId send request faild: %s will be closed.", FIpAddress.c_str());
        Disconnect();
        return -1;
    }
    return 1;
}
//---------------------------------------------------------------------------

int TClientSession::ReqStatusControl(char *ACmd, int ALen)
{
    TCDSCtlr *AObj = FCDSCtlr;
    if (!AObj) return -1;

    char *pSendData = NULL;
    int   nSendByte = 0;

    if (AObj->PROTOCOL_VER == 1)
    {
        VMS_REQ_INFO_DATA req;

        req.Group   = AObj->GROUP_NO;
        req.Ctlr    = AObj->CTLR_LOCAL_NO;

        if (ACmd[0] == 0x01)
        {
            //SignBoard On/Off
            req.OpCode  = e_txt_signboard_control;
            req.Length  = 1;
            req.Data[0] = ACmd[1];   //Power Off=0, Power On = 1

            pSendData = (char*)&req;
            nSendByte = sizeof(VMS_REQ_DATA)+req.Length;
        }
        else
        if (ACmd[0] == 0x02)
        {
            //Initialize(Reset)
            req.OpCode  = e_txt_initialize;
            req.Length  = 0;

            pSendData = (char*)&req;
            nSendByte = sizeof(VMS_REQ_DATA)+req.Length;
        }
        else
        if (ACmd[0] == 0x06)
        {
            //Set luminance Level
            req.OpCode  = e_txt_set_luminance_level;
            req.Length  = 1;
            req.Data[0] = ACmd[1];
            switch(ACmd[1]) //도형식과 비교해서 값이 다름
            {
            case 0x00:  //주간
                req.Data[0] = 1;
                break;
            case 0x01:  //야간
                req.Data[0] = 2;
                break;
            case 0x02:  //자동
                req.Data[0] = 0;
                break;
            }

            pSendData = (char*)&req;
            nSendByte = sizeof(VMS_REQ_DATA)+req.Length;
        }
    }
    else
    {
        VMS_REQ_INFO_DATA req;

        req.OpCode = e_vms_status_control;
        req.Group  = AObj->GROUP_NO;
        req.Ctlr   = AObj->CTLR_LOCAL_NO;
        memcpy(req.Data, ACmd, ALen);
        req.Length = ALen;

        pSendData = (char*)&req;
        nSendByte = sizeof(VMS_REQ_DATA)+ALen;
    }

    if (pSendData == NULL || nSendByte == 0)
    {
        return 1;
    }
    if (!SendPacket(pSendData, nSendByte))
    {
        SERROR("+CLI ReqStatusControl send request faild: %s will be closed.", FIpAddress.c_str());
        MERROR("+CLI ReqStatusControl send request faild: %s will be closed.", FIpAddress.c_str());
        Disconnect();
        return -1;
    }
    return 1;
}
//---------------------------------------------------------------------------

int TClientSession::download_form_schedule_complete()
{
    // VMS 메시지 다운로드 완료
    TCDSCtlr *AObj = FCDSCtlr;
    if (AObj)
    {
        if (AObj->CTRLMODE->Schedule)
        {
            VMS_PROVIDE_RESULE ProvideSave;

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

            ProvideSave.Type    = provide_form;
            ProvideSave.Count   = 1;
            ProvideSave.pObj[0] = (void*)AObj;

            AObj->CTRLMODE->Enable   = object_disable;
            AObj->CTRLMODE->SvcDate  = Now().FormatString("yyyymmddhhnnss");
            AObj->CTRLMODE->SaveFlag = true;
            AObj->CTRLMODE->Result   = true;

            APP_PostDbThreadWriteMessage(dbm_provide_result, sizeof(ProvideSave), &ProvideSave);
        }
    }
    return 0;
}
//---------------------------------------------------------------------------

int TClientSession::download_form_schedule(bool ASchedule/*=true*/)
{
    TCDSCtlr *AObj = FCDSCtlr;
    if (!AObj) return -1;

    if (ASchedule)
    {
        LDEBUG("Download Form Schedule by schedule...");
    }
    else
    {
        LDEBUG("Download Form Schedule by user control...");
    }

    AObj->CTRLMODE->Schedule = ASchedule;   // 스케쥴 모드인 경우 디비에 저장한다.

    //다운로드 정보만 초기화 한다.
    memset((char*)&AObj->FormDownload, 0x00, sizeof(VMS_DOWNLOAD_DATA));
    AObj->FTxtOpCode == 0x00;

    int nForms = 0;
    int nFormCnt = 0;

    AObj->pForms->Lock();
	try
	{
        nFormCnt = AObj->pForms->Count();
        if (nFormCnt == 0)
        {
            return 0;
        }
        if (nFormCnt > MAX_VMS_SCENARIO_FORM) {
            MERROR("+CLI %25.25s: %s, Form Count Over: %d/%d EA.", __MYFUNC__, AObj->CTLR_NMBR.c_str(), nFormCnt, MAX_VMS_SCENARIO_FORM);
            nFormCnt = MAX_VMS_SCENARIO_FORM;
        }

	    for (int ii = 0; ii < nFormCnt; ii++)
	    {
            TVmsForm *pForm = AObj->pForms->GetItem(ii);
            if (!pForm->Success)
            {
                continue;
            }
            if (pForm->fileType == P_FILE_TYPE_VIDEO  || pForm->fileType == P_FILE_TYPE_STREAM)
            {
                continue;
            }
            if (!pForm->pStream || pForm->pStream->Size == 0)
            {
                continue;
            }

            AObj->FormDownload.Info[nForms].VMS_FORM_ID = pForm->VMS_FORM_ID;
            AObj->FormDownload.Info[nForms].IsDownload  = true;
            AObj->FormDownload.Info[nForms].FormIdx     = ii;                       // 리스트상의 순서
            if (AObj->PROTOCOL_VER == 1)
            {
                //문자식 프로토콜 적용
                //AObj->FormDownload.Info[nForms].BitmapId = (pForm->VMS_FORM_ID.ToIntDef(0) % 1000) + TEXT_BASE_FORMID;  // 리스트상의 순서
                AObj->FormDownload.Info[nForms].BitmapId = nForms + TEXT_BASE_FORMID;  // 리스트상의 순서
                AObj->FormDownload.Info[nForms].FormNo   = AObj->FormDownload.Info[nForms].BitmapId;                    // 실재 다운로드되는 순서
            }
            else
            {
                //도형식 프로토콜 적용
                //AObj->FormDownload.Info[nForms].BitmapId = (pForm->VMS_FORM_ID.ToIntDef(0) % 1000) + 1000;              // 리스트상의 순서
                AObj->FormDownload.Info[nForms].BitmapId = nForms + 1000;                                               // 리스트상의 순서
                AObj->FormDownload.Info[nForms].FormNo   = PICTURE_BASE_FORMID+nForms;                                  // 실재 다운로드되는 순서
            }
            AObj->FormDownload.Info[nForms].DispSec = (BYTE)pForm->DSPL_HH;

            TDownloadForm *pInfo    = AObj->FDownloadLists.Find(pForm->VMS_FORM_ID);
            TCDSForm      *pCDSForm = CDSFormManager->FLists.Find(pForm->VMS_FORM_ID);
            if (pCDSForm)
            {
                if (pCDSForm->VMS_FORM_TYPE_CD == eFormTp_hongbo)
                {
                    if (AObj->PROTOCOL_VER == 1)
                    {
                        //문자식 프로토콜 적용
                        AObj->FormDownload.Info[nForms].BitmapId = (pForm->VMS_FORM_ID.ToIntDef(0) % 1000) + TEXT_BASE_FORMID;  // 리스트상의 순서
                        AObj->FormDownload.Info[nForms].FormNo   = AObj->FormDownload.Info[nForms].BitmapId;                    // 실재 다운로드되는 순서
                    }
                    else
                    {
                        //도형식 프로토콜 적용
                        AObj->FormDownload.Info[nForms].BitmapId = (pForm->VMS_FORM_ID.ToIntDef(0) % 1000) + 1000;              // 리스트상의 순서
                    }
                }

                //홍보폼이면서 신규폼이 아니면서 이전 다운로드 목록이 존재하는 경우에 다운로드 여부를 체크한다.
                if (pCDSForm->VMS_FORM_TYPE_CD == eFormTp_hongbo && pCDSForm->IsNewForm == false && pInfo)
                {
                    if (pInfo->AlreadyDownload)
                    {
                        // 이미 이전에 다운로드를 했기때문에 이번에는 제어기로 다운로드를 하지 않는다.
                        AObj->FormDownload.Info[nForms].IsDownload = false;
                    }
                }
                //이전에 다운로드한 정보가 존재하면
                if (pInfo)
                {
                    if (pInfo->UPDT_DT != pCDSForm->UPDT_DT)
                    {
                        // 업데이트시각이 다르기때문에 신규폼으로 판단한다.
                        pInfo->AlreadyDownload = false;
                        AObj->FormDownload.Info[nForms].IsDownload = true;
                        pInfo->UPDT_DT = pCDSForm->UPDT_DT;
                    }
                }
            }
            if (!pInfo && pCDSForm)
            {
                pInfo = AObj->FDownloadLists.Find(pForm->VMS_FORM_ID);
                if (!pInfo)
                {
                    pInfo = new TDownloadForm();
                    if (pInfo)
                    {
                        //신규로추가
                        pInfo->VMS_FORM_ID = pForm->VMS_FORM_ID;
                        AObj->FDownloadLists.Push(pInfo->VMS_FORM_ID, pInfo);
                    }
                }
                if (pInfo)
                {
                    //다운로드정보설정
                    pInfo->AlreadyDownload = false;
                    pInfo->UPDT_DT = pCDSForm->UPDT_DT;
                }
            }

            nForms++;
            if (nForms >= MAX_VMS_SCENARIO_FORM)
            {
                // 최대폼까지 다운로드
                break;
            }
        }
	}
	__finally
	{
        AObj->pForms->UnLock();
	}

    for (int jj = 0; jj < nFormCnt; jj++)
    {
        LDEBUG("Form schedule(%2d), VMS_FORM_ID: %s, FormIdx: %d, FormId: %d, BitmapId: %d, IsDownload: %s",
            jj,
            AObj->FormDownload.Info[jj].VMS_FORM_ID.c_str(),
            AObj->FormDownload.Info[jj].FormIdx,
            AObj->FormDownload.Info[jj].FormNo,
            AObj->FormDownload.Info[jj].BitmapId,
            AObj->FormDownload.Info[jj].IsDownload ? "true" : "false");
    }

    if (nForms <= 0)
    {
        return 0;
    }

    AObj->FormDownload.MaxSchedule = nForms;
    AObj->FormDownload.DownloadCnt = 0;

    if (AObj->PROTOCOL_VER == 1)
    {
        //문자식 프로토콜 적용
        AObj->FormDownload.IsDefault = false;
        download_lib_form_0x0A();
    }
    else
    {
        //도형식 프로토콜 적용
        if (AObj->OPER_MODE == "B")
        {
            // 기본모드인 경우
            //e_vms_download_form          = 0x9A,//    Download Form                           송신    Form download                               센터 → VMS
            //e_vms_file_download          = 0x82,//    데이터 다운로드                         송신    INI, CFG , Bitmap , Data파일송신            센터 → VMS
            //e_vms_download_schedule_form = 0x96,//    Display Schedule Form                   송신    계획된 Form 표출 요구                       센터 → VMS
            //e_vms_blank                  = 0x9E,//    Blank                                   송신    schedule 표출                               센터 → VMS
            AObj->FormDownload.IsDefault = true;
            download_default_form_0x9A();         // Download Form  (기본폼은 하나의 폼에 여러폼을 다운로드한다.)
        }
        else
        {
            // 스케쥴 모드인 경우(A:자동, F:고정)
            //e_vms_download_form          = 0x9A,//    Download Form                           송신    Form download                               센터 → VMS
            //e_vms_file_download          = 0x82,//    데이터 다운로드                         송신    INI, CFG , Bitmap , Data파일송신            센터 → VMS
            //e_vms_download_schedule_form = 0x96,//    Display Schedule Form                   송신    계획된 Form 표출 요구                       센터 → VMS
            //e_vms_blank                  = 0x9E,//    Blank                                   송신    schedule 표출                               센터 → VMS
            AObj->FormDownload.IsDefault = false;
            download_form_0x9A();         // Download Form  (기본폼은 하나의 폼에 여러폼을 다운로드한다.)
        }
    }
    return 1;
}
//---------------------------------------------------------------------------

int TClientSession::download_default_form_0x9A()
{
    IPC_JOB_MESSAGE *pMsg = g_jobBuff.GetBuff();
    TCDSCtlr *AObj = FCDSCtlr;
    if (!AObj) return -1;

    BYTE               *msgPtr;
    // 파일다운로드
    VMS_HEAD           *pHead;
    VMS_FILE_DATA      *pFile;
    char               *pStrm;

    // 폼다운로드
    VMS_FORM_HEAD      *pForm;
    VMS_FORM_ID_DATA   *pData;

    WORD crc;
    int  nPktSize;

    msgPtr = (BYTE*)pMsg->Buff;
    pHead  = (VMS_HEAD*)&msgPtr[0];
    pForm  = (VMS_FORM_HEAD*)&msgPtr[sizeof(VMS_HEAD)];
    pData  = (VMS_FORM_ID_DATA*)&msgPtr[sizeof(VMS_HEAD)+sizeof(VMS_FORM_HEAD)];

    pHead->Dle    = VMS_DLE;
    pHead->Stx    = VMS_STX;
    pHead->Group  = AObj->GROUP_NO;
    pHead->Ctlr   = AObj->CTLR_LOCAL_NO;
    pHead->OpCode = e_vms_download_form;
    pHead->Curr   = 1;
    pHead->Total  = 1;
    pHead->Length = 0;

    int nFormId  = DEFAULT_FORMID;
    int nFormCnt = AObj->FormDownload.MaxSchedule;   // 폼정보는 하나만 내려보내야 한다. 제어기에서 수용하지 못함

    LDEBUG("download_default_form_0x9A: FormId: %d, FormCnt: %d", nFormId, nFormCnt);

    pForm->FORM_ID  = htons(nFormId);
    pForm->FORM_CNT = htons(nFormCnt);

    pHead->Length = sizeof(VMS_FORM_HEAD)+(sizeof(VMS_FORM_ID_INFO)*nFormCnt);

    for (int ii = 0; ii < nFormCnt; ii++)
    {
        pData->INFO[ii].data.FORM_SEQ     = htons(ii);                                  // 폼 표출 일련번호,        2Byte
        pData->INFO[ii].data.DISPLAY_TIME = 4;                                          // 폼의 표출시간을 지정,    1Byte( 0x00 이면 계속 표출 ) ==> 제어기에서 사용안함
        pData->INFO[ii].data.DISPLAY_TYPE = e_static_normal;                            // 폼의 표출유형을 지정,    1Byte
        pData->INFO[ii].data.BG_RGB       = e_bg_black;                                 // 폼의 배경색을 지정,      1Byte
        pData->INFO[ii].data.OBJ_CNT      = 1;                                          // 표출할 오브젝트 전체 수, 1Byte

        pData->INFO[ii].obj.OBJ_TYPE    = e_obj_bitmapid;                               // 오브젝트 종류
        pData->INFO[ii].obj.OBJ_SIZE    = htons(sizeof(VMS_OBJ_BITMAPID));              // 오브젝트 데이터 크기
        pData->INFO[ii].obj.FLASH       = 0x00;                                         // 점멸여부, 1Byte(0x00 : 고정, 0x01 : 점멸)
        pData->INFO[ii].obj.X           = htons(0);                                     // 좌표 X
        pData->INFO[ii].obj.Y           = htons(0);                                     // 좌표 Y
        pData->INFO[ii].obj.TEXT_BG_RGB = e_bg_black;                                   // 문자열 배경색을 지정

        pData->INFO[ii].bid.WIDTH     = htons(AObj->WIDTH);                             // 비트맵 표시 Width,  2 Byte, 0 ~ 1023 : 표출 비트맵 Width
        pData->INFO[ii].bid.HEIGHT    = htons(AObj->HEIGHT);                            // 비트맵 표시 Heitht, 2 Byte, 0 ~ 1023 : 표출 비트맵 Width
        pData->INFO[ii].bid.IMG_TYPE  = e_img_bitmap;                                   // e_img_type
        pData->INFO[ii].bid.BITMAP_ID = htons(AObj->FormDownload.Info[ii].BitmapId);    // 표출할 비트맵 ID,   2 Byte, 0～ 9999 : 표출할 비트맵 ID

        LDEBUG("download_default_form_0x9A: FormSeq: %d, FormId: %d", ii, AObj->FormDownload.Info[ii].BitmapId);
    }

    nPktSize = sizeof(VMS_HEAD)+pHead->Length-2; //DLE/STX
    crc  = GETCRC16((char*)&pHead->Group, nPktSize);
    msgPtr[sizeof(VMS_HEAD)+pHead->Length+0] = VMS_DLE;
    msgPtr[sizeof(VMS_HEAD)+pHead->Length+1] = VMS_ETX;
    msgPtr[sizeof(VMS_HEAD)+pHead->Length+2] = HIBYTE(crc);
    msgPtr[sizeof(VMS_HEAD)+pHead->Length+3] = LOBYTE(crc);

    SendPacketDLE((char*)msgPtr, nPktSize+6);
    return 1;
}
//---------------------------------------------------------------------------

int TClientSession::download_form_0x9A()
{
    IPC_JOB_MESSAGE *pMsg = g_jobBuff.GetBuff();
    TCDSCtlr *AObj = FCDSCtlr;
    if (!AObj) return -1;

    if (AObj->FormDownload.DownloadCnt && AObj->FormDownload.MaxSchedule &&
        AObj->FormDownload.DownloadCnt >= AObj->FormDownload.MaxSchedule)
    {
        // 폼정보를 모두 다운로드 했기때문에
        // 폼파일을 다운로드 해야 한다.
        AObj->FormDownload.DownloadCnt = 0; // 폼이미지파일을 다운로드해야 하기때문에 다운로드 인덱스를 다시 0으로 리셋
        download_file_0x82();
        return 1;
    }

    BYTE               *msgPtr;
    // 파일다운로드
    VMS_HEAD           *pHead;
    VMS_FILE_DATA      *pFile;
    char               *pStrm;

    // 폼다운로드
    VMS_FORM_HEAD      *pForm;
    VMS_FORM_ID_DATA   *pData;

    WORD crc;
    int  nPktSize;

    msgPtr = (BYTE*)pMsg->Buff;
    pHead  = (VMS_HEAD*)&msgPtr[0];
    pForm  = (VMS_FORM_HEAD*)&msgPtr[sizeof(VMS_HEAD)];
    pData  = (VMS_FORM_ID_DATA*)&msgPtr[sizeof(VMS_HEAD)+sizeof(VMS_FORM_HEAD)];

    pHead->Dle    = VMS_DLE;
    pHead->Stx    = VMS_STX;
    pHead->Group  = AObj->GROUP_NO;
    pHead->Ctlr   = AObj->CTLR_LOCAL_NO;
    pHead->OpCode = e_vms_download_form;
    pHead->Curr   = 1;
    pHead->Total  = 1;
    pHead->Length = 0;

    // 폼아이디는 제어기가 최초에 접속했을때 한번만 내려보내기 때문에
    // 폼아이디를 여기서 설정해 주어야 한다.
    int nFormId   = AObj->FormDownload.Info[AObj->FormDownload.DownloadCnt].FormNo;
    int nBitmapId = AObj->FormDownload.Info[AObj->FormDownload.DownloadCnt].BitmapId;
    int nFormCnt  = 1;   // 폼정보는 하나만 내려보내야 한다. 제어기에서 수용하지 못함

    LDEBUG("download_form_0x9A: DownloadCnt: %d, FormId: %d, BitmapId: %d", AObj->FormDownload.DownloadCnt, nFormId, nBitmapId);

    pForm->FORM_ID  = htons(nFormId);
    pForm->FORM_CNT = htons(nFormCnt);

    pHead->Length = sizeof(VMS_FORM_HEAD)+(sizeof(VMS_FORM_ID_INFO)*nFormCnt);

    for (int ii = 0; ii < nFormCnt; ii++)
    {
        pData->INFO[ii].data.FORM_SEQ     = htons(nFormId);                         // 폼 표출 일련번호,        2Byte
        pData->INFO[ii].data.DISPLAY_TIME = 1;                                      // 폼의 표출시간을 지정,    1Byte( 0x00 이면 계속 표출 ) ==> 제어기에서 사용안함
        pData->INFO[ii].data.DISPLAY_TYPE = e_static_normal;                        // 폼의 표출유형을 지정,    1Byte
        pData->INFO[ii].data.BG_RGB       = e_bg_black;                             // 폼의 배경색을 지정,      1Byte
        pData->INFO[ii].data.OBJ_CNT      = 1;                                      // 표출할 오브젝트 전체 수, 1Byte

        pData->INFO[ii].obj.OBJ_TYPE    = e_obj_bitmapid;                           // 오브젝트 종류
        pData->INFO[ii].obj.OBJ_SIZE    = htons(sizeof(VMS_OBJ_BITMAPID));          // 오브젝트 데이터 크기
        pData->INFO[ii].obj.FLASH       = 0x00;                                     // 점멸여부, 1Byte(0x00 : 고정, 0x01 : 점멸)
        pData->INFO[ii].obj.X           = htons(0);                                 // 좌표 X
        pData->INFO[ii].obj.Y           = htons(0);                                 // 좌표 Y
        pData->INFO[ii].obj.TEXT_BG_RGB = e_bg_black;                               // 문자열 배경색을 지정

        pData->INFO[ii].bid.WIDTH     = htons(AObj->WIDTH);                         // 비트맵 표시 Width,  2 Byte, 0 ~ 1023 : 표출 비트맵 Width
        pData->INFO[ii].bid.HEIGHT    = htons(AObj->HEIGHT);                        // 비트맵 표시 Heitht, 2 Byte, 0 ~ 1023 : 표출 비트맵 Width
        pData->INFO[ii].bid.IMG_TYPE  = e_img_bitmap;                               // e_img_type
        pData->INFO[ii].bid.BITMAP_ID = htons(nBitmapId);                           // 표출할 비트맵 ID,   2 Byte, 0～ 9999 : 표출할 비트맵 ID
    }

    nPktSize = sizeof(VMS_HEAD)+pHead->Length-2; //DLE/STX
    crc  = GETCRC16((char*)&pHead->Group, nPktSize);
    msgPtr[sizeof(VMS_HEAD)+pHead->Length+0] = VMS_DLE;
    msgPtr[sizeof(VMS_HEAD)+pHead->Length+1] = VMS_ETX;
    msgPtr[sizeof(VMS_HEAD)+pHead->Length+2] = HIBYTE(crc);
    msgPtr[sizeof(VMS_HEAD)+pHead->Length+3] = LOBYTE(crc);

    AObj->FormDownload.DownloadCnt++;

    SendPacketDLE((char*)msgPtr, nPktSize+6);

    return 1;
}
//---------------------------------------------------------------------------

int TClientSession::download_file_0x82()
{
    IPC_JOB_MESSAGE *pMsg = g_jobBuff.GetBuff();
    TCDSCtlr *AObj = FCDSCtlr;
    if (!AObj) return -1;

    if (AObj->FormDownload.MaxSchedule == 0)
    {
        // 여기 들어오면 안됌, 다운로드할 폼정보가 존해해야 여기 함수를 호출하게 돼있음
        return 0;
    }

    int nDownloadCnt = AObj->FormDownload.DownloadCnt;
    if (nDownloadCnt >= AObj->FormDownload.MaxSchedule)
    {
        // 폼파일이(폼이미지파일) 모두 다운로드 되었으므로 스케쥴 정보를 다운로드 한다.
        download_schedule_form_0x96();  // Display Schedule Form
        return 0;
    }

    bool                bResult = true;
    BYTE               *msgPtr;
    // 파일다운로드
    VMS_HEAD           *pHead;
    VMS_FILE_DATA      *pFile;
    char               *pStrm;

    // 폼다운로드
    VMS_FORM_HEAD      *pForm;
    VMS_FORM_ID_DATA   *pData;

    WORD crc;
    int  nPktSize;

    int  ii;
    bool isEndDownload = true;
    AObj->pForms->Lock();
	try
	{
        for (ii = nDownloadCnt; ii < AObj->FormDownload.MaxSchedule; ii++)
        {
            AObj->FormDownload.DownloadCnt++;

            int nFormId   = AObj->FormDownload.Info[ii].FormNo;
            int nBitmapId = AObj->FormDownload.Info[ii].BitmapId;
            int nFormIdx  = AObj->FormDownload.Info[ii].FormIdx;

            if (g_AppCfg.IsCheckNewForm && AObj->FormDownload.Info[ii].IsDownload == false)
            {
                // 이미 다운로드 했기 때문에 다시 다운로드 하지 않는다.
                LDEBUG("download_file_0x82: DownloadCnt: %d, FormId: %d, BitmapId: %d, already download...", ii, nFormId, nBitmapId);
                continue;
            }

            TVmsForm *pForm = AObj->pForms->FLists.Find(nFormIdx);
            if (!pForm)
            {
                continue;
            }
            if (!pForm->Success)
            {
                continue;
            }

            if (pForm->fileType == P_FILE_TYPE_VIDEO  || pForm->fileType == P_FILE_TYPE_STREAM)
            {
                continue;
            }
            if (!pForm->pStream || pForm->pStream->Size == 0)
            {
                continue;
            }

            isEndDownload = false;
            AObj->DownloadFormId = AObj->FormDownload.Info[ii].VMS_FORM_ID;

            LDEBUG("download_file_0x82: DownloadCnt: %d, FormId: %d, BitmapId: %d, VMS_FORM_ID: %s", ii, nFormId, nBitmapId, AObj->DownloadFormId.c_str());

            // 다운로드
            msgPtr = (BYTE*)pMsg->Buff;
            pHead  = (VMS_HEAD*)&msgPtr[0];
            pFile  = (VMS_FILE_DATA*)&msgPtr[sizeof(VMS_HEAD)];
            pStrm  = (char*)&msgPtr[sizeof(VMS_HEAD)+sizeof(VMS_FILE_DATA)];

            pHead->Dle    = VMS_DLE;
            pHead->Stx    = VMS_STX;
            pHead->Group  = AObj->GROUP_NO;
            pHead->Ctlr   = AObj->CTLR_LOCAL_NO;
            pHead->OpCode = e_vms_file_download;
            pHead->Curr   = 1;
            pHead->Total  = 1;
            pHead->Length = 0;

            int nFileNameSize = 11;
            int nFileSize     = pForm->pStream->Size;

            nFileNameSize = 11;
            pHead->Length = sizeof(VMS_FILE_DATA)+nFileNameSize+nFileSize;

            pFile->head.SAVE_LOC  = e_download_prog_image;   // Download Data 저장위치 Code,    1 Byte
            pFile->head.NAME_SIZE = 11;                      // 파일명 길이,                    1 Byte, 1～ 255
            pFile->head.SIZE      = nFileSize;               // 저장하여야 할 데이터의 크기,    4 Byte

            pForm->pStream->Position = 0;

            try
            {
                sprintf((char*)&pStrm[0], "BID%04d.BMP", nBitmapId);
                memcpy((char*)&pStrm[pFile->head.NAME_SIZE], (char*)pForm->pStream->Memory, nFileSize);

                // 바이트 오더링 변환
                pFile->head.SIZE = htonl(pFile->head.SIZE);

                nPktSize = sizeof(VMS_HEAD)+pHead->Length-2; //DLE/STX
                crc  = GETCRC16((char*)&pHead->Group, nPktSize);
                msgPtr[sizeof(VMS_HEAD)+pHead->Length+0] = VMS_DLE;
                msgPtr[sizeof(VMS_HEAD)+pHead->Length+1] = VMS_ETX;
                msgPtr[sizeof(VMS_HEAD)+pHead->Length+2] = HIBYTE(crc);
                msgPtr[sizeof(VMS_HEAD)+pHead->Length+3] = LOBYTE(crc);

                SendPacketDLE((char*)msgPtr, nPktSize+6);
                break;
            }
            catch(Exception &e)
            {
                bResult = false;
            }
        }
	}
	__finally
	{
        AObj->pForms->UnLock();
	}

    if (isEndDownload)
    {
        // 폼이미지 정보가 모두 다운로드 되었으므로 스케쥴 정보를 다운로드 한다.
        download_schedule_form_0x96();  // Display Schedule Form
    }
    return 1;
}
//---------------------------------------------------------------------------

int TClientSession::download_schedule_form_0x96()
{
    TCDSCtlr *AObj = FCDSCtlr;
    if (!AObj) return -1;

    char                Buff[1024];
    BYTE               *msgPtr;
    VMS_HEAD           *pHead;
    VMS_SCHEDULE_FORM  *pSche;

    WORD crc;
    int  nPktSize;

    msgPtr = Buff;
    pHead  = (VMS_HEAD*)&msgPtr[0];
    pSche  = (VMS_SCHEDULE_FORM*)&msgPtr[sizeof(VMS_HEAD)];

    pHead->Dle    = VMS_DLE;
    pHead->Stx    = VMS_STX;
    pHead->Group  = AObj->GROUP_NO;
    pHead->Ctlr   = AObj->CTLR_LOCAL_NO;
    pHead->OpCode = e_vms_download_schedule_form;
    pHead->Curr   = 1;
    pHead->Total  = 1;
    pHead->Length = sizeof(VMS_SCHEDULE_FORM);

    memset((char*)pSche, 0x00, sizeof(VMS_SCHEDULE_FORM));

    if (AObj->FormDownload.IsDefault)
    {
        pSche->Form[0].FormNo  = htons(DEFAULT_FORMID);
        pSche->Form[0].DispSec = 4;
        LDEBUG("download_schedule_form_0x96: 0, DEFAULT_FORMID: %d, DispSec: %d", DEFAULT_FORMID, pSche->Form[0].DispSec);
    }
    else
    {
        for (int ii = 0; ii < AObj->FormDownload.MaxSchedule && ii < MAX_VMS_SCENARIO_FORM; ii++)
        {
            pSche->Form[ii].FormNo  = htons(AObj->FormDownload.Info[ii].FormNo);
            pSche->Form[ii].DispSec = AObj->FormDownload.Info[ii].DispSec;
            LDEBUG("download_schedule_form_0x96: %d, FormId: %d, DispSec: %d", ii, AObj->FormDownload.Info[ii].FormNo, AObj->FormDownload.Info[ii].DispSec);
        }
    }

    nPktSize = sizeof(VMS_HEAD)+pHead->Length-2; //DLE/STX
    crc  = GETCRC16((char*)&pHead->Group, nPktSize);
    msgPtr[sizeof(VMS_HEAD)+pHead->Length+0] = VMS_DLE;
    msgPtr[sizeof(VMS_HEAD)+pHead->Length+1] = VMS_ETX;
    msgPtr[sizeof(VMS_HEAD)+pHead->Length+2] = HIBYTE(crc);
    msgPtr[sizeof(VMS_HEAD)+pHead->Length+3] = LOBYTE(crc);

    SendPacketDLE((char*)msgPtr, nPktSize+6);

    return 1;
}
//---------------------------------------------------------------------------

int TClientSession::download_blank_0x9E()
{
    TCDSCtlr *AObj = FCDSCtlr;
    if (!AObj) return -1;

    char                Buff[1024];
    BYTE               *msgPtr;
    VMS_HEAD           *pHead;

    WORD crc;
    int  nPktSize;

    LDEBUG("download_blank_0x9E: .................");

    msgPtr = Buff;
    pHead  = (VMS_HEAD*)&msgPtr[0];

    pHead->Dle    = VMS_DLE;
    pHead->Stx    = VMS_STX;
    pHead->Group  = AObj->GROUP_NO;
    pHead->Ctlr   = AObj->CTLR_LOCAL_NO;
    pHead->OpCode = e_vms_blank;
    pHead->Curr   = 1;
    pHead->Total  = 1;
    pHead->Length = 0;

    nPktSize = sizeof(VMS_HEAD)+pHead->Length-2; //DLE/STX
    crc  = GETCRC16((char*)&pHead->Group, nPktSize);
    msgPtr[sizeof(VMS_HEAD)+pHead->Length+0] = VMS_DLE;
    msgPtr[sizeof(VMS_HEAD)+pHead->Length+1] = VMS_ETX;
    msgPtr[sizeof(VMS_HEAD)+pHead->Length+2] = HIBYTE(crc);
    msgPtr[sizeof(VMS_HEAD)+pHead->Length+3] = LOBYTE(crc);

    SendPacketDLE((char*)msgPtr, nPktSize+6);

    return 1;
}
//---------------------------------------------------------------------------

int TClientSession::download_lib_form_0x0A()
{
    IPC_JOB_MESSAGE *pMsg = g_jobBuff.GetBuff();
    TCDSCtlr *AObj = FCDSCtlr;
    if (!AObj) return -1;

    if (AObj->FormDownload.MaxSchedule == 0)
    {
        // 여기 들어오면 안됌, 다운로드할 폼정보가 존해해야 여기 함수를 호출하게 돼있음
        return 0;
    }

    int nDownloadCnt = AObj->FormDownload.DownloadCnt;
    if (nDownloadCnt >= AObj->FormDownload.MaxSchedule)
    {
        // 폼파일이(폼이미지파일) 모두 다운로드 되었으므로 스케쥴 정보를 다운로드 한다.
        download_schedule_form_0x0E();  // Display Schedule Form
        return 0;
    }

    bool                bResult = true;
    BYTE               *msgPtr;
    // Download Graphics Library (Full Graphic Data)
    VMS_HEAD             *pHead;
    VMS_FULL_GRAPHIC_LIB *pFile;

    WORD crc;
    int  nPktSize;

    int  ii;
    bool isEndDownload = true;
    AObj->pForms->Lock();
	try
	{
        for (ii = nDownloadCnt; ii < AObj->FormDownload.MaxSchedule; ii++)
        {
            AObj->FormDownload.DownloadCnt++;

            int nFormId   = AObj->FormDownload.Info[ii].FormNo;
            int nBitmapId = AObj->FormDownload.Info[ii].BitmapId;
            int nFormIdx  = AObj->FormDownload.Info[ii].FormIdx;

            if (g_AppCfg.IsCheckNewForm && AObj->FormDownload.Info[ii].IsDownload == false)
            {
                // 이미 다운로드 했기 때문에 다시 다운로드 하지 않는다.
                LDEBUG("download_lib_form_0x0A: DownloadCnt: %d, FormId: %d, BitmapId: %d, already download...", ii, nFormId, nBitmapId);
                continue;
            }

            TVmsForm *pForm = AObj->pForms->FLists.Find(nFormIdx);
            if (!pForm)
            {
                continue;
            }
            if (!pForm->Success)
            {
                continue;
            }

            if (pForm->fileType == P_FILE_TYPE_VIDEO  || pForm->fileType == P_FILE_TYPE_STREAM)
            {
                continue;
            }

            if (!pForm->pStream || pForm->pStream->Size == 0)
            {
                continue;
            }
            if (!pForm->pBitmap || pForm->pBitmap->Width == 0 || pForm->pBitmap->Height == 0)
            {
                continue;
            }

            // pForm->pBitmap->PixelFormat = pf24bit;
            // 픽셀포멧이 24비트여야 ScanLine을 사용할 수 있다. 24비트가 아닌경우에는 다른 방법으로 처리해야 한다.

            isEndDownload = false;
            AObj->DownloadFormId = AObj->FormDownload.Info[ii].VMS_FORM_ID;

            LDEBUG("download_lib_form_0x0A: DownloadCnt: %d, FormId: %d, BitmapId: %d, VMS_FORM_ID: %s", ii, nFormId, nBitmapId, AObj->DownloadFormId.c_str());

            // 다운로드
            msgPtr = (BYTE*)pMsg->Buff;
            pHead  = (VMS_HEAD*)&msgPtr[0];
            pFile  = (VMS_FULL_GRAPHIC_LIB*)&msgPtr[sizeof(VMS_HEAD)];

            AObj->FTxtOpCode = e_txt_download_full_graphic_lib;

            pHead->Dle    = VMS_DLE;
            pHead->Stx    = VMS_STX;
            pHead->Group  = AObj->GROUP_NO;
            pHead->Ctlr   = AObj->CTLR_LOCAL_NO;
            pHead->OpCode = e_txt_download_full_graphic_lib;
            pHead->Curr   = 1;
            pHead->Total  = 1;
            pHead->Length = sizeof(VMS_FULL_GRAPHIC_LIB);

            memset((char*)pFile, 0x00, sizeof(VMS_FULL_GRAPHIC_LIB));

            pFile->Phase    = 0x00;     // 0x00(1phase), 0x01(2phase)
            pFile->DispFunc = 0x07;     // 0x07(static)
            pFile->DispDir  = 0x00;     // 0x00(drop down)
            pFile->MsgNmbr  = (WORD)nBitmapId;

            pFile->MsgNmbr = htons(pFile->MsgNmbr);
            try
            {
                int idx = 0;
                int ll, mm;
                int r, g, b;
                int nW = pForm->pBitmap->Width;
                int nH = pForm->pBitmap->Height;

                TPixelFormat PixelFormat = pForm->pBitmap->PixelFormat;
                if (PixelFormat == pf24bit)
                {
                    for (ll = 0; ll < nH; ll++)
                    {
                        TRGBTriple *p = reinterpret_cast<TRGBTriple *>(pForm->pBitmap->ScanLine[ll]);
                        for (mm = 0; mm < nW; mm++)
                        {
                            r = p[mm].rgbtRed;
                            g = p[mm].rgbtGreen;
                            //b = p[mm].rgbtBlue;

                            if (r > g_AppCfg.PixelValue) CComm_SetBitString(pFile->R_Data1, idx, 1);
                            if (g > g_AppCfg.PixelValue) CComm_SetBitString(pFile->G_Data1, idx, 1);
                            idx++;
                        }
                    }
                }
                else
                if (PixelFormat == pf32bit)
                {
                    for (ll = 0; ll < nH; ll++)
                    {
                        TRGBQuad *p = reinterpret_cast<TRGBQuad *>(pForm->pBitmap->ScanLine[ll]);
                        for (mm = 0; mm < nW; mm++)
                        {
                            r = p[mm].rgbRed;
                            g = p[mm].rgbGreen;
                            //b = p[mm].rgbBlue;

                            if (r > g_AppCfg.PixelValue) CComm_SetBitString(pFile->R_Data1, idx, 1);
                            if (g > g_AppCfg.PixelValue) CComm_SetBitString(pFile->G_Data1, idx, 1);
                            idx++;
                        }
                    }
                }
                else
                if (PixelFormat == pf16bit)
                {
                    //FILE *fp = fopen("C:\\temp.dat", "w+");
                    for (ll = 0; ll < nH; ll++)
                    {
                        WORD *p = reinterpret_cast<WORD *>(pForm->pBitmap->ScanLine[ll]);
                        for (mm = 0; mm < nW; mm++)
                        {
                            r = p[mm] >> 11 & 0x1F; // 5
                            g = p[mm] >>  5 & 0x3F; // 6
                            //b = p[mm] >>  0 & 0x1F; // 5
                            //((blue>>3)<<10) | ((green>>3)<<5) | (red>>3);

                            if (r > g_AppCfg.PixelValue) CComm_SetBitString(pFile->R_Data1, idx, 1);
                            if (g > g_AppCfg.PixelValue) CComm_SetBitString(pFile->G_Data1, idx, 1);
                            idx++;

                            //if (r > 0 || g > 0) fprintf(fp, "*"); else fprintf(fp, "-");
                        }
                        //fprintf(fp, "\n");
                    }
                    //fclose(fp);
                }
                else
                if (PixelFormat == pf8bit)
                {
                    PALETTEENTRY PalEntries[257];
                    if (pForm->pBitmap->Palette != 0)
                    {
                        GetPaletteEntries(pForm->pBitmap->Palette, 0, 256, (LPPALETTEENTRY)PalEntries);
                        //FILE *fp = fopen("C:\\temp.dat", "w+");
                        for (ll = 0; ll < nH; ll++)
                        {
                            BYTE *p = reinterpret_cast<BYTE *>(pForm->pBitmap->ScanLine[ll]);
                            for (mm = 0; mm < nW; mm++)
                            {
                                r = PalEntries[p[mm]].peRed;
                                g = PalEntries[p[mm]].peGreen;
                                b = PalEntries[p[mm]].peBlue;

                                if (r > g_AppCfg.PixelValue) CComm_SetBitString(pFile->R_Data1, idx, 1);
                                if (g > g_AppCfg.PixelValue) CComm_SetBitString(pFile->G_Data1, idx, 1);
                                idx++;

                                //if (r > 0 || g > 0) fprintf(fp, "*"); else fprintf(fp, "-");
                            }
                            //fprintf(fp, "\n");
                        }
                        //fclose(fp);
                    }
                }
                else
                if (PixelFormat == pf4bit)
                //    PixelFormat == pf1bit)
                {
                    PALETTEENTRY PalEntries[17];
                    if (pForm->pBitmap->Palette != 0)
                    {
                        int clrIdx;
                        GetPaletteEntries(pForm->pBitmap->Palette, 0, 16, (LPPALETTEENTRY)PalEntries);
                        //FILE *fp = fopen("C:\\temp.dat", "w+");
                        for (ll = 0; ll < nH; ll++)
                        {
                            BYTE *p = reinterpret_cast<BYTE *>(pForm->pBitmap->ScanLine[ll]);
                            for (mm = 0; mm < nW/2; mm++)
                            {
                                clrIdx = (p[mm] >> 4) & 0xF;
                                r = PalEntries[clrIdx].peRed;
                                g = PalEntries[clrIdx].peGreen;
                                b = PalEntries[clrIdx].peBlue;

                                if (r > g_AppCfg.PixelValue) CComm_SetBitString(pFile->R_Data1, idx, 1);
                                if (g > g_AppCfg.PixelValue) CComm_SetBitString(pFile->G_Data1, idx, 1);
                                idx++;

                                //if (r > 0 || g > 0) fprintf(fp, "*"); else fprintf(fp, "-");

                                clrIdx = p[mm] & 0xF;
                                r = PalEntries[clrIdx].peRed;
                                g = PalEntries[clrIdx].peGreen;
                                b = PalEntries[clrIdx].peBlue;

                                if (r > g_AppCfg.PixelValue) CComm_SetBitString(pFile->R_Data1, idx, 1);
                                if (g > g_AppCfg.PixelValue) CComm_SetBitString(pFile->G_Data1, idx, 1);
                                idx++;

                                //if (r > 0 || g > 0) fprintf(fp, "*"); else fprintf(fp, "-");
                            }
                            //fprintf(fp, "\n");
                        }
                        //fclose(fp);
                    }
                }

                nPktSize = sizeof(VMS_HEAD)+pHead->Length-2; //DLE/STX
                crc  = GETCRC16((char*)&pHead->Group, nPktSize);
                msgPtr[sizeof(VMS_HEAD)+pHead->Length+0] = VMS_DLE;
                msgPtr[sizeof(VMS_HEAD)+pHead->Length+1] = VMS_ETX;
                msgPtr[sizeof(VMS_HEAD)+pHead->Length+2] = HIBYTE(crc);
                msgPtr[sizeof(VMS_HEAD)+pHead->Length+3] = LOBYTE(crc);

                SendPacketDLE((char*)msgPtr, nPktSize+6);
                break;
            }
            catch(Exception &e)
            {
                bResult = false;
            }
        }
	}
	__finally
	{
        AObj->pForms->UnLock();
	}

    if (isEndDownload)
    {
        // 폼이미지 정보가 모두 다운로드 되었으므로 스케쥴 정보를 다운로드 한다.
        download_schedule_form_0x0E();  // Display Schedule Form
    }
    return 1;
}
//---------------------------------------------------------------------------

int TClientSession::download_schedule_form_0x0E()
{
    TCDSCtlr *AObj = FCDSCtlr;
    if (!AObj) return -1;

    char                Buff[1024];
    BYTE               *msgPtr;
    VMS_HEAD           *pHead;
    VMS_SCHEDULE_FORM  *pSche;

    WORD crc;
    int  nPktSize;

    AObj->FTxtOpCode = e_txt_display_schedule_msg;

    msgPtr = Buff;
    pHead  = (VMS_HEAD*)&msgPtr[0];
    pSche  = (VMS_SCHEDULE_FORM*)&msgPtr[sizeof(VMS_HEAD)];

    pHead->Dle    = VMS_DLE;
    pHead->Stx    = VMS_STX;
    pHead->Group  = AObj->GROUP_NO;
    pHead->Ctlr   = AObj->CTLR_LOCAL_NO;
    pHead->OpCode = e_txt_display_schedule_msg;
    pHead->Curr   = 1;
    pHead->Total  = 1;
    pHead->Length = sizeof(VMS_SCHEDULE_FORM);

    memset((char*)pSche, 0x00, sizeof(VMS_SCHEDULE_FORM));

    for (int ii = 0; ii < AObj->FormDownload.MaxSchedule && ii < MAX_VMS_SCENARIO_FORM; ii++)
    {
        pSche->Form[ii].FormNo  = htons(AObj->FormDownload.Info[ii].FormNo);
        pSche->Form[ii].DispSec = AObj->FormDownload.Info[ii].DispSec;
        LDEBUG("download_lib_form_0x0A: %d, FormId: %d, DispSec: %d", ii, AObj->FormDownload.Info[ii].FormNo, AObj->FormDownload.Info[ii].DispSec);
    }

    nPktSize = sizeof(VMS_HEAD)+pHead->Length-2; //DLE/STX
    crc  = GETCRC16((char*)&pHead->Group, nPktSize);
    msgPtr[sizeof(VMS_HEAD)+pHead->Length+0] = VMS_DLE;
    msgPtr[sizeof(VMS_HEAD)+pHead->Length+1] = VMS_ETX;
    msgPtr[sizeof(VMS_HEAD)+pHead->Length+2] = HIBYTE(crc);
    msgPtr[sizeof(VMS_HEAD)+pHead->Length+3] = LOBYTE(crc);

    SendPacketDLE((char*)msgPtr, nPktSize+6);

    return 1;
}
//---------------------------------------------------------------------------

int TClientSession::download_blank_0x16()
{
    TCDSCtlr *AObj = FCDSCtlr;
    if (!AObj) return -1;

    char                Buff[1024];
    BYTE               *msgPtr;
    VMS_HEAD           *pHead;

    WORD crc;
    int  nPktSize;

    AObj->FTxtOpCode = e_txt_blank;

    msgPtr = Buff;
    pHead  = (VMS_HEAD*)&msgPtr[0];

    pHead->Dle    = VMS_DLE;
    pHead->Stx    = VMS_STX;
    pHead->Group  = AObj->GROUP_NO;
    pHead->Ctlr   = AObj->CTLR_LOCAL_NO;
    pHead->OpCode = e_txt_blank;
    pHead->Curr   = 1;
    pHead->Total  = 1;
    pHead->Length = 0;

    nPktSize = sizeof(VMS_HEAD)+pHead->Length-2; //DLE/STX
    crc  = GETCRC16((char*)&pHead->Group, nPktSize);
    msgPtr[sizeof(VMS_HEAD)+pHead->Length+0] = VMS_DLE;
    msgPtr[sizeof(VMS_HEAD)+pHead->Length+1] = VMS_ETX;
    msgPtr[sizeof(VMS_HEAD)+pHead->Length+2] = HIBYTE(crc);
    msgPtr[sizeof(VMS_HEAD)+pHead->Length+3] = LOBYTE(crc);

    SendPacketDLE((char*)msgPtr, nPktSize+6);

    return 1;
}
//---------------------------------------------------------------------------

int TClientSession::ReqSendPacket(char *ACmd, int ALen)
{
    VMS_HEAD *pHead = (VMS_HEAD*)ACmd;

    if (ALen <= 0)
    {
        return -1;
    }

    if (!SendRequest(ACmd, ALen))
    {
        SERROR("+CLI ReqSendPacket send request faild: %s, 0x%02X will be closed.", FIpAddress.c_str(), pHead->OpCode);
        MERROR("+CLI ReqSendPacket send request faild: %s, 0x%02X will be closed.", FIpAddress.c_str(), pHead->OpCode);
        Disconnect();
        return -2;
    }

    SendFlushComplete();

    return 1;
}
//---------------------------------------------------------------------------

