DiscardInBuffer() public méthode

public DiscardInBuffer ( ) : void
Résultat void
        /// <summary>
        /// Функция посылает запрос в порт, потом отсчитывает время readTimeout и проверяет буфер порта на чтение.
        /// Таким образом обеспечивается одинаковый промежуток времени между запросами в порт.
        /// </summary>
        public async Task <byte[]> RequestAndRespawnConstPeriodAsync(byte[] writeBuffer, int nBytesRead, int readTimeout, CancellationToken ct)
        {
            if (!_port.IsOpen)
            {
                return(await Task <byte[]> .Factory.StartNew(() => null, ct));
            }

            //очистили буферы порта
            _port.DiscardInBuffer();
            _port.DiscardOutBuffer();

            //отправили данные в порт
            _port.WriteTimeout = 500;
            _port.Write(writeBuffer, 0, writeBuffer.Length);

            //ждем ответа....
            await Task.Delay(readTimeout, ct);

            //проверяем ответ
            var buffer = new byte[nBytesRead];

            if (_port.BytesToRead >= nBytesRead)
            {
                _port.Read(buffer, 0, nBytesRead);
                return(buffer);
            }
            Debug.WriteLine($"Время на ожидание ответа вышло {_port.BytesToRead} >= {nBytesRead}");
            throw new TimeoutException("Время на ожидание ответа вышло");
        }
Exemple #2
0
        public static bool PLCStop(PPIReadWritePara para)
        {
            if (!serialPort1.IsOpen)
            {
                serialPort1.Open();
            }
            PPIAddress ppiAddress = new PPIAddress();

            ppiAddress.DAddress = Convert.ToByte(para.PlcAddress);

            serialPort1.DiscardInBuffer();
            serialPort1.DiscardOutBuffer();

            serialPort1.Write(ppiAddress.StopBytesyte, 0, ppiAddress.StopBytesyte.Length);
            //Thread.Sleep(10);
            string str = ByteHelper.ByteToString(ppiAddress.StopBytesyte);

            if (serialPort1.ReadByte() == 0xE5)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
Exemple #3
0
 public void DiscardInBuffer()
 {
     if (!serialport.IsOpen)
     {
         Open();
     }
     if (serialport.IsOpen)
     {
         serialport.DiscardInBuffer();
     }
 }
Exemple #4
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("请打开某个串口", "错误提示");
            }
        }
Exemple #5
0
 public bool Close()
 {
     if (sp != null && sp.IsOpen)
     {
         lock (SyncLock)
         {
             sp.DiscardInBuffer();
             sp.DiscardOutBuffer();
             sp.Close();
         }
     }
     return(sp.IsOpen);
 }
Exemple #6
0
        private void Button_Click(object sender, RoutedEventArgs e)//按钮打开事件
        {
            try
            {
                open.IsEnabled = false;
                stop.IsEnabled = true;
                control.IsEnabled = true;
                port = new SerialPort();
                port.BaudRate = 115200;
                port.PortName = COMName.Text;
                port.DataBits = 8;

                port.Open();
                port.DiscardInBuffer();
                port.DiscardOutBuffer();
                MessageBox.Show("串口打开成功", "系统提示");
            }
            catch (IOException ex)
            {
                MessageBox.Show("串口打开失败" + ex, "系统提示");
                return;
            }
            _keepReading = true;
            _readThread = new Thread(ReadPort);
            _readThread.Start();
        }
Exemple #7
0
        private void PortReceiveData(object sender, SerialDataReceivedEventArgs e)
        {
            byte[] receiveData = new byte[serialPort.BytesToRead];
            try
            {
                int len = serialPort.Read(receiveData, 0, receiveData.Length);
                if (len > 0)
                {
                    StringBuilder sb = new StringBuilder();

                    sb.Append(Encoding.Default.GetString(receiveData, 0, len));
                    string str = sb.ToString().Trim();
                    str = str.Trim("\n\r".ToCharArray());
                    ReceiveMsgEventArgs msg = new ReceiveMsgEventArgs(str);
                    ReceiveDataEvent?.Invoke(this, msg);
                }
            }
            catch (Exception ex)
            {
                CommonModules.Notifier.NotifyHelper.Notify(CommonModules.Notifier.NotifyLevel.ERROR,
                                                           $"串口{serialPort.PortName}接收数据出错,错误信息:{ex.Message}。");
            }
            finally
            {
                serialPort.DiscardInBuffer();
            }
        }
Exemple #8
0
 /// <summary>
 /// 接收数据
 /// </summary>
 public bool ReadData()
 {
     try
     {
         //comportIsReading = true;
         if (ComPort_2.BytesToRead > 0)
         {
             int read_buffer_length = ComPort_2.BytesToRead;
             Read_Buffer = new byte[read_buffer_length];
             ComPort_2.Read(Read_Buffer, 0, read_buffer_length);
             List <byte> buffer = Read_Buffer.ToList();
             All_Content_byte.AddRange(buffer.ToList());
             //All_Content += Encoding.Default.GetString(buffer.ToArray());
             return(true);
         }
         else
         {
             return(false);
         }
         //comportIsReading = false;
     }
     catch (Exception)
     {
         ComPort_2.DiscardInBuffer();
         return(false);
     }
 }
        //public static void Main()
        public static void Main()
        {
            SerialPort port = new SerialPort("COM7", 115200, Parity.None, 8, StopBits.One);
            SerialPortInterface portInterface = new SerialPortInterface(port);
            portInterface.Open();

            port.DiscardInBuffer();
            while (true)
            {
                while (portInterface.ReadByte() != 'S')
                {

                }

                float sintime = portInterface.ReadShort();
                float sinval = portInterface.ReadFloat();
                float fsintime = portInterface.ReadShort();
                float fsinval = portInterface.ReadFloat();

                Console.WriteLine(String.Format("{0},{1},{2},{3}", sintime, sinval, fsintime, fsinval));

                /*
                float accx = portInterface.ReadFloat();
                float accy = portInterface.ReadFloat() * (float)(180.0f / Math.PI);
                float accz = portInterface.ReadFloat() * (float)(180.0f / Math.PI);
                float magx = portInterface.ReadFloat();
                float magy = portInterface.ReadFloat();
                float magz = portInterface.ReadFloat();

                Console.WriteLine(String.Format("{0},{1},{2},{3},{4},{5}", accx, accy, accz, magx, magy, magz));
                 */

            }
        }
 //        public Serial2Matlab(string port, int baudRate = 115200, Parity parity = Parity.None, int dataBits = 8, StopBits stopBits = StopBits.One)
 public Serial2Matlab()
 {
     serialPort = new SerialPort("COM43", 115200, Parity.None, 8, StopBits.One);
     serialPort.ReadTimeout = 2;
     serialPort.Open();
     serialPort.DiscardInBuffer();
 }
        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();
            }
        }
