Exemple #1
0
        public bool Open()
        {
            try
            {
                _stream = new SerialPortStream(_serialPort, 57600, 8, Parity.None,
                                               StopBits.One)
                {
                    ReadTimeout     = 1000,
                    WriteTimeout    = 1000,
                    ReadBufferSize  = 65535,
                    WriteBufferSize = 65535
                };

                _stream.DataReceived += _stream_DataReceived;

                _stream.Open();
                _connected = true;
            }
            catch (Exception e)
            {
                Logger.Logger.Instance.LogError("Could not open serial interface {0} {1}", _serialPort, e);

                return(false);
            }
            return(true);
        }
        public void SerialPortStream_Flush()
        {
            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);

                    byte[] sdata = new byte[512];
                    for (int i = 0; i < sdata.Length; i++)
                    {
                        sdata[i] = (byte)(64 + i % 48);
                    }

                    src.Write(sdata, 0, sdata.Length);
                    //System.Threading.Thread.Sleep(10);
                    src.Flush();
                    Assert.That(src.BytesToWrite, Is.EqualTo(0));

                    src.Write(sdata, 0, sdata.Length);
                    //System.Threading.Thread.Sleep(10);
                    src.Flush();
                    Assert.That(src.BytesToWrite, Is.EqualTo(0));
                }
        }
        public void SerialPortStream_WriteReadLine_CharForChar()
        {
            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);

                    bool   err = false;
                    string s   = null;

                    const string send = "A Brief History Of Time\n";

                    for (int i = 0; i < send.Length; i++)
                    {
                        src.Write(send[i].ToString());
                        try {
                            s = dst.ReadLine();
                        } catch (System.Exception e) {
                            if (e is TimeoutException)
                            {
                                err = true;
                            }
                        }
                        if (i < send.Length - 1)
                        {
                            Assert.IsTrue(err, "No timeout exception occurred when waiting for " + send[i].ToString() + " (position " + i.ToString() + ")");
                        }
                    }
                    Assert.AreEqual("A Brief History Of Time", s);
                }
        }
