예제 #1
0
 void sp_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
 {
     OnDataReceived(e);
 }
예제 #2
0
        // UART RX interrupt. only fires if at least 4 bytes are in the buffer
        private void serialPort_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            /////////////////////////////////////////////////////////////////////////////////////////////////////////
            //// Syncronization check ///////////////////////////////////////////////////////////////////////////////
            /////////////////////////////////////////////////////////////////////////////////////////////////////////

            if (!uartSynced)
            {
                RXData = serialPort.ReadExisting();
            }

            // check if SQ_uart is syncronized. If not, wait for '!' and restart uart operation
            if (!uartSynced && RXData.Contains("!"))
            {
                serialPort.DiscardInBuffer();
                serialPort.ReceivedBytesThreshold = 9;
                uartSynced = true;
                return;
            }
            else if (!uartSynced)
            {
                // SQ_uart is not syncronized and didnt recieve the sync char '!' yet
                serialPort.DiscardInBuffer();
                return;
            }

            //RXData = serialPort.ReadTo("?");
            RXData = serialPort.ReadExisting();

            // check if transmission is sync'd
            if (uartSynced && !RXData.Contains("!"))
            {
                // SQ-transmission is not syncronized
                uartSynced = false;
                serialPort.ReceivedBytesThreshold = 1; // set this to 1 to check every incomming byte untli resynced
                // update uart info
                SQ_sync_lost++;
                SQ_packets_missed++;
                //Console.WriteLine("RX data skiped: " + SQ_packets_missed);
                uartLink1.setMissedPackets(SQ_packets_missed);
                uartLink1.setSyncLost(SQ_sync_lost);
                serialPort.DiscardInBuffer();
                return;
            }

            /////////////////////////////////////////////////////////////////////////////////////////////////////////
            /////////////////////////////////////////////////////////////////////////////////////////////////////////
            /////////////////////////////////////////////////////////////////////////////////////////////////////////


            //Console.WriteLine("RX: " + RXData);
            if (uartSynced && RXData.ElementAt(8) == 0x21) // 0x21 = '!'
            {
                // update last-ping
                uartLink1.setTimeLastPing(DateTime.Now);

                // check what kind of data was transmitted

                // data = channel value
                if ((RXData.ElementAt(0) == 'c') && (RXData.ElementAt(1) == 'h'))
                {
                    //Console.WriteLine(" Channel: " + RXData.ElementAt(2) + " Value: " + RXData.Substring(3));
                    this.updataChannel((int)Char.GetNumericValue(RXData.ElementAt(2)), (ushort)Convert.ToInt16(RXData.Substring(3, 4)));
                }
                // data = warning
                else if ((RXData.ElementAt(0) == 'w'))
                {
                    Console.WriteLine("Warning from drone. Warning_code: " + RXData.ElementAt(2));
                }
                // data = motor speeds
                else if ((RXData.ElementAt(0) == 'm') && (RXData.ElementAt(1) == 'u'))
                {
                    // motor panel 1
                    if (RXData.ElementAt(2) > 0)
                    {
                        ctrlMotorPanel1.updateSpeed((int)RXData.ElementAt(2));
                    }
                    else
                    {
                        ctrlMotorPanel1.updateSpeed(0);
                    }
                    // motor panel 2
                    if (RXData.ElementAt(3) > 0)
                    {
                        ctrlMotorPanel2.updateSpeed((int)RXData.ElementAt(3));
                    }
                    else
                    {
                        ctrlMotorPanel2.updateSpeed(0);
                    }
                    // motor panel 3
                    if (RXData.ElementAt(4) > 0)
                    {
                        ctrlMotorPanel3.updateSpeed((int)RXData.ElementAt(4));
                    }
                    else
                    {
                        ctrlMotorPanel3.updateSpeed(0);
                    }
                    // motor panel 4
                    if (RXData.ElementAt(5) > 0)
                    {
                        ctrlMotorPanel4.updateSpeed((int)RXData.ElementAt(5));
                    }
                    else
                    {
                        ctrlMotorPanel4.updateSpeed(0);
                    }
                }
                // data = connection test
                else if ((RXData.ElementAt(0) == 'x'))
                {
                    Console.WriteLine("Connection check answer: " + RXData);
                    // check if the 3 next bytes match the x1_bytes
                    if (RXData[2] == x1_bytes[0] && RXData[3] == x1_bytes[1] && RXData[4] == x1_bytes[2])
                    {
                        // x1_bytes match. connetion is good
                        setConnected(true);
                        droneConnected = true;
                        uartLink1.setTimeLastPing(DateTime.Now);
                        // enable the tab control
                        if (this.tabControl1.InvokeRequired)
                        {
                            this.tabControl1.BeginInvoke((MethodInvoker) delegate() { tabControl1.Enabled = true; });
                        }
                        else
                        {
                            tabControl1.Enabled = true;;
                        }
                    }
                    else
                    {
                        // x1_bytes dont match. connetion is bad
                        setConnected(false);
                        droneConnected = false;
                        // disabel the tab control
                        if (this.tabControl1.InvokeRequired)
                        {
                            this.tabControl1.BeginInvoke((MethodInvoker) delegate() { tabControl1.Enabled = false; });
                        }
                        else
                        {
                            tabControl1.Enabled = false;;
                        }
                    }
                }
                serialPort.DiscardInBuffer();
            }
            else
            {
                if ((uartSynced) && RXData != "")
                {
                    Console.WriteLine("RX error: no ! found. Data: " + RXData);
                }
                else if (uartSynced && RXData == "")
                {
                    Console.WriteLine("RX error: empty buffer");
                }
            }
        }
