Exemple #1
0
        private void OnReceive(IAsyncResult result)
        {
            try
            {
                _recvLength += _socket.EndReceive(result);

                if (_recvStatus == ReceiveStatus.Idle)
                {
                    if (_recvLength < 4)
                    {
                        return;
                    }
                    _packetLength = BitConverter.ToInt32(_recvBuffer.Take(4).Reverse().ToArray(), 0);
                    Array.Resize(ref _recvBuffer, _packetLength);
                    _recvStatus = ReceiveStatus.RecvBody;
                }

                if (_recvStatus == ReceiveStatus.RecvBody)
                {
                    if (_recvLength == _packetLength)
                    {
                        _recvLength = 0;
                        _recvStatus = ReceiveStatus.Idle;

                        OnPacket(_recvBuffer);
                    }
                }
            }
            finally
            {
                _socket.BeginReceive(_recvBuffer, _recvLength, _recvBuffer.Length - _recvLength, SocketFlags.None, OnReceive, null);
            }
        }
Exemple #2
0
        public NodeEvent(byte[] payload)
            : base(FrameHeader.SOF, MessageType.Response, Channel.Function.ApplicationCommandHandler)
        {
            if (payload == null)
                throw new ArgumentNullException(nameof(payload));
            if (payload.Length < 2)
                throw new ReponseFormatException($"The response was not in the expected format. NodeEvent, payload: {BitConverter.ToString(payload)}");

            ReceiveStatus = ReceiveStatus.None;

            if ((payload[0] & 0x01) > 0)
                ReceiveStatus |= ReceiveStatus.RoutedBusy;
            if ((payload[0] & 0x02) > 0)
                ReceiveStatus |= ReceiveStatus.LowPower;
            if ((payload[0] & 0x0C) == 0x00)
                ReceiveStatus |= ReceiveStatus.TypeSingle;
            if ((payload[0] & 0x0C) == 0x01)
                ReceiveStatus |= ReceiveStatus.TypeBroad;
            if ((payload[0] & 0x0C) == 0x10)
                ReceiveStatus |= ReceiveStatus.TypeMulti;
            if ((payload[0] & 0x10) > 0)
                ReceiveStatus |= ReceiveStatus.TypeExplore;
            if ((payload[0] & 0x40) > 0)
                ReceiveStatus |= ReceiveStatus.ForeignFrame;

            NodeID = payload[1];
            Command = Command.Parse(payload.Skip(2).ToArray());
        }
Exemple #3
0
 public Messenger(ILog log)
 {
     _log = log;
     _receiveStatus = ReceiveStatus.AWAITING_CONTROL;
     _buffer = new List<byte>();
     _pending = new Queue<Message>();
     _incoming = new ConcurrentQueue<Incoming>();
     _processing = false;
 }
Exemple #4
0
 public Messenger(ILog log)
 {
     _log           = log;
     _receiveStatus = ReceiveStatus.AWAITING_CONTROL;
     _buffer        = new List <byte>();
     _pending       = new Queue <Message>();
     _incoming      = new ConcurrentQueue <Incoming>();
     _processing    = false;
 }
Exemple #5
0
        private ComResult SendBytes(byte[] bytes)
        {
            int  mychecksum;
            bool timeout = false;

            //send bytes & wait for checksum & check it
            bool checkOK = false;
            int  checks  = 0;

            theCheckSum = 0;              //reset the checksum (updated by receiving thread)
            while (!checkOK && checks < NR_MAX_CHECKSUM_CHECKS && !timeout)
            {
                //Console.WriteLine("Send2Bytes(" + byte1.ToString("X") + "," + byte2.ToString("X") + ")");
                mychecksum    = 0;
                receiveStatus = ReceiveStatus.Checksum;
                for (int i = 0; i < bytes.Length; i++)
                {
                    cm11.SendByte(bytes[i]);
                    mychecksum += bytes[i];
                }
                mychecksum = mychecksum & 255;

                if (evtChecksumReceived.WaitOne(TIME_WAIT_CHECKSUM, true))
                {
                    if (mychecksum == theCheckSum)
                    {
                        checkOK = true;
                    }
                    else
                    {
                        checks++;
                    }
                }
                else
                {
                    timeout = true;
                }
            }

            ComResult r;

            if (timeout)
            {
                r = ComResult.TimeOut;
            }
            else if (!checkOK)
            {
                r = ComResult.TooManyRetries;
            }
            else
            {
                r = ComResult.OK;
            }

            return(r);
        }