Exemple #12
0
        public BK8500(string comPortname, byte address)
        {
            instrumentError = false;

            //Setup serial port
            P = new SerialPort(comPortname, 38400);
            P.DataBits = 8;
            P.StopBits = StopBits.One;
            P.Parity = Parity.None;
            P.RtsEnable = true;
            P.ReadTimeout = 200;

            //Setup event for received data
            P.ReceivedBytesThreshold = packetLength;  //all packets for this device are 26 bytes in length
            P.DataReceived += new SerialDataReceivedEventHandler(P_DataReceived);
            dataWaitHandle = new EventWaitHandle(false, EventResetMode.ManualReset);  //this syncs the received data event handler to the main thread

            P.Open();
            P.DiscardInBuffer();
            this.address = address;

            //enter local mode
            this.remoteOperation = true;
            this.loadON = false;
            this.deviceConnected = true;
        }
        public bool Open(string[] args)
        {
            string portName = args[0];  // we must pass serial port name here
            int baudRate = 115200;

            Debug.WriteLine("Trying serial port: " + portName);

            serialPort = new SerialPort(portName, baudRate, Parity.None, 8, StopBits.One);
            serialPort.PortName = portName;
            serialPort.BaudRate = baudRate;
            serialPort.Parity = Parity.None;
            serialPort.DataBits = 8;
            serialPort.StopBits = StopBits.One;
            serialPort.DtrEnable = true;    // Arduino Leonardo requires this
            //serialPort.RtsEnable = false;
            //serialPort.ReadTimeout = 300;
            //serialPort.WriteTimeout = 10000;
            serialPort.DataReceived += serialPort_DataReceived;
            serialPort.ErrorReceived += serialPort_ErrorReceived;
            //serialPort.
            //serialPort.NewLine = "\r";

            Debug.WriteLine("IP: serial port - opening...");
            serialPort.Open();

            Debug.WriteLine("OK: opened");

            // Clear receive buffer out, since the bootloader can send
            // some junk characters, which might hose subsequent command responses:
            serialPort.DiscardInBuffer();

            stopWatch.Start();

            return true;
        }
Exemple #14
0
        private byte[] ReadByteInPort()
        {
            //Thread.Sleep(1000);

            byte[] r = new byte[_serialPort.BytesToRead];
            try
            {
                _serialPort.Read(r, 0, _serialPort.BytesToRead);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Exception read byte in port: " + ex.ToString());
            }
            finally
            {
                if (_serialPort.BytesToRead != 0)
                {
                    _serialPort.DiscardInBuffer();
                }

                Debug.WriteLine("Read byte in port finally");
            }

            return(r);
        }
Exemple #15
0
        static public int GetWeight()
        {
            try
            {
                int W = 0;
                if (iniFile.ScaleType == 1)
                {
                    port.DiscardInBuffer();
                    port.DiscardOutBuffer();
                    byte[] com = HexStringToByteArray("45");
                    port.Write(com, 0, 1);
                    int      k  = (port.Read(com, 0, 1));
                    BitArray Ba = new BitArray(com);

                    int      k2  = (port.Read(com, 0, 1));
                    BitArray Ba2 = new BitArray(com);

                    BitArray ba3 = new BitArray(16);

                    for (int i = 0; i < 16; i++)
                    {
                        if (i < 8)
                        {
                            ba3.Set(i, Ba[i]);
                        }
                        else
                        {
                            ba3.Set(i, Ba2[i - 8]);
                        }
                    }


                    W = getIntFromBitArray(ba3);
                }
                else if (iniFile.ScaleType == 2)
                {
                    W = ScaleCasAD.GetWeight();
                }
                return(W);
            }
            catch (Exception e)
            {
                Utils.ToCardLog("[Error] GetWeight " + e.Message);
                return(-1);
            }
        }
Exemple #16
0
        public CSerializer(string com)
        {
            m_serial = new SerialPort(com, 19200, Parity.None, 8, StopBits.One);

            m_serial.Open();
            m_serial.Flush();
            m_serial.DiscardInBuffer();
        }
 public CompanySerialIO(int serialPortNumber)
 {
     _semaphore = new Semaphore(1, 1);
     _serialPort = new SerialPort("COM" + serialPortNumber);
     _serialPort.ReadTimeout = 1000;
     _serialPort.Open();
     _serialPort.DiscardInBuffer(); // Discard unsynchronized data
     _serialPort.DiscardOutBuffer(); // Discard unsynchronized data
 }
Exemple #18
0
        /// <summary>
        /// 向串口发送指令
        /// </summary>
        /// <param name="command"></param>
        public void SendCommand(String command)
        {
            string hexCommand = tool.GetHexString(command);

            byte[] datat = tool.GetByteData(hexCommand);
            m_port.DiscardInBuffer();
            m_port.DiscardOutBuffer();
            m_port.Write(datat, 0, datat.Length);
        }
        public void theLoop()
        {
            int listenPort = 11000;
            UdpClient listener = new UdpClient(listenPort);
            IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, listenPort);
            SerialPort portCOM1 = new SerialPort();
            try{
                portCOM1 = new SerialPort("/dev/ttyS0", 115200, Parity.None, 8, StopBits.One);
                portCOM1.Open();
            }
            catch(Exception ee)
            {
                Console.WriteLine("Not connected to COM1");
                Console.WriteLine(ee.Message.ToString());
            }
            string received_data;
            byte[] received_byte_array;

            bool done = false;

            while(!done)
            {
                Console.WriteLine("Waiting For Data - press (q) to quit");
                received_byte_array = listener.Receive(ref groupEP);
                received_data = "";
                for(int i = 0; i < received_byte_array.Length; i++)
                {
                    received_data = received_data+received_byte_array[i]+" ";
                }
                Console.WriteLine("Recived Data From {0}: {1}", groupEP.ToString(), received_data);
                try{
                    portCOM1.Write(received_byte_array,0,received_byte_array.Length);		// write what was recived on UDP to com 1
                    Console.WriteLine("Wrote data to COM1 @ 115200 8N1");
                }
                catch(Exception ee)
                {
                    Console.WriteLine(ee.Message.ToString());
                    try{
                        portCOM1.Close();
                        portCOM1.DiscardOutBuffer();
                        portCOM1.DiscardInBuffer();

                        listener.Close();

                        listener = new UdpClient(listenPort);
                 		groupEP = new IPEndPoint(IPAddress.Any, listenPort);
                    }
                    catch(Exception eee)
                    {
                        Console.WriteLine(eee.Message.ToString());
                    }

                }

            }
        }