예제 #3
0
        private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            string Recieved = serialPort1.ReadLine();

            MessageBox.Show("Test" + Recieved);
            //          richTextBox2.Text = Recieved;

            /* if(path_b){
             *     path = Recieved;
             *     richTextBox1.Text = path;
             *
             *     path_b = false;
             *     return;
             * }*/



            /*      switch (int.Parse(Recieved))
             *    {
             *        case 0: // new folder
             *            System.IO.Directory.CreateDirectory(@"C:\Users\abdal\Desktop\tests\as");
             *            resault = " sucess add folder";
             *
             *            break;
             *        case 1: // dell file
             *
             *            //    path_b = true;
             *            try
             *            {
             *                System.IO.Directory.Delete(@"C:\Users\abdal\Desktop\tests\as");
             *
             *            }
             *            catch
             *            {
             *                resault = " sucess del folder ";
             *
             *            }
             *
             *
             *
             *            break;
             *        case 2: // change photo name
             *            File.Move(@"C:\Users\abdal\Desktop\tests\a1.jpg", @"C:\Users\abdal\Desktop\tests\a11aa.jpg");
             *            resault = " sucess change pic name";
             *
             *            break;
             *        case 3: // file size
             *            resault = " info : " + DirectorySize(@"C:\Users\abdal\Desktop\acm");
             *
             *            break;
             *        case 4: // show all printers
             *
             *            String s = "";
             *            foreach (String strPrinter in PrinterSettings.InstalledPrinters)
             *            {
             *                s += "printer " + strPrinter + " , ";
             *            }
             *            resault = s;
             *            break;
             *        case 5: // default printer
             *                // افتراضية
             *            PrintDocument prtdoc = new PrintDocument();
             *            string strDefaultPrinter = prtdoc.PrinterSettings.PrinterName;
             *            resault = " default printer : " + strDefaultPrinter;
             *
             *            break;
             *
             *        case 6: // show all process
             *
             *            string ss = "";
             *            ss += String.Format("ID:\tProcess name:");
             *            ss += String.Format("--\t------------ \n");
             *            foreach (System.Diagnostics.Process process in System.Diagnostics.Process.GetProcesses())
             *                ss += String.Format("{0}\t{1}\t,\t", process.Id, process.ProcessName); resault = " sucess add";
             *            resault = ss;
             *            break;
             *        case 7: // screen shoot
             *            int screenWidth = Screen.GetBounds(new Point(0, 0)).Width;
             *            int screenHeight = Screen.GetBounds(new Point(0, 0)).Height;
             *            Bitmap bmpScreenShot = new Bitmap(screenWidth, screenHeight);
             *            Graphics gfx = Graphics.FromImage((Image)bmpScreenShot);
             *            gfx.CopyFromScreen(0, 0, 0, 0, new Size(screenWidth, screenHeight));
             *            bmpScreenShot.Save("D:/test1.jpg", ImageFormat.Jpeg);
             *            resault = " sucess add";
             *            resault = " screan shoot done .. ";
             *            break;
             *        case 8: // read text
             *            string s1 = "";
             *            System.IO.StreamReader sr = new System.IO.StreamReader(@"C:\Users\Admin\Desktop\tests\a\rr.txt");
             *            string line;
             *            while ((line = sr.ReadLine()) != null)
             *            {
             *                Console.WriteLine(line);
             *                s1 += line;
             *            }
             *            sr.Close();
             *            resault = " text file : " + s1;
             *
             *            break;
             *        case 9: // monitoring
             *            FileSystemWatcher fileSystemWatcher = new FileSystemWatcher();
             *            fileSystemWatcher.Path = @"C:\Users\abdal\Desktop\tests";
             *            fileSystemWatcher.NotifyFilter = NotifyFilters.LastWrite;
             *            fileSystemWatcher.Filter = "*.*"; //ex: "*.*" watch all file type
             *            fileSystemWatcher.Changed += new FileSystemEventHandler(OnChanged);
             *            fileSystemWatcher.EnableRaisingEvents = true;
             *            Console.Write("Listening for changes in 'directory_path' directory...press any key to exit");
             *            Console.Read();
             *
             *
             *            resault = res;
             *
             *            break;
             *        case 10: // drives info
             *            string s2 = "";
             *            System.IO.DriveInfo[] allDrives = System.IO.DriveInfo.GetDrives();
             *            foreach (System.IO.DriveInfo driver in allDrives)
             *            {
             *                Console.WriteLine("Drive {0}", driver.Name);
             *                s2 += String.Format(" File type: {0} ", driver.DriveType);
             *                if (driver.IsReady == true)
             *                {
             *                    Console.WriteLine(", Volume label: {0}", driver.VolumeLabel);
             *                    s2 += String.Format(", File system: {0} ", driver.DriveFormat);
             *                    s2 += String.Format(", Available space to current user:{0, 15} bytes ",
             *                      driver.AvailableFreeSpace);
             *                    s2 += String.Format(", Total available space: {0, 15} bytes ", driver.TotalFreeSpace);
             *                    s2 += String.Format(", Total size of drive: {0, 15} bytes  ", driver.TotalSize);
             *                }
             *            }
             *            resault = " my drivers info : " + s2;
             *
             *            break;
             *
             *
             *
             *        default:
             *            richTextBox2.Text = Recieved;
             *
             *            break;
             *    }
             *    richTextBox1.Text = resault;
             *    serialPort1.WriteLine(resault);*/
        }
예제 #4
0
        private void serialPortAVR_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            int datanums = serialPortAVR.BytesToRead;

            for (int i = 0; i < datanums; i++)
            {
                int receive = serialPortAVR.ReadByte();
                data.Add((Byte)receive);
            }
            if (data.Count > 3)
            {
                if (data[0] == 255)
                {
                    data.RemoveAt(0);

                    byte rel = data[0];
                    data.RemoveAt(0);

                    byte reh = data[0];
                    data.RemoveAt(0);

                    total = rel + (reh << 8);

                    status = true;
                }
                else
                {
                    data.RemoveAt(0);
                }
            }
            if (data.Count > 100)
            {
                data.Clear();
            }

            labelICR.Invoke(new MethodInvoker(delegate()
            {
                if (status)
                {
                    labelICR.Text = total.ToString();
                }
            }));

            labelDistance.Invoke(new MethodInvoker(delegate()
            {
                if (status)
                {
                    // 260 ~ 1500
                    // 270 ~ 1400


                    //double result = ((double)(total)) * 4 * 377 * 100 * 0.0000002;
                    double result = ((double)(total)) * 1000000.0 * 64 / 16000000;
                    //double result = map(total, 260, 1450, 3, 50);
                    labelDistance.Text = result.ToString() + " cm";
                    status             = false;
                    trigger            = true;
                    if (result > 40)
                    {
                        imageSelect = 0;
                    }
                    else if (result > 30)
                    {
                        imageSelect = 1;
                    }
                    else if (result > 20)
                    {
                        imageSelect = 2;
                    }
                    else
                    {
                        imageSelect = 3;
                    }
                }
            }));

            pictureBoxCar.Invoke(new MethodInvoker(delegate()
            {
                if (trigger)
                {
                    trigger = false;
                    pictureBoxCar.ImageLocation = "./" + imageSelect.ToString() + ".jpg";
                }
            }));
        }
