//---------------------------------------------------------------------------
// For SELMA100/200, 20180223, moon, 완료
// USB->TCP/IP
//---------------------------------------------------------------------------

#include <vcl.h>
#pragma hdrstop

#define MAX_RETRY_COUNT			2

#include "CommControl_Form.h"
#include "Message_Form.h"
#include "USBMessage_Form.h"
#include "VirtualMachine_Form.h"
#include "MultiLanguage.h"
#include "Environment.h"
#include <inifiles.hpp>
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "TntExtCtrls"
#pragma link "TntStdCtrls"
#pragma link "TntButtons"
#pragma resource "*.dfm"

bool CommSimulationMode = false;
bool SvrConFlag = false; //sjm tcpip
bool TcpSndFlag = false; //sjm tcpip
bool Comm_IsActiveForm= false;
TDualRxTabletInsInfo DualRxTabletInsInfo; //sjm TCPIP
TDualTxTabletInsInfo DualTxTabletInsInfo; //sjm TCPIP
TMODUS_HEAD MODUS_HEAD;						//sjm TCPIP

TCommControlForm *CommControlForm = NULL;
//---------------------------------------------------------------------------
__fastcall TCommControlForm::TCommControlForm(TComponent* Owner)
	: TTntForm(Owner)
{
  if(DefaultLCID == 1028 || DefaultLCID == 2052 || DefaultLCID == 3076 || DefaultLCID == 4100)
    ComponentSetFontName(this, "SimSun");
  else if(DefaultLCID == 1041)
    ComponentSetFontName(this, "Meiryo UI");
  else if(DefaultLCID == 3082)
  {
    ComponentSetFontName(this, "Segoe UI");
    ComponentSetMultiLine(this);
  }

  TIniFile *iniFile = new TIniFile(ProgramPath.Env + "\\UserSetting.ini");
	if (iniFile)
	{
    activemode=	iniFile->ReadInteger("RecentBoardActiveStatus","Active",2);
    if(activemode == 1)
      ActiveStatus1->Down = true;
    else if(activemode == 2)
      ActiveStatus2->Down = true;
    else
      ActiveStatus3->Down = true;
    delete iniFile; // 1-usb all 2-hcb-usb/tcp-spb  3-tcp all
  }

  for(int index = 0; index < 1 + MachineSetupData.IPB_BoardCount ; ++index )
  {
    TcpConnection[index].SetActiveMode(activemode);
  }

  GetDefaultString();
	for (int commIndex = 0; commIndex < TOTAL_COMM_COUNT; commIndex++)
	{
		FBusy[commIndex] = false;
	}
}
//---------------------------------------------------------------------------
void __fastcall TCommControlForm::GetDefaultString()
{
  TCommControlForm *tmpForm = this;

  tmpForm->Caption = COMMCONTROLFORM_FORM_CAPTION_01;
  tmpForm->ReconnectButton1->Caption = COMMCONTROLFORM_BUTTON_CAPTION_01;
  tmpForm->ReconnectButton2->Caption = COMMCONTROLFORM_BUTTON_CAPTION_01;
  tmpForm->ReconnectButton3->Caption = COMMCONTROLFORM_BUTTON_CAPTION_01;
  tmpForm->ReconnectButton4->Caption = COMMCONTROLFORM_BUTTON_CAPTION_01;
  tmpForm->ReconnectButton5->Caption = COMMCONTROLFORM_BUTTON_CAPTION_01;
  tmpForm->ReconnectButton6->Caption = COMMCONTROLFORM_BUTTON_CAPTION_01;
  tmpForm->ReconnectButton7->Caption = COMMCONTROLFORM_BUTTON_CAPTION_01;
  tmpForm->ReconnectButton8->Caption = COMMCONTROLFORM_BUTTON_CAPTION_01;
  tmpForm->ReconnectButton9->Caption = COMMCONTROLFORM_BUTTON_CAPTION_01;
  tmpForm->ReconnectButton10->Caption = COMMCONTROLFORM_BUTTON_CAPTION_01;
	  
  
  tmpForm->CloseButton->Caption = COMMCONTROLFORM_BUTTON_CAPTION_02;
  tmpForm->RecoverButton1->Caption = COMMCONTROLFORM_BUTTON_CAPTION_03;
  tmpForm->RecoverButton2->Caption = COMMCONTROLFORM_BUTTON_CAPTION_03;
  tmpForm->RecoverButton3->Caption = COMMCONTROLFORM_BUTTON_CAPTION_03;
  tmpForm->RecoverButton4->Caption = COMMCONTROLFORM_BUTTON_CAPTION_03;
  tmpForm->RecoverButton5->Caption = COMMCONTROLFORM_BUTTON_CAPTION_03;
  tmpForm->RecoverButton6->Caption = COMMCONTROLFORM_BUTTON_CAPTION_03;
  tmpForm->RecoverButton7->Caption = COMMCONTROLFORM_BUTTON_CAPTION_03;

  tmpForm->GroupBox1->Caption = COMMCONTROLFORM_GROUPBOX_CAPTION_01;

  tmpForm->HCBConnectionLabel->Caption = COMMCONTROLFORM_LABEL_CAPTION_02;
  tmpForm->SPBConnectionLabel1->Caption = COMMCONTROLFORM_LABEL_CAPTION_02;
  tmpForm->SPBConnectionLabel2->Caption = COMMCONTROLFORM_LABEL_CAPTION_02;
  tmpForm->SPBConnectionLabel3->Caption = COMMCONTROLFORM_LABEL_CAPTION_02;
  tmpForm->SPBConnectionLabel4->Caption = COMMCONTROLFORM_LABEL_CAPTION_02;
  tmpForm->SPBConnectionLabel5->Caption = COMMCONTROLFORM_LABEL_CAPTION_02;
  tmpForm->SPBConnectionLabel6->Caption = COMMCONTROLFORM_LABEL_CAPTION_02;
  tmpForm->SPBConnectionLabel7->Caption = COMMCONTROLFORM_LABEL_CAPTION_02;
  tmpForm->SPBConnectionLabel8->Caption = COMMCONTROLFORM_LABEL_CAPTION_02;
  tmpForm->TPBConnectionLabel->Caption = COMMCONTROLFORM_LABEL_CAPTION_02;
}
//---------------------------------------------------------------------------
void __fastcall TCommControlForm::Connect(int commIndex)
{
  TcpConnection[commIndex].IgnoreState = true;
  
	if (activemode == 1)
	{
		AnsiString deviceName = "";
		switch (commIndex)
		{
			case COMM_HCB:
				deviceName = "\\\\.\\USBFAE_HCB_1";
				break;
			case COMM_SPB_1:
				deviceName = "\\\\.\\USBFAE_SPB_1";
				break;
			case COMM_SPB_2:
				deviceName = "\\\\.\\USBFAE_SPB_2";
				break;
			case COMM_SPB_3:
				deviceName = "\\\\.\\USBFAE_SPB_3";
				break;
			case COMM_SPB_4:
				deviceName = "\\\\.\\USBFAE_SPB_4";
				break;
      case COMM_SPB_5:
				deviceName = "\\\\.\\USBFAE_SPB_5";
				break;
      case COMM_SPB_6:
				deviceName = "\\\\.\\USBFAE_SPB_6";
				break;
		}
		if (deviceName != "")
		{
			if (!CommSimulationMode)
			{
				TcpConnection[commIndex].USBConnect(deviceName);
				TcpConnection[commIndex].ProtocolCheck(commIndex);
			}
		}
	}
	else if (activemode == 2) 
	{
		AnsiString deviceName = ""; // add hcbusb
		AnsiString  sIpAddr = "";
		int         nPort;
		switch (commIndex)
		{
			case COMM_HCB:
				deviceName = "\\\\.\\USBFAE_HCB_1";
				break;
			case COMM_SPB_1:
			case COMM_SPB_2:
			case COMM_SPB_3:
			case COMM_SPB_4:
			case COMM_SPB_5:
      			case COMM_SPB_6:
			case COMM_SPB_7:
			case COMM_SPB_8:	
				sIpAddr = SPBSystemSetupData[commIndex - COMM_SPB_1].szIpAddr;
				nPort = SPBSystemSetupData[commIndex - COMM_SPB_1].nTcpPort;
				break;
			case COMM_TPB:
				sIpAddr = "192.168.0.70";
				nPort   = 1002;
				break;					
		}
		///// hcb usb add /////
		if (commIndex == 0)
		{
			if (deviceName != "")
			{
				if (!CommSimulationMode)
				{
					TcpConnection[commIndex].USBConnect(deviceName);    // 이전 함수 콜
					TcpConnection[commIndex].ProtocolCheck(commIndex);
				}
			}
		}
		else
		{
			if (sIpAddr != "")
			{
				if (!CommSimulationMode)
				{
					TcpConnection[commIndex].TCPConnect(sIpAddr, nPort);
					TcpConnection[commIndex].ProtocolCheck(commIndex);
				}
			}
		}
	}
	else 
	{
		AnsiString  sIpAddr = "";
		int         nPort;
		switch (commIndex)
		{
			case COMM_HCB:
				sIpAddr = MachineSetupData.szHCB_IpAddr;
				nPort   = MachineSetupData.nHCB_TcpPort;
				break;
			case COMM_SPB_1:
			case COMM_SPB_2:
			case COMM_SPB_3:
			case COMM_SPB_4:
			case COMM_SPB_5:
     			case COMM_SPB_6:
			case COMM_SPB_7:
			case COMM_SPB_8:	
				sIpAddr = SPBSystemSetupData[commIndex - COMM_SPB_1].szIpAddr;
				nPort   = SPBSystemSetupData[commIndex - COMM_SPB_1].nTcpPort;
				break;
			case COMM_TPB:
				sIpAddr = "192.168.0.70";
				nPort   = 1002;
				break;				
		}
		if (sIpAddr != "")
		{
			if (!CommSimulationMode)
			{
				if(TcpConnection[commIndex].TCPConnect(sIpAddr, nPort))
        {
          if(PCProgramOption.TcpIpMonitorActive)
          {
       			 	freopen("CONOUT$","wt",stdout);
 				   	if(commIndex ==COMM_HCB)
 					{
 						printf("Time : %d ::HCB Connection Complete\n",GetTickCount());
 					}
					else if(commIndex ==COMM_TPB)
					{
						printf("Time : %d ::TPB Connection Complete\n",GetTickCount());
					}
 					else
 					{
 						printf("Time : %d ::%d IPB Connection Complete\n",GetTickCount(),commIndex);
 					}
          }
//				 	 TcpConnection[commIndex].ProtocolCheck(commIndex);
      				 }
				else
				{
          if(PCProgramOption.TcpIpMonitorActive)
          {
       			 	freopen("CONOUT$","wt",stdout);
 				   	if(commIndex ==COMM_HCB)
 					{
 						printf("Time : %d ::HCB Connection fail\n",GetTickCount());
 					}
					else if(commIndex ==COMM_TPB)
					{
						printf("Time : %d ::TPB Connection fail\n",GetTickCount());
					}					
 					else
 					{
 						printf("Time : %d ::%d IPB Connection fail\n",GetTickCount(),commIndex);
 					}
         }				
				}
			}
		}
	}
}
//---------------------------------------------------------------------------
void __fastcall TCommControlForm::Disconnect(int commIndex)
{
	if (activemode == 1 || (activemode == 2 && commIndex == 0))
	{
		TcpConnection[commIndex].USBDisconnect();
	}
	else {
		TcpConnection[commIndex].TCPDisconnect();
	}
}
//---------------------------------------------------------------------------
bool __fastcall TCommControlForm::IsConnected(int commIndex)
{
	bool bConnected = false;
	if (commIndex >= 0 && commIndex < TOTAL_COMM_COUNT)
	{
		bConnected = TcpConnection[commIndex].Connected;
	}
	return bConnected;
}
//---------------------------------------------------------------------------
bool __fastcall TCommControlForm::GetIgnoreState(int commIndex)
{
	bool bConnected = false;

	bConnected =	TcpConnection[commIndex].IgnoreState;

	return bConnected;
}
//---------------------------------------------------------------------------
bool __fastcall TCommControlForm::Request(int commIndex, unsigned short command, void *data, unsigned int dataLength,
	void *receiveBuffer, unsigned int receiveBufferMaxSize)
{
	int result, retryCount;
	AnsiString boardName;
  	retryCount = 0;
	

	if (FBusy[commIndex])
	{
		return false;
	}
	if (TcpConnection[commIndex].VirtualState)
	{
		FBusy[commIndex] = false;
		return true;
	}
	if (TcpConnection[commIndex].IgnoreState)
	{
		FBusy[commIndex] = false;
		return false;
	}
	
	FBusy[commIndex] = true;
	
retry:
	
	if(TcpConnection[commIndex].Connected)
	{
		if (TcpConnection[commIndex].RequestCommand(commIndex, command, data, dataLength, receiveBuffer, receiveBufferMaxSize))
		{
			FBusy[commIndex] = false;
			return true;
		}
	}

	retryCount++;
	if (retryCount < MAX_RETRY_COUNT)
	{
		Sleep(300);
    if(PCProgramOption.TcpIpMonitorActive)
    {
	       freopen("CONOUT$","wt",stdout);
	   	if(commIndex ==COMM_HCB)
		{
			printf("Time : %d ::HCB command  : %x  RETRY Count : %d\n",GetTickCount(),command, retryCount);
		}
		else if(commIndex ==COMM_TPB)
		{
			printf("Time : %d ::TBP command  : %x  RETRY Count : %d\n",GetTickCount(),command, retryCount);
		}
		else
		{
			printf("Time : %d ::%d IPB command  : %x  RETRY Count : %d\n",GetTickCount(),commIndex, command, retryCount);
		}
    }		
		Comm_Connect(commIndex);
		Sleep(300);
		goto retry;
	}
	FBusy[commIndex] = false;
	return false;
	
}
//---------------------------------------------------------------------------
bool __fastcall TCommControlForm::RequestEx(int commIndex, unsigned short command, void *shortData, unsigned int shortDataLength,
	void *longData, unsigned int longDataLength, void *receiveBuffer, unsigned int receiveBufferMaxSize,
	TUSBCompletionRoutine CompletionRoutine, TOverlapIOStr *OverlapIOStr)
{
	int result,retryCount;
	AnsiString boardName;

	retryCount = 0;
	
	if (FBusy[commIndex])
	{
		return false;
	}
	if (TcpConnection[commIndex].VirtualState)
	{
		FBusy[commIndex] = false;
		return true;
	}
	if (TcpConnection[commIndex].IgnoreState)
	{
		FBusy[commIndex] = false;
		return false;
	}
	
	FBusy[commIndex] = true;
	
retry:
	
	if(TcpConnection[commIndex].Connected)
	{
		if (TcpConnection[commIndex].RequestCommandEx(commIndex, command, shortData, shortDataLength, longData, longDataLength,receiveBuffer, receiveBufferMaxSize, CompletionRoutine, OverlapIOStr))
		{
			FBusy[commIndex] = false;
			return true;
		}
	}

	retryCount++;
	if (retryCount < MAX_RETRY_COUNT)
	{
		Sleep(300);
    if(PCProgramOption.TcpIpMonitorActive)
    {
	       freopen("CONOUT$","wt",stdout);
	   	if(commIndex ==COMM_HCB)
		{
			printf("Time : %d ::HCB command  : %x  RETRY Count : %d\n",GetTickCount(), command, retryCount);
		}
		else if(commIndex ==COMM_TPB)
		{
			printf("Time : %d ::TPB command  : %x  RETRY Count : %d\n",GetTickCount(), command, retryCount);
		}
		else
		{
			printf("Time : %d ::%d IPB command  : %x  RETRY Count : %d\n",GetTickCount(), commIndex, command, retryCount);
		}
    }				
		Comm_Connect(commIndex);
		Sleep(300);
		goto retry;
	}

	FBusy[commIndex] = false;
	return false;
}
//---------------------------------------------------------------------------
void __fastcall TCommControlForm::SetMaxWaitingTime(int commIndex, int waitingTime)
{
	TcpConnection[commIndex].MaxWaitingTime = waitingTime;
}
//---------------------------------------------------------------------------
void __fastcall TCommControlForm::SetDefaultMaxWaitingTime(int commIndex)
{
	TcpConnection[commIndex].SetDefaultMaxWaitingTime();
}
//---------------------------------------------------------------------------
bool __fastcall TCommControlForm::Recover(int commIndex)
{
	if (TcpConnection[commIndex].RecoverDevice(commIndex))
	{
		return true;
	}
	else
	{
		ShowMessageFA(TcpConnection[commIndex].GetLastErrorMessage());
		return false;
	}
}
//---------------------------------------------------------------------------
void __fastcall TCommControlForm::Reconnect(int commIndex)
{
	Connect(commIndex);
	CheckStatus();
}
//---------------------------------------------------------------------------
void __fastcall TCommControlForm::RequestStallTest(int commIndex, int testMode)
{
	TcpConnection[commIndex].RequestStallTest(testMode);
}
//---------------------------------------------------------------------------
//	external functions
//---------------------------------------------------------------------------
void __fastcall Comm_Connect(int commIndex)
{
	if (CommControlForm != NULL)
	{
		CommControlForm->Connect(commIndex);
	}
}
//---------------------------------------------------------------------------
void __fastcall Comm_Disconnect(int commIndex)
{
	if (CommControlForm != NULL)
	{
		CommControlForm->Disconnect(commIndex);
	}
}
//---------------------------------------------------------------------------
void __fastcall Comm_ConnectAll(void)
{
	if (CommControlForm == NULL)
	{
		CommControlForm = new TCommControlForm(NULL);
		CommControlForm->Connect(COMM_HCB);
		CommControlForm->Connect(COMM_SPB_1);
		CommControlForm->Connect(COMM_SPB_2);
		CommControlForm->Connect(COMM_SPB_3);
		CommControlForm->Connect(COMM_SPB_4);
		CommControlForm->Connect(COMM_SPB_5);
    		CommControlForm->Connect(COMM_SPB_6);
		CommControlForm->Connect(COMM_SPB_7);
		CommControlForm->Connect(COMM_SPB_8);
		CommControlForm->Connect(COMM_TPB);
	}
}
//---------------------------------------------------------------------------
void __fastcall Comm_DisconnectAll(void)
{
	if (CommControlForm != NULL)
	{
		CommControlForm->Disconnect(COMM_HCB);
		CommControlForm->Disconnect(COMM_SPB_1);
		CommControlForm->Disconnect(COMM_SPB_2);
		CommControlForm->Disconnect(COMM_SPB_3);
		CommControlForm->Disconnect(COMM_SPB_4);
		CommControlForm->Disconnect(COMM_SPB_5);
    		CommControlForm->Disconnect(COMM_SPB_6);
		CommControlForm->Disconnect(COMM_SPB_7);
		CommControlForm->Disconnect(COMM_SPB_8);
		CommControlForm->Disconnect(COMM_TPB);
		delete CommControlForm;
		CommControlForm = NULL;
	}
}
//---------------------------------------------------------------------------
bool __fastcall Comm_IsConnected(int commIndex)
{
	if (!CommSimulationMode)
	{
		bool bConnected = false;
		if (CommControlForm != NULL)
		{
			bConnected = CommControlForm->IsConnected(commIndex);
		}
		return bConnected;
	}
	else
	{
		return true;
	}
}
//---------------------------------------------------------------------------
bool __fastcall Comm_Request(int commIndex, unsigned short command, void *data, unsigned int dataLength,
	void *receiveBuffer, unsigned int receiveBufferMaxSize)
{

  if (!Comm_IsConnected(commIndex)) 
  {
  	Comm_Connect(commIndex);
	if (!Comm_IsConnected(commIndex))
	{
		return false;
	}
  }
  
  if(0)//(MachineSetupData.LasercomplexerInfo.Laser_complexer_Enable)
  {
    int spbIndex;
    int camIndex;

    spbIndex = CameraMapInfo[SD1_3D_FRONT_FACE_CAMERA_INDEX - 1].SPBIndex;
    camIndex = CameraMapInfo[SD1_3D_FRONT_FACE_CAMERA_INDEX - 1].CamIndex;
    if(CameraMapInfo[SD1_3D_FRONT_FACE_CAMERA_INDEX - 1].CameraInspectPosition == CAMERA_POSITION_3D)
    {
      if(commIndex & COMM_SPB + spbIndex)
      {
        if(command == CMD_CAPTURE_SETUP)
        {
          TCaptureSetupData *pCaptureSetupData;
          pCaptureSetupData = (TCaptureSetupData*)data;

          RecentDisk1ThreeDCameraLSFValue = pCaptureSetupData->TriggerFreq[camIndex]; 
        }
        else if(command == CMD_STUDY_READY)
        {
          TStudySetupData *pStudySetupData;
          pStudySetupData = (TStudySetupData*)data;

          RecentDisk1ThreeDCameraLSFValue = pStudySetupData->TriggerFreq[camIndex];
        }
        else if(command == CMD_INSPECTION_READY)
        {
          TInspectData *pInspectData;
          pInspectData = (TInspectData*)data;

          RecentDisk1ThreeDCameraLSFValue = pInspectData->TriggerFreq[camIndex];
        }
      }
    }

    spbIndex = CameraMapInfo[SD2_3D_FRONT_FACE_CAMERA_INDEX - 1].SPBIndex;
    camIndex = CameraMapInfo[SD2_3D_FRONT_FACE_CAMERA_INDEX - 1].CamIndex;

    if(CameraMapInfo[SD2_3D_FRONT_FACE_CAMERA_INDEX - 1].CameraInspectPosition == CAMERA_POSITION_3D)
    {
      if(commIndex & COMM_SPB + spbIndex)
      {
        if(command == CMD_CAPTURE_SETUP)
        {
          TCaptureSetupData *pCaptureSetupData;
          pCaptureSetupData = (TCaptureSetupData*)data;

          RecentDisk2ThreeDCameraLSFValue = pCaptureSetupData->TriggerFreq[camIndex];
        }
        else if(command == CMD_STUDY_READY)
        {
          TStudySetupData *pStudySetupData;
          pStudySetupData = (TStudySetupData*)data;

          RecentDisk2ThreeDCameraLSFValue = pStudySetupData->TriggerFreq[camIndex];
        }
        else if(command == CMD_INSPECTION_READY)
        {
          TInspectData *pInspectData;
          pInspectData = (TInspectData*)data;

          RecentDisk2ThreeDCameraLSFValue = pInspectData->TriggerFreq[camIndex];
        }
      }
    }
  }

	if (!CommSimulationMode)
	{
		return CommControlForm->Request(commIndex, command, data, dataLength, receiveBuffer, receiveBufferMaxSize);
	}
	else
	{
		return VirtualMachineForm->CommRequest(commIndex, command, data, dataLength, receiveBuffer, receiveBufferMaxSize);
	}
}
//---------------------------------------------------------------------------
bool __fastcall Comm_RequestEx(int commIndex, unsigned short command, void *shortData, unsigned int shortDataLength,
	void *longData, unsigned int longDataLength, void *receiveBuffer, unsigned int receiveBufferMaxSize,
	TUSBCompletionRoutine CompletionRoutine, TOverlapIOStr *OverlapIOStr)
{
	if (!Comm_IsConnected(commIndex)) 
	{
		Comm_Connect(commIndex);
		if (!Comm_IsConnected(commIndex))
		{
			return false;
		}
	}
	if (!CommSimulationMode)
	{
		return CommControlForm->RequestEx(commIndex, command, shortData, shortDataLength, longData, longDataLength,
			receiveBuffer, receiveBufferMaxSize, CompletionRoutine, OverlapIOStr);
	}
	else
	{
		return VirtualMachineForm->CommRequestEx(commIndex, command, shortData, shortDataLength, longData, longDataLength,
			receiveBuffer, receiveBufferMaxSize, CompletionRoutine, OverlapIOStr);
	}
}
//---------------------------------------------------------------------------
void __fastcall Comm_SetMaxWaitingTime(int commIndex, int waitingTime)
{
	CommControlForm->SetMaxWaitingTime(commIndex, waitingTime);
}
//---------------------------------------------------------------------------
void __fastcall Comm_SetDefaultMaxWaitingTime(int commIndex)
{
	CommControlForm->SetDefaultMaxWaitingTime(commIndex);
}
//---------------------------------------------------------------------------
bool __fastcall Comm_Recover(int commIndex)
{
	CommControlForm->Recover(commIndex);
}
//---------------------------------------------------------------------------
void __fastcall Comm_RequestStallTest(int commIndex, int testMode)
{
	CommControlForm->RequestStallTest(commIndex, testMode);
}
//---------------------------------------------------------------------------
void __fastcall Comm_Reconnect(int commIndex)
{
    CommControlForm->Reconnect(commIndex);
}
//---------------------------------------------------------------------------
void __fastcall TCommControlForm::StatusTimerTimer(TObject *Sender)
{
  if(!bSystemStatusCheckSW) return;
  
	CheckStatus();
}
//---------------------------------------------------------------------------
void __fastcall TCommControlForm::CheckStatus(void)
{
	if (TcpConnection[COMM_HCB].VirtualState)
	{
		HCBConnectionLabel->Font->Color = clBlue;
		HCBConnectionLabel->Caption = COMMCONTROLFORM_LABEL_CAPTION_01;
	}
	else if (TcpConnection[COMM_HCB].Connected)
	{
		if (TcpConnection[COMM_HCB].IgnoreState)
		{
			HCBConnectionLabel->Font->Color = clFuchsia;
			HCBConnectionLabel->Caption = COMMCONTROLFORM_LABEL_CAPTION_02;
		}
		else
		{
			HCBConnectionLabel->Font->Color = clLime;
			HCBConnectionLabel->Caption = COMMCONTROLFORM_LABEL_CAPTION_05;
		}
	}
	else
	{
		HCBConnectionLabel->Font->Color = clRed;
		HCBConnectionLabel->Caption = COMMCONTROLFORM_LABEL_CAPTION_02;
	}
	
	if (TcpConnection[COMM_TPB].VirtualState)
	{
		TPBConnectionLabel->Font->Color = clBlue;
		TPBConnectionLabel->Caption = COMMCONTROLFORM_LABEL_CAPTION_01;
	}
	else if (TcpConnection[COMM_TPB].Connected)
	{
		if (TcpConnection[COMM_TPB].IgnoreState)
		{
			TPBConnectionLabel->Font->Color = clFuchsia;
			TPBConnectionLabel->Caption = COMMCONTROLFORM_LABEL_CAPTION_02;
		}
		else
		{
			TPBConnectionLabel->Font->Color = clLime;
			TPBConnectionLabel->Caption = COMMCONTROLFORM_LABEL_CAPTION_05;
		}
	}
	else
	{
		TPBConnectionLabel->Font->Color = clRed;
		TPBConnectionLabel->Caption = COMMCONTROLFORM_LABEL_CAPTION_02;
	}
	for (int spbIndex = 0; spbIndex < MachineSetupData.IPB_BoardCount; spbIndex++)
	{
		TTntLabel *connectionLabel = (TTntLabel *) FindComponent("SPBConnectionLabel" + IntToStr(spbIndex + 1));
		if (connectionLabel)
		{
			if (TcpConnection[COMM_SPB + spbIndex].VirtualState)
			{
				connectionLabel->Font->Color = clBlue;
				connectionLabel->Caption = COMMCONTROLFORM_LABEL_CAPTION_01;
			}
			else if (TcpConnection[COMM_SPB + spbIndex].Connected)
			{
				if (TcpConnection[COMM_SPB + spbIndex].IgnoreState)
				{
					connectionLabel->Font->Color = clFuchsia;
					connectionLabel->Caption = COMMCONTROLFORM_LABEL_CAPTION_02;
				}
				else
				{
					connectionLabel->Font->Color = clLime;
					connectionLabel->Caption = COMMCONTROLFORM_LABEL_CAPTION_05;
				}
			}
			else
			{
				connectionLabel->Font->Color = clRed;
				connectionLabel->Caption = COMMCONTROLFORM_LABEL_CAPTION_02;
			}
		}
	}

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


void __fastcall TCommControlForm::FormCreate(TObject *Sender)
{
  SOCLST = new TList; //sjm tcpip

	
	for (int spbIndex = 0; spbIndex < SYSTEM_SPB_MAX_COUNT; spbIndex++)
	{
		TTntLabel *connectionLabel = (TTntLabel *) FindComponent("SPBConnectionLabel" + IntToStr(spbIndex + 1));
		TTntLabel *BoardLabel = (TTntLabel *) FindComponent("IPBBoardLable" + IntToStr(spbIndex + 1));
		TTntButton *Reconnect = (TTntButton *) FindComponent("ReconnectButton" + IntToStr(spbIndex + 2));
		TTntButton *Recover   = (TTntButton *) FindComponent("RecoverButton" + IntToStr(spbIndex + 2));
		if (connectionLabel)
		{
			 connectionLabel->Visible = false;
		}
		if (BoardLabel)
		{
			 BoardLabel->Visible = false;
 		}

		if (Reconnect)
		{
			 Reconnect->Visible = false;
		}
		if (Recover)
		{
			 Recover->Visible = false;
		}		
	}
	for (int spbIndex = 0; spbIndex < MachineSetupData.IPB_BoardCount; spbIndex++)
	{
		TTntLabel *connectionLabel = (TTntLabel *) FindComponent("SPBConnectionLabel" + IntToStr(spbIndex + 1));
		TTntLabel *BoardLabel = (TTntLabel *) FindComponent("IPBBoardLable" + IntToStr(spbIndex + 1));
		TTntButton *Reconnect = (TTntButton *) FindComponent("ReconnectButton" + IntToStr(spbIndex + 2));
		if (connectionLabel)
		{
			 connectionLabel->Visible = true;
		}
		if (BoardLabel)
		{
			 BoardLabel->Visible = true;
 		}

		if (Reconnect)
		{
			 Reconnect->Visible = true;
		}
	}
  CheckStatus();
}
//---------------------------------------------------------------------------

void __fastcall TCommControlForm::CloseButtonClick(TObject *Sender)
{
	this->Close();
}
//---------------------------------------------------------------------------

void __fastcall TCommControlForm::ReconnectButtonClick(TObject *Sender)
{
	TTntButton *theButton = (TTntButton *) Sender;
	int commIndex = theButton->Tag;
	Connect(commIndex);
	CheckStatus();
}
//---------------------------------------------------------------------------

void __fastcall TCommControlForm::RecoverButtonClick(TObject *Sender)
{
	TTntButton *theButton = (TTntButton *) Sender;
	int commIndex = theButton->Tag;
	Recover(commIndex);
	CheckStatus();
}
//---------------------------------------------------------------------------
void __fastcall TCommControlForm::Panel1DblClick(TObject *Sender)
{
	if (!TcpConnection[COMM_HCB].VirtualState)
	{
		if (MessageDlgFA(COMMCONTROLFORM_MSG_01, mtConfirmation, TMsgDlgButtons() << mbOK << mbCancel) == mrOk)
		{
			TcpConnection[COMM_HCB].VirtualState = true;
			TcpConnection[COMM_SPB_1].VirtualState = true;
			TcpConnection[COMM_SPB_2].VirtualState = true;
			TcpConnection[COMM_SPB_3].VirtualState = true;
			TcpConnection[COMM_SPB_4].VirtualState = true;
			TcpConnection[COMM_SPB_5].VirtualState = true;
    			TcpConnection[COMM_SPB_6].VirtualState = true;
			TcpConnection[COMM_SPB_7].VirtualState = true;
			TcpConnection[COMM_SPB_8].VirtualState = true;
			TcpConnection[COMM_TPB].VirtualState = true;
				
		}
	}
	else
	{
		TcpConnection[COMM_HCB].VirtualState = false;
		TcpConnection[COMM_SPB_1].VirtualState = false;
		TcpConnection[COMM_SPB_2].VirtualState = false;
		TcpConnection[COMM_SPB_3].VirtualState = false;
		TcpConnection[COMM_SPB_4].VirtualState = false;
		TcpConnection[COMM_SPB_5].VirtualState = false;
  	 	TcpConnection[COMM_SPB_6].VirtualState = false;
		TcpConnection[COMM_SPB_7].VirtualState = false;
  	 	TcpConnection[COMM_SPB_8].VirtualState = false;
		TcpConnection[COMM_TPB].VirtualState = false;
	}
	CheckStatus();
}
//---------------------------------------------------------------------------
//===========================================================================
//====================== SJM TCP/IP ADD  ====================================
//    ClientSocket1->Socket->SendText("ABCDEFG");    // 문자열 데이터 전송시
//
//    char    Data[10];
//    ClientSocket1->Socket->SendBuf(Data, 10);     //메모리 버퍼로 전송시
//
//    ClientSocket1->Socket->SendStream()    		//스트림으로 전송시
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
int __fastcall TCommControlForm::TxDatalength(AnsiString str)
{
	int	lng;

    lng =  str.Length();

    return lng;

}
//---------------------------------------------------------------------------
void __fastcall TCommControlForm::TxAlarmDataToTcp(int code, AnsiString str)
{
	AnsiString strData;

    if(str.Length() < 1) return;
    if(SvrConFlag == false ) return;

    //ShowMessage(str);

 	//MODUS_HEAD.transaction_id1 	= 0;
    //MODUS_HEAD.transaction_id2 	= 0;
    MODUS_HEAD.protocol_id1	 	= 0;
    MODUS_HEAD.protocol_id2	 	= 0;
    MODUS_HEAD.length1			= 0;
    MODUS_HEAD.length2 			= str.Length() + 2;    //str + unit ID + FC
    MODUS_HEAD.unit_id 			= 0;

    if(code == 0)
    {
    	MODUS_HEAD.function_code	= "@";     //Error
    }
    else if(code == 1)
    {
    	MODUS_HEAD.function_code	= "A";    //Alarm
    }
    strData =  IntToStr(MODUS_HEAD.transaction_id1)
    			+IntToStr(MODUS_HEAD.transaction_id2)
    			+IntToStr(MODUS_HEAD.protocol_id1)
                +IntToStr(MODUS_HEAD.protocol_id2)
                +IntToStr(MODUS_HEAD.length1)
                +IntToStr(MODUS_HEAD.length2)
                +IntToStr(MODUS_HEAD.unit_id)
                +MODUS_HEAD.function_code
                +str;

    TCustomWinSocket *soc;
    for(int c=0;c< SOCLST->Count;c++)
    {
        soc=(TCustomWinSocket *)SOCLST->Items[c];
        if(soc->Connected)soc->SendText(strData);
    }
}
/* /---------------------------------------------------------------------------
void __fastcall TCommControlForm::AlarmDataToTcp(int code, Byte acode)
{
    Byte TData[6];

    if(SvrConFlag == false ) return;

    TData[0] = 0x00;		//transaction ID
    TData[1] = 0x00;		//protocol ID
    TData[2] = 0x02;    	//Length
    TData[3] = 0x00;    	//Unit ID
    if(code == 0)
    {
    	TData[4] = 0x40;    //Function code (Packet Error)
    }
    else if(code == 1)
    {
    	TData[4] = 0x41;    //Function code (Alarm)
    }
    TData[5] = acode;		//Alarm Code

    TCustomWinSocket *soc;
    for(int c=0;c< SOCLST->Count;c++)
    {
        soc=(TCustomWinSocket *)SOCLST->Items[c];
        if(soc->Connected)soc->SendBuf(TData, 6);
    }
} */
//---------------------------------------------------------------------------
void __fastcall TCommControlForm::TxDataToTcp(AnsiString str)
{
    if(str.Length() < 1) return;
    if(SvrConFlag == false ) return;
    //ShowMessage(str.Length());

    TCustomWinSocket *soc;
    for(int c=0;c< SOCLST->Count;c++)
    {
        soc=(TCustomWinSocket *)SOCLST->Items[c];
        if(soc->Connected)soc->SendText(str);
    }
}
//---------------------------------------------------------------------------
AnsiString __fastcall BufferToHexSpace(unsigned char *Buf, int BufSize)
{
    String Result="";
    String HexStr="0x";

    if(BufSize<1)return "";

    for ( int i=0; i < BufSize -1; i++)
    {
        Result = Result + (IntToHex(Buf[i], 2)-30) ;
    }

    return Result;
}
//---------------------------------------------------------------------------
void __fastcall TCommControlForm::SrvSocketClientRead(TObject *Sender,
      TCustomWinSocket *Socket)
{
	int i;
	int packetErr = 0;
	int codeErr   = 0;

	memset(&cBuf[0], 0, 20);

	int rxlen=Socket->ReceiveLength();
	Socket->ReceiveBuf(&cBuf[0],rxlen);

	for(i=0; i < 8; i ++)
	{
		ShowMessage(cBuf[i]);
	}

	if(cBuf[2] != 0 || cBuf[3] != 0)   //Protocol ID   (2 Byte)
	{
		packetErr = 1;
		//break;
	}
	if(cBuf[4] != 0 || cBuf[5] != 2)   //Length        (2 Byte)
	{
	packetErr = 1;
	//break;
	}
	if(cBuf[6] != 0)   					//Unit ID      (1 Byte)
	{
		packetErr = 1;
		//break;
	}

	if(TcpSndFlag == false)
	{  
		if(cBuf[7] != 105) // 0x69)    				//Function Code (Start)    (1 Byte)
		{
			codeErr = 1;
			packetErr = 1;
			//break;
		}
	}
	else if(TcpSndFlag == true)
	{
		if(cBuf[7] != 106) //0x6A)    				//Function Code (Stop)
		{
			codeErr = 1;
			packetErr = 1;
			//break;
		}
	}

	MODUS_HEAD.transaction_id1 	= cBuf[0];
	MODUS_HEAD.transaction_id2 	= cBuf[1];

	if(packetErr == 1)
	{
		TxAlarmDataToTcp(0,1);
	}
	else if(cBuf[7] == 105) //0x69)
	{
		if(Machine.Status.OperationState != MACHINE_STATE_STARTING)     // InspectState != MACHINE_STATE_STARTING
		{
			TxAlarmDataToTcp(0,2);
		}
		else
		{
			TcpSndFlag = true;
		}
	}
	else if(cBuf[7] == 106) //0x6A)
	{
		ShowMessage("Timer Disable");
		TcpSndFlag = false;
	}
}
//---------------------------------------------------------------------------

void __fastcall TCommControlForm::ServerButtonClick(TObject *Sender)
{
	if(SrvSocket->Active == true) return;

    SrvSocket->Close();
    SrvSocket->Port         = 502;
    SrvSocket->Active       = true;
    ServerButton->Enabled   = false;

    SCADAStatusLabel->Caption = "";
    SCADAStatusLabel->Font->Color = clGreen;
    SCADAStatusLabel->Caption = "Please Wait Connecting ....";
}
//---------------------------------------------------------------------------
void __fastcall TCommControlForm::StopSvrButtonClick(TObject *Sender)
{

	  SrvSocket->Active=false;
    SOCLST->Clear();
    ServerButton->Enabled = true;

    SCADAStatusLabel->Caption = "";
    SCADAStatusLabel->Font->Color = clRed;
    SCADAStatusLabel->Caption = "DISCONNECTING ....";

    TcpSndFlag = false;
    SvrConFlag = false;
}
//---------------------------------------------------------------------------
void __fastcall TCommControlForm::SrvSocketClientConnect(TObject *Sender,
      TCustomWinSocket *Socket)
{
	SOCLST->Add(Socket);
    SvrConFlag = true;
    TcpSndFlag = true;

    SCADAStatusLabel->Font->Color = clBlue;
    SCADAStatusLabel->Caption = "CONNECTED ....";

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

void __fastcall TCommControlForm::SrvSocketClientDisconnect(
      TObject *Sender, TCustomWinSocket *Socket)
{
	  SOCLST->Remove(Socket);

    ServerButton->Enabled = true;
    SvrConFlag = false;
    TcpSndFlag = false;

    SCADAStatusLabel->Caption = "";
    SCADAStatusLabel->Font->Color = clRed;
    SCADAStatusLabel->Caption = "DISCONNECTED ....";

}
//---------------------------------------------------------------------------
void __fastcall TCommControlForm::FormActivate(TObject *Sender)
{
  Comm_IsActiveForm = true;
  if(PCProgramOption.SCADASystemSwitchEnabled)
  {
    this->Width = 581;
    this->Height = 788+170;
    CloseButton->Top = 676+170;
    CloseButton->Left = 432;

    SCADAPanel->Visible = true;
    SCADAStatusLabel->Visible = true;
  }
  else
  {
    this->Width = 581;
    this->Height = 788;
    CloseButton->Top = 676;
    CloseButton->Left = 224;
    SCADAPanel->Visible = false;
    SCADAStatusLabel->Visible = false;
  }
}
//---------------------------------------------------------------------------

void __fastcall TCommControlForm::ActiveStatus1Click(
      TObject *Sender)
{
  TTntSpeedButton * Btn = (TTntSpeedButton*)Sender;
  activemode = Btn->Tag;

  TIniFile *iniFile = new TIniFile(ProgramPath.Env + "\\UserSetting.ini");
	if (iniFile)
	{
    iniFile->WriteInteger("RecentBoardActiveStatus","Active",activemode);
    delete iniFile; // 1-usb all 2-hcb-usb/tcp-spb  3-tcp all
  }

  for(int index = 0; index < 1 + MachineSetupData.IPB_BoardCount; ++index )
  {
    TcpConnection[index].SetActiveMode(activemode);
  }
}
//---------------------------------------------------------------------------
bool __fastcall Comm_GetIgnoreState(int commIndex)
{
  bool State = false;
  if (CommControlForm != NULL)
	{
		State = CommControlForm->GetIgnoreState(commIndex);
	}
  return State;
}
//----------------------------------------------------------------------------
void __fastcall TCommControlForm::TntFormClose(TObject *Sender,
      TCloseAction &Action)
{
  Comm_IsActiveForm = false;  
}
//---------------------------------------------------------------------------