Exemple #20
0
        private void singleServoControl(byte lrBody, byte idNum, byte pose)
        {
            if (comportCheck())
            {
                byte[] servo = new byte[7];

                servo[0] = 255;
                servo[1] = lrBody;
                servo[2] = 4;
                servo[3] = 2;
                servo[4] = idNum;
                servo[5] = pose;
                servo[6] = Convert.ToByte(textBox4.Text);

                port.DiscardInBuffer();  //buffer clear
                port.DiscardOutBuffer(); //buffer clear
                port.Write(servo, 0, servo.Length);
            }
        }
Exemple #21
0
        /* open serial port */
        public void Open(string portName, uint baudRate)
        {
            /* initialize serial port */
            sp = new SerialPort(portName, (int)baudRate, Parity.Even, 8);
            /* open serial port */
            sp.Open();

            /* discard buffers */
            sp.DiscardInBuffer();
            sp.DiscardOutBuffer();
        }
        /// <summary>
        /// Changes the current port to the given port.
        /// </summary>
        /// <param name="portName">The name of the port to change to.</param>
        public void ChangePort(string portName)
        {
            if (_port != null && _port.IsOpen)
                ClosePort();

            _port = new SerialPort(portName);
            _port.BaudRate = 9600;
            _port.DataReceived += new SerialDataReceivedEventHandler(onPortDataReceived);
            _port.Open();
            _port.DiscardInBuffer();
        }
Exemple #23
0
 public SerialComm(string port)
 {
     serial = new SerialPort(port, 115200, Parity.None, 8, StopBits.One)
     {
         Handshake = Handshake.None, //Handshake not needed
     };
     serial.DataReceived += SerialDataReceived;
     serial.Open();
     serial.DiscardOutBuffer();
     serial.DiscardInBuffer();
 }
Exemple #24
0
        public static string ExecCommand(SerialPort port, string command, int responseTimeout, string errorMessage)
        {
            port.DiscardOutBuffer();
            port.DiscardInBuffer();
            receiveNow.Reset();
            port.Write(command + "\r");

            string input = ReadResponse(port, responseTimeout);
            if ((input.Length == 0) || ((!input.EndsWith("\r\n> ")) && (!input.EndsWith("\r\nOK\r\n"))))
                throw new ApplicationException("No success message was received.");
            return input;
        }
Exemple #25
0
 public Modem(SerialPort port)
 {            
     serialPort = port;
     //init port
     EnsurePortOpen();
     //we will handle read timeout manually, system implementation is not consistent
     serialPort.ReadTimeout = 0;
     serialPort.WriteTimeout = SerialPort.InfiniteTimeout;
     serialPort.DiscardInBuffer();
     serialPort.DiscardOutBuffer();
     serialPort.NewLine = "\r";
     serialPort.Encoding = Encoding.ASCII;
 }
        public void gainsmessageasync_test()
        {
            SerialPort port = new SerialPort("COM7", 250000, Parity.None, 8, StopBits.One);

            SerialPortInterface portInterface = new SerialPortInterface(port);

            using (FlightComputerInterface fcInt = new FlightComputerInterface(portInterface))
            {
                fcInt.Open();
                port.DiscardInBuffer();
                port.DiscardOutBuffer();

                FlightComputerTelemetryMessage gains = null;

                for (int i = 0; i < 1000; i++)
                {
                    gains = (FlightComputerTelemetryMessage) fcInt.Receive();

                    Assert.IsTrue(gains.LateralInnerLoopGain == 1.1f);
                    Assert.IsTrue(gains.LongitudeInnerLoopGain == 1.2f);
                    Assert.IsTrue(gains.PitchAngularVelocityGain == 1.3f);
                    Assert.IsTrue(gains.RollAngularVelocityGain == 1.4f);
                    Assert.IsTrue(gains.XAntiWindupGain == 1.5f);
                    Assert.IsTrue(gains.XDerivativeGain == 1.6f);
                    Assert.IsTrue(gains.XIntegralGain == 1.7f);
                    Assert.IsTrue(gains.XProportionalGain == 1.8f);
                    Assert.IsTrue(gains.YAntiWindupGain == 1.9f);
                    Assert.IsTrue(gains.YawAntiWindupGain == 1.0f);
                    Assert.IsTrue(gains.YawDerivativeGain == 1.11f);
                    Assert.IsTrue(gains.YawIntegralGain == 1.12f);
                    Assert.IsTrue(gains.YawProportionalGain == 1.13f);
                    Assert.IsTrue(gains.YDerivativeGain == 1.14f);
                    Assert.IsTrue(gains.YIntegralGain == 1.15f);
                    Assert.IsTrue(gains.YProportionalGain == 1.16f);
                    Assert.IsTrue(gains.ZAntiWindupGain == 1.17f);
                    Assert.IsTrue(gains.ZDerivativeGain == 1.18f);
                    Assert.IsTrue(gains.ZIntegralGain == 1.19f);
                    Assert.IsTrue(gains.ZProportionalGain == i);

                    Debug.WriteLine(i);

                    fcInt.Transmit(gains);
                }

                gains = (FlightComputerTelemetryMessage) fcInt.Receive();

                Assert.IsTrue(gains.ZProportionalGain == 12);

            }
        }
Exemple #27
0
 public static bool ClearBuffer(SerialPort port)
 {
     try
     {
         port.DiscardOutBuffer();
         port.DiscardInBuffer();
         return true;
     }
     catch(Exception ex)
     {
         FileWorker.WriteEventFile(DateTime.Now, "ASubDriver", "ClearBuffer", ex.Message);
         return false;
     }
 }
