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));
                }
        }
Esempio n. 2
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));
                }
        }
Esempio n. 3
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 DisconnectOnFlushBlocked()
        {
            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(
                        () => {
                        Console.WriteLine("DisconnectOnFlushBlocked Writing");
                        serialSource.Write(buffer, 0, buffer.Length);
                        Console.WriteLine("DisconnectOnFlushBlocked Flushing");
                        serialSource.Flush();
                        Console.WriteLine("DisconnectOnFlushBlocked Flushed");
                    }, Throws.InstanceOf <System.IO.IOException>());

                    // Device should still be open.
                    Assert.That(serialSource.IsOpen, Is.True);
                    serialSource.Close();
                }
        }
Esempio n. 5
0
        public void SendReceive(ArduinoCommand cmd, out ArduinoCommand resp)
        {
            const long timeout = 2000;

            byte[] packet = cmd.Build();
            port.ReadExisting();
            log.Info("Отправляем команду: {0}", Encoding.ASCII.GetString(packet));
            port.Write(packet, 0, packet.Length);

            if (!ReadPort(packet, 3, timeout))
            {
                log.Error("Не удалось прочитать заголовок команды");
                port.Flush();
                throw new IOException();
            }
            if (packet[0] != ':')
            {
                log.Error("Заголовок команды содержит неверный стартовый символ");
                port.Flush();
                throw new IOException();
            }
            string strLen  = Encoding.ASCII.GetString(packet, 1, 2);
            int    len     = int.Parse(strLen, NumberStyles.AllowHexSpecifier);
            string strResp = "";

            if (len > 0)
            {
                packet = new byte[len];
                if (!ReadPort(packet, len, timeout))
                {
                    log.Error("Не удалось прочитать команду: неправильная длина");
                    port.Flush();
                    throw new IOException();
                }
                strResp = Encoding.ASCII.GetString(packet, 1, packet.Length - 2);
            }
            resp = new ArduinoCommand
            {
                Command    = Encoding.ASCII.GetString(packet, 0, 1)[0],
                Parameters = new List <string>(strResp.Split(new  [] { ',' }, StringSplitOptions.RemoveEmptyEntries))
            };

            log.Info("Получена команда {0} {1}", resp.Command, strResp);
        }
        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 DisposedWhenFlushBlocked()
        {
            byte[] buffer = new byte[8192];

            SerialPortStream serialSource = new SerialPortStream(SourcePort, 115200, 8, Parity.None, StopBits.One);
            Thread           testThread;

            using (ManualResetEvent disposedEvent = new ManualResetEvent(false))
                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);

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

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

                    Assert.That(
                        () => {
                        Console.WriteLine("DisposedWhenFlushBlocked Writing");
                        serialSource.Write(buffer, 0, buffer.Length);
                        Console.WriteLine("DisposedWhenFlushBlocked Flushing");
                        serialSource.Flush();
                        Console.WriteLine("DisposedWhenFlushBlocked Flushed");
                        if (disposedEvent.WaitOne(0))
                        {
                            Assert.Fail("Write returned after being disposed.");
                        }
                    }, Throws.InstanceOf <ObjectDisposedException>());
                }

            testThread.Join(20000);
            Console.WriteLine("Finished");
        }
Esempio n. 8
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);
                    }
        }
        private void ReadStreamListener()
        {
            _serialPort.Flush();
            while (IsSerialPortAvailable())
            {
                try
                {
                    var line = _serialPort.ReadLine();
                    _resp.FeedMessage(line);
#if DEBUG
                    _conversationLogger.ReceivedBySerial(line);
#endif
                }
                catch (Exception)
                {
                }
            }
        }
Esempio n. 10
0
 public void Close()
 {
     if (!IsOpen)
     {
         return;
     }
     try
     {
         _arduinoPort.Flush();
         _arduinoPort.DataReceived -= DataRecieved;
         _arduinoPort.Close();
         IsOpen = false;
     }
     catch (Exception)
     {
         //do nothing
     }
 }
        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()");
                }
        }
Esempio n. 12
0
        public void SendReceiveBoundaries()
        {
            using (var sp = new SerialPortStream(SourcePort, 56700))
                using (var spReceive = new SerialPortStream(DestPort, 56700)) {
                    var bufferSize = 250;

                    // get data which is a bit larger than twice the size of the buffer (0x20000*2)
                    var data     = Enumerable.Range(0, (sp.WriteBufferSize * 2) + 0x100).Select(e => (byte)(e % 0xFF)).ToArray();
                    var size     = data.Length; // 0x40100
                    var position = 0;
                    sp.Open();
                    spReceive.Open();

                    List <int> positions = new List <int>();
                    while (size - position > bufferSize)
                    {
                        positions.Add(position);
                        if (position >= sp.WriteBufferSize - bufferSize)
                        {
                            Console.WriteLine("data[{0:x}] = {1:x}", position, data[position]);
                        }
                        sp.Write(data, position, bufferSize);
                        position += bufferSize;
                    }
                    positions.Add(position);
                    if (data.Length - position > 0)
                    {
                        sp.Write(data, position, data.Length - position);
                    }

                    sp.Flush();

                    byte[] receiveData = ReceiveData(spReceive, size);
                    Assert.That(Compare(data, receiveData), Is.True);

                    sp.Close();
                    spReceive.Close();
                }
        }
 protected bool SendColorsToDevice(byte[] colors, bool forced)
 {
     try
     {
         byte[] packet = new byte[header.Length + colors.Length];
         Array.Copy(header, packet, header.Length);
         Array.Copy(colors, 0, packet, header.Length, colors.Length);
         byte[] ackBuffer = new byte[MAGIC.Length];
         lock (port)
         {
             port.Write(packet, 0, packet.Length);
             port.Flush();
             port.Read(ackBuffer, 0, ackBuffer.Length);
         }
         watch.Stop();
         Interlocked.Exchange(ref lastUpdateTime, watch.ElapsedMilliseconds);
         return(ackBuffer.SequenceEqual(MAGIC));
     }
     catch (Exception ex)
     {
         Crash(ex, "SendColorsToDevice");
         return(false);
     }
 }