Exemple #6
0
        /// <summary>
        /// 打開網路插座
        /// </summary>
        /// <returns></returns>
        public bool OpenSocket()
        {
            _recvBuffer = new byte[2048];
            _recvStatus = ReceiveStatus.Idle;

            _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            _socket.Connect(_msfServers[0].url, _msfServers[0].port);
            _socket.BeginReceive(_recvBuffer, 0, _recvBuffer.Length, SocketFlags.None, OnReceive, null);

            return(true);
        }
Exemple #7
0
        /// <summary>
        /// 關閉網路插座
        /// </summary>
        /// <returns></returns>
        public bool CloseSocket()
        {
            if (_recvStatus == ReceiveStatus.Stop)
            {
                return(false);
            }

            _socket.Close();
            _recvStatus = ReceiveStatus.Stop;
            return(true);
        }
Exemple #8
0
 /// <summary>
 /// Casts ReceiveStatus events coming from a different thread to the UI thread when necessary.
 /// </summary>
 /// <param name="sender">The source of the event.</param>
 /// <param name="e">The <see cref="StatusEventArgs" /> instance containing the device status.</param>
 /// <exception cref="System.NullReferenceException">Platform not set.</exception>
 private void _comm_ReceiveStatus(object sender, StatusEventArgs e)
 {
     if (_platform == null)
     {
         throw new NullReferenceException("Platform not set.");
     }
     if (_platform.InvokeIfRequired(new StatusEventHandler(_comm_ReceiveStatus), sender, e)) //Recast event to UI thread when necessary
     {
         return;
     }
     ReceiveStatus?.Invoke(this, e);
 }
Exemple #9
0
        private void ProcessData()
        {
            status = ReceiveStatus.ReadData;
            var b2 = readBuffer.Pop(TcpConstant.DataLenghFieldLength);

            expectLength = TcpConstant.BitConvert.ToUInt16(b2);

            if (expectLength > Config.PackageMaxSize)
            {
                Connection.Close(ConnectionCloseType.PackageSizeTooLarge);
            }

            ProcessReceive();
        }
Exemple #10
0
        protected void ReceiveOnePointData()
        {
            receive_status = ReceivePointValues();

            if (receive_status == ReceiveStatus.DATA_TYPE)
            {
                Debug.Log("RECEIVED DATA_TYPE");
                ReceiveOnePointData();
            }

            // if (receive_status == ReceiveStatus.SET_COLOR)
            // {
            //     CloudUpdater.instance.ChangeCurrentColorMap(SMAPColorMap, false);
            // }

            if (receive_status == ReceiveStatus.SUCCESS)
            {
                Debug.Log("SUCCESS");
            }

            if (receive_status == ReceiveStatus.TIMEOUT)
            {
                Debug.Log("ERROR : Timeout");
            }

            if (receive_status == ReceiveStatus.INVALID_FORMAT)
            {
                Debug.Log("ERROR : Invalid Format");
            }

            if (receive_status == ReceiveStatus.BYTE_CONVERSION_ERROR)
            {
                Debug.Log("ERROR : Can't convert Bytes into floats");
            }

            if (receive_status == ReceiveStatus.NO_BYTES)
            {
                Debug.Log("ERROR : No Bytes were sent");
            }

            if (receive_status == ReceiveStatus.COLLUMN_SIZE_DISCREPANCY)
            {
                Debug.Log("ERROR : All collumns do not have the same size");
            }

            StopConnection();
        }
Exemple #11
0
        protected void SendOnePointData()
        {
            receive_status = SendPointValues();

            if (receive_status == ReceiveStatus.SUCCESS)
            {
                Debug.Log("SUCCESS");
            }

            if (receive_status == ReceiveStatus.TIMEOUT)
            {
                Debug.Log("ERROR : Timeout");
            }


            StopConnection();
        }