Exemple #4
0
        public void SendReceiveWithBeginEnd()
        {
            using (SerialPortStream src = new SerialPortStream(SourcePort, 115200, 8, Parity.None, StopBits.One))
                using (SerialPortStream dst = new SerialPortStream(DestPort, 115200, 8, Parity.None, StopBits.One)) {
                    src.WriteTimeout = TimeOut; src.ReadTimeout = TimeOut;
                    dst.WriteTimeout = TimeOut; dst.ReadTimeout = TimeOut;
                    src.Open(); Assert.That(src.IsOpen, Is.True);
                    dst.Open(); Assert.That(dst.IsOpen, Is.True);

                    SendReceiveAsyncState state = new SendReceiveAsyncState {
                        src     = src,
                        dst     = dst,
                        sendBuf = new byte[src.WriteBufferSize],
                        recvBuf = new byte[src.WriteBufferSize + 10]
                    };
                    Random r = new Random();
                    r.NextBytes(state.sendBuf);

                    // Here we start the read and write in parallel. The read will wait up to c_Timeout for the first byte.
                    dst.BeginRead(state.recvBuf, 0, state.recvBuf.Length, SendReceiveAsyncReadComplete, state);
                    src.BeginWrite(state.sendBuf, 0, state.sendBuf.Length, SendReceiveAsyncWriteComplete, state);
                    if (!state.finished.WaitOne(30000))
                    {
                        Assert.Fail("BeginWrite/BeginRead test case timeout");
                    }
                }
        }
        public void SerialPortStream_ReadTo_Overflow()
        {
            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 2048 ASCII characters
                    Random r     = new Random();
                    byte[] sdata = new byte[2048];
                    for (int i = 0; i < sdata.Length; i++)
                    {
                        sdata[i] = (byte)r.Next(65, 65 + 26);
                    }

                    // Wait for the data to be received
                    src.Write(sdata, 0, sdata.Length);
                    src.Write("EOF");
                    while (dst.BytesToRead < sdata.Length)
                    {
                        System.Threading.Thread.Sleep(100);
                    }

                    string result = dst.ReadTo("EOF");
                    Assert.AreEqual(0, dst.BytesToRead);
                    Assert.AreEqual(1024 - 3, result.Length);
                    int offset = sdata.Length - result.Length;
                    for (int i = 0; i < result.Length; i++)
                    {
                        Assert.AreEqual((int)sdata[offset + i], (int)result[i]);
                    }
                }
        }
        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();
            }
        }
        public void SerialPortStream_WriteReadLine_Multilines()
        {
            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);

                    bool err = false;

                    string s;
                    src.Write("Line1\nLine2\n");
                    s = dst.ReadLine();
                    Assert.AreEqual("Line1", s);
                    s = dst.ReadLine();
                    Assert.AreEqual("Line2", s);

                    try {
                        s = dst.ReadLine();
                    } catch (System.Exception e) {
                        if (e is TimeoutException)
                        {
                            err = true;
                        }
                    }
                    Assert.IsTrue(err, "No timeout exception occurred");
                }
        }
        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));
                    }
        }
        public void DisconnectOnWriteAsyncBlocked()
        {
            byte[] buffer = new byte[8192];
            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  = 8192;
                    serialSource.WriteBufferSize = 8192;
                    serialDest.ReadBufferSize    = 8192;
                    serialDest.WriteBufferSize   = 8192;
                    serialSource.Handshake       = Handshake.Rts;
                    serialSource.Open();
                    serialDest.Open();

                    serialDest.RtsEnable = false;
                    Thread.Sleep(100);

                    Assert.That(
                        () => {
                        while (true)
                        {
                            Console.WriteLine("DisconnectOnWriteAsyncBlocked BeginWrite");
                            IAsyncResult ar = serialSource.BeginWrite(buffer, 0, buffer.Length, null, null);
                            Console.WriteLine("DisconnectOnWriteAsyncBlocked EndWrite");
                            serialSource.EndWrite(ar);
                        }
                    }, Throws.InstanceOf <System.IO.IOException>());

                    // Device should still be open.
                    Assert.That(serialSource.IsOpen, Is.True);
                    serialSource.Close();
                }
        }
 private void portSelect_SelectedIndexChanged(object sender, EventArgs e)
 {
     if ((string)portSelect.SelectedItem == "(none)")
     {
         portStream.Close();
     }
     else
     {
         try
         {
             portStream.PortName = (string)portSelect.SelectedItem;
             portStream.Open();
         }
         catch
         {
             portStream.Close();
             RefreshPorts();
         }
     }
     transmitButton.Enabled = portStream.IsOpen;
     if (portStream.IsOpen)
     {
         statLabel.Text = "Connected to " + portStream.PortName;
     }
     else
     {
         statLabel.Text = "Not connected";
     }
 }
        public override void EstablishSync()
        {
            var ports   = SerialPortStream.GetPortNames();
            var newPort = ports.Except(originalPorts).SingleOrDefault();

            if (newPort == null)
            {
                UploaderLogger.LogErrorAndThrow(
                    string.Format(
                        "No (unambiguous) virtual COM port detected (after {0}ms).",
                        VIRTUAL_COM_CREATION_TIMEOUT));
            }

            SerialPort = new SerialPortStream
            {
                BaudRate  = 57600,
                PortName  = newPort,
                DataBits  = 8,
                Parity    = Parity.None,
                StopBits  = StopBits.One,
                Handshake = Handshake.DtrRts
            };
            try
            {
                SerialPort.Open();
            }
            catch (Exception ex)
            {
                UploaderLogger.LogErrorAndThrow(
                    string.Format("Unable to open serial port - {0}.", ex.Message));
            }
        }
        public override void Open()
        {
            var portName = serialPortConfig.PortName;
            var baudRate = serialPortConfig.BaudRate;

            logger.Info("Opening serial port {0} - baudrate {1}", serialPortConfig.PortName, serialPortConfig.BaudRate);

            SerialPort = new SerialPortStream(portName, baudRate)
            {
                ReadTimeout  = serialPortConfig.ReadTimeOut,
                WriteTimeout = serialPortConfig.WriteTimeOut,
                DtrEnable    = true // This means the Arduino will reset the moment we open the serial connection.
            };
            try
            {
                SerialPort.Open();
            }
            catch (ObjectDisposedException ex)
            {
                UploaderLogger.LogErrorAndQuit(
                    string.Format("Unable to open serial port {0} - {1}.", portName, ex.Message));
            }
            catch (InvalidOperationException ex)
            {
                UploaderLogger.LogErrorAndQuit(
                    string.Format("Unable to open serial port {0} - {1}.", portName, ex.Message));
            }
            logger.Trace("Opened serial port {0} with baud rate {1}!", portName, baudRate);
        }
        [Timeout(2000)] // We abort the test after timeout. This tests the blocking behavior in ReadAsync and the test will fail if ReadAsync blocks.
        public async Task WriteAsync()
        {
            using (var serialPortStreamWrite = new SerialPortStream("COM1", 9600, 8, Parity.None, StopBits.One))
                using (var serialPortStreamRead = new SerialPortStream("COM2", 9600, 8, Parity.None, StopBits.One))
                {
                    serialPortStreamWrite.Open();
                    serialPortStreamRead.Open();

                    var buffer   = new byte[1024];
                    var readTask = Task.Run(async() => await serialPortStreamRead.ReadAsync(buffer, 0, buffer.Length));

                    var bytes = new byte[] { 0x01, 0x02, 0x03 };
                    await serialPortStreamWrite.WriteAsync(bytes, 0, bytes.Length);

                    await serialPortStreamWrite.FlushAsync();

                    // ReadAsync blocks here even if something gets written and flushed to the underlying COM device.
                    // Fails for netcoreapp3.1, works with net472
                    await readTask;

                    Assert.That(buffer[0], Is.EqualTo(0x01));
                    Assert.That(buffer[1], Is.EqualTo(0x02));
                    Assert.That(buffer[2], Is.EqualTo(0x03));
                }
        }
