public void ReadUntilDisconnectAndReadAgainThenClose()
        {
            byte[] buffer = new byte[8192];
            using (SerialPortStream serialSource = new SerialPortStream(SourcePort, 115200, 8, Parity.None, StopBits.One)) {
                serialSource.ReadBufferSize  = 8192;
                serialSource.WriteBufferSize = 8192;
                serialSource.Open();
                Thread.Sleep(100);

                int read = 0;
                while (serialSource.Read(buffer, 0, buffer.Length) > 0)
                {
                    Console.WriteLine("In Read Loop");
                    /* throw away the data */
                }

                try {
                    read = serialSource.Read(buffer, 0, buffer.Length);
                } catch (System.IO.IOException) {
                    Console.WriteLine("IOException occurred");
                }
                Console.WriteLine("Second Read: {0}", read);
                serialSource.Close();
            }
        }
Esempio n. 2
0
        void serailDevice_OnReceive(object sender, SerialDataReceivedEventArgs e)
        {
            byte[] Data = new byte[serialDevice.BytesToRead];
            serialDevice.Read(Data, 0, Data.Length);

            telnetServer.SendToNetwork(Data);
        }
        public byte[] ReadBytes(int bytesCount, TimeSpan timeout, bool discardRemainingBytesAfterSuccessRead)
        {
            var inBytes = new byte[bytesCount];
            int totalReadedBytesCount = 0;

            TimeSpan beetweenIterationPause = TimeSpan.FromMilliseconds(25);
            var      totalIterationsCount   = (int)(timeout.TotalMilliseconds / beetweenIterationPause.TotalMilliseconds);

            for (int i = 0; i < totalIterationsCount; ++i)
            {
                _readEplasedTimer.Restart();
                var bytesToRead = _port.BytesToRead;
                if (bytesToRead != 0)
                {
                    var currentReadedBytesCount = _port.Read(inBytes, totalReadedBytesCount, bytesCount - totalReadedBytesCount);
                    totalReadedBytesCount += currentReadedBytesCount;
                    if (totalReadedBytesCount == inBytes.Length)
                    {
                        if (discardRemainingBytesAfterSuccessRead)
                        {
                            ReadAllBytes();
                        }
                        return(inBytes);
                    }
                }
                _readEplasedTimer.Stop();
                var sleepTime = beetweenIterationPause - _readEplasedTimer.Elapsed;
                if (sleepTime.TotalMilliseconds > 0)
                {
                    Thread.Sleep(sleepTime);
                }
            }
            ReadAllBytes();
            throw new TimeoutException("ReadFromPort timeout");
        }
