Exemple #1
0
        static public List <List <double> > poll_for_data(SerialPortStream port, string user_input = "0")
        {
            // Send Command to Start, send it desired speed to run at
            port.Write("<1>");
            bool quick_three = true;

            while (quick_three)
            {
                if (port.BytesToRead > 0)
                {
                    string s = port.ReadLine();
                    s = Regex.Replace(s, @"\r", string.Empty);

                    // Either prompt user for input, or take in function line arugment for a desired RPM to run at
                    if (s == "give")
                    {
                        port.WriteLine(user_input);

                        quick_three = false;
                        break;
                    }
                }
            }
            bool stop = true;

            Console.WriteLine("Test Started");


            //Collect data with this loop
            List <double>         temp = new List <double>();
            List <List <double> > data = new List <List <double> >();

            while (stop)
            {
                if (port.BytesToRead > 0)
                {
                    string s = port.ReadLine();
                    s = Regex.Replace(s, @"\r", string.Empty);
                    if (s == "end")
                    {
                        stop = false;
                        break;
                    }
                    string[] message = s.Split(',');

                    //temp.Add(Convert.ToDouble(s));
                    foreach (string element in message)
                    {
                        //Console.WriteLine(element);

                        double value = Convert.ToDouble(element);
                        temp.Add(value);
                        Console.WriteLine(element);
                    }
                    data.Add(temp);
                }
            }

            return(data);
        }
Exemple #2
0
        public string ReadLineBlocking()          //la lettura della com è bloccante per natura
        {
            if (com != null)
            {
                System.Threading.Thread.Sleep(100000);
                return(null);

                if (ComLogger.Enabled)
                {
                    System.Threading.Thread.Sleep(100000);
                    string rv = com.ReadLine();
                    ComLogger.Log("rx", rv);
                    return(rv);
                }
                else
                {
                    System.Threading.Thread.Sleep(100000);
                    return(com.ReadLine());
                }
            }
            else
            {
                throw new System.IO.IOException("Cannot read from COM port, port is closed!");
            }
        }
        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 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'));
                }
        }
        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 #7
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 #8
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 #9
0
        public void CanWrite()
        {
            EnsureConnected();
            extension.CallArgs(theirPort, "write", "Hello, World!\n");
            ourPort.ReadTimeout = 1000;
            var line = ourPort.ReadLine();

            Assert.AreEqual("Hello, World!", line);
        }
        public void WriteLineReadLineMultilines()
        {
            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);

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

                    Assert.Throws <TimeoutException>(() => { s = dst.ReadLine(); }, "No timeout exception occurred");
                }
        }
        public void WriteLineReadLine()
        {
            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);

                    string s;
                    src.WriteLine("TestString");
                    s = dst.ReadLine();
                    Assert.That(s, Is.EqualTo("TestString"));
                }
        }
        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 ReadToResetWithMbcs3()
        {
            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);

                    src.Write(new byte[] { 0xE2, 0x82, 0xAC, 0x40, 0x41, 0x62 }, 0, 6);
                    Assert.That(() => { dst.ReadLine(); }, Throws.Exception.TypeOf <TimeoutException>());

                    Assert.That(dst.ReadChar(), Is.EqualTo((int)'€'));
                    Assert.That(dst.ReadByte(), Is.EqualTo(0x40));
                    Assert.That(dst.ReadExisting(), Is.EqualTo("Ab"));
                }
        }
        public void ReadToResetWithMbcs2()
        {
            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);

                    src.Write(new byte[] { 0xE2, 0x82, 0xAC, 0x40, 0x41, 0x62 }, 0, 6);
                    Assert.That(() => { dst.ReadLine(); }, Throws.Exception.TypeOf <TimeoutException>());

                    // So now we should have data in the character cache, but we'll ready a byte.
                    Assert.That(dst.ReadByte(), Is.EqualTo(0xE2));
                    Assert.That(dst.ReadExisting(), Is.EqualTo("��@Ab"));
                }
        }