Exemple #14
0
        public static List <List <double> > begin_test(SerialPortStream port)
        {
            port.Open();
            Console.WriteLine("Press any button to begin");
            Console.ReadKey(true);
            port.Write("<1>");
            List <List <double> > data = new List <List <double> >();
            bool collecting_data       = true;

            while (collecting_data)
            {
                if (port.BytesToRead > 0)
                {
                    string s = port.ReadLine();
                    s = Regex.Replace(s, @"\r", string.Empty);
                    if (s == "Done")
                    {
                        collecting_data = false;
                        break;
                    }
                    string[]      message = s.Split(',');
                    List <double> temp    = new List <double>();
                    foreach (string element in message)
                    {
                        double value = Convert.ToDouble(element);
                        temp.Add(value);
                        Console.WriteLine(element);
                    }
                    data.Add(temp);
                }
            }

            return(data);
        }
Exemple #15
0
        public void Flush()
        {
            using (SerialPortStream src = new SerialPortStream(SourcePort, 115200, 8, Parity.None, StopBits.One))
                using (SerialPortStream dst = new SerialPortStream(DestPort, 115200, 8, Parity.None, StopBits.One)) {
                    src.WriteTimeout = TimeOut; src.ReadTimeout = TimeOut;
                    dst.WriteTimeout = TimeOut; dst.ReadTimeout = TimeOut;
                    src.Open(); Assert.That(src.IsOpen, Is.True);
                    dst.Open(); Assert.That(dst.IsOpen, Is.True);

                    byte[] sdata = new byte[512];
                    for (int i = 0; i < sdata.Length; i++)
                    {
                        sdata[i] = (byte)(64 + i % 48);
                    }

                    // It should take 512 * 10 / 115200 s = 44ms to send, timeout of 300ms.
                    src.Write(sdata, 0, sdata.Length);
                    src.Flush();
                    Assert.That(src.BytesToWrite, Is.EqualTo(0));

                    src.Write(sdata, 0, sdata.Length);
                    src.Flush();
                    Assert.That(src.BytesToWrite, Is.EqualTo(0));
                }
        }