Exemple #12
0
        public NodeEvent(byte[] payload)
            : base(FrameHeader.SOF, MessageType.Response, Channel.Function.ApplicationCommandHandler)
        {
            if (payload == null)
            {
                throw new ArgumentNullException(nameof(payload));
            }
            if (payload.Length < 2)
            {
                throw new ReponseFormatException($"The response was not in the expected format. NodeEvent, payload: {BitConverter.ToString(payload)}");
            }

            ReceiveStatus = ReceiveStatus.None;

            if ((payload[0] & 0x01) > 0)
            {
                ReceiveStatus |= ReceiveStatus.RoutedBusy;
            }
            if ((payload[0] & 0x02) > 0)
            {
                ReceiveStatus |= ReceiveStatus.LowPower;
            }
            if ((payload[0] & 0x0C) == 0x00)
            {
                ReceiveStatus |= ReceiveStatus.TypeSingle;
            }
            if ((payload[0] & 0x0C) == 0x01)
            {
                ReceiveStatus |= ReceiveStatus.TypeBroad;
            }
            if ((payload[0] & 0x0C) == 0x10)
            {
                ReceiveStatus |= ReceiveStatus.TypeMulti;
            }
            if ((payload[0] & 0x10) > 0)
            {
                ReceiveStatus |= ReceiveStatus.TypeExplore;
            }
            if ((payload[0] & 0x40) > 0)
            {
                ReceiveStatus |= ReceiveStatus.ForeignFrame;
            }

            NodeID  = payload[1];
            Command = Command.Parse(payload.Skip(2).ToArray());
        }
    protected void repeatControl_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        DataRowView drv = e.Item.DataItem as DataRowView;

        if (drv == null)
        {
            return;
        }

        string rcvNumber = Cast.String(drv["OrderNumber"]);

        ReceiveStatus     status = Cast.Enum <ReceiveStatus>(drv["Status"]);
        HtmlInputCheckBox chk    = e.Item.FindControl("checkbox") as HtmlInputCheckBox;

        //LinkButton cmdDelete = e.Item.FindControl("cmdDelete") as LinkButton;
        //cmdDelete.Attributes["ordNum"] = rcvNumber;
        if (status != ReceiveStatus.New)
        {
            chk.Visible = false;
        }

        ApproveStatus approveResult  = Cast.Enum <ApproveStatus>(drv["ApproveResult"]);
        Label         lblApproveText = e.Item.FindControl("lblApproveResult") as Label;

        switch (approveResult)
        {
        case ApproveStatus.UnApprove:
            lblApproveText.Text = "";
            break;

        case ApproveStatus.Approve:
            lblApproveText.Text      = "通过";
            lblApproveText.ForeColor = System.Drawing.Color.Blue;
            break;

        case ApproveStatus.Reject:
            lblApproveText.Text      = "驳回";
            lblApproveText.ForeColor = System.Drawing.Color.Red;
            break;
        }
    }
Exemple #14
0
        private ComResult SendOKByte()
        {
            bool timeout = false;

            //send byte 0 & wait
            receiveStatus = ReceiveStatus.InterfaceReady;
            cm11.SendByte(0);

            if (!evtIFReadyReceived.WaitOne(TIME_WAIT_IFREADY, true))
            {
                timeout = true;
            }

            //collisions (CM11 starts upload of buffer) may happen when waiting for InterfaceReady
            if (collisionFlag)
            {
                collisionFlag = false;
                return(ComResult.Collision);
            }

            return(timeout?ComResult.TimeOut:ComResult.OK);
        }
Exemple #15
0
        protected void ReceiveOnePointData()
        {
            receive_status = ReceivePointValues();

            if (receive_status == ReceiveStatus.SUCCESS)
            {
                Debug.Log("SUCCESS");
            }

            if (receive_status == ReceiveStatus.TIMEOUT)
            {
                Debug.Log("ERROR : Timeout");
            }

            if (receive_status == ReceiveStatus.INVALID_FORMAT)
            {
                Debug.Log("ERROR : Invalid Format");
            }

            if (receive_status == ReceiveStatus.BYTE_CONVERSION_ERROR)
            {
                Debug.Log("ERROR : Can't convert Bytes into floats");
            }

            if (receive_status == ReceiveStatus.NO_BYTES)
            {
                Debug.Log("ERROR : No Bytes were sent");
            }

            if (receive_status == ReceiveStatus.COLLUMN_SIZE_DISCREPANCY)
            {
                Debug.Log("ERROR : All collumns do not have the same size");
            }


            StopConnection();
        }
