Пример #1
0
 /// <summary>
 /// When serial received data, will call this method
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void DataReceived(object sender, SerialDataReceivedEventArgs e)
 {
     if (sp.BytesToRead <= 0)
     {
         return;
     }
     //Thread Safety explain in MSDN:
     // Any public static (Shared in Visual Basic) members of this type are thread safe.
     // Any instance members are not guaranteed to be thread safe.
     // So, we need to synchronize I/O
     lock (thisLock)
     {
         int    len  = sp.BytesToRead;
         Byte[] data = new Byte[len];
         try
         {
             sp.Read(data, 0, len);
         }
         catch (System.Exception)
         {
             //catch read exception
         }
         SerialPortEventArgs args = new SerialPortEventArgs();
         args.receivedBytes = data;
         if (comReceiveDataEvent != null)
         {
             comReceiveDataEvent.Invoke(this, args);
         }
     }
 }
Пример #2
0
        /// <summary>
        /// update status bar
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void CloseComEvent(Object sender, SerialPortEventArgs e)
        {
            if (this.InvokeRequired)
            {
                Invoke(new Action <Object, SerialPortEventArgs>(CloseComEvent), sender, e);
                return;
            }

            if (!e.isOpend) //close successfully
            {
                statuslabel.Text    = comListCbx.Text + " Closed";
                openCloseSpbtn.Text = "Open";

                sendbtn.Enabled     = false;
                sendtbx.ReadOnly    = false;
                autoSendcbx.Enabled = false;
                autoSendtimer.Stop();

                comListCbx.Enabled     = true;
                baudRateCbx.Enabled    = true;
                dataBitsCbx.Enabled    = true;
                stopBitsCbx.Enabled    = true;
                parityCbx.Enabled      = true;
                handshakingcbx.Enabled = true;
                refreshbtn.Enabled     = true;
            }
        }
Пример #3
0
        private void pinChange(object sender, SerialPinChangedEventArgs e)
        {
            SerialPortEventArgs args = new SerialPortEventArgs();

            if (comNumEvent != null)
            {
                comNumEvent.Invoke(this, args);
            }
        }
Пример #4
0
        /// <summary>
        /// When serial received data, will call this method
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void errorRecieve(object sender, SerialErrorReceivedEventArgs e)
        {
            SerialPortEventArgs args = new SerialPortEventArgs();

            if (comNumEvent != null)
            {
                comNumEvent.Invoke(this, args);
            }
        }
Пример #5
0
        /// <summary>
        /// Open Serial port
        /// </summary>
        /// <param name="portName"></param>
        /// <param name="baudRate"></param>
        /// <param name="dataBits"></param>
        /// <param name="stopBits"></param>
        /// <param name="parity"></param>
        /// <param name="handshake"></param>
        public void Open(string portName, String baudRate,
                         string dataBits, string stopBits, string parity,
                         string handshake)
        {
            if (sp.IsOpen)
            {
                Close();
            }

            sp.PortName = portName;
            sp.BaudRate = Convert.ToInt32(baudRate);
            sp.DataBits = Convert.ToInt16(dataBits);

            /**
             *  If the Handshake property is set to None the DTR and RTS pins
             *  are then freed up for the common use of Power, the PC on which
             *  this is being typed gives +10.99 volts on the DTR pin & +10.99
             *  volts again on the RTS pin if set to true. If set to false
             *  it gives -9.95 volts on the DTR, -9.94 volts on the RTS.
             *  These values are between +3 to +25 and -3 to -25 volts this
             *  give a dead zone to allow for noise immunity.
             *  http://www.codeproject.com/Articles/678025/Serial-Comms-in-Csharp-for-Beginners
             */
            if (handshake == "None")
            {
                //Never delete this property
                sp.RtsEnable = true;
                sp.DtrEnable = true;
            }

            SerialPortEventArgs args = new SerialPortEventArgs();

            try
            {
                sp.StopBits     = (StopBits)Enum.Parse(typeof(StopBits), stopBits);
                sp.Parity       = (Parity)Enum.Parse(typeof(Parity), parity);
                sp.Handshake    = (Handshake)Enum.Parse(typeof(Handshake), handshake);
                sp.WriteTimeout = 1000; /*Write time out*/
                sp.Open();
                sp.DataReceived += new SerialDataReceivedEventHandler(DataReceived);
                args.isOpend     = true;
            }
            catch (System.Exception)
            {
                args.isOpend = false;
            }

            if (comOpenEvent != null)
            {
                comOpenEvent.Invoke(this, args);
            }
        }