Exemple #28
0
		public Link (int BUFSIZE)
		{
			// Create a new SerialPort object with default settings.
			serialPort = new SerialPort("/dev/ttyS1",115200,Parity.None,8,StopBits.One);

			if(!serialPort.IsOpen)
				serialPort.Open();

			buffer = new byte[(BUFSIZE*2)];

			serialPort.ReadTimeout = 500;
			serialPort.DiscardInBuffer ();
			serialPort.DiscardOutBuffer ();
		}
        private bool identify(ref Dictionary<string, Arduino> _ArduinoMap, string _potentialArduino) {
            if (!_ArduinoMap.ContainsKey(_potentialArduino)) {
                SerialPort temp;
                try {
                    temp = new SerialPort(_potentialArduino);
                    temp.Open();
                    string toWrite = Arduino_Codes.IDENTITY_QUERY;
                    temp.DiscardOutBuffer();
                    temp.DiscardInBuffer();
                    Thread.Sleep(100);
                    temp.WriteLine(toWrite);
                    Thread.Sleep(200);
                    temp.WriteLine(toWrite);
                    Thread.Sleep(200);
                    string ID = temp.ReadExisting();
                    if (ID.Contains(Arduino_Codes.ARM_IDENTITY_RESPONSE))
                    {
                        _ArduinoMap.Add(Arduino_Codes.ARM_IDENTITY, new Arduino(temp, Arduino_Codes.ARM_IDENTITY));
                        return true;
                    }
                    else if (ID.Contains(Arduino_Codes.HAND_IDENTITY_RESPONSE))
                    {
                        _ArduinoMap.Add(Arduino_Codes.HAND_IDENTITY, new Arduino(temp, Arduino_Codes.HAND_IDENTITY));
                        return true;
                    }
                    else if (ID.Contains(Arduino_Codes.DRIVEFRONT_IDENTITY_RESPONSE))
                    {
                        _ArduinoMap.Add(Arduino_Codes.DRIVEFRONT_IDENTITY, new Arduino(temp, Arduino_Codes.DRIVEFRONT_IDENTITY));
                        return true;
                    }
                    else if (ID.Contains(Arduino_Codes.DRIVEBACK_IDENTITY_RESPONSE))
                    {
                        _ArduinoMap.Add(Arduino_Codes.DRIVEBACK_IDENTITY, new Arduino(temp, Arduino_Codes.DRIVEBACK_IDENTITY));
                        return true;
                    }
                    else if (ID.Contains(Arduino_Codes.PT_IDENTITY_RESPONSE))
                    {
                        _ArduinoMap.Add(Arduino_Codes.PT_IDENTITY, new Arduino(temp, Arduino_Codes.PT_IDENTITY));
                        return true;
                    }

                    temp.Dispose(); //Gets rid of safe handle issue! Or at least appears to!
                }
                catch {
                    return false;
                }
            }
            return false;
        }
Exemple #30
0
 public Program(string port)
 {
     serial = new SerialPort(port, 9600, Parity.None, 8, StopBits.One)
     {
         Handshake = Handshake.RequestToSend,
         NewLine = "\r",
     };
     serial.DataReceived +=(o,e)=>
     {
         var num = serial.BytesToRead;
         if (num == 0)
             return;
         var data = new byte[num];
         serial.Read(data, 0, num);
         foreach (var b in data)
         {
             switch (phase)
             {
                 case 0:
                     if (b == 0x0A)
                         phase = 1;
                     else
                         message.Append((char) b);
                     break;
                 case 1:
                     phase = (b == 0x30) ? 2 : 0;
                     break;
                 case 2:
                     phase = (b == 0x30) ? 3 : 0;
                     break;
                 case 3:
                     if (b == 0x0D)
                     {
                         if (message.Length > 0 && verbose)
                             Console.WriteLine(message);
                         lastMessage = message.ToString();
                         message.Clear();
                         syncEvent.Set();
                     }
                     phase = 0;
                     break;
             }
         }
     };
     serial.Open();
     //serial.RtsEnable = true;
     serial.DiscardOutBuffer();
     serial.DiscardInBuffer();
 }
 private void closePort()
 {
     if (port != null && port.IsOpen)
     {
         port.DiscardInBuffer();
         port.Dispose();
         port.Close(); // close the port
     }
     StatusLabel.Text           = "Disconnected";
     StatusLabel.BackColor      = Color.IndianRed;
     DissconnectButton.Enabled  = false;
     BaudrateBox.Enabled        = false; //baud rate
     DatabitBox.Enabled         = false; //BFS
     StopbitBox.Enabled         = false; //stop bit
     ParityBox.Enabled          = false; //pairty box
     CommandPanelButton.Enabled = false; //you can inter the command
     SendPanelButton.Enabled    = false; // files enabled
     RecievePanelButton.Enabled = false;
     SendPara.Enabled           = false;
     if (ControllerParaChange != true)
     {
         ConnectButton.Enabled = true;
     }
 }
Exemple #32
0
        public static bool ConfigPort(System.IO.Ports.SerialPort _serialPort, SerialPortConfig _serialPortConfig = default(SerialPortConfig))
        {
            Console.WriteLine(" Port: " + _serialPort.PortName);
            if (_serialPortConfig == null)
            {
                _serialPortConfig = new SerialPortConfig();
            }

            bool portOpened = false;

            try
            {
                _serialPort.DataBits        = _serialPortConfig.DataBits;
                _serialPort.StopBits        = _serialPortConfig.StopBits;
                _serialPort.Parity          = _serialPortConfig.Parity;
                _serialPort.Handshake       = _serialPortConfig.Handshake;
                _serialPort.WriteBufferSize = _serialPortConfig.WriteBufferSize;
                _serialPort.ReadBufferSize  = _serialPortConfig.ReadBufferSize;
                _serialPort.Encoding        = System.Text.Encoding.GetEncoding(28591);

                //Causes an error if it is being used
                openPort(_serialPort);
                _serialPort.DiscardInBuffer();
                _serialPort.DiscardOutBuffer();

                portOpened = true;
            }
            catch (Exception ex)
            {
                Console.WriteLine(System.Reflection.MethodInfo.GetCurrentMethod().Name + ". Error: " + ex.Message);
            }

            if (portOpened)
            {
                try
                {
                    //Causes error in Mono for non-standard baud rate
                    _serialPort.BaudRate = _serialPortConfig.BaudRate;
                }
                catch (Exception ex)
                {
                    Console.WriteLine(System.Reflection.MethodInfo.GetCurrentMethod().Name + ". Error: " + ex.Message);
                    ForceSetBaudRate(_serialPort.PortName, _serialPortConfig.BaudRate);
                }
            }

            return(portOpened);
        }
Exemple #33
0
 //打开端口
 public bool OpenPort(SerialPort port)
 {
     bool bflag = false;
     try
     {
         port.Open();
         port.DiscardInBuffer();
         port.DiscardOutBuffer();
         bflag = true;
     }
     catch (IOException ex)
     {
         bflag = false;
     }
     return bflag;
 }
        private void InitializeSerialPort(string serialPortName)
        {
            // Start receive queue worker
            ThreadPool.QueueUserWorkItem(
                new WaitCallback(ProcessReceiveQueue), null);

            // Start send queue worker
            ThreadPool.QueueUserWorkItem(
                new WaitCallback(ProcessSendQueue));

            // Open SerialPort
            mSerialPort = new SerialPort(serialPortName) { BaudRate = BaudRate };
            mSerialPort.Open();
            mSerialPort.DiscardInBuffer(); // Remove any "leftovers" from the buffer
            mSerialPort.DataReceived += DataReceived;
        }
