ReadLine() публичный Метод

public ReadLine ( ) : string
Результат string
Пример #1
0
        public bool ParseResponse(SerialPort serialPort)
        {
            try
            {
                StringBuilder sb = new StringBuilder(capacity: 50000);

                var s = serialPort.ReadLine();

                while (true)
                {
                    s = serialPort.ReadLine().Trim();

                    if (string.IsNullOrEmpty(s))
                        continue;

                    if (s == "OK") break;

                    sb.Append(s);
                }

                string bigStr = sb.ToString();

                SnapshotImage = MakeBitmap(bigStr);

                return true;
            }
            catch (Exception ex) { MessageBox.Show(ex.Message); return false; }
        }
Пример #2
0
        public bool ParseResponse(SerialPort serialPort)
        {
            try
            {
                // Dummy read of command;
                serialPort.ReadLine();

                var resp = serialPort.ReadLine().Trim();

                Regex regex = new Regex(@"time=""(.*)"",P=""([0-9A-Fa-f]*)"",H=""([0-9A-Fa-f]*)"",T1=""([0-9A-Fa-f]*)""");

                var match = regex.Match(resp);

                // Empty line
                serialPort.ReadLine();

                var ack = serialPort.ReadLine().Trim();

                Time = match.Groups[1].Value;
                Pressure = int.Parse(match.Groups[2].Value, NumberStyles.AllowHexSpecifier);
                Humidity = int.Parse(match.Groups[3].Value, NumberStyles.AllowHexSpecifier);
                Temperature = int.Parse(match.Groups[4].Value, NumberStyles.AllowHexSpecifier);

                return ack.Equals("OK");
            }
            catch (Exception)
            {
                return false;
            }
        }
Пример #3
0
        private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {        // Event for receiving data
            // should we loop to get all data or just work line to line..
            // we could catch the read timeout exception and carry on as normal...
            try
            {
                if (m_blnSocketOpen)
                {
                    // Read the buffer to text box.
                    string newLine = m_spGPS.ReadLine();
                    //string newLine = m_spGPS.ReadExisting();
                    m_gpsDataParser.ParseNMEASentence(newLine);

                    if (LoggingNMEAMessages())
                    {
                        m_swLogFile.WriteLine(newLine);
                        m_swLogFile.Flush();
                    }
                }
                //GPSCoordinateChange(this,new EventArgs());
                // need to raise a event to signify that data has been received..
            }
            catch (Exception ex)
            {
                RaiseExceptionEvent("Error Occured In port_DataReceived(...)", ex);
            }
        }
Пример #4
0
        public static bool connectDisplay(SerialPort serial)
        {
            if (serial == null || !serial.IsOpen)
            {
                throw new Exception(StringResource.E00001);
            }

            string accessString = "";
            try
            {
                accessString = serial.ReadLine();
            }
            catch (Exception)
            {
                //if Display is idle. Try to close it and reconnect
                serial.WriteLine("close:");

                try
                {
                    accessString = serial.ReadLine();
                }
                catch (TimeoutException)
                {
                    return false;
                }
            }

            if (accessString == DisplayToAppAccessString)
            {

                serial.WriteLine(AppToDisplayAccessString);
                return true;
            }
            return false;
        }
Пример #5
0
        /// <summary>
        /// 温度采集
        /// </summary>
        /// <returns></returns>
        public string GetTempreture()
        {
            //sensorPort.DataReceived += sensorPort_DataReceived;
            Execute(CMD_TP);

            // 读取温度
            string temp = sensorPort.ReadLine();

            return(temp);//"TP";
        }
Пример #6
0
        void acquire()
        {
            if(port!=null)
                port.Dispose();
            port = new SerialPort("COM4", 9600);
            port.Open();
            DateTime refreshTimer = DateTime.Now;
            while (!closeThread)
            {
                try
                {
                    while (port.BytesToRead > 0 && !closeThread)
                    {
                        port.ReadLine();
                        string data = port.ReadLine();

                        DateTime newTime = DateTime.Now;

                        if (newTime.Subtract(refreshTimer).Milliseconds > 30)
                        {
                            data = data.Substring(7);
                            string[] vals = data.Split(new char[] { ' ' });
                            double[] dvals = new double[vals.Length];
                            double total = 0;
                            for (int i = 0; i < dvals.Length; i++)
                            {
                                dvals[i] = double.Parse(vals[i].Trim());
                                total += dvals[i];
                            }

                            if (setScalingValues)
                            {
                                scalingValues = new double[dvals.Length];
                                for (int i = 0; i < scalingValues.Length; i++)
                                    scalingValues[i] = 255/dvals[i];
                                setScalingValues = false;
                            }

                            double avg = total / dvals.Length;

                            refreshTimer = newTime;

                            AddPoint(avg);
                            RefreshForm(dvals);
                            port.DiscardInBuffer();
                        }
                    }
                }
                catch (Exception) { }
                Thread.Sleep(10);
            }
            closeThread = false;
        }
Пример #7
0
        static string Call(string port_name)
        {
            try
            {
                Serial = new SerialPort(port_name, 38400, System.IO.Ports.Parity.None, 8, StopBits.One);

                Serial.Open();
                Thread.Sleep(10);

                Serial.WriteLine("0");
                Serial.ReadTimeout = 1000;
            }
            catch {
            }
            try
            {
                string ans = Serial.ReadLine();
                Serial.Close();
                ans = ans.Trim();
                return(ans);
            }
            catch
            {
                return("0");
            }
        }
        public double ReadData()
        {
            double Output = 0;

            try
            {
                SerialPortLaser.Open();
                SerialPortLaser.WriteLine("F");
                string input = SerialPortLaser.ReadLine();
                int    index = input.IndexOf("m");
                if (index > 0)
                {
                    input = input.Substring(0, index);
                }

                index  = input.LastIndexOf(":") + 2;
                input  = (input.Substring(index, input.Length - index));
                input  = input.Replace(".", ",");
                Output = Double.Parse(input);
            }
            catch (Exception ex)
            {
                //Ignore
            }
            SerialPortLaser.Close();
            return(Output);
        }