Пример #6
0
        /// <summary>
        /// Close serial port thread
        /// </summary>
        private void CloseSpThread()
        {
            SerialPortEventArgs args = new SerialPortEventArgs();

            args.isOpend = false;
            try
            {
                sp.Close(); //close the serial port
                sp.DataReceived -= new SerialDataReceivedEventHandler(DataReceived);
            }
            catch (Exception)
            {
                args.isOpend = true;
            }
            if (comCloseEvent != null)
            {
                comCloseEvent.Invoke(this, args);
            }
        }
Пример #7
0
        /// <summary>
        /// update status bar
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void OpenComEvent(Object sender, SerialPortEventArgs e)
        {
            if (this.InvokeRequired)
            {
                Invoke(new Action <Object, SerialPortEventArgs>(OpenComEvent), sender, e);
                return;
            }

            if (e.isOpend)  //Open successfully
            {
                statuslabel.Text     = comListCbx.Text + " Opend";
                openCloseSpbtn.Text  = "Close";
                sendbtn.Enabled      = true;
                autoSendcbx.Enabled  = true;
                autoReplyCbx.Enabled = true;

                comListCbx.Enabled     = false;
                baudRateCbx.Enabled    = false;
                dataBitsCbx.Enabled    = false;
                stopBitsCbx.Enabled    = false;
                parityCbx.Enabled      = false;
                handshakingcbx.Enabled = false;
                refreshbtn.Enabled     = false;

                if (autoSendcbx.Checked)
                {
                    autoSendtimer.Start();
                    sendtbx.ReadOnly = true;
                }
            }
            else    //Open failed
            {
                statuslabel.Text     = "Open failed !";
                sendbtn.Enabled      = false;
                autoSendcbx.Enabled  = false;
                autoReplyCbx.Enabled = false;
            }
        }
Пример #8
0
        /// <summary>
        /// Display received data
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void ComReceiveDataEvent(Object sender, SerialPortEventArgs e)
        {
            if (this.InvokeRequired)
            {
                try
                {
                    Invoke(new Action <Object, SerialPortEventArgs>(ComReceiveDataEvent), sender, e);
                }
                catch (System.Exception)
                {
                    //disable form destroy exception
                }
                return;
            }

            if (recStrRadiobtn.Checked) //display as string
            {
                receivetbx.AppendText(Encoding.Default.GetString(e.receivedBytes));
            }
            else //display as hex
            {
                if (receivetbx.Text.Length > 0)
                {
                    receivetbx.AppendText("-");
                }
                receivetbx.AppendText(IController.Bytes2Hex(e.receivedBytes));
            }
            //update status bar
            receiveBytesCount     += e.receivedBytes.Length;
            toolStripStatusRx.Text = "Received: " + receiveBytesCount.ToString();

            //auto reply
            if (autoReplyCbx.Checked)
            {
                sendbtn_Click(this, new EventArgs());
            }
        }