Exemple #16
0
 private void ProcessDataLength()
 {
     status       = ReceiveStatus.ReadDataLength;
     expectLength = TcpConstant.DataLenghFieldLength;
     ProcessReceive();
 }
Exemple #17
0
        private void ReceiveLoopInternal()
        {
            StackPacket[] packets       = null;
            ReceiveStatus receiveStatus = ReceiveStatus.Success;
            //object endPoint = null;
            int bytesRecv      = 0;
            int leftCount      = 0;
            int expectedLength = this.maxBufferSize;

            while (!receiveThreadCancellationTokenSource.IsCancellationRequested)
            {
                if (expectedLength <= 0)
                {
                    expectedLength = this.maxBufferSize;
                }

                byte[] receivingBuffer = new byte[expectedLength];
                try
                {
                    bytesRecv = this.receiveStream.Read(receivingBuffer, 0, receivingBuffer.Length);

                    if (bytesRecv == 0)
                    {
                        receiveStatus = ReceiveStatus.Disconnected;
                    }
                    else
                    {
                        receiveStatus = ReceiveStatus.Success;
                    }
                }
                catch (IOException ioException)
                {
                    if (ioException.InnerException is SocketException socketException)
                    {
                        if (socketException.SocketErrorCode == SocketError.WouldBlock)
                        {
                            continue;
                        }
                    }

                    // If this is an IOException, treat it as a disconnection.
                    if (this.packetQueue != null)
                    {
                        TransportEvent exceptionEvent = new TransportEvent(EventType.Disconnected, this.endPointIdentity, null);
                        this.packetQueue.AddObject(exceptionEvent);
                        break;
                    }
                    else
                    {
                        throw;
                    }
                }

                if (receiveStatus == ReceiveStatus.Success)
                {
                    byte[] data = new byte[bytesRecv + receivedCaches.Length];
                    Array.Copy(receivedCaches, data, receivedCaches.Length);
                    Array.Copy(receivingBuffer, 0, data, receivedCaches.Length, bytesRecv);
                    while (true)
                    {
                        int consumedLength;

                        try
                        {
                            packets = this.decoder(this.endPointIdentity, data, out consumedLength, out expectedLength);
                        }
                        catch (Exception e)
                        {
                            TransportEvent exceptionEvent = new TransportEvent(EventType.Exception, this.endPointIdentity, e);
                            this.packetQueue.AddObject(exceptionEvent);

                            // If decoder throw exception, we think decoder will throw exception again when it decode
                            // subsequent received data So here we terminate the receive thread.
                            return;
                        }

                        if (consumedLength > 0)
                        {
                            //add packet to queue
                            if (packets != null && packets.Length > 0)
                            {
                                AddPacketToQueueManager(this.endPointIdentity, packets);
                            }

                            //check if continue the decoding
                            leftCount = data.Length - consumedLength;
                            if (leftCount <= 0)
                            {
                                receivedCaches = new byte[0];
                                data           = new byte[0];
                                break;
                            }
                            else
                            {
                                // Update caches contents to the bytes which is not consumed
                                receivedCaches = new byte[leftCount];
                                Array.Copy(data, consumedLength, receivedCaches, 0, leftCount);
                                data = new byte[receivedCaches.Length];
                                Array.Copy(receivedCaches, data, data.Length);
                            }
                        }
                        else
                        {
                            //if no data consumed, it means the left data cannot be decoded separately, so cache it and jump out.
                            receivedCaches = new byte[data.Length];
                            Array.Copy(data, receivedCaches, receivedCaches.Length);
                            break;
                        }
                    }
                }
                else if (receiveStatus == ReceiveStatus.Disconnected)
                {
                    if (this.packetQueue != null)
                    {
                        TransportEvent disconnectEvent = new TransportEvent(EventType.Disconnected, this.endPointIdentity, null);
                        this.packetQueue.AddObject(disconnectEvent);
                        break;
                    }
                    else
                    {
                        throw new InvalidOperationException("The transport is disconnected by remote host.");
                    }
                }
                else
                {
                    throw new InvalidOperationException("Unknown status returned from receiving method.");
                }
            }
        }
        public void Post()
        {
            _OrderStatus = ReceiveStatus.Complete;
            OnChanged("OrderStatus");

            SubProdOrder.UpdateQty();
            SubProdOrder.updateTimeStamp = false;
            SubProdOrder.Save();
        }