예제 #5
0
 private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
 {
 }
예제 #6
0
        private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            try
            { VariablesGlobales.DatoRx = serialPort1.ReadLine(); }
            catch
            {
                MessageBox.Show("Error de recepción\nRevise conexiones del puerto serial");
            }
            VariablesGlobales.ErrorComunicacion = false;

            VariablesGlobales.DatoRecibido = new char[100];
            VariablesGlobales.DatoRecibido = VariablesGlobales.DatoRx.ToCharArray();

            // IndDatoRx.Text = "DatoRx:" + VariablesGlobales.DatoRx;
            try
            {
                if (VariablesGlobales.DatoRecibido[0] == 'd' && VariablesGlobales.DatoRecibido[1] == 'a' && VariablesGlobales.DatoRecibido[2] == 't' && VariablesGlobales.DatoRecibido[3] == 'o' && VariablesGlobales.DatoRecibido[4] == '2')
                {
                    //   IndPuertoCOM.BackColor = Color.LightGreen;
                    //   IndPuertoCOM.Text = VariablesGlobales.PuertoSerieEscogido;
                    EntradasGlobales.BandaAlimentadora           = VariablesGlobales.DatoRecibido[5];
                    EntradasGlobales.Zaranda                     = VariablesGlobales.DatoRecibido[6];
                    EntradasGlobales.BandaColectora              = VariablesGlobales.DatoRecibido[7];
                    EntradasGlobales.PesoPruebaBandaAlimentadora = VariablesGlobales.DatoRecibido[8];
                    EntradasGlobales.BandaAgregados1             = VariablesGlobales.DatoRecibido[9];
                    EntradasGlobales.BandaAgregados2             = VariablesGlobales.DatoRecibido[10];
                    EntradasGlobales.BandaAgregados3             = VariablesGlobales.DatoRecibido[11];
                    EntradasGlobales.BandaAgregados4             = VariablesGlobales.DatoRecibido[12];
                    EntradasGlobales.BandaInclinadaReciclado     = VariablesGlobales.DatoRecibido[13];
                    EntradasGlobales.BandaAgregadoReciclado      = VariablesGlobales.DatoRecibido[14];
                    EntradasGlobales.MotorTrituradoReciclado     = VariablesGlobales.DatoRecibido[15];
                    EntradasGlobales.PesoPruebaBandaReciclado    = VariablesGlobales.DatoRecibido[16];
                    EntradasGlobales.CompuertaReciclado          = VariablesGlobales.DatoRecibido[17];
                    EntradasGlobales.MotorBlowerBH               = VariablesGlobales.DatoRecibido[18];
                    EntradasGlobales.MotorVannerBH               = VariablesGlobales.DatoRecibido[19];
                    EntradasGlobales.SinFinColector1BH           = VariablesGlobales.DatoRecibido[20];
                    EntradasGlobales.SinFinColector2BH           = VariablesGlobales.DatoRecibido[21];
                    EntradasGlobales.SinFinTransversalBH         = VariablesGlobales.DatoRecibido[22];
                    EntradasGlobales.Compresor                   = VariablesGlobales.DatoRecibido[23];
                    EntradasGlobales.BombaAsfaltoAdelante        = VariablesGlobales.DatoRecibido[24];
                    EntradasGlobales.BombaAsfaltoAtras           = VariablesGlobales.DatoRecibido[25];
                    EntradasGlobales.Extractor1BH                = VariablesGlobales.DatoRecibido[26];
                    EntradasGlobales.Extractor2BH                = VariablesGlobales.DatoRecibido[27];
                    EntradasGlobales.BlowerQuemador              = VariablesGlobales.DatoRecibido[28];
                    EntradasGlobales.Elevador                    = VariablesGlobales.DatoRecibido[29];
                    EntradasGlobales.CompuertaRechazo            = VariablesGlobales.DatoRecibido[30];
                    EntradasGlobales.Secador                     = VariablesGlobales.DatoRecibido[31];
                    EntradasGlobales.SlingerAdelante             = VariablesGlobales.DatoRecibido[32];
                    EntradasGlobales.SlingerAtras                = VariablesGlobales.DatoRecibido[33];
                    EntradasGlobales.BombaCombustible            = VariablesGlobales.DatoRecibido[34];
                    EntradasGlobales.Damper           = VariablesGlobales.DatoRecibido[35];
                    EntradasGlobales.PilotoValvula    = VariablesGlobales.DatoRecibido[36];
                    EntradasGlobales.MainLlama        = VariablesGlobales.DatoRecibido[37];
                    EntradasGlobales.Rotor1BH         = VariablesGlobales.DatoRecibido[38];
                    EntradasGlobales.Rotor2BH         = VariablesGlobales.DatoRecibido[39];
                    EntradasGlobales.Rotor3BH         = VariablesGlobales.DatoRecibido[40];
                    EntradasGlobales.AlimentacionSilo = VariablesGlobales.DatoRecibido[41];
                    EntradasGlobales.ValvulaAceite    = VariablesGlobales.DatoRecibido[42];
                    EntradasGlobales.ValvulaGas       = VariablesGlobales.DatoRecibido[43];//*/
                }
            }
            catch
            {
                MessageBox.Show("error interno, cierre esta ventana");
            }
            try
            {
                if (VariablesGlobales.DatoRecibido[0] == 'd' && VariablesGlobales.DatoRecibido[1] == 'a' && VariablesGlobales.DatoRecibido[2] == 't' && VariablesGlobales.DatoRecibido[3] == 'o' && VariablesGlobales.DatoRecibido[4] == '3')


                {
                    try
                    {
                        VariablesGlobales.RecibiendoDatos = true;                    // para que no se cierre el puerto mientras esta recibiendo
                        //VariablesGlobales.DatoRx = serialPort1.ReadLine();
                        VariablesGlobales.DatoPBHRx        = serialPort1.ReadLine(); //presión casa de bolsas
                        VariablesGlobales.DatoTBHRx        = serialPort1.ReadLine(); //presión casa de bolsas
                        VariablesGlobales.DatoTMzRx        = serialPort1.ReadLine(); //presión casa de bolsas
                        VariablesGlobales.DatoTExausthRx   = serialPort1.ReadLine(); //temperatura exausth
                        VariablesGlobales.DatoTasfRx       = serialPort1.ReadLine(); // temperatura asfalto
                        VariablesGlobales.DatoPDQRx        = serialPort1.ReadLine(); //presión casa de bolsas
                        VariablesGlobales.DatoPDERx        = serialPort1.ReadLine(); //presión casa de bolsas
                        VariablesGlobales.DatoFlameEye     = serialPort1.ReadLine(); // valor de 0-1023 del porcentaje de llama
                        VariablesGlobales.DatoIndAgregados = serialPort1.ReadLine(); // valor de 0-1023 proveniente dle valor del indicador de agregados
                        VariablesGlobales.DatoIndAsfalto   = serialPort1.ReadLine(); // valor de 0-123 proveniente del valor del indicador del asfalto
                        VariablesGlobales.DatoIndReciclado = serialPort1.ReadLine(); //valor de 0-123 proveniente del valor del indicador del reciclado
                        VariablesGlobales.RecibiendoDatos  = false;                  //para permitir cerrar el puerto
                    }
                    catch
                    {
                        MessageBox.Show("Error de recepción\nRevise conexiones  del puerto serial");
                    }
                }
                else
                {
                    IndBasculaAgregados.Text = "error";
                }
                IndBasculaAgregados.Text = Convert.ToString(VariablesGlobales.ConstanteBasAgregados * (VariablesGlobales.Valor_mA_Agregados - VariablesGlobales.ValorCeroBasAgregados));
            }
            catch
            {
                MessageBox.Show("erro interno, cierre esta ventana");
            }
        }