Пример #9
0
        private void button3_Click(object sender, EventArgs e)
        {
            // Define Serial Port
            //string COM = inputCOM.Text;
            string COM = comboBoxStagePorts.Text;

            System.IO.Ports.SerialPort stage = new System.IO.Ports.SerialPort(COM, 115200, System.IO.Ports.Parity.None, 8, System.IO.Ports.StopBits.One);

            // Open Serial Port
            try
            {
                stage.Open();
            }
            catch (Exception err)
            {
                LogLine("Open failed " + err.Message);
                return;
            }
            // Request XY-position
            string xy_request = "1HW Z\r";

            stage.Write(xy_request);

            // Read XY-position
            string msg = stage.ReadLine();

            MessageBox.Show(msg);

            // Close Serial Port
            stage.Close();
        }
Пример #10
0
        private void _serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            //0;0;3;0;14;Gateway startup complete
            string indata = _serialPort.ReadLine();

            if (indata.StartsWith("0;0;3;0;14;"))
            {
                _gatewayReady = true;
            }

            Task.Factory.StartNew(() =>
            {
                var parsedMessage = MessageFactory.ConstructMessageFromRaw(indata);

                Console.WriteLine("Receive Message from {0} Type {1} SubType {2}", parsedMessage.NodeId == 0 ? "Gateway" : parsedMessage.NodeId.ToString(), parsedMessage.GetType().Name, parsedMessage.SubType);
                var messageProcessor = MessageProcessorFactory.CreateMessageProcessor(parsedMessage);
                if (messageProcessor != null)
                {
                    string responseMessageString = null;
                    var raiseEvent = messageProcessor.ProcessIncomingMessage(parsedMessage, out responseMessageString);
                    if (!string.IsNullOrEmpty(responseMessageString))
                    {
                        _serialPort.Write(responseMessageString);
                    }
                    if (raiseEvent && OnReceiveMessageFromSensors != null)
                    {
                        OnReceiveMessageFromSensors(parsedMessage);
                    }
                }
            });
        }
Пример #11
0
        public SPICommunicator()
        {
            port = new SerialPort() {
                BaudRate = 115200,
                DataBits = 8,
                StopBits = StopBits.One,
                Parity = Parity.None,
                PortName = "COM3",
                Handshake = Handshake.None
            };

            if (!port.IsOpen) {
                port.Open();
            }

            string line = "TEST";
            int i = 0;
            do {
                port.Write(line);
                string inLine = port.ReadLine();
                i++;
            } while (i < 3);

            port.Close();
        }
Пример #12
0
        static void Main(string[] args)
        {
            try
            {
                Serfid appSerfid = new Serfid();
                appSerfid.Run();

                _serfidPort = new SerialPort("COM3");
                _serfidPort.Open();

                System.Console.WriteLine("Serfid reading on port: COM3");
                while (true)
                {
                    System.Console.WriteLine("\nWaiting for readings...");
                    string reading = _serfidPort.ReadLine();
                    appSerfid.ReadWeft(reading);

                    System.Console.SetCursorPosition(0, System.Console.CursorTop - 1);
                    string result = string.Format("Tag {0} processed successful", reading.Replace("\r", ""));
                    System.Console.WriteLine(result);
                }
            }
            finally
            {
                _serfidPort.Close();
            }
        }
Пример #13
0
        private void Reading()
        {
            var currentPort = new SerialPort(_name, 115200);
            currentPort.Open();
            while (!stop)
            {
                var line = currentPort.ReadLine();
                try
                {
                    var strings = line.Replace("\r", "").Split(',');
                    var x = (int)int.Parse(strings[0]) / 16384.0F;
                    var y = (int)int.Parse(strings[1]) / 16384.0F;
                    var z = (int)int.Parse(strings[2]) / 16384.0F;
                    if (!_valuesInitialized)
                    {
                        _x = x;
                        _y = y;
                        _z = z;
                        _valuesInitialized = true;
                    }

                    _x = (_x*3 + x)/4;
                    _y = (_y*3 + y)/4;
                    _z = (_z*3 + z)/4;
                }
                catch (Exception)
                {

                }

                HasNew = true;
            }
        }
Пример #14
0
        public static void Main(string[] args)
        {
            activeConfig = new SerialMonitorConfig ("Serial.conf",args);

            //assign time outs to all network commands
            foreach (int  i in activeConfig.networkCommands.Keys) {
                timeouts.Add (i, DateTime.Now);
            }

            stamp ();

            SerialPort serialPort = new SerialPort ();
            serialPort.BaudRate = activeConfig.baudrate;
            serialPort.PortName = activeConfig.portname;
            //serialPort.Parity = activeConfig.Parity;
            serialPort.ReadTimeout = activeConfig.readtimeout;
            serialPort.WriteTimeout = activeConfig.writetimeout;

            serialPort.Open ();
            string message;
            while (true) {
                try{
                    message= serialPort.ReadLine ();

                    int cmd = 0;
                    if(int.TryParse(message, out cmd)){
                        readCommand(cmd);
                    }

                }
                catch(Exception ex){
                    //
                }
            }
        }