Exemple #19
0
 void processIncoming(byte[] cldata, int clsize)
 {
     _log.Debug("++ " + clsize.ToString() + " " + Encoding.UTF8.GetString(cldata, 0, clsize).Replace(System.Environment.NewLine, "RN"));
     _buffer.AddRange(cldata.Take(clsize));
     while (hasData())
     {
         _log.Debug("** " + _buffer.Count.ToString() + " " + Encoding.UTF8.GetString(_buffer.ToArray(), 0, _buffer.Count).Replace(System.Environment.NewLine, "RN"));
         _log.Debug(ControlStatus);
         if (_receiveStatus == ReceiveStatus.AWAITING_CONTROL)
         {
             string ctl = nextControl();
             if (ctl != null)
             {
                 _log.Debug("OP: {0}", ctl);
                 if (ctl.StartsWith(Message.MSG))
                 {
                     Message msg = Message.Parse(ctl);
                     _pending.Enqueue(msg);
                     _log.Debug("MSG {0} : {1}", msg.Size, _buffer.Count);
                     _receiveStatus = ReceiveStatus.AWAITING_PAYLOAD;
                     if (_buffer.Count < msg.Size + Message.CRLF.Length)
                     {
                         _log.Debug("Wait for remainder of message");
                         return;
                     }
                 }
                 else if (ctl.StartsWith(Message.PING))
                 {
                     _log.Debug("PING");
                     RaisePing();
                 }
                 else if (ctl.StartsWith(Message.PONG))
                 {
                     _log.Debug("PONG");
                     RaisePong();
                 }
                 else if (ctl.StartsWith(Message.OK))
                 {
                     _log.Debug("OK");
                 }
                 else if (ctl.StartsWith(Message.ERR))
                 {
                     _log.Debug("Error");
                     RaiseError();
                 }
                 else if (ctl.StartsWith(Message.INFO))
                 {
                     _log.Debug("Info");
                     RaiseInfo();
                 }
                 else if (ctl.StartsWith(Message.CRLF))
                 {
                     _log.Debug("CRLF");
                 }
                 else
                 {
                     _log.Warn("Unknown control received: {0}", ctl);
                 }
             }
         }
         else if (_receiveStatus == ReceiveStatus.AWAITING_PAYLOAD)
         {
             Message msg = _pending.Peek();
             if (_buffer.Count < msg.Size)// + Message.CRLF.Length)
             {
                 _log.Debug("Still waiting for remainder of message");
                 return;
             }
             _log.Debug("Reading Message {0}", msg.Size);// + Message.CRLF.Length);
             msg.Data = readData(msg.Size);// + Message.CRLF.Length);
             int idx = msg.Data.LastIndexOf(Message.CRLF);
             if (idx > -1)
                 msg.Data = msg.Data.Remove(idx, Message.CRLF.Length);
             _pending.Dequeue();
             RaiseMessage(msg);
             _receiveStatus = ReceiveStatus.AWAITING_CONTROL;
         }
     }
 }
Exemple #20
0
 public void CloseSocket()
 {
     _socket.Close();
     _recvStatus = ReceiveStatus.Stop;
     // _thread.Join();
 }