예제 #7
0
        private void portRead(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            //Initialize a buffer to hold the received data
            byte[] buffer = new byte[serialPort.ReadBufferSize];

            //There is no accurate method for checking how many bytes are read
            //unless you check the return from the Read method
            int bytesRead = serialPort.Read(buffer, 0, buffer.Length);

            //For the example assume the data we are received is ASCII data.
            tString += Encoding.ASCII.GetString(buffer, 0, bytesRead) + "\r\n";
            //Check if string contains the terminator
            //if (tString.IndexOf((char)_terminator) > -1)
            //  {
            //If tString does contain terminator we cannot assume that it is the last character received
            // string workingString = tString.Substring(0, tString.IndexOf((char)_terminator));
            //Remove the data up to the terminator from tString
            //tString = tString.Substring(tString.IndexOf((char)_terminator));
            //Do something with workingString
            int           read;
            List <string> msg = tString.ToString().Split("\r\n".ToCharArray()).ToList();

            msg.RemoveAll(isBlank);
            bool succeed = Int32.TryParse(msg[0], out read);

            if (succeed)
            {
                switch (read)
                {
                case 0:
                    SendKeys.SendWait(textBox1.Text);
                    Console.WriteLine("0 Pressed, Sending \"" + textBox1.Text + "\" To the current application");
                    break;

                case 1:
                    SendKeys.SendWait(textBox2.Text);
                    Console.WriteLine("1 Pressed, Sending \"" + textBox2.Text + "\" To the current application");
                    break;

                case 2:
                    SendKeys.SendWait(textBox3.Text);
                    Console.WriteLine("2 Pressed, Sending \"" + textBox3.Text + "\" To the current application");
                    break;

                case 3:
                    SendKeys.SendWait(textBox4.Text);
                    Console.WriteLine("3 Pressed, Sending \"" + textBox4.Text + "\" To the current application");
                    break;

                case 4:
                    SendKeys.SendWait(textBox5.Text);
                    Console.WriteLine("4 Pressed, Sending \"" + textBox5.Text + "\" To the current application");
                    break;

                case 5:
                    SendKeys.SendWait(textBox6.Text);
                    Console.WriteLine("5 Pressed, Sending \"" + textBox6.Text + "\" To the current application");
                    break;

                case 6:
                    SendKeys.SendWait(textBox7.Text);
                    Console.WriteLine("6 Pressed, Sending \"" + textBox7.Text + "\" To the current application");
                    break;

                case 7:
                    SendKeys.SendWait(textBox8.Text);
                    Console.WriteLine("7 Pressed, Sending \"" + textBox8.Text + "\" To the current application");
                    break;

                case 8:
                    SendKeys.SendWait(textBox9.Text);
                    Console.WriteLine("8 Pressed, Sending \"" + textBox9.Text + "\" To the current application");
                    break;

                case 9:
                    SendKeys.SendWait(textBox10.Text);
                    Console.WriteLine("9 Pressed, Sending \"" + textBox10.Text + "\" To the current application");
                    break;

                default:
                    Console.WriteLine("No match");
                    break;
                }
            }
            else
            {
                Console.WriteLine("Error, Data not read");
            }


            //  }
        }
예제 #8
0
        private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            string line = serialPort1.ReadLine();

            this.BeginInvoke(new LineReceivedEvent(LineReceived1), line);
        }
예제 #9
0
        private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            //char[] str = new char[200];
            //str = data.Split('#');

            if (serialPort1.BytesToRead >= 200)
            {
                double[] x_axis = new double[200];
                for (int i = 0; i < 200; i++)
                {
                    buffer[i] = 0;
                }
                int values = serialPort1.Read(buffer, 0, 200);
                //list.Clear();
                for (int x = 0; x < 200; x++)
                {
                    samples[x] = System.Convert.ToDouble((buffer[x]));
                    x_axis[x]  = System.Convert.ToDouble(x);
                    //Double.TryParse([x], out samples[x]);
                    //list.Add((double)x, (samples[x] * 5) / 255);
                    //list.Add(Convert.ToDouble(x), Convert.ToDouble(buffer[x]));
                    list.Add(x_axis[x], ((samples[x] * 5) / 255));
                }
                zedGraphControl1.Invalidate();
                zedGraphControl1.AxisChange();
                serialPort1.Write("@");

                /////////////////////////////////////////////
                for (int c = 0; c < 200; c++)
                {
                    imaginary[c] = 0;
                    real[c]      = 0;
                }

                for (int a = 0; a < 200; a++)
                {
                    for (int n = 0; n < 200; n++)
                    {
                        real[a]      += samples[n] * Math.Cos((2 * Math.PI * a * n) / 200);
                        imaginary[a] += samples[n] * Math.Sin((2 * Math.PI * a * n) / 200);
                    }
                }

                for (int x = 0; x < 200; x++)
                {
                    wave[x] = Math.Sqrt(real[x] * real[x] + imaginary[x] * imaginary[x]);
                }
                max_value = 0;
                min_value = 1;
                for (int x = 1; x < 200; x++)
                {
                    if (max_value < wave[x])
                    {
                        max_value = wave[x];
                        min_value = x;
                    }
                }
                CreateChart2(zedGraphControl2);
                CreateChart(zedGraphControl1);
                serialPort1.DiscardInBuffer();

                if (serialPort1.IsOpen)
                {
                    serialPort1.Write("@");
                }
            }
        }
