private void PollingThread() { pollingThreadEvent = new ManualResetEvent(false); while (pollingThreadFlag) { try { //폴링 명령 클래스 생성 IEASProtocolBase protocolBase = IEASProtocolManager.CreateProtocol(0xFF); //전송 시스템 종류 셋팅 protocolBase.SenderType = IEASSenderType.SAS; //byte[] 형식의 frame 으로 변환 byte[] sendData = IEASProtocolManager.MakeFrame(protocolBase); //통합게이트웨이로 전송 if (SessionManager.GetInstance().Send(sendData)) { ListItemAdd("폴링 데이터 전송"); } else { ListItemAdd("폴링 데이터 전송 실패"); } pollingThreadEvent.WaitOne(5000); pollingThreadEvent.Reset(); } catch (Exception ex) { ListItemAdd("PollingThread Exception - " + ex.Message); } } pollingThreadEvent.Dispose(); pollingThreadEvent = null; }
/// <summary> /// SessionManager 연결 성공 이벤트 /// </summary> /// <param name="sender"></param> private void OnConnect(object sender) { ListItemAdd("통합게이트웨이 연결 성공"); gatewayIPTextBox.Invoke(new MethodInvoker(delegate() { gatewayIPTextBox.Enabled = false; })); gatewayPortTextBox.Invoke(new MethodInvoker(delegate() { gatewayPortTextBox.Enabled = false;; })); authentiCodeTextBox.Invoke(new MethodInvoker(delegate() { authentiCodeTextBox.Enabled = false; })); connectBtn.Invoke(new MethodInvoker(delegate() { connectBtn.Enabled = false; })); disconnectBtn.Invoke(new MethodInvoker(delegate() { disconnectBtn.Enabled = true; })); CreateParsingThread(); #region 접속 인증 요청 //접속 인증 요청 명령 클래스 생성 IEASProtocolBase protocolBase = IEASProtocolManager.CreateProtocol(0x03); //전송 시스템 종류 셋팅 protocolBase.SenderType = IEASSenderType.SAS; //명령 코드에 해당하는 클래스로 캐스팅 IEASPrtCmd3 prt3 = protocolBase as IEASPrtCmd3; //인증 코드 셋팅(32자) string authentiCode = authentiCodeTextBox.Text; prt3.AuthentiCode = authentiCode; //byte[] 형식의 frame 으로 변환 byte[] sendData = IEASProtocolManager.MakeFrame(prt3); //통합게이트웨이로 전송 if (SessionManager.GetInstance().Send(sendData)) { ListItemAdd("접속 인증 요청 전송"); } else { ListItemAdd("접속 인증 요청 전송 실패"); } #endregion }
/// <summary> /// 큐에 저장된 패킷 데이터를 프레임 단위로 파싱. /// </summary> private int ParsingQueuingData(byte[] queuingData) { try { if (queuingData == null) { System.Console.WriteLine("[CommunicationManager] 파싱 실패 : 입력 파라미터가 널"); return(-1); } AnalyzeResult frameResult = IEASProtocolManager.AnalyzeFrame(this.remainderPacket, queuingData); if (frameResult == null || frameResult.FrameInfo == null) { System.Console.WriteLine("[CommunicationManager] 파싱 실패 : 입력 파라미터가 널"); return(-2); } // 프레임을 분리하고 남은 불완전 데이터를 남은데이터 보관 버퍼(로컬)에 저장 this.remainderPacket = null; if (frameResult.RemainderFrame != null && frameResult.RemainderFrame.Length > 0) { this.remainderPacket = new byte[frameResult.RemainderFrame.Length]; Buffer.BlockCopy(frameResult.RemainderFrame, 0, this.remainderPacket, 0, frameResult.RemainderFrame.Length); } // 파싱 실패 체크: 프레임 단위로 분리할 만한 데이터 크기가 아닌 경우 등 if (frameResult.FrameInfo.Count == 0) { System.Console.WriteLine("[CommunicationManager] 프레임 분리 실패(길이 부족 등)"); return(-3); } for (int index = 0; index < frameResult.FrameInfo.Count; index++) { Frame currentFrame = frameResult.FrameInfo[index]; if (currentFrame.HeaderKind == HeaderKind.KCAP) { IEASProtocolBase baseData = IEASProtocolManager.ParseFrameForKCAP(currentFrame.Data); DistributeKCAPCommandData(baseData.CmdValue, baseData); } else { SYNCProtocolBase baseData = IEASProtocolManager.ParseFrameForSYNC(currentFrame.Data); DistributeSYNCCommandData(baseData.CmdValue, baseData); } } } catch (Exception ex) { System.Console.WriteLine("[CommunicationManager] ParsingQueuingData( " + ex.ToString() + " )"); FileLogManager.GetInstance().WriteLog("[CommunicationManager] ParsingQueuingData( Exception=[" + ex.ToString() + "] )"); return(-99); } return(0); }
/// <summary> /// 게이트웨이로 CAP 메시지 전송 /// </summary> public int SendCAP(string xmlCAPData) { try { IEASProtocolBase protoBase = IEASProtocolManager.CreateProtocolForKCAP(KCAPCmdValue.Order); protoBase.SenderType = IEASSenderType.SWI; IEASPrtCmd1 protoCmd1 = protoBase as IEASPrtCmd1; protoCmd1.CAPMessage = xmlCAPData; byte[] frameData = IEASProtocolManager.MakeFrameForKCAP(protoCmd1); bool result = this.sessionManager.SendData(frameData); } catch (Exception ex) { System.Console.WriteLine("[CommunicationManager] SendCAP( " + ex.ToString() + " )"); FileLogManager.GetInstance().WriteLog("[CommunicationManager] SendCAP( Exception=[" + ex.ToString() + "] )"); return(-99); } return(0); }
/// <summary> /// [발령 CAP 시험] 버튼 클릭 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void alertCAPTestBtn_Click(object sender, EventArgs e) { try { //발령 응답 명령 클래스 생성 IEASProtocolBase protocolBase = IEASProtocolManager.CreateProtocol(0x01); //전송 시스템 종류 셋팅 protocolBase.SenderType = IEASSenderType.SWI; //명령 코드에 해당하는 클래스로 캐스팅 IEASPrtCmd1 prt1 = protocolBase as IEASPrtCmd1; //응답 CAP 메시지 셋팅 string path = System.Environment.CurrentDirectory + @"\" + alertCAPMessageSampleFileName; prt1.CAPMessage = File.ReadAllText(path); //byte[] 형식의 frame 으로 변환 byte[] frame = IEASProtocolManager.MakeFrame(prt1); SessionManager.GetInstance().Send(frame); //발령 Frame 수신처리 //OnReceive(SessionManager.GetInstance(), frame); } catch (Exception ex) { ListItemAdd("발령 CAP 메시지 시험 실패 - " + ex.Message); } }
/// <summary> /// 인증 요청 /// </summary> public bool RequestAuth(string authCode) { bool result = false; try { IEASProtocolBase protoBase = IEASProtocolManager.CreateProtocolForKCAP(KCAPCmdValue.RequestAuth); protoBase.SenderType = IEASSenderType.SWI; IEASPrtCmd3 protoCmd3 = protoBase as IEASPrtCmd3; protoCmd3.AuthentiCode = authCode; byte[] authRequest = IEASProtocolManager.MakeFrameForKCAP(protoCmd3); result = this.sessionManager.SendData(authRequest); } catch (Exception ex) { System.Console.WriteLine("[CommunicationManager] RequestAuth( " + ex.ToString() + " )"); FileLogManager.GetInstance().WriteLog("[CommunicationManager] RequestAuth( Exception=[" + ex.ToString() + "] )"); return(false); } return(result); }
/// <summary> /// 파싱된 프로토콜 처리 /// </summary> /// <param name="prtBase"></param> private void ProtocolProcessing(IEASProtocolBase prtBase) { switch (prtBase.CMD) { case 0x01: { IEASPrtCmd1 prt1 = prtBase as IEASPrtCmd1; ListItemAdd("발령 CAP 메시지 수신 - CAP 메시지 : " + prt1.CAPMessage); MessageBox.Show(prt1.CAPMessage, "CAP 메시지 수신", MessageBoxButtons.OK); #region 응답 CAP 메시지 전송 //발령 응답 명령 클래스 생성 IEASProtocolBase protocolBase = IEASProtocolManager.CreateProtocol(0x02); //전송 시스템 종류 셋팅 protocolBase.SenderType = IEASSenderType.SAS; //명령 코드에 해당하는 클래스로 캐스팅 IEASPrtCmd2 prt2 = protocolBase as IEASPrtCmd2; //응답 CAP 메시지 셋팅 string path = System.Environment.CurrentDirectory + @"\" + ackCAPMessageSampleFileName; prt2.CAPMessage = File.ReadAllText(path); //byte[] 형식의 frame 으로 변환 byte[] sendData = IEASProtocolManager.MakeFrame(prt2); //frame 전송 if (SessionManager.GetInstance().Send(sendData)) { ListItemAdd("응답 CAP 메시지 전송"); } else { ListItemAdd("응답 CAP 메시지 전송 실패"); } #endregion } break; case 0x02: { IEASPrtCmd2 prt2 = prtBase as IEASPrtCmd2; ListItemAdd("응답 CAP 메시지 수신 - CAP 메시지 : " + prt2.CAPMessage); } break; case 0x03: { IEASPrtCmd3 prt3 = prtBase as IEASPrtCmd3; ListItemAdd("접속 인증 요청 명령 수신 - 인증코드 : " + prt3.AuthentiCode); } break; case 0x04: { IEASPrtCmd4 prt4 = prtBase as IEASPrtCmd4; if (prt4.AuthentiResult == 1) { ListItemAdd("접속 인증 결과 수신 - 접속승인"); CreatePollingThread(); } else { ListItemAdd("접속 인증 결과 수신 - 접속거부"); } } break; case 0xFF: { ListItemAdd("폴링 데이터 수신"); } break; default: { ListItemAdd("Parsing 결과 - 지원하지 않는 명령어 코드 입니다"); } break; } }
private void ParsingThread() { parsingThreadEvent = new ManualResetEvent(false); while (parsingThreadFlag) { try { int queueCount = 0; lock (receiveDataQueue) queueCount = receiveDataQueue.Count; if (queueCount > 0) { byte[] receiveData = null; lock (receiveDataQueue) receiveData = receiveDataQueue.Dequeue(); if (receiveData != null) { byte[] totalBuffer = new byte[remainBuffer.Length + receiveData.Length]; Array.Clear(totalBuffer, 0, totalBuffer.Length); int index = 0; Buffer.BlockCopy(remainBuffer, 0, totalBuffer, 0, remainBuffer.Length); index += remainBuffer.Length; Buffer.BlockCopy(receiveData, 0, totalBuffer, index, receiveData.Length); index += receiveData.Length; if (totalBuffer.Length > 6) { for (int i = 0; i < totalBuffer.Length; i++) { if (totalBuffer[i] == Convert.ToByte('K')) { if (i + 5 < totalBuffer.Length) { if (totalBuffer[i + 1] == Convert.ToByte('C') && totalBuffer[i + 2] == Convert.ToByte('A') && totalBuffer[i + 3] == Convert.ToByte('P')) { byte[] byDataLen = new byte[2]; Array.Clear(byDataLen, 0, 2); byDataLen[0] = totalBuffer[i + 4]; byDataLen[1] = totalBuffer[i + 5]; int dataLen = BitConverter.ToInt16(byDataLen, 0); if (i + 9 + dataLen < totalBuffer.Length) { byte[] frame = new byte[dataLen + 10]; Array.Clear(frame, 0, frame.Length); Buffer.BlockCopy(totalBuffer, i, frame, 0, frame.Length); i += frame.Length - 1; try { IEASProtocolBase prtBase = IEASProtocolManager.ParseFrame(frame); ProtocolProcessing(prtBase); } catch (Exception ex) { ListItemAdd("파싱 Exception - " + ex.Message); } } else { remainBuffer = new byte[totalBuffer.Length - i - 1]; Array.Clear(remainBuffer, 0, remainBuffer.Length); Buffer.BlockCopy(totalBuffer, i, remainBuffer, 0, remainBuffer.Length); break; } } else { continue; } } else { remainBuffer = new byte[totalBuffer.Length - i - 1]; Array.Clear(remainBuffer, 0, remainBuffer.Length); Buffer.BlockCopy(totalBuffer, i, remainBuffer, 0, remainBuffer.Length); break; } } else { if (i + 6 < totalBuffer.Length) { continue; } else { remainBuffer = new byte[totalBuffer.Length - i - 2]; Array.Clear(remainBuffer, 0, remainBuffer.Length); Buffer.BlockCopy(totalBuffer, i + 1, remainBuffer, 0, remainBuffer.Length); break; } } } } else { remainBuffer = new byte[totalBuffer.Length]; Array.Clear(remainBuffer, 0, remainBuffer.Length); Buffer.BlockCopy(totalBuffer, 0, remainBuffer, 0, totalBuffer.Length); continue; } } } else { parsingThreadEvent.WaitOne(500); parsingThreadEvent.Reset(); } } catch (Exception ex) { ListItemAdd("ParsingThread Exception - " + ex.Message); } } parsingThreadEvent.Dispose(); parsingThreadEvent = null; }
/// <summary> /// 폴링 처리 (쓰레드 호출용 함수) /// </summary> public void Polling() { try { System.Console.WriteLine("[CommunicationManager] 폴링 감시 준비"); if (this.manualEvtPolling == null) { this.manualEvtPolling = new ManualResetEvent(false); } // 최초 5초는 폴링 없이 대기 this.manualEvtPolling.WaitOne(5000); this.manualEvtPolling.Reset(); IEASProtocolBase protoBase = IEASProtocolManager.CreateProtocolForKCAP(KCAPCmdValue.Polling); protoBase.SenderType = IEASSenderType.SWI; byte[] pollingData = IEASProtocolManager.MakeFrameForKCAP(protoBase); System.Console.WriteLine("[CommunicationManager] 폴링 감시 시작"); while (this.isPollingContinue) { System.Console.WriteLine("[CommunicationManager] 폴링 체크"); bool pollingState = this.sessionManager.SendData(pollingData); if (this.NotifyIAGWConnectionState != null) { IAGWConnectionEventArgs copy = new IAGWConnectionEventArgs(); lock (this.currentIAGWConnectionState) { this.currentIAGWConnectionState.IsConnected = pollingState; copy.DeepCopyFrom(this.currentIAGWConnectionState); } this.NotifyIAGWConnectionState(this, copy); } this.manualEvtPolling.WaitOne(5000); this.manualEvtPolling.Reset(); } } catch (ThreadAbortException ex) { System.Console.WriteLine("[CommunicationManager] Polling( Exception=[ ThreadAbortException ] )"); FileLogManager.GetInstance().WriteLog("[CommunicationManager] Polling( Exception=[ ThreadAbortException ] )"); Thread.ResetAbort(); } catch (Exception ex) { System.Console.WriteLine("[CommunicationManager] Polling( Exception=[" + ex.ToString() + "] )"); FileLogManager.GetInstance().WriteLog("[CommunicationManager] Polling( Exception=[" + ex.ToString() + "] )"); throw new Exception("[CommunicationManager] 통합경보게이트웨이 연결 감시 처리 중에 예외가 발생하였습니다."); } finally { System.Console.WriteLine("[CommunicationManager] 폴링 감시 종료"); FileLogManager.GetInstance().WriteLog("[CommunicationManager] Polling( 종료 )"); this.isPollingContinue = false; if (this.manualEvtPolling != null) { this.manualEvtPolling.Close(); this.manualEvtPolling = null; } } }
/// <summary> /// 큐에 저장된 패킷 데이터를 프레임 단위로 파싱. /// </summary> private int DistributeKCAPCommandData(KCAPCmdValue command, IEASProtocolBase baseData) { try { System.Console.WriteLine("[CommunicationManager] KCAP 프레임 데이터 분배 - command(" + command + ")"); switch (command) { case KCAPCmdValue.OrderResponse: { IEASPrtCmd2 protoCmd2 = baseData as IEASPrtCmd2; if (this.NotifyCAPReceived != null) { CAP capMsg = new CAP(protoCmd2.CAPMessage); SenderTypes senderType = ConvertToLocalSenderType(protoCmd2.SenderType); ReceivedCAPInfo capInfo = new ReceivedCAPInfo(senderType, capMsg); this.NotifyCAPReceived(this, new CapEventArgs(capInfo)); } } break; case KCAPCmdValue.AuthResult: { IEASPrtCmd4 protoCmd4 = baseData as IEASPrtCmd4; if (this.NotifyIAGWConnectionState != null) { if (protoCmd4.SenderType == IEASSenderType.IAGW) { bool authResult = (protoCmd4.AuthentiResult == 0x01) ? true : false; IAGWConnectionEventArgs copy = new IAGWConnectionEventArgs(); lock (this.currentIAGWConnectionState) { this.currentIAGWConnectionState.IsAuthenticated = authResult; copy.DeepCopyFrom(this.currentIAGWConnectionState); } this.NotifyIAGWConnectionState(this, copy); } else { // 메시지 유효성 오류: 무시 } } } break; case KCAPCmdValue.Order: { IEASPrtCmd1 protoCmd1 = baseData as IEASPrtCmd1; if (this.NotifyCAPReceived != null) { CAP capMsg = new CAP(protoCmd1.CAPMessage); SenderTypes senderType = ConvertToLocalSenderType(protoCmd1.SenderType); ReceivedCAPInfo capInfo = new ReceivedCAPInfo(senderType, capMsg); this.NotifyCAPReceived(this, new CapEventArgs(capInfo)); } } break; case KCAPCmdValue.Polling: default: { // do nothing } break; } } catch (Exception ex) { System.Console.WriteLine("[CommunicationManager] DistributeKCAPCommandData( " + ex.ToString() + " )"); FileLogManager.GetInstance().WriteLog("[CommunicationManager] DistributeKCAPCommandData( Exception=[" + ex.ToString() + "] )"); return(-99); } return(0); }