ReadTo() public méthode

public ReadTo ( string value ) : string
value string
Résultat string
Exemple #1
0
        /// <summary>
        /// Read PLC via SerialPort
        /// </summary>
        /// <param name="PlcPort">Serial Port address</param>
        /// <returns></returns>
        public static string ReadPLC(System.IO.Ports.SerialPort PlcPort)
        {
            string FCS_rxd;
            string FCS  = "";
            string RXD  = "";
            string data = "";

            Stopwatch stopwatch = new Stopwatch();

            try
            {
                RXD  = "";
                data = "";
                PlcPort.ReadTimeout = 1000;
                RXD = PlcPort.ReadTo("\r");
            }
            catch (Exception)
            {
                return(null);
            }

            FCS_rxd = RXD.Substring(RXD.Length - 3, 2);
            if (RXD.Substring(0, 1) == "@" && RXD.Length > 3) //response has data
            {
                RXD = RXD.Substring(0, RXD.Length - 3);
            }

            /*else if (RXD.Substring(0, 1) == "@" && RXD.Length == 11)//reponse has no data but error
             * {
             *  MessageBox.Show("PLC comm error");
             *  return data;
             * }*/
            else if (RXD == "")
            {
                return(null);
            }

            FCS = GetFCS(RXD);
            if (FCS == FCS_rxd)
            {
                data = RXD.Substring(23, RXD.Length - 23);
                return(data);
            }
            else
            {
                return(null);
            }
        }
Exemple #2
0
        void ComPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            if (sender.GetType() != typeof(System.IO.Ports.SerialPort))
            {
                return;
            }
            System.IO.Ports.SerialPort comPort = (System.IO.Ports.SerialPort)sender;

            try
            {
                string infoMessage1 = comPort.ReadTo("=>");
                infoMessage1 = infoMessage1.Trim().Replace("\0", "").Replace("\n\r", "\r\n");

                //实现委托
                MyInvoke Invoke1 = new MyInvoke(UpdateForm);
                this.BeginInvoke(Invoke1, infoMessage1);
                comPort.DiscardInBuffer();
                comPort.DiscardOutBuffer();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        // TODO постараться вынести инициализацию в метод Read
        private InitializationData ReadInitialization(SerialPort readport)
        {
            while (true)
               {
               try
               {
                   readport.ReadTo("\xAA\x55");

                   // Считывание данных для создания пакета
                   // Здесь важен строгий порядок считывания байтов, точно как в пакете.
                   byte recipient = (byte)readport.ReadByte();
                   byte sender = (byte)readport.ReadByte();
                   ushort dataLenght = BitConverter.ToUInt16(
                       new byte[] { (byte)readport.ReadByte(), (byte)readport.ReadByte() }, 0);
                   byte option1 = (byte)readport.ReadByte();
                   byte option2 = (byte)readport.ReadByte();
                   ushort crc = BitConverter.ToUInt16(
                       new byte[] { (byte)readport.ReadByte(), (byte)readport.ReadByte() }, 0);

                   // Счетчик количества итерация цикла while
                   int count = 0;
                   while (readport.BytesToRead < dataLenght)
                   {
                       count++;
                       Thread.Sleep(_sleepTime);
                       if (count > dataLenght)
                       {
                           break;
                       }
                   }

                   byte[] data = new byte[dataLenght];
                   readport.Read(data, 0, dataLenght);

                   var packet = new Packet.Packet(new Header(recipient, sender, option1, option2), data);

                       // Проверка crc и id клиента, id отправителя и типа пакета
                       if (packet.Header.Crc == crc && packet.Header.Recipient == ClietnId && packet.Header.Sender == 0 && packet.Data.Type == DataType.Initialization)
                       {
                           SendAcknowledge(packet);

                           var initialization = StructConvertor.FromBytes<InitializationData>(packet.Data.Content);

                           return initialization;
                       }
               }

               catch (InvalidOperationException)
               {
                   IsPortAvailable(readport);
                   Thread.Sleep(3000);
               }

               catch (TimeoutException exception)
               {
                   // TODO ограничить количество отправок запроса
                   SendInitializationRequest();
               }

               catch (Exception exception)
               {
                   LogHelper.GetLogger<CommunicationUnit>().Error("Ошибка при чтение с порта", exception);
               }

               }
        }
Exemple #4
0
 public string PCempfangen()
 {
     input = comPort.ReadTo("\r");
     DecodeDaten(input);
     return(input);
 }
Exemple #5
0
        private void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            // run all background tasks here
            //autoSerialPort = FindPort();
            IProgress <string> progress = null;

            var ports = System.IO.Ports.SerialPort.GetPortNames().OrderBy(s => s);

            if (ports.Count() <= 0)
            {
                MessageBox.Show(
                    "Error: No Serial Ports avaliable.  Make sure the gps reciever is plugged in and installed.  Contact your system administrator for help. \n"
                    , "Error 1: No Serial Ports Found",
                    MessageBoxButton.OK,
                    MessageBoxImage.Error);
                _continue      = false;
                autoSerialPort = null;
                return;
            }
            Application.Current.Dispatcher.Invoke((Action) delegate
            {
                prog = new autoscanProgress();
                prog.Show();
            });


            int i       = 0;
            int portNum = 0;
            int total   = ports.Count() * 3;

            prog.scanPercentLabel.Dispatcher.BeginInvoke((Action)(() => prog.scanPercentLabel.Content = "Beginning Scan..."));
            prog.autoscanProgressBar.Dispatcher.BeginInvoke((Action)(() => prog.autoscanProgressBar.Value = 2));

            foreach (var portName in ports)
            {
                portNum++;
                using (var port = new System.IO.Ports.SerialPort(portName))
                {
                    var        defaultRate     = port.BaudRate;
                    List <int> baudRatesToTest = new List <int>(new[] { 9600, 4800, 19200 }); //Ordered by likelihood // removed: 115200, 57600, 38400, 2400
                                                                                              //Move default rate to first spot
                    if (baudRatesToTest.Contains(defaultRate))
                    {
                        baudRatesToTest.Remove(defaultRate);
                    }
                    baudRatesToTest.Insert(0, defaultRate);

                    foreach (var baud in baudRatesToTest)
                    {
                        i++;
                        double test    = (double)(i) / total;
                        int    percent = (int)(test * 100);
                        Trace.WriteLine("Percent complete: " + percent + "%");

                        Application.Current.Dispatcher.Invoke((Action) delegate
                        {
                            prog.autoscanProgressBar.Value = percent;
                            prog.scanPercentLabel.Content  = "Scanning Port " + portNum + " at Baud " + baud;
                        });

                        if (progress != null)
                        {
                            progress.Report(string.Format("Trying {0} @ {1}baud", portName, port.BaudRate));
                            worker.ReportProgress(percent);
                        }
                        port.BaudRate    = baud;
                        port.ReadTimeout = 2500; //this might not be long enough
                        bool success = false;
                        try
                        {
                            port.Open();
                            if (!port.IsOpen)
                            {
                                continue; //couldn't open port
                            }
                            try
                            {
                                port.ReadTo("$GP");
                                success = true;
                                Trace.WriteLine("GPS Found at: " + port.PortName + " baud " + port.BaudRate);
                            }
                            catch (TimeoutException)
                            {
                                continue;
                            }
                        }
                        catch
                        {
                            //Error reading
                        }
                        finally
                        {
                            port.Close();
                            //prog.Close();
                        }
                        if (success)
                        {
                            Application.Current.Dispatcher.Invoke((Action) delegate
                            {
                                prog.Close();
                            });
                            autoSerialPort = new System.IO.Ports.SerialPort(portName, baud);
                            return;
                        }
                    }
                }
            }
            //serialPort = new System.IO.Ports.SerialPort("COM6", 9600);
            //return serialPort;

            MessageBox.Show(
                "Error: Could not AutoDetect a GPS device.  Make sure the gps reciever is plugged in and installed.  If you believe your device is properly installed, it may not be on a scanned baud rate (9600, 4800, 19200).  " +
                "If this is the case, please go to settings and manually enter the information for your GPS reciever. \n" +
                "Contact your system administrator for help. \n"
                , "Error 1: No Serial Ports Found",
                MessageBoxButton.OK,
                MessageBoxImage.Error);
            autoSerialPort = null;
            Application.Current.Dispatcher.Invoke((Action) delegate
            {
                prog.Close();
            });
            return;
        }