Пример #15
0
        private void SerialPort_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            if (state == "S0")
            {
                setFrame("F0");
            }
            else
            {
                // Check connected or disconnected
                if (serialPort == null)
                {
                    return;
                }
                if (serialPort.IsOpen == false)
                {
                    return;
                }
                receiveText.Dispatcher.Invoke(
                    new Action(() =>
                {
                    receiveText.Clear();
                })
                    );

                // Show in the textbox
                try
                {
                    receiveText.Dispatcher.Invoke(
                        new Action(() =>
                    {
                        while (serialPort.BytesToRead > 0)
                        {
                            string inbound = serialPort.ReadLine();
                            //MessageBox.Show(inbound);
                            receiveText.Text += inbound;
                        }
                        if (state == "S0" || state == "S5")
                        {
                            receiveText.Clear();
                        }
                        else if (receiveText.Text.Contains("(") && receiveText.Text.Contains(")"))
                        {
                            processReadings(receiveText.Text.Trim());
                        }
                    })

                        );
                }
                catch
                {
                    receiveText.Dispatcher.Invoke(
                        new Action(() =>
                    {
                        receiveText.Text = "!Error! cannot connect to " + serialPort.PortName;
                    })
                        );
                }
                serialPort.DiscardInBuffer();
            }
        }
        static void Main(string[] args)
        {
            String RxedData;                         // String to store received data
                String COM_PortName;                     // String to store the name of the serial port
                SerialPort MyCOMPort = new SerialPort(); // Create a new SerialPort Object

                Console.WriteLine("\t+------------------------------------------+");
                Console.WriteLine("\t|    Reading from Serial Port using C#     |");
                Console.WriteLine("\t+------------------------------------------+");
                Console.WriteLine("\t|          (c) www.xanthium.in             |");
                Console.WriteLine("\t+------------------------------------------+");
                Console.Write("\n\t  Enter the COM port [eg COM32] -> ");
                COM_PortName = Console.ReadLine();

                COM_PortName = COM_PortName.Trim();     // Remove any extra spaces
                COM_PortName = COM_PortName.ToUpper();  // convert the string to upper case

                //------------ COM port settings to 8N1 mode ------------------//

                MyCOMPort.PortName = COM_PortName;       // Name of the COM port
                MyCOMPort.BaudRate = 9600;               // Baudrate = 9600bps
                MyCOMPort.Parity   = Parity.None;        // Parity bits = none
                MyCOMPort.DataBits = 8;                  // No of Data bits = 8
                MyCOMPort.StopBits = StopBits.One;       // No of Stop bits = 1

                MyCOMPort.Open();                                 // Open the port
                Console.WriteLine("\n\t  Waiting for Data....");
                RxedData = MyCOMPort.ReadLine();                  // Wait for data reception
                Console.WriteLine("\n\t  \" {0} \"",RxedData);    // Write the data to console
                Console.WriteLine("\n\t  Press any Key to Exit");
                Console.Read();                                   // Press any key to exit

                MyCOMPort.Close();                       // Close port
        }
Пример #17
0
        private void tmrData_Tick(object sender, EventArgs e)
        {
            string port = cbxPorts.SelectedItem.ToString();

            if (port == "")
            {
                return;
            }
            System.IO.Ports.SerialPort myPort = new System.IO.Ports.SerialPort(port);
            myPort.BaudRate = 9600;
            if (myPort.IsOpen == false) //if not open, open the port
            {
                myPort.Open();
            }
            //do your work here
            if (myPort.IsOpen == false) //if not open, open the port
            {
                return;
            }
            String data;

            //data = myPort.ReadExisting();
            data = myPort.ReadLine();
            myPort.Close();
            //tmrData.Enabled = true;
        }
        public static void Main()
        {
            string ttyname = "";         // for storing name of the serial port
            string ReceivedData = "";    // for storing received data from microcontroller

            SerialPort Serial_tty = new SerialPort(); //Create a new serialPort object

            Console.Write("\nEnter Your SerialPort[tty] name (eg ttyUSB0)->");
            ttyname = Console.ReadLine();             // Read the name of the port eg ttyUSB0
            ttyname = @"/dev/" + ttyname;             // Concatanate so name looks like /dev/ttyUSB0

            Serial_tty.PortName = ttyname;            // assign the port name
            Serial_tty.BaudRate = 9600;               // Baudrate = 9600bps
            Serial_tty.Parity   = Parity.None;        // Parity bits = none
            Serial_tty.DataBits = 8;                  // No of Data bits = 8
            Serial_tty.StopBits = StopBits.One;       // No of Stop bits = 1

            try
            {
                Serial_tty.Open();                             //open the port
                Console.WriteLine("\nWaiting for Data......");
                ReceivedData = Serial_tty.ReadLine();     // Read the data send from microcontroller
                Serial_tty.Close();                       // Close port
                Console.WriteLine("\n{0} received\n", ReceivedData);
            }
            catch
            {
                Console.WriteLine("Error in Opening {0}\n",Serial_tty.PortName);
            }
        }