Exemple #21
0
        private bool pullPackage(byte[] buffer, out byte[] package)
        {
            package = new byte[0];

            bool ret = false;

            foreach (byte data in buffer)
            {
                switch (receiveStatus)
                {
                case ReceiveStatus.Start:
                    if (data == Protocal.PROTOCAL_START)
                    {
                        package       = ByteArray.CombomByteArray(package, new byte[] { data });
                        receiveStatus = ReceiveStatus.Addr;
                    }
                    break;

                case ReceiveStatus.Addr:
                    if (data != (byte)Communication.ADDR_TYPE.UDP)
                    {
                        receiveStatus = ReceiveStatus.Start;
                    }
                    else
                    {
                        package       = ByteArray.CombomByteArray(package, new byte[] { data });
                        receiveStatus = ReceiveStatus.Index;
                        rxIndex       = 0;
                    }
                    break;

                case ReceiveStatus.Index:
                    package = ByteArray.CombomByteArray(package, new byte[] { data });
                    if (++rxIndex >= 2)
                    {
                        rxIndex       = 0;
                        receiveStatus = ReceiveStatus.Size;
                    }
                    break;

                case ReceiveStatus.Size:
                    package = ByteArray.CombomByteArray(package, new byte[] { data });
                    rxIndex++;
                    if (rxIndex == 1)
                    {
                        dataSize = data;
                    }
                    else if (rxIndex == 2)
                    {
                        dataSize |= data << 8;
                    }
                    else
                    {
                        receiveStatus = ReceiveStatus.Token;
                    }
                    break;

                case ReceiveStatus.Token:
                    if (data != (byte)Protocal.PROTOCAL_TOKEN)
                    {
                        receiveStatus = ReceiveStatus.Start;
                    }
                    else
                    {
                        package       = ByteArray.CombomByteArray(package, new byte[] { data });
                        receiveStatus = ReceiveStatus.Data;
                    }
                    break;

                case ReceiveStatus.Data:
                    if ((dataSize--) != 0)
                    {
                        package = ByteArray.CombomByteArray(package, new byte[] { data });
                    }
                    if (dataSize == 0)
                    {
                        receiveStatus = ReceiveStatus.Crc16;
                        rxIndex       = 0;
                    }
                    break;

                case ReceiveStatus.Crc16:
                    package = ByteArray.CombomByteArray(package, new byte[] { data });
                    if (++rxIndex >= 2)
                    {
                        receiveStatus = ReceiveStatus.End;
                    }
                    break;

                case ReceiveStatus.End:
                    if (data == (byte)Protocal.PROTOCAL_END)
                    {
                        package = ByteArray.CombomByteArray(package, new byte[] { data });
                        ret     = true;
                    }
                    receiveStatus = ReceiveStatus.Start;
                    break;
                }
            }
            return(ret);
        }
Exemple #22
0
        private ComResult SendBytes(byte[] bytes)
        {
            int mychecksum;
            bool timeout = false;

            //send bytes & wait for checksum & check it
            bool checkOK = false;
            int checks = 0;
            theCheckSum = 0;  //reset the checksum (updated by receiving thread)
            while (!checkOK && checks<NR_MAX_CHECKSUM_CHECKS && !timeout)
            {
                //Console.WriteLine("Send2Bytes(" + byte1.ToString("X") + "," + byte2.ToString("X") + ")");
                mychecksum = 0;
                receiveStatus = ReceiveStatus.Checksum;
                for (int i=0; i<bytes.Length; i++)
                {
                    cm11.SendByte(bytes[i]);
                    mychecksum += bytes[i];
                }
                mychecksum = mychecksum & 255;

                if (evtChecksumReceived.WaitOne(TIME_WAIT_CHECKSUM, true))
                {
                    if (mychecksum == theCheckSum)
                        checkOK = true;
                    else
                        checks++;
                }
                else
                    timeout = true;
            }

            ComResult r;
            if (timeout)
                r=ComResult.TimeOut;
            else if(!checkOK)
                r=ComResult.TooManyRetries;
            else
                r=ComResult.OK;

            return r;
        }