Exemple #35
0
 public COMmngr()
 {
     //dataReceiveCBs += new DataReceivedCBDeleage(CC2540.DataReceivedCB);
     com = new SerialPort();
     com.BaudRate = 115200;
     com.PortName = Properties.Settings.Default.COMport;
     com.Parity = Parity.None;
     com.Handshake = Handshake.RequestToSend;
     com.StopBits = StopBits.One;
     com.DataBits = 8;
     com.ReadTimeout = 5000;
     com.WriteTimeout = 5000;
     com.DataReceived += new SerialDataReceivedEventHandler(COMDataReceivedCB);
     com.Open();
     com.DiscardInBuffer();
     com.DiscardOutBuffer();
 }
Exemple #36
0
        public bool Connect(bool exposeExceptions = false)
        {
            try
            {
                // Setup read thread
                readThread = new Thread(ReadResponseBytes);

                // Create a new SerialPort object with default settings.
                serialPort = new System.IO.Ports.SerialPort(COMMPort);

                // Update the Handshake
                serialPort.Handshake = System.IO.Ports.Handshake.None;

                // Set the read/write timeouts
                serialPort.ReadTimeout  = 10000;
                serialPort.WriteTimeout = 10000;

                // open serial port
                serialPort.Open();

                // monitor port changes
                PortsChanged += OnPortsChanged;

                // discard any buffered bytes
                serialPort.DiscardInBuffer();
                serialPort.DiscardOutBuffer();

                ResponseBytesHandler += ReadResponses;

                readThread.Start();

                return(connected = true);
            }
            catch (Exception)
            {
                if (exposeExceptions)
                {
                    throw;
                }
            }

            return(false);
        }
 private void Button_Click_3(object sender, RoutedEventArgs e)
 {
     try
     {
         if (serialPort.IsOpen)
         {
             serialPort.DiscardOutBuffer(); //清空发送缓存
             serialPort.DiscardInBuffer();  //清空接收缓存
         }
         else
         {
             return;
         }
     }
     catch (Exception error)
     {
         MessageBox.Show(error.ToString());
     }
 }
Exemple #38
0
 public Arduino(int compoort)
 {
     serialPort = new SerialPort();
     serialPort.BaudRate = 9600;
     string port = "COM" + Convert.ToString(compoort);
     try
     {
         serialPort.PortName = port;
         serialPort.Open();
         if (serialPort.IsOpen)
         {
             serialPort.DiscardInBuffer();
             serialPort.DiscardOutBuffer();
         }
     }
     catch
     {
     }
 }
 public serial_driver(String port_name, MainPanel panel_form, Profiler probe_profiler_para, stream_source stream_source_para)
 {
     main_form = panel_form;
     data_stream = new SerialPort(port_name, 115200, Parity.None, 8, StopBits.One);
     data_stream.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
     data_stream.ReceivedBytesThreshold = 1;
     data_stream.Open();
     data_stream.DtrEnable = true;
     data_stream.DtrEnable = false;
     data_stream.DiscardInBuffer();
     data_stream.DiscardOutBuffer();
     frame_prop packet_config;
     packet_config.padding_len = 3;
     packet_config.padding_byte = new byte[3] { 0xFF, 0x00, 0xAA };
     packet_config.pad_EOH = 0xFF;
     packet_config.pad_EOP = 0xFF;
     packet_config.header_len = 2;
     packet_config.crc_len = 2;
     parser = new Serial_parser(packet_config, main_form, probe_profiler_para, stream_source_para);
 }
        protected override bool DoInitialize()
        {
            try
            {
                _port = new SerialPort(Settings.PortName);
                _port.BaudRate = 38400;
                _port.RtsEnable = false;
                _port.DtrEnable = false;
                _port.Open();
                _port.DiscardOutBuffer();
                _port.DiscardInBuffer();
                _port.DataReceived += port_DataReceived;
            }
            catch (Exception e)
            {
                InteractionService.UserIntraction.DisplayPopup("", "Hugin Caller ID Error", e.Message);
                return false;
            }

            return true;
        }
Exemple #41
0
        public void ClosePort()
        {
            serial.ErrorReceived -= new Ports.SerialErrorReceivedEventHandler(serial_ErrorReceived);
            serial.DataReceived  -= new Ports.SerialDataReceivedEventHandler(serial_DataReceived);

            serial.DiscardInBuffer();
            serial.DiscardOutBuffer();
            var stream = serial.BaseStream;

            stream.Flush();
            stream.Close();
            stream.Dispose();

            serial.Close();

            serial.Dispose();

            serial = null;
            stream = null;
            GC.Collect();
        }
Exemple #42
0
        //Execute AT Command
        public string ExecCommand(SerialPort port,string command, int responseTimeout, string errorMessage)
        {
            try
            {
                // receiveNow = new AutoResetEvent();
                port.DiscardOutBuffer();
                port.DiscardInBuffer();
                receiveNow.Reset();
                port.Write(command + "\r");

                //Thread.Sleep(3000); //3 seconds
                string input = ReadResponse(port, responseTimeout);
                if ((input.Length == 0) || ((!input.EndsWith("\r\n> ")) && (!input.EndsWith("\r\nOK\r\n"))))
                    throw new ApplicationException("No success message was received.");
                return input;
            }
            catch (Exception ex)
            {
                throw new ApplicationException(errorMessage, ex);
            }
        }   
Exemple #43
0
        }         // WriteToHands

        private static int ClearBuffers(String hand)
        {
            /*======================================================================================\
            | * Clears serial buffers for both hands in try catch blocks.                           |
            | * PostConditions: returns 1 for error in L, -1 for R, otherwise 0                     |
            \======================================================================================*/

            if (hand == "Left" || hand == "Both")
            {
                try
                {
                    handPortL.DiscardOutBuffer();
                    handPortL.DiscardInBuffer();

                    //handPortL.Close();
                }
                catch (Exception e)
                {
                    UnityEngine.Debug.Log("ClearBuffers() L failed");
                    return(1);                            //if one fails they all will fail, should write this seperate -- lazy.
                }
            }

            if (hand == "Right" || hand == "Both")
            {
                try
                {
                    handPortR.DiscardOutBuffer();
                    handPortR.DiscardInBuffer();

                    //handPortL.Close();
                }
                catch (Exception e)
                {
                    UnityEngine.Debug.Log("Error in ClearBuffers() R");
                    return(-1);
                }
            }
            return(0);
        }        // ClearBuffers