Пример #19
0
        static void Main(string[] args)
        {
            ////////////// KONSOL AYARLARI ///////////////////////////////////
            Console.SetWindowSize(70, 30);
            Console.BackgroundColor = ConsoleColor.DarkBlue;
            Console.ForegroundColor = ConsoleColor.White;
            Console.Clear();
            /////////////////////////////////////////////////////////////////

            /////////////////////////////////////////////////////////////////
            SerialPort myport = new SerialPort();
            myport.BaudRate = 9600;
            myport.PortName = "COM3";
            myport.Open();
            /////////////////////////////////////////////////////////////////

            /////////////////////////////////////////////////////////////////
            bool devametsinmi = true;
            while (devametsinmi && true)
            {
                string data_rx = myport.ReadLine();
                Console.WriteLine(data_rx);
            }
            /////////////////////////////////////////////////////////////////
        }
Пример #20
0
 private void ThreadedColorCopy(object threadParamsVar)
 {
     if (port != null)
     {
         string tmp = port.ReadLine();
         int.TryParse(tmp, out score);
     }
 }
Пример #21
0
        private static decimal ParseReceivedLine(SerialPort port)
        {
            string line = port.ReadLine();
            var match = Regex.Match(line, @"^(\d+\.\d+)\s*$");
            var degrees = decimal.Parse(match.Groups[1].Value);

            return degrees;
        }
Пример #22
0
        static void Main(string[] args)
        {
            _port = new SerialPort();
            _port.PortName = "COM3";
            _port.BaudRate = 9600;

            _port.ReadTimeout = 500;
            _port.WriteTimeout = 500;

            _port.Open();

            Thread thread = new Thread(new ThreadStart(delegate()
                {
                    while (_continue)
                    {
                        try
                        {
                            string data = _port.ReadLine();
                            string[] bits = data.Replace("\r", "").Split('\t').ToArray();
                            Console.WriteLine(data);

                            if (bits.Length == 3 && bits[0].Length > 0 && bits[1].Length > 0 && bits[2].Length > 0)
                            {
                                int xOriginal = int.Parse(bits[1]);
                                int yOriginal = int.Parse(bits[2]);

                                if (Math.Abs(xOriginal) > 50 || Math.Abs(yOriginal) > 50)
                                {
                                    Cursor.Position = new System.Drawing.Point
                                    {
                                        X = Cursor.Position.X + -1 * xOriginal / 10,
                                        Y = Cursor.Position.Y + yOriginal / 10
                                    };
                                }

                                if (bits[0] == "1" && !_inClick)
                                {
                                    _inClick = true;
                                    mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, (uint)Cursor.Position.X, (uint)Cursor.Position.Y, 0, 0);
                                }
                                else if (bits[0] == "0")
                                {
                                    _inClick = false;
                                }
                            }
                        }
                        catch (TimeoutException) { }
                    }
                }));
            thread.Start();

            Console.WriteLine("Hit ENTER to quit.");
            Console.ReadLine();

            _continue = false;
            thread.Join();
        }
Пример #23
0
 // Select the CC1101 chip's SPI
 public static bool SelectRf(SerialPort sp)
 {
     sp.Write("{c00}");
     string result = sp.ReadLine();
     if (result == "c1")
     {
         return true;
     }
     return false;
 }
Пример #24
0
        public String Receber(int i)
        {
            if (i == -1)
            {
                return(serialPort.ReadLine());
            }

            if (Historico.Count > 300)
            {
                Historico.RemoveAt(0);
            }

            Historico.Add(serialPort.ReadLine());

            String dt = serialPort.ReadLine();

            String[] dts = dt.Split('/');
            return(dts[i]);
        }
Пример #25
0
        private static void DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            string Incoming = ComPort.ReadLine();

            if (Incoming != String.Empty)
            {
                Incoming = "i";
            }
            //Data.MoniteurSerieText = Incoming;
        }
Пример #26
0
 // Delays the MCU for a time between 0-255 ms
 public static bool Delay(SerialPort sp, byte delayTime)
 {
     sp.Write("{b" + StringifyByteWithPadding(delayTime) + "}");
     string result = sp.ReadLine();
     if (result == "b1")
     {
         return true;
     }
     return false;
 }
Пример #27
0
 // Gets the uart->spi bridge's signature (MSP430 etc)
 public static string GetBridgeSignature(SerialPort sp)
 {
     //sp.Write("{g00}");
     sp.Write("{");
     sp.Write("g");
     sp.Write("0");
     sp.Write("0");
     sp.Write("}");
     return sp.ReadLine();
 }
 public string Check()
 {
     portName = GetPortName();
     port = new SerialPort(portName);
     port.Open();
     port.Write("pi");
     string response = port.ReadLine();
     port.Close();
     return response;
 }
        static void Main(string[] args)
        {
            // open serial port communications with your arduino board
            // you may need to change COM3 to some other port number
            // check in device manager to see which port is used by arduino
            SerialPort serialPort = new SerialPort("COM3", 9600, Parity.None, 8, StopBits.One);

            serialPort.Open();

            while(true)
            {
                string message = null;

                try
                {
                    // receive a line of text from arduino
                    message = serialPort.ReadLine();

                    // remove newline used to separate messages coming from arduino
                    message = message.Trim();

                    if (string.IsNullOrWhiteSpace(message) == false)
                    {
                        // message should be something like: light|28|power|651|temperature|22
                        // we split it here in six parts separated by the | character
                        string[] parts = message.Split('|');

                        if (parts.Length == 6)
                        {
                            // part integer readings for light, power and temperature
                            int lightValue = int.Parse(parts[1]);
                            int powerValue = int.Parse(parts[3]);
                            int tempValue = int.Parse(parts[5]);

                            // url that we need to call to pass our readings to open energy
                            string eneryMonitorUrl = "http://emoncms.org/input/post.json?json={light:" + lightValue + ",power:" + powerValue + ",temperature:" + tempValue + "}&apikey=" + kOpenEnergyMonitorApiKey;

                            // we do an HTTP GET to open energy monitor
                            WebClient webClient = new WebClient();
                            string energyMonitorResponse = webClient.DownloadString(new Uri(eneryMonitorUrl));

                            Console.WriteLine("arduino says: " + message);
                            Console.WriteLine("we call: " + eneryMonitorUrl);
                            Console.WriteLine("energy monitor responds: " + energyMonitorResponse);
                            Console.WriteLine(Environment.NewLine);
                        }
                    }
                }

                catch (Exception exception)
                {
                    Console.WriteLine("An error occoured, message received: '" + message + "', exception: " + exception);
                }
            }
        }