Пример #9
0
 /// <summary>
 /// When serial received data, will call this method
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void DataReceived(object sender, SerialDataReceivedEventArgs e)
 {
     if (sp.BytesToRead <= 0)
     {
         return;
     }
     //Thread Safety explain in MSDN:
     // Any public static (Shared in Visual Basic) members of this type are thread safe. 
     // Any instance members are not guaranteed to be thread safe.
     // So, we need to synchronize I/O
     lock (thisLock)
     {
         int len = sp.BytesToRead;
         Byte[] data = new Byte[len];
         try
         {
             sp.Read(data, 0, len);
         }
         catch (System.Exception)
         {
             //catch read exception
         }
         SerialPortEventArgs args = new SerialPortEventArgs();
         args.receivedBytes = data;
         if (comReceiveDataEvent != null)
         {
             comReceiveDataEvent.Invoke(this, args);
         }
     }
 }
Пример #10
0
 /// <summary>
 /// Close serial port thread
 /// </summary>
 private void CloseSpThread()
 {
     SerialPortEventArgs args = new SerialPortEventArgs();
     args.isOpend = false;
     try
     {
         sp.Close(); //close the serial port
         sp.DataReceived -= new SerialDataReceivedEventHandler(DataReceived);
     }
     catch (Exception)
     {
         args.isOpend = true;
     }
     if (comCloseEvent != null)
     {
         comCloseEvent.Invoke(this, args);
     }
     
 }
Пример #11
0
        /// <summary>
        /// Open Serial port
        /// </summary>
        /// <param name="portName"></param>
        /// <param name="baudRate"></param>
        /// <param name="dataBits"></param>
        /// <param name="stopBits"></param>
        /// <param name="parity"></param>
        /// <param name="handshake"></param>
        public void Open(string portName, String baudRate,
            string dataBits, string stopBits, string parity,
            string handshake)
        {
            if (sp.IsOpen)
            {
                Close();
            }
            sp.PortName = portName;
            sp.BaudRate = Convert.ToInt32(baudRate);
            sp.DataBits = Convert.ToInt16(dataBits);

            /**
             *  If the Handshake property is set to None the DTR and RTS pins 
             *  are then freed up for the common use of Power, the PC on which
             *  this is being typed gives +10.99 volts on the DTR pin & +10.99
             *  volts again on the RTS pin if set to true. If set to false 
             *  it gives -9.95 volts on the DTR, -9.94 volts on the RTS. 
             *  These values are between +3 to +25 and -3 to -25 volts this 
             *  give a dead zone to allow for noise immunity.
             *  http://www.codeproject.com/Articles/678025/Serial-Comms-in-Csharp-for-Beginners
             */
            if (handshake == "None")
            {
                //Never delete this property
                sp.RtsEnable = true; 
                sp.DtrEnable = true;
            }
            
            SerialPortEventArgs args = new SerialPortEventArgs();
            try
            {
                sp.StopBits = (StopBits)Enum.Parse(typeof(StopBits), stopBits);
                sp.Parity = (Parity)Enum.Parse(typeof(Parity), parity);
                sp.Handshake = (Handshake)Enum.Parse(typeof(Handshake), handshake);
                sp.WriteTimeout = 1000; /*Write time out*/
                sp.Open();
                sp.DataReceived += new SerialDataReceivedEventHandler(DataReceived);
                args.isOpend = true;
            }
            catch (System.Exception)
            {
                args.isOpend = false;
            }
            if (comOpenEvent != null)
            {
                comOpenEvent.Invoke(this, args);
            }
            
        }
Пример #12
0
        /// <summary>
        /// Display received data
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void ComReceiveDataEvent(Object sender, SerialPortEventArgs e)
        {
            if (this.InvokeRequired)
            {
                try
                {
                    Invoke(new Action<Object, SerialPortEventArgs>(ComReceiveDataEvent), sender, e);
                }
                catch (System.Exception)
                {
                    //disable form destroy exception
                }
                return;
            }

            if (recStrRadiobtn.Checked) //display as string
            {
                receivetbx.AppendText(Encoding.Default.GetString(e.receivedBytes));
            }
            else //display as hex
            {
                if (receivetbx.Text.Length > 0)
                {
                    receivetbx.AppendText("-");
                }
                receivetbx.AppendText(IController.Bytes2Hex(e.receivedBytes));
            }
            //update status bar
            receiveBytesCount += e.receivedBytes.Length;
            toolStripStatusRx.Text = "Received: "+receiveBytesCount.ToString();

            //auto reply
            if (autoReplyCbx.Checked)
            {
                sendbtn_Click(this, new EventArgs());
            }

        }