Exemple #23
0
 void processIncoming(byte[] cldata, int clsize)
 {
     _log.Debug("++ " + clsize.ToString() + " " + Encoding.UTF8.GetString(cldata, 0, clsize).Replace(System.Environment.NewLine, "RN"));
     _buffer.AddRange(cldata.Take(clsize));
     while (hasData())
     {
         _log.Debug("** " + _buffer.Count.ToString() + " " + Encoding.UTF8.GetString(_buffer.ToArray(), 0, _buffer.Count).Replace(System.Environment.NewLine, "RN"));
         _log.Debug(ControlStatus);
         if (_receiveStatus == ReceiveStatus.AWAITING_CONTROL)
         {
             string ctl = nextControl();
             if (ctl != null)
             {
                 _log.Debug("OP: {0}", ctl);
                 if (ctl.StartsWith(Message.MSG))
                 {
                     Message msg = Message.Parse(ctl);
                     _pending.Enqueue(msg);
                     _log.Debug("MSG {0} : {1}", msg.Size, _buffer.Count);
                     _receiveStatus = ReceiveStatus.AWAITING_PAYLOAD;
                     if (_buffer.Count < msg.Size + Message.CRLF.Length)
                     {
                         _log.Debug("Wait for remainder of message");
                         return;
                     }
                 }
                 else if (ctl.StartsWith(Message.PING))
                 {
                     _log.Debug("PING");
                     RaisePing();
                 }
                 else if (ctl.StartsWith(Message.PONG))
                 {
                     _log.Debug("PONG");
                     RaisePong();
                 }
                 else if (ctl.StartsWith(Message.OK))
                 {
                     _log.Debug("OK");
                 }
                 else if (ctl.StartsWith(Message.ERR))
                 {
                     _log.Debug("Error");
                     RaiseError();
                 }
                 else if (ctl.StartsWith(Message.INFO))
                 {
                     _log.Debug("Info");
                     RaiseInfo();
                 }
                 else if (ctl.StartsWith(Message.CRLF))
                 {
                     _log.Debug("CRLF");
                 }
                 else
                 {
                     _log.Warn("Unknown control received: {0}", ctl);
                 }
             }
         }
         else if (_receiveStatus == ReceiveStatus.AWAITING_PAYLOAD)
         {
             Message msg = _pending.Peek();
             if (_buffer.Count < msg.Size)                    // + Message.CRLF.Length)
             {
                 _log.Debug("Still waiting for remainder of message");
                 return;
             }
             _log.Debug("Reading Message {0}", msg.Size); // + Message.CRLF.Length);
             msg.Data = readData(msg.Size);               // + Message.CRLF.Length);
             int idx = msg.Data.LastIndexOf(Message.CRLF);
             if (idx > -1)
             {
                 msg.Data = msg.Data.Remove(idx, Message.CRLF.Length);
             }
             _pending.Dequeue();
             RaiseMessage(msg);
             _receiveStatus = ReceiveStatus.AWAITING_CONTROL;
         }
     }
 }
Exemple #24
0
 private void NextPackage()
 {
     status       = ReceiveStatus.ReadType;
     expectLength = TcpConstant.HeadTypeLength;
     ProcessReceive();
 }