Пример #30
0
        public bool ParseResponse(SerialPort serialPort)
        {
            try
            {
                // Dummy read of command;

                serialPort.ReadLine();
                DeviceVersion = serialPort.ReadLine().Trim();

                // Empty line
                serialPort.ReadLine();

                var ack = serialPort.ReadLine().Trim();
                return ack.Equals("OK");
            }
            catch (Exception)
            {
                return false;
            }
        }
Пример #31
0
 public void captureMovement() {
     while (true)
     {
         port = new SerialPort("COM3", 9600);
         port.Open();
         String s = port.ReadLine();
         Thread.Sleep(1200);
         imgCapture.Image = imgVideo.Image;
         port.Close();
     }
 }
Пример #32
0
 public bool ParseResponse(SerialPort serialPort)
 {
     try
     {
         while (true)
         {
             Writer.WriteLine(serialPort.ReadLine());
         }
     }
     catch (TimeoutException) { return true; }
     catch (Exception) { return false; }
 }
Пример #33
0
 public void Read()
 {
     while (port.IsOpen)
     {
         try
         {
             string message = port.ReadLine();
             this.SetText(message);
         }
         catch (TimeoutException) { }
     }
 }
Пример #34
0
 public void Read()
 {
     while (_continue)
     {
         try
         {
             string message = _serialPort.ReadLine();
             System.Diagnostics.Debug.WriteLine(message);
         }
         catch (TimeoutException) { }
     }
 }
Пример #35
0
 private void sport_DataReceived(object sender, SerialDataReceivedEventArgs e)
 {
     try
     {
         DateTime dt  = DateTime.Now;
         String   dtn = dt.ToLongTimeString();
         sport.NewLine = eol1;
         string RXline = sport.ReadLine();
         SetText(RXline.ToString());
     }
     catch (Exception) { }//MessageBox.Show(ex.ToString(), "Error"); }
 }
Пример #36
0
        private void UpdateAyam()
        {
            try
            {
                System.ComponentModel.IContainer components = new System.ComponentModel.Container();
                myport = new SerialPort(components);
                myport.BaudRate = 9600;
                myport.PortName = portname;
                myport.Open();

                string RXstring = myport.ReadLine();
                myport.WriteLine("5");
                ayam.suhu = RXstring + " °C";
                myport.WriteLine("6");
                RXstring = myport.ReadLine();
                ayam.kelembaban = RXstring + " %";
            }
            catch (Exception)
            {
            }
        }
Пример #37
0
        public bool Start()
        {
            bool success = false;
            SerialPort serialPort;
            try
            {
                SendCommand newCommand = new SendCommand(config);
                serialPort = new SerialPort(threadSerialPort, baudRate, Parity.None, 8, StopBits.One);
                serialPort.Open();
                while (true)
                {
                    string message = serialPort.ReadLine().Trim();
                    string[] submessage = message.Split(':');
                    switch (submessage[0])
                    {
                        case "Lock":
                            if (submessage[1]=="open")
                            {
                                newCommand.openlock();
                            }
                            if (submessage[1]=="close")
                            {
                                newCommand.closelock();

                            }
                            break;
                        case "Toilet":
                            if (submessage[1]=="in")
                            {
                                newCommand.occupy();
                            }
                            if (submessage[1]=="out")
                            {
                                newCommand.release();
                            }
                            break;
                        case "beep":
                            newCommand.beepRFID(submessage[1]);
                            break;
                        default:
                            Console.WriteLine("什麼都沒做。");
                            break;
                    }

                }
            }
            catch (Exception)
            {
                success = false;
            }
            return success;
        }
Пример #38
0
        void sp1_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            if (sp1.IsOpen)     //此处可能没有必要判断是否打开串口,但为了严谨性,我还是加上了
            {
                //输出当前时间
                DateTime dt = DateTime.Now;
                txtReceive.Text += dt.GetDateTimeFormats('f')[0].ToString() + "\r\n";
                txtReceive.SelectAll();
                txtReceive.SelectionColor = Color.Blue;         //改变字体的颜色

                byte[] byteRead = new byte[sp1.BytesToRead];    //BytesToRead:sp1接收的字符个数
                if (rdSendStr.Checked)                          //'发送字符串'单选按钮
                {
                    txtReceive.Text += sp1.ReadLine() + "\r\n"; //注意:回车换行必须这样写,单独使用"\r"和"\n"都不会有效果
                    sp1.DiscardInBuffer();                      //清空SerialPort控件的Buffer
                }
                else                                            //'发送16进制按钮'
                {
                    try
                    {
                        Byte[] receivedData = new Byte[sp1.BytesToRead];        //创建接收字节数组
                        sp1.Read(receivedData, 0, receivedData.Length);         //读取数据
                        //string text = sp1.Read();   //Encoding.ASCII.GetString(receivedData);
                        sp1.DiscardInBuffer();                                  //清空SerialPort控件的Buffer
                        //这是用以显示字符串
                        //    string strRcv = null;
                        //    for (int i = 0; i < receivedData.Length; i++ )
                        //    {
                        //        strRcv += ((char)Convert.ToInt32(receivedData[i])) ;
                        //    }
                        //    txtReceive.Text += strRcv + "\r\n";             //显示信息
                        //}
                        string strRcv = null;
                        //int decNum = 0;//存储十进制
                        for (int i = 0; i < receivedData.Length; i++) //窗体显示
                        {
                            strRcv += receivedData[i].ToString("X2"); //16进制显示
                        }
                        txtReceive.Text += strRcv + "\r\n";
                    }
                    catch (System.Exception ex)
                    {
                        MessageBox.Show(ex.Message, "出错提示");
                        txtSend.Text = "";
                    }
                }
            }
            else
            {
                MessageBox.Show("请打开某个串口", "错误提示");
            }
        }