Exemple #44
0
        private static void InitCom()
        {
            if (iniFile.DisplayBoardType == 1)
            {
                port.WriteTimeout    = 2000;
                port.ReadTimeout     = 20000;
                port.BaudRate        = iniFile.DisplayBoardPortBaudRate;
                port.PortName        = "com" + iniFile.DisplayBoardPort;
                port.NewLine         = Environment.NewLine;
                port.DtrEnable       = true;
                port.RtsEnable       = true;
                port.Parity          = Parity.None;
                port.ReadBufferSize  = 1024;
                port.WriteBufferSize = 1024;
                port.Handshake       = Handshake.None;
                port.Open();
                port.DiscardInBuffer();
                port.DiscardOutBuffer();
            }
            else if ((iniFile.DisplayBoardType == 2) || (iniFile.DisplayBoardType == 3))
            {
                port.WriteTimeout    = -1;
                port.ReadTimeout     = -1;
                port.BaudRate        = iniFile.DisplayBoardPortBaudRate;
                port.PortName        = "com" + iniFile.DisplayBoardPort;
                port.NewLine         = Environment.NewLine;
                port.DtrEnable       = true;
                port.RtsEnable       = true;
                port.Parity          = Parity.None;
                port.ReadBufferSize  = 4096;
                port.WriteBufferSize = 2048;
                port.Handshake       = Handshake.None;
                //port.ParityReplace = 20;

                port.Open();
                //port.DiscardInBuffer();
                //port.DiscardOutBuffer();
            }
        }
Exemple #45
0
        public bool SendReceiveInitData()
        {
            bool bret = true;

            byte[] cmdByteArray = new byte[5];
            openPort.DiscardInBuffer();
            openPort.DiscardOutBuffer();
            // Send byte data
            cmdByteArray[0] = 0x00;
            cmdByteArray[1] = 0xFF;
            cmdByteArray[2] = 0x01;
            cmdByteArray[3] = 0x01;
            cmdByteArray[4] = 0x00;

            openPort.Write(cmdByteArray, 0, 5);

            strBalanceReturn = "";
            if (ptReceiveData != null)
            {
                ptReceiveData = null;
            }

            while (openPort.BytesToRead == 0 && nCnt < 10)
            {
                nCnt++;
                Thread.Sleep(1000);
            }

            byte[] inbyte = new byte[5];
            openPort.Read(inbyte, 0, 5);
            ptReceiveData    = inbyte;
            strBalanceReturn = BitConverter.ToString(inbyte);

            if (nCnt >= 10)
            {
                bret        = false;
                strErrorMsg = "There is impossible to receive any data from microcontroller. Make sure the connection state or Select the correct Comport.";
            }
            nCnt = 0;
            return(bret);
        }
        /// <summary>
        /// Schreibt ein AT-Command an das Modem
        /// </summary>
        /// <param name="command"></param>
        private void PortComandExe(string command)
        {
            System.IO.Ports.SerialPort port = _spManager.SerialPort;
            //Port bereit?
            if (port == null)
            {
                MessageBox.Show("2003111425 serieller Port ist unbestimmt. Befehl an GSM-Modem wird abgebrochen.");
                return;
            }

            if (!SerialPort.GetPortNames().ToList().Contains(port.PortName))
            {
                MessageBox.Show("2003111551 Der Port >" + port.PortName + " < existiert nicht.");
                return;
            }

            try
            {
                if (!port.IsOpen)
                {
                    MessageBox.Show("2003110953 Port >" + port.PortName + "< ist nicht offen. Versuche zu öffnen");

                    _spManager.SerialPort.Open();
                    System.Threading.Thread.Sleep(500);
                }

                port.DiscardOutBuffer();
                port.DiscardInBuffer();

                _spManager.SerialPort.Write(command + "\r");
                //MessageBox.Show("PortComandExe(" + command + ")");
            }
            catch (System.IO.IOException ex_io)
            {
                MessageBox.Show("2003110956 Konnte Befehl nicht an COM-Port senden.\r\n" + ex_io.Message);
                return;
            }
        }
Exemple #47
0
        public void Stop()
        {
            try
            {
                ThreadRunFlag = false;

                if (SerialPortMng != null)
                {
                    SerialPortMng.DiscardOutBuffer();
                    SerialPortMng.DiscardInBuffer();
                    SerialPortMng.Close();
                    SerialPortMng.Dispose();
                }

                SendOrderQueue.Clear();
                ReceiveDataQueue.Clear();

                ReceiveData.Clear();
            }
            catch (Exception ex)
            {
            }
        }
Exemple #48
0
        public BK2831E(string comPort)
        {
            P = new SerialPort(comPort);
            P.BaudRate = 38400;
            P.ReadTimeout = 1000;
            P.Open();

            P.DiscardInBuffer();
            P.DiscardOutBuffer();

            int i = 0;
            modes = new string[9];
            modes[i++] = "VOLTAGE:AC";
            modes[i++] = "VOLTAGE:DC";
            modes[i++] = "CURRENT:AC";
            modes[i++] = "CURRENT:DC";
            modes[i++] = "RESISTANCE";
            modes[i++] = "FREQUENCY";
            modes[i++] = "PERIOD";
            modes[i++] = "DIODE";
            modes[i++] = "CONTINUITY";

            reset();

            //test comms with the device
            try
            {
                string instrID = this.instrumentID;
                if (!instrID.Contains("2831E  Multimeter"))
                    throw new Exception("Instrument expected on " + comPort + " is a BK2831E  Multimeter, " + instrID + " was found");
            }
            catch (TimeoutException)
            {
                throw new Exception("No instrument was found on " + comPort + ", A BK2831E was expected");
            }
        }
        protected override bool DoInitialize()
        {
            try
            {
                _port = new SerialPort(Settings.PortName);
                _port.Open();
                _port.DiscardOutBuffer();
                _port.DiscardInBuffer();
                _port.RtsEnable = true;
                var lines = GetInitializationString().Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (var line in lines)
                {
                    _port.WriteLine(line + "\r");
                }
                _port.DataReceived += port_DataReceived;
            }
            catch (Exception e)
            {
                InteractionService.UserIntraction.DisplayPopup("", "Generic Modem Error", e.Message);
                return false;
            }

            return true;
        }