Exemple #15
0
        static void Main(string[] args)
        {
            SerialPortStream arduinoPort = null;

            Console.WriteLine("Hola Proyecto Final IOT");
            Console.WriteLine(Environment.Version.ToString());
            //string[] ports = GetPortNames();
            // We know that ttyACM0 is the port to read from and copied the same read config from node-red arduino config :)
            arduinoPort = new SerialPortStream("/dev/ttyACM0", 9600, 8, Parity.None, StopBits.One);
            arduinoPort.Open();
            if (!arduinoPort.IsOpen)
            {
                Console.WriteLine("Error opening serial port");
                return;
            }
            Console.WriteLine("Port open");
            arduinoPort.Handshake   = Handshake.None;
            arduinoPort.ReadTimeout = 10000;
            arduinoPort.NewLine     = "\r\n";

            while (!Console.KeyAvailable)
            {
                try
                {
                    string retrievedLine = arduinoPort.ReadLine();

                    var lineParts = retrievedLine.Split(',');

                    var parkingId = lineParts[0];
                    var isUsed    = (YesNo)Enum.Parse(typeof(YesNo), lineParts[1]);

                    var httpClient = new HttpClient();

                    var response = httpClient.GetAsync($"https://us-central1-iot-isil.cloudfunctions.net/startService?parkingId={parkingId}&isUsed={isUsed}")
                                   .Result;

                    var result = JsonConvert.DeserializeObject <ServiceResponse>(response.Content.ReadAsStringAsync().Result);

                    Console.WriteLine(retrievedLine);
                }
                catch (Exception ex)
                {
                    Console.WriteLine($" :( Error: {ex.Message}");
                }
            }
        }
Exemple #16
0
        public void Begin_Test(CommandPacket commands, SerialPortStream port)
        {
            port.Write("<" + commands.RunTest + "," + commands.DisplacementRate + "," + commands.Displacement + "," + commands.Retract + ">");

            bool test_in_progress = true;

            while (test_in_progress)
            {
                if (port.BytesToRead > 0)
                {
                    string s = port.ReadLine();
                    s = Regex.Replace(s, @"\r", string.Empty);
                    if (s == "done")
                    {
                        test_in_progress = false;
                        break;
                    }
                    string[] message = s.Split(',');
                    if (message.Length > 1)
                    {
                        string displacement  = message[0];
                        string load_str      = message[2];
                        string load_time_str = message[3];
                        append_distance_box(displacement);
                        double load = Convert.ToDouble(load_str);
                        //load = ((load - 0) * (105.369 - 40.92)) / ((1023 - 0) + 40.92);
                        append_loadcell_box(load.ToString());

                        append_live_chart(load, Convert.ToDouble(load_time_str), Convert.ToDouble(displacement) / 1024, Convert.ToDouble(message[1]));


                        List <double> temp = new List <double>();
                        foreach (string element in message)
                        {
                            double value = Convert.ToDouble(element);
                            temp.Add(value);
                        }
                        data.Add(temp);
                    }
                }
            }


            MessageBox.Show("Test Finished, Data ready to save", "Mechanica", MessageBoxButton.OK, MessageBoxImage.Information);
        }
        public void DisconnectOnReadLineBlocked()
        {
            using (SerialPortStream serialSource = new SerialPortStream(SourcePort, 115200, 8, Parity.None, StopBits.One)) {
                serialSource.Open();

                Assert.That(
                    () => {
                    string l = serialSource.ReadLine();
                    Console.WriteLine("line read length={0} ({1})",
                                      l == null ? -1 : l.Length,
                                      l ?? string.Empty);
                }, Throws.InstanceOf <System.IO.IOException>());

                // Device should still be open.
                Assert.That(serialSource.IsOpen, Is.True);
                serialSource.Close();
            }
        }
        private void ReadStreamListener()
        {
            _serialPort.Flush();
            while (IsSerialPortAvailable())
            {
                try
                {
                    var line = _serialPort.ReadLine();
                    _resp.FeedMessage(line);
#if DEBUG
                    _conversationLogger.ReceivedBySerial(line);
#endif
                }
                catch (Exception)
                {
                }
            }
        }
Exemple #19
0
        public void SerialPortRead()
        {
            while (_continue)
            {
                if (_serialPort.IsOpen)
                {
                    try
                    {
                        string message = _serialPort.ReadLine();

                        if (OnDataReceived != null)
                        {
                            OnDataReceived(message);
                        }
                    }
                    catch (TimeoutException) { }
                }
            }
        }
Exemple #20
0
        private void ReadFromPort()
        {
            try
            {
                _stream = new SerialPortStream(_request.PortNumber, _request.BaudRate, 8, Parity.None, StopBits.One);
                _stream.Open();

                try
                {
                    while (true)
                    {
                        var data = _stream.ReadLine();

                        if (!IsValid(data))
                        {
                            _logService.Log(LogEventLevel.Information, "Dato invalido");
                            continue;
                        }


                        _logService.Log(LogEventLevel.Information, "data: {data}", data);

                        var reading = _dataParser.GetReading(data);

                        DataReceived?.Invoke(this, reading);

                        _wdaqFileService.WriteToFile(reading, _currentFile);
                    }
                }
                catch (Exception exception)
                {
                    _logService.Log(exception, LogEventLevel.Fatal, "Ha occurrido un error");
                }
            }
            catch (Exception e)
            {
                _logService.Log(e, LogEventLevel.Fatal, "Ha occurrido un error");
            }
            finally
            {
                _stream?.Dispose();
            }
        }