Exemple #16
0
 /// <summary>
 /// 接続を開きます
 /// </summary>
 /// <param name="port">The name of the COM port, such as "COM1" or "COM33".</param>
 /// <param name="baud">The baud rate that is passed to the underlying driver.</param>
 /// <param name="data">
 /// The number of data bits. This is checked that the driver supports the data bits
 /// provided. The special type 16X is not supported.
 /// </param>
 /// <param name="parity">The parity for the data stream.</param>
 /// <param name="stopbits">Number of stop bits.</param>
 public void Open(string port, int baud, int data, Parity parity, StopBits stopbits)
 {
     _logger.LogTrace("Open");
     serialPort = new SerialPortStream(port, baud, data, parity, stopbits);
     serialPort.DataReceived += DataReceived;
     serialPort.Open();
 }
        public void DtrDisableBeforeOpen()
        {
            SerialPortStream serial = null;

            try {
                serial = new SerialPortStream(SourcePort)
                {
                    BaudRate     = 115200,
                    DataBits     = 8,
                    Parity       = Parity.None,
                    DtrEnable    = false,
                    StopBits     = StopBits.One,
                    ReadTimeout  = -1,
                    WriteTimeout = -1
                };

                serial.Open();
                Assert.That(serial.DtrEnable, Is.False);
            } finally {
                if (serial != null)
                {
                    serial.Dispose();
                }
            }
        }
        public void ReadToOverflow()
        {
            using (SerialPortStream src = new SerialPortStream(SourcePort, 115200, 8, Parity.None, StopBits.One))
                using (SerialPortStream dst = new SerialPortStream(DestPort, 115200, 8, Parity.None, StopBits.One)) {
                    src.WriteTimeout = TimeOut; src.ReadTimeout = TimeOut;
                    dst.WriteTimeout = TimeOut; dst.ReadTimeout = TimeOut;
                    src.Open(); Assert.That(src.IsOpen, Is.True);
                    dst.Open(); Assert.That(dst.IsOpen, Is.True);

                    // Send 2048 ASCII characters
                    Random r     = new Random();
                    byte[] sdata = new byte[2048];
                    for (int i = 0; i < sdata.Length; i++)
                    {
                        sdata[i] = (byte)r.Next(65, 65 + 26);
                    }

                    // Wait for the data to be received
                    src.Write(sdata, 0, sdata.Length);
                    src.Write("EOF");
                    while (dst.BytesToRead < sdata.Length)
                    {
                        Thread.Sleep(100);
                    }

                    string result = dst.ReadTo("EOF");
                    Assert.That(dst.BytesToRead, Is.EqualTo(0));
                    Assert.That(result.Length, Is.EqualTo(1024 - 3));
                    int offset = sdata.Length - result.Length;
                    for (int i = 0; i < result.Length; i++)
                    {
                        Assert.That((int)result[i], Is.EqualTo(sdata[offset + i]));
                    }
                }
        }
        public void Prepare(Configurations configuration)
        {
            Current = this;

            SerialPortStream serialPortStream = new SerialPortStream(configuration.SerialPortName,
                                                                     configuration.SerialPortBaudRate,
                                                                     configuration.SerialPortDataBits,
                                                                     configuration.SerialPortParity,
                                                                     configuration.SerialPortStopBits);

            serialPortStream.Open( );

            SerialManager = new StreamManager(serialPortStream, configuration.ReceiveMode, configuration.SendMode);

            SerialManager.Run( );

            if (configuration.IsStatusServer)
            {
                TcpListener listener = new TcpListener(IPAddress.Any, configuration.StatusPort);
            }

            else
            {
                TcpClient client = new TcpClient(configuration.StatusServerHostName, configuration.StatusPort);

                SslStream sslStream = new SslStream(client.GetStream( ),
                                                    false,
                                                    ValidateServerCertificate,
                                                    null);

                sslStream.AuthenticateAsClient(configuration.StatusServerHostName);

                SocketManager = new StreamManager(sslStream, configuration.ReceiveMode, configuration.SendMode);
            }
        }
        public void ModemSignalsWithSleep10()
        {
            // On some chipsets (PL2303H Win7 x86), need small delays for this test case to work properly.
            using (SerialPortStream src = new SerialPortStream(SourcePort))
                using (SerialPortStream dst = new SerialPortStream(DestPort)) {
                    src.Handshake = Handshake.None;
                    dst.Handshake = Handshake.None;

                    src.Open();
                    dst.Open();

                    src.RtsEnable = false;
                    Thread.Sleep(10); // Required for PL2303H
                    Assert.That(dst.CtsHolding, Is.False);

                    src.RtsEnable = true;
                    Thread.Sleep(10); // Required for PL2303H
                    Assert.That(dst.CtsHolding, Is.True);

                    src.DtrEnable = false;
                    Thread.Sleep(10); // Required for PL2303H
                    Assert.That(dst.DsrHolding, Is.False);

                    src.DtrEnable = true;
                    Thread.Sleep(10); // Required for PL2303H
                    Assert.That(dst.DsrHolding, Is.True);
                }
        }
