Source

SerialPortTest / SerialPortTest / MainClass.cs

Full commit
namespace Sti.IO.SerialPortTest
{
    using System;
    using System.IO.Ports;

    public static class MainClass
    {
        private const int BAUD_RATE = 9600;
        private const int DATA_BITS = 8;
        private const Parity PARITY = Parity.None;
        private const string PORT_NAME = "COM8";
        private const int READ_TIMEOUT = 100;
        private const StopBits STOP_BITS = StopBits.One;

        public static void Main(string[] args)
        {
            SerialPort port = null;
            try
            {
                port = new SerialPort(PORT_NAME, BAUD_RATE, PARITY, DATA_BITS, STOP_BITS);
                port.ReadTimeout = READ_TIMEOUT;
                port.ErrorReceived += ErrorReceived;
                port.PinChanged += PinChanged;

                PortHandler handler = new PortHandler(port);
                handler.ReadComplete += ReadComplete;

                port.Open();

                Console.Out.WriteLine("You may press any key at any time to quit.");
                Console.ReadKey(true);

                port.Close();
            }
            catch (Exception ex)
            {
                Console.Out.WriteLine("Error opening serial port: " + ex.Message);
                Console.Error.WriteLine(ex);
            }
            finally
            {
                if (port != null)
                    port.Dispose();
            }
        }

        static void ReadComplete(object sender, ReadCompleteEventArgs e)
        {
            if (e.Error != null)
            {
                Console.Out.WriteLine("A read was incomplete because of an error.");
                Console.Error.WriteLine(e.Error);
            }
            else
            {
                Console.Out.WriteLine(string.Format(
                    "Data was successfully read (length = {0}): \"{1}\"",
                    e.Content.Length,
                    Convert.ToBase64String(e.Content)));
            }
        }

        private static void PinChanged(object sender, SerialPinChangedEventArgs e)
        {
            Console.Out.WriteLine("PinChanged event: EventType = " + e.EventType);
        }

        private static void ErrorReceived(object sender, SerialErrorReceivedEventArgs e)
        {
            Console.Out.WriteLine("ErrorReceived event: Event Type = " + e.EventType);
        }
    }
}