public void Write(ref byte[] buffer, int offset, int count)
        {
            var masterStopWatch           = Stopwatch.StartNew();
            var startTime                 = DateTime.Now;
            var numberOfActualBitsPerByte = (1 + (SerialPort.Parity == Parity.None ? 0 : 1) + SerialPort.DataBits + (SerialPort.StopBits == StopBits.None ? 0 : SerialPort.StopBits == StopBits.One ? 1 : SerialPort.StopBits == StopBits.OnePointFive ? 1.5 : 2));
            var transmitTimeMilliseconds  = ((count * numberOfActualBitsPerByte) / SerialPort.BaudRate) * 1000;
            var bufferLength              = buffer.Length;
            var writeBuffer               = new byte[bufferLength];

            Buffer.BlockCopy(buffer, 0, writeBuffer, 0, bufferLength);
            SerialPort.BaseStream.Write(writeBuffer, offset, count);
            SerialPort.BaseStream.Flush();
            while (SerialPort.BytesToWrite > 0)
            {
                Thread.Sleep(0);
            }

            TimedThreadBlocker.Wait((int)transmitTimeMilliseconds);

            masterStopWatch.Stop();
            if (TracingEnabled)
            {
                Trace.WriteLine(string.Format("Channel,{0},{1},{2},ChannelWrite,{3},{4},{5},SerialPortChannel", Name, startTime.ToString("O"), (1000.0 * (((double)masterStopWatch.ElapsedTicks) * (1.0 / ((double)Stopwatch.Frequency)))), 0, count, HexConverter.ToHexString(buffer)));
            }
        }
        private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            var startTime  = DateTime.Now;
            var lockObject = SourceChannel.LockObject;

            lock (lockObject)
            {
                var masterStopWatch = new Stopwatch();
                var requestBytes    = new byte[] { };

                TimedThreadBlocker.Wait(requestDelay);

                requestBytes = new byte[SerialPort.BytesToRead];

                if (requestBytes.Length > 0)
                {
                    Read(ref requestBytes, 0, requestBytes.Length, 0);
                    SourceChannel.Write(ref requestBytes, 0, requestBytes.Length);
                    TimedThreadBlocker.Wait(responseDelay);
                    masterStopWatch.Start();

                    var sequence = 0;
                    while (SourceChannel.NumberOfBytesAvailable > 0 && responseTimeout > masterStopWatch.ElapsedMilliseconds)
                    {
                        var responseBytes = new byte[SourceChannel.NumberOfBytesAvailable];

                        SourceChannel.Read(ref responseBytes, 0, responseBytes.Length, sequence++);
                        Write(ref responseBytes, 0, responseBytes.Length);
                    }

                    masterStopWatch.Stop();
                }
            }
        }
        public int Read(ref byte[] buffer, int offset, int count, int sequence)
        {
            var masterStopWatch           = Stopwatch.StartNew();
            var startTime                 = DateTime.Now;
            var bytesRead                 = new List <byte>();
            var numberOfActualBitsPerByte = (1 + (SerialPort.Parity == Parity.None ? 0 : 1) + SerialPort.DataBits + (SerialPort.StopBits == StopBits.None ? 0 : SerialPort.StopBits == StopBits.One ? 1 : SerialPort.StopBits == StopBits.OnePointFive ? 1.5 : 2));
            var receiveTimeMilliseconds   = ((count * numberOfActualBitsPerByte) / SerialPort.BaudRate) * 1000;

            TimedThreadBlocker.Wait((int)receiveTimeMilliseconds);

            var timeoutStopWatch = Stopwatch.StartNew();

            while (ReadTimeout > timeoutStopWatch.ElapsedMilliseconds)
            {
                var byteValue = -1;
                try
                {
                    byteValue = SerialPort.ReadByte();
                    if (byteValue >= 0)
                    {
                        bytesRead.Add((byte)byteValue);
                    }
                    if (count == bytesRead.Count)
                    {
                        goto Finish;
                    }
                }
                catch (TimeoutException toex)
                {
                    masterStopWatch.Stop();

                    if (bytesRead.Count > 0)
                    {
                        Buffer.BlockCopy(bytesRead.ToArray(), 0, buffer, offset, bytesRead.Count);
                    }

                    if (TracingEnabled)
                    {
                        Trace.WriteLine(string.Format("Channel,{0},{1},{2},ChannelRead,{3},{4},{5},SerialPortChannel", Name, startTime.ToString("O"), (1000.0 * (((double)masterStopWatch.ElapsedTicks) * (1.0 / ((double)Stopwatch.Frequency)))), sequence, bytesRead.Count, HexConverter.ToHexString(bytesRead.ToArray())));
                    }
                    throw toex;
                }
                Thread.Sleep(0);
            }

Finish:
            timeoutStopWatch.Stop();
            masterStopWatch.Stop();

            if (bytesRead.Count > 0)
            {
                Buffer.BlockCopy(bytesRead.ToArray(), 0, buffer, offset, bytesRead.Count);
            }

            if (TracingEnabled)
            {
                Trace.WriteLine(string.Format("Channel,{0},{1},{2},ChannelRead,{3},{4},{5},SerialPortChannel", Name, startTime.ToString("O"), (1000.0 * (((double)masterStopWatch.ElapsedTicks) * (1.0 / ((double)Stopwatch.Frequency)))), sequence, bytesRead.Count, HexConverter.ToHexString(bytesRead.ToArray())));
            }

            if (count != bytesRead.Count)
            {
                throw new TimeoutException("Read Timeout");
            }
            else
            {
                return(count);
            }
        }