Пример #39
0
 IEnumerator IReadTag()
 {
     while (true)
     {
         string readLine = Port.ReadLine();
         if (readLine != "NULL")
         {
             Debug.Log("connecté !!");
             sound.Play();
         }
     }
     yield return(null);
 }
Пример #40
0
        private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            System.IO.Ports.SerialPort sp = (System.IO.Ports.SerialPort)sender;

            string indata = sp.ReadLine();

            if (checkBox1.Checked == true)
            {
                WriteLog(indata);
            }
            // Show all the incoming data in the port's buffer
            //Console.WriteLine(port.ReadExisting());
            richTextBox1.Text = indata;
        }
Пример #41
0
      private void button1_Click(object sender, EventArgs e)
      {
         serialPort = new SerialPort("COM12", 115200, Parity.None, 8, StopBits.One);

         serialPort.ReadTimeout = 1000;

         serialPort.Open();

         try
         {
            Send("p " + (Kp.Value / 1000.0).ToString());
            Send("i " + (Ki.Value / 1000.0).ToString());
            Send("d " + (Kd.Value / 1000.0).ToString());
            Send("s " + Setpoint.Value.ToString());
            Send("l 500");
            Send("g");
            string s_Kp = serialPort.ReadLine();
            string s_Ki = serialPort.ReadLine();
            string s_Kd = serialPort.ReadLine();
            string s_SetPoint = serialPort.ReadLine();
            string loops = serialPort.ReadLine();

            DataBlock db = new DataBlock();
            db.m_channels = 2;
            db.m_samplesPerChannel = 500;
            db.Alloc();

            for (int i = 0; i < 500; i++)
            {
               string str = serialPort.ReadLine();

               string[] ss = str.Split(' ');

               int val1;
               int val2;
               int.TryParse(ss[0], out val1);
               int.TryParse(ss[1], out val2);

               if (val1 < 0)
                  val1 = 0;

               db.SetVoltage(0, i,  (int)(val1 * 128 / Setpoint.Value));
               db.SetVoltage(1, i,  (int)((val2 / 2) + 128));
            }
            db.m_sampleRate = 25;
            db.m_channels = 2;
            db.m_dataType = DataBlock.DATA_TYPE.ANALOG;


            graphControl1.SetScopeData(db);
         }
         catch
         {
            graphControl1.SetScopeData(null);
         }
         serialPort.Close();
      }
Пример #42
0
		public static string ReadDescription(SerialPort port)
		{
			port.ReadTimeout = 100;
			port.NewLine = "\r\n";
			string desc = "";
			try {
				port.Open();
				port.WriteLine("R");
				Thread.Sleep(1000);
				desc = port.ReadLine();
			} catch (TimeoutException) {
			}
			port.Close();
			return desc;
		}
Пример #43
0
 //static StreamReader arq = new StreamReader("exp1.txt");
 //static StreamReader arq = new StreamReader(Form1.Porta.ReadExisting());
 public double ler(SerialPort Port)
 {
     try
     {
         //string linha = "";
         //linha
         double num = double.Parse(Port.ReadLine());
         //double num = double.Parse(linha);
         return (num);
     }
     catch (Exception e)
     {
         return (-1);
     }
 }
Пример #44
0
        public string ReadLine()
        {
            string data = "";

            if (!serialport.IsOpen)
            {
                Open();
            }
            if (serialport.IsOpen)
            {
                data = serialport.ReadLine();
                serialport.DiscardInBuffer();
            }
            return(data);
        }
Пример #45
0
    public void leer()
    {
        lectura = ArduinoPort.ReadLine();
        if (lectura == "c")
        {
            UIImagen.sprite = Resources.Load <Sprite>("vidas");
        }

        if (lectura != "c")
        {
            speed.text      = "" + lectura + " km/h";
            UIImagen.sprite = Resources.Load <Sprite>("corazon2");
        }

        ArduinoPort.Close();
    }
Пример #46
0
 private void button2_Click(object sender, EventArgs e)
 {
     SerialPort tmp = new SerialPort();
     tmp.BaudRate = 9600;
     tmp.PortName = hardwarebox.SelectedItem.ToString();
     tmp.Open();
     if (tmp.ReadLine().Contains("1234#"))
     {
         Boot.hardware = tmp;
         this.Close();
     }
     else
     {
         MessageBox.Show("Is dit gecertificeerde hardware", "Hardware fout", MessageBoxButtons.OK, MessageBoxIcon.Error);
         tmp.Close();
     }
 }