Exemple #25
0
        /// <summary>
        /// Receive data, decode Packet and add them to QueueManager in the loop.
        /// </summary>
        private void ReceiveLoop()
        {
            StackPacket[] packets       = null;
            ReceiveStatus receiveStatus = ReceiveStatus.Success;
            //object endPoint = null;
            int bytesRecv      = 0;
            int leftCount      = 0;
            int expectedLength = this.maxBufferSize;

            byte[] receivedCaches = new byte[0];

            while (!exitLoop)
            {
                if (expectedLength <= 0)
                {
                    expectedLength = this.maxBufferSize;
                }

                byte[] receivingBuffer = new byte[expectedLength];
                try
                {
                    bytesRecv = this.receiveStream.Read(receivingBuffer, 0, receivingBuffer.Length);

                    if (bytesRecv == 0)
                    {
                        receiveStatus = ReceiveStatus.Disconnected;
                    }
                    else
                    {
                        receiveStatus = ReceiveStatus.Success;
                    }
                }
                catch (System.IO.IOException)
                {
                    // If this is an IOException, treat it as a disconnection.
                    if (!exitLoop)
                    {
                        if (this.packetQueue != null)
                        {
                            TransportEvent exceptionEvent = new TransportEvent(EventType.Disconnected, this.endPointIdentity, null);
                            this.packetQueue.AddObject(exceptionEvent);
                            break;
                        }
                        else
                        {
                            throw;
                        }
                    }
                }
                catch (Exception e)
                {
                    if (!exitLoop)
                    {
                        if (this.packetQueue != null)
                        {
                            TransportEvent exceptionEvent = new TransportEvent(EventType.Exception, this.endPointIdentity, e);
                            this.packetQueue.AddObject(exceptionEvent);
                            break;
                        }
                        else
                        {
                            throw;
                        }
                    }
                }

                if (receiveStatus == ReceiveStatus.Success)
                {
                    byte[] data = new byte[bytesRecv + receivedCaches.Length];
                    Array.Copy(receivedCaches, data, receivedCaches.Length);
                    Array.Copy(receivingBuffer, 0, data, receivedCaches.Length, bytesRecv);
                    while (true)
                    {
                        int consumedLength;

                        try
                        {
                            packets = this.decoder(this.endPointIdentity, data, out consumedLength, out expectedLength);
                        }
                        catch (Exception e)
                        {
                            TransportEvent exceptionEvent = new TransportEvent(EventType.Exception, this.endPointIdentity, e);
                            this.packetQueue.AddObject(exceptionEvent);

                            // If decoder throw exception, we think decoder will throw exception again when it decode
                            // subsequent received data So here we terminate the receive thread.
                            return;
                        }

                        if (consumedLength > 0)
                        {
                            //add packet to queue
                            if (packets != null && packets.Length > 0)
                            {
                                AddPacketToQueueManager(this.endPointIdentity, packets);
                                bytesRecv = 0;
                                foreach (StackPacket pdu in packets)
                                {
                                    if (pdu.GetType() == typeof(Client_X_224_Connection_Request_Pdu))
                                    {
                                        // Block the thread if received a Client X224 Connection Request PDU
                                        // the main thread will resume the thread after it send X224 Connection confirm PDU and other necessary process, such as TLS Handshake
                                        rdpbcgrServer.ReceiveThreadControlEvent.WaitOne();
                                    }
                                }
                            }

                            //check if continue the decoding
                            leftCount = data.Length - consumedLength;
                            if (leftCount <= 0)
                            {
                                receivedCaches = new byte[0];
                                data           = new byte[0];
                                break;
                            }
                            else
                            {
                                // Update caches contents to the bytes which is not consumed
                                receivedCaches = new byte[leftCount];
                                Array.Copy(data, consumedLength, receivedCaches, 0, leftCount);
                                data = new byte[receivedCaches.Length];
                                Array.Copy(receivedCaches, data, data.Length);
                            }
                        }
                        else
                        {
                            //if no data consumed, it means the left data cannot be decoded separately, so cache it and jump out.
                            receivedCaches = new byte[data.Length];
                            Array.Copy(data, receivedCaches, receivedCaches.Length);
                            break;
                        }
                    }
                }
                else if (receiveStatus == ReceiveStatus.Disconnected)
                {
                    if (this.packetQueue != null)
                    {
                        TransportEvent disconnectEvent = new TransportEvent(EventType.Disconnected, this.endPointIdentity, null);
                        this.packetQueue.AddObject(disconnectEvent);
                        break;
                    }
                    else
                    {
                        throw new InvalidOperationException("The transport is disconnected by remote host.");
                    }
                }
                else
                {
                    throw new InvalidOperationException("Unknown status returned from receiving method.");
                }
            }
        }
Exemple #26
0
        private ComResult SendOKByte()
        {
            bool timeout = false;

            //send byte 0 & wait
            receiveStatus = ReceiveStatus.InterfaceReady;
            cm11.SendByte(0);

            if (!evtIFReadyReceived.WaitOne(TIME_WAIT_IFREADY, true))
                timeout = true;

            //collisions (CM11 starts upload of buffer) may happen when waiting for InterfaceReady
            if (collisionFlag)
            {
                collisionFlag = false;
                return ComResult.Collision;
            }

            return (timeout?ComResult.TimeOut:ComResult.OK);
        }
        public void Post()
        {
            _OrderStatus = ReceiveStatus.Complete;
            OnChanged("OrderStatus");

            PurchOrderLine.UpdateQty();
            PurchOrderLine.updateTimeStamp = false;
            PurchOrderLine.Save();

            if (SalesOrderLine != null)
            {
                SalesOrderLine.updateTimeStamp = false;
                SalesOrderLine.UpdateQty();
                SalesOrderLine.Save();
            }

            if (PurchOrderLine.SubItem.ItemType == SubItem.SubItemType.Subcon)
            {
                SubItemMonthly subItemMonthy = SubItemMonthly.Find(Session, PurchOrderLine.SubItem.ItemNo, CreatedDate.Year, CreatedDate.Month);

                if (subItemMonthy == null)
                {
                    subItemMonthy = new SubItemMonthly(Session);
                    subItemMonthy.SubItem = PurchOrderLine.SubItem;
                    subItemMonthy.DefaultGoodPercentage = PurchOrderLine.SubItem.DefaultGoodPercentage;
                    subItemMonthy.Year = CreatedDate.Year;
                    subItemMonthy.Month = CreatedDate.Month;
                    subItemMonthy.Save();
                }

                subItemMonthy.UpdateQty();
                subItemMonthy.Save();
            }
        }