Exemple #21
0
 public async Task <bool> Connect()
 {
     if (_serial == null)
     {
         _serial           = new SerialPortStream();
         _serial.PortName  = Name;
         _serial.BaudRate  = Baud;
         _serial.Parity    = Parity;
         _serial.DataBits  = DataBits;
         _serial.StopBits  = StopBits;
         _serial.Handshake = Handshake;
     }
     try
     {
         if (!_serial.IsOpen)
         {
             await Task.Factory.StartNew(() => _serial.Open());
         }
         Stream = _serial;
         return(true);
     }
     catch (Exception)
     {
         return(false);
     }
 }
Exemple #22
0
 /// <summary>
 /// Initializes work of Arduino
 /// </summary>
 public void Initialize()
 {
     if (!_serialPort.IsOpen)
     {
         _serialPort.Open();
     }
 }
        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 ReadToWithOverflow2()
        {
            using (SerialPortStream src = new SerialPortStream(SourcePort, 115200, 8, Parity.None, StopBits.One))
                using (SerialPortStream dst = new SerialPortStream(DestPort, 115200, 8, Parity.None, StopBits.One)) {
                    src.WriteTimeout = -1; src.ReadTimeout = -1;
                    dst.WriteTimeout = -1; dst.ReadTimeout = -1;
                    src.Open(); Assert.That(src.IsOpen, Is.True);
                    dst.Open(); Assert.That(dst.IsOpen, Is.True);

                    byte[] writeData = new byte[2048];
                    for (int i = 0; i < writeData.Length - 1; i++)
                    {
                        writeData[i] = (byte)((i % 26) + 0x41);
                    }
                    writeData[writeData.Length - 1] = (byte)'\n';

                    // We write 2048 bytes that starts with A..Z repeated.
                    //  Position 0 = A
                    //  Position 1023 = J
                    //  Position 1024 = K
                    //  Position 2047 = \n
                    src.Write(writeData, 0, writeData.Length);
                    string line = dst.ReadLine();
                    Assert.That(line[0], Is.EqualTo('K'));
                    Assert.That(line.Length, Is.EqualTo(1023)); // Is 1024 - Length('\n').
                }
        }
        public void ReadToResetWithOverflow()
        {
            using (SerialPortStream src = new SerialPortStream(SourcePort, 115200, 8, Parity.None, StopBits.One))
                using (SerialPortStream dst = new SerialPortStream(DestPort, 115200, 8, Parity.None, StopBits.One)) {
                    src.WriteTimeout = TimeOut; src.ReadTimeout = TimeOut;
                    dst.WriteTimeout = TimeOut; dst.ReadTimeout = TimeOut;
                    src.Open(); Assert.That(src.IsOpen, Is.True);
                    dst.Open(); Assert.That(dst.IsOpen, Is.True);

                    byte[] writeData = new byte[2048];
                    for (int i = 0; i < writeData.Length; i++)
                    {
                        writeData[i] = (byte)((i % 26) + 0x41);
                    }

                    // We write 2048 bytes that starts with A..Z repeated.
                    //  Position 0 = A
                    //  Position 1023 = J
                    // To read a line, it parses the 2048 characters, not finding a new line. Then we read a character and
                    // we expect to get 'A'.
                    src.Write(writeData, 0, writeData.Length);
                    Assert.That(() => { dst.ReadLine(); }, Throws.Exception.TypeOf <TimeoutException>());
                    Assert.That(dst.ReadChar(), Is.EqualTo((int)'A'));
                }
        }