Exemple #21
0
        public void Begin_Zero(CommandPacket commands, SerialPortStream port)
        {
            port.Write("<" + commands.RunTest + "," + commands.DisplacementRate + "," + commands.Displacement + "," + commands.Retract + ">");
            bool reset_in_progress = true;

            while (reset_in_progress)
            {
                if (port.BytesToRead > 0)
                {
                    string s = port.ReadLine();
                    s = Regex.Replace(s, @"\r", string.Empty);
                    if (s == "go")
                    {
                        reset_in_progress = false;
                        break;
                    }
                }
            }

            MessageBox.Show("Retract Finished, Ready to Test", "Mechanica", MessageBoxButton.OK, MessageBoxImage.Information);
        }
        /// <summary>
        /// Read to the line db, and disgards rest of the buffer
        /// </summary>
        /// <returns></returns>
        private string ReadToDB(SerialPortStream serialPort)
        {
            string result = string.Empty;

            // get the last line
            try
            {
                result = serialPort.ReadLine();
            }
            catch (Exception exp)
            {
                logger.Error(exp, "Failed to read the result fro NTI XL2 on port {0}", portName);
                return("-999");
            }

            logger.Trace("Read \"{0}\" from NTI XL2 on port {1}", result.Trim(), portName);

            string db = "-999";

            try
            {
                int dBindex = result.IndexOf("dB");
                if (dBindex > 0)
                {
                    db = result.Substring(0, dBindex).Trim();
                }
                else
                {
                    logger.Warn("Result did not contain the word \"dB\" as expected.");
                }
            }
            catch (Exception exp)
            {
                Console.WriteLine(exp.Message);
            }
            return(db);
        }
        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);
                }
        }
Exemple #24
0
        public void Main_PortHandler(SerialPortStream port)
        {
            string serialPortName = Find_Port_Name();

            port.PortName = serialPortName;
            port.BaudRate = 250000;
            port.Open();
            bool connecting = true;

            while (connecting)
            {
                if (port.BytesToRead > 0)
                {
                    string s = port.ReadLine();
                    s = Regex.Replace(s, @"\r", string.Empty);
                    if (s == "ready")
                    {
                        connecting = false;
                        append_connect_box("Connected!");
                        break;
                    }
                }
            }
        }
        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_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_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);
            }
        }