Пример #13
0
        /// <summary>
        /// update status bar
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void CloseComEvent(Object sender, SerialPortEventArgs e)
        {
            if (this.InvokeRequired)
            {
                Invoke(new Action<Object, SerialPortEventArgs>(CloseComEvent), sender, e);
                return;
            }

            if (!e.isOpend) //close successfully
            {
                statuslabel.Text = comListCbx.Text + " Closed";
                openCloseSpbtn.Text = "Open";

                sendbtn.Enabled = false;
                sendtbx.ReadOnly = false;
                autoSendcbx.Enabled = false;
                autoSendtimer.Stop();

                comListCbx.Enabled = true;
                baudRateCbx.Enabled = true;
                dataBitsCbx.Enabled = true;
                stopBitsCbx.Enabled = true;
                parityCbx.Enabled = true;
                handshakingcbx.Enabled = true;
                refreshbtn.Enabled = true;
            }
        }
Пример #14
0
        /// <summary>
        /// update status bar
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void OpenComEvent(Object sender, SerialPortEventArgs e)
        {
            if (this.InvokeRequired)
            {
                Invoke(new Action<Object, SerialPortEventArgs>(OpenComEvent), sender, e);
                return;
            }

            if (e.isOpend)  //Open successfully
            {
                statuslabel.Text = comListCbx.Text + " Opend";
                openCloseSpbtn.Text = "Close";
                sendbtn.Enabled = true;
                autoSendcbx.Enabled = true;
                autoReplyCbx.Enabled = true;

                comListCbx.Enabled = false;
                baudRateCbx.Enabled = false;
                dataBitsCbx.Enabled = false;
                stopBitsCbx.Enabled = false;
                parityCbx.Enabled = false;
                handshakingcbx.Enabled = false;
                refreshbtn.Enabled = false;

                if (autoSendcbx.Checked)
                {
                    autoSendtimer.Start();
                    sendtbx.ReadOnly = true;
                }
            }
            else    //Open failed
            {
                statuslabel.Text = "Open failed !";
                sendbtn.Enabled = false;
                autoSendcbx.Enabled = false;
                autoReplyCbx.Enabled = false;
            }
        }
Пример #15
0
        private void DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
                if (sp.BytesToRead <= 0)
                {
                    return;
                }

                //Thread Safety explain in MSDN:
                // Any public static (Shared in Visual Basic) members of this type are thread safe.
                // Any instance members are not guaranteed to be thread safe.
                // So, we need to synchronize I/O
                lock (thisLock)
                {
                    int satrt = Environment.TickCount;
                    while (Math.Abs(Environment.TickCount - satrt) < 500)
                    {
                        int    len  = sp.BytesToRead;
                        Byte[] data = new Byte[len];
                        try
                        {
                            sp.Read(data, 0, len);
                        }
                        catch (System.Exception)
                        {
                            //catch read exception
                        }

                        buffer.AddRange(data);
                    }

//                Thread.Sleep(1000);



                    SerialPortEventArgs args = new SerialPortEventArgs();
//                args.receivedBytes = data;
                    args.receivedBytes = buffer.ToArray();
                    serialPortEvent    = args;


                    if (comReceiveDataEvent != null)
                    {
                        try
                        {
                            comReceiveDataEvent.Invoke(this, args);
                        }
                        catch (Exception exception)
                        {
                            Console.WriteLine(exception);
//                        throw;
                        }
                    }

                    buffer.Clear();
                }
            }
            catch (Exception exception)
            {
                throw exception;
            }
        }