Exemple #26
0
        /// <summary>
        /// Reads and writes data to an arduino controller through a serialport to
        /// </summary>
        /// <param name="force">Force applied to point of rotation</param>
        /// <returns>Returns current angle of pendulum</returns>
        public double Calculate(double force)
        {
            // Read data from MPU6050
            // Write data to DC Motor

            // DC motor must not be based on velocity, the output should be based on torque change
            // IE higher motor output doesn't just increase speed, it also increases torque

            if (serialPort.IsOpen && serialPort.CanRead && serialPort.CanWrite)
            {
                //Write motor force to arduino
                serialPort.WriteLine(force.ToString());

                //Read current angle from arduino
                Double.TryParse(serialPort.ReadLine(), out double arduinoMPUData);

                theta = arduinoMPUData;
            }
            else
            {
                try
                {
                    serialPort.Open();
                }
                catch (Exception ex) { }

                //Use to test functionality of this application
                //modifier -= force * 0.001;
                //theta += modifier;
            }

            return(theta);
        }
Exemple #27
0
        public void Connect()
        {
            try
            {
                if (_serialPort.IsOpen)
                {
                    _serialPort.Close();
                }

                _serialPort.ReadTimeout    = -1;
                _serialPort.ErrorReceived += _serialPort_ErrorReceived;
                _serialPort.Open();
                if (_serialPort.IsOpen)
                {
                    if (OnConnected != null)
                    {
                        OnConnected();
                    }

                    _continue         = true;
                    _serialReadThread = new Thread(SerialPortRead);
                    _serialReadThread.Start();
                }
            } catch (Exception e)
            {
                if (OnDisconnected != null)
                {
                    OnDisconnected(e.Message);
                }
            }
        }
 public bool Initialize()
 {
     try
     {
         header = new byte[MAGIC.Length + 3];
         Array.Copy(MAGIC, header, MAGIC.Length);
         byte hi, lo, chk;
         hi  = (byte)((LedCount - 1) >> 8);
         lo  = (byte)((LedCount - 1) & 0xff);
         chk = (byte)(hi ^ lo ^ 0x55);
         header[MAGIC.Length]     = hi;
         header[MAGIC.Length + 1] = lo;
         header[MAGIC.Length + 2] = chk;
         if (port != null)
         {
             lock (port)
             {
                 port.Dispose();
             }
         }
         port          = new SerialPortStream();
         port.PortName = SerialPort;
         port.BaudRate = Baudrate;
         port.Open();
         AssignLeds();
         isInitialized = true;
         crashed       = false;
         return(true);
     }
     catch (Exception ex)
     {
         Crash(ex, "Initialization");
         return(false);
     }
 }
        private async Task <string> RunBootLoader(string nonBootLoaderPort, List <string> baselinePorts)
        {
            var port = new SerialPortStream(nonBootLoaderPort, 1200);

            port.Open();
            await Task.Delay(TimeSpan.FromSeconds(1));

            port.Close();
            int triesRemaining = 8;

            while (triesRemaining > 0)
            {
                await Task.Delay(TimeSpan.FromSeconds(1));

                var    candidates = SerialPortStream.GetPortNames().ToList();
                string candidateBootloaderPort = DetectNewPort(baselinePorts, candidates);
                if (!string.IsNullOrWhiteSpace(candidateBootloaderPort))
                {
                    return(candidateBootloaderPort);
                }
                --triesRemaining;
            }

            return(string.Empty);
        }
 public void DiscardOutBuffer()
 {
     using (SerialPortStream serialSource = new SerialPortStream(SourcePort, 115200, 8, Parity.None, StopBits.One)) {
         serialSource.Open();
         serialSource.DiscardOutBuffer();
     }
 }
        public void SerialPortStream_Basic()
        {
            using (SerialPortStream src = new SerialPortStream(c_SourcePort, 115200, 8, Parity.None, StopBits.One)) {
                src.WriteTimeout = 100;
                src.ReadTimeout = 100;

                Assert.IsTrue(src.CanRead);
                Assert.IsFalse(src.CanWrite);
                Assert.AreEqual(c_SourcePort, src.PortName);
                Assert.AreEqual(0, src.BytesToRead);
                Assert.AreEqual(0, src.BytesToWrite);

                src.Open();
                Assert.IsTrue(src.CanRead);
                Assert.IsTrue(src.CanWrite);
                Assert.IsTrue(src.IsOpen);

                src.Close();
                Assert.IsTrue(src.CanRead);
                Assert.IsFalse(src.CanWrite);
                Assert.IsFalse(src.IsOpen);
            }
        }
        public void SerialPortStream_WriteReadLine_MbcsByteForByte()
        {
            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);

                bool err = false;
                string s = null;

                byte[] buf = new byte[] {
                0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4A,
                0xE2, 0x82, 0xAC, 0x0A
            };

                for (int i = 0; i < buf.Length; i++) {
                    src.Write(buf, i, 1);
                    try {
                        s = dst.ReadLine();
                    } catch (System.Exception e) {
                        if (e is TimeoutException) err = true;
                    }
                    if (i < buf.Length - 1) {
                        Assert.IsTrue(err, "No timeout exception occurred when waiting for " + buf[i].ToString("X2") + " (position " + i.ToString() + ")");
                    }
                }
                Assert.AreEqual("ABCDEFGHIJ€", s);
            }
        }
        public void SerialPortStream_WriteReadLine_Timeout2()
        {
            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);

                bool err = false;

                string s;
                src.Write("Test");
                try {
                    s = dst.ReadLine();
                } catch (System.Exception e) {
                    if (e is TimeoutException) err = true;
                }
                Assert.IsTrue(err, "No timeout exception occurred");

                src.WriteLine("String");
                s = dst.ReadLine();
                Assert.AreEqual("TestString", s);
            }
        }
        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");
            }
        }
        public void SerialPortStream_WriteReadLine_CharForChar()
        {
            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);

                bool err = false;
                string s = null;

                const string send = "A Brief History Of Time\n";

                for (int i = 0; i < send.Length; i++) {
                    src.Write(send[i].ToString());
                    try {
                        s = dst.ReadLine();
                    } catch (System.Exception e) {
                        if (e is TimeoutException) err = true;
                    }
                    if (i < send.Length - 1) {
                        Assert.IsTrue(err, "No timeout exception occurred when waiting for " + send[i].ToString() + " (position " + i.ToString() + ")");
                    }
                }
                Assert.AreEqual("A Brief History Of Time", s);
            }
        }
        public void SerialPortStream_SendAndFlush1()
        {
            using (SerialPortStream dst = new SerialPortStream(c_DestPort, 115200, 8, Parity.None, StopBits.One))
            using (SerialPortStream src = new SerialPortStream(c_SourcePort, 115200, 8, Parity.None, StopBits.One)) {
                // Required for com0com to send the data (the remote side must receive it)
                dst.Open();

                src.Open();
                src.WriteLine("Connected");
                src.Flush();
            }
        }
        public void SerialPortStream_WriteReadLine()
        {
            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);

                string s;
                src.WriteLine("TestString");
                s = dst.ReadLine();
                Assert.AreEqual("TestString", s);
            }
        }
        public void SerialPortStream_ReadTo_Normal()
        {
            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);

                string s;

                src.Write("superfoobar");
                s = dst.ReadTo("foo");
                Assert.AreEqual("super", s);

                s = dst.ReadExisting();
                Assert.AreEqual("bar", s);
            }
        }
        public void SerialPortStream_SendAndFlush2()
        {
            using (SerialPortStream dst = new SerialPortStream(c_DestPort, 115200, 8, Parity.None, StopBits.One))
            using (SerialPortStream src = new SerialPortStream(c_SourcePort, 115200, 8, Parity.None, StopBits.One)) {
                // Required for com0com to send the data (the remote side must receive it)
                dst.Open();

                Trace.WriteLine("1. Open()");
                src.Open();
                Trace.WriteLine("2. WriteLine()");
                src.WriteLine("Connected");
                Trace.WriteLine("3. Sleep()");
                System.Threading.Thread.Sleep(100);
                Trace.WriteLine("4. WriteLine()");
                src.WriteLine("Disconnected");
                Trace.WriteLine("5. Flush()");
                src.Flush();
                Trace.WriteLine("6. Dispose()");
            }
        }
        public void SerialPortStream_OpenInUse()
        {
            using (SerialPortStream src = new SerialPortStream(c_SourcePort, 115200, 8, Parity.None, StopBits.One)) {
                src.Open();

                using (SerialPortStream s2 = new SerialPortStream(c_SourcePort, 9600, 8, Parity.None, StopBits.One)) {
                    bool err = false;
                    try {
                        s2.Open();
                    } catch {
                        err = true;
                    }
                    Assert.IsTrue(err, "Expected exception opening the port twice");
                }
            }
        }
        public void SerialPortStream_ReadTo_Overflow()
        {
            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 2048 ASCII characters
                Random r = new Random();
                byte[] sdata = new byte[2048];
                for (int i = 0; i < sdata.Length; i++) {
                    sdata[i] = (byte)r.Next(65, 65 + 26);
                }

                // Wait for the data to be received
                src.Write(sdata, 0, sdata.Length);
                src.Write("EOF");
                while (dst.BytesToRead < sdata.Length) {
                    System.Threading.Thread.Sleep(100);
                }

                string result = dst.ReadTo("EOF");
                Assert.AreEqual(0, dst.BytesToRead);
                Assert.AreEqual(1024 - 3, result.Length);
                int offset = sdata.Length - result.Length;
                for (int i = 0; i < result.Length; i++) {
                    Assert.AreEqual((int)sdata[offset + i], (int)result[i]);
                }
            }
        }
        public void SerialPortStream_OpenClose()
        {
            SerialPortStream src;
            using (src = new SerialPortStream(c_SourcePort, 115200, 8, Parity.None, StopBits.One)) {
                src.WriteTimeout = 100;
                src.ReadTimeout = 100;

                Assert.IsTrue(src.CanRead);
                Assert.IsFalse(src.CanWrite);
                Assert.IsFalse(src.IsOpen);
                Assert.IsFalse(src.IsDisposed);

                src.Open();
                Assert.IsTrue(src.CanRead);
                Assert.IsTrue(src.CanWrite);
                Assert.IsTrue(src.IsOpen);
                Assert.IsFalse(src.IsDisposed);

                src.Close();
                Assert.IsTrue(src.CanRead);
                Assert.IsFalse(src.CanWrite);
                Assert.IsFalse(src.IsOpen);
                Assert.IsFalse(src.IsDisposed);

                src.Open();
                Assert.IsTrue(src.CanRead);
                Assert.IsTrue(src.CanWrite);
                Assert.IsTrue(src.IsOpen);
                Assert.IsFalse(src.IsDisposed);

                src.Close();
                Assert.IsTrue(src.CanRead);
                Assert.IsFalse(src.CanWrite);
                Assert.IsFalse(src.IsOpen);
                Assert.IsFalse(src.IsDisposed);
            }
            Assert.IsTrue(src.IsDisposed);
        }
        public void SerialPortStream_ReadTo_Cached()
        {
            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);

                bool err = false;
                string s;

                src.Write("foobar");
                try {
                    s = dst.ReadTo("baz");
                } catch (System.Exception e) {
                    if (e is TimeoutException) err = true;
                }
                Assert.IsTrue(err, "No timeout exception occurred when reading 'baz'");

                s = dst.ReadTo("foo");
                Assert.AreEqual("", s);

                s = dst.ReadTo("bar");
                Assert.AreEqual("", s);

                try {
                    s = dst.ReadTo("baz");
                } catch (System.Exception e) {
                    if (e is TimeoutException) err = true;
                }
                Assert.IsTrue(err, "No timeout exception occurred when reading 'baz' when empty");
            }
        }