Exemple #29
0
        static async Task Main(string[] args)
        {
            var port = new SerialPortStream(Credential.SerialPortDeviceName, 115200);

            port.NewLine  = "\r\n";
            port.Encoding = Encoding.ASCII;
            port.Open();

            {
                port.WriteLine("SKVER");
                Console.WriteLine(port.ReadLine());
                Console.WriteLine(port.ReadLine());

                port.WriteLine("SKINFO");
                Console.WriteLine(port.ReadLine());
                Console.WriteLine(port.ReadLine());
                Console.WriteLine(port.ReadLine());

                port.WriteLine("SKSETPWD C " + Credential.BRouteId);
                Console.WriteLine(port.ReadLine());
                Console.WriteLine(port.ReadLine());

                port.WriteLine("SKSETRBID " + Credential.BRoutePasscode);
                Console.WriteLine(port.ReadLine());
                Console.WriteLine(port.ReadLine());
            }

            var httpClient = new HttpClient();

scanretry:
            var duration = 4;
            var map = new Dictionary <string, string>();

            while (!map.ContainsKey("Channel"))
            {
                port.WriteLine("SKSCAN 2 FFFFFFFF " + duration++);

                var scanEnd = false;
                while (!scanEnd)
                {
                    var line = port.ReadLine();
                    Console.WriteLine(line);

                    if (line.StartsWith("EVENT 22"))
                    {
                        scanEnd = true;
                    }
                    else if (line.StartsWith("  "))
                    {
                        var str = line.Trim().Split(':');

                        map[str[0]] = str[1];
                    }
                }
                if (duration > 8)
                {
                    Console.WriteLine("Duration Exceeded");
                    goto scanretry;
                }
            }

            port.WriteLine("SKSREG S2 " + map["Channel"]);
            Console.WriteLine(port.ReadLine());
            Console.WriteLine(port.ReadLine());

            port.WriteLine("SKSREG S3 " + map["Pan ID"]);
            Console.WriteLine(port.ReadLine());
            Console.WriteLine(port.ReadLine());

            port.WriteLine("SKLL64 " + map["Addr"]);
            Console.WriteLine(port.ReadLine());
            var ipv6 = port.ReadLine().Trim();

            Console.WriteLine(ipv6);

            port.WriteLine("SKJOIN " + ipv6);
            Console.WriteLine(port.ReadLine());
            Console.WriteLine(port.ReadLine());

            var pana = false;

            while (!pana)
            {
                var line = port.ReadLine();
                Console.WriteLine(line);

                if (line.StartsWith("EVENT 24"))
                {
                    Console.WriteLine("失敗");
                    break;
                }
                else if (line.StartsWith("EVENT 25"))
                {
                    pana = true;
                }
            }

            port.ReadTimeout  = 2000;
            port.WriteTimeout = 2000;

            while (pana)
            {
retry:
                try {
                    var echonetFrame = "";
                    echonetFrame += "\x10\x81";
                    echonetFrame += "\x00\x01";

                    echonetFrame += "\x05\xFF\x01";
                    echonetFrame += "\x02\x88\x01";
                    echonetFrame += "\x62";
                    echonetFrame += "\x01";
                    echonetFrame += "\xE7";
                    echonetFrame += "\x00";

                    var memory = new MemoryStream();
                    var writer = new BinaryWriter(memory);

                    var tt = $"SKSENDTO 1 {ipv6} 0E1A 1 {echonetFrame.Length.ToString("X4")} ";

                    writer.Write(Encoding.ASCII.GetBytes(tt));
                    writer.Write((byte)0x10);
                    writer.Write((byte)0x81);
                    writer.Write((byte)0x00);
                    writer.Write((byte)0x01);
                    writer.Write((byte)0x05);
                    writer.Write((byte)0xFF);
                    writer.Write((byte)0x01);
                    writer.Write((byte)0x02);
                    writer.Write((byte)0x88);
                    writer.Write((byte)0x01);
                    writer.Write((byte)0x62);
                    writer.Write((byte)0x01);
                    writer.Write((byte)0xE7);
                    writer.Write((byte)0x00);

                    var b = memory.ToArray();
                    port.Write(b, 0, b.Length);

                    Console.WriteLine(port.ReadLine());
                    Console.WriteLine(port.ReadLine());
                    Console.WriteLine(port.ReadLine());

                    var erxudp = port.ReadLine();
                    Console.WriteLine(erxudp);

                    if (erxudp.StartsWith("ERXUDP"))
                    {
                        var str = erxudp.Split(' ');
                        var res = str[8];

                        var seoj = res.Substring(8, 6);
                        var esv  = res.Substring(20, 2);

                        if (seoj == "028801" && esv == "72")
                        {
                            var epc = res.Substring(24, 2);

                            if (epc == "E7")
                            {
                                var wat = int.Parse(erxudp.Substring(erxudp.Length - 8), NumberStyles.HexNumber);

                                var request = new HttpRequestMessage(HttpMethod.Post, Credential.ApiEndpoint);
                                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", Credential.BearerToken);

                                var pairs = new List <KeyValuePair <string, string> >();
                                pairs.Add(new KeyValuePair <string, string>("wat", wat.ToString()));
                                request.Content = new FormUrlEncodedContent(pairs);


                                await httpClient.SendAsync(request);

                                Console.WriteLine("瞬時電力計測値:" + wat + " W");
                            }
                        }
                    }
                } catch (TimeoutException) {
                    goto retry;
                }
            }
        }
Exemple #30
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();
        }
Exemple #31
0
        static void Main(string[] args)
        {
            Console.WriteLine("Starting Up Program");

            string serialPortName = "COM9";
            var    allPortNames   = SerialPortStream.GetPortNames();
            var    distinctPorts  = allPortNames.Distinct().ToList();

            // If we don't specify a COM port, automagically select one if there is only a single match.
            if (distinctPorts.SingleOrDefault() != null)
            {
                serialPortName = distinctPorts.Single();
            }



            SerialPortStream port = new SerialPortStream(serialPortName, 115200);

            port.Open();

            // Hold program and wait till Device is ready
            bool quick = true;

            while (quick)
            {
                if (port.BytesToRead > 0)
                {
                    string s = port.ReadLine();
                    s = Regex.Replace(s, @"\r", string.Empty);
                    Console.WriteLine("Connecting to Arduino");
                    if (s == "ready")
                    {
                        quick = false;
                        Console.WriteLine("Device Ready");
                        break;
                    }
                }
            }

            // Start Test
            Console.WriteLine("Input Desired RPM: ");
            string user_input      = Console.ReadLine();
            double temp_user_input = Convert.ToDouble(user_input);

            user_input = ((temp_user_input * 200) / 60).ToString();
            List <List <double> > data = new List <List <double> >();

            data = poll_for_data(port, user_input);

            // After test is over write it to file
            Console.WriteLine("File Name: ");
            string file_name = Console.ReadLine();

            using (TextWriter tw = new StreamWriter(file_name + ".csv"))
            {
                foreach (List <double> member in data)
                {
                    //tw.Write(member);

                    foreach (double guy in member)
                    {
                        tw.Write(guy);
                        tw.Write(",");
                    }
                    tw.WriteLine();
                }
            }
            Console.WriteLine("Wrote to file");
        }