Exemple #6
0
        private static System.IO.Ports.SerialPort FindPort(IProgress <string> progress = null)
        {
            var ports = System.IO.Ports.SerialPort.GetPortNames().OrderBy(s => s);

            if (ports.Count() <= 0)
            {
                MessageBox.Show(
                    "Error: No Serial Ports avaliable.  Make sure the gps reciever is plugged in and installed.  Contact your system administrator for help. \n"
                    , "Error 1: No Serial Ports Found",
                    MessageBoxButton.OK,
                    MessageBoxImage.Error);
                _continue = false;
                return(null);
            }
            prog = new autoscanProgress();
            prog.Show();

            int i     = 0;
            int total = ports.Count() * 4;

            prog.scanPercentLabel.Dispatcher.BeginInvoke((Action)(() => prog.scanPercentLabel.Content = "Beginning Scan..."));
            prog.autoscanProgressBar.Dispatcher.BeginInvoke((Action)(() => prog.autoscanProgressBar.Value = 2));

            foreach (var portName in ports)
            {
                i++;
                int j = 0;
                using (var port = new System.IO.Ports.SerialPort(portName))
                {
                    j++;
                    var        defaultRate     = port.BaudRate;
                    List <int> baudRatesToTest = new List <int>(new[] { 9600, 4800, 19200 }); //Ordered by likelihood // removed: 115200, 57600, 38400, 2400
                                                                                              //Move default rate to first spot
                    if (baudRatesToTest.Contains(defaultRate))
                    {
                        baudRatesToTest.Remove(defaultRate);
                    }
                    baudRatesToTest.Insert(0, defaultRate);
                    foreach (var baud in baudRatesToTest)
                    {
                        //prog.autoscanProgressBar.Dispatcher.BeginInvoke((Action)(() => prog.autoscanProgressBar.Value = (double)(((i + j) / total) * 100)));
                        prog.SetProgress((int)(double)(((i + j) / total) * 100));
                        prog.scanPercentLabel.Dispatcher.BeginInvoke((Action)(() => prog.scanPercentLabel.Content = "Scanning Port " + i + " at Baud " + baud));

                        if (progress != null)
                        {
                            progress.Report(string.Format("Trying {0} @ {1}baud", portName, port.BaudRate));
                        }
                        port.BaudRate    = baud;
                        port.ReadTimeout = 2000; //this might not be long enough
                        bool success = false;
                        try
                        {
                            port.Open();
                            if (!port.IsOpen)
                            {
                                continue; //couldn't open port
                            }
                            try
                            {
                                port.ReadTo("$GP");
                                success = true;
                            }
                            catch (TimeoutException)
                            {
                                continue;
                            }
                        }
                        catch
                        {
                            //Error reading
                        }
                        finally
                        {
                            port.Close();
                            //prog.Close();
                        }
                        if (success)
                        {
                            prog.Close();
                            return(new System.IO.Ports.SerialPort(portName, baud));
                        }
                    }
                }
            }
            //serialPort = new System.IO.Ports.SerialPort("COM6", 9600);
            //return serialPort;

            MessageBox.Show(
                "Error: Could not AutoDetect a GPS device.  Make sure the gps reciever is plugged in and installed.  If you believe your device is properly installed, it may not be on a scanned baud rate (9600, 4800, 19200).  " +
                "If this is the case, please go to settings and manually enter the information for your GPS reciever. \n" +
                "Contact your system administrator for help. \n"
                , "Error 1: No Serial Ports Found",
                MessageBoxButton.OK,
                MessageBoxImage.Error);
            return(null);
        }
 /// <summary>
 /// 一直读取到输入缓冲区中的指定 value 的字符串。
 /// </summary>
 /// <param name="value">一直读取到输入缓冲区中的指定 value 的字符串</param>
 /// <returns>输入缓冲区中直到指定 value 的内容。</returns>
 public string ReadTo(string value)
 {
     return(COM.ReadTo(value));
 }
        public static String[] Read(SerialPort port)
        {
            long Inlatitude;
            long Inlongitude;
            string strLatitude = "";
            string strLongitude = "";
            double latitude;
            double longitude;
            int Heart_Rate;
            bool flag_badData = false;
            string Date_Time;
            string[] words = {""};
            string data = "";

            do
            {
                flag_badData = false;
                data = port.ReadTo("]");
                words = data.Split(',');
                if (words.Length != 4 || words[0].Length < 8 || words[1].Length < 10 || words[2].Length > 3)
                {
                    flag_badData = true;
                }
                else
                {
                    strLatitude = words[0].Remove(0, words[0].Length - 8);
                    strLongitude = words[1].Remove(0, words[1].Length - 10);
                    if (!IsAllDigits(strLatitude) || !IsAllDigits(strLongitude) || !IsAllDigits(words[2]))
                    {
                        flag_badData = true;
                    }
                }
                
            } while ( flag_badData || Int64.Parse(strLatitude) > 90000000 || Int64.Parse(strLatitude) < -90000000 || Int64.Parse(strLongitude) < -180000000 || Int64.Parse(strLongitude) > 180000000);
            // lat = 90 long = 180
            if (words[0] != null && words[1] != null)
            {
                try
                {
                    Inlatitude = Int64.Parse(strLatitude);
                    latitude = (Inlatitude / 1000000.0);
                    Inlongitude = Int64.Parse(strLongitude);
                    longitude = (Inlongitude / 1000000.0);
                    words[0] = ("" + latitude);
                    words[1] = ("" + longitude);
                    //Location_ShowAll_Tab.Text = ("Lat:" + latitude + " Lon:" + longitude);            
                }
                catch (FormatException)
                {
                    // Location_ShowAll_Tab.Text = ("Format Issue!!!!");
                    latitude = 38.556868;
                    words[0] = "38.556868";
                    longitude = -121.358592;
                    words[1] = "-121.358592";
                    Read(port);
                }

                if (words[2] == null)
                {
                    Heart_Rate = 0; //set default heart rate
                    words[2] = ("N/A");
                    // Heart_Rate_ShowAll_Tab.Text = ("Set to default");
                }
                else
                {
                    try
                    {
                        Heart_Rate = Convert.ToInt32(words[2]);    // Convert String into int
                        words[2] = ("" + Heart_Rate);
                    }
                    catch (FormatException)
                    {
                        words[2] = ("Format Error");
                    }
                }
                if (words[3] == null)
                {
                    words[3] = ("Not available");
                }
                else
                {
                    try
                    {
                        Date_Time = words[3]; //  Keeps string as a string
                        words[3] = ("" + Date_Time);
                    }
                    catch (FormatException)
                    {
                        words[3] = ("Format Error");
                    }
                }
            }
            else
            {
                //set default lat/ long - csus
                latitude = 38.556868;
                words[0] = "38.556868";
                longitude = -121.358592;
                words[1] = "-121.358592";
                Read(port);
            }
            return words;
        }