예제 #1
0
        public static void ReadCallback(IAsyncResult ar)
        {
            String content = String.Empty;

            // Retrieve the state object and the handler socket
            // from the asynchronous state object.
            StateObject  state   = (StateObject)ar.AsyncState;
            Socket       handler = state.workSocket;
            EtherHandler eh      = (EtherHandler)Form.commHandler;

            eh.CSocketHandler = handler;

            try
            {
                if (handler != null)
                {
                    if (handler.Connected)
                    {
                        // Read data from the client socket.
                        int bytesRead = handler.EndReceive(ar);

                        if (bytesRead > 0)
                        {
                            // There  might be more data, so store the data received so far.
                            //state.sb.Append(Encoding.ASCII.GetString(
                            //  state.buffer, 0, bytesRead));

                            // Check for end-of-file tag. If it is not there, read
                            // more data.

                            //string str = string.Empty;
                            int           cnt = 0;
                            StringBuilder sb  = new StringBuilder();

                            foreach (byte b in state.buffer)
                            {
                                sb.Append(string.Format("[" + "{0:x2}" + "]", b));
                                cnt++;
                                if (cnt == bytesRead)
                                {
                                    break;
                                }
                            }

                            Form.Dispatcher.Invoke(() =>
                            {
                                //code 로 메시지 확인
                                switch (state.buffer[Frame.Code])
                                {
                                case Code.ACK:
                                    recvTab.SeqNum = (int)state.buffer[Frame.Seq];      ///전송연번 업데이트
                                    break;

                                case Code.NACK:
                                    recvTab.SeqNum = (int)state.buffer[Frame.Seq];      ///전송연번 업데이트
                                    //추후 재전송 로직 추가
                                    break;

                                case Code.STATUS_RES:                                  ///상태정보 수신
                                    {
                                        recvTab.SeqNum = (int)state.buffer[Frame.Seq]; ///전송연번 업데이트
                                        //ACK를 보내줌.
                                        ProcItem item = null;
                                        sndTab.MakeFrame(Code.ACK, out byte[] data, Form.comm, ref item);
                                        Send(data);
                                    }
                                    break;

                                case Code.VIO_CONFIRM_REQ:                             ///위반확인요구 수신
                                    {
                                        recvTab.SeqNum = (int)state.buffer[Frame.Seq]; ///전송연번 업데이트
                                        //ACK를 보내줌.
                                        //sndTab.MakeEtherFrame(Code.ACK, out byte[] data);
                                        //Send(handler, data);

                                        int nCopy        = Marshal.SizeOf(typeof(PACKET_VIO_REQUEST));
                                        byte[] _cpyArray = new byte[nCopy];

                                        Array.Copy(state.buffer, Frame.Data, _cpyArray, 0, nCopy);

                                        //위반확인응답을 보내줌.
                                        PACKET_VIO_REQUEST pVioReq = (PACKET_VIO_REQUEST)PacketMethods.ByteToStructure(_cpyArray, typeof(PACKET_VIO_REQUEST));
                                        if (pVioReq.imgStatus == 0x00)
                                        {
                                            recvTab.triggerStatus.Text = "정상";
                                        }
                                        else
                                        {
                                            recvTab.triggerStatus.Text = "비정상";
                                        }

                                        ProcItem pItem = new ProcItem((uint)sndTab.pcComboBox.SelectedIndex + 1);
                                        pItem.seq      = state.buffer[Frame.Seq];
                                        pItem.vioNum   = pVioReq.imagNum;
                                        sndTab.procList.Add(pItem);
                                        /// 영상번호 업데이트
                                        recvTab.imageNum.Text = pVioReq.imagNum.ToString();
                                        if (sndTab.syncMethod.SelectedIndex == 1)
                                        {
                                            int setByteOrder = sndTab.ByteOrder.SelectedIndex;
                                            sndTab.VioNumber = pVioReq.imagNum;

                                            byte[] cvtVioNum = BitConverter.GetBytes((short)sndTab.VioNumber);

                                            if (setByteOrder == 1)         // Big endian
                                            {
                                                cvtVioNum        = cvtVioNum.Reverse().ToArray();
                                                sndTab.VioNumber = BitConverter.ToInt16(cvtVioNum, 0);
                                            }
                                        }

                                        //위반확인자동응답 체크 시 전송을 수행함.
                                        if (othTab.autoVioSendCheck.IsChecked == true)
                                        {
                                            int maxLoop      = sndTab.pcComboBox.SelectedIndex + 1;
                                            uint saveProcNum = sndTab.ProcNumber1;
                                            for (sndTab.cycleNum = 1; sndTab.cycleNum <= maxLoop; sndTab.cycleNum++)
                                            {
                                                if (othTab.cnfResTypeComboBox.SelectedIndex == 0)
                                                {
                                                    if (sndTab.MakeFrame(Code.VIO_CONFIRM_RES, out byte[] data, ((MainWindow)System.Windows.Application.Current.MainWindow).comm, ref pItem) == true)
                                                    {
                                                        ((MainWindow)System.Windows.Application.Current.MainWindow).SendData(data, data.Length);
                                                    }
                                                }
                                                else
                                                {
                                                    //신규응답으로 보낸다.
                                                    if (sndTab.MakeFrame(Code.VIO_CONFIRM_RES_N, out byte[] data, ((MainWindow)System.Windows.Application.Current.MainWindow).comm, ref pItem) == true)
예제 #2
0
        public static void ReadCallback(IAsyncResult ar)
        {
            String content = String.Empty;

            // Retrieve the state object and the handler socket
            // from the asynchronous state object.
            StateObject state   = (StateObject)ar.AsyncState;
            Socket      handler = state.workSocket;

            Form.csocketHandler = handler;

            try
            {
                if (handler != null)
                {
                    if (handler.Connected)
                    {
                        // Read data from the client socket.
                        int bytesRead = handler.EndReceive(ar);

                        if (bytesRead > 0)
                        {
                            // There  might be more data, so store the data received so far.
                            //state.sb.Append(Encoding.ASCII.GetString(
                            //  state.buffer, 0, bytesRead));

                            // Check for end-of-file tag. If it is not there, read
                            // more data.

                            string str = string.Empty;
                            int    cnt = 0;
                            foreach (byte b in state.buffer)
                            {
                                str += string.Format("[" + "{0:x2}" + "]", b);
                                cnt++;
                                if (cnt == bytesRead)
                                {
                                    break;
                                }
                            }

                            Form.Dispatcher.Invoke(() =>
                            {
                                //code 로 메시지 확인
                                switch (state.buffer[Frame.Code])
                                {
                                case Code.ACK:
                                    recvTab.SeqNum = (int)state.buffer[Frame.Seq];      ///전송연번 업데이트
                                    break;

                                case Code.NACK:
                                    recvTab.SeqNum = (int)state.buffer[Frame.Seq];      ///전송연번 업데이트
                                    //추후 재전송 로직 추가
                                    break;

                                case Code.STATUS_RES:                                  ///상태정보 수신
                                    {
                                        recvTab.SeqNum = (int)state.buffer[Frame.Seq]; ///전송연번 업데이트
                                        //ACK를 보내줌.
                                        sndTab.MakeEtherFrame(Code.ACK, out byte[] data);
                                        Send(handler, data);
                                        //Thread.Sleep(100);
                                        //sndTab.MakeEtherFrame(Code.VIO_CONFIRM_RES, out byte[] data1);
                                        //Send(handler, data1);
                                    }
                                    break;

                                case Code.VIO_CONFIRM_REQ:                             ///위반확인요구 수신
                                    {
                                        recvTab.SeqNum = (int)state.buffer[Frame.Seq]; ///전송연번 업데이트
                                        //ACK를 보내줌.
                                        //sndTab.MakeEtherFrame(Code.ACK, out byte[] data);
                                        //Send(handler, data);

                                        int nCopy        = Marshal.SizeOf(typeof(PACKET_VIO_REQUEST));
                                        byte[] _cpyArray = new byte[nCopy];

                                        Array.Copy(state.buffer, Frame.Data, _cpyArray, 0, nCopy);

                                        //위반확인응답을 보내줌.
                                        PACKET_VIO_REQUEST pVioReq = (PACKET_VIO_REQUEST)PacketMethods.ByteToStructure(_cpyArray, typeof(PACKET_VIO_REQUEST));
                                        if (pVioReq.imgStatus == 0x00)
                                        {
                                            recvTab.triggerStatus.Text = "정상";
                                        }
                                        else
                                        {
                                            recvTab.triggerStatus.Text = "비정상";
                                        }

                                        ProcItem pItem = new ProcItem();
                                        pItem.seq      = state.buffer[Frame.Seq];
                                        pItem.vioNum   = pVioReq.imagNum;
                                        sndTab.procList.Add(pItem);
                                        /// 영상번호 업데이트
                                        recvTab.imageNum.Text = pVioReq.imagNum.ToString();
                                        if (sndTab.syncMethod.SelectedIndex == 1)
                                        {
                                            sndTab.VioNumber = pVioReq.imagNum;
                                        }


                                        //sndTab.MakeEtherFrame(Code.VIO_CONFIRM_RES, out byte[] data);
                                        //Send(handler, data);
                                    }
                                    break;

                                case Code.PLATE_RECOG_NOTIFY:
                                    {
                                        recvTab.SeqNum = (int)state.buffer[Frame.Seq];      ///전송연번 업데이트
                                    }
                                    break;

                                default:
                                    break;
                                }
                            }
                                                   );

                            try
                            {
                                Form.Dispatcher.Invoke(new UpdateTextDelegate(Form.DisplayText), recvTab.SocketRxList, str);
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show(ex.ToString());
                            }



                            if (content.IndexOf("<EOF>") > -1)
                            {
                                // All the data has been read from the
                                // client. Display it on the console.
                                Console.WriteLine("Read {0} bytes from socket. \n Data : {1}",
                                                  content.Length, content);
                                // Echo the data back to the client.
                                Send(handler, content);
                            }
                            else
                            {
                                // Not all data received. Get more.
                                handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                                                     new AsyncCallback(ReadCallback), state);
                            }
                        }
                        else
                        {
                            //소켓을 끊을 때.
                            handler.Shutdown(SocketShutdown.Both);
                            handler.Close();
                            try
                            {
                                Form.Dispatcher.Invoke(new UpdateTextDelegate(Form.DisplayText), recvTab.SocketRxList, "클라이언트 연결 끊김!!");
                                if (Form.runServer == false)
                                {
                                    Form.Dispatcher.Invoke(new UpdateButtonTextDelegate(Form.UpdateButtonText), "서버 시작");
                                }
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show(ex.ToString());
                            }
                        }
                    }
                    else
                    {
                        handler.Shutdown(SocketShutdown.Both);
                        handler.Close();
                        Form.Dispatcher.Invoke(new UpdateTextDelegate(Form.DisplayText), recvTab.SocketRxList, "강제로 소켓 끊김");
                        Form.Dispatcher.Invoke(new UpdateButtonTextDelegate(Form.UpdateButtonText), "서버 시작");
                    }
                }
                else
                {
                    Form.Dispatcher.Invoke(new UpdateTextDelegate(Form.DisplayText), recvTab.SocketRxList, "Client 소켓이 유효하지 않음");
                }
            }
            catch (Exception e)
            {
                if (Form.runServer == false)
                {
                    //사람이 서버를 종료한 경우에 한하여 버튼을 바꾼다.
                    Form.Dispatcher.Invoke(new UpdateButtonTextDelegate(Form.UpdateButtonText), "서버 시작");
                }
                Form.Dispatcher.Invoke(new UpdateTextDelegate(Form.DisplayText), recvTab.SocketRxList, "소켓 종료됨");
                //Form.Dispatcher.Invoke(new UpdateTextDelegate(Form.DisplayText), Form.SocketRxList, e.Message);
            }
        }
예제 #3
0
        void Serial_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            int len = commHandler.Read(dataBuf.buff, dataBuf.buffLen, dataBuf.buff.Length);

            dataBuf.buffLen += len;

            if (dataBuf.buffLen <= frameHeader.MinFrameLen)
            {
                return;
            }

            if (dataBuf.buff[dataBuf.buffLen - 2] != Protocols.ETX || dataBuf.buff[dataBuf.buffLen - 3] != Protocols.DLE)
            {
                return;
            }

            if (dataBuf.buffLen >= 1024)
            {
                dataBuf.reset();
            }


            Array.Copy(dataBuf.buff, 0, recvBuff.buff, recvBuff.buffLen, dataBuf.buffLen);
            recvBuff.buffLen += dataBuf.buffLen;
            dataBuf.reset();


            SerialRecvDelegate srdel = delegate()
            {
                byte[]        array = new byte[256];
                string        str   = string.Empty;
                StringBuilder sb    = new StringBuilder();

                bool findFrame = false;

                while (recvBuff.buffLen > 0)
                {
                    findFrame = false;
                    sb.Clear();

                    for (int i = frameHeader.MinFrameLen - 1; i < recvBuff.buffLen; i++)
                    {
                        if (recvBuff.buff[i - 1] == Protocols.ETX && recvBuff.buff[i - 2] == Protocols.DLE)
                        {
                            frameBuf.buffLen = i + 1;
                            Array.Copy(recvBuff.buff, 0, frameBuf.buff, 0, frameBuf.buffLen);
                            findFrame = true;
                            break;
                        }
                    }

                    if (findFrame == false)
                    {
                        return;
                    }

                    byte revBcc = frameBuf.buff[frameBuf.buffLen - 1];            //BCC 저장

                    Array.Copy(frameBuf.buff, 2, array, 0, frameBuf.buffLen - 5); // DLE STX ~ DLE ETX BCC 를 뺌.
                    int validSize = DelDLE(ref array, frameBuf.buffLen - 5);
                    Array.Copy(array, 0, recvBuff.buff, frameHeader.LenPos, validSize);

                    byte[] bccData = new byte[validSize - 1]; //LEN이 빠진 데이터 길이.

                    Array.Copy(array, 1, bccData, 0, bccData.Length);

                    byte calBcc = MainWindow.CalBCC(bccData, bccData.Length);

                    if (revBcc != calBcc)
                    {
                        frameBuf.reset();  //BCC 오류
                        Array.Clear(frameBuf.buff, 0, frameBuf.buff.Length);
                        sb.Append("BCC 오류");
                        return;
                    }
                    else
                    {
                        //frameBuf.buffLen = 5 + validSize;
                        frameBuf.buff[frameBuf.buffLen - 3] = Protocols.DLE;
                        frameBuf.buff[frameBuf.buffLen - 2] = Protocols.ETX;
                        frameBuf.buff[frameBuf.buffLen - 1] = revBcc;
                    }

                    switch (frameBuf.buff[frameHeader.CodePos])
                    {
                    case Code.ACK:
                        recvTab.SeqNum = (int)frameBuf.buff[frameHeader.SeqPos];      ///전송연번 업데이트
                        break;

                    case Code.NACK:
                        recvTab.SeqNum = (int)frameBuf.buff[frameHeader.SeqPos];      ///전송연번 업데이트
                        //추후 재전송 로직 추가
                        break;

                    case Code.STATUS_RES:                                        ///상태정보 수신
                    {
                        recvTab.SeqNum = (int)frameBuf.buff[frameHeader.SeqPos]; ///전송연번 업데이트
                        //ACK를 보내줌.
                        ProcItem item = null;
                        sndTab.MakeFrame(Code.ACK, out byte[] data, comm, ref item);
                        data[frameHeader.SeqPos] = frameBuf.buff[frameHeader.SeqPos];
                        //commHandler.Send(data,data.Length);
                        MainWindow.Send(data);
                    }
                    break;

                    case Code.VIO_CONFIRM_REQ:       ///위반확인요구 수신
                    {
                        ProcItem item = null;
                        recvTab.SeqNum = (int)frameBuf.buff[frameHeader.SeqPos];          ///전송연번 업데이트
                        sndTab.MakeFrame(Code.ACK, out byte[] data, comm, ref item);
                        data[frameHeader.SeqPos] = frameBuf.buff[frameHeader.SeqPos];
                        //commHandler.Send(data, data.Length);
                        MainWindow.Send(data);
                        //ACK를 보내줌.
                        int    nCopy     = Marshal.SizeOf(typeof(PACKET_VIO_REQUEST));
                        byte[] _cpyArray = new byte[nCopy];
                        Array.Copy(frameBuf.buff, 5, _cpyArray, 0, nCopy);

                        //위반확인응답을 보내줌.
                        PACKET_VIO_REQUEST pVioReq = (PACKET_VIO_REQUEST)PacketMethods.ByteToStructure(_cpyArray, typeof(PACKET_VIO_REQUEST));
                        if (pVioReq.imgStatus == 0x00)
                        {
                            recvTab.triggerStatus.Text = "정상";
                        }
                        else
                        {
                            recvTab.triggerStatus.Text = "비정상";
                        }

                        ProcItem pItem = new ProcItem((uint)sndTab.pcComboBox.SelectedIndex + 1);
                        pItem.seq    = frameBuf.buff[frameHeader.SeqPos];
                        pItem.vioNum = pVioReq.imagNum;
                        sndTab.procList.Add(pItem);
                        /// 영상번호 업데이트
                        recvTab.imageNum.Text = pVioReq.imagNum.ToString();
                        if (sndTab.syncMethod.SelectedIndex == 1)
                        {
                            sndTab.VioNumber = pVioReq.imagNum;
                        }

                        //위반확인자동응답 체크 시 전송을 수행함.
                        if (othTab.autoVioSendCheck.IsChecked == true)
                        {
                            int  maxLoop     = sndTab.pcComboBox.SelectedIndex + 1;
                            uint saveProcNum = sndTab.ProcNumber1;
                            for (sndTab.cycleNum = 1; sndTab.cycleNum <= maxLoop; sndTab.cycleNum++)
                            {
                                if (othTab.cnfResTypeComboBox.SelectedIndex == 0)
                                {
                                    if (sndTab.MakeFrame(Code.VIO_CONFIRM_RES, out byte[] auto_data, ((MainWindow)System.Windows.Application.Current.MainWindow).comm, ref pItem) == true)
                                    {
                                        ((MainWindow)System.Windows.Application.Current.MainWindow).SendData(auto_data, auto_data.Length);
                                    }
                                }