Exemple #50
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);
            }
        }
        static void Main(string[] args)
        {
            string[] ports = SerialPort.GetPortNames();
            foreach (string p in ports)
            {

                var port = new SerialPort(p);
                port.BaudRate = 19200; // 115200;
                port.Parity = Parity.None;
                port.StopBits = StopBits.One;
                port.Handshake = Handshake.RequestToSend;
                port.DtrEnable = true;
                port.RtsEnable = true;
                port.NewLine = System.Environment.NewLine;
                port.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);

                try
                {
                    port.Open();
                    port.DiscardInBuffer();
                    port.DiscardOutBuffer();
                    var command = "AT";
                    while (!command.Equals("exit"))
                    {
                        port.WriteLine(command);
                        command = Console.ReadLine();
                    }
                    port.Close();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }
            }
            Console.ReadKey();
        }
Exemple #52
0
 public void Flush()
 {
     port.ReadExisting();
     port.DiscardInBuffer();
     //port.DiscardOutBuffer();
 }
Exemple #53
0
        void OnProcessExit(object sender, EventArgs e)
        {
            // Cancel the heat
            SerialPort serialPortCancel = null;
            try
            {


                // Create a new SerialPort object with default settings.
                serialPortCancel = new SerialPort();

                // Allow the user to set the appropriate properties.
                serialPortCancel.PortName = COM.SelectedItem.ToString();
                serialPortCancel.DataBits = 8;
                serialPortCancel.Parity = Parity.None;
                serialPortCancel.StopBits = StopBits.One;
                serialPortCancel.BaudRate = 9600;

                // Set the read/write timeouts
                serialPortCancel.ReadTimeout = 500;
                serialPortCancel.WriteTimeout = 500;

                serialPortCancel.Open();
                serialPortCancel.DiscardOutBuffer();
                serialPortCancel.DiscardInBuffer();

                String ReceivedData;
                //RecievedData = serialPort.ReadLine();
                //serialPort.DataReceived += new SerialDataReceivedEventHandler(responseHandler);
                serialPortCancel.Write("C" + "\r\n");

                Boolean conti = true;
                do
                {
                    ReceivedData = serialPortCancel.ReadLine();
                    if (ReceivedData.Contains('$'))
                    {
                        conti = false;
                    }
                } while (conti);


                ReceivedData = ReceivedData.Replace("$", "");
                ReceivedData = ReceivedData.Replace("\r", "");
                ReceivedData = ReceivedData.Replace("\n", "");

                serialPortCancel.Close();

            }
            catch (Exception exc)
            {
                MessageBox.Show("Serial could not be opened, please check that the device is correct one. The heat could not be turned off.");
                serialPortCancel.Close();
            }
        }
Exemple #54
0
        private void doAssay()
        {
            Boolean cont = true;

            int loop = 0;

            do
            {
                DateTime current = DateTime.Now;
                int endCycle = current.Hour * 60 * 60 + current.Minute * 60 + current.Second;

                if (duration < endCycle)
                {
                    cont = false;
                    
                }
                

                SerialPort serialPort = null;

                // Create a new SerialPort object with default settings.
                serialPort = new SerialPort();

                // Allow the user to set the appropriate properties.
                serialPort.PortName = port;
                serialPort.DataBits = 8;
                serialPort.Parity = Parity.None;
                serialPort.StopBits = StopBits.One;
                serialPort.BaudRate = 9600;

                // Set the read/write timeouts
                serialPort.ReadTimeout = 10000;
                serialPort.WriteTimeout = 500;

                try
                {
                    serialPort.Open();
                    serialPort.DiscardOutBuffer();
                    serialPort.DiscardInBuffer();

                    String ReceivedData;
                    //RecievedData = serialPort.ReadLine();
                    //serialPort.DataReceived += new SerialDataReceivedEventHandler(responseHandler);
                    serialPort.Write("R" + "\r\n");

                    Boolean conti = true;
                    do
                    {
                        ReceivedData = serialPort.ReadLine();
                        if (ReceivedData.Contains('$'))
                        {
                            conti = false;
                        }
                    } while (conti);


                    conti = true;

                    serialPort.Write("i" + "\r\n");
                    String ReceivedData1;
                    do
                    {
                        ReceivedData1 = serialPort.ReadLine();
                        if (ReceivedData1.Contains('$'))
                        {
                            conti = false;
                        }
                    } while (conti);


                    conti = true;


                    Thread.Sleep(2000);

                    ReceivedData = ReceivedData.Replace("$", "");
                    ReceivedData1 = ReceivedData1.Replace("$", "");
                    ReceivedData = ReceivedData.Replace("\r", "");
                    ReceivedData1 = ReceivedData1.Replace("\r", "");
                    ReceivedData = ReceivedData.Replace("\n", "");
                    ReceivedData1 = ReceivedData1.Replace("\n", "");

                    AppendHeatLabel("Temperature U:" + ReceivedData1.Split(',')[4] + "," + "Temperature M:" + ReceivedData1.Split(',')[5]);



                    AppendData(loop.ToString() + "," + ReceivedData1.Split(',')[4] + "," +
                    ReceivedData1.Split(',')[5] + "," + ReceivedData);

                    string resToAppend = loop.ToString() + ",U,M,";
                
                    AppendResult(loop.ToString() + "," + ReceivedData1.Split(',')[4] + "," +
                        ReceivedData1.Split(',')[5] + "," + ReceivedData);

                    Thread.Sleep(2000);

                    serialPort.Close();

                }
                catch (Exception exc)
                {
                    MessageBox.Show("Serial could not be opened, please check that the device is correct one");
                    serialPort.Close();
                }


                Boolean timeRunning = true;



                do
                {
                    DateTime wait = DateTime.Now;
                    if (endCycle + 120 < wait.Hour * 60 * 60 + wait.Minute * 60 + wait.Second)
                    {
                        timeRunning = false;
                    }
                    Thread.Sleep(100);
                } while (timeRunning);
                loop += 1;

            } while (cont);

            // Cancel the heat
            SerialPort serialPortCancel = null; 
            try
            {


                // Create a new SerialPort object with default settings.
                serialPortCancel = new SerialPort();

                // Allow the user to set the appropriate properties.
                serialPortCancel.PortName = port;
                serialPortCancel.DataBits = 8;
                serialPortCancel.Parity = Parity.None;
                serialPortCancel.StopBits = StopBits.One;
                serialPortCancel.BaudRate = 9600;

                // Set the read/write timeouts
                serialPortCancel.ReadTimeout = 500;
                serialPortCancel.WriteTimeout = 500;

                serialPortCancel.Open();
                serialPortCancel.DiscardOutBuffer();
                serialPortCancel.DiscardInBuffer();

                String ReceivedData;
                //RecievedData = serialPort.ReadLine();
                //serialPort.DataReceived += new SerialDataReceivedEventHandler(responseHandler);
                serialPortCancel.Write("C" + "\r\n");

                Boolean conti = true;
                do
                {
                    ReceivedData = serialPortCancel.ReadLine();
                    if (ReceivedData.Contains('$'))
                    {
                        conti = false;
                    }
                } while (conti);


                ReceivedData = ReceivedData.Replace("$", "");
                ReceivedData = ReceivedData.Replace("\r", "");
                ReceivedData = ReceivedData.Replace("\n", "");

                serialPortCancel.Close();

            }
            catch (Exception exc)
            {
                MessageBox.Show("Serial could not be opened, please check that the device is correct one");
                serialPortCancel.Close();
            }
            MessageBox.Show("Assay ready");
        }