Esempio n. 14
0
        protected override void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    if(Connected && IsScanning)
                    {
                        // make sure we're in a halfway known state...
                        StopScan();
                    }

                    if(serialPort.IsOpen)
                        serialPort.Flush();

                    if(!serialPort.IsDisposed)
                        serialPort.Dispose();
                }

                disposedValue = true;
            }

            base.Dispose(disposing);
        }
        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_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()");
            }
        }
Esempio n. 17
0
 public void Flush()
 {
     SerialPort.Flush();
 }
Esempio n. 18
0
        static void Main(string[] args)
        {
            Console.WriteLine("Select port name from available port list:");
            foreach (string c in SerialPortStream.GetPortNames())
            {
                Console.WriteLine(c);
            }
            Console.WriteLine("///////////////////");
            string           portName = Console.ReadLine();
            SerialPortStream myPort   = null;
            string           db_cfg   = "";

            myPort = new SerialPortStream(portName, 9600, 8, Parity.None, StopBits.One);
            myPort.WriteTimeout = 100;
            myPort.ReadTimeout  = 100;
            myPort.Open();
            Console.WriteLine("///////////////////");
            if (!myPort.IsOpen)
            {
                Console.WriteLine("Error opening serial port");
                return;
            }
            Console.WriteLine("Port open");
            if (!File.Exists("db.cfg"))
            {
                Console.WriteLine("Config file not found");
                File.WriteAllText("db.cfg", "Server=localhost;Database=Diplom;User Id=root;password=4326");
            }
            else
            {
                db_cfg = File.ReadAllText("db.cfg");
                Console.WriteLine("Настройки подключения загружены");
            }
            while (!Console.KeyAvailable)
            {
                string buff = "";
                try
                {
                    buff = myPort.ReadLine();
                }catch { System.Threading.Thread.Sleep(30); };
                if (buff != "")
                {
                    if (buff.Length > 3 && buff.Contains("req: "))
                    {
                        buff = buff.Replace(" ", "");
                        if (buff.Length > 40)
                        {
                            continue;
                        }
                        buff = buff.Substring(4, buff.Length - 4 - 1);
                        string[] arg = buff.Split(';');
                        Console.WriteLine("request FROM: " + arg[0] + ", Identificator: " + arg[1]);
                        MySqlConnection connection = new MySqlConnection(db_cfg);
                        connection.Open();
                        string sql = "SELECT get_access('" + arg[1] + "','" + arg[0] + "') AS ACCESS;";
                        Console.WriteLine(sql);
                        MySqlCommand cmd = new MySqlCommand();
                        cmd.Connection  = connection;
                        cmd.CommandText = sql;
                        string       ans    = "";
                        DbDataReader reader = cmd.ExecuteReader();
                        if (reader.HasRows)
                        {
                            while (reader.Read())
                            {
                                ans = reader.GetString(reader.GetOrdinal("ACCESS"));
                            }
                        }
                        connection.Close();
                        try
                        {
                            while (!myPort.CanWrite)
                            {
                            }
                            string a = "Denied";
                            if (ans == "1")
                            {
                                a = "Allowed";
                            }
                            Console.WriteLine("ACCESS: " + a);
                            Console.WriteLine("ans:" + arg[0] + ";" + a + "\r\n");
                            myPort.Write("ans:" + arg[0] + ";" + a + "\r\n");
                            System.Threading.Thread.Sleep(10);
                            myPort.Flush();
                        }catch { Console.WriteLine(buff.Substring(0, buff.Length - 2) + " args[0]: " + arg[0] + " args[1]: " + arg[1]); };
                        buff = string.Empty;
                    }
                    else
                    {
                        buff = string.Empty;
                    }
                }
            }
            myPort.Close();
        }
Esempio n. 19
0
 private void WriteNewLine()
 {
     logger.LogInformation("PORT.NewLine");
     Write('\r'.ToString());
     port.Flush();
 }
Esempio n. 20
0
 private void Send(byte[] cmd)
 {
     _stream.Write(cmd, 0, cmd.Length);
     _stream.Flush();
 }
Esempio n. 21
0
 public void Send(string cmd)
 {
     _stream.Write(cmd + "\r");
     _stream.Flush();
 }