예제 #10
0
        private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            string POT = ArduinoPort.ReadLine();

            this.BeginInvoke(new LineReceivedEvent(LineReceived), POT);
        }
예제 #11
0
 private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
 {
     ThreadHelperClass.SetText(this, richTextBox1, serialPort1.ReadExisting());
 }
예제 #12
0
 private void portRead(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
 {
     textBox1.Text += serialPort.ReadExisting();
 }
예제 #13
0
 private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
 {
     serialDataIn = serialPort1.ReadLine();
     this.BeginInvoke(new EventHandler(ProceessData));
 }
        public static short command_ack   = 0x00; //标志:接收到的帧为控制命令返回帧
        //接收数据
        private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            if (closing)
            {
                return;          //如果正在关闭串口,忽略操作,直接返回
            }
            try
            {
                //button_port_state.BackgroundImage = Properties.Resources.red_bulb;
                com_receiving = 0x10;
                int    n   = serialPort1.BytesToRead; //接收缓存区中的字节数
                byte[] buf = new byte[n];             //声明一个临时数组存储当前来的串口数据
                serialPort1.Read(buf, 0, n);          //读取缓存数据
                foreach (byte data in buf)
                {
                    //传感器数据帧帧头5AA5
                    if (data == 0x5a & frame_start == 0x00)
                    {
                        RC_Flag = rx_head;
                        rx_buffer[rx_wr_index++] = data;
                        frame_start = 0x10;
                    }
                    else if (data == 0xa5 & RC_Flag == rx_head & frame_start == 0x10)
                    {
                        RC_Flag = 0x00;
                        rx_buffer[rx_wr_index++] = data;
                        frame_start = 0x11;
                        data_ack    = 0x11;             //标志:表示接收到的帧数据为传感器数据
                    }
                    //返回的控制命令帧帧头A55A
                    else if (data == 0xa5 & frame_start == 0x00)
                    {
                        RC_Flag = rx_head;
                        rx_buffer[rx_wr_index++] = data;
                        frame_start = 0x01;
                    }
                    else if (data == 0x5a & RC_Flag == rx_head & frame_start == 0x01)
                    {
                        RC_Flag = 0x00;
                        rx_buffer[rx_wr_index++] = data;
                        frame_start = 0x11;
                        command_ack = 0x11;        //标志:表示接收到的数据为dsp返回的控制命令
                    }
                    //有效数据部分
                    else if (frame_start == 0x11)
                    {
                        RC_Flag |= 0x00;
                        rx_buffer[rx_wr_index++] = data;
                        //传感器数据帧
                        if (rx_wr_index == (rx_buffer[2] + 6) & data_ack == 0x11)
                        {
                            frame_start   = 0x00;
                            rx_wr_index   = 0;
                            Flag_Received = 0x11;
                            RC_Flag       = rx_over;
                            data_ack      = 0x00;
                            Show_IMU();
                            Show_Motion();
                        }
                        //控制命令返回帧
                        else if (rx_wr_index == (rx_buffer[2] + 2) & command_ack == 0x11)
                        {
                            frame_start   = 0x00;
                            rx_wr_index   = 0;
                            Flag_Received = 0x11;
                            RC_Flag       = rx_over;
                            command_ack   = 0x00;
                            Data_show_command_ack();
                        }
                    }
                    else
                    {
                        rx_wr_index = 0;
                        frame_start = 0x00;
                    }

                    if (rx_wr_index == RX_BUFFER_SIZE)
                    {
                        rx_wr_index--;
                    }
                }
                com_receiving = 0x00;
                //button_port_state.BackgroundImage = Properties.Resources.green_bulb;
            }
            catch
            {
                MessageBox.Show("不能正确读取数据", "错误");
            }
        }
예제 #15
0
파일: Form1.cs 프로젝트: Amit-Zohar/Scopino
 // Get COM data
 private void com_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
 {
     try { buf = com.ReadLine(); }
     catch { };
 }