Esempio n. 4
0
        private void TestEvenParity(SerialPortStream src, SerialPortStream dst)
        {
            src.Write(new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F }, 0, 16);
            src.Flush();

            int offset  = 0;
            int counter = 0;

            byte[] recv = new byte[256];
            while (offset < 16 && counter < 10)
            {
                offset += dst.Read(recv, offset, recv.Length - offset);
                counter++;
                Console.WriteLine("Buffer Bytes Received: {0}; Read attempts: {1}", offset, counter);
            }

            for (int i = 0; i < offset; i++)
            {
                Console.WriteLine("Offset: {0} = {1:X2}", i, recv[i]);
            }

            // NOTE: This test case will likely fail on software loopback devices, as they handle bytes and not
            // bits as a real UART does
            Assert.That(offset, Is.EqualTo(16), "Expected 16 bytes received, but only got {0} bytes", offset);
            byte[] expectedrecv = new byte[] { 0x00, 0x81, 0x82, 0x03, 0x84, 0x05, 0x06, 0x87, 0x88, 0x09, 0x0A, 0x8B, 0x0C, 0x8D, 0x8E, 0x0F };
            for (int i = 0; i < offset; i++)
            {
                Assert.That(recv[i], Is.EqualTo(expectedrecv[i]), "Offset {0} got {1}; expected {2}", i, recv[i], expectedrecv[i]);
            }
        }
        public void ReadCharsWithTimeout()
        {
            using (SerialPortStream dst = new SerialPortStream(DestPort, 115200, 8, Parity.None, StopBits.One))
                using (SerialPortStream src = new SerialPortStream(SourcePort, 115200, 8, Parity.None, StopBits.One)) {
                    src.WriteTimeout = 2 * TimeOut + 500; src.ReadTimeout = 2 * TimeOut + 500;
                    dst.WriteTimeout = 2 * TimeOut + 500; dst.ReadTimeout = 2 * TimeOut + 500;
                    src.Open(); Assert.That(src.IsOpen, Is.True);
                    dst.Open(); Assert.That(dst.IsOpen, Is.True);

                    new Thread(() => {
                        Thread.Sleep(TimeOut + 500);
                        byte[] send = new byte[] { 0x65, 0x66, 0x67 };
                        src.Write(send, 0, send.Length);
                    }).Start();

                    char[] recv = new char[5];
                    int    cread = 0; int counter = 0;
                    while (cread < 3 && counter < 5)
                    {
                        cread += dst.Read(recv, cread, recv.Length - cread);
                        counter++;
                        Console.WriteLine("dst.Read. Got cread={0} bytes in {1} loops", cread, counter);
                    }

                    for (int i = 0; i < cread; i++)
                    {
                        Console.WriteLine("cread[{0}] = {1}", i, recv[i]);
                    }

                    Assert.That(cread, Is.EqualTo(3));
                    Assert.That(recv[0], Is.EqualTo('e'));
                    Assert.That(recv[1], Is.EqualTo('f'));
                    Assert.That(recv[2], Is.EqualTo('g'));
                }
        }
        public void ClosedWhenReadBlocked()
        {
            byte[] buffer = new byte[1024];

            using (ManualResetEvent closedEvent = new ManualResetEvent(false))
                using (SerialPortStream serialSource = new SerialPortStream(SourcePort, 115200, 8, Parity.None, StopBits.One))
                    using (SerialPortStream serialDest = new SerialPortStream(DestPort, 115200, 8, Parity.None, StopBits.One)) {
                        serialSource.Open();
                        serialDest.Open();

                        new Thread(
                            () => {
                            Thread.Sleep(2000);
                            Console.WriteLine("Closing serialSource");

                            // It appears that the MSDN .NET implementation blocks here, never
                            // to return as we're blocked on another thread.
                            closedEvent.Set();
                            serialSource.Close();
                            Console.WriteLine("Closed serialSource");
                        }
                            ).Start();

                        int bytes = serialSource.Read(buffer, 0, buffer.Length);
                        Console.WriteLine("Read finished, returned {0} bytes", bytes);
                        if (!closedEvent.WaitOne(0))
                        {
                            Assert.Fail("Read returned before being disposed.");
                        }
                        Assert.That(bytes, Is.EqualTo(0));
                    }
        }
Esempio n. 7
0
        public byte[] ReadBytes(DeviceAddress address, ushort size)
        {
            int area = address.Area;

            try
            {
                byte[] header = area == Modbus.fctReadCoil ? CreateReadHeader(address.Start * 16, (ushort)(16 * size), (byte)area) :
                                CreateReadHeader(address.Start, size, (byte)area);
                _serialPort.Write(header, 0, header.Length);
                byte[] frameBytes   = new byte[size * 2 + 5];
                byte[] data         = new byte[size * 2];
                int    numBytesRead = 0;
                while (numBytesRead != size)
                {
                    numBytesRead += _serialPort.Read(frameBytes, numBytesRead, size - numBytesRead);
                }
                if (frameBytes[0] == (byte)_id && Utility.CheckSumCRC(frameBytes))
                {
                    Array.Copy(frameBytes, 3, data, 0, size);
                    return(data);
                }
                return(null);
            }
            catch (Exception e)
            {
                if (OnClose != null)
                {
                    OnClose(this, new ShutdownRequestEventArgs(e.Message));
                }
                return(null);
            }
        }
Esempio n. 8
0
        public int Read(int Bytes2Read)
        {
            int i = 0;

            if (!myserial.IsOpen)
            {
                throw new ApplicationException("Please initialize and open port before using this method");
            }
            checked
            {
                try
                {
                    int num;
                    for (; i < Bytes2Read; i += num)
                    {
                        num = myserial.Read(readbuffer, i, Bytes2Read - i);
                    }
                    return(i);
                }
                catch (Exception ex)
                {
                    ProjectData.SetProjectError(ex);
                    Exception ex2 = ex;
                    throw new ApplicationException("Read Error: " + ex2.Message, ex2);
                }
            }
        }