Пример #47
0
        public static bool connectDisplay(SerialPort serial)
        {
            if (serial == null || !serial.IsOpen)
            {
                throw new Exception(StringResources.E00001);
            }

            string accessString = serial.ReadLine();

            if (accessString == DisplayToAppAccessString)
            {

                serial.WriteLine(AppToDisplayAccessString);
                return true;
            }
            return false;
        }
        static void Main(string[] args)
        {
            string COMPortName;                  // Variable for Holding Serial port number ,eg:- ttyUSB0
            string RxedData;                     // Variable for Holding received data

            Menu();                              // Used for displaying the banner

            Console.Write("\t  Enter Serial Port Number(eg :- ttyUSB0) ->");
            COMPortName = Console.ReadLine();     //Store COM number in COMPortName

            COMPortName = COMPortName.Trim();     // Remove any trailing whitespaces
            COMPortName = @"/dev/" +COMPortName;  //

            SerialPort COMPort = new SerialPort();// Create a SerialPort Object called COMPort

            COMPort.PortName = COMPortName;       // Assign the COM port number
            COMPort.BaudRate = 9600;              // Set Baud rate = 9600
            COMPort.DataBits = 8;                 // Number of data bits = 8
            COMPort.Parity   = Parity.None;       // No parity
            COMPort.StopBits = StopBits.One;      // One stop bit

            Console.WriteLine();
            Console.WriteLine("\t  {0} Selected  \n",COMPortName);
            Console.WriteLine("\t  Baud rate = {0}",COMPort.BaudRate);
            Console.WriteLine("\t  Data Bits = {0}",COMPort.DataBits);
            Console.WriteLine("\t  Parity    = {0}",COMPort.Parity);
            Console.WriteLine("\t  Stop Bits = {0}",COMPort.StopBits);

            COMPort.Open();                       // Open the serial port
            Console.WriteLine("\n\t  {0} opened \n", COMPortName);

            COMPort.RtsEnable = true;            // Since RTS = 1, ~RTS = 0 So ~RE = 0 Receive  Mode enabled
            COMPort.DtrEnable = true;            // Since DTR = 1. ~DTR = 0 So  DE = 0
                                                 //~RE and DE LED's on USB2SERIAL board will be off

            Console.WriteLine("\t  RTS = 1 so ~RTS = 0, ~RE = 0 Receive  Mode enabled");
            Console.WriteLine("\t  DTR = 1 so ~DTR = 0,  DE = 0 ");

            RxedData = COMPort.ReadLine();       // Wait for data reception

            Console.WriteLine("\n\t  Data Received ");
            Console.WriteLine("\n\t \" {0} \" ", RxedData);

            Menu_End();
            Console.Read();                       // Press to Exit
        }
Пример #49
0
        private void sport_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            TextBox.CheckForIllegalCrossThreadCalls = false;

            #region displ1 substing
            string gr   = sport.ReadLine();
            string greg = gr.Substring(2, 11);
            string g    = RemoveWhitespace(greg);



            textBoxGreutateSenzor.Text = g;

            greutateGlobala = textBoxGreutateSenzor.Text;

            #endregion
        }
Пример #50
0
        private void takeFoto(object sender, SerialDataReceivedEventArgs e)
        {
            string read = arduinoPort.ReadLine();

            char[] aa = read.ToCharArray();
            if (aa.Length > 0)
            {
                char a = aa[0];
                Console.WriteLine("Serial: " + a);
                if (a == 'm' && bitmap != null)
                {
                    Console.WriteLine("Entroooooooooo");
                    var dir = System.IO.Directory.GetCurrentDirectory() + "\\foto_" + DateTime.Now.Millisecond + ".png";
                    bitmap.Save(dir, ImageFormat.Png);

                    Console.WriteLine("Listo");
                }
            }
        }
Пример #51
0
        public virtual void Read()
        {
            while (!KillThread)
            {
                try
                {
                    switch (RMode)
                    {
                    case tRMode.LINE_MODE:
                        COM_line(ComPort.ReadLine().TrimEnd('\r', '\n'));
                        break;

                    case tRMode.BYTE_MODE:
                        int b = ComPort.ReadByte();
                        if (b == -1)
                        {
                            KillThread = true;
                        }
                        else
                        {
                            if (recv_buff == null)
                            {
                                recv_buff        = new byte[2048];
                                recv_buff_length = 0;
                            }
                            recv_buff[recv_buff_length++] = (byte)b;
                            if (COM_byte(recv_buff, recv_buff_length))
                            {
                                recv_buff        = null;
                                recv_buff_length = 0;
                            }
                        }
                        break;
                    }
                }
                catch (Exception e)
                {
                    Program.Logger(e.ToString());
                    KillThread = true;
                }
            }
        }
Пример #52
0
        private void ListenSerial()
        {
            while (!IsClosed)
            {
                try
                {
                    //read to data from arduino
                    string AString = Port.ReadLine();

                    //write the data in something textbox
                    Dolazni_podatci.Invoke(new MethodInvoker(
                                               delegate
                    {
                        SaveMeasurementData(AString);
                    }
                                               ));
                }
                catch { }
            }
        }
Пример #53
0
 public string ReadFromArduino(int timeout = 0)
 {
     if (arduinoSerialPort != null && arduinoSerialPort.IsOpen)
     {
         if (timeout > 0)
         {
             arduinoSerialPort.ReadTimeout = timeout;
         }
         try {
             //            if (arduinoSerialPort != null && arduinoSerialPort.IsOpen && arduinoSerialPort.BytesToRead > 0){ // If there are any bytes to read in the input buffer
             return(arduinoSerialPort.ReadLine());
             //            }else{
             //                return null;
             //            }
         } catch (TimeoutException) {
             return(null);
         }
     }
     return(null);
 }