예제 #16
0
        private void serialPort1_DataReceived_1(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            string Rfidkart = serialPort1.ReadLine();

            Rfidkart = Rfidkart.Replace("\r", string.Empty);

            try
            {
                DataSet   dtst  = new DataSet();
                DataTable table = new DataTable();
                dtst.Tables.Add(table);
                textBox1.Text = Rfidkart;
                SqlCommand comm = new SqlCommand("select Rfid From Kayit WHERE Rfid Like'" + textBox1.Text + "%'", sCon);
                sCon.Open();
                SqlDataReader dr = comm.ExecuteReader();

                string oku;
                dr.Read();

                oku = dr["Rfid"].ToString();
                dr.Close();
                oku = oku.Replace("\r", string.Empty);

                if (textBox1.Text == oku)
                {
                    SqlCommand    cmd = new SqlCommand("select Giris,Resim From Kayit WHERE Rfid Like'" + textBox1.Text + "%'", sCon);
                    SqlDataReader d   = cmd.ExecuteReader();
                    d.Read();
                    pictureBox1.ImageLocation = d["Resim"].ToString();
                    bool kontrol = Convert.ToBoolean(d["Giris"].ToString());

                    if (kontrol == true)
                    {
                        d.Close();

                        serialPort1.WriteLine("1");

                        SqlCommand con = new SqlCommand("Update Kayit set GTarihSaat = '" + DateTime.Now.ToString() + "'where Rfid Like'" + textBox1.Text + "%'", sCon);
                        con.ExecuteNonQuery();
                        SqlDataAdapter adtr = new SqlDataAdapter("Select Ad,Soyad,OgrenciNo,GTarihSaat,CTarihSaat,Giris From Kayit WHERE Rfid Like'" + textBox1.Text + "%'", sCon);

                        table.Clear();
                        adtr.Fill(table);


                        datagrideDTbagla(table);
                        SqlCommand kmt = new SqlCommand("insert into Hoca(Ad,Soyad,OgrenciNo,GTarihSaat) values('" + dataGridView1.CurrentRow.Cells[0].Value + "','" + dataGridView1.CurrentRow.Cells[1].Value + "','" + dataGridView1.CurrentRow.Cells[2].Value + "','" + dataGridView1.CurrentRow.Cells[3].Value + "')", sCon);
                        kmt.ExecuteNonQuery();
                        kontrol = !kontrol;
                        int deg = Convert.ToInt32(kontrol);

                        SqlCommand com = new SqlCommand("Update Kayit set Giris = '" + deg + "'where Rfid Like'" + textBox1.Text + "%'", sCon);
                        com.ExecuteNonQuery();

                        textBox1.Clear();
                    }

                    else
                    {
                        serialPort1.WriteLine("1");
                        d.Close();
                        SqlConnection baglanti = new SqlConnection("Data Source=DESKTOP-8H18HGI\\SQLEXPRESS;Database=Rfid;Trusted_Connection=True;Integrated Security=True;");
                        baglanti.Open();
                        SqlCommand con = new SqlCommand("Update Kayit set CTarihSaat = '" + DateTime.Now.ToString() + "'where Rfid Like'" + textBox1.Text + "%'", sCon);
                        con.ExecuteNonQuery();

                        SqlCommand de = new SqlCommand("Update Kayit set CTarihSaat = '" + DateTime.Now.ToString() + "'where Rfid Like'" + textBox1.Text + "%'", sCon);
                        de.ExecuteNonQuery();
                        SqlDataAdapter adtr = new SqlDataAdapter("Select Ad,Soyad,OgrenciNo,GTarihSaat,CTarihSaat,Giris From Kayit WHERE Rfid Like'" + textBox1.Text + "%'", sCon);

                        table.Clear();
                        adtr.Fill(table);


                        datagrideDTbagla(table);

                        SqlCommand kmt = new SqlCommand("insert into Hoca(Ad,Soyad,OgrenciNo,CTarihSaat) values('" + dataGridView1.CurrentRow.Cells[0].Value + "','" + dataGridView1.CurrentRow.Cells[1].Value + "','" + dataGridView1.CurrentRow.Cells[2].Value + "','" + dataGridView1.CurrentRow.Cells[4].Value + "')", sCon);
                        kmt.ExecuteNonQuery();
                        kontrol = !kontrol;
                        int deg = Convert.ToInt32(kontrol);
                        baglanti.Close();
                        SqlCommand com = new SqlCommand("Update Kayit set Giris = '" + deg + "'where Rfid Like'" + textBox1.Text + "%'", sCon);
                        com.ExecuteNonQuery();
                        textBox1.Clear();
                    }
                }

                dr.Close();
                sCon.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                sCon.Close();
            }
        }
예제 #17
0
 private void DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
 {
     //throw new NotImplementedException();
     RxString = serialPort1.ReadExisting();
     this.Invoke(new EventHandler(received_data_textbox_TextChanged));
 }
예제 #18
0
        private void port_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            byte[] buffer   = new byte[1];  //buffer pro zesileni
            double pomocnik = 0;

            while (port.BytesToRead > 9)
            {
                UInt16 id = ReadU16(port.BaseStream);

                if ((oldid + 1 != id) && (id != 1) && (oldid != 0xFFF)) //asi zjistuje jestli se neztratily zadny data
                {
                    Trace.WriteLine("LOST");
                    oldid = 0;
                    continue;
                }

                oldid = id;

                if (id <= 0xFFF)
                {
                    port.BaseStream.Read(buffer, 0, 1);
                    adc5[id] = ((UInt16)buffer[0] - adc5_offset) / adc5_gain;                   //zesileni

                    adc1[id] = (ReadU16(port.BaseStream) - adc1_offset) / adc1_gain;            //napeti

                    adc2[id] = (ReadU16(port.BaseStream) - adc2_offset) / adc2_gain / adc5[id]; //prvni proud
                    pomocnik = (ReadU16(port.BaseStream) - adc3_offset) / adc3_gain / adc5[id]; //druhy proud
                    if (adc2[id] < pomocnik)                                                    //porovnani proudu
                    {
                        adc2[id] = pomocnik;
                    }

                    adc3[id] = adc2[id] / resistance;                 //vypocita proud

                    if (adc3[id] > 8)                                 //pokud proud prekroci maximalni hodnotu, pokusi se vypnout mereni
                    {
                        if (port.IsOpen)
                        {
                            byte[] smazme = BitConverter.GetBytes((short)3);                                // 3 znaci ukoncit mereni
                            byte[] prikaz = new byte[2];
                            System.Buffer.BlockCopy(smazme, 0, prikaz, 0, 2);

                            port.Write(prikaz, 0, prikaz.Length); //posle 2 byty jako prikaz
                        }
                        else
                        {
                            MessageBox.Show("Current exceeded allowed value! Unable to abort the measurement. Serial port is not open.");
                        }

                        if (nasobitel != 1)
                        {
                            MessageBox.Show("The characteristic seems to be too steep, You should try to decrease the Time Scale value.");
                        }
                        else
                        {
                            MessageBox.Show("The characteristic seems to be too steep, You should try to decrease the Power Supply Voltage value.");
                        }
                    }

                    if (id == 0xF00)
                    {
                        if ((adc3[0xF00] - adc3[0x000]) < 2 && (adc3[0xEFF] - adc3[0x010]) < 2)
                        {
                            if (napajeci_napeti < 15)
                            {
                                MessageBox.Show("The characteristic seems to be incomplete, You should try to increase the Power Supply Voltage value.");
                            }
                            else
                            {
                                MessageBox.Show("The characteristic seems to be incomplete, You should try to increase the Time Scale value.");
                            }
                        }
                    }
                }
                else
                {
                    port.DiscardInBuffer();
                }
            }
        }
예제 #19
0
파일: frmComTest.cs 프로젝트: ssor/ComPlay
 private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
 {
     SetText(this.serialPort1.ReadExisting());
 }
예제 #20
0
 static void temp_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
 {
     throw new NotImplementedException();
 }