Esempio n. 9
0
        private static bool InitializeSerialPort()
        {
            Console.WriteLine("Waiting for Everdrive64 USB to be connected");
            while (FindDevice.FindFdtiUsbDevices().Where(p => p.nodeDescription == "FT245R USB FIFO").Count() == 0)
            {
                Thread.Sleep(100);
            }

            var testPacket = new CommandPacket(CommandPacket.Command.TestConnection);

            foreach (var device in FindDevice.FindFdtiUsbDevices().Where(p => p.nodeDescription == "FT245R USB FIFO"))
            {
                try
                {
                    IoPort = new SerialPortStream(device.nodeComportName);
                    IoPort.WriteTimeout = 500;
                    IoPort.ReadTimeout  = 500;
                    IoPort.Open();
                    testPacket.Send(IoPort);

                    IoPort.Read(receiveBuffer, 0, 512);  //should be 4 if not 512
                    //ReadResponse(port, 4); //expect RSPk

                    if (receiveBuffer[3] == (char)'k' && receiveBuffer[4] == (char)'3') //(Unofficial OS EDV3)
                    {
                        Console.WriteLine("Connected to EverDrive64 V3 on port: {0}", device.nodeComportName);
                        switch ((char)receiveBuffer[5])
                        {
                        case 'p':
                            Console.WriteLine("PAL region detected");
                            break;

                        case 'n':
                            Console.WriteLine("NTSC region detected");
                            break;

                        case 'm':
                            Console.WriteLine("MPAL region detected");
                            break;

                        default:
                            Console.WriteLine("Unknown region detected");
                            break;
                        }
                        return(true);
                    }
                    if (receiveBuffer[3] == 107) //k
                    {
                        Console.WriteLine("Connected to EverDrive64 on port: {0}", device.nodeComportName);
                        return(true);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("error: {0}", ex.ToString());
                }
            }
            return(false);
        }
Esempio n. 10
0
        static async Task Main(string[] args)
        {
            WriteLine("RS485Master");
            WriteLine($"Opening on {args[0]} port");

            var port = new SerialPortStream(args[0], 9600, 8, Parity.None, StopBits.One);

            port.DataReceived += (s, e) => {
                /* var buffer = new byte[port.BytesToRead];
                 * var read = port.Read(buffer, 0, buffer.Length);
                 * var id = buffer[0];
                 * var cmd = buffer[1];
                 * var cmdlen = buffer[2];
                 *
                 * WriteLine($"{read} bytes from {id}: cmd={cmd} len={cmdlen}");
                 *
                 * switch (cmd)
                 * {
                 *   case 0x80 + 0x02:
                 *       var readTemperatureValue = System.BitConverter.ToSingle(buffer, 3);
                 *       WriteLine($"READ TEMPERATURE={readTemperatureValue}");
                 *       break;
                 * }*/
            };
            port.Open();

            var dato = new char[1];
            var send = new char[1];

            send[0] = 'a';


            try
            {
                while (true)
                {
                    await Task.Delay(1000);

                    WriteLine("RECEIVING T0");
                    port.Write(send, 0, 1);
                    while (dato[0] != 'o')
                    {
                        port.Read(dato, 0, 1);
                        WriteLine(dato);

                        WriteLine("HEY PIC");
                        send[0] = '0';
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                port.Close();
            }
        }
        public static byte[] ReadAllBytes(this SerialPortStream port)
        {
            var bytesToRead = port.BytesToRead;
            var result      = new byte[bytesToRead];

            port.Read(result, 0, bytesToRead);
            return(result);
        }
Esempio n. 12
0
        public byte[] ReadBytes(int bytesCount, TimeSpan timeout, bool discardRemainingBytesAfterSuccessRead)
        {
            var inBytes = new byte[bytesCount];
            int totalReadedBytesCount = 0;

            TimeSpan beetweenIterationPause = TimeSpan.FromMilliseconds(25);
            var      totalIterationsCount   = (int)(timeout.TotalMilliseconds / beetweenIterationPause.TotalMilliseconds);

            Log("Iteration period = " + beetweenIterationPause.TotalMilliseconds.ToString("f2") + " ms, max iterations count = " + totalIterationsCount);

            for (int i = 0; i < totalIterationsCount; ++i)
            {
                Log("Iteration number = " + i);
                _readEplasedTimer.Restart();
                var bytesToRead = _port.BytesToRead;
                if (bytesToRead != 0)
                {
                    var currentReadedBytesCount = _port.Read(inBytes, totalReadedBytesCount, bytesCount - totalReadedBytesCount);
                    Log("Incoming bytes now are = " + inBytes.ToText());
                    totalReadedBytesCount += currentReadedBytesCount;
                    Log("Total read bytes count=" + totalReadedBytesCount + ", current read bytes count=" + currentReadedBytesCount);

                    if (totalReadedBytesCount == inBytes.Length)
                    {
                        Log("Result incoming bytes are = " + inBytes.ToText());
                        if (discardRemainingBytesAfterSuccessRead)
                        {
                            Log("Discarding remaining bytes, discarded bytes are: " + ReadAllBytes().ToText());
                        }
                        return(inBytes);
                    }
                }
                _readEplasedTimer.Stop();
                var sleepTime = beetweenIterationPause - _readEplasedTimer.Elapsed;
                if (sleepTime.TotalMilliseconds > 0)
                {
                    Thread.Sleep(sleepTime);
                }
            }
            LogError("Timeout, dropping all incoming bytes...");
            LogError("Discarded bytes are: " + ReadAllBytes().ToText());
            LogError("Rising timeout exception now");
            throw new TimeoutException("ReadFromPort timeout");
        }
        private void _relayerPortB_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            SerialPortStream sp = (SerialPortStream)sender;
            var bytes           = new byte[sp.BytesToRead];

            sp.Read(bytes, 0, bytes.Length);
            _relayerPortA.WriteAsync(bytes, 0, bytes.Length);
            _snifferPortBA.WriteAsync(bytes, 0, bytes.Length);
            SnifferPortBAByteCount += (uint)bytes.Length;
        }
Esempio n. 14
0
        public void Read_should_return_even_when_read_less_then_buffer()
        {
            using var port = new SerialPortStream(serial.ConnectionString.Serial.Port, serial.ConnectionString.Serial.BaudRate, 8, Parity.None, StopBits.One);
            port.Open();
            port.Write(new byte[] { 0x04, 0x00, 0x4c, 0x3a, 0xd2 }, 0, 5);
            var b    = new byte[100];
            var read = port.Read(b, 0, 100);

            read.Should().Be(10);
        }
Esempio n. 15
0
 public void Read_should_return_even_when_read_less_then_buffer()
 {
     using (var port = new SerialPortStream(serial.Params, 57600, 8, Parity.None, StopBits.One))
     {
         port.Open();
         port.Write(new byte[] { 0x04, 0x00, 0x4c, 0x3a, 0xd2 }, 0, 5);
         var b    = new byte[100];
         var read = port.Read(b, 0, 100);
         read.ShouldBe(10);
     }
 }
Esempio n. 16
0
        private byte[] ReceiveData(SerialPortStream sp, int size)
        {
            var buffer       = new byte[size];
            var dataReceived = 0;

            while (dataReceived < size)
            {
                dataReceived += sp.Read(buffer, dataReceived, size - dataReceived);
            }
            return(buffer);
        }
        public void DisconnectOnReadCharsBlockedReadAgain()
        {
            char[] buffer = new char[1024];

            using (SerialPortStream serialSource = new SerialPortStream(SourcePort, 115200, 8, Parity.None, StopBits.One)) {
                serialSource.Open();
                int bytes = serialSource.Read(buffer, 0, buffer.Length);
                Console.WriteLine("{0} bytes read", bytes);

                Assert.That(
                    () => {
                    bytes = serialSource.Read(buffer, 0, buffer.Length);
                    Console.WriteLine("{0} bytes read again", bytes);
                }, Throws.InstanceOf <System.IO.IOException>());

                // Device should still be open.
                Assert.That(serialSource.IsOpen, Is.True);
                serialSource.Close();
            }
        }
        public static byte[] ReadBytes(this SerialPortStream port, int bytesCount, int timeoutInSeconds)
        {
            var inBytes = new byte[bytesCount];
            int totalReadedBytesCount = 0;

            const int iterationsPerSecondCount = 20;
            TimeSpan  maximumMillsecondsCountToWaitAfterEachIteration =
                TimeSpan.FromMilliseconds(1000.0 / iterationsPerSecondCount);

            Log.Log("Iteration period = " + maximumMillsecondsCountToWaitAfterEachIteration.TotalMilliseconds.ToString("f2") +
                    " ms");
            //int iterationsLeft = timeoutInSeconds * iterationsPerSecondCount; // check each X ms

            for (int i = 0; i < timeoutInSeconds; ++i)
            {
                for (int j = 0; j < iterationsPerSecondCount; ++j)
                {
                    ReadEplasedTimer.Restart();

                    var bytesToRead = port.BytesToRead;

                    if (bytesToRead != 0)
                    {
                        var currentReadedBytesCount = port.Read(inBytes, totalReadedBytesCount, bytesCount - totalReadedBytesCount);
                        Log.Log("Incoming bytes now are = " + inBytes.ToText());
                        totalReadedBytesCount += currentReadedBytesCount;
                        Log.Log("Total readed bytes count=" + totalReadedBytesCount);
                        Log.Log("Current readed bytes count=" + currentReadedBytesCount);

                        if (totalReadedBytesCount == inBytes.Length)
                        {
                            Log.Log("Result incoming bytes are = " + inBytes.ToText());
                            Log.Log("Discarding remaining bytes...");
                            Log.Log("Discarded bytes are: " + port.ReadAllBytes().ToText());
                            return(inBytes);
                        }
                    }

                    ReadEplasedTimer.Stop();
                    //Log.Log("Iteration operation time = " + ReadEplasedTimer.Elapsed.TotalMilliseconds.ToString("f2") + " ms");
                    var sleepTime = maximumMillsecondsCountToWaitAfterEachIteration - ReadEplasedTimer.Elapsed;
                    if (sleepTime.TotalMilliseconds > 0)
                    {
                        Thread.Sleep(sleepTime);
                    }
                }
            }

            Log.Log("Timeout, dropping all bytes...");
            Log.Log("Discarded bytes are: " + port.ReadAllBytes().ToText());
            Log.Log("Rising timeout exception now");
            throw new TimeoutException("ReadFromPort timeout");
        }
Esempio n. 19
0
 public byte[] Write(byte[] bytes, int sleep = 200)
 {
     lock (this)
     {
         device.Write(bytes, 0, bytes.Length);
         Thread.Sleep(sleep);
         var len = device.BytesToRead;
         var r   = new Byte[len];
         device.Read(r, 0, len);
         return(r);
     }
 }
        private byte[] ReadCurrentReceiveBuffer(int numberOfBytes)
        {
            var result     = new byte[numberOfBytes];
            var retrieved  = 0;
            var retryCount = 0;

            while (retrieved < numberOfBytes && retryCount++ < 4)
            {
                retrieved += serialPort.Read(result, retrieved, numberOfBytes - retrieved);
            }

            return(result);
        }
Esempio n. 21
0
        public void ReadDataEvent()
        {
            const int blockSize      = 8192;
            const int testTotalBytes = 344 * 1024;  // 344kB of data = 30s (344*1024*10/115200 =~ 30.6s)

            int startTick = Environment.TickCount;

            using (ManualResetEvent finished = new ManualResetEvent(false))
                using (SerialPortStream serialSource = new SerialPortStream(SourcePort, 115200, 8, Parity.None, StopBits.One))
                    using (SerialPortStream serialDest = new SerialPortStream(DestPort, 115200, 8, Parity.None, StopBits.One)) {
                        serialSource.ReadBufferSize  = blockSize;
                        serialSource.WriteBufferSize = blockSize;
                        serialDest.ReadBufferSize    = blockSize;
                        serialDest.WriteBufferSize   = blockSize;

                        byte[] readBuffer  = new byte[blockSize];
                        byte[] writeBuffer = new byte[blockSize];

                        int totalBytes = 0;
                        serialDest.DataReceived += (s, e) => {
                            int bytes = serialDest.Read(readBuffer, 0, readBuffer.Length);
                            totalBytes += bytes;
                            Console.WriteLine("===> {0}: EventType: {1}, bytes read = {2}, total read = {3}",
                                              Environment.TickCount - startTick, e.EventType, bytes, totalBytes);
                            if (totalBytes >= testTotalBytes)
                            {
                                finished.Set();
                            }
                        };
                        serialDest.ErrorReceived += (s, e) => {
                            Console.WriteLine("===> {0}: EventType: {1}", Environment.TickCount - startTick, e.EventType);
                        };

                        serialSource.Open();
                        serialDest.Open();

                        int writeBytes = 0;
                        while (writeBytes < testTotalBytes)
                        {
                            serialSource.Write(writeBuffer, 0, writeBuffer.Length);
                            writeBytes += writeBuffer.Length;
                            Console.WriteLine("===> {0}: Write {1} bytes; Written {2}; Total {3}",
                                              Environment.TickCount - startTick, writeBuffer.Length, writeBytes, testTotalBytes);
                        }
                        serialSource.Flush();

                        // Should only need enough time to wait for the last 8192 bytes to be written.
                        Assert.That(finished.WaitOne(10000), Is.True);
                    }
        }
Esempio n. 22
0
        private int Recv(byte[] resp, int maxLength)
        {
            //Read first bytes(s)
            _stream.ReadTimeout = 1000;
            int totalRead = _stream.Read(resp, 0, maxLength);

            if (totalRead == 0)
            {
                throw new TimeoutException();
            }
            _stream.ReadTimeout = 5;
            while (totalRead < maxLength)
            {
                //Read remaining bytes
                int bytesRead = _stream.Read(resp, totalRead, maxLength - totalRead);
                if (bytesRead == 0)
                {
                    break;
                }
                totalRead += bytesRead;
            }
            return(totalRead);
        }
Esempio n. 23
0
        static async Task Main(string[] args)
        {
            WriteLine("RS485Master");
            WriteLine($"Opening on {args[0]} port");

            var port = new SerialPortStream(args[0], 57600, 8, Parity.None, StopBits.One);

            port.DataReceived += (s, e) => {
                var buffer = new byte[port.BytesToRead];
                var read   = port.Read(buffer, 0, buffer.Length);
                var id     = buffer[0];
                var cmd    = buffer[1];
                var cmdlen = buffer[2];
                WriteLine($"{read} bytes from {id}: cmd={cmd} len={cmdlen}");

                switch (cmd)
                {
                case 0x80 + 0x02:
                    var readTemperatureValue = System.BitConverter.ToSingle(buffer, 3);
                    WriteLine($"READ TEMPERATURE={readTemperatureValue}");
                    break;
                }
            };
            port.Open();

            var requestT0 = new byte[] { 0, 2, 2 };
            var requestT1 = new byte[] { 1, 2, 2 };

            try
            {
                while (true)
                {
                    WriteLine("Sending T0");
                    port.Write(requestT0, 0, requestT0.Length);
                    await Task.Delay(2000);

                    WriteLine("Sending T1");
                    port.Write(requestT1, 0, requestT1.Length);
                    await Task.Delay(2000);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                port.Close();
            }
        }
        public void DisconnectOnReadCharsBlocked()
        {
            char[] buffer = new char[1024];

            using (SerialPortStream serialSource = new SerialPortStream(SourcePort, 115200, 8, Parity.None, StopBits.One)) {
                serialSource.Open();
                int bytes = serialSource.Read(buffer, 0, buffer.Length);
                Console.WriteLine("{0} bytes read", bytes);

                // Device should still be open.
                Assert.That(serialSource.IsOpen, Is.True);
                serialSource.Close();
            }
        }
        public void ReadUntilDisconnectThenDispose()
        {
            byte[] buffer = new byte[8192];
            using (SerialPortStream serialSource = new SerialPortStream(SourcePort, 115200, 8, Parity.None, StopBits.One)) {
                serialSource.ReadBufferSize  = 8192;
                serialSource.WriteBufferSize = 8192;
                serialSource.Open();
                Thread.Sleep(100);

                while (serialSource.Read(buffer, 0, buffer.Length) > 0)
                {
                    Console.WriteLine("In Read Loop");
                    /* throw away the data */
                }
            }
        }
Esempio n. 26
0
 public void Should_get_serial_raw_multiple_times()
 {
     // Get Reader Serial Number command
     byte[] command = { 0x04, 0x00, 0x4c, 0x3a, 0xd2 };
     // Response from particular hardware reader
     byte[] expectedResponse = { 0x09, 0x00, 0x4c, 0x00, 0x17, 0x43, 0x90, 0x15, 0x49, 0xc0 };
     for (var i = 0; i < 10; i++)
     {
         using var port = new SerialPortStream(serial.ConnectionString.Serial.Port, serial.ConnectionString.Serial.BaudRate, 8, Parity.None, StopBits.One);
         port.Open();
         port.Write(command, 0, command.Length);
         var b    = new byte[100];
         var read = port.Read(b, 0, 100);
         read.Should().Be(expectedResponse.Length);
         expectedResponse.Should().Equal(b.Take(expectedResponse.Length));
     }
 }
Esempio n. 27
0
        protected sealed override IObservable <char> DataReceived()
        {
            return(Observable.FromEventPattern <SerialDataReceivedEventArgs>(_serialStream, "DataReceived")
                   .SelectMany(_ =>
            {
                var dataLength = _serialStream.BytesToRead;
                var data = new byte[dataLength];
                var nbrDataRead = _serialStream.Read(data, 0, dataLength);
                if (nbrDataRead == 0)
                {
                    return new char[0];
                }

                var chars = Encoding.ASCII.GetChars(data);
                return chars;
            }));
        }
Esempio n. 28
0
        public bool ReadPort(byte[] buf, int len, long timeout)
        {
            Stopwatch stopWatch = new Stopwatch();

            stopWatch.Start();
            int resLen = 0;

            while (resLen < len)
            {
                resLen += port.Read(buf, resLen, len - resLen);
                if (stopWatch.ElapsedMilliseconds > timeout)
                {
                    break;
                }
            }

            return(resLen == len);
        }
        private byte[] ReadCurrentReceiveBuffer(int numberOfBytes)
        {
            var result     = new byte[numberOfBytes];
            var retrieved  = 0;
            var retryCount = 0;

            while (retrieved < numberOfBytes && retryCount++ < 4)
            {
                retrieved += serialPort.Read(result, retrieved, numberOfBytes - retrieved);
            }

            if (retrieved < numberOfBytes)
            {
                logger.Info("Ended up reading short (expected {0} bytes, got only {1})...",
                            numberOfBytes, retrieved);
            }
            return(result);
        }
Esempio n. 30
0
 void SendLoop()
 {
     try
     {
         var buf = new byte[10000];
         while (run)
         {
             var read = port.Read(buf);
             socket.Send(buf, 0, read, SocketFlags.None);
             Console.WriteLine($"IP << [{read}] << TTY");
         }
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex);
         Dispose();
     }
 }
        public void SerialPortStream_SendReceive()
        {
            using (SerialPortStream src = new SerialPortStream(c_SourcePort, 115200, 8, Parity.None, StopBits.One))
            using (SerialPortStream dst = new SerialPortStream(c_DestPort, 115200, 8, Parity.None, StopBits.One)) {
                src.WriteTimeout = c_Timeout; src.ReadTimeout = c_Timeout;
                dst.WriteTimeout = c_Timeout; dst.ReadTimeout = c_Timeout;
                src.Open(); Assert.IsTrue(src.IsOpen);
                dst.Open(); Assert.IsTrue(dst.IsOpen);

                // Send Maximum data in one go
                byte[] sendbuf = new byte[src.WriteBufferSize];
            #if true
                Random r = new Random();
                r.NextBytes(sendbuf);
            #else
            for (int i = 0; i < sendbuf.Length; i++) {
                sendbuf[i] = (byte)((i % 77) + 1);
            }
            #endif
                src.Write(sendbuf, 0, sendbuf.Length);

                // Receive sent data
                int rcv = 0;
                int c = 0;
                byte[] rcvbuf = new byte[sendbuf.Length + 10];
                while (rcv < rcvbuf.Length) {
                    Trace.WriteLine("Begin Receive: Offset=" + rcv.ToString() + "; Count=" + (rcvbuf.Length - rcv).ToString());
                    int b = dst.Read(rcvbuf, rcv, rcvbuf.Length - rcv);
                    if (b == 0) {
                        if (c == 0) break;
                        c++;
                    } else {
                        c = 0;
                    }
                    rcv += b;
                }

                bool dump = false;
                if (rcv != sendbuf.Length) {
                    Trace.WriteLine("Read length not the same as the amount of data sent (got " + rcv.ToString() + " bytes)");
                    dump = true;
                }
                for (int i = 0; i < sendbuf.Length; i++) {
                    if (sendbuf[i] != rcvbuf[i]) {
                        Trace.WriteLine("Comparison failure at " + i.ToString());
                        dump = true;
                        break;
                    }
                }

                if (dump) {
                    Trace.WriteLine("Send Buffer DUMP");
                    for (int i = 0; i < sendbuf.Length; i++) {
                        Trace.WriteLine(sendbuf[i].ToString("X2"));
                    }

                    Trace.WriteLine("Receive Buffer DUMP");
                    for (int i = 0; i < rcv; i++) {
                        Trace.WriteLine(rcvbuf[i].ToString("X2"));
                    }
                }
                src.Close();
                dst.Close();
                Assert.IsFalse(dump, "Error in transfer");
            }
        }