Exemple #4
0
        private void TcpClientBeginReadCallback(IAsyncResult asyncResult)
        {
            var tcpClient = asyncResult.AsyncState as TcpClient;

            try
            {
                if (asyncResult.IsCompleted)
                {
                    if (tcpClient != null)
                    {
                        try
                        {
                            var startTime = DateTime.Now;
                            var sourceChannelLockObject = SourceChannel.LockObject;
                            lock (sourceChannelLockObject)
                            {
                                lock (lockObject)
                                {
                                    var readBuffer      = new byte[1500];
                                    var masterStopWatch = new Stopwatch();
                                    var requestBytes    = new byte[] { };
                                    var networkStream   = tcpClient.GetStream();

                                    this.tcpClient = tcpClient;

                                    TimedThreadBlocker.Wait(requestDelay);

                                    requestBytes = new byte[tcpClient.Available];

                                    if (requestBytes.Length > 0)
                                    {
                                        Read(ref requestBytes, 0, requestBytes.Length, 0);
                                        SourceChannel.Write(ref requestBytes, 0, requestBytes.Length);
                                        TimedThreadBlocker.Wait(responseDelay);
                                        masterStopWatch.Start();

                                        var sequence = 0;
                                        while (SourceChannel.NumberOfBytesAvailable > 0 && responseTimeout > masterStopWatch.ElapsedMilliseconds)
                                        {
                                            var responseBytes = new byte[SourceChannel.NumberOfBytesAvailable];

                                            SourceChannel.Read(ref responseBytes, 0, responseBytes.Length, sequence++);
                                            Write(ref responseBytes, 0, responseBytes.Length);
                                        }

                                        masterStopWatch.Stop();
                                    }

                                    networkStream.BeginRead(readBuffer, 0, 0, new AsyncCallback(TcpClientBeginReadCallback), tcpClient);

                                    return;
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Trace.TraceError($"Error reading newtwork stream: {ex.Message}");
                        }
                    }
                }

                try
                {
                    tcpClient.Dispose();
                }
                catch (Exception ex)
                {
                    Trace.TraceError($"Error disposing TCP Client: {ex.Message}");
                }

                try
                {
                    tcpClients.Remove(tcpClient);
                }
                catch (Exception ex)
                {
                    Trace.TraceError($"Error removing TCP Client from list: {ex.Message}");
                }

                Interlocked.Decrement(ref numberOfTcpClients);
            }
            catch (Exception ex)
            {
                Trace.TraceError($"Error disposing TCP Client: {ex.Message}");
            }
        }