예제 #21
0
        private void serialPort_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            try
            {
                string   rx  = serialPort.ReadLine();
                string[] arr = rx.Split('_');

                if (arr[0][0] == 'X') //Kennzeichnet den Start eines Kommandos
                {
                    command = arr[0][1];
                }


                if (command == 'B') //Sensor Kommando erkannt
                {
                    if (Convert.ToInt32(arr[2]) == interfaceForm.val)
                    {
                        return;
                    }
                    interfaceForm.id  = Convert.ToInt32(arr[1]);
                    interfaceForm.val = Convert.ToInt32(arr[2]);

                    if (this.InvokeRequired)
                    {
                        this.Invoke(new MethodInvoker(interfaceForm.ShowData));
                    }
                }
                else if (command == 'P') //Parameter einlesen
                {
                    interfaceForm.id = 4;


                    if (arr[1].ToString() == "1")
                    {
                        if (interfaceForm.drehzeit != arr[1].ToString())
                        {
                            interfaceForm.drehzeit = arr[2].ToString();
                        }
                        else
                        {
                            return;
                        }
                    }
                    else if (arr[1].ToString() == "2")
                    {
                        if (interfaceForm.min_dist_front != arr[2].ToString())
                        {
                            interfaceForm.min_dist_front = arr[2].ToString();
                        }
                        else
                        {
                            return;
                        }
                    }
                    else if (arr[1].ToString() == "3")
                    {
                        if (interfaceForm.min_dist_side != arr[2].ToString())
                        {
                            interfaceForm.min_dist_side = arr[2].ToString();
                        }
                        else
                        {
                            return;
                        }
                    }

                    if (this.InvokeRequired)
                    {
                        this.Invoke(new MethodInvoker(interfaceForm.ShowData));
                    }
                }
                else if (command == 'S') //State einlesen
                {
                    interfaceForm.id = 5;


                    if (interfaceForm.state != arr[2].ToString())
                    {
                        interfaceForm.state = arr[2].ToString();
                    }
                    else
                    {
                        return;
                    }

                    if (this.InvokeRequired)
                    {
                        this.Invoke(new MethodInvoker(interfaceForm.ShowData));
                    }
                }
            }
            catch (Exception ex) { }
        }
        }//frmSerial

        private void DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            richTextBox1.BeginInvoke(new myDelegate(updateTextBox));
        }//DataReceived
        private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            bool   opened = false;
            string readPort;

            if (alreadyLog == 1)
            {
                readPort = serialPort1.ReadExisting();

                if (readPort.Contains("c"))
                {
                    serialPort1.Write("c");
                    MessageBox.Show("Connection to console has been established!");
                    readPort        = "";
                    checkConnection = true;
                }
                if (checkConnection == true)
                {
                    foreach (Form a in Application.OpenForms)
                    {
                        if (a is NewReadingForm)
                        {
                            opened = true;
                        }
                    }

                    if (ccount == 0 && readPort.Contains("s"))
                    {
                        if (opened == false)
                        {
                            serialPort1.Close();
                            form4 = new NewReadingForm();
                            form4.ShowDialog();
                            serialPort1.Open();
                        }
                        ccount++;
                    }
                    try
                    {
                        while (opened)
                        {
                            foreach (Form a in Application.OpenForms)
                            {
                                if (a is NewReadingForm)
                                {
                                    opened = true;
                                    break;
                                }
                                else
                                {
                                    opened = false;
                                }
                            }
                        }
                        if (ccount == 1)
                        {
                            if (serialSystolic != null && serialDiastolic != null)
                            {
                                serialPort1.Close();
                                serialPort1.Open();
                                opened = false;
                                ccount = 0;

                                serialSystolic  = NonNumericString(serialSystolic);
                                serialDiastolic = NonNumericString(serialDiastolic);
                                string          source = "INSERT INTO Record (PatientID, Systolic, Diastolic, CDate, CTime,Status,Comments) VALUES('" + patientID + "'," + Convert.ToInt32(serialSystolic) + "," + Convert.ToInt32(serialDiastolic) + ",#" + DateTime.Parse(date) + "#,'" + time + "','" + status + "','" + comments + "') ";
                                OleDbConnection cn     = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + "C:\\Patient\'s Record.accdb");
                                OleDbCommand    cmd    = new OleDbCommand(source, cn);
                                cn.Open();
                                cmd.ExecuteNonQuery();
                                cn.Close();

                                timeList.Add(time);
                                dateList.Add(date);
                                urSystolic.Add(serialSystolic);
                                urDiastolic.Add(serialDiastolic);
                                urStatus.Add(status);
                                show30MinuteChart();
                                eventIndicator.Add("add");
                                eCount++;
                                serialDiastolic = null;
                                serialSystolic  = null;
                                status          = null;
                                comments        = null;
                            }
                            else
                            {
                                MessageBox.Show("Invalid reading has been received!\nPlease check the connections");
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }
            }
        }
예제 #24
0
 private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
 {
     abc = serialPort1.ReadExisting();
     this.Invoke(new EventHandler(check));
 }
예제 #25
0
        private void DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            if (SerialPort1.IsOpen)
            {
                                        //此处可能没有必要判断是否打开串口,但为了严谨性,我还是加上了  
                             {
                    //等待硬件传输完所有消息
                    Thread.Sleep(10);
                    //byte[] byteRead = new byte[SerialPort1.BytesToRead];    //BytesToRead:sp1接收的字符个数  
                                     //if (CB_RHEX.Checked==false)                          //'发送字符串'单选按钮  
                                     //{
                                     //    try
                                     //    {
                                     //        Byte[] receivedData = new Byte[SerialPort1.BytesToRead];        //创建接收字节数组  
                                     //        SerialPort1.Read(receivedData, 0, receivedData.Length);
                                     //        string strRcv = null;

                    //        strRcv = Encoding.Default.GetString(receivedData);
                    //        TB_recieve.AppendText(string.Format("{0:HH:mm:ss:ffff}", DateTime.Now) + " :  " +  strRcv + "\r\n");

                    //        //TB_recieve.Text += SerialPort1.ReadLine() + "\r\n"; //注意:回车换行必须这样写,单独使用"\r"和"\n"都不会有效果  
                    //        //SerialPort1.DiscardInBuffer();                      //清空SerialPort控件的Buffer   
                    //    }
                    //    catch(Exception ex)
                    //    {
                    //        MessageBox.Show(ex.Message, "出错提示");
                    //    }
                                         //}
                                         //else                                            //'发送16进制按钮'  
                                         //{
                    try
                    {
                        Byte[] receivedData = new Byte[SerialPort1.BytesToRead];                                  //创建接收字节数组  
                                                SerialPort1.Read(receivedData, 0, receivedData.Length);           //读取数据                         
                                                SerialPort1.DiscardInBuffer();                                    //清空SerialPort控件的Buffer  
                                                string strRcv = null;

                        strRcv = Encoding.Default.GetString(receivedData);
                        TB_recieve.AppendText(string.Format("{0:HH:mm:ss:ffff}", DateTime.Now) + " :  " + strRcv + "\r\n");

                        //TB_Recieve_HEX.Text += SerialPort1.ReadLine() + "\r\n";

                        strRcv = null;
                        for (int i = 0; i < receivedData.Length; i++)
                        {
                                                                                   //窗体显示  
                                                     {
                                strRcv += " " + receivedData[i].ToString("X2");    //16进制显示  
                                                            
                            }
                        }
                        TB_Recieve_HEX.AppendText(string.Format("{0:HH:mm:ss:ffff}", DateTime.Now) + "(HEX) :  " + strRcv + "\r\n");
                    }
                    catch (System.Exception ex)
                    {
                        MessageBox.Show(ex.Message, "出错提示");
                    }
                    //}
                }
            }
            else
            {
                MessageBox.Show("请打开某个串口", "错误提示");
            }
        }