Exemple #55
0
        public int GetWeight(out double Weight, out bool Stable, out string ErrMess)
        {
            Weight  = 0;
            ErrMess = "";
            Stable  = true;
            try
            {
                Utils.ToLog("GetWeight ");
                port.DiscardInBuffer();
                port.DiscardOutBuffer();
                byte[] com = HexStringToByteArray("05");
                port.Write(com, 0, 1);
                Utils.ToLog("GetWeight Send 05");

                byte[] com2 = new byte[16];
                int    k    = (port.Read(com2, 0, 2));
                if (com2[0] != 6)
                {
                    Utils.ToLog("GetWeight Неверный ответ на инит запрос Get " + com2[0].ToString());
                    ErrMess = "Некорректный ответ от весов";
                    return(-2); //Неверный ответ на инит запрос
                }

                com = HexStringToByteArray("11");
                port.Write(com, 0, 1);
                Thread.Sleep(500);
                Utils.ToLog("GetWeight Send 11");
                k = (port.Read(com2, 0, 15));
                string Prt = "";
                for (int j = 0; j < 15; j++)
                {
                    Prt += com2[j].ToString() + " ";
                }
                Utils.ToLog("Answer " + Prt);

                if ((com2[0] != 1) || (com2[1] != 2))
                {
                    Utils.ToLog("GetWeight Неверный ответ на инит запрос 2 Get " + com2.ToString());
                    ErrMess = "Некорректный ответ от весов";
                    return(-3); //Неверный ответ на инит запрос 2
                }
                if (com2[2] != 0x53)
                {
                    Stable = false;
                    //Utils.ToLog("GetWeight Весы нестабильны " + com2.ToString());
                    //return -4; //Весы нестабильны
                }
                int Plus = 1;
                if (com2[3] != 0x20)
                {
                    //Utils.ToLog("GetWeight Вес отрицателен " + com2.ToString());
                    Plus = -1;
                    //return -5; //Вес отрицателен
                }
                string res = "";
                for (int i = 0; i < 6; i++)
                {
                    Utils.ToLog("sc res = " + res);
                    res += Convert.ToChar(com2[i + 4]).ToString();
                }
                Weight = Convert.ToDouble(ReplDemSep(res)) * Plus;
                return(0);
            }
            catch (Exception e)
            {
                Utils.ToLog("Error GetWeight " + e.Message);
                ErrMess = "Ошибка " + e.Message;
                return(-1);
            }
        }
 protected override void FlushConnection()
 {
     SerialPort.DiscardInBuffer();
     SerialPort.DiscardOutBuffer();
 }
Exemple #57
0
        //----------------------------------------------------------------------------
        /// <summary>
        /// Обработчик события приёма данных из COM-порта
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ComPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            int data;

            // Сбрасываем межкадровый таймер
            _tmrInterFrameDelay.Stop();

            if (_serialPort.BytesToRead == 0)
            {
                if ((_MaskOfMessageLog & TypeOfMessageLog.Warning) == TypeOfMessageLog.Warning)
                {
                    Trace.TraceWarning("{0}: Поток ID: {1} : Принята нулевая посылка",
                                       DateTime.Now.ToLongTimeString(), Thread.CurrentThread.ManagedThreadId);
                }
                // После принятия очердной порции байт ответа
                // Запускаем межкадровый таймер
                _tmrInterFrameDelay.Start();
                return;
            }
            else
            {
                StringBuilder sb;

                // Идёт транзакция запрос-ответ?
                if (_transaction == TransactionType.UnicastMode)
                {
                    // Да - Принимаем байты
                    sb = new StringBuilder();

                    while (_serialPort.BytesToRead != 0)
                    {
                        data = _serialPort.ReadByte();

                        if (data != -1)
                        {
                            lock (_incomingBuffer)
                            {
                                _incomingBuffer.Add(System.Convert.ToByte(data));
                                sb.Append(data.ToString("X2"));
                                sb.Append(" ");
                            }
                        }
                    }

                    if ((_MaskOfMessageLog & TypeOfMessageLog.Information) == TypeOfMessageLog.Information)
                    {
                        Trace.TraceInformation("{0}: Поток ID: {1} : Принято байт: {2}",
                                               DateTime.Now.ToLongTimeString(),
                                               Thread.CurrentThread.ManagedThreadId, sb.ToString());
                    }

                    // После принятия очердной порции байт ответа
                    // Запускаем межкадровый таймер
                    _tmrInterFrameDelay.Start();
                }
                else
                {
                    // Нет - принят мусор с линии
                    sb = new StringBuilder();
                    // Вычитываем этот мусор
                    while (_serialPort.BytesToRead != 0)
                    {
                        data = _serialPort.ReadByte();

                        if (data != -1)
                        {
                            lock (_incomingBuffer)
                            {
                                sb.Append(data.ToString("X2"));
                                sb.Append(" ");
                            }
                        }
                    }

                    if ((_MaskOfMessageLog & TypeOfMessageLog.Warning) == TypeOfMessageLog.Warning)
                    {
                        Trace.TraceWarning("{0}: Поток ID: {1} : Приняты данные, в отсутствии запроса : {2}",
                                           DateTime.Now.ToLongTimeString(), Thread.CurrentThread.ManagedThreadId, sb.ToString());
                    }
                    _serialPort.DiscardInBuffer();
                }
            }
        }
Exemple #58
0
 public void WriteBuffer(byte[] Buf, int Length)
 {
     SP.DiscardInBuffer();
     SP.Write(Buf, 0, Length);
     Thread.Sleep(40);
 }
Exemple #59
0
 public override void DiscardInBuffer()
 {
     _port.DiscardInBuffer();
 }
Exemple #60
0
 private bool PortDiscard()
 {
     m_ComPort.DiscardInBuffer();
     return(true);
 }