Пример #54
0
 public async void ReceivePort(object sender, SerialDataReceivedEventArgs e)
 {
     try
     {
         string data = Serial.ReadLine();
         if (_Continue)
         {
             await Task.Run(() =>
             {
                 var Movement = this.Machine.MovementList.Where(o => data.IndexOf(o.RecieverTag) != -1).FirstOrDefault();
                 if (Movement != null)
                 {
                     Movement.Value = data;
                 }
             });
         }
     }
     catch (Exception)
     {
     }
 }
Пример #55
0
        private void EscucharHilo()
        {
            while (!cerrado)
            {
                try
                {
                    string acceso = Port.ReadLine();
                    labelMessage.Invoke(new MethodInvoker(
                                            delegate
                    {
                        labelMessage.Text = acceso;
                        boca.SpeakAsync(acceso);
                    }

                                            ));
                }
                catch (Exception)
                {
                }
            }
        }
Пример #56
0
        public void spislem(object sender, SerialDataReceivedEventArgs e) //SERİPORT EVENTİ
        {
            SerialPort sp      = (SerialPort)sender;
            Turnike    turnike = new Turnike();

            turnike.Haberlesme = "SER";
            turnike.PortNo     = sp.PortName;;
            string gelenmesaj = sp.ReadLine();

            try
            {
                if (gelenmesaj.Length < 4)
                {
                    return;
                }
                if (gelenmesaj.Substring(0, 4) == "<ID>")
                {
                    string modulid   = gelenmesaj.Substring(gelenmesaj.IndexOf("<ID>") + 4, 1);
                    string modulport = sp.PortName;
                    turnike.No     = Convert.ToInt32(modulid);
                    turnike.PortNo = modulport;
                }
                if (gelenmesaj.Substring(0, 4) == "TNO:")
                {
                    turnike.No     = Convert.ToInt32(gelenmesaj.Substring(4, 1));
                    turnike.KartNo = gelenmesaj.Substring(gelenmesaj.IndexOf("UID:") + 4, 8);
                    turnike.Reader = Convert.ToInt32(gelenmesaj.Substring(gelenmesaj.IndexOf("Reader") + 7, 1));
                    textBoxparmakizikimliği.Text = turnike.KartNo;
                    Ogrenci ogrenci = OgrenciIsleri.KartNoileGetir(turnike.KartNo);
                    if (turnike.Reader == 0)
                    {
                        OgrenciGirisi(ogrenci, turnike);
                    }
                }
            }
            catch (Exception ex)
            {
                Helper.DosyayaYaz(ex.ToString());
            }
        }
Пример #57
0
        void _serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            //we have recieved data
            while (_serialPort.BytesToRead > 0)
            {
                string   rec   = _serialPort.ReadLine().Replace("\r", "").Replace("\n", "");
                string[] words = rec.Split(' ');
                switch (words[0])
                {
                case "read":
                {
                    lastReading = DateTime.Now;
                    //file isnt paused, log results
                    addreading(words);
                }
                break;

                default:
                    break;
                }
            }
        }
Пример #58
0
        private void displayReceived(/*object sender, SerialDataReceivedEventArgs e*/)
        {
            string message = "";

            try
            {
                message = serialPort.ReadLine();
            }
            catch (Exception ex)
            {
                message = "Receiving message goes wrong";
            }

            if (inPlaceCheckBox.Checked)
            {
                receivedMessageTextBox.Text = message;
            }
            else
            {
                receivedMessageTextBox.Text += message + Environment.NewLine;
            }
        }
Пример #59
0
 public static void Read()
 {
     while (_continue)
     {
         try
         {
             string message = _serialPort.ReadLine();
             var    idx     = message.IndexOf("--");
             string ans     = "";
             if (message.Remove(idx).EndsWith("Forward"))
             {
                 ans += "w";
             }
             if (message.Remove(idx).EndsWith("Backwards"))
             {
                 ans += "x";
             }
             if (message.Substring(idx + 2).StartsWith("Left"))
             {
                 ans += "a";
             }
             if (message.Substring(idx + 2).StartsWith("Right"))
             {
                 ans += "d";
             }
             //message = message.Substring(message.LastIndexOf(' ') + 1);
             if (ans == "")
             {
                 ans = "s";
             }
             Console.WriteLine(message.Trim() + "\t ans=" + ans);
             //if (ans == "a" || ans == "d") SendLine("1");
             //if (ans == "w" || ans == "x") SendLine("3");
             SendLine(ans);
         }
         catch (TimeoutException) { }
     }
 }
Пример #60
-1
        public bool ParseResponse(SerialPort serialPort)
        {
            try
            {
                // Dummy read of command;
                serialPort.ReadLine();

                var resp = serialPort.ReadLine().Trim();

                resp = resp.Replace('.', ',');

                Regex regex = new Regex(@"time=""(.*)"",P=""([0-9,]*)"",H=""([0-9,]*)"",T=""([0-9,]*)""");

                var match = regex.Match(resp);

                // Empty line
                serialPort.ReadLine();

                var ack = serialPort.ReadLine().Trim();

                Time = match.Groups[1].Value;
                Pressure = float.Parse(match.Groups[2].Value);
                Humidity = float.Parse(match.Groups[3].Value);
                Temperature = float.Parse(match.Groups[4].Value);

                return ack.Equals("OK");
            }
            catch (Exception)
            {
                return false;
            }
        }