예제 #26
0
 private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
 {
     rxString = serialPort1.ReadExisting();
     this.Invoke(new EventHandler(displayText));
 }
예제 #27
0
 private void serial_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
 {
     RxString += serial.ReadExisting();
     Invoke(new EventHandler(TratarDadosRecebidos));
 }
예제 #28
0
 private void uartPort_recvData(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
 {
 }
예제 #29
0
        private void sp_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            try
            {
                if (!db.recv)
                {
                    return;
                }
                if (sp.ReadByte() != 255)
                {
                    return;
                }
                input_speed   = sp.ReadByte();
                messure_speed = sp.ReadByte();
                angle         = sp.ReadByte();
                if (angle >= 128)
                {
                    angle = angle - 256;
                }
                midLine = sp.ReadByte();
                battery = sp.ReadByte();
                cond    = sp.ReadByte();
                for (int i = 0; i < 128; i++)
                {
                    graph[i] = sp.ReadByte();
                }
                db.Progress_Input_Speed.Invoke(new MethodInvoker(

                                                   delegate
                {
                    db.Progress_Input_Speed.Value = input_speed;
                }

                                                   ));
                db.Label_Input_Speed.Invoke(new MethodInvoker(

                                                delegate
                {
                    db.Label_Input_Speed.Text = input_speed.ToString();
                }

                                                ));
                db.Label_Messure_Speed.Invoke(new MethodInvoker(

                                                  delegate
                {
                    db.Label_Messure_Speed.Text = messure_speed.ToString();
                }

                                                  ));
                db.Progress_Messure_Speed.Invoke(new MethodInvoker(

                                                     delegate
                {
                    db.Progress_Messure_Speed.Value = messure_speed;
                }

                                                     ));
                db.Progress_Angle.Invoke(new MethodInvoker(

                                             delegate
                {
                    db.Progress_Angle.Value = angle + 128;
                }

                                             ));
                db.Label_Angle.Invoke(new MethodInvoker(

                                          delegate
                {
                    db.Label_Angle.Text = angle.ToString();
                }

                                          ));
                db.Progress_Battery.Invoke(new MethodInvoker(

                                               delegate
                {
                    db.Progress_Battery.Value = battery;
                }

                                               ));
                db.Progress_Battery.Invoke(new MethodInvoker(

                                               delegate
                {
                    db.Progress_Battery.Value = battery;
                }

                                               ));
            }
            catch (InvalidOperationException)
            {
                return;
            }
            catch (Exception)
            {
                // MessageBox.Show("Some Unknown Error");
                return;
            }
        }
예제 #30
0
        void comport_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            if (this.bClosing == true)
            {
                return;
            }
            try
            {
                string temp = comport.ReadExisting();
                buffer.Append(temp);

                //解析返回的数据
                // 首先确定已经接收到的数据中含有指示命令和标签UID
                string currentData = buffer.ToString();

                Debug.WriteLine(
                    string.Format("frmHFRead.comport_DataReceived  -> current buffer = {0}"
                                  , currentData));

                int    iTagit = -1;
                int    i1443a = -1;
                int    i1443b = -1;
                int    i15693 = -1;
                int    iPro   = -1;
                string strPro = string.Empty;
                iTagit = currentData.IndexOf(HFCommandItem.读取TAGIT协议标签);
                if (iTagit >= 0)
                {
                    iPro   = iTagit;
                    strPro = "TAGIT协议";
                    goto Found;
                }
                i1443a = currentData.IndexOf(HFCommandItem.读取14443A协议标签);
                if (i1443a >= 0)
                {
                    iPro   = i1443a;
                    strPro = "14443A协议";

                    goto Found;
                }
                i1443b = currentData.IndexOf(HFCommandItem.读取14443B协议标签);
                if (i1443b >= 0)
                {
                    iPro   = i1443b;
                    strPro = "14443B协议";
                    goto Found;
                }
                i15693 = currentData.IndexOf(HFCommandItem.读取15693协议标签);
                if (i15693 >= 0)
                {
                    iPro   = i15693;
                    strPro = "15693协议";
                    goto Found;
                }

                Found : if (iPro > -1)
                {
                    int iright = -1;
                    iright = currentData.IndexOf("]", iPro); //先检测右边括号,没有右边的话说明数据不完整
                    if ((iright > -1) && iright > iPro)      // ] 必须在协议的后面,否则就说明这不是同一个数据段
                    {
                        int ileft = -1;
                        ileft = currentData.IndexOf("[", iPro);
                        if (ileft != -1 && ileft < iright)
                        {
                            string tagID = string.Empty;
                            tagID = currentData.Substring(ileft + 1, iright - ileft - 1);
                            if (tagID.Length > 0)
                            {
                                int dindex = tagID.IndexOf(",");
                                if (dindex >= 0)
                                {
                                    tagID = tagID.Substring(0, dindex);
                                    if (tagID != null && tagID.Length > 0)
                                    {
                                        Debug.WriteLine(
                                            string.Format("frmHFRead.comport_DataReceived  -> tagID = {0}"
                                                          , tagID));
                                        this.Invoke(new deleControlInvoke(receiveNewTagInfo), new HFTagInfo(strPro, tagID));
                                    }
                                }
                            }

                            buffer.Remove(0, iright + 1);
                        }
                    }
                }
                //if (buffer.IndexOf("\r\n") != -1)
                //{
                //this.Invoke(new deleUpdateContorl(updateText), buffer);
                //buffer = string.Empty;
                //}
            }
            catch (System.Exception ex)
            {
                Debug.WriteLine(
                    string.Format("frmHFRead.comport_DataReceived  -> exception = {0}"
                                  , ex.Message));
            }
        }